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