LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: bb45db3982713bfd5bec075773079136e362195e.info Lines: 0.0 % 4357 0
Test Date: 2024-12-11 15:53:32 Functions: 0.0 % 413 0

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

Generated by: LCOV version 2.1-beta