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

Generated by: LCOV version 2.1-beta