LCOV - code coverage report
Current view: top level - control_plane/src/bin - neon_local.rs (source / functions) Coverage Total Hit
Test: 75747cdbffeb0b6d2a2a311584368de68cd9aadc.info Lines: 27.5 % 1335 367
Test Date: 2024-06-24 06:52:57 Functions: 2.2 % 90 2

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

Generated by: LCOV version 2.1-beta