Line data Source code
1 : use std::collections::{HashMap, HashSet};
2 : use std::str::FromStr;
3 : use std::time::Duration;
4 :
5 : use clap::{Parser, Subcommand};
6 : use futures::StreamExt;
7 : use pageserver_api::controller_api::{
8 : AvailabilityZone, NodeAvailabilityWrapper, NodeConfigureRequest, NodeDescribeResponse,
9 : NodeRegisterRequest, NodeSchedulingPolicy, NodeShardResponse, PlacementPolicy,
10 : SafekeeperDescribeResponse, SafekeeperSchedulingPolicyRequest, ShardSchedulingPolicy,
11 : ShardsPreferredAzsRequest, ShardsPreferredAzsResponse, SkSchedulingPolicy, TenantCreateRequest,
12 : TenantDescribeResponse, TenantPolicyRequest, TenantShardMigrateRequest,
13 : TenantShardMigrateResponse,
14 : };
15 : use pageserver_api::models::{
16 : EvictionPolicy, EvictionPolicyLayerAccessThreshold, LocationConfigSecondary, ShardParameters,
17 : TenantConfig, TenantConfigPatchRequest, TenantConfigRequest, TenantShardSplitRequest,
18 : TenantShardSplitResponse,
19 : };
20 : use pageserver_api::shard::{ShardStripeSize, TenantShardId};
21 : use pageserver_client::mgmt_api::{self};
22 : use reqwest::{Method, StatusCode, Url};
23 : use storage_controller_client::control_api::Client;
24 : use utils::id::{NodeId, TenantId, TimelineId};
25 :
26 : #[derive(Subcommand, Debug)]
27 : enum Command {
28 : /// Register a pageserver with the storage controller. This shouldn't usually be necessary,
29 : /// since pageservers auto-register when they start up
30 : NodeRegister {
31 : #[arg(long)]
32 0 : node_id: NodeId,
33 :
34 : #[arg(long)]
35 0 : listen_pg_addr: String,
36 : #[arg(long)]
37 0 : listen_pg_port: u16,
38 :
39 : #[arg(long)]
40 0 : listen_http_addr: String,
41 : #[arg(long)]
42 0 : listen_http_port: u16,
43 : #[arg(long)]
44 : listen_https_port: Option<u16>,
45 :
46 : #[arg(long)]
47 0 : availability_zone_id: String,
48 : },
49 :
50 : /// Modify a node's configuration in the storage controller
51 : NodeConfigure {
52 : #[arg(long)]
53 0 : node_id: NodeId,
54 :
55 : /// Availability is usually auto-detected based on heartbeats. Set 'offline' here to
56 : /// manually mark a node offline
57 : #[arg(long)]
58 : availability: Option<NodeAvailabilityArg>,
59 : /// Scheduling policy controls whether tenant shards may be scheduled onto this node.
60 : #[arg(long)]
61 : scheduling: Option<NodeSchedulingPolicy>,
62 : },
63 : NodeDelete {
64 : #[arg(long)]
65 0 : node_id: NodeId,
66 : },
67 : /// Modify a tenant's policies in the storage controller
68 : TenantPolicy {
69 : #[arg(long)]
70 0 : tenant_id: TenantId,
71 : /// Placement policy controls whether a tenant is `detached`, has only a secondary location (`secondary`),
72 : /// or is in the normal attached state with N secondary locations (`attached:N`)
73 : #[arg(long)]
74 : placement: Option<PlacementPolicyArg>,
75 : /// Scheduling policy enables pausing the controller's scheduling activity involving this tenant. `active` is normal,
76 : /// `essential` disables optimization scheduling changes, `pause` disables all scheduling changes, and `stop` prevents
77 : /// all reconciliation activity including for scheduling changes already made. `pause` and `stop` can make a tenant
78 : /// unavailable, and are only for use in emergencies.
79 : #[arg(long)]
80 : scheduling: Option<ShardSchedulingPolicyArg>,
81 : },
82 : /// List nodes known to the storage controller
83 : Nodes {},
84 : /// List tenants known to the storage controller
85 : Tenants {
86 : /// If this field is set, it will list the tenants on a specific node
87 : node_id: Option<NodeId>,
88 : },
89 : /// Create a new tenant in the storage controller, and by extension on pageservers.
90 : TenantCreate {
91 : #[arg(long)]
92 0 : tenant_id: TenantId,
93 : },
94 : /// Delete a tenant in the storage controller, and by extension on pageservers.
95 : TenantDelete {
96 : #[arg(long)]
97 0 : tenant_id: TenantId,
98 : },
99 : /// Split an existing tenant into a higher number of shards than its current shard count.
100 : TenantShardSplit {
101 : #[arg(long)]
102 0 : tenant_id: TenantId,
103 : #[arg(long)]
104 0 : shard_count: u8,
105 : /// Optional, in 8kiB pages. e.g. set 2048 for 16MB stripes.
106 : #[arg(long)]
107 : stripe_size: Option<u32>,
108 : },
109 : /// Migrate the attached location for a tenant shard to a specific pageserver.
110 : TenantShardMigrate {
111 : #[arg(long)]
112 0 : tenant_shard_id: TenantShardId,
113 : #[arg(long)]
114 0 : node: NodeId,
115 : },
116 : /// Migrate the secondary location for a tenant shard to a specific pageserver.
117 : TenantShardMigrateSecondary {
118 : #[arg(long)]
119 0 : tenant_shard_id: TenantShardId,
120 : #[arg(long)]
121 0 : node: NodeId,
122 : },
123 : /// Cancel any ongoing reconciliation for this shard
124 : TenantShardCancelReconcile {
125 : #[arg(long)]
126 0 : tenant_shard_id: TenantShardId,
127 : },
128 : /// Set the pageserver tenant configuration of a tenant: this is the configuration structure
129 : /// that is passed through to pageservers, and does not affect storage controller behavior.
130 : /// Any previous tenant configs are overwritten.
131 : SetTenantConfig {
132 : #[arg(long)]
133 0 : tenant_id: TenantId,
134 : #[arg(long)]
135 0 : config: String,
136 : },
137 : /// Patch the pageserver tenant configuration of a tenant. Any fields with null values in the
138 : /// provided JSON are unset from the tenant config and all fields with non-null values are set.
139 : /// Unspecified fields are not changed.
140 : PatchTenantConfig {
141 : #[arg(long)]
142 0 : tenant_id: TenantId,
143 : #[arg(long)]
144 0 : config: String,
145 : },
146 : /// Print details about a particular tenant, including all its shards' states.
147 : TenantDescribe {
148 : #[arg(long)]
149 0 : tenant_id: TenantId,
150 : },
151 : /// For a tenant which hasn't been onboarded to the storage controller yet, add it in secondary
152 : /// mode so that it can warm up content on a pageserver.
153 : TenantWarmup {
154 : #[arg(long)]
155 0 : tenant_id: TenantId,
156 : },
157 : TenantSetPreferredAz {
158 : #[arg(long)]
159 0 : tenant_id: TenantId,
160 : #[arg(long)]
161 : preferred_az: Option<String>,
162 : },
163 : /// Uncleanly drop a tenant from the storage controller: this doesn't delete anything from pageservers. Appropriate
164 : /// if you e.g. used `tenant-warmup` by mistake on a tenant ID that doesn't really exist, or is in some other region.
165 : TenantDrop {
166 : #[arg(long)]
167 0 : tenant_id: TenantId,
168 : #[arg(long)]
169 0 : unclean: bool,
170 : },
171 : NodeDrop {
172 : #[arg(long)]
173 0 : node_id: NodeId,
174 : #[arg(long)]
175 0 : unclean: bool,
176 : },
177 : TenantSetTimeBasedEviction {
178 : #[arg(long)]
179 0 : tenant_id: TenantId,
180 : #[arg(long)]
181 0 : period: humantime::Duration,
182 : #[arg(long)]
183 0 : threshold: humantime::Duration,
184 : },
185 : // Migrate away from a set of specified pageservers by moving the primary attachments to pageservers
186 : // outside of the specified set.
187 : BulkMigrate {
188 : // Set of pageserver node ids to drain.
189 : #[arg(long)]
190 0 : nodes: Vec<NodeId>,
191 : // Optional: migration concurrency (default is 8)
192 : #[arg(long)]
193 : concurrency: Option<usize>,
194 : // Optional: maximum number of shards to migrate
195 : #[arg(long)]
196 : max_shards: Option<usize>,
197 : // Optional: when set to true, nothing is migrated, but the plan is printed to stdout
198 : #[arg(long)]
199 : dry_run: Option<bool>,
200 : },
201 : /// Start draining the specified pageserver.
202 : /// The drain is complete when the schedulling policy returns to active.
203 : StartDrain {
204 : #[arg(long)]
205 0 : node_id: NodeId,
206 : },
207 : /// Cancel draining the specified pageserver and wait for `timeout`
208 : /// for the operation to be canceled. May be retried.
209 : CancelDrain {
210 : #[arg(long)]
211 0 : node_id: NodeId,
212 : #[arg(long)]
213 0 : timeout: humantime::Duration,
214 : },
215 : /// Start filling the specified pageserver.
216 : /// The drain is complete when the schedulling policy returns to active.
217 : StartFill {
218 : #[arg(long)]
219 0 : node_id: NodeId,
220 : },
221 : /// Cancel filling the specified pageserver and wait for `timeout`
222 : /// for the operation to be canceled. May be retried.
223 : CancelFill {
224 : #[arg(long)]
225 0 : node_id: NodeId,
226 : #[arg(long)]
227 0 : timeout: humantime::Duration,
228 : },
229 : /// List safekeepers known to the storage controller
230 : Safekeepers {},
231 : /// Set the scheduling policy of the specified safekeeper
232 : SafekeeperScheduling {
233 : #[arg(long)]
234 0 : node_id: NodeId,
235 : #[arg(long)]
236 0 : scheduling_policy: SkSchedulingPolicyArg,
237 : },
238 : /// Downloads any missing heatmap layers for all shard for a given timeline
239 : DownloadHeatmapLayers {
240 : /// Tenant ID or tenant shard ID. When an unsharded tenant ID is specified,
241 : /// the operation is performed on all shards. When a sharded tenant ID is
242 : /// specified, the operation is only performed on the specified shard.
243 : #[arg(long)]
244 0 : tenant_shard_id: TenantShardId,
245 : #[arg(long)]
246 0 : timeline_id: TimelineId,
247 : /// Optional: Maximum download concurrency (default is 16)
248 : #[arg(long)]
249 : concurrency: Option<usize>,
250 : },
251 : }
252 :
253 : #[derive(Parser)]
254 : #[command(
255 : author,
256 : version,
257 : about,
258 : long_about = "CLI for Storage Controller Support/Debug"
259 : )]
260 : #[command(arg_required_else_help(true))]
261 : struct Cli {
262 : #[arg(long)]
263 : /// URL to storage controller. e.g. http://127.0.0.1:1234 when using `neon_local`
264 0 : api: Url,
265 :
266 : #[arg(long)]
267 : /// JWT token for authenticating with storage controller. Depending on the API used, this
268 : /// should have either `pageserverapi` or `admin` scopes: for convenience, you should mint
269 : /// a token with both scopes to use with this tool.
270 : jwt: Option<String>,
271 :
272 : #[command(subcommand)]
273 : command: Command,
274 : }
275 :
276 : #[derive(Debug, Clone)]
277 : struct PlacementPolicyArg(PlacementPolicy);
278 :
279 : impl FromStr for PlacementPolicyArg {
280 : type Err = anyhow::Error;
281 :
282 0 : fn from_str(s: &str) -> Result<Self, Self::Err> {
283 0 : match s {
284 0 : "detached" => Ok(Self(PlacementPolicy::Detached)),
285 0 : "secondary" => Ok(Self(PlacementPolicy::Secondary)),
286 0 : _ if s.starts_with("attached:") => {
287 0 : let mut splitter = s.split(':');
288 0 : let _prefix = splitter.next().unwrap();
289 0 : match splitter.next().and_then(|s| s.parse::<usize>().ok()) {
290 0 : Some(n) => Ok(Self(PlacementPolicy::Attached(n))),
291 0 : None => Err(anyhow::anyhow!(
292 0 : "Invalid format '{s}', a valid example is 'attached:1'"
293 0 : )),
294 : }
295 : }
296 0 : _ => Err(anyhow::anyhow!(
297 0 : "Unknown placement policy '{s}', try detached,secondary,attached:<n>"
298 0 : )),
299 : }
300 0 : }
301 : }
302 :
303 : #[derive(Debug, Clone)]
304 : struct SkSchedulingPolicyArg(SkSchedulingPolicy);
305 :
306 : impl FromStr for SkSchedulingPolicyArg {
307 : type Err = anyhow::Error;
308 :
309 0 : fn from_str(s: &str) -> Result<Self, Self::Err> {
310 0 : SkSchedulingPolicy::from_str(s).map(Self)
311 0 : }
312 : }
313 :
314 : #[derive(Debug, Clone)]
315 : struct ShardSchedulingPolicyArg(ShardSchedulingPolicy);
316 :
317 : impl FromStr for ShardSchedulingPolicyArg {
318 : type Err = anyhow::Error;
319 :
320 0 : fn from_str(s: &str) -> Result<Self, Self::Err> {
321 0 : match s {
322 0 : "active" => Ok(Self(ShardSchedulingPolicy::Active)),
323 0 : "essential" => Ok(Self(ShardSchedulingPolicy::Essential)),
324 0 : "pause" => Ok(Self(ShardSchedulingPolicy::Pause)),
325 0 : "stop" => Ok(Self(ShardSchedulingPolicy::Stop)),
326 0 : _ => Err(anyhow::anyhow!(
327 0 : "Unknown scheduling policy '{s}', try active,essential,pause,stop"
328 0 : )),
329 : }
330 0 : }
331 : }
332 :
333 : #[derive(Debug, Clone)]
334 : struct NodeAvailabilityArg(NodeAvailabilityWrapper);
335 :
336 : impl FromStr for NodeAvailabilityArg {
337 : type Err = anyhow::Error;
338 :
339 0 : fn from_str(s: &str) -> Result<Self, Self::Err> {
340 0 : match s {
341 0 : "active" => Ok(Self(NodeAvailabilityWrapper::Active)),
342 0 : "offline" => Ok(Self(NodeAvailabilityWrapper::Offline)),
343 0 : _ => Err(anyhow::anyhow!("Unknown availability state '{s}'")),
344 : }
345 0 : }
346 : }
347 :
348 0 : async fn wait_for_scheduling_policy<F>(
349 0 : client: Client,
350 0 : node_id: NodeId,
351 0 : timeout: Duration,
352 0 : f: F,
353 0 : ) -> anyhow::Result<NodeSchedulingPolicy>
354 0 : where
355 0 : F: Fn(NodeSchedulingPolicy) -> bool,
356 0 : {
357 0 : let waiter = tokio::time::timeout(timeout, async move {
358 : loop {
359 0 : let node = client
360 0 : .dispatch::<(), NodeDescribeResponse>(
361 0 : Method::GET,
362 0 : format!("control/v1/node/{node_id}"),
363 0 : None,
364 0 : )
365 0 : .await?;
366 :
367 0 : if f(node.scheduling) {
368 0 : return Ok::<NodeSchedulingPolicy, mgmt_api::Error>(node.scheduling);
369 0 : }
370 : }
371 0 : });
372 0 :
373 0 : Ok(waiter.await??)
374 0 : }
375 :
376 : #[tokio::main]
377 0 : async fn main() -> anyhow::Result<()> {
378 0 : let cli = Cli::parse();
379 0 :
380 0 : let storcon_client = Client::new(cli.api.clone(), cli.jwt.clone());
381 0 :
382 0 : let mut trimmed = cli.api.to_string();
383 0 : trimmed.pop();
384 0 : let vps_client = mgmt_api::Client::new(trimmed, cli.jwt.as_deref());
385 0 :
386 0 : match cli.command {
387 0 : Command::NodeRegister {
388 0 : node_id,
389 0 : listen_pg_addr,
390 0 : listen_pg_port,
391 0 : listen_http_addr,
392 0 : listen_http_port,
393 0 : listen_https_port,
394 0 : availability_zone_id,
395 0 : } => {
396 0 : storcon_client
397 0 : .dispatch::<_, ()>(
398 0 : Method::POST,
399 0 : "control/v1/node".to_string(),
400 0 : Some(NodeRegisterRequest {
401 0 : node_id,
402 0 : listen_pg_addr,
403 0 : listen_pg_port,
404 0 : listen_http_addr,
405 0 : listen_http_port,
406 0 : listen_https_port,
407 0 : availability_zone_id: AvailabilityZone(availability_zone_id),
408 0 : }),
409 0 : )
410 0 : .await?;
411 0 : }
412 0 : Command::TenantCreate { tenant_id } => {
413 0 : storcon_client
414 0 : .dispatch::<_, ()>(
415 0 : Method::POST,
416 0 : "v1/tenant".to_string(),
417 0 : Some(TenantCreateRequest {
418 0 : new_tenant_id: TenantShardId::unsharded(tenant_id),
419 0 : generation: None,
420 0 : shard_parameters: ShardParameters::default(),
421 0 : placement_policy: Some(PlacementPolicy::Attached(1)),
422 0 : config: TenantConfig::default(),
423 0 : }),
424 0 : )
425 0 : .await?;
426 0 : }
427 0 : Command::TenantDelete { tenant_id } => {
428 0 : let status = vps_client
429 0 : .tenant_delete(TenantShardId::unsharded(tenant_id))
430 0 : .await?;
431 0 : tracing::info!("Delete status: {}", status);
432 0 : }
433 0 : Command::Nodes {} => {
434 0 : let mut resp = storcon_client
435 0 : .dispatch::<(), Vec<NodeDescribeResponse>>(
436 0 : Method::GET,
437 0 : "control/v1/node".to_string(),
438 0 : None,
439 0 : )
440 0 : .await?;
441 0 :
442 0 : resp.sort_by(|a, b| a.listen_http_addr.cmp(&b.listen_http_addr));
443 0 :
444 0 : let mut table = comfy_table::Table::new();
445 0 : table.set_header(["Id", "Hostname", "AZ", "Scheduling", "Availability"]);
446 0 : for node in resp {
447 0 : table.add_row([
448 0 : format!("{}", node.id),
449 0 : node.listen_http_addr,
450 0 : node.availability_zone_id,
451 0 : format!("{:?}", node.scheduling),
452 0 : format!("{:?}", node.availability),
453 0 : ]);
454 0 : }
455 0 : println!("{table}");
456 0 : }
457 0 : Command::NodeConfigure {
458 0 : node_id,
459 0 : availability,
460 0 : scheduling,
461 0 : } => {
462 0 : let req = NodeConfigureRequest {
463 0 : node_id,
464 0 : availability: availability.map(|a| a.0),
465 0 : scheduling,
466 0 : };
467 0 : storcon_client
468 0 : .dispatch::<_, ()>(
469 0 : Method::PUT,
470 0 : format!("control/v1/node/{node_id}/config"),
471 0 : Some(req),
472 0 : )
473 0 : .await?;
474 0 : }
475 0 : Command::Tenants {
476 0 : node_id: Some(node_id),
477 0 : } => {
478 0 : let describe_response = storcon_client
479 0 : .dispatch::<(), NodeShardResponse>(
480 0 : Method::GET,
481 0 : format!("control/v1/node/{node_id}/shards"),
482 0 : None,
483 0 : )
484 0 : .await?;
485 0 : let shards = describe_response.shards;
486 0 : let mut table = comfy_table::Table::new();
487 0 : table.set_header([
488 0 : "Shard",
489 0 : "Intended Primary/Secondary",
490 0 : "Observed Primary/Secondary",
491 0 : ]);
492 0 : for shard in shards {
493 0 : table.add_row([
494 0 : format!("{}", shard.tenant_shard_id),
495 0 : match shard.is_intended_secondary {
496 0 : None => "".to_string(),
497 0 : Some(true) => "Secondary".to_string(),
498 0 : Some(false) => "Primary".to_string(),
499 0 : },
500 0 : match shard.is_observed_secondary {
501 0 : None => "".to_string(),
502 0 : Some(true) => "Secondary".to_string(),
503 0 : Some(false) => "Primary".to_string(),
504 0 : },
505 0 : ]);
506 0 : }
507 0 : println!("{table}");
508 0 : }
509 0 : Command::Tenants { node_id: None } => {
510 0 : // Set up output formatting
511 0 : let mut table = comfy_table::Table::new();
512 0 : table.set_header([
513 0 : "TenantId",
514 0 : "Preferred AZ",
515 0 : "ShardCount",
516 0 : "StripeSize",
517 0 : "Placement",
518 0 : "Scheduling",
519 0 : ]);
520 0 :
521 0 : // Pagination loop over listing API
522 0 : let mut start_after = None;
523 0 : const LIMIT: usize = 1000;
524 0 : loop {
525 0 : let path = match start_after {
526 0 : None => format!("control/v1/tenant?limit={LIMIT}"),
527 0 : Some(start_after) => {
528 0 : format!("control/v1/tenant?limit={LIMIT}&start_after={start_after}")
529 0 : }
530 0 : };
531 0 :
532 0 : let resp = storcon_client
533 0 : .dispatch::<(), Vec<TenantDescribeResponse>>(Method::GET, path, None)
534 0 : .await?;
535 0 :
536 0 : if resp.is_empty() {
537 0 : // End of data reached
538 0 : break;
539 0 : }
540 0 :
541 0 : // Give some visual feedback while we're building up the table (comfy_table doesn't have
542 0 : // streaming output)
543 0 : if resp.len() >= LIMIT {
544 0 : eprint!(".");
545 0 : }
546 0 :
547 0 : start_after = Some(resp.last().unwrap().tenant_id);
548 0 :
549 0 : for tenant in resp {
550 0 : let shard_zero = tenant.shards.into_iter().next().unwrap();
551 0 : table.add_row([
552 0 : format!("{}", tenant.tenant_id),
553 0 : shard_zero
554 0 : .preferred_az_id
555 0 : .as_ref()
556 0 : .cloned()
557 0 : .unwrap_or("".to_string()),
558 0 : format!("{}", shard_zero.tenant_shard_id.shard_count.literal()),
559 0 : format!("{:?}", tenant.stripe_size),
560 0 : format!("{:?}", tenant.policy),
561 0 : format!("{:?}", shard_zero.scheduling_policy),
562 0 : ]);
563 0 : }
564 0 : }
565 0 :
566 0 : // Terminate progress dots
567 0 : if table.row_count() > LIMIT {
568 0 : eprint!("");
569 0 : }
570 0 :
571 0 : println!("{table}");
572 0 : }
573 0 : Command::TenantPolicy {
574 0 : tenant_id,
575 0 : placement,
576 0 : scheduling,
577 0 : } => {
578 0 : let req = TenantPolicyRequest {
579 0 : scheduling: scheduling.map(|s| s.0),
580 0 : placement: placement.map(|p| p.0),
581 0 : };
582 0 : storcon_client
583 0 : .dispatch::<_, ()>(
584 0 : Method::PUT,
585 0 : format!("control/v1/tenant/{tenant_id}/policy"),
586 0 : Some(req),
587 0 : )
588 0 : .await?;
589 0 : }
590 0 : Command::TenantShardSplit {
591 0 : tenant_id,
592 0 : shard_count,
593 0 : stripe_size,
594 0 : } => {
595 0 : let req = TenantShardSplitRequest {
596 0 : new_shard_count: shard_count,
597 0 : new_stripe_size: stripe_size.map(ShardStripeSize),
598 0 : };
599 0 :
600 0 : let response = storcon_client
601 0 : .dispatch::<TenantShardSplitRequest, TenantShardSplitResponse>(
602 0 : Method::PUT,
603 0 : format!("control/v1/tenant/{tenant_id}/shard_split"),
604 0 : Some(req),
605 0 : )
606 0 : .await?;
607 0 : println!(
608 0 : "Split tenant {} into {} shards: {}",
609 0 : tenant_id,
610 0 : shard_count,
611 0 : response
612 0 : .new_shards
613 0 : .iter()
614 0 : .map(|s| format!("{:?}", s))
615 0 : .collect::<Vec<_>>()
616 0 : .join(",")
617 0 : );
618 0 : }
619 0 : Command::TenantShardMigrate {
620 0 : tenant_shard_id,
621 0 : node,
622 0 : } => {
623 0 : let req = TenantShardMigrateRequest {
624 0 : node_id: node,
625 0 : migration_config: None,
626 0 : };
627 0 :
628 0 : storcon_client
629 0 : .dispatch::<TenantShardMigrateRequest, TenantShardMigrateResponse>(
630 0 : Method::PUT,
631 0 : format!("control/v1/tenant/{tenant_shard_id}/migrate"),
632 0 : Some(req),
633 0 : )
634 0 : .await?;
635 0 : }
636 0 : Command::TenantShardMigrateSecondary {
637 0 : tenant_shard_id,
638 0 : node,
639 0 : } => {
640 0 : let req = TenantShardMigrateRequest {
641 0 : node_id: node,
642 0 : migration_config: None,
643 0 : };
644 0 :
645 0 : storcon_client
646 0 : .dispatch::<TenantShardMigrateRequest, TenantShardMigrateResponse>(
647 0 : Method::PUT,
648 0 : format!("control/v1/tenant/{tenant_shard_id}/migrate_secondary"),
649 0 : Some(req),
650 0 : )
651 0 : .await?;
652 0 : }
653 0 : Command::TenantShardCancelReconcile { tenant_shard_id } => {
654 0 : storcon_client
655 0 : .dispatch::<(), ()>(
656 0 : Method::PUT,
657 0 : format!("control/v1/tenant/{tenant_shard_id}/cancel_reconcile"),
658 0 : None,
659 0 : )
660 0 : .await?;
661 0 : }
662 0 : Command::SetTenantConfig { tenant_id, config } => {
663 0 : let tenant_conf = serde_json::from_str(&config)?;
664 0 :
665 0 : vps_client
666 0 : .set_tenant_config(&TenantConfigRequest {
667 0 : tenant_id,
668 0 : config: tenant_conf,
669 0 : })
670 0 : .await?;
671 0 : }
672 0 : Command::PatchTenantConfig { tenant_id, config } => {
673 0 : let tenant_conf = serde_json::from_str(&config)?;
674 0 :
675 0 : vps_client
676 0 : .patch_tenant_config(&TenantConfigPatchRequest {
677 0 : tenant_id,
678 0 : config: tenant_conf,
679 0 : })
680 0 : .await?;
681 0 : }
682 0 : Command::TenantDescribe { tenant_id } => {
683 0 : let TenantDescribeResponse {
684 0 : tenant_id,
685 0 : shards,
686 0 : stripe_size,
687 0 : policy,
688 0 : config,
689 0 : } = storcon_client
690 0 : .dispatch::<(), TenantDescribeResponse>(
691 0 : Method::GET,
692 0 : format!("control/v1/tenant/{tenant_id}"),
693 0 : None,
694 0 : )
695 0 : .await?;
696 0 :
697 0 : let nodes = storcon_client
698 0 : .dispatch::<(), Vec<NodeDescribeResponse>>(
699 0 : Method::GET,
700 0 : "control/v1/node".to_string(),
701 0 : None,
702 0 : )
703 0 : .await?;
704 0 : let nodes = nodes
705 0 : .into_iter()
706 0 : .map(|n| (n.id, n))
707 0 : .collect::<HashMap<_, _>>();
708 0 :
709 0 : println!("Tenant {tenant_id}");
710 0 : let mut table = comfy_table::Table::new();
711 0 : table.add_row(["Policy", &format!("{:?}", policy)]);
712 0 : table.add_row(["Stripe size", &format!("{:?}", stripe_size)]);
713 0 : table.add_row(["Config", &serde_json::to_string_pretty(&config).unwrap()]);
714 0 : println!("{table}");
715 0 : println!("Shards:");
716 0 : let mut table = comfy_table::Table::new();
717 0 : table.set_header([
718 0 : "Shard",
719 0 : "Attached",
720 0 : "Attached AZ",
721 0 : "Secondary",
722 0 : "Last error",
723 0 : "status",
724 0 : ]);
725 0 : for shard in shards {
726 0 : let secondary = shard
727 0 : .node_secondary
728 0 : .iter()
729 0 : .map(|n| format!("{}", n))
730 0 : .collect::<Vec<_>>()
731 0 : .join(",");
732 0 :
733 0 : let mut status_parts = Vec::new();
734 0 : if shard.is_reconciling {
735 0 : status_parts.push("reconciling");
736 0 : }
737 0 :
738 0 : if shard.is_pending_compute_notification {
739 0 : status_parts.push("pending_compute");
740 0 : }
741 0 :
742 0 : if shard.is_splitting {
743 0 : status_parts.push("splitting");
744 0 : }
745 0 : let status = status_parts.join(",");
746 0 :
747 0 : let attached_node = shard
748 0 : .node_attached
749 0 : .as_ref()
750 0 : .map(|id| nodes.get(id).expect("Shard references nonexistent node"));
751 0 :
752 0 : table.add_row([
753 0 : format!("{}", shard.tenant_shard_id),
754 0 : attached_node
755 0 : .map(|n| format!("{} ({})", n.listen_http_addr, n.id))
756 0 : .unwrap_or(String::new()),
757 0 : attached_node
758 0 : .map(|n| n.availability_zone_id.clone())
759 0 : .unwrap_or(String::new()),
760 0 : secondary,
761 0 : shard.last_error,
762 0 : status,
763 0 : ]);
764 0 : }
765 0 : println!("{table}");
766 0 : }
767 0 : Command::TenantSetPreferredAz {
768 0 : tenant_id,
769 0 : preferred_az,
770 0 : } => {
771 0 : // First learn about the tenant's shards
772 0 : let describe_response = storcon_client
773 0 : .dispatch::<(), TenantDescribeResponse>(
774 0 : Method::GET,
775 0 : format!("control/v1/tenant/{tenant_id}"),
776 0 : None,
777 0 : )
778 0 : .await?;
779 0 :
780 0 : // Learn about nodes to validate the AZ ID
781 0 : let nodes = storcon_client
782 0 : .dispatch::<(), Vec<NodeDescribeResponse>>(
783 0 : Method::GET,
784 0 : "control/v1/node".to_string(),
785 0 : None,
786 0 : )
787 0 : .await?;
788 0 :
789 0 : if let Some(preferred_az) = &preferred_az {
790 0 : let azs = nodes
791 0 : .into_iter()
792 0 : .map(|n| (n.availability_zone_id))
793 0 : .collect::<HashSet<_>>();
794 0 : if !azs.contains(preferred_az) {
795 0 : anyhow::bail!(
796 0 : "AZ {} not found on any node: known AZs are: {:?}",
797 0 : preferred_az,
798 0 : azs
799 0 : );
800 0 : }
801 0 : } else {
802 0 : // Make it obvious to the user that since they've omitted an AZ, we're clearing it
803 0 : eprintln!("Clearing preferred AZ for tenant {}", tenant_id);
804 0 : }
805 0 :
806 0 : // Construct a request that modifies all the tenant's shards
807 0 : let req = ShardsPreferredAzsRequest {
808 0 : preferred_az_ids: describe_response
809 0 : .shards
810 0 : .into_iter()
811 0 : .map(|s| {
812 0 : (
813 0 : s.tenant_shard_id,
814 0 : preferred_az.clone().map(AvailabilityZone),
815 0 : )
816 0 : })
817 0 : .collect(),
818 0 : };
819 0 : storcon_client
820 0 : .dispatch::<ShardsPreferredAzsRequest, ShardsPreferredAzsResponse>(
821 0 : Method::PUT,
822 0 : "control/v1/preferred_azs".to_string(),
823 0 : Some(req),
824 0 : )
825 0 : .await?;
826 0 : }
827 0 : Command::TenantWarmup { tenant_id } => {
828 0 : let describe_response = storcon_client
829 0 : .dispatch::<(), TenantDescribeResponse>(
830 0 : Method::GET,
831 0 : format!("control/v1/tenant/{tenant_id}"),
832 0 : None,
833 0 : )
834 0 : .await;
835 0 : match describe_response {
836 0 : Ok(describe) => {
837 0 : if matches!(describe.policy, PlacementPolicy::Secondary) {
838 0 : // Fine: it's already known to controller in secondary mode: calling
839 0 : // again to put it into secondary mode won't cause problems.
840 0 : } else {
841 0 : anyhow::bail!("Tenant already present with policy {:?}", describe.policy);
842 0 : }
843 0 : }
844 0 : Err(mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _)) => {
845 0 : // Fine: this tenant isn't know to the storage controller yet.
846 0 : }
847 0 : Err(e) => {
848 0 : // Unexpected API error
849 0 : return Err(e.into());
850 0 : }
851 0 : }
852 0 :
853 0 : vps_client
854 0 : .location_config(
855 0 : TenantShardId::unsharded(tenant_id),
856 0 : pageserver_api::models::LocationConfig {
857 0 : mode: pageserver_api::models::LocationConfigMode::Secondary,
858 0 : generation: None,
859 0 : secondary_conf: Some(LocationConfigSecondary { warm: true }),
860 0 : shard_number: 0,
861 0 : shard_count: 0,
862 0 : shard_stripe_size: ShardParameters::DEFAULT_STRIPE_SIZE.0,
863 0 : tenant_conf: TenantConfig::default(),
864 0 : },
865 0 : None,
866 0 : true,
867 0 : )
868 0 : .await?;
869 0 :
870 0 : let describe_response = storcon_client
871 0 : .dispatch::<(), TenantDescribeResponse>(
872 0 : Method::GET,
873 0 : format!("control/v1/tenant/{tenant_id}"),
874 0 : None,
875 0 : )
876 0 : .await?;
877 0 :
878 0 : let secondary_ps_id = describe_response
879 0 : .shards
880 0 : .first()
881 0 : .unwrap()
882 0 : .node_secondary
883 0 : .first()
884 0 : .unwrap();
885 0 :
886 0 : println!("Tenant {tenant_id} warming up on pageserver {secondary_ps_id}");
887 0 : loop {
888 0 : let (status, progress) = vps_client
889 0 : .tenant_secondary_download(
890 0 : TenantShardId::unsharded(tenant_id),
891 0 : Some(Duration::from_secs(10)),
892 0 : )
893 0 : .await?;
894 0 : println!(
895 0 : "Progress: {}/{} layers, {}/{} bytes",
896 0 : progress.layers_downloaded,
897 0 : progress.layers_total,
898 0 : progress.bytes_downloaded,
899 0 : progress.bytes_total
900 0 : );
901 0 : match status {
902 0 : StatusCode::OK => {
903 0 : println!("Download complete");
904 0 : break;
905 0 : }
906 0 : StatusCode::ACCEPTED => {
907 0 : // Loop
908 0 : }
909 0 : _ => {
910 0 : anyhow::bail!("Unexpected download status: {status}");
911 0 : }
912 0 : }
913 0 : }
914 0 : }
915 0 : Command::TenantDrop { tenant_id, unclean } => {
916 0 : if !unclean {
917 0 : anyhow::bail!(
918 0 : "This command is not a tenant deletion, and uncleanly drops all controller state for the tenant. If you know what you're doing, add `--unclean` to proceed."
919 0 : )
920 0 : }
921 0 : storcon_client
922 0 : .dispatch::<(), ()>(
923 0 : Method::POST,
924 0 : format!("debug/v1/tenant/{tenant_id}/drop"),
925 0 : None,
926 0 : )
927 0 : .await?;
928 0 : }
929 0 : Command::NodeDrop { node_id, unclean } => {
930 0 : if !unclean {
931 0 : anyhow::bail!(
932 0 : "This command is not a clean node decommission, and uncleanly drops all controller state for the node, without checking if any tenants still refer to it. If you know what you're doing, add `--unclean` to proceed."
933 0 : )
934 0 : }
935 0 : storcon_client
936 0 : .dispatch::<(), ()>(Method::POST, format!("debug/v1/node/{node_id}/drop"), None)
937 0 : .await?;
938 0 : }
939 0 : Command::NodeDelete { node_id } => {
940 0 : storcon_client
941 0 : .dispatch::<(), ()>(Method::DELETE, format!("control/v1/node/{node_id}"), None)
942 0 : .await?;
943 0 : }
944 0 : Command::TenantSetTimeBasedEviction {
945 0 : tenant_id,
946 0 : period,
947 0 : threshold,
948 0 : } => {
949 0 : vps_client
950 0 : .set_tenant_config(&TenantConfigRequest {
951 0 : tenant_id,
952 0 : config: TenantConfig {
953 0 : eviction_policy: Some(EvictionPolicy::LayerAccessThreshold(
954 0 : EvictionPolicyLayerAccessThreshold {
955 0 : period: period.into(),
956 0 : threshold: threshold.into(),
957 0 : },
958 0 : )),
959 0 : heatmap_period: Some(Duration::from_secs(300)),
960 0 : ..Default::default()
961 0 : },
962 0 : })
963 0 : .await?;
964 0 : }
965 0 : Command::BulkMigrate {
966 0 : nodes,
967 0 : concurrency,
968 0 : max_shards,
969 0 : dry_run,
970 0 : } => {
971 0 : // Load the list of nodes, split them up into the drained and filled sets,
972 0 : // and validate that draining is possible.
973 0 : let node_descs = storcon_client
974 0 : .dispatch::<(), Vec<NodeDescribeResponse>>(
975 0 : Method::GET,
976 0 : "control/v1/node".to_string(),
977 0 : None,
978 0 : )
979 0 : .await?;
980 0 :
981 0 : let mut node_to_drain_descs = Vec::new();
982 0 : let mut node_to_fill_descs = Vec::new();
983 0 :
984 0 : for desc in node_descs {
985 0 : let to_drain = nodes.iter().any(|id| *id == desc.id);
986 0 : if to_drain {
987 0 : node_to_drain_descs.push(desc);
988 0 : } else {
989 0 : node_to_fill_descs.push(desc);
990 0 : }
991 0 : }
992 0 :
993 0 : if nodes.len() != node_to_drain_descs.len() {
994 0 : anyhow::bail!("Bulk migration requested away from node which doesn't exist.")
995 0 : }
996 0 :
997 0 : node_to_fill_descs.retain(|desc| {
998 0 : matches!(desc.availability, NodeAvailabilityWrapper::Active)
999 0 : && matches!(
1000 0 : desc.scheduling,
1001 0 : NodeSchedulingPolicy::Active | NodeSchedulingPolicy::Filling
1002 0 : )
1003 0 : });
1004 0 :
1005 0 : if node_to_fill_descs.is_empty() {
1006 0 : anyhow::bail!("There are no nodes to migrate to")
1007 0 : }
1008 0 :
1009 0 : // Set the node scheduling policy to draining for the nodes which
1010 0 : // we plan to drain.
1011 0 : for node_desc in node_to_drain_descs.iter() {
1012 0 : let req = NodeConfigureRequest {
1013 0 : node_id: node_desc.id,
1014 0 : availability: None,
1015 0 : scheduling: Some(NodeSchedulingPolicy::Draining),
1016 0 : };
1017 0 :
1018 0 : storcon_client
1019 0 : .dispatch::<_, ()>(
1020 0 : Method::PUT,
1021 0 : format!("control/v1/node/{}/config", node_desc.id),
1022 0 : Some(req),
1023 0 : )
1024 0 : .await?;
1025 0 : }
1026 0 :
1027 0 : // Perform the migration: move each tenant shard scheduled on a node to
1028 0 : // be drained to a node which is being filled. A simple round robin
1029 0 : // strategy is used to pick the new node.
1030 0 : let tenants = storcon_client
1031 0 : .dispatch::<(), Vec<TenantDescribeResponse>>(
1032 0 : Method::GET,
1033 0 : "control/v1/tenant".to_string(),
1034 0 : None,
1035 0 : )
1036 0 : .await?;
1037 0 :
1038 0 : let mut selected_node_idx = 0;
1039 0 :
1040 0 : struct MigrationMove {
1041 0 : tenant_shard_id: TenantShardId,
1042 0 : from: NodeId,
1043 0 : to: NodeId,
1044 0 : }
1045 0 :
1046 0 : let mut moves: Vec<MigrationMove> = Vec::new();
1047 0 :
1048 0 : let shards = tenants
1049 0 : .into_iter()
1050 0 : .flat_map(|tenant| tenant.shards.into_iter());
1051 0 : for shard in shards {
1052 0 : if let Some(max_shards) = max_shards {
1053 0 : if moves.len() >= max_shards {
1054 0 : println!(
1055 0 : "Stop planning shard moves since the requested maximum was reached"
1056 0 : );
1057 0 : break;
1058 0 : }
1059 0 : }
1060 0 :
1061 0 : let should_migrate = {
1062 0 : if let Some(attached_to) = shard.node_attached {
1063 0 : node_to_drain_descs
1064 0 : .iter()
1065 0 : .map(|desc| desc.id)
1066 0 : .any(|id| id == attached_to)
1067 0 : } else {
1068 0 : false
1069 0 : }
1070 0 : };
1071 0 :
1072 0 : if !should_migrate {
1073 0 : continue;
1074 0 : }
1075 0 :
1076 0 : moves.push(MigrationMove {
1077 0 : tenant_shard_id: shard.tenant_shard_id,
1078 0 : from: shard
1079 0 : .node_attached
1080 0 : .expect("We only migrate attached tenant shards"),
1081 0 : to: node_to_fill_descs[selected_node_idx].id,
1082 0 : });
1083 0 : selected_node_idx = (selected_node_idx + 1) % node_to_fill_descs.len();
1084 0 : }
1085 0 :
1086 0 : let total_moves = moves.len();
1087 0 :
1088 0 : if dry_run == Some(true) {
1089 0 : println!("Dryrun requested. Planned {total_moves} moves:");
1090 0 : for mv in &moves {
1091 0 : println!("{}: {} -> {}", mv.tenant_shard_id, mv.from, mv.to)
1092 0 : }
1093 0 :
1094 0 : return Ok(());
1095 0 : }
1096 0 :
1097 0 : const DEFAULT_MIGRATE_CONCURRENCY: usize = 8;
1098 0 : let mut stream = futures::stream::iter(moves)
1099 0 : .map(|mv| {
1100 0 : let client = Client::new(cli.api.clone(), cli.jwt.clone());
1101 0 : async move {
1102 0 : client
1103 0 : .dispatch::<TenantShardMigrateRequest, TenantShardMigrateResponse>(
1104 0 : Method::PUT,
1105 0 : format!("control/v1/tenant/{}/migrate", mv.tenant_shard_id),
1106 0 : Some(TenantShardMigrateRequest {
1107 0 : node_id: mv.to,
1108 0 : migration_config: None,
1109 0 : }),
1110 0 : )
1111 0 : .await
1112 0 : .map_err(|e| (mv.tenant_shard_id, mv.from, mv.to, e))
1113 0 : }
1114 0 : })
1115 0 : .buffered(concurrency.unwrap_or(DEFAULT_MIGRATE_CONCURRENCY));
1116 0 :
1117 0 : let mut success = 0;
1118 0 : let mut failure = 0;
1119 0 :
1120 0 : while let Some(res) = stream.next().await {
1121 0 : match res {
1122 0 : Ok(_) => {
1123 0 : success += 1;
1124 0 : }
1125 0 : Err((tenant_shard_id, from, to, error)) => {
1126 0 : failure += 1;
1127 0 : println!(
1128 0 : "Failed to migrate {} from node {} to node {}: {}",
1129 0 : tenant_shard_id, from, to, error
1130 0 : );
1131 0 : }
1132 0 : }
1133 0 :
1134 0 : if (success + failure) % 20 == 0 {
1135 0 : println!(
1136 0 : "Processed {}/{} shards: {} succeeded, {} failed",
1137 0 : success + failure,
1138 0 : total_moves,
1139 0 : success,
1140 0 : failure
1141 0 : );
1142 0 : }
1143 0 : }
1144 0 :
1145 0 : println!(
1146 0 : "Processed {}/{} shards: {} succeeded, {} failed",
1147 0 : success + failure,
1148 0 : total_moves,
1149 0 : success,
1150 0 : failure
1151 0 : );
1152 0 : }
1153 0 : Command::StartDrain { node_id } => {
1154 0 : storcon_client
1155 0 : .dispatch::<(), ()>(
1156 0 : Method::PUT,
1157 0 : format!("control/v1/node/{node_id}/drain"),
1158 0 : None,
1159 0 : )
1160 0 : .await?;
1161 0 : println!("Drain started for {node_id}");
1162 0 : }
1163 0 : Command::CancelDrain { node_id, timeout } => {
1164 0 : storcon_client
1165 0 : .dispatch::<(), ()>(
1166 0 : Method::DELETE,
1167 0 : format!("control/v1/node/{node_id}/drain"),
1168 0 : None,
1169 0 : )
1170 0 : .await?;
1171 0 :
1172 0 : println!("Waiting for node {node_id} to quiesce on scheduling policy ...");
1173 0 :
1174 0 : let final_policy =
1175 0 : wait_for_scheduling_policy(storcon_client, node_id, *timeout, |sched| {
1176 0 : use NodeSchedulingPolicy::*;
1177 0 : matches!(sched, Active | PauseForRestart)
1178 0 : })
1179 0 : .await?;
1180 0 :
1181 0 : println!(
1182 0 : "Drain was cancelled for node {node_id}. Schedulling policy is now {final_policy:?}"
1183 0 : );
1184 0 : }
1185 0 : Command::StartFill { node_id } => {
1186 0 : storcon_client
1187 0 : .dispatch::<(), ()>(Method::PUT, format!("control/v1/node/{node_id}/fill"), None)
1188 0 : .await?;
1189 0 :
1190 0 : println!("Fill started for {node_id}");
1191 0 : }
1192 0 : Command::CancelFill { node_id, timeout } => {
1193 0 : storcon_client
1194 0 : .dispatch::<(), ()>(
1195 0 : Method::DELETE,
1196 0 : format!("control/v1/node/{node_id}/fill"),
1197 0 : None,
1198 0 : )
1199 0 : .await?;
1200 0 :
1201 0 : println!("Waiting for node {node_id} to quiesce on scheduling policy ...");
1202 0 :
1203 0 : let final_policy =
1204 0 : wait_for_scheduling_policy(storcon_client, node_id, *timeout, |sched| {
1205 0 : use NodeSchedulingPolicy::*;
1206 0 : matches!(sched, Active)
1207 0 : })
1208 0 : .await?;
1209 0 :
1210 0 : println!(
1211 0 : "Fill was cancelled for node {node_id}. Schedulling policy is now {final_policy:?}"
1212 0 : );
1213 0 : }
1214 0 : Command::Safekeepers {} => {
1215 0 : let mut resp = storcon_client
1216 0 : .dispatch::<(), Vec<SafekeeperDescribeResponse>>(
1217 0 : Method::GET,
1218 0 : "control/v1/safekeeper".to_string(),
1219 0 : None,
1220 0 : )
1221 0 : .await?;
1222 0 :
1223 0 : resp.sort_by(|a, b| a.id.cmp(&b.id));
1224 0 :
1225 0 : let mut table = comfy_table::Table::new();
1226 0 : table.set_header([
1227 0 : "Id",
1228 0 : "Version",
1229 0 : "Host",
1230 0 : "Port",
1231 0 : "Http Port",
1232 0 : "AZ Id",
1233 0 : "Scheduling",
1234 0 : ]);
1235 0 : for sk in resp {
1236 0 : table.add_row([
1237 0 : format!("{}", sk.id),
1238 0 : format!("{}", sk.version),
1239 0 : sk.host,
1240 0 : format!("{}", sk.port),
1241 0 : format!("{}", sk.http_port),
1242 0 : sk.availability_zone_id.clone(),
1243 0 : String::from(sk.scheduling_policy),
1244 0 : ]);
1245 0 : }
1246 0 : println!("{table}");
1247 0 : }
1248 0 : Command::SafekeeperScheduling {
1249 0 : node_id,
1250 0 : scheduling_policy,
1251 0 : } => {
1252 0 : let scheduling_policy = scheduling_policy.0;
1253 0 : storcon_client
1254 0 : .dispatch::<SafekeeperSchedulingPolicyRequest, ()>(
1255 0 : Method::POST,
1256 0 : format!("control/v1/safekeeper/{node_id}/scheduling_policy"),
1257 0 : Some(SafekeeperSchedulingPolicyRequest { scheduling_policy }),
1258 0 : )
1259 0 : .await?;
1260 0 : println!(
1261 0 : "Scheduling policy of {node_id} set to {}",
1262 0 : String::from(scheduling_policy)
1263 0 : );
1264 0 : }
1265 0 : Command::DownloadHeatmapLayers {
1266 0 : tenant_shard_id,
1267 0 : timeline_id,
1268 0 : concurrency,
1269 0 : } => {
1270 0 : let mut path = format!(
1271 0 : "/v1/tenant/{}/timeline/{}/download_heatmap_layers",
1272 0 : tenant_shard_id, timeline_id,
1273 0 : );
1274 0 :
1275 0 : if let Some(c) = concurrency {
1276 0 : path = format!("{path}?concurrency={c}");
1277 0 : }
1278 0 :
1279 0 : storcon_client
1280 0 : .dispatch::<(), ()>(Method::POST, path, None)
1281 0 : .await?;
1282 0 : }
1283 0 : }
1284 0 :
1285 0 : Ok(())
1286 0 : }
|