LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: 301bdf92abcf0ea5a6eae33176b2b7ec68543c11.info Lines: 5.5 % 5807 321
Test Date: 2025-04-25 09:17:05 Functions: 0.4 % 517 2

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

Generated by: LCOV version 2.1-beta