LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: ae4948feae6a1d420c855050eb8c189119446a71.info Lines: 0.0 % 5116 0
Test Date: 2025-03-18 18:33:46 Functions: 0.0 % 476 0

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

Generated by: LCOV version 2.1-beta