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