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