LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: 4e30745f424539d3816b821c09fe7733c446c226.info Lines: 0.0 % 3323 0
Test Date: 2024-06-19 13:20:49 Functions: 0.0 % 264 0

            Line data    Source code
       1              : use std::{
       2              :     borrow::Cow,
       3              :     cmp::Ordering,
       4              :     collections::{BTreeMap, HashMap, HashSet},
       5              :     str::FromStr,
       6              :     sync::Arc,
       7              :     time::{Duration, Instant},
       8              : };
       9              : 
      10              : use crate::{
      11              :     background_node_operations::{
      12              :         Drain, Fill, Operation, OperationError, OperationHandler, MAX_RECONCILES_PER_OPERATION,
      13              :     },
      14              :     compute_hook::NotifyError,
      15              :     id_lock_map::{trace_exclusive_lock, trace_shared_lock, IdLockMap, WrappedWriteGuard},
      16              :     persistence::{AbortShardSplitStatus, TenantFilter},
      17              :     reconciler::{ReconcileError, ReconcileUnits},
      18              :     scheduler::{MaySchedule, ScheduleContext, ScheduleMode},
      19              :     tenant_shard::{
      20              :         MigrateAttachment, ReconcileNeeded, ReconcilerStatus, ScheduleOptimization,
      21              :         ScheduleOptimizationAction,
      22              :     },
      23              : };
      24              : use anyhow::Context;
      25              : use control_plane::storage_controller::{
      26              :     AttachHookRequest, AttachHookResponse, InspectRequest, InspectResponse,
      27              : };
      28              : use diesel::result::DatabaseErrorKind;
      29              : use futures::{stream::FuturesUnordered, StreamExt};
      30              : use itertools::Itertools;
      31              : use pageserver_api::{
      32              :     controller_api::{
      33              :         NodeAvailability, NodeRegisterRequest, NodeSchedulingPolicy, PlacementPolicy,
      34              :         ShardSchedulingPolicy, TenantCreateResponse, TenantCreateResponseShard,
      35              :         TenantDescribeResponse, TenantDescribeResponseShard, TenantLocateResponse,
      36              :         TenantPolicyRequest, TenantShardMigrateRequest, TenantShardMigrateResponse,
      37              :         UtilizationScore,
      38              :     },
      39              :     models::{SecondaryProgress, TenantConfigRequest, TopTenantShardsRequest},
      40              : };
      41              : use reqwest::StatusCode;
      42              : use tracing::{instrument, Instrument};
      43              : 
      44              : use crate::pageserver_client::PageserverClient;
      45              : use pageserver_api::{
      46              :     models::{
      47              :         self, LocationConfig, LocationConfigListResponse, LocationConfigMode,
      48              :         PageserverUtilization, ShardParameters, TenantConfig, TenantCreateRequest,
      49              :         TenantLocationConfigRequest, TenantLocationConfigResponse, TenantShardLocation,
      50              :         TenantShardSplitRequest, TenantShardSplitResponse, TenantTimeTravelRequest,
      51              :         TimelineCreateRequest, TimelineInfo,
      52              :     },
      53              :     shard::{ShardCount, ShardIdentity, ShardNumber, ShardStripeSize, TenantShardId},
      54              :     upcall_api::{
      55              :         ReAttachRequest, ReAttachResponse, ReAttachResponseTenant, ValidateRequest,
      56              :         ValidateResponse, ValidateResponseTenant,
      57              :     },
      58              : };
      59              : use pageserver_client::mgmt_api;
      60              : use tokio::sync::mpsc::error::TrySendError;
      61              : use tokio_util::sync::CancellationToken;
      62              : use utils::{
      63              :     completion::Barrier,
      64              :     failpoint_support,
      65              :     generation::Generation,
      66              :     http::error::ApiError,
      67              :     id::{NodeId, TenantId, TimelineId},
      68              :     sync::gate::Gate,
      69              : };
      70              : 
      71              : use crate::{
      72              :     compute_hook::ComputeHook,
      73              :     heartbeater::{Heartbeater, PageserverState},
      74              :     node::{AvailabilityTransition, Node},
      75              :     persistence::{split_state::SplitState, DatabaseError, Persistence, TenantShardPersistence},
      76              :     reconciler::attached_location_conf,
      77              :     scheduler::Scheduler,
      78              :     tenant_shard::{
      79              :         IntentState, ObservedState, ObservedStateLocation, ReconcileResult, ReconcileWaitError,
      80              :         ReconcilerWaiter, TenantShard,
      81              :     },
      82              : };
      83              : 
      84              : // For operations that should be quick, like attaching a new tenant
      85              : const SHORT_RECONCILE_TIMEOUT: Duration = Duration::from_secs(5);
      86              : 
      87              : // For operations that might be slow, like migrating a tenant with
      88              : // some data in it.
      89              : pub const RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
      90              : 
      91              : // If we receive a call using Secondary mode initially, it will omit generation.  We will initialize
      92              : // tenant shards into this generation, and as long as it remains in this generation, we will accept
      93              : // input generation from future requests as authoritative.
      94              : const INITIAL_GENERATION: Generation = Generation::new(0);
      95              : 
      96              : /// How long [`Service::startup_reconcile`] is allowed to take before it should give
      97              : /// up on unresponsive pageservers and proceed.
      98              : pub(crate) const STARTUP_RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
      99              : 
     100              : /// How long a node may be unresponsive to heartbeats before we declare it offline.
     101              : /// This must be long enough to cover node restarts as well as normal operations: in future
     102              : /// it should be separated into distinct timeouts for startup vs. normal operation
     103              : /// (`<https://github.com/neondatabase/neon/issues/7552>`)
     104              : pub const MAX_UNAVAILABLE_INTERVAL_DEFAULT: Duration = Duration::from_secs(300);
     105              : 
     106            0 : #[derive(Clone, strum_macros::Display)]
     107              : enum TenantOperations {
     108              :     Create,
     109              :     LocationConfig,
     110              :     ConfigSet,
     111              :     TimeTravelRemoteStorage,
     112              :     Delete,
     113              :     UpdatePolicy,
     114              :     ShardSplit,
     115              :     SecondaryDownload,
     116              :     TimelineCreate,
     117              :     TimelineDelete,
     118              : }
     119              : 
     120            0 : #[derive(Clone, strum_macros::Display)]
     121              : enum NodeOperations {
     122              :     Register,
     123              :     Configure,
     124              : }
     125              : 
     126              : pub const RECONCILER_CONCURRENCY_DEFAULT: usize = 128;
     127              : 
     128              : // Depth of the channel used to enqueue shards for reconciliation when they can't do it immediately.
     129              : // This channel is finite-size to avoid using excessive memory if we get into a state where reconciles are finishing more slowly
     130              : // than they're being pushed onto the queue.
     131              : const MAX_DELAYED_RECONCILES: usize = 10000;
     132              : 
     133              : // Top level state available to all HTTP handlers
     134              : struct ServiceState {
     135              :     tenants: BTreeMap<TenantShardId, TenantShard>,
     136              : 
     137              :     nodes: Arc<HashMap<NodeId, Node>>,
     138              : 
     139              :     scheduler: Scheduler,
     140              : 
     141              :     /// Ongoing background operation on the cluster if any is running.
     142              :     /// Note that only one such operation may run at any given time,
     143              :     /// hence the type choice.
     144              :     ongoing_operation: Option<OperationHandler>,
     145              : 
     146              :     /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
     147              :     delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
     148              : }
     149              : 
     150              : /// Transform an error from a pageserver into an error to return to callers of a storage
     151              : /// controller API.
     152            0 : fn passthrough_api_error(node: &Node, e: mgmt_api::Error) -> ApiError {
     153            0 :     match e {
     154            0 :         mgmt_api::Error::ReceiveErrorBody(str) => {
     155            0 :             // Presume errors receiving body are connectivity/availability issues
     156            0 :             ApiError::ResourceUnavailable(
     157            0 :                 format!("{node} error receiving error body: {str}").into(),
     158            0 :             )
     159              :         }
     160            0 :         mgmt_api::Error::ReceiveBody(str) => {
     161            0 :             // Presume errors receiving body are connectivity/availability issues
     162            0 :             ApiError::ResourceUnavailable(format!("{node} error receiving body: {str}").into())
     163              :         }
     164            0 :         mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, msg) => {
     165            0 :             ApiError::NotFound(anyhow::anyhow!(format!("{node}: {msg}")).into())
     166              :         }
     167            0 :         mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg) => {
     168            0 :             ApiError::ResourceUnavailable(format!("{node}: {msg}").into())
     169              :         }
     170            0 :         mgmt_api::Error::ApiError(status @ StatusCode::UNAUTHORIZED, msg)
     171            0 :         | mgmt_api::Error::ApiError(status @ StatusCode::FORBIDDEN, msg) => {
     172              :             // Auth errors talking to a pageserver are not auth errors for the caller: they are
     173              :             // internal server errors, showing that something is wrong with the pageserver or
     174              :             // storage controller's auth configuration.
     175            0 :             ApiError::InternalServerError(anyhow::anyhow!("{node} {status}: {msg}"))
     176              :         }
     177            0 :         mgmt_api::Error::ApiError(status, msg) => {
     178            0 :             // Presume general case of pageserver API errors is that we tried to do something
     179            0 :             // that can't be done right now.
     180            0 :             ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
     181              :         }
     182            0 :         mgmt_api::Error::Cancelled => ApiError::ShuttingDown,
     183              :     }
     184            0 : }
     185              : 
     186              : impl ServiceState {
     187            0 :     fn new(
     188            0 :         nodes: HashMap<NodeId, Node>,
     189            0 :         tenants: BTreeMap<TenantShardId, TenantShard>,
     190            0 :         scheduler: Scheduler,
     191            0 :         delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
     192            0 :     ) -> Self {
     193            0 :         Self {
     194            0 :             tenants,
     195            0 :             nodes: Arc::new(nodes),
     196            0 :             scheduler,
     197            0 :             ongoing_operation: None,
     198            0 :             delayed_reconcile_rx,
     199            0 :         }
     200            0 :     }
     201              : 
     202            0 :     fn parts_mut(
     203            0 :         &mut self,
     204            0 :     ) -> (
     205            0 :         &mut Arc<HashMap<NodeId, Node>>,
     206            0 :         &mut BTreeMap<TenantShardId, TenantShard>,
     207            0 :         &mut Scheduler,
     208            0 :     ) {
     209            0 :         (&mut self.nodes, &mut self.tenants, &mut self.scheduler)
     210            0 :     }
     211              : }
     212              : 
     213              : #[derive(Clone)]
     214              : pub struct Config {
     215              :     // All pageservers managed by one instance of this service must have
     216              :     // the same public key.  This JWT token will be used to authenticate
     217              :     // this service to the pageservers it manages.
     218              :     pub jwt_token: Option<String>,
     219              : 
     220              :     // This JWT token will be used to authenticate this service to the control plane.
     221              :     pub control_plane_jwt_token: Option<String>,
     222              : 
     223              :     /// Where the compute hook should send notifications of pageserver attachment locations
     224              :     /// (this URL points to the control plane in prod). If this is None, the compute hook will
     225              :     /// assume it is running in a test environment and try to update neon_local.
     226              :     pub compute_hook_url: Option<String>,
     227              : 
     228              :     /// Grace period within which a pageserver does not respond to heartbeats, but is still
     229              :     /// considered active. Once the grace period elapses, the next heartbeat failure will
     230              :     /// mark the pagseserver offline.
     231              :     pub max_unavailable_interval: Duration,
     232              : 
     233              :     /// How many Reconcilers may be spawned concurrently
     234              :     pub reconciler_concurrency: usize,
     235              : 
     236              :     /// How large must a shard grow in bytes before we split it?
     237              :     /// None disables auto-splitting.
     238              :     pub split_threshold: Option<u64>,
     239              : }
     240              : 
     241              : impl From<DatabaseError> for ApiError {
     242            0 :     fn from(err: DatabaseError) -> ApiError {
     243            0 :         match err {
     244            0 :             DatabaseError::Query(e) => ApiError::InternalServerError(e.into()),
     245              :             // FIXME: ApiError doesn't have an Unavailable variant, but ShuttingDown maps to 503.
     246              :             DatabaseError::Connection(_) | DatabaseError::ConnectionPool(_) => {
     247            0 :                 ApiError::ShuttingDown
     248              :             }
     249            0 :             DatabaseError::Logical(reason) => {
     250            0 :                 ApiError::InternalServerError(anyhow::anyhow!(reason))
     251              :             }
     252              :         }
     253            0 :     }
     254              : }
     255              : 
     256              : pub struct Service {
     257              :     inner: Arc<std::sync::RwLock<ServiceState>>,
     258              :     config: Config,
     259              :     persistence: Arc<Persistence>,
     260              :     compute_hook: Arc<ComputeHook>,
     261              :     result_tx: tokio::sync::mpsc::UnboundedSender<ReconcileResult>,
     262              : 
     263              :     heartbeater: Heartbeater,
     264              : 
     265              :     // Channel for background cleanup from failed operations that require cleanup, such as shard split
     266              :     abort_tx: tokio::sync::mpsc::UnboundedSender<TenantShardSplitAbort>,
     267              : 
     268              :     // Locking on a tenant granularity (covers all shards in the tenant):
     269              :     // - Take exclusively for rare operations that mutate the tenant's persistent state (e.g. create/delete/split)
     270              :     // - Take in shared mode for operations that need the set of shards to stay the same to complete reliably (e.g. timeline CRUD)
     271              :     tenant_op_locks: IdLockMap<TenantId, TenantOperations>,
     272              : 
     273              :     // Locking for node-mutating operations: take exclusively for operations that modify the node's persistent state, or
     274              :     // that transition it to/from Active.
     275              :     node_op_locks: IdLockMap<NodeId, NodeOperations>,
     276              : 
     277              :     // Limit how many Reconcilers we will spawn concurrently
     278              :     reconciler_concurrency: Arc<tokio::sync::Semaphore>,
     279              : 
     280              :     /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
     281              :     /// Send into this queue to promptly attempt to reconcile this shard next time units are available.
     282              :     ///
     283              :     /// Note that this state logically lives inside ServiceInner, but carrying Sender here makes the code simpler
     284              :     /// by avoiding needing a &mut ref to something inside the ServiceInner.  This could be optimized to
     285              :     /// use a VecDeque instead of a channel to reduce synchronization overhead, at the cost of some code complexity.
     286              :     delayed_reconcile_tx: tokio::sync::mpsc::Sender<TenantShardId>,
     287              : 
     288              :     // Process shutdown will fire this token
     289              :     cancel: CancellationToken,
     290              : 
     291              :     // Background tasks will hold this gate
     292              :     gate: Gate,
     293              : 
     294              :     /// This waits for initial reconciliation with pageservers to complete.  Until this barrier
     295              :     /// passes, it isn't safe to do any actions that mutate tenants.
     296              :     pub(crate) startup_complete: Barrier,
     297              : }
     298              : 
     299              : impl From<ReconcileWaitError> for ApiError {
     300            0 :     fn from(value: ReconcileWaitError) -> Self {
     301            0 :         match value {
     302            0 :             ReconcileWaitError::Shutdown => ApiError::ShuttingDown,
     303            0 :             e @ ReconcileWaitError::Timeout(_) => ApiError::Timeout(format!("{e}").into()),
     304            0 :             e @ ReconcileWaitError::Failed(..) => ApiError::InternalServerError(anyhow::anyhow!(e)),
     305              :         }
     306            0 :     }
     307              : }
     308              : 
     309              : impl From<OperationError> for ApiError {
     310            0 :     fn from(value: OperationError) -> Self {
     311            0 :         match value {
     312            0 :             OperationError::NodeStateChanged(err) | OperationError::FinalizeError(err) => {
     313            0 :                 ApiError::InternalServerError(anyhow::anyhow!(err))
     314              :             }
     315            0 :             OperationError::Cancelled => ApiError::Conflict("Operation was cancelled".into()),
     316              :         }
     317            0 :     }
     318              : }
     319              : 
     320              : #[allow(clippy::large_enum_variant)]
     321              : enum TenantCreateOrUpdate {
     322              :     Create(TenantCreateRequest),
     323              :     Update(Vec<ShardUpdate>),
     324              : }
     325              : 
     326              : struct ShardSplitParams {
     327              :     old_shard_count: ShardCount,
     328              :     new_shard_count: ShardCount,
     329              :     new_stripe_size: Option<ShardStripeSize>,
     330              :     targets: Vec<ShardSplitTarget>,
     331              :     policy: PlacementPolicy,
     332              :     config: TenantConfig,
     333              :     shard_ident: ShardIdentity,
     334              : }
     335              : 
     336              : // When preparing for a shard split, we may either choose to proceed with the split,
     337              : // or find that the work is already done and return NoOp.
     338              : enum ShardSplitAction {
     339              :     Split(ShardSplitParams),
     340              :     NoOp(TenantShardSplitResponse),
     341              : }
     342              : 
     343              : // A parent shard which will be split
     344              : struct ShardSplitTarget {
     345              :     parent_id: TenantShardId,
     346              :     node: Node,
     347              :     child_ids: Vec<TenantShardId>,
     348              : }
     349              : 
     350              : /// When we tenant shard split operation fails, we may not be able to clean up immediately, because nodes
     351              : /// might not be available.  We therefore use a queue of abort operations processed in the background.
     352              : struct TenantShardSplitAbort {
     353              :     tenant_id: TenantId,
     354              :     /// The target values from the request that failed
     355              :     new_shard_count: ShardCount,
     356              :     new_stripe_size: Option<ShardStripeSize>,
     357              :     /// Until this abort op is complete, no other operations may be done on the tenant
     358              :     _tenant_lock: WrappedWriteGuard<TenantOperations>,
     359              : }
     360              : 
     361            0 : #[derive(thiserror::Error, Debug)]
     362              : enum TenantShardSplitAbortError {
     363              :     #[error(transparent)]
     364              :     Database(#[from] DatabaseError),
     365              :     #[error(transparent)]
     366              :     Remote(#[from] mgmt_api::Error),
     367              :     #[error("Unavailable")]
     368              :     Unavailable,
     369              : }
     370              : 
     371              : struct ShardUpdate {
     372              :     tenant_shard_id: TenantShardId,
     373              :     placement_policy: PlacementPolicy,
     374              :     tenant_config: TenantConfig,
     375              : 
     376              :     /// If this is None, generation is not updated.
     377              :     generation: Option<Generation>,
     378              : }
     379              : 
     380              : impl Service {
     381            0 :     pub fn get_config(&self) -> &Config {
     382            0 :         &self.config
     383            0 :     }
     384              : 
     385              :     /// Called once on startup, this function attempts to contact all pageservers to build an up-to-date
     386              :     /// view of the world, and determine which pageservers are responsive.
     387            0 :     #[instrument(skip_all)]
     388              :     async fn startup_reconcile(
     389              :         self: &Arc<Service>,
     390              :         bg_compute_notify_result_tx: tokio::sync::mpsc::Sender<
     391              :             Result<(), (TenantShardId, NotifyError)>,
     392              :         >,
     393              :     ) {
     394              :         // For all tenant shards, a vector of observed states on nodes (where None means
     395              :         // indeterminate, same as in [`ObservedStateLocation`])
     396              :         let mut observed: HashMap<TenantShardId, Vec<(NodeId, Option<LocationConfig>)>> =
     397              :             HashMap::new();
     398              : 
     399              :         // Startup reconciliation does I/O to other services: whether they
     400              :         // are responsive or not, we should aim to finish within our deadline, because:
     401              :         // - If we don't, a k8s readiness hook watching /ready will kill us.
     402              :         // - While we're waiting for startup reconciliation, we are not fully
     403              :         //   available for end user operations like creating/deleting tenants and timelines.
     404              :         //
     405              :         // We set multiple deadlines to break up the time available between the phases of work: this is
     406              :         // arbitrary, but avoids a situation where the first phase could burn our entire timeout period.
     407              :         let start_at = Instant::now();
     408              :         let node_scan_deadline = start_at
     409              :             .checked_add(STARTUP_RECONCILE_TIMEOUT / 2)
     410              :             .expect("Reconcile timeout is a modest constant");
     411              : 
     412              :         // Accumulate a list of any tenant locations that ought to be detached
     413              :         let mut cleanup = Vec::new();
     414              : 
     415              :         let node_listings = self.scan_node_locations(node_scan_deadline).await;
     416              :         // Send initial heartbeat requests to nodes that replied to the location listing above.
     417              :         let nodes_online = self.initial_heartbeat_round(node_listings.keys()).await;
     418              : 
     419              :         for (node_id, list_response) in node_listings {
     420              :             let tenant_shards = list_response.tenant_shards;
     421              :             tracing::info!(
     422              :                 "Received {} shard statuses from pageserver {}, setting it to Active",
     423              :                 tenant_shards.len(),
     424              :                 node_id
     425              :             );
     426              : 
     427              :             for (tenant_shard_id, conf_opt) in tenant_shards {
     428              :                 let shard_observations = observed.entry(tenant_shard_id).or_default();
     429              :                 shard_observations.push((node_id, conf_opt));
     430              :             }
     431              :         }
     432              : 
     433              :         // List of tenants for which we will attempt to notify compute of their location at startup
     434              :         let mut compute_notifications = Vec::new();
     435              : 
     436              :         // Populate intent and observed states for all tenants, based on reported state on pageservers
     437              :         tracing::info!("Populating tenant shards' states from initial pageserver scan...");
     438              :         let shard_count = {
     439              :             let mut locked = self.inner.write().unwrap();
     440              :             let (nodes, tenants, scheduler) = locked.parts_mut();
     441              : 
     442              :             // Mark nodes online if they responded to us: nodes are offline by default after a restart.
     443              :             let mut new_nodes = (**nodes).clone();
     444              :             for (node_id, node) in new_nodes.iter_mut() {
     445              :                 if let Some(utilization) = nodes_online.get(node_id) {
     446              :                     node.set_availability(NodeAvailability::Active(UtilizationScore(
     447              :                         utilization.utilization_score,
     448              :                     )));
     449              :                     scheduler.node_upsert(node);
     450              :                 }
     451              :             }
     452              :             *nodes = Arc::new(new_nodes);
     453              : 
     454              :             for (tenant_shard_id, shard_observations) in observed {
     455              :                 for (node_id, observed_loc) in shard_observations {
     456              :                     let Some(tenant_shard) = tenants.get_mut(&tenant_shard_id) else {
     457              :                         cleanup.push((tenant_shard_id, node_id));
     458              :                         continue;
     459              :                     };
     460              :                     tenant_shard
     461              :                         .observed
     462              :                         .locations
     463              :                         .insert(node_id, ObservedStateLocation { conf: observed_loc });
     464              :                 }
     465              :             }
     466              : 
     467              :             // Populate each tenant's intent state
     468              :             let mut schedule_context = ScheduleContext::default();
     469              :             for (tenant_shard_id, tenant_shard) in tenants.iter_mut() {
     470              :                 if tenant_shard_id.shard_number == ShardNumber(0) {
     471              :                     // Reset scheduling context each time we advance to the next Tenant
     472              :                     schedule_context = ScheduleContext::default();
     473              :                 }
     474              : 
     475              :                 tenant_shard.intent_from_observed(scheduler);
     476              :                 if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
     477              :                     // Non-fatal error: we are unable to properly schedule the tenant, perhaps because
     478              :                     // not enough pageservers are available.  The tenant may well still be available
     479              :                     // to clients.
     480              :                     tracing::error!("Failed to schedule tenant {tenant_shard_id} at startup: {e}");
     481              :                 } else {
     482              :                     // If we're both intending and observed to be attached at a particular node, we will
     483              :                     // emit a compute notification for this. In the case where our observed state does not
     484              :                     // yet match our intent, we will eventually reconcile, and that will emit a compute notification.
     485              :                     if let Some(attached_at) = tenant_shard.stably_attached() {
     486              :                         compute_notifications.push((
     487              :                             *tenant_shard_id,
     488              :                             attached_at,
     489              :                             tenant_shard.shard.stripe_size,
     490              :                         ));
     491              :                     }
     492              :                 }
     493              :             }
     494              : 
     495              :             tenants.len()
     496              :         };
     497              : 
     498              :         // TODO: if any tenant's intent now differs from its loaded generation_pageserver, we should clear that
     499              :         // generation_pageserver in the database.
     500              : 
     501              :         // Emit compute hook notifications for all tenants which are already stably attached.  Other tenants
     502              :         // will emit compute hook notifications when they reconcile.
     503              :         //
     504              :         // Ordering: our calls to notify_background synchronously establish a relative order for these notifications vs. any later
     505              :         // calls into the ComputeHook for the same tenant: we can leave these to run to completion in the background and any later
     506              :         // calls will be correctly ordered wrt these.
     507              :         //
     508              :         // Concurrency: we call notify_background for all tenants, which will create O(N) tokio tasks, but almost all of them
     509              :         // will just wait on the ComputeHook::API_CONCURRENCY semaphore immediately, so very cheap until they get that semaphore
     510              :         // unit and start doing I/O.
     511              :         tracing::info!(
     512              :             "Sending {} compute notifications",
     513              :             compute_notifications.len()
     514              :         );
     515              :         self.compute_hook.notify_background(
     516              :             compute_notifications,
     517              :             bg_compute_notify_result_tx.clone(),
     518              :             &self.cancel,
     519              :         );
     520              : 
     521              :         // Finally, now that the service is up and running, launch reconcile operations for any tenants
     522              :         // which require it: under normal circumstances this should only include tenants that were in some
     523              :         // transient state before we restarted, or any tenants whose compute hooks failed above.
     524              :         tracing::info!("Checking for shards in need of reconciliation...");
     525              :         let reconcile_tasks = self.reconcile_all();
     526              :         // We will not wait for these reconciliation tasks to run here: we're now done with startup and
     527              :         // normal operations may proceed.
     528              : 
     529              :         // Clean up any tenants that were found on pageservers but are not known to us.  Do this in the
     530              :         // background because it does not need to complete in order to proceed with other work.
     531              :         if !cleanup.is_empty() {
     532              :             tracing::info!("Cleaning up {} locations in the background", cleanup.len());
     533              :             tokio::task::spawn({
     534              :                 let cleanup_self = self.clone();
     535            0 :                 async move { cleanup_self.cleanup_locations(cleanup).await }
     536              :             });
     537              :         }
     538              : 
     539              :         tracing::info!("Startup complete, spawned {reconcile_tasks} reconciliation tasks ({shard_count} shards total)");
     540              :     }
     541              : 
     542            0 :     async fn initial_heartbeat_round<'a>(
     543            0 :         &self,
     544            0 :         node_ids: impl Iterator<Item = &'a NodeId>,
     545            0 :     ) -> HashMap<NodeId, PageserverUtilization> {
     546            0 :         assert!(!self.startup_complete.is_ready());
     547              : 
     548            0 :         let all_nodes = {
     549            0 :             let locked = self.inner.read().unwrap();
     550            0 :             locked.nodes.clone()
     551            0 :         };
     552            0 : 
     553            0 :         let mut nodes_to_heartbeat = HashMap::new();
     554            0 :         for node_id in node_ids {
     555            0 :             match all_nodes.get(node_id) {
     556            0 :                 Some(node) => {
     557            0 :                     nodes_to_heartbeat.insert(*node_id, node.clone());
     558            0 :                 }
     559              :                 None => {
     560            0 :                     tracing::warn!("Node {node_id} was removed during start-up");
     561              :                 }
     562              :             }
     563              :         }
     564              : 
     565            0 :         tracing::info!("Sending initial heartbeats...");
     566            0 :         let res = self
     567            0 :             .heartbeater
     568            0 :             .heartbeat(Arc::new(nodes_to_heartbeat))
     569            0 :             .await;
     570              : 
     571            0 :         let mut online_nodes = HashMap::new();
     572            0 :         if let Ok(deltas) = res {
     573            0 :             for (node_id, status) in deltas.0 {
     574            0 :                 match status {
     575            0 :                     PageserverState::Available { utilization, .. } => {
     576            0 :                         online_nodes.insert(node_id, utilization);
     577            0 :                     }
     578            0 :                     PageserverState::Offline => {}
     579              :                 }
     580              :             }
     581            0 :         }
     582              : 
     583            0 :         online_nodes
     584            0 :     }
     585              : 
     586              :     /// Used during [`Self::startup_reconcile`]: issue GETs to all nodes concurrently, with a deadline.
     587              :     ///
     588              :     /// The result includes only nodes which responded within the deadline
     589            0 :     async fn scan_node_locations(
     590            0 :         &self,
     591            0 :         deadline: Instant,
     592            0 :     ) -> HashMap<NodeId, LocationConfigListResponse> {
     593            0 :         let nodes = {
     594            0 :             let locked = self.inner.read().unwrap();
     595            0 :             locked.nodes.clone()
     596            0 :         };
     597            0 : 
     598            0 :         let mut node_results = HashMap::new();
     599            0 : 
     600            0 :         let mut node_list_futs = FuturesUnordered::new();
     601            0 : 
     602            0 :         tracing::info!("Scanning shards on {} nodes...", nodes.len());
     603            0 :         for node in nodes.values() {
     604            0 :             node_list_futs.push({
     605            0 :                 async move {
     606            0 :                     tracing::info!("Scanning shards on node {node}...");
     607            0 :                     let timeout = Duration::from_secs(1);
     608            0 :                     let response = node
     609            0 :                         .with_client_retries(
     610            0 :                             |client| async move { client.list_location_config().await },
     611            0 :                             &self.config.jwt_token,
     612            0 :                             1,
     613            0 :                             5,
     614            0 :                             timeout,
     615            0 :                             &self.cancel,
     616            0 :                         )
     617            0 :                         .await;
     618            0 :                     (node.get_id(), response)
     619            0 :                 }
     620            0 :             });
     621            0 :         }
     622              : 
     623              :         loop {
     624            0 :             let (node_id, result) = tokio::select! {
     625              :                 next = node_list_futs.next() => {
     626              :                     match next {
     627              :                         Some(result) => result,
     628              :                         None =>{
     629              :                             // We got results for all our nodes
     630              :                             break;
     631              :                         }
     632              : 
     633              :                     }
     634              :                 },
     635              :                 _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
     636              :                     // Give up waiting for anyone who hasn't responded: we will yield the results that we have
     637              :                     tracing::info!("Reached deadline while waiting for nodes to respond to location listing requests");
     638              :                     break;
     639              :                 }
     640              :             };
     641              : 
     642            0 :             let Some(list_response) = result else {
     643            0 :                 tracing::info!("Shutdown during startup_reconcile");
     644            0 :                 break;
     645              :             };
     646              : 
     647            0 :             match list_response {
     648            0 :                 Err(e) => {
     649            0 :                     tracing::warn!("Could not scan node {} ({e})", node_id);
     650              :                 }
     651            0 :                 Ok(listing) => {
     652            0 :                     node_results.insert(node_id, listing);
     653            0 :                 }
     654              :             }
     655              :         }
     656              : 
     657            0 :         node_results
     658            0 :     }
     659              : 
     660              :     /// Used during [`Self::startup_reconcile`]: detach a list of unknown-to-us tenants from pageservers.
     661              :     ///
     662              :     /// This is safe to run in the background, because if we don't have this TenantShardId in our map of
     663              :     /// tenants, then it is probably something incompletely deleted before: we will not fight with any
     664              :     /// other task trying to attach it.
     665            0 :     #[instrument(skip_all)]
     666              :     async fn cleanup_locations(&self, cleanup: Vec<(TenantShardId, NodeId)>) {
     667              :         let nodes = self.inner.read().unwrap().nodes.clone();
     668              : 
     669              :         for (tenant_shard_id, node_id) in cleanup {
     670              :             // A node reported a tenant_shard_id which is unknown to us: detach it.
     671              :             let Some(node) = nodes.get(&node_id) else {
     672              :                 // This is legitimate; we run in the background and [`Self::startup_reconcile`] might have identified
     673              :                 // a location to clean up on a node that has since been removed.
     674              :                 tracing::info!(
     675              :                     "Not cleaning up location {node_id}/{tenant_shard_id}: node not found"
     676              :                 );
     677              :                 continue;
     678              :             };
     679              : 
     680              :             if self.cancel.is_cancelled() {
     681              :                 break;
     682              :             }
     683              : 
     684              :             let client = PageserverClient::new(
     685              :                 node.get_id(),
     686              :                 node.base_url(),
     687              :                 self.config.jwt_token.as_deref(),
     688              :             );
     689              :             match client
     690              :                 .location_config(
     691              :                     tenant_shard_id,
     692              :                     LocationConfig {
     693              :                         mode: LocationConfigMode::Detached,
     694              :                         generation: None,
     695              :                         secondary_conf: None,
     696              :                         shard_number: tenant_shard_id.shard_number.0,
     697              :                         shard_count: tenant_shard_id.shard_count.literal(),
     698              :                         shard_stripe_size: 0,
     699              :                         tenant_conf: models::TenantConfig::default(),
     700              :                     },
     701              :                     None,
     702              :                     false,
     703              :                 )
     704              :                 .await
     705              :             {
     706              :                 Ok(()) => {
     707              :                     tracing::info!(
     708              :                         "Detached unknown shard {tenant_shard_id} on pageserver {node_id}"
     709              :                     );
     710              :                 }
     711              :                 Err(e) => {
     712              :                     // Non-fatal error: leaving a tenant shard behind that we are not managing shouldn't
     713              :                     // break anything.
     714              :                     tracing::error!(
     715              :                         "Failed to detach unknkown shard {tenant_shard_id} on pageserver {node_id}: {e}"
     716              :                     );
     717              :                 }
     718              :             }
     719              :         }
     720              :     }
     721              : 
     722              :     /// Long running background task that periodically wakes up and looks for shards that need
     723              :     /// reconciliation.  Reconciliation is fallible, so any reconciliation tasks that fail during
     724              :     /// e.g. a tenant create/attach/migrate must eventually be retried: this task is responsible
     725              :     /// for those retries.
     726            0 :     #[instrument(skip_all)]
     727              :     async fn background_reconcile(self: &Arc<Self>) {
     728              :         self.startup_complete.clone().wait().await;
     729              : 
     730              :         const BACKGROUND_RECONCILE_PERIOD: Duration = Duration::from_secs(20);
     731              : 
     732              :         let mut interval = tokio::time::interval(BACKGROUND_RECONCILE_PERIOD);
     733              :         while !self.cancel.is_cancelled() {
     734              :             tokio::select! {
     735              :               _ = interval.tick() => {
     736              :                 let reconciles_spawned = self.reconcile_all();
     737              :                 if reconciles_spawned == 0 {
     738              :                     // Run optimizer only when we didn't find any other work to do
     739              :                     let optimizations = self.optimize_all().await;
     740              :                     if optimizations == 0 {
     741              :                         // Run new splits only when no optimizations are pending
     742              :                         self.autosplit_tenants().await;
     743              :                     }
     744              :                 }
     745              :             }
     746              :               _ = self.cancel.cancelled() => return
     747              :             }
     748              :         }
     749              :     }
     750            0 :     #[instrument(skip_all)]
     751              :     async fn spawn_heartbeat_driver(&self) {
     752              :         self.startup_complete.clone().wait().await;
     753              : 
     754              :         const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
     755              : 
     756              :         let mut interval = tokio::time::interval(HEARTBEAT_INTERVAL);
     757              :         while !self.cancel.is_cancelled() {
     758              :             tokio::select! {
     759              :               _ = interval.tick() => { }
     760              :               _ = self.cancel.cancelled() => return
     761              :             };
     762              : 
     763              :             let nodes = {
     764              :                 let locked = self.inner.read().unwrap();
     765              :                 locked.nodes.clone()
     766              :             };
     767              : 
     768              :             let res = self.heartbeater.heartbeat(nodes).await;
     769              :             if let Ok(deltas) = res {
     770              :                 for (node_id, state) in deltas.0 {
     771              :                     let (new_node, new_availability) = match state {
     772              :                         PageserverState::Available {
     773              :                             utilization, new, ..
     774              :                         } => (
     775              :                             new,
     776              :                             NodeAvailability::Active(UtilizationScore(
     777              :                                 utilization.utilization_score,
     778              :                             )),
     779              :                         ),
     780              :                         PageserverState::Offline => (false, NodeAvailability::Offline),
     781              :                     };
     782              : 
     783              :                     if new_node {
     784              :                         // When the heartbeats detect a newly added node, we don't wish
     785              :                         // to attempt to reconcile the shards assigned to it. The node
     786              :                         // is likely handling it's re-attach response, so reconciling now
     787              :                         // would be counterproductive.
     788              :                         //
     789              :                         // Instead, update the in-memory state with the details learned about the
     790              :                         // node.
     791              :                         let mut locked = self.inner.write().unwrap();
     792              :                         let (nodes, _tenants, scheduler) = locked.parts_mut();
     793              : 
     794              :                         let mut new_nodes = (**nodes).clone();
     795              : 
     796              :                         if let Some(node) = new_nodes.get_mut(&node_id) {
     797              :                             node.set_availability(new_availability);
     798              :                             scheduler.node_upsert(node);
     799              :                         }
     800              : 
     801              :                         locked.nodes = Arc::new(new_nodes);
     802              :                     } else {
     803              :                         // This is the code path for geniune availability transitions (i.e node
     804              :                         // goes unavailable and/or comes back online).
     805              :                         let res = self
     806              :                             .node_configure(node_id, Some(new_availability), None)
     807              :                             .await;
     808              : 
     809              :                         match res {
     810              :                             Ok(()) => {}
     811              :                             Err(ApiError::NotFound(_)) => {
     812              :                                 // This should be rare, but legitimate since the heartbeats are done
     813              :                                 // on a snapshot of the nodes.
     814              :                                 tracing::info!(
     815              :                                     "Node {} was not found after heartbeat round",
     816              :                                     node_id
     817              :                                 );
     818              :                             }
     819              :                             Err(err) => {
     820              :                                 tracing::error!(
     821              :                                     "Failed to update node {} after heartbeat round: {}",
     822              :                                     node_id,
     823              :                                     err
     824              :                                 );
     825              :                             }
     826              :                         }
     827              :                     }
     828              :                 }
     829              :             }
     830              :         }
     831              :     }
     832              : 
     833              :     /// Apply the contents of a [`ReconcileResult`] to our in-memory state: if the reconciliation
     834              :     /// was successful and intent hasn't changed since the Reconciler was spawned, this will update
     835              :     /// the observed state of the tenant such that subsequent calls to [`TenantShard::get_reconcile_needed`]
     836              :     /// will indicate that reconciliation is not needed.
     837            0 :     #[instrument(skip_all, fields(
     838              :         tenant_id=%result.tenant_shard_id.tenant_id, shard_id=%result.tenant_shard_id.shard_slug(),
     839              :         sequence=%result.sequence
     840            0 :     ))]
     841              :     fn process_result(&self, result: ReconcileResult) {
     842              :         let mut locked = self.inner.write().unwrap();
     843              :         let Some(tenant) = locked.tenants.get_mut(&result.tenant_shard_id) else {
     844              :             // A reconciliation result might race with removing a tenant: drop results for
     845              :             // tenants that aren't in our map.
     846              :             return;
     847              :         };
     848              : 
     849              :         // Usually generation should only be updated via this path, so the max() isn't
     850              :         // needed, but it is used to handle out-of-band updates via. e.g. test hook.
     851              :         tenant.generation = std::cmp::max(tenant.generation, result.generation);
     852              : 
     853              :         // If the reconciler signals that it failed to notify compute, set this state on
     854              :         // the shard so that a future [`TenantShard::maybe_reconcile`] will try again.
     855              :         tenant.pending_compute_notification = result.pending_compute_notification;
     856              : 
     857              :         // Let the TenantShard know it is idle.
     858              :         tenant.reconcile_complete(result.sequence);
     859              : 
     860              :         match result.result {
     861              :             Ok(()) => {
     862              :                 for (node_id, loc) in &result.observed.locations {
     863              :                     if let Some(conf) = &loc.conf {
     864              :                         tracing::info!("Updating observed location {}: {:?}", node_id, conf);
     865              :                     } else {
     866              :                         tracing::info!("Setting observed location {} to None", node_id,)
     867              :                     }
     868              :                 }
     869              :                 tenant.observed = result.observed;
     870              :                 tenant.waiter.advance(result.sequence);
     871              :             }
     872              :             Err(e) => {
     873              :                 match e {
     874              :                     ReconcileError::Cancel => {
     875              :                         tracing::info!("Reconciler was cancelled");
     876              :                     }
     877              :                     ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
     878              :                         // This might be due to the reconciler getting cancelled, or it might
     879              :                         // be due to the `Node` being marked offline.
     880              :                         tracing::info!("Reconciler cancelled during pageserver API call");
     881              :                     }
     882              :                     _ => {
     883              :                         tracing::warn!("Reconcile error: {}", e);
     884              :                     }
     885              :                 }
     886              : 
     887              :                 // Ordering: populate last_error before advancing error_seq,
     888              :                 // so that waiters will see the correct error after waiting.
     889              :                 tenant.set_last_error(result.sequence, e);
     890              : 
     891              :                 for (node_id, o) in result.observed.locations {
     892              :                     tenant.observed.locations.insert(node_id, o);
     893              :                 }
     894              :             }
     895              :         }
     896              : 
     897              :         // Maybe some other work can proceed now that this job finished.
     898              :         if self.reconciler_concurrency.available_permits() > 0 {
     899              :             while let Ok(tenant_shard_id) = locked.delayed_reconcile_rx.try_recv() {
     900              :                 let (nodes, tenants, _scheduler) = locked.parts_mut();
     901              :                 if let Some(shard) = tenants.get_mut(&tenant_shard_id) {
     902              :                     shard.delayed_reconcile = false;
     903              :                     self.maybe_reconcile_shard(shard, nodes);
     904              :                 }
     905              : 
     906              :                 if self.reconciler_concurrency.available_permits() == 0 {
     907              :                     break;
     908              :                 }
     909              :             }
     910              :         }
     911              :     }
     912              : 
     913            0 :     async fn process_results(
     914            0 :         &self,
     915            0 :         mut result_rx: tokio::sync::mpsc::UnboundedReceiver<ReconcileResult>,
     916            0 :         mut bg_compute_hook_result_rx: tokio::sync::mpsc::Receiver<
     917            0 :             Result<(), (TenantShardId, NotifyError)>,
     918            0 :         >,
     919            0 :     ) {
     920            0 :         loop {
     921            0 :             // Wait for the next result, or for cancellation
     922            0 :             tokio::select! {
     923              :                 r = result_rx.recv() => {
     924              :                     match r {
     925              :                         Some(result) => {self.process_result(result);},
     926              :                         None => {break;}
     927              :                     }
     928              :                 }
     929            0 :                 _ = async{
     930            0 :                     match bg_compute_hook_result_rx.recv().await {
     931            0 :                         Some(result) => {
     932            0 :                             if let Err((tenant_shard_id, notify_error)) = result {
     933            0 :                                 tracing::warn!("Marking shard {tenant_shard_id} for notification retry, due to error {notify_error}");
     934            0 :                                 let mut locked = self.inner.write().unwrap();
     935            0 :                                 if let Some(shard) = locked.tenants.get_mut(&tenant_shard_id) {
     936            0 :                                     shard.pending_compute_notification = true;
     937            0 :                                 }
     938              : 
     939            0 :                             }
     940              :                         },
     941              :                         None => {
     942              :                             // This channel is dead, but we don't want to terminate the outer loop{}: just wait for shutdown
     943            0 :                             self.cancel.cancelled().await;
     944              :                         }
     945              :                     }
     946            0 :                 } => {},
     947              :                 _ = self.cancel.cancelled() => {
     948              :                     break;
     949              :                 }
     950            0 :             };
     951            0 :         }
     952              : 
     953              :         // We should only fall through on shutdown
     954            0 :         assert!(self.cancel.is_cancelled());
     955            0 :     }
     956              : 
     957            0 :     async fn process_aborts(
     958            0 :         &self,
     959            0 :         mut abort_rx: tokio::sync::mpsc::UnboundedReceiver<TenantShardSplitAbort>,
     960            0 :     ) {
     961              :         loop {
     962              :             // Wait for the next result, or for cancellation
     963            0 :             let op = tokio::select! {
     964              :                 r = abort_rx.recv() => {
     965              :                     match r {
     966              :                         Some(op) => {op},
     967              :                         None => {break;}
     968              :                     }
     969              :                 }
     970              :                 _ = self.cancel.cancelled() => {
     971              :                     break;
     972              :                 }
     973              :             };
     974              : 
     975              :             // Retry until shutdown: we must keep this request object alive until it is properly
     976              :             // processed, as it holds a lock guard that prevents other operations trying to do things
     977              :             // to the tenant while it is in a weird part-split state.
     978            0 :             while !self.cancel.is_cancelled() {
     979            0 :                 match self.abort_tenant_shard_split(&op).await {
     980            0 :                     Ok(_) => break,
     981            0 :                     Err(e) => {
     982            0 :                         tracing::warn!(
     983            0 :                             "Failed to abort shard split on {}, will retry: {e}",
     984              :                             op.tenant_id
     985              :                         );
     986              : 
     987              :                         // If a node is unavailable, we hope that it has been properly marked Offline
     988              :                         // when we retry, so that the abort op will succeed.  If the abort op is failing
     989              :                         // for some other reason, we will keep retrying forever, or until a human notices
     990              :                         // and does something about it (either fixing a pageserver or restarting the controller).
     991            0 :                         tokio::time::timeout(Duration::from_secs(5), self.cancel.cancelled())
     992            0 :                             .await
     993            0 :                             .ok();
     994              :                     }
     995              :                 }
     996              :             }
     997              :         }
     998            0 :     }
     999              : 
    1000            0 :     pub async fn spawn(config: Config, persistence: Arc<Persistence>) -> anyhow::Result<Arc<Self>> {
    1001            0 :         let (result_tx, result_rx) = tokio::sync::mpsc::unbounded_channel();
    1002            0 :         let (abort_tx, abort_rx) = tokio::sync::mpsc::unbounded_channel();
    1003            0 : 
    1004            0 :         tracing::info!("Loading nodes from database...");
    1005            0 :         let nodes = persistence
    1006            0 :             .list_nodes()
    1007            0 :             .await?
    1008            0 :             .into_iter()
    1009            0 :             .map(Node::from_persistent)
    1010            0 :             .collect::<Vec<_>>();
    1011            0 :         let nodes: HashMap<NodeId, Node> = nodes.into_iter().map(|n| (n.get_id(), n)).collect();
    1012            0 :         tracing::info!("Loaded {} nodes from database.", nodes.len());
    1013              : 
    1014            0 :         tracing::info!("Loading shards from database...");
    1015            0 :         let mut tenant_shard_persistence = persistence.list_tenant_shards().await?;
    1016            0 :         tracing::info!(
    1017            0 :             "Loaded {} shards from database.",
    1018            0 :             tenant_shard_persistence.len()
    1019              :         );
    1020              : 
    1021              :         // If any shard splits were in progress, reset the database state to abort them
    1022            0 :         let mut tenant_shard_count_min_max: HashMap<TenantId, (ShardCount, ShardCount)> =
    1023            0 :             HashMap::new();
    1024            0 :         for tsp in &mut tenant_shard_persistence {
    1025            0 :             let shard = tsp.get_shard_identity()?;
    1026            0 :             let tenant_shard_id = tsp.get_tenant_shard_id()?;
    1027            0 :             let entry = tenant_shard_count_min_max
    1028            0 :                 .entry(tenant_shard_id.tenant_id)
    1029            0 :                 .or_insert_with(|| (shard.count, shard.count));
    1030            0 :             entry.0 = std::cmp::min(entry.0, shard.count);
    1031            0 :             entry.1 = std::cmp::max(entry.1, shard.count);
    1032              :         }
    1033              : 
    1034            0 :         for (tenant_id, (count_min, count_max)) in tenant_shard_count_min_max {
    1035            0 :             if count_min != count_max {
    1036              :                 // Aborting the split in the database and dropping the child shards is sufficient: the reconciliation in
    1037              :                 // [`Self::startup_reconcile`] will implicitly drop the child shards on remote pageservers, or they'll
    1038              :                 // be dropped later in [`Self::node_activate_reconcile`] if it isn't available right now.
    1039            0 :                 tracing::info!("Aborting shard split {tenant_id} {count_min:?} -> {count_max:?}");
    1040            0 :                 let abort_status = persistence.abort_shard_split(tenant_id, count_max).await?;
    1041              : 
    1042              :                 // We may never see the Complete status here: if the split was complete, we wouldn't have
    1043              :                 // identified this tenant has having mismatching min/max counts.
    1044            0 :                 assert!(matches!(abort_status, AbortShardSplitStatus::Aborted));
    1045              : 
    1046              :                 // Clear the splitting status in-memory, to reflect that we just aborted in the database
    1047            0 :                 tenant_shard_persistence.iter_mut().for_each(|tsp| {
    1048            0 :                     // Set idle split state on those shards that we will retain.
    1049            0 :                     let tsp_tenant_id = TenantId::from_str(tsp.tenant_id.as_str()).unwrap();
    1050            0 :                     if tsp_tenant_id == tenant_id
    1051            0 :                         && tsp.get_shard_identity().unwrap().count == count_min
    1052            0 :                     {
    1053            0 :                         tsp.splitting = SplitState::Idle;
    1054            0 :                     } else if tsp_tenant_id == tenant_id {
    1055              :                         // Leave the splitting state on the child shards: this will be used next to
    1056              :                         // drop them.
    1057            0 :                         tracing::info!(
    1058            0 :                             "Shard {tsp_tenant_id} will be dropped after shard split abort",
    1059              :                         );
    1060            0 :                     }
    1061            0 :                 });
    1062            0 : 
    1063            0 :                 // Drop shards for this tenant which we didn't just mark idle (i.e. child shards of the aborted split)
    1064            0 :                 tenant_shard_persistence.retain(|tsp| {
    1065            0 :                     TenantId::from_str(tsp.tenant_id.as_str()).unwrap() != tenant_id
    1066            0 :                         || tsp.splitting == SplitState::Idle
    1067            0 :                 });
    1068            0 :             }
    1069              :         }
    1070              : 
    1071            0 :         let mut tenants = BTreeMap::new();
    1072            0 : 
    1073            0 :         let mut scheduler = Scheduler::new(nodes.values());
    1074            0 : 
    1075            0 :         #[cfg(feature = "testing")]
    1076            0 :         {
    1077            0 :             // Hack: insert scheduler state for all nodes referenced by shards, as compatibility
    1078            0 :             // tests only store the shards, not the nodes.  The nodes will be loaded shortly
    1079            0 :             // after when pageservers start up and register.
    1080            0 :             let mut node_ids = HashSet::new();
    1081            0 :             for tsp in &tenant_shard_persistence {
    1082            0 :                 if let Some(node_id) = tsp.generation_pageserver {
    1083            0 :                     node_ids.insert(node_id);
    1084            0 :                 }
    1085              :             }
    1086            0 :             for node_id in node_ids {
    1087            0 :                 tracing::info!("Creating node {} in scheduler for tests", node_id);
    1088            0 :                 let node = Node::new(
    1089            0 :                     NodeId(node_id as u64),
    1090            0 :                     "".to_string(),
    1091            0 :                     123,
    1092            0 :                     "".to_string(),
    1093            0 :                     123,
    1094            0 :                 );
    1095            0 : 
    1096            0 :                 scheduler.node_upsert(&node);
    1097              :             }
    1098              :         }
    1099            0 :         for tsp in tenant_shard_persistence {
    1100            0 :             let tenant_shard_id = tsp.get_tenant_shard_id()?;
    1101              : 
    1102              :             // We will populate intent properly later in [`Self::startup_reconcile`], initially populate
    1103              :             // it with what we can infer: the node for which a generation was most recently issued.
    1104            0 :             let mut intent = IntentState::new();
    1105            0 :             if let Some(generation_pageserver) = tsp.generation_pageserver {
    1106            0 :                 intent.set_attached(&mut scheduler, Some(NodeId(generation_pageserver as u64)));
    1107            0 :             }
    1108            0 :             let new_tenant = TenantShard::from_persistent(tsp, intent)?;
    1109              : 
    1110            0 :             tenants.insert(tenant_shard_id, new_tenant);
    1111              :         }
    1112              : 
    1113            0 :         let (startup_completion, startup_complete) = utils::completion::channel();
    1114            0 : 
    1115            0 :         // This channel is continuously consumed by process_results, so doesn't need to be very large.
    1116            0 :         let (bg_compute_notify_result_tx, bg_compute_notify_result_rx) =
    1117            0 :             tokio::sync::mpsc::channel(512);
    1118            0 : 
    1119            0 :         let (delayed_reconcile_tx, delayed_reconcile_rx) =
    1120            0 :             tokio::sync::mpsc::channel(MAX_DELAYED_RECONCILES);
    1121            0 : 
    1122            0 :         let cancel = CancellationToken::new();
    1123            0 :         let heartbeater = Heartbeater::new(
    1124            0 :             config.jwt_token.clone(),
    1125            0 :             config.max_unavailable_interval,
    1126            0 :             cancel.clone(),
    1127            0 :         );
    1128            0 :         let this = Arc::new(Self {
    1129            0 :             inner: Arc::new(std::sync::RwLock::new(ServiceState::new(
    1130            0 :                 nodes,
    1131            0 :                 tenants,
    1132            0 :                 scheduler,
    1133            0 :                 delayed_reconcile_rx,
    1134            0 :             ))),
    1135            0 :             config: config.clone(),
    1136            0 :             persistence,
    1137            0 :             compute_hook: Arc::new(ComputeHook::new(config.clone())),
    1138            0 :             result_tx,
    1139            0 :             heartbeater,
    1140            0 :             reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
    1141            0 :                 config.reconciler_concurrency,
    1142            0 :             )),
    1143            0 :             delayed_reconcile_tx,
    1144            0 :             abort_tx,
    1145            0 :             startup_complete: startup_complete.clone(),
    1146            0 :             cancel,
    1147            0 :             gate: Gate::default(),
    1148            0 :             tenant_op_locks: Default::default(),
    1149            0 :             node_op_locks: Default::default(),
    1150            0 :         });
    1151            0 : 
    1152            0 :         let result_task_this = this.clone();
    1153            0 :         tokio::task::spawn(async move {
    1154              :             // Block shutdown until we're done (we must respect self.cancel)
    1155            0 :             if let Ok(_gate) = result_task_this.gate.enter() {
    1156            0 :                 result_task_this
    1157            0 :                     .process_results(result_rx, bg_compute_notify_result_rx)
    1158            0 :                     .await
    1159            0 :             }
    1160            0 :         });
    1161            0 : 
    1162            0 :         tokio::task::spawn({
    1163            0 :             let this = this.clone();
    1164            0 :             async move {
    1165              :                 // Block shutdown until we're done (we must respect self.cancel)
    1166            0 :                 if let Ok(_gate) = this.gate.enter() {
    1167            0 :                     this.process_aborts(abort_rx).await
    1168            0 :                 }
    1169            0 :             }
    1170            0 :         });
    1171            0 : 
    1172            0 :         tokio::task::spawn({
    1173            0 :             let this = this.clone();
    1174            0 :             async move {
    1175            0 :                 if let Ok(_gate) = this.gate.enter() {
    1176            0 :                     loop {
    1177            0 :                         tokio::select! {
    1178              :                             _ = this.cancel.cancelled() => {
    1179              :                                 break;
    1180              :                             },
    1181              :                             _ = tokio::time::sleep(Duration::from_secs(60)) => {}
    1182            0 :                         };
    1183            0 :                         this.tenant_op_locks.housekeeping();
    1184            0 :                     }
    1185            0 :                 }
    1186            0 :             }
    1187            0 :         });
    1188            0 : 
    1189            0 :         tokio::task::spawn({
    1190            0 :             let this = this.clone();
    1191            0 :             // We will block the [`Service::startup_complete`] barrier until [`Self::startup_reconcile`]
    1192            0 :             // is done.
    1193            0 :             let startup_completion = startup_completion.clone();
    1194            0 :             async move {
    1195              :                 // Block shutdown until we're done (we must respect self.cancel)
    1196            0 :                 let Ok(_gate) = this.gate.enter() else {
    1197            0 :                     return;
    1198              :                 };
    1199              : 
    1200            0 :                 this.startup_reconcile(bg_compute_notify_result_tx).await;
    1201            0 :                 drop(startup_completion);
    1202            0 :             }
    1203            0 :         });
    1204            0 : 
    1205            0 :         tokio::task::spawn({
    1206            0 :             let this = this.clone();
    1207            0 :             let startup_complete = startup_complete.clone();
    1208            0 :             async move {
    1209            0 :                 startup_complete.wait().await;
    1210            0 :                 this.background_reconcile().await;
    1211            0 :             }
    1212            0 :         });
    1213            0 : 
    1214            0 :         tokio::task::spawn({
    1215            0 :             let this = this.clone();
    1216            0 :             let startup_complete = startup_complete.clone();
    1217            0 :             async move {
    1218            0 :                 startup_complete.wait().await;
    1219            0 :                 this.spawn_heartbeat_driver().await;
    1220            0 :             }
    1221            0 :         });
    1222            0 : 
    1223            0 :         Ok(this)
    1224            0 :     }
    1225              : 
    1226            0 :     pub(crate) async fn attach_hook(
    1227            0 :         &self,
    1228            0 :         attach_req: AttachHookRequest,
    1229            0 :     ) -> anyhow::Result<AttachHookResponse> {
    1230            0 :         // This is a test hook.  To enable using it on tenants that were created directly with
    1231            0 :         // the pageserver API (not via this service), we will auto-create any missing tenant
    1232            0 :         // shards with default state.
    1233            0 :         let insert = {
    1234            0 :             let locked = self.inner.write().unwrap();
    1235            0 :             !locked.tenants.contains_key(&attach_req.tenant_shard_id)
    1236            0 :         };
    1237            0 : 
    1238            0 :         if insert {
    1239            0 :             let tsp = TenantShardPersistence {
    1240            0 :                 tenant_id: attach_req.tenant_shard_id.tenant_id.to_string(),
    1241            0 :                 shard_number: attach_req.tenant_shard_id.shard_number.0 as i32,
    1242            0 :                 shard_count: attach_req.tenant_shard_id.shard_count.literal() as i32,
    1243            0 :                 shard_stripe_size: 0,
    1244            0 :                 generation: attach_req.generation_override.or(Some(0)),
    1245            0 :                 generation_pageserver: None,
    1246            0 :                 placement_policy: serde_json::to_string(&PlacementPolicy::Attached(0)).unwrap(),
    1247            0 :                 config: serde_json::to_string(&TenantConfig::default()).unwrap(),
    1248            0 :                 splitting: SplitState::default(),
    1249            0 :                 scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    1250            0 :                     .unwrap(),
    1251            0 :             };
    1252            0 : 
    1253            0 :             match self.persistence.insert_tenant_shards(vec![tsp]).await {
    1254            0 :                 Err(e) => match e {
    1255              :                     DatabaseError::Query(diesel::result::Error::DatabaseError(
    1256              :                         DatabaseErrorKind::UniqueViolation,
    1257              :                         _,
    1258              :                     )) => {
    1259            0 :                         tracing::info!(
    1260            0 :                             "Raced with another request to insert tenant {}",
    1261              :                             attach_req.tenant_shard_id
    1262              :                         )
    1263              :                     }
    1264            0 :                     _ => return Err(e.into()),
    1265              :                 },
    1266              :                 Ok(()) => {
    1267            0 :                     tracing::info!("Inserted shard {} in database", attach_req.tenant_shard_id);
    1268              : 
    1269            0 :                     let mut locked = self.inner.write().unwrap();
    1270            0 :                     locked.tenants.insert(
    1271            0 :                         attach_req.tenant_shard_id,
    1272            0 :                         TenantShard::new(
    1273            0 :                             attach_req.tenant_shard_id,
    1274            0 :                             ShardIdentity::unsharded(),
    1275            0 :                             PlacementPolicy::Attached(0),
    1276            0 :                         ),
    1277            0 :                     );
    1278            0 :                     tracing::info!("Inserted shard {} in memory", attach_req.tenant_shard_id);
    1279              :                 }
    1280              :             }
    1281            0 :         }
    1282              : 
    1283            0 :         let new_generation = if let Some(req_node_id) = attach_req.node_id {
    1284            0 :             let maybe_tenant_conf = {
    1285            0 :                 let locked = self.inner.write().unwrap();
    1286            0 :                 locked
    1287            0 :                     .tenants
    1288            0 :                     .get(&attach_req.tenant_shard_id)
    1289            0 :                     .map(|t| t.config.clone())
    1290            0 :             };
    1291            0 : 
    1292            0 :             match maybe_tenant_conf {
    1293            0 :                 Some(conf) => {
    1294            0 :                     let new_generation = self
    1295            0 :                         .persistence
    1296            0 :                         .increment_generation(attach_req.tenant_shard_id, req_node_id)
    1297            0 :                         .await?;
    1298              : 
    1299              :                     // Persist the placement policy update. This is required
    1300              :                     // when we reattaching a detached tenant.
    1301            0 :                     self.persistence
    1302            0 :                         .update_tenant_shard(
    1303            0 :                             TenantFilter::Shard(attach_req.tenant_shard_id),
    1304            0 :                             Some(PlacementPolicy::Attached(0)),
    1305            0 :                             Some(conf),
    1306            0 :                             None,
    1307            0 :                             None,
    1308            0 :                         )
    1309            0 :                         .await?;
    1310            0 :                     Some(new_generation)
    1311              :                 }
    1312              :                 None => {
    1313            0 :                     anyhow::bail!("Attach hook handling raced with tenant removal")
    1314              :                 }
    1315              :             }
    1316              :         } else {
    1317            0 :             self.persistence.detach(attach_req.tenant_shard_id).await?;
    1318            0 :             None
    1319              :         };
    1320              : 
    1321            0 :         let mut locked = self.inner.write().unwrap();
    1322            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    1323            0 : 
    1324            0 :         let tenant_shard = tenants
    1325            0 :             .get_mut(&attach_req.tenant_shard_id)
    1326            0 :             .expect("Checked for existence above");
    1327              : 
    1328            0 :         if let Some(new_generation) = new_generation {
    1329            0 :             tenant_shard.generation = Some(new_generation);
    1330            0 :             tenant_shard.policy = PlacementPolicy::Attached(0);
    1331            0 :         } else {
    1332              :             // This is a detach notification.  We must update placement policy to avoid re-attaching
    1333              :             // during background scheduling/reconciliation, or during storage controller restart.
    1334            0 :             assert!(attach_req.node_id.is_none());
    1335            0 :             tenant_shard.policy = PlacementPolicy::Detached;
    1336              :         }
    1337              : 
    1338            0 :         if let Some(attaching_pageserver) = attach_req.node_id.as_ref() {
    1339            0 :             tracing::info!(
    1340              :                 tenant_id = %attach_req.tenant_shard_id,
    1341              :                 ps_id = %attaching_pageserver,
    1342              :                 generation = ?tenant_shard.generation,
    1343            0 :                 "issuing",
    1344              :             );
    1345            0 :         } else if let Some(ps_id) = tenant_shard.intent.get_attached() {
    1346            0 :             tracing::info!(
    1347              :                 tenant_id = %attach_req.tenant_shard_id,
    1348              :                 %ps_id,
    1349              :                 generation = ?tenant_shard.generation,
    1350            0 :                 "dropping",
    1351              :             );
    1352              :         } else {
    1353            0 :             tracing::info!(
    1354              :             tenant_id = %attach_req.tenant_shard_id,
    1355            0 :             "no-op: tenant already has no pageserver");
    1356              :         }
    1357            0 :         tenant_shard
    1358            0 :             .intent
    1359            0 :             .set_attached(scheduler, attach_req.node_id);
    1360            0 : 
    1361            0 :         tracing::info!(
    1362            0 :             "attach_hook: tenant {} set generation {:?}, pageserver {}",
    1363            0 :             attach_req.tenant_shard_id,
    1364            0 :             tenant_shard.generation,
    1365            0 :             // TODO: this is an odd number of 0xf's
    1366            0 :             attach_req.node_id.unwrap_or(utils::id::NodeId(0xfffffff))
    1367              :         );
    1368              : 
    1369              :         // Trick the reconciler into not doing anything for this tenant: this helps
    1370              :         // tests that manually configure a tenant on the pagesrever, and then call this
    1371              :         // attach hook: they don't want background reconciliation to modify what they
    1372              :         // did to the pageserver.
    1373              :         #[cfg(feature = "testing")]
    1374              :         {
    1375            0 :             if let Some(node_id) = attach_req.node_id {
    1376            0 :                 tenant_shard.observed.locations = HashMap::from([(
    1377            0 :                     node_id,
    1378            0 :                     ObservedStateLocation {
    1379            0 :                         conf: Some(attached_location_conf(
    1380            0 :                             tenant_shard.generation.unwrap(),
    1381            0 :                             &tenant_shard.shard,
    1382            0 :                             &tenant_shard.config,
    1383            0 :                             false,
    1384            0 :                         )),
    1385            0 :                     },
    1386            0 :                 )]);
    1387            0 :             } else {
    1388            0 :                 tenant_shard.observed.locations.clear();
    1389            0 :             }
    1390              :         }
    1391              : 
    1392            0 :         Ok(AttachHookResponse {
    1393            0 :             gen: attach_req
    1394            0 :                 .node_id
    1395            0 :                 .map(|_| tenant_shard.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap()),
    1396            0 :         })
    1397            0 :     }
    1398              : 
    1399            0 :     pub(crate) fn inspect(&self, inspect_req: InspectRequest) -> InspectResponse {
    1400            0 :         let locked = self.inner.read().unwrap();
    1401            0 : 
    1402            0 :         let tenant_shard = locked.tenants.get(&inspect_req.tenant_shard_id);
    1403            0 : 
    1404            0 :         InspectResponse {
    1405            0 :             attachment: tenant_shard.and_then(|s| {
    1406            0 :                 s.intent
    1407            0 :                     .get_attached()
    1408            0 :                     .map(|ps| (s.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap(), ps))
    1409            0 :             }),
    1410            0 :         }
    1411            0 :     }
    1412              : 
    1413              :     // When the availability state of a node transitions to active, we must do a full reconciliation
    1414              :     // of LocationConfigs on that node.  This is because while a node was offline:
    1415              :     // - we might have proceeded through startup_reconcile without checking for extraneous LocationConfigs on this node
    1416              :     // - aborting a tenant shard split might have left rogue child shards behind on this node.
    1417              :     //
    1418              :     // This function must complete _before_ setting a `Node` to Active: once it is set to Active, other
    1419              :     // Reconcilers might communicate with the node, and these must not overlap with the work we do in
    1420              :     // this function.
    1421              :     //
    1422              :     // The reconciliation logic in here is very similar to what [`Self::startup_reconcile`] does, but
    1423              :     // for written for a single node rather than as a batch job for all nodes.
    1424            0 :     #[tracing::instrument(skip_all, fields(node_id=%node.get_id()))]
    1425              :     async fn node_activate_reconcile(
    1426              :         &self,
    1427              :         mut node: Node,
    1428              :         _lock: &WrappedWriteGuard<NodeOperations>,
    1429              :     ) -> Result<(), ApiError> {
    1430              :         // This Node is a mutable local copy: we will set it active so that we can use its
    1431              :         // API client to reconcile with the node.  The Node in [`Self::nodes`] will get updated
    1432              :         // later.
    1433              :         node.set_availability(NodeAvailability::Active(UtilizationScore::worst()));
    1434              : 
    1435              :         let configs = match node
    1436              :             .with_client_retries(
    1437            0 :                 |client| async move { client.list_location_config().await },
    1438              :                 &self.config.jwt_token,
    1439              :                 1,
    1440              :                 5,
    1441              :                 SHORT_RECONCILE_TIMEOUT,
    1442              :                 &self.cancel,
    1443              :             )
    1444              :             .await
    1445              :         {
    1446              :             None => {
    1447              :                 // We're shutting down (the Node's cancellation token can't have fired, because
    1448              :                 // we're the only scope that has a reference to it, and we didn't fire it).
    1449              :                 return Err(ApiError::ShuttingDown);
    1450              :             }
    1451              :             Some(Err(e)) => {
    1452              :                 // This node didn't succeed listing its locations: it may not proceed to active state
    1453              :                 // as it is apparently unavailable.
    1454              :                 return Err(ApiError::PreconditionFailed(
    1455              :                     format!("Failed to query node location configs, cannot activate ({e})").into(),
    1456              :                 ));
    1457              :             }
    1458              :             Some(Ok(configs)) => configs,
    1459              :         };
    1460              :         tracing::info!("Loaded {} LocationConfigs", configs.tenant_shards.len());
    1461              : 
    1462              :         let mut cleanup = Vec::new();
    1463              :         {
    1464              :             let mut locked = self.inner.write().unwrap();
    1465              : 
    1466              :             for (tenant_shard_id, observed_loc) in configs.tenant_shards {
    1467              :                 let Some(tenant_shard) = locked.tenants.get_mut(&tenant_shard_id) else {
    1468              :                     cleanup.push(tenant_shard_id);
    1469              :                     continue;
    1470              :                 };
    1471              :                 tenant_shard
    1472              :                     .observed
    1473              :                     .locations
    1474              :                     .insert(node.get_id(), ObservedStateLocation { conf: observed_loc });
    1475              :             }
    1476              :         }
    1477              : 
    1478              :         for tenant_shard_id in cleanup {
    1479              :             tracing::info!("Detaching {tenant_shard_id}");
    1480              :             match node
    1481              :                 .with_client_retries(
    1482            0 :                     |client| async move {
    1483            0 :                         let config = LocationConfig {
    1484            0 :                             mode: LocationConfigMode::Detached,
    1485            0 :                             generation: None,
    1486            0 :                             secondary_conf: None,
    1487            0 :                             shard_number: tenant_shard_id.shard_number.0,
    1488            0 :                             shard_count: tenant_shard_id.shard_count.literal(),
    1489            0 :                             shard_stripe_size: 0,
    1490            0 :                             tenant_conf: models::TenantConfig::default(),
    1491            0 :                         };
    1492            0 :                         client
    1493            0 :                             .location_config(tenant_shard_id, config, None, false)
    1494            0 :                             .await
    1495            0 :                     },
    1496              :                     &self.config.jwt_token,
    1497              :                     1,
    1498              :                     5,
    1499              :                     SHORT_RECONCILE_TIMEOUT,
    1500              :                     &self.cancel,
    1501              :                 )
    1502              :                 .await
    1503              :             {
    1504              :                 None => {
    1505              :                     // We're shutting down (the Node's cancellation token can't have fired, because
    1506              :                     // we're the only scope that has a reference to it, and we didn't fire it).
    1507              :                     return Err(ApiError::ShuttingDown);
    1508              :                 }
    1509              :                 Some(Err(e)) => {
    1510              :                     // Do not let the node proceed to Active state if it is not responsive to requests
    1511              :                     // to detach.  This could happen if e.g. a shutdown bug in the pageserver is preventing
    1512              :                     // detach completing: we should not let this node back into the set of nodes considered
    1513              :                     // okay for scheduling.
    1514              :                     return Err(ApiError::Conflict(format!(
    1515              :                         "Node {node} failed to detach {tenant_shard_id}: {e}"
    1516              :                     )));
    1517              :                 }
    1518              :                 Some(Ok(_)) => {}
    1519              :             };
    1520              :         }
    1521              : 
    1522              :         Ok(())
    1523              :     }
    1524              : 
    1525            0 :     pub(crate) async fn re_attach(
    1526            0 :         &self,
    1527            0 :         reattach_req: ReAttachRequest,
    1528            0 :     ) -> Result<ReAttachResponse, ApiError> {
    1529            0 :         if let Some(register_req) = reattach_req.register {
    1530            0 :             self.node_register(register_req).await?;
    1531            0 :         }
    1532              : 
    1533              :         // Ordering: we must persist generation number updates before making them visible in the in-memory state
    1534            0 :         let incremented_generations = self.persistence.re_attach(reattach_req.node_id).await?;
    1535              : 
    1536            0 :         tracing::info!(
    1537              :             node_id=%reattach_req.node_id,
    1538            0 :             "Incremented {} tenant shards' generations",
    1539            0 :             incremented_generations.len()
    1540              :         );
    1541              : 
    1542              :         // Apply the updated generation to our in-memory state, and
    1543              :         // gather discover secondary locations.
    1544            0 :         let mut locked = self.inner.write().unwrap();
    1545            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    1546            0 : 
    1547            0 :         let mut response = ReAttachResponse {
    1548            0 :             tenants: Vec::new(),
    1549            0 :         };
    1550              : 
    1551              :         // TODO: cancel/restart any running reconciliation for this tenant, it might be trying
    1552              :         // to call location_conf API with an old generation.  Wait for cancellation to complete
    1553              :         // before responding to this request.  Requires well implemented CancellationToken logic
    1554              :         // all the way to where we call location_conf.  Even then, there can still be a location_conf
    1555              :         // request in flight over the network: TODO handle that by making location_conf API refuse
    1556              :         // to go backward in generations.
    1557              : 
    1558              :         // Scan through all shards, applying updates for ones where we updated generation
    1559              :         // and identifying shards that intend to have a secondary location on this node.
    1560            0 :         for (tenant_shard_id, shard) in tenants {
    1561            0 :             if let Some(new_gen) = incremented_generations.get(tenant_shard_id) {
    1562            0 :                 let new_gen = *new_gen;
    1563            0 :                 response.tenants.push(ReAttachResponseTenant {
    1564            0 :                     id: *tenant_shard_id,
    1565            0 :                     gen: Some(new_gen.into().unwrap()),
    1566            0 :                     // A tenant is only put into multi or stale modes in the middle of a [`Reconciler::live_migrate`]
    1567            0 :                     // execution.  If a pageserver is restarted during that process, then the reconcile pass will
    1568            0 :                     // fail, and start from scratch, so it doesn't make sense for us to try and preserve
    1569            0 :                     // the stale/multi states at this point.
    1570            0 :                     mode: LocationConfigMode::AttachedSingle,
    1571            0 :                 });
    1572            0 : 
    1573            0 :                 shard.generation = std::cmp::max(shard.generation, Some(new_gen));
    1574            0 :                 if let Some(observed) = shard.observed.locations.get_mut(&reattach_req.node_id) {
    1575              :                     // Why can we update `observed` even though we're not sure our response will be received
    1576              :                     // by the pageserver?  Because the pageserver will not proceed with startup until
    1577              :                     // it has processed response: if it loses it, we'll see another request and increment
    1578              :                     // generation again, avoiding any uncertainty about dirtiness of tenant's state.
    1579            0 :                     if let Some(conf) = observed.conf.as_mut() {
    1580            0 :                         conf.generation = new_gen.into();
    1581            0 :                     }
    1582            0 :                 } else {
    1583            0 :                     // This node has no observed state for the shard: perhaps it was offline
    1584            0 :                     // when the pageserver restarted.  Insert a None, so that the Reconciler
    1585            0 :                     // will be prompted to learn the location's state before it makes changes.
    1586            0 :                     shard
    1587            0 :                         .observed
    1588            0 :                         .locations
    1589            0 :                         .insert(reattach_req.node_id, ObservedStateLocation { conf: None });
    1590            0 :                 }
    1591            0 :             } else if shard.intent.get_secondary().contains(&reattach_req.node_id) {
    1592            0 :                 // Ordering: pageserver will not accept /location_config requests until it has
    1593            0 :                 // finished processing the response from re-attach.  So we can update our in-memory state
    1594            0 :                 // now, and be confident that we are not stamping on the result of some later location config.
    1595            0 :                 // TODO: however, we are not strictly ordered wrt ReconcileResults queue,
    1596            0 :                 // so we might update observed state here, and then get over-written by some racing
    1597            0 :                 // ReconcileResult.  The impact is low however, since we have set state on pageserver something
    1598            0 :                 // that matches intent, so worst case if we race then we end up doing a spurious reconcile.
    1599            0 : 
    1600            0 :                 response.tenants.push(ReAttachResponseTenant {
    1601            0 :                     id: *tenant_shard_id,
    1602            0 :                     gen: None,
    1603            0 :                     mode: LocationConfigMode::Secondary,
    1604            0 :                 });
    1605            0 : 
    1606            0 :                 // We must not update observed, because we have no guarantee that our
    1607            0 :                 // response will be received by the pageserver. This could leave it
    1608            0 :                 // falsely dirty, but the resulting reconcile should be idempotent.
    1609            0 :             }
    1610              :         }
    1611              : 
    1612              :         // We consider a node Active once we have composed a re-attach response, but we
    1613              :         // do not call [`Self::node_activate_reconcile`]: the handling of the re-attach response
    1614              :         // implicitly synchronizes the LocationConfigs on the node.
    1615              :         //
    1616              :         // Setting a node active unblocks any Reconcilers that might write to the location config API,
    1617              :         // but those requests will not be accepted by the node until it has finished processing
    1618              :         // the re-attach response.
    1619              :         //
    1620              :         // Additionally, reset the nodes scheduling policy to match the conditional update done
    1621              :         // in [`Persistence::re_attach`].
    1622            0 :         if let Some(node) = nodes.get(&reattach_req.node_id) {
    1623            0 :             let reset_scheduling = matches!(
    1624            0 :                 node.get_scheduling(),
    1625              :                 NodeSchedulingPolicy::PauseForRestart
    1626              :                     | NodeSchedulingPolicy::Draining
    1627              :                     | NodeSchedulingPolicy::Filling
    1628              :             );
    1629              : 
    1630            0 :             if !node.is_available() || reset_scheduling {
    1631            0 :                 let mut new_nodes = (**nodes).clone();
    1632            0 :                 if let Some(node) = new_nodes.get_mut(&reattach_req.node_id) {
    1633            0 :                     if !node.is_available() {
    1634            0 :                         node.set_availability(NodeAvailability::Active(UtilizationScore::worst()));
    1635            0 :                     }
    1636              : 
    1637            0 :                     if reset_scheduling {
    1638            0 :                         node.set_scheduling(NodeSchedulingPolicy::Active);
    1639            0 :                     }
    1640              : 
    1641            0 :                     scheduler.node_upsert(node);
    1642            0 :                     let new_nodes = Arc::new(new_nodes);
    1643            0 :                     *nodes = new_nodes;
    1644            0 :                 }
    1645            0 :             }
    1646            0 :         }
    1647              : 
    1648            0 :         Ok(response)
    1649            0 :     }
    1650              : 
    1651            0 :     pub(crate) fn validate(&self, validate_req: ValidateRequest) -> ValidateResponse {
    1652            0 :         let locked = self.inner.read().unwrap();
    1653            0 : 
    1654            0 :         let mut response = ValidateResponse {
    1655            0 :             tenants: Vec::new(),
    1656            0 :         };
    1657              : 
    1658            0 :         for req_tenant in validate_req.tenants {
    1659            0 :             if let Some(tenant_shard) = locked.tenants.get(&req_tenant.id) {
    1660            0 :                 let valid = tenant_shard.generation == Some(Generation::new(req_tenant.gen));
    1661            0 :                 tracing::info!(
    1662            0 :                     "handle_validate: {}(gen {}): valid={valid} (latest {:?})",
    1663              :                     req_tenant.id,
    1664              :                     req_tenant.gen,
    1665              :                     tenant_shard.generation
    1666              :                 );
    1667            0 :                 response.tenants.push(ValidateResponseTenant {
    1668            0 :                     id: req_tenant.id,
    1669            0 :                     valid,
    1670            0 :                 });
    1671            0 :             } else {
    1672            0 :                 // After tenant deletion, we may approve any validation.  This avoids
    1673            0 :                 // spurious warnings on the pageserver if it has pending LSN updates
    1674            0 :                 // at the point a deletion happens.
    1675            0 :                 response.tenants.push(ValidateResponseTenant {
    1676            0 :                     id: req_tenant.id,
    1677            0 :                     valid: true,
    1678            0 :                 });
    1679            0 :             }
    1680              :         }
    1681            0 :         response
    1682            0 :     }
    1683              : 
    1684            0 :     pub(crate) async fn tenant_create(
    1685            0 :         &self,
    1686            0 :         create_req: TenantCreateRequest,
    1687            0 :     ) -> Result<TenantCreateResponse, ApiError> {
    1688            0 :         let tenant_id = create_req.new_tenant_id.tenant_id;
    1689              : 
    1690              :         // Exclude any concurrent attempts to create/access the same tenant ID
    1691            0 :         let _tenant_lock = trace_exclusive_lock(
    1692            0 :             &self.tenant_op_locks,
    1693            0 :             create_req.new_tenant_id.tenant_id,
    1694            0 :             TenantOperations::Create,
    1695            0 :         )
    1696            0 :         .await;
    1697            0 :         let (response, waiters) = self.do_tenant_create(create_req).await?;
    1698              : 
    1699            0 :         if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    1700              :             // Avoid deadlock: reconcile may fail while notifying compute, if the cloud control plane refuses to
    1701              :             // accept compute notifications while it is in the process of creating.  Reconciliation will
    1702              :             // be retried in the background.
    1703            0 :             tracing::warn!(%tenant_id, "Reconcile not done yet while creating tenant ({e})");
    1704            0 :         }
    1705            0 :         Ok(response)
    1706            0 :     }
    1707              : 
    1708            0 :     pub(crate) async fn do_tenant_create(
    1709            0 :         &self,
    1710            0 :         create_req: TenantCreateRequest,
    1711            0 :     ) -> Result<(TenantCreateResponse, Vec<ReconcilerWaiter>), ApiError> {
    1712            0 :         let placement_policy = create_req
    1713            0 :             .placement_policy
    1714            0 :             .clone()
    1715            0 :             // As a default, zero secondaries is convenient for tests that don't choose a policy.
    1716            0 :             .unwrap_or(PlacementPolicy::Attached(0));
    1717              : 
    1718              :         // This service expects to handle sharding itself: it is an error to try and directly create
    1719              :         // a particular shard here.
    1720            0 :         let tenant_id = if !create_req.new_tenant_id.is_unsharded() {
    1721            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!(
    1722            0 :                 "Attempted to create a specific shard, this API is for creating the whole tenant"
    1723            0 :             )));
    1724              :         } else {
    1725            0 :             create_req.new_tenant_id.tenant_id
    1726            0 :         };
    1727            0 : 
    1728            0 :         tracing::info!(
    1729            0 :             "Creating tenant {}, shard_count={:?}",
    1730              :             create_req.new_tenant_id,
    1731              :             create_req.shard_parameters.count,
    1732              :         );
    1733              : 
    1734            0 :         let create_ids = (0..create_req.shard_parameters.count.count())
    1735            0 :             .map(|i| TenantShardId {
    1736            0 :                 tenant_id,
    1737            0 :                 shard_number: ShardNumber(i),
    1738            0 :                 shard_count: create_req.shard_parameters.count,
    1739            0 :             })
    1740            0 :             .collect::<Vec<_>>();
    1741              : 
    1742              :         // If the caller specifies a None generation, it means "start from default".  This is different
    1743              :         // to [`Self::tenant_location_config`], where a None generation is used to represent
    1744              :         // an incompletely-onboarded tenant.
    1745            0 :         let initial_generation = if matches!(placement_policy, PlacementPolicy::Secondary) {
    1746            0 :             tracing::info!(
    1747            0 :                 "tenant_create: secondary mode, generation is_some={}",
    1748            0 :                 create_req.generation.is_some()
    1749              :             );
    1750            0 :             create_req.generation.map(Generation::new)
    1751              :         } else {
    1752            0 :             tracing::info!(
    1753            0 :                 "tenant_create: not secondary mode, generation is_some={}",
    1754            0 :                 create_req.generation.is_some()
    1755              :             );
    1756            0 :             Some(
    1757            0 :                 create_req
    1758            0 :                     .generation
    1759            0 :                     .map(Generation::new)
    1760            0 :                     .unwrap_or(INITIAL_GENERATION),
    1761            0 :             )
    1762              :         };
    1763              : 
    1764              :         // Ordering: we persist tenant shards before creating them on the pageserver.  This enables a caller
    1765              :         // to clean up after themselves by issuing a tenant deletion if something goes wrong and we restart
    1766              :         // during the creation, rather than risking leaving orphan objects in S3.
    1767            0 :         let persist_tenant_shards = create_ids
    1768            0 :             .iter()
    1769            0 :             .map(|tenant_shard_id| TenantShardPersistence {
    1770            0 :                 tenant_id: tenant_shard_id.tenant_id.to_string(),
    1771            0 :                 shard_number: tenant_shard_id.shard_number.0 as i32,
    1772            0 :                 shard_count: tenant_shard_id.shard_count.literal() as i32,
    1773            0 :                 shard_stripe_size: create_req.shard_parameters.stripe_size.0 as i32,
    1774            0 :                 generation: initial_generation.map(|g| g.into().unwrap() as i32),
    1775            0 :                 // The pageserver is not known until scheduling happens: we will set this column when
    1776            0 :                 // incrementing the generation the first time we attach to a pageserver.
    1777            0 :                 generation_pageserver: None,
    1778            0 :                 placement_policy: serde_json::to_string(&placement_policy).unwrap(),
    1779            0 :                 config: serde_json::to_string(&create_req.config).unwrap(),
    1780            0 :                 splitting: SplitState::default(),
    1781            0 :                 scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    1782            0 :                     .unwrap(),
    1783            0 :             })
    1784            0 :             .collect();
    1785            0 : 
    1786            0 :         match self
    1787            0 :             .persistence
    1788            0 :             .insert_tenant_shards(persist_tenant_shards)
    1789            0 :             .await
    1790              :         {
    1791            0 :             Ok(_) => {}
    1792              :             Err(DatabaseError::Query(diesel::result::Error::DatabaseError(
    1793              :                 DatabaseErrorKind::UniqueViolation,
    1794              :                 _,
    1795              :             ))) => {
    1796              :                 // Unique key violation: this is probably a retry.  Because the shard count is part of the unique key,
    1797              :                 // if we see a unique key violation it means that the creation request's shard count matches the previous
    1798              :                 // creation's shard count.
    1799            0 :                 tracing::info!("Tenant shards already present in database, proceeding with idempotent creation...");
    1800              :             }
    1801              :             // Any other database error is unexpected and a bug.
    1802            0 :             Err(e) => return Err(ApiError::InternalServerError(anyhow::anyhow!(e))),
    1803              :         };
    1804              : 
    1805            0 :         let mut schedule_context = ScheduleContext::default();
    1806              : 
    1807            0 :         let (waiters, response_shards) = {
    1808            0 :             let mut locked = self.inner.write().unwrap();
    1809            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    1810            0 : 
    1811            0 :             let mut response_shards = Vec::new();
    1812            0 :             let mut schcedule_error = None;
    1813              : 
    1814            0 :             for tenant_shard_id in create_ids {
    1815            0 :                 tracing::info!("Creating shard {tenant_shard_id}...");
    1816              : 
    1817              :                 use std::collections::btree_map::Entry;
    1818            0 :                 match tenants.entry(tenant_shard_id) {
    1819            0 :                     Entry::Occupied(mut entry) => {
    1820            0 :                         tracing::info!(
    1821            0 :                             "Tenant shard {tenant_shard_id} already exists while creating"
    1822              :                         );
    1823              : 
    1824              :                         // TODO: schedule() should take an anti-affinity expression that pushes
    1825              :                         // attached and secondary locations (independently) away frorm those
    1826              :                         // pageservers also holding a shard for this tenant.
    1827              : 
    1828            0 :                         entry
    1829            0 :                             .get_mut()
    1830            0 :                             .schedule(scheduler, &mut schedule_context)
    1831            0 :                             .map_err(|e| {
    1832            0 :                                 ApiError::Conflict(format!(
    1833            0 :                                     "Failed to schedule shard {tenant_shard_id}: {e}"
    1834            0 :                                 ))
    1835            0 :                             })?;
    1836              : 
    1837            0 :                         if let Some(node_id) = entry.get().intent.get_attached() {
    1838            0 :                             let generation = entry
    1839            0 :                                 .get()
    1840            0 :                                 .generation
    1841            0 :                                 .expect("Generation is set when in attached mode");
    1842            0 :                             response_shards.push(TenantCreateResponseShard {
    1843            0 :                                 shard_id: tenant_shard_id,
    1844            0 :                                 node_id: *node_id,
    1845            0 :                                 generation: generation.into().unwrap(),
    1846            0 :                             });
    1847            0 :                         }
    1848              : 
    1849            0 :                         continue;
    1850              :                     }
    1851            0 :                     Entry::Vacant(entry) => {
    1852            0 :                         let state = entry.insert(TenantShard::new(
    1853            0 :                             tenant_shard_id,
    1854            0 :                             ShardIdentity::from_params(
    1855            0 :                                 tenant_shard_id.shard_number,
    1856            0 :                                 &create_req.shard_parameters,
    1857            0 :                             ),
    1858            0 :                             placement_policy.clone(),
    1859            0 :                         ));
    1860            0 : 
    1861            0 :                         state.generation = initial_generation;
    1862            0 :                         state.config = create_req.config.clone();
    1863            0 :                         if let Err(e) = state.schedule(scheduler, &mut schedule_context) {
    1864            0 :                             schcedule_error = Some(e);
    1865            0 :                         }
    1866              : 
    1867              :                         // Only include shards in result if we are attaching: the purpose
    1868              :                         // of the response is to tell the caller where the shards are attached.
    1869            0 :                         if let Some(node_id) = state.intent.get_attached() {
    1870            0 :                             let generation = state
    1871            0 :                                 .generation
    1872            0 :                                 .expect("Generation is set when in attached mode");
    1873            0 :                             response_shards.push(TenantCreateResponseShard {
    1874            0 :                                 shard_id: tenant_shard_id,
    1875            0 :                                 node_id: *node_id,
    1876            0 :                                 generation: generation.into().unwrap(),
    1877            0 :                             });
    1878            0 :                         }
    1879              :                     }
    1880              :                 };
    1881              :             }
    1882              : 
    1883              :             // If we failed to schedule shards, then they are still created in the controller,
    1884              :             // but we return an error to the requester to avoid a silent failure when someone
    1885              :             // tries to e.g. create a tenant whose placement policy requires more nodes than
    1886              :             // are present in the system.  We do this here rather than in the above loop, to
    1887              :             // avoid situations where we only create a subset of shards in the tenant.
    1888            0 :             if let Some(e) = schcedule_error {
    1889            0 :                 return Err(ApiError::Conflict(format!(
    1890            0 :                     "Failed to schedule shard(s): {e}"
    1891            0 :                 )));
    1892            0 :             }
    1893            0 : 
    1894            0 :             let waiters = tenants
    1895            0 :                 .range_mut(TenantShardId::tenant_range(tenant_id))
    1896            0 :                 .filter_map(|(_shard_id, shard)| self.maybe_reconcile_shard(shard, nodes))
    1897            0 :                 .collect::<Vec<_>>();
    1898            0 :             (waiters, response_shards)
    1899            0 :         };
    1900            0 : 
    1901            0 :         Ok((
    1902            0 :             TenantCreateResponse {
    1903            0 :                 shards: response_shards,
    1904            0 :             },
    1905            0 :             waiters,
    1906            0 :         ))
    1907            0 :     }
    1908              : 
    1909              :     /// Helper for functions that reconcile a number of shards, and would like to do a timeout-bounded
    1910              :     /// wait for reconciliation to complete before responding.
    1911            0 :     async fn await_waiters(
    1912            0 :         &self,
    1913            0 :         waiters: Vec<ReconcilerWaiter>,
    1914            0 :         timeout: Duration,
    1915            0 :     ) -> Result<(), ReconcileWaitError> {
    1916            0 :         let deadline = Instant::now().checked_add(timeout).unwrap();
    1917            0 :         for waiter in waiters {
    1918            0 :             let timeout = deadline.duration_since(Instant::now());
    1919            0 :             waiter.wait_timeout(timeout).await?;
    1920              :         }
    1921              : 
    1922            0 :         Ok(())
    1923            0 :     }
    1924              : 
    1925              :     /// Same as [`Service::await_waiters`], but returns the waiters which are still
    1926              :     /// in progress
    1927            0 :     async fn await_waiters_remainder(
    1928            0 :         &self,
    1929            0 :         waiters: Vec<ReconcilerWaiter>,
    1930            0 :         timeout: Duration,
    1931            0 :     ) -> Vec<ReconcilerWaiter> {
    1932            0 :         let deadline = Instant::now().checked_add(timeout).unwrap();
    1933            0 :         for waiter in waiters.iter() {
    1934            0 :             let timeout = deadline.duration_since(Instant::now());
    1935            0 :             let _ = waiter.wait_timeout(timeout).await;
    1936              :         }
    1937              : 
    1938            0 :         waiters
    1939            0 :             .into_iter()
    1940            0 :             .filter(|waiter| matches!(waiter.get_status(), ReconcilerStatus::InProgress))
    1941            0 :             .collect::<Vec<_>>()
    1942            0 :     }
    1943              : 
    1944              :     /// Part of [`Self::tenant_location_config`]: dissect an incoming location config request,
    1945              :     /// and transform it into either a tenant creation of a series of shard updates.
    1946              :     ///
    1947              :     /// If the incoming request makes no changes, a [`TenantCreateOrUpdate::Update`] result will
    1948              :     /// still be returned.
    1949            0 :     fn tenant_location_config_prepare(
    1950            0 :         &self,
    1951            0 :         tenant_id: TenantId,
    1952            0 :         req: TenantLocationConfigRequest,
    1953            0 :     ) -> TenantCreateOrUpdate {
    1954            0 :         let mut updates = Vec::new();
    1955            0 :         let mut locked = self.inner.write().unwrap();
    1956            0 :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    1957            0 :         let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    1958              : 
    1959              :         // Use location config mode as an indicator of policy.
    1960            0 :         let placement_policy = match req.config.mode {
    1961            0 :             LocationConfigMode::Detached => PlacementPolicy::Detached,
    1962            0 :             LocationConfigMode::Secondary => PlacementPolicy::Secondary,
    1963              :             LocationConfigMode::AttachedMulti
    1964              :             | LocationConfigMode::AttachedSingle
    1965              :             | LocationConfigMode::AttachedStale => {
    1966            0 :                 if nodes.len() > 1 {
    1967            0 :                     PlacementPolicy::Attached(1)
    1968              :                 } else {
    1969              :                     // Convenience for dev/test: if we just have one pageserver, import
    1970              :                     // tenants into non-HA mode so that scheduling will succeed.
    1971            0 :                     PlacementPolicy::Attached(0)
    1972              :                 }
    1973              :             }
    1974              :         };
    1975              : 
    1976            0 :         let mut create = true;
    1977            0 :         for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    1978              :             // Saw an existing shard: this is not a creation
    1979            0 :             create = false;
    1980              : 
    1981              :             // Shards may have initially been created by a Secondary request, where we
    1982              :             // would have left generation as None.
    1983              :             //
    1984              :             // We only update generation the first time we see an attached-mode request,
    1985              :             // and if there is no existing generation set. The caller is responsible for
    1986              :             // ensuring that no non-storage-controller pageserver ever uses a higher
    1987              :             // generation than they passed in here.
    1988              :             use LocationConfigMode::*;
    1989            0 :             let set_generation = match req.config.mode {
    1990            0 :                 AttachedMulti | AttachedSingle | AttachedStale if shard.generation.is_none() => {
    1991            0 :                     req.config.generation.map(Generation::new)
    1992              :                 }
    1993            0 :                 _ => None,
    1994              :             };
    1995              : 
    1996            0 :             updates.push(ShardUpdate {
    1997            0 :                 tenant_shard_id: *shard_id,
    1998            0 :                 placement_policy: placement_policy.clone(),
    1999            0 :                 tenant_config: req.config.tenant_conf.clone(),
    2000            0 :                 generation: set_generation,
    2001            0 :             });
    2002              :         }
    2003              : 
    2004            0 :         if create {
    2005              :             use LocationConfigMode::*;
    2006            0 :             let generation = match req.config.mode {
    2007            0 :                 AttachedMulti | AttachedSingle | AttachedStale => req.config.generation,
    2008              :                 // If a caller provided a generation in a non-attached request, ignore it
    2009              :                 // and leave our generation as None: this enables a subsequent update to set
    2010              :                 // the generation when setting an attached mode for the first time.
    2011            0 :                 _ => None,
    2012              :             };
    2013              : 
    2014            0 :             TenantCreateOrUpdate::Create(
    2015            0 :                 // Synthesize a creation request
    2016            0 :                 TenantCreateRequest {
    2017            0 :                     new_tenant_id: tenant_shard_id,
    2018            0 :                     generation,
    2019            0 :                     shard_parameters: ShardParameters {
    2020            0 :                         count: tenant_shard_id.shard_count,
    2021            0 :                         // We only import un-sharded or single-sharded tenants, so stripe
    2022            0 :                         // size can be made up arbitrarily here.
    2023            0 :                         stripe_size: ShardParameters::DEFAULT_STRIPE_SIZE,
    2024            0 :                     },
    2025            0 :                     placement_policy: Some(placement_policy),
    2026            0 :                     config: req.config.tenant_conf,
    2027            0 :                 },
    2028            0 :             )
    2029              :         } else {
    2030            0 :             assert!(!updates.is_empty());
    2031            0 :             TenantCreateOrUpdate::Update(updates)
    2032              :         }
    2033            0 :     }
    2034              : 
    2035              :     /// This API is used by the cloud control plane to migrate unsharded tenants that it created
    2036              :     /// directly with pageservers into this service.
    2037              :     ///
    2038              :     /// Cloud control plane MUST NOT continue issuing GENERATION NUMBERS for this tenant once it
    2039              :     /// has attempted to call this API. Failure to oblige to this rule may lead to S3 corruption.
    2040              :     /// Think of the first attempt to call this API as a transfer of absolute authority over the
    2041              :     /// tenant's source of generation numbers.
    2042              :     ///
    2043              :     /// The mode in this request coarse-grained control of tenants:
    2044              :     /// - Call with mode Attached* to upsert the tenant.
    2045              :     /// - Call with mode Secondary to either onboard a tenant without attaching it, or
    2046              :     ///   to set an existing tenant to PolicyMode::Secondary
    2047              :     /// - Call with mode Detached to switch to PolicyMode::Detached
    2048            0 :     pub(crate) async fn tenant_location_config(
    2049            0 :         &self,
    2050            0 :         tenant_shard_id: TenantShardId,
    2051            0 :         req: TenantLocationConfigRequest,
    2052            0 :     ) -> Result<TenantLocationConfigResponse, ApiError> {
    2053              :         // We require an exclusive lock, because we are updating both persistent and in-memory state
    2054            0 :         let _tenant_lock = trace_exclusive_lock(
    2055            0 :             &self.tenant_op_locks,
    2056            0 :             tenant_shard_id.tenant_id,
    2057            0 :             TenantOperations::LocationConfig,
    2058            0 :         )
    2059            0 :         .await;
    2060              : 
    2061            0 :         if !tenant_shard_id.is_unsharded() {
    2062            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!(
    2063            0 :                 "This API is for importing single-sharded or unsharded tenants"
    2064            0 :             )));
    2065            0 :         }
    2066            0 : 
    2067            0 :         // First check if this is a creation or an update
    2068            0 :         let create_or_update = self.tenant_location_config_prepare(tenant_shard_id.tenant_id, req);
    2069            0 : 
    2070            0 :         let mut result = TenantLocationConfigResponse {
    2071            0 :             shards: Vec::new(),
    2072            0 :             stripe_size: None,
    2073            0 :         };
    2074            0 :         let waiters = match create_or_update {
    2075            0 :             TenantCreateOrUpdate::Create(create_req) => {
    2076            0 :                 let (create_resp, waiters) = self.do_tenant_create(create_req).await?;
    2077            0 :                 result.shards = create_resp
    2078            0 :                     .shards
    2079            0 :                     .into_iter()
    2080            0 :                     .map(|s| TenantShardLocation {
    2081            0 :                         node_id: s.node_id,
    2082            0 :                         shard_id: s.shard_id,
    2083            0 :                     })
    2084            0 :                     .collect();
    2085            0 :                 waiters
    2086              :             }
    2087            0 :             TenantCreateOrUpdate::Update(updates) => {
    2088            0 :                 // Persist updates
    2089            0 :                 // Ordering: write to the database before applying changes in-memory, so that
    2090            0 :                 // we will not appear time-travel backwards on a restart.
    2091            0 :                 let mut schedule_context = ScheduleContext::default();
    2092              :                 for ShardUpdate {
    2093            0 :                     tenant_shard_id,
    2094            0 :                     placement_policy,
    2095            0 :                     tenant_config,
    2096            0 :                     generation,
    2097            0 :                 } in &updates
    2098              :                 {
    2099            0 :                     self.persistence
    2100            0 :                         .update_tenant_shard(
    2101            0 :                             TenantFilter::Shard(*tenant_shard_id),
    2102            0 :                             Some(placement_policy.clone()),
    2103            0 :                             Some(tenant_config.clone()),
    2104            0 :                             *generation,
    2105            0 :                             None,
    2106            0 :                         )
    2107            0 :                         .await?;
    2108              :                 }
    2109              : 
    2110              :                 // Apply updates in-memory
    2111            0 :                 let mut waiters = Vec::new();
    2112            0 :                 {
    2113            0 :                     let mut locked = self.inner.write().unwrap();
    2114            0 :                     let (nodes, tenants, scheduler) = locked.parts_mut();
    2115              : 
    2116              :                     for ShardUpdate {
    2117            0 :                         tenant_shard_id,
    2118            0 :                         placement_policy,
    2119            0 :                         tenant_config,
    2120            0 :                         generation: update_generation,
    2121            0 :                     } in updates
    2122              :                     {
    2123            0 :                         let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    2124            0 :                             tracing::warn!("Shard {tenant_shard_id} removed while updating");
    2125            0 :                             continue;
    2126              :                         };
    2127              : 
    2128              :                         // Update stripe size
    2129            0 :                         if result.stripe_size.is_none() && shard.shard.count.count() > 1 {
    2130            0 :                             result.stripe_size = Some(shard.shard.stripe_size);
    2131            0 :                         }
    2132              : 
    2133            0 :                         shard.policy = placement_policy;
    2134            0 :                         shard.config = tenant_config;
    2135            0 :                         if let Some(generation) = update_generation {
    2136            0 :                             shard.generation = Some(generation);
    2137            0 :                         }
    2138              : 
    2139            0 :                         shard.schedule(scheduler, &mut schedule_context)?;
    2140              : 
    2141            0 :                         let maybe_waiter = self.maybe_reconcile_shard(shard, nodes);
    2142            0 :                         if let Some(waiter) = maybe_waiter {
    2143            0 :                             waiters.push(waiter);
    2144            0 :                         }
    2145              : 
    2146            0 :                         if let Some(node_id) = shard.intent.get_attached() {
    2147            0 :                             result.shards.push(TenantShardLocation {
    2148            0 :                                 shard_id: tenant_shard_id,
    2149            0 :                                 node_id: *node_id,
    2150            0 :                             })
    2151            0 :                         }
    2152              :                     }
    2153              :                 }
    2154            0 :                 waiters
    2155              :             }
    2156              :         };
    2157              : 
    2158            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    2159              :             // Do not treat a reconcile error as fatal: we have already applied any requested
    2160              :             // Intent changes, and the reconcile can fail for external reasons like unavailable
    2161              :             // compute notification API.  In these cases, it is important that we do not
    2162              :             // cause the cloud control plane to retry forever on this API.
    2163            0 :             tracing::warn!(
    2164            0 :                 "Failed to reconcile after /location_config: {e}, returning success anyway"
    2165              :             );
    2166            0 :         }
    2167              : 
    2168              :         // Logging the full result is useful because it lets us cross-check what the cloud control
    2169              :         // plane's tenant_shards table should contain.
    2170            0 :         tracing::info!("Complete, returning {result:?}");
    2171              : 
    2172            0 :         Ok(result)
    2173            0 :     }
    2174              : 
    2175            0 :     pub(crate) async fn tenant_config_set(&self, req: TenantConfigRequest) -> Result<(), ApiError> {
    2176              :         // We require an exclusive lock, because we are updating persistent and in-memory state
    2177            0 :         let _tenant_lock = trace_exclusive_lock(
    2178            0 :             &self.tenant_op_locks,
    2179            0 :             req.tenant_id,
    2180            0 :             TenantOperations::ConfigSet,
    2181            0 :         )
    2182            0 :         .await;
    2183              : 
    2184            0 :         let tenant_id = req.tenant_id;
    2185            0 :         let config = req.config;
    2186            0 : 
    2187            0 :         self.persistence
    2188            0 :             .update_tenant_shard(
    2189            0 :                 TenantFilter::Tenant(req.tenant_id),
    2190            0 :                 None,
    2191            0 :                 Some(config.clone()),
    2192            0 :                 None,
    2193            0 :                 None,
    2194            0 :             )
    2195            0 :             .await?;
    2196              : 
    2197            0 :         let waiters = {
    2198            0 :             let mut waiters = Vec::new();
    2199            0 :             let mut locked = self.inner.write().unwrap();
    2200            0 :             let (nodes, tenants, _scheduler) = locked.parts_mut();
    2201            0 :             for (_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    2202            0 :                 shard.config = config.clone();
    2203            0 :                 if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
    2204            0 :                     waiters.push(waiter);
    2205            0 :                 }
    2206              :             }
    2207            0 :             waiters
    2208              :         };
    2209              : 
    2210            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    2211              :             // Treat this as success because we have stored the configuration.  If e.g.
    2212              :             // a node was unavailable at this time, it should not stop us accepting a
    2213              :             // configuration change.
    2214            0 :             tracing::warn!(%tenant_id, "Accepted configuration update but reconciliation failed: {e}");
    2215            0 :         }
    2216              : 
    2217            0 :         Ok(())
    2218            0 :     }
    2219              : 
    2220            0 :     pub(crate) fn tenant_config_get(
    2221            0 :         &self,
    2222            0 :         tenant_id: TenantId,
    2223            0 :     ) -> Result<HashMap<&str, serde_json::Value>, ApiError> {
    2224            0 :         let config = {
    2225            0 :             let locked = self.inner.read().unwrap();
    2226            0 : 
    2227            0 :             match locked
    2228            0 :                 .tenants
    2229            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    2230            0 :                 .next()
    2231              :             {
    2232            0 :                 Some((_tenant_shard_id, shard)) => shard.config.clone(),
    2233              :                 None => {
    2234            0 :                     return Err(ApiError::NotFound(
    2235            0 :                         anyhow::anyhow!("Tenant not found").into(),
    2236            0 :                     ))
    2237              :                 }
    2238              :             }
    2239              :         };
    2240              : 
    2241              :         // Unlike the pageserver, we do not have a set of global defaults: the config is
    2242              :         // entirely per-tenant.  Therefore the distinction between `tenant_specific_overrides`
    2243              :         // and `effective_config` in the response is meaningless, but we retain that syntax
    2244              :         // in order to remain compatible with the pageserver API.
    2245              : 
    2246            0 :         let response = HashMap::from([
    2247              :             (
    2248              :                 "tenant_specific_overrides",
    2249            0 :                 serde_json::to_value(&config)
    2250            0 :                     .context("serializing tenant specific overrides")
    2251            0 :                     .map_err(ApiError::InternalServerError)?,
    2252              :             ),
    2253              :             (
    2254            0 :                 "effective_config",
    2255            0 :                 serde_json::to_value(&config)
    2256            0 :                     .context("serializing effective config")
    2257            0 :                     .map_err(ApiError::InternalServerError)?,
    2258              :             ),
    2259              :         ]);
    2260              : 
    2261            0 :         Ok(response)
    2262            0 :     }
    2263              : 
    2264            0 :     pub(crate) async fn tenant_time_travel_remote_storage(
    2265            0 :         &self,
    2266            0 :         time_travel_req: &TenantTimeTravelRequest,
    2267            0 :         tenant_id: TenantId,
    2268            0 :         timestamp: Cow<'_, str>,
    2269            0 :         done_if_after: Cow<'_, str>,
    2270            0 :     ) -> Result<(), ApiError> {
    2271            0 :         let _tenant_lock = trace_exclusive_lock(
    2272            0 :             &self.tenant_op_locks,
    2273            0 :             tenant_id,
    2274            0 :             TenantOperations::TimeTravelRemoteStorage,
    2275            0 :         )
    2276            0 :         .await;
    2277              : 
    2278            0 :         let node = {
    2279            0 :             let locked = self.inner.read().unwrap();
    2280              :             // Just a sanity check to prevent misuse: the API expects that the tenant is fully
    2281              :             // detached everywhere, and nothing writes to S3 storage. Here, we verify that,
    2282              :             // but only at the start of the process, so it's really just to prevent operator
    2283              :             // mistakes.
    2284            0 :             for (shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
    2285            0 :                 if shard.intent.get_attached().is_some() || !shard.intent.get_secondary().is_empty()
    2286              :                 {
    2287            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    2288            0 :                         "We want tenant to be attached in shard with tenant_shard_id={shard_id}"
    2289            0 :                     )));
    2290            0 :                 }
    2291            0 :                 let maybe_attached = shard
    2292            0 :                     .observed
    2293            0 :                     .locations
    2294            0 :                     .iter()
    2295            0 :                     .filter_map(|(node_id, observed_location)| {
    2296            0 :                         observed_location
    2297            0 :                             .conf
    2298            0 :                             .as_ref()
    2299            0 :                             .map(|loc| (node_id, observed_location, loc.mode))
    2300            0 :                     })
    2301            0 :                     .find(|(_, _, mode)| *mode != LocationConfigMode::Detached);
    2302            0 :                 if let Some((node_id, _observed_location, mode)) = maybe_attached {
    2303            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!("We observed attached={mode:?} tenant in node_id={node_id} shard with tenant_shard_id={shard_id}")));
    2304            0 :                 }
    2305              :             }
    2306            0 :             let scheduler = &locked.scheduler;
    2307              :             // Right now we only perform the operation on a single node without parallelization
    2308              :             // TODO fan out the operation to multiple nodes for better performance
    2309            0 :             let node_id = scheduler.schedule_shard(&[], &ScheduleContext::default())?;
    2310            0 :             let node = locked
    2311            0 :                 .nodes
    2312            0 :                 .get(&node_id)
    2313            0 :                 .expect("Pageservers may not be deleted while lock is active");
    2314            0 :             node.clone()
    2315            0 :         };
    2316            0 : 
    2317            0 :         // The shard count is encoded in the remote storage's URL, so we need to handle all historically used shard counts
    2318            0 :         let mut counts = time_travel_req
    2319            0 :             .shard_counts
    2320            0 :             .iter()
    2321            0 :             .copied()
    2322            0 :             .collect::<HashSet<_>>()
    2323            0 :             .into_iter()
    2324            0 :             .collect::<Vec<_>>();
    2325            0 :         counts.sort_unstable();
    2326              : 
    2327            0 :         for count in counts {
    2328            0 :             let shard_ids = (0..count.count())
    2329            0 :                 .map(|i| TenantShardId {
    2330            0 :                     tenant_id,
    2331            0 :                     shard_number: ShardNumber(i),
    2332            0 :                     shard_count: count,
    2333            0 :                 })
    2334            0 :                 .collect::<Vec<_>>();
    2335            0 :             for tenant_shard_id in shard_ids {
    2336            0 :                 let client = PageserverClient::new(
    2337            0 :                     node.get_id(),
    2338            0 :                     node.base_url(),
    2339            0 :                     self.config.jwt_token.as_deref(),
    2340            0 :                 );
    2341            0 : 
    2342            0 :                 tracing::info!("Doing time travel recovery for shard {tenant_shard_id}",);
    2343              : 
    2344            0 :                 client
    2345            0 :                         .tenant_time_travel_remote_storage(
    2346            0 :                             tenant_shard_id,
    2347            0 :                             &timestamp,
    2348            0 :                             &done_if_after,
    2349            0 :                         )
    2350            0 :                         .await
    2351            0 :                         .map_err(|e| {
    2352            0 :                             ApiError::InternalServerError(anyhow::anyhow!(
    2353            0 :                                 "Error doing time travel recovery for shard {tenant_shard_id} on node {}: {e}",
    2354            0 :                                 node
    2355            0 :                             ))
    2356            0 :                         })?;
    2357              :             }
    2358              :         }
    2359            0 :         Ok(())
    2360            0 :     }
    2361              : 
    2362            0 :     pub(crate) async fn tenant_secondary_download(
    2363            0 :         &self,
    2364            0 :         tenant_id: TenantId,
    2365            0 :         wait: Option<Duration>,
    2366            0 :     ) -> Result<(StatusCode, SecondaryProgress), ApiError> {
    2367            0 :         let _tenant_lock = trace_shared_lock(
    2368            0 :             &self.tenant_op_locks,
    2369            0 :             tenant_id,
    2370            0 :             TenantOperations::SecondaryDownload,
    2371            0 :         )
    2372            0 :         .await;
    2373              : 
    2374              :         // Acquire lock and yield the collection of shard-node tuples which we will send requests onward to
    2375            0 :         let targets = {
    2376            0 :             let locked = self.inner.read().unwrap();
    2377            0 :             let mut targets = Vec::new();
    2378              : 
    2379            0 :             for (tenant_shard_id, shard) in
    2380            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    2381              :             {
    2382            0 :                 for node_id in shard.intent.get_secondary() {
    2383            0 :                     let node = locked
    2384            0 :                         .nodes
    2385            0 :                         .get(node_id)
    2386            0 :                         .expect("Pageservers may not be deleted while referenced");
    2387            0 : 
    2388            0 :                     targets.push((*tenant_shard_id, node.clone()));
    2389            0 :                 }
    2390              :             }
    2391            0 :             targets
    2392            0 :         };
    2393            0 : 
    2394            0 :         // Issue concurrent requests to all shards' locations
    2395            0 :         let mut futs = FuturesUnordered::new();
    2396            0 :         for (tenant_shard_id, node) in targets {
    2397            0 :             let client = PageserverClient::new(
    2398            0 :                 node.get_id(),
    2399            0 :                 node.base_url(),
    2400            0 :                 self.config.jwt_token.as_deref(),
    2401            0 :             );
    2402            0 :             futs.push(async move {
    2403            0 :                 let result = client
    2404            0 :                     .tenant_secondary_download(tenant_shard_id, wait)
    2405            0 :                     .await;
    2406            0 :                 (result, node, tenant_shard_id)
    2407            0 :             })
    2408              :         }
    2409              : 
    2410              :         // Handle any errors returned by pageservers.  This includes cases like this request racing with
    2411              :         // a scheduling operation, such that the tenant shard we're calling doesn't exist on that pageserver any more, as
    2412              :         // well as more general cases like 503s, 500s, or timeouts.
    2413            0 :         let mut aggregate_progress = SecondaryProgress::default();
    2414            0 :         let mut aggregate_status: Option<StatusCode> = None;
    2415            0 :         let mut error: Option<mgmt_api::Error> = None;
    2416            0 :         while let Some((result, node, tenant_shard_id)) = futs.next().await {
    2417            0 :             match result {
    2418            0 :                 Err(e) => {
    2419            0 :                     // Secondary downloads are always advisory: if something fails, we nevertheless report success, so that whoever
    2420            0 :                     // is calling us will proceed with whatever migration they're doing, albeit with a slightly less warm cache
    2421            0 :                     // than they had hoped for.
    2422            0 :                     tracing::warn!("Secondary download error from pageserver {node}: {e}",);
    2423            0 :                     error = Some(e)
    2424              :                 }
    2425            0 :                 Ok((status_code, progress)) => {
    2426            0 :                     tracing::info!(%tenant_shard_id, "Shard status={status_code} progress: {progress:?}");
    2427            0 :                     aggregate_progress.layers_downloaded += progress.layers_downloaded;
    2428            0 :                     aggregate_progress.layers_total += progress.layers_total;
    2429            0 :                     aggregate_progress.bytes_downloaded += progress.bytes_downloaded;
    2430            0 :                     aggregate_progress.bytes_total += progress.bytes_total;
    2431            0 :                     aggregate_progress.heatmap_mtime =
    2432            0 :                         std::cmp::max(aggregate_progress.heatmap_mtime, progress.heatmap_mtime);
    2433            0 :                     aggregate_status = match aggregate_status {
    2434            0 :                         None => Some(status_code),
    2435            0 :                         Some(StatusCode::OK) => Some(status_code),
    2436            0 :                         Some(cur) => {
    2437            0 :                             // Other status codes (e.g. 202) -- do not overwrite.
    2438            0 :                             Some(cur)
    2439              :                         }
    2440              :                     };
    2441              :                 }
    2442              :             }
    2443              :         }
    2444              : 
    2445              :         // If any of the shards return 202, indicate our result as 202.
    2446            0 :         match aggregate_status {
    2447              :             None => {
    2448            0 :                 match error {
    2449            0 :                     Some(e) => {
    2450            0 :                         // No successes, and an error: surface it
    2451            0 :                         Err(ApiError::Conflict(format!("Error from pageserver: {e}")))
    2452              :                     }
    2453              :                     None => {
    2454              :                         // No shards found
    2455            0 :                         Err(ApiError::NotFound(
    2456            0 :                             anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    2457            0 :                         ))
    2458              :                     }
    2459              :                 }
    2460              :             }
    2461            0 :             Some(aggregate_status) => Ok((aggregate_status, aggregate_progress)),
    2462              :         }
    2463            0 :     }
    2464              : 
    2465            0 :     pub(crate) async fn tenant_delete(&self, tenant_id: TenantId) -> Result<StatusCode, ApiError> {
    2466            0 :         let _tenant_lock =
    2467            0 :             trace_exclusive_lock(&self.tenant_op_locks, tenant_id, TenantOperations::Delete).await;
    2468              : 
    2469              :         // Detach all shards
    2470            0 :         let (detach_waiters, shard_ids, node) = {
    2471            0 :             let mut shard_ids = Vec::new();
    2472            0 :             let mut detach_waiters = Vec::new();
    2473            0 :             let mut locked = self.inner.write().unwrap();
    2474            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    2475            0 :             for (tenant_shard_id, shard) in
    2476            0 :                 tenants.range_mut(TenantShardId::tenant_range(tenant_id))
    2477              :             {
    2478            0 :                 shard_ids.push(*tenant_shard_id);
    2479            0 : 
    2480            0 :                 // Update the tenant's intent to remove all attachments
    2481            0 :                 shard.policy = PlacementPolicy::Detached;
    2482            0 :                 shard
    2483            0 :                     .schedule(scheduler, &mut ScheduleContext::default())
    2484            0 :                     .expect("De-scheduling is infallible");
    2485            0 :                 debug_assert!(shard.intent.get_attached().is_none());
    2486            0 :                 debug_assert!(shard.intent.get_secondary().is_empty());
    2487              : 
    2488            0 :                 if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
    2489            0 :                     detach_waiters.push(waiter);
    2490            0 :                 }
    2491              :             }
    2492              : 
    2493              :             // Pick an arbitrary node to use for remote deletions (does not have to be where the tenant
    2494              :             // was attached, just has to be able to see the S3 content)
    2495            0 :             let node_id = scheduler.schedule_shard(&[], &ScheduleContext::default())?;
    2496            0 :             let node = nodes
    2497            0 :                 .get(&node_id)
    2498            0 :                 .expect("Pageservers may not be deleted while lock is active");
    2499            0 :             (detach_waiters, shard_ids, node.clone())
    2500            0 :         };
    2501            0 : 
    2502            0 :         // This reconcile wait can fail in a few ways:
    2503            0 :         //  A there is a very long queue for the reconciler semaphore
    2504            0 :         //  B some pageserver is failing to handle a detach promptly
    2505            0 :         //  C some pageserver goes offline right at the moment we send it a request.
    2506            0 :         //
    2507            0 :         // A and C are transient: the semaphore will eventually become available, and once a node is marked offline
    2508            0 :         // the next attempt to reconcile will silently skip detaches for an offline node and succeed.  If B happens,
    2509            0 :         // it's a bug, and needs resolving at the pageserver level (we shouldn't just leave attachments behind while
    2510            0 :         // deleting the underlying data).
    2511            0 :         self.await_waiters(detach_waiters, RECONCILE_TIMEOUT)
    2512            0 :             .await?;
    2513              : 
    2514            0 :         let locations = shard_ids
    2515            0 :             .into_iter()
    2516            0 :             .map(|s| (s, node.clone()))
    2517            0 :             .collect::<Vec<_>>();
    2518            0 :         let results = self.tenant_for_shards_api(
    2519            0 :             locations,
    2520            0 :             |tenant_shard_id, client| async move { client.tenant_delete(tenant_shard_id).await },
    2521            0 :             1,
    2522            0 :             3,
    2523            0 :             RECONCILE_TIMEOUT,
    2524            0 :             &self.cancel,
    2525            0 :         )
    2526            0 :         .await;
    2527            0 :         for result in results {
    2528            0 :             match result {
    2529              :                 Ok(StatusCode::ACCEPTED) => {
    2530              :                     // This should never happen: we waited for detaches to finish above
    2531            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    2532            0 :                         "Unexpectedly still attached on {}",
    2533            0 :                         node
    2534            0 :                     )));
    2535              :                 }
    2536            0 :                 Ok(_) => {}
    2537              :                 Err(mgmt_api::Error::Cancelled) => {
    2538            0 :                     return Err(ApiError::ShuttingDown);
    2539              :                 }
    2540            0 :                 Err(e) => {
    2541            0 :                     // This is unexpected: remote deletion should be infallible, unless the object store
    2542            0 :                     // at large is unavailable.
    2543            0 :                     tracing::error!("Error deleting via node {}: {e}", node);
    2544            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
    2545              :                 }
    2546              :             }
    2547              :         }
    2548              : 
    2549              :         // Fall through: deletion of the tenant on pageservers is complete, we may proceed to drop
    2550              :         // our in-memory state and database state.
    2551              : 
    2552              :         // Ordering: we delete persistent state first: if we then
    2553              :         // crash, we will drop the in-memory state.
    2554              : 
    2555              :         // Drop persistent state.
    2556            0 :         self.persistence.delete_tenant(tenant_id).await?;
    2557              : 
    2558              :         // Drop in-memory state
    2559              :         {
    2560            0 :             let mut locked = self.inner.write().unwrap();
    2561            0 :             let (_nodes, tenants, scheduler) = locked.parts_mut();
    2562              : 
    2563              :             // Dereference Scheduler from shards before dropping them
    2564            0 :             for (_tenant_shard_id, shard) in
    2565            0 :                 tenants.range_mut(TenantShardId::tenant_range(tenant_id))
    2566            0 :             {
    2567            0 :                 shard.intent.clear(scheduler);
    2568            0 :             }
    2569              : 
    2570            0 :             tenants.retain(|tenant_shard_id, _shard| tenant_shard_id.tenant_id != tenant_id);
    2571            0 :             tracing::info!(
    2572            0 :                 "Deleted tenant {tenant_id}, now have {} tenants",
    2573            0 :                 locked.tenants.len()
    2574              :             );
    2575              :         };
    2576              : 
    2577              :         // Success is represented as 404, to imitate the existing pageserver deletion API
    2578            0 :         Ok(StatusCode::NOT_FOUND)
    2579            0 :     }
    2580              : 
    2581              :     /// Naming: this configures the storage controller's policies for a tenant, whereas [`Self::tenant_config_set`] is "set the TenantConfig"
    2582              :     /// for a tenant.  The TenantConfig is passed through to pageservers, whereas this function modifies
    2583              :     /// the tenant's policies (configuration) within the storage controller
    2584            0 :     pub(crate) async fn tenant_update_policy(
    2585            0 :         &self,
    2586            0 :         tenant_id: TenantId,
    2587            0 :         req: TenantPolicyRequest,
    2588            0 :     ) -> Result<(), ApiError> {
    2589              :         // We require an exclusive lock, because we are updating persistent and in-memory state
    2590            0 :         let _tenant_lock = trace_exclusive_lock(
    2591            0 :             &self.tenant_op_locks,
    2592            0 :             tenant_id,
    2593            0 :             TenantOperations::UpdatePolicy,
    2594            0 :         )
    2595            0 :         .await;
    2596              : 
    2597            0 :         failpoint_support::sleep_millis_async!("tenant-update-policy-exclusive-lock");
    2598              : 
    2599              :         let TenantPolicyRequest {
    2600            0 :             placement,
    2601            0 :             scheduling,
    2602            0 :         } = req;
    2603            0 : 
    2604            0 :         self.persistence
    2605            0 :             .update_tenant_shard(
    2606            0 :                 TenantFilter::Tenant(tenant_id),
    2607            0 :                 placement.clone(),
    2608            0 :                 None,
    2609            0 :                 None,
    2610            0 :                 scheduling,
    2611            0 :             )
    2612            0 :             .await?;
    2613              : 
    2614            0 :         let mut schedule_context = ScheduleContext::default();
    2615            0 :         let mut locked = self.inner.write().unwrap();
    2616            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    2617            0 :         for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    2618            0 :             if let Some(placement) = &placement {
    2619            0 :                 shard.policy = placement.clone();
    2620            0 : 
    2621            0 :                 tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
    2622            0 :                                "Updated placement policy to {placement:?}");
    2623            0 :             }
    2624              : 
    2625            0 :             if let Some(scheduling) = &scheduling {
    2626            0 :                 shard.set_scheduling_policy(*scheduling);
    2627            0 : 
    2628            0 :                 tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
    2629            0 :                                "Updated scheduling policy to {scheduling:?}");
    2630            0 :             }
    2631              : 
    2632              :             // In case scheduling is being switched back on, try it now.
    2633            0 :             shard.schedule(scheduler, &mut schedule_context).ok();
    2634            0 :             self.maybe_reconcile_shard(shard, nodes);
    2635              :         }
    2636              : 
    2637            0 :         Ok(())
    2638            0 :     }
    2639              : 
    2640            0 :     pub(crate) async fn tenant_timeline_create(
    2641            0 :         &self,
    2642            0 :         tenant_id: TenantId,
    2643            0 :         mut create_req: TimelineCreateRequest,
    2644            0 :     ) -> Result<TimelineInfo, ApiError> {
    2645            0 :         tracing::info!(
    2646            0 :             "Creating timeline {}/{}",
    2647              :             tenant_id,
    2648              :             create_req.new_timeline_id,
    2649              :         );
    2650              : 
    2651            0 :         let _tenant_lock = trace_shared_lock(
    2652            0 :             &self.tenant_op_locks,
    2653            0 :             tenant_id,
    2654            0 :             TenantOperations::TimelineCreate,
    2655            0 :         )
    2656            0 :         .await;
    2657              : 
    2658            0 :         self.ensure_attached_wait(tenant_id).await?;
    2659              : 
    2660            0 :         let mut targets = {
    2661            0 :             let locked = self.inner.read().unwrap();
    2662            0 :             let mut targets = Vec::new();
    2663              : 
    2664            0 :             for (tenant_shard_id, shard) in
    2665            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    2666            0 :             {
    2667            0 :                 let node_id = shard.intent.get_attached().ok_or_else(|| {
    2668            0 :                     ApiError::InternalServerError(anyhow::anyhow!("Shard not scheduled"))
    2669            0 :                 })?;
    2670            0 :                 let node = locked
    2671            0 :                     .nodes
    2672            0 :                     .get(&node_id)
    2673            0 :                     .expect("Pageservers may not be deleted while referenced");
    2674            0 : 
    2675            0 :                 targets.push((*tenant_shard_id, node.clone()));
    2676              :             }
    2677            0 :             targets
    2678            0 :         };
    2679            0 : 
    2680            0 :         if targets.is_empty() {
    2681            0 :             return Err(ApiError::NotFound(
    2682            0 :                 anyhow::anyhow!("Tenant not found").into(),
    2683            0 :             ));
    2684            0 :         };
    2685            0 :         let shard_zero = targets.remove(0);
    2686              : 
    2687            0 :         async fn create_one(
    2688            0 :             tenant_shard_id: TenantShardId,
    2689            0 :             node: Node,
    2690            0 :             jwt: Option<String>,
    2691            0 :             create_req: TimelineCreateRequest,
    2692            0 :         ) -> Result<TimelineInfo, ApiError> {
    2693            0 :             tracing::info!(
    2694            0 :                 "Creating timeline on shard {}/{}, attached to node {node}",
    2695              :                 tenant_shard_id,
    2696              :                 create_req.new_timeline_id,
    2697              :             );
    2698            0 :             let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
    2699            0 : 
    2700            0 :             client
    2701            0 :                 .timeline_create(tenant_shard_id, &create_req)
    2702            0 :                 .await
    2703            0 :                 .map_err(|e| passthrough_api_error(&node, e))
    2704            0 :         }
    2705              : 
    2706              :         // Because the caller might not provide an explicit LSN, we must do the creation first on a single shard, and then
    2707              :         // use whatever LSN that shard picked when creating on subsequent shards.  We arbitrarily use shard zero as the shard
    2708              :         // that will get the first creation request, and propagate the LSN to all the >0 shards.
    2709            0 :         let timeline_info = create_one(
    2710            0 :             shard_zero.0,
    2711            0 :             shard_zero.1,
    2712            0 :             self.config.jwt_token.clone(),
    2713            0 :             create_req.clone(),
    2714            0 :         )
    2715            0 :         .await?;
    2716              : 
    2717              :         // Propagate the LSN that shard zero picked, if caller didn't provide one
    2718            0 :         if create_req.ancestor_timeline_id.is_some() && create_req.ancestor_start_lsn.is_none() {
    2719            0 :             create_req.ancestor_start_lsn = timeline_info.ancestor_lsn;
    2720            0 :         }
    2721              : 
    2722              :         // Create timeline on remaining shards with number >0
    2723            0 :         if !targets.is_empty() {
    2724              :             // If we had multiple shards, issue requests for the remainder now.
    2725            0 :             let jwt = self.config.jwt_token.clone();
    2726            0 :             self.tenant_for_shards(targets, |tenant_shard_id: TenantShardId, node: Node| {
    2727            0 :                 let create_req = create_req.clone();
    2728            0 :                 Box::pin(create_one(tenant_shard_id, node, jwt.clone(), create_req))
    2729            0 :             })
    2730            0 :             .await?;
    2731            0 :         }
    2732              : 
    2733            0 :         Ok(timeline_info)
    2734            0 :     }
    2735              : 
    2736              :     /// Helper for concurrently calling a pageserver API on a number of shards, such as timeline creation.
    2737              :     ///
    2738              :     /// On success, the returned vector contains exactly the same number of elements as the input `locations`.
    2739            0 :     async fn tenant_for_shards<F, R>(
    2740            0 :         &self,
    2741            0 :         locations: Vec<(TenantShardId, Node)>,
    2742            0 :         mut req_fn: F,
    2743            0 :     ) -> Result<Vec<R>, ApiError>
    2744            0 :     where
    2745            0 :         F: FnMut(
    2746            0 :             TenantShardId,
    2747            0 :             Node,
    2748            0 :         )
    2749            0 :             -> std::pin::Pin<Box<dyn futures::Future<Output = Result<R, ApiError>> + Send>>,
    2750            0 :     {
    2751            0 :         let mut futs = FuturesUnordered::new();
    2752            0 :         let mut results = Vec::with_capacity(locations.len());
    2753              : 
    2754            0 :         for (tenant_shard_id, node) in locations {
    2755            0 :             futs.push(req_fn(tenant_shard_id, node));
    2756            0 :         }
    2757              : 
    2758            0 :         while let Some(r) = futs.next().await {
    2759            0 :             results.push(r?);
    2760              :         }
    2761              : 
    2762            0 :         Ok(results)
    2763            0 :     }
    2764              : 
    2765              :     /// Concurrently invoke a pageserver API call on many shards at once
    2766            0 :     pub(crate) async fn tenant_for_shards_api<T, O, F>(
    2767            0 :         &self,
    2768            0 :         locations: Vec<(TenantShardId, Node)>,
    2769            0 :         op: O,
    2770            0 :         warn_threshold: u32,
    2771            0 :         max_retries: u32,
    2772            0 :         timeout: Duration,
    2773            0 :         cancel: &CancellationToken,
    2774            0 :     ) -> Vec<mgmt_api::Result<T>>
    2775            0 :     where
    2776            0 :         O: Fn(TenantShardId, PageserverClient) -> F + Copy,
    2777            0 :         F: std::future::Future<Output = mgmt_api::Result<T>>,
    2778            0 :     {
    2779            0 :         let mut futs = FuturesUnordered::new();
    2780            0 :         let mut results = Vec::with_capacity(locations.len());
    2781              : 
    2782            0 :         for (tenant_shard_id, node) in locations {
    2783            0 :             futs.push(async move {
    2784            0 :                 node.with_client_retries(
    2785            0 :                     |client| op(tenant_shard_id, client),
    2786            0 :                     &self.config.jwt_token,
    2787            0 :                     warn_threshold,
    2788            0 :                     max_retries,
    2789            0 :                     timeout,
    2790            0 :                     cancel,
    2791            0 :                 )
    2792            0 :                 .await
    2793            0 :             });
    2794            0 :         }
    2795              : 
    2796            0 :         while let Some(r) = futs.next().await {
    2797            0 :             let r = r.unwrap_or(Err(mgmt_api::Error::Cancelled));
    2798            0 :             results.push(r);
    2799            0 :         }
    2800              : 
    2801            0 :         results
    2802            0 :     }
    2803              : 
    2804            0 :     pub(crate) async fn tenant_timeline_delete(
    2805            0 :         &self,
    2806            0 :         tenant_id: TenantId,
    2807            0 :         timeline_id: TimelineId,
    2808            0 :     ) -> Result<StatusCode, ApiError> {
    2809            0 :         tracing::info!("Deleting timeline {}/{}", tenant_id, timeline_id,);
    2810            0 :         let _tenant_lock = trace_shared_lock(
    2811            0 :             &self.tenant_op_locks,
    2812            0 :             tenant_id,
    2813            0 :             TenantOperations::TimelineDelete,
    2814            0 :         )
    2815            0 :         .await;
    2816              : 
    2817            0 :         self.ensure_attached_wait(tenant_id).await?;
    2818              : 
    2819            0 :         let mut targets = {
    2820            0 :             let locked = self.inner.read().unwrap();
    2821            0 :             let mut targets = Vec::new();
    2822              : 
    2823            0 :             for (tenant_shard_id, shard) in
    2824            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    2825            0 :             {
    2826            0 :                 let node_id = shard.intent.get_attached().ok_or_else(|| {
    2827            0 :                     ApiError::InternalServerError(anyhow::anyhow!("Shard not scheduled"))
    2828            0 :                 })?;
    2829            0 :                 let node = locked
    2830            0 :                     .nodes
    2831            0 :                     .get(&node_id)
    2832            0 :                     .expect("Pageservers may not be deleted while referenced");
    2833            0 : 
    2834            0 :                 targets.push((*tenant_shard_id, node.clone()));
    2835              :             }
    2836            0 :             targets
    2837            0 :         };
    2838            0 : 
    2839            0 :         if targets.is_empty() {
    2840            0 :             return Err(ApiError::NotFound(
    2841            0 :                 anyhow::anyhow!("Tenant not found").into(),
    2842            0 :             ));
    2843            0 :         }
    2844            0 :         let shard_zero = targets.remove(0);
    2845              : 
    2846            0 :         async fn delete_one(
    2847            0 :             tenant_shard_id: TenantShardId,
    2848            0 :             timeline_id: TimelineId,
    2849            0 :             node: Node,
    2850            0 :             jwt: Option<String>,
    2851            0 :         ) -> Result<StatusCode, ApiError> {
    2852            0 :             tracing::info!(
    2853            0 :                 "Deleting timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
    2854              :             );
    2855              : 
    2856            0 :             let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
    2857            0 :             client
    2858            0 :                 .timeline_delete(tenant_shard_id, timeline_id)
    2859            0 :                 .await
    2860            0 :                 .map_err(|e| {
    2861            0 :                     ApiError::InternalServerError(anyhow::anyhow!(
    2862            0 :                     "Error deleting timeline {timeline_id} on {tenant_shard_id} on node {node}: {e}",
    2863            0 :                 ))
    2864            0 :                 })
    2865            0 :         }
    2866              : 
    2867            0 :         let statuses = self
    2868            0 :             .tenant_for_shards(targets, |tenant_shard_id: TenantShardId, node: Node| {
    2869            0 :                 Box::pin(delete_one(
    2870            0 :                     tenant_shard_id,
    2871            0 :                     timeline_id,
    2872            0 :                     node,
    2873            0 :                     self.config.jwt_token.clone(),
    2874            0 :                 ))
    2875            0 :             })
    2876            0 :             .await?;
    2877              : 
    2878              :         // If any shards >0 haven't finished deletion yet, don't start deletion on shard zero
    2879            0 :         if statuses.iter().any(|s| s != &StatusCode::NOT_FOUND) {
    2880            0 :             return Ok(StatusCode::ACCEPTED);
    2881            0 :         }
    2882              : 
    2883              :         // Delete shard zero last: this is not strictly necessary, but since a caller's GET on a timeline will be routed
    2884              :         // to shard zero, it gives a more obvious behavior that a GET returns 404 once the deletion is done.
    2885            0 :         let shard_zero_status = delete_one(
    2886            0 :             shard_zero.0,
    2887            0 :             timeline_id,
    2888            0 :             shard_zero.1,
    2889            0 :             self.config.jwt_token.clone(),
    2890            0 :         )
    2891            0 :         .await?;
    2892              : 
    2893            0 :         Ok(shard_zero_status)
    2894            0 :     }
    2895              : 
    2896              :     /// When you need to send an HTTP request to the pageserver that holds shard0 of a tenant, this
    2897              :     /// function looks up and returns node. If the tenant isn't found, returns Err(ApiError::NotFound)
    2898            0 :     pub(crate) fn tenant_shard0_node(
    2899            0 :         &self,
    2900            0 :         tenant_id: TenantId,
    2901            0 :     ) -> Result<(Node, TenantShardId), ApiError> {
    2902            0 :         let locked = self.inner.read().unwrap();
    2903            0 :         let Some((tenant_shard_id, shard)) = locked
    2904            0 :             .tenants
    2905            0 :             .range(TenantShardId::tenant_range(tenant_id))
    2906            0 :             .next()
    2907              :         else {
    2908            0 :             return Err(ApiError::NotFound(
    2909            0 :                 anyhow::anyhow!("Tenant {tenant_id} not found").into(),
    2910            0 :             ));
    2911              :         };
    2912              : 
    2913              :         // TODO: should use the ID last published to compute_hook, rather than the intent: the intent might
    2914              :         // point to somewhere we haven't attached yet.
    2915            0 :         let Some(node_id) = shard.intent.get_attached() else {
    2916            0 :             tracing::warn!(
    2917            0 :                 tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
    2918            0 :                 "Shard not scheduled (policy {:?}), cannot generate pass-through URL",
    2919              :                 shard.policy
    2920              :             );
    2921            0 :             return Err(ApiError::Conflict(
    2922            0 :                 "Cannot call timeline API on non-attached tenant".to_string(),
    2923            0 :             ));
    2924              :         };
    2925              : 
    2926            0 :         let Some(node) = locked.nodes.get(node_id) else {
    2927              :             // This should never happen
    2928            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    2929            0 :                 "Shard refers to nonexistent node"
    2930            0 :             )));
    2931              :         };
    2932              : 
    2933            0 :         Ok((node.clone(), *tenant_shard_id))
    2934            0 :     }
    2935              : 
    2936            0 :     pub(crate) fn tenant_locate(
    2937            0 :         &self,
    2938            0 :         tenant_id: TenantId,
    2939            0 :     ) -> Result<TenantLocateResponse, ApiError> {
    2940            0 :         let locked = self.inner.read().unwrap();
    2941            0 :         tracing::info!("Locating shards for tenant {tenant_id}");
    2942              : 
    2943            0 :         let mut result = Vec::new();
    2944            0 :         let mut shard_params: Option<ShardParameters> = None;
    2945              : 
    2946            0 :         for (tenant_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    2947              :         {
    2948            0 :             let node_id =
    2949            0 :                 shard
    2950            0 :                     .intent
    2951            0 :                     .get_attached()
    2952            0 :                     .ok_or(ApiError::BadRequest(anyhow::anyhow!(
    2953            0 :                         "Cannot locate a tenant that is not attached"
    2954            0 :                     )))?;
    2955              : 
    2956            0 :             let node = locked
    2957            0 :                 .nodes
    2958            0 :                 .get(&node_id)
    2959            0 :                 .expect("Pageservers may not be deleted while referenced");
    2960            0 : 
    2961            0 :             result.push(node.shard_location(*tenant_shard_id));
    2962            0 : 
    2963            0 :             match &shard_params {
    2964            0 :                 None => {
    2965            0 :                     shard_params = Some(ShardParameters {
    2966            0 :                         stripe_size: shard.shard.stripe_size,
    2967            0 :                         count: shard.shard.count,
    2968            0 :                     });
    2969            0 :                 }
    2970            0 :                 Some(params) => {
    2971            0 :                     if params.stripe_size != shard.shard.stripe_size {
    2972              :                         // This should never happen.  We enforce at runtime because it's simpler than
    2973              :                         // adding an extra per-tenant data structure to store the things that should be the same
    2974            0 :                         return Err(ApiError::InternalServerError(anyhow::anyhow!(
    2975            0 :                             "Inconsistent shard stripe size parameters!"
    2976            0 :                         )));
    2977            0 :                     }
    2978              :                 }
    2979              :             }
    2980              :         }
    2981              : 
    2982            0 :         if result.is_empty() {
    2983            0 :             return Err(ApiError::NotFound(
    2984            0 :                 anyhow::anyhow!("No shards for this tenant ID found").into(),
    2985            0 :             ));
    2986            0 :         }
    2987            0 :         let shard_params = shard_params.expect("result is non-empty, therefore this is set");
    2988            0 :         tracing::info!(
    2989            0 :             "Located tenant {} with params {:?} on shards {}",
    2990            0 :             tenant_id,
    2991            0 :             shard_params,
    2992            0 :             result
    2993            0 :                 .iter()
    2994            0 :                 .map(|s| format!("{:?}", s))
    2995            0 :                 .collect::<Vec<_>>()
    2996            0 :                 .join(",")
    2997              :         );
    2998              : 
    2999            0 :         Ok(TenantLocateResponse {
    3000            0 :             shards: result,
    3001            0 :             shard_params,
    3002            0 :         })
    3003            0 :     }
    3004              : 
    3005              :     /// Returns None if the input iterator of shards does not include a shard with number=0
    3006            0 :     fn tenant_describe_impl<'a>(
    3007            0 :         &self,
    3008            0 :         shards: impl Iterator<Item = &'a TenantShard>,
    3009            0 :     ) -> Option<TenantDescribeResponse> {
    3010            0 :         let mut shard_zero = None;
    3011            0 :         let mut describe_shards = Vec::new();
    3012              : 
    3013            0 :         for shard in shards {
    3014            0 :             if shard.tenant_shard_id.is_shard_zero() {
    3015            0 :                 shard_zero = Some(shard);
    3016            0 :             }
    3017              : 
    3018            0 :             describe_shards.push(TenantDescribeResponseShard {
    3019            0 :                 tenant_shard_id: shard.tenant_shard_id,
    3020            0 :                 node_attached: *shard.intent.get_attached(),
    3021            0 :                 node_secondary: shard.intent.get_secondary().to_vec(),
    3022            0 :                 last_error: shard
    3023            0 :                     .last_error
    3024            0 :                     .lock()
    3025            0 :                     .unwrap()
    3026            0 :                     .as_ref()
    3027            0 :                     .map(|e| format!("{e}"))
    3028            0 :                     .unwrap_or("".to_string())
    3029            0 :                     .clone(),
    3030            0 :                 is_reconciling: shard.reconciler.is_some(),
    3031            0 :                 is_pending_compute_notification: shard.pending_compute_notification,
    3032            0 :                 is_splitting: matches!(shard.splitting, SplitState::Splitting),
    3033            0 :                 scheduling_policy: *shard.get_scheduling_policy(),
    3034              :             })
    3035              :         }
    3036              : 
    3037            0 :         let shard_zero = shard_zero?;
    3038              : 
    3039            0 :         Some(TenantDescribeResponse {
    3040            0 :             tenant_id: shard_zero.tenant_shard_id.tenant_id,
    3041            0 :             shards: describe_shards,
    3042            0 :             stripe_size: shard_zero.shard.stripe_size,
    3043            0 :             policy: shard_zero.policy.clone(),
    3044            0 :             config: shard_zero.config.clone(),
    3045            0 :         })
    3046            0 :     }
    3047              : 
    3048            0 :     pub(crate) fn tenant_describe(
    3049            0 :         &self,
    3050            0 :         tenant_id: TenantId,
    3051            0 :     ) -> Result<TenantDescribeResponse, ApiError> {
    3052            0 :         let locked = self.inner.read().unwrap();
    3053            0 : 
    3054            0 :         self.tenant_describe_impl(
    3055            0 :             locked
    3056            0 :                 .tenants
    3057            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    3058            0 :                 .map(|(_k, v)| v),
    3059            0 :         )
    3060            0 :         .ok_or_else(|| ApiError::NotFound(anyhow::anyhow!("Tenant {tenant_id} not found").into()))
    3061            0 :     }
    3062              : 
    3063            0 :     pub(crate) fn tenant_list(&self) -> Vec<TenantDescribeResponse> {
    3064            0 :         let locked = self.inner.read().unwrap();
    3065            0 : 
    3066            0 :         let mut result = Vec::new();
    3067            0 :         for (_tenant_id, tenant_shards) in
    3068            0 :             &locked.tenants.iter().group_by(|(id, _shard)| id.tenant_id)
    3069            0 :         {
    3070            0 :             result.push(
    3071            0 :                 self.tenant_describe_impl(tenant_shards.map(|(_k, v)| v))
    3072            0 :                     .expect("Groups are always non-empty"),
    3073            0 :             );
    3074            0 :         }
    3075              : 
    3076            0 :         result
    3077            0 :     }
    3078              : 
    3079            0 :     #[instrument(skip_all, fields(tenant_id=%op.tenant_id))]
    3080              :     async fn abort_tenant_shard_split(
    3081              :         &self,
    3082              :         op: &TenantShardSplitAbort,
    3083              :     ) -> Result<(), TenantShardSplitAbortError> {
    3084              :         // Cleaning up a split:
    3085              :         // - Parent shards are not destroyed during a split, just detached.
    3086              :         // - Failed pageserver split API calls can leave the remote node with just the parent attached,
    3087              :         //   just the children attached, or both.
    3088              :         //
    3089              :         // Therefore our work to do is to:
    3090              :         // 1. Clean up storage controller's internal state to just refer to parents, no children
    3091              :         // 2. Call out to pageservers to ensure that children are detached
    3092              :         // 3. Call out to pageservers to ensure that parents are attached.
    3093              :         //
    3094              :         // Crash safety:
    3095              :         // - If the storage controller stops running during this cleanup *after* clearing the splitting state
    3096              :         //   from our database, then [`Self::startup_reconcile`] will regard child attachments as garbage
    3097              :         //   and detach them.
    3098              :         // - TODO: If the storage controller stops running during this cleanup *before* clearing the splitting state
    3099              :         //   from our database, then we will re-enter this cleanup routine on startup.
    3100              : 
    3101              :         let TenantShardSplitAbort {
    3102              :             tenant_id,
    3103              :             new_shard_count,
    3104              :             new_stripe_size,
    3105              :             ..
    3106              :         } = op;
    3107              : 
    3108              :         // First abort persistent state, if any exists.
    3109              :         match self
    3110              :             .persistence
    3111              :             .abort_shard_split(*tenant_id, *new_shard_count)
    3112              :             .await?
    3113              :         {
    3114              :             AbortShardSplitStatus::Aborted => {
    3115              :                 // Proceed to roll back any child shards created on pageservers
    3116              :             }
    3117              :             AbortShardSplitStatus::Complete => {
    3118              :                 // The split completed (we might hit that path if e.g. our database transaction
    3119              :                 // to write the completion landed in the database, but we dropped connection
    3120              :                 // before seeing the result).
    3121              :                 //
    3122              :                 // We must update in-memory state to reflect the successful split.
    3123              :                 self.tenant_shard_split_commit_inmem(
    3124              :                     *tenant_id,
    3125              :                     *new_shard_count,
    3126              :                     *new_stripe_size,
    3127              :                 );
    3128              :                 return Ok(());
    3129              :             }
    3130              :         }
    3131              : 
    3132              :         // Clean up in-memory state, and accumulate the list of child locations that need detaching
    3133              :         let detach_locations: Vec<(Node, TenantShardId)> = {
    3134              :             let mut detach_locations = Vec::new();
    3135              :             let mut locked = self.inner.write().unwrap();
    3136              :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3137              : 
    3138              :             for (tenant_shard_id, shard) in
    3139              :                 tenants.range_mut(TenantShardId::tenant_range(op.tenant_id))
    3140              :             {
    3141              :                 if shard.shard.count == op.new_shard_count {
    3142              :                     // Surprising: the phase of [`Self::do_tenant_shard_split`] which inserts child shards in-memory
    3143              :                     // is infallible, so if we got an error we shouldn't have got that far.
    3144              :                     tracing::warn!(
    3145              :                         "During split abort, child shard {tenant_shard_id} found in-memory"
    3146              :                     );
    3147              :                     continue;
    3148              :                 }
    3149              : 
    3150              :                 // Add the children of this shard to this list of things to detach
    3151              :                 if let Some(node_id) = shard.intent.get_attached() {
    3152              :                     for child_id in tenant_shard_id.split(*new_shard_count) {
    3153              :                         detach_locations.push((
    3154              :                             nodes
    3155              :                                 .get(node_id)
    3156              :                                 .expect("Intent references nonexistent node")
    3157              :                                 .clone(),
    3158              :                             child_id,
    3159              :                         ));
    3160              :                     }
    3161              :                 } else {
    3162              :                     tracing::warn!(
    3163              :                         "During split abort, shard {tenant_shard_id} has no attached location"
    3164              :                     );
    3165              :                 }
    3166              : 
    3167              :                 tracing::info!("Restoring parent shard {tenant_shard_id}");
    3168              :                 shard.splitting = SplitState::Idle;
    3169              :                 if let Err(e) = shard.schedule(scheduler, &mut ScheduleContext::default()) {
    3170              :                     // If this shard can't be scheduled now (perhaps due to offline nodes or
    3171              :                     // capacity issues), that must not prevent us rolling back a split.  In this
    3172              :                     // case it should be eventually scheduled in the background.
    3173              :                     tracing::warn!("Failed to schedule {tenant_shard_id} during shard abort: {e}")
    3174              :                 }
    3175              : 
    3176              :                 self.maybe_reconcile_shard(shard, nodes);
    3177              :             }
    3178              : 
    3179              :             // We don't expect any new_shard_count shards to exist here, but drop them just in case
    3180            0 :             tenants.retain(|_id, s| s.shard.count != *new_shard_count);
    3181              : 
    3182              :             detach_locations
    3183              :         };
    3184              : 
    3185              :         for (node, child_id) in detach_locations {
    3186              :             if !node.is_available() {
    3187              :                 // An unavailable node cannot be cleaned up now: to avoid blocking forever, we will permit this, and
    3188              :                 // rely on the reconciliation that happens when a node transitions to Active to clean up. Since we have
    3189              :                 // removed child shards from our in-memory state and database, the reconciliation will implicitly remove
    3190              :                 // them from the node.
    3191              :                 tracing::warn!("Node {node} unavailable, can't clean up during split abort. It will be cleaned up when it is reactivated.");
    3192              :                 continue;
    3193              :             }
    3194              : 
    3195              :             // Detach the remote child.  If the pageserver split API call is still in progress, this call will get
    3196              :             // a 503 and retry, up to our limit.
    3197              :             tracing::info!("Detaching {child_id} on {node}...");
    3198              :             match node
    3199              :                 .with_client_retries(
    3200            0 :                     |client| async move {
    3201            0 :                         let config = LocationConfig {
    3202            0 :                             mode: LocationConfigMode::Detached,
    3203            0 :                             generation: None,
    3204            0 :                             secondary_conf: None,
    3205            0 :                             shard_number: child_id.shard_number.0,
    3206            0 :                             shard_count: child_id.shard_count.literal(),
    3207            0 :                             // Stripe size and tenant config don't matter when detaching
    3208            0 :                             shard_stripe_size: 0,
    3209            0 :                             tenant_conf: TenantConfig::default(),
    3210            0 :                         };
    3211            0 : 
    3212            0 :                         client.location_config(child_id, config, None, false).await
    3213            0 :                     },
    3214              :                     &self.config.jwt_token,
    3215              :                     1,
    3216              :                     10,
    3217              :                     Duration::from_secs(5),
    3218              :                     &self.cancel,
    3219              :                 )
    3220              :                 .await
    3221              :             {
    3222              :                 Some(Ok(_)) => {}
    3223              :                 Some(Err(e)) => {
    3224              :                     // We failed to communicate with the remote node.  This is problematic: we may be
    3225              :                     // leaving it with a rogue child shard.
    3226              :                     tracing::warn!(
    3227              :                         "Failed to detach child {child_id} from node {node} during abort"
    3228              :                     );
    3229              :                     return Err(e.into());
    3230              :                 }
    3231              :                 None => {
    3232              :                     // Cancellation: we were shutdown or the node went offline. Shutdown is fine, we'll
    3233              :                     // clean up on restart. The node going offline requires a retry.
    3234              :                     return Err(TenantShardSplitAbortError::Unavailable);
    3235              :                 }
    3236              :             };
    3237              :         }
    3238              : 
    3239              :         tracing::info!("Successfully aborted split");
    3240              :         Ok(())
    3241              :     }
    3242              : 
    3243              :     /// Infallible final stage of [`Self::tenant_shard_split`]: update the contents
    3244              :     /// of the tenant map to reflect the child shards that exist after the split.
    3245            0 :     fn tenant_shard_split_commit_inmem(
    3246            0 :         &self,
    3247            0 :         tenant_id: TenantId,
    3248            0 :         new_shard_count: ShardCount,
    3249            0 :         new_stripe_size: Option<ShardStripeSize>,
    3250            0 :     ) -> (
    3251            0 :         TenantShardSplitResponse,
    3252            0 :         Vec<(TenantShardId, NodeId, ShardStripeSize)>,
    3253            0 :         Vec<ReconcilerWaiter>,
    3254            0 :     ) {
    3255            0 :         let mut response = TenantShardSplitResponse {
    3256            0 :             new_shards: Vec::new(),
    3257            0 :         };
    3258            0 :         let mut child_locations = Vec::new();
    3259            0 :         let mut waiters = Vec::new();
    3260            0 : 
    3261            0 :         {
    3262            0 :             let mut locked = self.inner.write().unwrap();
    3263            0 : 
    3264            0 :             let parent_ids = locked
    3265            0 :                 .tenants
    3266            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    3267            0 :                 .map(|(shard_id, _)| *shard_id)
    3268            0 :                 .collect::<Vec<_>>();
    3269            0 : 
    3270            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3271            0 :             for parent_id in parent_ids {
    3272            0 :                 let child_ids = parent_id.split(new_shard_count);
    3273              : 
    3274            0 :                 let (pageserver, generation, policy, parent_ident, config) = {
    3275            0 :                     let mut old_state = tenants
    3276            0 :                         .remove(&parent_id)
    3277            0 :                         .expect("It was present, we just split it");
    3278            0 : 
    3279            0 :                     // A non-splitting state is impossible, because [`Self::tenant_shard_split`] holds
    3280            0 :                     // a TenantId lock and passes it through to [`TenantShardSplitAbort`] in case of cleanup:
    3281            0 :                     // nothing else can clear this.
    3282            0 :                     assert!(matches!(old_state.splitting, SplitState::Splitting));
    3283              : 
    3284            0 :                     let old_attached = old_state.intent.get_attached().unwrap();
    3285            0 :                     old_state.intent.clear(scheduler);
    3286            0 :                     let generation = old_state.generation.expect("Shard must have been attached");
    3287            0 :                     (
    3288            0 :                         old_attached,
    3289            0 :                         generation,
    3290            0 :                         old_state.policy,
    3291            0 :                         old_state.shard,
    3292            0 :                         old_state.config,
    3293            0 :                     )
    3294            0 :                 };
    3295            0 : 
    3296            0 :                 let mut schedule_context = ScheduleContext::default();
    3297            0 :                 for child in child_ids {
    3298            0 :                     let mut child_shard = parent_ident;
    3299            0 :                     child_shard.number = child.shard_number;
    3300            0 :                     child_shard.count = child.shard_count;
    3301            0 :                     if let Some(stripe_size) = new_stripe_size {
    3302            0 :                         child_shard.stripe_size = stripe_size;
    3303            0 :                     }
    3304              : 
    3305            0 :                     let mut child_observed: HashMap<NodeId, ObservedStateLocation> = HashMap::new();
    3306            0 :                     child_observed.insert(
    3307            0 :                         pageserver,
    3308            0 :                         ObservedStateLocation {
    3309            0 :                             conf: Some(attached_location_conf(
    3310            0 :                                 generation,
    3311            0 :                                 &child_shard,
    3312            0 :                                 &config,
    3313            0 :                                 matches!(policy, PlacementPolicy::Attached(n) if n > 0),
    3314              :                             )),
    3315              :                         },
    3316              :                     );
    3317              : 
    3318            0 :                     let mut child_state = TenantShard::new(child, child_shard, policy.clone());
    3319            0 :                     child_state.intent = IntentState::single(scheduler, Some(pageserver));
    3320            0 :                     child_state.observed = ObservedState {
    3321            0 :                         locations: child_observed,
    3322            0 :                     };
    3323            0 :                     child_state.generation = Some(generation);
    3324            0 :                     child_state.config = config.clone();
    3325            0 : 
    3326            0 :                     // The child's TenantShard::splitting is intentionally left at the default value of Idle,
    3327            0 :                     // as at this point in the split process we have succeeded and this part is infallible:
    3328            0 :                     // we will never need to do any special recovery from this state.
    3329            0 : 
    3330            0 :                     child_locations.push((child, pageserver, child_shard.stripe_size));
    3331              : 
    3332            0 :                     if let Err(e) = child_state.schedule(scheduler, &mut schedule_context) {
    3333              :                         // This is not fatal, because we've implicitly already got an attached
    3334              :                         // location for the child shard.  Failure here just means we couldn't
    3335              :                         // find a secondary (e.g. because cluster is overloaded).
    3336            0 :                         tracing::warn!("Failed to schedule child shard {child}: {e}");
    3337            0 :                     }
    3338              :                     // In the background, attach secondary locations for the new shards
    3339            0 :                     if let Some(waiter) = self.maybe_reconcile_shard(&mut child_state, nodes) {
    3340            0 :                         waiters.push(waiter);
    3341            0 :                     }
    3342              : 
    3343            0 :                     tenants.insert(child, child_state);
    3344            0 :                     response.new_shards.push(child);
    3345              :                 }
    3346              :             }
    3347            0 :             (response, child_locations, waiters)
    3348            0 :         }
    3349            0 :     }
    3350              : 
    3351            0 :     async fn tenant_shard_split_start_secondaries(
    3352            0 :         &self,
    3353            0 :         tenant_id: TenantId,
    3354            0 :         waiters: Vec<ReconcilerWaiter>,
    3355            0 :     ) {
    3356              :         // Wait for initial reconcile of child shards, this creates the secondary locations
    3357            0 :         if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    3358              :             // This is not a failure to split: it's some issue reconciling the new child shards, perhaps
    3359              :             // their secondaries couldn't be attached.
    3360            0 :             tracing::warn!("Failed to reconcile after split: {e}");
    3361            0 :             return;
    3362            0 :         }
    3363              : 
    3364              :         // Take the state lock to discover the attached & secondary intents for all shards
    3365            0 :         let (attached, secondary) = {
    3366            0 :             let locked = self.inner.read().unwrap();
    3367            0 :             let mut attached = Vec::new();
    3368            0 :             let mut secondary = Vec::new();
    3369              : 
    3370            0 :             for (tenant_shard_id, shard) in
    3371            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    3372              :             {
    3373            0 :                 let Some(node_id) = shard.intent.get_attached() else {
    3374              :                     // Unexpected.  Race with a PlacementPolicy change?
    3375            0 :                     tracing::warn!(
    3376            0 :                         "No attached node on {tenant_shard_id} immediately after shard split!"
    3377              :                     );
    3378            0 :                     continue;
    3379              :                 };
    3380              : 
    3381            0 :                 let Some(secondary_node_id) = shard.intent.get_secondary().first() else {
    3382              :                     // No secondary location.  Nothing for us to do.
    3383            0 :                     continue;
    3384              :                 };
    3385              : 
    3386            0 :                 let attached_node = locked
    3387            0 :                     .nodes
    3388            0 :                     .get(node_id)
    3389            0 :                     .expect("Pageservers may not be deleted while referenced");
    3390            0 : 
    3391            0 :                 let secondary_node = locked
    3392            0 :                     .nodes
    3393            0 :                     .get(secondary_node_id)
    3394            0 :                     .expect("Pageservers may not be deleted while referenced");
    3395            0 : 
    3396            0 :                 attached.push((*tenant_shard_id, attached_node.clone()));
    3397            0 :                 secondary.push((*tenant_shard_id, secondary_node.clone()));
    3398              :             }
    3399            0 :             (attached, secondary)
    3400            0 :         };
    3401            0 : 
    3402            0 :         if secondary.is_empty() {
    3403              :             // No secondary locations; nothing for us to do
    3404            0 :             return;
    3405            0 :         }
    3406              : 
    3407            0 :         for result in self
    3408            0 :             .tenant_for_shards_api(
    3409            0 :                 attached,
    3410            0 :                 |tenant_shard_id, client| async move {
    3411            0 :                     client.tenant_heatmap_upload(tenant_shard_id).await
    3412            0 :                 },
    3413            0 :                 1,
    3414            0 :                 1,
    3415            0 :                 SHORT_RECONCILE_TIMEOUT,
    3416            0 :                 &self.cancel,
    3417            0 :             )
    3418            0 :             .await
    3419              :         {
    3420            0 :             if let Err(e) = result {
    3421            0 :                 tracing::warn!("Error calling heatmap upload after shard split: {e}");
    3422            0 :                 return;
    3423            0 :             }
    3424              :         }
    3425              : 
    3426            0 :         for result in self
    3427            0 :             .tenant_for_shards_api(
    3428            0 :                 secondary,
    3429            0 :                 |tenant_shard_id, client| async move {
    3430            0 :                     client
    3431            0 :                         .tenant_secondary_download(tenant_shard_id, Some(Duration::ZERO))
    3432            0 :                         .await
    3433            0 :                 },
    3434            0 :                 1,
    3435            0 :                 1,
    3436            0 :                 SHORT_RECONCILE_TIMEOUT,
    3437            0 :                 &self.cancel,
    3438            0 :             )
    3439            0 :             .await
    3440              :         {
    3441            0 :             if let Err(e) = result {
    3442            0 :                 tracing::warn!("Error calling secondary download after shard split: {e}");
    3443            0 :                 return;
    3444            0 :             }
    3445              :         }
    3446            0 :     }
    3447              : 
    3448            0 :     pub(crate) async fn tenant_shard_split(
    3449            0 :         &self,
    3450            0 :         tenant_id: TenantId,
    3451            0 :         split_req: TenantShardSplitRequest,
    3452            0 :     ) -> Result<TenantShardSplitResponse, ApiError> {
    3453              :         // TODO: return 503 if we get stuck waiting for this lock
    3454              :         // (issue https://github.com/neondatabase/neon/issues/7108)
    3455            0 :         let _tenant_lock = trace_exclusive_lock(
    3456            0 :             &self.tenant_op_locks,
    3457            0 :             tenant_id,
    3458            0 :             TenantOperations::ShardSplit,
    3459            0 :         )
    3460            0 :         .await;
    3461              : 
    3462            0 :         let new_shard_count = ShardCount::new(split_req.new_shard_count);
    3463            0 :         let new_stripe_size = split_req.new_stripe_size;
    3464              : 
    3465              :         // Validate the request and construct parameters.  This phase is fallible, but does not require
    3466              :         // rollback on errors, as it does no I/O and mutates no state.
    3467            0 :         let shard_split_params = match self.prepare_tenant_shard_split(tenant_id, split_req)? {
    3468            0 :             ShardSplitAction::NoOp(resp) => return Ok(resp),
    3469            0 :             ShardSplitAction::Split(params) => params,
    3470              :         };
    3471              : 
    3472              :         // Execute this split: this phase mutates state and does remote I/O on pageservers.  If it fails,
    3473              :         // we must roll back.
    3474            0 :         let r = self
    3475            0 :             .do_tenant_shard_split(tenant_id, shard_split_params)
    3476            0 :             .await;
    3477              : 
    3478            0 :         let (response, waiters) = match r {
    3479            0 :             Ok(r) => r,
    3480            0 :             Err(e) => {
    3481            0 :                 // Split might be part-done, we must do work to abort it.
    3482            0 :                 tracing::warn!("Enqueuing background abort of split on {tenant_id}");
    3483            0 :                 self.abort_tx
    3484            0 :                     .send(TenantShardSplitAbort {
    3485            0 :                         tenant_id,
    3486            0 :                         new_shard_count,
    3487            0 :                         new_stripe_size,
    3488            0 :                         _tenant_lock,
    3489            0 :                     })
    3490            0 :                     // Ignore error sending: that just means we're shutting down: aborts are ephemeral so it's fine to drop it.
    3491            0 :                     .ok();
    3492            0 :                 return Err(e);
    3493              :             }
    3494              :         };
    3495              : 
    3496              :         // The split is now complete.  As an optimization, we will trigger all the child shards to upload
    3497              :         // a heatmap immediately, and all their secondary locations to start downloading: this avoids waiting
    3498              :         // for the background heatmap/download interval before secondaries get warm enough to migrate shards
    3499              :         // in [`Self::optimize_all`]
    3500            0 :         self.tenant_shard_split_start_secondaries(tenant_id, waiters)
    3501            0 :             .await;
    3502            0 :         Ok(response)
    3503            0 :     }
    3504              : 
    3505            0 :     fn prepare_tenant_shard_split(
    3506            0 :         &self,
    3507            0 :         tenant_id: TenantId,
    3508            0 :         split_req: TenantShardSplitRequest,
    3509            0 :     ) -> Result<ShardSplitAction, ApiError> {
    3510            0 :         fail::fail_point!("shard-split-validation", |_| Err(ApiError::BadRequest(
    3511            0 :             anyhow::anyhow!("failpoint")
    3512            0 :         )));
    3513              : 
    3514            0 :         let mut policy = None;
    3515            0 :         let mut config = None;
    3516            0 :         let mut shard_ident = None;
    3517              :         // Validate input, and calculate which shards we will create
    3518            0 :         let (old_shard_count, targets) =
    3519              :             {
    3520            0 :                 let locked = self.inner.read().unwrap();
    3521            0 : 
    3522            0 :                 let pageservers = locked.nodes.clone();
    3523            0 : 
    3524            0 :                 let mut targets = Vec::new();
    3525            0 : 
    3526            0 :                 // In case this is a retry, count how many already-split shards we found
    3527            0 :                 let mut children_found = Vec::new();
    3528            0 :                 let mut old_shard_count = None;
    3529              : 
    3530            0 :                 for (tenant_shard_id, shard) in
    3531            0 :                     locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    3532              :                 {
    3533            0 :                     match shard.shard.count.count().cmp(&split_req.new_shard_count) {
    3534              :                         Ordering::Equal => {
    3535              :                             //  Already split this
    3536            0 :                             children_found.push(*tenant_shard_id);
    3537            0 :                             continue;
    3538              :                         }
    3539              :                         Ordering::Greater => {
    3540            0 :                             return Err(ApiError::BadRequest(anyhow::anyhow!(
    3541            0 :                                 "Requested count {} but already have shards at count {}",
    3542            0 :                                 split_req.new_shard_count,
    3543            0 :                                 shard.shard.count.count()
    3544            0 :                             )));
    3545              :                         }
    3546            0 :                         Ordering::Less => {
    3547            0 :                             // Fall through: this shard has lower count than requested,
    3548            0 :                             // is a candidate for splitting.
    3549            0 :                         }
    3550            0 :                     }
    3551            0 : 
    3552            0 :                     match old_shard_count {
    3553            0 :                         None => old_shard_count = Some(shard.shard.count),
    3554            0 :                         Some(old_shard_count) => {
    3555            0 :                             if old_shard_count != shard.shard.count {
    3556              :                                 // We may hit this case if a caller asked for two splits to
    3557              :                                 // different sizes, before the first one is complete.
    3558              :                                 // e.g. 1->2, 2->4, where the 4 call comes while we have a mixture
    3559              :                                 // of shard_count=1 and shard_count=2 shards in the map.
    3560            0 :                                 return Err(ApiError::Conflict(
    3561            0 :                                     "Cannot split, currently mid-split".to_string(),
    3562            0 :                                 ));
    3563            0 :                             }
    3564              :                         }
    3565              :                     }
    3566            0 :                     if policy.is_none() {
    3567            0 :                         policy = Some(shard.policy.clone());
    3568            0 :                     }
    3569            0 :                     if shard_ident.is_none() {
    3570            0 :                         shard_ident = Some(shard.shard);
    3571            0 :                     }
    3572            0 :                     if config.is_none() {
    3573            0 :                         config = Some(shard.config.clone());
    3574            0 :                     }
    3575              : 
    3576            0 :                     if tenant_shard_id.shard_count.count() == split_req.new_shard_count {
    3577            0 :                         tracing::info!(
    3578            0 :                             "Tenant shard {} already has shard count {}",
    3579              :                             tenant_shard_id,
    3580              :                             split_req.new_shard_count
    3581              :                         );
    3582            0 :                         continue;
    3583            0 :                     }
    3584              : 
    3585            0 :                     let node_id = shard.intent.get_attached().ok_or(ApiError::BadRequest(
    3586            0 :                         anyhow::anyhow!("Cannot split a tenant that is not attached"),
    3587            0 :                     ))?;
    3588              : 
    3589            0 :                     let node = pageservers
    3590            0 :                         .get(&node_id)
    3591            0 :                         .expect("Pageservers may not be deleted while referenced");
    3592            0 : 
    3593            0 :                     targets.push(ShardSplitTarget {
    3594            0 :                         parent_id: *tenant_shard_id,
    3595            0 :                         node: node.clone(),
    3596            0 :                         child_ids: tenant_shard_id
    3597            0 :                             .split(ShardCount::new(split_req.new_shard_count)),
    3598            0 :                     });
    3599              :                 }
    3600              : 
    3601            0 :                 if targets.is_empty() {
    3602            0 :                     if children_found.len() == split_req.new_shard_count as usize {
    3603            0 :                         return Ok(ShardSplitAction::NoOp(TenantShardSplitResponse {
    3604            0 :                             new_shards: children_found,
    3605            0 :                         }));
    3606              :                     } else {
    3607              :                         // No shards found to split, and no existing children found: the
    3608              :                         // tenant doesn't exist at all.
    3609            0 :                         return Err(ApiError::NotFound(
    3610            0 :                             anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    3611            0 :                         ));
    3612              :                     }
    3613            0 :                 }
    3614            0 : 
    3615            0 :                 (old_shard_count, targets)
    3616            0 :             };
    3617            0 : 
    3618            0 :         // unwrap safety: we would have returned above if we didn't find at least one shard to split
    3619            0 :         let old_shard_count = old_shard_count.unwrap();
    3620            0 :         let shard_ident = if let Some(new_stripe_size) = split_req.new_stripe_size {
    3621              :             // This ShardIdentity will be used as the template for all children, so this implicitly
    3622              :             // applies the new stripe size to the children.
    3623            0 :             let mut shard_ident = shard_ident.unwrap();
    3624            0 :             if shard_ident.count.count() > 1 && shard_ident.stripe_size != new_stripe_size {
    3625            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!("Attempted to change stripe size ({:?}->{new_stripe_size:?}) on a tenant with multiple shards", shard_ident.stripe_size)));
    3626            0 :             }
    3627            0 : 
    3628            0 :             shard_ident.stripe_size = new_stripe_size;
    3629            0 :             tracing::info!("applied  stripe size {}", shard_ident.stripe_size.0);
    3630            0 :             shard_ident
    3631              :         } else {
    3632            0 :             shard_ident.unwrap()
    3633              :         };
    3634            0 :         let policy = policy.unwrap();
    3635            0 :         let config = config.unwrap();
    3636            0 : 
    3637            0 :         Ok(ShardSplitAction::Split(ShardSplitParams {
    3638            0 :             old_shard_count,
    3639            0 :             new_shard_count: ShardCount::new(split_req.new_shard_count),
    3640            0 :             new_stripe_size: split_req.new_stripe_size,
    3641            0 :             targets,
    3642            0 :             policy,
    3643            0 :             config,
    3644            0 :             shard_ident,
    3645            0 :         }))
    3646            0 :     }
    3647              : 
    3648            0 :     async fn do_tenant_shard_split(
    3649            0 :         &self,
    3650            0 :         tenant_id: TenantId,
    3651            0 :         params: ShardSplitParams,
    3652            0 :     ) -> Result<(TenantShardSplitResponse, Vec<ReconcilerWaiter>), ApiError> {
    3653            0 :         // FIXME: we have dropped self.inner lock, and not yet written anything to the database: another
    3654            0 :         // request could occur here, deleting or mutating the tenant.  begin_shard_split checks that the
    3655            0 :         // parent shards exist as expected, but it would be neater to do the above pre-checks within the
    3656            0 :         // same database transaction rather than pre-check in-memory and then maybe-fail the database write.
    3657            0 :         // (https://github.com/neondatabase/neon/issues/6676)
    3658            0 : 
    3659            0 :         let ShardSplitParams {
    3660            0 :             old_shard_count,
    3661            0 :             new_shard_count,
    3662            0 :             new_stripe_size,
    3663            0 :             mut targets,
    3664            0 :             policy,
    3665            0 :             config,
    3666            0 :             shard_ident,
    3667            0 :         } = params;
    3668              : 
    3669              :         // Drop any secondary locations: pageservers do not support splitting these, and in any case the
    3670              :         // end-state for a split tenant will usually be to have secondary locations on different nodes.
    3671              :         // The reconciliation calls in this block also implicitly cancel+barrier wrt any ongoing reconciliation
    3672              :         // at the time of split.
    3673            0 :         let waiters = {
    3674            0 :             let mut locked = self.inner.write().unwrap();
    3675            0 :             let mut waiters = Vec::new();
    3676            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3677            0 :             for target in &mut targets {
    3678            0 :                 let Some(shard) = tenants.get_mut(&target.parent_id) else {
    3679              :                     // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
    3680            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3681            0 :                         "Shard {} not found",
    3682            0 :                         target.parent_id
    3683            0 :                     )));
    3684              :                 };
    3685              : 
    3686            0 :                 if shard.intent.get_attached() != &Some(target.node.get_id()) {
    3687              :                     // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
    3688            0 :                     return Err(ApiError::Conflict(format!(
    3689            0 :                         "Shard {} unexpectedly rescheduled during split",
    3690            0 :                         target.parent_id
    3691            0 :                     )));
    3692            0 :                 }
    3693            0 : 
    3694            0 :                 // Irrespective of PlacementPolicy, clear secondary locations from intent
    3695            0 :                 shard.intent.clear_secondary(scheduler);
    3696              : 
    3697              :                 // Run Reconciler to execute detach fo secondary locations.
    3698            0 :                 if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
    3699            0 :                     waiters.push(waiter);
    3700            0 :                 }
    3701              :             }
    3702            0 :             waiters
    3703            0 :         };
    3704            0 :         self.await_waiters(waiters, RECONCILE_TIMEOUT).await?;
    3705              : 
    3706              :         // Before creating any new child shards in memory or on the pageservers, persist them: this
    3707              :         // enables us to ensure that we will always be able to clean up if something goes wrong.  This also
    3708              :         // acts as the protection against two concurrent attempts to split: one of them will get a database
    3709              :         // error trying to insert the child shards.
    3710            0 :         let mut child_tsps = Vec::new();
    3711            0 :         for target in &targets {
    3712            0 :             let mut this_child_tsps = Vec::new();
    3713            0 :             for child in &target.child_ids {
    3714            0 :                 let mut child_shard = shard_ident;
    3715            0 :                 child_shard.number = child.shard_number;
    3716            0 :                 child_shard.count = child.shard_count;
    3717            0 : 
    3718            0 :                 tracing::info!(
    3719            0 :                     "Create child shard persistence with stripe size {}",
    3720              :                     shard_ident.stripe_size.0
    3721              :                 );
    3722              : 
    3723            0 :                 this_child_tsps.push(TenantShardPersistence {
    3724            0 :                     tenant_id: child.tenant_id.to_string(),
    3725            0 :                     shard_number: child.shard_number.0 as i32,
    3726            0 :                     shard_count: child.shard_count.literal() as i32,
    3727            0 :                     shard_stripe_size: shard_ident.stripe_size.0 as i32,
    3728            0 :                     // Note: this generation is a placeholder, [`Persistence::begin_shard_split`] will
    3729            0 :                     // populate the correct generation as part of its transaction, to protect us
    3730            0 :                     // against racing with changes in the state of the parent.
    3731            0 :                     generation: None,
    3732            0 :                     generation_pageserver: Some(target.node.get_id().0 as i64),
    3733            0 :                     placement_policy: serde_json::to_string(&policy).unwrap(),
    3734            0 :                     config: serde_json::to_string(&config).unwrap(),
    3735            0 :                     splitting: SplitState::Splitting,
    3736            0 : 
    3737            0 :                     // Scheduling policies do not carry through to children
    3738            0 :                     scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    3739            0 :                         .unwrap(),
    3740            0 :                 });
    3741              :             }
    3742              : 
    3743            0 :             child_tsps.push((target.parent_id, this_child_tsps));
    3744              :         }
    3745              : 
    3746            0 :         if let Err(e) = self
    3747            0 :             .persistence
    3748            0 :             .begin_shard_split(old_shard_count, tenant_id, child_tsps)
    3749            0 :             .await
    3750              :         {
    3751            0 :             match e {
    3752              :                 DatabaseError::Query(diesel::result::Error::DatabaseError(
    3753              :                     DatabaseErrorKind::UniqueViolation,
    3754              :                     _,
    3755              :                 )) => {
    3756              :                     // Inserting a child shard violated a unique constraint: we raced with another call to
    3757              :                     // this function
    3758            0 :                     tracing::warn!("Conflicting attempt to split {tenant_id}: {e}");
    3759            0 :                     return Err(ApiError::Conflict("Tenant is already splitting".into()));
    3760              :                 }
    3761            0 :                 _ => return Err(ApiError::InternalServerError(e.into())),
    3762              :             }
    3763            0 :         }
    3764            0 :         fail::fail_point!("shard-split-post-begin", |_| Err(
    3765            0 :             ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
    3766            0 :         ));
    3767              : 
    3768              :         // Now that I have persisted the splitting state, apply it in-memory.  This is infallible, so
    3769              :         // callers may assume that if splitting is set in memory, then it was persisted, and if splitting
    3770              :         // is not set in memory, then it was not persisted.
    3771              :         {
    3772            0 :             let mut locked = self.inner.write().unwrap();
    3773            0 :             for target in &targets {
    3774            0 :                 if let Some(parent_shard) = locked.tenants.get_mut(&target.parent_id) {
    3775            0 :                     parent_shard.splitting = SplitState::Splitting;
    3776            0 :                     // Put the observed state to None, to reflect that it is indeterminate once we start the
    3777            0 :                     // split operation.
    3778            0 :                     parent_shard
    3779            0 :                         .observed
    3780            0 :                         .locations
    3781            0 :                         .insert(target.node.get_id(), ObservedStateLocation { conf: None });
    3782            0 :                 }
    3783              :             }
    3784              :         }
    3785              : 
    3786              :         // TODO: issue split calls concurrently (this only matters once we're splitting
    3787              :         // N>1 shards into M shards -- initially we're usually splitting 1 shard into N).
    3788              : 
    3789            0 :         for target in &targets {
    3790              :             let ShardSplitTarget {
    3791            0 :                 parent_id,
    3792            0 :                 node,
    3793            0 :                 child_ids,
    3794            0 :             } = target;
    3795            0 :             let client = PageserverClient::new(
    3796            0 :                 node.get_id(),
    3797            0 :                 node.base_url(),
    3798            0 :                 self.config.jwt_token.as_deref(),
    3799            0 :             );
    3800            0 :             let response = client
    3801            0 :                 .tenant_shard_split(
    3802            0 :                     *parent_id,
    3803            0 :                     TenantShardSplitRequest {
    3804            0 :                         new_shard_count: new_shard_count.literal(),
    3805            0 :                         new_stripe_size,
    3806            0 :                     },
    3807            0 :                 )
    3808            0 :                 .await
    3809            0 :                 .map_err(|e| ApiError::Conflict(format!("Failed to split {}: {}", parent_id, e)))?;
    3810              : 
    3811            0 :             fail::fail_point!("shard-split-post-remote", |_| Err(ApiError::Conflict(
    3812            0 :                 "failpoint".to_string()
    3813            0 :             )));
    3814              : 
    3815            0 :             tracing::info!(
    3816            0 :                 "Split {} into {}",
    3817            0 :                 parent_id,
    3818            0 :                 response
    3819            0 :                     .new_shards
    3820            0 :                     .iter()
    3821            0 :                     .map(|s| format!("{:?}", s))
    3822            0 :                     .collect::<Vec<_>>()
    3823            0 :                     .join(",")
    3824              :             );
    3825              : 
    3826            0 :             if &response.new_shards != child_ids {
    3827              :                 // This should never happen: the pageserver should agree with us on how shard splits work.
    3828            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3829            0 :                     "Splitting shard {} resulted in unexpected IDs: {:?} (expected {:?})",
    3830            0 :                     parent_id,
    3831            0 :                     response.new_shards,
    3832            0 :                     child_ids
    3833            0 :                 )));
    3834            0 :             }
    3835              :         }
    3836              : 
    3837              :         // TODO: if the pageserver restarted concurrently with our split API call,
    3838              :         // the actual generation of the child shard might differ from the generation
    3839              :         // we expect it to have.  In order for our in-database generation to end up
    3840              :         // correct, we should carry the child generation back in the response and apply it here
    3841              :         // in complete_shard_split (and apply the correct generation in memory)
    3842              :         // (or, we can carry generation in the request and reject the request if
    3843              :         //  it doesn't match, but that requires more retry logic on this side)
    3844              : 
    3845            0 :         self.persistence
    3846            0 :             .complete_shard_split(tenant_id, old_shard_count)
    3847            0 :             .await?;
    3848              : 
    3849            0 :         fail::fail_point!("shard-split-post-complete", |_| Err(
    3850            0 :             ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
    3851            0 :         ));
    3852              : 
    3853              :         // Replace all the shards we just split with their children: this phase is infallible.
    3854            0 :         let (response, child_locations, waiters) =
    3855            0 :             self.tenant_shard_split_commit_inmem(tenant_id, new_shard_count, new_stripe_size);
    3856            0 : 
    3857            0 :         // Send compute notifications for all the new shards
    3858            0 :         let mut failed_notifications = Vec::new();
    3859            0 :         for (child_id, child_ps, stripe_size) in child_locations {
    3860            0 :             if let Err(e) = self
    3861            0 :                 .compute_hook
    3862            0 :                 .notify(child_id, child_ps, stripe_size, &self.cancel)
    3863            0 :                 .await
    3864              :             {
    3865            0 :                 tracing::warn!("Failed to update compute of {}->{} during split, proceeding anyway to complete split ({e})",
    3866              :                         child_id, child_ps);
    3867            0 :                 failed_notifications.push(child_id);
    3868            0 :             }
    3869              :         }
    3870              : 
    3871              :         // If we failed any compute notifications, make a note to retry later.
    3872            0 :         if !failed_notifications.is_empty() {
    3873            0 :             let mut locked = self.inner.write().unwrap();
    3874            0 :             for failed in failed_notifications {
    3875            0 :                 if let Some(shard) = locked.tenants.get_mut(&failed) {
    3876            0 :                     shard.pending_compute_notification = true;
    3877            0 :                 }
    3878              :             }
    3879            0 :         }
    3880              : 
    3881            0 :         Ok((response, waiters))
    3882            0 :     }
    3883              : 
    3884            0 :     pub(crate) async fn tenant_shard_migrate(
    3885            0 :         &self,
    3886            0 :         tenant_shard_id: TenantShardId,
    3887            0 :         migrate_req: TenantShardMigrateRequest,
    3888            0 :     ) -> Result<TenantShardMigrateResponse, ApiError> {
    3889            0 :         let waiter = {
    3890            0 :             let mut locked = self.inner.write().unwrap();
    3891            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3892              : 
    3893            0 :             let Some(node) = nodes.get(&migrate_req.node_id) else {
    3894            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    3895            0 :                     "Node {} not found",
    3896            0 :                     migrate_req.node_id
    3897            0 :                 )));
    3898              :             };
    3899              : 
    3900            0 :             if !node.is_available() {
    3901              :                 // Warn but proceed: the caller may intend to manually adjust the placement of
    3902              :                 // a shard even if the node is down, e.g. if intervening during an incident.
    3903            0 :                 tracing::warn!("Migrating to unavailable node {node}");
    3904            0 :             }
    3905              : 
    3906            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    3907            0 :                 return Err(ApiError::NotFound(
    3908            0 :                     anyhow::anyhow!("Tenant shard not found").into(),
    3909            0 :                 ));
    3910              :             };
    3911              : 
    3912            0 :             if shard.intent.get_attached() == &Some(migrate_req.node_id) {
    3913              :                 // No-op case: we will still proceed to wait for reconciliation in case it is
    3914              :                 // incomplete from an earlier update to the intent.
    3915            0 :                 tracing::info!("Migrating: intent is unchanged {:?}", shard.intent);
    3916              :             } else {
    3917            0 :                 let old_attached = *shard.intent.get_attached();
    3918            0 : 
    3919            0 :                 match shard.policy {
    3920            0 :                     PlacementPolicy::Attached(n) => {
    3921            0 :                         // If our new attached node was a secondary, it no longer should be.
    3922            0 :                         shard.intent.remove_secondary(scheduler, migrate_req.node_id);
    3923              : 
    3924              :                         // If we were already attached to something, demote that to a secondary
    3925            0 :                         if let Some(old_attached) = old_attached {
    3926            0 :                             if n > 0 {
    3927              :                                 // Remove other secondaries to make room for the location we'll demote
    3928            0 :                                 while shard.intent.get_secondary().len() >= n {
    3929            0 :                                     shard.intent.pop_secondary(scheduler);
    3930            0 :                                 }
    3931              : 
    3932            0 :                                 shard.intent.push_secondary(scheduler, old_attached);
    3933            0 :                             }
    3934            0 :                         }
    3935              : 
    3936            0 :                         shard.intent.set_attached(scheduler, Some(migrate_req.node_id));
    3937              :                     }
    3938            0 :                     PlacementPolicy::Secondary => {
    3939            0 :                         shard.intent.clear(scheduler);
    3940            0 :                         shard.intent.push_secondary(scheduler, migrate_req.node_id);
    3941            0 :                     }
    3942              :                     PlacementPolicy::Detached => {
    3943            0 :                         return Err(ApiError::BadRequest(anyhow::anyhow!(
    3944            0 :                             "Cannot migrate a tenant that is PlacementPolicy::Detached: configure it to an attached policy first"
    3945            0 :                         )))
    3946              :                     }
    3947              :                 }
    3948              : 
    3949            0 :                 tracing::info!("Migrating: new intent {:?}", shard.intent);
    3950            0 :                 shard.sequence = shard.sequence.next();
    3951              :             }
    3952              : 
    3953            0 :             self.maybe_reconcile_shard(shard, nodes)
    3954              :         };
    3955              : 
    3956            0 :         if let Some(waiter) = waiter {
    3957            0 :             waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
    3958              :         } else {
    3959            0 :             tracing::info!("Migration is a no-op");
    3960              :         }
    3961              : 
    3962            0 :         Ok(TenantShardMigrateResponse {})
    3963            0 :     }
    3964              : 
    3965              :     /// This is for debug/support only: we simply drop all state for a tenant, without
    3966              :     /// detaching or deleting it on pageservers.
    3967            0 :     pub(crate) async fn tenant_drop(&self, tenant_id: TenantId) -> Result<(), ApiError> {
    3968            0 :         self.persistence.delete_tenant(tenant_id).await?;
    3969              : 
    3970            0 :         let mut locked = self.inner.write().unwrap();
    3971            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    3972            0 :         let mut shards = Vec::new();
    3973            0 :         for (tenant_shard_id, _) in tenants.range(TenantShardId::tenant_range(tenant_id)) {
    3974            0 :             shards.push(*tenant_shard_id);
    3975            0 :         }
    3976              : 
    3977            0 :         for shard_id in shards {
    3978            0 :             if let Some(mut shard) = tenants.remove(&shard_id) {
    3979            0 :                 shard.intent.clear(scheduler);
    3980            0 :             }
    3981              :         }
    3982              : 
    3983            0 :         Ok(())
    3984            0 :     }
    3985              : 
    3986              :     /// This is for debug/support only: assuming tenant data is already present in S3, we "create" a
    3987              :     /// tenant with a very high generation number so that it will see the existing data.
    3988            0 :     pub(crate) async fn tenant_import(
    3989            0 :         &self,
    3990            0 :         tenant_id: TenantId,
    3991            0 :     ) -> Result<TenantCreateResponse, ApiError> {
    3992            0 :         // Pick an arbitrary available pageserver to use for scanning the tenant in remote storage
    3993            0 :         let maybe_node = {
    3994            0 :             self.inner
    3995            0 :                 .read()
    3996            0 :                 .unwrap()
    3997            0 :                 .nodes
    3998            0 :                 .values()
    3999            0 :                 .find(|n| n.is_available())
    4000            0 :                 .cloned()
    4001              :         };
    4002            0 :         let Some(node) = maybe_node else {
    4003            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!("No nodes available")));
    4004              :         };
    4005              : 
    4006            0 :         let client = PageserverClient::new(
    4007            0 :             node.get_id(),
    4008            0 :             node.base_url(),
    4009            0 :             self.config.jwt_token.as_deref(),
    4010            0 :         );
    4011              : 
    4012            0 :         let scan_result = client
    4013            0 :             .tenant_scan_remote_storage(tenant_id)
    4014            0 :             .await
    4015            0 :             .map_err(|e| passthrough_api_error(&node, e))?;
    4016              : 
    4017              :         // A post-split tenant may contain a mixture of shard counts in remote storage: pick the highest count.
    4018            0 :         let Some(shard_count) = scan_result
    4019            0 :             .shards
    4020            0 :             .iter()
    4021            0 :             .map(|s| s.tenant_shard_id.shard_count)
    4022            0 :             .max()
    4023              :         else {
    4024            0 :             return Err(ApiError::NotFound(
    4025            0 :                 anyhow::anyhow!("No shards found").into(),
    4026            0 :             ));
    4027              :         };
    4028              : 
    4029              :         // Ideally we would set each newly imported shard's generation independently, but for correctness it is sufficient
    4030              :         // to
    4031            0 :         let generation = scan_result
    4032            0 :             .shards
    4033            0 :             .iter()
    4034            0 :             .map(|s| s.generation)
    4035            0 :             .max()
    4036            0 :             .expect("We already validated >0 shards");
    4037            0 : 
    4038            0 :         // FIXME: we have no way to recover the shard stripe size from contents of remote storage: this will
    4039            0 :         // only work if they were using the default stripe size.
    4040            0 :         let stripe_size = ShardParameters::DEFAULT_STRIPE_SIZE;
    4041              : 
    4042            0 :         let (response, waiters) = self
    4043            0 :             .do_tenant_create(TenantCreateRequest {
    4044            0 :                 new_tenant_id: TenantShardId::unsharded(tenant_id),
    4045            0 :                 generation,
    4046            0 : 
    4047            0 :                 shard_parameters: ShardParameters {
    4048            0 :                     count: shard_count,
    4049            0 :                     stripe_size,
    4050            0 :                 },
    4051            0 :                 placement_policy: Some(PlacementPolicy::Attached(0)), // No secondaries, for convenient debug/hacking
    4052            0 : 
    4053            0 :                 // There is no way to know what the tenant's config was: revert to defaults
    4054            0 :                 config: TenantConfig::default(),
    4055            0 :             })
    4056            0 :             .await?;
    4057              : 
    4058            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    4059              :             // Since this is a debug/support operation, all kinds of weird issues are possible (e.g. this
    4060              :             // tenant doesn't exist in the control plane), so don't fail the request if it can't fully
    4061              :             // reconcile, as reconciliation includes notifying compute.
    4062            0 :             tracing::warn!(%tenant_id, "Reconcile not done yet while importing tenant ({e})");
    4063            0 :         }
    4064              : 
    4065            0 :         Ok(response)
    4066            0 :     }
    4067              : 
    4068              :     /// For debug/support: a full JSON dump of TenantShards.  Returns a response so that
    4069              :     /// we don't have to make TenantShard clonable in the return path.
    4070            0 :     pub(crate) fn tenants_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
    4071            0 :         let serialized = {
    4072            0 :             let locked = self.inner.read().unwrap();
    4073            0 :             let result = locked.tenants.values().collect::<Vec<_>>();
    4074            0 :             serde_json::to_string(&result).map_err(|e| ApiError::InternalServerError(e.into()))?
    4075              :         };
    4076              : 
    4077            0 :         hyper::Response::builder()
    4078            0 :             .status(hyper::StatusCode::OK)
    4079            0 :             .header(hyper::header::CONTENT_TYPE, "application/json")
    4080            0 :             .body(hyper::Body::from(serialized))
    4081            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))
    4082            0 :     }
    4083              : 
    4084              :     /// Check the consistency of in-memory state vs. persistent state, and check that the
    4085              :     /// scheduler's statistics are up to date.
    4086              :     ///
    4087              :     /// These consistency checks expect an **idle** system.  If changes are going on while
    4088              :     /// we run, then we can falsely indicate a consistency issue.  This is sufficient for end-of-test
    4089              :     /// checks, but not suitable for running continuously in the background in the field.
    4090            0 :     pub(crate) async fn consistency_check(&self) -> Result<(), ApiError> {
    4091            0 :         let (mut expect_nodes, mut expect_shards) = {
    4092            0 :             let locked = self.inner.read().unwrap();
    4093            0 : 
    4094            0 :             locked
    4095            0 :                 .scheduler
    4096            0 :                 .consistency_check(locked.nodes.values(), locked.tenants.values())
    4097            0 :                 .context("Scheduler checks")
    4098            0 :                 .map_err(ApiError::InternalServerError)?;
    4099              : 
    4100            0 :             let expect_nodes = locked
    4101            0 :                 .nodes
    4102            0 :                 .values()
    4103            0 :                 .map(|n| n.to_persistent())
    4104            0 :                 .collect::<Vec<_>>();
    4105            0 : 
    4106            0 :             let expect_shards = locked
    4107            0 :                 .tenants
    4108            0 :                 .values()
    4109            0 :                 .map(|t| t.to_persistent())
    4110            0 :                 .collect::<Vec<_>>();
    4111              : 
    4112              :             // This method can only validate the state of an idle system: if a reconcile is in
    4113              :             // progress, fail out early to avoid giving false errors on state that won't match
    4114              :             // between database and memory under a ReconcileResult is processed.
    4115            0 :             for t in locked.tenants.values() {
    4116            0 :                 if t.reconciler.is_some() {
    4117            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4118            0 :                         "Shard {} reconciliation in progress",
    4119            0 :                         t.tenant_shard_id
    4120            0 :                     )));
    4121            0 :                 }
    4122              :             }
    4123              : 
    4124            0 :             (expect_nodes, expect_shards)
    4125              :         };
    4126              : 
    4127            0 :         let mut nodes = self.persistence.list_nodes().await?;
    4128            0 :         expect_nodes.sort_by_key(|n| n.node_id);
    4129            0 :         nodes.sort_by_key(|n| n.node_id);
    4130            0 : 
    4131            0 :         if nodes != expect_nodes {
    4132            0 :             tracing::error!("Consistency check failed on nodes.");
    4133            0 :             tracing::error!(
    4134            0 :                 "Nodes in memory: {}",
    4135            0 :                 serde_json::to_string(&expect_nodes)
    4136            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    4137              :             );
    4138            0 :             tracing::error!(
    4139            0 :                 "Nodes in database: {}",
    4140            0 :                 serde_json::to_string(&nodes)
    4141            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    4142              :             );
    4143            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4144            0 :                 "Node consistency failure"
    4145            0 :             )));
    4146            0 :         }
    4147              : 
    4148            0 :         let mut shards = self.persistence.list_tenant_shards().await?;
    4149            0 :         shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
    4150            0 :         expect_shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
    4151            0 : 
    4152            0 :         if shards != expect_shards {
    4153            0 :             tracing::error!("Consistency check failed on shards.");
    4154            0 :             tracing::error!(
    4155            0 :                 "Shards in memory: {}",
    4156            0 :                 serde_json::to_string(&expect_shards)
    4157            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    4158              :             );
    4159            0 :             tracing::error!(
    4160            0 :                 "Shards in database: {}",
    4161            0 :                 serde_json::to_string(&shards)
    4162            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    4163              :             );
    4164            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4165            0 :                 "Shard consistency failure"
    4166            0 :             )));
    4167            0 :         }
    4168            0 : 
    4169            0 :         Ok(())
    4170            0 :     }
    4171              : 
    4172              :     /// For debug/support: a JSON dump of the [`Scheduler`].  Returns a response so that
    4173              :     /// we don't have to make TenantShard clonable in the return path.
    4174            0 :     pub(crate) fn scheduler_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
    4175            0 :         let serialized = {
    4176            0 :             let locked = self.inner.read().unwrap();
    4177            0 :             serde_json::to_string(&locked.scheduler)
    4178            0 :                 .map_err(|e| ApiError::InternalServerError(e.into()))?
    4179              :         };
    4180              : 
    4181            0 :         hyper::Response::builder()
    4182            0 :             .status(hyper::StatusCode::OK)
    4183            0 :             .header(hyper::header::CONTENT_TYPE, "application/json")
    4184            0 :             .body(hyper::Body::from(serialized))
    4185            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))
    4186            0 :     }
    4187              : 
    4188              :     /// This is for debug/support only: we simply drop all state for a tenant, without
    4189              :     /// detaching or deleting it on pageservers.  We do not try and re-schedule any
    4190              :     /// tenants that were on this node.
    4191              :     ///
    4192              :     /// TODO: proper node deletion API that unhooks things more gracefully
    4193            0 :     pub(crate) async fn node_drop(&self, node_id: NodeId) -> Result<(), ApiError> {
    4194            0 :         self.persistence.delete_node(node_id).await?;
    4195              : 
    4196            0 :         let mut locked = self.inner.write().unwrap();
    4197              : 
    4198            0 :         for shard in locked.tenants.values_mut() {
    4199            0 :             shard.deref_node(node_id);
    4200            0 :         }
    4201              : 
    4202            0 :         let mut nodes = (*locked.nodes).clone();
    4203            0 :         nodes.remove(&node_id);
    4204            0 :         locked.nodes = Arc::new(nodes);
    4205            0 : 
    4206            0 :         locked.scheduler.node_remove(node_id);
    4207            0 : 
    4208            0 :         Ok(())
    4209            0 :     }
    4210              : 
    4211            0 :     pub(crate) async fn node_list(&self) -> Result<Vec<Node>, ApiError> {
    4212            0 :         let nodes = {
    4213            0 :             self.inner
    4214            0 :                 .read()
    4215            0 :                 .unwrap()
    4216            0 :                 .nodes
    4217            0 :                 .values()
    4218            0 :                 .cloned()
    4219            0 :                 .collect::<Vec<_>>()
    4220            0 :         };
    4221            0 : 
    4222            0 :         Ok(nodes)
    4223            0 :     }
    4224              : 
    4225            0 :     pub(crate) async fn get_node(&self, node_id: NodeId) -> Result<Node, ApiError> {
    4226            0 :         self.inner
    4227            0 :             .read()
    4228            0 :             .unwrap()
    4229            0 :             .nodes
    4230            0 :             .get(&node_id)
    4231            0 :             .cloned()
    4232            0 :             .ok_or(ApiError::NotFound(
    4233            0 :                 format!("Node {node_id} not registered").into(),
    4234            0 :             ))
    4235            0 :     }
    4236              : 
    4237            0 :     pub(crate) async fn node_register(
    4238            0 :         &self,
    4239            0 :         register_req: NodeRegisterRequest,
    4240            0 :     ) -> Result<(), ApiError> {
    4241            0 :         let _node_lock = trace_exclusive_lock(
    4242            0 :             &self.node_op_locks,
    4243            0 :             register_req.node_id,
    4244            0 :             NodeOperations::Register,
    4245            0 :         )
    4246            0 :         .await;
    4247              : 
    4248              :         {
    4249            0 :             let locked = self.inner.read().unwrap();
    4250            0 :             if let Some(node) = locked.nodes.get(&register_req.node_id) {
    4251              :                 // Note that we do not do a total equality of the struct, because we don't require
    4252              :                 // the availability/scheduling states to agree for a POST to be idempotent.
    4253            0 :                 if node.registration_match(&register_req) {
    4254            0 :                     tracing::info!(
    4255            0 :                         "Node {} re-registered with matching address",
    4256              :                         register_req.node_id
    4257              :                     );
    4258            0 :                     return Ok(());
    4259              :                 } else {
    4260              :                     // TODO: decide if we want to allow modifying node addresses without removing and re-adding
    4261              :                     // the node.  Safest/simplest thing is to refuse it, and usually we deploy with
    4262              :                     // a fixed address through the lifetime of a node.
    4263            0 :                     tracing::warn!(
    4264            0 :                         "Node {} tried to register with different address",
    4265              :                         register_req.node_id
    4266              :                     );
    4267            0 :                     return Err(ApiError::Conflict(
    4268            0 :                         "Node is already registered with different address".to_string(),
    4269            0 :                     ));
    4270              :                 }
    4271            0 :             }
    4272            0 :         }
    4273            0 : 
    4274            0 :         // We do not require that a node is actually online when registered (it will start life
    4275            0 :         // with it's  availability set to Offline), but we _do_ require that its DNS record exists. We're
    4276            0 :         // therefore not immune to asymmetric L3 connectivity issues, but we are protected against nodes
    4277            0 :         // that register themselves with a broken DNS config.  We check only the HTTP hostname, because
    4278            0 :         // the postgres hostname might only be resolvable to clients (e.g. if we're on a different VPC than clients).
    4279            0 :         if tokio::net::lookup_host(format!(
    4280            0 :             "{}:{}",
    4281            0 :             register_req.listen_http_addr, register_req.listen_http_port
    4282            0 :         ))
    4283            0 :         .await
    4284            0 :         .is_err()
    4285              :         {
    4286              :             // If we have a transient DNS issue, it's up to the caller to retry their registration.  Because
    4287              :             // we can't robustly distinguish between an intermittent issue and a totally bogus DNS situation,
    4288              :             // we return a soft 503 error, to encourage callers to retry past transient issues.
    4289            0 :             return Err(ApiError::ResourceUnavailable(
    4290            0 :                 format!(
    4291            0 :                     "Node {} tried to register with unknown DNS name '{}'",
    4292            0 :                     register_req.node_id, register_req.listen_http_addr
    4293            0 :                 )
    4294            0 :                 .into(),
    4295            0 :             ));
    4296            0 :         }
    4297            0 : 
    4298            0 :         // Ordering: we must persist the new node _before_ adding it to in-memory state.
    4299            0 :         // This ensures that before we use it for anything or expose it via any external
    4300            0 :         // API, it is guaranteed to be available after a restart.
    4301            0 :         let new_node = Node::new(
    4302            0 :             register_req.node_id,
    4303            0 :             register_req.listen_http_addr,
    4304            0 :             register_req.listen_http_port,
    4305            0 :             register_req.listen_pg_addr,
    4306            0 :             register_req.listen_pg_port,
    4307            0 :         );
    4308            0 : 
    4309            0 :         // TODO: idempotency if the node already exists in the database
    4310            0 :         self.persistence.insert_node(&new_node).await?;
    4311              : 
    4312            0 :         let mut locked = self.inner.write().unwrap();
    4313            0 :         let mut new_nodes = (*locked.nodes).clone();
    4314            0 : 
    4315            0 :         locked.scheduler.node_upsert(&new_node);
    4316            0 :         new_nodes.insert(register_req.node_id, new_node);
    4317            0 : 
    4318            0 :         locked.nodes = Arc::new(new_nodes);
    4319            0 : 
    4320            0 :         tracing::info!(
    4321            0 :             "Registered pageserver {}, now have {} pageservers",
    4322            0 :             register_req.node_id,
    4323            0 :             locked.nodes.len()
    4324              :         );
    4325            0 :         Ok(())
    4326            0 :     }
    4327              : 
    4328            0 :     pub(crate) async fn node_configure(
    4329            0 :         &self,
    4330            0 :         node_id: NodeId,
    4331            0 :         availability: Option<NodeAvailability>,
    4332            0 :         scheduling: Option<NodeSchedulingPolicy>,
    4333            0 :     ) -> Result<(), ApiError> {
    4334            0 :         let _node_lock =
    4335            0 :             trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Configure).await;
    4336              : 
    4337            0 :         if let Some(scheduling) = scheduling {
    4338              :             // Scheduling is a persistent part of Node: we must write updates to the database before
    4339              :             // applying them in memory
    4340            0 :             self.persistence.update_node(node_id, scheduling).await?;
    4341            0 :         }
    4342              : 
    4343              :         // If we're activating a node, then before setting it active we must reconcile any shard locations
    4344              :         // on that node, in case it is out of sync, e.g. due to being unavailable during controller startup,
    4345              :         // by calling [`Self::node_activate_reconcile`]
    4346              :         //
    4347              :         // The transition we calculate here remains valid later in the function because we hold the op lock on the node:
    4348              :         // nothing else can mutate its availability while we run.
    4349            0 :         let availability_transition = if let Some(input_availability) = availability {
    4350            0 :             let (activate_node, availability_transition) = {
    4351            0 :                 let locked = self.inner.read().unwrap();
    4352            0 :                 let Some(node) = locked.nodes.get(&node_id) else {
    4353            0 :                     return Err(ApiError::NotFound(
    4354            0 :                         anyhow::anyhow!("Node {} not registered", node_id).into(),
    4355            0 :                     ));
    4356              :                 };
    4357              : 
    4358            0 :                 (
    4359            0 :                     node.clone(),
    4360            0 :                     node.get_availability_transition(input_availability),
    4361            0 :                 )
    4362              :             };
    4363              : 
    4364            0 :             if matches!(availability_transition, AvailabilityTransition::ToActive) {
    4365            0 :                 self.node_activate_reconcile(activate_node, &_node_lock)
    4366            0 :                     .await?;
    4367            0 :             }
    4368            0 :             availability_transition
    4369              :         } else {
    4370            0 :             AvailabilityTransition::Unchanged
    4371              :         };
    4372              : 
    4373              :         // Apply changes from the request to our in-memory state for the Node
    4374            0 :         let mut locked = self.inner.write().unwrap();
    4375            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    4376            0 : 
    4377            0 :         let mut new_nodes = (**nodes).clone();
    4378              : 
    4379            0 :         let Some(node) = new_nodes.get_mut(&node_id) else {
    4380            0 :             return Err(ApiError::NotFound(
    4381            0 :                 anyhow::anyhow!("Node not registered").into(),
    4382            0 :             ));
    4383              :         };
    4384              : 
    4385            0 :         if let Some(availability) = &availability {
    4386            0 :             node.set_availability(*availability);
    4387            0 :         }
    4388              : 
    4389            0 :         if let Some(scheduling) = scheduling {
    4390            0 :             node.set_scheduling(scheduling);
    4391            0 :         }
    4392              : 
    4393              :         // Update the scheduler, in case the elegibility of the node for new shards has changed
    4394            0 :         scheduler.node_upsert(node);
    4395            0 : 
    4396            0 :         let new_nodes = Arc::new(new_nodes);
    4397            0 : 
    4398            0 :         // Modify scheduling state for any Tenants that are affected by a change in the node's availability state.
    4399            0 :         match availability_transition {
    4400              :             AvailabilityTransition::ToOffline => {
    4401            0 :                 tracing::info!("Node {} transition to offline", node_id);
    4402            0 :                 let mut tenants_affected: usize = 0;
    4403              : 
    4404            0 :                 for (tenant_shard_id, tenant_shard) in tenants {
    4405            0 :                     if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
    4406            0 :                         // When a node goes offline, we set its observed configuration to None, indicating unknown: we will
    4407            0 :                         // not assume our knowledge of the node's configuration is accurate until it comes back online
    4408            0 :                         observed_loc.conf = None;
    4409            0 :                     }
    4410              : 
    4411            0 :                     if new_nodes.len() == 1 {
    4412              :                         // Special case for single-node cluster: there is no point trying to reschedule
    4413              :                         // any tenant shards: avoid doing so, in order to avoid spewing warnings about
    4414              :                         // failures to schedule them.
    4415            0 :                         continue;
    4416            0 :                     }
    4417            0 : 
    4418            0 :                     if !new_nodes
    4419            0 :                         .values()
    4420            0 :                         .any(|n| matches!(n.may_schedule(), MaySchedule::Yes(_)))
    4421              :                     {
    4422              :                         // Special case for when all nodes are unavailable and/or unschedulable: there is no point
    4423              :                         // trying to reschedule since there's nowhere else to go. Without this
    4424              :                         // branch we incorrectly detach tenants in response to node unavailability.
    4425            0 :                         continue;
    4426            0 :                     }
    4427            0 : 
    4428            0 :                     if tenant_shard.intent.demote_attached(scheduler, node_id) {
    4429            0 :                         tenant_shard.sequence = tenant_shard.sequence.next();
    4430            0 : 
    4431            0 :                         // TODO: populate a ScheduleContext including all shards in the same tenant_id (only matters
    4432            0 :                         // for tenants without secondary locations: if they have a secondary location, then this
    4433            0 :                         // schedule() call is just promoting an existing secondary)
    4434            0 :                         let mut schedule_context = ScheduleContext::default();
    4435            0 : 
    4436            0 :                         match tenant_shard.schedule(scheduler, &mut schedule_context) {
    4437            0 :                             Err(e) => {
    4438            0 :                                 // It is possible that some tenants will become unschedulable when too many pageservers
    4439            0 :                                 // go offline: in this case there isn't much we can do other than make the issue observable.
    4440            0 :                                 // TODO: give TenantShard a scheduling error attribute to be queried later.
    4441            0 :                                 tracing::warn!(%tenant_shard_id, "Scheduling error when marking pageserver {} offline: {e}", node_id);
    4442              :                             }
    4443              :                             Ok(()) => {
    4444            0 :                                 if self
    4445            0 :                                     .maybe_reconcile_shard(tenant_shard, &new_nodes)
    4446            0 :                                     .is_some()
    4447            0 :                                 {
    4448            0 :                                     tenants_affected += 1;
    4449            0 :                                 };
    4450              :                             }
    4451              :                         }
    4452            0 :                     }
    4453              :                 }
    4454            0 :                 tracing::info!(
    4455            0 :                     "Launched {} reconciler tasks for tenants affected by node {} going offline",
    4456              :                     tenants_affected,
    4457              :                     node_id
    4458              :                 )
    4459              :             }
    4460              :             AvailabilityTransition::ToActive => {
    4461            0 :                 tracing::info!("Node {} transition to active", node_id);
    4462              :                 // When a node comes back online, we must reconcile any tenant that has a None observed
    4463              :                 // location on the node.
    4464            0 :                 for tenant_shard in locked.tenants.values_mut() {
    4465              :                     // If a reconciliation is already in progress, rely on the previous scheduling
    4466              :                     // decision and skip triggering a new reconciliation.
    4467            0 :                     if tenant_shard.reconciler.is_some() {
    4468            0 :                         continue;
    4469            0 :                     }
    4470              : 
    4471            0 :                     if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
    4472            0 :                         if observed_loc.conf.is_none() {
    4473            0 :                             self.maybe_reconcile_shard(tenant_shard, &new_nodes);
    4474            0 :                         }
    4475            0 :                     }
    4476              :                 }
    4477              : 
    4478              :                 // TODO: in the background, we should balance work back onto this pageserver
    4479              :             }
    4480              :             AvailabilityTransition::Unchanged => {
    4481            0 :                 tracing::debug!("Node {} no availability change during config", node_id);
    4482              :             }
    4483              :         }
    4484              : 
    4485            0 :         locked.nodes = new_nodes;
    4486            0 : 
    4487            0 :         Ok(())
    4488            0 :     }
    4489              : 
    4490            0 :     pub(crate) async fn start_node_drain(
    4491            0 :         self: &Arc<Self>,
    4492            0 :         node_id: NodeId,
    4493            0 :     ) -> Result<(), ApiError> {
    4494            0 :         let (ongoing_op, node_available, node_policy, schedulable_nodes_count) = {
    4495            0 :             let locked = self.inner.read().unwrap();
    4496            0 :             let nodes = &locked.nodes;
    4497            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    4498            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    4499            0 :             ))?;
    4500            0 :             let schedulable_nodes_count = nodes
    4501            0 :                 .iter()
    4502            0 :                 .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
    4503            0 :                 .count();
    4504            0 : 
    4505            0 :             (
    4506            0 :                 locked
    4507            0 :                     .ongoing_operation
    4508            0 :                     .as_ref()
    4509            0 :                     .map(|ongoing| ongoing.operation),
    4510            0 :                 node.is_available(),
    4511            0 :                 node.get_scheduling(),
    4512            0 :                 schedulable_nodes_count,
    4513            0 :             )
    4514              :         };
    4515              : 
    4516            0 :         if let Some(ongoing) = ongoing_op {
    4517            0 :             return Err(ApiError::PreconditionFailed(
    4518            0 :                 format!("Background operation already ongoing for node: {}", ongoing).into(),
    4519            0 :             ));
    4520            0 :         }
    4521            0 : 
    4522            0 :         if !node_available {
    4523            0 :             return Err(ApiError::ResourceUnavailable(
    4524            0 :                 format!("Node {node_id} is currently unavailable").into(),
    4525            0 :             ));
    4526            0 :         }
    4527            0 : 
    4528            0 :         if schedulable_nodes_count == 0 {
    4529            0 :             return Err(ApiError::PreconditionFailed(
    4530            0 :                 "No other schedulable nodes to drain to".into(),
    4531            0 :             ));
    4532            0 :         }
    4533            0 : 
    4534            0 :         match node_policy {
    4535              :             NodeSchedulingPolicy::Active | NodeSchedulingPolicy::Pause => {
    4536            0 :                 self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Draining))
    4537            0 :                     .await?;
    4538              : 
    4539            0 :                 let cancel = CancellationToken::new();
    4540            0 : 
    4541            0 :                 self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
    4542            0 :                     operation: Operation::Drain(Drain { node_id }),
    4543            0 :                     cancel: cancel.clone(),
    4544            0 :                 });
    4545            0 : 
    4546            0 :                 tokio::task::spawn({
    4547            0 :                     let service = self.clone();
    4548            0 :                     let cancel = cancel.clone();
    4549            0 :                     async move {
    4550              :                         scopeguard::defer! {
    4551              :                             let prev = service.inner.write().unwrap().ongoing_operation.take();
    4552              : 
    4553            0 :                             if let Some(Operation::Drain(removed_drain)) = prev.map(|h| h.operation) {
    4554              :                                 assert_eq!(removed_drain.node_id, node_id, "We always take the same operation");
    4555              :                             } else {
    4556              :                                 panic!("We always remove the same operation")
    4557              :                             }
    4558              :                         }
    4559              : 
    4560            0 :                         tracing::info!(%node_id, "Drain background operation starting");
    4561            0 :                         let res = service.drain_node(node_id, cancel).await;
    4562            0 :                         match res {
    4563              :                             Ok(()) => {
    4564            0 :                                 tracing::info!(%node_id, "Drain background operation completed successfully");
    4565              :                             }
    4566              :                             Err(OperationError::Cancelled) => {
    4567            0 :                                 tracing::info!(%node_id, "Drain background operation was cancelled");
    4568              :                             }
    4569            0 :                             Err(err) => {
    4570            0 :                                 tracing::error!(%node_id, "Drain background operation encountered: {err}")
    4571              :                             }
    4572              :                         }
    4573            0 :                     }
    4574            0 :                 });
    4575              :             }
    4576              :             NodeSchedulingPolicy::Draining => {
    4577            0 :                 return Err(ApiError::Conflict(format!(
    4578            0 :                     "Node {node_id} has drain in progress"
    4579            0 :                 )));
    4580              :             }
    4581            0 :             policy => {
    4582            0 :                 return Err(ApiError::PreconditionFailed(
    4583            0 :                     format!("Node {node_id} cannot be drained due to {policy:?} policy").into(),
    4584            0 :                 ));
    4585              :             }
    4586              :         }
    4587              : 
    4588            0 :         Ok(())
    4589            0 :     }
    4590              : 
    4591            0 :     pub(crate) async fn start_node_fill(self: &Arc<Self>, node_id: NodeId) -> Result<(), ApiError> {
    4592            0 :         let (ongoing_op, node_available, node_policy, total_nodes_count) = {
    4593            0 :             let locked = self.inner.read().unwrap();
    4594            0 :             let nodes = &locked.nodes;
    4595            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    4596            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    4597            0 :             ))?;
    4598              : 
    4599            0 :             (
    4600            0 :                 locked
    4601            0 :                     .ongoing_operation
    4602            0 :                     .as_ref()
    4603            0 :                     .map(|ongoing| ongoing.operation),
    4604            0 :                 node.is_available(),
    4605            0 :                 node.get_scheduling(),
    4606            0 :                 nodes.len(),
    4607            0 :             )
    4608              :         };
    4609              : 
    4610            0 :         if let Some(ongoing) = ongoing_op {
    4611            0 :             return Err(ApiError::PreconditionFailed(
    4612            0 :                 format!("Background operation already ongoing for node: {}", ongoing).into(),
    4613            0 :             ));
    4614            0 :         }
    4615            0 : 
    4616            0 :         if !node_available {
    4617            0 :             return Err(ApiError::ResourceUnavailable(
    4618            0 :                 format!("Node {node_id} is currently unavailable").into(),
    4619            0 :             ));
    4620            0 :         }
    4621            0 : 
    4622            0 :         if total_nodes_count <= 1 {
    4623            0 :             return Err(ApiError::PreconditionFailed(
    4624            0 :                 "No other nodes to fill from".into(),
    4625            0 :             ));
    4626            0 :         }
    4627            0 : 
    4628            0 :         match node_policy {
    4629              :             NodeSchedulingPolicy::Active => {
    4630            0 :                 self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Filling))
    4631            0 :                     .await?;
    4632              : 
    4633            0 :                 let cancel = CancellationToken::new();
    4634            0 : 
    4635            0 :                 self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
    4636            0 :                     operation: Operation::Fill(Fill { node_id }),
    4637            0 :                     cancel: cancel.clone(),
    4638            0 :                 });
    4639            0 : 
    4640            0 :                 tokio::task::spawn({
    4641            0 :                     let service = self.clone();
    4642            0 :                     let cancel = cancel.clone();
    4643            0 :                     async move {
    4644              :                         scopeguard::defer! {
    4645              :                             let prev = service.inner.write().unwrap().ongoing_operation.take();
    4646              : 
    4647            0 :                             if let Some(Operation::Fill(removed_fill)) = prev.map(|h| h.operation) {
    4648              :                                 assert_eq!(removed_fill.node_id, node_id, "We always take the same operation");
    4649              :                             } else {
    4650              :                                 panic!("We always remove the same operation")
    4651              :                             }
    4652              :                         }
    4653              : 
    4654            0 :                         tracing::info!(%node_id, "Fill background operation starting");
    4655            0 :                         let res = service.fill_node(node_id, cancel).await;
    4656            0 :                         match res {
    4657              :                             Ok(()) => {
    4658            0 :                                 tracing::info!(%node_id, "Fill background operation completed successfully");
    4659              :                             }
    4660              :                             Err(OperationError::Cancelled) => {
    4661            0 :                                 tracing::info!(%node_id, "Fill background operation was cancelled");
    4662              :                             }
    4663            0 :                             Err(err) => {
    4664            0 :                                 tracing::error!(%node_id, "Fill background operation encountered: {err}")
    4665              :                             }
    4666              :                         }
    4667            0 :                     }
    4668            0 :                 });
    4669              :             }
    4670              :             NodeSchedulingPolicy::Filling => {
    4671            0 :                 return Err(ApiError::Conflict(format!(
    4672            0 :                     "Node {node_id} has fill in progress"
    4673            0 :                 )));
    4674              :             }
    4675            0 :             policy => {
    4676            0 :                 return Err(ApiError::PreconditionFailed(
    4677            0 :                     format!("Node {node_id} cannot be filled due to {policy:?} policy").into(),
    4678            0 :                 ));
    4679              :             }
    4680              :         }
    4681              : 
    4682            0 :         Ok(())
    4683            0 :     }
    4684              : 
    4685              :     /// Helper for methods that will try and call pageserver APIs for
    4686              :     /// a tenant, such as timeline CRUD: they cannot proceed unless the tenant
    4687              :     /// is attached somewhere.
    4688            0 :     fn ensure_attached_schedule(
    4689            0 :         &self,
    4690            0 :         mut locked: std::sync::RwLockWriteGuard<'_, ServiceState>,
    4691            0 :         tenant_id: TenantId,
    4692            0 :     ) -> Result<Vec<ReconcilerWaiter>, anyhow::Error> {
    4693            0 :         let mut waiters = Vec::new();
    4694            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    4695            0 : 
    4696            0 :         let mut schedule_context = ScheduleContext::default();
    4697            0 :         for (tenant_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    4698            0 :             shard.schedule(scheduler, &mut schedule_context)?;
    4699              : 
    4700              :             // The shard's policies may not result in an attached location being scheduled: this
    4701              :             // is an error because our caller needs it attached somewhere.
    4702            0 :             if shard.intent.get_attached().is_none() {
    4703            0 :                 return Err(anyhow::anyhow!(
    4704            0 :                     "Tenant {tenant_id} not scheduled to be attached"
    4705            0 :                 ));
    4706            0 :             };
    4707            0 : 
    4708            0 :             if shard.stably_attached().is_some() {
    4709              :                 // We do not require the shard to be totally up to date on reconciliation: we just require
    4710              :                 // that it has been attached on the intended node.   Other dirty state such as unattached secondary
    4711              :                 // locations, or compute hook notifications can be ignored.
    4712            0 :                 continue;
    4713            0 :             }
    4714              : 
    4715            0 :             if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
    4716            0 :                 tracing::info!("Waiting for shard {tenant_shard_id} to reconcile, in order to ensure it is attached");
    4717            0 :                 waiters.push(waiter);
    4718            0 :             }
    4719              :         }
    4720            0 :         Ok(waiters)
    4721            0 :     }
    4722              : 
    4723            0 :     async fn ensure_attached_wait(&self, tenant_id: TenantId) -> Result<(), ApiError> {
    4724            0 :         let ensure_waiters = {
    4725            0 :             let locked = self.inner.write().unwrap();
    4726              : 
    4727              :             // Check if the tenant is splitting: in this case, even if it is attached,
    4728              :             // we must act as if it is not: this blocks e.g. timeline creation/deletion
    4729              :             // operations during the split.
    4730            0 :             for (_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
    4731            0 :                 if !matches!(shard.splitting, SplitState::Idle) {
    4732            0 :                     return Err(ApiError::ResourceUnavailable(
    4733            0 :                         "Tenant shards are currently splitting".into(),
    4734            0 :                     ));
    4735            0 :                 }
    4736              :             }
    4737              : 
    4738            0 :             self.ensure_attached_schedule(locked, tenant_id)
    4739            0 :                 .map_err(ApiError::InternalServerError)?
    4740              :         };
    4741              : 
    4742            0 :         let deadline = Instant::now().checked_add(Duration::from_secs(5)).unwrap();
    4743            0 :         for waiter in ensure_waiters {
    4744            0 :             let timeout = deadline.duration_since(Instant::now());
    4745            0 :             waiter.wait_timeout(timeout).await?;
    4746              :         }
    4747              : 
    4748            0 :         Ok(())
    4749            0 :     }
    4750              : 
    4751              :     /// Wrap [`TenantShard`] reconciliation methods with acquisition of [`Gate`] and [`ReconcileUnits`],
    4752            0 :     fn maybe_reconcile_shard(
    4753            0 :         &self,
    4754            0 :         shard: &mut TenantShard,
    4755            0 :         nodes: &Arc<HashMap<NodeId, Node>>,
    4756            0 :     ) -> Option<ReconcilerWaiter> {
    4757            0 :         let reconcile_needed = shard.get_reconcile_needed(nodes);
    4758            0 : 
    4759            0 :         match reconcile_needed {
    4760            0 :             ReconcileNeeded::No => return None,
    4761            0 :             ReconcileNeeded::WaitExisting(waiter) => return Some(waiter),
    4762            0 :             ReconcileNeeded::Yes => {
    4763            0 :                 // Fall through to try and acquire units for spawning reconciler
    4764            0 :             }
    4765              :         };
    4766              : 
    4767            0 :         let units = match self.reconciler_concurrency.clone().try_acquire_owned() {
    4768            0 :             Ok(u) => ReconcileUnits::new(u),
    4769              :             Err(_) => {
    4770            0 :                 tracing::info!(tenant_id=%shard.tenant_shard_id.tenant_id, shard_id=%shard.tenant_shard_id.shard_slug(),
    4771            0 :                     "Concurrency limited: enqueued for reconcile later");
    4772            0 :                 if !shard.delayed_reconcile {
    4773            0 :                     match self.delayed_reconcile_tx.try_send(shard.tenant_shard_id) {
    4774            0 :                         Err(TrySendError::Closed(_)) => {
    4775            0 :                             // Weird mid-shutdown case?
    4776            0 :                         }
    4777              :                         Err(TrySendError::Full(_)) => {
    4778              :                             // It is safe to skip sending our ID in the channel: we will eventually get retried by the background reconcile task.
    4779            0 :                             tracing::warn!(
    4780            0 :                                 "Many shards are waiting to reconcile: delayed_reconcile queue is full"
    4781              :                             );
    4782              :                         }
    4783            0 :                         Ok(()) => {
    4784            0 :                             shard.delayed_reconcile = true;
    4785            0 :                         }
    4786              :                     }
    4787            0 :                 }
    4788              : 
    4789              :                 // We won't spawn a reconciler, but we will construct a waiter that waits for the shard's sequence
    4790              :                 // number to advance.  When this function is eventually called again and succeeds in getting units,
    4791              :                 // it will spawn a reconciler that makes this waiter complete.
    4792            0 :                 return Some(shard.future_reconcile_waiter());
    4793              :             }
    4794              :         };
    4795              : 
    4796            0 :         let Ok(gate_guard) = self.gate.enter() else {
    4797              :             // Gate closed: we're shutting down, drop out.
    4798            0 :             return None;
    4799              :         };
    4800              : 
    4801            0 :         shard.spawn_reconciler(
    4802            0 :             &self.result_tx,
    4803            0 :             nodes,
    4804            0 :             &self.compute_hook,
    4805            0 :             &self.config,
    4806            0 :             &self.persistence,
    4807            0 :             units,
    4808            0 :             gate_guard,
    4809            0 :             &self.cancel,
    4810            0 :         )
    4811            0 :     }
    4812              : 
    4813              :     /// Check all tenants for pending reconciliation work, and reconcile those in need.
    4814              :     /// Additionally, reschedule tenants that require it.
    4815              :     ///
    4816              :     /// Returns how many reconciliation tasks were started, or `1` if no reconciles were
    4817              :     /// spawned but some _would_ have been spawned if `reconciler_concurrency` units where
    4818              :     /// available.  A return value of 0 indicates that everything is fully reconciled already.
    4819            0 :     fn reconcile_all(&self) -> usize {
    4820            0 :         let mut locked = self.inner.write().unwrap();
    4821            0 :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    4822            0 :         let pageservers = nodes.clone();
    4823            0 : 
    4824            0 :         let mut schedule_context = ScheduleContext::default();
    4825            0 : 
    4826            0 :         let mut reconciles_spawned = 0;
    4827            0 :         for (tenant_shard_id, shard) in tenants.iter_mut() {
    4828            0 :             if tenant_shard_id.is_shard_zero() {
    4829            0 :                 schedule_context = ScheduleContext::default();
    4830            0 :             }
    4831              : 
    4832              :             // Skip checking if this shard is already enqueued for reconciliation
    4833            0 :             if shard.delayed_reconcile && self.reconciler_concurrency.available_permits() == 0 {
    4834              :                 // If there is something delayed, then return a nonzero count so that
    4835              :                 // callers like reconcile_all_now do not incorrectly get the impression
    4836              :                 // that the system is in a quiescent state.
    4837            0 :                 reconciles_spawned = std::cmp::max(1, reconciles_spawned);
    4838            0 :                 continue;
    4839            0 :             }
    4840            0 : 
    4841            0 :             // Eventual consistency: if an earlier reconcile job failed, and the shard is still
    4842            0 :             // dirty, spawn another rone
    4843            0 :             if self.maybe_reconcile_shard(shard, &pageservers).is_some() {
    4844            0 :                 reconciles_spawned += 1;
    4845            0 :             }
    4846              : 
    4847            0 :             schedule_context.avoid(&shard.intent.all_pageservers());
    4848              :         }
    4849              : 
    4850            0 :         reconciles_spawned
    4851            0 :     }
    4852              : 
    4853              :     /// `optimize` in this context means identifying shards which have valid scheduled locations, but
    4854              :     /// could be scheduled somewhere better:
    4855              :     /// - Cutting over to a secondary if the node with the secondary is more lightly loaded
    4856              :     ///    * e.g. after a node fails then recovers, to move some work back to it
    4857              :     /// - Cutting over to a secondary if it improves the spread of shard attachments within a tenant
    4858              :     ///    * e.g. after a shard split, the initial attached locations will all be on the node where
    4859              :     ///      we did the split, but are probably better placed elsewhere.
    4860              :     /// - Creating new secondary locations if it improves the spreading of a sharded tenant
    4861              :     ///    * e.g. after a shard split, some locations will be on the same node (where the split
    4862              :     ///     happened), and will probably be better placed elsewhere.
    4863              :     ///
    4864              :     /// To put it more briefly: whereas the scheduler respects soft constraints in a ScheduleContext at
    4865              :     /// the time of scheduling, this function looks for cases where a better-scoring location is available
    4866              :     /// according to those same soft constraints.
    4867            0 :     async fn optimize_all(&self) -> usize {
    4868            0 :         // Limit on how many shards' optmizations each call to this function will execute.  Combined
    4869            0 :         // with the frequency of background calls, this acts as an implicit rate limit that runs a small
    4870            0 :         // trickle of optimizations in the background, rather than executing a large number in parallel
    4871            0 :         // when a change occurs.
    4872            0 :         const MAX_OPTIMIZATIONS_EXEC_PER_PASS: usize = 2;
    4873            0 : 
    4874            0 :         // Synchronous prepare: scan shards for possible scheduling optimizations
    4875            0 :         let candidate_work = self.optimize_all_plan();
    4876            0 :         let candidate_work_len = candidate_work.len();
    4877              : 
    4878              :         // Asynchronous validate: I/O to pageservers to make sure shards are in a good state to apply validation
    4879            0 :         let validated_work = self.optimize_all_validate(candidate_work).await;
    4880              : 
    4881            0 :         let was_work_filtered = validated_work.len() != candidate_work_len;
    4882            0 : 
    4883            0 :         // Synchronous apply: update the shards' intent states according to validated optimisations
    4884            0 :         let mut reconciles_spawned = 0;
    4885            0 :         let mut optimizations_applied = 0;
    4886            0 :         let mut locked = self.inner.write().unwrap();
    4887            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    4888            0 :         for (tenant_shard_id, optimization) in validated_work {
    4889            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    4890              :                 // Shard was dropped between planning and execution;
    4891            0 :                 continue;
    4892              :             };
    4893            0 :             if shard.apply_optimization(scheduler, optimization) {
    4894            0 :                 optimizations_applied += 1;
    4895            0 :                 if self.maybe_reconcile_shard(shard, nodes).is_some() {
    4896            0 :                     reconciles_spawned += 1;
    4897            0 :                 }
    4898            0 :             }
    4899              : 
    4900            0 :             if optimizations_applied >= MAX_OPTIMIZATIONS_EXEC_PER_PASS {
    4901            0 :                 break;
    4902            0 :             }
    4903              :         }
    4904              : 
    4905            0 :         if was_work_filtered {
    4906            0 :             // If we filtered any work out during validation, ensure we return a nonzero value to indicate
    4907            0 :             // to callers that the system is not in a truly quiet state, it's going to do some work as soon
    4908            0 :             // as these validations start passing.
    4909            0 :             reconciles_spawned = std::cmp::max(reconciles_spawned, 1);
    4910            0 :         }
    4911              : 
    4912            0 :         reconciles_spawned
    4913            0 :     }
    4914              : 
    4915            0 :     fn optimize_all_plan(&self) -> Vec<(TenantShardId, ScheduleOptimization)> {
    4916            0 :         let mut schedule_context = ScheduleContext::default();
    4917            0 : 
    4918            0 :         let mut tenant_shards: Vec<&TenantShard> = Vec::new();
    4919            0 : 
    4920            0 :         // How many candidate optimizations we will generate, before evaluating them for readniess: setting
    4921            0 :         // this higher than the execution limit gives us a chance to execute some work even if the first
    4922            0 :         // few optimizations we find are not ready.
    4923            0 :         const MAX_OPTIMIZATIONS_PLAN_PER_PASS: usize = 8;
    4924            0 : 
    4925            0 :         let mut work = Vec::new();
    4926            0 : 
    4927            0 :         let mut locked = self.inner.write().unwrap();
    4928            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    4929            0 :         for (tenant_shard_id, shard) in tenants.iter() {
    4930            0 :             if tenant_shard_id.is_shard_zero() {
    4931            0 :                 // Reset accumulators on the first shard in a tenant
    4932            0 :                 schedule_context = ScheduleContext::default();
    4933            0 :                 schedule_context.mode = ScheduleMode::Speculative;
    4934            0 :                 tenant_shards.clear();
    4935            0 :             }
    4936              : 
    4937            0 :             if work.len() >= MAX_OPTIMIZATIONS_PLAN_PER_PASS {
    4938            0 :                 break;
    4939            0 :             }
    4940            0 : 
    4941            0 :             match shard.get_scheduling_policy() {
    4942            0 :                 ShardSchedulingPolicy::Active => {
    4943            0 :                     // Ok to do optimization
    4944            0 :                 }
    4945              :                 ShardSchedulingPolicy::Essential
    4946              :                 | ShardSchedulingPolicy::Pause
    4947              :                 | ShardSchedulingPolicy::Stop => {
    4948              :                     // Policy prevents optimizing this shard.
    4949            0 :                     continue;
    4950              :                 }
    4951              :             }
    4952              : 
    4953              :             // Accumulate the schedule context for all the shards in a tenant: we must have
    4954              :             // the total view of all shards before we can try to optimize any of them.
    4955            0 :             schedule_context.avoid(&shard.intent.all_pageservers());
    4956            0 :             if let Some(attached) = shard.intent.get_attached() {
    4957            0 :                 schedule_context.push_attached(*attached);
    4958            0 :             }
    4959            0 :             tenant_shards.push(shard);
    4960            0 : 
    4961            0 :             // Once we have seen the last shard in the tenant, proceed to search across all shards
    4962            0 :             // in the tenant for optimizations
    4963            0 :             if shard.shard.number.0 == shard.shard.count.count() - 1 {
    4964            0 :                 if tenant_shards.iter().any(|s| s.reconciler.is_some()) {
    4965              :                     // Do not start any optimizations while another change to the tenant is ongoing: this
    4966              :                     // is not necessary for correctness, but simplifies operations and implicitly throttles
    4967              :                     // optimization changes to happen in a "trickle" over time.
    4968            0 :                     continue;
    4969            0 :                 }
    4970            0 : 
    4971            0 :                 if tenant_shards.iter().any(|s| {
    4972            0 :                     !matches!(s.splitting, SplitState::Idle)
    4973            0 :                         || matches!(s.policy, PlacementPolicy::Detached)
    4974            0 :                 }) {
    4975              :                     // Never attempt to optimize a tenant that is currently being split, or
    4976              :                     // a tenant that is meant to be detached
    4977            0 :                     continue;
    4978            0 :                 }
    4979              : 
    4980              :                 // TODO: optimization calculations are relatively expensive: create some fast-path for
    4981              :                 // the common idle case (avoiding the search on tenants that we have recently checked)
    4982              : 
    4983            0 :                 for shard in &tenant_shards {
    4984            0 :                     if let Some(optimization) =
    4985              :                         // If idle, maybe ptimize attachments: if a shard has a secondary location that is preferable to
    4986              :                         // its primary location based on soft constraints, cut it over.
    4987            0 :                         shard.optimize_attachment(nodes, &schedule_context)
    4988              :                     {
    4989            0 :                         work.push((shard.tenant_shard_id, optimization));
    4990            0 :                         break;
    4991            0 :                     } else if let Some(optimization) =
    4992              :                         // If idle, maybe optimize secondary locations: if a shard has a secondary location that would be
    4993              :                         // better placed on another node, based on ScheduleContext, then adjust it.  This
    4994              :                         // covers cases like after a shard split, where we might have too many shards
    4995              :                         // in the same tenant with secondary locations on the node where they originally split.
    4996            0 :                         shard.optimize_secondary(scheduler, &schedule_context)
    4997              :                     {
    4998            0 :                         work.push((shard.tenant_shard_id, optimization));
    4999            0 :                         break;
    5000            0 :                     }
    5001              : 
    5002              :                     // TODO: extend this mechanism to prefer attaching on nodes with fewer attached
    5003              :                     // tenants (i.e. extend schedule state to distinguish attached from secondary counts),
    5004              :                     // for the total number of attachments on a node (not just within a tenant.)
    5005              :                 }
    5006            0 :             }
    5007              :         }
    5008              : 
    5009            0 :         work
    5010            0 :     }
    5011              : 
    5012            0 :     async fn optimize_all_validate(
    5013            0 :         &self,
    5014            0 :         candidate_work: Vec<(TenantShardId, ScheduleOptimization)>,
    5015            0 :     ) -> Vec<(TenantShardId, ScheduleOptimization)> {
    5016            0 :         // Take a clone of the node map to use outside the lock in async validation phase
    5017            0 :         let validation_nodes = { self.inner.read().unwrap().nodes.clone() };
    5018            0 : 
    5019            0 :         let mut want_secondary_status = Vec::new();
    5020            0 : 
    5021            0 :         // Validate our plans: this is an async phase where we may do I/O to pageservers to
    5022            0 :         // check that the state of locations is acceptable to run the optimization, such as
    5023            0 :         // checking that a secondary location is sufficiently warmed-up to cleanly cut over
    5024            0 :         // in a live migration.
    5025            0 :         let mut validated_work = Vec::new();
    5026            0 :         for (tenant_shard_id, optimization) in candidate_work {
    5027            0 :             match optimization.action {
    5028              :                 ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    5029              :                     old_attached_node_id: _,
    5030            0 :                     new_attached_node_id,
    5031            0 :                 }) => {
    5032            0 :                     match validation_nodes.get(&new_attached_node_id) {
    5033            0 :                         None => {
    5034            0 :                             // Node was dropped between planning and validation
    5035            0 :                         }
    5036            0 :                         Some(node) => {
    5037            0 :                             if !node.is_available() {
    5038            0 :                                 tracing::info!("Skipping optimization migration of {tenant_shard_id} to {new_attached_node_id} because node unavailable");
    5039            0 :                             } else {
    5040            0 :                                 // Accumulate optimizations that require fetching secondary status, so that we can execute these
    5041            0 :                                 // remote API requests concurrently.
    5042            0 :                                 want_secondary_status.push((
    5043            0 :                                     tenant_shard_id,
    5044            0 :                                     node.clone(),
    5045            0 :                                     optimization,
    5046            0 :                                 ));
    5047            0 :                             }
    5048              :                         }
    5049              :                     }
    5050              :                 }
    5051              :                 ScheduleOptimizationAction::ReplaceSecondary(_) => {
    5052              :                     // No extra checks needed to replace a secondary: this does not interrupt client access
    5053            0 :                     validated_work.push((tenant_shard_id, optimization))
    5054              :                 }
    5055              :             };
    5056              :         }
    5057              : 
    5058              :         // Call into pageserver API to find out if the destination secondary location is warm enough for a reasonably smooth migration: we
    5059              :         // do this so that we avoid spawning a Reconciler that would have to wait minutes/hours for a destination to warm up: that reconciler
    5060              :         // would hold a precious reconcile semaphore unit the whole time it was waiting for the destination to warm up.
    5061            0 :         let results = self
    5062            0 :             .tenant_for_shards_api(
    5063            0 :                 want_secondary_status
    5064            0 :                     .iter()
    5065            0 :                     .map(|i| (i.0, i.1.clone()))
    5066            0 :                     .collect(),
    5067            0 :                 |tenant_shard_id, client| async move {
    5068            0 :                     client.tenant_secondary_status(tenant_shard_id).await
    5069            0 :                 },
    5070            0 :                 1,
    5071            0 :                 1,
    5072            0 :                 SHORT_RECONCILE_TIMEOUT,
    5073            0 :                 &self.cancel,
    5074            0 :             )
    5075            0 :             .await;
    5076              : 
    5077            0 :         for ((tenant_shard_id, node, optimization), secondary_status) in
    5078            0 :             want_secondary_status.into_iter().zip(results.into_iter())
    5079              :         {
    5080            0 :             match secondary_status {
    5081            0 :                 Err(e) => {
    5082            0 :                     tracing::info!("Skipping migration of {tenant_shard_id} to {node}, error querying secondary: {e}");
    5083              :                 }
    5084            0 :                 Ok(progress) => {
    5085            0 :                     // We require secondary locations to have less than 10GiB of downloads pending before we will use
    5086            0 :                     // them in an optimization
    5087            0 :                     const DOWNLOAD_FRESHNESS_THRESHOLD: u64 = 10 * 1024 * 1024 * 1024;
    5088            0 : 
    5089            0 :                     if progress.heatmap_mtime.is_none()
    5090            0 :                         || progress.bytes_total < DOWNLOAD_FRESHNESS_THRESHOLD
    5091            0 :                             && progress.bytes_downloaded != progress.bytes_total
    5092            0 :                         || progress.bytes_total - progress.bytes_downloaded
    5093            0 :                             > DOWNLOAD_FRESHNESS_THRESHOLD
    5094              :                     {
    5095            0 :                         tracing::info!("Skipping migration of {tenant_shard_id} to {node} because secondary isn't ready: {progress:?}");
    5096              :                     } else {
    5097              :                         // Location looks ready: proceed
    5098            0 :                         tracing::info!(
    5099            0 :                             "{tenant_shard_id} secondary on {node} is warm enough for migration: {progress:?}"
    5100              :                         );
    5101            0 :                         validated_work.push((tenant_shard_id, optimization))
    5102              :                     }
    5103              :                 }
    5104              :             }
    5105              :         }
    5106              : 
    5107            0 :         validated_work
    5108            0 :     }
    5109              : 
    5110              :     /// Look for shards which are oversized and in need of splitting
    5111            0 :     async fn autosplit_tenants(self: &Arc<Self>) {
    5112            0 :         let Some(split_threshold) = self.config.split_threshold else {
    5113              :             // Auto-splitting is disabled
    5114            0 :             return;
    5115              :         };
    5116              : 
    5117            0 :         let nodes = self.inner.read().unwrap().nodes.clone();
    5118            0 : 
    5119            0 :         const SPLIT_TO_MAX: ShardCount = ShardCount::new(8);
    5120            0 : 
    5121            0 :         let mut top_n = Vec::new();
    5122            0 : 
    5123            0 :         // Call into each node to look for big tenants
    5124            0 :         let top_n_request = TopTenantShardsRequest {
    5125            0 :             // We currently split based on logical size, for simplicity: logical size is a signal of
    5126            0 :             // the user's intent to run a large database, whereas physical/resident size can be symptoms
    5127            0 :             // of compaction issues.  Eventually we should switch to using resident size to bound the
    5128            0 :             // disk space impact of one shard.
    5129            0 :             order_by: models::TenantSorting::MaxLogicalSize,
    5130            0 :             limit: 10,
    5131            0 :             where_shards_lt: Some(SPLIT_TO_MAX),
    5132            0 :             where_gt: Some(split_threshold),
    5133            0 :         };
    5134            0 :         for node in nodes.values() {
    5135            0 :             let request_ref = &top_n_request;
    5136            0 :             match node
    5137            0 :                 .with_client_retries(
    5138            0 :                     |client| async move {
    5139            0 :                         let request = request_ref.clone();
    5140            0 :                         client.top_tenant_shards(request.clone()).await
    5141            0 :                     },
    5142            0 :                     &self.config.jwt_token,
    5143            0 :                     3,
    5144            0 :                     3,
    5145            0 :                     Duration::from_secs(5),
    5146            0 :                     &self.cancel,
    5147            0 :                 )
    5148            0 :                 .await
    5149              :             {
    5150            0 :                 Some(Ok(node_top_n)) => {
    5151            0 :                     top_n.extend(node_top_n.shards.into_iter());
    5152            0 :                 }
    5153              :                 Some(Err(mgmt_api::Error::Cancelled)) => {
    5154            0 :                     continue;
    5155              :                 }
    5156            0 :                 Some(Err(e)) => {
    5157            0 :                     tracing::warn!("Failed to fetch top N tenants from {node}: {e}");
    5158            0 :                     continue;
    5159              :                 }
    5160              :                 None => {
    5161              :                     // Node is shutting down
    5162            0 :                     continue;
    5163              :                 }
    5164              :             };
    5165              :         }
    5166              : 
    5167              :         // Pick the biggest tenant to split first
    5168            0 :         top_n.sort_by_key(|i| i.resident_size);
    5169            0 :         let Some(split_candidate) = top_n.into_iter().next() else {
    5170            0 :             tracing::debug!("No split-elegible shards found");
    5171            0 :             return;
    5172              :         };
    5173              : 
    5174              :         // We spawn a task to run this, so it's exactly like some external API client requesting it.  We don't
    5175              :         // want to block the background reconcile loop on this.
    5176            0 :         tracing::info!("Auto-splitting tenant for size threshold {split_threshold}: current size {split_candidate:?}");
    5177              : 
    5178            0 :         let this = self.clone();
    5179            0 :         tokio::spawn(
    5180            0 :             async move {
    5181            0 :                 match this
    5182            0 :                     .tenant_shard_split(
    5183            0 :                         split_candidate.id.tenant_id,
    5184            0 :                         TenantShardSplitRequest {
    5185            0 :                             // Always split to the max number of shards: this avoids stepping through
    5186            0 :                             // intervening shard counts and encountering the overrhead of a split+cleanup
    5187            0 :                             // each time as a tenant grows, and is not too expensive because our max shard
    5188            0 :                             // count is relatively low anyway.
    5189            0 :                             // This policy will be adjusted in future once we support higher shard count.
    5190            0 :                             new_shard_count: SPLIT_TO_MAX.literal(),
    5191            0 :                             new_stripe_size: Some(ShardParameters::DEFAULT_STRIPE_SIZE),
    5192            0 :                         },
    5193            0 :                     )
    5194            0 :                     .await
    5195              :                 {
    5196              :                     Ok(_) => {
    5197            0 :                         tracing::info!("Successful auto-split");
    5198              :                     }
    5199            0 :                     Err(e) => {
    5200            0 :                         tracing::error!("Auto-split failed: {e}");
    5201              :                     }
    5202              :                 }
    5203            0 :             }
    5204            0 :             .instrument(tracing::info_span!("auto_split", tenant_id=%split_candidate.id.tenant_id)),
    5205              :         );
    5206            0 :     }
    5207              : 
    5208              :     /// Useful for tests: run whatever work a background [`Self::reconcile_all`] would have done, but
    5209              :     /// also wait for any generated Reconcilers to complete.  Calling this until it returns zero should
    5210              :     /// put the system into a quiescent state where future background reconciliations won't do anything.
    5211            0 :     pub(crate) async fn reconcile_all_now(&self) -> Result<usize, ReconcileWaitError> {
    5212            0 :         let reconciles_spawned = self.reconcile_all();
    5213            0 :         let reconciles_spawned = if reconciles_spawned == 0 {
    5214              :             // Only optimize when we are otherwise idle
    5215            0 :             self.optimize_all().await
    5216              :         } else {
    5217            0 :             reconciles_spawned
    5218              :         };
    5219              : 
    5220            0 :         let waiters = {
    5221            0 :             let mut waiters = Vec::new();
    5222            0 :             let locked = self.inner.read().unwrap();
    5223            0 :             for (_tenant_shard_id, shard) in locked.tenants.iter() {
    5224            0 :                 if let Some(waiter) = shard.get_waiter() {
    5225            0 :                     waiters.push(waiter);
    5226            0 :                 }
    5227              :             }
    5228            0 :             waiters
    5229            0 :         };
    5230            0 : 
    5231            0 :         let waiter_count = waiters.len();
    5232            0 :         match self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    5233            0 :             Ok(()) => {}
    5234            0 :             Err(ReconcileWaitError::Failed(_, reconcile_error))
    5235            0 :                 if matches!(*reconcile_error, ReconcileError::Cancel) =>
    5236            0 :             {
    5237            0 :                 // Ignore reconciler cancel errors: this reconciler might have shut down
    5238            0 :                 // because some other change superceded it.  We will return a nonzero number,
    5239            0 :                 // so the caller knows they might have to call again to quiesce the system.
    5240            0 :             }
    5241            0 :             Err(e) => {
    5242            0 :                 return Err(e);
    5243              :             }
    5244              :         };
    5245              : 
    5246            0 :         tracing::info!(
    5247            0 :             "{} reconciles in reconcile_all, {} waiters",
    5248              :             reconciles_spawned,
    5249              :             waiter_count
    5250              :         );
    5251              : 
    5252            0 :         Ok(std::cmp::max(waiter_count, reconciles_spawned))
    5253            0 :     }
    5254              : 
    5255            0 :     pub async fn shutdown(&self) {
    5256            0 :         // Note that this already stops processing any results from reconciles: so
    5257            0 :         // we do not expect that our [`TenantShard`] objects will reach a neat
    5258            0 :         // final state.
    5259            0 :         self.cancel.cancel();
    5260            0 : 
    5261            0 :         // The cancellation tokens in [`crate::reconciler::Reconciler`] are children
    5262            0 :         // of our cancellation token, so we do not need to explicitly cancel each of
    5263            0 :         // them.
    5264            0 : 
    5265            0 :         // Background tasks and reconcilers hold gate guards: this waits for them all
    5266            0 :         // to complete.
    5267            0 :         self.gate.close().await;
    5268            0 :     }
    5269              : 
    5270              :     /// Drain a node by moving the shards attached to it as primaries.
    5271              :     /// This is a long running operation and it should run as a separate Tokio task.
    5272            0 :     pub(crate) async fn drain_node(
    5273            0 :         &self,
    5274            0 :         node_id: NodeId,
    5275            0 :         cancel: CancellationToken,
    5276            0 :     ) -> Result<(), OperationError> {
    5277            0 :         let mut last_inspected_shard: Option<TenantShardId> = None;
    5278            0 :         let mut inspected_all_shards = false;
    5279            0 :         let mut waiters = Vec::new();
    5280            0 :         let mut schedule_context = ScheduleContext::default();
    5281              : 
    5282            0 :         while !inspected_all_shards {
    5283            0 :             if cancel.is_cancelled() {
    5284            0 :                 return Err(OperationError::Cancelled);
    5285            0 :             }
    5286            0 : 
    5287            0 :             {
    5288            0 :                 let mut locked = self.inner.write().unwrap();
    5289            0 :                 let (nodes, tenants, scheduler) = locked.parts_mut();
    5290              : 
    5291            0 :                 let node = nodes.get(&node_id).ok_or(OperationError::NodeStateChanged(
    5292            0 :                     format!("node {node_id} was removed").into(),
    5293            0 :                 ))?;
    5294              : 
    5295            0 :                 let current_policy = node.get_scheduling();
    5296            0 :                 if !matches!(current_policy, NodeSchedulingPolicy::Draining) {
    5297              :                     // TODO(vlad): maybe cancel pending reconciles before erroring out. need to think
    5298              :                     // about it
    5299            0 :                     return Err(OperationError::NodeStateChanged(
    5300            0 :                         format!("node {node_id} changed state to {current_policy:?}").into(),
    5301            0 :                     ));
    5302            0 :                 }
    5303            0 : 
    5304            0 :                 let mut cursor = tenants.iter_mut().skip_while({
    5305            0 :                     let skip_past = last_inspected_shard;
    5306            0 :                     move |(tid, _)| match skip_past {
    5307            0 :                         Some(last) => **tid != last,
    5308            0 :                         None => false,
    5309            0 :                     }
    5310            0 :                 });
    5311              : 
    5312            0 :                 while waiters.len() < MAX_RECONCILES_PER_OPERATION {
    5313            0 :                     let (tid, tenant_shard) = match cursor.next() {
    5314            0 :                         Some(some) => some,
    5315              :                         None => {
    5316            0 :                             inspected_all_shards = true;
    5317            0 :                             break;
    5318              :                         }
    5319              :                     };
    5320              : 
    5321            0 :                     if tenant_shard.intent.demote_attached(scheduler, node_id) {
    5322            0 :                         match tenant_shard.schedule(scheduler, &mut schedule_context) {
    5323            0 :                             Err(e) => {
    5324            0 :                                 tracing::warn!(
    5325            0 :                                     tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    5326            0 :                                     "Scheduling error when draining pageserver {} : {e}", node_id
    5327              :                                 );
    5328              :                             }
    5329              :                             Ok(()) => {
    5330            0 :                                 let scheduled_to = tenant_shard.intent.get_attached();
    5331            0 :                                 tracing::info!(
    5332            0 :                                     tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    5333            0 :                                     "Rescheduled shard while draining node {}: {} -> {:?}",
    5334              :                                     node_id,
    5335              :                                     node_id,
    5336              :                                     scheduled_to
    5337              :                                 );
    5338              : 
    5339            0 :                                 let waiter = self.maybe_reconcile_shard(tenant_shard, nodes);
    5340            0 :                                 if let Some(some) = waiter {
    5341            0 :                                     waiters.push(some);
    5342            0 :                                 }
    5343              :                             }
    5344              :                         }
    5345            0 :                     }
    5346              : 
    5347            0 :                     last_inspected_shard = Some(*tid);
    5348              :                 }
    5349              :             }
    5350              : 
    5351            0 :             waiters = self
    5352            0 :                 .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
    5353            0 :                 .await;
    5354              :         }
    5355              : 
    5356            0 :         while !waiters.is_empty() {
    5357            0 :             tracing::info!("Awaiting {} pending drain reconciliations", waiters.len());
    5358              : 
    5359            0 :             waiters = self
    5360            0 :                 .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
    5361            0 :                 .await;
    5362              :         }
    5363              : 
    5364              :         // At this point we have done the best we could to drain shards from this node.
    5365              :         // Set the node scheduling policy to `[NodeSchedulingPolicy::PauseForRestart]`
    5366              :         // to complete the drain.
    5367            0 :         if let Err(err) = self
    5368            0 :             .node_configure(node_id, None, Some(NodeSchedulingPolicy::PauseForRestart))
    5369            0 :             .await
    5370              :         {
    5371              :             // This is not fatal. Anything that is polling the node scheduling policy to detect
    5372              :             // the end of the drain operations will hang, but all such places should enforce an
    5373              :             // overall timeout. The scheduling policy will be updated upon node re-attach and/or
    5374              :             // by the counterpart fill operation.
    5375            0 :             return Err(OperationError::FinalizeError(
    5376            0 :                 format!(
    5377            0 :                     "Failed to finalise drain of {node_id} by setting scheduling policy to PauseForRestart: {err}"
    5378            0 :                 )
    5379            0 :                 .into(),
    5380            0 :             ));
    5381            0 :         }
    5382            0 : 
    5383            0 :         Ok(())
    5384            0 :     }
    5385              : 
    5386              :     /// Create a node fill plan (pick secondaries to promote) that meets the following requirements:
    5387              :     /// 1. The node should be filled until it reaches the expected cluster average of
    5388              :     /// attached shards. If there are not enough secondaries on the node, the plan stops early.
    5389              :     /// 2. Select tenant shards to promote such that the number of attached shards is balanced
    5390              :     /// throughout the cluster. We achieve this by picking tenant shards from each node,
    5391              :     /// starting from the ones with the largest number of attached shards, until the node
    5392              :     /// reaches the expected cluster average.
    5393            0 :     fn fill_node_plan(&self, node_id: NodeId) -> Vec<TenantShardId> {
    5394            0 :         let mut locked = self.inner.write().unwrap();
    5395            0 :         let fill_requirement = locked.scheduler.compute_fill_requirement(node_id);
    5396            0 : 
    5397            0 :         let mut tids_by_node = locked
    5398            0 :             .tenants
    5399            0 :             .iter_mut()
    5400            0 :             .filter_map(|(tid, tenant_shard)| {
    5401            0 :                 if tenant_shard.intent.get_secondary().contains(&node_id) {
    5402            0 :                     if let Some(primary) = tenant_shard.intent.get_attached() {
    5403            0 :                         return Some((*primary, *tid));
    5404            0 :                     }
    5405            0 :                 }
    5406              : 
    5407            0 :                 None
    5408            0 :             })
    5409            0 :             .into_group_map();
    5410            0 : 
    5411            0 :         let expected_attached = locked.scheduler.expected_attached_shard_count();
    5412            0 :         let nodes_by_load = locked.scheduler.nodes_by_attached_shard_count();
    5413            0 : 
    5414            0 :         let mut plan = Vec::new();
    5415            0 :         for (node_id, attached) in nodes_by_load {
    5416            0 :             if plan.len() >= fill_requirement
    5417            0 :                 || tids_by_node.is_empty()
    5418            0 :                 || attached <= expected_attached
    5419              :             {
    5420            0 :                 break;
    5421            0 :             }
    5422            0 : 
    5423            0 :             let can_take = attached - expected_attached;
    5424            0 :             let mut remove_node = false;
    5425            0 :             for _ in 0..can_take {
    5426            0 :                 match tids_by_node.get_mut(&node_id) {
    5427            0 :                     Some(tids) => match tids.pop() {
    5428            0 :                         Some(tid) => {
    5429            0 :                             plan.push(tid);
    5430            0 :                         }
    5431              :                         None => {
    5432            0 :                             remove_node = true;
    5433            0 :                             break;
    5434              :                         }
    5435              :                     },
    5436              :                     None => {
    5437            0 :                         break;
    5438              :                     }
    5439              :                 }
    5440              :             }
    5441              : 
    5442            0 :             if remove_node {
    5443            0 :                 tids_by_node.remove(&node_id);
    5444            0 :             }
    5445              :         }
    5446              : 
    5447            0 :         plan
    5448            0 :     }
    5449              : 
    5450              :     /// Fill a node by promoting its secondaries until the cluster is balanced
    5451              :     /// with regards to attached shard counts. Note that this operation only
    5452              :     /// makes sense as a counterpart to the drain implemented in [`Service::drain_node`].
    5453              :     /// This is a long running operation and it should run as a separate Tokio task.
    5454            0 :     pub(crate) async fn fill_node(
    5455            0 :         &self,
    5456            0 :         node_id: NodeId,
    5457            0 :         cancel: CancellationToken,
    5458            0 :     ) -> Result<(), OperationError> {
    5459            0 :         // TODO(vlad): Currently this operates on the assumption that all
    5460            0 :         // secondaries are warm. This is not always true (e.g. we just migrated the
    5461            0 :         // tenant). Take that into consideration by checking the secondary status.
    5462            0 :         let mut tids_to_promote = self.fill_node_plan(node_id);
    5463            0 : 
    5464            0 :         let mut waiters = Vec::new();
    5465            0 :         let mut schedule_context = ScheduleContext::default();
    5466              : 
    5467              :         // Execute the plan we've composed above. Before aplying each move from the plan,
    5468              :         // we validate to ensure that it has not gone stale in the meantime.
    5469            0 :         while !tids_to_promote.is_empty() {
    5470            0 :             if cancel.is_cancelled() {
    5471            0 :                 return Err(OperationError::Cancelled);
    5472            0 :             }
    5473            0 : 
    5474            0 :             {
    5475            0 :                 let mut locked = self.inner.write().unwrap();
    5476            0 :                 let (nodes, tenants, scheduler) = locked.parts_mut();
    5477              : 
    5478            0 :                 let node = nodes.get(&node_id).ok_or(OperationError::NodeStateChanged(
    5479            0 :                     format!("node {node_id} was removed").into(),
    5480            0 :                 ))?;
    5481              : 
    5482            0 :                 let current_policy = node.get_scheduling();
    5483            0 :                 if !matches!(current_policy, NodeSchedulingPolicy::Filling) {
    5484              :                     // TODO(vlad): maybe cancel pending reconciles before erroring out. need to think
    5485              :                     // about it
    5486            0 :                     return Err(OperationError::NodeStateChanged(
    5487            0 :                         format!("node {node_id} changed state to {current_policy:?}").into(),
    5488            0 :                     ));
    5489            0 :                 }
    5490              : 
    5491            0 :                 while waiters.len() < MAX_RECONCILES_PER_OPERATION {
    5492            0 :                     if let Some(tid) = tids_to_promote.pop() {
    5493            0 :                         if let Some(tenant_shard) = tenants.get_mut(&tid) {
    5494              :                             // If the node being filled is not a secondary anymore,
    5495              :                             // skip the promotion.
    5496            0 :                             if !tenant_shard.intent.get_secondary().contains(&node_id) {
    5497            0 :                                 continue;
    5498            0 :                             }
    5499            0 : 
    5500            0 :                             let previously_attached_to = *tenant_shard.intent.get_attached();
    5501            0 : 
    5502            0 :                             tenant_shard.intent.promote_attached(scheduler, node_id);
    5503            0 :                             match tenant_shard.schedule(scheduler, &mut schedule_context) {
    5504            0 :                                 Err(e) => {
    5505            0 :                                     tracing::warn!(
    5506            0 :                                         tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    5507            0 :                                         "Scheduling error when filling pageserver {} : {e}", node_id
    5508              :                                     );
    5509              :                                 }
    5510              :                                 Ok(()) => {
    5511            0 :                                     tracing::info!(
    5512            0 :                                         tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    5513            0 :                                         "Rescheduled shard while filling node {}: {:?} -> {}",
    5514              :                                         node_id,
    5515              :                                         previously_attached_to,
    5516              :                                         node_id
    5517              :                                     );
    5518              : 
    5519            0 :                                     if let Some(waiter) =
    5520            0 :                                         self.maybe_reconcile_shard(tenant_shard, nodes)
    5521            0 :                                     {
    5522            0 :                                         waiters.push(waiter);
    5523            0 :                                     }
    5524              :                                 }
    5525              :                             }
    5526            0 :                         }
    5527              :                     } else {
    5528            0 :                         break;
    5529              :                     }
    5530              :                 }
    5531              :             }
    5532              : 
    5533            0 :             waiters = self
    5534            0 :                 .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
    5535            0 :                 .await;
    5536              :         }
    5537              : 
    5538            0 :         while !waiters.is_empty() {
    5539            0 :             tracing::info!("Awaiting {} pending fill reconciliations", waiters.len());
    5540              : 
    5541            0 :             waiters = self
    5542            0 :                 .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
    5543            0 :                 .await;
    5544              :         }
    5545              : 
    5546            0 :         if let Err(err) = self
    5547            0 :             .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
    5548            0 :             .await
    5549              :         {
    5550              :             // This isn't a huge issue since the filling process starts upon request. However, it
    5551              :             // will prevent the next drain from starting. The only case in which this can fail
    5552              :             // is database unavailability. Such a case will require manual intervention.
    5553            0 :             return Err(OperationError::FinalizeError(
    5554            0 :                 format!("Failed to finalise fill of {node_id} by setting scheduling policy to Active: {err}")
    5555            0 :                     .into(),
    5556            0 :             ));
    5557            0 :         }
    5558            0 : 
    5559            0 :         Ok(())
    5560            0 :     }
    5561              : }
        

Generated by: LCOV version 2.1-beta