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

Generated by: LCOV version 2.1-beta