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

Generated by: LCOV version 2.1-beta