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