Line data Source code
1 : use futures::StreamExt;
2 : use std::{str::FromStr, time::Duration};
3 :
4 : use clap::{Parser, Subcommand};
5 : use pageserver_api::{
6 : controller_api::{
7 : NodeAvailabilityWrapper, NodeDescribeResponse, ShardSchedulingPolicy, TenantCreateRequest,
8 : TenantDescribeResponse, TenantPolicyRequest,
9 : },
10 : models::{
11 : EvictionPolicy, EvictionPolicyLayerAccessThreshold, LocationConfigSecondary,
12 : ShardParameters, TenantConfig, TenantConfigRequest, TenantShardSplitRequest,
13 : TenantShardSplitResponse,
14 : },
15 : shard::{ShardStripeSize, TenantShardId},
16 : };
17 : use pageserver_client::mgmt_api::{self, ResponseErrorMessageExt};
18 : use reqwest::{Method, StatusCode, Url};
19 : use serde::{de::DeserializeOwned, Serialize};
20 : use utils::id::{NodeId, TenantId};
21 :
22 : use pageserver_api::controller_api::{
23 : NodeConfigureRequest, NodeRegisterRequest, NodeSchedulingPolicy, PlacementPolicy,
24 : TenantShardMigrateRequest, TenantShardMigrateResponse,
25 : };
26 :
27 0 : #[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 : },
45 :
46 : /// Modify a node's configuration in the storage controller
47 : NodeConfigure {
48 : #[arg(long)]
49 0 : node_id: NodeId,
50 :
51 : /// Availability is usually auto-detected based on heartbeats. Set 'offline' here to
52 : /// manually mark a node offline
53 : #[arg(long)]
54 : availability: Option<NodeAvailabilityArg>,
55 : /// Scheduling policy controls whether tenant shards may be scheduled onto this node.
56 : #[arg(long)]
57 : scheduling: Option<NodeSchedulingPolicy>,
58 : },
59 : /// Modify a tenant's policies in the storage controller
60 : TenantPolicy {
61 : #[arg(long)]
62 0 : tenant_id: TenantId,
63 : /// Placement policy controls whether a tenant is `detached`, has only a secondary location (`secondary`),
64 : /// or is in the normal attached state with N secondary locations (`attached:N`)
65 : #[arg(long)]
66 : placement: Option<PlacementPolicyArg>,
67 : /// Scheduling policy enables pausing the controller's scheduling activity involving this tenant. `active` is normal,
68 : /// `essential` disables optimization scheduling changes, `pause` disables all scheduling changes, and `stop` prevents
69 : /// all reconciliation activity including for scheduling changes already made. `pause` and `stop` can make a tenant
70 : /// unavailable, and are only for use in emergencies.
71 : #[arg(long)]
72 : scheduling: Option<ShardSchedulingPolicyArg>,
73 : },
74 : /// List nodes known to the storage controller
75 : Nodes {},
76 : /// List tenants known to the storage controller
77 : Tenants {},
78 : /// Create a new tenant in the storage controller, and by extension on pageservers.
79 : TenantCreate {
80 : #[arg(long)]
81 0 : tenant_id: TenantId,
82 : },
83 : /// Delete a tenant in the storage controller, and by extension on pageservers.
84 : TenantDelete {
85 : #[arg(long)]
86 0 : tenant_id: TenantId,
87 : },
88 : /// Split an existing tenant into a higher number of shards than its current shard count.
89 : TenantShardSplit {
90 : #[arg(long)]
91 0 : tenant_id: TenantId,
92 : #[arg(long)]
93 0 : shard_count: u8,
94 : /// Optional, in 8kiB pages. e.g. set 2048 for 16MB stripes.
95 : #[arg(long)]
96 : stripe_size: Option<u32>,
97 : },
98 : /// Migrate the attached location for a tenant shard to a specific pageserver.
99 : TenantShardMigrate {
100 : #[arg(long)]
101 0 : tenant_shard_id: TenantShardId,
102 : #[arg(long)]
103 0 : node: NodeId,
104 : },
105 : /// Modify the pageserver tenant configuration of a tenant: this is the configuration structure
106 : /// that is passed through to pageservers, and does not affect storage controller behavior.
107 : TenantConfig {
108 : #[arg(long)]
109 0 : tenant_id: TenantId,
110 : #[arg(long)]
111 0 : config: String,
112 : },
113 : /// Print details about a particular tenant, including all its shards' states.
114 : TenantDescribe {
115 : #[arg(long)]
116 0 : tenant_id: TenantId,
117 : },
118 : /// For a tenant which hasn't been onboarded to the storage controller yet, add it in secondary
119 : /// mode so that it can warm up content on a pageserver.
120 : TenantWarmup {
121 : #[arg(long)]
122 0 : tenant_id: TenantId,
123 : },
124 : /// Uncleanly drop a tenant from the storage controller: this doesn't delete anything from pageservers. Appropriate
125 : /// if you e.g. used `tenant-warmup` by mistake on a tenant ID that doesn't really exist, or is in some other region.
126 : TenantDrop {
127 : #[arg(long)]
128 0 : tenant_id: TenantId,
129 : #[arg(long)]
130 0 : unclean: bool,
131 : },
132 : NodeDrop {
133 : #[arg(long)]
134 0 : node_id: NodeId,
135 : #[arg(long)]
136 0 : unclean: bool,
137 : },
138 : TenantSetTimeBasedEviction {
139 : #[arg(long)]
140 0 : tenant_id: TenantId,
141 : #[arg(long)]
142 0 : period: humantime::Duration,
143 : #[arg(long)]
144 0 : threshold: humantime::Duration,
145 : },
146 : // Drain a set of specified pageservers by moving the primary attachments to pageservers
147 : // outside of the specified set.
148 : Drain {
149 : // Set of pageserver node ids to drain.
150 : #[arg(long)]
151 0 : nodes: Vec<NodeId>,
152 : // Optional: migration concurrency (default is 8)
153 : #[arg(long)]
154 : concurrency: Option<usize>,
155 : // Optional: maximum number of shards to migrate
156 : #[arg(long)]
157 : max_shards: Option<usize>,
158 : // Optional: when set to true, nothing is migrated, but the plan is printed to stdout
159 : #[arg(long)]
160 : dry_run: Option<bool>,
161 : },
162 : }
163 :
164 0 : #[derive(Parser)]
165 : #[command(
166 : author,
167 : version,
168 : about,
169 : long_about = "CLI for Storage Controller Support/Debug"
170 : )]
171 : #[command(arg_required_else_help(true))]
172 : struct Cli {
173 : #[arg(long)]
174 : /// URL to storage controller. e.g. http://127.0.0.1:1234 when using `neon_local`
175 0 : api: Url,
176 :
177 : #[arg(long)]
178 : /// JWT token for authenticating with storage controller. Depending on the API used, this
179 : /// should have either `pageserverapi` or `admin` scopes: for convenience, you should mint
180 : /// a token with both scopes to use with this tool.
181 : jwt: Option<String>,
182 :
183 : #[command(subcommand)]
184 : command: Command,
185 : }
186 :
187 : #[derive(Debug, Clone)]
188 : struct PlacementPolicyArg(PlacementPolicy);
189 :
190 : impl FromStr for PlacementPolicyArg {
191 : type Err = anyhow::Error;
192 :
193 0 : fn from_str(s: &str) -> Result<Self, Self::Err> {
194 0 : match s {
195 0 : "detached" => Ok(Self(PlacementPolicy::Detached)),
196 0 : "secondary" => Ok(Self(PlacementPolicy::Secondary)),
197 0 : _ if s.starts_with("attached:") => {
198 0 : let mut splitter = s.split(':');
199 0 : let _prefix = splitter.next().unwrap();
200 0 : match splitter.next().and_then(|s| s.parse::<usize>().ok()) {
201 0 : Some(n) => Ok(Self(PlacementPolicy::Attached(n))),
202 0 : None => Err(anyhow::anyhow!(
203 0 : "Invalid format '{s}', a valid example is 'attached:1'"
204 0 : )),
205 : }
206 : }
207 0 : _ => Err(anyhow::anyhow!(
208 0 : "Unknown placement policy '{s}', try detached,secondary,attached:<n>"
209 0 : )),
210 : }
211 0 : }
212 : }
213 :
214 : #[derive(Debug, Clone)]
215 : struct ShardSchedulingPolicyArg(ShardSchedulingPolicy);
216 :
217 : impl FromStr for ShardSchedulingPolicyArg {
218 : type Err = anyhow::Error;
219 :
220 0 : fn from_str(s: &str) -> Result<Self, Self::Err> {
221 0 : match s {
222 0 : "active" => Ok(Self(ShardSchedulingPolicy::Active)),
223 0 : "essential" => Ok(Self(ShardSchedulingPolicy::Essential)),
224 0 : "pause" => Ok(Self(ShardSchedulingPolicy::Pause)),
225 0 : "stop" => Ok(Self(ShardSchedulingPolicy::Stop)),
226 0 : _ => Err(anyhow::anyhow!(
227 0 : "Unknown scheduling policy '{s}', try active,essential,pause,stop"
228 0 : )),
229 : }
230 0 : }
231 : }
232 :
233 : #[derive(Debug, Clone)]
234 : struct NodeAvailabilityArg(NodeAvailabilityWrapper);
235 :
236 : impl FromStr for NodeAvailabilityArg {
237 : type Err = anyhow::Error;
238 :
239 0 : fn from_str(s: &str) -> Result<Self, Self::Err> {
240 0 : match s {
241 0 : "active" => Ok(Self(NodeAvailabilityWrapper::Active)),
242 0 : "offline" => Ok(Self(NodeAvailabilityWrapper::Offline)),
243 0 : _ => Err(anyhow::anyhow!("Unknown availability state '{s}'")),
244 : }
245 0 : }
246 : }
247 :
248 : struct Client {
249 : base_url: Url,
250 : jwt_token: Option<String>,
251 : client: reqwest::Client,
252 : }
253 :
254 : impl Client {
255 0 : fn new(base_url: Url, jwt_token: Option<String>) -> Self {
256 0 : Self {
257 0 : base_url,
258 0 : jwt_token,
259 0 : client: reqwest::ClientBuilder::new()
260 0 : .build()
261 0 : .expect("Failed to construct http client"),
262 0 : }
263 0 : }
264 :
265 : /// Simple HTTP request wrapper for calling into storage controller
266 0 : async fn dispatch<RQ, RS>(
267 0 : &self,
268 0 : method: Method,
269 0 : path: String,
270 0 : body: Option<RQ>,
271 0 : ) -> mgmt_api::Result<RS>
272 0 : where
273 0 : RQ: Serialize + Sized,
274 0 : RS: DeserializeOwned + Sized,
275 0 : {
276 0 : // The configured URL has the /upcall path prefix for pageservers to use: we will strip that out
277 0 : // for general purpose API access.
278 0 : let url = Url::from_str(&format!(
279 0 : "http://{}:{}/{path}",
280 0 : self.base_url.host_str().unwrap(),
281 0 : self.base_url.port().unwrap()
282 0 : ))
283 0 : .unwrap();
284 0 :
285 0 : let mut builder = self.client.request(method, url);
286 0 : if let Some(body) = body {
287 0 : builder = builder.json(&body)
288 0 : }
289 0 : if let Some(jwt_token) = &self.jwt_token {
290 0 : builder = builder.header(
291 0 : reqwest::header::AUTHORIZATION,
292 0 : format!("Bearer {jwt_token}"),
293 0 : );
294 0 : }
295 :
296 0 : let response = builder.send().await.map_err(mgmt_api::Error::ReceiveBody)?;
297 0 : let response = response.error_from_body().await?;
298 :
299 0 : response
300 0 : .json()
301 0 : .await
302 0 : .map_err(pageserver_client::mgmt_api::Error::ReceiveBody)
303 0 : }
304 : }
305 :
306 : #[tokio::main]
307 0 : async fn main() -> anyhow::Result<()> {
308 0 : let cli = Cli::parse();
309 0 :
310 0 : let storcon_client = Client::new(cli.api.clone(), cli.jwt.clone());
311 0 :
312 0 : let mut trimmed = cli.api.to_string();
313 0 : trimmed.pop();
314 0 : let vps_client = mgmt_api::Client::new(trimmed, cli.jwt.as_deref());
315 0 :
316 0 : match cli.command {
317 0 : Command::NodeRegister {
318 0 : node_id,
319 0 : listen_pg_addr,
320 0 : listen_pg_port,
321 0 : listen_http_addr,
322 0 : listen_http_port,
323 0 : } => {
324 0 : storcon_client
325 0 : .dispatch::<_, ()>(
326 0 : Method::POST,
327 0 : "control/v1/node".to_string(),
328 0 : Some(NodeRegisterRequest {
329 0 : node_id,
330 0 : listen_pg_addr,
331 0 : listen_pg_port,
332 0 : listen_http_addr,
333 0 : listen_http_port,
334 0 : }),
335 0 : )
336 0 : .await?;
337 0 : }
338 0 : Command::TenantCreate { tenant_id } => {
339 0 : storcon_client
340 0 : .dispatch(
341 0 : Method::POST,
342 0 : "v1/tenant".to_string(),
343 0 : Some(TenantCreateRequest {
344 0 : new_tenant_id: TenantShardId::unsharded(tenant_id),
345 0 : generation: None,
346 0 : shard_parameters: ShardParameters::default(),
347 0 : placement_policy: Some(PlacementPolicy::Attached(1)),
348 0 : config: TenantConfig::default(),
349 0 : }),
350 0 : )
351 0 : .await?;
352 0 : }
353 0 : Command::TenantDelete { tenant_id } => {
354 0 : let status = vps_client
355 0 : .tenant_delete(TenantShardId::unsharded(tenant_id))
356 0 : .await?;
357 0 : tracing::info!("Delete status: {}", status);
358 0 : }
359 0 : Command::Nodes {} => {
360 0 : let resp = storcon_client
361 0 : .dispatch::<(), Vec<NodeDescribeResponse>>(
362 0 : Method::GET,
363 0 : "control/v1/node".to_string(),
364 0 : None,
365 0 : )
366 0 : .await?;
367 0 : let mut table = comfy_table::Table::new();
368 0 : table.set_header(["Id", "Hostname", "Scheduling", "Availability"]);
369 0 : for node in resp {
370 0 : table.add_row([
371 0 : format!("{}", node.id),
372 0 : node.listen_http_addr,
373 0 : format!("{:?}", node.scheduling),
374 0 : format!("{:?}", node.availability),
375 0 : ]);
376 0 : }
377 0 : println!("{table}");
378 0 : }
379 0 : Command::NodeConfigure {
380 0 : node_id,
381 0 : availability,
382 0 : scheduling,
383 0 : } => {
384 0 : let req = NodeConfigureRequest {
385 0 : node_id,
386 0 : availability: availability.map(|a| a.0),
387 0 : scheduling,
388 0 : };
389 0 : storcon_client
390 0 : .dispatch::<_, ()>(
391 0 : Method::PUT,
392 0 : format!("control/v1/node/{node_id}/config"),
393 0 : Some(req),
394 0 : )
395 0 : .await?;
396 0 : }
397 0 : Command::Tenants {} => {
398 0 : let resp = storcon_client
399 0 : .dispatch::<(), Vec<TenantDescribeResponse>>(
400 0 : Method::GET,
401 0 : "control/v1/tenant".to_string(),
402 0 : None,
403 0 : )
404 0 : .await?;
405 0 : let mut table = comfy_table::Table::new();
406 0 : table.set_header([
407 0 : "TenantId",
408 0 : "ShardCount",
409 0 : "StripeSize",
410 0 : "Placement",
411 0 : "Scheduling",
412 0 : ]);
413 0 : for tenant in resp {
414 0 : let shard_zero = tenant.shards.into_iter().next().unwrap();
415 0 : table.add_row([
416 0 : format!("{}", tenant.tenant_id),
417 0 : format!("{}", shard_zero.tenant_shard_id.shard_count.literal()),
418 0 : format!("{:?}", tenant.stripe_size),
419 0 : format!("{:?}", tenant.policy),
420 0 : format!("{:?}", shard_zero.scheduling_policy),
421 0 : ]);
422 0 : }
423 0 :
424 0 : println!("{table}");
425 0 : }
426 0 : Command::TenantPolicy {
427 0 : tenant_id,
428 0 : placement,
429 0 : scheduling,
430 0 : } => {
431 0 : let req = TenantPolicyRequest {
432 0 : scheduling: scheduling.map(|s| s.0),
433 0 : placement: placement.map(|p| p.0),
434 0 : };
435 0 : storcon_client
436 0 : .dispatch::<_, ()>(
437 0 : Method::PUT,
438 0 : format!("control/v1/tenant/{tenant_id}/policy"),
439 0 : Some(req),
440 0 : )
441 0 : .await?;
442 0 : }
443 0 : Command::TenantShardSplit {
444 0 : tenant_id,
445 0 : shard_count,
446 0 : stripe_size,
447 0 : } => {
448 0 : let req = TenantShardSplitRequest {
449 0 : new_shard_count: shard_count,
450 0 : new_stripe_size: stripe_size.map(ShardStripeSize),
451 0 : };
452 0 :
453 0 : let response = storcon_client
454 0 : .dispatch::<TenantShardSplitRequest, TenantShardSplitResponse>(
455 0 : Method::PUT,
456 0 : format!("control/v1/tenant/{tenant_id}/shard_split"),
457 0 : Some(req),
458 0 : )
459 0 : .await?;
460 0 : println!(
461 0 : "Split tenant {} into {} shards: {}",
462 0 : tenant_id,
463 0 : shard_count,
464 0 : response
465 0 : .new_shards
466 0 : .iter()
467 0 : .map(|s| format!("{:?}", s))
468 0 : .collect::<Vec<_>>()
469 0 : .join(",")
470 0 : );
471 0 : }
472 0 : Command::TenantShardMigrate {
473 0 : tenant_shard_id,
474 0 : node,
475 0 : } => {
476 0 : let req = TenantShardMigrateRequest {
477 0 : tenant_shard_id,
478 0 : node_id: node,
479 0 : };
480 0 :
481 0 : storcon_client
482 0 : .dispatch::<TenantShardMigrateRequest, TenantShardMigrateResponse>(
483 0 : Method::PUT,
484 0 : format!("control/v1/tenant/{tenant_shard_id}/migrate"),
485 0 : Some(req),
486 0 : )
487 0 : .await?;
488 0 : }
489 0 : Command::TenantConfig { tenant_id, config } => {
490 0 : let tenant_conf = serde_json::from_str(&config)?;
491 0 :
492 0 : vps_client
493 0 : .tenant_config(&TenantConfigRequest {
494 0 : tenant_id,
495 0 : config: tenant_conf,
496 0 : })
497 0 : .await?;
498 0 : }
499 0 : Command::TenantDescribe { tenant_id } => {
500 0 : let describe_response = storcon_client
501 0 : .dispatch::<(), TenantDescribeResponse>(
502 0 : Method::GET,
503 0 : format!("control/v1/tenant/{tenant_id}"),
504 0 : None,
505 0 : )
506 0 : .await?;
507 0 : let shards = describe_response.shards;
508 0 : let mut table = comfy_table::Table::new();
509 0 : table.set_header(["Shard", "Attached", "Secondary", "Last error", "status"]);
510 0 : for shard in shards {
511 0 : let secondary = shard
512 0 : .node_secondary
513 0 : .iter()
514 0 : .map(|n| format!("{}", n))
515 0 : .collect::<Vec<_>>()
516 0 : .join(",");
517 0 :
518 0 : let mut status_parts = Vec::new();
519 0 : if shard.is_reconciling {
520 0 : status_parts.push("reconciling");
521 0 : }
522 0 :
523 0 : if shard.is_pending_compute_notification {
524 0 : status_parts.push("pending_compute");
525 0 : }
526 0 :
527 0 : if shard.is_splitting {
528 0 : status_parts.push("splitting");
529 0 : }
530 0 : let status = status_parts.join(",");
531 0 :
532 0 : table.add_row([
533 0 : format!("{}", shard.tenant_shard_id),
534 0 : shard
535 0 : .node_attached
536 0 : .map(|n| format!("{}", n))
537 0 : .unwrap_or(String::new()),
538 0 : secondary,
539 0 : shard.last_error,
540 0 : status,
541 0 : ]);
542 0 : }
543 0 : println!("{table}");
544 0 : }
545 0 : Command::TenantWarmup { tenant_id } => {
546 0 : let describe_response = storcon_client
547 0 : .dispatch::<(), TenantDescribeResponse>(
548 0 : Method::GET,
549 0 : format!("control/v1/tenant/{tenant_id}"),
550 0 : None,
551 0 : )
552 0 : .await;
553 0 : match describe_response {
554 0 : Ok(describe) => {
555 0 : if matches!(describe.policy, PlacementPolicy::Secondary) {
556 0 : // Fine: it's already known to controller in secondary mode: calling
557 0 : // again to put it into secondary mode won't cause problems.
558 0 : } else {
559 0 : anyhow::bail!("Tenant already present with policy {:?}", describe.policy);
560 0 : }
561 0 : }
562 0 : Err(mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _)) => {
563 0 : // Fine: this tenant isn't know to the storage controller yet.
564 0 : }
565 0 : Err(e) => {
566 0 : // Unexpected API error
567 0 : return Err(e.into());
568 0 : }
569 0 : }
570 0 :
571 0 : vps_client
572 0 : .location_config(
573 0 : TenantShardId::unsharded(tenant_id),
574 0 : pageserver_api::models::LocationConfig {
575 0 : mode: pageserver_api::models::LocationConfigMode::Secondary,
576 0 : generation: None,
577 0 : secondary_conf: Some(LocationConfigSecondary { warm: true }),
578 0 : shard_number: 0,
579 0 : shard_count: 0,
580 0 : shard_stripe_size: ShardParameters::DEFAULT_STRIPE_SIZE.0,
581 0 : tenant_conf: TenantConfig::default(),
582 0 : },
583 0 : None,
584 0 : true,
585 0 : )
586 0 : .await?;
587 0 :
588 0 : let describe_response = storcon_client
589 0 : .dispatch::<(), TenantDescribeResponse>(
590 0 : Method::GET,
591 0 : format!("control/v1/tenant/{tenant_id}"),
592 0 : None,
593 0 : )
594 0 : .await?;
595 0 :
596 0 : let secondary_ps_id = describe_response
597 0 : .shards
598 0 : .first()
599 0 : .unwrap()
600 0 : .node_secondary
601 0 : .first()
602 0 : .unwrap();
603 0 :
604 0 : println!("Tenant {tenant_id} warming up on pageserver {secondary_ps_id}");
605 0 : loop {
606 0 : let (status, progress) = vps_client
607 0 : .tenant_secondary_download(
608 0 : TenantShardId::unsharded(tenant_id),
609 0 : Some(Duration::from_secs(10)),
610 0 : )
611 0 : .await?;
612 0 : println!(
613 0 : "Progress: {}/{} layers, {}/{} bytes",
614 0 : progress.layers_downloaded,
615 0 : progress.layers_total,
616 0 : progress.bytes_downloaded,
617 0 : progress.bytes_total
618 0 : );
619 0 : match status {
620 0 : StatusCode::OK => {
621 0 : println!("Download complete");
622 0 : break;
623 0 : }
624 0 : StatusCode::ACCEPTED => {
625 0 : // Loop
626 0 : }
627 0 : _ => {
628 0 : anyhow::bail!("Unexpected download status: {status}");
629 0 : }
630 0 : }
631 0 : }
632 0 : }
633 0 : Command::TenantDrop { tenant_id, unclean } => {
634 0 : if !unclean {
635 0 : anyhow::bail!("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.")
636 0 : }
637 0 : storcon_client
638 0 : .dispatch::<(), ()>(
639 0 : Method::POST,
640 0 : format!("debug/v1/tenant/{tenant_id}/drop"),
641 0 : None,
642 0 : )
643 0 : .await?;
644 0 : }
645 0 : Command::NodeDrop { node_id, unclean } => {
646 0 : if !unclean {
647 0 : anyhow::bail!("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.")
648 0 : }
649 0 : storcon_client
650 0 : .dispatch::<(), ()>(Method::POST, format!("debug/v1/node/{node_id}/drop"), None)
651 0 : .await?;
652 0 : }
653 0 : Command::TenantSetTimeBasedEviction {
654 0 : tenant_id,
655 0 : period,
656 0 : threshold,
657 0 : } => {
658 0 : vps_client
659 0 : .tenant_config(&TenantConfigRequest {
660 0 : tenant_id,
661 0 : config: TenantConfig {
662 0 : eviction_policy: Some(EvictionPolicy::LayerAccessThreshold(
663 0 : EvictionPolicyLayerAccessThreshold {
664 0 : period: period.into(),
665 0 : threshold: threshold.into(),
666 0 : },
667 0 : )),
668 0 : ..Default::default()
669 0 : },
670 0 : })
671 0 : .await?;
672 0 : }
673 0 : Command::Drain {
674 0 : nodes,
675 0 : concurrency,
676 0 : max_shards,
677 0 : dry_run,
678 0 : } => {
679 0 : // Load the list of nodes, split them up into the drained and filled sets,
680 0 : // and validate that draining is possible.
681 0 : let node_descs = storcon_client
682 0 : .dispatch::<(), Vec<NodeDescribeResponse>>(
683 0 : Method::GET,
684 0 : "control/v1/node".to_string(),
685 0 : None,
686 0 : )
687 0 : .await?;
688 0 :
689 0 : let mut node_to_drain_descs = Vec::new();
690 0 : let mut node_to_fill_descs = Vec::new();
691 0 :
692 0 : for desc in node_descs {
693 0 : let to_drain = nodes.iter().any(|id| *id == desc.id);
694 0 : if to_drain {
695 0 : node_to_drain_descs.push(desc);
696 0 : } else {
697 0 : node_to_fill_descs.push(desc);
698 0 : }
699 0 : }
700 0 :
701 0 : if nodes.len() != node_to_drain_descs.len() {
702 0 : anyhow::bail!("Drain requested for node which doesn't exist.")
703 0 : }
704 0 :
705 0 : node_to_fill_descs.retain(|desc| {
706 0 : matches!(desc.availability, NodeAvailabilityWrapper::Active)
707 0 : && matches!(
708 0 : desc.scheduling,
709 0 : NodeSchedulingPolicy::Active | NodeSchedulingPolicy::Filling
710 0 : )
711 0 : });
712 0 :
713 0 : if node_to_fill_descs.is_empty() {
714 0 : anyhow::bail!("There are no nodes to drain to")
715 0 : }
716 0 :
717 0 : // Set the node scheduling policy to draining for the nodes which
718 0 : // we plan to drain.
719 0 : for node_desc in node_to_drain_descs.iter() {
720 0 : let req = NodeConfigureRequest {
721 0 : node_id: node_desc.id,
722 0 : availability: None,
723 0 : scheduling: Some(NodeSchedulingPolicy::Draining),
724 0 : };
725 0 :
726 0 : storcon_client
727 0 : .dispatch::<_, ()>(
728 0 : Method::PUT,
729 0 : format!("control/v1/node/{}/config", node_desc.id),
730 0 : Some(req),
731 0 : )
732 0 : .await?;
733 0 : }
734 0 :
735 0 : // Perform the drain: move each tenant shard scheduled on a node to
736 0 : // be drained to a node which is being filled. A simple round robin
737 0 : // strategy is used to pick the new node.
738 0 : let tenants = storcon_client
739 0 : .dispatch::<(), Vec<TenantDescribeResponse>>(
740 0 : Method::GET,
741 0 : "control/v1/tenant".to_string(),
742 0 : None,
743 0 : )
744 0 : .await?;
745 0 :
746 0 : let mut selected_node_idx = 0;
747 0 :
748 0 : struct DrainMove {
749 0 : tenant_shard_id: TenantShardId,
750 0 : from: NodeId,
751 0 : to: NodeId,
752 0 : }
753 0 :
754 0 : let mut moves: Vec<DrainMove> = Vec::new();
755 0 :
756 0 : let shards = tenants
757 0 : .into_iter()
758 0 : .flat_map(|tenant| tenant.shards.into_iter());
759 0 : for shard in shards {
760 0 : if let Some(max_shards) = max_shards {
761 0 : if moves.len() >= max_shards {
762 0 : println!(
763 0 : "Stop planning shard moves since the requested maximum was reached"
764 0 : );
765 0 : break;
766 0 : }
767 0 : }
768 0 :
769 0 : let should_migrate = {
770 0 : if let Some(attached_to) = shard.node_attached {
771 0 : node_to_drain_descs
772 0 : .iter()
773 0 : .map(|desc| desc.id)
774 0 : .any(|id| id == attached_to)
775 0 : } else {
776 0 : false
777 0 : }
778 0 : };
779 0 :
780 0 : if !should_migrate {
781 0 : continue;
782 0 : }
783 0 :
784 0 : moves.push(DrainMove {
785 0 : tenant_shard_id: shard.tenant_shard_id,
786 0 : from: shard
787 0 : .node_attached
788 0 : .expect("We only migrate attached tenant shards"),
789 0 : to: node_to_fill_descs[selected_node_idx].id,
790 0 : });
791 0 : selected_node_idx = (selected_node_idx + 1) % node_to_fill_descs.len();
792 0 : }
793 0 :
794 0 : let total_moves = moves.len();
795 0 :
796 0 : if dry_run == Some(true) {
797 0 : println!("Dryrun requested. Planned {total_moves} moves:");
798 0 : for mv in &moves {
799 0 : println!("{}: {} -> {}", mv.tenant_shard_id, mv.from, mv.to)
800 0 : }
801 0 :
802 0 : return Ok(());
803 0 : }
804 0 :
805 0 : const DEFAULT_MIGRATE_CONCURRENCY: usize = 8;
806 0 : let mut stream = futures::stream::iter(moves)
807 0 : .map(|mv| {
808 0 : let client = Client::new(cli.api.clone(), cli.jwt.clone());
809 0 : async move {
810 0 : client
811 0 : .dispatch::<TenantShardMigrateRequest, TenantShardMigrateResponse>(
812 0 : Method::PUT,
813 0 : format!("control/v1/tenant/{}/migrate", mv.tenant_shard_id),
814 0 : Some(TenantShardMigrateRequest {
815 0 : tenant_shard_id: mv.tenant_shard_id,
816 0 : node_id: mv.to,
817 0 : }),
818 0 : )
819 0 : .await
820 0 : .map_err(|e| (mv.tenant_shard_id, mv.from, mv.to, e))
821 0 : }
822 0 : })
823 0 : .buffered(concurrency.unwrap_or(DEFAULT_MIGRATE_CONCURRENCY));
824 0 :
825 0 : let mut success = 0;
826 0 : let mut failure = 0;
827 0 :
828 0 : while let Some(res) = stream.next().await {
829 0 : match res {
830 0 : Ok(_) => {
831 0 : success += 1;
832 0 : }
833 0 : Err((tenant_shard_id, from, to, error)) => {
834 0 : failure += 1;
835 0 : println!(
836 0 : "Failed to migrate {} from node {} to node {}: {}",
837 0 : tenant_shard_id, from, to, error
838 0 : );
839 0 : }
840 0 : }
841 0 :
842 0 : if (success + failure) % 20 == 0 {
843 0 : println!(
844 0 : "Processed {}/{} shards: {} succeeded, {} failed",
845 0 : success + failure,
846 0 : total_moves,
847 0 : success,
848 0 : failure
849 0 : );
850 0 : }
851 0 : }
852 0 :
853 0 : println!(
854 0 : "Processed {}/{} shards: {} succeeded, {} failed",
855 0 : success + failure,
856 0 : total_moves,
857 0 : success,
858 0 : failure
859 0 : );
860 0 : }
861 0 : }
862 0 :
863 0 : Ok(())
864 0 : }
|