LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: 2453312769e0b6b061a2008879e6693300d0b938.info Lines: 0.0 % 4039 0
Test Date: 2024-09-06 16:40:18 Functions: 0.0 % 380 0

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

Generated by: LCOV version 2.1-beta