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

Generated by: LCOV version 2.1-beta