LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: 1c072cf775425a8f441e533586eea4edd880d500.info Lines: 0.0 % 4805 0
Test Date: 2025-02-14 11:35:56 Functions: 0.0 % 429 0

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

Generated by: LCOV version 2.1-beta