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

Generated by: LCOV version 2.1-beta