LCOV - code coverage report
Current view: top level - control_plane/storcon_cli/src - main.rs (source / functions) Coverage Total Hit
Test: 2a9d99866121f170b43760bd62e1e2431e597707.info Lines: 0.0 % 725 0
Test Date: 2024-09-02 14:10:37 Functions: 0.0 % 114 0

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

Generated by: LCOV version 2.1-beta