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