LCOV - code coverage report
Current view: top level - control_plane/src/bin - neon_local.rs (source / functions) Coverage Total Hit
Test: feead26e04cdef6e988ff1765b1cb7075eb48d3d.info Lines: 0.0 % 984 0
Test Date: 2025-02-28 12:11:00 Functions: 0.0 % 202 0

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

Generated by: LCOV version 2.1-beta