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

Generated by: LCOV version 2.1-beta