LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: 90b23405d17e36048d3bb64e314067f397803f1b.info Lines: 0.0 % 4116 0
Test Date: 2024-09-20 13:14:58 Functions: 0.0 % 399 0

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

Generated by: LCOV version 2.1-beta