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

Generated by: LCOV version 2.1-beta