Line data Source code
1 : //!
2 : //! `neon_local` is an executable that can be used to create a local
3 : //! Neon environment, for testing purposes. The local environment is
4 : //! quite different from the cloud environment with Kubernetes, but it
5 : //! easier to work with locally. The python tests in `test_runner`
6 : //! rely on `neon_local` to set up the environment for each test.
7 : //!
8 : use std::borrow::Cow;
9 : use std::collections::{BTreeSet, HashMap};
10 : use std::fs::File;
11 : use std::os::fd::AsRawFd;
12 : use std::path::PathBuf;
13 : use std::process::exit;
14 : use std::str::FromStr;
15 : use std::time::Duration;
16 :
17 : use anyhow::{Context, Result, anyhow, bail};
18 : use clap::Parser;
19 : use compute_api::spec::ComputeMode;
20 : use control_plane::endpoint::ComputeControlPlane;
21 : use control_plane::local_env::{
22 : InitForceMode, LocalEnv, NeonBroker, NeonLocalInitConf, NeonLocalInitPageserverConf,
23 : ObjectStorageConf, SafekeeperConf,
24 : };
25 : use control_plane::object_storage::OBJECT_STORAGE_DEFAULT_PORT;
26 : use control_plane::object_storage::ObjectStorage;
27 : use control_plane::pageserver::PageServerNode;
28 : use control_plane::safekeeper::SafekeeperNode;
29 : use control_plane::storage_controller::{
30 : NeonStorageControllerStartArgs, NeonStorageControllerStopArgs, StorageController,
31 : };
32 : use control_plane::{broker, local_env};
33 : use nix::fcntl::{FlockArg, flock};
34 : use pageserver_api::config::{
35 : DEFAULT_HTTP_LISTEN_PORT as DEFAULT_PAGESERVER_HTTP_PORT,
36 : DEFAULT_PG_LISTEN_PORT as DEFAULT_PAGESERVER_PG_PORT,
37 : };
38 : use pageserver_api::controller_api::{
39 : NodeAvailabilityWrapper, PlacementPolicy, TenantCreateRequest,
40 : };
41 : use pageserver_api::models::{
42 : ShardParameters, TenantConfigRequest, TimelineCreateRequest, TimelineInfo,
43 : };
44 : use pageserver_api::shard::{DEFAULT_STRIPE_SIZE, ShardCount, ShardStripeSize, TenantShardId};
45 : use postgres_backend::AuthType;
46 : use postgres_connection::parse_host_port;
47 : use safekeeper_api::membership::SafekeeperGeneration;
48 : use safekeeper_api::{
49 : DEFAULT_HTTP_LISTEN_PORT as DEFAULT_SAFEKEEPER_HTTP_PORT,
50 : DEFAULT_PG_LISTEN_PORT as DEFAULT_SAFEKEEPER_PG_PORT,
51 : };
52 : use storage_broker::DEFAULT_LISTEN_ADDR as DEFAULT_BROKER_ADDR;
53 : use tokio::task::JoinSet;
54 : use url::Host;
55 : use utils::auth::{Claims, Scope};
56 : use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId};
57 : use utils::lsn::Lsn;
58 : use utils::project_git_version;
59 :
60 : // Default id of a safekeeper node, if not specified on the command line.
61 : const DEFAULT_SAFEKEEPER_ID: NodeId = NodeId(1);
62 : const DEFAULT_PAGESERVER_ID: NodeId = NodeId(1);
63 : const DEFAULT_BRANCH_NAME: &str = "main";
64 : project_git_version!(GIT_VERSION);
65 :
66 : const DEFAULT_PG_VERSION: u32 = 17;
67 :
68 : const DEFAULT_PAGESERVER_CONTROL_PLANE_API: &str = "http://127.0.0.1:1234/upcall/v1/";
69 :
70 : #[derive(clap::Parser)]
71 : #[command(version = GIT_VERSION, about, name = "Neon CLI")]
72 : struct Cli {
73 : #[command(subcommand)]
74 : command: NeonLocalCmd,
75 : }
76 :
77 : #[derive(clap::Subcommand)]
78 : enum NeonLocalCmd {
79 : Init(InitCmdArgs),
80 :
81 : #[command(subcommand)]
82 : Tenant(TenantCmd),
83 : #[command(subcommand)]
84 : Timeline(TimelineCmd),
85 : #[command(subcommand)]
86 : Pageserver(PageserverCmd),
87 : #[command(subcommand)]
88 : #[clap(alias = "storage_controller")]
89 : StorageController(StorageControllerCmd),
90 : #[command(subcommand)]
91 : #[clap(alias = "storage_broker")]
92 : StorageBroker(StorageBrokerCmd),
93 : #[command(subcommand)]
94 : Safekeeper(SafekeeperCmd),
95 : #[command(subcommand)]
96 : ObjectStorage(ObjectStorageCmd),
97 : #[command(subcommand)]
98 : Endpoint(EndpointCmd),
99 : #[command(subcommand)]
100 : Mappings(MappingsCmd),
101 :
102 : Start(StartCmdArgs),
103 : Stop(StopCmdArgs),
104 : }
105 :
106 : #[derive(clap::Args)]
107 : #[clap(about = "Initialize a new Neon repository, preparing configs for services to start with")]
108 : struct InitCmdArgs {
109 : #[clap(long, help("How many pageservers to create (default 1)"))]
110 : num_pageservers: Option<u16>,
111 :
112 : #[clap(long)]
113 : config: Option<PathBuf>,
114 :
115 : #[clap(long, help("Force initialization even if the repository is not empty"))]
116 : #[arg(value_parser)]
117 : #[clap(default_value = "must-not-exist")]
118 0 : force: InitForceMode,
119 : }
120 :
121 : #[derive(clap::Args)]
122 : #[clap(about = "Start pageserver and safekeepers")]
123 : struct StartCmdArgs {
124 : #[clap(long = "start-timeout", default_value = "10s")]
125 0 : timeout: humantime::Duration,
126 : }
127 :
128 : #[derive(clap::Args)]
129 : #[clap(about = "Stop pageserver and safekeepers")]
130 : struct StopCmdArgs {
131 : #[arg(value_enum)]
132 0 : #[clap(long, default_value_t = StopMode::Fast)]
133 0 : mode: StopMode,
134 : }
135 :
136 : #[derive(Clone, Copy, clap::ValueEnum)]
137 : enum StopMode {
138 : Fast,
139 : Immediate,
140 : }
141 :
142 : #[derive(clap::Subcommand)]
143 : #[clap(about = "Manage tenants")]
144 : enum TenantCmd {
145 : List,
146 : Create(TenantCreateCmdArgs),
147 : SetDefault(TenantSetDefaultCmdArgs),
148 : Config(TenantConfigCmdArgs),
149 : Import(TenantImportCmdArgs),
150 : }
151 :
152 : #[derive(clap::Args)]
153 : struct TenantCreateCmdArgs {
154 : #[clap(
155 : long = "tenant-id",
156 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
157 : )]
158 : tenant_id: Option<TenantId>,
159 :
160 : #[clap(
161 : long,
162 : help = "Use a specific timeline id when creating a tenant and its initial timeline"
163 : )]
164 : timeline_id: Option<TimelineId>,
165 :
166 : #[clap(short = 'c')]
167 0 : config: Vec<String>,
168 :
169 0 : #[arg(default_value_t = DEFAULT_PG_VERSION)]
170 : #[clap(long, help = "Postgres version to use for the initial timeline")]
171 0 : pg_version: u32,
172 :
173 : #[clap(
174 : long,
175 : help = "Use this tenant in future CLI commands where tenant_id is needed, but not specified"
176 : )]
177 0 : set_default: bool,
178 :
179 : #[clap(long, help = "Number of shards in the new tenant")]
180 0 : #[arg(default_value_t = 0)]
181 0 : shard_count: u8,
182 : #[clap(long, help = "Sharding stripe size in pages")]
183 : shard_stripe_size: Option<u32>,
184 :
185 : #[clap(long, help = "Placement policy shards in this tenant")]
186 : #[arg(value_parser = parse_placement_policy)]
187 : placement_policy: Option<PlacementPolicy>,
188 : }
189 :
190 0 : fn parse_placement_policy(s: &str) -> anyhow::Result<PlacementPolicy> {
191 0 : Ok(serde_json::from_str::<PlacementPolicy>(s)?)
192 0 : }
193 :
194 : #[derive(clap::Args)]
195 : #[clap(
196 : about = "Set a particular tenant as default in future CLI commands where tenant_id is needed, but not specified"
197 : )]
198 : struct TenantSetDefaultCmdArgs {
199 : #[clap(
200 : long = "tenant-id",
201 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
202 : )]
203 0 : tenant_id: TenantId,
204 : }
205 :
206 : #[derive(clap::Args)]
207 : struct TenantConfigCmdArgs {
208 : #[clap(
209 : long = "tenant-id",
210 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
211 : )]
212 : tenant_id: Option<TenantId>,
213 :
214 : #[clap(short = 'c')]
215 0 : config: Vec<String>,
216 : }
217 :
218 : #[derive(clap::Args)]
219 : #[clap(
220 : about = "Import a tenant that is present in remote storage, and create branches for its timelines"
221 : )]
222 : struct TenantImportCmdArgs {
223 : #[clap(
224 : long = "tenant-id",
225 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
226 : )]
227 0 : tenant_id: TenantId,
228 : }
229 :
230 : #[derive(clap::Subcommand)]
231 : #[clap(about = "Manage timelines")]
232 : enum TimelineCmd {
233 : List(TimelineListCmdArgs),
234 : Branch(TimelineBranchCmdArgs),
235 : Create(TimelineCreateCmdArgs),
236 : Import(TimelineImportCmdArgs),
237 : }
238 :
239 : #[derive(clap::Args)]
240 : #[clap(about = "List all timelines available to this pageserver")]
241 : struct TimelineListCmdArgs {
242 : #[clap(
243 : long = "tenant-id",
244 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
245 : )]
246 : tenant_shard_id: Option<TenantShardId>,
247 : }
248 :
249 : #[derive(clap::Args)]
250 : #[clap(about = "Create a new timeline, branching off from another timeline")]
251 : struct TimelineBranchCmdArgs {
252 : #[clap(
253 : long = "tenant-id",
254 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
255 : )]
256 : tenant_id: Option<TenantId>,
257 :
258 : #[clap(long, help = "New timeline's ID")]
259 : timeline_id: Option<TimelineId>,
260 :
261 : #[clap(long, help = "Human-readable alias for the new timeline")]
262 0 : branch_name: String,
263 :
264 : #[clap(
265 : long,
266 : help = "Use last Lsn of another timeline (and its data) as base when creating the new timeline. The timeline gets resolved by its branch name."
267 : )]
268 : ancestor_branch_name: Option<String>,
269 :
270 : #[clap(
271 : long,
272 : help = "When using another timeline as base, use a specific Lsn in it instead of the latest one"
273 : )]
274 : ancestor_start_lsn: Option<Lsn>,
275 : }
276 :
277 : #[derive(clap::Args)]
278 : #[clap(about = "Create a new blank timeline")]
279 : struct TimelineCreateCmdArgs {
280 : #[clap(
281 : long = "tenant-id",
282 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
283 : )]
284 : tenant_id: Option<TenantId>,
285 :
286 : #[clap(long, help = "New timeline's ID")]
287 : timeline_id: Option<TimelineId>,
288 :
289 : #[clap(long, help = "Human-readable alias for the new timeline")]
290 0 : branch_name: String,
291 :
292 0 : #[arg(default_value_t = DEFAULT_PG_VERSION)]
293 : #[clap(long, help = "Postgres version")]
294 0 : pg_version: u32,
295 : }
296 :
297 : #[derive(clap::Args)]
298 : #[clap(about = "Import timeline from a basebackup directory")]
299 : struct TimelineImportCmdArgs {
300 : #[clap(
301 : long = "tenant-id",
302 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
303 : )]
304 : tenant_id: Option<TenantId>,
305 :
306 : #[clap(long, help = "New timeline's ID")]
307 0 : timeline_id: TimelineId,
308 :
309 : #[clap(long, help = "Human-readable alias for the new timeline")]
310 0 : branch_name: String,
311 :
312 : #[clap(long, help = "Basebackup tarfile to import")]
313 0 : base_tarfile: PathBuf,
314 :
315 : #[clap(long, help = "Lsn the basebackup starts at")]
316 0 : base_lsn: Lsn,
317 :
318 : #[clap(long, help = "Wal to add after base")]
319 : wal_tarfile: Option<PathBuf>,
320 :
321 : #[clap(long, help = "Lsn the basebackup ends at")]
322 : end_lsn: Option<Lsn>,
323 :
324 0 : #[arg(default_value_t = DEFAULT_PG_VERSION)]
325 : #[clap(long, help = "Postgres version of the backup being imported")]
326 0 : pg_version: u32,
327 : }
328 :
329 : #[derive(clap::Subcommand)]
330 : #[clap(about = "Manage pageservers")]
331 : enum PageserverCmd {
332 : Status(PageserverStatusCmdArgs),
333 : Start(PageserverStartCmdArgs),
334 : Stop(PageserverStopCmdArgs),
335 : Restart(PageserverRestartCmdArgs),
336 : }
337 :
338 : #[derive(clap::Args)]
339 : #[clap(about = "Show status of a local pageserver")]
340 : struct PageserverStatusCmdArgs {
341 : #[clap(long = "id", help = "pageserver id")]
342 : pageserver_id: Option<NodeId>,
343 : }
344 :
345 : #[derive(clap::Args)]
346 : #[clap(about = "Start local pageserver")]
347 : struct PageserverStartCmdArgs {
348 : #[clap(long = "id", help = "pageserver id")]
349 : pageserver_id: Option<NodeId>,
350 :
351 : #[clap(short = 't', long, help = "timeout until we fail the command")]
352 : #[arg(default_value = "10s")]
353 0 : start_timeout: humantime::Duration,
354 : }
355 :
356 : #[derive(clap::Args)]
357 : #[clap(about = "Stop local pageserver")]
358 : struct PageserverStopCmdArgs {
359 : #[clap(long = "id", help = "pageserver id")]
360 : pageserver_id: Option<NodeId>,
361 :
362 : #[clap(
363 : short = 'm',
364 : help = "If 'immediate', don't flush repository data at shutdown"
365 : )]
366 : #[arg(value_enum, default_value = "fast")]
367 0 : stop_mode: StopMode,
368 : }
369 :
370 : #[derive(clap::Args)]
371 : #[clap(about = "Restart local pageserver")]
372 : struct PageserverRestartCmdArgs {
373 : #[clap(long = "id", help = "pageserver id")]
374 : pageserver_id: Option<NodeId>,
375 :
376 : #[clap(short = 't', long, help = "timeout until we fail the command")]
377 : #[arg(default_value = "10s")]
378 0 : start_timeout: humantime::Duration,
379 : }
380 :
381 : #[derive(clap::Subcommand)]
382 : #[clap(about = "Manage storage controller")]
383 : enum StorageControllerCmd {
384 : Start(StorageControllerStartCmdArgs),
385 : Stop(StorageControllerStopCmdArgs),
386 : }
387 :
388 : #[derive(clap::Args)]
389 : #[clap(about = "Start storage controller")]
390 : struct StorageControllerStartCmdArgs {
391 : #[clap(short = 't', long, help = "timeout until we fail the command")]
392 : #[arg(default_value = "10s")]
393 0 : start_timeout: humantime::Duration,
394 :
395 : #[clap(
396 : long,
397 : help = "Identifier used to distinguish storage controller instances"
398 : )]
399 0 : #[arg(default_value_t = 1)]
400 0 : instance_id: u8,
401 :
402 : #[clap(
403 : long,
404 : help = "Base port for the storage controller instance idenfified by instance-id (defaults to pageserver cplane api)"
405 : )]
406 : base_port: Option<u16>,
407 : }
408 :
409 : #[derive(clap::Args)]
410 : #[clap(about = "Stop storage controller")]
411 : struct StorageControllerStopCmdArgs {
412 : #[clap(
413 : short = 'm',
414 : help = "If 'immediate', don't flush repository data at shutdown"
415 : )]
416 : #[arg(value_enum, default_value = "fast")]
417 0 : stop_mode: StopMode,
418 :
419 : #[clap(
420 : long,
421 : help = "Identifier used to distinguish storage controller instances"
422 : )]
423 0 : #[arg(default_value_t = 1)]
424 0 : instance_id: u8,
425 : }
426 :
427 : #[derive(clap::Subcommand)]
428 : #[clap(about = "Manage storage broker")]
429 : enum StorageBrokerCmd {
430 : Start(StorageBrokerStartCmdArgs),
431 : Stop(StorageBrokerStopCmdArgs),
432 : }
433 :
434 : #[derive(clap::Args)]
435 : #[clap(about = "Start broker")]
436 : struct StorageBrokerStartCmdArgs {
437 : #[clap(short = 't', long, help = "timeout until we fail the command")]
438 : #[arg(default_value = "10s")]
439 0 : start_timeout: humantime::Duration,
440 : }
441 :
442 : #[derive(clap::Args)]
443 : #[clap(about = "stop broker")]
444 : struct StorageBrokerStopCmdArgs {
445 : #[clap(
446 : short = 'm',
447 : help = "If 'immediate', don't flush repository data at shutdown"
448 : )]
449 : #[arg(value_enum, default_value = "fast")]
450 0 : stop_mode: StopMode,
451 : }
452 :
453 : #[derive(clap::Subcommand)]
454 : #[clap(about = "Manage safekeepers")]
455 : enum SafekeeperCmd {
456 : Start(SafekeeperStartCmdArgs),
457 : Stop(SafekeeperStopCmdArgs),
458 : Restart(SafekeeperRestartCmdArgs),
459 : }
460 :
461 : #[derive(clap::Subcommand)]
462 : #[clap(about = "Manage object storage")]
463 : enum ObjectStorageCmd {
464 : Start(ObjectStorageStartCmd),
465 : Stop(ObjectStorageStopCmd),
466 : }
467 :
468 : #[derive(clap::Args)]
469 : #[clap(about = "Start object storage")]
470 : struct ObjectStorageStartCmd {
471 : #[clap(short = 't', long, help = "timeout until we fail the command")]
472 : #[arg(default_value = "10s")]
473 0 : start_timeout: humantime::Duration,
474 : }
475 :
476 : #[derive(clap::Args)]
477 : #[clap(about = "Stop object storage")]
478 : struct ObjectStorageStopCmd {
479 : #[arg(value_enum, default_value = "fast")]
480 : #[clap(
481 : short = 'm',
482 : help = "If 'immediate', don't flush repository data at shutdown"
483 : )]
484 0 : stop_mode: StopMode,
485 : }
486 :
487 : #[derive(clap::Args)]
488 : #[clap(about = "Start local safekeeper")]
489 : struct SafekeeperStartCmdArgs {
490 : #[clap(help = "safekeeper id")]
491 0 : #[arg(default_value_t = NodeId(1))]
492 0 : id: NodeId,
493 :
494 : #[clap(
495 : short = 'e',
496 : long = "safekeeper-extra-opt",
497 : help = "Additional safekeeper invocation options, e.g. -e=--http-auth-public-key-path=foo"
498 : )]
499 0 : extra_opt: Vec<String>,
500 :
501 : #[clap(short = 't', long, help = "timeout until we fail the command")]
502 : #[arg(default_value = "10s")]
503 0 : start_timeout: humantime::Duration,
504 : }
505 :
506 : #[derive(clap::Args)]
507 : #[clap(about = "Stop local safekeeper")]
508 : struct SafekeeperStopCmdArgs {
509 : #[clap(help = "safekeeper id")]
510 0 : #[arg(default_value_t = NodeId(1))]
511 0 : id: NodeId,
512 :
513 : #[arg(value_enum, default_value = "fast")]
514 : #[clap(
515 : short = 'm',
516 : help = "If 'immediate', don't flush repository data at shutdown"
517 : )]
518 0 : stop_mode: StopMode,
519 : }
520 :
521 : #[derive(clap::Args)]
522 : #[clap(about = "Restart local safekeeper")]
523 : struct SafekeeperRestartCmdArgs {
524 : #[clap(help = "safekeeper id")]
525 0 : #[arg(default_value_t = NodeId(1))]
526 0 : id: NodeId,
527 :
528 : #[arg(value_enum, default_value = "fast")]
529 : #[clap(
530 : short = 'm',
531 : help = "If 'immediate', don't flush repository data at shutdown"
532 : )]
533 0 : stop_mode: StopMode,
534 :
535 : #[clap(
536 : short = 'e',
537 : long = "safekeeper-extra-opt",
538 : help = "Additional safekeeper invocation options, e.g. -e=--http-auth-public-key-path=foo"
539 : )]
540 0 : extra_opt: Vec<String>,
541 :
542 : #[clap(short = 't', long, help = "timeout until we fail the command")]
543 : #[arg(default_value = "10s")]
544 0 : start_timeout: humantime::Duration,
545 : }
546 :
547 : #[derive(clap::Subcommand)]
548 : #[clap(about = "Manage Postgres instances")]
549 : enum EndpointCmd {
550 : List(EndpointListCmdArgs),
551 : Create(EndpointCreateCmdArgs),
552 : Start(EndpointStartCmdArgs),
553 : Reconfigure(EndpointReconfigureCmdArgs),
554 : Stop(EndpointStopCmdArgs),
555 : GenerateJwt(EndpointGenerateJwtCmdArgs),
556 : }
557 :
558 : #[derive(clap::Args)]
559 : #[clap(about = "List endpoints")]
560 : struct EndpointListCmdArgs {
561 : #[clap(
562 : long = "tenant-id",
563 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
564 : )]
565 : tenant_shard_id: Option<TenantShardId>,
566 : }
567 :
568 : #[derive(clap::Args)]
569 : #[clap(about = "Create a compute endpoint")]
570 : struct EndpointCreateCmdArgs {
571 : #[clap(
572 : long = "tenant-id",
573 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
574 : )]
575 : tenant_id: Option<TenantId>,
576 :
577 : #[clap(help = "Postgres endpoint id")]
578 : endpoint_id: Option<String>,
579 : #[clap(long, help = "Name of the branch the endpoint will run on")]
580 : branch_name: Option<String>,
581 : #[clap(
582 : long,
583 : help = "Specify Lsn on the timeline to start from. By default, end of the timeline would be used"
584 : )]
585 : lsn: Option<Lsn>,
586 : #[clap(long)]
587 : pg_port: Option<u16>,
588 : #[clap(long, alias = "http-port")]
589 : external_http_port: Option<u16>,
590 : #[clap(long)]
591 : internal_http_port: Option<u16>,
592 : #[clap(long = "pageserver-id")]
593 : endpoint_pageserver_id: Option<NodeId>,
594 :
595 : #[clap(
596 : long,
597 : help = "Don't do basebackup, create endpoint directory with only config files",
598 : action = clap::ArgAction::Set,
599 0 : default_value_t = false
600 : )]
601 0 : config_only: bool,
602 :
603 0 : #[arg(default_value_t = DEFAULT_PG_VERSION)]
604 : #[clap(long, help = "Postgres version")]
605 0 : pg_version: u32,
606 :
607 : #[clap(
608 : long,
609 : help = "If set, the node will be a hot replica on the specified timeline",
610 : action = clap::ArgAction::Set,
611 0 : default_value_t = false
612 : )]
613 0 : hot_standby: bool,
614 :
615 : #[clap(long, help = "If set, will set up the catalog for neon_superuser")]
616 0 : update_catalog: bool,
617 :
618 : #[clap(
619 : long,
620 : help = "Allow multiple primary endpoints running on the same branch. Shouldn't be used normally, but useful for tests."
621 : )]
622 0 : allow_multiple: bool,
623 : }
624 :
625 : #[derive(clap::Args)]
626 : #[clap(about = "Start postgres. If the endpoint doesn't exist yet, it is created.")]
627 : struct EndpointStartCmdArgs {
628 : #[clap(help = "Postgres endpoint id")]
629 0 : endpoint_id: String,
630 : #[clap(long = "pageserver-id")]
631 : endpoint_pageserver_id: Option<NodeId>,
632 :
633 : #[clap(
634 : long,
635 : help = "Safekeepers membership generation to prefix neon.safekeepers with. Normally neon_local sets it on its own, but this option allows to override. Non zero value forces endpoint to use membership configurations."
636 : )]
637 : safekeepers_generation: Option<u32>,
638 : #[clap(
639 : long,
640 : help = "List of safekeepers endpoint will talk to. Normally neon_local chooses them on its own, but this option allows to override."
641 : )]
642 : safekeepers: Option<String>,
643 :
644 : #[clap(
645 : long,
646 : help = "Configure the remote extensions storage proxy gateway to request for extensions."
647 : )]
648 : remote_ext_config: Option<String>,
649 :
650 : #[clap(
651 : long,
652 : help = "If set, will create test user `user` and `neondb` database. Requires `update-catalog = true`"
653 : )]
654 0 : create_test_user: bool,
655 :
656 : #[clap(
657 : long,
658 : help = "Allow multiple primary endpoints running on the same branch. Shouldn't be used normally, but useful for tests."
659 : )]
660 0 : allow_multiple: bool,
661 :
662 : #[clap(short = 't', long, value_parser= humantime::parse_duration, help = "timeout until we fail the command")]
663 : #[arg(default_value = "90s")]
664 0 : start_timeout: Duration,
665 : }
666 :
667 : #[derive(clap::Args)]
668 : #[clap(about = "Reconfigure an endpoint")]
669 : struct EndpointReconfigureCmdArgs {
670 : #[clap(
671 : long = "tenant-id",
672 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
673 : )]
674 : tenant_id: Option<TenantId>,
675 :
676 : #[clap(help = "Postgres endpoint id")]
677 0 : endpoint_id: String,
678 : #[clap(long = "pageserver-id")]
679 : endpoint_pageserver_id: Option<NodeId>,
680 :
681 : #[clap(long)]
682 : safekeepers: Option<String>,
683 : }
684 :
685 : #[derive(clap::Args)]
686 : #[clap(about = "Stop an endpoint")]
687 : struct EndpointStopCmdArgs {
688 : #[clap(help = "Postgres endpoint id")]
689 0 : endpoint_id: String,
690 :
691 : #[clap(
692 : long,
693 : help = "Also delete data directory (now optional, should be default in future)"
694 : )]
695 0 : destroy: bool,
696 :
697 : #[clap(long, help = "Postgres shutdown mode, passed to \"pg_ctl -m <mode>\"")]
698 : #[arg(value_parser(["smart", "fast", "immediate"]))]
699 : #[arg(default_value = "fast")]
700 0 : mode: String,
701 : }
702 :
703 : #[derive(clap::Args)]
704 : #[clap(about = "Generate a JWT for an endpoint")]
705 : struct EndpointGenerateJwtCmdArgs {
706 : #[clap(help = "Postgres endpoint id")]
707 0 : endpoint_id: String,
708 : }
709 :
710 : #[derive(clap::Subcommand)]
711 : #[clap(about = "Manage neon_local branch name mappings")]
712 : enum MappingsCmd {
713 : Map(MappingsMapCmdArgs),
714 : }
715 :
716 : #[derive(clap::Args)]
717 : #[clap(about = "Create new mapping which cannot exist already")]
718 : struct MappingsMapCmdArgs {
719 : #[clap(
720 : long,
721 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
722 : )]
723 0 : tenant_id: TenantId,
724 : #[clap(
725 : long,
726 : help = "Timeline id. Represented as a hexadecimal string 32 symbols length"
727 : )]
728 0 : timeline_id: TimelineId,
729 : #[clap(long, help = "Branch name to give to the timeline")]
730 0 : branch_name: String,
731 : }
732 :
733 : ///
734 : /// Timelines tree element used as a value in the HashMap.
735 : ///
736 : struct TimelineTreeEl {
737 : /// `TimelineInfo` received from the `pageserver` via the `timeline_list` http API call.
738 : pub info: TimelineInfo,
739 : /// Name, recovered from neon config mappings
740 : pub name: Option<String>,
741 : /// Holds all direct children of this timeline referenced using `timeline_id`.
742 : pub children: BTreeSet<TimelineId>,
743 : }
744 :
745 : /// A flock-based guard over the neon_local repository directory
746 : struct RepoLock {
747 : _file: File,
748 : }
749 :
750 : impl RepoLock {
751 0 : fn new() -> Result<Self> {
752 0 : let repo_dir = File::open(local_env::base_path())?;
753 0 : let repo_dir_fd = repo_dir.as_raw_fd();
754 0 : flock(repo_dir_fd, FlockArg::LockExclusive)?;
755 :
756 0 : Ok(Self { _file: repo_dir })
757 0 : }
758 : }
759 :
760 : // Main entry point for the 'neon_local' CLI utility
761 : //
762 : // This utility helps to manage neon installation. That includes following:
763 : // * Management of local postgres installations running on top of the
764 : // pageserver.
765 : // * Providing CLI api to the pageserver
766 : // * TODO: export/import to/from usual postgres
767 0 : fn main() -> Result<()> {
768 0 : let cli = Cli::parse();
769 :
770 : // Check for 'neon init' command first.
771 0 : let (subcommand_result, _lock) = if let NeonLocalCmd::Init(args) = cli.command {
772 0 : (handle_init(&args).map(|env| Some(Cow::Owned(env))), None)
773 : } else {
774 : // This tool uses a collection of simple files to store its state, and consequently
775 : // it is not generally safe to run multiple commands concurrently. Rather than expect
776 : // all callers to know this, use a lock file to protect against concurrent execution.
777 0 : let _repo_lock = RepoLock::new().unwrap();
778 :
779 : // all other commands need an existing config
780 0 : let env = LocalEnv::load_config(&local_env::base_path()).context("Error loading config")?;
781 0 : let original_env = env.clone();
782 0 : let env = Box::leak(Box::new(env));
783 0 : let rt = tokio::runtime::Builder::new_current_thread()
784 0 : .enable_all()
785 0 : .build()
786 0 : .unwrap();
787 :
788 0 : let subcommand_result = match cli.command {
789 0 : NeonLocalCmd::Init(_) => unreachable!("init was handled earlier already"),
790 0 : NeonLocalCmd::Start(args) => rt.block_on(handle_start_all(&args, env)),
791 0 : NeonLocalCmd::Stop(args) => rt.block_on(handle_stop_all(&args, env)),
792 0 : NeonLocalCmd::Tenant(subcmd) => rt.block_on(handle_tenant(&subcmd, env)),
793 0 : NeonLocalCmd::Timeline(subcmd) => rt.block_on(handle_timeline(&subcmd, env)),
794 0 : NeonLocalCmd::Pageserver(subcmd) => rt.block_on(handle_pageserver(&subcmd, env)),
795 0 : NeonLocalCmd::StorageController(subcmd) => {
796 0 : rt.block_on(handle_storage_controller(&subcmd, env))
797 : }
798 0 : NeonLocalCmd::StorageBroker(subcmd) => rt.block_on(handle_storage_broker(&subcmd, env)),
799 0 : NeonLocalCmd::Safekeeper(subcmd) => rt.block_on(handle_safekeeper(&subcmd, env)),
800 0 : NeonLocalCmd::ObjectStorage(subcmd) => rt.block_on(handle_object_storage(&subcmd, env)),
801 0 : NeonLocalCmd::Endpoint(subcmd) => rt.block_on(handle_endpoint(&subcmd, env)),
802 0 : NeonLocalCmd::Mappings(subcmd) => handle_mappings(&subcmd, env),
803 : };
804 :
805 0 : let subcommand_result = if &original_env != env {
806 0 : subcommand_result.map(|()| Some(Cow::Borrowed(env)))
807 : } else {
808 0 : subcommand_result.map(|()| None)
809 : };
810 0 : (subcommand_result, Some(_repo_lock))
811 : };
812 :
813 0 : match subcommand_result {
814 0 : Ok(Some(updated_env)) => updated_env.persist_config()?,
815 0 : Ok(None) => (),
816 0 : Err(e) => {
817 0 : eprintln!("command failed: {e:?}");
818 0 : exit(1);
819 : }
820 : }
821 0 : Ok(())
822 0 : }
823 :
824 : ///
825 : /// Prints timelines list as a tree-like structure.
826 : ///
827 0 : fn print_timelines_tree(
828 0 : timelines: Vec<TimelineInfo>,
829 0 : mut timeline_name_mappings: HashMap<TenantTimelineId, String>,
830 0 : ) -> Result<()> {
831 0 : let mut timelines_hash = timelines
832 0 : .iter()
833 0 : .map(|t| {
834 0 : (
835 0 : t.timeline_id,
836 0 : TimelineTreeEl {
837 0 : info: t.clone(),
838 0 : children: BTreeSet::new(),
839 0 : name: timeline_name_mappings
840 0 : .remove(&TenantTimelineId::new(t.tenant_id.tenant_id, t.timeline_id)),
841 0 : },
842 0 : )
843 0 : })
844 0 : .collect::<HashMap<_, _>>();
845 :
846 : // Memorize all direct children of each timeline.
847 0 : for timeline in timelines.iter() {
848 0 : if let Some(ancestor_timeline_id) = timeline.ancestor_timeline_id {
849 0 : timelines_hash
850 0 : .get_mut(&ancestor_timeline_id)
851 0 : .context("missing timeline info in the HashMap")?
852 : .children
853 0 : .insert(timeline.timeline_id);
854 0 : }
855 : }
856 :
857 0 : for timeline in timelines_hash.values() {
858 : // Start with root local timelines (no ancestors) first.
859 0 : if timeline.info.ancestor_timeline_id.is_none() {
860 0 : print_timeline(0, &Vec::from([true]), timeline, &timelines_hash)?;
861 0 : }
862 : }
863 :
864 0 : Ok(())
865 0 : }
866 :
867 : ///
868 : /// Recursively prints timeline info with all its children.
869 : ///
870 0 : fn print_timeline(
871 0 : nesting_level: usize,
872 0 : is_last: &[bool],
873 0 : timeline: &TimelineTreeEl,
874 0 : timelines: &HashMap<TimelineId, TimelineTreeEl>,
875 0 : ) -> Result<()> {
876 0 : if nesting_level > 0 {
877 0 : let ancestor_lsn = match timeline.info.ancestor_lsn {
878 0 : Some(lsn) => lsn.to_string(),
879 0 : None => "Unknown Lsn".to_string(),
880 : };
881 :
882 0 : let mut br_sym = "┣━";
883 0 :
884 0 : // Draw each nesting padding with proper style
885 0 : // depending on whether its timeline ended or not.
886 0 : if nesting_level > 1 {
887 0 : for l in &is_last[1..is_last.len() - 1] {
888 0 : if *l {
889 0 : print!(" ");
890 0 : } else {
891 0 : print!("┃ ");
892 0 : }
893 : }
894 0 : }
895 :
896 : // We are the last in this sub-timeline
897 0 : if *is_last.last().unwrap() {
898 0 : br_sym = "┗━";
899 0 : }
900 :
901 0 : print!("{} @{}: ", br_sym, ancestor_lsn);
902 0 : }
903 :
904 : // Finally print a timeline id and name with new line
905 0 : println!(
906 0 : "{} [{}]",
907 0 : timeline.name.as_deref().unwrap_or("_no_name_"),
908 0 : timeline.info.timeline_id
909 0 : );
910 0 :
911 0 : let len = timeline.children.len();
912 0 : let mut i: usize = 0;
913 0 : let mut is_last_new = Vec::from(is_last);
914 0 : is_last_new.push(false);
915 :
916 0 : for child in &timeline.children {
917 0 : i += 1;
918 0 :
919 0 : // Mark that the last padding is the end of the timeline
920 0 : if i == len {
921 0 : if let Some(last) = is_last_new.last_mut() {
922 0 : *last = true;
923 0 : }
924 0 : }
925 :
926 : print_timeline(
927 0 : nesting_level + 1,
928 0 : &is_last_new,
929 0 : timelines
930 0 : .get(child)
931 0 : .context("missing timeline info in the HashMap")?,
932 0 : timelines,
933 0 : )?;
934 : }
935 :
936 0 : Ok(())
937 0 : }
938 :
939 : /// Helper function to get tenant id from an optional --tenant_id option or from the config file
940 0 : fn get_tenant_id(
941 0 : tenant_id_arg: Option<TenantId>,
942 0 : env: &local_env::LocalEnv,
943 0 : ) -> anyhow::Result<TenantId> {
944 0 : if let Some(tenant_id_from_arguments) = tenant_id_arg {
945 0 : Ok(tenant_id_from_arguments)
946 0 : } else if let Some(default_id) = env.default_tenant_id {
947 0 : Ok(default_id)
948 : } else {
949 0 : anyhow::bail!("No tenant id. Use --tenant-id, or set a default tenant");
950 : }
951 0 : }
952 :
953 : /// Helper function to get tenant-shard ID from an optional --tenant_id option or from the config file,
954 : /// for commands that accept a shard suffix
955 0 : fn get_tenant_shard_id(
956 0 : tenant_shard_id_arg: Option<TenantShardId>,
957 0 : env: &local_env::LocalEnv,
958 0 : ) -> anyhow::Result<TenantShardId> {
959 0 : if let Some(tenant_id_from_arguments) = tenant_shard_id_arg {
960 0 : Ok(tenant_id_from_arguments)
961 0 : } else if let Some(default_id) = env.default_tenant_id {
962 0 : Ok(TenantShardId::unsharded(default_id))
963 : } else {
964 0 : anyhow::bail!("No tenant shard id. Use --tenant-id, or set a default tenant");
965 : }
966 0 : }
967 :
968 0 : fn handle_init(args: &InitCmdArgs) -> anyhow::Result<LocalEnv> {
969 : // Create the in-memory `LocalEnv` that we'd normally load from disk in `load_config`.
970 0 : let init_conf: NeonLocalInitConf = if let Some(config_path) = &args.config {
971 : // User (likely the Python test suite) provided a description of the environment.
972 0 : if args.num_pageservers.is_some() {
973 0 : bail!(
974 0 : "Cannot specify both --num-pageservers and --config, use key `pageservers` in the --config file instead"
975 0 : );
976 0 : }
977 : // load and parse the file
978 0 : let contents = std::fs::read_to_string(config_path).with_context(|| {
979 0 : format!(
980 0 : "Could not read configuration file '{}'",
981 0 : config_path.display()
982 0 : )
983 0 : })?;
984 0 : toml_edit::de::from_str(&contents)?
985 : } else {
986 : // User (likely interactive) did not provide a description of the environment, give them the default
987 0 : NeonLocalInitConf {
988 0 : control_plane_api: Some(DEFAULT_PAGESERVER_CONTROL_PLANE_API.parse().unwrap()),
989 0 : broker: NeonBroker {
990 0 : listen_addr: DEFAULT_BROKER_ADDR.parse().unwrap(),
991 0 : },
992 0 : safekeepers: vec![SafekeeperConf {
993 0 : id: DEFAULT_SAFEKEEPER_ID,
994 0 : pg_port: DEFAULT_SAFEKEEPER_PG_PORT,
995 0 : http_port: DEFAULT_SAFEKEEPER_HTTP_PORT,
996 0 : ..Default::default()
997 0 : }],
998 0 : pageservers: (0..args.num_pageservers.unwrap_or(1))
999 0 : .map(|i| {
1000 0 : let pageserver_id = NodeId(DEFAULT_PAGESERVER_ID.0 + i as u64);
1001 0 : let pg_port = DEFAULT_PAGESERVER_PG_PORT + i;
1002 0 : let http_port = DEFAULT_PAGESERVER_HTTP_PORT + i;
1003 0 : NeonLocalInitPageserverConf {
1004 0 : id: pageserver_id,
1005 0 : listen_pg_addr: format!("127.0.0.1:{pg_port}"),
1006 0 : listen_http_addr: format!("127.0.0.1:{http_port}"),
1007 0 : listen_https_addr: None,
1008 0 : pg_auth_type: AuthType::Trust,
1009 0 : http_auth_type: AuthType::Trust,
1010 0 : other: Default::default(),
1011 0 : // Typical developer machines use disks with slow fsync, and we don't care
1012 0 : // about data integrity: disable disk syncs.
1013 0 : no_sync: true,
1014 0 : }
1015 0 : })
1016 0 : .collect(),
1017 0 : object_storage: ObjectStorageConf {
1018 0 : port: OBJECT_STORAGE_DEFAULT_PORT,
1019 0 : },
1020 0 : pg_distrib_dir: None,
1021 0 : neon_distrib_dir: None,
1022 0 : default_tenant_id: TenantId::from_array(std::array::from_fn(|_| 0)),
1023 0 : storage_controller: None,
1024 0 : control_plane_hooks_api: None,
1025 0 : generate_local_ssl_certs: false,
1026 0 : }
1027 : };
1028 :
1029 0 : LocalEnv::init(init_conf, &args.force)
1030 0 : .context("materialize initial neon_local environment on disk")?;
1031 0 : Ok(LocalEnv::load_config(&local_env::base_path())
1032 0 : .expect("freshly written config should be loadable"))
1033 0 : }
1034 :
1035 : /// The default pageserver is the one where CLI tenant/timeline operations are sent by default.
1036 : /// For typical interactive use, one would just run with a single pageserver. Scenarios with
1037 : /// tenant/timeline placement across multiple pageservers are managed by python test code rather
1038 : /// than this CLI.
1039 0 : fn get_default_pageserver(env: &local_env::LocalEnv) -> PageServerNode {
1040 0 : let ps_conf = env
1041 0 : .pageservers
1042 0 : .first()
1043 0 : .expect("Config is validated to contain at least one pageserver");
1044 0 : PageServerNode::from_env(env, ps_conf)
1045 0 : }
1046 :
1047 0 : async fn handle_tenant(subcmd: &TenantCmd, env: &mut local_env::LocalEnv) -> anyhow::Result<()> {
1048 0 : let pageserver = get_default_pageserver(env);
1049 0 : match subcmd {
1050 : TenantCmd::List => {
1051 0 : for t in pageserver.tenant_list().await? {
1052 0 : println!("{} {:?}", t.id, t.state);
1053 0 : }
1054 : }
1055 0 : TenantCmd::Import(args) => {
1056 0 : let tenant_id = args.tenant_id;
1057 0 :
1058 0 : let storage_controller = StorageController::from_env(env);
1059 0 : let create_response = storage_controller.tenant_import(tenant_id).await?;
1060 :
1061 0 : let shard_zero = create_response
1062 0 : .shards
1063 0 : .first()
1064 0 : .expect("Import response omitted shards");
1065 0 :
1066 0 : let attached_pageserver_id = shard_zero.node_id;
1067 0 : let pageserver =
1068 0 : PageServerNode::from_env(env, env.get_pageserver_conf(attached_pageserver_id)?);
1069 :
1070 0 : println!(
1071 0 : "Imported tenant {tenant_id}, attached to pageserver {attached_pageserver_id}"
1072 0 : );
1073 :
1074 0 : let timelines = pageserver
1075 0 : .http_client
1076 0 : .list_timelines(shard_zero.shard_id)
1077 0 : .await?;
1078 :
1079 : // Pick a 'main' timeline that has no ancestors, the rest will get arbitrary names
1080 0 : let main_timeline = timelines
1081 0 : .iter()
1082 0 : .find(|t| t.ancestor_timeline_id.is_none())
1083 0 : .expect("No timelines found")
1084 0 : .timeline_id;
1085 0 :
1086 0 : let mut branch_i = 0;
1087 0 : for timeline in timelines.iter() {
1088 0 : let branch_name = if timeline.timeline_id == main_timeline {
1089 0 : "main".to_string()
1090 : } else {
1091 0 : branch_i += 1;
1092 0 : format!("branch_{branch_i}")
1093 : };
1094 :
1095 0 : println!(
1096 0 : "Importing timeline {tenant_id}/{} as branch {branch_name}",
1097 0 : timeline.timeline_id
1098 0 : );
1099 0 :
1100 0 : env.register_branch_mapping(branch_name, tenant_id, timeline.timeline_id)?;
1101 : }
1102 : }
1103 0 : TenantCmd::Create(args) => {
1104 0 : let tenant_conf: HashMap<_, _> =
1105 0 : args.config.iter().flat_map(|c| c.split_once(':')).collect();
1106 :
1107 0 : let tenant_conf = PageServerNode::parse_config(tenant_conf)?;
1108 :
1109 : // If tenant ID was not specified, generate one
1110 0 : let tenant_id = args.tenant_id.unwrap_or_else(TenantId::generate);
1111 0 :
1112 0 : // We must register the tenant with the storage controller, so
1113 0 : // that when the pageserver restarts, it will be re-attached.
1114 0 : let storage_controller = StorageController::from_env(env);
1115 0 : storage_controller
1116 0 : .tenant_create(TenantCreateRequest {
1117 0 : // Note that ::unsharded here isn't actually because the tenant is unsharded, its because the
1118 0 : // storage controller expects a shard-naive tenant_id in this attribute, and the TenantCreateRequest
1119 0 : // type is used both in the storage controller (for creating tenants) and in the pageserver (for
1120 0 : // creating shards)
1121 0 : new_tenant_id: TenantShardId::unsharded(tenant_id),
1122 0 : generation: None,
1123 0 : shard_parameters: ShardParameters {
1124 0 : count: ShardCount::new(args.shard_count),
1125 0 : stripe_size: args
1126 0 : .shard_stripe_size
1127 0 : .map(ShardStripeSize)
1128 0 : .unwrap_or(DEFAULT_STRIPE_SIZE),
1129 0 : },
1130 0 : placement_policy: args.placement_policy.clone(),
1131 0 : config: tenant_conf,
1132 0 : })
1133 0 : .await?;
1134 0 : println!("tenant {tenant_id} successfully created on the pageserver");
1135 0 :
1136 0 : // Create an initial timeline for the new tenant
1137 0 : let new_timeline_id = args.timeline_id.unwrap_or(TimelineId::generate());
1138 0 :
1139 0 : // FIXME: passing None for ancestor_start_lsn is not kosher in a sharded world: we can't have
1140 0 : // different shards picking different start lsns. Maybe we have to teach storage controller
1141 0 : // to let shard 0 branch first and then propagate the chosen LSN to other shards.
1142 0 : storage_controller
1143 0 : .tenant_timeline_create(
1144 0 : tenant_id,
1145 0 : TimelineCreateRequest {
1146 0 : new_timeline_id,
1147 0 : mode: pageserver_api::models::TimelineCreateRequestMode::Bootstrap {
1148 0 : existing_initdb_timeline_id: None,
1149 0 : pg_version: Some(args.pg_version),
1150 0 : },
1151 0 : },
1152 0 : )
1153 0 : .await?;
1154 :
1155 0 : env.register_branch_mapping(
1156 0 : DEFAULT_BRANCH_NAME.to_string(),
1157 0 : tenant_id,
1158 0 : new_timeline_id,
1159 0 : )?;
1160 :
1161 0 : println!("Created an initial timeline '{new_timeline_id}' for tenant: {tenant_id}",);
1162 0 :
1163 0 : if args.set_default {
1164 0 : println!("Setting tenant {tenant_id} as a default one");
1165 0 : env.default_tenant_id = Some(tenant_id);
1166 0 : }
1167 : }
1168 0 : TenantCmd::SetDefault(args) => {
1169 0 : println!("Setting tenant {} as a default one", args.tenant_id);
1170 0 : env.default_tenant_id = Some(args.tenant_id);
1171 0 : }
1172 0 : TenantCmd::Config(args) => {
1173 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1174 0 : let tenant_conf: HashMap<_, _> =
1175 0 : args.config.iter().flat_map(|c| c.split_once(':')).collect();
1176 0 : let config = PageServerNode::parse_config(tenant_conf)?;
1177 :
1178 0 : let req = TenantConfigRequest { tenant_id, config };
1179 0 :
1180 0 : let storage_controller = StorageController::from_env(env);
1181 0 : storage_controller
1182 0 : .set_tenant_config(&req)
1183 0 : .await
1184 0 : .with_context(|| format!("Tenant config failed for tenant with id {tenant_id}"))?;
1185 0 : println!("tenant {tenant_id} successfully configured via storcon");
1186 : }
1187 : }
1188 0 : Ok(())
1189 0 : }
1190 :
1191 0 : async fn handle_timeline(cmd: &TimelineCmd, env: &mut local_env::LocalEnv) -> Result<()> {
1192 0 : let pageserver = get_default_pageserver(env);
1193 0 :
1194 0 : match cmd {
1195 0 : TimelineCmd::List(args) => {
1196 : // TODO(sharding): this command shouldn't have to specify a shard ID: we should ask the storage controller
1197 : // where shard 0 is attached, and query there.
1198 0 : let tenant_shard_id = get_tenant_shard_id(args.tenant_shard_id, env)?;
1199 0 : let timelines = pageserver.timeline_list(&tenant_shard_id).await?;
1200 0 : print_timelines_tree(timelines, env.timeline_name_mappings())?;
1201 : }
1202 0 : TimelineCmd::Create(args) => {
1203 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1204 0 : let new_branch_name = &args.branch_name;
1205 0 : let new_timeline_id_opt = args.timeline_id;
1206 0 : let new_timeline_id = new_timeline_id_opt.unwrap_or(TimelineId::generate());
1207 0 :
1208 0 : let storage_controller = StorageController::from_env(env);
1209 0 : let create_req = TimelineCreateRequest {
1210 0 : new_timeline_id,
1211 0 : mode: pageserver_api::models::TimelineCreateRequestMode::Bootstrap {
1212 0 : existing_initdb_timeline_id: None,
1213 0 : pg_version: Some(args.pg_version),
1214 0 : },
1215 0 : };
1216 0 : let timeline_info = storage_controller
1217 0 : .tenant_timeline_create(tenant_id, create_req)
1218 0 : .await?;
1219 :
1220 0 : let last_record_lsn = timeline_info.last_record_lsn;
1221 0 : env.register_branch_mapping(new_branch_name.to_string(), tenant_id, new_timeline_id)?;
1222 :
1223 0 : println!(
1224 0 : "Created timeline '{}' at Lsn {last_record_lsn} for tenant: {tenant_id}",
1225 0 : timeline_info.timeline_id
1226 0 : );
1227 : }
1228 : // TODO: rename to import-basebackup-plus-wal
1229 0 : TimelineCmd::Import(args) => {
1230 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1231 0 : let timeline_id = args.timeline_id;
1232 0 : let branch_name = &args.branch_name;
1233 0 :
1234 0 : // Parse base inputs
1235 0 : let base = (args.base_lsn, args.base_tarfile.clone());
1236 0 :
1237 0 : // Parse pg_wal inputs
1238 0 : let wal_tarfile = args.wal_tarfile.clone();
1239 0 : let end_lsn = args.end_lsn;
1240 0 : // TODO validate both or none are provided
1241 0 : let pg_wal = end_lsn.zip(wal_tarfile);
1242 0 :
1243 0 : println!("Importing timeline into pageserver ...");
1244 0 : pageserver
1245 0 : .timeline_import(tenant_id, timeline_id, base, pg_wal, args.pg_version)
1246 0 : .await?;
1247 0 : env.register_branch_mapping(branch_name.to_string(), tenant_id, timeline_id)?;
1248 0 : println!("Done");
1249 : }
1250 0 : TimelineCmd::Branch(args) => {
1251 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1252 0 : let new_timeline_id = args.timeline_id.unwrap_or(TimelineId::generate());
1253 0 : let new_branch_name = &args.branch_name;
1254 0 : let ancestor_branch_name = args
1255 0 : .ancestor_branch_name
1256 0 : .clone()
1257 0 : .unwrap_or(DEFAULT_BRANCH_NAME.to_owned());
1258 0 : let ancestor_timeline_id = env
1259 0 : .get_branch_timeline_id(&ancestor_branch_name, tenant_id)
1260 0 : .ok_or_else(|| {
1261 0 : anyhow!("Found no timeline id for branch name '{ancestor_branch_name}'")
1262 0 : })?;
1263 :
1264 0 : let start_lsn = args.ancestor_start_lsn;
1265 0 : let storage_controller = StorageController::from_env(env);
1266 0 : let create_req = TimelineCreateRequest {
1267 0 : new_timeline_id,
1268 0 : mode: pageserver_api::models::TimelineCreateRequestMode::Branch {
1269 0 : ancestor_timeline_id,
1270 0 : ancestor_start_lsn: start_lsn,
1271 0 : pg_version: None,
1272 0 : },
1273 0 : };
1274 0 : let timeline_info = storage_controller
1275 0 : .tenant_timeline_create(tenant_id, create_req)
1276 0 : .await?;
1277 :
1278 0 : let last_record_lsn = timeline_info.last_record_lsn;
1279 0 :
1280 0 : env.register_branch_mapping(new_branch_name.to_string(), tenant_id, new_timeline_id)?;
1281 :
1282 0 : println!(
1283 0 : "Created timeline '{}' at Lsn {last_record_lsn} for tenant: {tenant_id}. Ancestor timeline: '{ancestor_branch_name}'",
1284 0 : timeline_info.timeline_id
1285 0 : );
1286 : }
1287 : }
1288 :
1289 0 : Ok(())
1290 0 : }
1291 :
1292 0 : async fn handle_endpoint(subcmd: &EndpointCmd, env: &local_env::LocalEnv) -> Result<()> {
1293 0 : let mut cplane = ComputeControlPlane::load(env.clone())?;
1294 :
1295 0 : match subcmd {
1296 0 : EndpointCmd::List(args) => {
1297 : // TODO(sharding): this command shouldn't have to specify a shard ID: we should ask the storage controller
1298 : // where shard 0 is attached, and query there.
1299 0 : let tenant_shard_id = get_tenant_shard_id(args.tenant_shard_id, env)?;
1300 :
1301 0 : let timeline_name_mappings = env.timeline_name_mappings();
1302 0 :
1303 0 : let mut table = comfy_table::Table::new();
1304 0 :
1305 0 : table.load_preset(comfy_table::presets::NOTHING);
1306 0 :
1307 0 : table.set_header([
1308 0 : "ENDPOINT",
1309 0 : "ADDRESS",
1310 0 : "TIMELINE",
1311 0 : "BRANCH NAME",
1312 0 : "LSN",
1313 0 : "STATUS",
1314 0 : ]);
1315 :
1316 0 : for (endpoint_id, endpoint) in cplane
1317 0 : .endpoints
1318 0 : .iter()
1319 0 : .filter(|(_, endpoint)| endpoint.tenant_id == tenant_shard_id.tenant_id)
1320 : {
1321 0 : let lsn_str = match endpoint.mode {
1322 0 : ComputeMode::Static(lsn) => {
1323 0 : // -> read-only endpoint
1324 0 : // Use the node's LSN.
1325 0 : lsn.to_string()
1326 : }
1327 : _ => {
1328 : // As the LSN here refers to the one that the compute is started with,
1329 : // we display nothing as it is a primary/hot standby compute.
1330 0 : "---".to_string()
1331 : }
1332 : };
1333 :
1334 0 : let branch_name = timeline_name_mappings
1335 0 : .get(&TenantTimelineId::new(
1336 0 : tenant_shard_id.tenant_id,
1337 0 : endpoint.timeline_id,
1338 0 : ))
1339 0 : .map(|name| name.as_str())
1340 0 : .unwrap_or("?");
1341 0 :
1342 0 : table.add_row([
1343 0 : endpoint_id.as_str(),
1344 0 : &endpoint.pg_address.to_string(),
1345 0 : &endpoint.timeline_id.to_string(),
1346 0 : branch_name,
1347 0 : lsn_str.as_str(),
1348 0 : &format!("{}", endpoint.status()),
1349 0 : ]);
1350 0 : }
1351 :
1352 0 : println!("{table}");
1353 : }
1354 0 : EndpointCmd::Create(args) => {
1355 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1356 0 : let branch_name = args
1357 0 : .branch_name
1358 0 : .clone()
1359 0 : .unwrap_or(DEFAULT_BRANCH_NAME.to_owned());
1360 0 : let endpoint_id = args
1361 0 : .endpoint_id
1362 0 : .clone()
1363 0 : .unwrap_or_else(|| format!("ep-{branch_name}"));
1364 :
1365 0 : let timeline_id = env
1366 0 : .get_branch_timeline_id(&branch_name, tenant_id)
1367 0 : .ok_or_else(|| anyhow!("Found no timeline id for branch name '{branch_name}'"))?;
1368 :
1369 0 : let mode = match (args.lsn, args.hot_standby) {
1370 0 : (Some(lsn), false) => ComputeMode::Static(lsn),
1371 0 : (None, true) => ComputeMode::Replica,
1372 0 : (None, false) => ComputeMode::Primary,
1373 0 : (Some(_), true) => anyhow::bail!("cannot specify both lsn and hot-standby"),
1374 : };
1375 :
1376 0 : match (mode, args.hot_standby) {
1377 : (ComputeMode::Static(_), true) => {
1378 0 : bail!(
1379 0 : "Cannot start a node in hot standby mode when it is already configured as a static replica"
1380 0 : )
1381 : }
1382 : (ComputeMode::Primary, true) => {
1383 0 : bail!(
1384 0 : "Cannot start a node as a hot standby replica, it is already configured as primary node"
1385 0 : )
1386 : }
1387 0 : _ => {}
1388 0 : }
1389 0 :
1390 0 : if !args.allow_multiple {
1391 0 : cplane.check_conflicting_endpoints(mode, tenant_id, timeline_id)?;
1392 0 : }
1393 :
1394 0 : cplane.new_endpoint(
1395 0 : &endpoint_id,
1396 0 : tenant_id,
1397 0 : timeline_id,
1398 0 : args.pg_port,
1399 0 : args.external_http_port,
1400 0 : args.internal_http_port,
1401 0 : args.pg_version,
1402 0 : mode,
1403 0 : !args.update_catalog,
1404 0 : false,
1405 0 : )?;
1406 : }
1407 0 : EndpointCmd::Start(args) => {
1408 0 : let endpoint_id = &args.endpoint_id;
1409 0 : let pageserver_id = args.endpoint_pageserver_id;
1410 0 : let remote_ext_config = &args.remote_ext_config;
1411 0 :
1412 0 : let safekeepers_generation = args.safekeepers_generation.map(SafekeeperGeneration::new);
1413 : // If --safekeepers argument is given, use only the listed
1414 : // safekeeper nodes; otherwise all from the env.
1415 0 : let safekeepers = if let Some(safekeepers) = parse_safekeepers(&args.safekeepers)? {
1416 0 : safekeepers
1417 : } else {
1418 0 : env.safekeepers.iter().map(|sk| sk.id).collect()
1419 : };
1420 :
1421 0 : let endpoint = cplane
1422 0 : .endpoints
1423 0 : .get(endpoint_id.as_str())
1424 0 : .ok_or_else(|| anyhow::anyhow!("endpoint {endpoint_id} not found"))?;
1425 :
1426 0 : if !args.allow_multiple {
1427 0 : cplane.check_conflicting_endpoints(
1428 0 : endpoint.mode,
1429 0 : endpoint.tenant_id,
1430 0 : endpoint.timeline_id,
1431 0 : )?;
1432 0 : }
1433 :
1434 0 : let (pageservers, stripe_size) = if let Some(pageserver_id) = pageserver_id {
1435 0 : let conf = env.get_pageserver_conf(pageserver_id).unwrap();
1436 0 : let parsed = parse_host_port(&conf.listen_pg_addr).expect("Bad config");
1437 0 : (
1438 0 : vec![(parsed.0, parsed.1.unwrap_or(5432))],
1439 0 : // If caller is telling us what pageserver to use, this is not a tenant which is
1440 0 : // full managed by storage controller, therefore not sharded.
1441 0 : DEFAULT_STRIPE_SIZE,
1442 0 : )
1443 : } else {
1444 : // Look up the currently attached location of the tenant, and its striping metadata,
1445 : // to pass these on to postgres.
1446 0 : let storage_controller = StorageController::from_env(env);
1447 0 : let locate_result = storage_controller.tenant_locate(endpoint.tenant_id).await?;
1448 0 : let pageservers = futures::future::try_join_all(
1449 0 : locate_result.shards.into_iter().map(|shard| async move {
1450 0 : if let ComputeMode::Static(lsn) = endpoint.mode {
1451 : // Initialize LSN leases for static computes.
1452 0 : let conf = env.get_pageserver_conf(shard.node_id).unwrap();
1453 0 : let pageserver = PageServerNode::from_env(env, conf);
1454 0 :
1455 0 : pageserver
1456 0 : .http_client
1457 0 : .timeline_init_lsn_lease(shard.shard_id, endpoint.timeline_id, lsn)
1458 0 : .await?;
1459 0 : }
1460 :
1461 0 : anyhow::Ok((
1462 0 : Host::parse(&shard.listen_pg_addr)
1463 0 : .expect("Storage controller reported bad hostname"),
1464 0 : shard.listen_pg_port,
1465 0 : ))
1466 0 : }),
1467 0 : )
1468 0 : .await?;
1469 0 : let stripe_size = locate_result.shard_params.stripe_size;
1470 0 :
1471 0 : (pageservers, stripe_size)
1472 : };
1473 0 : assert!(!pageservers.is_empty());
1474 :
1475 0 : let ps_conf = env.get_pageserver_conf(DEFAULT_PAGESERVER_ID)?;
1476 0 : let auth_token = if matches!(ps_conf.pg_auth_type, AuthType::NeonJWT) {
1477 0 : let claims = Claims::new(Some(endpoint.tenant_id), Scope::Tenant);
1478 0 :
1479 0 : Some(env.generate_auth_token(&claims)?)
1480 : } else {
1481 0 : None
1482 : };
1483 :
1484 0 : println!("Starting existing endpoint {endpoint_id}...");
1485 0 : endpoint
1486 0 : .start(
1487 0 : &auth_token,
1488 0 : safekeepers_generation,
1489 0 : safekeepers,
1490 0 : pageservers,
1491 0 : remote_ext_config.as_ref(),
1492 0 : stripe_size.0 as usize,
1493 0 : args.create_test_user,
1494 0 : args.start_timeout,
1495 0 : )
1496 0 : .await?;
1497 : }
1498 0 : EndpointCmd::Reconfigure(args) => {
1499 0 : let endpoint_id = &args.endpoint_id;
1500 0 : let endpoint = cplane
1501 0 : .endpoints
1502 0 : .get(endpoint_id.as_str())
1503 0 : .with_context(|| format!("postgres endpoint {endpoint_id} is not found"))?;
1504 0 : let pageservers = if let Some(ps_id) = args.endpoint_pageserver_id {
1505 0 : let pageserver = PageServerNode::from_env(env, env.get_pageserver_conf(ps_id)?);
1506 0 : vec![(
1507 0 : pageserver.pg_connection_config.host().clone(),
1508 0 : pageserver.pg_connection_config.port(),
1509 0 : )]
1510 : } else {
1511 0 : let storage_controller = StorageController::from_env(env);
1512 0 : storage_controller
1513 0 : .tenant_locate(endpoint.tenant_id)
1514 0 : .await?
1515 : .shards
1516 0 : .into_iter()
1517 0 : .map(|shard| {
1518 0 : (
1519 0 : Host::parse(&shard.listen_pg_addr)
1520 0 : .expect("Storage controller reported malformed host"),
1521 0 : shard.listen_pg_port,
1522 0 : )
1523 0 : })
1524 0 : .collect::<Vec<_>>()
1525 : };
1526 : // If --safekeepers argument is given, use only the listed
1527 : // safekeeper nodes; otherwise all from the env.
1528 0 : let safekeepers = parse_safekeepers(&args.safekeepers)?;
1529 0 : endpoint.reconfigure(pageservers, None, safekeepers).await?;
1530 : }
1531 0 : EndpointCmd::Stop(args) => {
1532 0 : let endpoint_id = &args.endpoint_id;
1533 0 : let endpoint = cplane
1534 0 : .endpoints
1535 0 : .get(endpoint_id)
1536 0 : .with_context(|| format!("postgres endpoint {endpoint_id} is not found"))?;
1537 0 : endpoint.stop(&args.mode, args.destroy)?;
1538 : }
1539 0 : EndpointCmd::GenerateJwt(args) => {
1540 0 : let endpoint_id = &args.endpoint_id;
1541 0 : let endpoint = cplane
1542 0 : .endpoints
1543 0 : .get(endpoint_id)
1544 0 : .with_context(|| format!("postgres endpoint {endpoint_id} is not found"))?;
1545 0 : let jwt = endpoint.generate_jwt()?;
1546 :
1547 0 : print!("{jwt}");
1548 : }
1549 : }
1550 :
1551 0 : Ok(())
1552 0 : }
1553 :
1554 : /// Parse --safekeepers as list of safekeeper ids.
1555 0 : fn parse_safekeepers(safekeepers_str: &Option<String>) -> Result<Option<Vec<NodeId>>> {
1556 0 : if let Some(safekeepers_str) = safekeepers_str {
1557 0 : let mut safekeepers: Vec<NodeId> = Vec::new();
1558 0 : for sk_id in safekeepers_str.split(',').map(str::trim) {
1559 0 : let sk_id = NodeId(
1560 0 : u64::from_str(sk_id)
1561 0 : .map_err(|_| anyhow!("invalid node ID \"{sk_id}\" in --safekeepers list"))?,
1562 : );
1563 0 : safekeepers.push(sk_id);
1564 : }
1565 0 : Ok(Some(safekeepers))
1566 : } else {
1567 0 : Ok(None)
1568 : }
1569 0 : }
1570 :
1571 0 : fn handle_mappings(subcmd: &MappingsCmd, env: &mut local_env::LocalEnv) -> Result<()> {
1572 0 : match subcmd {
1573 0 : MappingsCmd::Map(args) => {
1574 0 : env.register_branch_mapping(
1575 0 : args.branch_name.to_owned(),
1576 0 : args.tenant_id,
1577 0 : args.timeline_id,
1578 0 : )?;
1579 :
1580 0 : Ok(())
1581 : }
1582 : }
1583 0 : }
1584 :
1585 0 : fn get_pageserver(
1586 0 : env: &local_env::LocalEnv,
1587 0 : pageserver_id_arg: Option<NodeId>,
1588 0 : ) -> Result<PageServerNode> {
1589 0 : let node_id = pageserver_id_arg.unwrap_or(DEFAULT_PAGESERVER_ID);
1590 0 :
1591 0 : Ok(PageServerNode::from_env(
1592 0 : env,
1593 0 : env.get_pageserver_conf(node_id)?,
1594 : ))
1595 0 : }
1596 :
1597 0 : async fn handle_pageserver(subcmd: &PageserverCmd, env: &local_env::LocalEnv) -> Result<()> {
1598 0 : match subcmd {
1599 0 : PageserverCmd::Start(args) => {
1600 0 : if let Err(e) = get_pageserver(env, args.pageserver_id)?
1601 0 : .start(&args.start_timeout)
1602 0 : .await
1603 : {
1604 0 : eprintln!("pageserver start failed: {e}");
1605 0 : exit(1);
1606 0 : }
1607 : }
1608 :
1609 0 : PageserverCmd::Stop(args) => {
1610 0 : let immediate = match args.stop_mode {
1611 0 : StopMode::Fast => false,
1612 0 : StopMode::Immediate => true,
1613 : };
1614 0 : if let Err(e) = get_pageserver(env, args.pageserver_id)?.stop(immediate) {
1615 0 : eprintln!("pageserver stop failed: {}", e);
1616 0 : exit(1);
1617 0 : }
1618 : }
1619 :
1620 0 : PageserverCmd::Restart(args) => {
1621 0 : let pageserver = get_pageserver(env, args.pageserver_id)?;
1622 : //TODO what shutdown strategy should we use here?
1623 0 : if let Err(e) = pageserver.stop(false) {
1624 0 : eprintln!("pageserver stop failed: {}", e);
1625 0 : exit(1);
1626 0 : }
1627 :
1628 0 : if let Err(e) = pageserver.start(&args.start_timeout).await {
1629 0 : eprintln!("pageserver start failed: {e}");
1630 0 : exit(1);
1631 0 : }
1632 : }
1633 :
1634 0 : PageserverCmd::Status(args) => {
1635 0 : match get_pageserver(env, args.pageserver_id)?
1636 0 : .check_status()
1637 0 : .await
1638 : {
1639 0 : Ok(_) => println!("Page server is up and running"),
1640 0 : Err(err) => {
1641 0 : eprintln!("Page server is not available: {}", err);
1642 0 : exit(1);
1643 : }
1644 : }
1645 : }
1646 : }
1647 0 : Ok(())
1648 0 : }
1649 :
1650 0 : async fn handle_storage_controller(
1651 0 : subcmd: &StorageControllerCmd,
1652 0 : env: &local_env::LocalEnv,
1653 0 : ) -> Result<()> {
1654 0 : let svc = StorageController::from_env(env);
1655 0 : match subcmd {
1656 0 : StorageControllerCmd::Start(args) => {
1657 0 : let start_args = NeonStorageControllerStartArgs {
1658 0 : instance_id: args.instance_id,
1659 0 : base_port: args.base_port,
1660 0 : start_timeout: args.start_timeout,
1661 0 : };
1662 :
1663 0 : if let Err(e) = svc.start(start_args).await {
1664 0 : eprintln!("start failed: {e}");
1665 0 : exit(1);
1666 0 : }
1667 : }
1668 :
1669 0 : StorageControllerCmd::Stop(args) => {
1670 0 : let stop_args = NeonStorageControllerStopArgs {
1671 0 : instance_id: args.instance_id,
1672 0 : immediate: match args.stop_mode {
1673 0 : StopMode::Fast => false,
1674 0 : StopMode::Immediate => true,
1675 : },
1676 : };
1677 0 : if let Err(e) = svc.stop(stop_args).await {
1678 0 : eprintln!("stop failed: {}", e);
1679 0 : exit(1);
1680 0 : }
1681 : }
1682 : }
1683 0 : Ok(())
1684 0 : }
1685 :
1686 0 : fn get_safekeeper(env: &local_env::LocalEnv, id: NodeId) -> Result<SafekeeperNode> {
1687 0 : if let Some(node) = env.safekeepers.iter().find(|node| node.id == id) {
1688 0 : Ok(SafekeeperNode::from_env(env, node))
1689 : } else {
1690 0 : bail!("could not find safekeeper {id}")
1691 : }
1692 0 : }
1693 :
1694 0 : async fn handle_safekeeper(subcmd: &SafekeeperCmd, env: &local_env::LocalEnv) -> Result<()> {
1695 0 : match subcmd {
1696 0 : SafekeeperCmd::Start(args) => {
1697 0 : let safekeeper = get_safekeeper(env, args.id)?;
1698 :
1699 0 : if let Err(e) = safekeeper.start(&args.extra_opt, &args.start_timeout).await {
1700 0 : eprintln!("safekeeper start failed: {}", e);
1701 0 : exit(1);
1702 0 : }
1703 : }
1704 :
1705 0 : SafekeeperCmd::Stop(args) => {
1706 0 : let safekeeper = get_safekeeper(env, args.id)?;
1707 0 : let immediate = match args.stop_mode {
1708 0 : StopMode::Fast => false,
1709 0 : StopMode::Immediate => true,
1710 : };
1711 0 : if let Err(e) = safekeeper.stop(immediate) {
1712 0 : eprintln!("safekeeper stop failed: {}", e);
1713 0 : exit(1);
1714 0 : }
1715 : }
1716 :
1717 0 : SafekeeperCmd::Restart(args) => {
1718 0 : let safekeeper = get_safekeeper(env, args.id)?;
1719 0 : let immediate = match args.stop_mode {
1720 0 : StopMode::Fast => false,
1721 0 : StopMode::Immediate => true,
1722 : };
1723 :
1724 0 : if let Err(e) = safekeeper.stop(immediate) {
1725 0 : eprintln!("safekeeper stop failed: {}", e);
1726 0 : exit(1);
1727 0 : }
1728 :
1729 0 : if let Err(e) = safekeeper.start(&args.extra_opt, &args.start_timeout).await {
1730 0 : eprintln!("safekeeper start failed: {}", e);
1731 0 : exit(1);
1732 0 : }
1733 : }
1734 : }
1735 0 : Ok(())
1736 0 : }
1737 :
1738 0 : async fn handle_object_storage(subcmd: &ObjectStorageCmd, env: &local_env::LocalEnv) -> Result<()> {
1739 : use ObjectStorageCmd::*;
1740 0 : let storage = ObjectStorage::from_env(env);
1741 0 :
1742 0 : // In tests like test_forward_compatibility or test_graceful_cluster_restart
1743 0 : // old neon binaries (without object_storage) are present
1744 0 : if !storage.bin.exists() {
1745 0 : eprintln!(
1746 0 : "{} binary not found. Ignore if this is a compatibility test",
1747 0 : storage.bin
1748 0 : );
1749 0 : return Ok(());
1750 0 : }
1751 0 :
1752 0 : match subcmd {
1753 0 : Start(ObjectStorageStartCmd { start_timeout }) => {
1754 0 : if let Err(e) = storage.start(start_timeout).await {
1755 0 : eprintln!("object_storage start failed: {e}");
1756 0 : exit(1);
1757 0 : }
1758 : }
1759 0 : Stop(ObjectStorageStopCmd { stop_mode }) => {
1760 0 : let immediate = match stop_mode {
1761 0 : StopMode::Fast => false,
1762 0 : StopMode::Immediate => true,
1763 : };
1764 0 : if let Err(e) = storage.stop(immediate) {
1765 0 : eprintln!("proxy stop failed: {e}");
1766 0 : exit(1);
1767 0 : }
1768 : }
1769 : };
1770 0 : Ok(())
1771 0 : }
1772 :
1773 0 : async fn handle_storage_broker(subcmd: &StorageBrokerCmd, env: &local_env::LocalEnv) -> Result<()> {
1774 0 : match subcmd {
1775 0 : StorageBrokerCmd::Start(args) => {
1776 0 : if let Err(e) = broker::start_broker_process(env, &args.start_timeout).await {
1777 0 : eprintln!("broker start failed: {e}");
1778 0 : exit(1);
1779 0 : }
1780 : }
1781 :
1782 0 : StorageBrokerCmd::Stop(_args) => {
1783 : // FIXME: stop_mode unused
1784 0 : if let Err(e) = broker::stop_broker_process(env) {
1785 0 : eprintln!("broker stop failed: {e}");
1786 0 : exit(1);
1787 0 : }
1788 : }
1789 : }
1790 0 : Ok(())
1791 0 : }
1792 :
1793 0 : async fn handle_start_all(
1794 0 : args: &StartCmdArgs,
1795 0 : env: &'static local_env::LocalEnv,
1796 0 : ) -> anyhow::Result<()> {
1797 : // FIXME: this was called "retry_timeout", is it right?
1798 0 : let Err(errors) = handle_start_all_impl(env, args.timeout).await else {
1799 0 : neon_start_status_check(env, args.timeout.as_ref())
1800 0 : .await
1801 0 : .context("status check after successful startup of all services")?;
1802 0 : return Ok(());
1803 : };
1804 :
1805 0 : eprintln!("startup failed because one or more services could not be started");
1806 :
1807 0 : for e in errors {
1808 0 : eprintln!("{e}");
1809 0 : let debug_repr = format!("{e:?}");
1810 0 : for line in debug_repr.lines() {
1811 0 : eprintln!(" {line}");
1812 0 : }
1813 : }
1814 :
1815 0 : try_stop_all(env, true).await;
1816 :
1817 0 : exit(2);
1818 0 : }
1819 :
1820 : /// Returns Ok() if and only if all services could be started successfully.
1821 : /// Otherwise, returns the list of errors that occurred during startup.
1822 0 : async fn handle_start_all_impl(
1823 0 : env: &'static local_env::LocalEnv,
1824 0 : retry_timeout: humantime::Duration,
1825 0 : ) -> Result<(), Vec<anyhow::Error>> {
1826 0 : // Endpoints are not started automatically
1827 0 :
1828 0 : let mut js = JoinSet::new();
1829 :
1830 : // force infalliblity through closure
1831 : #[allow(clippy::redundant_closure_call)]
1832 0 : (|| {
1833 0 : js.spawn(async move {
1834 0 : let retry_timeout = retry_timeout;
1835 0 : broker::start_broker_process(env, &retry_timeout).await
1836 0 : });
1837 0 :
1838 0 : js.spawn(async move {
1839 0 : let storage_controller = StorageController::from_env(env);
1840 0 : storage_controller
1841 0 : .start(NeonStorageControllerStartArgs::with_default_instance_id(
1842 0 : retry_timeout,
1843 0 : ))
1844 0 : .await
1845 0 : .map_err(|e| e.context("start storage_controller"))
1846 0 : });
1847 :
1848 0 : for ps_conf in &env.pageservers {
1849 0 : js.spawn(async move {
1850 0 : let pageserver = PageServerNode::from_env(env, ps_conf);
1851 0 : pageserver
1852 0 : .start(&retry_timeout)
1853 0 : .await
1854 0 : .map_err(|e| e.context(format!("start pageserver {}", ps_conf.id)))
1855 0 : });
1856 0 : }
1857 :
1858 0 : for node in env.safekeepers.iter() {
1859 0 : js.spawn(async move {
1860 0 : let safekeeper = SafekeeperNode::from_env(env, node);
1861 0 : safekeeper
1862 0 : .start(&[], &retry_timeout)
1863 0 : .await
1864 0 : .map_err(|e| e.context(format!("start safekeeper {}", safekeeper.id)))
1865 0 : });
1866 0 : }
1867 :
1868 0 : js.spawn(async move {
1869 0 : ObjectStorage::from_env(env)
1870 0 : .start(&retry_timeout)
1871 0 : .await
1872 0 : .map_err(|e| e.context("start object_storage"))
1873 0 : });
1874 0 : })();
1875 0 :
1876 0 : let mut errors = Vec::new();
1877 0 : while let Some(result) = js.join_next().await {
1878 0 : let result = result.expect("we don't panic or cancel the tasks");
1879 0 : if let Err(e) = result {
1880 0 : errors.push(e);
1881 0 : }
1882 : }
1883 :
1884 0 : if !errors.is_empty() {
1885 0 : return Err(errors);
1886 0 : }
1887 0 :
1888 0 : Ok(())
1889 0 : }
1890 :
1891 0 : async fn neon_start_status_check(
1892 0 : env: &local_env::LocalEnv,
1893 0 : retry_timeout: &Duration,
1894 0 : ) -> anyhow::Result<()> {
1895 : const RETRY_INTERVAL: Duration = Duration::from_millis(100);
1896 : const NOTICE_AFTER_RETRIES: Duration = Duration::from_secs(5);
1897 :
1898 0 : let storcon = StorageController::from_env(env);
1899 0 :
1900 0 : let retries = retry_timeout.as_millis() / RETRY_INTERVAL.as_millis();
1901 0 : let notice_after_retries = retry_timeout.as_millis() / NOTICE_AFTER_RETRIES.as_millis();
1902 0 :
1903 0 : println!("\nRunning neon status check");
1904 :
1905 0 : for retry in 0..retries {
1906 0 : if retry == notice_after_retries {
1907 0 : println!("\nNeon status check has not passed yet, continuing to wait")
1908 0 : }
1909 :
1910 0 : let mut passed = true;
1911 0 : let mut nodes = storcon.node_list().await?;
1912 0 : let mut pageservers = env.pageservers.clone();
1913 0 :
1914 0 : if nodes.len() != pageservers.len() {
1915 0 : continue;
1916 0 : }
1917 0 :
1918 0 : nodes.sort_by_key(|ps| ps.id);
1919 0 : pageservers.sort_by_key(|ps| ps.id);
1920 :
1921 0 : for (idx, pageserver) in pageservers.iter().enumerate() {
1922 0 : let node = &nodes[idx];
1923 0 : if node.id != pageserver.id {
1924 0 : passed = false;
1925 0 : break;
1926 0 : }
1927 :
1928 0 : if !matches!(node.availability, NodeAvailabilityWrapper::Active) {
1929 0 : passed = false;
1930 0 : break;
1931 0 : }
1932 : }
1933 :
1934 0 : if passed {
1935 0 : println!("\nNeon started and passed status check");
1936 0 : return Ok(());
1937 0 : }
1938 0 :
1939 0 : tokio::time::sleep(RETRY_INTERVAL).await;
1940 : }
1941 :
1942 0 : anyhow::bail!("\nNeon passed status check")
1943 0 : }
1944 :
1945 0 : async fn handle_stop_all(args: &StopCmdArgs, env: &local_env::LocalEnv) -> Result<()> {
1946 0 : let immediate = match args.mode {
1947 0 : StopMode::Fast => false,
1948 0 : StopMode::Immediate => true,
1949 : };
1950 :
1951 0 : try_stop_all(env, immediate).await;
1952 :
1953 0 : Ok(())
1954 0 : }
1955 :
1956 0 : async fn try_stop_all(env: &local_env::LocalEnv, immediate: bool) {
1957 0 : // Stop all endpoints
1958 0 : match ComputeControlPlane::load(env.clone()) {
1959 0 : Ok(cplane) => {
1960 0 : for (_k, node) in cplane.endpoints {
1961 0 : if let Err(e) = node.stop(if immediate { "immediate" } else { "fast" }, false) {
1962 0 : eprintln!("postgres stop failed: {e:#}");
1963 0 : }
1964 : }
1965 : }
1966 0 : Err(e) => {
1967 0 : eprintln!("postgres stop failed, could not restore control plane data from env: {e:#}")
1968 : }
1969 : }
1970 :
1971 0 : let storage = ObjectStorage::from_env(env);
1972 0 : if let Err(e) = storage.stop(immediate) {
1973 0 : eprintln!("object_storage stop failed: {:#}", e);
1974 0 : }
1975 :
1976 0 : for ps_conf in &env.pageservers {
1977 0 : let pageserver = PageServerNode::from_env(env, ps_conf);
1978 0 : if let Err(e) = pageserver.stop(immediate) {
1979 0 : eprintln!("pageserver {} stop failed: {:#}", ps_conf.id, e);
1980 0 : }
1981 : }
1982 :
1983 0 : for node in env.safekeepers.iter() {
1984 0 : let safekeeper = SafekeeperNode::from_env(env, node);
1985 0 : if let Err(e) = safekeeper.stop(immediate) {
1986 0 : eprintln!("safekeeper {} stop failed: {:#}", safekeeper.id, e);
1987 0 : }
1988 : }
1989 :
1990 0 : if let Err(e) = broker::stop_broker_process(env) {
1991 0 : eprintln!("neon broker stop failed: {e:#}");
1992 0 : }
1993 :
1994 : // Stop all storage controller instances. In the most common case there's only one,
1995 : // but iterate though the base data directory in order to discover the instances.
1996 0 : let storcon_instances = env
1997 0 : .storage_controller_instances()
1998 0 : .await
1999 0 : .expect("Must inspect data dir");
2000 0 : for (instance_id, _instance_dir_path) in storcon_instances {
2001 0 : let storage_controller = StorageController::from_env(env);
2002 0 : let stop_args = NeonStorageControllerStopArgs {
2003 0 : instance_id,
2004 0 : immediate,
2005 0 : };
2006 :
2007 0 : if let Err(e) = storage_controller.stop(stop_args).await {
2008 0 : eprintln!("Storage controller instance {instance_id} stop failed: {e:#}");
2009 0 : }
2010 : }
2011 0 : }
|