LCOV - code coverage report
Current view: top level - control_plane/storcon_cli/src - main.rs (source / functions) Coverage Total Hit
Test: 45c9170b95180e9ecfad9a53e031030abf2a178c.info Lines: 0.0 % 1009 0
Test Date: 2025-02-21 15:51:08 Functions: 0.0 % 124 0

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

Generated by: LCOV version 2.1-beta