LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: 4be46b1c0003aa3bbac9ade362c676b419df4c20.info Lines: 4.4 % 5850 258
Test Date: 2025-07-22 17:50:06 Functions: 0.3 % 589 2

            Line data    Source code
       1              : pub mod chaos_injector;
       2              : pub mod feature_flag;
       3              : pub(crate) mod safekeeper_reconciler;
       4              : mod safekeeper_service;
       5              : mod tenant_shard_iterator;
       6              : 
       7              : use std::borrow::Cow;
       8              : use std::cmp::Ordering;
       9              : use std::collections::{BTreeMap, HashMap, HashSet};
      10              : use std::error::Error;
      11              : use std::num::NonZeroU32;
      12              : use std::ops::{Deref, DerefMut};
      13              : use std::path::PathBuf;
      14              : use std::str::FromStr;
      15              : use std::sync::{Arc, OnceLock};
      16              : use std::time::{Duration, Instant, SystemTime};
      17              : 
      18              : use anyhow::Context;
      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::config::PostHogConfig;
      29              : use pageserver_api::controller_api::{
      30              :     AvailabilityZone, MetadataHealthRecord, MetadataHealthUpdateRequest, NodeAvailability,
      31              :     NodeRegisterRequest, NodeSchedulingPolicy, NodeShard, NodeShardResponse, PlacementPolicy,
      32              :     ShardSchedulingPolicy, ShardsPreferredAzsRequest, ShardsPreferredAzsResponse,
      33              :     SkSchedulingPolicy, TenantCreateRequest, TenantCreateResponse, TenantCreateResponseShard,
      34              :     TenantDescribeResponse, TenantDescribeResponseShard, TenantLocateResponse, TenantPolicyRequest,
      35              :     TenantShardMigrateRequest, TenantShardMigrateResponse, TenantTimelineDescribeResponse,
      36              : };
      37              : use pageserver_api::models::{
      38              :     self, DetachBehavior, LocationConfig, LocationConfigListResponse, LocationConfigMode, LsnLease,
      39              :     PageserverUtilization, SecondaryProgress, ShardImportStatus, ShardParameters, TenantConfig,
      40              :     TenantConfigPatchRequest, TenantConfigRequest, TenantLocationConfigRequest,
      41              :     TenantLocationConfigResponse, TenantShardLocation, TenantShardSplitRequest,
      42              :     TenantShardSplitResponse, TenantSorting, TenantTimeTravelRequest,
      43              :     TimelineArchivalConfigRequest, TimelineCreateRequest, TimelineCreateResponseStorcon,
      44              :     TimelineInfo, TopTenantShardItem, TopTenantShardsRequest,
      45              : };
      46              : use pageserver_api::shard::{
      47              :     DEFAULT_STRIPE_SIZE, ShardCount, ShardIdentity, ShardNumber, ShardStripeSize, TenantShardId,
      48              : };
      49              : use pageserver_api::upcall_api::{
      50              :     PutTimelineImportStatusRequest, ReAttachRequest, ReAttachResponse, ReAttachResponseTenant,
      51              :     TimelineImportStatusRequest, ValidateRequest, ValidateResponse, ValidateResponseTenant,
      52              : };
      53              : use pageserver_client::{BlockUnblock, mgmt_api};
      54              : use reqwest::{Certificate, StatusCode};
      55              : use safekeeper_api::models::SafekeeperUtilization;
      56              : use safekeeper_reconciler::SafekeeperReconcilers;
      57              : use tenant_shard_iterator::{TenantShardExclusiveIterator, create_shared_shard_iterator};
      58              : use tokio::sync::TryAcquireError;
      59              : use tokio::sync::mpsc::error::TrySendError;
      60              : use tokio_util::sync::CancellationToken;
      61              : use tracing::{Instrument, debug, error, info, info_span, instrument, warn};
      62              : use utils::completion::Barrier;
      63              : use utils::env;
      64              : use utils::generation::Generation;
      65              : use utils::id::{NodeId, TenantId, TimelineId};
      66              : use utils::lsn::Lsn;
      67              : use utils::shard::ShardIndex;
      68              : use utils::sync::gate::{Gate, GateGuard};
      69              : use utils::{failpoint_support, pausable_failpoint};
      70              : 
      71              : use crate::background_node_operations::{
      72              :     Delete, Drain, Fill, MAX_RECONCILES_PER_OPERATION, Operation, OperationError, OperationHandler,
      73              : };
      74              : use crate::compute_hook::{self, ComputeHook, NotifyError};
      75              : use crate::heartbeater::{Heartbeater, PageserverState, SafekeeperState};
      76              : use crate::id_lock_map::{
      77              :     IdLockMap, TracingExclusiveGuard, trace_exclusive_lock, trace_shared_lock,
      78              : };
      79              : use crate::leadership::Leadership;
      80              : use crate::metrics;
      81              : use crate::node::{AvailabilityTransition, Node};
      82              : use crate::operation_utils::{self, TenantShardDrain};
      83              : use crate::pageserver_client::PageserverClient;
      84              : use crate::peer_client::GlobalObservedState;
      85              : use crate::persistence::split_state::SplitState;
      86              : use crate::persistence::{
      87              :     AbortShardSplitStatus, ControllerPersistence, DatabaseError, DatabaseResult,
      88              :     MetadataHealthPersistence, Persistence, ShardGenerationState, TenantFilter,
      89              :     TenantShardPersistence,
      90              : };
      91              : use crate::reconciler::{
      92              :     ReconcileError, ReconcileUnits, ReconcilerConfig, ReconcilerConfigBuilder, ReconcilerPriority,
      93              :     attached_location_conf,
      94              : };
      95              : use crate::safekeeper::Safekeeper;
      96              : use crate::scheduler::{
      97              :     AttachedShardTag, MaySchedule, ScheduleContext, ScheduleError, ScheduleMode, Scheduler,
      98              : };
      99              : use crate::tenant_shard::{
     100              :     IntentState, MigrateAttachment, ObservedState, ObservedStateDelta, ObservedStateLocation,
     101              :     ReconcileNeeded, ReconcileResult, ReconcileWaitError, ReconcilerStatus, ReconcilerWaiter,
     102              :     ScheduleOptimization, ScheduleOptimizationAction, TenantShard,
     103              : };
     104              : use crate::timeline_import::{
     105              :     FinalizingImport, ImportResult, ShardImportStatuses, TimelineImport,
     106              :     TimelineImportFinalizeError, TimelineImportState, UpcallClient,
     107              : };
     108              : 
     109              : const WAITER_OPERATION_POLL_TIMEOUT: Duration = Duration::from_millis(500);
     110              : 
     111              : // For operations that should be quick, like attaching a new tenant
     112              : const SHORT_RECONCILE_TIMEOUT: Duration = Duration::from_secs(5);
     113              : 
     114              : // For operations that might be slow, like migrating a tenant with
     115              : // some data in it.
     116              : pub const RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
     117              : 
     118              : // If we receive a call using Secondary mode initially, it will omit generation.  We will initialize
     119              : // tenant shards into this generation, and as long as it remains in this generation, we will accept
     120              : // input generation from future requests as authoritative.
     121              : const INITIAL_GENERATION: Generation = Generation::new(0);
     122              : 
     123              : /// How long [`Service::startup_reconcile`] is allowed to take before it should give
     124              : /// up on unresponsive pageservers and proceed.
     125              : pub(crate) const STARTUP_RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
     126              : 
     127              : /// How long a node may be unresponsive to heartbeats before we declare it offline.
     128              : /// This must be long enough to cover node restarts as well as normal operations: in future
     129              : pub const MAX_OFFLINE_INTERVAL_DEFAULT: Duration = Duration::from_secs(30);
     130              : 
     131              : /// How long a node may be unresponsive to heartbeats during start up before we declare it
     132              : /// offline.
     133              : ///
     134              : /// This is much more lenient than [`MAX_OFFLINE_INTERVAL_DEFAULT`] since the pageserver's
     135              : /// handling of the re-attach response may take a long time and blocks heartbeats from
     136              : /// being handled on the pageserver side.
     137              : pub const MAX_WARMING_UP_INTERVAL_DEFAULT: Duration = Duration::from_secs(300);
     138              : 
     139              : /// How often to send heartbeats to registered nodes?
     140              : pub const HEARTBEAT_INTERVAL_DEFAULT: Duration = Duration::from_secs(5);
     141              : 
     142              : /// How long is too long for a reconciliation?
     143              : pub const LONG_RECONCILE_THRESHOLD_DEFAULT: Duration = Duration::from_secs(120);
     144              : 
     145              : #[derive(Clone, strum_macros::Display)]
     146              : enum TenantOperations {
     147              :     Create,
     148              :     LocationConfig,
     149              :     ConfigSet,
     150              :     ConfigPatch,
     151              :     TimeTravelRemoteStorage,
     152              :     Delete,
     153              :     UpdatePolicy,
     154              :     ShardSplit,
     155              :     SecondaryDownload,
     156              :     TimelineCreate,
     157              :     TimelineDelete,
     158              :     AttachHook,
     159              :     TimelineArchivalConfig,
     160              :     TimelineDetachAncestor,
     161              :     TimelineGcBlockUnblock,
     162              :     DropDetached,
     163              :     DownloadHeatmapLayers,
     164              :     TimelineLsnLease,
     165              :     TimelineSafekeeperMigrate,
     166              : }
     167              : 
     168              : #[derive(Clone, strum_macros::Display)]
     169              : enum NodeOperations {
     170              :     Register,
     171              :     Configure,
     172              :     Delete,
     173              :     DeleteTombstone,
     174              : }
     175              : 
     176              : /// The leadership status for the storage controller process.
     177              : /// Allowed transitions are:
     178              : /// 1. Leader -> SteppedDown
     179              : /// 2. Candidate -> Leader
     180              : #[derive(
     181              :     Eq,
     182              :     PartialEq,
     183              :     Copy,
     184              :     Clone,
     185              :     strum_macros::Display,
     186              :     strum_macros::EnumIter,
     187              :     measured::FixedCardinalityLabel,
     188              : )]
     189              : #[strum(serialize_all = "snake_case")]
     190              : pub(crate) enum LeadershipStatus {
     191              :     /// This is the steady state where the storage controller can produce
     192              :     /// side effects in the cluster.
     193              :     Leader,
     194              :     /// We've been notified to step down by another candidate. No reconciliations
     195              :     /// take place in this state.
     196              :     SteppedDown,
     197              :     /// Initial state for a new storage controller instance. Will attempt to assume leadership.
     198              :     #[allow(unused)]
     199              :     Candidate,
     200              : }
     201              : 
     202              : enum ShardGenerationValidity {
     203              :     Valid,
     204              :     Mismatched {
     205              :         claimed: Generation,
     206              :         actual: Option<Generation>,
     207              :     },
     208              : }
     209              : 
     210              : pub const RECONCILER_CONCURRENCY_DEFAULT: usize = 128;
     211              : pub const PRIORITY_RECONCILER_CONCURRENCY_DEFAULT: usize = 256;
     212              : pub const SAFEKEEPER_RECONCILER_CONCURRENCY_DEFAULT: usize = 32;
     213              : 
     214              : // Number of consecutive reconciliations that have occurred for one shard,
     215              : // after which the shard is ignored when considering to run optimizations.
     216              : const MAX_CONSECUTIVE_RECONCILES: usize = 10;
     217              : 
     218              : // Depth of the channel used to enqueue shards for reconciliation when they can't do it immediately.
     219              : // This channel is finite-size to avoid using excessive memory if we get into a state where reconciles are finishing more slowly
     220              : // than they're being pushed onto the queue.
     221              : const MAX_DELAYED_RECONCILES: usize = 10000;
     222              : 
     223              : // Top level state available to all HTTP handlers
     224              : struct ServiceState {
     225              :     leadership_status: LeadershipStatus,
     226              : 
     227              :     tenants: BTreeMap<TenantShardId, TenantShard>,
     228              : 
     229              :     nodes: Arc<HashMap<NodeId, Node>>,
     230              : 
     231              :     safekeepers: Arc<HashMap<NodeId, Safekeeper>>,
     232              : 
     233              :     safekeeper_reconcilers: SafekeeperReconcilers,
     234              : 
     235              :     scheduler: Scheduler,
     236              : 
     237              :     /// Ongoing background operation on the cluster if any is running.
     238              :     /// Note that only one such operation may run at any given time,
     239              :     /// hence the type choice.
     240              :     ongoing_operation: Option<OperationHandler>,
     241              : 
     242              :     /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
     243              :     delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
     244              : 
     245              :     /// Tracks ongoing timeline import finalization tasks
     246              :     imports_finalizing: BTreeMap<(TenantId, TimelineId), FinalizingImport>,
     247              : }
     248              : 
     249              : /// Transform an error from a pageserver into an error to return to callers of a storage
     250              : /// controller API.
     251            0 : fn passthrough_api_error(node: &Node, e: mgmt_api::Error) -> ApiError {
     252            0 :     match e {
     253            0 :         mgmt_api::Error::SendRequest(e) => {
     254              :             // Presume errors sending requests are connectivity/availability issues
     255            0 :             ApiError::ResourceUnavailable(format!("{node} error sending request: {e}").into())
     256              :         }
     257            0 :         mgmt_api::Error::ReceiveErrorBody(str) => {
     258              :             // Presume errors receiving body are connectivity/availability issues
     259            0 :             ApiError::ResourceUnavailable(
     260            0 :                 format!("{node} error receiving error body: {str}").into(),
     261            0 :             )
     262              :         }
     263            0 :         mgmt_api::Error::ReceiveBody(err) if err.is_decode() => {
     264              :             // Return 500 for decoding errors.
     265            0 :             ApiError::InternalServerError(anyhow::Error::from(err).context("error decoding body"))
     266              :         }
     267            0 :         mgmt_api::Error::ReceiveBody(err) => {
     268              :             // Presume errors receiving body are connectivity/availability issues except for decoding errors
     269            0 :             let src_str = err.source().map(|e| e.to_string()).unwrap_or_default();
     270            0 :             ApiError::ResourceUnavailable(
     271            0 :                 format!("{node} error receiving error body: {err} {src_str}").into(),
     272            0 :             )
     273              :         }
     274            0 :         mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, msg) => {
     275            0 :             ApiError::NotFound(anyhow::anyhow!(format!("{node}: {msg}")).into())
     276              :         }
     277            0 :         mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg) => {
     278            0 :             ApiError::ResourceUnavailable(format!("{node}: {msg}").into())
     279              :         }
     280            0 :         mgmt_api::Error::ApiError(status @ StatusCode::UNAUTHORIZED, msg)
     281            0 :         | mgmt_api::Error::ApiError(status @ StatusCode::FORBIDDEN, msg) => {
     282              :             // Auth errors talking to a pageserver are not auth errors for the caller: they are
     283              :             // internal server errors, showing that something is wrong with the pageserver or
     284              :             // storage controller's auth configuration.
     285            0 :             ApiError::InternalServerError(anyhow::anyhow!("{node} {status}: {msg}"))
     286              :         }
     287            0 :         mgmt_api::Error::ApiError(status @ StatusCode::TOO_MANY_REQUESTS, msg) => {
     288              :             // Pass through 429 errors: if pageserver is asking us to wait + retry, we in
     289              :             // turn ask our clients to wait + retry
     290            0 :             ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
     291              :         }
     292            0 :         mgmt_api::Error::ApiError(status, msg) => {
     293              :             // Presume general case of pageserver API errors is that we tried to do something
     294              :             // that can't be done right now.
     295            0 :             ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
     296              :         }
     297            0 :         mgmt_api::Error::Cancelled => ApiError::ShuttingDown,
     298            0 :         mgmt_api::Error::Timeout(e) => ApiError::Timeout(e.into()),
     299              :     }
     300            0 : }
     301              : 
     302              : impl ServiceState {
     303            0 :     fn new(
     304            0 :         nodes: HashMap<NodeId, Node>,
     305            0 :         safekeepers: HashMap<NodeId, Safekeeper>,
     306            0 :         tenants: BTreeMap<TenantShardId, TenantShard>,
     307            0 :         scheduler: Scheduler,
     308            0 :         delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
     309            0 :         initial_leadership_status: LeadershipStatus,
     310            0 :         reconcilers_cancel: CancellationToken,
     311            0 :     ) -> Self {
     312            0 :         metrics::update_leadership_status(initial_leadership_status);
     313              : 
     314            0 :         Self {
     315            0 :             leadership_status: initial_leadership_status,
     316            0 :             tenants,
     317            0 :             nodes: Arc::new(nodes),
     318            0 :             safekeepers: Arc::new(safekeepers),
     319            0 :             safekeeper_reconcilers: SafekeeperReconcilers::new(reconcilers_cancel),
     320            0 :             scheduler,
     321            0 :             ongoing_operation: None,
     322            0 :             delayed_reconcile_rx,
     323            0 :             imports_finalizing: Default::default(),
     324            0 :         }
     325            0 :     }
     326              : 
     327            0 :     fn parts_mut(
     328            0 :         &mut self,
     329            0 :     ) -> (
     330            0 :         &mut Arc<HashMap<NodeId, Node>>,
     331            0 :         &mut BTreeMap<TenantShardId, TenantShard>,
     332            0 :         &mut Scheduler,
     333            0 :     ) {
     334            0 :         (&mut self.nodes, &mut self.tenants, &mut self.scheduler)
     335            0 :     }
     336              : 
     337              :     #[allow(clippy::type_complexity)]
     338            0 :     fn parts_mut_sk(
     339            0 :         &mut self,
     340            0 :     ) -> (
     341            0 :         &mut Arc<HashMap<NodeId, Node>>,
     342            0 :         &mut Arc<HashMap<NodeId, Safekeeper>>,
     343            0 :         &mut BTreeMap<TenantShardId, TenantShard>,
     344            0 :         &mut Scheduler,
     345            0 :     ) {
     346            0 :         (
     347            0 :             &mut self.nodes,
     348            0 :             &mut self.safekeepers,
     349            0 :             &mut self.tenants,
     350            0 :             &mut self.scheduler,
     351            0 :         )
     352            0 :     }
     353              : 
     354            0 :     fn get_leadership_status(&self) -> LeadershipStatus {
     355            0 :         self.leadership_status
     356            0 :     }
     357              : 
     358            0 :     fn step_down(&mut self) {
     359            0 :         self.leadership_status = LeadershipStatus::SteppedDown;
     360            0 :         metrics::update_leadership_status(self.leadership_status);
     361            0 :     }
     362              : 
     363            0 :     fn become_leader(&mut self) {
     364            0 :         self.leadership_status = LeadershipStatus::Leader;
     365            0 :         metrics::update_leadership_status(self.leadership_status);
     366            0 :     }
     367              : }
     368              : 
     369              : #[derive(Clone)]
     370              : pub struct Config {
     371              :     // All pageservers managed by one instance of this service must have
     372              :     // the same public key.  This JWT token will be used to authenticate
     373              :     // this service to the pageservers it manages.
     374              :     pub pageserver_jwt_token: Option<String>,
     375              : 
     376              :     // All safekeepers managed by one instance of this service must have
     377              :     // the same public key. This JWT token will be used to authenticate
     378              :     // this service to the safekeepers it manages.
     379              :     pub safekeeper_jwt_token: Option<String>,
     380              : 
     381              :     // This JWT token will be used to authenticate this service to the control plane.
     382              :     pub control_plane_jwt_token: Option<String>,
     383              : 
     384              :     // This JWT token will be used to authenticate with other storage controller instances
     385              :     pub peer_jwt_token: Option<String>,
     386              : 
     387              :     /// Prefix for storage API endpoints of the control plane. We use this prefix to compute
     388              :     /// URLs that we use to send pageserver and safekeeper attachment locations.
     389              :     /// If this is None, the compute hook will assume it is running in a test environment
     390              :     /// and try to invoke neon_local instead.
     391              :     pub control_plane_url: Option<String>,
     392              : 
     393              :     /// Grace period within which a pageserver does not respond to heartbeats, but is still
     394              :     /// considered active. Once the grace period elapses, the next heartbeat failure will
     395              :     /// mark the pagseserver offline.
     396              :     pub max_offline_interval: Duration,
     397              : 
     398              :     /// Extended grace period within which pageserver may not respond to heartbeats.
     399              :     /// This extended grace period kicks in after the node has been drained for restart
     400              :     /// and/or upon handling the re-attach request from a node.
     401              :     pub max_warming_up_interval: Duration,
     402              : 
     403              :     /// How many normal-priority Reconcilers may be spawned concurrently
     404              :     pub reconciler_concurrency: usize,
     405              : 
     406              :     /// How many high-priority Reconcilers may be spawned concurrently
     407              :     pub priority_reconciler_concurrency: usize,
     408              : 
     409              :     /// How many safekeeper reconciles may happen concurrently (per safekeeper)
     410              :     pub safekeeper_reconciler_concurrency: usize,
     411              : 
     412              :     /// How many API requests per second to allow per tenant, across all
     413              :     /// tenant-scoped API endpoints. Further API requests queue until ready.
     414              :     pub tenant_rate_limit: NonZeroU32,
     415              : 
     416              :     /// If a tenant shard's largest timeline (max_logical_size) exceeds this value, all tenant
     417              :     /// shards will be split in 2 until they fall below split_threshold (up to max_split_shards).
     418              :     ///
     419              :     /// This will greedily split into as many shards as necessary to fall below split_threshold, as
     420              :     /// powers of 2: if a tenant shard is 7 times larger than split_threshold, it will split into 8
     421              :     /// immediately, rather than first 2 then 4 then 8.
     422              :     ///
     423              :     /// None or 0 disables auto-splitting.
     424              :     ///
     425              :     /// TODO: consider using total logical size of all timelines instead.
     426              :     pub split_threshold: Option<u64>,
     427              : 
     428              :     /// The maximum number of shards a tenant can be split into during autosplits. Does not affect
     429              :     /// manual split requests. 0 or 1 disables autosplits, as we already have 1 shard.
     430              :     pub max_split_shards: u8,
     431              : 
     432              :     /// The size at which an unsharded tenant should initially split. Ingestion is significantly
     433              :     /// faster with multiple shards, so eagerly splitting below split_threshold will typically speed
     434              :     /// up initial ingestion of large tenants.
     435              :     ///
     436              :     /// This should be below split_threshold, but it is not required. If both split_threshold and
     437              :     /// initial_split_threshold qualify, the largest number of target shards will be used.
     438              :     ///
     439              :     /// Does not apply to already sharded tenants: changing initial_split_threshold or
     440              :     /// initial_split_shards is not retroactive for already-sharded tenants.
     441              :     ///
     442              :     /// None or 0 disables initial splits.
     443              :     pub initial_split_threshold: Option<u64>,
     444              : 
     445              :     /// The number of shards to split into when reaching initial_split_threshold. Will
     446              :     /// be clamped to max_split_shards.
     447              :     ///
     448              :     /// 0 or 1 disables initial splits. Has no effect if initial_split_threshold is disabled.
     449              :     pub initial_split_shards: u8,
     450              : 
     451              :     // TODO: make this cfg(feature  = "testing")
     452              :     pub neon_local_repo_dir: Option<PathBuf>,
     453              : 
     454              :     // Maximum acceptable download lag for the secondary location
     455              :     // while draining a node. If the secondary location is lagging
     456              :     // by more than the configured amount, then the secondary is not
     457              :     // upgraded to primary.
     458              :     pub max_secondary_lag_bytes: Option<u64>,
     459              : 
     460              :     pub heartbeat_interval: Duration,
     461              : 
     462              :     pub address_for_peers: Option<Uri>,
     463              : 
     464              :     pub start_as_candidate: bool,
     465              : 
     466              :     pub long_reconcile_threshold: Duration,
     467              : 
     468              :     pub use_https_pageserver_api: bool,
     469              : 
     470              :     pub use_https_safekeeper_api: bool,
     471              : 
     472              :     pub ssl_ca_certs: Vec<Certificate>,
     473              : 
     474              :     pub timelines_onto_safekeepers: bool,
     475              : 
     476              :     pub use_local_compute_notifications: bool,
     477              : 
     478              :     /// Number of safekeepers to choose for a timeline when creating it.
     479              :     /// Safekeepers will be choosen from different availability zones.
     480              :     pub timeline_safekeeper_count: usize,
     481              : 
     482              :     /// PostHog integration config
     483              :     pub posthog_config: Option<PostHogConfig>,
     484              : 
     485              :     /// When set, actively checks and initiates heatmap downloads/uploads.
     486              :     pub kick_secondary_downloads: bool,
     487              : 
     488              :     /// Timeout used for HTTP client of split requests. [`Duration::MAX`] if None.
     489              :     pub shard_split_request_timeout: Duration,
     490              : 
     491              :     // Feature flag: Whether the storage controller should act to rectify pageserver-reported local disk loss.
     492              :     pub handle_ps_local_disk_loss: bool,
     493              : }
     494              : 
     495              : impl From<DatabaseError> for ApiError {
     496            0 :     fn from(err: DatabaseError) -> ApiError {
     497            0 :         match err {
     498            0 :             DatabaseError::Query(e) => ApiError::InternalServerError(e.into()),
     499              :             // FIXME: ApiError doesn't have an Unavailable variant, but ShuttingDown maps to 503.
     500              :             DatabaseError::Connection(_) | DatabaseError::ConnectionPool(_) => {
     501            0 :                 ApiError::ShuttingDown
     502              :             }
     503            0 :             DatabaseError::Logical(reason) | DatabaseError::Migration(reason) => {
     504            0 :                 ApiError::InternalServerError(anyhow::anyhow!(reason))
     505              :             }
     506            0 :             DatabaseError::Cas(reason) => ApiError::Conflict(reason),
     507              :         }
     508            0 :     }
     509              : }
     510              : 
     511              : enum InitialShardScheduleOutcome {
     512              :     Scheduled(TenantCreateResponseShard),
     513              :     NotScheduled,
     514              :     ShardScheduleError(ScheduleError),
     515              : }
     516              : 
     517              : pub struct Service {
     518              :     inner: Arc<std::sync::RwLock<ServiceState>>,
     519              :     config: Config,
     520              :     persistence: Arc<Persistence>,
     521              :     compute_hook: Arc<ComputeHook>,
     522              :     result_tx: tokio::sync::mpsc::UnboundedSender<ReconcileResultRequest>,
     523              : 
     524              :     heartbeater_ps: Heartbeater<Node, PageserverState>,
     525              :     heartbeater_sk: Heartbeater<Safekeeper, SafekeeperState>,
     526              : 
     527              :     // Channel for background cleanup from failed operations that require cleanup, such as shard split
     528              :     abort_tx: tokio::sync::mpsc::UnboundedSender<TenantShardSplitAbort>,
     529              : 
     530              :     // Locking on a tenant granularity (covers all shards in the tenant):
     531              :     // - Take exclusively for rare operations that mutate the tenant's persistent state (e.g. create/delete/split)
     532              :     // - Take in shared mode for operations that need the set of shards to stay the same to complete reliably (e.g. timeline CRUD)
     533              :     tenant_op_locks: IdLockMap<TenantId, TenantOperations>,
     534              : 
     535              :     // Locking for node-mutating operations: take exclusively for operations that modify the node's persistent state, or
     536              :     // that transition it to/from Active.
     537              :     node_op_locks: IdLockMap<NodeId, NodeOperations>,
     538              : 
     539              :     // Limit how many Reconcilers we will spawn concurrently for normal-priority tasks such as background reconciliations
     540              :     // and reconciliation on startup.
     541              :     reconciler_concurrency: Arc<tokio::sync::Semaphore>,
     542              : 
     543              :     // Limit how many Reconcilers we will spawn concurrently for high-priority tasks such as tenant/timeline CRUD, which
     544              :     // a human user might be waiting for.
     545              :     priority_reconciler_concurrency: Arc<tokio::sync::Semaphore>,
     546              : 
     547              :     /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
     548              :     /// Send into this queue to promptly attempt to reconcile this shard next time units are available.
     549              :     ///
     550              :     /// Note that this state logically lives inside ServiceState, but carrying Sender here makes the code simpler
     551              :     /// by avoiding needing a &mut ref to something inside the ServiceState.  This could be optimized to
     552              :     /// use a VecDeque instead of a channel to reduce synchronization overhead, at the cost of some code complexity.
     553              :     delayed_reconcile_tx: tokio::sync::mpsc::Sender<TenantShardId>,
     554              : 
     555              :     // Process shutdown will fire this token
     556              :     cancel: CancellationToken,
     557              : 
     558              :     // Child token of [`Service::cancel`] used by reconcilers
     559              :     reconcilers_cancel: CancellationToken,
     560              : 
     561              :     // Background tasks will hold this gate
     562              :     gate: Gate,
     563              : 
     564              :     // Reconcilers background tasks will hold this gate
     565              :     reconcilers_gate: Gate,
     566              : 
     567              :     /// This waits for initial reconciliation with pageservers to complete.  Until this barrier
     568              :     /// passes, it isn't safe to do any actions that mutate tenants.
     569              :     pub(crate) startup_complete: Barrier,
     570              : 
     571              :     /// HTTP client with proper CA certs.
     572              :     http_client: reqwest::Client,
     573              : 
     574              :     /// Handle for the step down background task if one was ever requested
     575              :     step_down_barrier: OnceLock<tokio::sync::watch::Receiver<Option<GlobalObservedState>>>,
     576              : }
     577              : 
     578              : impl From<ReconcileWaitError> for ApiError {
     579            0 :     fn from(value: ReconcileWaitError) -> Self {
     580            0 :         match value {
     581            0 :             ReconcileWaitError::Shutdown => ApiError::ShuttingDown,
     582            0 :             e @ ReconcileWaitError::Timeout(_) => ApiError::Timeout(format!("{e}").into()),
     583            0 :             e @ ReconcileWaitError::Failed(..) => ApiError::InternalServerError(anyhow::anyhow!(e)),
     584              :         }
     585            0 :     }
     586              : }
     587              : 
     588              : impl From<OperationError> for ApiError {
     589            0 :     fn from(value: OperationError) -> Self {
     590            0 :         match value {
     591            0 :             OperationError::NodeStateChanged(err)
     592            0 :             | OperationError::FinalizeError(err)
     593            0 :             | OperationError::ImpossibleConstraint(err) => {
     594            0 :                 ApiError::InternalServerError(anyhow::anyhow!(err))
     595              :             }
     596            0 :             OperationError::Cancelled => ApiError::Conflict("Operation was cancelled".into()),
     597              :         }
     598            0 :     }
     599              : }
     600              : 
     601              : #[allow(clippy::large_enum_variant)]
     602              : enum TenantCreateOrUpdate {
     603              :     Create(TenantCreateRequest),
     604              :     Update(Vec<ShardUpdate>),
     605              : }
     606              : 
     607              : struct ShardSplitParams {
     608              :     old_shard_count: ShardCount,
     609              :     new_shard_count: ShardCount,
     610              :     new_stripe_size: Option<ShardStripeSize>,
     611              :     targets: Vec<ShardSplitTarget>,
     612              :     policy: PlacementPolicy,
     613              :     config: TenantConfig,
     614              :     shard_ident: ShardIdentity,
     615              :     preferred_az_id: Option<AvailabilityZone>,
     616              : }
     617              : 
     618              : // When preparing for a shard split, we may either choose to proceed with the split,
     619              : // or find that the work is already done and return NoOp.
     620              : enum ShardSplitAction {
     621              :     Split(Box<ShardSplitParams>),
     622              :     NoOp(TenantShardSplitResponse),
     623              : }
     624              : 
     625              : // A parent shard which will be split
     626              : struct ShardSplitTarget {
     627              :     parent_id: TenantShardId,
     628              :     node: Node,
     629              :     child_ids: Vec<TenantShardId>,
     630              : }
     631              : 
     632              : /// When we tenant shard split operation fails, we may not be able to clean up immediately, because nodes
     633              : /// might not be available.  We therefore use a queue of abort operations processed in the background.
     634              : struct TenantShardSplitAbort {
     635              :     tenant_id: TenantId,
     636              :     /// The target values from the request that failed
     637              :     new_shard_count: ShardCount,
     638              :     new_stripe_size: Option<ShardStripeSize>,
     639              :     /// Until this abort op is complete, no other operations may be done on the tenant
     640              :     _tenant_lock: TracingExclusiveGuard<TenantOperations>,
     641              :     /// The reconciler gate for the duration of the split operation, and any included abort.
     642              :     _gate: GateGuard,
     643              : }
     644              : 
     645              : #[derive(thiserror::Error, Debug)]
     646              : enum TenantShardSplitAbortError {
     647              :     #[error(transparent)]
     648              :     Database(#[from] DatabaseError),
     649              :     #[error(transparent)]
     650              :     Remote(#[from] mgmt_api::Error),
     651              :     #[error("Unavailable")]
     652              :     Unavailable,
     653              : }
     654              : 
     655              : /// Inputs for computing a target shard count for a tenant.
     656              : struct ShardSplitInputs {
     657              :     /// Current shard count.
     658              :     shard_count: ShardCount,
     659              :     /// Total size of largest timeline summed across all shards.
     660              :     max_logical_size: u64,
     661              :     /// Size-based split threshold. Zero if size-based splits are disabled.
     662              :     split_threshold: u64,
     663              :     /// Upper bound on target shards. 0 or 1 disables splits.
     664              :     max_split_shards: u8,
     665              :     /// Initial split threshold. Zero if initial splits are disabled.
     666              :     initial_split_threshold: u64,
     667              :     /// Number of shards for initial splits. 0 or 1 disables initial splits.
     668              :     initial_split_shards: u8,
     669              : }
     670              : 
     671              : struct ShardUpdate {
     672              :     tenant_shard_id: TenantShardId,
     673              :     placement_policy: PlacementPolicy,
     674              :     tenant_config: TenantConfig,
     675              : 
     676              :     /// If this is None, generation is not updated.
     677              :     generation: Option<Generation>,
     678              : 
     679              :     /// If this is None, scheduling policy is not updated.
     680              :     scheduling_policy: Option<ShardSchedulingPolicy>,
     681              : }
     682              : 
     683              : enum StopReconciliationsReason {
     684              :     ShuttingDown,
     685              :     SteppingDown,
     686              : }
     687              : 
     688              : impl std::fmt::Display for StopReconciliationsReason {
     689            0 :     fn fmt(&self, writer: &mut std::fmt::Formatter) -> std::fmt::Result {
     690            0 :         let s = match self {
     691            0 :             Self::ShuttingDown => "Shutting down",
     692            0 :             Self::SteppingDown => "Stepping down",
     693              :         };
     694            0 :         write!(writer, "{s}")
     695            0 :     }
     696              : }
     697              : 
     698              : pub(crate) enum ReconcileResultRequest {
     699              :     ReconcileResult(ReconcileResult),
     700              :     Stop,
     701              : }
     702              : 
     703              : #[derive(Clone)]
     704              : pub(crate) struct MutationLocation {
     705              :     pub(crate) node: Node,
     706              :     pub(crate) generation: Generation,
     707              : }
     708              : 
     709              : #[derive(Clone)]
     710              : pub(crate) struct ShardMutationLocations {
     711              :     pub(crate) latest: MutationLocation,
     712              :     pub(crate) other: Vec<MutationLocation>,
     713              : }
     714              : 
     715              : #[derive(Default, Clone)]
     716              : pub(crate) struct TenantMutationLocations(pub BTreeMap<TenantShardId, ShardMutationLocations>);
     717              : 
     718              : struct ReconcileAllResult {
     719              :     spawned_reconciles: usize,
     720              :     stuck_reconciles: usize,
     721              :     has_delayed_reconciles: bool,
     722              : }
     723              : 
     724              : impl ReconcileAllResult {
     725            0 :     fn new(
     726            0 :         spawned_reconciles: usize,
     727            0 :         stuck_reconciles: usize,
     728            0 :         has_delayed_reconciles: bool,
     729            0 :     ) -> Self {
     730            0 :         assert!(
     731            0 :             spawned_reconciles >= stuck_reconciles,
     732            0 :             "It is impossible to have less spawned reconciles than stuck reconciles"
     733              :         );
     734            0 :         Self {
     735            0 :             spawned_reconciles,
     736            0 :             stuck_reconciles,
     737            0 :             has_delayed_reconciles,
     738            0 :         }
     739            0 :     }
     740              : 
     741              :     /// We can run optimizations only if we don't have any delayed reconciles and
     742              :     /// all spawned reconciles are also stuck reconciles.
     743            0 :     fn can_run_optimizations(&self) -> bool {
     744            0 :         !self.has_delayed_reconciles && self.spawned_reconciles == self.stuck_reconciles
     745            0 :     }
     746              : }
     747              : 
     748              : enum TenantIdOrShardId {
     749              :     TenantId(TenantId),
     750              :     TenantShardId(TenantShardId),
     751              : }
     752              : 
     753              : impl TenantIdOrShardId {
     754            0 :     fn tenant_id(&self) -> TenantId {
     755            0 :         match self {
     756            0 :             TenantIdOrShardId::TenantId(tenant_id) => *tenant_id,
     757            0 :             TenantIdOrShardId::TenantShardId(tenant_shard_id) => tenant_shard_id.tenant_id,
     758              :         }
     759            0 :     }
     760              : 
     761            0 :     fn matches(&self, tenant_shard_id: &TenantShardId) -> bool {
     762            0 :         match self {
     763            0 :             TenantIdOrShardId::TenantId(tenant_id) => tenant_shard_id.tenant_id == *tenant_id,
     764            0 :             TenantIdOrShardId::TenantShardId(this_tenant_shard_id) => {
     765            0 :                 this_tenant_shard_id == tenant_shard_id
     766              :             }
     767              :         }
     768            0 :     }
     769              : }
     770              : 
     771              : impl Service {
     772            0 :     pub fn get_config(&self) -> &Config {
     773            0 :         &self.config
     774            0 :     }
     775              : 
     776            0 :     pub fn get_http_client(&self) -> &reqwest::Client {
     777            0 :         &self.http_client
     778            0 :     }
     779              : 
     780              :     /// Called once on startup, this function attempts to contact all pageservers to build an up-to-date
     781              :     /// view of the world, and determine which pageservers are responsive.
     782              :     #[instrument(skip_all)]
     783              :     async fn startup_reconcile(
     784              :         self: &Arc<Service>,
     785              :         current_leader: Option<ControllerPersistence>,
     786              :         leader_step_down_state: Option<GlobalObservedState>,
     787              :         bg_compute_notify_result_tx: tokio::sync::mpsc::Sender<
     788              :             Result<(), (TenantShardId, NotifyError)>,
     789              :         >,
     790              :     ) {
     791              :         // Startup reconciliation does I/O to other services: whether they
     792              :         // are responsive or not, we should aim to finish within our deadline, because:
     793              :         // - If we don't, a k8s readiness hook watching /ready will kill us.
     794              :         // - While we're waiting for startup reconciliation, we are not fully
     795              :         //   available for end user operations like creating/deleting tenants and timelines.
     796              :         //
     797              :         // We set multiple deadlines to break up the time available between the phases of work: this is
     798              :         // arbitrary, but avoids a situation where the first phase could burn our entire timeout period.
     799              :         let start_at = Instant::now();
     800              :         let node_scan_deadline = start_at
     801              :             .checked_add(STARTUP_RECONCILE_TIMEOUT / 2)
     802              :             .expect("Reconcile timeout is a modest constant");
     803              : 
     804              :         let observed = if let Some(state) = leader_step_down_state {
     805              :             tracing::info!(
     806              :                 "Using observed state received from leader at {}",
     807              :                 current_leader.as_ref().unwrap().address
     808              :             );
     809              : 
     810              :             state
     811              :         } else {
     812              :             self.build_global_observed_state(node_scan_deadline).await
     813              :         };
     814              : 
     815              :         // Accumulate a list of any tenant locations that ought to be detached
     816              :         let mut cleanup = Vec::new();
     817              : 
     818              :         // Send initial heartbeat requests to all nodes loaded from the database
     819              :         let all_nodes = {
     820              :             let locked = self.inner.read().unwrap();
     821              :             locked.nodes.clone()
     822              :         };
     823              :         let (mut nodes_online, mut sks_online) =
     824              :             self.initial_heartbeat_round(all_nodes.keys()).await;
     825              : 
     826              :         // List of tenants for which we will attempt to notify compute of their location at startup
     827              :         let mut compute_notifications = Vec::new();
     828              : 
     829              :         // Populate intent and observed states for all tenants, based on reported state on pageservers
     830              :         tracing::info!("Populating tenant shards' states from initial pageserver scan...");
     831              :         let shard_count = {
     832              :             let mut locked = self.inner.write().unwrap();
     833              :             let (nodes, safekeepers, tenants, scheduler) = locked.parts_mut_sk();
     834              : 
     835              :             // Mark nodes online if they responded to us: nodes are offline by default after a restart.
     836              :             let mut new_nodes = (**nodes).clone();
     837              :             for (node_id, node) in new_nodes.iter_mut() {
     838              :                 if let Some(utilization) = nodes_online.remove(node_id) {
     839              :                     node.set_availability(NodeAvailability::Active(utilization));
     840              :                     scheduler.node_upsert(node);
     841              :                 }
     842              :             }
     843              :             *nodes = Arc::new(new_nodes);
     844              : 
     845              :             let mut new_sks = (**safekeepers).clone();
     846              :             for (node_id, node) in new_sks.iter_mut() {
     847              :                 if let Some((utilization, last_seen_at)) = sks_online.remove(node_id) {
     848              :                     node.set_availability(SafekeeperState::Available {
     849              :                         utilization,
     850              :                         last_seen_at,
     851              :                     });
     852              :                 }
     853              :             }
     854              :             *safekeepers = Arc::new(new_sks);
     855              : 
     856              :             for (tenant_shard_id, observed_state) in observed.0 {
     857              :                 let Some(tenant_shard) = tenants.get_mut(&tenant_shard_id) else {
     858              :                     for node_id in observed_state.locations.keys() {
     859              :                         cleanup.push((tenant_shard_id, *node_id));
     860              :                     }
     861              : 
     862              :                     continue;
     863              :                 };
     864              : 
     865              :                 tenant_shard.observed = observed_state;
     866              :             }
     867              : 
     868              :             // Populate each tenant's intent state
     869              :             let mut schedule_context = ScheduleContext::default();
     870              :             for (tenant_shard_id, tenant_shard) in tenants.iter_mut() {
     871              :                 if tenant_shard_id.shard_number == ShardNumber(0) {
     872              :                     // Reset scheduling context each time we advance to the next Tenant
     873              :                     schedule_context = ScheduleContext::default();
     874              :                 }
     875              : 
     876              :                 tenant_shard.intent_from_observed(scheduler);
     877              :                 if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
     878              :                     // Non-fatal error: we are unable to properly schedule the tenant, perhaps because
     879              :                     // not enough pageservers are available.  The tenant may well still be available
     880              :                     // to clients.
     881              :                     tracing::error!("Failed to schedule tenant {tenant_shard_id} at startup: {e}");
     882              :                 } else {
     883              :                     // If we're both intending and observed to be attached at a particular node, we will
     884              :                     // emit a compute notification for this. In the case where our observed state does not
     885              :                     // yet match our intent, we will eventually reconcile, and that will emit a compute notification.
     886              :                     if let Some(attached_at) = tenant_shard.stably_attached() {
     887              :                         compute_notifications.push(compute_hook::ShardUpdate {
     888              :                             tenant_shard_id: *tenant_shard_id,
     889              :                             node_id: attached_at,
     890              :                             stripe_size: tenant_shard.shard.stripe_size,
     891              :                             preferred_az: tenant_shard
     892              :                                 .preferred_az()
     893            0 :                                 .map(|az| Cow::Owned(az.clone())),
     894              :                         });
     895              :                     }
     896              :                 }
     897              :             }
     898              : 
     899              :             tenants.len()
     900              :         };
     901              : 
     902              :         // Before making any obeservable changes to the cluster, persist self
     903              :         // as leader in database and memory.
     904              :         let leadership = Leadership::new(
     905              :             self.persistence.clone(),
     906              :             self.config.clone(),
     907              :             self.cancel.child_token(),
     908              :         );
     909              : 
     910              :         if let Err(e) = leadership.become_leader(current_leader).await {
     911              :             tracing::error!("Failed to persist self as leader: {e}. Aborting start-up ...");
     912              :             std::process::exit(1);
     913              :         }
     914              : 
     915              :         let safekeepers = self.inner.read().unwrap().safekeepers.clone();
     916              :         let sk_schedule_requests =
     917              :             match safekeeper_reconciler::load_schedule_requests(self, &safekeepers).await {
     918              :                 Ok(v) => v,
     919              :                 Err(e) => {
     920              :                     tracing::warn!(
     921              :                         "Failed to load safekeeper pending ops at startup: {e}." // Don't abort for now: " Aborting start-up..."
     922              :                     );
     923              :                     // std::process::exit(1);
     924              :                     Vec::new()
     925              :                 }
     926              :             };
     927              : 
     928              :         {
     929              :             let mut locked = self.inner.write().unwrap();
     930              :             locked.become_leader();
     931              : 
     932              :             for (sk_id, _sk) in locked.safekeepers.clone().iter() {
     933              :                 locked.safekeeper_reconcilers.start_reconciler(*sk_id, self);
     934              :             }
     935              : 
     936              :             locked
     937              :                 .safekeeper_reconcilers
     938              :                 .schedule_request_vec(sk_schedule_requests);
     939              :         }
     940              : 
     941              :         // TODO: if any tenant's intent now differs from its loaded generation_pageserver, we should clear that
     942              :         // generation_pageserver in the database.
     943              : 
     944              :         // Emit compute hook notifications for all tenants which are already stably attached.  Other tenants
     945              :         // will emit compute hook notifications when they reconcile.
     946              :         //
     947              :         // Ordering: our calls to notify_attach_background synchronously establish a relative order for these notifications vs. any later
     948              :         // calls into the ComputeHook for the same tenant: we can leave these to run to completion in the background and any later
     949              :         // calls will be correctly ordered wrt these.
     950              :         //
     951              :         // Concurrency: we call notify_attach_background for all tenants, which will create O(N) tokio tasks, but almost all of them
     952              :         // will just wait on the ComputeHook::API_CONCURRENCY semaphore immediately, so very cheap until they get that semaphore
     953              :         // unit and start doing I/O.
     954              :         tracing::info!(
     955              :             "Sending {} compute notifications",
     956              :             compute_notifications.len()
     957              :         );
     958              :         self.compute_hook.notify_attach_background(
     959              :             compute_notifications,
     960              :             bg_compute_notify_result_tx.clone(),
     961              :             &self.cancel,
     962              :         );
     963              : 
     964              :         // Finally, now that the service is up and running, launch reconcile operations for any tenants
     965              :         // which require it: under normal circumstances this should only include tenants that were in some
     966              :         // transient state before we restarted, or any tenants whose compute hooks failed above.
     967              :         tracing::info!("Checking for shards in need of reconciliation...");
     968              :         let reconcile_all_result = self.reconcile_all();
     969              :         // We will not wait for these reconciliation tasks to run here: we're now done with startup and
     970              :         // normal operations may proceed.
     971              : 
     972              :         // Clean up any tenants that were found on pageservers but are not known to us.  Do this in the
     973              :         // background because it does not need to complete in order to proceed with other work.
     974              :         if !cleanup.is_empty() {
     975              :             tracing::info!("Cleaning up {} locations in the background", cleanup.len());
     976              :             tokio::task::spawn({
     977              :                 let cleanup_self = self.clone();
     978            0 :                 async move { cleanup_self.cleanup_locations(cleanup).await }
     979              :             });
     980              :         }
     981              : 
     982              :         // Reconcile the timeline imports:
     983              :         // 1. Mark each tenant shard of tenants with an importing timeline as importing.
     984              :         // 2. Finalize the completed imports in the background. This handles the case where
     985              :         //    the previous storage controller instance shut down whilst finalizing imports.
     986              :         let imports = self.persistence.list_timeline_imports().await;
     987              :         match imports {
     988              :             Ok(mut imports) => {
     989              :                 {
     990              :                     let mut locked = self.inner.write().unwrap();
     991              :                     for import in &imports {
     992              :                         locked
     993              :                             .tenants
     994              :                             .range_mut(TenantShardId::tenant_range(import.tenant_id))
     995            0 :                             .for_each(|(_id, shard)| {
     996            0 :                                 shard.importing = TimelineImportState::Importing
     997            0 :                             });
     998              :                     }
     999              :                 }
    1000              : 
    1001            0 :                 imports.retain(|import| import.is_complete());
    1002              :                 tokio::task::spawn({
    1003              :                     let finalize_imports_self = self.clone();
    1004            0 :                     async move {
    1005            0 :                         finalize_imports_self
    1006            0 :                             .finalize_timeline_imports(imports)
    1007            0 :                             .await
    1008            0 :                     }
    1009              :                 });
    1010              :             }
    1011              :             Err(err) => {
    1012              :                 tracing::error!("Could not retrieve completed imports from database: {err}");
    1013              :             }
    1014              :         }
    1015              : 
    1016              :         let spawned_reconciles = reconcile_all_result.spawned_reconciles;
    1017              :         tracing::info!(
    1018              :             "Startup complete, spawned {spawned_reconciles} reconciliation tasks ({shard_count} shards total)"
    1019              :         );
    1020              :     }
    1021              : 
    1022            0 :     async fn initial_heartbeat_round<'a>(
    1023            0 :         &self,
    1024            0 :         node_ids: impl Iterator<Item = &'a NodeId>,
    1025            0 :     ) -> (
    1026            0 :         HashMap<NodeId, PageserverUtilization>,
    1027            0 :         HashMap<NodeId, (SafekeeperUtilization, Instant)>,
    1028            0 :     ) {
    1029            0 :         assert!(!self.startup_complete.is_ready());
    1030              : 
    1031            0 :         let all_nodes = {
    1032            0 :             let locked = self.inner.read().unwrap();
    1033            0 :             locked.nodes.clone()
    1034              :         };
    1035              : 
    1036            0 :         let mut nodes_to_heartbeat = HashMap::new();
    1037            0 :         for node_id in node_ids {
    1038            0 :             match all_nodes.get(node_id) {
    1039            0 :                 Some(node) => {
    1040            0 :                     nodes_to_heartbeat.insert(*node_id, node.clone());
    1041            0 :                 }
    1042              :                 None => {
    1043            0 :                     tracing::warn!("Node {node_id} was removed during start-up");
    1044              :                 }
    1045              :             }
    1046              :         }
    1047              : 
    1048            0 :         let all_sks = {
    1049            0 :             let locked = self.inner.read().unwrap();
    1050            0 :             locked.safekeepers.clone()
    1051              :         };
    1052              : 
    1053            0 :         tracing::info!("Sending initial heartbeats...");
    1054            0 :         let (res_ps, res_sk) = tokio::join!(
    1055            0 :             self.heartbeater_ps.heartbeat(Arc::new(nodes_to_heartbeat)),
    1056            0 :             self.heartbeater_sk.heartbeat(all_sks)
    1057              :         );
    1058              : 
    1059            0 :         let mut online_nodes = HashMap::new();
    1060            0 :         if let Ok(deltas) = res_ps {
    1061            0 :             for (node_id, status) in deltas.0 {
    1062            0 :                 match status {
    1063            0 :                     PageserverState::Available { utilization, .. } => {
    1064            0 :                         online_nodes.insert(node_id, utilization);
    1065            0 :                     }
    1066            0 :                     PageserverState::Offline => {}
    1067              :                     PageserverState::WarmingUp { .. } => {
    1068            0 :                         unreachable!("Nodes are never marked warming-up during startup reconcile")
    1069              :                     }
    1070              :                 }
    1071              :             }
    1072            0 :         }
    1073              : 
    1074            0 :         let mut online_sks = HashMap::new();
    1075            0 :         if let Ok(deltas) = res_sk {
    1076            0 :             for (node_id, status) in deltas.0 {
    1077            0 :                 match status {
    1078              :                     SafekeeperState::Available {
    1079            0 :                         utilization,
    1080            0 :                         last_seen_at,
    1081            0 :                     } => {
    1082            0 :                         online_sks.insert(node_id, (utilization, last_seen_at));
    1083            0 :                     }
    1084            0 :                     SafekeeperState::Offline => {}
    1085              :                 }
    1086              :             }
    1087            0 :         }
    1088              : 
    1089            0 :         (online_nodes, online_sks)
    1090            0 :     }
    1091              : 
    1092              :     /// Used during [`Self::startup_reconcile`]: issue GETs to all nodes concurrently, with a deadline.
    1093              :     ///
    1094              :     /// The result includes only nodes which responded within the deadline
    1095            0 :     async fn scan_node_locations(
    1096            0 :         &self,
    1097            0 :         deadline: Instant,
    1098            0 :     ) -> HashMap<NodeId, LocationConfigListResponse> {
    1099            0 :         let nodes = {
    1100            0 :             let locked = self.inner.read().unwrap();
    1101            0 :             locked.nodes.clone()
    1102              :         };
    1103              : 
    1104            0 :         let mut node_results = HashMap::new();
    1105              : 
    1106            0 :         let mut node_list_futs = FuturesUnordered::new();
    1107              : 
    1108            0 :         tracing::info!("Scanning shards on {} nodes...", nodes.len());
    1109            0 :         for node in nodes.values() {
    1110            0 :             node_list_futs.push({
    1111            0 :                 async move {
    1112            0 :                     tracing::info!("Scanning shards on node {node}...");
    1113            0 :                     let timeout = Duration::from_secs(5);
    1114            0 :                     let response = node
    1115            0 :                         .with_client_retries(
    1116            0 :                             |client| async move { client.list_location_config().await },
    1117            0 :                             &self.http_client,
    1118            0 :                             &self.config.pageserver_jwt_token,
    1119              :                             1,
    1120              :                             5,
    1121            0 :                             timeout,
    1122            0 :                             &self.cancel,
    1123              :                         )
    1124            0 :                         .await;
    1125            0 :                     (node.get_id(), response)
    1126            0 :                 }
    1127              :             });
    1128              :         }
    1129              : 
    1130              :         loop {
    1131            0 :             let (node_id, result) = tokio::select! {
    1132            0 :                 next = node_list_futs.next() => {
    1133            0 :                     match next {
    1134            0 :                         Some(result) => result,
    1135              :                         None =>{
    1136              :                             // We got results for all our nodes
    1137            0 :                             break;
    1138              :                         }
    1139              : 
    1140              :                     }
    1141              :                 },
    1142            0 :                 _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
    1143              :                     // Give up waiting for anyone who hasn't responded: we will yield the results that we have
    1144            0 :                     tracing::info!("Reached deadline while waiting for nodes to respond to location listing requests");
    1145            0 :                     break;
    1146              :                 }
    1147              :             };
    1148              : 
    1149            0 :             let Some(list_response) = result else {
    1150            0 :                 tracing::info!("Shutdown during startup_reconcile");
    1151            0 :                 break;
    1152              :             };
    1153              : 
    1154            0 :             match list_response {
    1155            0 :                 Err(e) => {
    1156            0 :                     tracing::warn!("Could not scan node {} ({e})", node_id);
    1157              :                 }
    1158            0 :                 Ok(listing) => {
    1159            0 :                     node_results.insert(node_id, listing);
    1160            0 :                 }
    1161              :             }
    1162              :         }
    1163              : 
    1164            0 :         node_results
    1165            0 :     }
    1166              : 
    1167            0 :     async fn build_global_observed_state(&self, deadline: Instant) -> GlobalObservedState {
    1168            0 :         let node_listings = self.scan_node_locations(deadline).await;
    1169            0 :         let mut observed = GlobalObservedState::default();
    1170              : 
    1171            0 :         for (node_id, location_confs) in node_listings {
    1172            0 :             tracing::info!(
    1173            0 :                 "Received {} shard statuses from pageserver {}",
    1174            0 :                 location_confs.tenant_shards.len(),
    1175              :                 node_id
    1176              :             );
    1177              : 
    1178            0 :             for (tid, location_conf) in location_confs.tenant_shards {
    1179            0 :                 let entry = observed.0.entry(tid).or_default();
    1180            0 :                 entry.locations.insert(
    1181            0 :                     node_id,
    1182            0 :                     ObservedStateLocation {
    1183            0 :                         conf: location_conf,
    1184            0 :                     },
    1185            0 :                 );
    1186            0 :             }
    1187              :         }
    1188              : 
    1189            0 :         observed
    1190            0 :     }
    1191              : 
    1192              :     /// Used during [`Self::startup_reconcile`] and shard splits: detach a list of unknown-to-us
    1193              :     /// tenants from pageservers.
    1194              :     ///
    1195              :     /// This is safe to run in the background, because if we don't have this TenantShardId in our map of
    1196              :     /// tenants, then it is probably something incompletely deleted before: we will not fight with any
    1197              :     /// other task trying to attach it.
    1198              :     #[instrument(skip_all)]
    1199              :     async fn cleanup_locations(&self, cleanup: Vec<(TenantShardId, NodeId)>) {
    1200              :         let nodes = self.inner.read().unwrap().nodes.clone();
    1201              : 
    1202              :         for (tenant_shard_id, node_id) in cleanup {
    1203              :             // A node reported a tenant_shard_id which is unknown to us: detach it.
    1204              :             let Some(node) = nodes.get(&node_id) else {
    1205              :                 // This is legitimate; we run in the background and [`Self::startup_reconcile`] might have identified
    1206              :                 // a location to clean up on a node that has since been removed.
    1207              :                 tracing::info!(
    1208              :                     "Not cleaning up location {node_id}/{tenant_shard_id}: node not found"
    1209              :                 );
    1210              :                 continue;
    1211              :             };
    1212              : 
    1213              :             if self.cancel.is_cancelled() {
    1214              :                 break;
    1215              :             }
    1216              : 
    1217              :             let client = PageserverClient::new(
    1218              :                 node.get_id(),
    1219              :                 self.http_client.clone(),
    1220              :                 node.base_url(),
    1221              :                 self.config.pageserver_jwt_token.as_deref(),
    1222              :             );
    1223              :             match client
    1224              :                 .location_config(
    1225              :                     tenant_shard_id,
    1226              :                     LocationConfig {
    1227              :                         mode: LocationConfigMode::Detached,
    1228              :                         generation: None,
    1229              :                         secondary_conf: None,
    1230              :                         shard_number: tenant_shard_id.shard_number.0,
    1231              :                         shard_count: tenant_shard_id.shard_count.literal(),
    1232              :                         shard_stripe_size: 0,
    1233              :                         tenant_conf: models::TenantConfig::default(),
    1234              :                     },
    1235              :                     None,
    1236              :                     false,
    1237              :                 )
    1238              :                 .await
    1239              :             {
    1240              :                 Ok(()) => {
    1241              :                     tracing::info!(
    1242              :                         "Detached unknown shard {tenant_shard_id} on pageserver {node_id}"
    1243              :                     );
    1244              :                 }
    1245              :                 Err(e) => {
    1246              :                     // Non-fatal error: leaving a tenant shard behind that we are not managing shouldn't
    1247              :                     // break anything.
    1248              :                     tracing::error!(
    1249              :                         "Failed to detach unknown shard {tenant_shard_id} on pageserver {node_id}: {e}"
    1250              :                     );
    1251              :                 }
    1252              :             }
    1253              :         }
    1254              :     }
    1255              : 
    1256              :     /// Long running background task that periodically wakes up and looks for shards that need
    1257              :     /// reconciliation.  Reconciliation is fallible, so any reconciliation tasks that fail during
    1258              :     /// e.g. a tenant create/attach/migrate must eventually be retried: this task is responsible
    1259              :     /// for those retries.
    1260              :     #[instrument(skip_all)]
    1261              :     async fn background_reconcile(self: &Arc<Self>) {
    1262              :         self.startup_complete.clone().wait().await;
    1263              : 
    1264              :         const BACKGROUND_RECONCILE_PERIOD: Duration = Duration::from_secs(20);
    1265              :         let mut interval = tokio::time::interval(BACKGROUND_RECONCILE_PERIOD);
    1266              :         while !self.reconcilers_cancel.is_cancelled() {
    1267              :             tokio::select! {
    1268              :               _ = interval.tick() => {
    1269              :                 let reconcile_all_result = self.reconcile_all();
    1270              :                 if reconcile_all_result.can_run_optimizations() {
    1271              :                     // Run optimizer only when we didn't find any other work to do
    1272              :                     self.optimize_all().await;
    1273              :                 }
    1274              :                 // Always attempt autosplits. Sharding is crucial for bulk ingest performance, so we
    1275              :                 // must be responsive when new projects begin ingesting and reach the threshold.
    1276              :                 self.autosplit_tenants().await;
    1277              :             }
    1278              :               _ = self.reconcilers_cancel.cancelled() => return
    1279              :             }
    1280              :         }
    1281              :     }
    1282              :     /// Heartbeat all storage nodes once in a while.
    1283              :     #[instrument(skip_all)]
    1284              :     async fn spawn_heartbeat_driver(self: &Arc<Self>) {
    1285              :         self.startup_complete.clone().wait().await;
    1286              : 
    1287              :         let mut interval = tokio::time::interval(self.config.heartbeat_interval);
    1288              :         while !self.cancel.is_cancelled() {
    1289              :             tokio::select! {
    1290              :               _ = interval.tick() => { }
    1291              :               _ = self.cancel.cancelled() => return
    1292              :             };
    1293              : 
    1294              :             let nodes = {
    1295              :                 let locked = self.inner.read().unwrap();
    1296              :                 locked.nodes.clone()
    1297              :             };
    1298              : 
    1299              :             let safekeepers = {
    1300              :                 let locked = self.inner.read().unwrap();
    1301              :                 locked.safekeepers.clone()
    1302              :             };
    1303              : 
    1304              :             let (res_ps, res_sk) = tokio::join!(
    1305              :                 self.heartbeater_ps.heartbeat(nodes),
    1306              :                 self.heartbeater_sk.heartbeat(safekeepers)
    1307              :             );
    1308              : 
    1309              :             if let Ok(deltas) = res_ps {
    1310              :                 let mut to_handle = Vec::default();
    1311              : 
    1312              :                 for (node_id, state) in deltas.0 {
    1313              :                     let new_availability = match state {
    1314              :                         PageserverState::Available { utilization, .. } => {
    1315              :                             NodeAvailability::Active(utilization)
    1316              :                         }
    1317              :                         PageserverState::WarmingUp { started_at } => {
    1318              :                             NodeAvailability::WarmingUp(started_at)
    1319              :                         }
    1320              :                         PageserverState::Offline => {
    1321              :                             // The node might have been placed in the WarmingUp state
    1322              :                             // while the heartbeat round was on-going. Hence, filter out
    1323              :                             // offline transitions for WarmingUp nodes that are still within
    1324              :                             // their grace period.
    1325              :                             if let Ok(NodeAvailability::WarmingUp(started_at)) = self
    1326              :                                 .get_node(node_id)
    1327              :                                 .await
    1328              :                                 .as_ref()
    1329            0 :                                 .map(|n| n.get_availability())
    1330              :                             {
    1331              :                                 let now = Instant::now();
    1332              :                                 if now - *started_at >= self.config.max_warming_up_interval {
    1333              :                                     NodeAvailability::Offline
    1334              :                                 } else {
    1335              :                                     NodeAvailability::WarmingUp(*started_at)
    1336              :                                 }
    1337              :                             } else {
    1338              :                                 NodeAvailability::Offline
    1339              :                             }
    1340              :                         }
    1341              :                     };
    1342              : 
    1343              :                     let node_lock = trace_exclusive_lock(
    1344              :                         &self.node_op_locks,
    1345              :                         node_id,
    1346              :                         NodeOperations::Configure,
    1347              :                     )
    1348              :                     .await;
    1349              : 
    1350              :                     pausable_failpoint!("heartbeat-pre-node-state-configure");
    1351              : 
    1352              :                     // This is the code path for geniune availability transitions (i.e node
    1353              :                     // goes unavailable and/or comes back online).
    1354              :                     let res = self
    1355              :                         .node_state_configure(node_id, Some(new_availability), None, &node_lock)
    1356              :                         .await;
    1357              : 
    1358              :                     match res {
    1359              :                         Ok(transition) => {
    1360              :                             // Keep hold of the lock until the availability transitions
    1361              :                             // have been handled in
    1362              :                             // [`Service::handle_node_availability_transitions`] in order avoid
    1363              :                             // racing with [`Service::external_node_configure`].
    1364              :                             to_handle.push((node_id, node_lock, transition));
    1365              :                         }
    1366              :                         Err(ApiError::NotFound(_)) => {
    1367              :                             // This should be rare, but legitimate since the heartbeats are done
    1368              :                             // on a snapshot of the nodes.
    1369              :                             tracing::info!("Node {} was not found after heartbeat round", node_id);
    1370              :                         }
    1371              :                         Err(ApiError::ShuttingDown) => {
    1372              :                             // No-op: we're shutting down, no need to try and update any nodes' statuses
    1373              :                         }
    1374              :                         Err(err) => {
    1375              :                             // Transition to active involves reconciling: if a node responds to a heartbeat then
    1376              :                             // becomes unavailable again, we may get an error here.
    1377              :                             tracing::error!(
    1378              :                                 "Failed to update node state {} after heartbeat round: {}",
    1379              :                                 node_id,
    1380              :                                 err
    1381              :                             );
    1382              :                         }
    1383              :                     }
    1384              :                 }
    1385              : 
    1386              :                 // We collected all the transitions above and now we handle them.
    1387              :                 let res = self.handle_node_availability_transitions(to_handle).await;
    1388              :                 if let Err(errs) = res {
    1389              :                     for (node_id, err) in errs {
    1390              :                         match err {
    1391              :                             ApiError::NotFound(_) => {
    1392              :                                 // This should be rare, but legitimate since the heartbeats are done
    1393              :                                 // on a snapshot of the nodes.
    1394              :                                 tracing::info!(
    1395              :                                     "Node {} was not found after heartbeat round",
    1396              :                                     node_id
    1397              :                                 );
    1398              :                             }
    1399              :                             err => {
    1400              :                                 tracing::error!(
    1401              :                                     "Failed to handle availability transition for {} after heartbeat round: {}",
    1402              :                                     node_id,
    1403              :                                     err
    1404              :                                 );
    1405              :                             }
    1406              :                         }
    1407              :                     }
    1408              :                 }
    1409              :             }
    1410              :             if let Ok(deltas) = res_sk {
    1411              :                 let mut to_activate = Vec::new();
    1412              :                 {
    1413              :                     let mut locked = self.inner.write().unwrap();
    1414              :                     let mut safekeepers = (*locked.safekeepers).clone();
    1415              : 
    1416              :                     for (id, state) in deltas.0 {
    1417              :                         let Some(sk) = safekeepers.get_mut(&id) else {
    1418              :                             tracing::info!(
    1419              :                                 "Couldn't update safekeeper safekeeper state for id {id} from heartbeat={state:?}"
    1420              :                             );
    1421              :                             continue;
    1422              :                         };
    1423              :                         if sk.scheduling_policy() == SkSchedulingPolicy::Activating
    1424              :                             && let SafekeeperState::Available { .. } = state
    1425              :                         {
    1426              :                             to_activate.push(id);
    1427              :                         }
    1428              :                         sk.set_availability(state);
    1429              :                     }
    1430              :                     locked.safekeepers = Arc::new(safekeepers);
    1431              :                 }
    1432              :                 for sk_id in to_activate {
    1433              :                     // TODO this can race with set_scheduling_policy (can create disjoint DB <-> in-memory state)
    1434              :                     tracing::info!("Activating safekeeper {sk_id}");
    1435              :                     match self.persistence.activate_safekeeper(sk_id.0 as i64).await {
    1436              :                         Ok(Some(())) => {}
    1437              :                         Ok(None) => {
    1438              :                             tracing::info!(
    1439              :                                 "safekeeper {sk_id} has been removed from db or has different scheduling policy than active or activating"
    1440              :                             );
    1441              :                         }
    1442              :                         Err(e) => {
    1443              :                             tracing::warn!("couldn't apply activation of {sk_id} to db: {e}");
    1444              :                             continue;
    1445              :                         }
    1446              :                     }
    1447              :                     if let Err(e) = self
    1448              :                         .set_safekeeper_scheduling_policy_in_mem(sk_id, SkSchedulingPolicy::Active)
    1449              :                         .await
    1450              :                     {
    1451              :                         tracing::info!("couldn't activate safekeeper {sk_id} in memory: {e}");
    1452              :                         continue;
    1453              :                     }
    1454              :                     tracing::info!("Activation of safekeeper {sk_id} done");
    1455              :                 }
    1456              :             }
    1457              :         }
    1458              :     }
    1459              : 
    1460              :     /// Apply the contents of a [`ReconcileResult`] to our in-memory state: if the reconciliation
    1461              :     /// was successful and intent hasn't changed since the Reconciler was spawned, this will update
    1462              :     /// the observed state of the tenant such that subsequent calls to [`TenantShard::get_reconcile_needed`]
    1463              :     /// will indicate that reconciliation is not needed.
    1464              :     #[instrument(skip_all, fields(
    1465              :         seq=%result.sequence,
    1466              :         tenant_id=%result.tenant_shard_id.tenant_id,
    1467              :         shard_id=%result.tenant_shard_id.shard_slug(),
    1468              :     ))]
    1469              :     fn process_result(&self, result: ReconcileResult) {
    1470              :         let mut locked = self.inner.write().unwrap();
    1471              :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    1472              :         let Some(tenant) = tenants.get_mut(&result.tenant_shard_id) else {
    1473              :             // A reconciliation result might race with removing a tenant: drop results for
    1474              :             // tenants that aren't in our map.
    1475              :             return;
    1476              :         };
    1477              : 
    1478              :         // Usually generation should only be updated via this path, so the max() isn't
    1479              :         // needed, but it is used to handle out-of-band updates via. e.g. test hook.
    1480              :         tenant.generation = std::cmp::max(tenant.generation, result.generation);
    1481              : 
    1482              :         // If the reconciler signals that it failed to notify compute, set this state on
    1483              :         // the shard so that a future [`TenantShard::maybe_reconcile`] will try again.
    1484              :         tenant.pending_compute_notification = result.pending_compute_notification;
    1485              : 
    1486              :         // Let the TenantShard know it is idle.
    1487              :         tenant.reconcile_complete(result.sequence);
    1488              : 
    1489              :         // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
    1490              :         // make to the tenant
    1491            0 :         let deltas = result.observed_deltas.into_iter().flat_map(|delta| {
    1492              :             // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
    1493              :             // make to the tenant
    1494            0 :             let node = nodes.get(delta.node_id())?;
    1495              : 
    1496            0 :             if node.is_available() {
    1497            0 :                 return Some(delta);
    1498            0 :             }
    1499              : 
    1500              :             // In case a node became unavailable concurrently with the reconcile, observed
    1501              :             // locations on it are now uncertain. By convention, set them to None in order
    1502              :             // for them to get refreshed when the node comes back online.
    1503            0 :             Some(ObservedStateDelta::Upsert(Box::new((
    1504            0 :                 node.get_id(),
    1505            0 :                 ObservedStateLocation { conf: None },
    1506            0 :             ))))
    1507            0 :         });
    1508              : 
    1509              :         match result.result {
    1510              :             Ok(()) => {
    1511              :                 tenant.apply_observed_deltas(deltas);
    1512              :                 tenant.waiter.advance(result.sequence);
    1513              :             }
    1514              :             Err(e) => {
    1515              :                 match e {
    1516              :                     ReconcileError::Cancel => {
    1517              :                         tracing::info!("Reconciler was cancelled");
    1518              :                     }
    1519              :                     ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
    1520              :                         // This might be due to the reconciler getting cancelled, or it might
    1521              :                         // be due to the `Node` being marked offline.
    1522              :                         tracing::info!("Reconciler cancelled during pageserver API call");
    1523              :                     }
    1524              :                     _ => {
    1525              :                         tracing::warn!("Reconcile error: {}", e);
    1526              :                     }
    1527              :                 }
    1528              : 
    1529              :                 // Ordering: populate last_error before advancing error_seq,
    1530              :                 // so that waiters will see the correct error after waiting.
    1531              :                 tenant.set_last_error(result.sequence, e);
    1532              : 
    1533              :                 // Skip deletions on reconcile failures
    1534              :                 let upsert_deltas =
    1535            0 :                     deltas.filter(|delta| matches!(delta, ObservedStateDelta::Upsert(_)));
    1536              :                 tenant.apply_observed_deltas(upsert_deltas);
    1537              :             }
    1538              :         }
    1539              : 
    1540              :         tenant.consecutive_reconciles_count = tenant.consecutive_reconciles_count.saturating_add(1);
    1541              : 
    1542              :         // If we just finished detaching all shards for a tenant, it might be time to drop it from memory.
    1543              :         if tenant.policy == PlacementPolicy::Detached {
    1544              :             // We may only drop a tenant from memory while holding the exclusive lock on the tenant ID: this protects us
    1545              :             // from concurrent execution wrt a request handler that might expect the tenant to remain in memory for the
    1546              :             // duration of the request.
    1547              :             let guard = self.tenant_op_locks.try_exclusive(
    1548              :                 tenant.tenant_shard_id.tenant_id,
    1549              :                 TenantOperations::DropDetached,
    1550              :             );
    1551              :             if let Some(guard) = guard {
    1552              :                 self.maybe_drop_tenant(tenant.tenant_shard_id.tenant_id, &mut locked, &guard);
    1553              :             }
    1554              :         }
    1555              : 
    1556              :         // Maybe some other work can proceed now that this job finished.
    1557              :         //
    1558              :         // Only bother with this if we have some semaphore units available in the normal-priority semaphore (these
    1559              :         // reconciles are scheduled at `[ReconcilerPriority::Normal]`).
    1560              :         if self.reconciler_concurrency.available_permits() > 0 {
    1561              :             while let Ok(tenant_shard_id) = locked.delayed_reconcile_rx.try_recv() {
    1562              :                 let (nodes, tenants, _scheduler) = locked.parts_mut();
    1563              :                 if let Some(shard) = tenants.get_mut(&tenant_shard_id) {
    1564              :                     shard.delayed_reconcile = false;
    1565              :                     self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
    1566              :                 }
    1567              : 
    1568              :                 if self.reconciler_concurrency.available_permits() == 0 {
    1569              :                     break;
    1570              :                 }
    1571              :             }
    1572              :         }
    1573              :     }
    1574              : 
    1575            0 :     async fn process_results(
    1576            0 :         &self,
    1577            0 :         mut result_rx: tokio::sync::mpsc::UnboundedReceiver<ReconcileResultRequest>,
    1578            0 :         mut bg_compute_hook_result_rx: tokio::sync::mpsc::Receiver<
    1579            0 :             Result<(), (TenantShardId, NotifyError)>,
    1580            0 :         >,
    1581            0 :     ) {
    1582              :         loop {
    1583              :             // Wait for the next result, or for cancellation
    1584            0 :             tokio::select! {
    1585            0 :                 r = result_rx.recv() => {
    1586            0 :                     match r {
    1587            0 :                         Some(ReconcileResultRequest::ReconcileResult(result)) => {self.process_result(result);},
    1588            0 :                         None | Some(ReconcileResultRequest::Stop) => {break;}
    1589              :                     }
    1590              :                 }
    1591            0 :                 _ = async{
    1592            0 :                     match bg_compute_hook_result_rx.recv().await {
    1593            0 :                         Some(result) => {
    1594            0 :                             if let Err((tenant_shard_id, notify_error)) = result {
    1595            0 :                                 tracing::warn!("Marking shard {tenant_shard_id} for notification retry, due to error {notify_error}");
    1596            0 :                                 let mut locked = self.inner.write().unwrap();
    1597            0 :                                 if let Some(shard) = locked.tenants.get_mut(&tenant_shard_id) {
    1598            0 :                                     shard.pending_compute_notification = true;
    1599            0 :                                 }
    1600              : 
    1601            0 :                             }
    1602              :                         },
    1603              :                         None => {
    1604              :                             // This channel is dead, but we don't want to terminate the outer loop{}: just wait for shutdown
    1605            0 :                             self.cancel.cancelled().await;
    1606              :                         }
    1607              :                     }
    1608            0 :                 } => {},
    1609            0 :                 _ = self.cancel.cancelled() => {
    1610            0 :                     break;
    1611              :                 }
    1612              :             };
    1613              :         }
    1614            0 :     }
    1615              : 
    1616            0 :     async fn process_aborts(
    1617            0 :         &self,
    1618            0 :         mut abort_rx: tokio::sync::mpsc::UnboundedReceiver<TenantShardSplitAbort>,
    1619            0 :     ) {
    1620              :         loop {
    1621              :             // Wait for the next result, or for cancellation
    1622            0 :             let op = tokio::select! {
    1623            0 :                 r = abort_rx.recv() => {
    1624            0 :                     match r {
    1625            0 :                         Some(op) => {op},
    1626            0 :                         None => {break;}
    1627              :                     }
    1628              :                 }
    1629            0 :                 _ = self.cancel.cancelled() => {
    1630            0 :                     break;
    1631              :                 }
    1632              :             };
    1633              : 
    1634              :             // Retry until shutdown: we must keep this request object alive until it is properly
    1635              :             // processed, as it holds a lock guard that prevents other operations trying to do things
    1636              :             // to the tenant while it is in a weird part-split state.
    1637            0 :             while !self.reconcilers_cancel.is_cancelled() {
    1638            0 :                 match self.abort_tenant_shard_split(&op).await {
    1639            0 :                     Ok(_) => break,
    1640            0 :                     Err(e) => {
    1641            0 :                         tracing::warn!(
    1642            0 :                             "Failed to abort shard split on {}, will retry: {e}",
    1643              :                             op.tenant_id
    1644              :                         );
    1645              : 
    1646              :                         // If a node is unavailable, we hope that it has been properly marked Offline
    1647              :                         // when we retry, so that the abort op will succeed.  If the abort op is failing
    1648              :                         // for some other reason, we will keep retrying forever, or until a human notices
    1649              :                         // and does something about it (either fixing a pageserver or restarting the controller).
    1650            0 :                         tokio::time::timeout(
    1651            0 :                             Duration::from_secs(5),
    1652            0 :                             self.reconcilers_cancel.cancelled(),
    1653            0 :                         )
    1654            0 :                         .await
    1655            0 :                         .ok();
    1656              :                     }
    1657              :                 }
    1658              :             }
    1659              :         }
    1660            0 :     }
    1661              : 
    1662            0 :     pub async fn spawn(config: Config, persistence: Arc<Persistence>) -> anyhow::Result<Arc<Self>> {
    1663            0 :         let (result_tx, result_rx) = tokio::sync::mpsc::unbounded_channel();
    1664            0 :         let (abort_tx, abort_rx) = tokio::sync::mpsc::unbounded_channel();
    1665              : 
    1666            0 :         let leadership_cancel = CancellationToken::new();
    1667            0 :         let leadership = Leadership::new(persistence.clone(), config.clone(), leadership_cancel);
    1668            0 :         let (leader, leader_step_down_state) = leadership.step_down_current_leader().await?;
    1669              : 
    1670              :         // Apply the migrations **after** the current leader has stepped down
    1671              :         // (or we've given up waiting for it), but **before** reading from the
    1672              :         // database. The only exception is reading the current leader before
    1673              :         // migrating.
    1674            0 :         persistence.migration_run().await?;
    1675              : 
    1676            0 :         tracing::info!("Loading nodes from database...");
    1677            0 :         let nodes = persistence
    1678            0 :             .list_nodes()
    1679            0 :             .await?
    1680            0 :             .into_iter()
    1681            0 :             .map(|x| Node::from_persistent(x, config.use_https_pageserver_api))
    1682            0 :             .collect::<anyhow::Result<Vec<Node>>>()?;
    1683            0 :         let nodes: HashMap<NodeId, Node> = nodes.into_iter().map(|n| (n.get_id(), n)).collect();
    1684            0 :         tracing::info!("Loaded {} nodes from database.", nodes.len());
    1685            0 :         metrics::METRICS_REGISTRY
    1686            0 :             .metrics_group
    1687            0 :             .storage_controller_pageserver_nodes
    1688            0 :             .set(nodes.len() as i64);
    1689            0 :         metrics::METRICS_REGISTRY
    1690            0 :             .metrics_group
    1691            0 :             .storage_controller_https_pageserver_nodes
    1692            0 :             .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
    1693              : 
    1694            0 :         tracing::info!("Loading safekeepers from database...");
    1695            0 :         let safekeepers = persistence
    1696            0 :             .list_safekeepers()
    1697            0 :             .await?
    1698            0 :             .into_iter()
    1699            0 :             .map(|skp| {
    1700            0 :                 Safekeeper::from_persistence(
    1701            0 :                     skp,
    1702            0 :                     CancellationToken::new(),
    1703            0 :                     config.use_https_safekeeper_api,
    1704              :                 )
    1705            0 :             })
    1706            0 :             .collect::<anyhow::Result<Vec<_>>>()?;
    1707            0 :         let safekeepers: HashMap<NodeId, Safekeeper> =
    1708            0 :             safekeepers.into_iter().map(|n| (n.get_id(), n)).collect();
    1709            0 :         let count_policy = |policy| {
    1710            0 :             safekeepers
    1711            0 :                 .iter()
    1712            0 :                 .filter(|sk| sk.1.scheduling_policy() == policy)
    1713            0 :                 .count()
    1714            0 :         };
    1715            0 :         let active_sk_count = count_policy(SkSchedulingPolicy::Active);
    1716            0 :         let activating_sk_count = count_policy(SkSchedulingPolicy::Activating);
    1717            0 :         let pause_sk_count = count_policy(SkSchedulingPolicy::Pause);
    1718            0 :         let decom_sk_count = count_policy(SkSchedulingPolicy::Decomissioned);
    1719            0 :         tracing::info!(
    1720            0 :             "Loaded {} safekeepers from database. Active {active_sk_count}, activating {activating_sk_count}, \
    1721            0 :             paused {pause_sk_count}, decomissioned {decom_sk_count}.",
    1722            0 :             safekeepers.len()
    1723              :         );
    1724            0 :         metrics::METRICS_REGISTRY
    1725            0 :             .metrics_group
    1726            0 :             .storage_controller_safekeeper_nodes
    1727            0 :             .set(safekeepers.len() as i64);
    1728            0 :         metrics::METRICS_REGISTRY
    1729            0 :             .metrics_group
    1730            0 :             .storage_controller_https_safekeeper_nodes
    1731            0 :             .set(safekeepers.values().filter(|s| s.has_https_port()).count() as i64);
    1732              : 
    1733            0 :         tracing::info!("Loading shards from database...");
    1734            0 :         let mut tenant_shard_persistence = persistence.load_active_tenant_shards().await?;
    1735            0 :         tracing::info!(
    1736            0 :             "Loaded {} shards from database.",
    1737            0 :             tenant_shard_persistence.len()
    1738              :         );
    1739              : 
    1740              :         // If any shard splits were in progress, reset the database state to abort them
    1741            0 :         let mut tenant_shard_count_min_max: HashMap<TenantId, (ShardCount, ShardCount)> =
    1742            0 :             HashMap::new();
    1743            0 :         for tsp in &mut tenant_shard_persistence {
    1744            0 :             let shard = tsp.get_shard_identity()?;
    1745            0 :             let tenant_shard_id = tsp.get_tenant_shard_id()?;
    1746            0 :             let entry = tenant_shard_count_min_max
    1747            0 :                 .entry(tenant_shard_id.tenant_id)
    1748            0 :                 .or_insert_with(|| (shard.count, shard.count));
    1749            0 :             entry.0 = std::cmp::min(entry.0, shard.count);
    1750            0 :             entry.1 = std::cmp::max(entry.1, shard.count);
    1751              :         }
    1752              : 
    1753            0 :         for (tenant_id, (count_min, count_max)) in tenant_shard_count_min_max {
    1754            0 :             if count_min != count_max {
    1755              :                 // Aborting the split in the database and dropping the child shards is sufficient: the reconciliation in
    1756              :                 // [`Self::startup_reconcile`] will implicitly drop the child shards on remote pageservers, or they'll
    1757              :                 // be dropped later in [`Self::node_activate_reconcile`] if it isn't available right now.
    1758            0 :                 tracing::info!("Aborting shard split {tenant_id} {count_min:?} -> {count_max:?}");
    1759            0 :                 let abort_status = persistence.abort_shard_split(tenant_id, count_max).await?;
    1760              : 
    1761              :                 // We may never see the Complete status here: if the split was complete, we wouldn't have
    1762              :                 // identified this tenant has having mismatching min/max counts.
    1763            0 :                 assert!(matches!(abort_status, AbortShardSplitStatus::Aborted));
    1764              : 
    1765              :                 // Clear the splitting status in-memory, to reflect that we just aborted in the database
    1766            0 :                 tenant_shard_persistence.iter_mut().for_each(|tsp| {
    1767              :                     // Set idle split state on those shards that we will retain.
    1768            0 :                     let tsp_tenant_id = TenantId::from_str(tsp.tenant_id.as_str()).unwrap();
    1769            0 :                     if tsp_tenant_id == tenant_id
    1770            0 :                         && tsp.get_shard_identity().unwrap().count == count_min
    1771            0 :                     {
    1772            0 :                         tsp.splitting = SplitState::Idle;
    1773            0 :                     } else if tsp_tenant_id == tenant_id {
    1774              :                         // Leave the splitting state on the child shards: this will be used next to
    1775              :                         // drop them.
    1776            0 :                         tracing::info!(
    1777            0 :                             "Shard {tsp_tenant_id} will be dropped after shard split abort",
    1778              :                         );
    1779            0 :                     }
    1780            0 :                 });
    1781              : 
    1782              :                 // Drop shards for this tenant which we didn't just mark idle (i.e. child shards of the aborted split)
    1783            0 :                 tenant_shard_persistence.retain(|tsp| {
    1784            0 :                     TenantId::from_str(tsp.tenant_id.as_str()).unwrap() != tenant_id
    1785            0 :                         || tsp.splitting == SplitState::Idle
    1786            0 :                 });
    1787            0 :             }
    1788              :         }
    1789              : 
    1790            0 :         let mut tenants = BTreeMap::new();
    1791              : 
    1792            0 :         let mut scheduler = Scheduler::new(nodes.values());
    1793              : 
    1794              :         #[cfg(feature = "testing")]
    1795              :         {
    1796              :             use pageserver_api::controller_api::AvailabilityZone;
    1797              : 
    1798              :             // Hack: insert scheduler state for all nodes referenced by shards, as compatibility
    1799              :             // tests only store the shards, not the nodes.  The nodes will be loaded shortly
    1800              :             // after when pageservers start up and register.
    1801            0 :             let mut node_ids = HashSet::new();
    1802            0 :             for tsp in &tenant_shard_persistence {
    1803            0 :                 if let Some(node_id) = tsp.generation_pageserver {
    1804            0 :                     node_ids.insert(node_id);
    1805            0 :                 }
    1806              :             }
    1807            0 :             for node_id in node_ids {
    1808            0 :                 tracing::info!("Creating node {} in scheduler for tests", node_id);
    1809            0 :                 let node = Node::new(
    1810            0 :                     NodeId(node_id as u64),
    1811            0 :                     "".to_string(),
    1812              :                     123,
    1813            0 :                     None,
    1814            0 :                     "".to_string(),
    1815              :                     123,
    1816            0 :                     None,
    1817            0 :                     None,
    1818            0 :                     AvailabilityZone("test_az".to_string()),
    1819              :                     false,
    1820              :                 )
    1821            0 :                 .unwrap();
    1822              : 
    1823            0 :                 scheduler.node_upsert(&node);
    1824              :             }
    1825              :         }
    1826            0 :         for tsp in tenant_shard_persistence {
    1827            0 :             let tenant_shard_id = tsp.get_tenant_shard_id()?;
    1828              : 
    1829              :             // We will populate intent properly later in [`Self::startup_reconcile`], initially populate
    1830              :             // it with what we can infer: the node for which a generation was most recently issued.
    1831            0 :             let mut intent = IntentState::new(
    1832            0 :                 tsp.preferred_az_id
    1833            0 :                     .as_ref()
    1834            0 :                     .map(|az| AvailabilityZone(az.clone())),
    1835              :             );
    1836            0 :             if let Some(generation_pageserver) = tsp.generation_pageserver.map(|n| NodeId(n as u64))
    1837              :             {
    1838            0 :                 if nodes.contains_key(&generation_pageserver) {
    1839            0 :                     intent.set_attached(&mut scheduler, Some(generation_pageserver));
    1840            0 :                 } else {
    1841              :                     // If a node was removed before being completely drained, it is legal for it to leave behind a `generation_pageserver` referring
    1842              :                     // to a non-existent node, because node deletion doesn't block on completing the reconciliations that will issue new generations
    1843              :                     // on different pageservers.
    1844            0 :                     tracing::warn!(
    1845            0 :                         "Tenant shard {tenant_shard_id} references non-existent node {generation_pageserver} in database, will be rescheduled"
    1846              :                     );
    1847              :                 }
    1848            0 :             }
    1849            0 :             let new_tenant = TenantShard::from_persistent(tsp, intent)?;
    1850              : 
    1851            0 :             tenants.insert(tenant_shard_id, new_tenant);
    1852              :         }
    1853              : 
    1854            0 :         let (startup_completion, startup_complete) = utils::completion::channel();
    1855              : 
    1856              :         // This channel is continuously consumed by process_results, so doesn't need to be very large.
    1857            0 :         let (bg_compute_notify_result_tx, bg_compute_notify_result_rx) =
    1858            0 :             tokio::sync::mpsc::channel(512);
    1859              : 
    1860            0 :         let (delayed_reconcile_tx, delayed_reconcile_rx) =
    1861            0 :             tokio::sync::mpsc::channel(MAX_DELAYED_RECONCILES);
    1862              : 
    1863            0 :         let cancel = CancellationToken::new();
    1864            0 :         let reconcilers_cancel = cancel.child_token();
    1865              : 
    1866            0 :         let mut http_client = reqwest::Client::builder();
    1867              :         // We intentionally disable the connection pool, so every request will create its own TCP connection.
    1868              :         // It's especially important for heartbeaters to notice more network problems.
    1869              :         //
    1870              :         // TODO: It makes sense to use this client only in heartbeaters and create a second one with
    1871              :         // connection pooling for everything else. But reqwest::Client may create a connection without
    1872              :         // ever using it (it uses hyper's Client under the hood):
    1873              :         // https://github.com/hyperium/hyper-util/blob/d51318df3461d40e5f5e5ca163cb3905ac960209/src/client/legacy/client.rs#L415
    1874              :         //
    1875              :         // Because of a bug in hyper0::Connection::graceful_shutdown such connections hang during
    1876              :         // graceful server shutdown: https://github.com/hyperium/hyper/issues/2730
    1877              :         //
    1878              :         // The bug has been fixed in hyper v1, so keep alive may be enabled only after we migrate to hyper1.
    1879            0 :         http_client = http_client.pool_max_idle_per_host(0);
    1880            0 :         for ssl_ca_cert in &config.ssl_ca_certs {
    1881            0 :             http_client = http_client.add_root_certificate(ssl_ca_cert.clone());
    1882            0 :         }
    1883            0 :         let http_client = http_client.build()?;
    1884              : 
    1885            0 :         let heartbeater_ps = Heartbeater::new(
    1886            0 :             http_client.clone(),
    1887            0 :             config.pageserver_jwt_token.clone(),
    1888            0 :             config.max_offline_interval,
    1889            0 :             config.max_warming_up_interval,
    1890            0 :             cancel.clone(),
    1891              :         );
    1892              : 
    1893            0 :         let heartbeater_sk = Heartbeater::new(
    1894            0 :             http_client.clone(),
    1895            0 :             config.safekeeper_jwt_token.clone(),
    1896            0 :             config.max_offline_interval,
    1897            0 :             config.max_warming_up_interval,
    1898            0 :             cancel.clone(),
    1899              :         );
    1900              : 
    1901            0 :         let initial_leadership_status = if config.start_as_candidate {
    1902            0 :             LeadershipStatus::Candidate
    1903              :         } else {
    1904            0 :             LeadershipStatus::Leader
    1905              :         };
    1906              : 
    1907            0 :         let this = Arc::new(Self {
    1908            0 :             inner: Arc::new(std::sync::RwLock::new(ServiceState::new(
    1909            0 :                 nodes,
    1910            0 :                 safekeepers,
    1911            0 :                 tenants,
    1912            0 :                 scheduler,
    1913            0 :                 delayed_reconcile_rx,
    1914            0 :                 initial_leadership_status,
    1915            0 :                 reconcilers_cancel.clone(),
    1916              :             ))),
    1917            0 :             config: config.clone(),
    1918            0 :             persistence,
    1919            0 :             compute_hook: Arc::new(ComputeHook::new(config.clone())?),
    1920            0 :             result_tx,
    1921            0 :             heartbeater_ps,
    1922            0 :             heartbeater_sk,
    1923            0 :             reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
    1924            0 :                 config.reconciler_concurrency,
    1925              :             )),
    1926            0 :             priority_reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
    1927            0 :                 config.priority_reconciler_concurrency,
    1928              :             )),
    1929            0 :             delayed_reconcile_tx,
    1930            0 :             abort_tx,
    1931            0 :             startup_complete: startup_complete.clone(),
    1932            0 :             cancel,
    1933            0 :             reconcilers_cancel,
    1934            0 :             gate: Gate::default(),
    1935            0 :             reconcilers_gate: Gate::default(),
    1936            0 :             tenant_op_locks: Default::default(),
    1937            0 :             node_op_locks: Default::default(),
    1938            0 :             http_client,
    1939            0 :             step_down_barrier: Default::default(),
    1940              :         });
    1941              : 
    1942            0 :         let result_task_this = this.clone();
    1943            0 :         tokio::task::spawn(async move {
    1944              :             // Block shutdown until we're done (we must respect self.cancel)
    1945            0 :             if let Ok(_gate) = result_task_this.gate.enter() {
    1946            0 :                 result_task_this
    1947            0 :                     .process_results(result_rx, bg_compute_notify_result_rx)
    1948            0 :                     .await
    1949            0 :             }
    1950            0 :         });
    1951              : 
    1952            0 :         tokio::task::spawn({
    1953            0 :             let this = this.clone();
    1954            0 :             async move {
    1955              :                 // Block shutdown until we're done (we must respect self.cancel)
    1956            0 :                 if let Ok(_gate) = this.gate.enter() {
    1957            0 :                     this.process_aborts(abort_rx).await
    1958            0 :                 }
    1959            0 :             }
    1960              :         });
    1961              : 
    1962            0 :         tokio::task::spawn({
    1963            0 :             let this = this.clone();
    1964            0 :             async move {
    1965            0 :                 if let Ok(_gate) = this.gate.enter() {
    1966              :                     loop {
    1967            0 :                         tokio::select! {
    1968            0 :                             _ = this.cancel.cancelled() => {
    1969            0 :                                 break;
    1970              :                             },
    1971            0 :                             _ = tokio::time::sleep(Duration::from_secs(60)) => {}
    1972              :                         };
    1973            0 :                         this.tenant_op_locks.housekeeping();
    1974              :                     }
    1975            0 :                 }
    1976            0 :             }
    1977              :         });
    1978              : 
    1979            0 :         tokio::task::spawn({
    1980            0 :             let this = this.clone();
    1981              :             // We will block the [`Service::startup_complete`] barrier until [`Self::startup_reconcile`]
    1982              :             // is done.
    1983            0 :             let startup_completion = startup_completion.clone();
    1984            0 :             async move {
    1985              :                 // Block shutdown until we're done (we must respect self.cancel)
    1986            0 :                 let Ok(_gate) = this.gate.enter() else {
    1987            0 :                     return;
    1988              :                 };
    1989              : 
    1990            0 :                 this.startup_reconcile(leader, leader_step_down_state, bg_compute_notify_result_tx)
    1991            0 :                     .await;
    1992              : 
    1993            0 :                 drop(startup_completion);
    1994            0 :             }
    1995              :         });
    1996              : 
    1997            0 :         tokio::task::spawn({
    1998            0 :             let this = this.clone();
    1999            0 :             let startup_complete = startup_complete.clone();
    2000            0 :             async move {
    2001            0 :                 startup_complete.wait().await;
    2002            0 :                 this.background_reconcile().await;
    2003            0 :             }
    2004              :         });
    2005              : 
    2006            0 :         tokio::task::spawn({
    2007            0 :             let this = this.clone();
    2008            0 :             let startup_complete = startup_complete.clone();
    2009            0 :             async move {
    2010            0 :                 startup_complete.wait().await;
    2011            0 :                 this.spawn_heartbeat_driver().await;
    2012            0 :             }
    2013              :         });
    2014              : 
    2015              :         // Check that there is enough safekeepers configured that we can create new timelines
    2016            0 :         let test_sk_res_str = match this.safekeepers_for_new_timeline().await {
    2017            0 :             Ok(v) => format!("Ok({v:?})"),
    2018            0 :             Err(v) => format!("Err({v:})"),
    2019              :         };
    2020            0 :         tracing::info!(
    2021              :             timeline_safekeeper_count = config.timeline_safekeeper_count,
    2022              :             timelines_onto_safekeepers = config.timelines_onto_safekeepers,
    2023            0 :             "viability test result (test timeline creation on safekeepers): {test_sk_res_str}",
    2024              :         );
    2025              : 
    2026            0 :         Ok(this)
    2027            0 :     }
    2028              : 
    2029            0 :     pub(crate) async fn attach_hook(
    2030            0 :         &self,
    2031            0 :         attach_req: AttachHookRequest,
    2032            0 :     ) -> anyhow::Result<AttachHookResponse> {
    2033            0 :         let _tenant_lock = trace_exclusive_lock(
    2034            0 :             &self.tenant_op_locks,
    2035            0 :             attach_req.tenant_shard_id.tenant_id,
    2036            0 :             TenantOperations::AttachHook,
    2037            0 :         )
    2038            0 :         .await;
    2039              : 
    2040              :         // This is a test hook.  To enable using it on tenants that were created directly with
    2041              :         // the pageserver API (not via this service), we will auto-create any missing tenant
    2042              :         // shards with default state.
    2043            0 :         let insert = {
    2044            0 :             match self
    2045            0 :                 .maybe_load_tenant(attach_req.tenant_shard_id.tenant_id, &_tenant_lock)
    2046            0 :                 .await
    2047              :             {
    2048            0 :                 Ok(_) => false,
    2049            0 :                 Err(ApiError::NotFound(_)) => true,
    2050            0 :                 Err(e) => return Err(e.into()),
    2051              :             }
    2052              :         };
    2053              : 
    2054            0 :         if insert {
    2055            0 :             let config = attach_req.config.clone().unwrap_or_default();
    2056            0 :             let tsp = TenantShardPersistence {
    2057            0 :                 tenant_id: attach_req.tenant_shard_id.tenant_id.to_string(),
    2058            0 :                 shard_number: attach_req.tenant_shard_id.shard_number.0 as i32,
    2059            0 :                 shard_count: attach_req.tenant_shard_id.shard_count.literal() as i32,
    2060            0 :                 shard_stripe_size: 0,
    2061            0 :                 generation: attach_req.generation_override.or(Some(0)),
    2062            0 :                 generation_pageserver: None,
    2063            0 :                 placement_policy: serde_json::to_string(&PlacementPolicy::Attached(0)).unwrap(),
    2064            0 :                 config: serde_json::to_string(&config).unwrap(),
    2065            0 :                 splitting: SplitState::default(),
    2066            0 :                 scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    2067            0 :                     .unwrap(),
    2068            0 :                 preferred_az_id: None,
    2069            0 :             };
    2070              : 
    2071            0 :             match self.persistence.insert_tenant_shards(vec![tsp]).await {
    2072            0 :                 Err(e) => match e {
    2073              :                     DatabaseError::Query(diesel::result::Error::DatabaseError(
    2074              :                         DatabaseErrorKind::UniqueViolation,
    2075              :                         _,
    2076              :                     )) => {
    2077            0 :                         tracing::info!(
    2078            0 :                             "Raced with another request to insert tenant {}",
    2079              :                             attach_req.tenant_shard_id
    2080              :                         )
    2081              :                     }
    2082            0 :                     _ => return Err(e.into()),
    2083              :                 },
    2084              :                 Ok(()) => {
    2085            0 :                     tracing::info!("Inserted shard {} in database", attach_req.tenant_shard_id);
    2086              : 
    2087            0 :                     let mut shard = TenantShard::new(
    2088            0 :                         attach_req.tenant_shard_id,
    2089            0 :                         ShardIdentity::unsharded(),
    2090            0 :                         PlacementPolicy::Attached(0),
    2091            0 :                         None,
    2092              :                     );
    2093            0 :                     shard.config = config;
    2094              : 
    2095            0 :                     let mut locked = self.inner.write().unwrap();
    2096            0 :                     locked.tenants.insert(attach_req.tenant_shard_id, shard);
    2097            0 :                     tracing::info!("Inserted shard {} in memory", attach_req.tenant_shard_id);
    2098              :                 }
    2099              :             }
    2100            0 :         }
    2101              : 
    2102            0 :         let new_generation = if let Some(req_node_id) = attach_req.node_id {
    2103            0 :             let maybe_tenant_conf = {
    2104            0 :                 let locked = self.inner.write().unwrap();
    2105            0 :                 locked
    2106            0 :                     .tenants
    2107            0 :                     .get(&attach_req.tenant_shard_id)
    2108            0 :                     .map(|t| t.config.clone())
    2109              :             };
    2110              : 
    2111            0 :             match maybe_tenant_conf {
    2112            0 :                 Some(conf) => {
    2113            0 :                     let new_generation = self
    2114            0 :                         .persistence
    2115            0 :                         .increment_generation(attach_req.tenant_shard_id, req_node_id)
    2116            0 :                         .await?;
    2117              : 
    2118              :                     // Persist the placement policy update. This is required
    2119              :                     // when we reattaching a detached tenant.
    2120            0 :                     self.persistence
    2121            0 :                         .update_tenant_shard(
    2122            0 :                             TenantFilter::Shard(attach_req.tenant_shard_id),
    2123            0 :                             Some(PlacementPolicy::Attached(0)),
    2124            0 :                             Some(conf),
    2125            0 :                             None,
    2126            0 :                             None,
    2127            0 :                         )
    2128            0 :                         .await?;
    2129            0 :                     Some(new_generation)
    2130              :                 }
    2131              :                 None => {
    2132            0 :                     anyhow::bail!("Attach hook handling raced with tenant removal")
    2133              :                 }
    2134              :             }
    2135              :         } else {
    2136            0 :             self.persistence.detach(attach_req.tenant_shard_id).await?;
    2137            0 :             None
    2138              :         };
    2139              : 
    2140            0 :         let mut locked = self.inner.write().unwrap();
    2141            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    2142              : 
    2143            0 :         let tenant_shard = tenants
    2144            0 :             .get_mut(&attach_req.tenant_shard_id)
    2145            0 :             .expect("Checked for existence above");
    2146              : 
    2147            0 :         if let Some(new_generation) = new_generation {
    2148            0 :             tenant_shard.generation = Some(new_generation);
    2149            0 :             tenant_shard.policy = PlacementPolicy::Attached(0);
    2150            0 :         } else {
    2151              :             // This is a detach notification.  We must update placement policy to avoid re-attaching
    2152              :             // during background scheduling/reconciliation, or during storage controller restart.
    2153            0 :             assert!(attach_req.node_id.is_none());
    2154            0 :             tenant_shard.policy = PlacementPolicy::Detached;
    2155              :         }
    2156              : 
    2157            0 :         if let Some(attaching_pageserver) = attach_req.node_id.as_ref() {
    2158            0 :             tracing::info!(
    2159              :                 tenant_id = %attach_req.tenant_shard_id,
    2160              :                 ps_id = %attaching_pageserver,
    2161              :                 generation = ?tenant_shard.generation,
    2162            0 :                 "issuing",
    2163              :             );
    2164            0 :         } else if let Some(ps_id) = tenant_shard.intent.get_attached() {
    2165            0 :             tracing::info!(
    2166              :                 tenant_id = %attach_req.tenant_shard_id,
    2167              :                 %ps_id,
    2168              :                 generation = ?tenant_shard.generation,
    2169            0 :                 "dropping",
    2170              :             );
    2171              :         } else {
    2172            0 :             tracing::info!(
    2173              :             tenant_id = %attach_req.tenant_shard_id,
    2174            0 :             "no-op: tenant already has no pageserver");
    2175              :         }
    2176            0 :         tenant_shard
    2177            0 :             .intent
    2178            0 :             .set_attached(scheduler, attach_req.node_id);
    2179              : 
    2180            0 :         tracing::info!(
    2181            0 :             "attach_hook: tenant {} set generation {:?}, pageserver {}, config {:?}",
    2182              :             attach_req.tenant_shard_id,
    2183              :             tenant_shard.generation,
    2184              :             // TODO: this is an odd number of 0xf's
    2185            0 :             attach_req.node_id.unwrap_or(utils::id::NodeId(0xfffffff)),
    2186              :             attach_req.config,
    2187              :         );
    2188              : 
    2189              :         // Trick the reconciler into not doing anything for this tenant: this helps
    2190              :         // tests that manually configure a tenant on the pagesrever, and then call this
    2191              :         // attach hook: they don't want background reconciliation to modify what they
    2192              :         // did to the pageserver.
    2193              :         #[cfg(feature = "testing")]
    2194              :         {
    2195            0 :             if let Some(node_id) = attach_req.node_id {
    2196            0 :                 tenant_shard.observed.locations = HashMap::from([(
    2197            0 :                     node_id,
    2198            0 :                     ObservedStateLocation {
    2199            0 :                         conf: Some(attached_location_conf(
    2200            0 :                             tenant_shard.generation.unwrap(),
    2201            0 :                             &tenant_shard.shard,
    2202            0 :                             &tenant_shard.config,
    2203            0 :                             &PlacementPolicy::Attached(0),
    2204            0 :                             tenant_shard.intent.get_secondary().len(),
    2205            0 :                         )),
    2206            0 :                     },
    2207            0 :                 )]);
    2208            0 :             } else {
    2209            0 :                 tenant_shard.observed.locations.clear();
    2210            0 :             }
    2211              :         }
    2212              : 
    2213              :         Ok(AttachHookResponse {
    2214            0 :             generation: attach_req
    2215            0 :                 .node_id
    2216            0 :                 .map(|_| tenant_shard.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap()),
    2217              :         })
    2218            0 :     }
    2219              : 
    2220            0 :     pub(crate) fn inspect(&self, inspect_req: InspectRequest) -> InspectResponse {
    2221            0 :         let locked = self.inner.read().unwrap();
    2222              : 
    2223            0 :         let tenant_shard = locked.tenants.get(&inspect_req.tenant_shard_id);
    2224              : 
    2225              :         InspectResponse {
    2226            0 :             attachment: tenant_shard.and_then(|s| {
    2227            0 :                 s.intent
    2228            0 :                     .get_attached()
    2229            0 :                     .map(|ps| (s.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap(), ps))
    2230            0 :             }),
    2231              :         }
    2232            0 :     }
    2233              : 
    2234              :     // When the availability state of a node transitions to active, we must do a full reconciliation
    2235              :     // of LocationConfigs on that node.  This is because while a node was offline:
    2236              :     // - we might have proceeded through startup_reconcile without checking for extraneous LocationConfigs on this node
    2237              :     // - aborting a tenant shard split might have left rogue child shards behind on this node.
    2238              :     //
    2239              :     // This function must complete _before_ setting a `Node` to Active: once it is set to Active, other
    2240              :     // Reconcilers might communicate with the node, and these must not overlap with the work we do in
    2241              :     // this function.
    2242              :     //
    2243              :     // The reconciliation logic in here is very similar to what [`Self::startup_reconcile`] does, but
    2244              :     // for written for a single node rather than as a batch job for all nodes.
    2245              :     #[tracing::instrument(skip_all, fields(node_id=%node.get_id()))]
    2246              :     async fn node_activate_reconcile(
    2247              :         &self,
    2248              :         mut node: Node,
    2249              :         _lock: &TracingExclusiveGuard<NodeOperations>,
    2250              :     ) -> Result<(), ApiError> {
    2251              :         // This Node is a mutable local copy: we will set it active so that we can use its
    2252              :         // API client to reconcile with the node.  The Node in [`Self::nodes`] will get updated
    2253              :         // later.
    2254              :         node.set_availability(NodeAvailability::Active(PageserverUtilization::full()));
    2255              : 
    2256              :         let configs = match node
    2257              :             .with_client_retries(
    2258            0 :                 |client| async move { client.list_location_config().await },
    2259              :                 &self.http_client,
    2260              :                 &self.config.pageserver_jwt_token,
    2261              :                 1,
    2262              :                 5,
    2263              :                 SHORT_RECONCILE_TIMEOUT,
    2264              :                 &self.cancel,
    2265              :             )
    2266              :             .await
    2267              :         {
    2268              :             None => {
    2269              :                 // We're shutting down (the Node's cancellation token can't have fired, because
    2270              :                 // we're the only scope that has a reference to it, and we didn't fire it).
    2271              :                 return Err(ApiError::ShuttingDown);
    2272              :             }
    2273              :             Some(Err(e)) => {
    2274              :                 // This node didn't succeed listing its locations: it may not proceed to active state
    2275              :                 // as it is apparently unavailable.
    2276              :                 return Err(ApiError::PreconditionFailed(
    2277              :                     format!("Failed to query node location configs, cannot activate ({e})").into(),
    2278              :                 ));
    2279              :             }
    2280              :             Some(Ok(configs)) => configs,
    2281              :         };
    2282              :         tracing::info!("Loaded {} LocationConfigs", configs.tenant_shards.len());
    2283              : 
    2284              :         let mut cleanup = Vec::new();
    2285              :         let mut mismatched_locations = 0;
    2286              :         {
    2287              :             let mut locked = self.inner.write().unwrap();
    2288              : 
    2289              :             for (tenant_shard_id, reported) in configs.tenant_shards {
    2290              :                 let Some(tenant_shard) = locked.tenants.get_mut(&tenant_shard_id) else {
    2291              :                     cleanup.push(tenant_shard_id);
    2292              :                     continue;
    2293              :                 };
    2294              : 
    2295              :                 let on_record = &mut tenant_shard
    2296              :                     .observed
    2297              :                     .locations
    2298              :                     .entry(node.get_id())
    2299            0 :                     .or_insert_with(|| ObservedStateLocation { conf: None })
    2300              :                     .conf;
    2301              : 
    2302              :                 // If the location reported by the node does not match our observed state,
    2303              :                 // then we mark it as uncertain and let the background reconciliation loop
    2304              :                 // deal with it.
    2305              :                 //
    2306              :                 // Note that this also covers net new locations reported by the node.
    2307              :                 if *on_record != reported {
    2308              :                     mismatched_locations += 1;
    2309              :                     *on_record = None;
    2310              :                 }
    2311              :             }
    2312              :         }
    2313              : 
    2314              :         if mismatched_locations > 0 {
    2315              :             tracing::info!(
    2316              :                 "Set observed state to None for {mismatched_locations} mismatched locations"
    2317              :             );
    2318              :         }
    2319              : 
    2320              :         for tenant_shard_id in cleanup {
    2321              :             tracing::info!("Detaching {tenant_shard_id}");
    2322              :             match node
    2323              :                 .with_client_retries(
    2324            0 :                     |client| async move {
    2325            0 :                         let config = LocationConfig {
    2326            0 :                             mode: LocationConfigMode::Detached,
    2327            0 :                             generation: None,
    2328            0 :                             secondary_conf: None,
    2329            0 :                             shard_number: tenant_shard_id.shard_number.0,
    2330            0 :                             shard_count: tenant_shard_id.shard_count.literal(),
    2331            0 :                             shard_stripe_size: 0,
    2332            0 :                             tenant_conf: models::TenantConfig::default(),
    2333            0 :                         };
    2334            0 :                         client
    2335            0 :                             .location_config(tenant_shard_id, config, None, false)
    2336            0 :                             .await
    2337            0 :                     },
    2338              :                     &self.http_client,
    2339              :                     &self.config.pageserver_jwt_token,
    2340              :                     1,
    2341              :                     5,
    2342              :                     SHORT_RECONCILE_TIMEOUT,
    2343              :                     &self.cancel,
    2344              :                 )
    2345              :                 .await
    2346              :             {
    2347              :                 None => {
    2348              :                     // We're shutting down (the Node's cancellation token can't have fired, because
    2349              :                     // we're the only scope that has a reference to it, and we didn't fire it).
    2350              :                     return Err(ApiError::ShuttingDown);
    2351              :                 }
    2352              :                 Some(Err(e)) => {
    2353              :                     // Do not let the node proceed to Active state if it is not responsive to requests
    2354              :                     // to detach.  This could happen if e.g. a shutdown bug in the pageserver is preventing
    2355              :                     // detach completing: we should not let this node back into the set of nodes considered
    2356              :                     // okay for scheduling.
    2357              :                     return Err(ApiError::Conflict(format!(
    2358              :                         "Node {node} failed to detach {tenant_shard_id}: {e}"
    2359              :                     )));
    2360              :                 }
    2361              :                 Some(Ok(_)) => {}
    2362              :             };
    2363              :         }
    2364              : 
    2365              :         Ok(())
    2366              :     }
    2367              : 
    2368            0 :     pub(crate) async fn re_attach(
    2369            0 :         &self,
    2370            0 :         reattach_req: ReAttachRequest,
    2371            0 :     ) -> Result<ReAttachResponse, ApiError> {
    2372            0 :         if let Some(register_req) = reattach_req.register {
    2373            0 :             self.node_register(register_req).await?;
    2374            0 :         }
    2375              : 
    2376              :         // Ordering: we must persist generation number updates before making them visible in the in-memory state
    2377            0 :         let incremented_generations = self.persistence.re_attach(reattach_req.node_id).await?;
    2378              : 
    2379            0 :         tracing::info!(
    2380              :             node_id=%reattach_req.node_id,
    2381            0 :             "Incremented {} tenant shards' generations",
    2382            0 :             incremented_generations.len()
    2383              :         );
    2384              : 
    2385              :         // Apply the updated generation to our in-memory state, and
    2386              :         // gather discover secondary locations.
    2387            0 :         let mut locked = self.inner.write().unwrap();
    2388            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    2389              : 
    2390            0 :         let mut response = ReAttachResponse {
    2391            0 :             tenants: Vec::new(),
    2392            0 :         };
    2393              : 
    2394              :         // [Hadron] If the pageserver reports in the reattach message that it has an empty disk, it's possible that it just
    2395              :         // recovered from a local disk failure. The response of the reattach request will contain a list of tenants but it
    2396              :         // will not be honored by the pageserver in this case (disk failure). We should make sure we clear any observed
    2397              :         // locations of tenants attached to the node so that the reconciler will discover the discrpancy and reconfigure the
    2398              :         // missing tenants on the node properly.
    2399            0 :         if self.config.handle_ps_local_disk_loss && reattach_req.empty_local_disk.unwrap_or(false) {
    2400            0 :             tracing::info!(
    2401            0 :                 "Pageserver {node_id} reports empty local disk, clearing observed locations referencing the pageserver for all tenants",
    2402              :                 node_id = reattach_req.node_id
    2403              :             );
    2404            0 :             let mut num_tenant_shards_affected = 0;
    2405            0 :             for (tenant_shard_id, shard) in tenants.iter_mut() {
    2406            0 :                 if shard
    2407            0 :                     .observed
    2408            0 :                     .locations
    2409            0 :                     .remove(&reattach_req.node_id)
    2410            0 :                     .is_some()
    2411              :                 {
    2412            0 :                     tracing::info!("Cleared observed location for tenant shard {tenant_shard_id}");
    2413            0 :                     num_tenant_shards_affected += 1;
    2414            0 :                 }
    2415              :             }
    2416            0 :             tracing::info!(
    2417            0 :                 "Cleared observed locations for {num_tenant_shards_affected} tenant shards"
    2418              :             );
    2419            0 :         }
    2420              : 
    2421              :         // TODO: cancel/restart any running reconciliation for this tenant, it might be trying
    2422              :         // to call location_conf API with an old generation.  Wait for cancellation to complete
    2423              :         // before responding to this request.  Requires well implemented CancellationToken logic
    2424              :         // all the way to where we call location_conf.  Even then, there can still be a location_conf
    2425              :         // request in flight over the network: TODO handle that by making location_conf API refuse
    2426              :         // to go backward in generations.
    2427              : 
    2428              :         // Scan through all shards, applying updates for ones where we updated generation
    2429              :         // and identifying shards that intend to have a secondary location on this node.
    2430            0 :         for (tenant_shard_id, shard) in tenants {
    2431            0 :             if let Some(new_gen) = incremented_generations.get(tenant_shard_id) {
    2432            0 :                 let new_gen = *new_gen;
    2433            0 :                 response.tenants.push(ReAttachResponseTenant {
    2434            0 :                     id: *tenant_shard_id,
    2435            0 :                     r#gen: Some(new_gen.into().unwrap()),
    2436            0 :                     // A tenant is only put into multi or stale modes in the middle of a [`Reconciler::live_migrate`]
    2437            0 :                     // execution.  If a pageserver is restarted during that process, then the reconcile pass will
    2438            0 :                     // fail, and start from scratch, so it doesn't make sense for us to try and preserve
    2439            0 :                     // the stale/multi states at this point.
    2440            0 :                     mode: LocationConfigMode::AttachedSingle,
    2441            0 :                     stripe_size: shard.shard.stripe_size,
    2442            0 :                 });
    2443              : 
    2444            0 :                 shard.generation = std::cmp::max(shard.generation, Some(new_gen));
    2445            0 :                 if let Some(observed) = shard.observed.locations.get_mut(&reattach_req.node_id) {
    2446              :                     // Why can we update `observed` even though we're not sure our response will be received
    2447              :                     // by the pageserver?  Because the pageserver will not proceed with startup until
    2448              :                     // it has processed response: if it loses it, we'll see another request and increment
    2449              :                     // generation again, avoiding any uncertainty about dirtiness of tenant's state.
    2450            0 :                     if let Some(conf) = observed.conf.as_mut() {
    2451            0 :                         conf.generation = new_gen.into();
    2452            0 :                     }
    2453            0 :                 } else {
    2454            0 :                     // This node has no observed state for the shard: perhaps it was offline
    2455            0 :                     // when the pageserver restarted.  Insert a None, so that the Reconciler
    2456            0 :                     // will be prompted to learn the location's state before it makes changes.
    2457            0 :                     shard
    2458            0 :                         .observed
    2459            0 :                         .locations
    2460            0 :                         .insert(reattach_req.node_id, ObservedStateLocation { conf: None });
    2461            0 :                 }
    2462            0 :             } else if shard.intent.get_secondary().contains(&reattach_req.node_id) {
    2463            0 :                 // Ordering: pageserver will not accept /location_config requests until it has
    2464            0 :                 // finished processing the response from re-attach.  So we can update our in-memory state
    2465            0 :                 // now, and be confident that we are not stamping on the result of some later location config.
    2466            0 :                 // TODO: however, we are not strictly ordered wrt ReconcileResults queue,
    2467            0 :                 // so we might update observed state here, and then get over-written by some racing
    2468            0 :                 // ReconcileResult.  The impact is low however, since we have set state on pageserver something
    2469            0 :                 // that matches intent, so worst case if we race then we end up doing a spurious reconcile.
    2470            0 : 
    2471            0 :                 response.tenants.push(ReAttachResponseTenant {
    2472            0 :                     id: *tenant_shard_id,
    2473            0 :                     r#gen: None,
    2474            0 :                     mode: LocationConfigMode::Secondary,
    2475            0 :                     stripe_size: shard.shard.stripe_size,
    2476            0 :                 });
    2477            0 : 
    2478            0 :                 // We must not update observed, because we have no guarantee that our
    2479            0 :                 // response will be received by the pageserver. This could leave it
    2480            0 :                 // falsely dirty, but the resulting reconcile should be idempotent.
    2481            0 :             }
    2482              :         }
    2483              : 
    2484              :         // We consider a node Active once we have composed a re-attach response, but we
    2485              :         // do not call [`Self::node_activate_reconcile`]: the handling of the re-attach response
    2486              :         // implicitly synchronizes the LocationConfigs on the node.
    2487              :         //
    2488              :         // Setting a node active unblocks any Reconcilers that might write to the location config API,
    2489              :         // but those requests will not be accepted by the node until it has finished processing
    2490              :         // the re-attach response.
    2491              :         //
    2492              :         // Additionally, reset the nodes scheduling policy to match the conditional update done
    2493              :         // in [`Persistence::re_attach`].
    2494            0 :         if let Some(node) = nodes.get(&reattach_req.node_id) {
    2495            0 :             let reset_scheduling = matches!(
    2496            0 :                 node.get_scheduling(),
    2497              :                 NodeSchedulingPolicy::PauseForRestart
    2498              :                     | NodeSchedulingPolicy::Draining
    2499              :                     | NodeSchedulingPolicy::Filling
    2500              :                     | NodeSchedulingPolicy::Deleting
    2501              :             );
    2502              : 
    2503            0 :             let mut new_nodes = (**nodes).clone();
    2504            0 :             if let Some(node) = new_nodes.get_mut(&reattach_req.node_id) {
    2505            0 :                 if reset_scheduling {
    2506            0 :                     node.set_scheduling(NodeSchedulingPolicy::Active);
    2507            0 :                 }
    2508              : 
    2509            0 :                 tracing::info!("Marking {} warming-up on reattach", reattach_req.node_id);
    2510            0 :                 node.set_availability(NodeAvailability::WarmingUp(std::time::Instant::now()));
    2511              : 
    2512            0 :                 scheduler.node_upsert(node);
    2513            0 :                 let new_nodes = Arc::new(new_nodes);
    2514            0 :                 *nodes = new_nodes;
    2515              :             } else {
    2516            0 :                 tracing::error!(
    2517            0 :                     "Reattaching node {} was removed while processing the request",
    2518              :                     reattach_req.node_id
    2519              :                 );
    2520              :             }
    2521            0 :         }
    2522              : 
    2523            0 :         Ok(response)
    2524            0 :     }
    2525              : 
    2526            0 :     pub(crate) async fn validate(
    2527            0 :         &self,
    2528            0 :         validate_req: ValidateRequest,
    2529            0 :     ) -> Result<ValidateResponse, DatabaseError> {
    2530              :         // Fast in-memory check: we may reject validation on anything that doesn't match our
    2531              :         // in-memory generation for a shard
    2532            0 :         let in_memory_result = {
    2533            0 :             let mut in_memory_result = Vec::new();
    2534            0 :             let locked = self.inner.read().unwrap();
    2535            0 :             for req_tenant in validate_req.tenants {
    2536            0 :                 if let Some(tenant_shard) = locked.tenants.get(&req_tenant.id) {
    2537            0 :                     let valid = tenant_shard.generation == Some(Generation::new(req_tenant.r#gen));
    2538            0 :                     tracing::info!(
    2539            0 :                         "handle_validate: {}(gen {}): valid={valid} (latest {:?})",
    2540              :                         req_tenant.id,
    2541              :                         req_tenant.r#gen,
    2542              :                         tenant_shard.generation
    2543              :                     );
    2544              : 
    2545            0 :                     in_memory_result.push((
    2546            0 :                         req_tenant.id,
    2547            0 :                         Generation::new(req_tenant.r#gen),
    2548            0 :                         valid,
    2549            0 :                     ));
    2550              :                 } else {
    2551              :                     // This is legal: for example during a shard split the pageserver may still
    2552              :                     // have deletions in its queue from the old pre-split shard, or after deletion
    2553              :                     // of a tenant that was busy with compaction/gc while being deleted.
    2554            0 :                     tracing::info!(
    2555            0 :                         "Refusing deletion validation for missing shard {}",
    2556              :                         req_tenant.id
    2557              :                     );
    2558              :                 }
    2559              :             }
    2560              : 
    2561            0 :             in_memory_result
    2562              :         };
    2563              : 
    2564              :         // Database calls to confirm validity for anything that passed the in-memory check.  We must do this
    2565              :         // in case of controller split-brain, where some other controller process might have incremented the generation.
    2566            0 :         let db_generations = self
    2567            0 :             .persistence
    2568            0 :             .shard_generations(
    2569            0 :                 in_memory_result
    2570            0 :                     .iter()
    2571            0 :                     .filter_map(|i| if i.2 { Some(&i.0) } else { None }),
    2572              :             )
    2573            0 :             .await?;
    2574            0 :         let db_generations = db_generations.into_iter().collect::<HashMap<_, _>>();
    2575              : 
    2576            0 :         let mut response = ValidateResponse {
    2577            0 :             tenants: Vec::new(),
    2578            0 :         };
    2579            0 :         for (tenant_shard_id, validate_generation, valid) in in_memory_result.into_iter() {
    2580            0 :             let valid = if valid {
    2581            0 :                 let db_generation = db_generations.get(&tenant_shard_id);
    2582            0 :                 db_generation == Some(&Some(validate_generation))
    2583              :             } else {
    2584              :                 // If in-memory state says it's invalid, trust that.  It's always safe to fail a validation, at worst
    2585              :                 // this prevents a pageserver from cleaning up an object in S3.
    2586            0 :                 false
    2587              :             };
    2588              : 
    2589            0 :             response.tenants.push(ValidateResponseTenant {
    2590            0 :                 id: tenant_shard_id,
    2591            0 :                 valid,
    2592            0 :             })
    2593              :         }
    2594              : 
    2595            0 :         Ok(response)
    2596            0 :     }
    2597              : 
    2598            0 :     pub(crate) async fn tenant_create(
    2599            0 :         &self,
    2600            0 :         create_req: TenantCreateRequest,
    2601            0 :     ) -> Result<TenantCreateResponse, ApiError> {
    2602            0 :         let tenant_id = create_req.new_tenant_id.tenant_id;
    2603              : 
    2604              :         // Exclude any concurrent attempts to create/access the same tenant ID
    2605            0 :         let _tenant_lock = trace_exclusive_lock(
    2606            0 :             &self.tenant_op_locks,
    2607            0 :             create_req.new_tenant_id.tenant_id,
    2608            0 :             TenantOperations::Create,
    2609            0 :         )
    2610            0 :         .await;
    2611            0 :         let (response, waiters) = self.do_tenant_create(create_req).await?;
    2612              : 
    2613            0 :         if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    2614              :             // Avoid deadlock: reconcile may fail while notifying compute, if the cloud control plane refuses to
    2615              :             // accept compute notifications while it is in the process of creating.  Reconciliation will
    2616              :             // be retried in the background.
    2617            0 :             tracing::warn!(%tenant_id, "Reconcile not done yet while creating tenant ({e})");
    2618            0 :         }
    2619            0 :         Ok(response)
    2620            0 :     }
    2621              : 
    2622            0 :     pub(crate) async fn do_tenant_create(
    2623            0 :         &self,
    2624            0 :         create_req: TenantCreateRequest,
    2625            0 :     ) -> Result<(TenantCreateResponse, Vec<ReconcilerWaiter>), ApiError> {
    2626            0 :         let placement_policy = create_req
    2627            0 :             .placement_policy
    2628            0 :             .clone()
    2629              :             // As a default, zero secondaries is convenient for tests that don't choose a policy.
    2630            0 :             .unwrap_or(PlacementPolicy::Attached(0));
    2631              : 
    2632              :         // This service expects to handle sharding itself: it is an error to try and directly create
    2633              :         // a particular shard here.
    2634            0 :         let tenant_id = if !create_req.new_tenant_id.is_unsharded() {
    2635            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!(
    2636            0 :                 "Attempted to create a specific shard, this API is for creating the whole tenant"
    2637            0 :             )));
    2638              :         } else {
    2639            0 :             create_req.new_tenant_id.tenant_id
    2640              :         };
    2641              : 
    2642            0 :         tracing::info!(
    2643            0 :             "Creating tenant {}, shard_count={:?}",
    2644              :             create_req.new_tenant_id,
    2645              :             create_req.shard_parameters.count,
    2646              :         );
    2647              : 
    2648            0 :         let create_ids = (0..create_req.shard_parameters.count.count())
    2649            0 :             .map(|i| TenantShardId {
    2650            0 :                 tenant_id,
    2651            0 :                 shard_number: ShardNumber(i),
    2652            0 :                 shard_count: create_req.shard_parameters.count,
    2653            0 :             })
    2654            0 :             .collect::<Vec<_>>();
    2655              : 
    2656              :         // If the caller specifies a None generation, it means "start from default".  This is different
    2657              :         // to [`Self::tenant_location_config`], where a None generation is used to represent
    2658              :         // an incompletely-onboarded tenant.
    2659            0 :         let initial_generation = if matches!(placement_policy, PlacementPolicy::Secondary) {
    2660            0 :             tracing::info!(
    2661            0 :                 "tenant_create: secondary mode, generation is_some={}",
    2662            0 :                 create_req.generation.is_some()
    2663              :             );
    2664            0 :             create_req.generation.map(Generation::new)
    2665              :         } else {
    2666            0 :             tracing::info!(
    2667            0 :                 "tenant_create: not secondary mode, generation is_some={}",
    2668            0 :                 create_req.generation.is_some()
    2669              :             );
    2670            0 :             Some(
    2671            0 :                 create_req
    2672            0 :                     .generation
    2673            0 :                     .map(Generation::new)
    2674            0 :                     .unwrap_or(INITIAL_GENERATION),
    2675            0 :             )
    2676              :         };
    2677              : 
    2678            0 :         let preferred_az_id = {
    2679            0 :             let locked = self.inner.read().unwrap();
    2680              :             // Idempotency: take the existing value if the tenant already exists
    2681            0 :             if let Some(shard) = locked.tenants.get(create_ids.first().unwrap()) {
    2682            0 :                 shard.preferred_az().cloned()
    2683              :             } else {
    2684            0 :                 locked.scheduler.get_az_for_new_tenant()
    2685              :             }
    2686              :         };
    2687              : 
    2688              :         // Ordering: we persist tenant shards before creating them on the pageserver.  This enables a caller
    2689              :         // to clean up after themselves by issuing a tenant deletion if something goes wrong and we restart
    2690              :         // during the creation, rather than risking leaving orphan objects in S3.
    2691            0 :         let persist_tenant_shards = create_ids
    2692            0 :             .iter()
    2693            0 :             .map(|tenant_shard_id| TenantShardPersistence {
    2694            0 :                 tenant_id: tenant_shard_id.tenant_id.to_string(),
    2695            0 :                 shard_number: tenant_shard_id.shard_number.0 as i32,
    2696            0 :                 shard_count: tenant_shard_id.shard_count.literal() as i32,
    2697            0 :                 shard_stripe_size: create_req.shard_parameters.stripe_size.0 as i32,
    2698            0 :                 generation: initial_generation.map(|g| g.into().unwrap() as i32),
    2699              :                 // The pageserver is not known until scheduling happens: we will set this column when
    2700              :                 // incrementing the generation the first time we attach to a pageserver.
    2701            0 :                 generation_pageserver: None,
    2702            0 :                 placement_policy: serde_json::to_string(&placement_policy).unwrap(),
    2703            0 :                 config: serde_json::to_string(&create_req.config).unwrap(),
    2704            0 :                 splitting: SplitState::default(),
    2705            0 :                 scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    2706            0 :                     .unwrap(),
    2707            0 :                 preferred_az_id: preferred_az_id.as_ref().map(|az| az.to_string()),
    2708            0 :             })
    2709            0 :             .collect();
    2710              : 
    2711            0 :         match self
    2712            0 :             .persistence
    2713            0 :             .insert_tenant_shards(persist_tenant_shards)
    2714            0 :             .await
    2715              :         {
    2716            0 :             Ok(_) => {}
    2717              :             Err(DatabaseError::Query(diesel::result::Error::DatabaseError(
    2718              :                 DatabaseErrorKind::UniqueViolation,
    2719              :                 _,
    2720              :             ))) => {
    2721              :                 // Unique key violation: this is probably a retry.  Because the shard count is part of the unique key,
    2722              :                 // if we see a unique key violation it means that the creation request's shard count matches the previous
    2723              :                 // creation's shard count.
    2724            0 :                 tracing::info!(
    2725            0 :                     "Tenant shards already present in database, proceeding with idempotent creation..."
    2726              :                 );
    2727              :             }
    2728              :             // Any other database error is unexpected and a bug.
    2729            0 :             Err(e) => return Err(ApiError::InternalServerError(anyhow::anyhow!(e))),
    2730              :         };
    2731              : 
    2732            0 :         let mut schedule_context = ScheduleContext::default();
    2733            0 :         let mut schedule_error = None;
    2734            0 :         let mut response_shards = Vec::new();
    2735            0 :         for tenant_shard_id in create_ids {
    2736            0 :             tracing::info!("Creating shard {tenant_shard_id}...");
    2737              : 
    2738            0 :             let outcome = self
    2739            0 :                 .do_initial_shard_scheduling(
    2740            0 :                     tenant_shard_id,
    2741            0 :                     initial_generation,
    2742            0 :                     create_req.shard_parameters,
    2743            0 :                     create_req.config.clone(),
    2744            0 :                     placement_policy.clone(),
    2745            0 :                     preferred_az_id.as_ref(),
    2746            0 :                     &mut schedule_context,
    2747            0 :                 )
    2748            0 :                 .await;
    2749              : 
    2750            0 :             match outcome {
    2751            0 :                 InitialShardScheduleOutcome::Scheduled(resp) => response_shards.push(resp),
    2752            0 :                 InitialShardScheduleOutcome::NotScheduled => {}
    2753            0 :                 InitialShardScheduleOutcome::ShardScheduleError(err) => {
    2754            0 :                     schedule_error = Some(err);
    2755            0 :                 }
    2756              :             }
    2757              :         }
    2758              : 
    2759              :         // If we failed to schedule shards, then they are still created in the controller,
    2760              :         // but we return an error to the requester to avoid a silent failure when someone
    2761              :         // tries to e.g. create a tenant whose placement policy requires more nodes than
    2762              :         // are present in the system.  We do this here rather than in the above loop, to
    2763              :         // avoid situations where we only create a subset of shards in the tenant.
    2764            0 :         if let Some(e) = schedule_error {
    2765            0 :             return Err(ApiError::Conflict(format!(
    2766            0 :                 "Failed to schedule shard(s): {e}"
    2767            0 :             )));
    2768            0 :         }
    2769              : 
    2770            0 :         let waiters = {
    2771            0 :             let mut locked = self.inner.write().unwrap();
    2772            0 :             let (nodes, tenants, _scheduler) = locked.parts_mut();
    2773            0 :             let config = ReconcilerConfigBuilder::new(ReconcilerPriority::High)
    2774            0 :                 .tenant_creation_hint(true)
    2775            0 :                 .build();
    2776            0 :             tenants
    2777            0 :                 .range_mut(TenantShardId::tenant_range(tenant_id))
    2778            0 :                 .filter_map(|(_shard_id, shard)| {
    2779            0 :                     self.maybe_configured_reconcile_shard(shard, nodes, config)
    2780            0 :                 })
    2781            0 :                 .collect::<Vec<_>>()
    2782              :         };
    2783              : 
    2784            0 :         Ok((
    2785            0 :             TenantCreateResponse {
    2786            0 :                 shards: response_shards,
    2787            0 :             },
    2788            0 :             waiters,
    2789            0 :         ))
    2790            0 :     }
    2791              : 
    2792              :     /// Helper for tenant creation that does the scheduling for an individual shard. Covers both the
    2793              :     /// case of a new tenant and a pre-existing one.
    2794              :     #[allow(clippy::too_many_arguments)]
    2795            0 :     async fn do_initial_shard_scheduling(
    2796            0 :         &self,
    2797            0 :         tenant_shard_id: TenantShardId,
    2798            0 :         initial_generation: Option<Generation>,
    2799            0 :         shard_params: ShardParameters,
    2800            0 :         config: TenantConfig,
    2801            0 :         placement_policy: PlacementPolicy,
    2802            0 :         preferred_az_id: Option<&AvailabilityZone>,
    2803            0 :         schedule_context: &mut ScheduleContext,
    2804            0 :     ) -> InitialShardScheduleOutcome {
    2805            0 :         let mut locked = self.inner.write().unwrap();
    2806            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    2807              : 
    2808              :         use std::collections::btree_map::Entry;
    2809            0 :         match tenants.entry(tenant_shard_id) {
    2810            0 :             Entry::Occupied(mut entry) => {
    2811            0 :                 tracing::info!("Tenant shard {tenant_shard_id} already exists while creating");
    2812              : 
    2813            0 :                 if let Err(err) = entry.get_mut().schedule(scheduler, schedule_context) {
    2814            0 :                     return InitialShardScheduleOutcome::ShardScheduleError(err);
    2815            0 :                 }
    2816              : 
    2817            0 :                 if let Some(node_id) = entry.get().intent.get_attached() {
    2818            0 :                     let generation = entry
    2819            0 :                         .get()
    2820            0 :                         .generation
    2821            0 :                         .expect("Generation is set when in attached mode");
    2822            0 :                     InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
    2823            0 :                         shard_id: tenant_shard_id,
    2824            0 :                         node_id: *node_id,
    2825            0 :                         generation: generation.into().unwrap(),
    2826            0 :                     })
    2827              :                 } else {
    2828            0 :                     InitialShardScheduleOutcome::NotScheduled
    2829              :                 }
    2830              :             }
    2831            0 :             Entry::Vacant(entry) => {
    2832            0 :                 let state = entry.insert(TenantShard::new(
    2833            0 :                     tenant_shard_id,
    2834            0 :                     ShardIdentity::from_params(tenant_shard_id.shard_number, shard_params),
    2835            0 :                     placement_policy,
    2836            0 :                     preferred_az_id.cloned(),
    2837              :                 ));
    2838              : 
    2839            0 :                 state.generation = initial_generation;
    2840            0 :                 state.config = config;
    2841            0 :                 if let Err(e) = state.schedule(scheduler, schedule_context) {
    2842            0 :                     return InitialShardScheduleOutcome::ShardScheduleError(e);
    2843            0 :                 }
    2844              : 
    2845              :                 // Only include shards in result if we are attaching: the purpose
    2846              :                 // of the response is to tell the caller where the shards are attached.
    2847            0 :                 if let Some(node_id) = state.intent.get_attached() {
    2848            0 :                     let generation = state
    2849            0 :                         .generation
    2850            0 :                         .expect("Generation is set when in attached mode");
    2851            0 :                     InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
    2852            0 :                         shard_id: tenant_shard_id,
    2853            0 :                         node_id: *node_id,
    2854            0 :                         generation: generation.into().unwrap(),
    2855            0 :                     })
    2856              :                 } else {
    2857            0 :                     InitialShardScheduleOutcome::NotScheduled
    2858              :                 }
    2859              :             }
    2860              :         }
    2861            0 :     }
    2862              : 
    2863              :     /// Helper for functions that reconcile a number of shards, and would like to do a timeout-bounded
    2864              :     /// wait for reconciliation to complete before responding.
    2865            0 :     async fn await_waiters(
    2866            0 :         &self,
    2867            0 :         waiters: Vec<ReconcilerWaiter>,
    2868            0 :         timeout: Duration,
    2869            0 :     ) -> Result<(), ReconcileWaitError> {
    2870            0 :         let deadline = Instant::now().checked_add(timeout).unwrap();
    2871            0 :         for waiter in waiters {
    2872            0 :             let timeout = deadline.duration_since(Instant::now());
    2873            0 :             waiter.wait_timeout(timeout).await?;
    2874              :         }
    2875              : 
    2876            0 :         Ok(())
    2877            0 :     }
    2878              : 
    2879              :     /// Same as [`Service::await_waiters`], but returns the waiters which are still
    2880              :     /// in progress
    2881            0 :     async fn await_waiters_remainder(
    2882            0 :         &self,
    2883            0 :         waiters: Vec<ReconcilerWaiter>,
    2884            0 :         timeout: Duration,
    2885            0 :     ) -> Vec<ReconcilerWaiter> {
    2886            0 :         let deadline = Instant::now().checked_add(timeout).unwrap();
    2887            0 :         for waiter in waiters.iter() {
    2888            0 :             let timeout = deadline.duration_since(Instant::now());
    2889            0 :             let _ = waiter.wait_timeout(timeout).await;
    2890              :         }
    2891              : 
    2892            0 :         waiters
    2893            0 :             .into_iter()
    2894            0 :             .filter(|waiter| matches!(waiter.get_status(), ReconcilerStatus::InProgress))
    2895            0 :             .collect::<Vec<_>>()
    2896            0 :     }
    2897              : 
    2898              :     /// Part of [`Self::tenant_location_config`]: dissect an incoming location config request,
    2899              :     /// and transform it into either a tenant creation of a series of shard updates.
    2900              :     ///
    2901              :     /// If the incoming request makes no changes, a [`TenantCreateOrUpdate::Update`] result will
    2902              :     /// still be returned.
    2903            0 :     fn tenant_location_config_prepare(
    2904            0 :         &self,
    2905            0 :         tenant_id: TenantId,
    2906            0 :         req: TenantLocationConfigRequest,
    2907            0 :     ) -> TenantCreateOrUpdate {
    2908            0 :         let mut updates = Vec::new();
    2909            0 :         let mut locked = self.inner.write().unwrap();
    2910            0 :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    2911            0 :         let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    2912              : 
    2913              :         // Use location config mode as an indicator of policy.
    2914            0 :         let placement_policy = match req.config.mode {
    2915            0 :             LocationConfigMode::Detached => PlacementPolicy::Detached,
    2916            0 :             LocationConfigMode::Secondary => PlacementPolicy::Secondary,
    2917              :             LocationConfigMode::AttachedMulti
    2918              :             | LocationConfigMode::AttachedSingle
    2919              :             | LocationConfigMode::AttachedStale => {
    2920            0 :                 if nodes.len() > 1 {
    2921            0 :                     PlacementPolicy::Attached(1)
    2922              :                 } else {
    2923              :                     // Convenience for dev/test: if we just have one pageserver, import
    2924              :                     // tenants into non-HA mode so that scheduling will succeed.
    2925            0 :                     PlacementPolicy::Attached(0)
    2926              :                 }
    2927              :             }
    2928              :         };
    2929              : 
    2930              :         // Ordinarily we do not update scheduling policy, but when making major changes
    2931              :         // like detaching or demoting to secondary-only, we need to force the scheduling
    2932              :         // mode to Active, or the caller's expected outcome (detach it) will not happen.
    2933            0 :         let scheduling_policy = match req.config.mode {
    2934              :             LocationConfigMode::Detached | LocationConfigMode::Secondary => {
    2935              :                 // Special case: when making major changes like detaching or demoting to secondary-only,
    2936              :                 // we need to force the scheduling mode to Active, or nothing will happen.
    2937            0 :                 Some(ShardSchedulingPolicy::Active)
    2938              :             }
    2939              :             LocationConfigMode::AttachedMulti
    2940              :             | LocationConfigMode::AttachedSingle
    2941              :             | LocationConfigMode::AttachedStale => {
    2942              :                 // While attached, continue to respect whatever the existing scheduling mode is.
    2943            0 :                 None
    2944              :             }
    2945              :         };
    2946              : 
    2947            0 :         let mut create = true;
    2948            0 :         for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    2949              :             // Saw an existing shard: this is not a creation
    2950            0 :             create = false;
    2951              : 
    2952              :             // Shards may have initially been created by a Secondary request, where we
    2953              :             // would have left generation as None.
    2954              :             //
    2955              :             // We only update generation the first time we see an attached-mode request,
    2956              :             // and if there is no existing generation set. The caller is responsible for
    2957              :             // ensuring that no non-storage-controller pageserver ever uses a higher
    2958              :             // generation than they passed in here.
    2959              :             use LocationConfigMode::*;
    2960            0 :             let set_generation = match req.config.mode {
    2961            0 :                 AttachedMulti | AttachedSingle | AttachedStale if shard.generation.is_none() => {
    2962            0 :                     req.config.generation.map(Generation::new)
    2963              :                 }
    2964            0 :                 _ => None,
    2965              :             };
    2966              : 
    2967            0 :             updates.push(ShardUpdate {
    2968            0 :                 tenant_shard_id: *shard_id,
    2969            0 :                 placement_policy: placement_policy.clone(),
    2970            0 :                 tenant_config: req.config.tenant_conf.clone(),
    2971            0 :                 generation: set_generation,
    2972            0 :                 scheduling_policy,
    2973            0 :             });
    2974              :         }
    2975              : 
    2976            0 :         if create {
    2977              :             use LocationConfigMode::*;
    2978            0 :             let generation = match req.config.mode {
    2979            0 :                 AttachedMulti | AttachedSingle | AttachedStale => req.config.generation,
    2980              :                 // If a caller provided a generation in a non-attached request, ignore it
    2981              :                 // and leave our generation as None: this enables a subsequent update to set
    2982              :                 // the generation when setting an attached mode for the first time.
    2983            0 :                 _ => None,
    2984              :             };
    2985              : 
    2986            0 :             TenantCreateOrUpdate::Create(
    2987            0 :                 // Synthesize a creation request
    2988            0 :                 TenantCreateRequest {
    2989            0 :                     new_tenant_id: tenant_shard_id,
    2990            0 :                     generation,
    2991            0 :                     shard_parameters: ShardParameters {
    2992            0 :                         count: tenant_shard_id.shard_count,
    2993            0 :                         // We only import un-sharded or single-sharded tenants, so stripe
    2994            0 :                         // size can be made up arbitrarily here.
    2995            0 :                         stripe_size: DEFAULT_STRIPE_SIZE,
    2996            0 :                     },
    2997            0 :                     placement_policy: Some(placement_policy),
    2998            0 :                     config: req.config.tenant_conf,
    2999            0 :                 },
    3000            0 :             )
    3001              :         } else {
    3002            0 :             assert!(!updates.is_empty());
    3003            0 :             TenantCreateOrUpdate::Update(updates)
    3004              :         }
    3005            0 :     }
    3006              : 
    3007              :     /// For APIs that might act on tenants with [`PlacementPolicy::Detached`], first check if
    3008              :     /// the tenant is present in memory. If not, load it from the database.  If it is found
    3009              :     /// in neither location, return a NotFound error.
    3010              :     ///
    3011              :     /// Caller must demonstrate they hold a lock guard, as otherwise two callers might try and load
    3012              :     /// it at the same time, or we might race with [`Self::maybe_drop_tenant`]
    3013            0 :     async fn maybe_load_tenant(
    3014            0 :         &self,
    3015            0 :         tenant_id: TenantId,
    3016            0 :         _guard: &TracingExclusiveGuard<TenantOperations>,
    3017            0 :     ) -> Result<(), ApiError> {
    3018              :         // Check if the tenant is present in memory, and select an AZ to use when loading
    3019              :         // if we will load it.
    3020            0 :         let load_in_az = {
    3021            0 :             let locked = self.inner.read().unwrap();
    3022            0 :             let existing = locked
    3023            0 :                 .tenants
    3024            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    3025            0 :                 .next();
    3026              : 
    3027              :             // If the tenant is not present in memory, we expect to load it from database,
    3028              :             // so let's figure out what AZ to load it into while we have self.inner locked.
    3029            0 :             if existing.is_none() {
    3030            0 :                 locked
    3031            0 :                     .scheduler
    3032            0 :                     .get_az_for_new_tenant()
    3033            0 :                     .ok_or(ApiError::BadRequest(anyhow::anyhow!(
    3034            0 :                         "No AZ with nodes found to load tenant"
    3035            0 :                     )))?
    3036              :             } else {
    3037              :                 // We already have this tenant in memory
    3038            0 :                 return Ok(());
    3039              :             }
    3040              :         };
    3041              : 
    3042            0 :         let tenant_shards = self.persistence.load_tenant(tenant_id).await?;
    3043            0 :         if tenant_shards.is_empty() {
    3044            0 :             return Err(ApiError::NotFound(
    3045            0 :                 anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    3046            0 :             ));
    3047            0 :         }
    3048              : 
    3049              :         // Update the persistent shards with the AZ that we are about to apply to in-memory state
    3050            0 :         self.persistence
    3051            0 :             .set_tenant_shard_preferred_azs(
    3052            0 :                 tenant_shards
    3053            0 :                     .iter()
    3054            0 :                     .map(|t| {
    3055            0 :                         (
    3056            0 :                             t.get_tenant_shard_id().expect("Corrupt shard in database"),
    3057            0 :                             Some(load_in_az.clone()),
    3058            0 :                         )
    3059            0 :                     })
    3060            0 :                     .collect(),
    3061              :             )
    3062            0 :             .await?;
    3063              : 
    3064            0 :         let mut locked = self.inner.write().unwrap();
    3065            0 :         tracing::info!(
    3066            0 :             "Loaded {} shards for tenant {}",
    3067            0 :             tenant_shards.len(),
    3068              :             tenant_id
    3069              :         );
    3070              : 
    3071            0 :         locked.tenants.extend(tenant_shards.into_iter().map(|p| {
    3072            0 :             let intent = IntentState::new(Some(load_in_az.clone()));
    3073            0 :             let shard =
    3074            0 :                 TenantShard::from_persistent(p, intent).expect("Corrupt shard row in database");
    3075              : 
    3076              :             // Sanity check: when loading on-demand, we should always be loaded something Detached
    3077            0 :             debug_assert!(shard.policy == PlacementPolicy::Detached);
    3078            0 :             if shard.policy != PlacementPolicy::Detached {
    3079            0 :                 tracing::error!(
    3080            0 :                     "Tenant shard {} loaded on-demand, but has non-Detached policy {:?}",
    3081              :                     shard.tenant_shard_id,
    3082              :                     shard.policy
    3083              :                 );
    3084            0 :             }
    3085              : 
    3086            0 :             (shard.tenant_shard_id, shard)
    3087            0 :         }));
    3088              : 
    3089            0 :         Ok(())
    3090            0 :     }
    3091              : 
    3092              :     /// If all shards for a tenant are detached, and in a fully quiescent state (no observed locations on pageservers),
    3093              :     /// and have no reconciler running, then we can drop the tenant from memory.  It will be reloaded on-demand
    3094              :     /// if we are asked to attach it again (see [`Self::maybe_load_tenant`]).
    3095              :     ///
    3096              :     /// Caller must demonstrate they hold a lock guard, as otherwise it is unsafe to drop a tenant from
    3097              :     /// memory while some other function might assume it continues to exist while not holding the lock on Self::inner.
    3098            0 :     fn maybe_drop_tenant(
    3099            0 :         &self,
    3100            0 :         tenant_id: TenantId,
    3101            0 :         locked: &mut std::sync::RwLockWriteGuard<ServiceState>,
    3102            0 :         _guard: &TracingExclusiveGuard<TenantOperations>,
    3103            0 :     ) {
    3104            0 :         let mut tenant_shards = locked.tenants.range(TenantShardId::tenant_range(tenant_id));
    3105            0 :         if tenant_shards.all(|(_id, shard)| {
    3106            0 :             shard.policy == PlacementPolicy::Detached
    3107            0 :                 && shard.reconciler.is_none()
    3108            0 :                 && shard.observed.is_empty()
    3109            0 :         }) {
    3110            0 :             let keys = locked
    3111            0 :                 .tenants
    3112            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    3113            0 :                 .map(|(id, _)| id)
    3114            0 :                 .copied()
    3115            0 :                 .collect::<Vec<_>>();
    3116            0 :             for key in keys {
    3117            0 :                 tracing::info!("Dropping detached tenant shard {} from memory", key);
    3118            0 :                 locked.tenants.remove(&key);
    3119              :             }
    3120            0 :         }
    3121            0 :     }
    3122              : 
    3123              :     /// This API is used by the cloud control plane to migrate unsharded tenants that it created
    3124              :     /// directly with pageservers into this service.
    3125              :     ///
    3126              :     /// Cloud control plane MUST NOT continue issuing GENERATION NUMBERS for this tenant once it
    3127              :     /// has attempted to call this API. Failure to oblige to this rule may lead to S3 corruption.
    3128              :     /// Think of the first attempt to call this API as a transfer of absolute authority over the
    3129              :     /// tenant's source of generation numbers.
    3130              :     ///
    3131              :     /// The mode in this request coarse-grained control of tenants:
    3132              :     /// - Call with mode Attached* to upsert the tenant.
    3133              :     /// - Call with mode Secondary to either onboard a tenant without attaching it, or
    3134              :     ///   to set an existing tenant to PolicyMode::Secondary
    3135              :     /// - Call with mode Detached to switch to PolicyMode::Detached
    3136            0 :     pub(crate) async fn tenant_location_config(
    3137            0 :         &self,
    3138            0 :         tenant_shard_id: TenantShardId,
    3139            0 :         req: TenantLocationConfigRequest,
    3140            0 :     ) -> Result<TenantLocationConfigResponse, ApiError> {
    3141              :         // We require an exclusive lock, because we are updating both persistent and in-memory state
    3142            0 :         let _tenant_lock = trace_exclusive_lock(
    3143            0 :             &self.tenant_op_locks,
    3144            0 :             tenant_shard_id.tenant_id,
    3145            0 :             TenantOperations::LocationConfig,
    3146            0 :         )
    3147            0 :         .await;
    3148              : 
    3149            0 :         let tenant_id = if !tenant_shard_id.is_unsharded() {
    3150            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!(
    3151            0 :                 "This API is for importing single-sharded or unsharded tenants"
    3152            0 :             )));
    3153              :         } else {
    3154            0 :             tenant_shard_id.tenant_id
    3155              :         };
    3156              : 
    3157              :         // In case we are waking up a Detached tenant
    3158            0 :         match self.maybe_load_tenant(tenant_id, &_tenant_lock).await {
    3159            0 :             Ok(()) | Err(ApiError::NotFound(_)) => {
    3160            0 :                 // This is a creation or an update
    3161            0 :             }
    3162            0 :             Err(e) => {
    3163            0 :                 return Err(e);
    3164              :             }
    3165              :         };
    3166              : 
    3167              :         // First check if this is a creation or an update
    3168            0 :         let create_or_update = self.tenant_location_config_prepare(tenant_id, req);
    3169              : 
    3170            0 :         let mut result = TenantLocationConfigResponse {
    3171            0 :             shards: Vec::new(),
    3172            0 :             stripe_size: None,
    3173            0 :         };
    3174            0 :         let waiters = match create_or_update {
    3175            0 :             TenantCreateOrUpdate::Create(create_req) => {
    3176            0 :                 let (create_resp, waiters) = self.do_tenant_create(create_req).await?;
    3177            0 :                 result.shards = create_resp
    3178            0 :                     .shards
    3179            0 :                     .into_iter()
    3180            0 :                     .map(|s| TenantShardLocation {
    3181            0 :                         node_id: s.node_id,
    3182            0 :                         shard_id: s.shard_id,
    3183            0 :                     })
    3184            0 :                     .collect();
    3185            0 :                 waiters
    3186              :             }
    3187            0 :             TenantCreateOrUpdate::Update(updates) => {
    3188              :                 // Persist updates
    3189              :                 // Ordering: write to the database before applying changes in-memory, so that
    3190              :                 // we will not appear time-travel backwards on a restart.
    3191              : 
    3192            0 :                 let mut schedule_context = ScheduleContext::default();
    3193              :                 for ShardUpdate {
    3194            0 :                     tenant_shard_id,
    3195            0 :                     placement_policy,
    3196            0 :                     tenant_config,
    3197            0 :                     generation,
    3198            0 :                     scheduling_policy,
    3199            0 :                 } in &updates
    3200              :                 {
    3201            0 :                     self.persistence
    3202            0 :                         .update_tenant_shard(
    3203            0 :                             TenantFilter::Shard(*tenant_shard_id),
    3204            0 :                             Some(placement_policy.clone()),
    3205            0 :                             Some(tenant_config.clone()),
    3206            0 :                             *generation,
    3207            0 :                             *scheduling_policy,
    3208            0 :                         )
    3209            0 :                         .await?;
    3210              :                 }
    3211              : 
    3212              :                 // Apply updates in-memory
    3213            0 :                 let mut waiters = Vec::new();
    3214              :                 {
    3215            0 :                     let mut locked = self.inner.write().unwrap();
    3216            0 :                     let (nodes, tenants, scheduler) = locked.parts_mut();
    3217              : 
    3218              :                     for ShardUpdate {
    3219            0 :                         tenant_shard_id,
    3220            0 :                         placement_policy,
    3221            0 :                         tenant_config,
    3222            0 :                         generation: update_generation,
    3223            0 :                         scheduling_policy,
    3224            0 :                     } in updates
    3225              :                     {
    3226            0 :                         let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    3227            0 :                             tracing::warn!("Shard {tenant_shard_id} removed while updating");
    3228            0 :                             continue;
    3229              :                         };
    3230              : 
    3231              :                         // Update stripe size
    3232            0 :                         if result.stripe_size.is_none() && shard.shard.count.count() > 1 {
    3233            0 :                             result.stripe_size = Some(shard.shard.stripe_size);
    3234            0 :                         }
    3235              : 
    3236            0 :                         shard.policy = placement_policy;
    3237            0 :                         shard.config = tenant_config;
    3238            0 :                         if let Some(generation) = update_generation {
    3239            0 :                             shard.generation = Some(generation);
    3240            0 :                         }
    3241              : 
    3242            0 :                         if let Some(scheduling_policy) = scheduling_policy {
    3243            0 :                             shard.set_scheduling_policy(scheduling_policy);
    3244            0 :                         }
    3245              : 
    3246            0 :                         shard.schedule(scheduler, &mut schedule_context)?;
    3247              : 
    3248            0 :                         let maybe_waiter =
    3249            0 :                             self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
    3250            0 :                         if let Some(waiter) = maybe_waiter {
    3251            0 :                             waiters.push(waiter);
    3252            0 :                         }
    3253              : 
    3254            0 :                         if let Some(node_id) = shard.intent.get_attached() {
    3255            0 :                             result.shards.push(TenantShardLocation {
    3256            0 :                                 shard_id: tenant_shard_id,
    3257            0 :                                 node_id: *node_id,
    3258            0 :                             })
    3259            0 :                         }
    3260              :                     }
    3261              :                 }
    3262            0 :                 waiters
    3263              :             }
    3264              :         };
    3265              : 
    3266            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    3267              :             // Do not treat a reconcile error as fatal: we have already applied any requested
    3268              :             // Intent changes, and the reconcile can fail for external reasons like unavailable
    3269              :             // compute notification API.  In these cases, it is important that we do not
    3270              :             // cause the cloud control plane to retry forever on this API.
    3271            0 :             tracing::warn!(
    3272            0 :                 "Failed to reconcile after /location_config: {e}, returning success anyway"
    3273              :             );
    3274            0 :         }
    3275              : 
    3276              :         // Logging the full result is useful because it lets us cross-check what the cloud control
    3277              :         // plane's tenant_shards table should contain.
    3278            0 :         tracing::info!("Complete, returning {result:?}");
    3279              : 
    3280            0 :         Ok(result)
    3281            0 :     }
    3282              : 
    3283            0 :     pub(crate) async fn tenant_config_patch(
    3284            0 :         &self,
    3285            0 :         req: TenantConfigPatchRequest,
    3286            0 :     ) -> Result<(), ApiError> {
    3287            0 :         let _tenant_lock = trace_exclusive_lock(
    3288            0 :             &self.tenant_op_locks,
    3289            0 :             req.tenant_id,
    3290            0 :             TenantOperations::ConfigPatch,
    3291            0 :         )
    3292            0 :         .await;
    3293              : 
    3294            0 :         let tenant_id = req.tenant_id;
    3295            0 :         let patch = req.config;
    3296              : 
    3297            0 :         self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
    3298              : 
    3299            0 :         let base = {
    3300            0 :             let locked = self.inner.read().unwrap();
    3301            0 :             let shards = locked
    3302            0 :                 .tenants
    3303            0 :                 .range(TenantShardId::tenant_range(req.tenant_id));
    3304              : 
    3305            0 :             let mut configs = shards.map(|(_sid, shard)| &shard.config).peekable();
    3306              : 
    3307            0 :             let first = match configs.peek() {
    3308            0 :                 Some(first) => (*first).clone(),
    3309              :                 None => {
    3310            0 :                     return Err(ApiError::NotFound(
    3311            0 :                         anyhow::anyhow!("Tenant {} not found", req.tenant_id).into(),
    3312            0 :                     ));
    3313              :                 }
    3314              :             };
    3315              : 
    3316            0 :             if !configs.all_equal() {
    3317            0 :                 tracing::error!("Tenant configs for {} are mismatched. ", req.tenant_id);
    3318              :                 // This can't happen because we atomically update the database records
    3319              :                 // of all shards to the new value in [`Self::set_tenant_config_and_reconcile`].
    3320            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3321            0 :                     "Tenant configs for {} are mismatched",
    3322            0 :                     req.tenant_id
    3323            0 :                 )));
    3324            0 :             }
    3325              : 
    3326            0 :             first
    3327              :         };
    3328              : 
    3329            0 :         let updated_config = base
    3330            0 :             .apply_patch(patch)
    3331            0 :             .map_err(|err| ApiError::BadRequest(anyhow::anyhow!(err)))?;
    3332            0 :         self.set_tenant_config_and_reconcile(tenant_id, updated_config)
    3333            0 :             .await
    3334            0 :     }
    3335              : 
    3336            0 :     pub(crate) async fn tenant_config_set(&self, req: TenantConfigRequest) -> Result<(), ApiError> {
    3337              :         // We require an exclusive lock, because we are updating persistent and in-memory state
    3338            0 :         let _tenant_lock = trace_exclusive_lock(
    3339            0 :             &self.tenant_op_locks,
    3340            0 :             req.tenant_id,
    3341            0 :             TenantOperations::ConfigSet,
    3342            0 :         )
    3343            0 :         .await;
    3344              : 
    3345            0 :         self.maybe_load_tenant(req.tenant_id, &_tenant_lock).await?;
    3346              : 
    3347            0 :         self.set_tenant_config_and_reconcile(req.tenant_id, req.config)
    3348            0 :             .await
    3349            0 :     }
    3350              : 
    3351            0 :     async fn set_tenant_config_and_reconcile(
    3352            0 :         &self,
    3353            0 :         tenant_id: TenantId,
    3354            0 :         config: TenantConfig,
    3355            0 :     ) -> Result<(), ApiError> {
    3356            0 :         self.persistence
    3357            0 :             .update_tenant_shard(
    3358            0 :                 TenantFilter::Tenant(tenant_id),
    3359            0 :                 None,
    3360            0 :                 Some(config.clone()),
    3361            0 :                 None,
    3362            0 :                 None,
    3363            0 :             )
    3364            0 :             .await?;
    3365              : 
    3366            0 :         let waiters = {
    3367            0 :             let mut waiters = Vec::new();
    3368            0 :             let mut locked = self.inner.write().unwrap();
    3369            0 :             let (nodes, tenants, _scheduler) = locked.parts_mut();
    3370            0 :             for (_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    3371            0 :                 shard.config = config.clone();
    3372            0 :                 if let Some(waiter) =
    3373            0 :                     self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
    3374            0 :                 {
    3375            0 :                     waiters.push(waiter);
    3376            0 :                 }
    3377              :             }
    3378            0 :             waiters
    3379              :         };
    3380              : 
    3381            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    3382              :             // Treat this as success because we have stored the configuration.  If e.g.
    3383              :             // a node was unavailable at this time, it should not stop us accepting a
    3384              :             // configuration change.
    3385            0 :             tracing::warn!(%tenant_id, "Accepted configuration update but reconciliation failed: {e}");
    3386            0 :         }
    3387              : 
    3388            0 :         Ok(())
    3389            0 :     }
    3390              : 
    3391            0 :     pub(crate) fn tenant_config_get(
    3392            0 :         &self,
    3393            0 :         tenant_id: TenantId,
    3394            0 :     ) -> Result<HashMap<&str, serde_json::Value>, ApiError> {
    3395            0 :         let config = {
    3396            0 :             let locked = self.inner.read().unwrap();
    3397              : 
    3398            0 :             match locked
    3399            0 :                 .tenants
    3400            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    3401            0 :                 .next()
    3402              :             {
    3403            0 :                 Some((_tenant_shard_id, shard)) => shard.config.clone(),
    3404              :                 None => {
    3405            0 :                     return Err(ApiError::NotFound(
    3406            0 :                         anyhow::anyhow!("Tenant not found").into(),
    3407            0 :                     ));
    3408              :                 }
    3409              :             }
    3410              :         };
    3411              : 
    3412              :         // Unlike the pageserver, we do not have a set of global defaults: the config is
    3413              :         // entirely per-tenant.  Therefore the distinction between `tenant_specific_overrides`
    3414              :         // and `effective_config` in the response is meaningless, but we retain that syntax
    3415              :         // in order to remain compatible with the pageserver API.
    3416              : 
    3417            0 :         let response = HashMap::from([
    3418              :             (
    3419              :                 "tenant_specific_overrides",
    3420            0 :                 serde_json::to_value(&config)
    3421            0 :                     .context("serializing tenant specific overrides")
    3422            0 :                     .map_err(ApiError::InternalServerError)?,
    3423              :             ),
    3424              :             (
    3425            0 :                 "effective_config",
    3426            0 :                 serde_json::to_value(&config)
    3427            0 :                     .context("serializing effective config")
    3428            0 :                     .map_err(ApiError::InternalServerError)?,
    3429              :             ),
    3430              :         ]);
    3431              : 
    3432            0 :         Ok(response)
    3433            0 :     }
    3434              : 
    3435            0 :     pub(crate) async fn tenant_time_travel_remote_storage(
    3436            0 :         &self,
    3437            0 :         time_travel_req: &TenantTimeTravelRequest,
    3438            0 :         tenant_id: TenantId,
    3439            0 :         timestamp: Cow<'_, str>,
    3440            0 :         done_if_after: Cow<'_, str>,
    3441            0 :     ) -> Result<(), ApiError> {
    3442            0 :         let _tenant_lock = trace_exclusive_lock(
    3443            0 :             &self.tenant_op_locks,
    3444            0 :             tenant_id,
    3445            0 :             TenantOperations::TimeTravelRemoteStorage,
    3446            0 :         )
    3447            0 :         .await;
    3448              : 
    3449            0 :         let node = {
    3450            0 :             let mut locked = self.inner.write().unwrap();
    3451              :             // Just a sanity check to prevent misuse: the API expects that the tenant is fully
    3452              :             // detached everywhere, and nothing writes to S3 storage. Here, we verify that,
    3453              :             // but only at the start of the process, so it's really just to prevent operator
    3454              :             // mistakes.
    3455            0 :             for (shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
    3456            0 :                 if shard.intent.get_attached().is_some() || !shard.intent.get_secondary().is_empty()
    3457              :                 {
    3458            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3459            0 :                         "We want tenant to be attached in shard with tenant_shard_id={shard_id}"
    3460            0 :                     )));
    3461            0 :                 }
    3462            0 :                 let maybe_attached = shard
    3463            0 :                     .observed
    3464            0 :                     .locations
    3465            0 :                     .iter()
    3466            0 :                     .filter_map(|(node_id, observed_location)| {
    3467            0 :                         observed_location
    3468            0 :                             .conf
    3469            0 :                             .as_ref()
    3470            0 :                             .map(|loc| (node_id, observed_location, loc.mode))
    3471            0 :                     })
    3472            0 :                     .find(|(_, _, mode)| *mode != LocationConfigMode::Detached);
    3473            0 :                 if let Some((node_id, _observed_location, mode)) = maybe_attached {
    3474            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3475            0 :                         "We observed attached={mode:?} tenant in node_id={node_id} shard with tenant_shard_id={shard_id}"
    3476            0 :                     )));
    3477            0 :                 }
    3478              :             }
    3479            0 :             let scheduler = &mut locked.scheduler;
    3480              :             // Right now we only perform the operation on a single node without parallelization
    3481              :             // TODO fan out the operation to multiple nodes for better performance
    3482            0 :             let node_id = scheduler.any_available_node()?;
    3483            0 :             let node = locked
    3484            0 :                 .nodes
    3485            0 :                 .get(&node_id)
    3486            0 :                 .expect("Pageservers may not be deleted while lock is active");
    3487            0 :             node.clone()
    3488              :         };
    3489              : 
    3490              :         // The shard count is encoded in the remote storage's URL, so we need to handle all historically used shard counts
    3491            0 :         let mut counts = time_travel_req
    3492            0 :             .shard_counts
    3493            0 :             .iter()
    3494            0 :             .copied()
    3495            0 :             .collect::<HashSet<_>>()
    3496            0 :             .into_iter()
    3497            0 :             .collect::<Vec<_>>();
    3498            0 :         counts.sort_unstable();
    3499              : 
    3500            0 :         for count in counts {
    3501            0 :             let shard_ids = (0..count.count())
    3502            0 :                 .map(|i| TenantShardId {
    3503            0 :                     tenant_id,
    3504            0 :                     shard_number: ShardNumber(i),
    3505            0 :                     shard_count: count,
    3506            0 :                 })
    3507            0 :                 .collect::<Vec<_>>();
    3508            0 :             for tenant_shard_id in shard_ids {
    3509            0 :                 let client = PageserverClient::new(
    3510            0 :                     node.get_id(),
    3511            0 :                     self.http_client.clone(),
    3512            0 :                     node.base_url(),
    3513            0 :                     self.config.pageserver_jwt_token.as_deref(),
    3514              :                 );
    3515              : 
    3516            0 :                 tracing::info!("Doing time travel recovery for shard {tenant_shard_id}",);
    3517              : 
    3518            0 :                 client
    3519            0 :                     .tenant_time_travel_remote_storage(
    3520            0 :                         tenant_shard_id,
    3521            0 :                         &timestamp,
    3522            0 :                         &done_if_after,
    3523            0 :                     )
    3524            0 :                     .await
    3525            0 :                     .map_err(|e| {
    3526            0 :                         ApiError::InternalServerError(anyhow::anyhow!(
    3527            0 :                             "Error doing time travel recovery for shard {tenant_shard_id} on node {}: {e}",
    3528            0 :                             node
    3529            0 :                         ))
    3530            0 :                     })?;
    3531              :             }
    3532              :         }
    3533            0 :         Ok(())
    3534            0 :     }
    3535              : 
    3536            0 :     pub(crate) async fn tenant_secondary_download(
    3537            0 :         &self,
    3538            0 :         tenant_id: TenantId,
    3539            0 :         wait: Option<Duration>,
    3540            0 :     ) -> Result<(StatusCode, SecondaryProgress), ApiError> {
    3541            0 :         let _tenant_lock = trace_shared_lock(
    3542            0 :             &self.tenant_op_locks,
    3543            0 :             tenant_id,
    3544            0 :             TenantOperations::SecondaryDownload,
    3545            0 :         )
    3546            0 :         .await;
    3547              : 
    3548              :         // Acquire lock and yield the collection of shard-node tuples which we will send requests onward to
    3549            0 :         let targets = {
    3550            0 :             let locked = self.inner.read().unwrap();
    3551            0 :             let mut targets = Vec::new();
    3552              : 
    3553            0 :             for (tenant_shard_id, shard) in
    3554            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    3555              :             {
    3556            0 :                 for node_id in shard.intent.get_secondary() {
    3557            0 :                     let node = locked
    3558            0 :                         .nodes
    3559            0 :                         .get(node_id)
    3560            0 :                         .expect("Pageservers may not be deleted while referenced");
    3561            0 : 
    3562            0 :                     targets.push((*tenant_shard_id, node.clone()));
    3563            0 :                 }
    3564              :             }
    3565            0 :             targets
    3566              :         };
    3567              : 
    3568              :         // Issue concurrent requests to all shards' locations
    3569            0 :         let mut futs = FuturesUnordered::new();
    3570            0 :         for (tenant_shard_id, node) in targets {
    3571            0 :             let client = PageserverClient::new(
    3572            0 :                 node.get_id(),
    3573            0 :                 self.http_client.clone(),
    3574            0 :                 node.base_url(),
    3575            0 :                 self.config.pageserver_jwt_token.as_deref(),
    3576              :             );
    3577            0 :             futs.push(async move {
    3578            0 :                 let result = client
    3579            0 :                     .tenant_secondary_download(tenant_shard_id, wait)
    3580            0 :                     .await;
    3581            0 :                 (result, node, tenant_shard_id)
    3582            0 :             })
    3583              :         }
    3584              : 
    3585              :         // Handle any errors returned by pageservers.  This includes cases like this request racing with
    3586              :         // a scheduling operation, such that the tenant shard we're calling doesn't exist on that pageserver any more, as
    3587              :         // well as more general cases like 503s, 500s, or timeouts.
    3588            0 :         let mut aggregate_progress = SecondaryProgress::default();
    3589            0 :         let mut aggregate_status: Option<StatusCode> = None;
    3590            0 :         let mut error: Option<mgmt_api::Error> = None;
    3591            0 :         while let Some((result, node, tenant_shard_id)) = futs.next().await {
    3592            0 :             match result {
    3593            0 :                 Err(e) => {
    3594              :                     // Secondary downloads are always advisory: if something fails, we nevertheless report success, so that whoever
    3595              :                     // is calling us will proceed with whatever migration they're doing, albeit with a slightly less warm cache
    3596              :                     // than they had hoped for.
    3597            0 :                     tracing::warn!("Secondary download error from pageserver {node}: {e}",);
    3598            0 :                     error = Some(e)
    3599              :                 }
    3600            0 :                 Ok((status_code, progress)) => {
    3601            0 :                     tracing::info!(%tenant_shard_id, "Shard status={status_code} progress: {progress:?}");
    3602            0 :                     aggregate_progress.layers_downloaded += progress.layers_downloaded;
    3603            0 :                     aggregate_progress.layers_total += progress.layers_total;
    3604            0 :                     aggregate_progress.bytes_downloaded += progress.bytes_downloaded;
    3605            0 :                     aggregate_progress.bytes_total += progress.bytes_total;
    3606            0 :                     aggregate_progress.heatmap_mtime =
    3607            0 :                         std::cmp::max(aggregate_progress.heatmap_mtime, progress.heatmap_mtime);
    3608            0 :                     aggregate_status = match aggregate_status {
    3609            0 :                         None => Some(status_code),
    3610            0 :                         Some(StatusCode::OK) => Some(status_code),
    3611            0 :                         Some(cur) => {
    3612              :                             // Other status codes (e.g. 202) -- do not overwrite.
    3613            0 :                             Some(cur)
    3614              :                         }
    3615              :                     };
    3616              :                 }
    3617              :             }
    3618              :         }
    3619              : 
    3620              :         // If any of the shards return 202, indicate our result as 202.
    3621            0 :         match aggregate_status {
    3622              :             None => {
    3623            0 :                 match error {
    3624            0 :                     Some(e) => {
    3625              :                         // No successes, and an error: surface it
    3626            0 :                         Err(ApiError::Conflict(format!("Error from pageserver: {e}")))
    3627              :                     }
    3628              :                     None => {
    3629              :                         // No shards found
    3630            0 :                         Err(ApiError::NotFound(
    3631            0 :                             anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    3632            0 :                         ))
    3633              :                     }
    3634              :                 }
    3635              :             }
    3636            0 :             Some(aggregate_status) => Ok((aggregate_status, aggregate_progress)),
    3637              :         }
    3638            0 :     }
    3639              : 
    3640            0 :     pub(crate) async fn tenant_delete(
    3641            0 :         self: &Arc<Self>,
    3642            0 :         tenant_id: TenantId,
    3643            0 :     ) -> Result<StatusCode, ApiError> {
    3644            0 :         let _tenant_lock =
    3645            0 :             trace_exclusive_lock(&self.tenant_op_locks, tenant_id, TenantOperations::Delete).await;
    3646              : 
    3647            0 :         self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
    3648              : 
    3649              :         // Detach all shards. This also deletes local pageserver shard data.
    3650            0 :         let (detach_waiters, node) = {
    3651            0 :             let mut detach_waiters = Vec::new();
    3652            0 :             let mut locked = self.inner.write().unwrap();
    3653            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3654            0 :             for (_, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    3655              :                 // Update the tenant's intent to remove all attachments
    3656            0 :                 shard.policy = PlacementPolicy::Detached;
    3657            0 :                 shard
    3658            0 :                     .schedule(scheduler, &mut ScheduleContext::default())
    3659            0 :                     .expect("De-scheduling is infallible");
    3660            0 :                 debug_assert!(shard.intent.get_attached().is_none());
    3661            0 :                 debug_assert!(shard.intent.get_secondary().is_empty());
    3662              : 
    3663            0 :                 if let Some(waiter) =
    3664            0 :                     self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
    3665            0 :                 {
    3666            0 :                     detach_waiters.push(waiter);
    3667            0 :                 }
    3668              :             }
    3669              : 
    3670              :             // Pick an arbitrary node to use for remote deletions (does not have to be where the tenant
    3671              :             // was attached, just has to be able to see the S3 content)
    3672            0 :             let node_id = scheduler.any_available_node()?;
    3673            0 :             let node = nodes
    3674            0 :                 .get(&node_id)
    3675            0 :                 .expect("Pageservers may not be deleted while lock is active");
    3676            0 :             (detach_waiters, node.clone())
    3677              :         };
    3678              : 
    3679              :         // This reconcile wait can fail in a few ways:
    3680              :         //  A there is a very long queue for the reconciler semaphore
    3681              :         //  B some pageserver is failing to handle a detach promptly
    3682              :         //  C some pageserver goes offline right at the moment we send it a request.
    3683              :         //
    3684              :         // A and C are transient: the semaphore will eventually become available, and once a node is marked offline
    3685              :         // the next attempt to reconcile will silently skip detaches for an offline node and succeed.  If B happens,
    3686              :         // it's a bug, and needs resolving at the pageserver level (we shouldn't just leave attachments behind while
    3687              :         // deleting the underlying data).
    3688            0 :         self.await_waiters(detach_waiters, RECONCILE_TIMEOUT)
    3689            0 :             .await?;
    3690              : 
    3691              :         // Delete the entire tenant (all shards) from remote storage via a random pageserver.
    3692              :         // Passing an unsharded tenant ID will cause the pageserver to remove all remote paths with
    3693              :         // the tenant ID prefix, including all shards (even possibly stale ones).
    3694            0 :         match node
    3695            0 :             .with_client_retries(
    3696            0 :                 |client| async move {
    3697            0 :                     client
    3698            0 :                         .tenant_delete(TenantShardId::unsharded(tenant_id))
    3699            0 :                         .await
    3700            0 :                 },
    3701            0 :                 &self.http_client,
    3702            0 :                 &self.config.pageserver_jwt_token,
    3703              :                 1,
    3704              :                 3,
    3705              :                 RECONCILE_TIMEOUT,
    3706            0 :                 &self.cancel,
    3707              :             )
    3708            0 :             .await
    3709            0 :             .unwrap_or(Err(mgmt_api::Error::Cancelled))
    3710              :         {
    3711            0 :             Ok(_) => {}
    3712              :             Err(mgmt_api::Error::Cancelled) => {
    3713            0 :                 return Err(ApiError::ShuttingDown);
    3714              :             }
    3715            0 :             Err(e) => {
    3716              :                 // This is unexpected: remote deletion should be infallible, unless the object store
    3717              :                 // at large is unavailable.
    3718            0 :                 tracing::error!("Error deleting via node {node}: {e}");
    3719            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
    3720              :             }
    3721              :         }
    3722              : 
    3723              :         // Fall through: deletion of the tenant on pageservers is complete, we may proceed to drop
    3724              :         // our in-memory state and database state.
    3725              : 
    3726              :         // Ordering: we delete persistent state first: if we then
    3727              :         // crash, we will drop the in-memory state.
    3728              : 
    3729              :         // Drop persistent state.
    3730            0 :         self.persistence.delete_tenant(tenant_id).await?;
    3731              : 
    3732              :         // Drop in-memory state
    3733              :         {
    3734            0 :             let mut locked = self.inner.write().unwrap();
    3735            0 :             let (_nodes, tenants, scheduler) = locked.parts_mut();
    3736              : 
    3737              :             // Dereference Scheduler from shards before dropping them
    3738            0 :             for (_tenant_shard_id, shard) in
    3739            0 :                 tenants.range_mut(TenantShardId::tenant_range(tenant_id))
    3740            0 :             {
    3741            0 :                 shard.intent.clear(scheduler);
    3742            0 :             }
    3743              : 
    3744            0 :             tenants.retain(|tenant_shard_id, _shard| tenant_shard_id.tenant_id != tenant_id);
    3745            0 :             tracing::info!(
    3746            0 :                 "Deleted tenant {tenant_id}, now have {} tenants",
    3747            0 :                 locked.tenants.len()
    3748              :             );
    3749              :         };
    3750              : 
    3751              :         // Delete the tenant from safekeepers (if needed)
    3752            0 :         self.tenant_delete_safekeepers(tenant_id)
    3753            0 :             .instrument(tracing::info_span!("tenant_delete_safekeepers", %tenant_id))
    3754            0 :             .await?;
    3755              : 
    3756              :         // Success is represented as 404, to imitate the existing pageserver deletion API
    3757            0 :         Ok(StatusCode::NOT_FOUND)
    3758            0 :     }
    3759              : 
    3760              :     /// Naming: this configures the storage controller's policies for a tenant, whereas [`Self::tenant_config_set`] is "set the TenantConfig"
    3761              :     /// for a tenant.  The TenantConfig is passed through to pageservers, whereas this function modifies
    3762              :     /// the tenant's policies (configuration) within the storage controller
    3763            0 :     pub(crate) async fn tenant_update_policy(
    3764            0 :         &self,
    3765            0 :         tenant_id: TenantId,
    3766            0 :         req: TenantPolicyRequest,
    3767            0 :     ) -> Result<(), ApiError> {
    3768              :         // We require an exclusive lock, because we are updating persistent and in-memory state
    3769            0 :         let _tenant_lock = trace_exclusive_lock(
    3770            0 :             &self.tenant_op_locks,
    3771            0 :             tenant_id,
    3772            0 :             TenantOperations::UpdatePolicy,
    3773            0 :         )
    3774            0 :         .await;
    3775              : 
    3776            0 :         self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
    3777              : 
    3778            0 :         failpoint_support::sleep_millis_async!("tenant-update-policy-exclusive-lock");
    3779              : 
    3780              :         let TenantPolicyRequest {
    3781            0 :             placement,
    3782            0 :             mut scheduling,
    3783            0 :         } = req;
    3784              : 
    3785            0 :         if let Some(PlacementPolicy::Detached | PlacementPolicy::Secondary) = placement {
    3786              :             // When someone configures a tenant to detach, we force the scheduling policy to enable
    3787              :             // this to take effect.
    3788            0 :             if scheduling.is_none() {
    3789            0 :                 scheduling = Some(ShardSchedulingPolicy::Active);
    3790            0 :             }
    3791            0 :         }
    3792              : 
    3793            0 :         self.persistence
    3794            0 :             .update_tenant_shard(
    3795            0 :                 TenantFilter::Tenant(tenant_id),
    3796            0 :                 placement.clone(),
    3797            0 :                 None,
    3798            0 :                 None,
    3799            0 :                 scheduling,
    3800            0 :             )
    3801            0 :             .await?;
    3802              : 
    3803            0 :         let mut schedule_context = ScheduleContext::default();
    3804            0 :         let mut locked = self.inner.write().unwrap();
    3805            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    3806            0 :         for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    3807            0 :             if let Some(placement) = &placement {
    3808            0 :                 shard.policy = placement.clone();
    3809              : 
    3810            0 :                 tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
    3811            0 :                                "Updated placement policy to {placement:?}");
    3812            0 :             }
    3813              : 
    3814            0 :             if let Some(scheduling) = &scheduling {
    3815            0 :                 shard.set_scheduling_policy(*scheduling);
    3816              : 
    3817            0 :                 tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
    3818            0 :                                "Updated scheduling policy to {scheduling:?}");
    3819            0 :             }
    3820              : 
    3821              :             // In case scheduling is being switched back on, try it now.
    3822            0 :             shard.schedule(scheduler, &mut schedule_context).ok();
    3823            0 :             self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
    3824              :         }
    3825              : 
    3826            0 :         Ok(())
    3827            0 :     }
    3828              : 
    3829            0 :     pub(crate) async fn tenant_timeline_create_pageservers(
    3830            0 :         &self,
    3831            0 :         tenant_id: TenantId,
    3832            0 :         mut create_req: TimelineCreateRequest,
    3833            0 :     ) -> Result<TimelineInfo, ApiError> {
    3834            0 :         tracing::info!(
    3835            0 :             "Creating timeline {}/{}",
    3836              :             tenant_id,
    3837              :             create_req.new_timeline_id,
    3838              :         );
    3839              : 
    3840            0 :         self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
    3841            0 :             if targets.0.is_empty() {
    3842            0 :                 return Err(ApiError::NotFound(
    3843            0 :                     anyhow::anyhow!("Tenant not found").into(),
    3844            0 :                 ));
    3845            0 :             };
    3846              : 
    3847            0 :             let (shard_zero_tid, shard_zero_locations) =
    3848            0 :                 targets.0.pop_first().expect("Must have at least one shard");
    3849            0 :             assert!(shard_zero_tid.is_shard_zero());
    3850              : 
    3851            0 :             async fn create_one(
    3852            0 :                 tenant_shard_id: TenantShardId,
    3853            0 :                 locations: ShardMutationLocations,
    3854            0 :                 http_client: reqwest::Client,
    3855            0 :                 jwt: Option<String>,
    3856            0 :                 mut create_req: TimelineCreateRequest,
    3857            0 :             ) -> Result<TimelineInfo, ApiError> {
    3858            0 :                 let latest = locations.latest.node;
    3859              : 
    3860            0 :                 tracing::info!(
    3861            0 :                     "Creating timeline on shard {}/{}, attached to node {latest} in generation {:?}",
    3862              :                     tenant_shard_id,
    3863              :                     create_req.new_timeline_id,
    3864              :                     locations.latest.generation
    3865              :                 );
    3866              : 
    3867            0 :                 let client =
    3868            0 :                     PageserverClient::new(latest.get_id(), http_client.clone(), latest.base_url(), jwt.as_deref());
    3869              : 
    3870            0 :                 let timeline_info = client
    3871            0 :                     .timeline_create(tenant_shard_id, &create_req)
    3872            0 :                     .await
    3873            0 :                     .map_err(|e| passthrough_api_error(&latest, e))?;
    3874              : 
    3875              :                 // If we are going to create the timeline on some stale locations for shard 0, then ask them to re-use
    3876              :                 // the initdb generated by the latest location, rather than generating their own.  This avoids racing uploads
    3877              :                 // of initdb to S3 which might not be binary-identical if different pageservers have different postgres binaries.
    3878            0 :                 if tenant_shard_id.is_shard_zero() {
    3879            0 :                     if let models::TimelineCreateRequestMode::Bootstrap { existing_initdb_timeline_id, .. } = &mut create_req.mode {
    3880            0 :                         *existing_initdb_timeline_id = Some(create_req.new_timeline_id);
    3881            0 :                     }
    3882            0 :                 }
    3883              : 
    3884              :                 // We propagate timeline creations to all attached locations such that a compute
    3885              :                 // for the new timeline is able to start regardless of the current state of the
    3886              :                 // tenant shard reconciliation.
    3887            0 :                 for location in locations.other {
    3888            0 :                     tracing::info!(
    3889            0 :                         "Creating timeline on shard {}/{}, stale attached to node {} in generation {:?}",
    3890              :                         tenant_shard_id,
    3891              :                         create_req.new_timeline_id,
    3892              :                         location.node,
    3893              :                         location.generation
    3894              :                     );
    3895              : 
    3896            0 :                     let client = PageserverClient::new(
    3897            0 :                         location.node.get_id(),
    3898            0 :                         http_client.clone(),
    3899            0 :                         location.node.base_url(),
    3900            0 :                         jwt.as_deref(),
    3901              :                     );
    3902              : 
    3903            0 :                     let res = client
    3904            0 :                         .timeline_create(tenant_shard_id, &create_req)
    3905            0 :                         .await;
    3906              : 
    3907            0 :                     if let Err(e) = res {
    3908            0 :                         match e {
    3909            0 :                             mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _) => {
    3910            0 :                                 // Tenant might have been detached from the stale location,
    3911            0 :                                 // so ignore 404s.
    3912            0 :                             },
    3913              :                             _ => {
    3914            0 :                                 return Err(passthrough_api_error(&location.node, e));
    3915              :                             }
    3916              :                         }
    3917            0 :                     }
    3918              :                 }
    3919              : 
    3920            0 :                 Ok(timeline_info)
    3921            0 :             }
    3922              : 
    3923              :             // Because the caller might not provide an explicit LSN, we must do the creation first on a single shard, and then
    3924              :             // use whatever LSN that shard picked when creating on subsequent shards.  We arbitrarily use shard zero as the shard
    3925              :             // that will get the first creation request, and propagate the LSN to all the >0 shards.
    3926              :             //
    3927              :             // This also enables non-zero shards to use the initdb that shard 0 generated and uploaded to S3, rather than
    3928              :             // independently generating their own initdb.  This guarantees that shards cannot end up with different initial
    3929              :             // states if e.g. they have different postgres binary versions.
    3930            0 :             let timeline_info = create_one(
    3931            0 :                 shard_zero_tid,
    3932            0 :                 shard_zero_locations,
    3933            0 :                 self.http_client.clone(),
    3934            0 :                 self.config.pageserver_jwt_token.clone(),
    3935            0 :                 create_req.clone(),
    3936            0 :             )
    3937            0 :             .await?;
    3938              : 
    3939              :             // Update the create request for shards >= 0
    3940            0 :             match &mut create_req.mode {
    3941            0 :                 models::TimelineCreateRequestMode::Branch { ancestor_start_lsn, .. } if ancestor_start_lsn.is_none() => {
    3942            0 :                     // Propagate the LSN that shard zero picked, if caller didn't provide one
    3943            0 :                     *ancestor_start_lsn = timeline_info.ancestor_lsn;
    3944            0 :                 },
    3945            0 :                 models::TimelineCreateRequestMode::Bootstrap { existing_initdb_timeline_id, .. } => {
    3946              :                     // For shards >= 0, do not run initdb: use the one that shard 0 uploaded to S3
    3947            0 :                     *existing_initdb_timeline_id = Some(create_req.new_timeline_id)
    3948              :                 }
    3949            0 :                 _ => {}
    3950              :             }
    3951              : 
    3952              :             // Create timeline on remaining shards with number >0
    3953            0 :             if !targets.0.is_empty() {
    3954              :                 // If we had multiple shards, issue requests for the remainder now.
    3955            0 :                 let jwt = &self.config.pageserver_jwt_token;
    3956            0 :                 self.tenant_for_shards(
    3957            0 :                     targets
    3958            0 :                         .0
    3959            0 :                         .iter()
    3960            0 :                         .map(|t| (*t.0, t.1.latest.node.clone()))
    3961            0 :                         .collect(),
    3962            0 :                     |tenant_shard_id: TenantShardId, _node: Node| {
    3963            0 :                         let create_req = create_req.clone();
    3964            0 :                         let mutation_locations = targets.0.remove(&tenant_shard_id).unwrap();
    3965            0 :                         Box::pin(create_one(
    3966            0 :                             tenant_shard_id,
    3967            0 :                             mutation_locations,
    3968            0 :                             self.http_client.clone(),
    3969            0 :                             jwt.clone(),
    3970            0 :                             create_req,
    3971            0 :                         ))
    3972            0 :                     },
    3973              :                 )
    3974            0 :                 .await?;
    3975            0 :             }
    3976              : 
    3977            0 :             Ok(timeline_info)
    3978            0 :         })
    3979            0 :         .await?
    3980            0 :     }
    3981              : 
    3982            0 :     pub(crate) async fn tenant_timeline_create(
    3983            0 :         self: &Arc<Self>,
    3984            0 :         tenant_id: TenantId,
    3985            0 :         create_req: TimelineCreateRequest,
    3986            0 :     ) -> Result<TimelineCreateResponseStorcon, ApiError> {
    3987            0 :         let safekeepers = self.config.timelines_onto_safekeepers;
    3988            0 :         let timeline_id = create_req.new_timeline_id;
    3989              : 
    3990            0 :         tracing::info!(
    3991            0 :             mode=%create_req.mode_tag(),
    3992              :             %safekeepers,
    3993            0 :             "Creating timeline {}/{}",
    3994              :             tenant_id,
    3995              :             timeline_id,
    3996              :         );
    3997              : 
    3998            0 :         let _tenant_lock = trace_shared_lock(
    3999            0 :             &self.tenant_op_locks,
    4000            0 :             tenant_id,
    4001            0 :             TenantOperations::TimelineCreate,
    4002            0 :         )
    4003            0 :         .await;
    4004            0 :         failpoint_support::sleep_millis_async!("tenant-create-timeline-shared-lock");
    4005            0 :         let is_import = create_req.is_import();
    4006            0 :         let read_only = matches!(
    4007            0 :             create_req.mode,
    4008              :             models::TimelineCreateRequestMode::Branch {
    4009              :                 read_only: true,
    4010              :                 ..
    4011              :             }
    4012              :         );
    4013              : 
    4014            0 :         if is_import {
    4015              :             // Ensure that there is no split on-going.
    4016              :             // [`Self::tenant_shard_split`] holds the exclusive tenant lock
    4017              :             // for the duration of the split, but here we handle the case
    4018              :             // where we restarted and the split is being aborted.
    4019            0 :             let locked = self.inner.read().unwrap();
    4020            0 :             let splitting = locked
    4021            0 :                 .tenants
    4022            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    4023            0 :                 .any(|(_id, shard)| shard.splitting != SplitState::Idle);
    4024              : 
    4025            0 :             if splitting {
    4026            0 :                 return Err(ApiError::Conflict("Tenant is splitting shard".to_string()));
    4027            0 :             }
    4028            0 :         }
    4029              : 
    4030            0 :         let timeline_info = self
    4031            0 :             .tenant_timeline_create_pageservers(tenant_id, create_req)
    4032            0 :             .await?;
    4033              : 
    4034            0 :         let selected_safekeepers = if is_import {
    4035            0 :             let shards = {
    4036            0 :                 let locked = self.inner.read().unwrap();
    4037            0 :                 locked
    4038            0 :                     .tenants
    4039            0 :                     .range(TenantShardId::tenant_range(tenant_id))
    4040            0 :                     .map(|(ts_id, _)| ts_id.to_index())
    4041            0 :                     .collect::<Vec<_>>()
    4042              :             };
    4043              : 
    4044            0 :             if !shards
    4045            0 :                 .iter()
    4046            0 :                 .map(|shard_index| shard_index.shard_count)
    4047            0 :                 .all_equal()
    4048              :             {
    4049            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4050            0 :                     "Inconsistent shard count"
    4051            0 :                 )));
    4052            0 :             }
    4053              : 
    4054            0 :             let import = TimelineImport {
    4055            0 :                 tenant_id,
    4056            0 :                 timeline_id,
    4057            0 :                 shard_statuses: ShardImportStatuses::new(shards),
    4058            0 :             };
    4059              : 
    4060            0 :             let inserted = self
    4061            0 :                 .persistence
    4062            0 :                 .insert_timeline_import(import.to_persistent())
    4063            0 :                 .await
    4064            0 :                 .context("timeline import insert")
    4065            0 :                 .map_err(ApiError::InternalServerError)?;
    4066              : 
    4067              :             // Set the importing flag on the tenant shards
    4068            0 :             self.inner
    4069            0 :                 .write()
    4070            0 :                 .unwrap()
    4071            0 :                 .tenants
    4072            0 :                 .range_mut(TenantShardId::tenant_range(tenant_id))
    4073            0 :                 .for_each(|(_id, shard)| shard.importing = TimelineImportState::Importing);
    4074              : 
    4075            0 :             match inserted {
    4076              :                 true => {
    4077            0 :                     tracing::info!(%tenant_id, %timeline_id, "Inserted timeline import");
    4078              :                 }
    4079              :                 false => {
    4080            0 :                     tracing::info!(%tenant_id, %timeline_id, "Timeline import entry already present");
    4081              :                 }
    4082              :             }
    4083              : 
    4084            0 :             None
    4085            0 :         } else if safekeepers || read_only {
    4086              :             // Note that for imported timelines, we do not create the timeline on the safekeepers
    4087              :             // straight away. Instead, we do it once the import finalized such that we know what
    4088              :             // start LSN to provide for the safekeepers. This is done in
    4089              :             // [`Self::finalize_timeline_import`].
    4090            0 :             let res = self
    4091            0 :                 .tenant_timeline_create_safekeepers(tenant_id, &timeline_info, read_only)
    4092            0 :                 .instrument(tracing::info_span!("timeline_create_safekeepers", %tenant_id, timeline_id=%timeline_info.timeline_id))
    4093            0 :                 .await?;
    4094            0 :             Some(res)
    4095              :         } else {
    4096            0 :             None
    4097              :         };
    4098              : 
    4099            0 :         Ok(TimelineCreateResponseStorcon {
    4100            0 :             timeline_info,
    4101            0 :             safekeepers: selected_safekeepers,
    4102            0 :         })
    4103            0 :     }
    4104              : 
    4105              :     #[instrument(skip_all, fields(
    4106              :         tenant_id=%req.tenant_shard_id.tenant_id,
    4107              :         shard_id=%req.tenant_shard_id.shard_slug(),
    4108              :         timeline_id=%req.timeline_id,
    4109              :     ))]
    4110              :     pub(crate) async fn handle_timeline_shard_import_progress(
    4111              :         self: &Arc<Self>,
    4112              :         req: TimelineImportStatusRequest,
    4113              :     ) -> Result<ShardImportStatus, ApiError> {
    4114              :         let validity = self
    4115              :             .validate_shard_generation(req.tenant_shard_id, req.generation)
    4116              :             .await?;
    4117              :         match validity {
    4118              :             ShardGenerationValidity::Valid => {
    4119              :                 // fallthrough
    4120              :             }
    4121              :             ShardGenerationValidity::Mismatched { claimed, actual } => {
    4122              :                 tracing::info!(
    4123              :                     claimed=?claimed.into(),
    4124            0 :                     actual=?actual.and_then(|g| g.into()),
    4125              :                     "Rejecting import progress fetch from stale generation"
    4126              :                 );
    4127              : 
    4128              :                 return Err(ApiError::BadRequest(anyhow::anyhow!("Invalid generation")));
    4129              :             }
    4130              :         }
    4131              : 
    4132              :         let maybe_import = self
    4133              :             .persistence
    4134              :             .get_timeline_import(req.tenant_shard_id.tenant_id, req.timeline_id)
    4135              :             .await?;
    4136              : 
    4137            0 :         let import = maybe_import.ok_or_else(|| {
    4138            0 :             ApiError::NotFound(
    4139            0 :                 format!(
    4140            0 :                     "import for {}/{} not found",
    4141            0 :                     req.tenant_shard_id.tenant_id, req.timeline_id
    4142            0 :                 )
    4143            0 :                 .into(),
    4144            0 :             )
    4145            0 :         })?;
    4146              : 
    4147              :         import
    4148              :             .shard_statuses
    4149              :             .0
    4150              :             .get(&req.tenant_shard_id.to_index())
    4151              :             .cloned()
    4152            0 :             .ok_or_else(|| {
    4153            0 :                 ApiError::NotFound(
    4154            0 :                     format!("shard {} not found", req.tenant_shard_id.shard_slug()).into(),
    4155            0 :                 )
    4156            0 :             })
    4157              :     }
    4158              : 
    4159              :     #[instrument(skip_all, fields(
    4160              :         tenant_id=%req.tenant_shard_id.tenant_id,
    4161              :         shard_id=%req.tenant_shard_id.shard_slug(),
    4162              :         timeline_id=%req.timeline_id,
    4163              :     ))]
    4164              :     pub(crate) async fn handle_timeline_shard_import_progress_upcall(
    4165              :         self: &Arc<Self>,
    4166              :         req: PutTimelineImportStatusRequest,
    4167              :     ) -> Result<(), ApiError> {
    4168              :         let validity = self
    4169              :             .validate_shard_generation(req.tenant_shard_id, req.generation)
    4170              :             .await?;
    4171              :         match validity {
    4172              :             ShardGenerationValidity::Valid => {
    4173              :                 // fallthrough
    4174              :             }
    4175              :             ShardGenerationValidity::Mismatched { claimed, actual } => {
    4176              :                 tracing::info!(
    4177              :                     claimed=?claimed.into(),
    4178            0 :                     actual=?actual.and_then(|g| g.into()),
    4179              :                     "Rejecting import progress update from stale generation"
    4180              :                 );
    4181              : 
    4182              :                 return Err(ApiError::PreconditionFailed("Invalid generation".into()));
    4183              :             }
    4184              :         }
    4185              : 
    4186              :         let res = self
    4187              :             .persistence
    4188              :             .update_timeline_import(req.tenant_shard_id, req.timeline_id, req.status)
    4189              :             .await;
    4190              :         let timeline_import = match res {
    4191              :             Ok(Ok(Some(timeline_import))) => timeline_import,
    4192              :             Ok(Ok(None)) => {
    4193              :                 // Idempotency: we've already seen and handled this update.
    4194              :                 return Ok(());
    4195              :             }
    4196              :             Ok(Err(logical_err)) => {
    4197              :                 return Err(logical_err.into());
    4198              :             }
    4199              :             Err(db_err) => {
    4200              :                 return Err(db_err.into());
    4201              :             }
    4202              :         };
    4203              : 
    4204              :         tracing::info!(
    4205              :             tenant_id=%req.tenant_shard_id.tenant_id,
    4206              :             timeline_id=%req.timeline_id,
    4207              :             shard_id=%req.tenant_shard_id.shard_slug(),
    4208              :             "Updated timeline import status to: {timeline_import:?}");
    4209              : 
    4210              :         if timeline_import.is_complete() {
    4211              :             tokio::task::spawn({
    4212              :                 let this = self.clone();
    4213            0 :                 async move { this.finalize_timeline_import(timeline_import).await }
    4214              :             });
    4215              :         }
    4216              : 
    4217              :         Ok(())
    4218              :     }
    4219              : 
    4220              :     /// Check that a provided generation for some tenant shard is the most recent one.
    4221              :     ///
    4222              :     /// Validate with the in-mem state first, and, if that passes, validate with the
    4223              :     /// database state which is authoritative.
    4224            0 :     async fn validate_shard_generation(
    4225            0 :         self: &Arc<Self>,
    4226            0 :         tenant_shard_id: TenantShardId,
    4227            0 :         generation: Generation,
    4228            0 :     ) -> Result<ShardGenerationValidity, ApiError> {
    4229              :         {
    4230            0 :             let locked = self.inner.read().unwrap();
    4231            0 :             let tenant_shard =
    4232            0 :                 locked
    4233            0 :                     .tenants
    4234            0 :                     .get(&tenant_shard_id)
    4235            0 :                     .ok_or(ApiError::InternalServerError(anyhow::anyhow!(
    4236            0 :                         "{} shard not found",
    4237            0 :                         tenant_shard_id
    4238            0 :                     )))?;
    4239              : 
    4240            0 :             if tenant_shard.generation != Some(generation) {
    4241            0 :                 return Ok(ShardGenerationValidity::Mismatched {
    4242            0 :                     claimed: generation,
    4243            0 :                     actual: tenant_shard.generation,
    4244            0 :                 });
    4245            0 :             }
    4246              :         }
    4247              : 
    4248            0 :         let mut db_generations = self
    4249            0 :             .persistence
    4250            0 :             .shard_generations(std::iter::once(&tenant_shard_id))
    4251            0 :             .await?;
    4252            0 :         let (_tid, db_generation) =
    4253            0 :             db_generations
    4254            0 :                 .pop()
    4255            0 :                 .ok_or(ApiError::InternalServerError(anyhow::anyhow!(
    4256            0 :                     "{} shard not found",
    4257            0 :                     tenant_shard_id
    4258            0 :                 )))?;
    4259              : 
    4260            0 :         if db_generation != Some(generation) {
    4261            0 :             return Ok(ShardGenerationValidity::Mismatched {
    4262            0 :                 claimed: generation,
    4263            0 :                 actual: db_generation,
    4264            0 :             });
    4265            0 :         }
    4266              : 
    4267            0 :         Ok(ShardGenerationValidity::Valid)
    4268            0 :     }
    4269              : 
    4270              :     /// Finalize the import of a timeline
    4271              :     ///
    4272              :     /// This method should be called once all shards have reported that the import is complete.
    4273              :     /// Firstly, it polls the post import timeline activation endpoint exposed by the pageserver.
    4274              :     /// Once the timeline is active on all shards, the timeline also gets created on the
    4275              :     /// safekeepers. Finally, notify cplane of the import completion (whether failed or
    4276              :     /// successful), and remove the import from the database and in-memory.
    4277              :     ///
    4278              :     /// If this method gets pre-empted by shut down, it will be called again at start-up (on-going
    4279              :     /// imports are stored in the database).
    4280              :     ///
    4281              :     /// # Cancel-Safety
    4282              :     /// Not cancel safe.
    4283              :     /// If the caller stops polling, the import will not be removed from
    4284              :     /// [`ServiceState::imports_finalizing`].
    4285              :     #[instrument(skip_all, fields(
    4286              :         tenant_id=%import.tenant_id,
    4287              :         timeline_id=%import.timeline_id,
    4288              :     ))]
    4289              : 
    4290              :     async fn finalize_timeline_import(
    4291              :         self: &Arc<Self>,
    4292              :         import: TimelineImport,
    4293              :     ) -> Result<(), TimelineImportFinalizeError> {
    4294              :         let tenant_timeline = (import.tenant_id, import.timeline_id);
    4295              : 
    4296              :         let (_finalize_import_guard, cancel) = {
    4297              :             let mut locked = self.inner.write().unwrap();
    4298              :             let gate = Gate::default();
    4299              :             let cancel = CancellationToken::default();
    4300              : 
    4301              :             let guard = gate.enter().unwrap();
    4302              : 
    4303              :             locked.imports_finalizing.insert(
    4304              :                 tenant_timeline,
    4305              :                 FinalizingImport {
    4306              :                     gate,
    4307              :                     cancel: cancel.clone(),
    4308              :                 },
    4309              :             );
    4310              : 
    4311              :             (guard, cancel)
    4312              :         };
    4313              : 
    4314              :         let res = tokio::select! {
    4315              :             res = self.finalize_timeline_import_impl(import) => {
    4316              :                 res
    4317              :             },
    4318              :             _ = cancel.cancelled() => {
    4319              :                 Err(TimelineImportFinalizeError::Cancelled)
    4320              :             }
    4321              :         };
    4322              : 
    4323              :         let mut locked = self.inner.write().unwrap();
    4324              :         locked.imports_finalizing.remove(&tenant_timeline);
    4325              : 
    4326              :         res
    4327              :     }
    4328              : 
    4329            0 :     async fn finalize_timeline_import_impl(
    4330            0 :         self: &Arc<Self>,
    4331            0 :         import: TimelineImport,
    4332            0 :     ) -> Result<(), TimelineImportFinalizeError> {
    4333            0 :         tracing::info!("Finalizing timeline import");
    4334              : 
    4335            0 :         pausable_failpoint!("timeline-import-pre-cplane-notification");
    4336              : 
    4337            0 :         let tenant_id = import.tenant_id;
    4338            0 :         let timeline_id = import.timeline_id;
    4339              : 
    4340            0 :         let import_error = import.completion_error();
    4341            0 :         match import_error {
    4342            0 :             Some(err) => {
    4343            0 :                 self.notify_cplane_and_delete_import(tenant_id, timeline_id, Err(err))
    4344            0 :                     .await?;
    4345            0 :                 tracing::warn!("Timeline import completed with shard errors");
    4346            0 :                 Ok(())
    4347              :             }
    4348            0 :             None => match self.activate_timeline_post_import(&import).await {
    4349            0 :                 Ok(timeline_info) => {
    4350            0 :                     tracing::info!("Post import timeline activation complete");
    4351              : 
    4352            0 :                     if self.config.timelines_onto_safekeepers {
    4353              :                         // Now that we know the start LSN of this timeline, create it on the
    4354              :                         // safekeepers.
    4355            0 :                         self.tenant_timeline_create_safekeepers_until_success(
    4356            0 :                             import.tenant_id,
    4357            0 :                             timeline_info,
    4358            0 :                         )
    4359            0 :                         .await?;
    4360            0 :                     }
    4361              : 
    4362            0 :                     self.notify_cplane_and_delete_import(tenant_id, timeline_id, Ok(()))
    4363            0 :                         .await?;
    4364              : 
    4365            0 :                     tracing::info!("Timeline import completed successfully");
    4366            0 :                     Ok(())
    4367              :                 }
    4368              :                 Err(TimelineImportFinalizeError::ShuttingDown) => {
    4369              :                     // We got pre-empted by shut down and will resume after the restart.
    4370            0 :                     Err(TimelineImportFinalizeError::ShuttingDown)
    4371              :                 }
    4372            0 :                 Err(err) => {
    4373              :                     // Any finalize error apart from shut down is permanent and requires us to notify
    4374              :                     // cplane such that it can clean up.
    4375            0 :                     tracing::error!("Import finalize failed with permanent error: {err}");
    4376            0 :                     self.notify_cplane_and_delete_import(
    4377            0 :                         tenant_id,
    4378            0 :                         timeline_id,
    4379            0 :                         Err(err.to_string()),
    4380            0 :                     )
    4381            0 :                     .await?;
    4382            0 :                     Err(err)
    4383              :                 }
    4384              :             },
    4385              :         }
    4386            0 :     }
    4387              : 
    4388            0 :     async fn notify_cplane_and_delete_import(
    4389            0 :         self: &Arc<Self>,
    4390            0 :         tenant_id: TenantId,
    4391            0 :         timeline_id: TimelineId,
    4392            0 :         import_result: ImportResult,
    4393            0 :     ) -> Result<(), TimelineImportFinalizeError> {
    4394            0 :         let import_failed = import_result.is_err();
    4395            0 :         tracing::info!(%import_failed, "Notifying cplane of import completion");
    4396              : 
    4397            0 :         let client = UpcallClient::new(self.get_config(), self.cancel.child_token());
    4398            0 :         client
    4399            0 :             .notify_import_complete(tenant_id, timeline_id, import_result)
    4400            0 :             .await
    4401            0 :             .map_err(|_err| TimelineImportFinalizeError::ShuttingDown)?;
    4402              : 
    4403            0 :         if let Err(err) = self
    4404            0 :             .persistence
    4405            0 :             .delete_timeline_import(tenant_id, timeline_id)
    4406            0 :             .await
    4407              :         {
    4408            0 :             tracing::warn!("Failed to delete timeline import entry from database: {err}");
    4409            0 :         }
    4410              : 
    4411            0 :         self.inner
    4412            0 :             .write()
    4413            0 :             .unwrap()
    4414            0 :             .tenants
    4415            0 :             .range_mut(TenantShardId::tenant_range(tenant_id))
    4416            0 :             .for_each(|(_id, shard)| shard.importing = TimelineImportState::Idle);
    4417              : 
    4418            0 :         Ok(())
    4419            0 :     }
    4420              : 
    4421              :     /// Activate an imported timeline on all shards once the import is complete.
    4422              :     /// Returns the [`TimelineInfo`] reported by shard zero.
    4423            0 :     async fn activate_timeline_post_import(
    4424            0 :         self: &Arc<Self>,
    4425            0 :         import: &TimelineImport,
    4426            0 :     ) -> Result<TimelineInfo, TimelineImportFinalizeError> {
    4427              :         const TIMELINE_ACTIVATE_TIMEOUT: Duration = Duration::from_millis(128);
    4428              : 
    4429            0 :         let mut shards_to_activate: HashSet<ShardIndex> =
    4430            0 :             import.shard_statuses.0.keys().cloned().collect();
    4431            0 :         let mut shard_zero_timeline_info = None;
    4432              : 
    4433            0 :         while !shards_to_activate.is_empty() {
    4434            0 :             if self.cancel.is_cancelled() {
    4435            0 :                 return Err(TimelineImportFinalizeError::ShuttingDown);
    4436            0 :             }
    4437              : 
    4438            0 :             let targets = {
    4439            0 :                 let locked = self.inner.read().unwrap();
    4440            0 :                 let mut targets = Vec::new();
    4441              : 
    4442            0 :                 for (tenant_shard_id, shard) in locked
    4443            0 :                     .tenants
    4444            0 :                     .range(TenantShardId::tenant_range(import.tenant_id))
    4445              :                 {
    4446            0 :                     if !import
    4447            0 :                         .shard_statuses
    4448            0 :                         .0
    4449            0 :                         .contains_key(&tenant_shard_id.to_index())
    4450              :                     {
    4451            0 :                         return Err(TimelineImportFinalizeError::MismatchedShards(
    4452            0 :                             tenant_shard_id.to_index(),
    4453            0 :                         ));
    4454            0 :                     }
    4455              : 
    4456            0 :                     if let Some(node_id) = shard.intent.get_attached() {
    4457            0 :                         let node = locked
    4458            0 :                             .nodes
    4459            0 :                             .get(node_id)
    4460            0 :                             .expect("Pageservers may not be deleted while referenced");
    4461            0 :                         targets.push((*tenant_shard_id, node.clone()));
    4462            0 :                     }
    4463              :                 }
    4464              : 
    4465            0 :                 targets
    4466              :             };
    4467              : 
    4468            0 :             let targeted_tenant_shards: Vec<_> = targets.iter().map(|(tid, _node)| *tid).collect();
    4469              : 
    4470            0 :             let results = self
    4471            0 :                 .tenant_for_shards_api(
    4472            0 :                     targets,
    4473            0 :                     |tenant_shard_id, client| async move {
    4474            0 :                         client
    4475            0 :                             .activate_post_import(
    4476            0 :                                 tenant_shard_id,
    4477            0 :                                 import.timeline_id,
    4478            0 :                                 TIMELINE_ACTIVATE_TIMEOUT,
    4479            0 :                             )
    4480            0 :                             .await
    4481            0 :                     },
    4482              :                     1,
    4483              :                     1,
    4484              :                     SHORT_RECONCILE_TIMEOUT,
    4485            0 :                     &self.cancel,
    4486              :                 )
    4487            0 :                 .await;
    4488              : 
    4489            0 :             let mut failed = 0;
    4490            0 :             for (tid, (_, result)) in targeted_tenant_shards.iter().zip(results.into_iter()) {
    4491            0 :                 match result {
    4492            0 :                     Ok(ok) => {
    4493            0 :                         if tid.is_shard_zero() {
    4494            0 :                             shard_zero_timeline_info = Some(ok);
    4495            0 :                         }
    4496              : 
    4497            0 :                         shards_to_activate.remove(&tid.to_index());
    4498              :                     }
    4499            0 :                     Err(_err) => {
    4500            0 :                         failed += 1;
    4501            0 :                     }
    4502              :                 }
    4503              :             }
    4504              : 
    4505            0 :             if failed > 0 {
    4506            0 :                 tracing::info!(
    4507            0 :                     "Failed to activate timeline on {failed} shards post import. Will retry"
    4508              :                 );
    4509            0 :             }
    4510              : 
    4511            0 :             tokio::select! {
    4512            0 :                 _ = tokio::time::sleep(Duration::from_millis(250)) => {},
    4513            0 :                 _ = self.cancel.cancelled() => {
    4514            0 :                     return Err(TimelineImportFinalizeError::ShuttingDown);
    4515              :                 }
    4516              :             }
    4517              :         }
    4518              : 
    4519            0 :         Ok(shard_zero_timeline_info.expect("All shards replied"))
    4520            0 :     }
    4521              : 
    4522            0 :     async fn finalize_timeline_imports(self: &Arc<Self>, imports: Vec<TimelineImport>) {
    4523            0 :         futures::future::join_all(
    4524            0 :             imports
    4525            0 :                 .into_iter()
    4526            0 :                 .map(|import| self.finalize_timeline_import(import)),
    4527              :         )
    4528            0 :         .await;
    4529            0 :     }
    4530              : 
    4531              :     /// Delete a timeline import if it exists
    4532              :     ///
    4533              :     /// Firstly, delete the entry from the database. Any updates
    4534              :     /// from pageservers after the update will fail with a 404, so the
    4535              :     /// import cannot progress into finalizing state if it's not there already.
    4536              :     /// Secondly, cancel the finalization if one is in progress.
    4537            0 :     pub(crate) async fn maybe_delete_timeline_import(
    4538            0 :         self: &Arc<Self>,
    4539            0 :         tenant_id: TenantId,
    4540            0 :         timeline_id: TimelineId,
    4541            0 :     ) -> Result<(), DatabaseError> {
    4542            0 :         let tenant_has_ongoing_import = {
    4543            0 :             let locked = self.inner.read().unwrap();
    4544            0 :             locked
    4545            0 :                 .tenants
    4546            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    4547            0 :                 .any(|(_tid, shard)| shard.importing == TimelineImportState::Importing)
    4548              :         };
    4549              : 
    4550            0 :         if !tenant_has_ongoing_import {
    4551            0 :             return Ok(());
    4552            0 :         }
    4553              : 
    4554            0 :         self.persistence
    4555            0 :             .delete_timeline_import(tenant_id, timeline_id)
    4556            0 :             .await?;
    4557              : 
    4558            0 :         let maybe_finalizing = {
    4559            0 :             let mut locked = self.inner.write().unwrap();
    4560            0 :             locked.imports_finalizing.remove(&(tenant_id, timeline_id))
    4561              :         };
    4562              : 
    4563            0 :         if let Some(finalizing) = maybe_finalizing {
    4564            0 :             finalizing.cancel.cancel();
    4565            0 :             finalizing.gate.close().await;
    4566            0 :         }
    4567              : 
    4568            0 :         Ok(())
    4569            0 :     }
    4570              : 
    4571            0 :     pub(crate) async fn tenant_timeline_archival_config(
    4572            0 :         &self,
    4573            0 :         tenant_id: TenantId,
    4574            0 :         timeline_id: TimelineId,
    4575            0 :         req: TimelineArchivalConfigRequest,
    4576            0 :     ) -> Result<(), ApiError> {
    4577            0 :         tracing::info!(
    4578            0 :             "Setting archival config of timeline {tenant_id}/{timeline_id} to '{:?}'",
    4579              :             req.state
    4580              :         );
    4581              : 
    4582            0 :         let _tenant_lock = trace_shared_lock(
    4583            0 :             &self.tenant_op_locks,
    4584            0 :             tenant_id,
    4585            0 :             TenantOperations::TimelineArchivalConfig,
    4586            0 :         )
    4587            0 :         .await;
    4588              : 
    4589            0 :         self.tenant_remote_mutation(tenant_id, move |targets| async move {
    4590            0 :             if targets.0.is_empty() {
    4591            0 :                 return Err(ApiError::NotFound(
    4592            0 :                     anyhow::anyhow!("Tenant not found").into(),
    4593            0 :                 ));
    4594            0 :             }
    4595            0 :             async fn config_one(
    4596            0 :                 tenant_shard_id: TenantShardId,
    4597            0 :                 timeline_id: TimelineId,
    4598            0 :                 node: Node,
    4599            0 :                 http_client: reqwest::Client,
    4600            0 :                 jwt: Option<String>,
    4601            0 :                 req: TimelineArchivalConfigRequest,
    4602            0 :             ) -> Result<(), ApiError> {
    4603            0 :                 tracing::info!(
    4604            0 :                     "Setting archival config of timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
    4605              :                 );
    4606              : 
    4607            0 :                 let client = PageserverClient::new(node.get_id(),  http_client, node.base_url(), jwt.as_deref());
    4608              : 
    4609            0 :                 client
    4610            0 :                     .timeline_archival_config(tenant_shard_id, timeline_id, &req)
    4611            0 :                     .await
    4612            0 :                     .map_err(|e| match e {
    4613            0 :                         mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg) => {
    4614            0 :                             ApiError::PreconditionFailed(msg.into_boxed_str())
    4615              :                         }
    4616            0 :                         _ => passthrough_api_error(&node, e),
    4617            0 :                     })
    4618            0 :             }
    4619              : 
    4620              :             // no shard needs to go first/last; the operation should be idempotent
    4621              :             // TODO: it would be great to ensure that all shards return the same error
    4622            0 :             let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
    4623            0 :             let results = self
    4624            0 :                 .tenant_for_shards(locations, |tenant_shard_id, node| {
    4625            0 :                     futures::FutureExt::boxed(config_one(
    4626            0 :                         tenant_shard_id,
    4627            0 :                         timeline_id,
    4628            0 :                         node,
    4629            0 :                         self.http_client.clone(),
    4630            0 :                         self.config.pageserver_jwt_token.clone(),
    4631            0 :                         req.clone(),
    4632            0 :                     ))
    4633            0 :                 })
    4634            0 :                 .await?;
    4635            0 :             assert!(!results.is_empty(), "must have at least one result");
    4636              : 
    4637            0 :             Ok(())
    4638            0 :         }).await?
    4639            0 :     }
    4640              : 
    4641            0 :     pub(crate) async fn tenant_timeline_detach_ancestor(
    4642            0 :         &self,
    4643            0 :         tenant_id: TenantId,
    4644            0 :         timeline_id: TimelineId,
    4645            0 :         behavior: Option<DetachBehavior>,
    4646            0 :     ) -> Result<models::detach_ancestor::AncestorDetached, ApiError> {
    4647            0 :         tracing::info!("Detaching timeline {tenant_id}/{timeline_id}",);
    4648              : 
    4649            0 :         let _tenant_lock = trace_shared_lock(
    4650            0 :             &self.tenant_op_locks,
    4651            0 :             tenant_id,
    4652            0 :             TenantOperations::TimelineDetachAncestor,
    4653            0 :         )
    4654            0 :         .await;
    4655              : 
    4656            0 :         self.tenant_remote_mutation(tenant_id, move |targets| async move {
    4657            0 :             if targets.0.is_empty() {
    4658            0 :                 return Err(ApiError::NotFound(
    4659            0 :                     anyhow::anyhow!("Tenant not found").into(),
    4660            0 :                 ));
    4661            0 :             }
    4662              : 
    4663            0 :             async fn detach_one(
    4664            0 :                 tenant_shard_id: TenantShardId,
    4665            0 :                 timeline_id: TimelineId,
    4666            0 :                 node: Node,
    4667            0 :                 http_client: reqwest::Client,
    4668            0 :                 jwt: Option<String>,
    4669            0 :                 behavior: Option<DetachBehavior>,
    4670            0 :             ) -> Result<(ShardNumber, models::detach_ancestor::AncestorDetached), ApiError> {
    4671            0 :                 tracing::info!(
    4672            0 :                     "Detaching timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
    4673              :                 );
    4674              : 
    4675            0 :                 let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
    4676              : 
    4677            0 :                 client
    4678            0 :                     .timeline_detach_ancestor(tenant_shard_id, timeline_id, behavior)
    4679            0 :                     .await
    4680            0 :                     .map_err(|e| {
    4681              :                         use mgmt_api::Error;
    4682              : 
    4683            0 :                         match e {
    4684              :                             // no ancestor (ever)
    4685            0 :                             Error::ApiError(StatusCode::CONFLICT, msg) => ApiError::Conflict(format!(
    4686            0 :                                 "{node}: {}",
    4687            0 :                                 msg.strip_prefix("Conflict: ").unwrap_or(&msg)
    4688            0 :                             )),
    4689              :                             // too many ancestors
    4690            0 :                             Error::ApiError(StatusCode::BAD_REQUEST, msg) => {
    4691            0 :                                 ApiError::BadRequest(anyhow::anyhow!("{node}: {msg}"))
    4692              :                             }
    4693            0 :                             Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, msg) => {
    4694              :                                 // avoid turning these into conflicts to remain compatible with
    4695              :                                 // pageservers, 500 errors are sadly retryable with timeline ancestor
    4696              :                                 // detach
    4697            0 :                                 ApiError::InternalServerError(anyhow::anyhow!("{node}: {msg}"))
    4698              :                             }
    4699              :                             // rest can be mapped as usual
    4700            0 :                             other => passthrough_api_error(&node, other),
    4701              :                         }
    4702            0 :                     })
    4703            0 :                     .map(|res| (tenant_shard_id.shard_number, res))
    4704            0 :             }
    4705              : 
    4706              :             // no shard needs to go first/last; the operation should be idempotent
    4707            0 :             let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
    4708            0 :             let mut results = self
    4709            0 :                 .tenant_for_shards(locations, |tenant_shard_id, node| {
    4710            0 :                     futures::FutureExt::boxed(detach_one(
    4711            0 :                         tenant_shard_id,
    4712            0 :                         timeline_id,
    4713            0 :                         node,
    4714            0 :                         self.http_client.clone(),
    4715            0 :                         self.config.pageserver_jwt_token.clone(),
    4716            0 :                         behavior,
    4717            0 :                     ))
    4718            0 :                 })
    4719            0 :                 .await?;
    4720              : 
    4721            0 :             let any = results.pop().expect("we must have at least one response");
    4722              : 
    4723            0 :             let mismatching = results
    4724            0 :                 .iter()
    4725            0 :                 .filter(|(_, res)| res != &any.1)
    4726            0 :                 .collect::<Vec<_>>();
    4727            0 :             if !mismatching.is_empty() {
    4728              :                 // this can be hit by races which should not happen because operation lock on cplane
    4729            0 :                 let matching = results.len() - mismatching.len();
    4730            0 :                 tracing::error!(
    4731              :                     matching,
    4732              :                     compared_against=?any,
    4733              :                     ?mismatching,
    4734            0 :                     "shards returned different results"
    4735              :                 );
    4736              : 
    4737            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!("pageservers returned mixed results for ancestor detach; manual intervention is required.")));
    4738            0 :             }
    4739              : 
    4740            0 :             Ok(any.1)
    4741            0 :         }).await?
    4742            0 :     }
    4743              : 
    4744            0 :     pub(crate) async fn tenant_timeline_block_unblock_gc(
    4745            0 :         &self,
    4746            0 :         tenant_id: TenantId,
    4747            0 :         timeline_id: TimelineId,
    4748            0 :         dir: BlockUnblock,
    4749            0 :     ) -> Result<(), ApiError> {
    4750            0 :         let _tenant_lock = trace_shared_lock(
    4751            0 :             &self.tenant_op_locks,
    4752            0 :             tenant_id,
    4753            0 :             TenantOperations::TimelineGcBlockUnblock,
    4754            0 :         )
    4755            0 :         .await;
    4756              : 
    4757            0 :         self.tenant_remote_mutation(tenant_id, move |targets| async move {
    4758            0 :             if targets.0.is_empty() {
    4759            0 :                 return Err(ApiError::NotFound(
    4760            0 :                     anyhow::anyhow!("Tenant not found").into(),
    4761            0 :                 ));
    4762            0 :             }
    4763              : 
    4764            0 :             async fn do_one(
    4765            0 :                 tenant_shard_id: TenantShardId,
    4766            0 :                 timeline_id: TimelineId,
    4767            0 :                 node: Node,
    4768            0 :                 http_client: reqwest::Client,
    4769            0 :                 jwt: Option<String>,
    4770            0 :                 dir: BlockUnblock,
    4771            0 :             ) -> Result<(), ApiError> {
    4772            0 :                 let client = PageserverClient::new(
    4773            0 :                     node.get_id(),
    4774            0 :                     http_client,
    4775            0 :                     node.base_url(),
    4776            0 :                     jwt.as_deref(),
    4777              :                 );
    4778              : 
    4779            0 :                 client
    4780            0 :                     .timeline_block_unblock_gc(tenant_shard_id, timeline_id, dir)
    4781            0 :                     .await
    4782            0 :                     .map_err(|e| passthrough_api_error(&node, e))
    4783            0 :             }
    4784              : 
    4785              :             // no shard needs to go first/last; the operation should be idempotent
    4786            0 :             let locations = targets
    4787            0 :                 .0
    4788            0 :                 .iter()
    4789            0 :                 .map(|t| (*t.0, t.1.latest.node.clone()))
    4790            0 :                 .collect();
    4791            0 :             self.tenant_for_shards(locations, |tenant_shard_id, node| {
    4792            0 :                 futures::FutureExt::boxed(do_one(
    4793            0 :                     tenant_shard_id,
    4794            0 :                     timeline_id,
    4795            0 :                     node,
    4796            0 :                     self.http_client.clone(),
    4797            0 :                     self.config.pageserver_jwt_token.clone(),
    4798            0 :                     dir,
    4799            0 :                 ))
    4800            0 :             })
    4801            0 :             .await
    4802            0 :         })
    4803            0 :         .await??;
    4804            0 :         Ok(())
    4805            0 :     }
    4806              : 
    4807            0 :     pub(crate) fn is_tenant_not_found_error(body: &str, tenant_id: TenantId) -> bool {
    4808            0 :         body.contains(&format!("tenant {tenant_id}"))
    4809            0 :     }
    4810              : 
    4811            0 :     fn process_result_and_passthrough_errors<T>(
    4812            0 :         &self,
    4813            0 :         tenant_id: TenantId,
    4814            0 :         results: Vec<(Node, Result<T, mgmt_api::Error>)>,
    4815            0 :     ) -> Result<Vec<(Node, T)>, ApiError> {
    4816            0 :         let mut processed_results: Vec<(Node, T)> = Vec::with_capacity(results.len());
    4817            0 :         for (node, res) in results {
    4818            0 :             match res {
    4819            0 :                 Ok(res) => processed_results.push((node, res)),
    4820            0 :                 Err(mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, body))
    4821            0 :                     if Self::is_tenant_not_found_error(&body, tenant_id) =>
    4822              :                 {
    4823              :                     // If there's a tenant not found, we are still in the process of attaching the tenant.
    4824              :                     // Return 503 so that the client can retry.
    4825            0 :                     return Err(ApiError::ResourceUnavailable(
    4826            0 :                         format!(
    4827            0 :                             "Timeline is not attached to the pageserver {} yet, please retry",
    4828            0 :                             node.get_id()
    4829            0 :                         )
    4830            0 :                         .into(),
    4831            0 :                     ));
    4832              :                 }
    4833            0 :                 Err(e) => return Err(passthrough_api_error(&node, e)),
    4834              :             }
    4835              :         }
    4836            0 :         Ok(processed_results)
    4837            0 :     }
    4838              : 
    4839            0 :     pub(crate) async fn tenant_timeline_lsn_lease(
    4840            0 :         &self,
    4841            0 :         tenant_id: TenantId,
    4842            0 :         timeline_id: TimelineId,
    4843            0 :         lsn: Lsn,
    4844            0 :     ) -> Result<LsnLease, ApiError> {
    4845            0 :         let _tenant_lock = trace_shared_lock(
    4846            0 :             &self.tenant_op_locks,
    4847            0 :             tenant_id,
    4848            0 :             TenantOperations::TimelineLsnLease,
    4849            0 :         )
    4850            0 :         .await;
    4851              : 
    4852            0 :         self.tenant_remote_mutation(tenant_id, |locations| async move {
    4853            0 :             if locations.0.is_empty() {
    4854            0 :                 return Err(ApiError::NotFound(
    4855            0 :                     anyhow::anyhow!("Tenant not found").into(),
    4856            0 :                 ));
    4857            0 :             }
    4858              : 
    4859            0 :             let results = self
    4860            0 :                 .tenant_for_shards_api(
    4861            0 :                     locations
    4862            0 :                         .0
    4863            0 :                         .iter()
    4864            0 :                         .map(|(tenant_shard_id, ShardMutationLocations { latest, .. })| {
    4865            0 :                             (*tenant_shard_id, latest.node.clone())
    4866            0 :                         })
    4867            0 :                         .collect(),
    4868            0 :                     |tenant_shard_id, client| async move {
    4869            0 :                         client
    4870            0 :                             .timeline_lease_lsn(tenant_shard_id, timeline_id, lsn)
    4871            0 :                             .await
    4872            0 :                     },
    4873              :                     1,
    4874              :                     1,
    4875              :                     SHORT_RECONCILE_TIMEOUT,
    4876            0 :                     &self.cancel,
    4877              :                 )
    4878            0 :                 .await;
    4879              : 
    4880            0 :             let leases = self.process_result_and_passthrough_errors(tenant_id, results)?;
    4881            0 :             let mut valid_until = None;
    4882            0 :             for (_, lease) in leases {
    4883            0 :                 if let Some(ref mut valid_until) = valid_until {
    4884            0 :                     *valid_until = std::cmp::min(*valid_until, lease.valid_until);
    4885            0 :                 } else {
    4886            0 :                     valid_until = Some(lease.valid_until);
    4887            0 :                 }
    4888              :             }
    4889            0 :             Ok(LsnLease {
    4890            0 :                 valid_until: valid_until.unwrap_or_else(SystemTime::now),
    4891            0 :             })
    4892            0 :         })
    4893            0 :         .await?
    4894            0 :     }
    4895              : 
    4896            0 :     pub(crate) async fn tenant_timeline_download_heatmap_layers(
    4897            0 :         &self,
    4898            0 :         tenant_shard_id: TenantShardId,
    4899            0 :         timeline_id: TimelineId,
    4900            0 :         concurrency: Option<usize>,
    4901            0 :         recurse: bool,
    4902            0 :     ) -> Result<(), ApiError> {
    4903            0 :         let _tenant_lock = trace_shared_lock(
    4904            0 :             &self.tenant_op_locks,
    4905            0 :             tenant_shard_id.tenant_id,
    4906            0 :             TenantOperations::DownloadHeatmapLayers,
    4907            0 :         )
    4908            0 :         .await;
    4909              : 
    4910            0 :         let targets = {
    4911            0 :             let locked = self.inner.read().unwrap();
    4912            0 :             let mut targets = Vec::new();
    4913              : 
    4914              :             // If the request got an unsharded tenant id, then apply
    4915              :             // the operation to all shards. Otherwise, apply it to a specific shard.
    4916            0 :             let shards_range = if tenant_shard_id.is_unsharded() {
    4917            0 :                 TenantShardId::tenant_range(tenant_shard_id.tenant_id)
    4918              :             } else {
    4919            0 :                 tenant_shard_id.range()
    4920              :             };
    4921              : 
    4922            0 :             for (tenant_shard_id, shard) in locked.tenants.range(shards_range) {
    4923            0 :                 if let Some(node_id) = shard.intent.get_attached() {
    4924            0 :                     let node = locked
    4925            0 :                         .nodes
    4926            0 :                         .get(node_id)
    4927            0 :                         .expect("Pageservers may not be deleted while referenced");
    4928            0 : 
    4929            0 :                     targets.push((*tenant_shard_id, node.clone()));
    4930            0 :                 }
    4931              :             }
    4932            0 :             targets
    4933              :         };
    4934              : 
    4935            0 :         self.tenant_for_shards_api(
    4936            0 :             targets,
    4937            0 :             |tenant_shard_id, client| async move {
    4938            0 :                 client
    4939            0 :                     .timeline_download_heatmap_layers(
    4940            0 :                         tenant_shard_id,
    4941            0 :                         timeline_id,
    4942            0 :                         concurrency,
    4943            0 :                         recurse,
    4944            0 :                     )
    4945            0 :                     .await
    4946            0 :             },
    4947              :             1,
    4948              :             1,
    4949              :             SHORT_RECONCILE_TIMEOUT,
    4950            0 :             &self.cancel,
    4951              :         )
    4952            0 :         .await;
    4953              : 
    4954            0 :         Ok(())
    4955            0 :     }
    4956              : 
    4957              :     /// Helper for concurrently calling a pageserver API on a number of shards, such as timeline creation.
    4958              :     ///
    4959              :     /// On success, the returned vector contains exactly the same number of elements as the input `locations`
    4960              :     /// and returned element at index `i` is the result for `req_fn(op(locations[i])`.
    4961            0 :     async fn tenant_for_shards<F, R>(
    4962            0 :         &self,
    4963            0 :         locations: Vec<(TenantShardId, Node)>,
    4964            0 :         mut req_fn: F,
    4965            0 :     ) -> Result<Vec<R>, ApiError>
    4966            0 :     where
    4967            0 :         F: FnMut(
    4968            0 :             TenantShardId,
    4969            0 :             Node,
    4970            0 :         )
    4971            0 :             -> std::pin::Pin<Box<dyn futures::Future<Output = Result<R, ApiError>> + Send>>,
    4972            0 :     {
    4973            0 :         let mut futs = FuturesUnordered::new();
    4974            0 :         let mut results = Vec::with_capacity(locations.len());
    4975              : 
    4976            0 :         for (idx, (tenant_shard_id, node)) in locations.into_iter().enumerate() {
    4977            0 :             let fut = req_fn(tenant_shard_id, node);
    4978            0 :             futs.push(async move { (idx, fut.await) });
    4979              :         }
    4980              : 
    4981            0 :         while let Some((idx, r)) = futs.next().await {
    4982            0 :             results.push((idx, r?));
    4983              :         }
    4984              : 
    4985            0 :         results.sort_by_key(|(idx, _)| *idx);
    4986            0 :         Ok(results.into_iter().map(|(_, r)| r).collect())
    4987            0 :     }
    4988              : 
    4989              :     /// Concurrently invoke a pageserver API call on many shards at once.
    4990              :     ///
    4991              :     /// The returned Vec has the same length as the `locations` Vec,
    4992              :     /// and returned element at index `i` is the result for `op(locations[i])`.
    4993            0 :     pub(crate) async fn tenant_for_shards_api<T, O, F>(
    4994            0 :         &self,
    4995            0 :         locations: Vec<(TenantShardId, Node)>,
    4996            0 :         op: O,
    4997            0 :         warn_threshold: u32,
    4998            0 :         max_retries: u32,
    4999            0 :         timeout: Duration,
    5000            0 :         cancel: &CancellationToken,
    5001            0 :     ) -> Vec<(Node, mgmt_api::Result<T>)>
    5002            0 :     where
    5003            0 :         O: Fn(TenantShardId, PageserverClient) -> F + Copy,
    5004            0 :         F: std::future::Future<Output = mgmt_api::Result<T>>,
    5005            0 :     {
    5006            0 :         let mut futs = FuturesUnordered::new();
    5007            0 :         let mut results = Vec::with_capacity(locations.len());
    5008              : 
    5009            0 :         for (idx, (tenant_shard_id, node)) in locations.into_iter().enumerate() {
    5010            0 :             futs.push(async move {
    5011            0 :                 let r = node
    5012            0 :                     .with_client_retries(
    5013            0 :                         |client| op(tenant_shard_id, client),
    5014            0 :                         &self.http_client,
    5015            0 :                         &self.config.pageserver_jwt_token,
    5016            0 :                         warn_threshold,
    5017            0 :                         max_retries,
    5018            0 :                         timeout,
    5019            0 :                         cancel,
    5020              :                     )
    5021            0 :                     .await;
    5022            0 :                 (idx, node, r)
    5023            0 :             });
    5024              :         }
    5025              : 
    5026            0 :         while let Some((idx, node, r)) = futs.next().await {
    5027            0 :             results.push((idx, node, r.unwrap_or(Err(mgmt_api::Error::Cancelled))));
    5028            0 :         }
    5029              : 
    5030            0 :         results.sort_by_key(|(idx, _, _)| *idx);
    5031            0 :         results.into_iter().map(|(_, node, r)| (node, r)).collect()
    5032            0 :     }
    5033              : 
    5034              :     /// Helper for safely working with the shards in a tenant remotely on pageservers, for example
    5035              :     /// when creating and deleting timelines:
    5036              :     /// - Makes sure shards are attached somewhere if they weren't already
    5037              :     /// - Looks up the shards and the nodes where they were most recently attached
    5038              :     /// - Guarantees that after the inner function returns, the shards' generations haven't moved on: this
    5039              :     ///   ensures that the remote operation acted on the most recent generation, and is therefore durable.
    5040            0 :     pub(crate) async fn tenant_remote_mutation<R, O, F>(
    5041            0 :         &self,
    5042            0 :         tenant_id: TenantId,
    5043            0 :         op: O,
    5044            0 :     ) -> Result<R, ApiError>
    5045            0 :     where
    5046            0 :         O: FnOnce(TenantMutationLocations) -> F,
    5047            0 :         F: std::future::Future<Output = R>,
    5048            0 :     {
    5049            0 :         self.tenant_remote_mutation_inner(TenantIdOrShardId::TenantId(tenant_id), op)
    5050            0 :             .await
    5051            0 :     }
    5052              : 
    5053            0 :     pub(crate) async fn tenant_shard_remote_mutation<R, O, F>(
    5054            0 :         &self,
    5055            0 :         tenant_shard_id: TenantShardId,
    5056            0 :         op: O,
    5057            0 :     ) -> Result<R, ApiError>
    5058            0 :     where
    5059            0 :         O: FnOnce(TenantMutationLocations) -> F,
    5060            0 :         F: std::future::Future<Output = R>,
    5061            0 :     {
    5062            0 :         self.tenant_remote_mutation_inner(TenantIdOrShardId::TenantShardId(tenant_shard_id), op)
    5063            0 :             .await
    5064            0 :     }
    5065              : 
    5066            0 :     async fn tenant_remote_mutation_inner<R, O, F>(
    5067            0 :         &self,
    5068            0 :         tenant_id_or_shard_id: TenantIdOrShardId,
    5069            0 :         op: O,
    5070            0 :     ) -> Result<R, ApiError>
    5071            0 :     where
    5072            0 :         O: FnOnce(TenantMutationLocations) -> F,
    5073            0 :         F: std::future::Future<Output = R>,
    5074            0 :     {
    5075            0 :         let mutation_locations = {
    5076            0 :             let mut locations = TenantMutationLocations::default();
    5077              : 
    5078              :             // Load the currently attached pageservers for the latest generation of each shard.  This can
    5079              :             // run concurrently with reconciliations, and it is not guaranteed that the node we find here
    5080              :             // will still be the latest when we're done: we will check generations again at the end of
    5081              :             // this function to handle that.
    5082            0 :             let generations = self
    5083            0 :                 .persistence
    5084            0 :                 .tenant_generations(tenant_id_or_shard_id.tenant_id())
    5085            0 :                 .await?
    5086            0 :                 .into_iter()
    5087            0 :                 .filter(|i| tenant_id_or_shard_id.matches(&i.tenant_shard_id))
    5088            0 :                 .collect::<Vec<_>>();
    5089              : 
    5090            0 :             if generations
    5091            0 :                 .iter()
    5092            0 :                 .any(|i| i.generation.is_none() || i.generation_pageserver.is_none())
    5093              :             {
    5094            0 :                 let shard_generations = generations
    5095            0 :                     .into_iter()
    5096            0 :                     .map(|i| (i.tenant_shard_id, (i.generation, i.generation_pageserver)))
    5097            0 :                     .collect::<HashMap<_, _>>();
    5098              : 
    5099              :                 // One or more shards has not been attached to a pageserver.  Check if this is because it's configured
    5100              :                 // to be detached (409: caller should give up), or because it's meant to be attached but isn't yet (503: caller should retry)
    5101            0 :                 let locked = self.inner.read().unwrap();
    5102            0 :                 let tenant_shards = locked
    5103            0 :                     .tenants
    5104            0 :                     .range(TenantShardId::tenant_range(
    5105            0 :                         tenant_id_or_shard_id.tenant_id(),
    5106              :                     ))
    5107            0 :                     .filter(|(shard_id, _)| tenant_id_or_shard_id.matches(shard_id))
    5108            0 :                     .collect::<Vec<_>>();
    5109            0 :                 for (shard_id, shard) in tenant_shards {
    5110            0 :                     match shard.policy {
    5111              :                         PlacementPolicy::Attached(_) => {
    5112              :                             // This shard is meant to be attached: the caller is not wrong to try and
    5113              :                             // use this function, but we can't service the request right now.
    5114            0 :                             let Some(generation) = shard_generations.get(shard_id) else {
    5115              :                                 // This can only happen if there is a split brain controller modifying the database.  This should
    5116              :                                 // never happen when testing, and if it happens in production we can only log the issue.
    5117            0 :                                 debug_assert!(false);
    5118            0 :                                 tracing::error!(
    5119            0 :                                     "Shard {shard_id} not found in generation state!  Is another rogue controller running?"
    5120              :                                 );
    5121            0 :                                 continue;
    5122              :                             };
    5123            0 :                             let (generation, generation_pageserver) = generation;
    5124            0 :                             if let Some(generation) = generation {
    5125            0 :                                 if generation_pageserver.is_none() {
    5126              :                                     // This is legitimate only in a very narrow window where the shard was only just configured into
    5127              :                                     // Attached mode after being created in Secondary or Detached mode, and it has had its generation
    5128              :                                     // set but not yet had a Reconciler run (reconciler is the only thing that sets generation_pageserver).
    5129            0 :                                     tracing::warn!(
    5130            0 :                                         "Shard {shard_id} generation is set ({generation:?}) but generation_pageserver is None, reconciler not run yet?"
    5131              :                                     );
    5132            0 :                                 }
    5133              :                             } else {
    5134              :                                 // This should never happen: a shard with no generation is only permitted when it was created in some state
    5135              :                                 // other than PlacementPolicy::Attached (and generation is always written to DB before setting Attached in memory)
    5136            0 :                                 debug_assert!(false);
    5137            0 :                                 tracing::error!(
    5138            0 :                                     "Shard {shard_id} generation is None, but it is in PlacementPolicy::Attached mode!"
    5139              :                                 );
    5140            0 :                                 continue;
    5141              :                             }
    5142              :                         }
    5143              :                         PlacementPolicy::Secondary | PlacementPolicy::Detached => {
    5144            0 :                             return Err(ApiError::Conflict(format!(
    5145            0 :                                 "Shard {shard_id} tenant has policy {:?}",
    5146            0 :                                 shard.policy
    5147            0 :                             )));
    5148              :                         }
    5149              :                     }
    5150              :                 }
    5151              : 
    5152            0 :                 return Err(ApiError::ResourceUnavailable(
    5153            0 :                     "One or more shards in tenant is not yet attached".into(),
    5154            0 :                 ));
    5155            0 :             }
    5156              : 
    5157            0 :             let locked = self.inner.read().unwrap();
    5158              :             for ShardGenerationState {
    5159            0 :                 tenant_shard_id,
    5160            0 :                 generation,
    5161            0 :                 generation_pageserver,
    5162            0 :             } in generations
    5163              :             {
    5164            0 :                 let node_id = generation_pageserver.expect("We checked for None above");
    5165            0 :                 let node = locked
    5166            0 :                     .nodes
    5167            0 :                     .get(&node_id)
    5168            0 :                     .ok_or(ApiError::Conflict(format!(
    5169            0 :                         "Raced with removal of node {node_id}"
    5170            0 :                     )))?;
    5171            0 :                 let generation = generation.expect("Checked above");
    5172              : 
    5173            0 :                 let tenant = locked.tenants.get(&tenant_shard_id);
    5174              : 
    5175              :                 // TODO(vlad): Abstract the logic that finds stale attached locations
    5176              :                 // from observed state into a [`Service`] method.
    5177            0 :                 let other_locations = match tenant {
    5178            0 :                     Some(tenant) => {
    5179            0 :                         let mut other = tenant.attached_locations();
    5180            0 :                         let latest_location_index =
    5181            0 :                             other.iter().position(|&l| l == (node.get_id(), generation));
    5182            0 :                         if let Some(idx) = latest_location_index {
    5183            0 :                             other.remove(idx);
    5184            0 :                         }
    5185              : 
    5186            0 :                         other
    5187              :                     }
    5188            0 :                     None => Vec::default(),
    5189              :                 };
    5190              : 
    5191            0 :                 let location = ShardMutationLocations {
    5192            0 :                     latest: MutationLocation {
    5193            0 :                         node: node.clone(),
    5194            0 :                         generation,
    5195            0 :                     },
    5196            0 :                     other: other_locations
    5197            0 :                         .into_iter()
    5198            0 :                         .filter_map(|(node_id, generation)| {
    5199            0 :                             let node = locked.nodes.get(&node_id)?;
    5200              : 
    5201            0 :                             Some(MutationLocation {
    5202            0 :                                 node: node.clone(),
    5203            0 :                                 generation,
    5204            0 :                             })
    5205            0 :                         })
    5206            0 :                         .collect(),
    5207              :                 };
    5208            0 :                 locations.0.insert(tenant_shard_id, location);
    5209              :             }
    5210              : 
    5211            0 :             locations
    5212              :         };
    5213              : 
    5214            0 :         let result = op(mutation_locations.clone()).await;
    5215              : 
    5216              :         // Post-check: are all the generations of all the shards the same as they were initially?  This proves that
    5217              :         // our remote operation executed on the latest generation and is therefore persistent.
    5218              :         {
    5219            0 :             let latest_generations = self
    5220            0 :                 .persistence
    5221            0 :                 .tenant_generations(tenant_id_or_shard_id.tenant_id())
    5222            0 :                 .await?
    5223            0 :                 .into_iter()
    5224            0 :                 .filter(|i| tenant_id_or_shard_id.matches(&i.tenant_shard_id))
    5225            0 :                 .collect::<Vec<_>>();
    5226              : 
    5227            0 :             if latest_generations
    5228            0 :                 .into_iter()
    5229            0 :                 .map(
    5230              :                     |ShardGenerationState {
    5231              :                          tenant_shard_id,
    5232              :                          generation,
    5233              :                          generation_pageserver: _,
    5234            0 :                      }| (tenant_shard_id, generation),
    5235              :                 )
    5236            0 :                 .collect::<Vec<_>>()
    5237            0 :                 != mutation_locations
    5238            0 :                     .0
    5239            0 :                     .into_iter()
    5240            0 :                     .map(|i| (i.0, Some(i.1.latest.generation)))
    5241            0 :                     .collect::<Vec<_>>()
    5242              :             {
    5243              :                 // We raced with something that incremented the generation, and therefore cannot be
    5244              :                 // confident that our actions are persistent (they might have hit an old generation).
    5245              :                 //
    5246              :                 // This is safe but requires a retry: ask the client to do that by giving them a 503 response.
    5247            0 :                 return Err(ApiError::ResourceUnavailable(
    5248            0 :                     "Tenant attachment changed, please retry".into(),
    5249            0 :                 ));
    5250            0 :             }
    5251              :         }
    5252              : 
    5253            0 :         Ok(result)
    5254            0 :     }
    5255              : 
    5256            0 :     pub(crate) async fn tenant_timeline_delete(
    5257            0 :         self: &Arc<Self>,
    5258            0 :         tenant_id: TenantId,
    5259            0 :         timeline_id: TimelineId,
    5260            0 :     ) -> Result<StatusCode, ApiError> {
    5261            0 :         tracing::info!("Deleting timeline {}/{}", tenant_id, timeline_id,);
    5262            0 :         let _tenant_lock = trace_shared_lock(
    5263            0 :             &self.tenant_op_locks,
    5264            0 :             tenant_id,
    5265            0 :             TenantOperations::TimelineDelete,
    5266            0 :         )
    5267            0 :         .await;
    5268              : 
    5269            0 :         let status_code = self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
    5270            0 :             if targets.0.is_empty() {
    5271            0 :                 return Err(ApiError::NotFound(
    5272            0 :                     anyhow::anyhow!("Tenant not found").into(),
    5273            0 :                 ));
    5274            0 :             }
    5275              : 
    5276            0 :             let (shard_zero_tid, shard_zero_locations) = targets.0.pop_first().expect("Must have at least one shard");
    5277            0 :             assert!(shard_zero_tid.is_shard_zero());
    5278              : 
    5279            0 :             async fn delete_one(
    5280            0 :                 tenant_shard_id: TenantShardId,
    5281            0 :                 timeline_id: TimelineId,
    5282            0 :                 node: Node,
    5283            0 :                 http_client: reqwest::Client,
    5284            0 :                 jwt: Option<String>,
    5285            0 :             ) -> Result<StatusCode, ApiError> {
    5286            0 :                 tracing::info!(
    5287            0 :                     "Deleting timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
    5288              :                 );
    5289              : 
    5290            0 :                 let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
    5291            0 :                 let res = client
    5292            0 :                     .timeline_delete(tenant_shard_id, timeline_id)
    5293            0 :                     .await;
    5294              : 
    5295            0 :                 match res {
    5296            0 :                     Ok(ok) => Ok(ok),
    5297            0 :                     Err(mgmt_api::Error::ApiError(StatusCode::CONFLICT, _)) => Ok(StatusCode::CONFLICT),
    5298            0 :                     Err(mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg)) if msg.contains("Requested tenant is missing") => {
    5299            0 :                         Err(ApiError::ResourceUnavailable("Tenant migration in progress".into()))
    5300              :                     },
    5301            0 :                     Err(mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg)) => Err(ApiError::ResourceUnavailable(msg.into())),
    5302            0 :                     Err(e) => {
    5303            0 :                         Err(
    5304            0 :                             ApiError::InternalServerError(anyhow::anyhow!(
    5305            0 :                                 "Error deleting timeline {timeline_id} on {tenant_shard_id} on node {node}: {e}",
    5306            0 :                             ))
    5307            0 :                         )
    5308              :                     }
    5309              :                 }
    5310            0 :             }
    5311              : 
    5312            0 :             let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
    5313            0 :             let statuses = self
    5314            0 :                 .tenant_for_shards(locations, |tenant_shard_id: TenantShardId, node: Node| {
    5315            0 :                     Box::pin(delete_one(
    5316            0 :                         tenant_shard_id,
    5317            0 :                         timeline_id,
    5318            0 :                         node,
    5319            0 :                         self.http_client.clone(),
    5320            0 :                         self.config.pageserver_jwt_token.clone(),
    5321            0 :                     ))
    5322            0 :                 })
    5323            0 :                 .await?;
    5324              : 
    5325              :             // If any shards >0 haven't finished deletion yet, don't start deletion on shard zero.
    5326              :             // We return 409 (Conflict) if deletion was already in progress on any of the shards
    5327              :             // and 202 (Accepted) if deletion was not already in progress on any of the shards.
    5328            0 :             if statuses.iter().any(|s| s == &StatusCode::CONFLICT) {
    5329            0 :                 return Ok(StatusCode::CONFLICT);
    5330            0 :             }
    5331              : 
    5332            0 :             if statuses.iter().any(|s| s != &StatusCode::NOT_FOUND) {
    5333            0 :                 return Ok(StatusCode::ACCEPTED);
    5334            0 :             }
    5335              : 
    5336              :             // Delete shard zero last: this is not strictly necessary, but since a caller's GET on a timeline will be routed
    5337              :             // to shard zero, it gives a more obvious behavior that a GET returns 404 once the deletion is done.
    5338            0 :             let shard_zero_status = delete_one(
    5339            0 :                 shard_zero_tid,
    5340            0 :                 timeline_id,
    5341            0 :                 shard_zero_locations.latest.node,
    5342            0 :                 self.http_client.clone(),
    5343            0 :                 self.config.pageserver_jwt_token.clone(),
    5344            0 :             )
    5345            0 :             .await?;
    5346            0 :             Ok(shard_zero_status)
    5347            0 :         }).await?;
    5348              : 
    5349            0 :         self.tenant_timeline_delete_safekeepers(tenant_id, timeline_id)
    5350            0 :             .await?;
    5351              : 
    5352            0 :         status_code
    5353            0 :     }
    5354              :     /// When you know the TenantId but not a specific shard, and would like to get the node holding shard 0.
    5355              :     ///
    5356              :     /// Returns the node, tenant shard id, and whether it is consistent with the observed state.
    5357            0 :     pub(crate) async fn tenant_shard0_node(
    5358            0 :         &self,
    5359            0 :         tenant_id: TenantId,
    5360            0 :     ) -> Result<(Node, TenantShardId), ApiError> {
    5361            0 :         let tenant_shard_id = {
    5362            0 :             let locked = self.inner.read().unwrap();
    5363            0 :             let Some((tenant_shard_id, _shard)) = locked
    5364            0 :                 .tenants
    5365            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    5366            0 :                 .next()
    5367              :             else {
    5368            0 :                 return Err(ApiError::NotFound(
    5369            0 :                     anyhow::anyhow!("Tenant {tenant_id} not found").into(),
    5370            0 :                 ));
    5371              :             };
    5372              : 
    5373            0 :             *tenant_shard_id
    5374              :         };
    5375              : 
    5376            0 :         self.tenant_shard_node(tenant_shard_id)
    5377            0 :             .await
    5378            0 :             .map(|node| (node, tenant_shard_id))
    5379            0 :     }
    5380              : 
    5381              :     /// When you need to send an HTTP request to the pageserver that holds a shard of a tenant, this
    5382              :     /// function looks up and returns node. If the shard isn't found, returns Err(ApiError::NotFound)
    5383              :     ///
    5384              :     /// Returns the intent node and whether it is consistent with the observed state.
    5385            0 :     pub(crate) async fn tenant_shard_node(
    5386            0 :         &self,
    5387            0 :         tenant_shard_id: TenantShardId,
    5388            0 :     ) -> Result<Node, ApiError> {
    5389              :         // Look up in-memory state and maybe use the node from there.
    5390              :         {
    5391            0 :             let locked = self.inner.read().unwrap();
    5392            0 :             let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
    5393            0 :                 return Err(ApiError::NotFound(
    5394            0 :                     anyhow::anyhow!("Tenant shard {tenant_shard_id} not found").into(),
    5395            0 :                 ));
    5396              :             };
    5397              : 
    5398            0 :             let Some(intent_node_id) = shard.intent.get_attached() else {
    5399            0 :                 tracing::warn!(
    5400            0 :                     tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
    5401            0 :                     "Shard not scheduled (policy {:?}), cannot generate pass-through URL",
    5402              :                     shard.policy
    5403              :                 );
    5404            0 :                 return Err(ApiError::Conflict(
    5405            0 :                     "Cannot call timeline API on non-attached tenant".to_string(),
    5406            0 :                 ));
    5407              :             };
    5408              : 
    5409            0 :             if shard.reconciler.is_none() {
    5410              :                 // Optimization: while no reconcile is in flight, we may trust our in-memory state
    5411              :                 // to tell us which pageserver to use. Otherwise we will fall through and hit the database
    5412            0 :                 let Some(node) = locked.nodes.get(intent_node_id) else {
    5413              :                     // This should never happen
    5414            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    5415            0 :                         "Shard refers to nonexistent node"
    5416            0 :                     )));
    5417              :                 };
    5418            0 :                 return Ok(node.clone());
    5419            0 :             }
    5420              :         };
    5421              : 
    5422              :         // Look up the latest attached pageserver location from the database
    5423              :         // generation state: this will reflect the progress of any ongoing migration.
    5424              :         // Note that it is not guaranteed to _stay_ here, our caller must still handle
    5425              :         // the case where they call through to the pageserver and get a 404.
    5426            0 :         let db_result = self
    5427            0 :             .persistence
    5428            0 :             .tenant_generations(tenant_shard_id.tenant_id)
    5429            0 :             .await?;
    5430              :         let Some(ShardGenerationState {
    5431              :             tenant_shard_id: _,
    5432              :             generation: _,
    5433            0 :             generation_pageserver: Some(node_id),
    5434            0 :         }) = db_result
    5435            0 :             .into_iter()
    5436            0 :             .find(|s| s.tenant_shard_id == tenant_shard_id)
    5437              :         else {
    5438              :             // This can happen if we raced with a tenant deletion or a shard split.  On a retry
    5439              :             // the caller will either succeed (shard split case), get a proper 404 (deletion case),
    5440              :             // or a conflict response (case where tenant was detached in background)
    5441            0 :             return Err(ApiError::ResourceUnavailable(
    5442            0 :                 format!("Shard {tenant_shard_id} not found in database, or is not attached").into(),
    5443            0 :             ));
    5444              :         };
    5445            0 :         let locked = self.inner.read().unwrap();
    5446            0 :         let Some(node) = locked.nodes.get(&node_id) else {
    5447              :             // This should never happen
    5448            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    5449            0 :                 "Shard refers to nonexistent node"
    5450            0 :             )));
    5451              :         };
    5452              :         // As a reconciliation is in flight, we do not have the observed state yet, and therefore we assume it is always inconsistent.
    5453            0 :         Ok(node.clone())
    5454            0 :     }
    5455              : 
    5456            0 :     pub(crate) fn tenant_locate(
    5457            0 :         &self,
    5458            0 :         tenant_id: TenantId,
    5459            0 :     ) -> Result<TenantLocateResponse, ApiError> {
    5460            0 :         let locked = self.inner.read().unwrap();
    5461            0 :         tracing::info!("Locating shards for tenant {tenant_id}");
    5462              : 
    5463            0 :         let mut result = Vec::new();
    5464            0 :         let mut shard_params: Option<ShardParameters> = None;
    5465              : 
    5466            0 :         for (tenant_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    5467              :         {
    5468            0 :             let node_id =
    5469            0 :                 shard
    5470            0 :                     .intent
    5471            0 :                     .get_attached()
    5472            0 :                     .ok_or(ApiError::BadRequest(anyhow::anyhow!(
    5473            0 :                         "Cannot locate a tenant that is not attached"
    5474            0 :                     )))?;
    5475              : 
    5476            0 :             let node = locked
    5477            0 :                 .nodes
    5478            0 :                 .get(&node_id)
    5479            0 :                 .expect("Pageservers may not be deleted while referenced");
    5480              : 
    5481            0 :             result.push(node.shard_location(*tenant_shard_id));
    5482              : 
    5483            0 :             match &shard_params {
    5484            0 :                 None => {
    5485            0 :                     shard_params = Some(ShardParameters {
    5486            0 :                         stripe_size: shard.shard.stripe_size,
    5487            0 :                         count: shard.shard.count,
    5488            0 :                     });
    5489            0 :                 }
    5490            0 :                 Some(params) => {
    5491            0 :                     if params.stripe_size != shard.shard.stripe_size {
    5492              :                         // This should never happen.  We enforce at runtime because it's simpler than
    5493              :                         // adding an extra per-tenant data structure to store the things that should be the same
    5494            0 :                         return Err(ApiError::InternalServerError(anyhow::anyhow!(
    5495            0 :                             "Inconsistent shard stripe size parameters!"
    5496            0 :                         )));
    5497            0 :                     }
    5498              :                 }
    5499              :             }
    5500              :         }
    5501              : 
    5502            0 :         if result.is_empty() {
    5503            0 :             return Err(ApiError::NotFound(
    5504            0 :                 anyhow::anyhow!("No shards for this tenant ID found").into(),
    5505            0 :             ));
    5506            0 :         }
    5507            0 :         let shard_params = shard_params.expect("result is non-empty, therefore this is set");
    5508            0 :         tracing::info!(
    5509            0 :             "Located tenant {} with params {:?} on shards {}",
    5510              :             tenant_id,
    5511              :             shard_params,
    5512            0 :             result
    5513            0 :                 .iter()
    5514            0 :                 .map(|s| format!("{s:?}"))
    5515            0 :                 .collect::<Vec<_>>()
    5516            0 :                 .join(",")
    5517              :         );
    5518              : 
    5519            0 :         Ok(TenantLocateResponse {
    5520            0 :             shards: result,
    5521            0 :             shard_params,
    5522            0 :         })
    5523            0 :     }
    5524              : 
    5525              :     /// Returns None if the input iterator of shards does not include a shard with number=0
    5526            0 :     fn tenant_describe_impl<'a>(
    5527            0 :         &self,
    5528            0 :         shards: impl Iterator<Item = &'a TenantShard>,
    5529            0 :     ) -> Option<TenantDescribeResponse> {
    5530            0 :         let mut shard_zero = None;
    5531            0 :         let mut describe_shards = Vec::new();
    5532              : 
    5533            0 :         for shard in shards {
    5534            0 :             if shard.tenant_shard_id.is_shard_zero() {
    5535            0 :                 shard_zero = Some(shard);
    5536            0 :             }
    5537              : 
    5538            0 :             describe_shards.push(TenantDescribeResponseShard {
    5539            0 :                 tenant_shard_id: shard.tenant_shard_id,
    5540            0 :                 node_attached: *shard.intent.get_attached(),
    5541            0 :                 node_secondary: shard.intent.get_secondary().to_vec(),
    5542            0 :                 last_error: shard
    5543            0 :                     .last_error
    5544            0 :                     .lock()
    5545            0 :                     .unwrap()
    5546            0 :                     .as_ref()
    5547            0 :                     .map(|e| format!("{e}"))
    5548            0 :                     .unwrap_or("".to_string())
    5549            0 :                     .clone(),
    5550            0 :                 is_reconciling: shard.reconciler.is_some(),
    5551            0 :                 is_pending_compute_notification: shard.pending_compute_notification,
    5552            0 :                 is_splitting: matches!(shard.splitting, SplitState::Splitting),
    5553            0 :                 is_importing: shard.importing == TimelineImportState::Importing,
    5554            0 :                 scheduling_policy: shard.get_scheduling_policy(),
    5555            0 :                 preferred_az_id: shard.preferred_az().map(ToString::to_string),
    5556              :             })
    5557              :         }
    5558              : 
    5559            0 :         let shard_zero = shard_zero?;
    5560              : 
    5561            0 :         Some(TenantDescribeResponse {
    5562            0 :             tenant_id: shard_zero.tenant_shard_id.tenant_id,
    5563            0 :             shards: describe_shards,
    5564            0 :             stripe_size: shard_zero.shard.stripe_size,
    5565            0 :             policy: shard_zero.policy.clone(),
    5566            0 :             config: shard_zero.config.clone(),
    5567            0 :         })
    5568            0 :     }
    5569              : 
    5570            0 :     pub(crate) fn tenant_describe(
    5571            0 :         &self,
    5572            0 :         tenant_id: TenantId,
    5573            0 :     ) -> Result<TenantDescribeResponse, ApiError> {
    5574            0 :         let locked = self.inner.read().unwrap();
    5575              : 
    5576            0 :         self.tenant_describe_impl(
    5577            0 :             locked
    5578            0 :                 .tenants
    5579            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    5580            0 :                 .map(|(_k, v)| v),
    5581              :         )
    5582            0 :         .ok_or_else(|| ApiError::NotFound(anyhow::anyhow!("Tenant {tenant_id} not found").into()))
    5583            0 :     }
    5584              : 
    5585              :     /* BEGIN_HADRON */
    5586            0 :     pub(crate) async fn tenant_timeline_describe(
    5587            0 :         &self,
    5588            0 :         tenant_id: TenantId,
    5589            0 :         timeline_id: TimelineId,
    5590            0 :     ) -> Result<TenantTimelineDescribeResponse, ApiError> {
    5591            0 :         self.tenant_remote_mutation(tenant_id, |locations| async move {
    5592            0 :             if locations.0.is_empty() {
    5593            0 :                 return Err(ApiError::NotFound(
    5594            0 :                     anyhow::anyhow!("Tenant not found").into(),
    5595            0 :                 ));
    5596            0 :             };
    5597              : 
    5598            0 :             let locations: Vec<(TenantShardId, Node)> = locations
    5599            0 :                 .0
    5600            0 :                 .iter()
    5601            0 :                 .map(|t| (*t.0, t.1.latest.node.clone()))
    5602            0 :                 .collect();
    5603            0 :             let mut futs = FuturesUnordered::new();
    5604              : 
    5605            0 :             for (shard_id, node) in locations {
    5606            0 :                 futs.push({
    5607            0 :                     async move {
    5608            0 :                         let result = node
    5609            0 :                             .with_client_retries(
    5610            0 :                                 |client| async move {
    5611            0 :                                     client
    5612            0 :                                         .tenant_timeline_describe(&shard_id, &timeline_id)
    5613            0 :                                         .await
    5614            0 :                                 },
    5615            0 :                                 &self.http_client,
    5616            0 :                                 &self.config.pageserver_jwt_token,
    5617              :                                 3,
    5618              :                                 3,
    5619            0 :                                 Duration::from_secs(30),
    5620            0 :                                 &self.cancel,
    5621              :                             )
    5622            0 :                             .await;
    5623            0 :                         (result, shard_id, node.get_id())
    5624            0 :                     }
    5625              :                 });
    5626              :             }
    5627              : 
    5628            0 :             let mut results: Vec<TimelineInfo> = Vec::new();
    5629            0 :             while let Some((result, tenant_shard_id, node_id)) = futs.next().await {
    5630            0 :                 match result {
    5631            0 :                     Some(Ok(timeline_info)) => results.push(timeline_info),
    5632            0 :                     Some(Err(e)) => {
    5633            0 :                         tracing::warn!(
    5634            0 :                             "Failed to describe tenant {} timeline {} for pageserver {}: {e}",
    5635              :                             tenant_shard_id,
    5636              :                             timeline_id,
    5637              :                             node_id,
    5638              :                         );
    5639            0 :                         return Err(ApiError::ResourceUnavailable(format!("{e}").into()));
    5640              :                     }
    5641            0 :                     None => return Err(ApiError::Cancelled),
    5642              :                 }
    5643              :             }
    5644            0 :             let mut image_consistent_lsn: Option<Lsn> = Some(Lsn::MAX);
    5645            0 :             for timeline_info in &results {
    5646            0 :                 if let Some(tline_image_consistent_lsn) = timeline_info.image_consistent_lsn {
    5647            0 :                     image_consistent_lsn = Some(std::cmp::min(
    5648            0 :                         image_consistent_lsn.unwrap(),
    5649            0 :                         tline_image_consistent_lsn,
    5650            0 :                     ));
    5651            0 :                 } else {
    5652            0 :                     tracing::warn!(
    5653            0 :                         "Timeline {} on shard {} does not have image consistent lsn",
    5654              :                         timeline_info.timeline_id,
    5655              :                         timeline_info.tenant_id
    5656              :                     );
    5657            0 :                     image_consistent_lsn = None;
    5658            0 :                     break;
    5659              :                 }
    5660              :             }
    5661              : 
    5662            0 :             Ok(TenantTimelineDescribeResponse {
    5663            0 :                 shards: results,
    5664            0 :                 image_consistent_lsn,
    5665            0 :             })
    5666            0 :         })
    5667            0 :         .await?
    5668            0 :     }
    5669              :     /* END_HADRON */
    5670              : 
    5671              :     /// limit & offset are pagination parameters. Since we are walking an in-memory HashMap, `offset` does not
    5672              :     /// avoid traversing data, it just avoid returning it. This is suitable for our purposes, since our in memory
    5673              :     /// maps are small enough to traverse fast, our pagination is just to avoid serializing huge JSON responses
    5674              :     /// in our external API.
    5675            0 :     pub(crate) fn tenant_list(
    5676            0 :         &self,
    5677            0 :         limit: Option<usize>,
    5678            0 :         start_after: Option<TenantId>,
    5679            0 :     ) -> Vec<TenantDescribeResponse> {
    5680            0 :         let locked = self.inner.read().unwrap();
    5681              : 
    5682              :         // Apply start_from parameter
    5683            0 :         let shard_range = match start_after {
    5684            0 :             None => locked.tenants.range(..),
    5685            0 :             Some(tenant_id) => locked.tenants.range(
    5686            0 :                 TenantShardId {
    5687            0 :                     tenant_id,
    5688            0 :                     shard_number: ShardNumber(u8::MAX),
    5689            0 :                     shard_count: ShardCount(u8::MAX),
    5690            0 :                 }..,
    5691              :             ),
    5692              :         };
    5693              : 
    5694            0 :         let mut result = Vec::new();
    5695            0 :         for (_tenant_id, tenant_shards) in &shard_range.group_by(|(id, _shard)| id.tenant_id) {
    5696            0 :             result.push(
    5697            0 :                 self.tenant_describe_impl(tenant_shards.map(|(_k, v)| v))
    5698            0 :                     .expect("Groups are always non-empty"),
    5699              :             );
    5700              : 
    5701              :             // Enforce `limit` parameter
    5702            0 :             if let Some(limit) = limit {
    5703            0 :                 if result.len() >= limit {
    5704            0 :                     break;
    5705            0 :                 }
    5706            0 :             }
    5707              :         }
    5708              : 
    5709            0 :         result
    5710            0 :     }
    5711              : 
    5712              :     #[instrument(skip_all, fields(tenant_id=%op.tenant_id))]
    5713              :     async fn abort_tenant_shard_split(
    5714              :         &self,
    5715              :         op: &TenantShardSplitAbort,
    5716              :     ) -> Result<(), TenantShardSplitAbortError> {
    5717              :         // Cleaning up a split:
    5718              :         // - Parent shards are not destroyed during a split, just detached.
    5719              :         // - Failed pageserver split API calls can leave the remote node with just the parent attached,
    5720              :         //   just the children attached, or both.
    5721              :         //
    5722              :         // Therefore our work to do is to:
    5723              :         // 1. Clean up storage controller's internal state to just refer to parents, no children
    5724              :         // 2. Call out to pageservers to ensure that children are detached
    5725              :         // 3. Call out to pageservers to ensure that parents are attached.
    5726              :         //
    5727              :         // Crash safety:
    5728              :         // - If the storage controller stops running during this cleanup *after* clearing the splitting state
    5729              :         //   from our database, then [`Self::startup_reconcile`] will regard child attachments as garbage
    5730              :         //   and detach them.
    5731              :         // - TODO: If the storage controller stops running during this cleanup *before* clearing the splitting state
    5732              :         //   from our database, then we will re-enter this cleanup routine on startup.
    5733              : 
    5734              :         let TenantShardSplitAbort {
    5735              :             tenant_id,
    5736              :             new_shard_count,
    5737              :             new_stripe_size,
    5738              :             ..
    5739              :         } = op;
    5740              : 
    5741              :         // First abort persistent state, if any exists.
    5742              :         match self
    5743              :             .persistence
    5744              :             .abort_shard_split(*tenant_id, *new_shard_count)
    5745              :             .await?
    5746              :         {
    5747              :             AbortShardSplitStatus::Aborted => {
    5748              :                 // Proceed to roll back any child shards created on pageservers
    5749              :             }
    5750              :             AbortShardSplitStatus::Complete => {
    5751              :                 // The split completed (we might hit that path if e.g. our database transaction
    5752              :                 // to write the completion landed in the database, but we dropped connection
    5753              :                 // before seeing the result).
    5754              :                 //
    5755              :                 // We must update in-memory state to reflect the successful split.
    5756              :                 self.tenant_shard_split_commit_inmem(
    5757              :                     *tenant_id,
    5758              :                     *new_shard_count,
    5759              :                     *new_stripe_size,
    5760              :                 );
    5761              :                 return Ok(());
    5762              :             }
    5763              :         }
    5764              : 
    5765              :         // Clean up in-memory state, and accumulate the list of child locations that need detaching
    5766              :         let detach_locations: Vec<(Node, TenantShardId)> = {
    5767              :             let mut detach_locations = Vec::new();
    5768              :             let mut locked = self.inner.write().unwrap();
    5769              :             let (nodes, tenants, scheduler) = locked.parts_mut();
    5770              : 
    5771              :             for (tenant_shard_id, shard) in
    5772              :                 tenants.range_mut(TenantShardId::tenant_range(op.tenant_id))
    5773              :             {
    5774              :                 if shard.shard.count == op.new_shard_count {
    5775              :                     // Surprising: the phase of [`Self::do_tenant_shard_split`] which inserts child shards in-memory
    5776              :                     // is infallible, so if we got an error we shouldn't have got that far.
    5777              :                     tracing::warn!(
    5778              :                         "During split abort, child shard {tenant_shard_id} found in-memory"
    5779              :                     );
    5780              :                     continue;
    5781              :                 }
    5782              : 
    5783              :                 // Add the children of this shard to this list of things to detach
    5784              :                 if let Some(node_id) = shard.intent.get_attached() {
    5785              :                     for child_id in tenant_shard_id.split(*new_shard_count) {
    5786              :                         detach_locations.push((
    5787              :                             nodes
    5788              :                                 .get(node_id)
    5789              :                                 .expect("Intent references nonexistent node")
    5790              :                                 .clone(),
    5791              :                             child_id,
    5792              :                         ));
    5793              :                     }
    5794              :                 } else {
    5795              :                     tracing::warn!(
    5796              :                         "During split abort, shard {tenant_shard_id} has no attached location"
    5797              :                     );
    5798              :                 }
    5799              : 
    5800              :                 tracing::info!("Restoring parent shard {tenant_shard_id}");
    5801              : 
    5802              :                 // Drop any intents that refer to unavailable nodes, to enable this abort to proceed even
    5803              :                 // if the original attachment location is offline.
    5804              :                 if let Some(node_id) = shard.intent.get_attached() {
    5805              :                     if !nodes.get(node_id).unwrap().is_available() {
    5806              :                         tracing::info!(
    5807              :                             "Demoting attached intent for {tenant_shard_id} on unavailable node {node_id}"
    5808              :                         );
    5809              :                         shard.intent.demote_attached(scheduler, *node_id);
    5810              :                     }
    5811              :                 }
    5812              :                 for node_id in shard.intent.get_secondary().clone() {
    5813              :                     if !nodes.get(&node_id).unwrap().is_available() {
    5814              :                         tracing::info!(
    5815              :                             "Dropping secondary intent for {tenant_shard_id} on unavailable node {node_id}"
    5816              :                         );
    5817              :                         shard.intent.remove_secondary(scheduler, node_id);
    5818              :                     }
    5819              :                 }
    5820              : 
    5821              :                 shard.splitting = SplitState::Idle;
    5822              :                 if let Err(e) = shard.schedule(scheduler, &mut ScheduleContext::default()) {
    5823              :                     // If this shard can't be scheduled now (perhaps due to offline nodes or
    5824              :                     // capacity issues), that must not prevent us rolling back a split.  In this
    5825              :                     // case it should be eventually scheduled in the background.
    5826              :                     tracing::warn!("Failed to schedule {tenant_shard_id} during shard abort: {e}")
    5827              :                 }
    5828              : 
    5829              :                 self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
    5830              :             }
    5831              : 
    5832              :             // We don't expect any new_shard_count shards to exist here, but drop them just in case
    5833              :             tenants
    5834            0 :                 .retain(|id, s| !(id.tenant_id == *tenant_id && s.shard.count == *new_shard_count));
    5835              : 
    5836              :             detach_locations
    5837              :         };
    5838              : 
    5839              :         for (node, child_id) in detach_locations {
    5840              :             if !node.is_available() {
    5841              :                 // An unavailable node cannot be cleaned up now: to avoid blocking forever, we will permit this, and
    5842              :                 // rely on the reconciliation that happens when a node transitions to Active to clean up. Since we have
    5843              :                 // removed child shards from our in-memory state and database, the reconciliation will implicitly remove
    5844              :                 // them from the node.
    5845              :                 tracing::warn!(
    5846              :                     "Node {node} unavailable, can't clean up during split abort. It will be cleaned up when it is reactivated."
    5847              :                 );
    5848              :                 continue;
    5849              :             }
    5850              : 
    5851              :             // Detach the remote child.  If the pageserver split API call is still in progress, this call will get
    5852              :             // a 503 and retry, up to our limit.
    5853              :             tracing::info!("Detaching {child_id} on {node}...");
    5854              :             match node
    5855              :                 .with_client_retries(
    5856            0 :                     |client| async move {
    5857            0 :                         let config = LocationConfig {
    5858            0 :                             mode: LocationConfigMode::Detached,
    5859            0 :                             generation: None,
    5860            0 :                             secondary_conf: None,
    5861            0 :                             shard_number: child_id.shard_number.0,
    5862            0 :                             shard_count: child_id.shard_count.literal(),
    5863            0 :                             // Stripe size and tenant config don't matter when detaching
    5864            0 :                             shard_stripe_size: 0,
    5865            0 :                             tenant_conf: TenantConfig::default(),
    5866            0 :                         };
    5867              : 
    5868            0 :                         client.location_config(child_id, config, None, false).await
    5869            0 :                     },
    5870              :                     &self.http_client,
    5871              :                     &self.config.pageserver_jwt_token,
    5872              :                     1,
    5873              :                     10,
    5874              :                     Duration::from_secs(5),
    5875              :                     &self.reconcilers_cancel,
    5876              :                 )
    5877              :                 .await
    5878              :             {
    5879              :                 Some(Ok(_)) => {}
    5880              :                 Some(Err(e)) => {
    5881              :                     // We failed to communicate with the remote node.  This is problematic: we may be
    5882              :                     // leaving it with a rogue child shard.
    5883              :                     tracing::warn!(
    5884              :                         "Failed to detach child {child_id} from node {node} during abort"
    5885              :                     );
    5886              :                     return Err(e.into());
    5887              :                 }
    5888              :                 None => {
    5889              :                     // Cancellation: we were shutdown or the node went offline. Shutdown is fine, we'll
    5890              :                     // clean up on restart. The node going offline requires a retry.
    5891              :                     return Err(TenantShardSplitAbortError::Unavailable);
    5892              :                 }
    5893              :             };
    5894              :         }
    5895              : 
    5896              :         tracing::info!("Successfully aborted split");
    5897              :         Ok(())
    5898              :     }
    5899              : 
    5900              :     /// Infallible final stage of [`Self::tenant_shard_split`]: update the contents
    5901              :     /// of the tenant map to reflect the child shards that exist after the split.
    5902            0 :     fn tenant_shard_split_commit_inmem(
    5903            0 :         &self,
    5904            0 :         tenant_id: TenantId,
    5905            0 :         new_shard_count: ShardCount,
    5906            0 :         new_stripe_size: Option<ShardStripeSize>,
    5907            0 :     ) -> (
    5908            0 :         TenantShardSplitResponse,
    5909            0 :         Vec<(TenantShardId, NodeId, ShardStripeSize)>,
    5910            0 :         Vec<ReconcilerWaiter>,
    5911            0 :     ) {
    5912            0 :         let mut response = TenantShardSplitResponse {
    5913            0 :             new_shards: Vec::new(),
    5914            0 :         };
    5915            0 :         let mut child_locations = Vec::new();
    5916            0 :         let mut waiters = Vec::new();
    5917              : 
    5918              :         {
    5919            0 :             let mut locked = self.inner.write().unwrap();
    5920              : 
    5921            0 :             let parent_ids = locked
    5922            0 :                 .tenants
    5923            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    5924            0 :                 .map(|(shard_id, _)| *shard_id)
    5925            0 :                 .collect::<Vec<_>>();
    5926              : 
    5927            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    5928            0 :             for parent_id in parent_ids {
    5929            0 :                 let child_ids = parent_id.split(new_shard_count);
    5930              : 
    5931              :                 let (
    5932            0 :                     pageserver,
    5933            0 :                     generation,
    5934            0 :                     policy,
    5935            0 :                     parent_ident,
    5936            0 :                     config,
    5937            0 :                     preferred_az,
    5938            0 :                     secondary_count,
    5939              :                 ) = {
    5940            0 :                     let mut old_state = tenants
    5941            0 :                         .remove(&parent_id)
    5942            0 :                         .expect("It was present, we just split it");
    5943              : 
    5944              :                     // A non-splitting state is impossible, because [`Self::tenant_shard_split`] holds
    5945              :                     // a TenantId lock and passes it through to [`TenantShardSplitAbort`] in case of cleanup:
    5946              :                     // nothing else can clear this.
    5947            0 :                     assert!(matches!(old_state.splitting, SplitState::Splitting));
    5948              : 
    5949            0 :                     let old_attached = old_state.intent.get_attached().unwrap();
    5950            0 :                     old_state.intent.clear(scheduler);
    5951            0 :                     let generation = old_state.generation.expect("Shard must have been attached");
    5952            0 :                     (
    5953            0 :                         old_attached,
    5954            0 :                         generation,
    5955            0 :                         old_state.policy.clone(),
    5956            0 :                         old_state.shard,
    5957            0 :                         old_state.config.clone(),
    5958            0 :                         old_state.preferred_az().cloned(),
    5959            0 :                         old_state.intent.get_secondary().len(),
    5960            0 :                     )
    5961              :                 };
    5962              : 
    5963            0 :                 let mut schedule_context = ScheduleContext::default();
    5964            0 :                 for child in child_ids {
    5965            0 :                     let mut child_shard = parent_ident;
    5966            0 :                     child_shard.number = child.shard_number;
    5967            0 :                     child_shard.count = child.shard_count;
    5968            0 :                     if let Some(stripe_size) = new_stripe_size {
    5969            0 :                         child_shard.stripe_size = stripe_size;
    5970            0 :                     }
    5971              : 
    5972            0 :                     let mut child_observed: HashMap<NodeId, ObservedStateLocation> = HashMap::new();
    5973            0 :                     child_observed.insert(
    5974            0 :                         pageserver,
    5975            0 :                         ObservedStateLocation {
    5976            0 :                             conf: Some(attached_location_conf(
    5977            0 :                                 generation,
    5978            0 :                                 &child_shard,
    5979            0 :                                 &config,
    5980            0 :                                 &policy,
    5981            0 :                                 secondary_count,
    5982            0 :                             )),
    5983            0 :                         },
    5984              :                     );
    5985              : 
    5986            0 :                     let mut child_state =
    5987            0 :                         TenantShard::new(child, child_shard, policy.clone(), preferred_az.clone());
    5988            0 :                     child_state.intent =
    5989            0 :                         IntentState::single(scheduler, Some(pageserver), preferred_az.clone());
    5990            0 :                     child_state.observed = ObservedState {
    5991            0 :                         locations: child_observed,
    5992            0 :                     };
    5993            0 :                     child_state.generation = Some(generation);
    5994            0 :                     child_state.config = config.clone();
    5995              : 
    5996              :                     // The child's TenantShard::splitting is intentionally left at the default value of Idle,
    5997              :                     // as at this point in the split process we have succeeded and this part is infallible:
    5998              :                     // we will never need to do any special recovery from this state.
    5999              : 
    6000            0 :                     child_locations.push((child, pageserver, child_shard.stripe_size));
    6001              : 
    6002            0 :                     if let Err(e) = child_state.schedule(scheduler, &mut schedule_context) {
    6003              :                         // This is not fatal, because we've implicitly already got an attached
    6004              :                         // location for the child shard.  Failure here just means we couldn't
    6005              :                         // find a secondary (e.g. because cluster is overloaded).
    6006            0 :                         tracing::warn!("Failed to schedule child shard {child}: {e}");
    6007            0 :                     }
    6008              :                     // In the background, attach secondary locations for the new shards
    6009            0 :                     if let Some(waiter) = self.maybe_reconcile_shard(
    6010            0 :                         &mut child_state,
    6011            0 :                         nodes,
    6012            0 :                         ReconcilerPriority::High,
    6013            0 :                     ) {
    6014            0 :                         waiters.push(waiter);
    6015            0 :                     }
    6016              : 
    6017            0 :                     tenants.insert(child, child_state);
    6018            0 :                     response.new_shards.push(child);
    6019              :                 }
    6020              :             }
    6021            0 :             (response, child_locations, waiters)
    6022              :         }
    6023            0 :     }
    6024              : 
    6025            0 :     async fn tenant_shard_split_start_secondaries(
    6026            0 :         &self,
    6027            0 :         tenant_id: TenantId,
    6028            0 :         waiters: Vec<ReconcilerWaiter>,
    6029            0 :     ) {
    6030              :         // Wait for initial reconcile of child shards, this creates the secondary locations
    6031            0 :         if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    6032              :             // This is not a failure to split: it's some issue reconciling the new child shards, perhaps
    6033              :             // their secondaries couldn't be attached.
    6034            0 :             tracing::warn!("Failed to reconcile after split: {e}");
    6035            0 :             return;
    6036            0 :         }
    6037              : 
    6038              :         // Take the state lock to discover the attached & secondary intents for all shards
    6039            0 :         let (attached, secondary) = {
    6040            0 :             let locked = self.inner.read().unwrap();
    6041            0 :             let mut attached = Vec::new();
    6042            0 :             let mut secondary = Vec::new();
    6043              : 
    6044            0 :             for (tenant_shard_id, shard) in
    6045            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    6046              :             {
    6047            0 :                 let Some(node_id) = shard.intent.get_attached() else {
    6048              :                     // Unexpected.  Race with a PlacementPolicy change?
    6049            0 :                     tracing::warn!(
    6050            0 :                         "No attached node on {tenant_shard_id} immediately after shard split!"
    6051              :                     );
    6052            0 :                     continue;
    6053              :                 };
    6054              : 
    6055            0 :                 let Some(secondary_node_id) = shard.intent.get_secondary().first() else {
    6056              :                     // No secondary location.  Nothing for us to do.
    6057            0 :                     continue;
    6058              :                 };
    6059              : 
    6060            0 :                 let attached_node = locked
    6061            0 :                     .nodes
    6062            0 :                     .get(node_id)
    6063            0 :                     .expect("Pageservers may not be deleted while referenced");
    6064              : 
    6065            0 :                 let secondary_node = locked
    6066            0 :                     .nodes
    6067            0 :                     .get(secondary_node_id)
    6068            0 :                     .expect("Pageservers may not be deleted while referenced");
    6069              : 
    6070            0 :                 attached.push((*tenant_shard_id, attached_node.clone()));
    6071            0 :                 secondary.push((*tenant_shard_id, secondary_node.clone()));
    6072              :             }
    6073            0 :             (attached, secondary)
    6074              :         };
    6075              : 
    6076            0 :         if secondary.is_empty() {
    6077              :             // No secondary locations; nothing for us to do
    6078            0 :             return;
    6079            0 :         }
    6080              : 
    6081            0 :         for (_, result) in self
    6082            0 :             .tenant_for_shards_api(
    6083            0 :                 attached,
    6084            0 :                 |tenant_shard_id, client| async move {
    6085            0 :                     client.tenant_heatmap_upload(tenant_shard_id).await
    6086            0 :                 },
    6087              :                 1,
    6088              :                 1,
    6089              :                 SHORT_RECONCILE_TIMEOUT,
    6090            0 :                 &self.cancel,
    6091              :             )
    6092            0 :             .await
    6093              :         {
    6094            0 :             if let Err(e) = result {
    6095            0 :                 tracing::warn!("Error calling heatmap upload after shard split: {e}");
    6096            0 :                 return;
    6097            0 :             }
    6098              :         }
    6099              : 
    6100            0 :         for (_, result) in self
    6101            0 :             .tenant_for_shards_api(
    6102            0 :                 secondary,
    6103            0 :                 |tenant_shard_id, client| async move {
    6104            0 :                     client
    6105            0 :                         .tenant_secondary_download(tenant_shard_id, Some(Duration::ZERO))
    6106            0 :                         .await
    6107            0 :                 },
    6108              :                 1,
    6109              :                 1,
    6110              :                 SHORT_RECONCILE_TIMEOUT,
    6111            0 :                 &self.cancel,
    6112              :             )
    6113            0 :             .await
    6114              :         {
    6115            0 :             if let Err(e) = result {
    6116            0 :                 tracing::warn!("Error calling secondary download after shard split: {e}");
    6117            0 :                 return;
    6118            0 :             }
    6119              :         }
    6120            0 :     }
    6121              : 
    6122            0 :     pub(crate) async fn tenant_shard_split(
    6123            0 :         &self,
    6124            0 :         tenant_id: TenantId,
    6125            0 :         split_req: TenantShardSplitRequest,
    6126            0 :     ) -> Result<TenantShardSplitResponse, ApiError> {
    6127              :         // TODO: return 503 if we get stuck waiting for this lock
    6128              :         // (issue https://github.com/neondatabase/neon/issues/7108)
    6129            0 :         let _tenant_lock = trace_exclusive_lock(
    6130            0 :             &self.tenant_op_locks,
    6131            0 :             tenant_id,
    6132            0 :             TenantOperations::ShardSplit,
    6133            0 :         )
    6134            0 :         .await;
    6135              : 
    6136            0 :         let _gate = self
    6137            0 :             .reconcilers_gate
    6138            0 :             .enter()
    6139            0 :             .map_err(|_| ApiError::ShuttingDown)?;
    6140              : 
    6141              :         // Timeline imports on the pageserver side can't handle shard-splits.
    6142              :         // If the tenant is importing a timeline, dont't shard split it.
    6143            0 :         match self
    6144            0 :             .persistence
    6145            0 :             .is_tenant_importing_timeline(tenant_id)
    6146            0 :             .await
    6147              :         {
    6148            0 :             Ok(importing) => {
    6149            0 :                 if importing {
    6150            0 :                     return Err(ApiError::Conflict(
    6151            0 :                         "Cannot shard split during timeline import".to_string(),
    6152            0 :                     ));
    6153            0 :                 }
    6154              :             }
    6155            0 :             Err(err) => {
    6156            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    6157            0 :                     "Failed to check for running imports: {err}"
    6158            0 :                 )));
    6159              :             }
    6160              :         }
    6161              : 
    6162            0 :         let new_shard_count = ShardCount::new(split_req.new_shard_count);
    6163            0 :         let new_stripe_size = split_req.new_stripe_size;
    6164              : 
    6165              :         // Validate the request and construct parameters.  This phase is fallible, but does not require
    6166              :         // rollback on errors, as it does no I/O and mutates no state.
    6167            0 :         let shard_split_params = match self.prepare_tenant_shard_split(tenant_id, split_req)? {
    6168            0 :             ShardSplitAction::NoOp(resp) => return Ok(resp),
    6169            0 :             ShardSplitAction::Split(params) => params,
    6170              :         };
    6171              : 
    6172              :         // Execute this split: this phase mutates state and does remote I/O on pageservers.  If it fails,
    6173              :         // we must roll back.
    6174            0 :         let r = self
    6175            0 :             .do_tenant_shard_split(tenant_id, shard_split_params)
    6176            0 :             .await;
    6177              : 
    6178            0 :         let (response, waiters) = match r {
    6179            0 :             Ok(r) => r,
    6180            0 :             Err(e) => {
    6181              :                 // Split might be part-done, we must do work to abort it.
    6182            0 :                 tracing::warn!("Enqueuing background abort of split on {tenant_id}");
    6183            0 :                 self.abort_tx
    6184            0 :                     .send(TenantShardSplitAbort {
    6185            0 :                         tenant_id,
    6186            0 :                         new_shard_count,
    6187            0 :                         new_stripe_size,
    6188            0 :                         _tenant_lock,
    6189            0 :                         _gate,
    6190            0 :                     })
    6191              :                     // Ignore error sending: that just means we're shutting down: aborts are ephemeral so it's fine to drop it.
    6192            0 :                     .ok();
    6193            0 :                 return Err(e);
    6194              :             }
    6195              :         };
    6196              : 
    6197              :         // The split is now complete.  As an optimization, we will trigger all the child shards to upload
    6198              :         // a heatmap immediately, and all their secondary locations to start downloading: this avoids waiting
    6199              :         // for the background heatmap/download interval before secondaries get warm enough to migrate shards
    6200              :         // in [`Self::optimize_all`]
    6201            0 :         self.tenant_shard_split_start_secondaries(tenant_id, waiters)
    6202            0 :             .await;
    6203            0 :         Ok(response)
    6204            0 :     }
    6205              : 
    6206            0 :     fn prepare_tenant_shard_split(
    6207            0 :         &self,
    6208            0 :         tenant_id: TenantId,
    6209            0 :         split_req: TenantShardSplitRequest,
    6210            0 :     ) -> Result<ShardSplitAction, ApiError> {
    6211            0 :         fail::fail_point!("shard-split-validation", |_| Err(ApiError::BadRequest(
    6212            0 :             anyhow::anyhow!("failpoint")
    6213            0 :         )));
    6214              : 
    6215            0 :         let mut policy = None;
    6216            0 :         let mut config = None;
    6217            0 :         let mut shard_ident = None;
    6218            0 :         let mut preferred_az_id = None;
    6219              :         // Validate input, and calculate which shards we will create
    6220            0 :         let (old_shard_count, targets) =
    6221              :             {
    6222            0 :                 let locked = self.inner.read().unwrap();
    6223              : 
    6224            0 :                 let pageservers = locked.nodes.clone();
    6225              : 
    6226            0 :                 let mut targets = Vec::new();
    6227              : 
    6228              :                 // In case this is a retry, count how many already-split shards we found
    6229            0 :                 let mut children_found = Vec::new();
    6230            0 :                 let mut old_shard_count = None;
    6231              : 
    6232            0 :                 for (tenant_shard_id, shard) in
    6233            0 :                     locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    6234              :                 {
    6235            0 :                     match shard.shard.count.count().cmp(&split_req.new_shard_count) {
    6236              :                         Ordering::Equal => {
    6237              :                             //  Already split this
    6238            0 :                             children_found.push(*tenant_shard_id);
    6239            0 :                             continue;
    6240              :                         }
    6241              :                         Ordering::Greater => {
    6242            0 :                             return Err(ApiError::BadRequest(anyhow::anyhow!(
    6243            0 :                                 "Requested count {} but already have shards at count {}",
    6244            0 :                                 split_req.new_shard_count,
    6245            0 :                                 shard.shard.count.count()
    6246            0 :                             )));
    6247              :                         }
    6248            0 :                         Ordering::Less => {
    6249            0 :                             // Fall through: this shard has lower count than requested,
    6250            0 :                             // is a candidate for splitting.
    6251            0 :                         }
    6252              :                     }
    6253              : 
    6254            0 :                     match old_shard_count {
    6255            0 :                         None => old_shard_count = Some(shard.shard.count),
    6256            0 :                         Some(old_shard_count) => {
    6257            0 :                             if old_shard_count != shard.shard.count {
    6258              :                                 // We may hit this case if a caller asked for two splits to
    6259              :                                 // different sizes, before the first one is complete.
    6260              :                                 // e.g. 1->2, 2->4, where the 4 call comes while we have a mixture
    6261              :                                 // of shard_count=1 and shard_count=2 shards in the map.
    6262            0 :                                 return Err(ApiError::Conflict(
    6263            0 :                                     "Cannot split, currently mid-split".to_string(),
    6264            0 :                                 ));
    6265            0 :                             }
    6266              :                         }
    6267              :                     }
    6268            0 :                     if policy.is_none() {
    6269            0 :                         policy = Some(shard.policy.clone());
    6270            0 :                     }
    6271            0 :                     if shard_ident.is_none() {
    6272            0 :                         shard_ident = Some(shard.shard);
    6273            0 :                     }
    6274            0 :                     if config.is_none() {
    6275            0 :                         config = Some(shard.config.clone());
    6276            0 :                     }
    6277            0 :                     if preferred_az_id.is_none() {
    6278            0 :                         preferred_az_id = shard.preferred_az().cloned();
    6279            0 :                     }
    6280              : 
    6281            0 :                     if tenant_shard_id.shard_count.count() == split_req.new_shard_count {
    6282            0 :                         tracing::info!(
    6283            0 :                             "Tenant shard {} already has shard count {}",
    6284              :                             tenant_shard_id,
    6285              :                             split_req.new_shard_count
    6286              :                         );
    6287            0 :                         continue;
    6288            0 :                     }
    6289              : 
    6290            0 :                     let node_id = shard.intent.get_attached().ok_or(ApiError::BadRequest(
    6291            0 :                         anyhow::anyhow!("Cannot split a tenant that is not attached"),
    6292            0 :                     ))?;
    6293              : 
    6294            0 :                     let node = pageservers
    6295            0 :                         .get(&node_id)
    6296            0 :                         .expect("Pageservers may not be deleted while referenced");
    6297              : 
    6298            0 :                     targets.push(ShardSplitTarget {
    6299            0 :                         parent_id: *tenant_shard_id,
    6300            0 :                         node: node.clone(),
    6301            0 :                         child_ids: tenant_shard_id
    6302            0 :                             .split(ShardCount::new(split_req.new_shard_count)),
    6303            0 :                     });
    6304              :                 }
    6305              : 
    6306            0 :                 if targets.is_empty() {
    6307            0 :                     if children_found.len() == split_req.new_shard_count as usize {
    6308            0 :                         return Ok(ShardSplitAction::NoOp(TenantShardSplitResponse {
    6309            0 :                             new_shards: children_found,
    6310            0 :                         }));
    6311              :                     } else {
    6312              :                         // No shards found to split, and no existing children found: the
    6313              :                         // tenant doesn't exist at all.
    6314            0 :                         return Err(ApiError::NotFound(
    6315            0 :                             anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    6316            0 :                         ));
    6317              :                     }
    6318            0 :                 }
    6319              : 
    6320            0 :                 (old_shard_count, targets)
    6321              :             };
    6322              : 
    6323              :         // unwrap safety: we would have returned above if we didn't find at least one shard to split
    6324            0 :         let old_shard_count = old_shard_count.unwrap();
    6325            0 :         let shard_ident = if let Some(new_stripe_size) = split_req.new_stripe_size {
    6326              :             // This ShardIdentity will be used as the template for all children, so this implicitly
    6327              :             // applies the new stripe size to the children.
    6328            0 :             let mut shard_ident = shard_ident.unwrap();
    6329            0 :             if shard_ident.count.count() > 1 && shard_ident.stripe_size != new_stripe_size {
    6330            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    6331            0 :                     "Attempted to change stripe size ({:?}->{new_stripe_size:?}) on a tenant with multiple shards",
    6332            0 :                     shard_ident.stripe_size
    6333            0 :                 )));
    6334            0 :             }
    6335              : 
    6336            0 :             shard_ident.stripe_size = new_stripe_size;
    6337            0 :             tracing::info!("applied  stripe size {}", shard_ident.stripe_size.0);
    6338            0 :             shard_ident
    6339              :         } else {
    6340            0 :             shard_ident.unwrap()
    6341              :         };
    6342            0 :         let policy = policy.unwrap();
    6343            0 :         let config = config.unwrap();
    6344              : 
    6345            0 :         Ok(ShardSplitAction::Split(Box::new(ShardSplitParams {
    6346            0 :             old_shard_count,
    6347            0 :             new_shard_count: ShardCount::new(split_req.new_shard_count),
    6348            0 :             new_stripe_size: split_req.new_stripe_size,
    6349            0 :             targets,
    6350            0 :             policy,
    6351            0 :             config,
    6352            0 :             shard_ident,
    6353            0 :             preferred_az_id,
    6354            0 :         })))
    6355            0 :     }
    6356              : 
    6357            0 :     async fn do_tenant_shard_split(
    6358            0 :         &self,
    6359            0 :         tenant_id: TenantId,
    6360            0 :         params: Box<ShardSplitParams>,
    6361            0 :     ) -> Result<(TenantShardSplitResponse, Vec<ReconcilerWaiter>), ApiError> {
    6362              :         // FIXME: we have dropped self.inner lock, and not yet written anything to the database: another
    6363              :         // request could occur here, deleting or mutating the tenant.  begin_shard_split checks that the
    6364              :         // parent shards exist as expected, but it would be neater to do the above pre-checks within the
    6365              :         // same database transaction rather than pre-check in-memory and then maybe-fail the database write.
    6366              :         // (https://github.com/neondatabase/neon/issues/6676)
    6367              : 
    6368              :         let ShardSplitParams {
    6369            0 :             old_shard_count,
    6370            0 :             new_shard_count,
    6371            0 :             new_stripe_size,
    6372            0 :             mut targets,
    6373            0 :             policy,
    6374            0 :             config,
    6375            0 :             shard_ident,
    6376            0 :             preferred_az_id,
    6377            0 :         } = *params;
    6378              : 
    6379              :         // Drop any secondary locations: pageservers do not support splitting these, and in any case the
    6380              :         // end-state for a split tenant will usually be to have secondary locations on different nodes.
    6381              :         // The reconciliation calls in this block also implicitly cancel+barrier wrt any ongoing reconciliation
    6382              :         // at the time of split.
    6383            0 :         let waiters = {
    6384            0 :             let mut locked = self.inner.write().unwrap();
    6385            0 :             let mut waiters = Vec::new();
    6386            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    6387            0 :             for target in &mut targets {
    6388            0 :                 let Some(shard) = tenants.get_mut(&target.parent_id) else {
    6389              :                     // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
    6390            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    6391            0 :                         "Shard {} not found",
    6392            0 :                         target.parent_id
    6393            0 :                     )));
    6394              :                 };
    6395              : 
    6396            0 :                 if shard.intent.get_attached() != &Some(target.node.get_id()) {
    6397              :                     // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
    6398            0 :                     return Err(ApiError::Conflict(format!(
    6399            0 :                         "Shard {} unexpectedly rescheduled during split",
    6400            0 :                         target.parent_id
    6401            0 :                     )));
    6402            0 :                 }
    6403              : 
    6404              :                 // Irrespective of PlacementPolicy, clear secondary locations from intent
    6405            0 :                 shard.intent.clear_secondary(scheduler);
    6406              : 
    6407              :                 // Run Reconciler to execute detach fo secondary locations.
    6408            0 :                 if let Some(waiter) =
    6409            0 :                     self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
    6410            0 :                 {
    6411            0 :                     waiters.push(waiter);
    6412            0 :                 }
    6413              :             }
    6414            0 :             waiters
    6415              :         };
    6416            0 :         self.await_waiters(waiters, RECONCILE_TIMEOUT).await?;
    6417              : 
    6418              :         // Before creating any new child shards in memory or on the pageservers, persist them: this
    6419              :         // enables us to ensure that we will always be able to clean up if something goes wrong.  This also
    6420              :         // acts as the protection against two concurrent attempts to split: one of them will get a database
    6421              :         // error trying to insert the child shards.
    6422            0 :         let mut child_tsps = Vec::new();
    6423            0 :         for target in &targets {
    6424            0 :             let mut this_child_tsps = Vec::new();
    6425            0 :             for child in &target.child_ids {
    6426            0 :                 let mut child_shard = shard_ident;
    6427            0 :                 child_shard.number = child.shard_number;
    6428            0 :                 child_shard.count = child.shard_count;
    6429              : 
    6430            0 :                 tracing::info!(
    6431            0 :                     "Create child shard persistence with stripe size {}",
    6432              :                     shard_ident.stripe_size.0
    6433              :                 );
    6434              : 
    6435            0 :                 this_child_tsps.push(TenantShardPersistence {
    6436            0 :                     tenant_id: child.tenant_id.to_string(),
    6437            0 :                     shard_number: child.shard_number.0 as i32,
    6438            0 :                     shard_count: child.shard_count.literal() as i32,
    6439            0 :                     shard_stripe_size: shard_ident.stripe_size.0 as i32,
    6440              :                     // Note: this generation is a placeholder, [`Persistence::begin_shard_split`] will
    6441              :                     // populate the correct generation as part of its transaction, to protect us
    6442              :                     // against racing with changes in the state of the parent.
    6443            0 :                     generation: None,
    6444            0 :                     generation_pageserver: Some(target.node.get_id().0 as i64),
    6445            0 :                     placement_policy: serde_json::to_string(&policy).unwrap(),
    6446            0 :                     config: serde_json::to_string(&config).unwrap(),
    6447            0 :                     splitting: SplitState::Splitting,
    6448              : 
    6449              :                     // Scheduling policies and preferred AZ do not carry through to children
    6450            0 :                     scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    6451            0 :                         .unwrap(),
    6452            0 :                     preferred_az_id: preferred_az_id.as_ref().map(|az| az.0.clone()),
    6453              :                 });
    6454              :             }
    6455              : 
    6456            0 :             child_tsps.push((target.parent_id, this_child_tsps));
    6457              :         }
    6458              : 
    6459            0 :         if let Err(e) = self
    6460            0 :             .persistence
    6461            0 :             .begin_shard_split(old_shard_count, tenant_id, child_tsps)
    6462            0 :             .await
    6463              :         {
    6464            0 :             match e {
    6465              :                 DatabaseError::Query(diesel::result::Error::DatabaseError(
    6466              :                     DatabaseErrorKind::UniqueViolation,
    6467              :                     _,
    6468              :                 )) => {
    6469              :                     // Inserting a child shard violated a unique constraint: we raced with another call to
    6470              :                     // this function
    6471            0 :                     tracing::warn!("Conflicting attempt to split {tenant_id}: {e}");
    6472            0 :                     return Err(ApiError::Conflict("Tenant is already splitting".into()));
    6473              :                 }
    6474            0 :                 _ => return Err(ApiError::InternalServerError(e.into())),
    6475              :             }
    6476            0 :         }
    6477            0 :         fail::fail_point!("shard-split-post-begin", |_| Err(
    6478            0 :             ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
    6479              :         ));
    6480              : 
    6481              :         // Now that I have persisted the splitting state, apply it in-memory.  This is infallible, so
    6482              :         // callers may assume that if splitting is set in memory, then it was persisted, and if splitting
    6483              :         // is not set in memory, then it was not persisted.
    6484              :         {
    6485            0 :             let mut locked = self.inner.write().unwrap();
    6486            0 :             for target in &targets {
    6487            0 :                 if let Some(parent_shard) = locked.tenants.get_mut(&target.parent_id) {
    6488            0 :                     parent_shard.splitting = SplitState::Splitting;
    6489            0 :                     // Put the observed state to None, to reflect that it is indeterminate once we start the
    6490            0 :                     // split operation.
    6491            0 :                     parent_shard
    6492            0 :                         .observed
    6493            0 :                         .locations
    6494            0 :                         .insert(target.node.get_id(), ObservedStateLocation { conf: None });
    6495            0 :                 }
    6496              :             }
    6497              :         }
    6498              : 
    6499              :         // TODO: issue split calls concurrently (this only matters once we're splitting
    6500              :         // N>1 shards into M shards -- initially we're usually splitting 1 shard into N).
    6501              : 
    6502              :         // HADRON: set a timeout for splitting individual shards on page servers.
    6503              :         // Currently we do not perform any retry because it's not clear if page server can handle
    6504              :         // partially split shards correctly.
    6505            0 :         let shard_split_timeout =
    6506            0 :             if let Some(env::DeploymentMode::Local) = env::get_deployment_mode() {
    6507            0 :                 Duration::from_secs(30)
    6508              :             } else {
    6509            0 :                 self.config.shard_split_request_timeout
    6510              :             };
    6511            0 :         let mut http_client_builder = reqwest::ClientBuilder::new()
    6512            0 :             .pool_max_idle_per_host(0)
    6513            0 :             .timeout(shard_split_timeout);
    6514              : 
    6515            0 :         for ssl_ca_cert in &self.config.ssl_ca_certs {
    6516            0 :             http_client_builder = http_client_builder.add_root_certificate(ssl_ca_cert.clone());
    6517            0 :         }
    6518            0 :         let http_client = http_client_builder
    6519            0 :             .build()
    6520            0 :             .expect("Failed to construct HTTP client");
    6521            0 :         for target in &targets {
    6522              :             let ShardSplitTarget {
    6523            0 :                 parent_id,
    6524            0 :                 node,
    6525            0 :                 child_ids,
    6526            0 :             } = target;
    6527              : 
    6528            0 :             let client = PageserverClient::new(
    6529            0 :                 node.get_id(),
    6530            0 :                 http_client.clone(),
    6531            0 :                 node.base_url(),
    6532            0 :                 self.config.pageserver_jwt_token.as_deref(),
    6533              :             );
    6534              : 
    6535            0 :             let response = client
    6536            0 :                 .tenant_shard_split(
    6537            0 :                     *parent_id,
    6538            0 :                     TenantShardSplitRequest {
    6539            0 :                         new_shard_count: new_shard_count.literal(),
    6540            0 :                         new_stripe_size,
    6541            0 :                     },
    6542            0 :                 )
    6543            0 :                 .await
    6544            0 :                 .map_err(|e| ApiError::Conflict(format!("Failed to split {parent_id}: {e}")))?;
    6545              : 
    6546            0 :             fail::fail_point!("shard-split-post-remote", |_| Err(ApiError::Conflict(
    6547            0 :                 "failpoint".to_string()
    6548            0 :             )));
    6549              : 
    6550            0 :             failpoint_support::sleep_millis_async!(
    6551              :                 "shard-split-post-remote-sleep",
    6552            0 :                 &self.reconcilers_cancel
    6553              :             );
    6554              : 
    6555            0 :             tracing::info!(
    6556            0 :                 "Split {} into {}",
    6557              :                 parent_id,
    6558            0 :                 response
    6559            0 :                     .new_shards
    6560            0 :                     .iter()
    6561            0 :                     .map(|s| format!("{s:?}"))
    6562            0 :                     .collect::<Vec<_>>()
    6563            0 :                     .join(",")
    6564              :             );
    6565              : 
    6566            0 :             if &response.new_shards != child_ids {
    6567              :                 // This should never happen: the pageserver should agree with us on how shard splits work.
    6568            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    6569            0 :                     "Splitting shard {} resulted in unexpected IDs: {:?} (expected {:?})",
    6570            0 :                     parent_id,
    6571            0 :                     response.new_shards,
    6572            0 :                     child_ids
    6573            0 :                 )));
    6574            0 :             }
    6575              :         }
    6576              : 
    6577            0 :         fail::fail_point!("shard-split-pre-complete", |_| Err(ApiError::Conflict(
    6578            0 :             "failpoint".to_string()
    6579            0 :         )));
    6580              : 
    6581            0 :         pausable_failpoint!("shard-split-pre-complete-pause");
    6582              : 
    6583              :         // TODO: if the pageserver restarted concurrently with our split API call,
    6584              :         // the actual generation of the child shard might differ from the generation
    6585              :         // we expect it to have.  In order for our in-database generation to end up
    6586              :         // correct, we should carry the child generation back in the response and apply it here
    6587              :         // in complete_shard_split (and apply the correct generation in memory)
    6588              :         // (or, we can carry generation in the request and reject the request if
    6589              :         //  it doesn't match, but that requires more retry logic on this side)
    6590              : 
    6591            0 :         self.persistence
    6592            0 :             .complete_shard_split(tenant_id, old_shard_count, new_shard_count)
    6593            0 :             .await?;
    6594              : 
    6595            0 :         fail::fail_point!("shard-split-post-complete", |_| Err(
    6596            0 :             ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
    6597              :         ));
    6598              : 
    6599              :         // Replace all the shards we just split with their children: this phase is infallible.
    6600            0 :         let (response, child_locations, waiters) =
    6601            0 :             self.tenant_shard_split_commit_inmem(tenant_id, new_shard_count, new_stripe_size);
    6602              : 
    6603              :         // Notify all page servers to detach and clean up the old shards because they will no longer
    6604              :         // be needed. This is best-effort: if it fails, it will be cleaned up on a subsequent
    6605              :         // Pageserver re-attach/startup.
    6606            0 :         let shards_to_cleanup = targets
    6607            0 :             .iter()
    6608            0 :             .map(|target| (target.parent_id, target.node.get_id()))
    6609            0 :             .collect();
    6610            0 :         self.cleanup_locations(shards_to_cleanup).await;
    6611              : 
    6612              :         // Send compute notifications for all the new shards
    6613            0 :         let mut failed_notifications = Vec::new();
    6614            0 :         for (child_id, child_ps, stripe_size) in child_locations {
    6615            0 :             if let Err(e) = self
    6616            0 :                 .compute_hook
    6617            0 :                 .notify_attach(
    6618            0 :                     compute_hook::ShardUpdate {
    6619            0 :                         tenant_shard_id: child_id,
    6620            0 :                         node_id: child_ps,
    6621            0 :                         stripe_size,
    6622            0 :                         preferred_az: preferred_az_id.as_ref().map(Cow::Borrowed),
    6623            0 :                     },
    6624            0 :                     &self.reconcilers_cancel,
    6625            0 :                 )
    6626            0 :                 .await
    6627              :             {
    6628            0 :                 tracing::warn!(
    6629            0 :                     "Failed to update compute of {}->{} during split, proceeding anyway to complete split ({e})",
    6630              :                     child_id,
    6631              :                     child_ps
    6632              :                 );
    6633            0 :                 failed_notifications.push(child_id);
    6634            0 :             }
    6635              :         }
    6636              : 
    6637              :         // If we failed any compute notifications, make a note to retry later.
    6638            0 :         if !failed_notifications.is_empty() {
    6639            0 :             let mut locked = self.inner.write().unwrap();
    6640            0 :             for failed in failed_notifications {
    6641            0 :                 if let Some(shard) = locked.tenants.get_mut(&failed) {
    6642            0 :                     shard.pending_compute_notification = true;
    6643            0 :                 }
    6644              :             }
    6645            0 :         }
    6646              : 
    6647            0 :         Ok((response, waiters))
    6648            0 :     }
    6649              : 
    6650              :     /// A graceful migration: update the preferred node and let optimisation handle the migration
    6651              :     /// in the background (may take a long time as it will fully warm up a location before cutting over)
    6652              :     ///
    6653              :     /// Our external API calls this a 'prewarm=true' migration, but internally it isn't a special prewarm step: it's
    6654              :     /// just a migration that uses the same graceful procedure as our background scheduling optimisations would use.
    6655            0 :     fn tenant_shard_migrate_with_prewarm(
    6656            0 :         &self,
    6657            0 :         migrate_req: &TenantShardMigrateRequest,
    6658            0 :         shard: &mut TenantShard,
    6659            0 :         scheduler: &mut Scheduler,
    6660            0 :         schedule_context: ScheduleContext,
    6661            0 :     ) -> Result<Option<ScheduleOptimization>, ApiError> {
    6662            0 :         shard.set_preferred_node(Some(migrate_req.node_id));
    6663              : 
    6664              :         // Generate whatever the initial change to the intent is: this could be creation of a secondary, or
    6665              :         // cutting over to an existing secondary.  Caller is responsible for validating this before applying it,
    6666              :         // e.g. by checking secondary is warm enough.
    6667            0 :         Ok(shard.optimize_attachment(scheduler, &schedule_context))
    6668            0 :     }
    6669              : 
    6670              :     /// Immediate migration: directly update the intent state and kick off a reconciler
    6671            0 :     fn tenant_shard_migrate_immediate(
    6672            0 :         &self,
    6673            0 :         migrate_req: &TenantShardMigrateRequest,
    6674            0 :         nodes: &Arc<HashMap<NodeId, Node>>,
    6675            0 :         shard: &mut TenantShard,
    6676            0 :         scheduler: &mut Scheduler,
    6677            0 :     ) -> Result<Option<ReconcilerWaiter>, ApiError> {
    6678              :         // Non-graceful migration: update the intent state immediately
    6679            0 :         let old_attached = *shard.intent.get_attached();
    6680            0 :         match shard.policy {
    6681            0 :             PlacementPolicy::Attached(n) => {
    6682              :                 // If our new attached node was a secondary, it no longer should be.
    6683            0 :                 shard
    6684            0 :                     .intent
    6685            0 :                     .remove_secondary(scheduler, migrate_req.node_id);
    6686              : 
    6687            0 :                 shard
    6688            0 :                     .intent
    6689            0 :                     .set_attached(scheduler, Some(migrate_req.node_id));
    6690              : 
    6691              :                 // If we were already attached to something, demote that to a secondary
    6692            0 :                 if let Some(old_attached) = old_attached {
    6693            0 :                     if n > 0 {
    6694              :                         // Remove other secondaries to make room for the location we'll demote
    6695            0 :                         while shard.intent.get_secondary().len() >= n {
    6696            0 :                             shard.intent.pop_secondary(scheduler);
    6697            0 :                         }
    6698              : 
    6699            0 :                         shard.intent.push_secondary(scheduler, old_attached);
    6700            0 :                     }
    6701            0 :                 }
    6702              :             }
    6703            0 :             PlacementPolicy::Secondary => {
    6704            0 :                 shard.intent.clear(scheduler);
    6705            0 :                 shard.intent.push_secondary(scheduler, migrate_req.node_id);
    6706            0 :             }
    6707              :             PlacementPolicy::Detached => {
    6708            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    6709            0 :                     "Cannot migrate a tenant that is PlacementPolicy::Detached: configure it to an attached policy first"
    6710            0 :                 )));
    6711              :             }
    6712              :         }
    6713              : 
    6714            0 :         tracing::info!("Migrating: new intent {:?}", shard.intent);
    6715            0 :         shard.sequence = shard.sequence.next();
    6716            0 :         shard.set_preferred_node(None); // Abort any in-flight graceful migration
    6717            0 :         Ok(self.maybe_configured_reconcile_shard(
    6718            0 :             shard,
    6719            0 :             nodes,
    6720            0 :             (&migrate_req.migration_config).into(),
    6721            0 :         ))
    6722            0 :     }
    6723              : 
    6724            0 :     pub(crate) async fn tenant_shard_migrate(
    6725            0 :         &self,
    6726            0 :         tenant_shard_id: TenantShardId,
    6727            0 :         migrate_req: TenantShardMigrateRequest,
    6728            0 :     ) -> Result<TenantShardMigrateResponse, ApiError> {
    6729              :         // Depending on whether the migration is a change and whether it's graceful or immediate, we might
    6730              :         // get a different outcome to handle
    6731              :         enum MigrationOutcome {
    6732              :             Optimization(Option<ScheduleOptimization>),
    6733              :             Reconcile(Option<ReconcilerWaiter>),
    6734              :         }
    6735              : 
    6736            0 :         let outcome = {
    6737            0 :             let mut locked = self.inner.write().unwrap();
    6738            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    6739              : 
    6740            0 :             let Some(node) = nodes.get(&migrate_req.node_id) else {
    6741            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    6742            0 :                     "Node {} not found",
    6743            0 :                     migrate_req.node_id
    6744            0 :                 )));
    6745              :             };
    6746              : 
    6747              :             // Migration to unavavailable node requires force flag
    6748            0 :             if !node.is_available() {
    6749            0 :                 if migrate_req.migration_config.override_scheduler {
    6750              :                     // Warn but proceed: the caller may intend to manually adjust the placement of
    6751              :                     // a shard even if the node is down, e.g. if intervening during an incident.
    6752            0 :                     tracing::warn!("Forcibly migrating to unavailable node {node}");
    6753              :                 } else {
    6754            0 :                     tracing::warn!("Node {node} is unavailable, refusing migration");
    6755            0 :                     return Err(ApiError::PreconditionFailed(
    6756            0 :                         format!("Node {node} is unavailable").into_boxed_str(),
    6757            0 :                     ));
    6758              :                 }
    6759            0 :             }
    6760              : 
    6761              :             // Calculate the ScheduleContext for this tenant
    6762            0 :             let mut schedule_context = ScheduleContext::default();
    6763            0 :             for (_shard_id, shard) in
    6764            0 :                 tenants.range(TenantShardId::tenant_range(tenant_shard_id.tenant_id))
    6765            0 :             {
    6766            0 :                 schedule_context.avoid(&shard.intent.all_pageservers());
    6767            0 :             }
    6768              : 
    6769              :             // Look up the specific shard we will migrate
    6770            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    6771            0 :                 return Err(ApiError::NotFound(
    6772            0 :                     anyhow::anyhow!("Tenant shard not found").into(),
    6773            0 :                 ));
    6774              :             };
    6775              : 
    6776              :             // Migration to a node with unfavorable scheduling score requires a force flag, because it might just
    6777              :             // be migrated back by the optimiser.
    6778            0 :             if let Some(better_node) = shard.find_better_location::<AttachedShardTag>(
    6779            0 :                 scheduler,
    6780            0 :                 &schedule_context,
    6781            0 :                 migrate_req.node_id,
    6782            0 :                 &[],
    6783            0 :             ) {
    6784            0 :                 if !migrate_req.migration_config.override_scheduler {
    6785            0 :                     return Err(ApiError::PreconditionFailed(
    6786            0 :                         "Migration to a worse-scoring node".into(),
    6787            0 :                     ));
    6788              :                 } else {
    6789            0 :                     tracing::info!(
    6790            0 :                         "Migrating to a worse-scoring node {} (optimiser would prefer {better_node})",
    6791              :                         migrate_req.node_id
    6792              :                     );
    6793              :                 }
    6794            0 :             }
    6795              : 
    6796            0 :             if let Some(origin_node_id) = migrate_req.origin_node_id {
    6797            0 :                 if shard.intent.get_attached() != &Some(origin_node_id) {
    6798            0 :                     return Err(ApiError::PreconditionFailed(
    6799            0 :                         format!(
    6800            0 :                             "Migration expected to originate from {} but shard is on {:?}",
    6801            0 :                             origin_node_id,
    6802            0 :                             shard.intent.get_attached()
    6803            0 :                         )
    6804            0 :                         .into(),
    6805            0 :                     ));
    6806            0 :                 }
    6807            0 :             }
    6808              : 
    6809            0 :             if shard.intent.get_attached() == &Some(migrate_req.node_id) {
    6810              :                 // No-op case: we will still proceed to wait for reconciliation in case it is
    6811              :                 // incomplete from an earlier update to the intent.
    6812            0 :                 tracing::info!("Migrating: intent is unchanged {:?}", shard.intent);
    6813              : 
    6814              :                 // An instruction to migrate to the currently attached node should
    6815              :                 // cancel any pending graceful migration
    6816            0 :                 shard.set_preferred_node(None);
    6817              : 
    6818            0 :                 MigrationOutcome::Reconcile(self.maybe_configured_reconcile_shard(
    6819            0 :                     shard,
    6820            0 :                     nodes,
    6821            0 :                     (&migrate_req.migration_config).into(),
    6822            0 :                 ))
    6823            0 :             } else if migrate_req.migration_config.prewarm {
    6824            0 :                 MigrationOutcome::Optimization(self.tenant_shard_migrate_with_prewarm(
    6825            0 :                     &migrate_req,
    6826            0 :                     shard,
    6827            0 :                     scheduler,
    6828            0 :                     schedule_context,
    6829            0 :                 )?)
    6830              :             } else {
    6831            0 :                 MigrationOutcome::Reconcile(self.tenant_shard_migrate_immediate(
    6832            0 :                     &migrate_req,
    6833            0 :                     nodes,
    6834            0 :                     shard,
    6835            0 :                     scheduler,
    6836            0 :                 )?)
    6837              :             }
    6838              :         };
    6839              : 
    6840              :         // We may need to validate + apply an optimisation, or we may need to just retrive a reconcile waiter
    6841            0 :         let waiter = match outcome {
    6842            0 :             MigrationOutcome::Optimization(Some(optimization)) => {
    6843              :                 // Validate and apply the optimization -- this would happen anyway in background reconcile loop, but
    6844              :                 // we might as well do it more promptly as this is a direct external request.
    6845            0 :                 let mut validated = self
    6846            0 :                     .optimize_all_validate(vec![(tenant_shard_id, optimization)])
    6847            0 :                     .await;
    6848            0 :                 if let Some((_shard_id, optimization)) = validated.pop() {
    6849            0 :                     let mut locked = self.inner.write().unwrap();
    6850            0 :                     let (nodes, tenants, scheduler) = locked.parts_mut();
    6851            0 :                     let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    6852              :                         // Rare but possible: tenant is removed between generating optimisation and validating it.
    6853            0 :                         return Err(ApiError::NotFound(
    6854            0 :                             anyhow::anyhow!("Tenant shard not found").into(),
    6855            0 :                         ));
    6856              :                     };
    6857              : 
    6858            0 :                     if !shard.apply_optimization(scheduler, optimization) {
    6859              :                         // This can happen but is unusual enough to warn on: something else changed in the shard that made the optimisation stale
    6860              :                         // and therefore not applied.
    6861            0 :                         tracing::warn!(
    6862            0 :                             "Schedule optimisation generated during graceful migration was not applied, shard changed?"
    6863              :                         );
    6864            0 :                     }
    6865            0 :                     self.maybe_configured_reconcile_shard(
    6866            0 :                         shard,
    6867            0 :                         nodes,
    6868            0 :                         (&migrate_req.migration_config).into(),
    6869              :                     )
    6870              :                 } else {
    6871            0 :                     None
    6872              :                 }
    6873              :             }
    6874            0 :             MigrationOutcome::Optimization(None) => None,
    6875            0 :             MigrationOutcome::Reconcile(waiter) => waiter,
    6876              :         };
    6877              : 
    6878              :         // Finally, wait for any reconcile we started to complete.  In the case of immediate-mode migrations to cold
    6879              :         // locations, this has a good chance of timing out.
    6880            0 :         if let Some(waiter) = waiter {
    6881            0 :             waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
    6882              :         } else {
    6883            0 :             tracing::info!("Migration is a no-op");
    6884              :         }
    6885              : 
    6886            0 :         Ok(TenantShardMigrateResponse {})
    6887            0 :     }
    6888              : 
    6889            0 :     pub(crate) async fn tenant_shard_migrate_secondary(
    6890            0 :         &self,
    6891            0 :         tenant_shard_id: TenantShardId,
    6892            0 :         migrate_req: TenantShardMigrateRequest,
    6893            0 :     ) -> Result<TenantShardMigrateResponse, ApiError> {
    6894            0 :         let waiter = {
    6895            0 :             let mut locked = self.inner.write().unwrap();
    6896            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    6897              : 
    6898            0 :             let Some(node) = nodes.get(&migrate_req.node_id) else {
    6899            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    6900            0 :                     "Node {} not found",
    6901            0 :                     migrate_req.node_id
    6902            0 :                 )));
    6903              :             };
    6904              : 
    6905            0 :             if !node.is_available() {
    6906              :                 // Warn but proceed: the caller may intend to manually adjust the placement of
    6907              :                 // a shard even if the node is down, e.g. if intervening during an incident.
    6908            0 :                 tracing::warn!("Migrating to unavailable node {node}");
    6909            0 :             }
    6910              : 
    6911            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    6912            0 :                 return Err(ApiError::NotFound(
    6913            0 :                     anyhow::anyhow!("Tenant shard not found").into(),
    6914            0 :                 ));
    6915              :             };
    6916              : 
    6917            0 :             if shard.intent.get_secondary().len() == 1
    6918            0 :                 && shard.intent.get_secondary()[0] == migrate_req.node_id
    6919              :             {
    6920            0 :                 tracing::info!(
    6921            0 :                     "Migrating secondary to {node}: intent is unchanged {:?}",
    6922              :                     shard.intent
    6923              :                 );
    6924            0 :             } else if shard.intent.get_attached() == &Some(migrate_req.node_id) {
    6925            0 :                 tracing::info!(
    6926            0 :                     "Migrating secondary to {node}: already attached where we were asked to create a secondary"
    6927              :                 );
    6928              :             } else {
    6929            0 :                 let old_secondaries = shard.intent.get_secondary().clone();
    6930            0 :                 for secondary in old_secondaries {
    6931            0 :                     shard.intent.remove_secondary(scheduler, secondary);
    6932            0 :                 }
    6933              : 
    6934            0 :                 shard.intent.push_secondary(scheduler, migrate_req.node_id);
    6935            0 :                 shard.sequence = shard.sequence.next();
    6936            0 :                 tracing::info!(
    6937            0 :                     "Migrating secondary to {node}: new intent {:?}",
    6938              :                     shard.intent
    6939              :                 );
    6940              :             }
    6941              : 
    6942            0 :             self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
    6943              :         };
    6944              : 
    6945            0 :         if let Some(waiter) = waiter {
    6946            0 :             waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
    6947              :         } else {
    6948            0 :             tracing::info!("Migration is a no-op");
    6949              :         }
    6950              : 
    6951            0 :         Ok(TenantShardMigrateResponse {})
    6952            0 :     }
    6953              : 
    6954              :     /// 'cancel' in this context means cancel any ongoing reconcile
    6955            0 :     pub(crate) async fn tenant_shard_cancel_reconcile(
    6956            0 :         &self,
    6957            0 :         tenant_shard_id: TenantShardId,
    6958            0 :     ) -> Result<(), ApiError> {
    6959              :         // Take state lock and fire the cancellation token, after which we drop lock and wait for any ongoing reconcile to complete
    6960            0 :         let waiter = {
    6961            0 :             let locked = self.inner.write().unwrap();
    6962            0 :             let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
    6963            0 :                 return Err(ApiError::NotFound(
    6964            0 :                     anyhow::anyhow!("Tenant shard not found").into(),
    6965            0 :                 ));
    6966              :             };
    6967              : 
    6968            0 :             let waiter = shard.get_waiter();
    6969            0 :             match waiter {
    6970              :                 None => {
    6971            0 :                     tracing::info!("Shard does not have an ongoing Reconciler");
    6972            0 :                     return Ok(());
    6973              :                 }
    6974            0 :                 Some(waiter) => {
    6975            0 :                     tracing::info!("Cancelling Reconciler");
    6976            0 :                     shard.cancel_reconciler();
    6977            0 :                     waiter
    6978              :                 }
    6979              :             }
    6980              :         };
    6981              : 
    6982              :         // Cancellation should be prompt.  If this fails we have still done our job of firing the
    6983              :         // cancellation token, but by returning an ApiError we will indicate to the caller that
    6984              :         // the Reconciler is misbehaving and not respecting the cancellation token
    6985            0 :         self.await_waiters(vec![waiter], SHORT_RECONCILE_TIMEOUT)
    6986            0 :             .await?;
    6987              : 
    6988            0 :         Ok(())
    6989            0 :     }
    6990              : 
    6991              :     /// This is for debug/support only: we simply drop all state for a tenant, without
    6992              :     /// detaching or deleting it on pageservers.
    6993            0 :     pub(crate) async fn tenant_drop(&self, tenant_id: TenantId) -> Result<(), ApiError> {
    6994            0 :         self.persistence.delete_tenant(tenant_id).await?;
    6995              : 
    6996            0 :         let mut locked = self.inner.write().unwrap();
    6997            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    6998            0 :         let mut shards = Vec::new();
    6999            0 :         for (tenant_shard_id, _) in tenants.range(TenantShardId::tenant_range(tenant_id)) {
    7000            0 :             shards.push(*tenant_shard_id);
    7001            0 :         }
    7002              : 
    7003            0 :         for shard_id in shards {
    7004            0 :             if let Some(mut shard) = tenants.remove(&shard_id) {
    7005            0 :                 shard.intent.clear(scheduler);
    7006            0 :             }
    7007              :         }
    7008              : 
    7009            0 :         Ok(())
    7010            0 :     }
    7011              : 
    7012              :     /// This is for debug/support only: assuming tenant data is already present in S3, we "create" a
    7013              :     /// tenant with a very high generation number so that it will see the existing data.
    7014              :     /// It does not create timelines on safekeepers, because they might already exist on some
    7015              :     /// safekeeper set. So, the timelines are not storcon-managed after the import.
    7016            0 :     pub(crate) async fn tenant_import(
    7017            0 :         &self,
    7018            0 :         tenant_id: TenantId,
    7019            0 :     ) -> Result<TenantCreateResponse, ApiError> {
    7020              :         // Pick an arbitrary available pageserver to use for scanning the tenant in remote storage
    7021            0 :         let maybe_node = {
    7022            0 :             self.inner
    7023            0 :                 .read()
    7024            0 :                 .unwrap()
    7025            0 :                 .nodes
    7026            0 :                 .values()
    7027            0 :                 .find(|n| n.is_available())
    7028            0 :                 .cloned()
    7029              :         };
    7030            0 :         let Some(node) = maybe_node else {
    7031            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!("No nodes available")));
    7032              :         };
    7033              : 
    7034            0 :         let client = PageserverClient::new(
    7035            0 :             node.get_id(),
    7036            0 :             self.http_client.clone(),
    7037            0 :             node.base_url(),
    7038            0 :             self.config.pageserver_jwt_token.as_deref(),
    7039              :         );
    7040              : 
    7041            0 :         let scan_result = client
    7042            0 :             .tenant_scan_remote_storage(tenant_id)
    7043            0 :             .await
    7044            0 :             .map_err(|e| passthrough_api_error(&node, e))?;
    7045              : 
    7046              :         // A post-split tenant may contain a mixture of shard counts in remote storage: pick the highest count.
    7047            0 :         let Some(shard_count) = scan_result
    7048            0 :             .shards
    7049            0 :             .iter()
    7050            0 :             .map(|s| s.tenant_shard_id.shard_count)
    7051            0 :             .max()
    7052              :         else {
    7053            0 :             return Err(ApiError::NotFound(
    7054            0 :                 anyhow::anyhow!("No shards found").into(),
    7055            0 :             ));
    7056              :         };
    7057              : 
    7058              :         // Ideally we would set each newly imported shard's generation independently, but for correctness it is sufficient
    7059              :         // to
    7060            0 :         let generation = scan_result
    7061            0 :             .shards
    7062            0 :             .iter()
    7063            0 :             .map(|s| s.generation)
    7064            0 :             .max()
    7065            0 :             .expect("We already validated >0 shards");
    7066              : 
    7067              :         // Find the tenant's stripe size. This wasn't always persisted in the tenant manifest, so
    7068              :         // fall back to the original default stripe size of 32768 (256 MB) if it's not specified.
    7069              :         const ORIGINAL_STRIPE_SIZE: ShardStripeSize = ShardStripeSize(32768);
    7070            0 :         let stripe_size = scan_result
    7071            0 :             .shards
    7072            0 :             .iter()
    7073            0 :             .find(|s| s.tenant_shard_id.shard_count == shard_count && s.generation == generation)
    7074            0 :             .expect("we validated >0 shards above")
    7075              :             .stripe_size
    7076            0 :             .unwrap_or_else(|| {
    7077            0 :                 if shard_count.count() > 1 {
    7078            0 :                     warn!("unknown stripe size, assuming {ORIGINAL_STRIPE_SIZE}");
    7079            0 :                 }
    7080            0 :                 ORIGINAL_STRIPE_SIZE
    7081            0 :             });
    7082              : 
    7083            0 :         let (response, waiters) = self
    7084            0 :             .do_tenant_create(TenantCreateRequest {
    7085            0 :                 new_tenant_id: TenantShardId::unsharded(tenant_id),
    7086            0 :                 generation,
    7087            0 : 
    7088            0 :                 shard_parameters: ShardParameters {
    7089            0 :                     count: shard_count,
    7090            0 :                     stripe_size,
    7091            0 :                 },
    7092            0 :                 placement_policy: Some(PlacementPolicy::Attached(0)), // No secondaries, for convenient debug/hacking
    7093            0 :                 config: TenantConfig::default(),
    7094            0 :             })
    7095            0 :             .await?;
    7096              : 
    7097            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    7098              :             // Since this is a debug/support operation, all kinds of weird issues are possible (e.g. this
    7099              :             // tenant doesn't exist in the control plane), so don't fail the request if it can't fully
    7100              :             // reconcile, as reconciliation includes notifying compute.
    7101            0 :             tracing::warn!(%tenant_id, "Reconcile not done yet while importing tenant ({e})");
    7102            0 :         }
    7103              : 
    7104            0 :         Ok(response)
    7105            0 :     }
    7106              : 
    7107              :     /// For debug/support: a full JSON dump of TenantShards.  Returns a response so that
    7108              :     /// we don't have to make TenantShard clonable in the return path.
    7109            0 :     pub(crate) fn tenants_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
    7110            0 :         let serialized = {
    7111            0 :             let locked = self.inner.read().unwrap();
    7112            0 :             let result = locked.tenants.values().collect::<Vec<_>>();
    7113            0 :             serde_json::to_string(&result).map_err(|e| ApiError::InternalServerError(e.into()))?
    7114              :         };
    7115              : 
    7116            0 :         hyper::Response::builder()
    7117            0 :             .status(hyper::StatusCode::OK)
    7118            0 :             .header(hyper::header::CONTENT_TYPE, "application/json")
    7119            0 :             .body(hyper::Body::from(serialized))
    7120            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))
    7121            0 :     }
    7122              : 
    7123              :     /// Check the consistency of in-memory state vs. persistent state, and check that the
    7124              :     /// scheduler's statistics are up to date.
    7125              :     ///
    7126              :     /// These consistency checks expect an **idle** system.  If changes are going on while
    7127              :     /// we run, then we can falsely indicate a consistency issue.  This is sufficient for end-of-test
    7128              :     /// checks, but not suitable for running continuously in the background in the field.
    7129            0 :     pub(crate) async fn consistency_check(&self) -> Result<(), ApiError> {
    7130            0 :         let (mut expect_nodes, mut expect_shards) = {
    7131            0 :             let locked = self.inner.read().unwrap();
    7132              : 
    7133            0 :             locked
    7134            0 :                 .scheduler
    7135            0 :                 .consistency_check(locked.nodes.values(), locked.tenants.values())
    7136            0 :                 .context("Scheduler checks")
    7137            0 :                 .map_err(ApiError::InternalServerError)?;
    7138              : 
    7139            0 :             let expect_nodes = locked
    7140            0 :                 .nodes
    7141            0 :                 .values()
    7142            0 :                 .map(|n| n.to_persistent())
    7143            0 :                 .collect::<Vec<_>>();
    7144              : 
    7145            0 :             let expect_shards = locked
    7146            0 :                 .tenants
    7147            0 :                 .values()
    7148            0 :                 .map(|t| t.to_persistent())
    7149            0 :                 .collect::<Vec<_>>();
    7150              : 
    7151              :             // This method can only validate the state of an idle system: if a reconcile is in
    7152              :             // progress, fail out early to avoid giving false errors on state that won't match
    7153              :             // between database and memory under a ReconcileResult is processed.
    7154            0 :             for t in locked.tenants.values() {
    7155            0 :                 if t.reconciler.is_some() {
    7156            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    7157            0 :                         "Shard {} reconciliation in progress",
    7158            0 :                         t.tenant_shard_id
    7159            0 :                     )));
    7160            0 :                 }
    7161              :             }
    7162              : 
    7163            0 :             (expect_nodes, expect_shards)
    7164              :         };
    7165              : 
    7166            0 :         let mut nodes = self.persistence.list_nodes().await?;
    7167            0 :         expect_nodes.sort_by_key(|n| n.node_id);
    7168            0 :         nodes.sort_by_key(|n| n.node_id);
    7169              : 
    7170              :         // Errors relating to nodes are deferred so that we don't skip the shard checks below if we have a node error
    7171            0 :         let node_result = if nodes != expect_nodes {
    7172            0 :             tracing::error!("Consistency check failed on nodes.");
    7173            0 :             tracing::error!(
    7174            0 :                 "Nodes in memory: {}",
    7175            0 :                 serde_json::to_string(&expect_nodes)
    7176            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    7177              :             );
    7178            0 :             tracing::error!(
    7179            0 :                 "Nodes in database: {}",
    7180            0 :                 serde_json::to_string(&nodes)
    7181            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    7182              :             );
    7183            0 :             Err(ApiError::InternalServerError(anyhow::anyhow!(
    7184            0 :                 "Node consistency failure"
    7185            0 :             )))
    7186              :         } else {
    7187            0 :             Ok(())
    7188              :         };
    7189              : 
    7190            0 :         let mut persistent_shards = self.persistence.load_active_tenant_shards().await?;
    7191            0 :         persistent_shards
    7192            0 :             .sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
    7193              : 
    7194            0 :         expect_shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
    7195              : 
    7196              :         // Because JSON contents of persistent tenants might disagree with the fields in current `TenantConfig`
    7197              :         // definition, we will do an encode/decode cycle to ensure any legacy fields are dropped and any new
    7198              :         // fields are added, before doing a comparison.
    7199            0 :         for tsp in &mut persistent_shards {
    7200            0 :             let config: TenantConfig = serde_json::from_str(&tsp.config)
    7201            0 :                 .map_err(|e| ApiError::InternalServerError(e.into()))?;
    7202            0 :             tsp.config = serde_json::to_string(&config).expect("Encoding config is infallible");
    7203              :         }
    7204              : 
    7205            0 :         if persistent_shards != expect_shards {
    7206            0 :             tracing::error!("Consistency check failed on shards.");
    7207              : 
    7208            0 :             tracing::error!(
    7209            0 :                 "Shards in memory: {}",
    7210            0 :                 serde_json::to_string(&expect_shards)
    7211            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    7212              :             );
    7213            0 :             tracing::error!(
    7214            0 :                 "Shards in database: {}",
    7215            0 :                 serde_json::to_string(&persistent_shards)
    7216            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    7217              :             );
    7218              : 
    7219              :             // The total dump log lines above are useful in testing but in the field grafana will
    7220              :             // usually just drop them because they're so large. So we also do some explicit logging
    7221              :             // of just the diffs.
    7222            0 :             let persistent_shards = persistent_shards
    7223            0 :                 .into_iter()
    7224            0 :                 .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
    7225            0 :                 .collect::<HashMap<_, _>>();
    7226            0 :             let expect_shards = expect_shards
    7227            0 :                 .into_iter()
    7228            0 :                 .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
    7229            0 :                 .collect::<HashMap<_, _>>();
    7230            0 :             for (tenant_shard_id, persistent_tsp) in &persistent_shards {
    7231            0 :                 match expect_shards.get(tenant_shard_id) {
    7232              :                     None => {
    7233            0 :                         tracing::error!(
    7234            0 :                             "Shard {} found in database but not in memory",
    7235              :                             tenant_shard_id
    7236              :                         );
    7237              :                     }
    7238            0 :                     Some(expect_tsp) => {
    7239            0 :                         if expect_tsp != persistent_tsp {
    7240            0 :                             tracing::error!(
    7241            0 :                                 "Shard {} is inconsistent.  In memory: {}, database has: {}",
    7242              :                                 tenant_shard_id,
    7243            0 :                                 serde_json::to_string(expect_tsp).unwrap(),
    7244            0 :                                 serde_json::to_string(&persistent_tsp).unwrap()
    7245              :                             );
    7246            0 :                         }
    7247              :                     }
    7248              :                 }
    7249              :             }
    7250              : 
    7251              :             // Having already logged any differences, log any shards that simply aren't present in the database
    7252            0 :             for (tenant_shard_id, memory_tsp) in &expect_shards {
    7253            0 :                 if !persistent_shards.contains_key(tenant_shard_id) {
    7254            0 :                     tracing::error!(
    7255            0 :                         "Shard {} found in memory but not in database: {}",
    7256              :                         tenant_shard_id,
    7257            0 :                         serde_json::to_string(memory_tsp)
    7258            0 :                             .map_err(|e| ApiError::InternalServerError(e.into()))?
    7259              :                     );
    7260            0 :                 }
    7261              :             }
    7262              : 
    7263            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    7264            0 :                 "Shard consistency failure"
    7265            0 :             )));
    7266            0 :         }
    7267              : 
    7268            0 :         node_result
    7269            0 :     }
    7270              : 
    7271              :     /// For debug/support: a JSON dump of the [`Scheduler`].  Returns a response so that
    7272              :     /// we don't have to make TenantShard clonable in the return path.
    7273            0 :     pub(crate) fn scheduler_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
    7274            0 :         let serialized = {
    7275            0 :             let locked = self.inner.read().unwrap();
    7276            0 :             serde_json::to_string(&locked.scheduler)
    7277            0 :                 .map_err(|e| ApiError::InternalServerError(e.into()))?
    7278              :         };
    7279              : 
    7280            0 :         hyper::Response::builder()
    7281            0 :             .status(hyper::StatusCode::OK)
    7282            0 :             .header(hyper::header::CONTENT_TYPE, "application/json")
    7283            0 :             .body(hyper::Body::from(serialized))
    7284            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))
    7285            0 :     }
    7286              : 
    7287              :     /// This is for debug/support only: we simply drop all state for a tenant, without
    7288              :     /// detaching or deleting it on pageservers.  We do not try and re-schedule any
    7289              :     /// tenants that were on this node.
    7290            0 :     pub(crate) async fn node_drop(&self, node_id: NodeId) -> Result<(), ApiError> {
    7291            0 :         self.persistence.set_tombstone(node_id).await?;
    7292              : 
    7293            0 :         let mut locked = self.inner.write().unwrap();
    7294              : 
    7295            0 :         for shard in locked.tenants.values_mut() {
    7296            0 :             shard.deref_node(node_id);
    7297            0 :             shard.observed.locations.remove(&node_id);
    7298            0 :         }
    7299              : 
    7300            0 :         let mut nodes = (*locked.nodes).clone();
    7301            0 :         nodes.remove(&node_id);
    7302            0 :         locked.nodes = Arc::new(nodes);
    7303            0 :         metrics::METRICS_REGISTRY
    7304            0 :             .metrics_group
    7305            0 :             .storage_controller_pageserver_nodes
    7306            0 :             .set(locked.nodes.len() as i64);
    7307            0 :         metrics::METRICS_REGISTRY
    7308            0 :             .metrics_group
    7309            0 :             .storage_controller_https_pageserver_nodes
    7310            0 :             .set(locked.nodes.values().filter(|n| n.has_https_port()).count() as i64);
    7311              : 
    7312            0 :         locked.scheduler.node_remove(node_id);
    7313              : 
    7314            0 :         Ok(())
    7315            0 :     }
    7316              : 
    7317              :     /// If a node has any work on it, it will be rescheduled: this is "clean" in the sense
    7318              :     /// that we don't leave any bad state behind in the storage controller, but unclean
    7319              :     /// in the sense that we are not carefully draining the node.
    7320            0 :     pub(crate) async fn node_delete_old(&self, node_id: NodeId) -> Result<(), ApiError> {
    7321            0 :         let _node_lock =
    7322            0 :             trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Delete).await;
    7323              : 
    7324              :         // 1. Atomically update in-memory state:
    7325              :         //    - set the scheduling state to Pause to make subsequent scheduling ops skip it
    7326              :         //    - update shards' intents to exclude the node, and reschedule any shards whose intents we modified.
    7327              :         //    - drop the node from the main nodes map, so that when running reconciles complete they do not
    7328              :         //      re-insert references to this node into the ObservedState of shards
    7329              :         //    - drop the node from the scheduler
    7330              :         {
    7331            0 :             let mut locked = self.inner.write().unwrap();
    7332            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    7333              : 
    7334              :             {
    7335            0 :                 let mut nodes_mut = (*nodes).deref().clone();
    7336            0 :                 match nodes_mut.get_mut(&node_id) {
    7337            0 :                     Some(node) => {
    7338            0 :                         // We do not bother setting this in the database, because we're about to delete the row anyway, and
    7339            0 :                         // if we crash it would not be desirable to leave the node paused after a restart.
    7340            0 :                         node.set_scheduling(NodeSchedulingPolicy::Pause);
    7341            0 :                     }
    7342              :                     None => {
    7343            0 :                         tracing::info!(
    7344            0 :                             "Node not found: presuming this is a retry and returning success"
    7345              :                         );
    7346            0 :                         return Ok(());
    7347              :                     }
    7348              :                 }
    7349              : 
    7350            0 :                 *nodes = Arc::new(nodes_mut);
    7351              :             }
    7352              : 
    7353            0 :             for (_tenant_id, mut schedule_context, shards) in
    7354            0 :                 TenantShardExclusiveIterator::new(tenants, ScheduleMode::Normal)
    7355              :             {
    7356            0 :                 for shard in shards {
    7357            0 :                     if shard.deref_node(node_id) {
    7358            0 :                         if let Err(e) = shard.schedule(scheduler, &mut schedule_context) {
    7359              :                             // TODO: implement force flag to remove a node even if we can't reschedule
    7360              :                             // a tenant
    7361            0 :                             tracing::error!(
    7362            0 :                                 "Refusing to delete node, shard {} can't be rescheduled: {e}",
    7363              :                                 shard.tenant_shard_id
    7364              :                             );
    7365            0 :                             return Err(e.into());
    7366              :                         } else {
    7367            0 :                             tracing::info!(
    7368            0 :                                 "Rescheduled shard {} away from node during deletion",
    7369              :                                 shard.tenant_shard_id
    7370              :                             )
    7371              :                         }
    7372              : 
    7373            0 :                         self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
    7374            0 :                     }
    7375              : 
    7376              :                     // Here we remove an existing observed location for the node we're removing, and it will
    7377              :                     // not be re-added by a reconciler's completion because we filter out removed nodes in
    7378              :                     // process_result.
    7379              :                     //
    7380              :                     // Note that we update the shard's observed state _after_ calling maybe_reconcile_shard: that
    7381              :                     // means any reconciles we spawned will know about the node we're deleting, enabling them
    7382              :                     // to do live migrations if it's still online.
    7383            0 :                     shard.observed.locations.remove(&node_id);
    7384              :                 }
    7385              :             }
    7386              : 
    7387            0 :             scheduler.node_remove(node_id);
    7388              : 
    7389              :             {
    7390            0 :                 let mut nodes_mut = (**nodes).clone();
    7391            0 :                 if let Some(mut removed_node) = nodes_mut.remove(&node_id) {
    7392            0 :                     // Ensure that any reconciler holding an Arc<> to this node will
    7393            0 :                     // drop out when trying to RPC to it (setting Offline state sets the
    7394            0 :                     // cancellation token on the Node object).
    7395            0 :                     removed_node.set_availability(NodeAvailability::Offline);
    7396            0 :                 }
    7397            0 :                 *nodes = Arc::new(nodes_mut);
    7398            0 :                 metrics::METRICS_REGISTRY
    7399            0 :                     .metrics_group
    7400            0 :                     .storage_controller_pageserver_nodes
    7401            0 :                     .set(nodes.len() as i64);
    7402            0 :                 metrics::METRICS_REGISTRY
    7403            0 :                     .metrics_group
    7404            0 :                     .storage_controller_https_pageserver_nodes
    7405            0 :                     .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
    7406              :             }
    7407              :         }
    7408              : 
    7409              :         // Note: some `generation_pageserver` columns on tenant shards in the database may still refer to
    7410              :         // the removed node, as this column means "The pageserver to which this generation was issued", and
    7411              :         // their generations won't get updated until the reconcilers moving them away from this node complete.
    7412              :         // That is safe because in Service::spawn we only use generation_pageserver if it refers to a node
    7413              :         // that exists.
    7414              : 
    7415              :         // 2. Actually delete the node from in-memory state and set tombstone to the database
    7416              :         // for preventing the node to register again.
    7417            0 :         tracing::info!("Deleting node from database");
    7418            0 :         self.persistence.set_tombstone(node_id).await?;
    7419              : 
    7420            0 :         Ok(())
    7421            0 :     }
    7422              : 
    7423            0 :     pub(crate) async fn delete_node(
    7424            0 :         self: &Arc<Self>,
    7425            0 :         node_id: NodeId,
    7426            0 :         policy_on_start: NodeSchedulingPolicy,
    7427            0 :         force: bool,
    7428            0 :         cancel: CancellationToken,
    7429            0 :     ) -> Result<(), OperationError> {
    7430            0 :         let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal).build();
    7431              : 
    7432            0 :         let mut waiters: Vec<ReconcilerWaiter> = Vec::new();
    7433            0 :         let mut tid_iter = create_shared_shard_iterator(self.clone());
    7434              : 
    7435            0 :         let reset_node_policy_on_cancel = || async {
    7436            0 :             match self
    7437            0 :                 .node_configure(node_id, None, Some(policy_on_start))
    7438            0 :                 .await
    7439              :             {
    7440            0 :                 Ok(()) => OperationError::Cancelled,
    7441            0 :                 Err(err) => {
    7442            0 :                     OperationError::FinalizeError(
    7443            0 :                         format!(
    7444            0 :                             "Failed to finalise delete cancel of {} by setting scheduling policy to {}: {}",
    7445            0 :                             node_id, String::from(policy_on_start), err
    7446            0 :                         )
    7447            0 :                         .into(),
    7448            0 :                     )
    7449              :                 }
    7450              :             }
    7451            0 :         };
    7452              : 
    7453            0 :         while !tid_iter.finished() {
    7454            0 :             if cancel.is_cancelled() {
    7455            0 :                 return Err(reset_node_policy_on_cancel().await);
    7456            0 :             }
    7457              : 
    7458            0 :             operation_utils::validate_node_state(
    7459            0 :                 &node_id,
    7460            0 :                 self.inner.read().unwrap().nodes.clone(),
    7461            0 :                 NodeSchedulingPolicy::Deleting,
    7462            0 :             )?;
    7463              : 
    7464            0 :             while waiters.len() < MAX_RECONCILES_PER_OPERATION {
    7465            0 :                 let tid = match tid_iter.next() {
    7466            0 :                     Some(tid) => tid,
    7467              :                     None => {
    7468            0 :                         break;
    7469              :                     }
    7470              :                 };
    7471              : 
    7472            0 :                 let mut locked = self.inner.write().unwrap();
    7473            0 :                 let (nodes, tenants, scheduler) = locked.parts_mut();
    7474              : 
    7475              :                 // Calculate a schedule context here to avoid borrow checker issues.
    7476            0 :                 let mut schedule_context = ScheduleContext::default();
    7477            0 :                 for (_, shard) in tenants.range(TenantShardId::tenant_range(tid.tenant_id)) {
    7478            0 :                     schedule_context.avoid(&shard.intent.all_pageservers());
    7479            0 :                 }
    7480              : 
    7481            0 :                 let tenant_shard = match tenants.get_mut(&tid) {
    7482            0 :                     Some(tenant_shard) => tenant_shard,
    7483              :                     None => {
    7484              :                         // Tenant shard was deleted by another operation. Skip it.
    7485            0 :                         continue;
    7486              :                     }
    7487              :                 };
    7488              : 
    7489            0 :                 match tenant_shard.get_scheduling_policy() {
    7490            0 :                     ShardSchedulingPolicy::Active | ShardSchedulingPolicy::Essential => {
    7491            0 :                         // A migration during delete is classed as 'essential' because it is required to
    7492            0 :                         // uphold our availability goals for the tenant: this shard is elegible for migration.
    7493            0 :                     }
    7494              :                     ShardSchedulingPolicy::Pause | ShardSchedulingPolicy::Stop => {
    7495              :                         // If we have been asked to avoid rescheduling this shard, then do not migrate it during a deletion
    7496            0 :                         tracing::warn!(
    7497            0 :                             tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    7498            0 :                             "Skip migration during deletion because shard scheduling policy {:?} disallows it",
    7499            0 :                             tenant_shard.get_scheduling_policy(),
    7500              :                         );
    7501            0 :                         continue;
    7502              :                     }
    7503              :                 }
    7504              : 
    7505            0 :                 if tenant_shard.deref_node(node_id) {
    7506            0 :                     if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
    7507            0 :                         tracing::error!(
    7508            0 :                             "Refusing to delete node, shard {} can't be rescheduled: {e}",
    7509              :                             tenant_shard.tenant_shard_id
    7510              :                         );
    7511            0 :                         return Err(OperationError::ImpossibleConstraint(e.to_string().into()));
    7512              :                     } else {
    7513            0 :                         tracing::info!(
    7514            0 :                             "Rescheduled shard {} away from node during deletion",
    7515              :                             tenant_shard.tenant_shard_id
    7516              :                         )
    7517              :                     }
    7518              : 
    7519            0 :                     let waiter = self.maybe_configured_reconcile_shard(
    7520            0 :                         tenant_shard,
    7521            0 :                         nodes,
    7522            0 :                         reconciler_config,
    7523            0 :                     );
    7524              : 
    7525            0 :                     if force {
    7526            0 :                         // Here we remove an existing observed location for the node we're removing, and it will
    7527            0 :                         // not be re-added by a reconciler's completion because we filter out removed nodes in
    7528            0 :                         // process_result.
    7529            0 :                         //
    7530            0 :                         // Note that we update the shard's observed state _after_ calling maybe_configured_reconcile_shard:
    7531            0 :                         // that means any reconciles we spawned will know about the node we're deleting,
    7532            0 :                         // enabling them to do live migrations if it's still online.
    7533            0 :                         tenant_shard.observed.locations.remove(&node_id);
    7534            0 :                     } else if let Some(waiter) = waiter {
    7535            0 :                         waiters.push(waiter);
    7536            0 :                     }
    7537            0 :                 }
    7538              :             }
    7539              : 
    7540            0 :             waiters = self
    7541            0 :                 .await_waiters_remainder(waiters, WAITER_OPERATION_POLL_TIMEOUT)
    7542            0 :                 .await;
    7543              : 
    7544            0 :             failpoint_support::sleep_millis_async!("sleepy-delete-loop", &cancel);
    7545              :         }
    7546              : 
    7547            0 :         while !waiters.is_empty() {
    7548            0 :             if cancel.is_cancelled() {
    7549            0 :                 return Err(reset_node_policy_on_cancel().await);
    7550            0 :             }
    7551              : 
    7552            0 :             tracing::info!("Awaiting {} pending delete reconciliations", waiters.len());
    7553              : 
    7554            0 :             waiters = self
    7555            0 :                 .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
    7556            0 :                 .await;
    7557              :         }
    7558              : 
    7559            0 :         let pf = pausable_failpoint!("delete-node-after-reconciles-spawned", &cancel);
    7560            0 :         if pf.is_err() {
    7561              :             // An error from pausable_failpoint indicates the cancel token was triggered.
    7562            0 :             return Err(reset_node_policy_on_cancel().await);
    7563            0 :         }
    7564              : 
    7565            0 :         self.persistence
    7566            0 :             .set_tombstone(node_id)
    7567            0 :             .await
    7568            0 :             .map_err(|e| OperationError::FinalizeError(e.to_string().into()))?;
    7569              : 
    7570              :         {
    7571            0 :             let mut locked = self.inner.write().unwrap();
    7572            0 :             let (nodes, _, scheduler) = locked.parts_mut();
    7573              : 
    7574            0 :             scheduler.node_remove(node_id);
    7575              : 
    7576            0 :             let mut nodes_mut = (**nodes).clone();
    7577            0 :             if let Some(mut removed_node) = nodes_mut.remove(&node_id) {
    7578            0 :                 // Ensure that any reconciler holding an Arc<> to this node will
    7579            0 :                 // drop out when trying to RPC to it (setting Offline state sets the
    7580            0 :                 // cancellation token on the Node object).
    7581            0 :                 removed_node.set_availability(NodeAvailability::Offline);
    7582            0 :             }
    7583            0 :             *nodes = Arc::new(nodes_mut);
    7584              : 
    7585            0 :             metrics::METRICS_REGISTRY
    7586            0 :                 .metrics_group
    7587            0 :                 .storage_controller_pageserver_nodes
    7588            0 :                 .set(nodes.len() as i64);
    7589            0 :             metrics::METRICS_REGISTRY
    7590            0 :                 .metrics_group
    7591            0 :                 .storage_controller_https_pageserver_nodes
    7592            0 :                 .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
    7593              :         }
    7594              : 
    7595            0 :         Ok(())
    7596            0 :     }
    7597              : 
    7598            0 :     pub(crate) async fn node_list(&self) -> Result<Vec<Node>, ApiError> {
    7599            0 :         let nodes = {
    7600            0 :             self.inner
    7601            0 :                 .read()
    7602            0 :                 .unwrap()
    7603            0 :                 .nodes
    7604            0 :                 .values()
    7605            0 :                 .cloned()
    7606            0 :                 .collect::<Vec<_>>()
    7607              :         };
    7608              : 
    7609            0 :         Ok(nodes)
    7610            0 :     }
    7611              : 
    7612            0 :     pub(crate) async fn tombstone_list(&self) -> Result<Vec<Node>, ApiError> {
    7613            0 :         self.persistence
    7614            0 :             .list_tombstones()
    7615            0 :             .await?
    7616            0 :             .into_iter()
    7617            0 :             .map(|np| Node::from_persistent(np, false))
    7618            0 :             .collect::<Result<Vec<_>, _>>()
    7619            0 :             .map_err(ApiError::InternalServerError)
    7620            0 :     }
    7621              : 
    7622            0 :     pub(crate) async fn tombstone_delete(&self, node_id: NodeId) -> Result<(), ApiError> {
    7623            0 :         let _node_lock = trace_exclusive_lock(
    7624            0 :             &self.node_op_locks,
    7625            0 :             node_id,
    7626            0 :             NodeOperations::DeleteTombstone,
    7627            0 :         )
    7628            0 :         .await;
    7629              : 
    7630            0 :         if matches!(self.get_node(node_id).await, Err(ApiError::NotFound(_))) {
    7631            0 :             self.persistence.delete_node(node_id).await?;
    7632            0 :             Ok(())
    7633              :         } else {
    7634            0 :             Err(ApiError::Conflict(format!(
    7635            0 :                 "Node {node_id} is in use, consider using tombstone API first"
    7636            0 :             )))
    7637              :         }
    7638            0 :     }
    7639              : 
    7640            0 :     pub(crate) async fn get_node(&self, node_id: NodeId) -> Result<Node, ApiError> {
    7641            0 :         self.inner
    7642            0 :             .read()
    7643            0 :             .unwrap()
    7644            0 :             .nodes
    7645            0 :             .get(&node_id)
    7646            0 :             .cloned()
    7647            0 :             .ok_or(ApiError::NotFound(
    7648            0 :                 format!("Node {node_id} not registered").into(),
    7649            0 :             ))
    7650            0 :     }
    7651              : 
    7652            0 :     pub(crate) async fn get_node_shards(
    7653            0 :         &self,
    7654            0 :         node_id: NodeId,
    7655            0 :     ) -> Result<NodeShardResponse, ApiError> {
    7656            0 :         let locked = self.inner.read().unwrap();
    7657            0 :         let mut shards = Vec::new();
    7658            0 :         for (tid, tenant) in locked.tenants.iter() {
    7659            0 :             let is_intended_secondary = match (
    7660            0 :                 tenant.intent.get_attached() == &Some(node_id),
    7661            0 :                 tenant.intent.get_secondary().contains(&node_id),
    7662            0 :             ) {
    7663              :                 (true, true) => {
    7664            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    7665            0 :                         "{} attached as primary+secondary on the same node",
    7666            0 :                         tid
    7667            0 :                     )));
    7668              :                 }
    7669            0 :                 (true, false) => Some(false),
    7670            0 :                 (false, true) => Some(true),
    7671            0 :                 (false, false) => None,
    7672              :             };
    7673            0 :             let is_observed_secondary = if let Some(ObservedStateLocation { conf: Some(conf) }) =
    7674            0 :                 tenant.observed.locations.get(&node_id)
    7675              :             {
    7676            0 :                 Some(conf.secondary_conf.is_some())
    7677              :             } else {
    7678            0 :                 None
    7679              :             };
    7680            0 :             if is_intended_secondary.is_some() || is_observed_secondary.is_some() {
    7681            0 :                 shards.push(NodeShard {
    7682            0 :                     tenant_shard_id: *tid,
    7683            0 :                     is_intended_secondary,
    7684            0 :                     is_observed_secondary,
    7685            0 :                 });
    7686            0 :             }
    7687              :         }
    7688            0 :         Ok(NodeShardResponse { node_id, shards })
    7689            0 :     }
    7690              : 
    7691            0 :     pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
    7692            0 :         self.persistence.get_leader().await
    7693            0 :     }
    7694              : 
    7695            0 :     pub(crate) async fn node_register(
    7696            0 :         &self,
    7697            0 :         register_req: NodeRegisterRequest,
    7698            0 :     ) -> Result<(), ApiError> {
    7699            0 :         let _node_lock = trace_exclusive_lock(
    7700            0 :             &self.node_op_locks,
    7701            0 :             register_req.node_id,
    7702            0 :             NodeOperations::Register,
    7703            0 :         )
    7704            0 :         .await;
    7705              : 
    7706              :         #[derive(PartialEq)]
    7707              :         enum RegistrationStatus {
    7708              :             UpToDate,
    7709              :             NeedUpdate,
    7710              :             Mismatched,
    7711              :             New,
    7712              :         }
    7713              : 
    7714            0 :         let registration_status = {
    7715            0 :             let locked = self.inner.read().unwrap();
    7716            0 :             if let Some(node) = locked.nodes.get(&register_req.node_id) {
    7717            0 :                 if node.registration_match(&register_req) {
    7718            0 :                     if node.need_update(&register_req) {
    7719            0 :                         RegistrationStatus::NeedUpdate
    7720              :                     } else {
    7721            0 :                         RegistrationStatus::UpToDate
    7722              :                     }
    7723              :                 } else {
    7724            0 :                     RegistrationStatus::Mismatched
    7725              :                 }
    7726              :             } else {
    7727            0 :                 RegistrationStatus::New
    7728              :             }
    7729              :         };
    7730              : 
    7731            0 :         match registration_status {
    7732              :             RegistrationStatus::UpToDate => {
    7733            0 :                 tracing::info!(
    7734            0 :                     "Node {} re-registered with matching address and is up to date",
    7735              :                     register_req.node_id
    7736              :                 );
    7737              : 
    7738            0 :                 return Ok(());
    7739              :             }
    7740              :             RegistrationStatus::Mismatched => {
    7741              :                 // TODO: decide if we want to allow modifying node addresses without removing and re-adding
    7742              :                 // the node.  Safest/simplest thing is to refuse it, and usually we deploy with
    7743              :                 // a fixed address through the lifetime of a node.
    7744            0 :                 tracing::warn!(
    7745            0 :                     "Node {} tried to register with different address",
    7746              :                     register_req.node_id
    7747              :                 );
    7748            0 :                 return Err(ApiError::Conflict(
    7749            0 :                     "Node is already registered with different address".to_string(),
    7750            0 :                 ));
    7751              :             }
    7752            0 :             RegistrationStatus::New | RegistrationStatus::NeedUpdate => {
    7753            0 :                 // fallthrough
    7754            0 :             }
    7755              :         }
    7756              : 
    7757              :         // We do not require that a node is actually online when registered (it will start life
    7758              :         // with it's  availability set to Offline), but we _do_ require that its DNS record exists. We're
    7759              :         // therefore not immune to asymmetric L3 connectivity issues, but we are protected against nodes
    7760              :         // that register themselves with a broken DNS config.  We check only the HTTP hostname, because
    7761              :         // the postgres hostname might only be resolvable to clients (e.g. if we're on a different VPC than clients).
    7762            0 :         if tokio::net::lookup_host(format!(
    7763            0 :             "{}:{}",
    7764              :             register_req.listen_http_addr, register_req.listen_http_port
    7765              :         ))
    7766            0 :         .await
    7767            0 :         .is_err()
    7768              :         {
    7769              :             // If we have a transient DNS issue, it's up to the caller to retry their registration.  Because
    7770              :             // we can't robustly distinguish between an intermittent issue and a totally bogus DNS situation,
    7771              :             // we return a soft 503 error, to encourage callers to retry past transient issues.
    7772            0 :             return Err(ApiError::ResourceUnavailable(
    7773            0 :                 format!(
    7774            0 :                     "Node {} tried to register with unknown DNS name '{}'",
    7775            0 :                     register_req.node_id, register_req.listen_http_addr
    7776            0 :                 )
    7777            0 :                 .into(),
    7778            0 :             ));
    7779            0 :         }
    7780              : 
    7781            0 :         if self.config.use_https_pageserver_api && register_req.listen_https_port.is_none() {
    7782            0 :             return Err(ApiError::PreconditionFailed(
    7783            0 :                 format!(
    7784            0 :                     "Node {} has no https port, but use_https is enabled",
    7785            0 :                     register_req.node_id
    7786            0 :                 )
    7787            0 :                 .into(),
    7788            0 :             ));
    7789            0 :         }
    7790              : 
    7791            0 :         if register_req.listen_grpc_addr.is_some() != register_req.listen_grpc_port.is_some() {
    7792            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!(
    7793            0 :                 "must specify both gRPC address and port"
    7794            0 :             )));
    7795            0 :         }
    7796              : 
    7797              :         // Ordering: we must persist the new node _before_ adding it to in-memory state.
    7798              :         // This ensures that before we use it for anything or expose it via any external
    7799              :         // API, it is guaranteed to be available after a restart.
    7800            0 :         let new_node = Node::new(
    7801            0 :             register_req.node_id,
    7802            0 :             register_req.listen_http_addr,
    7803            0 :             register_req.listen_http_port,
    7804            0 :             register_req.listen_https_port,
    7805            0 :             register_req.listen_pg_addr,
    7806            0 :             register_req.listen_pg_port,
    7807            0 :             register_req.listen_grpc_addr,
    7808            0 :             register_req.listen_grpc_port,
    7809            0 :             register_req.availability_zone_id.clone(),
    7810            0 :             self.config.use_https_pageserver_api,
    7811              :         );
    7812            0 :         let new_node = match new_node {
    7813            0 :             Ok(new_node) => new_node,
    7814            0 :             Err(error) => return Err(ApiError::InternalServerError(error)),
    7815              :         };
    7816              : 
    7817            0 :         match registration_status {
    7818              :             RegistrationStatus::New => {
    7819            0 :                 self.persistence.insert_node(&new_node).await.map_err(|e| {
    7820            0 :                     if matches!(
    7821            0 :                         e,
    7822              :                         crate::persistence::DatabaseError::Query(
    7823              :                             diesel::result::Error::DatabaseError(
    7824              :                                 diesel::result::DatabaseErrorKind::UniqueViolation,
    7825              :                                 _,
    7826              :                             )
    7827              :                         )
    7828              :                     ) {
    7829              :                         // The node can be deleted by tombstone API, and not show up in the list of nodes.
    7830              :                         // If you see this error, check tombstones first.
    7831            0 :                         ApiError::Conflict(format!("Node {} is already exists", new_node.get_id()))
    7832              :                     } else {
    7833            0 :                         ApiError::from(e)
    7834              :                     }
    7835            0 :                 })?;
    7836              :             }
    7837              :             RegistrationStatus::NeedUpdate => {
    7838            0 :                 self.persistence
    7839            0 :                     .update_node_on_registration(
    7840            0 :                         register_req.node_id,
    7841            0 :                         register_req.listen_https_port,
    7842            0 :                     )
    7843            0 :                     .await?
    7844              :             }
    7845            0 :             _ => unreachable!("Other statuses have been processed earlier"),
    7846              :         }
    7847              : 
    7848            0 :         let mut locked = self.inner.write().unwrap();
    7849            0 :         let mut new_nodes = (*locked.nodes).clone();
    7850              : 
    7851            0 :         locked.scheduler.node_upsert(&new_node);
    7852            0 :         new_nodes.insert(register_req.node_id, new_node);
    7853              : 
    7854            0 :         locked.nodes = Arc::new(new_nodes);
    7855              : 
    7856            0 :         metrics::METRICS_REGISTRY
    7857            0 :             .metrics_group
    7858            0 :             .storage_controller_pageserver_nodes
    7859            0 :             .set(locked.nodes.len() as i64);
    7860            0 :         metrics::METRICS_REGISTRY
    7861            0 :             .metrics_group
    7862            0 :             .storage_controller_https_pageserver_nodes
    7863            0 :             .set(locked.nodes.values().filter(|n| n.has_https_port()).count() as i64);
    7864              : 
    7865            0 :         match registration_status {
    7866              :             RegistrationStatus::New => {
    7867            0 :                 tracing::info!(
    7868            0 :                     "Registered pageserver {} ({}), now have {} pageservers",
    7869              :                     register_req.node_id,
    7870              :                     register_req.availability_zone_id,
    7871            0 :                     locked.nodes.len()
    7872              :                 );
    7873              :             }
    7874              :             RegistrationStatus::NeedUpdate => {
    7875            0 :                 tracing::info!(
    7876            0 :                     "Re-registered and updated node {} ({})",
    7877              :                     register_req.node_id,
    7878              :                     register_req.availability_zone_id,
    7879              :                 );
    7880              :             }
    7881            0 :             _ => unreachable!("Other statuses have been processed earlier"),
    7882              :         }
    7883            0 :         Ok(())
    7884            0 :     }
    7885              : 
    7886              :     /// Configure in-memory and persistent state of a node as requested
    7887              :     ///
    7888              :     /// Note that this function does not trigger any immediate side effects in response
    7889              :     /// to the changes. That part is handled by [`Self::handle_node_availability_transition`].
    7890            0 :     async fn node_state_configure(
    7891            0 :         &self,
    7892            0 :         node_id: NodeId,
    7893            0 :         availability: Option<NodeAvailability>,
    7894            0 :         scheduling: Option<NodeSchedulingPolicy>,
    7895            0 :         node_lock: &TracingExclusiveGuard<NodeOperations>,
    7896            0 :     ) -> Result<AvailabilityTransition, ApiError> {
    7897            0 :         if let Some(scheduling) = scheduling {
    7898              :             // Scheduling is a persistent part of Node: we must write updates to the database before
    7899              :             // applying them in memory
    7900            0 :             self.persistence
    7901            0 :                 .update_node_scheduling_policy(node_id, scheduling)
    7902            0 :                 .await?;
    7903            0 :         }
    7904              : 
    7905              :         // If we're activating a node, then before setting it active we must reconcile any shard locations
    7906              :         // on that node, in case it is out of sync, e.g. due to being unavailable during controller startup,
    7907              :         // by calling [`Self::node_activate_reconcile`]
    7908              :         //
    7909              :         // The transition we calculate here remains valid later in the function because we hold the op lock on the node:
    7910              :         // nothing else can mutate its availability while we run.
    7911            0 :         let availability_transition = if let Some(input_availability) = availability.as_ref() {
    7912            0 :             let (activate_node, availability_transition) = {
    7913            0 :                 let locked = self.inner.read().unwrap();
    7914            0 :                 let Some(node) = locked.nodes.get(&node_id) else {
    7915            0 :                     return Err(ApiError::NotFound(
    7916            0 :                         anyhow::anyhow!("Node {} not registered", node_id).into(),
    7917            0 :                     ));
    7918              :                 };
    7919              : 
    7920            0 :                 (
    7921            0 :                     node.clone(),
    7922            0 :                     node.get_availability_transition(input_availability),
    7923            0 :                 )
    7924              :             };
    7925              : 
    7926            0 :             if matches!(availability_transition, AvailabilityTransition::ToActive) {
    7927            0 :                 self.node_activate_reconcile(activate_node, node_lock)
    7928            0 :                     .await?;
    7929            0 :             }
    7930            0 :             availability_transition
    7931              :         } else {
    7932            0 :             AvailabilityTransition::Unchanged
    7933              :         };
    7934              : 
    7935              :         // Apply changes from the request to our in-memory state for the Node
    7936            0 :         let mut locked = self.inner.write().unwrap();
    7937            0 :         let (nodes, _tenants, scheduler) = locked.parts_mut();
    7938              : 
    7939            0 :         let mut new_nodes = (**nodes).clone();
    7940              : 
    7941            0 :         let Some(node) = new_nodes.get_mut(&node_id) else {
    7942            0 :             return Err(ApiError::NotFound(
    7943            0 :                 anyhow::anyhow!("Node not registered").into(),
    7944            0 :             ));
    7945              :         };
    7946              : 
    7947            0 :         if let Some(availability) = availability {
    7948            0 :             node.set_availability(availability);
    7949            0 :         }
    7950              : 
    7951            0 :         if let Some(scheduling) = scheduling {
    7952            0 :             node.set_scheduling(scheduling);
    7953            0 :         }
    7954              : 
    7955              :         // Update the scheduler, in case the elegibility of the node for new shards has changed
    7956            0 :         scheduler.node_upsert(node);
    7957              : 
    7958            0 :         let new_nodes = Arc::new(new_nodes);
    7959            0 :         locked.nodes = new_nodes;
    7960              : 
    7961            0 :         Ok(availability_transition)
    7962            0 :     }
    7963              : 
    7964              :     /// Handle availability transition of one node
    7965              :     ///
    7966              :     /// Note that you should first call [`Self::node_state_configure`] to update
    7967              :     /// the in-memory state referencing that node. If you need to handle more than one transition
    7968              :     /// consider using [`Self::handle_node_availability_transitions`].
    7969            0 :     async fn handle_node_availability_transition(
    7970            0 :         &self,
    7971            0 :         node_id: NodeId,
    7972            0 :         transition: AvailabilityTransition,
    7973            0 :         _node_lock: &TracingExclusiveGuard<NodeOperations>,
    7974            0 :     ) -> Result<(), ApiError> {
    7975              :         // Modify scheduling state for any Tenants that are affected by a change in the node's availability state.
    7976            0 :         match transition {
    7977              :             AvailabilityTransition::ToOffline => {
    7978            0 :                 tracing::info!("Node {} transition to offline", node_id);
    7979              : 
    7980            0 :                 let mut locked = self.inner.write().unwrap();
    7981            0 :                 let (nodes, tenants, scheduler) = locked.parts_mut();
    7982              : 
    7983            0 :                 let mut tenants_affected: usize = 0;
    7984              : 
    7985            0 :                 for (_tenant_id, mut schedule_context, shards) in
    7986            0 :                     TenantShardExclusiveIterator::new(tenants, ScheduleMode::Normal)
    7987              :                 {
    7988            0 :                     for tenant_shard in shards {
    7989            0 :                         let tenant_shard_id = tenant_shard.tenant_shard_id;
    7990            0 :                         if let Some(observed_loc) =
    7991            0 :                             tenant_shard.observed.locations.get_mut(&node_id)
    7992            0 :                         {
    7993            0 :                             // When a node goes offline, we set its observed configuration to None, indicating unknown: we will
    7994            0 :                             // not assume our knowledge of the node's configuration is accurate until it comes back online
    7995            0 :                             observed_loc.conf = None;
    7996            0 :                         }
    7997              : 
    7998            0 :                         if nodes.len() == 1 {
    7999              :                             // Special case for single-node cluster: there is no point trying to reschedule
    8000              :                             // any tenant shards: avoid doing so, in order to avoid spewing warnings about
    8001              :                             // failures to schedule them.
    8002            0 :                             continue;
    8003            0 :                         }
    8004              : 
    8005            0 :                         if !nodes
    8006            0 :                             .values()
    8007            0 :                             .any(|n| matches!(n.may_schedule(), MaySchedule::Yes(_)))
    8008              :                         {
    8009              :                             // Special case for when all nodes are unavailable and/or unschedulable: there is no point
    8010              :                             // trying to reschedule since there's nowhere else to go. Without this
    8011              :                             // branch we incorrectly detach tenants in response to node unavailability.
    8012            0 :                             continue;
    8013            0 :                         }
    8014              : 
    8015            0 :                         if tenant_shard.intent.demote_attached(scheduler, node_id) {
    8016            0 :                             tenant_shard.sequence = tenant_shard.sequence.next();
    8017              : 
    8018            0 :                             match tenant_shard.schedule(scheduler, &mut schedule_context) {
    8019            0 :                                 Err(e) => {
    8020              :                                     // It is possible that some tenants will become unschedulable when too many pageservers
    8021              :                                     // go offline: in this case there isn't much we can do other than make the issue observable.
    8022              :                                     // TODO: give TenantShard a scheduling error attribute to be queried later.
    8023            0 :                                     tracing::warn!(%tenant_shard_id, "Scheduling error when marking pageserver {} offline: {e}", node_id);
    8024              :                                 }
    8025              :                                 Ok(()) => {
    8026            0 :                                     if self
    8027            0 :                                         .maybe_reconcile_shard(
    8028            0 :                                             tenant_shard,
    8029            0 :                                             nodes,
    8030            0 :                                             ReconcilerPriority::Normal,
    8031            0 :                                         )
    8032            0 :                                         .is_some()
    8033            0 :                                     {
    8034            0 :                                         tenants_affected += 1;
    8035            0 :                                     };
    8036              :                                 }
    8037              :                             }
    8038            0 :                         }
    8039              :                     }
    8040              :                 }
    8041            0 :                 tracing::info!(
    8042            0 :                     "Launched {} reconciler tasks for tenants affected by node {} going offline",
    8043              :                     tenants_affected,
    8044              :                     node_id
    8045              :                 )
    8046              :             }
    8047              :             AvailabilityTransition::ToActive => {
    8048            0 :                 tracing::info!("Node {} transition to active", node_id);
    8049              : 
    8050            0 :                 let mut locked = self.inner.write().unwrap();
    8051            0 :                 let (nodes, tenants, _scheduler) = locked.parts_mut();
    8052              : 
    8053              :                 // When a node comes back online, we must reconcile any tenant that has a None observed
    8054              :                 // location on the node.
    8055            0 :                 for tenant_shard in tenants.values_mut() {
    8056              :                     // If a reconciliation is already in progress, rely on the previous scheduling
    8057              :                     // decision and skip triggering a new reconciliation.
    8058            0 :                     if tenant_shard.reconciler.is_some() {
    8059            0 :                         continue;
    8060            0 :                     }
    8061              : 
    8062            0 :                     if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
    8063            0 :                         if observed_loc.conf.is_none() {
    8064            0 :                             self.maybe_reconcile_shard(
    8065            0 :                                 tenant_shard,
    8066            0 :                                 nodes,
    8067            0 :                                 ReconcilerPriority::Normal,
    8068            0 :                             );
    8069            0 :                         }
    8070            0 :                     }
    8071              :                 }
    8072              : 
    8073              :                 // TODO: in the background, we should balance work back onto this pageserver
    8074              :             }
    8075              :             // No action required for the intermediate unavailable state.
    8076              :             // When we transition into active or offline from the unavailable state,
    8077              :             // the correct handling above will kick in.
    8078              :             AvailabilityTransition::ToWarmingUpFromActive => {
    8079            0 :                 tracing::info!("Node {} transition to unavailable from active", node_id);
    8080              :             }
    8081              :             AvailabilityTransition::ToWarmingUpFromOffline => {
    8082            0 :                 tracing::info!("Node {} transition to unavailable from offline", node_id);
    8083              :             }
    8084              :             AvailabilityTransition::Unchanged => {
    8085            0 :                 tracing::debug!("Node {} no availability change during config", node_id);
    8086              :             }
    8087              :         }
    8088              : 
    8089            0 :         Ok(())
    8090            0 :     }
    8091              : 
    8092              :     /// Handle availability transition for multiple nodes
    8093              :     ///
    8094              :     /// Note that you should first call [`Self::node_state_configure`] for
    8095              :     /// all nodes being handled here for the handling to use fresh in-memory state.
    8096            0 :     async fn handle_node_availability_transitions(
    8097            0 :         &self,
    8098            0 :         transitions: Vec<(
    8099            0 :             NodeId,
    8100            0 :             TracingExclusiveGuard<NodeOperations>,
    8101            0 :             AvailabilityTransition,
    8102            0 :         )>,
    8103            0 :     ) -> Result<(), Vec<(NodeId, ApiError)>> {
    8104            0 :         let mut errors = Vec::default();
    8105            0 :         for (node_id, node_lock, transition) in transitions {
    8106            0 :             let res = self
    8107            0 :                 .handle_node_availability_transition(node_id, transition, &node_lock)
    8108            0 :                 .await;
    8109            0 :             if let Err(err) = res {
    8110            0 :                 errors.push((node_id, err));
    8111            0 :             }
    8112              :         }
    8113              : 
    8114            0 :         if errors.is_empty() {
    8115            0 :             Ok(())
    8116              :         } else {
    8117            0 :             Err(errors)
    8118              :         }
    8119            0 :     }
    8120              : 
    8121            0 :     pub(crate) async fn node_configure(
    8122            0 :         &self,
    8123            0 :         node_id: NodeId,
    8124            0 :         availability: Option<NodeAvailability>,
    8125            0 :         scheduling: Option<NodeSchedulingPolicy>,
    8126            0 :     ) -> Result<(), ApiError> {
    8127            0 :         let node_lock =
    8128            0 :             trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Configure).await;
    8129              : 
    8130            0 :         let transition = self
    8131            0 :             .node_state_configure(node_id, availability, scheduling, &node_lock)
    8132            0 :             .await?;
    8133            0 :         self.handle_node_availability_transition(node_id, transition, &node_lock)
    8134            0 :             .await
    8135            0 :     }
    8136              : 
    8137              :     /// Wrapper around [`Self::node_configure`] which only allows changes while there is no ongoing
    8138              :     /// operation for HTTP api.
    8139            0 :     pub(crate) async fn external_node_configure(
    8140            0 :         &self,
    8141            0 :         node_id: NodeId,
    8142            0 :         availability: Option<NodeAvailability>,
    8143            0 :         scheduling: Option<NodeSchedulingPolicy>,
    8144            0 :     ) -> Result<(), ApiError> {
    8145              :         {
    8146            0 :             let locked = self.inner.read().unwrap();
    8147            0 :             if let Some(op) = locked.ongoing_operation.as_ref().map(|op| op.operation) {
    8148            0 :                 return Err(ApiError::PreconditionFailed(
    8149            0 :                     format!("Ongoing background operation forbids configuring: {op}").into(),
    8150            0 :                 ));
    8151            0 :             }
    8152              :         }
    8153              : 
    8154            0 :         self.node_configure(node_id, availability, scheduling).await
    8155            0 :     }
    8156              : 
    8157            0 :     pub(crate) async fn start_node_delete(
    8158            0 :         self: &Arc<Self>,
    8159            0 :         node_id: NodeId,
    8160            0 :         force: bool,
    8161            0 :     ) -> Result<(), ApiError> {
    8162            0 :         let (ongoing_op, node_policy, schedulable_nodes_count) = {
    8163            0 :             let locked = self.inner.read().unwrap();
    8164            0 :             let nodes = &locked.nodes;
    8165            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    8166            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    8167            0 :             ))?;
    8168            0 :             let schedulable_nodes_count = nodes
    8169            0 :                 .iter()
    8170            0 :                 .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
    8171            0 :                 .count();
    8172              : 
    8173              :             (
    8174            0 :                 locked
    8175            0 :                     .ongoing_operation
    8176            0 :                     .as_ref()
    8177            0 :                     .map(|ongoing| ongoing.operation),
    8178            0 :                 node.get_scheduling(),
    8179            0 :                 schedulable_nodes_count,
    8180              :             )
    8181              :         };
    8182              : 
    8183            0 :         if let Some(ongoing) = ongoing_op {
    8184            0 :             return Err(ApiError::PreconditionFailed(
    8185            0 :                 format!("Background operation already ongoing for node: {ongoing}").into(),
    8186            0 :             ));
    8187            0 :         }
    8188              : 
    8189            0 :         if schedulable_nodes_count == 0 {
    8190            0 :             return Err(ApiError::PreconditionFailed(
    8191            0 :                 "No other schedulable nodes to move shards".into(),
    8192            0 :             ));
    8193            0 :         }
    8194              : 
    8195            0 :         match node_policy {
    8196              :             NodeSchedulingPolicy::Active | NodeSchedulingPolicy::Pause => {
    8197            0 :                 self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Deleting))
    8198            0 :                     .await?;
    8199              : 
    8200            0 :                 let cancel = self.cancel.child_token();
    8201            0 :                 let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
    8202            0 :                 let policy_on_start = node_policy;
    8203              : 
    8204            0 :                 self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
    8205            0 :                     operation: Operation::Delete(Delete { node_id }),
    8206            0 :                     cancel: cancel.clone(),
    8207            0 :                 });
    8208              : 
    8209            0 :                 let span = tracing::info_span!(parent: None, "delete_node", %node_id);
    8210              : 
    8211            0 :                 tokio::task::spawn(
    8212              :                     {
    8213            0 :                         let service = self.clone();
    8214            0 :                         let cancel = cancel.clone();
    8215            0 :                         async move {
    8216            0 :                             let _gate_guard = gate_guard;
    8217              : 
    8218            0 :                             scopeguard::defer! {
    8219              :                                 let prev = service.inner.write().unwrap().ongoing_operation.take();
    8220              : 
    8221              :                                 if let Some(Operation::Delete(removed_delete)) = prev.map(|h| h.operation) {
    8222              :                                     assert_eq!(removed_delete.node_id, node_id, "We always take the same operation");
    8223              :                                 } else {
    8224              :                                     panic!("We always remove the same operation")
    8225              :                                 }
    8226              :                             }
    8227              : 
    8228            0 :                             tracing::info!("Delete background operation starting");
    8229            0 :                             let res = service
    8230            0 :                                 .delete_node(node_id, policy_on_start, force, cancel)
    8231            0 :                                 .await;
    8232            0 :                             match res {
    8233              :                                 Ok(()) => {
    8234            0 :                                     tracing::info!(
    8235            0 :                                         "Delete background operation completed successfully"
    8236              :                                     );
    8237              :                                 }
    8238              :                                 Err(OperationError::Cancelled) => {
    8239            0 :                                     tracing::info!("Delete background operation was cancelled");
    8240              :                                 }
    8241            0 :                                 Err(err) => {
    8242            0 :                                     tracing::error!(
    8243            0 :                                         "Delete background operation encountered: {err}"
    8244              :                                     )
    8245              :                                 }
    8246              :                             }
    8247            0 :                         }
    8248              :                     }
    8249            0 :                     .instrument(span),
    8250              :                 );
    8251              :             }
    8252              :             NodeSchedulingPolicy::Deleting => {
    8253            0 :                 return Err(ApiError::Conflict(format!(
    8254            0 :                     "Node {node_id} has delete in progress"
    8255            0 :                 )));
    8256              :             }
    8257            0 :             policy => {
    8258            0 :                 return Err(ApiError::PreconditionFailed(
    8259            0 :                     format!("Node {node_id} cannot be deleted due to {policy:?} policy").into(),
    8260            0 :                 ));
    8261              :             }
    8262              :         }
    8263              : 
    8264            0 :         Ok(())
    8265            0 :     }
    8266              : 
    8267            0 :     pub(crate) async fn cancel_node_delete(
    8268            0 :         self: &Arc<Self>,
    8269            0 :         node_id: NodeId,
    8270            0 :     ) -> Result<(), ApiError> {
    8271              :         {
    8272            0 :             let locked = self.inner.read().unwrap();
    8273            0 :             let nodes = &locked.nodes;
    8274            0 :             nodes.get(&node_id).ok_or(ApiError::NotFound(
    8275            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    8276            0 :             ))?;
    8277              :         }
    8278              : 
    8279            0 :         if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
    8280            0 :             if let Operation::Delete(delete) = op_handler.operation {
    8281            0 :                 if delete.node_id == node_id {
    8282            0 :                     tracing::info!("Cancelling background delete operation for node {node_id}");
    8283            0 :                     op_handler.cancel.cancel();
    8284            0 :                     return Ok(());
    8285            0 :                 }
    8286            0 :             }
    8287            0 :         }
    8288              : 
    8289            0 :         Err(ApiError::PreconditionFailed(
    8290            0 :             format!("Node {node_id} has no delete in progress").into(),
    8291            0 :         ))
    8292            0 :     }
    8293              : 
    8294            0 :     pub(crate) async fn start_node_drain(
    8295            0 :         self: &Arc<Self>,
    8296            0 :         node_id: NodeId,
    8297            0 :     ) -> Result<(), ApiError> {
    8298            0 :         let (ongoing_op, node_available, node_policy, schedulable_nodes_count) = {
    8299            0 :             let locked = self.inner.read().unwrap();
    8300            0 :             let nodes = &locked.nodes;
    8301            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    8302            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    8303            0 :             ))?;
    8304            0 :             let schedulable_nodes_count = nodes
    8305            0 :                 .iter()
    8306            0 :                 .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
    8307            0 :                 .count();
    8308              : 
    8309              :             (
    8310            0 :                 locked
    8311            0 :                     .ongoing_operation
    8312            0 :                     .as_ref()
    8313            0 :                     .map(|ongoing| ongoing.operation),
    8314            0 :                 node.is_available(),
    8315            0 :                 node.get_scheduling(),
    8316            0 :                 schedulable_nodes_count,
    8317              :             )
    8318              :         };
    8319              : 
    8320            0 :         if let Some(ongoing) = ongoing_op {
    8321            0 :             return Err(ApiError::PreconditionFailed(
    8322            0 :                 format!("Background operation already ongoing for node: {ongoing}").into(),
    8323            0 :             ));
    8324            0 :         }
    8325              : 
    8326            0 :         if !node_available {
    8327            0 :             return Err(ApiError::ResourceUnavailable(
    8328            0 :                 format!("Node {node_id} is currently unavailable").into(),
    8329            0 :             ));
    8330            0 :         }
    8331              : 
    8332            0 :         if schedulable_nodes_count == 0 {
    8333            0 :             return Err(ApiError::PreconditionFailed(
    8334            0 :                 "No other schedulable nodes to drain to".into(),
    8335            0 :             ));
    8336            0 :         }
    8337              : 
    8338            0 :         match node_policy {
    8339              :             NodeSchedulingPolicy::Active => {
    8340            0 :                 self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Draining))
    8341            0 :                     .await?;
    8342              : 
    8343            0 :                 let cancel = self.cancel.child_token();
    8344            0 :                 let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
    8345              : 
    8346            0 :                 self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
    8347            0 :                     operation: Operation::Drain(Drain { node_id }),
    8348            0 :                     cancel: cancel.clone(),
    8349            0 :                 });
    8350              : 
    8351            0 :                 let span = tracing::info_span!(parent: None, "drain_node", %node_id);
    8352              : 
    8353            0 :                 tokio::task::spawn({
    8354            0 :                     let service = self.clone();
    8355            0 :                     let cancel = cancel.clone();
    8356            0 :                     async move {
    8357            0 :                         let _gate_guard = gate_guard;
    8358              : 
    8359            0 :                         scopeguard::defer! {
    8360              :                             let prev = service.inner.write().unwrap().ongoing_operation.take();
    8361              : 
    8362              :                             if let Some(Operation::Drain(removed_drain)) = prev.map(|h| h.operation) {
    8363              :                                 assert_eq!(removed_drain.node_id, node_id, "We always take the same operation");
    8364              :                             } else {
    8365              :                                 panic!("We always remove the same operation")
    8366              :                             }
    8367              :                         }
    8368              : 
    8369            0 :                         tracing::info!("Drain background operation starting");
    8370            0 :                         let res = service.drain_node(node_id, cancel).await;
    8371            0 :                         match res {
    8372              :                             Ok(()) => {
    8373            0 :                                 tracing::info!("Drain background operation completed successfully");
    8374              :                             }
    8375              :                             Err(OperationError::Cancelled) => {
    8376            0 :                                 tracing::info!("Drain background operation was cancelled");
    8377              :                             }
    8378            0 :                             Err(err) => {
    8379            0 :                                 tracing::error!("Drain background operation encountered: {err}")
    8380              :                             }
    8381              :                         }
    8382            0 :                     }
    8383            0 :                 }.instrument(span));
    8384              :             }
    8385              :             NodeSchedulingPolicy::Draining => {
    8386            0 :                 return Err(ApiError::Conflict(format!(
    8387            0 :                     "Node {node_id} has drain in progress"
    8388            0 :                 )));
    8389              :             }
    8390            0 :             policy => {
    8391            0 :                 return Err(ApiError::PreconditionFailed(
    8392            0 :                     format!("Node {node_id} cannot be drained due to {policy:?} policy").into(),
    8393            0 :                 ));
    8394              :             }
    8395              :         }
    8396              : 
    8397            0 :         Ok(())
    8398            0 :     }
    8399              : 
    8400            0 :     pub(crate) async fn cancel_node_drain(&self, node_id: NodeId) -> Result<(), ApiError> {
    8401            0 :         let node_available = {
    8402            0 :             let locked = self.inner.read().unwrap();
    8403            0 :             let nodes = &locked.nodes;
    8404            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    8405            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    8406            0 :             ))?;
    8407              : 
    8408            0 :             node.is_available()
    8409              :         };
    8410              : 
    8411            0 :         if !node_available {
    8412            0 :             return Err(ApiError::ResourceUnavailable(
    8413            0 :                 format!("Node {node_id} is currently unavailable").into(),
    8414            0 :             ));
    8415            0 :         }
    8416              : 
    8417            0 :         if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
    8418            0 :             if let Operation::Drain(drain) = op_handler.operation {
    8419            0 :                 if drain.node_id == node_id {
    8420            0 :                     tracing::info!("Cancelling background drain operation for node {node_id}");
    8421            0 :                     op_handler.cancel.cancel();
    8422            0 :                     return Ok(());
    8423            0 :                 }
    8424            0 :             }
    8425            0 :         }
    8426              : 
    8427            0 :         Err(ApiError::PreconditionFailed(
    8428            0 :             format!("Node {node_id} has no drain in progress").into(),
    8429            0 :         ))
    8430            0 :     }
    8431              : 
    8432            0 :     pub(crate) async fn start_node_fill(self: &Arc<Self>, node_id: NodeId) -> Result<(), ApiError> {
    8433            0 :         let (ongoing_op, node_available, node_policy, total_nodes_count) = {
    8434            0 :             let locked = self.inner.read().unwrap();
    8435            0 :             let nodes = &locked.nodes;
    8436            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    8437            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    8438            0 :             ))?;
    8439              : 
    8440              :             (
    8441            0 :                 locked
    8442            0 :                     .ongoing_operation
    8443            0 :                     .as_ref()
    8444            0 :                     .map(|ongoing| ongoing.operation),
    8445            0 :                 node.is_available(),
    8446            0 :                 node.get_scheduling(),
    8447            0 :                 nodes.len(),
    8448              :             )
    8449              :         };
    8450              : 
    8451            0 :         if let Some(ongoing) = ongoing_op {
    8452            0 :             return Err(ApiError::PreconditionFailed(
    8453            0 :                 format!("Background operation already ongoing for node: {ongoing}").into(),
    8454            0 :             ));
    8455            0 :         }
    8456              : 
    8457            0 :         if !node_available {
    8458            0 :             return Err(ApiError::ResourceUnavailable(
    8459            0 :                 format!("Node {node_id} is currently unavailable").into(),
    8460            0 :             ));
    8461            0 :         }
    8462              : 
    8463            0 :         if total_nodes_count <= 1 {
    8464            0 :             return Err(ApiError::PreconditionFailed(
    8465            0 :                 "No other nodes to fill from".into(),
    8466            0 :             ));
    8467            0 :         }
    8468              : 
    8469            0 :         match node_policy {
    8470              :             NodeSchedulingPolicy::Active => {
    8471            0 :                 self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Filling))
    8472            0 :                     .await?;
    8473              : 
    8474            0 :                 let cancel = self.cancel.child_token();
    8475            0 :                 let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
    8476              : 
    8477            0 :                 self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
    8478            0 :                     operation: Operation::Fill(Fill { node_id }),
    8479            0 :                     cancel: cancel.clone(),
    8480            0 :                 });
    8481              : 
    8482            0 :                 let span = tracing::info_span!(parent: None, "fill_node", %node_id);
    8483              : 
    8484            0 :                 tokio::task::spawn({
    8485            0 :                     let service = self.clone();
    8486            0 :                     let cancel = cancel.clone();
    8487            0 :                     async move {
    8488            0 :                         let _gate_guard = gate_guard;
    8489              : 
    8490            0 :                         scopeguard::defer! {
    8491              :                             let prev = service.inner.write().unwrap().ongoing_operation.take();
    8492              : 
    8493              :                             if let Some(Operation::Fill(removed_fill)) = prev.map(|h| h.operation) {
    8494              :                                 assert_eq!(removed_fill.node_id, node_id, "We always take the same operation");
    8495              :                             } else {
    8496              :                                 panic!("We always remove the same operation")
    8497              :                             }
    8498              :                         }
    8499              : 
    8500            0 :                         tracing::info!("Fill background operation starting");
    8501            0 :                         let res = service.fill_node(node_id, cancel).await;
    8502            0 :                         match res {
    8503              :                             Ok(()) => {
    8504            0 :                                 tracing::info!("Fill background operation completed successfully");
    8505              :                             }
    8506              :                             Err(OperationError::Cancelled) => {
    8507            0 :                                 tracing::info!("Fill background operation was cancelled");
    8508              :                             }
    8509            0 :                             Err(err) => {
    8510            0 :                                 tracing::error!("Fill background operation encountered: {err}")
    8511              :                             }
    8512              :                         }
    8513            0 :                     }
    8514            0 :                 }.instrument(span));
    8515              :             }
    8516              :             NodeSchedulingPolicy::Filling => {
    8517            0 :                 return Err(ApiError::Conflict(format!(
    8518            0 :                     "Node {node_id} has fill in progress"
    8519            0 :                 )));
    8520              :             }
    8521            0 :             policy => {
    8522            0 :                 return Err(ApiError::PreconditionFailed(
    8523            0 :                     format!("Node {node_id} cannot be filled due to {policy:?} policy").into(),
    8524            0 :                 ));
    8525              :             }
    8526              :         }
    8527              : 
    8528            0 :         Ok(())
    8529            0 :     }
    8530              : 
    8531            0 :     pub(crate) async fn cancel_node_fill(&self, node_id: NodeId) -> Result<(), ApiError> {
    8532            0 :         let node_available = {
    8533            0 :             let locked = self.inner.read().unwrap();
    8534            0 :             let nodes = &locked.nodes;
    8535            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    8536            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    8537            0 :             ))?;
    8538              : 
    8539            0 :             node.is_available()
    8540              :         };
    8541              : 
    8542            0 :         if !node_available {
    8543            0 :             return Err(ApiError::ResourceUnavailable(
    8544            0 :                 format!("Node {node_id} is currently unavailable").into(),
    8545            0 :             ));
    8546            0 :         }
    8547              : 
    8548            0 :         if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
    8549            0 :             if let Operation::Fill(fill) = op_handler.operation {
    8550            0 :                 if fill.node_id == node_id {
    8551            0 :                     tracing::info!("Cancelling background drain operation for node {node_id}");
    8552            0 :                     op_handler.cancel.cancel();
    8553            0 :                     return Ok(());
    8554            0 :                 }
    8555            0 :             }
    8556            0 :         }
    8557              : 
    8558            0 :         Err(ApiError::PreconditionFailed(
    8559            0 :             format!("Node {node_id} has no fill in progress").into(),
    8560            0 :         ))
    8561            0 :     }
    8562              : 
    8563              :     /// Like [`Self::maybe_configured_reconcile_shard`], but uses the default reconciler
    8564              :     /// configuration
    8565            0 :     fn maybe_reconcile_shard(
    8566            0 :         &self,
    8567            0 :         shard: &mut TenantShard,
    8568            0 :         nodes: &Arc<HashMap<NodeId, Node>>,
    8569            0 :         priority: ReconcilerPriority,
    8570            0 :     ) -> Option<ReconcilerWaiter> {
    8571            0 :         self.maybe_configured_reconcile_shard(shard, nodes, ReconcilerConfig::new(priority))
    8572            0 :     }
    8573              : 
    8574              :     /// Before constructing a Reconciler, acquire semaphore units from the appropriate concurrency limit (depends on priority)
    8575            0 :     fn get_reconciler_units(
    8576            0 :         &self,
    8577            0 :         priority: ReconcilerPriority,
    8578            0 :     ) -> Result<ReconcileUnits, TryAcquireError> {
    8579            0 :         let units = match priority {
    8580            0 :             ReconcilerPriority::Normal => self.reconciler_concurrency.clone().try_acquire_owned(),
    8581              :             ReconcilerPriority::High => {
    8582            0 :                 match self
    8583            0 :                     .priority_reconciler_concurrency
    8584            0 :                     .clone()
    8585            0 :                     .try_acquire_owned()
    8586              :                 {
    8587            0 :                     Ok(u) => Ok(u),
    8588              :                     Err(TryAcquireError::NoPermits) => {
    8589              :                         // If the high priority semaphore is exhausted, then high priority tasks may steal units from
    8590              :                         // the normal priority semaphore.
    8591            0 :                         self.reconciler_concurrency.clone().try_acquire_owned()
    8592              :                     }
    8593            0 :                     Err(e) => Err(e),
    8594              :                 }
    8595              :             }
    8596              :         };
    8597              : 
    8598            0 :         units.map(ReconcileUnits::new)
    8599            0 :     }
    8600              : 
    8601              :     /// Wrap [`TenantShard`] reconciliation methods with acquisition of [`Gate`] and [`ReconcileUnits`],
    8602            0 :     fn maybe_configured_reconcile_shard(
    8603            0 :         &self,
    8604            0 :         shard: &mut TenantShard,
    8605            0 :         nodes: &Arc<HashMap<NodeId, Node>>,
    8606            0 :         reconciler_config: ReconcilerConfig,
    8607            0 :     ) -> Option<ReconcilerWaiter> {
    8608            0 :         let reconcile_needed = shard.get_reconcile_needed(nodes);
    8609              : 
    8610            0 :         let reconcile_reason = match reconcile_needed {
    8611            0 :             ReconcileNeeded::No => return None,
    8612            0 :             ReconcileNeeded::WaitExisting(waiter) => return Some(waiter),
    8613            0 :             ReconcileNeeded::Yes(reason) => {
    8614              :                 // Fall through to try and acquire units for spawning reconciler
    8615            0 :                 reason
    8616              :             }
    8617              :         };
    8618              : 
    8619            0 :         let units = match self.get_reconciler_units(reconciler_config.priority) {
    8620            0 :             Ok(u) => u,
    8621              :             Err(_) => {
    8622            0 :                 tracing::info!(tenant_id=%shard.tenant_shard_id.tenant_id, shard_id=%shard.tenant_shard_id.shard_slug(),
    8623            0 :                     "Concurrency limited: enqueued for reconcile later");
    8624            0 :                 if !shard.delayed_reconcile {
    8625            0 :                     match self.delayed_reconcile_tx.try_send(shard.tenant_shard_id) {
    8626            0 :                         Err(TrySendError::Closed(_)) => {
    8627            0 :                             // Weird mid-shutdown case?
    8628            0 :                         }
    8629              :                         Err(TrySendError::Full(_)) => {
    8630              :                             // It is safe to skip sending our ID in the channel: we will eventually get retried by the background reconcile task.
    8631            0 :                             tracing::warn!(
    8632            0 :                                 "Many shards are waiting to reconcile: delayed_reconcile queue is full"
    8633              :                             );
    8634              :                         }
    8635            0 :                         Ok(()) => {
    8636            0 :                             shard.delayed_reconcile = true;
    8637            0 :                         }
    8638              :                     }
    8639            0 :                 }
    8640              : 
    8641              :                 // We won't spawn a reconciler, but we will construct a waiter that waits for the shard's sequence
    8642              :                 // number to advance.  When this function is eventually called again and succeeds in getting units,
    8643              :                 // it will spawn a reconciler that makes this waiter complete.
    8644            0 :                 return Some(shard.future_reconcile_waiter());
    8645              :             }
    8646              :         };
    8647              : 
    8648            0 :         let Ok(gate_guard) = self.reconcilers_gate.enter() else {
    8649              :             // Gate closed: we're shutting down, drop out.
    8650            0 :             return None;
    8651              :         };
    8652              : 
    8653            0 :         shard.spawn_reconciler(
    8654            0 :             reconcile_reason,
    8655            0 :             &self.result_tx,
    8656            0 :             nodes,
    8657            0 :             &self.compute_hook,
    8658            0 :             reconciler_config,
    8659            0 :             &self.config,
    8660            0 :             &self.persistence,
    8661            0 :             units,
    8662            0 :             gate_guard,
    8663            0 :             &self.reconcilers_cancel,
    8664            0 :             self.http_client.clone(),
    8665              :         )
    8666            0 :     }
    8667              : 
    8668              :     /// Check all tenants for pending reconciliation work, and reconcile those in need.
    8669              :     /// Additionally, reschedule tenants that require it.
    8670              :     ///
    8671              :     /// Returns how many reconciliation tasks were started, or `1` if no reconciles were
    8672              :     /// spawned but some _would_ have been spawned if `reconciler_concurrency` units where
    8673              :     /// available.  A return value of 0 indicates that everything is fully reconciled already.
    8674            0 :     fn reconcile_all(&self) -> ReconcileAllResult {
    8675            0 :         let mut locked = self.inner.write().unwrap();
    8676            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    8677            0 :         let pageservers = nodes.clone();
    8678              : 
    8679              :         // This function is an efficient place to update lazy statistics, since we are walking
    8680              :         // all tenants.
    8681            0 :         let mut pending_reconciles = 0;
    8682            0 :         let mut stuck_reconciles = 0;
    8683            0 :         let mut az_violations = 0;
    8684              : 
    8685              :         // If we find any tenants to drop from memory, stash them to offload after
    8686              :         // we're done traversing the map of tenants.
    8687            0 :         let mut drop_detached_tenants = Vec::new();
    8688              : 
    8689            0 :         let mut spawned_reconciles = 0;
    8690            0 :         let mut has_delayed_reconciles = false;
    8691              : 
    8692            0 :         for shard in tenants.values_mut() {
    8693              :             // Accumulate scheduling statistics
    8694            0 :             if let (Some(attached), Some(preferred)) =
    8695            0 :                 (shard.intent.get_attached(), shard.preferred_az())
    8696              :             {
    8697            0 :                 let node_az = nodes
    8698            0 :                     .get(attached)
    8699            0 :                     .expect("Nodes exist if referenced")
    8700            0 :                     .get_availability_zone_id();
    8701            0 :                 if node_az != preferred {
    8702            0 :                     az_violations += 1;
    8703            0 :                 }
    8704            0 :             }
    8705              : 
    8706              :             // Skip checking if this shard is already enqueued for reconciliation
    8707            0 :             if shard.delayed_reconcile && self.reconciler_concurrency.available_permits() == 0 {
    8708              :                 // If there is something delayed, then return a nonzero count so that
    8709              :                 // callers like reconcile_all_now do not incorrectly get the impression
    8710              :                 // that the system is in a quiescent state.
    8711            0 :                 has_delayed_reconciles = true;
    8712            0 :                 pending_reconciles += 1;
    8713            0 :                 continue;
    8714            0 :             }
    8715              : 
    8716              :             // Eventual consistency: if an earlier reconcile job failed, and the shard is still
    8717              :             // dirty, spawn another one
    8718            0 :             if self
    8719            0 :                 .maybe_reconcile_shard(shard, &pageservers, ReconcilerPriority::Normal)
    8720            0 :                 .is_some()
    8721              :             {
    8722            0 :                 spawned_reconciles += 1;
    8723              : 
    8724            0 :                 if shard.consecutive_reconciles_count >= MAX_CONSECUTIVE_RECONCILES {
    8725              :                     // Count shards that are stuck, butwe still want to reconcile them.
    8726              :                     // We don't want to consider them when deciding to run optimizations.
    8727            0 :                     tracing::warn!(
    8728              :                         tenant_id=%shard.tenant_shard_id.tenant_id,
    8729            0 :                         shard_id=%shard.tenant_shard_id.shard_slug(),
    8730            0 :                         "Shard reconciliation is stuck: {} consecutive launches",
    8731              :                         shard.consecutive_reconciles_count
    8732              :                     );
    8733            0 :                     stuck_reconciles += 1;
    8734            0 :                 }
    8735              :             } else {
    8736            0 :                 if shard.delayed_reconcile {
    8737            0 :                     // Shard wanted to reconcile but for some reason couldn't.
    8738            0 :                     pending_reconciles += 1;
    8739            0 :                 }
    8740              : 
    8741              :                 // Reset the counter when we don't need to launch a reconcile.
    8742            0 :                 shard.consecutive_reconciles_count = 0;
    8743              :             }
    8744              :             // If this tenant is detached, try dropping it from memory. This is usually done
    8745              :             // proactively in [`Self::process_results`], but we do it here to handle the edge
    8746              :             // case where a reconcile completes while someone else is holding an op lock for the tenant.
    8747            0 :             if shard.tenant_shard_id.shard_number == ShardNumber(0)
    8748            0 :                 && shard.policy == PlacementPolicy::Detached
    8749              :             {
    8750            0 :                 if let Some(guard) = self.tenant_op_locks.try_exclusive(
    8751            0 :                     shard.tenant_shard_id.tenant_id,
    8752            0 :                     TenantOperations::DropDetached,
    8753            0 :                 ) {
    8754            0 :                     drop_detached_tenants.push((shard.tenant_shard_id.tenant_id, guard));
    8755            0 :                 }
    8756            0 :             }
    8757              :         }
    8758              : 
    8759              :         // Some metrics are calculated from SchedulerNode state, update these periodically
    8760            0 :         scheduler.update_metrics();
    8761              : 
    8762              :         // Process any deferred tenant drops
    8763            0 :         for (tenant_id, guard) in drop_detached_tenants {
    8764            0 :             self.maybe_drop_tenant(tenant_id, &mut locked, &guard);
    8765            0 :         }
    8766              : 
    8767            0 :         metrics::METRICS_REGISTRY
    8768            0 :             .metrics_group
    8769            0 :             .storage_controller_schedule_az_violation
    8770            0 :             .set(az_violations as i64);
    8771              : 
    8772            0 :         metrics::METRICS_REGISTRY
    8773            0 :             .metrics_group
    8774            0 :             .storage_controller_pending_reconciles
    8775            0 :             .set(pending_reconciles as i64);
    8776              : 
    8777            0 :         metrics::METRICS_REGISTRY
    8778            0 :             .metrics_group
    8779            0 :             .storage_controller_stuck_reconciles
    8780            0 :             .set(stuck_reconciles as i64);
    8781              : 
    8782            0 :         ReconcileAllResult::new(spawned_reconciles, stuck_reconciles, has_delayed_reconciles)
    8783            0 :     }
    8784              : 
    8785              :     /// `optimize` in this context means identifying shards which have valid scheduled locations, but
    8786              :     /// could be scheduled somewhere better:
    8787              :     /// - Cutting over to a secondary if the node with the secondary is more lightly loaded
    8788              :     ///    * e.g. after a node fails then recovers, to move some work back to it
    8789              :     /// - Cutting over to a secondary if it improves the spread of shard attachments within a tenant
    8790              :     ///    * e.g. after a shard split, the initial attached locations will all be on the node where
    8791              :     ///      we did the split, but are probably better placed elsewhere.
    8792              :     /// - Creating new secondary locations if it improves the spreading of a sharded tenant
    8793              :     ///    * e.g. after a shard split, some locations will be on the same node (where the split
    8794              :     ///      happened), and will probably be better placed elsewhere.
    8795              :     ///
    8796              :     /// To put it more briefly: whereas the scheduler respects soft constraints in a ScheduleContext at
    8797              :     /// the time of scheduling, this function looks for cases where a better-scoring location is available
    8798              :     /// according to those same soft constraints.
    8799            0 :     async fn optimize_all(&self) -> usize {
    8800              :         // Limit on how many shards' optmizations each call to this function will execute.  Combined
    8801              :         // with the frequency of background calls, this acts as an implicit rate limit that runs a small
    8802              :         // trickle of optimizations in the background, rather than executing a large number in parallel
    8803              :         // when a change occurs.
    8804              :         const MAX_OPTIMIZATIONS_EXEC_PER_PASS: usize = 16;
    8805              : 
    8806              :         // Synchronous prepare: scan shards for possible scheduling optimizations
    8807            0 :         let candidate_work = self.optimize_all_plan();
    8808            0 :         let candidate_work_len = candidate_work.len();
    8809              : 
    8810              :         // Asynchronous validate: I/O to pageservers to make sure shards are in a good state to apply validation
    8811            0 :         let validated_work = self.optimize_all_validate(candidate_work).await;
    8812              : 
    8813            0 :         let was_work_filtered = validated_work.len() != candidate_work_len;
    8814              : 
    8815              :         // Synchronous apply: update the shards' intent states according to validated optimisations
    8816            0 :         let mut reconciles_spawned = 0;
    8817            0 :         let mut optimizations_applied = 0;
    8818            0 :         let mut locked = self.inner.write().unwrap();
    8819            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    8820            0 :         for (tenant_shard_id, optimization) in validated_work {
    8821            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    8822              :                 // Shard was dropped between planning and execution;
    8823            0 :                 continue;
    8824              :             };
    8825            0 :             tracing::info!(tenant_shard_id=%tenant_shard_id, "Applying optimization: {optimization:?}");
    8826            0 :             if shard.apply_optimization(scheduler, optimization) {
    8827            0 :                 optimizations_applied += 1;
    8828            0 :                 if self
    8829            0 :                     .maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal)
    8830            0 :                     .is_some()
    8831            0 :                 {
    8832            0 :                     reconciles_spawned += 1;
    8833            0 :                 }
    8834            0 :             }
    8835              : 
    8836            0 :             if optimizations_applied >= MAX_OPTIMIZATIONS_EXEC_PER_PASS {
    8837            0 :                 break;
    8838            0 :             }
    8839              :         }
    8840              : 
    8841            0 :         if was_work_filtered {
    8842            0 :             // If we filtered any work out during validation, ensure we return a nonzero value to indicate
    8843            0 :             // to callers that the system is not in a truly quiet state, it's going to do some work as soon
    8844            0 :             // as these validations start passing.
    8845            0 :             reconciles_spawned = std::cmp::max(reconciles_spawned, 1);
    8846            0 :         }
    8847              : 
    8848            0 :         reconciles_spawned
    8849            0 :     }
    8850              : 
    8851            0 :     fn optimize_all_plan(&self) -> Vec<(TenantShardId, ScheduleOptimization)> {
    8852              :         // How many candidate optimizations we will generate, before evaluating them for readniess: setting
    8853              :         // this higher than the execution limit gives us a chance to execute some work even if the first
    8854              :         // few optimizations we find are not ready.
    8855              :         const MAX_OPTIMIZATIONS_PLAN_PER_PASS: usize = 64;
    8856              : 
    8857            0 :         let mut work = Vec::new();
    8858            0 :         let mut locked = self.inner.write().unwrap();
    8859            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    8860              : 
    8861              :         // We are going to plan a bunch of optimisations before applying any of them, so the
    8862              :         // utilisation stats on nodes will be effectively stale for the >1st optimisation we
    8863              :         // generate.  To avoid this causing unstable migrations/flapping, it's important that the
    8864              :         // code in TenantShard for finding optimisations uses [`NodeAttachmentSchedulingScore::disregard_utilization`]
    8865              :         // to ignore the utilisation component of the score.
    8866              : 
    8867            0 :         for (_tenant_id, schedule_context, shards) in
    8868            0 :             TenantShardExclusiveIterator::new(tenants, ScheduleMode::Speculative)
    8869              :         {
    8870            0 :             for shard in shards {
    8871            0 :                 if work.len() >= MAX_OPTIMIZATIONS_PLAN_PER_PASS {
    8872            0 :                     break;
    8873            0 :                 }
    8874            0 :                 match shard.get_scheduling_policy() {
    8875            0 :                     ShardSchedulingPolicy::Active => {
    8876            0 :                         // Ok to do optimization
    8877            0 :                     }
    8878            0 :                     ShardSchedulingPolicy::Essential if shard.get_preferred_node().is_some() => {
    8879            0 :                         // Ok to do optimization: we are executing a graceful migration that
    8880            0 :                         // has set preferred_node
    8881            0 :                     }
    8882              :                     ShardSchedulingPolicy::Essential
    8883              :                     | ShardSchedulingPolicy::Pause
    8884              :                     | ShardSchedulingPolicy::Stop => {
    8885              :                         // Policy prevents optimizing this shard.
    8886            0 :                         continue;
    8887              :                     }
    8888              :                 }
    8889              : 
    8890            0 :                 if !matches!(shard.splitting, SplitState::Idle)
    8891            0 :                     || matches!(shard.policy, PlacementPolicy::Detached)
    8892            0 :                     || shard.reconciler.is_some()
    8893              :                 {
    8894              :                     // Do not start any optimizations while another change to the tenant is ongoing: this
    8895              :                     // is not necessary for correctness, but simplifies operations and implicitly throttles
    8896              :                     // optimization changes to happen in a "trickle" over time.
    8897            0 :                     continue;
    8898            0 :                 }
    8899              : 
    8900              :                 // Fast path: we may quickly identify shards that don't have any possible optimisations
    8901            0 :                 if !shard.maybe_optimizable(scheduler, &schedule_context) {
    8902            0 :                     if cfg!(feature = "testing") {
    8903              :                         // Check that maybe_optimizable doesn't disagree with the actual optimization functions.
    8904              :                         // Only do this in testing builds because it is not a correctness-critical check, so we shouldn't
    8905              :                         // panic in prod if we hit this, or spend cycles on it in prod.
    8906            0 :                         assert!(
    8907            0 :                             shard
    8908            0 :                                 .optimize_attachment(scheduler, &schedule_context)
    8909            0 :                                 .is_none()
    8910              :                         );
    8911            0 :                         assert!(
    8912            0 :                             shard
    8913            0 :                                 .optimize_secondary(scheduler, &schedule_context)
    8914            0 :                                 .is_none()
    8915              :                         );
    8916            0 :                     }
    8917            0 :                     continue;
    8918            0 :                 }
    8919              : 
    8920            0 :                 if let Some(optimization) =
    8921              :                     // If idle, maybe optimize attachments: if a shard has a secondary location that is preferable to
    8922              :                     // its primary location based on soft constraints, cut it over.
    8923            0 :                     shard.optimize_attachment(scheduler, &schedule_context)
    8924              :                 {
    8925            0 :                     tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for attachment: {optimization:?}");
    8926            0 :                     work.push((shard.tenant_shard_id, optimization));
    8927            0 :                     break;
    8928            0 :                 } else if let Some(optimization) =
    8929              :                     // If idle, maybe optimize secondary locations: if a shard has a secondary location that would be
    8930              :                     // better placed on another node, based on ScheduleContext, then adjust it.  This
    8931              :                     // covers cases like after a shard split, where we might have too many shards
    8932              :                     // in the same tenant with secondary locations on the node where they originally split.
    8933            0 :                     shard.optimize_secondary(scheduler, &schedule_context)
    8934              :                 {
    8935            0 :                     tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for secondary: {optimization:?}");
    8936            0 :                     work.push((shard.tenant_shard_id, optimization));
    8937            0 :                     break;
    8938            0 :                 }
    8939              :             }
    8940              :         }
    8941              : 
    8942            0 :         work
    8943            0 :     }
    8944              : 
    8945            0 :     async fn optimize_all_validate(
    8946            0 :         &self,
    8947            0 :         candidate_work: Vec<(TenantShardId, ScheduleOptimization)>,
    8948            0 :     ) -> Vec<(TenantShardId, ScheduleOptimization)> {
    8949              :         // Take a clone of the node map to use outside the lock in async validation phase
    8950            0 :         let validation_nodes = { self.inner.read().unwrap().nodes.clone() };
    8951              : 
    8952            0 :         let mut want_secondary_status = Vec::new();
    8953              : 
    8954              :         // Validate our plans: this is an async phase where we may do I/O to pageservers to
    8955              :         // check that the state of locations is acceptable to run the optimization, such as
    8956              :         // checking that a secondary location is sufficiently warmed-up to cleanly cut over
    8957              :         // in a live migration.
    8958            0 :         let mut validated_work = Vec::new();
    8959            0 :         for (tenant_shard_id, optimization) in candidate_work {
    8960            0 :             match optimization.action {
    8961              :                 ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    8962              :                     old_attached_node_id: _,
    8963            0 :                     new_attached_node_id,
    8964              :                 }) => {
    8965            0 :                     match validation_nodes.get(&new_attached_node_id) {
    8966            0 :                         None => {
    8967            0 :                             // Node was dropped between planning and validation
    8968            0 :                         }
    8969            0 :                         Some(node) => {
    8970            0 :                             if !node.is_available() {
    8971            0 :                                 tracing::info!(
    8972            0 :                                     "Skipping optimization migration of {tenant_shard_id} to {new_attached_node_id} because node unavailable"
    8973              :                                 );
    8974            0 :                             } else {
    8975            0 :                                 // Accumulate optimizations that require fetching secondary status, so that we can execute these
    8976            0 :                                 // remote API requests concurrently.
    8977            0 :                                 want_secondary_status.push((
    8978            0 :                                     tenant_shard_id,
    8979            0 :                                     node.clone(),
    8980            0 :                                     optimization,
    8981            0 :                                 ));
    8982            0 :                             }
    8983              :                         }
    8984              :                     }
    8985              :                 }
    8986              :                 ScheduleOptimizationAction::ReplaceSecondary(_)
    8987              :                 | ScheduleOptimizationAction::CreateSecondary(_)
    8988              :                 | ScheduleOptimizationAction::RemoveSecondary(_) => {
    8989              :                     // No extra checks needed to manage secondaries: this does not interrupt client access
    8990            0 :                     validated_work.push((tenant_shard_id, optimization))
    8991              :                 }
    8992              :             };
    8993              :         }
    8994              : 
    8995              :         // Call into pageserver API to find out if the destination secondary location is warm enough for a reasonably smooth migration: we
    8996              :         // do this so that we avoid spawning a Reconciler that would have to wait minutes/hours for a destination to warm up: that reconciler
    8997              :         // would hold a precious reconcile semaphore unit the whole time it was waiting for the destination to warm up.
    8998            0 :         let results = self
    8999            0 :             .tenant_for_shards_api(
    9000            0 :                 want_secondary_status
    9001            0 :                     .iter()
    9002            0 :                     .map(|i| (i.0, i.1.clone()))
    9003            0 :                     .collect(),
    9004            0 :                 |tenant_shard_id, client| async move {
    9005            0 :                     client.tenant_secondary_status(tenant_shard_id).await
    9006            0 :                 },
    9007              :                 1,
    9008              :                 1,
    9009              :                 SHORT_RECONCILE_TIMEOUT,
    9010            0 :                 &self.cancel,
    9011              :             )
    9012            0 :             .await;
    9013              : 
    9014            0 :         for ((tenant_shard_id, node, optimization), (_, secondary_status)) in
    9015            0 :             want_secondary_status.into_iter().zip(results.into_iter())
    9016              :         {
    9017            0 :             match secondary_status {
    9018            0 :                 Err(e) => {
    9019            0 :                     tracing::info!(
    9020            0 :                         "Skipping migration of {tenant_shard_id} to {node}, error querying secondary: {e}"
    9021              :                     );
    9022              :                 }
    9023            0 :                 Ok(progress) => {
    9024              :                     // We require secondary locations to have less than 10GiB of downloads pending before we will use
    9025              :                     // them in an optimization
    9026              :                     const DOWNLOAD_FRESHNESS_THRESHOLD: u64 = 10 * 1024 * 1024 * 1024;
    9027              : 
    9028            0 :                     if progress.heatmap_mtime.is_none()
    9029            0 :                         || progress.bytes_total < DOWNLOAD_FRESHNESS_THRESHOLD
    9030            0 :                             && progress.bytes_downloaded != progress.bytes_total
    9031            0 :                         || progress.bytes_total - progress.bytes_downloaded
    9032            0 :                             > DOWNLOAD_FRESHNESS_THRESHOLD
    9033              :                     {
    9034            0 :                         tracing::info!(
    9035            0 :                             "Skipping migration of {tenant_shard_id} to {node} because secondary isn't ready: {progress:?}"
    9036              :                         );
    9037              : 
    9038            0 :                         if progress.heatmap_mtime.is_none() {
    9039              :                             // No heatmap might mean the attached location has never uploaded one, or that
    9040              :                             // the secondary download hasn't happened yet.  This is relatively unusual in the field,
    9041              :                             // but fairly common in tests.
    9042            0 :                             self.kick_secondary_download(tenant_shard_id).await;
    9043            0 :                         }
    9044              :                     } else {
    9045              :                         // Location looks ready: proceed
    9046            0 :                         tracing::info!(
    9047            0 :                             "{tenant_shard_id} secondary on {node} is warm enough for migration: {progress:?}"
    9048              :                         );
    9049            0 :                         validated_work.push((tenant_shard_id, optimization))
    9050              :                     }
    9051              :                 }
    9052              :             }
    9053              :         }
    9054              : 
    9055            0 :         validated_work
    9056            0 :     }
    9057              : 
    9058              :     /// Some aspects of scheduling optimisation wait for secondary locations to be warm.  This
    9059              :     /// happens on multi-minute timescales in the field, which is fine because optimisation is meant
    9060              :     /// to be a lazy background thing. However, when testing, it is not practical to wait around, so
    9061              :     /// we have this helper to move things along faster.
    9062            0 :     async fn kick_secondary_download(&self, tenant_shard_id: TenantShardId) {
    9063            0 :         if !self.config.kick_secondary_downloads {
    9064              :             // No-op if kick_secondary_downloads functionaliuty is not configured
    9065            0 :             return;
    9066            0 :         }
    9067              : 
    9068            0 :         let (attached_node, secondaries) = {
    9069            0 :             let locked = self.inner.read().unwrap();
    9070            0 :             let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
    9071            0 :                 tracing::warn!(
    9072            0 :                     "Skipping kick of secondary download for {tenant_shard_id}: not found"
    9073              :                 );
    9074            0 :                 return;
    9075              :             };
    9076              : 
    9077            0 :             let Some(attached) = shard.intent.get_attached() else {
    9078            0 :                 tracing::warn!(
    9079            0 :                     "Skipping kick of secondary download for {tenant_shard_id}: no attached"
    9080              :                 );
    9081            0 :                 return;
    9082              :             };
    9083              : 
    9084            0 :             let secondaries = shard
    9085            0 :                 .intent
    9086            0 :                 .get_secondary()
    9087            0 :                 .iter()
    9088            0 :                 .map(|n| locked.nodes.get(n).unwrap().clone())
    9089            0 :                 .collect::<Vec<_>>();
    9090              : 
    9091            0 :             (locked.nodes.get(attached).unwrap().clone(), secondaries)
    9092              :         };
    9093              : 
    9094              :         // Make remote API calls to upload + download heatmaps: we ignore errors because this is just
    9095              :         // a 'kick' to let scheduling optimisation run more promptly.
    9096            0 :         match attached_node
    9097            0 :             .with_client_retries(
    9098            0 :                 |client| async move { client.tenant_heatmap_upload(tenant_shard_id).await },
    9099            0 :                 &self.http_client,
    9100            0 :                 &self.config.pageserver_jwt_token,
    9101              :                 3,
    9102              :                 10,
    9103              :                 SHORT_RECONCILE_TIMEOUT,
    9104            0 :                 &self.cancel,
    9105              :             )
    9106            0 :             .await
    9107              :         {
    9108            0 :             Some(Err(e)) => {
    9109            0 :                 tracing::info!(
    9110            0 :                     "Failed to upload heatmap from {attached_node} for {tenant_shard_id}: {e}"
    9111              :                 );
    9112              :             }
    9113              :             None => {
    9114            0 :                 tracing::info!(
    9115            0 :                     "Cancelled while uploading heatmap from {attached_node} for {tenant_shard_id}"
    9116              :                 );
    9117              :             }
    9118              :             Some(Ok(_)) => {
    9119            0 :                 tracing::info!(
    9120            0 :                     "Successfully uploaded heatmap from {attached_node} for {tenant_shard_id}"
    9121              :                 );
    9122              :             }
    9123              :         }
    9124              : 
    9125            0 :         for secondary_node in secondaries {
    9126            0 :             match secondary_node
    9127            0 :                 .with_client_retries(
    9128            0 :                     |client| async move {
    9129            0 :                         client
    9130            0 :                             .tenant_secondary_download(
    9131            0 :                                 tenant_shard_id,
    9132            0 :                                 Some(Duration::from_secs(1)),
    9133            0 :                             )
    9134            0 :                             .await
    9135            0 :                     },
    9136            0 :                     &self.http_client,
    9137            0 :                     &self.config.pageserver_jwt_token,
    9138              :                     3,
    9139              :                     10,
    9140              :                     SHORT_RECONCILE_TIMEOUT,
    9141            0 :                     &self.cancel,
    9142              :                 )
    9143            0 :                 .await
    9144              :             {
    9145            0 :                 Some(Err(e)) => {
    9146            0 :                     tracing::info!(
    9147            0 :                         "Failed to download heatmap from {secondary_node} for {tenant_shard_id}: {e}"
    9148              :                     );
    9149              :                 }
    9150              :                 None => {
    9151            0 :                     tracing::info!(
    9152            0 :                         "Cancelled while downloading heatmap from {secondary_node} for {tenant_shard_id}"
    9153              :                     );
    9154              :                 }
    9155            0 :                 Some(Ok(progress)) => {
    9156            0 :                     tracing::info!(
    9157            0 :                         "Successfully downloaded heatmap from {secondary_node} for {tenant_shard_id}: {progress:?}"
    9158              :                     );
    9159              :                 }
    9160              :             }
    9161              :         }
    9162            0 :     }
    9163              : 
    9164              :     /// Asynchronously split a tenant that's eligible for automatic splits. At most one tenant will
    9165              :     /// be split per call.
    9166              :     ///
    9167              :     /// Two sets of criteria are used: initial splits and size-based splits (in that order).
    9168              :     /// Initial splits are used to eagerly split unsharded tenants that may be performing initial
    9169              :     /// ingestion, since sharded tenants have significantly better ingestion throughput. Size-based
    9170              :     /// splits are used to bound the maximum shard size and balance out load.
    9171              :     ///
    9172              :     /// Splits are based on max_logical_size, i.e. the logical size of the largest timeline in a
    9173              :     /// tenant. We use this instead of the total logical size because branches will duplicate
    9174              :     /// logical size without actually using more storage. We could also use visible physical size,
    9175              :     /// but this might overestimate tenants that frequently churn branches.
    9176              :     ///
    9177              :     /// Initial splits (initial_split_threshold):
    9178              :     /// * Applies to tenants with 1 shard.
    9179              :     /// * The largest timeline (max_logical_size) exceeds initial_split_threshold.
    9180              :     /// * Splits into initial_split_shards.
    9181              :     ///
    9182              :     /// Size-based splits (split_threshold):
    9183              :     /// * Applies to all tenants.
    9184              :     /// * The largest timeline (max_logical_size) divided by shard count exceeds split_threshold.
    9185              :     /// * Splits such that max_logical_size / shard_count <= split_threshold, in powers of 2.
    9186              :     ///
    9187              :     /// Tenant shards are ordered by descending max_logical_size, first initial split candidates
    9188              :     /// then size-based split candidates. The first matching candidate is split.
    9189              :     ///
    9190              :     /// The shard count is clamped to max_split_shards. If a candidate is eligible for both initial
    9191              :     /// and size-based splits, the largest shard count will be used.
    9192              :     ///
    9193              :     /// An unsharded tenant will get DEFAULT_STRIPE_SIZE, regardless of what its ShardIdentity says.
    9194              :     /// A sharded tenant will retain its stripe size, as splits do not allow changing it.
    9195              :     ///
    9196              :     /// TODO: consider spawning multiple splits in parallel: this is only called once every 20
    9197              :     /// seconds, so a large backlog can take a long time, and if a tenant fails to split it will
    9198              :     /// block all other splits.
    9199            0 :     async fn autosplit_tenants(self: &Arc<Self>) {
    9200              :         // If max_split_shards is set to 0 or 1, we can't split.
    9201            0 :         let max_split_shards = self.config.max_split_shards;
    9202            0 :         if max_split_shards <= 1 {
    9203            0 :             return;
    9204            0 :         }
    9205              : 
    9206              :         // If initial_split_shards is set to 0 or 1, disable initial splits.
    9207            0 :         let mut initial_split_threshold = self.config.initial_split_threshold.unwrap_or(0);
    9208            0 :         let initial_split_shards = self.config.initial_split_shards;
    9209            0 :         if initial_split_shards <= 1 {
    9210            0 :             initial_split_threshold = 0;
    9211            0 :         }
    9212              : 
    9213              :         // If no split_threshold nor initial_split_threshold, disable autosplits.
    9214            0 :         let split_threshold = self.config.split_threshold.unwrap_or(0);
    9215            0 :         if split_threshold == 0 && initial_split_threshold == 0 {
    9216            0 :             return;
    9217            0 :         }
    9218              : 
    9219              :         // Fetch split candidates in prioritized order.
    9220              :         //
    9221              :         // If initial splits are enabled, fetch eligible tenants first. We prioritize initial splits
    9222              :         // over size-based splits, since these are often performing initial ingestion and rely on
    9223              :         // splits to improve ingest throughput.
    9224            0 :         let mut candidates = Vec::new();
    9225              : 
    9226            0 :         if initial_split_threshold > 0 {
    9227              :             // Initial splits: fetch tenants with 1 shard where the logical size of the largest
    9228              :             // timeline exceeds the initial split threshold.
    9229            0 :             let initial_candidates = self
    9230            0 :                 .get_top_tenant_shards(&TopTenantShardsRequest {
    9231            0 :                     order_by: TenantSorting::MaxLogicalSize,
    9232            0 :                     limit: 10,
    9233            0 :                     where_shards_lt: Some(ShardCount(2)),
    9234            0 :                     where_gt: Some(initial_split_threshold),
    9235            0 :                 })
    9236            0 :                 .await;
    9237            0 :             candidates.extend(initial_candidates);
    9238            0 :         }
    9239              : 
    9240            0 :         if split_threshold > 0 {
    9241              :             // Size-based splits: fetch tenants where the logical size of the largest timeline
    9242              :             // divided by shard count exceeds the split threshold.
    9243              :             //
    9244              :             // max_logical_size is only tracked on shard 0, and contains the total logical size
    9245              :             // across all shards. We have to order and filter by MaxLogicalSizePerShard, i.e.
    9246              :             // max_logical_size / shard_count, such that we only receive tenants that are actually
    9247              :             // eligible for splits. But we still use max_logical_size for later split calculations.
    9248            0 :             let size_candidates = self
    9249            0 :                 .get_top_tenant_shards(&TopTenantShardsRequest {
    9250            0 :                     order_by: TenantSorting::MaxLogicalSizePerShard,
    9251            0 :                     limit: 10,
    9252            0 :                     where_shards_lt: Some(ShardCount(max_split_shards)),
    9253            0 :                     where_gt: Some(split_threshold),
    9254            0 :                 })
    9255            0 :                 .await;
    9256              :             #[cfg(feature = "testing")]
    9257            0 :             assert!(
    9258            0 :                 size_candidates.iter().all(|c| c.id.is_shard_zero()),
    9259            0 :                 "MaxLogicalSizePerShard returned non-zero shard: {size_candidates:?}",
    9260              :             );
    9261            0 :             candidates.extend(size_candidates);
    9262            0 :         }
    9263              : 
    9264              :         // Filter out tenants in a prohibiting scheduling modes
    9265              :         // and tenants with an ongoing import.
    9266              :         //
    9267              :         // Note that the import check here is oportunistic. An import might start
    9268              :         // after the check before we actually update [`TenantShard::splitting`].
    9269              :         // [`Self::tenant_shard_split`] checks the database whilst holding the exclusive
    9270              :         // tenant lock. Imports might take a long time, so the check here allows us
    9271              :         // to split something else instead of trying the same shard over and over.
    9272              :         {
    9273            0 :             let state = self.inner.read().unwrap();
    9274            0 :             candidates.retain(|i| {
    9275            0 :                 let shard = state.tenants.get(&i.id);
    9276            0 :                 match shard {
    9277            0 :                     Some(t) => {
    9278            0 :                         t.get_scheduling_policy() == ShardSchedulingPolicy::Active
    9279            0 :                             && t.importing == TimelineImportState::Idle
    9280              :                     }
    9281            0 :                     None => false,
    9282              :                 }
    9283            0 :             });
    9284              :         }
    9285              : 
    9286              :         // Pick the first candidate to split. This will generally always be the first one in
    9287              :         // candidates, but we defensively skip candidates that end up not actually splitting.
    9288            0 :         let Some((candidate, new_shard_count)) = candidates
    9289            0 :             .into_iter()
    9290            0 :             .filter_map(|candidate| {
    9291            0 :                 let new_shard_count = Self::compute_split_shards(ShardSplitInputs {
    9292            0 :                     shard_count: candidate.id.shard_count,
    9293            0 :                     max_logical_size: candidate.max_logical_size,
    9294            0 :                     split_threshold,
    9295            0 :                     max_split_shards,
    9296            0 :                     initial_split_threshold,
    9297            0 :                     initial_split_shards,
    9298            0 :                 });
    9299            0 :                 new_shard_count.map(|shards| (candidate, shards.count()))
    9300            0 :             })
    9301            0 :             .next()
    9302              :         else {
    9303            0 :             debug!("no split-eligible tenants found");
    9304            0 :             return;
    9305              :         };
    9306              : 
    9307              :         // Retain the stripe size of sharded tenants, as splits don't allow changing it. Otherwise,
    9308              :         // use DEFAULT_STRIPE_SIZE for unsharded tenants -- their stripe size doesn't really matter,
    9309              :         // and if we change the default stripe size we want to use the new default rather than an
    9310              :         // old, persisted stripe size.
    9311            0 :         let new_stripe_size = match candidate.id.shard_count.count() {
    9312            0 :             0 => panic!("invalid shard count 0"),
    9313            0 :             1 => Some(DEFAULT_STRIPE_SIZE),
    9314            0 :             2.. => None,
    9315              :         };
    9316              : 
    9317              :         // We spawn a task to run this, so it's exactly like some external API client requesting
    9318              :         // it.  We don't want to block the background reconcile loop on this.
    9319            0 :         let old_shard_count = candidate.id.shard_count.count();
    9320            0 :         info!(
    9321            0 :             "auto-splitting tenant {old_shard_count} → {new_shard_count} shards, \
    9322            0 :                 current size {candidate:?} (split_threshold={split_threshold} \
    9323            0 :                 initial_split_threshold={initial_split_threshold})"
    9324              :         );
    9325              : 
    9326            0 :         let this = self.clone();
    9327            0 :         tokio::spawn(
    9328            0 :             async move {
    9329            0 :                 match this
    9330            0 :                     .tenant_shard_split(
    9331            0 :                         candidate.id.tenant_id,
    9332            0 :                         TenantShardSplitRequest {
    9333            0 :                             new_shard_count,
    9334            0 :                             new_stripe_size,
    9335            0 :                         },
    9336            0 :                     )
    9337            0 :                     .await
    9338              :                 {
    9339              :                     Ok(_) => {
    9340            0 :                         info!("successful auto-split {old_shard_count} → {new_shard_count} shards")
    9341              :                     }
    9342            0 :                     Err(err) => error!("auto-split failed: {err}"),
    9343              :                 }
    9344            0 :             }
    9345            0 :             .instrument(info_span!("auto_split", tenant_id=%candidate.id.tenant_id)),
    9346              :         );
    9347            0 :     }
    9348              : 
    9349              :     /// Returns the number of shards to split a tenant into, or None if the tenant shouldn't split,
    9350              :     /// based on the total logical size of the largest timeline summed across all shards. Uses the
    9351              :     /// larger of size-based and initial splits, clamped to max_split_shards.
    9352              :     ///
    9353              :     /// NB: the thresholds are exclusive, since TopTenantShardsRequest uses where_gt.
    9354           25 :     fn compute_split_shards(inputs: ShardSplitInputs) -> Option<ShardCount> {
    9355              :         let ShardSplitInputs {
    9356           25 :             shard_count,
    9357           25 :             max_logical_size,
    9358           25 :             split_threshold,
    9359           25 :             max_split_shards,
    9360           25 :             initial_split_threshold,
    9361           25 :             initial_split_shards,
    9362           25 :         } = inputs;
    9363              : 
    9364           25 :         let mut new_shard_count: u8 = shard_count.count();
    9365              : 
    9366              :         // Size-based splits. Ensures max_logical_size / new_shard_count <= split_threshold, using
    9367              :         // power-of-two shard counts.
    9368              :         //
    9369              :         // If the current shard count is not a power of two, and does not exceed split_threshold,
    9370              :         // then we leave it alone rather than forcing a power-of-two split.
    9371           25 :         if split_threshold > 0
    9372           18 :             && max_logical_size.div_ceil(split_threshold) > shard_count.count() as u64
    9373           12 :         {
    9374           12 :             new_shard_count = max_logical_size
    9375           12 :                 .div_ceil(split_threshold)
    9376           12 :                 .checked_next_power_of_two()
    9377           12 :                 .unwrap_or(u8::MAX as u64)
    9378           12 :                 .try_into()
    9379           12 :                 .unwrap_or(u8::MAX);
    9380           13 :         }
    9381              : 
    9382              :         // Initial splits. Use the larger of size-based and initial split shard counts. This only
    9383              :         // applies to unsharded tenants, i.e. changes to initial_split_threshold or
    9384              :         // initial_split_shards are not retroactive for sharded tenants.
    9385           25 :         if initial_split_threshold > 0
    9386           14 :             && shard_count.count() <= 1
    9387           11 :             && max_logical_size > initial_split_threshold
    9388            8 :         {
    9389            8 :             new_shard_count = new_shard_count.max(initial_split_shards);
    9390           17 :         }
    9391              : 
    9392              :         // Clamp to max shards.
    9393           25 :         new_shard_count = new_shard_count.min(max_split_shards);
    9394              : 
    9395              :         // Don't split if we're not increasing the shard count.
    9396           25 :         if new_shard_count <= shard_count.count() {
    9397           10 :             return None;
    9398           15 :         }
    9399              : 
    9400           15 :         Some(ShardCount(new_shard_count))
    9401           25 :     }
    9402              : 
    9403              :     /// Fetches the top tenant shards from every available node, in descending order of
    9404              :     /// max logical size. Offline nodes are skipped, and any errors from available nodes
    9405              :     /// will be logged and ignored.
    9406            0 :     async fn get_top_tenant_shards(
    9407            0 :         &self,
    9408            0 :         request: &TopTenantShardsRequest,
    9409            0 :     ) -> Vec<TopTenantShardItem> {
    9410            0 :         let nodes = self
    9411            0 :             .inner
    9412            0 :             .read()
    9413            0 :             .unwrap()
    9414            0 :             .nodes
    9415            0 :             .values()
    9416            0 :             .filter(|node| node.is_available())
    9417            0 :             .cloned()
    9418            0 :             .collect_vec();
    9419              : 
    9420            0 :         let mut futures = FuturesUnordered::new();
    9421            0 :         for node in nodes {
    9422            0 :             futures.push(async move {
    9423            0 :                 node.with_client_retries(
    9424            0 :                     |client| async move { client.top_tenant_shards(request.clone()).await },
    9425            0 :                     &self.http_client,
    9426            0 :                     &self.config.pageserver_jwt_token,
    9427              :                     3,
    9428              :                     3,
    9429            0 :                     Duration::from_secs(5),
    9430            0 :                     &self.cancel,
    9431              :                 )
    9432            0 :                 .await
    9433            0 :             });
    9434              :         }
    9435              : 
    9436            0 :         let mut top = Vec::new();
    9437            0 :         while let Some(output) = futures.next().await {
    9438            0 :             match output {
    9439            0 :                 Some(Ok(response)) => top.extend(response.shards),
    9440            0 :                 Some(Err(mgmt_api::Error::Cancelled)) => {}
    9441            0 :                 Some(Err(err)) => warn!("failed to fetch top tenants: {err}"),
    9442            0 :                 None => {} // node is shutting down
    9443              :             }
    9444              :         }
    9445              : 
    9446            0 :         top.sort_by_key(|i| i.max_logical_size);
    9447            0 :         top.reverse();
    9448            0 :         top
    9449            0 :     }
    9450              : 
    9451              :     /// Useful for tests: run whatever work a background [`Self::reconcile_all`] would have done, but
    9452              :     /// also wait for any generated Reconcilers to complete.  Calling this until it returns zero should
    9453              :     /// put the system into a quiescent state where future background reconciliations won't do anything.
    9454            0 :     pub(crate) async fn reconcile_all_now(&self) -> Result<usize, ReconcileWaitError> {
    9455            0 :         let reconcile_all_result = self.reconcile_all();
    9456            0 :         let mut spawned_reconciles = reconcile_all_result.spawned_reconciles;
    9457            0 :         if reconcile_all_result.can_run_optimizations() {
    9458              :             // Only optimize when we are otherwise idle
    9459            0 :             let optimization_reconciles = self.optimize_all().await;
    9460            0 :             spawned_reconciles += optimization_reconciles;
    9461            0 :         }
    9462              : 
    9463            0 :         let waiters = {
    9464            0 :             let mut waiters = Vec::new();
    9465            0 :             let locked = self.inner.read().unwrap();
    9466            0 :             for (_tenant_shard_id, shard) in locked.tenants.iter() {
    9467            0 :                 if let Some(waiter) = shard.get_waiter() {
    9468            0 :                     waiters.push(waiter);
    9469            0 :                 }
    9470              :             }
    9471            0 :             waiters
    9472              :         };
    9473              : 
    9474            0 :         let waiter_count = waiters.len();
    9475            0 :         match self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    9476            0 :             Ok(()) => {}
    9477            0 :             Err(e) => {
    9478            0 :                 if let ReconcileWaitError::Failed(_, reconcile_error) = &e {
    9479            0 :                     match **reconcile_error {
    9480              :                         ReconcileError::Cancel
    9481            0 :                         | ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
    9482            0 :                             // Ignore reconciler cancel errors: this reconciler might have shut down
    9483            0 :                             // because some other change superceded it.  We will return a nonzero number,
    9484            0 :                             // so the caller knows they might have to call again to quiesce the system.
    9485            0 :                         }
    9486              :                         _ => {
    9487            0 :                             return Err(e);
    9488              :                         }
    9489              :                     }
    9490              :                 } else {
    9491            0 :                     return Err(e);
    9492              :                 }
    9493              :             }
    9494              :         };
    9495              : 
    9496            0 :         tracing::info!(
    9497            0 :             "{} reconciles in reconcile_all, {} waiters",
    9498              :             spawned_reconciles,
    9499              :             waiter_count
    9500              :         );
    9501              : 
    9502            0 :         Ok(std::cmp::max(waiter_count, spawned_reconciles))
    9503            0 :     }
    9504              : 
    9505            0 :     async fn stop_reconciliations(&self, reason: StopReconciliationsReason) {
    9506              :         // Cancel all on-going reconciles and wait for them to exit the gate.
    9507            0 :         tracing::info!("{reason}: cancelling and waiting for in-flight reconciles");
    9508            0 :         self.reconcilers_cancel.cancel();
    9509            0 :         self.reconcilers_gate.close().await;
    9510              : 
    9511              :         // Signal the background loop in [`Service::process_results`] to exit once
    9512              :         // it has proccessed the results from all the reconciles we cancelled earlier.
    9513            0 :         tracing::info!("{reason}: processing results from previously in-flight reconciles");
    9514            0 :         self.result_tx.send(ReconcileResultRequest::Stop).ok();
    9515            0 :         self.result_tx.closed().await;
    9516            0 :     }
    9517              : 
    9518            0 :     pub async fn shutdown(&self) {
    9519            0 :         self.stop_reconciliations(StopReconciliationsReason::ShuttingDown)
    9520            0 :             .await;
    9521              : 
    9522              :         // Background tasks hold gate guards: this notifies them of the cancellation and
    9523              :         // waits for them all to complete.
    9524            0 :         tracing::info!("Shutting down: cancelling and waiting for background tasks to exit");
    9525            0 :         self.cancel.cancel();
    9526            0 :         self.gate.close().await;
    9527            0 :     }
    9528              : 
    9529              :     /// Spot check the download lag for a secondary location of a shard.
    9530              :     /// Should be used as a heuristic, since it's not always precise: the
    9531              :     /// secondary might have not downloaded the new heat map yet and, hence,
    9532              :     /// is not aware of the lag.
    9533              :     ///
    9534              :     /// Returns:
    9535              :     /// * Ok(None) if the lag could not be determined from the status,
    9536              :     /// * Ok(Some(_)) if the lag could be determind
    9537              :     /// * Err on failures to query the pageserver.
    9538            0 :     async fn secondary_lag(
    9539            0 :         &self,
    9540            0 :         secondary: &NodeId,
    9541            0 :         tenant_shard_id: TenantShardId,
    9542            0 :     ) -> Result<Option<u64>, mgmt_api::Error> {
    9543            0 :         let nodes = self.inner.read().unwrap().nodes.clone();
    9544            0 :         let node = nodes.get(secondary).ok_or(mgmt_api::Error::ApiError(
    9545            0 :             StatusCode::NOT_FOUND,
    9546            0 :             format!("Node with id {secondary} not found"),
    9547            0 :         ))?;
    9548              : 
    9549            0 :         match node
    9550            0 :             .with_client_retries(
    9551            0 :                 |client| async move { client.tenant_secondary_status(tenant_shard_id).await },
    9552            0 :                 &self.http_client,
    9553            0 :                 &self.config.pageserver_jwt_token,
    9554              :                 1,
    9555              :                 3,
    9556            0 :                 Duration::from_millis(250),
    9557            0 :                 &self.cancel,
    9558              :             )
    9559            0 :             .await
    9560              :         {
    9561            0 :             Some(Ok(status)) => match status.heatmap_mtime {
    9562            0 :                 Some(_) => Ok(Some(status.bytes_total - status.bytes_downloaded)),
    9563            0 :                 None => Ok(None),
    9564              :             },
    9565            0 :             Some(Err(e)) => Err(e),
    9566            0 :             None => Err(mgmt_api::Error::Cancelled),
    9567              :         }
    9568            0 :     }
    9569              : 
    9570              :     /// Drain a node by moving the shards attached to it as primaries.
    9571              :     /// This is a long running operation and it should run as a separate Tokio task.
    9572            0 :     pub(crate) async fn drain_node(
    9573            0 :         self: &Arc<Self>,
    9574            0 :         node_id: NodeId,
    9575            0 :         cancel: CancellationToken,
    9576            0 :     ) -> Result<(), OperationError> {
    9577              :         const MAX_SECONDARY_LAG_BYTES_DEFAULT: u64 = 256 * 1024 * 1024;
    9578            0 :         let max_secondary_lag_bytes = self
    9579            0 :             .config
    9580            0 :             .max_secondary_lag_bytes
    9581            0 :             .unwrap_or(MAX_SECONDARY_LAG_BYTES_DEFAULT);
    9582              : 
    9583              :         // By default, live migrations are generous about the wait time for getting
    9584              :         // the secondary location up to speed. When draining, give up earlier in order
    9585              :         // to not stall the operation when a cold secondary is encountered.
    9586              :         const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(30);
    9587              :         const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
    9588            0 :         let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
    9589            0 :             .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
    9590            0 :             .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
    9591            0 :             .build();
    9592              : 
    9593            0 :         let mut waiters = Vec::new();
    9594              : 
    9595            0 :         let mut tid_iter = create_shared_shard_iterator(self.clone());
    9596              : 
    9597            0 :         while !tid_iter.finished() {
    9598            0 :             if cancel.is_cancelled() {
    9599            0 :                 match self
    9600            0 :                     .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
    9601            0 :                     .await
    9602              :                 {
    9603            0 :                     Ok(()) => return Err(OperationError::Cancelled),
    9604            0 :                     Err(err) => {
    9605            0 :                         return Err(OperationError::FinalizeError(
    9606            0 :                             format!(
    9607            0 :                                 "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
    9608            0 :                             )
    9609            0 :                             .into(),
    9610            0 :                         ));
    9611              :                     }
    9612              :                 }
    9613            0 :             }
    9614              : 
    9615            0 :             operation_utils::validate_node_state(
    9616            0 :                 &node_id,
    9617            0 :                 self.inner.read().unwrap().nodes.clone(),
    9618            0 :                 NodeSchedulingPolicy::Draining,
    9619            0 :             )?;
    9620              : 
    9621            0 :             while waiters.len() < MAX_RECONCILES_PER_OPERATION {
    9622            0 :                 let tid = match tid_iter.next() {
    9623            0 :                     Some(tid) => tid,
    9624              :                     None => {
    9625            0 :                         break;
    9626              :                     }
    9627              :                 };
    9628              : 
    9629            0 :                 let tid_drain = TenantShardDrain {
    9630            0 :                     drained_node: node_id,
    9631            0 :                     tenant_shard_id: tid,
    9632            0 :                 };
    9633              : 
    9634            0 :                 let dest_node_id = {
    9635            0 :                     let locked = self.inner.read().unwrap();
    9636              : 
    9637            0 :                     match tid_drain
    9638            0 :                         .tenant_shard_eligible_for_drain(&locked.tenants, &locked.scheduler)
    9639              :                     {
    9640            0 :                         Some(node_id) => node_id,
    9641              :                         None => {
    9642            0 :                             continue;
    9643              :                         }
    9644              :                     }
    9645              :                 };
    9646              : 
    9647            0 :                 match self.secondary_lag(&dest_node_id, tid).await {
    9648            0 :                     Ok(Some(lag)) if lag <= max_secondary_lag_bytes => {
    9649            0 :                         // The secondary is reasonably up to date.
    9650            0 :                         // Migrate to it
    9651            0 :                     }
    9652            0 :                     Ok(Some(lag)) => {
    9653            0 :                         tracing::info!(
    9654            0 :                             tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    9655            0 :                             "Secondary on node {dest_node_id} is lagging by {lag}. Skipping reconcile."
    9656              :                         );
    9657            0 :                         continue;
    9658              :                     }
    9659              :                     Ok(None) => {
    9660            0 :                         tracing::info!(
    9661            0 :                             tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    9662            0 :                             "Could not determine lag for secondary on node {dest_node_id}. Skipping reconcile."
    9663              :                         );
    9664            0 :                         continue;
    9665              :                     }
    9666            0 :                     Err(err) => {
    9667            0 :                         tracing::warn!(
    9668            0 :                             tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    9669            0 :                             "Failed to get secondary lag from node {dest_node_id}. Skipping reconcile: {err}"
    9670              :                         );
    9671            0 :                         continue;
    9672              :                     }
    9673              :                 }
    9674              : 
    9675              :                 {
    9676            0 :                     let mut locked = self.inner.write().unwrap();
    9677            0 :                     let (nodes, tenants, scheduler) = locked.parts_mut();
    9678            0 :                     let rescheduled = tid_drain.reschedule_to_secondary(
    9679            0 :                         dest_node_id,
    9680            0 :                         tenants,
    9681            0 :                         scheduler,
    9682            0 :                         nodes,
    9683            0 :                     )?;
    9684              : 
    9685            0 :                     if let Some(tenant_shard) = rescheduled {
    9686            0 :                         let waiter = self.maybe_configured_reconcile_shard(
    9687            0 :                             tenant_shard,
    9688            0 :                             nodes,
    9689            0 :                             reconciler_config,
    9690            0 :                         );
    9691            0 :                         if let Some(some) = waiter {
    9692            0 :                             waiters.push(some);
    9693            0 :                         }
    9694            0 :                     }
    9695              :                 }
    9696              :             }
    9697              : 
    9698            0 :             waiters = self
    9699            0 :                 .await_waiters_remainder(waiters, WAITER_OPERATION_POLL_TIMEOUT)
    9700            0 :                 .await;
    9701              : 
    9702            0 :             failpoint_support::sleep_millis_async!("sleepy-drain-loop", &cancel);
    9703              :         }
    9704              : 
    9705            0 :         while !waiters.is_empty() {
    9706            0 :             if cancel.is_cancelled() {
    9707            0 :                 match self
    9708            0 :                     .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
    9709            0 :                     .await
    9710              :                 {
    9711            0 :                     Ok(()) => return Err(OperationError::Cancelled),
    9712            0 :                     Err(err) => {
    9713            0 :                         return Err(OperationError::FinalizeError(
    9714            0 :                             format!(
    9715            0 :                                 "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
    9716            0 :                             )
    9717            0 :                             .into(),
    9718            0 :                         ));
    9719              :                     }
    9720              :                 }
    9721            0 :             }
    9722              : 
    9723            0 :             tracing::info!("Awaiting {} pending drain reconciliations", waiters.len());
    9724              : 
    9725            0 :             waiters = self
    9726            0 :                 .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
    9727            0 :                 .await;
    9728              :         }
    9729              : 
    9730              :         // At this point we have done the best we could to drain shards from this node.
    9731              :         // Set the node scheduling policy to `[NodeSchedulingPolicy::PauseForRestart]`
    9732              :         // to complete the drain.
    9733            0 :         if let Err(err) = self
    9734            0 :             .node_configure(node_id, None, Some(NodeSchedulingPolicy::PauseForRestart))
    9735            0 :             .await
    9736              :         {
    9737              :             // This is not fatal. Anything that is polling the node scheduling policy to detect
    9738              :             // the end of the drain operations will hang, but all such places should enforce an
    9739              :             // overall timeout. The scheduling policy will be updated upon node re-attach and/or
    9740              :             // by the counterpart fill operation.
    9741            0 :             return Err(OperationError::FinalizeError(
    9742            0 :                 format!(
    9743            0 :                     "Failed to finalise drain of {node_id} by setting scheduling policy to PauseForRestart: {err}"
    9744            0 :                 )
    9745            0 :                 .into(),
    9746            0 :             ));
    9747            0 :         }
    9748              : 
    9749            0 :         Ok(())
    9750            0 :     }
    9751              : 
    9752              :     /// Create a node fill plan (pick secondaries to promote), based on:
    9753              :     /// 1. Shards which have a secondary on this node, and this node is in their home AZ, and are currently attached to a node
    9754              :     ///    outside their home AZ, should be migrated back here.
    9755              :     /// 2. If after step 1 we have not migrated enough shards for this node to have its fair share of
    9756              :     ///    attached shards, we will promote more shards from the nodes with the most attached shards, unless
    9757              :     ///    those shards have a home AZ that doesn't match the node we're filling.
    9758            0 :     fn fill_node_plan(&self, node_id: NodeId) -> Vec<TenantShardId> {
    9759            0 :         let mut locked = self.inner.write().unwrap();
    9760            0 :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    9761              : 
    9762            0 :         let node_az = nodes
    9763            0 :             .get(&node_id)
    9764            0 :             .expect("Node must exist")
    9765            0 :             .get_availability_zone_id()
    9766            0 :             .clone();
    9767              : 
    9768              :         // The tenant shard IDs that we plan to promote from secondary to attached on this node
    9769            0 :         let mut plan = Vec::new();
    9770              : 
    9771              :         // Collect shards which do not have a preferred AZ & are elegible for moving in stage 2
    9772            0 :         let mut free_tids_by_node: HashMap<NodeId, Vec<TenantShardId>> = HashMap::new();
    9773              : 
    9774              :         // Don't respect AZ preferences if there is only one AZ.  This comes up in tests, but it could
    9775              :         // conceivably come up in real life if deploying a single-AZ region intentionally.
    9776            0 :         let respect_azs = nodes
    9777            0 :             .values()
    9778            0 :             .map(|n| n.get_availability_zone_id())
    9779            0 :             .unique()
    9780            0 :             .count()
    9781              :             > 1;
    9782              : 
    9783              :         // Step 1: collect all shards that we are required to migrate back to this node because their AZ preference
    9784              :         // requires it.
    9785            0 :         for (tsid, tenant_shard) in tenants {
    9786            0 :             if !tenant_shard.intent.get_secondary().contains(&node_id) {
    9787              :                 // Shard doesn't have a secondary on this node, ignore it.
    9788            0 :                 continue;
    9789            0 :             }
    9790              : 
    9791              :             // AZ check: when filling nodes after a restart, our intent is to move _back_ the
    9792              :             // shards which belong on this node, not to promote shards whose scheduling preference
    9793              :             // would be on their currently attached node.  So will avoid promoting shards whose
    9794              :             // home AZ doesn't match the AZ of the node we're filling.
    9795            0 :             match tenant_shard.preferred_az() {
    9796            0 :                 _ if !respect_azs => {
    9797            0 :                     if let Some(primary) = tenant_shard.intent.get_attached() {
    9798            0 :                         free_tids_by_node.entry(*primary).or_default().push(*tsid);
    9799            0 :                     }
    9800              :                 }
    9801              :                 None => {
    9802              :                     // Shard doesn't have an AZ preference: it is elegible to be moved, but we
    9803              :                     // will only do so if our target shard count requires it.
    9804            0 :                     if let Some(primary) = tenant_shard.intent.get_attached() {
    9805            0 :                         free_tids_by_node.entry(*primary).or_default().push(*tsid);
    9806            0 :                     }
    9807              :                 }
    9808            0 :                 Some(az) if az == &node_az => {
    9809              :                     // This shard's home AZ is equal to the node we're filling: it should
    9810              :                     // be moved back to this node as part of filling, unless its currently
    9811              :                     // attached location is also in its home AZ.
    9812            0 :                     if let Some(primary) = tenant_shard.intent.get_attached() {
    9813            0 :                         if nodes
    9814            0 :                             .get(primary)
    9815            0 :                             .expect("referenced node must exist")
    9816            0 :                             .get_availability_zone_id()
    9817            0 :                             != tenant_shard
    9818            0 :                                 .preferred_az()
    9819            0 :                                 .expect("tenant must have an AZ preference")
    9820              :                         {
    9821            0 :                             plan.push(*tsid)
    9822            0 :                         }
    9823              :                     } else {
    9824            0 :                         plan.push(*tsid)
    9825              :                     }
    9826              :                 }
    9827            0 :                 Some(_) => {
    9828            0 :                     // This shard's home AZ is somewhere other than the node we're filling,
    9829            0 :                     // it may not be moved back to this node as part of filling.  Ignore it
    9830            0 :                 }
    9831              :             }
    9832              :         }
    9833              : 
    9834              :         // Step 2: also promote any AZ-agnostic shards as required to achieve the target number of attachments
    9835            0 :         let fill_requirement = locked.scheduler.compute_fill_requirement(node_id);
    9836              : 
    9837            0 :         let expected_attached = locked.scheduler.expected_attached_shard_count();
    9838            0 :         let nodes_by_load = locked.scheduler.nodes_by_attached_shard_count();
    9839              : 
    9840            0 :         let mut promoted_per_tenant: HashMap<TenantId, usize> = HashMap::new();
    9841              : 
    9842            0 :         for (node_id, attached) in nodes_by_load {
    9843            0 :             let available = locked.nodes.get(&node_id).is_some_and(|n| n.is_available());
    9844            0 :             if !available {
    9845            0 :                 continue;
    9846            0 :             }
    9847              : 
    9848            0 :             if plan.len() >= fill_requirement
    9849            0 :                 || free_tids_by_node.is_empty()
    9850            0 :                 || attached <= expected_attached
    9851              :             {
    9852            0 :                 break;
    9853            0 :             }
    9854              : 
    9855            0 :             let can_take = attached - expected_attached;
    9856            0 :             let needed = fill_requirement - plan.len();
    9857            0 :             let mut take = std::cmp::min(can_take, needed);
    9858              : 
    9859            0 :             let mut remove_node = false;
    9860            0 :             while take > 0 {
    9861            0 :                 match free_tids_by_node.get_mut(&node_id) {
    9862            0 :                     Some(tids) => match tids.pop() {
    9863            0 :                         Some(tid) => {
    9864            0 :                             let max_promote_for_tenant = std::cmp::max(
    9865            0 :                                 tid.shard_count.count() as usize / locked.nodes.len(),
    9866              :                                 1,
    9867              :                             );
    9868            0 :                             let promoted = promoted_per_tenant.entry(tid.tenant_id).or_default();
    9869            0 :                             if *promoted < max_promote_for_tenant {
    9870            0 :                                 plan.push(tid);
    9871            0 :                                 *promoted += 1;
    9872            0 :                                 take -= 1;
    9873            0 :                             }
    9874              :                         }
    9875              :                         None => {
    9876            0 :                             remove_node = true;
    9877            0 :                             break;
    9878              :                         }
    9879              :                     },
    9880              :                     None => {
    9881            0 :                         break;
    9882              :                     }
    9883              :                 }
    9884              :             }
    9885              : 
    9886            0 :             if remove_node {
    9887            0 :                 free_tids_by_node.remove(&node_id);
    9888            0 :             }
    9889              :         }
    9890              : 
    9891            0 :         plan
    9892            0 :     }
    9893              : 
    9894              :     /// Fill a node by promoting its secondaries until the cluster is balanced
    9895              :     /// with regards to attached shard counts. Note that this operation only
    9896              :     /// makes sense as a counterpart to the drain implemented in [`Service::drain_node`].
    9897              :     /// This is a long running operation and it should run as a separate Tokio task.
    9898            0 :     pub(crate) async fn fill_node(
    9899            0 :         &self,
    9900            0 :         node_id: NodeId,
    9901            0 :         cancel: CancellationToken,
    9902            0 :     ) -> Result<(), OperationError> {
    9903              :         const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(30);
    9904              :         const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
    9905            0 :         let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
    9906            0 :             .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
    9907            0 :             .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
    9908            0 :             .build();
    9909              : 
    9910            0 :         let mut tids_to_promote = self.fill_node_plan(node_id);
    9911            0 :         let mut waiters = Vec::new();
    9912              : 
    9913              :         // Execute the plan we've composed above. Before aplying each move from the plan,
    9914              :         // we validate to ensure that it has not gone stale in the meantime.
    9915            0 :         while !tids_to_promote.is_empty() {
    9916            0 :             if cancel.is_cancelled() {
    9917            0 :                 match self
    9918            0 :                     .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
    9919            0 :                     .await
    9920              :                 {
    9921            0 :                     Ok(()) => return Err(OperationError::Cancelled),
    9922            0 :                     Err(err) => {
    9923            0 :                         return Err(OperationError::FinalizeError(
    9924            0 :                             format!(
    9925            0 :                                 "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
    9926            0 :                             )
    9927            0 :                             .into(),
    9928            0 :                         ));
    9929              :                     }
    9930              :                 }
    9931            0 :             }
    9932              : 
    9933              :             {
    9934            0 :                 let mut locked = self.inner.write().unwrap();
    9935            0 :                 let (nodes, tenants, scheduler) = locked.parts_mut();
    9936              : 
    9937            0 :                 let node = nodes.get(&node_id).ok_or(OperationError::NodeStateChanged(
    9938            0 :                     format!("node {node_id} was removed").into(),
    9939            0 :                 ))?;
    9940              : 
    9941            0 :                 let current_policy = node.get_scheduling();
    9942            0 :                 if !matches!(current_policy, NodeSchedulingPolicy::Filling) {
    9943              :                     // TODO(vlad): maybe cancel pending reconciles before erroring out. need to think
    9944              :                     // about it
    9945            0 :                     return Err(OperationError::NodeStateChanged(
    9946            0 :                         format!("node {node_id} changed state to {current_policy:?}").into(),
    9947            0 :                     ));
    9948            0 :                 }
    9949              : 
    9950            0 :                 while waiters.len() < MAX_RECONCILES_PER_OPERATION {
    9951            0 :                     if let Some(tid) = tids_to_promote.pop() {
    9952            0 :                         if let Some(tenant_shard) = tenants.get_mut(&tid) {
    9953              :                             // If the node being filled is not a secondary anymore,
    9954              :                             // skip the promotion.
    9955            0 :                             if !tenant_shard.intent.get_secondary().contains(&node_id) {
    9956            0 :                                 continue;
    9957            0 :                             }
    9958              : 
    9959            0 :                             let previously_attached_to = *tenant_shard.intent.get_attached();
    9960            0 :                             match tenant_shard.reschedule_to_secondary(Some(node_id), scheduler) {
    9961            0 :                                 Err(e) => {
    9962            0 :                                     tracing::warn!(
    9963            0 :                                         tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    9964            0 :                                         "Scheduling error when filling pageserver {} : {e}", node_id
    9965              :                                     );
    9966              :                                 }
    9967              :                                 Ok(()) => {
    9968            0 :                                     tracing::info!(
    9969            0 :                                         tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    9970            0 :                                         "Rescheduled shard while filling node {}: {:?} -> {}",
    9971              :                                         node_id,
    9972              :                                         previously_attached_to,
    9973              :                                         node_id
    9974              :                                     );
    9975              : 
    9976            0 :                                     if let Some(waiter) = self.maybe_configured_reconcile_shard(
    9977            0 :                                         tenant_shard,
    9978            0 :                                         nodes,
    9979            0 :                                         reconciler_config,
    9980            0 :                                     ) {
    9981            0 :                                         waiters.push(waiter);
    9982            0 :                                     }
    9983              :                                 }
    9984              :                             }
    9985            0 :                         }
    9986              :                     } else {
    9987            0 :                         break;
    9988              :                     }
    9989              :                 }
    9990              :             }
    9991              : 
    9992            0 :             waiters = self
    9993            0 :                 .await_waiters_remainder(waiters, WAITER_OPERATION_POLL_TIMEOUT)
    9994            0 :                 .await;
    9995              :         }
    9996              : 
    9997            0 :         while !waiters.is_empty() {
    9998            0 :             if cancel.is_cancelled() {
    9999            0 :                 match self
   10000            0 :                     .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
   10001            0 :                     .await
   10002              :                 {
   10003            0 :                     Ok(()) => return Err(OperationError::Cancelled),
   10004            0 :                     Err(err) => {
   10005            0 :                         return Err(OperationError::FinalizeError(
   10006            0 :                             format!(
   10007            0 :                                 "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
   10008            0 :                             )
   10009            0 :                             .into(),
   10010            0 :                         ));
   10011              :                     }
   10012              :                 }
   10013            0 :             }
   10014              : 
   10015            0 :             tracing::info!("Awaiting {} pending fill reconciliations", waiters.len());
   10016              : 
   10017            0 :             waiters = self
   10018            0 :                 .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
   10019            0 :                 .await;
   10020              :         }
   10021              : 
   10022            0 :         if let Err(err) = self
   10023            0 :             .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
   10024            0 :             .await
   10025              :         {
   10026              :             // This isn't a huge issue since the filling process starts upon request. However, it
   10027              :             // will prevent the next drain from starting. The only case in which this can fail
   10028              :             // is database unavailability. Such a case will require manual intervention.
   10029            0 :             return Err(OperationError::FinalizeError(
   10030            0 :                 format!("Failed to finalise fill of {node_id} by setting scheduling policy to Active: {err}")
   10031            0 :                     .into(),
   10032            0 :             ));
   10033            0 :         }
   10034              : 
   10035            0 :         Ok(())
   10036            0 :     }
   10037              : 
   10038              :     /// Updates scrubber metadata health check results.
   10039            0 :     pub(crate) async fn metadata_health_update(
   10040            0 :         &self,
   10041            0 :         update_req: MetadataHealthUpdateRequest,
   10042            0 :     ) -> Result<(), ApiError> {
   10043            0 :         let now = chrono::offset::Utc::now();
   10044            0 :         let (healthy_records, unhealthy_records) = {
   10045            0 :             let locked = self.inner.read().unwrap();
   10046            0 :             let healthy_records = update_req
   10047            0 :                 .healthy_tenant_shards
   10048            0 :                 .into_iter()
   10049              :                 // Retain only health records associated with tenant shards managed by storage controller.
   10050            0 :                 .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
   10051            0 :                 .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, true, now))
   10052            0 :                 .collect();
   10053            0 :             let unhealthy_records = update_req
   10054            0 :                 .unhealthy_tenant_shards
   10055            0 :                 .into_iter()
   10056            0 :                 .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
   10057            0 :                 .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, false, now))
   10058            0 :                 .collect();
   10059              : 
   10060            0 :             (healthy_records, unhealthy_records)
   10061              :         };
   10062              : 
   10063            0 :         self.persistence
   10064            0 :             .update_metadata_health_records(healthy_records, unhealthy_records, now)
   10065            0 :             .await?;
   10066            0 :         Ok(())
   10067            0 :     }
   10068              : 
   10069              :     /// Lists the tenant shards that has unhealthy metadata status.
   10070            0 :     pub(crate) async fn metadata_health_list_unhealthy(
   10071            0 :         &self,
   10072            0 :     ) -> Result<Vec<TenantShardId>, ApiError> {
   10073            0 :         let result = self
   10074            0 :             .persistence
   10075            0 :             .list_unhealthy_metadata_health_records()
   10076            0 :             .await?
   10077            0 :             .iter()
   10078            0 :             .map(|p| p.get_tenant_shard_id().unwrap())
   10079            0 :             .collect();
   10080              : 
   10081            0 :         Ok(result)
   10082            0 :     }
   10083              : 
   10084              :     /// Lists the tenant shards that have not been scrubbed for some duration.
   10085            0 :     pub(crate) async fn metadata_health_list_outdated(
   10086            0 :         &self,
   10087            0 :         not_scrubbed_for: Duration,
   10088            0 :     ) -> Result<Vec<MetadataHealthRecord>, ApiError> {
   10089            0 :         let earlier = chrono::offset::Utc::now() - not_scrubbed_for;
   10090            0 :         let result = self
   10091            0 :             .persistence
   10092            0 :             .list_outdated_metadata_health_records(earlier)
   10093            0 :             .await?
   10094            0 :             .into_iter()
   10095            0 :             .map(|record| record.into())
   10096            0 :             .collect();
   10097            0 :         Ok(result)
   10098            0 :     }
   10099              : 
   10100            0 :     pub(crate) fn get_leadership_status(&self) -> LeadershipStatus {
   10101            0 :         self.inner.read().unwrap().get_leadership_status()
   10102            0 :     }
   10103              : 
   10104              :     /// Handler for step down requests
   10105              :     ///
   10106              :     /// Step down runs in separate task since once it's called it should
   10107              :     /// be driven to completion. Subsequent requests will wait on the same
   10108              :     /// step down task.
   10109            0 :     pub(crate) async fn step_down(self: &Arc<Self>) -> GlobalObservedState {
   10110            0 :         let handle = self.step_down_barrier.get_or_init(|| {
   10111            0 :             let step_down_self = self.clone();
   10112            0 :             let (tx, rx) = tokio::sync::watch::channel::<Option<GlobalObservedState>>(None);
   10113            0 :             tokio::spawn(async move {
   10114            0 :                 let state = step_down_self.step_down_task().await;
   10115            0 :                 tx.send(Some(state))
   10116            0 :                     .expect("Task Arc<Service> keeps receiver alive");
   10117            0 :             });
   10118              : 
   10119            0 :             rx
   10120            0 :         });
   10121              : 
   10122            0 :         handle
   10123            0 :             .clone()
   10124            0 :             .wait_for(|observed_state| observed_state.is_some())
   10125            0 :             .await
   10126            0 :             .expect("Task Arc<Service> keeps sender alive")
   10127            0 :             .deref()
   10128            0 :             .clone()
   10129            0 :             .expect("Checked above")
   10130            0 :     }
   10131              : 
   10132            0 :     async fn step_down_task(&self) -> GlobalObservedState {
   10133            0 :         tracing::info!("Received step down request from peer");
   10134            0 :         failpoint_support::sleep_millis_async!("sleep-on-step-down-handling");
   10135              : 
   10136            0 :         self.inner.write().unwrap().step_down();
   10137              : 
   10138            0 :         let stop_reconciliations =
   10139            0 :             self.stop_reconciliations(StopReconciliationsReason::SteppingDown);
   10140            0 :         let mut stop_reconciliations = std::pin::pin!(stop_reconciliations);
   10141              : 
   10142            0 :         let started_at = Instant::now();
   10143              : 
   10144              :         // Wait for reconciliations to stop and warn if that's taking a long time
   10145              :         loop {
   10146            0 :             tokio::select! {
   10147            0 :                 _ = &mut stop_reconciliations => {
   10148            0 :                     tracing::info!("Reconciliations stopped, proceeding with step down");
   10149            0 :                     break;
   10150              :                 }
   10151            0 :                 _ = tokio::time::sleep(Duration::from_secs(10)) => {
   10152            0 :                     tracing::warn!(
   10153            0 :                         elapsed_sec=%started_at.elapsed().as_secs(),
   10154            0 :                         "Stopping reconciliations during step down is taking too long"
   10155              :                     );
   10156              :                 }
   10157              :             }
   10158              :         }
   10159              : 
   10160            0 :         let mut global_observed = GlobalObservedState::default();
   10161            0 :         let locked = self.inner.read().unwrap();
   10162            0 :         for (tid, tenant_shard) in locked.tenants.iter() {
   10163            0 :             global_observed
   10164            0 :                 .0
   10165            0 :                 .insert(*tid, tenant_shard.observed.clone());
   10166            0 :         }
   10167              : 
   10168            0 :         global_observed
   10169            0 :     }
   10170              : 
   10171            0 :     pub(crate) async fn update_shards_preferred_azs(
   10172            0 :         &self,
   10173            0 :         req: ShardsPreferredAzsRequest,
   10174            0 :     ) -> Result<ShardsPreferredAzsResponse, ApiError> {
   10175            0 :         let preferred_azs = req.preferred_az_ids.into_iter().collect::<Vec<_>>();
   10176            0 :         let updated = self
   10177            0 :             .persistence
   10178            0 :             .set_tenant_shard_preferred_azs(preferred_azs)
   10179            0 :             .await
   10180            0 :             .map_err(|err| {
   10181            0 :                 ApiError::InternalServerError(anyhow::anyhow!(
   10182            0 :                     "Failed to persist preferred AZs: {err}"
   10183            0 :                 ))
   10184            0 :             })?;
   10185              : 
   10186            0 :         let mut updated_in_mem_and_db = Vec::default();
   10187              : 
   10188            0 :         let mut locked = self.inner.write().unwrap();
   10189            0 :         let state = locked.deref_mut();
   10190            0 :         for (tid, az_id) in updated {
   10191            0 :             let shard = state.tenants.get_mut(&tid);
   10192            0 :             if let Some(shard) = shard {
   10193            0 :                 shard.set_preferred_az(&mut state.scheduler, az_id);
   10194            0 :                 updated_in_mem_and_db.push(tid);
   10195            0 :             }
   10196              :         }
   10197              : 
   10198            0 :         Ok(ShardsPreferredAzsResponse {
   10199            0 :             updated: updated_in_mem_and_db,
   10200            0 :         })
   10201            0 :     }
   10202              : }
   10203              : 
   10204              : #[cfg(test)]
   10205              : mod tests {
   10206              :     use super::*;
   10207              : 
   10208              :     /// Tests Service::compute_split_shards. For readability, this specifies sizes in GBs rather
   10209              :     /// than bytes. Note that max_logical_size is the total logical size of the largest timeline
   10210              :     /// summed across all shards.
   10211              :     #[test]
   10212            1 :     fn compute_split_shards() {
   10213              :         // Size-based split: two shards have a 500 GB timeline, which need to split into 8 shards
   10214              :         // that are <= 64 GB,
   10215            1 :         assert_eq!(
   10216            1 :             Service::compute_split_shards(ShardSplitInputs {
   10217            1 :                 shard_count: ShardCount(2),
   10218            1 :                 max_logical_size: 500,
   10219            1 :                 split_threshold: 64,
   10220            1 :                 max_split_shards: 16,
   10221            1 :                 initial_split_threshold: 0,
   10222            1 :                 initial_split_shards: 0,
   10223            1 :             }),
   10224              :             Some(ShardCount(8))
   10225              :         );
   10226              : 
   10227              :         // Size-based split: noop at or below threshold, fires above.
   10228            1 :         assert_eq!(
   10229            1 :             Service::compute_split_shards(ShardSplitInputs {
   10230            1 :                 shard_count: ShardCount(2),
   10231            1 :                 max_logical_size: 127,
   10232            1 :                 split_threshold: 64,
   10233            1 :                 max_split_shards: 16,
   10234            1 :                 initial_split_threshold: 0,
   10235            1 :                 initial_split_shards: 0,
   10236            1 :             }),
   10237              :             None,
   10238              :         );
   10239            1 :         assert_eq!(
   10240            1 :             Service::compute_split_shards(ShardSplitInputs {
   10241            1 :                 shard_count: ShardCount(2),
   10242            1 :                 max_logical_size: 128,
   10243            1 :                 split_threshold: 64,
   10244            1 :                 max_split_shards: 16,
   10245            1 :                 initial_split_threshold: 0,
   10246            1 :                 initial_split_shards: 0,
   10247            1 :             }),
   10248              :             None,
   10249              :         );
   10250            1 :         assert_eq!(
   10251            1 :             Service::compute_split_shards(ShardSplitInputs {
   10252            1 :                 shard_count: ShardCount(2),
   10253            1 :                 max_logical_size: 129,
   10254            1 :                 split_threshold: 64,
   10255            1 :                 max_split_shards: 16,
   10256            1 :                 initial_split_threshold: 0,
   10257            1 :                 initial_split_shards: 0,
   10258            1 :             }),
   10259              :             Some(ShardCount(4)),
   10260              :         );
   10261              : 
   10262              :         // Size-based split: clamped to max_split_shards.
   10263            1 :         assert_eq!(
   10264            1 :             Service::compute_split_shards(ShardSplitInputs {
   10265            1 :                 shard_count: ShardCount(2),
   10266            1 :                 max_logical_size: 10000,
   10267            1 :                 split_threshold: 64,
   10268            1 :                 max_split_shards: 16,
   10269            1 :                 initial_split_threshold: 0,
   10270            1 :                 initial_split_shards: 0,
   10271            1 :             }),
   10272              :             Some(ShardCount(16))
   10273              :         );
   10274              : 
   10275              :         // Size-based split: tenant already at or beyond max_split_shards is not split.
   10276            1 :         assert_eq!(
   10277            1 :             Service::compute_split_shards(ShardSplitInputs {
   10278            1 :                 shard_count: ShardCount(16),
   10279            1 :                 max_logical_size: 10000,
   10280            1 :                 split_threshold: 64,
   10281            1 :                 max_split_shards: 16,
   10282            1 :                 initial_split_threshold: 0,
   10283            1 :                 initial_split_shards: 0,
   10284            1 :             }),
   10285              :             None
   10286              :         );
   10287              : 
   10288            1 :         assert_eq!(
   10289            1 :             Service::compute_split_shards(ShardSplitInputs {
   10290            1 :                 shard_count: ShardCount(32),
   10291            1 :                 max_logical_size: 10000,
   10292            1 :                 split_threshold: 64,
   10293            1 :                 max_split_shards: 16,
   10294            1 :                 initial_split_threshold: 0,
   10295            1 :                 initial_split_shards: 0,
   10296            1 :             }),
   10297              :             None
   10298              :         );
   10299              : 
   10300              :         // Size-based split: a non-power-of-2 shard count is normalized to power-of-2 if it
   10301              :         // exceeds split_threshold (i.e. a 3-shard tenant splits into 8, not 6).
   10302            1 :         assert_eq!(
   10303            1 :             Service::compute_split_shards(ShardSplitInputs {
   10304            1 :                 shard_count: ShardCount(3),
   10305            1 :                 max_logical_size: 320,
   10306            1 :                 split_threshold: 64,
   10307            1 :                 max_split_shards: 16,
   10308            1 :                 initial_split_threshold: 0,
   10309            1 :                 initial_split_shards: 0,
   10310            1 :             }),
   10311              :             Some(ShardCount(8))
   10312              :         );
   10313              : 
   10314              :         // Size-based split: a non-power-of-2 shard count is not normalized to power-of-2 if the
   10315              :         // existing shards are below or at split_threshold, but splits into 4 if it exceeds it.
   10316            1 :         assert_eq!(
   10317            1 :             Service::compute_split_shards(ShardSplitInputs {
   10318            1 :                 shard_count: ShardCount(3),
   10319            1 :                 max_logical_size: 191,
   10320            1 :                 split_threshold: 64,
   10321            1 :                 max_split_shards: 16,
   10322            1 :                 initial_split_threshold: 0,
   10323            1 :                 initial_split_shards: 0,
   10324            1 :             }),
   10325              :             None
   10326              :         );
   10327            1 :         assert_eq!(
   10328            1 :             Service::compute_split_shards(ShardSplitInputs {
   10329            1 :                 shard_count: ShardCount(3),
   10330            1 :                 max_logical_size: 192,
   10331            1 :                 split_threshold: 64,
   10332            1 :                 max_split_shards: 16,
   10333            1 :                 initial_split_threshold: 0,
   10334            1 :                 initial_split_shards: 0,
   10335            1 :             }),
   10336              :             None
   10337              :         );
   10338            1 :         assert_eq!(
   10339            1 :             Service::compute_split_shards(ShardSplitInputs {
   10340            1 :                 shard_count: ShardCount(3),
   10341            1 :                 max_logical_size: 193,
   10342            1 :                 split_threshold: 64,
   10343            1 :                 max_split_shards: 16,
   10344            1 :                 initial_split_threshold: 0,
   10345            1 :                 initial_split_shards: 0,
   10346            1 :             }),
   10347              :             Some(ShardCount(4))
   10348              :         );
   10349              : 
   10350              :         // Initial split: tenant has a 10 GB timeline, split into 4 shards.
   10351            1 :         assert_eq!(
   10352            1 :             Service::compute_split_shards(ShardSplitInputs {
   10353            1 :                 shard_count: ShardCount(1),
   10354            1 :                 max_logical_size: 10,
   10355            1 :                 split_threshold: 0,
   10356            1 :                 max_split_shards: 16,
   10357            1 :                 initial_split_threshold: 8,
   10358            1 :                 initial_split_shards: 4,
   10359            1 :             }),
   10360              :             Some(ShardCount(4))
   10361              :         );
   10362              : 
   10363              :         // Initial split: 0 ShardCount is equivalent to 1.
   10364            1 :         assert_eq!(
   10365            1 :             Service::compute_split_shards(ShardSplitInputs {
   10366            1 :                 shard_count: ShardCount(0),
   10367            1 :                 max_logical_size: 10,
   10368            1 :                 split_threshold: 0,
   10369            1 :                 max_split_shards: 16,
   10370            1 :                 initial_split_threshold: 8,
   10371            1 :                 initial_split_shards: 4,
   10372            1 :             }),
   10373              :             Some(ShardCount(4))
   10374              :         );
   10375              : 
   10376              :         // Initial split: at or below threshold is noop.
   10377            1 :         assert_eq!(
   10378            1 :             Service::compute_split_shards(ShardSplitInputs {
   10379            1 :                 shard_count: ShardCount(1),
   10380            1 :                 max_logical_size: 7,
   10381            1 :                 split_threshold: 0,
   10382            1 :                 max_split_shards: 16,
   10383            1 :                 initial_split_threshold: 8,
   10384            1 :                 initial_split_shards: 4,
   10385            1 :             }),
   10386              :             None,
   10387              :         );
   10388            1 :         assert_eq!(
   10389            1 :             Service::compute_split_shards(ShardSplitInputs {
   10390            1 :                 shard_count: ShardCount(1),
   10391            1 :                 max_logical_size: 8,
   10392            1 :                 split_threshold: 0,
   10393            1 :                 max_split_shards: 16,
   10394            1 :                 initial_split_threshold: 8,
   10395            1 :                 initial_split_shards: 4,
   10396            1 :             }),
   10397              :             None,
   10398              :         );
   10399            1 :         assert_eq!(
   10400            1 :             Service::compute_split_shards(ShardSplitInputs {
   10401            1 :                 shard_count: ShardCount(1),
   10402            1 :                 max_logical_size: 9,
   10403            1 :                 split_threshold: 0,
   10404            1 :                 max_split_shards: 16,
   10405            1 :                 initial_split_threshold: 8,
   10406            1 :                 initial_split_shards: 4,
   10407            1 :             }),
   10408              :             Some(ShardCount(4))
   10409              :         );
   10410              : 
   10411              :         // Initial split: already sharded tenant is not affected, even if above threshold and below
   10412              :         // shard count.
   10413            1 :         assert_eq!(
   10414            1 :             Service::compute_split_shards(ShardSplitInputs {
   10415            1 :                 shard_count: ShardCount(2),
   10416            1 :                 max_logical_size: 20,
   10417            1 :                 split_threshold: 0,
   10418            1 :                 max_split_shards: 16,
   10419            1 :                 initial_split_threshold: 8,
   10420            1 :                 initial_split_shards: 4,
   10421            1 :             }),
   10422              :             None,
   10423              :         );
   10424              : 
   10425              :         // Initial split: clamped to max_shards.
   10426            1 :         assert_eq!(
   10427            1 :             Service::compute_split_shards(ShardSplitInputs {
   10428            1 :                 shard_count: ShardCount(1),
   10429            1 :                 max_logical_size: 10,
   10430            1 :                 split_threshold: 0,
   10431            1 :                 max_split_shards: 3,
   10432            1 :                 initial_split_threshold: 8,
   10433            1 :                 initial_split_shards: 4,
   10434            1 :             }),
   10435              :             Some(ShardCount(3)),
   10436              :         );
   10437              : 
   10438              :         // Initial+size split: tenant eligible for both will use the larger shard count.
   10439            1 :         assert_eq!(
   10440            1 :             Service::compute_split_shards(ShardSplitInputs {
   10441            1 :                 shard_count: ShardCount(1),
   10442            1 :                 max_logical_size: 10,
   10443            1 :                 split_threshold: 64,
   10444            1 :                 max_split_shards: 16,
   10445            1 :                 initial_split_threshold: 8,
   10446            1 :                 initial_split_shards: 4,
   10447            1 :             }),
   10448              :             Some(ShardCount(4)),
   10449              :         );
   10450            1 :         assert_eq!(
   10451            1 :             Service::compute_split_shards(ShardSplitInputs {
   10452            1 :                 shard_count: ShardCount(1),
   10453            1 :                 max_logical_size: 500,
   10454            1 :                 split_threshold: 64,
   10455            1 :                 max_split_shards: 16,
   10456            1 :                 initial_split_threshold: 8,
   10457            1 :                 initial_split_shards: 4,
   10458            1 :             }),
   10459              :             Some(ShardCount(8)),
   10460              :         );
   10461              : 
   10462              :         // Initial+size split: sharded tenant is only eligible for size-based split.
   10463            1 :         assert_eq!(
   10464            1 :             Service::compute_split_shards(ShardSplitInputs {
   10465            1 :                 shard_count: ShardCount(2),
   10466            1 :                 max_logical_size: 200,
   10467            1 :                 split_threshold: 64,
   10468            1 :                 max_split_shards: 16,
   10469            1 :                 initial_split_threshold: 8,
   10470            1 :                 initial_split_shards: 8,
   10471            1 :             }),
   10472              :             Some(ShardCount(4)),
   10473              :         );
   10474              : 
   10475              :         // Initial+size split: uses the larger shard count even with initial_split_threshold above
   10476              :         // split_threshold.
   10477            1 :         assert_eq!(
   10478            1 :             Service::compute_split_shards(ShardSplitInputs {
   10479            1 :                 shard_count: ShardCount(1),
   10480            1 :                 max_logical_size: 10,
   10481            1 :                 split_threshold: 4,
   10482            1 :                 max_split_shards: 16,
   10483            1 :                 initial_split_threshold: 8,
   10484            1 :                 initial_split_shards: 8,
   10485            1 :             }),
   10486              :             Some(ShardCount(8)),
   10487              :         );
   10488              : 
   10489              :         // Test backwards compatibility with production settings when initial/size-based splits were
   10490              :         // rolled out: a single split into 8 shards at 64 GB. Any already sharded tenants with <8
   10491              :         // shards will split according to split_threshold.
   10492            1 :         assert_eq!(
   10493            1 :             Service::compute_split_shards(ShardSplitInputs {
   10494            1 :                 shard_count: ShardCount(1),
   10495            1 :                 max_logical_size: 65,
   10496            1 :                 split_threshold: 64,
   10497            1 :                 max_split_shards: 8,
   10498            1 :                 initial_split_threshold: 64,
   10499            1 :                 initial_split_shards: 8,
   10500            1 :             }),
   10501              :             Some(ShardCount(8)),
   10502              :         );
   10503              : 
   10504            1 :         assert_eq!(
   10505            1 :             Service::compute_split_shards(ShardSplitInputs {
   10506            1 :                 shard_count: ShardCount(1),
   10507            1 :                 max_logical_size: 64,
   10508            1 :                 split_threshold: 64,
   10509            1 :                 max_split_shards: 8,
   10510            1 :                 initial_split_threshold: 64,
   10511            1 :                 initial_split_shards: 8,
   10512            1 :             }),
   10513              :             None,
   10514              :         );
   10515              : 
   10516            1 :         assert_eq!(
   10517            1 :             Service::compute_split_shards(ShardSplitInputs {
   10518            1 :                 shard_count: ShardCount(2),
   10519            1 :                 max_logical_size: 129,
   10520            1 :                 split_threshold: 64,
   10521            1 :                 max_split_shards: 8,
   10522            1 :                 initial_split_threshold: 64,
   10523            1 :                 initial_split_shards: 8,
   10524            1 :             }),
   10525              :             Some(ShardCount(4)),
   10526              :         );
   10527            1 :     }
   10528              : }
        

Generated by: LCOV version 2.1-beta