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