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

Generated by: LCOV version 2.1-beta