LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: 09e7485004805bd42b53a0c369170b3228136512.info Lines: 0.0 % 4326 0
Test Date: 2024-11-21 18:36:18 Functions: 0.0 % 415 0

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

Generated by: LCOV version 2.1-beta