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

Generated by: LCOV version 2.1-beta