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::path::PathBuf;
12 : use std::process::exit;
13 : use std::str::FromStr;
14 : use std::time::Duration;
15 :
16 : use anyhow::{Context, Result, anyhow, bail};
17 : use clap::Parser;
18 : use compute_api::requests::ComputeClaimsScope;
19 : use compute_api::spec::ComputeMode;
20 : use control_plane::broker::StorageBroker;
21 : use control_plane::endpoint::ComputeControlPlane;
22 : use control_plane::endpoint_storage::{ENDPOINT_STORAGE_DEFAULT_ADDR, EndpointStorage};
23 : use control_plane::local_env;
24 : use control_plane::local_env::{
25 : EndpointStorageConf, InitForceMode, LocalEnv, NeonBroker, NeonLocalInitConf,
26 : NeonLocalInitPageserverConf, SafekeeperConf,
27 : };
28 : use control_plane::pageserver::PageServerNode;
29 : use control_plane::safekeeper::SafekeeperNode;
30 : use control_plane::storage_controller::{
31 : NeonStorageControllerStartArgs, NeonStorageControllerStopArgs, StorageController,
32 : };
33 : use nix::fcntl::{Flock, FlockArg};
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 : EndpointStorage(EndpointStorageCmd),
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 EndpointStorageCmd {
464 : Start(EndpointStorageStartCmd),
465 : Stop(EndpointStorageStopCmd),
466 : }
467 :
468 : #[derive(clap::Args)]
469 : #[clap(about = "Start object storage")]
470 : struct EndpointStorageStartCmd {
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 EndpointStorageStopCmd {
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 URL to request for extensions.",
647 : alias = "remote-ext-config"
648 : )]
649 : remote_ext_base_url: Option<String>,
650 :
651 : #[clap(
652 : long,
653 : help = "If set, will create test user `user` and `neondb` database. Requires `update-catalog = true`"
654 : )]
655 0 : create_test_user: bool,
656 :
657 : #[clap(
658 : long,
659 : help = "Allow multiple primary endpoints running on the same branch. Shouldn't be used normally, but useful for tests."
660 : )]
661 0 : allow_multiple: bool,
662 :
663 : #[clap(short = 't', long, value_parser= humantime::parse_duration, help = "timeout until we fail the command")]
664 : #[arg(default_value = "90s")]
665 0 : start_timeout: Duration,
666 : }
667 :
668 : #[derive(clap::Args)]
669 : #[clap(about = "Reconfigure an endpoint")]
670 : struct EndpointReconfigureCmdArgs {
671 : #[clap(
672 : long = "tenant-id",
673 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
674 : )]
675 : tenant_id: Option<TenantId>,
676 :
677 : #[clap(help = "Postgres endpoint id")]
678 0 : endpoint_id: String,
679 : #[clap(long = "pageserver-id")]
680 : endpoint_pageserver_id: Option<NodeId>,
681 :
682 : #[clap(long)]
683 : safekeepers: Option<String>,
684 : }
685 :
686 : #[derive(clap::Args)]
687 : #[clap(about = "Stop an endpoint")]
688 : struct EndpointStopCmdArgs {
689 : #[clap(help = "Postgres endpoint id")]
690 0 : endpoint_id: String,
691 :
692 : #[clap(
693 : long,
694 : help = "Also delete data directory (now optional, should be default in future)"
695 : )]
696 0 : destroy: bool,
697 :
698 : #[clap(long, help = "Postgres shutdown mode, passed to \"pg_ctl -m <mode>\"")]
699 : #[arg(value_parser(["smart", "fast", "immediate"]))]
700 : #[arg(default_value = "fast")]
701 0 : mode: String,
702 : }
703 :
704 : #[derive(clap::Args)]
705 : #[clap(about = "Generate a JWT for an endpoint")]
706 : struct EndpointGenerateJwtCmdArgs {
707 : #[clap(help = "Postgres endpoint id")]
708 0 : endpoint_id: String,
709 :
710 : #[clap(short = 's', long, help = "Scope to generate the JWT with", value_parser = ComputeClaimsScope::from_str)]
711 : scope: Option<ComputeClaimsScope>,
712 : }
713 :
714 : #[derive(clap::Subcommand)]
715 : #[clap(about = "Manage neon_local branch name mappings")]
716 : enum MappingsCmd {
717 : Map(MappingsMapCmdArgs),
718 : }
719 :
720 : #[derive(clap::Args)]
721 : #[clap(about = "Create new mapping which cannot exist already")]
722 : struct MappingsMapCmdArgs {
723 : #[clap(
724 : long,
725 : help = "Tenant id. Represented as a hexadecimal string 32 symbols length"
726 : )]
727 0 : tenant_id: TenantId,
728 : #[clap(
729 : long,
730 : help = "Timeline id. Represented as a hexadecimal string 32 symbols length"
731 : )]
732 0 : timeline_id: TimelineId,
733 : #[clap(long, help = "Branch name to give to the timeline")]
734 0 : branch_name: String,
735 : }
736 :
737 : ///
738 : /// Timelines tree element used as a value in the HashMap.
739 : ///
740 : struct TimelineTreeEl {
741 : /// `TimelineInfo` received from the `pageserver` via the `timeline_list` http API call.
742 : pub info: TimelineInfo,
743 : /// Name, recovered from neon config mappings
744 : pub name: Option<String>,
745 : /// Holds all direct children of this timeline referenced using `timeline_id`.
746 : pub children: BTreeSet<TimelineId>,
747 : }
748 :
749 : /// A flock-based guard over the neon_local repository directory
750 : struct RepoLock {
751 : _file: Flock<File>,
752 : }
753 :
754 : impl RepoLock {
755 0 : fn new() -> Result<Self> {
756 0 : let repo_dir = File::open(local_env::base_path())?;
757 0 : match Flock::lock(repo_dir, FlockArg::LockExclusive) {
758 0 : Ok(f) => Ok(Self { _file: f }),
759 0 : Err((_, e)) => Err(e).context("flock error"),
760 : }
761 0 : }
762 : }
763 :
764 : // Main entry point for the 'neon_local' CLI utility
765 : //
766 : // This utility helps to manage neon installation. That includes following:
767 : // * Management of local postgres installations running on top of the
768 : // pageserver.
769 : // * Providing CLI api to the pageserver
770 : // * TODO: export/import to/from usual postgres
771 0 : fn main() -> Result<()> {
772 0 : let cli = Cli::parse();
773 :
774 : // Check for 'neon init' command first.
775 0 : let (subcommand_result, _lock) = if let NeonLocalCmd::Init(args) = cli.command {
776 0 : (handle_init(&args).map(|env| Some(Cow::Owned(env))), None)
777 : } else {
778 : // This tool uses a collection of simple files to store its state, and consequently
779 : // it is not generally safe to run multiple commands concurrently. Rather than expect
780 : // all callers to know this, use a lock file to protect against concurrent execution.
781 0 : let _repo_lock = RepoLock::new().unwrap();
782 :
783 : // all other commands need an existing config
784 0 : let env = LocalEnv::load_config(&local_env::base_path()).context("Error loading config")?;
785 0 : let original_env = env.clone();
786 0 : let env = Box::leak(Box::new(env));
787 0 : let rt = tokio::runtime::Builder::new_current_thread()
788 0 : .enable_all()
789 0 : .build()
790 0 : .unwrap();
791 :
792 0 : let subcommand_result = match cli.command {
793 0 : NeonLocalCmd::Init(_) => unreachable!("init was handled earlier already"),
794 0 : NeonLocalCmd::Start(args) => rt.block_on(handle_start_all(&args, env)),
795 0 : NeonLocalCmd::Stop(args) => rt.block_on(handle_stop_all(&args, env)),
796 0 : NeonLocalCmd::Tenant(subcmd) => rt.block_on(handle_tenant(&subcmd, env)),
797 0 : NeonLocalCmd::Timeline(subcmd) => rt.block_on(handle_timeline(&subcmd, env)),
798 0 : NeonLocalCmd::Pageserver(subcmd) => rt.block_on(handle_pageserver(&subcmd, env)),
799 0 : NeonLocalCmd::StorageController(subcmd) => {
800 0 : rt.block_on(handle_storage_controller(&subcmd, env))
801 : }
802 0 : NeonLocalCmd::StorageBroker(subcmd) => rt.block_on(handle_storage_broker(&subcmd, env)),
803 0 : NeonLocalCmd::Safekeeper(subcmd) => rt.block_on(handle_safekeeper(&subcmd, env)),
804 0 : NeonLocalCmd::EndpointStorage(subcmd) => {
805 0 : rt.block_on(handle_endpoint_storage(&subcmd, env))
806 : }
807 0 : NeonLocalCmd::Endpoint(subcmd) => rt.block_on(handle_endpoint(&subcmd, env)),
808 0 : NeonLocalCmd::Mappings(subcmd) => handle_mappings(&subcmd, env),
809 : };
810 :
811 0 : let subcommand_result = if &original_env != env {
812 0 : subcommand_result.map(|()| Some(Cow::Borrowed(env)))
813 : } else {
814 0 : subcommand_result.map(|()| None)
815 : };
816 0 : (subcommand_result, Some(_repo_lock))
817 : };
818 :
819 0 : match subcommand_result {
820 0 : Ok(Some(updated_env)) => updated_env.persist_config()?,
821 0 : Ok(None) => (),
822 0 : Err(e) => {
823 0 : eprintln!("command failed: {e:?}");
824 0 : exit(1);
825 : }
826 : }
827 0 : Ok(())
828 0 : }
829 :
830 : ///
831 : /// Prints timelines list as a tree-like structure.
832 : ///
833 0 : fn print_timelines_tree(
834 0 : timelines: Vec<TimelineInfo>,
835 0 : mut timeline_name_mappings: HashMap<TenantTimelineId, String>,
836 0 : ) -> Result<()> {
837 0 : let mut timelines_hash = timelines
838 0 : .iter()
839 0 : .map(|t| {
840 0 : (
841 0 : t.timeline_id,
842 0 : TimelineTreeEl {
843 0 : info: t.clone(),
844 0 : children: BTreeSet::new(),
845 0 : name: timeline_name_mappings
846 0 : .remove(&TenantTimelineId::new(t.tenant_id.tenant_id, t.timeline_id)),
847 0 : },
848 0 : )
849 0 : })
850 0 : .collect::<HashMap<_, _>>();
851 :
852 : // Memorize all direct children of each timeline.
853 0 : for timeline in timelines.iter() {
854 0 : if let Some(ancestor_timeline_id) = timeline.ancestor_timeline_id {
855 0 : timelines_hash
856 0 : .get_mut(&ancestor_timeline_id)
857 0 : .context("missing timeline info in the HashMap")?
858 : .children
859 0 : .insert(timeline.timeline_id);
860 0 : }
861 : }
862 :
863 0 : for timeline in timelines_hash.values() {
864 : // Start with root local timelines (no ancestors) first.
865 0 : if timeline.info.ancestor_timeline_id.is_none() {
866 0 : print_timeline(0, &Vec::from([true]), timeline, &timelines_hash)?;
867 0 : }
868 : }
869 :
870 0 : Ok(())
871 0 : }
872 :
873 : ///
874 : /// Recursively prints timeline info with all its children.
875 : ///
876 0 : fn print_timeline(
877 0 : nesting_level: usize,
878 0 : is_last: &[bool],
879 0 : timeline: &TimelineTreeEl,
880 0 : timelines: &HashMap<TimelineId, TimelineTreeEl>,
881 0 : ) -> Result<()> {
882 0 : if nesting_level > 0 {
883 0 : let ancestor_lsn = match timeline.info.ancestor_lsn {
884 0 : Some(lsn) => lsn.to_string(),
885 0 : None => "Unknown Lsn".to_string(),
886 : };
887 :
888 0 : let mut br_sym = "┣━";
889 0 :
890 0 : // Draw each nesting padding with proper style
891 0 : // depending on whether its timeline ended or not.
892 0 : if nesting_level > 1 {
893 0 : for l in &is_last[1..is_last.len() - 1] {
894 0 : if *l {
895 0 : print!(" ");
896 0 : } else {
897 0 : print!("┃ ");
898 0 : }
899 : }
900 0 : }
901 :
902 : // We are the last in this sub-timeline
903 0 : if *is_last.last().unwrap() {
904 0 : br_sym = "┗━";
905 0 : }
906 :
907 0 : print!("{} @{}: ", br_sym, ancestor_lsn);
908 0 : }
909 :
910 : // Finally print a timeline id and name with new line
911 0 : println!(
912 0 : "{} [{}]",
913 0 : timeline.name.as_deref().unwrap_or("_no_name_"),
914 0 : timeline.info.timeline_id
915 0 : );
916 0 :
917 0 : let len = timeline.children.len();
918 0 : let mut i: usize = 0;
919 0 : let mut is_last_new = Vec::from(is_last);
920 0 : is_last_new.push(false);
921 :
922 0 : for child in &timeline.children {
923 0 : i += 1;
924 0 :
925 0 : // Mark that the last padding is the end of the timeline
926 0 : if i == len {
927 0 : if let Some(last) = is_last_new.last_mut() {
928 0 : *last = true;
929 0 : }
930 0 : }
931 :
932 : print_timeline(
933 0 : nesting_level + 1,
934 0 : &is_last_new,
935 0 : timelines
936 0 : .get(child)
937 0 : .context("missing timeline info in the HashMap")?,
938 0 : timelines,
939 0 : )?;
940 : }
941 :
942 0 : Ok(())
943 0 : }
944 :
945 : /// Helper function to get tenant id from an optional --tenant_id option or from the config file
946 0 : fn get_tenant_id(
947 0 : tenant_id_arg: Option<TenantId>,
948 0 : env: &local_env::LocalEnv,
949 0 : ) -> anyhow::Result<TenantId> {
950 0 : if let Some(tenant_id_from_arguments) = tenant_id_arg {
951 0 : Ok(tenant_id_from_arguments)
952 0 : } else if let Some(default_id) = env.default_tenant_id {
953 0 : Ok(default_id)
954 : } else {
955 0 : anyhow::bail!("No tenant id. Use --tenant-id, or set a default tenant");
956 : }
957 0 : }
958 :
959 : /// Helper function to get tenant-shard ID from an optional --tenant_id option or from the config file,
960 : /// for commands that accept a shard suffix
961 0 : fn get_tenant_shard_id(
962 0 : tenant_shard_id_arg: Option<TenantShardId>,
963 0 : env: &local_env::LocalEnv,
964 0 : ) -> anyhow::Result<TenantShardId> {
965 0 : if let Some(tenant_id_from_arguments) = tenant_shard_id_arg {
966 0 : Ok(tenant_id_from_arguments)
967 0 : } else if let Some(default_id) = env.default_tenant_id {
968 0 : Ok(TenantShardId::unsharded(default_id))
969 : } else {
970 0 : anyhow::bail!("No tenant shard id. Use --tenant-id, or set a default tenant");
971 : }
972 0 : }
973 :
974 0 : fn handle_init(args: &InitCmdArgs) -> anyhow::Result<LocalEnv> {
975 : // Create the in-memory `LocalEnv` that we'd normally load from disk in `load_config`.
976 0 : let init_conf: NeonLocalInitConf = if let Some(config_path) = &args.config {
977 : // User (likely the Python test suite) provided a description of the environment.
978 0 : if args.num_pageservers.is_some() {
979 0 : bail!(
980 0 : "Cannot specify both --num-pageservers and --config, use key `pageservers` in the --config file instead"
981 0 : );
982 0 : }
983 : // load and parse the file
984 0 : let contents = std::fs::read_to_string(config_path).with_context(|| {
985 0 : format!(
986 0 : "Could not read configuration file '{}'",
987 0 : config_path.display()
988 0 : )
989 0 : })?;
990 0 : toml_edit::de::from_str(&contents)?
991 : } else {
992 : // User (likely interactive) did not provide a description of the environment, give them the default
993 0 : NeonLocalInitConf {
994 0 : control_plane_api: Some(DEFAULT_PAGESERVER_CONTROL_PLANE_API.parse().unwrap()),
995 0 : broker: NeonBroker {
996 0 : listen_addr: Some(DEFAULT_BROKER_ADDR.parse().unwrap()),
997 0 : listen_https_addr: None,
998 0 : },
999 0 : safekeepers: vec![SafekeeperConf {
1000 0 : id: DEFAULT_SAFEKEEPER_ID,
1001 0 : pg_port: DEFAULT_SAFEKEEPER_PG_PORT,
1002 0 : http_port: DEFAULT_SAFEKEEPER_HTTP_PORT,
1003 0 : ..Default::default()
1004 0 : }],
1005 0 : pageservers: (0..args.num_pageservers.unwrap_or(1))
1006 0 : .map(|i| {
1007 0 : let pageserver_id = NodeId(DEFAULT_PAGESERVER_ID.0 + i as u64);
1008 0 : let pg_port = DEFAULT_PAGESERVER_PG_PORT + i;
1009 0 : let http_port = DEFAULT_PAGESERVER_HTTP_PORT + i;
1010 0 : NeonLocalInitPageserverConf {
1011 0 : id: pageserver_id,
1012 0 : listen_pg_addr: format!("127.0.0.1:{pg_port}"),
1013 0 : listen_http_addr: format!("127.0.0.1:{http_port}"),
1014 0 : listen_https_addr: None,
1015 0 : pg_auth_type: AuthType::Trust,
1016 0 : http_auth_type: AuthType::Trust,
1017 0 : other: Default::default(),
1018 0 : // Typical developer machines use disks with slow fsync, and we don't care
1019 0 : // about data integrity: disable disk syncs.
1020 0 : no_sync: true,
1021 0 : }
1022 0 : })
1023 0 : .collect(),
1024 0 : endpoint_storage: EndpointStorageConf {
1025 0 : listen_addr: ENDPOINT_STORAGE_DEFAULT_ADDR,
1026 0 : },
1027 0 : pg_distrib_dir: None,
1028 0 : neon_distrib_dir: None,
1029 0 : default_tenant_id: TenantId::from_array(std::array::from_fn(|_| 0)),
1030 0 : storage_controller: None,
1031 0 : control_plane_hooks_api: None,
1032 0 : generate_local_ssl_certs: false,
1033 0 : }
1034 : };
1035 :
1036 0 : LocalEnv::init(init_conf, &args.force)
1037 0 : .context("materialize initial neon_local environment on disk")?;
1038 0 : Ok(LocalEnv::load_config(&local_env::base_path())
1039 0 : .expect("freshly written config should be loadable"))
1040 0 : }
1041 :
1042 : /// The default pageserver is the one where CLI tenant/timeline operations are sent by default.
1043 : /// For typical interactive use, one would just run with a single pageserver. Scenarios with
1044 : /// tenant/timeline placement across multiple pageservers are managed by python test code rather
1045 : /// than this CLI.
1046 0 : fn get_default_pageserver(env: &local_env::LocalEnv) -> PageServerNode {
1047 0 : let ps_conf = env
1048 0 : .pageservers
1049 0 : .first()
1050 0 : .expect("Config is validated to contain at least one pageserver");
1051 0 : PageServerNode::from_env(env, ps_conf)
1052 0 : }
1053 :
1054 0 : async fn handle_tenant(subcmd: &TenantCmd, env: &mut local_env::LocalEnv) -> anyhow::Result<()> {
1055 0 : let pageserver = get_default_pageserver(env);
1056 0 : match subcmd {
1057 : TenantCmd::List => {
1058 0 : for t in pageserver.tenant_list().await? {
1059 0 : println!("{} {:?}", t.id, t.state);
1060 0 : }
1061 : }
1062 0 : TenantCmd::Import(args) => {
1063 0 : let tenant_id = args.tenant_id;
1064 0 :
1065 0 : let storage_controller = StorageController::from_env(env);
1066 0 : let create_response = storage_controller.tenant_import(tenant_id).await?;
1067 :
1068 0 : let shard_zero = create_response
1069 0 : .shards
1070 0 : .first()
1071 0 : .expect("Import response omitted shards");
1072 0 :
1073 0 : let attached_pageserver_id = shard_zero.node_id;
1074 0 : let pageserver =
1075 0 : PageServerNode::from_env(env, env.get_pageserver_conf(attached_pageserver_id)?);
1076 :
1077 0 : println!(
1078 0 : "Imported tenant {tenant_id}, attached to pageserver {attached_pageserver_id}"
1079 0 : );
1080 :
1081 0 : let timelines = pageserver
1082 0 : .http_client
1083 0 : .list_timelines(shard_zero.shard_id)
1084 0 : .await?;
1085 :
1086 : // Pick a 'main' timeline that has no ancestors, the rest will get arbitrary names
1087 0 : let main_timeline = timelines
1088 0 : .iter()
1089 0 : .find(|t| t.ancestor_timeline_id.is_none())
1090 0 : .expect("No timelines found")
1091 0 : .timeline_id;
1092 0 :
1093 0 : let mut branch_i = 0;
1094 0 : for timeline in timelines.iter() {
1095 0 : let branch_name = if timeline.timeline_id == main_timeline {
1096 0 : "main".to_string()
1097 : } else {
1098 0 : branch_i += 1;
1099 0 : format!("branch_{branch_i}")
1100 : };
1101 :
1102 0 : println!(
1103 0 : "Importing timeline {tenant_id}/{} as branch {branch_name}",
1104 0 : timeline.timeline_id
1105 0 : );
1106 0 :
1107 0 : env.register_branch_mapping(branch_name, tenant_id, timeline.timeline_id)?;
1108 : }
1109 : }
1110 0 : TenantCmd::Create(args) => {
1111 0 : let tenant_conf: HashMap<_, _> =
1112 0 : args.config.iter().flat_map(|c| c.split_once(':')).collect();
1113 :
1114 0 : let tenant_conf = PageServerNode::parse_config(tenant_conf)?;
1115 :
1116 : // If tenant ID was not specified, generate one
1117 0 : let tenant_id = args.tenant_id.unwrap_or_else(TenantId::generate);
1118 0 :
1119 0 : // We must register the tenant with the storage controller, so
1120 0 : // that when the pageserver restarts, it will be re-attached.
1121 0 : let storage_controller = StorageController::from_env(env);
1122 0 : storage_controller
1123 0 : .tenant_create(TenantCreateRequest {
1124 0 : // Note that ::unsharded here isn't actually because the tenant is unsharded, its because the
1125 0 : // storage controller expects a shard-naive tenant_id in this attribute, and the TenantCreateRequest
1126 0 : // type is used both in the storage controller (for creating tenants) and in the pageserver (for
1127 0 : // creating shards)
1128 0 : new_tenant_id: TenantShardId::unsharded(tenant_id),
1129 0 : generation: None,
1130 0 : shard_parameters: ShardParameters {
1131 0 : count: ShardCount::new(args.shard_count),
1132 0 : stripe_size: args
1133 0 : .shard_stripe_size
1134 0 : .map(ShardStripeSize)
1135 0 : .unwrap_or(DEFAULT_STRIPE_SIZE),
1136 0 : },
1137 0 : placement_policy: args.placement_policy.clone(),
1138 0 : config: tenant_conf,
1139 0 : })
1140 0 : .await?;
1141 0 : println!("tenant {tenant_id} successfully created on the pageserver");
1142 0 :
1143 0 : // Create an initial timeline for the new tenant
1144 0 : let new_timeline_id = args.timeline_id.unwrap_or(TimelineId::generate());
1145 0 :
1146 0 : // FIXME: passing None for ancestor_start_lsn is not kosher in a sharded world: we can't have
1147 0 : // different shards picking different start lsns. Maybe we have to teach storage controller
1148 0 : // to let shard 0 branch first and then propagate the chosen LSN to other shards.
1149 0 : storage_controller
1150 0 : .tenant_timeline_create(
1151 0 : tenant_id,
1152 0 : TimelineCreateRequest {
1153 0 : new_timeline_id,
1154 0 : mode: pageserver_api::models::TimelineCreateRequestMode::Bootstrap {
1155 0 : existing_initdb_timeline_id: None,
1156 0 : pg_version: Some(args.pg_version),
1157 0 : },
1158 0 : },
1159 0 : )
1160 0 : .await?;
1161 :
1162 0 : env.register_branch_mapping(
1163 0 : DEFAULT_BRANCH_NAME.to_string(),
1164 0 : tenant_id,
1165 0 : new_timeline_id,
1166 0 : )?;
1167 :
1168 0 : println!("Created an initial timeline '{new_timeline_id}' for tenant: {tenant_id}",);
1169 0 :
1170 0 : if args.set_default {
1171 0 : println!("Setting tenant {tenant_id} as a default one");
1172 0 : env.default_tenant_id = Some(tenant_id);
1173 0 : }
1174 : }
1175 0 : TenantCmd::SetDefault(args) => {
1176 0 : println!("Setting tenant {} as a default one", args.tenant_id);
1177 0 : env.default_tenant_id = Some(args.tenant_id);
1178 0 : }
1179 0 : TenantCmd::Config(args) => {
1180 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1181 0 : let tenant_conf: HashMap<_, _> =
1182 0 : args.config.iter().flat_map(|c| c.split_once(':')).collect();
1183 0 : let config = PageServerNode::parse_config(tenant_conf)?;
1184 :
1185 0 : let req = TenantConfigRequest { tenant_id, config };
1186 0 :
1187 0 : let storage_controller = StorageController::from_env(env);
1188 0 : storage_controller
1189 0 : .set_tenant_config(&req)
1190 0 : .await
1191 0 : .with_context(|| format!("Tenant config failed for tenant with id {tenant_id}"))?;
1192 0 : println!("tenant {tenant_id} successfully configured via storcon");
1193 : }
1194 : }
1195 0 : Ok(())
1196 0 : }
1197 :
1198 0 : async fn handle_timeline(cmd: &TimelineCmd, env: &mut local_env::LocalEnv) -> Result<()> {
1199 0 : let pageserver = get_default_pageserver(env);
1200 0 :
1201 0 : match cmd {
1202 0 : TimelineCmd::List(args) => {
1203 : // TODO(sharding): this command shouldn't have to specify a shard ID: we should ask the storage controller
1204 : // where shard 0 is attached, and query there.
1205 0 : let tenant_shard_id = get_tenant_shard_id(args.tenant_shard_id, env)?;
1206 0 : let timelines = pageserver.timeline_list(&tenant_shard_id).await?;
1207 0 : print_timelines_tree(timelines, env.timeline_name_mappings())?;
1208 : }
1209 0 : TimelineCmd::Create(args) => {
1210 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1211 0 : let new_branch_name = &args.branch_name;
1212 0 : let new_timeline_id_opt = args.timeline_id;
1213 0 : let new_timeline_id = new_timeline_id_opt.unwrap_or(TimelineId::generate());
1214 0 :
1215 0 : let storage_controller = StorageController::from_env(env);
1216 0 : let create_req = TimelineCreateRequest {
1217 0 : new_timeline_id,
1218 0 : mode: pageserver_api::models::TimelineCreateRequestMode::Bootstrap {
1219 0 : existing_initdb_timeline_id: None,
1220 0 : pg_version: Some(args.pg_version),
1221 0 : },
1222 0 : };
1223 0 : let timeline_info = storage_controller
1224 0 : .tenant_timeline_create(tenant_id, create_req)
1225 0 : .await?;
1226 :
1227 0 : let last_record_lsn = timeline_info.last_record_lsn;
1228 0 : env.register_branch_mapping(new_branch_name.to_string(), tenant_id, new_timeline_id)?;
1229 :
1230 0 : println!(
1231 0 : "Created timeline '{}' at Lsn {last_record_lsn} for tenant: {tenant_id}",
1232 0 : timeline_info.timeline_id
1233 0 : );
1234 : }
1235 : // TODO: rename to import-basebackup-plus-wal
1236 0 : TimelineCmd::Import(args) => {
1237 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1238 0 : let timeline_id = args.timeline_id;
1239 0 : let branch_name = &args.branch_name;
1240 0 :
1241 0 : // Parse base inputs
1242 0 : let base = (args.base_lsn, args.base_tarfile.clone());
1243 0 :
1244 0 : // Parse pg_wal inputs
1245 0 : let wal_tarfile = args.wal_tarfile.clone();
1246 0 : let end_lsn = args.end_lsn;
1247 0 : // TODO validate both or none are provided
1248 0 : let pg_wal = end_lsn.zip(wal_tarfile);
1249 0 :
1250 0 : println!("Importing timeline into pageserver ...");
1251 0 : pageserver
1252 0 : .timeline_import(tenant_id, timeline_id, base, pg_wal, args.pg_version)
1253 0 : .await?;
1254 0 : env.register_branch_mapping(branch_name.to_string(), tenant_id, timeline_id)?;
1255 0 : println!("Done");
1256 : }
1257 0 : TimelineCmd::Branch(args) => {
1258 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1259 0 : let new_timeline_id = args.timeline_id.unwrap_or(TimelineId::generate());
1260 0 : let new_branch_name = &args.branch_name;
1261 0 : let ancestor_branch_name = args
1262 0 : .ancestor_branch_name
1263 0 : .clone()
1264 0 : .unwrap_or(DEFAULT_BRANCH_NAME.to_owned());
1265 0 : let ancestor_timeline_id = env
1266 0 : .get_branch_timeline_id(&ancestor_branch_name, tenant_id)
1267 0 : .ok_or_else(|| {
1268 0 : anyhow!("Found no timeline id for branch name '{ancestor_branch_name}'")
1269 0 : })?;
1270 :
1271 0 : let start_lsn = args.ancestor_start_lsn;
1272 0 : let storage_controller = StorageController::from_env(env);
1273 0 : let create_req = TimelineCreateRequest {
1274 0 : new_timeline_id,
1275 0 : mode: pageserver_api::models::TimelineCreateRequestMode::Branch {
1276 0 : ancestor_timeline_id,
1277 0 : ancestor_start_lsn: start_lsn,
1278 0 : pg_version: None,
1279 0 : },
1280 0 : };
1281 0 : let timeline_info = storage_controller
1282 0 : .tenant_timeline_create(tenant_id, create_req)
1283 0 : .await?;
1284 :
1285 0 : let last_record_lsn = timeline_info.last_record_lsn;
1286 0 :
1287 0 : env.register_branch_mapping(new_branch_name.to_string(), tenant_id, new_timeline_id)?;
1288 :
1289 0 : println!(
1290 0 : "Created timeline '{}' at Lsn {last_record_lsn} for tenant: {tenant_id}. Ancestor timeline: '{ancestor_branch_name}'",
1291 0 : timeline_info.timeline_id
1292 0 : );
1293 : }
1294 : }
1295 :
1296 0 : Ok(())
1297 0 : }
1298 :
1299 0 : async fn handle_endpoint(subcmd: &EndpointCmd, env: &local_env::LocalEnv) -> Result<()> {
1300 0 : let mut cplane = ComputeControlPlane::load(env.clone())?;
1301 :
1302 0 : match subcmd {
1303 0 : EndpointCmd::List(args) => {
1304 : // TODO(sharding): this command shouldn't have to specify a shard ID: we should ask the storage controller
1305 : // where shard 0 is attached, and query there.
1306 0 : let tenant_shard_id = get_tenant_shard_id(args.tenant_shard_id, env)?;
1307 :
1308 0 : let timeline_name_mappings = env.timeline_name_mappings();
1309 0 :
1310 0 : let mut table = comfy_table::Table::new();
1311 0 :
1312 0 : table.load_preset(comfy_table::presets::NOTHING);
1313 0 :
1314 0 : table.set_header([
1315 0 : "ENDPOINT",
1316 0 : "ADDRESS",
1317 0 : "TIMELINE",
1318 0 : "BRANCH NAME",
1319 0 : "LSN",
1320 0 : "STATUS",
1321 0 : ]);
1322 :
1323 0 : for (endpoint_id, endpoint) in cplane
1324 0 : .endpoints
1325 0 : .iter()
1326 0 : .filter(|(_, endpoint)| endpoint.tenant_id == tenant_shard_id.tenant_id)
1327 : {
1328 0 : let lsn_str = match endpoint.mode {
1329 0 : ComputeMode::Static(lsn) => {
1330 0 : // -> read-only endpoint
1331 0 : // Use the node's LSN.
1332 0 : lsn.to_string()
1333 : }
1334 : _ => {
1335 : // As the LSN here refers to the one that the compute is started with,
1336 : // we display nothing as it is a primary/hot standby compute.
1337 0 : "---".to_string()
1338 : }
1339 : };
1340 :
1341 0 : let branch_name = timeline_name_mappings
1342 0 : .get(&TenantTimelineId::new(
1343 0 : tenant_shard_id.tenant_id,
1344 0 : endpoint.timeline_id,
1345 0 : ))
1346 0 : .map(|name| name.as_str())
1347 0 : .unwrap_or("?");
1348 0 :
1349 0 : table.add_row([
1350 0 : endpoint_id.as_str(),
1351 0 : &endpoint.pg_address.to_string(),
1352 0 : &endpoint.timeline_id.to_string(),
1353 0 : branch_name,
1354 0 : lsn_str.as_str(),
1355 0 : &format!("{}", endpoint.status()),
1356 0 : ]);
1357 0 : }
1358 :
1359 0 : println!("{table}");
1360 : }
1361 0 : EndpointCmd::Create(args) => {
1362 0 : let tenant_id = get_tenant_id(args.tenant_id, env)?;
1363 0 : let branch_name = args
1364 0 : .branch_name
1365 0 : .clone()
1366 0 : .unwrap_or(DEFAULT_BRANCH_NAME.to_owned());
1367 0 : let endpoint_id = args
1368 0 : .endpoint_id
1369 0 : .clone()
1370 0 : .unwrap_or_else(|| format!("ep-{branch_name}"));
1371 :
1372 0 : let timeline_id = env
1373 0 : .get_branch_timeline_id(&branch_name, tenant_id)
1374 0 : .ok_or_else(|| anyhow!("Found no timeline id for branch name '{branch_name}'"))?;
1375 :
1376 0 : let mode = match (args.lsn, args.hot_standby) {
1377 0 : (Some(lsn), false) => ComputeMode::Static(lsn),
1378 0 : (None, true) => ComputeMode::Replica,
1379 0 : (None, false) => ComputeMode::Primary,
1380 0 : (Some(_), true) => anyhow::bail!("cannot specify both lsn and hot-standby"),
1381 : };
1382 :
1383 0 : match (mode, args.hot_standby) {
1384 : (ComputeMode::Static(_), true) => {
1385 0 : bail!(
1386 0 : "Cannot start a node in hot standby mode when it is already configured as a static replica"
1387 0 : )
1388 : }
1389 : (ComputeMode::Primary, true) => {
1390 0 : bail!(
1391 0 : "Cannot start a node as a hot standby replica, it is already configured as primary node"
1392 0 : )
1393 : }
1394 0 : _ => {}
1395 0 : }
1396 0 :
1397 0 : if !args.allow_multiple {
1398 0 : cplane.check_conflicting_endpoints(mode, tenant_id, timeline_id)?;
1399 0 : }
1400 :
1401 0 : cplane.new_endpoint(
1402 0 : &endpoint_id,
1403 0 : tenant_id,
1404 0 : timeline_id,
1405 0 : args.pg_port,
1406 0 : args.external_http_port,
1407 0 : args.internal_http_port,
1408 0 : args.pg_version,
1409 0 : mode,
1410 0 : !args.update_catalog,
1411 0 : false,
1412 0 : )?;
1413 : }
1414 0 : EndpointCmd::Start(args) => {
1415 0 : let endpoint_id = &args.endpoint_id;
1416 0 : let pageserver_id = args.endpoint_pageserver_id;
1417 0 : let remote_ext_base_url = &args.remote_ext_base_url;
1418 0 :
1419 0 : let default_generation = env
1420 0 : .storage_controller
1421 0 : .timelines_onto_safekeepers
1422 0 : .then_some(1);
1423 0 : let safekeepers_generation = args
1424 0 : .safekeepers_generation
1425 0 : .or(default_generation)
1426 0 : .map(SafekeeperGeneration::new);
1427 : // If --safekeepers argument is given, use only the listed
1428 : // safekeeper nodes; otherwise all from the env.
1429 0 : let safekeepers = if let Some(safekeepers) = parse_safekeepers(&args.safekeepers)? {
1430 0 : safekeepers
1431 : } else {
1432 0 : env.safekeepers.iter().map(|sk| sk.id).collect()
1433 : };
1434 :
1435 0 : let endpoint = cplane
1436 0 : .endpoints
1437 0 : .get(endpoint_id.as_str())
1438 0 : .ok_or_else(|| anyhow::anyhow!("endpoint {endpoint_id} not found"))?;
1439 :
1440 0 : if !args.allow_multiple {
1441 0 : cplane.check_conflicting_endpoints(
1442 0 : endpoint.mode,
1443 0 : endpoint.tenant_id,
1444 0 : endpoint.timeline_id,
1445 0 : )?;
1446 0 : }
1447 :
1448 0 : let (pageservers, stripe_size) = if let Some(pageserver_id) = pageserver_id {
1449 0 : let conf = env.get_pageserver_conf(pageserver_id).unwrap();
1450 0 : let parsed = parse_host_port(&conf.listen_pg_addr).expect("Bad config");
1451 0 : (
1452 0 : vec![(parsed.0, parsed.1.unwrap_or(5432))],
1453 0 : // If caller is telling us what pageserver to use, this is not a tenant which is
1454 0 : // full managed by storage controller, therefore not sharded.
1455 0 : DEFAULT_STRIPE_SIZE,
1456 0 : )
1457 : } else {
1458 : // Look up the currently attached location of the tenant, and its striping metadata,
1459 : // to pass these on to postgres.
1460 0 : let storage_controller = StorageController::from_env(env);
1461 0 : let locate_result = storage_controller.tenant_locate(endpoint.tenant_id).await?;
1462 0 : let pageservers = futures::future::try_join_all(
1463 0 : locate_result.shards.into_iter().map(|shard| async move {
1464 0 : if let ComputeMode::Static(lsn) = endpoint.mode {
1465 : // Initialize LSN leases for static computes.
1466 0 : let conf = env.get_pageserver_conf(shard.node_id).unwrap();
1467 0 : let pageserver = PageServerNode::from_env(env, conf);
1468 0 :
1469 0 : pageserver
1470 0 : .http_client
1471 0 : .timeline_init_lsn_lease(shard.shard_id, endpoint.timeline_id, lsn)
1472 0 : .await?;
1473 0 : }
1474 :
1475 0 : anyhow::Ok((
1476 0 : Host::parse(&shard.listen_pg_addr)
1477 0 : .expect("Storage controller reported bad hostname"),
1478 0 : shard.listen_pg_port,
1479 0 : ))
1480 0 : }),
1481 0 : )
1482 0 : .await?;
1483 0 : let stripe_size = locate_result.shard_params.stripe_size;
1484 0 :
1485 0 : (pageservers, stripe_size)
1486 : };
1487 0 : assert!(!pageservers.is_empty());
1488 :
1489 0 : let ps_conf = env.get_pageserver_conf(DEFAULT_PAGESERVER_ID)?;
1490 0 : let auth_token = if matches!(ps_conf.pg_auth_type, AuthType::NeonJWT) {
1491 0 : let claims = Claims::new(Some(endpoint.tenant_id), Scope::Tenant);
1492 0 :
1493 0 : Some(env.generate_auth_token(&claims)?)
1494 : } else {
1495 0 : None
1496 : };
1497 :
1498 0 : let exp = (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?
1499 0 : + Duration::from_secs(86400))
1500 0 : .as_secs();
1501 0 : let claims = endpoint_storage::claims::EndpointStorageClaims {
1502 0 : tenant_id: endpoint.tenant_id,
1503 0 : timeline_id: endpoint.timeline_id,
1504 0 : endpoint_id: endpoint_id.to_string(),
1505 0 : exp,
1506 0 : };
1507 :
1508 0 : let endpoint_storage_token = env.generate_auth_token(&claims)?;
1509 0 : let endpoint_storage_addr = env.endpoint_storage.listen_addr.to_string();
1510 0 :
1511 0 : println!("Starting existing endpoint {endpoint_id}...");
1512 0 : endpoint
1513 0 : .start(
1514 0 : &auth_token,
1515 0 : endpoint_storage_token,
1516 0 : endpoint_storage_addr,
1517 0 : safekeepers_generation,
1518 0 : safekeepers,
1519 0 : pageservers,
1520 0 : remote_ext_base_url.as_ref(),
1521 0 : stripe_size.0 as usize,
1522 0 : args.create_test_user,
1523 0 : args.start_timeout,
1524 0 : )
1525 0 : .await?;
1526 : }
1527 0 : EndpointCmd::Reconfigure(args) => {
1528 0 : let endpoint_id = &args.endpoint_id;
1529 0 : let endpoint = cplane
1530 0 : .endpoints
1531 0 : .get(endpoint_id.as_str())
1532 0 : .with_context(|| format!("postgres endpoint {endpoint_id} is not found"))?;
1533 0 : let pageservers = if let Some(ps_id) = args.endpoint_pageserver_id {
1534 0 : let pageserver = PageServerNode::from_env(env, env.get_pageserver_conf(ps_id)?);
1535 0 : vec![(
1536 0 : pageserver.pg_connection_config.host().clone(),
1537 0 : pageserver.pg_connection_config.port(),
1538 0 : )]
1539 : } else {
1540 0 : let storage_controller = StorageController::from_env(env);
1541 0 : storage_controller
1542 0 : .tenant_locate(endpoint.tenant_id)
1543 0 : .await?
1544 : .shards
1545 0 : .into_iter()
1546 0 : .map(|shard| {
1547 0 : (
1548 0 : Host::parse(&shard.listen_pg_addr)
1549 0 : .expect("Storage controller reported malformed host"),
1550 0 : shard.listen_pg_port,
1551 0 : )
1552 0 : })
1553 0 : .collect::<Vec<_>>()
1554 : };
1555 : // If --safekeepers argument is given, use only the listed
1556 : // safekeeper nodes; otherwise all from the env.
1557 0 : let safekeepers = parse_safekeepers(&args.safekeepers)?;
1558 0 : endpoint.reconfigure(pageservers, None, safekeepers).await?;
1559 : }
1560 0 : EndpointCmd::Stop(args) => {
1561 0 : let endpoint_id = &args.endpoint_id;
1562 0 : let endpoint = cplane
1563 0 : .endpoints
1564 0 : .get(endpoint_id)
1565 0 : .with_context(|| format!("postgres endpoint {endpoint_id} is not found"))?;
1566 0 : endpoint.stop(&args.mode, args.destroy)?;
1567 : }
1568 0 : EndpointCmd::GenerateJwt(args) => {
1569 0 : let endpoint = {
1570 0 : let endpoint_id = &args.endpoint_id;
1571 0 :
1572 0 : cplane
1573 0 : .endpoints
1574 0 : .get(endpoint_id)
1575 0 : .with_context(|| format!("postgres endpoint {endpoint_id} is not found"))?
1576 : };
1577 :
1578 0 : let jwt = endpoint.generate_jwt(args.scope)?;
1579 :
1580 0 : print!("{jwt}");
1581 : }
1582 : }
1583 :
1584 0 : Ok(())
1585 0 : }
1586 :
1587 : /// Parse --safekeepers as list of safekeeper ids.
1588 0 : fn parse_safekeepers(safekeepers_str: &Option<String>) -> Result<Option<Vec<NodeId>>> {
1589 0 : if let Some(safekeepers_str) = safekeepers_str {
1590 0 : let mut safekeepers: Vec<NodeId> = Vec::new();
1591 0 : for sk_id in safekeepers_str.split(',').map(str::trim) {
1592 0 : let sk_id = NodeId(
1593 0 : u64::from_str(sk_id)
1594 0 : .map_err(|_| anyhow!("invalid node ID \"{sk_id}\" in --safekeepers list"))?,
1595 : );
1596 0 : safekeepers.push(sk_id);
1597 : }
1598 0 : Ok(Some(safekeepers))
1599 : } else {
1600 0 : Ok(None)
1601 : }
1602 0 : }
1603 :
1604 0 : fn handle_mappings(subcmd: &MappingsCmd, env: &mut local_env::LocalEnv) -> Result<()> {
1605 0 : match subcmd {
1606 0 : MappingsCmd::Map(args) => {
1607 0 : env.register_branch_mapping(
1608 0 : args.branch_name.to_owned(),
1609 0 : args.tenant_id,
1610 0 : args.timeline_id,
1611 0 : )?;
1612 :
1613 0 : Ok(())
1614 : }
1615 : }
1616 0 : }
1617 :
1618 0 : fn get_pageserver(
1619 0 : env: &local_env::LocalEnv,
1620 0 : pageserver_id_arg: Option<NodeId>,
1621 0 : ) -> Result<PageServerNode> {
1622 0 : let node_id = pageserver_id_arg.unwrap_or(DEFAULT_PAGESERVER_ID);
1623 0 :
1624 0 : Ok(PageServerNode::from_env(
1625 0 : env,
1626 0 : env.get_pageserver_conf(node_id)?,
1627 : ))
1628 0 : }
1629 :
1630 0 : async fn handle_pageserver(subcmd: &PageserverCmd, env: &local_env::LocalEnv) -> Result<()> {
1631 0 : match subcmd {
1632 0 : PageserverCmd::Start(args) => {
1633 0 : if let Err(e) = get_pageserver(env, args.pageserver_id)?
1634 0 : .start(&args.start_timeout)
1635 0 : .await
1636 : {
1637 0 : eprintln!("pageserver start failed: {e}");
1638 0 : exit(1);
1639 0 : }
1640 : }
1641 :
1642 0 : PageserverCmd::Stop(args) => {
1643 0 : let immediate = match args.stop_mode {
1644 0 : StopMode::Fast => false,
1645 0 : StopMode::Immediate => true,
1646 : };
1647 0 : if let Err(e) = get_pageserver(env, args.pageserver_id)?.stop(immediate) {
1648 0 : eprintln!("pageserver stop failed: {}", e);
1649 0 : exit(1);
1650 0 : }
1651 : }
1652 :
1653 0 : PageserverCmd::Restart(args) => {
1654 0 : let pageserver = get_pageserver(env, args.pageserver_id)?;
1655 : //TODO what shutdown strategy should we use here?
1656 0 : if let Err(e) = pageserver.stop(false) {
1657 0 : eprintln!("pageserver stop failed: {}", e);
1658 0 : exit(1);
1659 0 : }
1660 :
1661 0 : if let Err(e) = pageserver.start(&args.start_timeout).await {
1662 0 : eprintln!("pageserver start failed: {e}");
1663 0 : exit(1);
1664 0 : }
1665 : }
1666 :
1667 0 : PageserverCmd::Status(args) => {
1668 0 : match get_pageserver(env, args.pageserver_id)?
1669 0 : .check_status()
1670 0 : .await
1671 : {
1672 0 : Ok(_) => println!("Page server is up and running"),
1673 0 : Err(err) => {
1674 0 : eprintln!("Page server is not available: {}", err);
1675 0 : exit(1);
1676 : }
1677 : }
1678 : }
1679 : }
1680 0 : Ok(())
1681 0 : }
1682 :
1683 0 : async fn handle_storage_controller(
1684 0 : subcmd: &StorageControllerCmd,
1685 0 : env: &local_env::LocalEnv,
1686 0 : ) -> Result<()> {
1687 0 : let svc = StorageController::from_env(env);
1688 0 : match subcmd {
1689 0 : StorageControllerCmd::Start(args) => {
1690 0 : let start_args = NeonStorageControllerStartArgs {
1691 0 : instance_id: args.instance_id,
1692 0 : base_port: args.base_port,
1693 0 : start_timeout: args.start_timeout,
1694 0 : };
1695 :
1696 0 : if let Err(e) = svc.start(start_args).await {
1697 0 : eprintln!("start failed: {e}");
1698 0 : exit(1);
1699 0 : }
1700 : }
1701 :
1702 0 : StorageControllerCmd::Stop(args) => {
1703 0 : let stop_args = NeonStorageControllerStopArgs {
1704 0 : instance_id: args.instance_id,
1705 0 : immediate: match args.stop_mode {
1706 0 : StopMode::Fast => false,
1707 0 : StopMode::Immediate => true,
1708 : },
1709 : };
1710 0 : if let Err(e) = svc.stop(stop_args).await {
1711 0 : eprintln!("stop failed: {}", e);
1712 0 : exit(1);
1713 0 : }
1714 : }
1715 : }
1716 0 : Ok(())
1717 0 : }
1718 :
1719 0 : fn get_safekeeper(env: &local_env::LocalEnv, id: NodeId) -> Result<SafekeeperNode> {
1720 0 : if let Some(node) = env.safekeepers.iter().find(|node| node.id == id) {
1721 0 : Ok(SafekeeperNode::from_env(env, node))
1722 : } else {
1723 0 : bail!("could not find safekeeper {id}")
1724 : }
1725 0 : }
1726 :
1727 0 : async fn handle_safekeeper(subcmd: &SafekeeperCmd, env: &local_env::LocalEnv) -> Result<()> {
1728 0 : match subcmd {
1729 0 : SafekeeperCmd::Start(args) => {
1730 0 : let safekeeper = get_safekeeper(env, args.id)?;
1731 :
1732 0 : if let Err(e) = safekeeper.start(&args.extra_opt, &args.start_timeout).await {
1733 0 : eprintln!("safekeeper start failed: {}", e);
1734 0 : exit(1);
1735 0 : }
1736 : }
1737 :
1738 0 : SafekeeperCmd::Stop(args) => {
1739 0 : let safekeeper = get_safekeeper(env, args.id)?;
1740 0 : let immediate = match args.stop_mode {
1741 0 : StopMode::Fast => false,
1742 0 : StopMode::Immediate => true,
1743 : };
1744 0 : if let Err(e) = safekeeper.stop(immediate) {
1745 0 : eprintln!("safekeeper stop failed: {}", e);
1746 0 : exit(1);
1747 0 : }
1748 : }
1749 :
1750 0 : SafekeeperCmd::Restart(args) => {
1751 0 : let safekeeper = get_safekeeper(env, args.id)?;
1752 0 : let immediate = match args.stop_mode {
1753 0 : StopMode::Fast => false,
1754 0 : StopMode::Immediate => true,
1755 : };
1756 :
1757 0 : if let Err(e) = safekeeper.stop(immediate) {
1758 0 : eprintln!("safekeeper stop failed: {}", e);
1759 0 : exit(1);
1760 0 : }
1761 :
1762 0 : if let Err(e) = safekeeper.start(&args.extra_opt, &args.start_timeout).await {
1763 0 : eprintln!("safekeeper start failed: {}", e);
1764 0 : exit(1);
1765 0 : }
1766 : }
1767 : }
1768 0 : Ok(())
1769 0 : }
1770 :
1771 0 : async fn handle_endpoint_storage(
1772 0 : subcmd: &EndpointStorageCmd,
1773 0 : env: &local_env::LocalEnv,
1774 0 : ) -> Result<()> {
1775 : use EndpointStorageCmd::*;
1776 0 : let storage = EndpointStorage::from_env(env);
1777 0 :
1778 0 : // In tests like test_forward_compatibility or test_graceful_cluster_restart
1779 0 : // old neon binaries (without endpoint_storage) are present
1780 0 : if !storage.bin.exists() {
1781 0 : eprintln!(
1782 0 : "{} binary not found. Ignore if this is a compatibility test",
1783 0 : storage.bin
1784 0 : );
1785 0 : return Ok(());
1786 0 : }
1787 0 :
1788 0 : match subcmd {
1789 0 : Start(EndpointStorageStartCmd { start_timeout }) => {
1790 0 : if let Err(e) = storage.start(start_timeout).await {
1791 0 : eprintln!("endpoint_storage start failed: {e}");
1792 0 : exit(1);
1793 0 : }
1794 : }
1795 0 : Stop(EndpointStorageStopCmd { stop_mode }) => {
1796 0 : let immediate = match stop_mode {
1797 0 : StopMode::Fast => false,
1798 0 : StopMode::Immediate => true,
1799 : };
1800 0 : if let Err(e) = storage.stop(immediate) {
1801 0 : eprintln!("proxy stop failed: {e}");
1802 0 : exit(1);
1803 0 : }
1804 : }
1805 : };
1806 0 : Ok(())
1807 0 : }
1808 :
1809 0 : async fn handle_storage_broker(subcmd: &StorageBrokerCmd, env: &local_env::LocalEnv) -> Result<()> {
1810 0 : match subcmd {
1811 0 : StorageBrokerCmd::Start(args) => {
1812 0 : let storage_broker = StorageBroker::from_env(env);
1813 0 : if let Err(e) = storage_broker.start(&args.start_timeout).await {
1814 0 : eprintln!("broker start failed: {e}");
1815 0 : exit(1);
1816 0 : }
1817 : }
1818 :
1819 0 : StorageBrokerCmd::Stop(_args) => {
1820 0 : // FIXME: stop_mode unused
1821 0 : let storage_broker = StorageBroker::from_env(env);
1822 0 : if let Err(e) = storage_broker.stop() {
1823 0 : eprintln!("broker stop failed: {e}");
1824 0 : exit(1);
1825 0 : }
1826 : }
1827 : }
1828 0 : Ok(())
1829 0 : }
1830 :
1831 0 : async fn handle_start_all(
1832 0 : args: &StartCmdArgs,
1833 0 : env: &'static local_env::LocalEnv,
1834 0 : ) -> anyhow::Result<()> {
1835 : // FIXME: this was called "retry_timeout", is it right?
1836 0 : let Err(errors) = handle_start_all_impl(env, args.timeout).await else {
1837 0 : neon_start_status_check(env, args.timeout.as_ref())
1838 0 : .await
1839 0 : .context("status check after successful startup of all services")?;
1840 0 : return Ok(());
1841 : };
1842 :
1843 0 : eprintln!("startup failed because one or more services could not be started");
1844 :
1845 0 : for e in errors {
1846 0 : eprintln!("{e}");
1847 0 : let debug_repr = format!("{e:?}");
1848 0 : for line in debug_repr.lines() {
1849 0 : eprintln!(" {line}");
1850 0 : }
1851 : }
1852 :
1853 0 : try_stop_all(env, true).await;
1854 :
1855 0 : exit(2);
1856 0 : }
1857 :
1858 : /// Returns Ok() if and only if all services could be started successfully.
1859 : /// Otherwise, returns the list of errors that occurred during startup.
1860 0 : async fn handle_start_all_impl(
1861 0 : env: &'static local_env::LocalEnv,
1862 0 : retry_timeout: humantime::Duration,
1863 0 : ) -> Result<(), Vec<anyhow::Error>> {
1864 0 : // Endpoints are not started automatically
1865 0 :
1866 0 : let mut js = JoinSet::new();
1867 :
1868 : // force infalliblity through closure
1869 : #[allow(clippy::redundant_closure_call)]
1870 0 : (|| {
1871 0 : js.spawn(async move {
1872 0 : let storage_broker = StorageBroker::from_env(env);
1873 0 : storage_broker
1874 0 : .start(&retry_timeout)
1875 0 : .await
1876 0 : .map_err(|e| e.context("start storage_broker"))
1877 0 : });
1878 0 :
1879 0 : js.spawn(async move {
1880 0 : let storage_controller = StorageController::from_env(env);
1881 0 : storage_controller
1882 0 : .start(NeonStorageControllerStartArgs::with_default_instance_id(
1883 0 : retry_timeout,
1884 0 : ))
1885 0 : .await
1886 0 : .map_err(|e| e.context("start storage_controller"))
1887 0 : });
1888 :
1889 0 : for ps_conf in &env.pageservers {
1890 0 : js.spawn(async move {
1891 0 : let pageserver = PageServerNode::from_env(env, ps_conf);
1892 0 : pageserver
1893 0 : .start(&retry_timeout)
1894 0 : .await
1895 0 : .map_err(|e| e.context(format!("start pageserver {}", ps_conf.id)))
1896 0 : });
1897 0 : }
1898 :
1899 0 : for node in env.safekeepers.iter() {
1900 0 : js.spawn(async move {
1901 0 : let safekeeper = SafekeeperNode::from_env(env, node);
1902 0 : safekeeper
1903 0 : .start(&[], &retry_timeout)
1904 0 : .await
1905 0 : .map_err(|e| e.context(format!("start safekeeper {}", safekeeper.id)))
1906 0 : });
1907 0 : }
1908 :
1909 0 : js.spawn(async move {
1910 0 : EndpointStorage::from_env(env)
1911 0 : .start(&retry_timeout)
1912 0 : .await
1913 0 : .map_err(|e| e.context("start endpoint_storage"))
1914 0 : });
1915 0 : })();
1916 0 :
1917 0 : let mut errors = Vec::new();
1918 0 : while let Some(result) = js.join_next().await {
1919 0 : let result = result.expect("we don't panic or cancel the tasks");
1920 0 : if let Err(e) = result {
1921 0 : errors.push(e);
1922 0 : }
1923 : }
1924 :
1925 0 : if !errors.is_empty() {
1926 0 : return Err(errors);
1927 0 : }
1928 0 :
1929 0 : Ok(())
1930 0 : }
1931 :
1932 0 : async fn neon_start_status_check(
1933 0 : env: &local_env::LocalEnv,
1934 0 : retry_timeout: &Duration,
1935 0 : ) -> anyhow::Result<()> {
1936 : const RETRY_INTERVAL: Duration = Duration::from_millis(100);
1937 : const NOTICE_AFTER_RETRIES: Duration = Duration::from_secs(5);
1938 :
1939 0 : let storcon = StorageController::from_env(env);
1940 0 :
1941 0 : let retries = retry_timeout.as_millis() / RETRY_INTERVAL.as_millis();
1942 0 : let notice_after_retries = retry_timeout.as_millis() / NOTICE_AFTER_RETRIES.as_millis();
1943 0 :
1944 0 : println!("\nRunning neon status check");
1945 :
1946 0 : for retry in 0..retries {
1947 0 : if retry == notice_after_retries {
1948 0 : println!("\nNeon status check has not passed yet, continuing to wait")
1949 0 : }
1950 :
1951 0 : let mut passed = true;
1952 0 : let mut nodes = storcon.node_list().await?;
1953 0 : let mut pageservers = env.pageservers.clone();
1954 0 :
1955 0 : if nodes.len() != pageservers.len() {
1956 0 : continue;
1957 0 : }
1958 0 :
1959 0 : nodes.sort_by_key(|ps| ps.id);
1960 0 : pageservers.sort_by_key(|ps| ps.id);
1961 :
1962 0 : for (idx, pageserver) in pageservers.iter().enumerate() {
1963 0 : let node = &nodes[idx];
1964 0 : if node.id != pageserver.id {
1965 0 : passed = false;
1966 0 : break;
1967 0 : }
1968 :
1969 0 : if !matches!(node.availability, NodeAvailabilityWrapper::Active) {
1970 0 : passed = false;
1971 0 : break;
1972 0 : }
1973 : }
1974 :
1975 0 : if passed {
1976 0 : println!("\nNeon started and passed status check");
1977 0 : return Ok(());
1978 0 : }
1979 0 :
1980 0 : tokio::time::sleep(RETRY_INTERVAL).await;
1981 : }
1982 :
1983 0 : anyhow::bail!("\nNeon passed status check")
1984 0 : }
1985 :
1986 0 : async fn handle_stop_all(args: &StopCmdArgs, env: &local_env::LocalEnv) -> Result<()> {
1987 0 : let immediate = match args.mode {
1988 0 : StopMode::Fast => false,
1989 0 : StopMode::Immediate => true,
1990 : };
1991 :
1992 0 : try_stop_all(env, immediate).await;
1993 :
1994 0 : Ok(())
1995 0 : }
1996 :
1997 0 : async fn try_stop_all(env: &local_env::LocalEnv, immediate: bool) {
1998 0 : // Stop all endpoints
1999 0 : match ComputeControlPlane::load(env.clone()) {
2000 0 : Ok(cplane) => {
2001 0 : for (_k, node) in cplane.endpoints {
2002 0 : if let Err(e) = node.stop(if immediate { "immediate" } else { "fast" }, false) {
2003 0 : eprintln!("postgres stop failed: {e:#}");
2004 0 : }
2005 : }
2006 : }
2007 0 : Err(e) => {
2008 0 : eprintln!("postgres stop failed, could not restore control plane data from env: {e:#}")
2009 : }
2010 : }
2011 :
2012 0 : let storage = EndpointStorage::from_env(env);
2013 0 : if let Err(e) = storage.stop(immediate) {
2014 0 : eprintln!("endpoint_storage stop failed: {:#}", e);
2015 0 : }
2016 :
2017 0 : for ps_conf in &env.pageservers {
2018 0 : let pageserver = PageServerNode::from_env(env, ps_conf);
2019 0 : if let Err(e) = pageserver.stop(immediate) {
2020 0 : eprintln!("pageserver {} stop failed: {:#}", ps_conf.id, e);
2021 0 : }
2022 : }
2023 :
2024 0 : for node in env.safekeepers.iter() {
2025 0 : let safekeeper = SafekeeperNode::from_env(env, node);
2026 0 : if let Err(e) = safekeeper.stop(immediate) {
2027 0 : eprintln!("safekeeper {} stop failed: {:#}", safekeeper.id, e);
2028 0 : }
2029 : }
2030 :
2031 0 : let storage_broker = StorageBroker::from_env(env);
2032 0 : if let Err(e) = storage_broker.stop() {
2033 0 : eprintln!("neon broker stop failed: {e:#}");
2034 0 : }
2035 :
2036 : // Stop all storage controller instances. In the most common case there's only one,
2037 : // but iterate though the base data directory in order to discover the instances.
2038 0 : let storcon_instances = env
2039 0 : .storage_controller_instances()
2040 0 : .await
2041 0 : .expect("Must inspect data dir");
2042 0 : for (instance_id, _instance_dir_path) in storcon_instances {
2043 0 : let storage_controller = StorageController::from_env(env);
2044 0 : let stop_args = NeonStorageControllerStopArgs {
2045 0 : instance_id,
2046 0 : immediate,
2047 0 : };
2048 :
2049 0 : if let Err(e) = storage_controller.stop(stop_args).await {
2050 0 : eprintln!("Storage controller instance {instance_id} stop failed: {e:#}");
2051 0 : }
2052 : }
2053 0 : }
|