LCOV - code coverage report
Current view: top level - control_plane/src/bin - neon_local.rs (source / functions) Coverage Total Hit
Test: 4be46b1c0003aa3bbac9ade362c676b419df4c20.info Lines: 0.0 % 1001 0
Test Date: 2025-07-22 17:50:06 Functions: 0.0 % 74 0

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

Generated by: LCOV version 2.1-beta