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