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