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