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,
8 : TenantDescribeResponse, TenantPolicyRequest,
9 : },
10 : models::{
11 : EvictionPolicy, EvictionPolicyLayerAccessThreshold, LocationConfigSecondary,
12 : ShardParameters, TenantConfig, TenantConfigRequest, TenantCreateRequest,
13 : TenantShardSplitRequest, 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 : vps_client
340 0 : .tenant_create(&TenantCreateRequest {
341 0 : new_tenant_id: TenantShardId::unsharded(tenant_id),
342 0 : generation: None,
343 0 : shard_parameters: ShardParameters::default(),
344 0 : placement_policy: Some(PlacementPolicy::Attached(1)),
345 0 : config: TenantConfig::default(),
346 0 : })
347 0 : .await?;
348 0 : }
349 0 : Command::TenantDelete { tenant_id } => {
350 0 : let status = vps_client
351 0 : .tenant_delete(TenantShardId::unsharded(tenant_id))
352 0 : .await?;
353 0 : tracing::info!("Delete status: {}", status);
354 0 : }
355 0 : Command::Nodes {} => {
356 0 : let resp = storcon_client
357 0 : .dispatch::<(), Vec<NodeDescribeResponse>>(
358 0 : Method::GET,
359 0 : "control/v1/node".to_string(),
360 0 : None,
361 0 : )
362 0 : .await?;
363 0 : let mut table = comfy_table::Table::new();
364 0 : table.set_header(["Id", "Hostname", "Scheduling", "Availability"]);
365 0 : for node in resp {
366 0 : table.add_row([
367 0 : format!("{}", node.id),
368 0 : node.listen_http_addr,
369 0 : format!("{:?}", node.scheduling),
370 0 : format!("{:?}", node.availability),
371 0 : ]);
372 0 : }
373 0 : println!("{table}");
374 0 : }
375 0 : Command::NodeConfigure {
376 0 : node_id,
377 0 : availability,
378 0 : scheduling,
379 0 : } => {
380 0 : let req = NodeConfigureRequest {
381 0 : node_id,
382 0 : availability: availability.map(|a| a.0),
383 0 : scheduling,
384 0 : };
385 0 : storcon_client
386 0 : .dispatch::<_, ()>(
387 0 : Method::PUT,
388 0 : format!("control/v1/node/{node_id}/config"),
389 0 : Some(req),
390 0 : )
391 0 : .await?;
392 0 : }
393 0 : Command::Tenants {} => {
394 0 : let resp = storcon_client
395 0 : .dispatch::<(), Vec<TenantDescribeResponse>>(
396 0 : Method::GET,
397 0 : "control/v1/tenant".to_string(),
398 0 : None,
399 0 : )
400 0 : .await?;
401 0 : let mut table = comfy_table::Table::new();
402 0 : table.set_header([
403 0 : "TenantId",
404 0 : "ShardCount",
405 0 : "StripeSize",
406 0 : "Placement",
407 0 : "Scheduling",
408 0 : ]);
409 0 : for tenant in resp {
410 0 : let shard_zero = tenant.shards.into_iter().next().unwrap();
411 0 : table.add_row([
412 0 : format!("{}", tenant.tenant_id),
413 0 : format!("{}", shard_zero.tenant_shard_id.shard_count.literal()),
414 0 : format!("{:?}", tenant.stripe_size),
415 0 : format!("{:?}", tenant.policy),
416 0 : format!("{:?}", shard_zero.scheduling_policy),
417 0 : ]);
418 0 : }
419 0 :
420 0 : println!("{table}");
421 0 : }
422 0 : Command::TenantPolicy {
423 0 : tenant_id,
424 0 : placement,
425 0 : scheduling,
426 0 : } => {
427 0 : let req = TenantPolicyRequest {
428 0 : scheduling: scheduling.map(|s| s.0),
429 0 : placement: placement.map(|p| p.0),
430 0 : };
431 0 : storcon_client
432 0 : .dispatch::<_, ()>(
433 0 : Method::PUT,
434 0 : format!("control/v1/tenant/{tenant_id}/policy"),
435 0 : Some(req),
436 0 : )
437 0 : .await?;
438 0 : }
439 0 : Command::TenantShardSplit {
440 0 : tenant_id,
441 0 : shard_count,
442 0 : stripe_size,
443 0 : } => {
444 0 : let req = TenantShardSplitRequest {
445 0 : new_shard_count: shard_count,
446 0 : new_stripe_size: stripe_size.map(ShardStripeSize),
447 0 : };
448 0 :
449 0 : let response = storcon_client
450 0 : .dispatch::<TenantShardSplitRequest, TenantShardSplitResponse>(
451 0 : Method::PUT,
452 0 : format!("control/v1/tenant/{tenant_id}/shard_split"),
453 0 : Some(req),
454 0 : )
455 0 : .await?;
456 0 : println!(
457 0 : "Split tenant {} into {} shards: {}",
458 0 : tenant_id,
459 0 : shard_count,
460 0 : response
461 0 : .new_shards
462 0 : .iter()
463 0 : .map(|s| format!("{:?}", s))
464 0 : .collect::<Vec<_>>()
465 0 : .join(",")
466 0 : );
467 0 : }
468 0 : Command::TenantShardMigrate {
469 0 : tenant_shard_id,
470 0 : node,
471 0 : } => {
472 0 : let req = TenantShardMigrateRequest {
473 0 : tenant_shard_id,
474 0 : node_id: node,
475 0 : };
476 0 :
477 0 : storcon_client
478 0 : .dispatch::<TenantShardMigrateRequest, TenantShardMigrateResponse>(
479 0 : Method::PUT,
480 0 : format!("control/v1/tenant/{tenant_shard_id}/migrate"),
481 0 : Some(req),
482 0 : )
483 0 : .await?;
484 0 : }
485 0 : Command::TenantConfig { tenant_id, config } => {
486 0 : let tenant_conf = serde_json::from_str(&config)?;
487 0 :
488 0 : vps_client
489 0 : .tenant_config(&TenantConfigRequest {
490 0 : tenant_id,
491 0 : config: tenant_conf,
492 0 : })
493 0 : .await?;
494 0 : }
495 0 : Command::TenantDescribe { tenant_id } => {
496 0 : let describe_response = storcon_client
497 0 : .dispatch::<(), TenantDescribeResponse>(
498 0 : Method::GET,
499 0 : format!("control/v1/tenant/{tenant_id}"),
500 0 : None,
501 0 : )
502 0 : .await?;
503 0 : let shards = describe_response.shards;
504 0 : let mut table = comfy_table::Table::new();
505 0 : table.set_header(["Shard", "Attached", "Secondary", "Last error", "status"]);
506 0 : for shard in shards {
507 0 : let secondary = shard
508 0 : .node_secondary
509 0 : .iter()
510 0 : .map(|n| format!("{}", n))
511 0 : .collect::<Vec<_>>()
512 0 : .join(",");
513 0 :
514 0 : let mut status_parts = Vec::new();
515 0 : if shard.is_reconciling {
516 0 : status_parts.push("reconciling");
517 0 : }
518 0 :
519 0 : if shard.is_pending_compute_notification {
520 0 : status_parts.push("pending_compute");
521 0 : }
522 0 :
523 0 : if shard.is_splitting {
524 0 : status_parts.push("splitting");
525 0 : }
526 0 : let status = status_parts.join(",");
527 0 :
528 0 : table.add_row([
529 0 : format!("{}", shard.tenant_shard_id),
530 0 : shard
531 0 : .node_attached
532 0 : .map(|n| format!("{}", n))
533 0 : .unwrap_or(String::new()),
534 0 : secondary,
535 0 : shard.last_error,
536 0 : status,
537 0 : ]);
538 0 : }
539 0 : println!("{table}");
540 0 : }
541 0 : Command::TenantWarmup { tenant_id } => {
542 0 : let describe_response = storcon_client
543 0 : .dispatch::<(), TenantDescribeResponse>(
544 0 : Method::GET,
545 0 : format!("control/v1/tenant/{tenant_id}"),
546 0 : None,
547 0 : )
548 0 : .await;
549 0 : match describe_response {
550 0 : Ok(describe) => {
551 0 : if matches!(describe.policy, PlacementPolicy::Secondary) {
552 0 : // Fine: it's already known to controller in secondary mode: calling
553 0 : // again to put it into secondary mode won't cause problems.
554 0 : } else {
555 0 : anyhow::bail!("Tenant already present with policy {:?}", describe.policy);
556 0 : }
557 0 : }
558 0 : Err(mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _)) => {
559 0 : // Fine: this tenant isn't know to the storage controller yet.
560 0 : }
561 0 : Err(e) => {
562 0 : // Unexpected API error
563 0 : return Err(e.into());
564 0 : }
565 0 : }
566 0 :
567 0 : vps_client
568 0 : .location_config(
569 0 : TenantShardId::unsharded(tenant_id),
570 0 : pageserver_api::models::LocationConfig {
571 0 : mode: pageserver_api::models::LocationConfigMode::Secondary,
572 0 : generation: None,
573 0 : secondary_conf: Some(LocationConfigSecondary { warm: true }),
574 0 : shard_number: 0,
575 0 : shard_count: 0,
576 0 : shard_stripe_size: ShardParameters::DEFAULT_STRIPE_SIZE.0,
577 0 : tenant_conf: TenantConfig::default(),
578 0 : },
579 0 : None,
580 0 : true,
581 0 : )
582 0 : .await?;
583 0 :
584 0 : let describe_response = storcon_client
585 0 : .dispatch::<(), TenantDescribeResponse>(
586 0 : Method::GET,
587 0 : format!("control/v1/tenant/{tenant_id}"),
588 0 : None,
589 0 : )
590 0 : .await?;
591 0 :
592 0 : let secondary_ps_id = describe_response
593 0 : .shards
594 0 : .first()
595 0 : .unwrap()
596 0 : .node_secondary
597 0 : .first()
598 0 : .unwrap();
599 0 :
600 0 : println!("Tenant {tenant_id} warming up on pageserver {secondary_ps_id}");
601 0 : loop {
602 0 : let (status, progress) = vps_client
603 0 : .tenant_secondary_download(
604 0 : TenantShardId::unsharded(tenant_id),
605 0 : Some(Duration::from_secs(10)),
606 0 : )
607 0 : .await?;
608 0 : println!(
609 0 : "Progress: {}/{} layers, {}/{} bytes",
610 0 : progress.layers_downloaded,
611 0 : progress.layers_total,
612 0 : progress.bytes_downloaded,
613 0 : progress.bytes_total
614 0 : );
615 0 : match status {
616 0 : StatusCode::OK => {
617 0 : println!("Download complete");
618 0 : break;
619 0 : }
620 0 : StatusCode::ACCEPTED => {
621 0 : // Loop
622 0 : }
623 0 : _ => {
624 0 : anyhow::bail!("Unexpected download status: {status}");
625 0 : }
626 0 : }
627 0 : }
628 0 : }
629 0 : Command::TenantDrop { tenant_id, unclean } => {
630 0 : if !unclean {
631 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.")
632 0 : }
633 0 : storcon_client
634 0 : .dispatch::<(), ()>(
635 0 : Method::POST,
636 0 : format!("debug/v1/tenant/{tenant_id}/drop"),
637 0 : None,
638 0 : )
639 0 : .await?;
640 0 : }
641 0 : Command::NodeDrop { node_id, unclean } => {
642 0 : if !unclean {
643 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.")
644 0 : }
645 0 : storcon_client
646 0 : .dispatch::<(), ()>(Method::POST, format!("debug/v1/node/{node_id}/drop"), None)
647 0 : .await?;
648 0 : }
649 0 : Command::TenantSetTimeBasedEviction {
650 0 : tenant_id,
651 0 : period,
652 0 : threshold,
653 0 : } => {
654 0 : vps_client
655 0 : .tenant_config(&TenantConfigRequest {
656 0 : tenant_id,
657 0 : config: TenantConfig {
658 0 : eviction_policy: Some(EvictionPolicy::LayerAccessThreshold(
659 0 : EvictionPolicyLayerAccessThreshold {
660 0 : period: period.into(),
661 0 : threshold: threshold.into(),
662 0 : },
663 0 : )),
664 0 : ..Default::default()
665 0 : },
666 0 : })
667 0 : .await?;
668 0 : }
669 0 : Command::Drain {
670 0 : nodes,
671 0 : concurrency,
672 0 : max_shards,
673 0 : dry_run,
674 0 : } => {
675 0 : // Load the list of nodes, split them up into the drained and filled sets,
676 0 : // and validate that draining is possible.
677 0 : let node_descs = storcon_client
678 0 : .dispatch::<(), Vec<NodeDescribeResponse>>(
679 0 : Method::GET,
680 0 : "control/v1/node".to_string(),
681 0 : None,
682 0 : )
683 0 : .await?;
684 0 :
685 0 : let mut node_to_drain_descs = Vec::new();
686 0 : let mut node_to_fill_descs = Vec::new();
687 0 :
688 0 : for desc in node_descs {
689 0 : let to_drain = nodes.iter().any(|id| *id == desc.id);
690 0 : if to_drain {
691 0 : node_to_drain_descs.push(desc);
692 0 : } else {
693 0 : node_to_fill_descs.push(desc);
694 0 : }
695 0 : }
696 0 :
697 0 : if nodes.len() != node_to_drain_descs.len() {
698 0 : anyhow::bail!("Drain requested for node which doesn't exist.")
699 0 : }
700 0 :
701 0 : node_to_fill_descs.retain(|desc| {
702 0 : matches!(desc.availability, NodeAvailabilityWrapper::Active)
703 0 : && matches!(
704 0 : desc.scheduling,
705 0 : NodeSchedulingPolicy::Active | NodeSchedulingPolicy::Filling
706 0 : )
707 0 : });
708 0 :
709 0 : if node_to_fill_descs.is_empty() {
710 0 : anyhow::bail!("There are no nodes to drain to")
711 0 : }
712 0 :
713 0 : // Set the node scheduling policy to draining for the nodes which
714 0 : // we plan to drain.
715 0 : for node_desc in node_to_drain_descs.iter() {
716 0 : let req = NodeConfigureRequest {
717 0 : node_id: node_desc.id,
718 0 : availability: None,
719 0 : scheduling: Some(NodeSchedulingPolicy::Draining),
720 0 : };
721 0 :
722 0 : storcon_client
723 0 : .dispatch::<_, ()>(
724 0 : Method::PUT,
725 0 : format!("control/v1/node/{}/config", node_desc.id),
726 0 : Some(req),
727 0 : )
728 0 : .await?;
729 0 : }
730 0 :
731 0 : // Perform the drain: move each tenant shard scheduled on a node to
732 0 : // be drained to a node which is being filled. A simple round robin
733 0 : // strategy is used to pick the new node.
734 0 : let tenants = storcon_client
735 0 : .dispatch::<(), Vec<TenantDescribeResponse>>(
736 0 : Method::GET,
737 0 : "control/v1/tenant".to_string(),
738 0 : None,
739 0 : )
740 0 : .await?;
741 0 :
742 0 : let mut selected_node_idx = 0;
743 0 :
744 0 : struct DrainMove {
745 0 : tenant_shard_id: TenantShardId,
746 0 : from: NodeId,
747 0 : to: NodeId,
748 0 : }
749 0 :
750 0 : let mut moves: Vec<DrainMove> = Vec::new();
751 0 :
752 0 : let shards = tenants
753 0 : .into_iter()
754 0 : .flat_map(|tenant| tenant.shards.into_iter());
755 0 : for shard in shards {
756 0 : if let Some(max_shards) = max_shards {
757 0 : if moves.len() >= max_shards {
758 0 : println!(
759 0 : "Stop planning shard moves since the requested maximum was reached"
760 0 : );
761 0 : break;
762 0 : }
763 0 : }
764 0 :
765 0 : let should_migrate = {
766 0 : if let Some(attached_to) = shard.node_attached {
767 0 : node_to_drain_descs
768 0 : .iter()
769 0 : .map(|desc| desc.id)
770 0 : .any(|id| id == attached_to)
771 0 : } else {
772 0 : false
773 0 : }
774 0 : };
775 0 :
776 0 : if !should_migrate {
777 0 : continue;
778 0 : }
779 0 :
780 0 : moves.push(DrainMove {
781 0 : tenant_shard_id: shard.tenant_shard_id,
782 0 : from: shard
783 0 : .node_attached
784 0 : .expect("We only migrate attached tenant shards"),
785 0 : to: node_to_fill_descs[selected_node_idx].id,
786 0 : });
787 0 : selected_node_idx = (selected_node_idx + 1) % node_to_fill_descs.len();
788 0 : }
789 0 :
790 0 : let total_moves = moves.len();
791 0 :
792 0 : if dry_run == Some(true) {
793 0 : println!("Dryrun requested. Planned {total_moves} moves:");
794 0 : for mv in &moves {
795 0 : println!("{}: {} -> {}", mv.tenant_shard_id, mv.from, mv.to)
796 0 : }
797 0 :
798 0 : return Ok(());
799 0 : }
800 0 :
801 0 : const DEFAULT_MIGRATE_CONCURRENCY: usize = 8;
802 0 : let mut stream = futures::stream::iter(moves)
803 0 : .map(|mv| {
804 0 : let client = Client::new(cli.api.clone(), cli.jwt.clone());
805 0 : async move {
806 0 : client
807 0 : .dispatch::<TenantShardMigrateRequest, TenantShardMigrateResponse>(
808 0 : Method::PUT,
809 0 : format!("control/v1/tenant/{}/migrate", mv.tenant_shard_id),
810 0 : Some(TenantShardMigrateRequest {
811 0 : tenant_shard_id: mv.tenant_shard_id,
812 0 : node_id: mv.to,
813 0 : }),
814 0 : )
815 0 : .await
816 0 : .map_err(|e| (mv.tenant_shard_id, mv.from, mv.to, e))
817 0 : }
818 0 : })
819 0 : .buffered(concurrency.unwrap_or(DEFAULT_MIGRATE_CONCURRENCY));
820 0 :
821 0 : let mut success = 0;
822 0 : let mut failure = 0;
823 0 :
824 0 : while let Some(res) = stream.next().await {
825 0 : match res {
826 0 : Ok(_) => {
827 0 : success += 1;
828 0 : }
829 0 : Err((tenant_shard_id, from, to, error)) => {
830 0 : failure += 1;
831 0 : println!(
832 0 : "Failed to migrate {} from node {} to node {}: {}",
833 0 : tenant_shard_id, from, to, error
834 0 : );
835 0 : }
836 0 : }
837 0 :
838 0 : if (success + failure) % 20 == 0 {
839 0 : println!(
840 0 : "Processed {}/{} shards: {} succeeded, {} failed",
841 0 : success + failure,
842 0 : total_moves,
843 0 : success,
844 0 : failure
845 0 : );
846 0 : }
847 0 : }
848 0 :
849 0 : println!(
850 0 : "Processed {}/{} shards: {} succeeded, {} failed",
851 0 : success + failure,
852 0 : total_moves,
853 0 : success,
854 0 : failure
855 0 : );
856 0 : }
857 0 : }
858 0 :
859 0 : Ok(())
860 0 : }
|