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

Generated by: LCOV version 2.1-beta