LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: 496e96cdfff2df79370229591d6427cda12fde29.info Lines: 0.0 % 2929 0
Test Date: 2024-05-21 18:28:29 Functions: 0.0 % 234 0

            Line data    Source code
       1              : use std::{
       2              :     borrow::Cow,
       3              :     cmp::Ordering,
       4              :     collections::{BTreeMap, HashMap, HashSet},
       5              :     str::FromStr,
       6              :     sync::Arc,
       7              :     time::{Duration, Instant},
       8              : };
       9              : 
      10              : use crate::{
      11              :     compute_hook::NotifyError,
      12              :     id_lock_map::{trace_exclusive_lock, trace_shared_lock, IdLockMap, WrappedWriteGuard},
      13              :     persistence::{AbortShardSplitStatus, TenantFilter},
      14              :     reconciler::{ReconcileError, ReconcileUnits},
      15              :     scheduler::{ScheduleContext, ScheduleMode},
      16              :     tenant_shard::{
      17              :         MigrateAttachment, ReconcileNeeded, ScheduleOptimization, ScheduleOptimizationAction,
      18              :     },
      19              : };
      20              : use anyhow::Context;
      21              : use control_plane::storage_controller::{
      22              :     AttachHookRequest, AttachHookResponse, InspectRequest, InspectResponse,
      23              : };
      24              : use diesel::result::DatabaseErrorKind;
      25              : use futures::{stream::FuturesUnordered, StreamExt};
      26              : use itertools::Itertools;
      27              : use pageserver_api::{
      28              :     controller_api::{
      29              :         NodeAvailability, NodeRegisterRequest, NodeSchedulingPolicy, PlacementPolicy,
      30              :         ShardSchedulingPolicy, TenantCreateResponse, TenantCreateResponseShard,
      31              :         TenantDescribeResponse, TenantDescribeResponseShard, TenantLocateResponse,
      32              :         TenantPolicyRequest, TenantShardMigrateRequest, TenantShardMigrateResponse,
      33              :         UtilizationScore,
      34              :     },
      35              :     models::{SecondaryProgress, TenantConfigRequest, TopTenantShardsRequest},
      36              : };
      37              : use reqwest::StatusCode;
      38              : use tracing::{instrument, Instrument};
      39              : 
      40              : use crate::pageserver_client::PageserverClient;
      41              : use pageserver_api::{
      42              :     models::{
      43              :         self, LocationConfig, LocationConfigListResponse, LocationConfigMode,
      44              :         PageserverUtilization, ShardParameters, TenantConfig, TenantCreateRequest,
      45              :         TenantLocationConfigRequest, TenantLocationConfigResponse, TenantShardLocation,
      46              :         TenantShardSplitRequest, TenantShardSplitResponse, TenantTimeTravelRequest,
      47              :         TimelineCreateRequest, TimelineInfo,
      48              :     },
      49              :     shard::{ShardCount, ShardIdentity, ShardNumber, ShardStripeSize, TenantShardId},
      50              :     upcall_api::{
      51              :         ReAttachRequest, ReAttachResponse, ReAttachResponseTenant, ValidateRequest,
      52              :         ValidateResponse, ValidateResponseTenant,
      53              :     },
      54              : };
      55              : use pageserver_client::mgmt_api;
      56              : use tokio::sync::mpsc::error::TrySendError;
      57              : use tokio_util::sync::CancellationToken;
      58              : use utils::{
      59              :     completion::Barrier,
      60              :     failpoint_support,
      61              :     generation::Generation,
      62              :     http::error::ApiError,
      63              :     id::{NodeId, TenantId, TimelineId},
      64              :     sync::gate::Gate,
      65              : };
      66              : 
      67              : use crate::{
      68              :     compute_hook::ComputeHook,
      69              :     heartbeater::{Heartbeater, PageserverState},
      70              :     node::{AvailabilityTransition, Node},
      71              :     persistence::{split_state::SplitState, DatabaseError, Persistence, TenantShardPersistence},
      72              :     reconciler::attached_location_conf,
      73              :     scheduler::Scheduler,
      74              :     tenant_shard::{
      75              :         IntentState, ObservedState, ObservedStateLocation, ReconcileResult, ReconcileWaitError,
      76              :         ReconcilerWaiter, TenantShard,
      77              :     },
      78              : };
      79              : 
      80              : // For operations that should be quick, like attaching a new tenant
      81              : const SHORT_RECONCILE_TIMEOUT: Duration = Duration::from_secs(5);
      82              : 
      83              : // For operations that might be slow, like migrating a tenant with
      84              : // some data in it.
      85              : pub const RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
      86              : 
      87              : // If we receive a call using Secondary mode initially, it will omit generation.  We will initialize
      88              : // tenant shards into this generation, and as long as it remains in this generation, we will accept
      89              : // input generation from future requests as authoritative.
      90              : const INITIAL_GENERATION: Generation = Generation::new(0);
      91              : 
      92              : /// How long [`Service::startup_reconcile`] is allowed to take before it should give
      93              : /// up on unresponsive pageservers and proceed.
      94              : pub(crate) const STARTUP_RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
      95              : 
      96              : /// How long a node may be unresponsive to heartbeats before we declare it offline.
      97              : /// This must be long enough to cover node restarts as well as normal operations: in future
      98              : /// it should be separated into distinct timeouts for startup vs. normal operation
      99              : /// (`<https://github.com/neondatabase/neon/issues/7552>`)
     100              : pub const MAX_UNAVAILABLE_INTERVAL_DEFAULT: Duration = Duration::from_secs(300);
     101              : 
     102            0 : #[derive(Clone, strum_macros::Display)]
     103              : enum TenantOperations {
     104              :     Create,
     105              :     LocationConfig,
     106              :     ConfigSet,
     107              :     TimeTravelRemoteStorage,
     108              :     Delete,
     109              :     UpdatePolicy,
     110              :     ShardSplit,
     111              :     SecondaryDownload,
     112              :     TimelineCreate,
     113              :     TimelineDelete,
     114              : }
     115              : 
     116            0 : #[derive(Clone, strum_macros::Display)]
     117              : enum NodeOperations {
     118              :     Register,
     119              :     Configure,
     120              : }
     121              : 
     122              : pub const RECONCILER_CONCURRENCY_DEFAULT: usize = 128;
     123              : 
     124              : // Depth of the channel used to enqueue shards for reconciliation when they can't do it immediately.
     125              : // This channel is finite-size to avoid using excessive memory if we get into a state where reconciles are finishing more slowly
     126              : // than they're being pushed onto the queue.
     127              : const MAX_DELAYED_RECONCILES: usize = 10000;
     128              : 
     129              : // Top level state available to all HTTP handlers
     130              : struct ServiceState {
     131              :     tenants: BTreeMap<TenantShardId, TenantShard>,
     132              : 
     133              :     nodes: Arc<HashMap<NodeId, Node>>,
     134              : 
     135              :     scheduler: Scheduler,
     136              : 
     137              :     /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
     138              :     delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
     139              : }
     140              : 
     141              : /// Transform an error from a pageserver into an error to return to callers of a storage
     142              : /// controller API.
     143            0 : fn passthrough_api_error(node: &Node, e: mgmt_api::Error) -> ApiError {
     144            0 :     match e {
     145            0 :         mgmt_api::Error::ReceiveErrorBody(str) => {
     146            0 :             // Presume errors receiving body are connectivity/availability issues
     147            0 :             ApiError::ResourceUnavailable(
     148            0 :                 format!("{node} error receiving error body: {str}").into(),
     149            0 :             )
     150              :         }
     151            0 :         mgmt_api::Error::ReceiveBody(str) => {
     152            0 :             // Presume errors receiving body are connectivity/availability issues
     153            0 :             ApiError::ResourceUnavailable(format!("{node} error receiving body: {str}").into())
     154              :         }
     155            0 :         mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, msg) => {
     156            0 :             ApiError::NotFound(anyhow::anyhow!(format!("{node}: {msg}")).into())
     157              :         }
     158            0 :         mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg) => {
     159            0 :             ApiError::ResourceUnavailable(format!("{node}: {msg}").into())
     160              :         }
     161            0 :         mgmt_api::Error::ApiError(status @ StatusCode::UNAUTHORIZED, msg)
     162            0 :         | mgmt_api::Error::ApiError(status @ StatusCode::FORBIDDEN, msg) => {
     163              :             // Auth errors talking to a pageserver are not auth errors for the caller: they are
     164              :             // internal server errors, showing that something is wrong with the pageserver or
     165              :             // storage controller's auth configuration.
     166            0 :             ApiError::InternalServerError(anyhow::anyhow!("{node} {status}: {msg}"))
     167              :         }
     168            0 :         mgmt_api::Error::ApiError(status, msg) => {
     169            0 :             // Presume general case of pageserver API errors is that we tried to do something
     170            0 :             // that can't be done right now.
     171            0 :             ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
     172              :         }
     173            0 :         mgmt_api::Error::Cancelled => ApiError::ShuttingDown,
     174              :     }
     175            0 : }
     176              : 
     177              : impl ServiceState {
     178            0 :     fn new(
     179            0 :         nodes: HashMap<NodeId, Node>,
     180            0 :         tenants: BTreeMap<TenantShardId, TenantShard>,
     181            0 :         scheduler: Scheduler,
     182            0 :         delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
     183            0 :     ) -> Self {
     184            0 :         Self {
     185            0 :             tenants,
     186            0 :             nodes: Arc::new(nodes),
     187            0 :             scheduler,
     188            0 :             delayed_reconcile_rx,
     189            0 :         }
     190            0 :     }
     191              : 
     192            0 :     fn parts_mut(
     193            0 :         &mut self,
     194            0 :     ) -> (
     195            0 :         &mut Arc<HashMap<NodeId, Node>>,
     196            0 :         &mut BTreeMap<TenantShardId, TenantShard>,
     197            0 :         &mut Scheduler,
     198            0 :     ) {
     199            0 :         (&mut self.nodes, &mut self.tenants, &mut self.scheduler)
     200            0 :     }
     201              : }
     202              : 
     203              : #[derive(Clone)]
     204              : pub struct Config {
     205              :     // All pageservers managed by one instance of this service must have
     206              :     // the same public key.  This JWT token will be used to authenticate
     207              :     // this service to the pageservers it manages.
     208              :     pub jwt_token: Option<String>,
     209              : 
     210              :     // This JWT token will be used to authenticate this service to the control plane.
     211              :     pub control_plane_jwt_token: Option<String>,
     212              : 
     213              :     /// Where the compute hook should send notifications of pageserver attachment locations
     214              :     /// (this URL points to the control plane in prod). If this is None, the compute hook will
     215              :     /// assume it is running in a test environment and try to update neon_local.
     216              :     pub compute_hook_url: Option<String>,
     217              : 
     218              :     /// Grace period within which a pageserver does not respond to heartbeats, but is still
     219              :     /// considered active. Once the grace period elapses, the next heartbeat failure will
     220              :     /// mark the pagseserver offline.
     221              :     pub max_unavailable_interval: Duration,
     222              : 
     223              :     /// How many Reconcilers may be spawned concurrently
     224              :     pub reconciler_concurrency: usize,
     225              : 
     226              :     /// How large must a shard grow in bytes before we split it?
     227              :     /// None disables auto-splitting.
     228              :     pub split_threshold: Option<u64>,
     229              : }
     230              : 
     231              : impl From<DatabaseError> for ApiError {
     232            0 :     fn from(err: DatabaseError) -> ApiError {
     233            0 :         match err {
     234            0 :             DatabaseError::Query(e) => ApiError::InternalServerError(e.into()),
     235              :             // FIXME: ApiError doesn't have an Unavailable variant, but ShuttingDown maps to 503.
     236              :             DatabaseError::Connection(_) | DatabaseError::ConnectionPool(_) => {
     237            0 :                 ApiError::ShuttingDown
     238              :             }
     239            0 :             DatabaseError::Logical(reason) => {
     240            0 :                 ApiError::InternalServerError(anyhow::anyhow!(reason))
     241              :             }
     242              :         }
     243            0 :     }
     244              : }
     245              : 
     246              : pub struct Service {
     247              :     inner: Arc<std::sync::RwLock<ServiceState>>,
     248              :     config: Config,
     249              :     persistence: Arc<Persistence>,
     250              :     compute_hook: Arc<ComputeHook>,
     251              :     result_tx: tokio::sync::mpsc::UnboundedSender<ReconcileResult>,
     252              : 
     253              :     heartbeater: Heartbeater,
     254              : 
     255              :     // Channel for background cleanup from failed operations that require cleanup, such as shard split
     256              :     abort_tx: tokio::sync::mpsc::UnboundedSender<TenantShardSplitAbort>,
     257              : 
     258              :     // Locking on a tenant granularity (covers all shards in the tenant):
     259              :     // - Take exclusively for rare operations that mutate the tenant's persistent state (e.g. create/delete/split)
     260              :     // - Take in shared mode for operations that need the set of shards to stay the same to complete reliably (e.g. timeline CRUD)
     261              :     tenant_op_locks: IdLockMap<TenantId, TenantOperations>,
     262              : 
     263              :     // Locking for node-mutating operations: take exclusively for operations that modify the node's persistent state, or
     264              :     // that transition it to/from Active.
     265              :     node_op_locks: IdLockMap<NodeId, NodeOperations>,
     266              : 
     267              :     // Limit how many Reconcilers we will spawn concurrently
     268              :     reconciler_concurrency: Arc<tokio::sync::Semaphore>,
     269              : 
     270              :     /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
     271              :     /// Send into this queue to promptly attempt to reconcile this shard next time units are available.
     272              :     ///
     273              :     /// Note that this state logically lives inside ServiceInner, but carrying Sender here makes the code simpler
     274              :     /// by avoiding needing a &mut ref to something inside the ServiceInner.  This could be optimized to
     275              :     /// use a VecDeque instead of a channel to reduce synchronization overhead, at the cost of some code complexity.
     276              :     delayed_reconcile_tx: tokio::sync::mpsc::Sender<TenantShardId>,
     277              : 
     278              :     // Process shutdown will fire this token
     279              :     cancel: CancellationToken,
     280              : 
     281              :     // Background tasks will hold this gate
     282              :     gate: Gate,
     283              : 
     284              :     /// This waits for initial reconciliation with pageservers to complete.  Until this barrier
     285              :     /// passes, it isn't safe to do any actions that mutate tenants.
     286              :     pub(crate) startup_complete: Barrier,
     287              : }
     288              : 
     289              : impl From<ReconcileWaitError> for ApiError {
     290            0 :     fn from(value: ReconcileWaitError) -> Self {
     291            0 :         match value {
     292            0 :             ReconcileWaitError::Shutdown => ApiError::ShuttingDown,
     293            0 :             e @ ReconcileWaitError::Timeout(_) => ApiError::Timeout(format!("{e}").into()),
     294            0 :             e @ ReconcileWaitError::Failed(..) => ApiError::InternalServerError(anyhow::anyhow!(e)),
     295              :         }
     296            0 :     }
     297              : }
     298              : 
     299              : #[allow(clippy::large_enum_variant)]
     300              : enum TenantCreateOrUpdate {
     301              :     Create(TenantCreateRequest),
     302              :     Update(Vec<ShardUpdate>),
     303              : }
     304              : 
     305              : struct ShardSplitParams {
     306              :     old_shard_count: ShardCount,
     307              :     new_shard_count: ShardCount,
     308              :     new_stripe_size: Option<ShardStripeSize>,
     309              :     targets: Vec<ShardSplitTarget>,
     310              :     policy: PlacementPolicy,
     311              :     config: TenantConfig,
     312              :     shard_ident: ShardIdentity,
     313              : }
     314              : 
     315              : // When preparing for a shard split, we may either choose to proceed with the split,
     316              : // or find that the work is already done and return NoOp.
     317              : enum ShardSplitAction {
     318              :     Split(ShardSplitParams),
     319              :     NoOp(TenantShardSplitResponse),
     320              : }
     321              : 
     322              : // A parent shard which will be split
     323              : struct ShardSplitTarget {
     324              :     parent_id: TenantShardId,
     325              :     node: Node,
     326              :     child_ids: Vec<TenantShardId>,
     327              : }
     328              : 
     329              : /// When we tenant shard split operation fails, we may not be able to clean up immediately, because nodes
     330              : /// might not be available.  We therefore use a queue of abort operations processed in the background.
     331              : struct TenantShardSplitAbort {
     332              :     tenant_id: TenantId,
     333              :     /// The target values from the request that failed
     334              :     new_shard_count: ShardCount,
     335              :     new_stripe_size: Option<ShardStripeSize>,
     336              :     /// Until this abort op is complete, no other operations may be done on the tenant
     337              :     _tenant_lock: WrappedWriteGuard<TenantOperations>,
     338              : }
     339              : 
     340            0 : #[derive(thiserror::Error, Debug)]
     341              : enum TenantShardSplitAbortError {
     342              :     #[error(transparent)]
     343              :     Database(#[from] DatabaseError),
     344              :     #[error(transparent)]
     345              :     Remote(#[from] mgmt_api::Error),
     346              :     #[error("Unavailable")]
     347              :     Unavailable,
     348              : }
     349              : 
     350              : struct ShardUpdate {
     351              :     tenant_shard_id: TenantShardId,
     352              :     placement_policy: PlacementPolicy,
     353              :     tenant_config: TenantConfig,
     354              : 
     355              :     /// If this is None, generation is not updated.
     356              :     generation: Option<Generation>,
     357              : }
     358              : 
     359              : impl Service {
     360            0 :     pub fn get_config(&self) -> &Config {
     361            0 :         &self.config
     362            0 :     }
     363              : 
     364              :     /// Called once on startup, this function attempts to contact all pageservers to build an up-to-date
     365              :     /// view of the world, and determine which pageservers are responsive.
     366            0 :     #[instrument(skip_all)]
     367              :     async fn startup_reconcile(
     368              :         self: &Arc<Service>,
     369              :         bg_compute_notify_result_tx: tokio::sync::mpsc::Sender<
     370              :             Result<(), (TenantShardId, NotifyError)>,
     371              :         >,
     372              :     ) {
     373              :         // For all tenant shards, a vector of observed states on nodes (where None means
     374              :         // indeterminate, same as in [`ObservedStateLocation`])
     375              :         let mut observed: HashMap<TenantShardId, Vec<(NodeId, Option<LocationConfig>)>> =
     376              :             HashMap::new();
     377              : 
     378              :         // Startup reconciliation does I/O to other services: whether they
     379              :         // are responsive or not, we should aim to finish within our deadline, because:
     380              :         // - If we don't, a k8s readiness hook watching /ready will kill us.
     381              :         // - While we're waiting for startup reconciliation, we are not fully
     382              :         //   available for end user operations like creating/deleting tenants and timelines.
     383              :         //
     384              :         // We set multiple deadlines to break up the time available between the phases of work: this is
     385              :         // arbitrary, but avoids a situation where the first phase could burn our entire timeout period.
     386              :         let start_at = Instant::now();
     387              :         let node_scan_deadline = start_at
     388              :             .checked_add(STARTUP_RECONCILE_TIMEOUT / 2)
     389              :             .expect("Reconcile timeout is a modest constant");
     390              : 
     391              :         // Accumulate a list of any tenant locations that ought to be detached
     392              :         let mut cleanup = Vec::new();
     393              : 
     394              :         let node_listings = self.scan_node_locations(node_scan_deadline).await;
     395              :         // Send initial heartbeat requests to nodes that replied to the location listing above.
     396              :         let nodes_online = self.initial_heartbeat_round(node_listings.keys()).await;
     397              : 
     398              :         for (node_id, list_response) in node_listings {
     399              :             let tenant_shards = list_response.tenant_shards;
     400              :             tracing::info!(
     401              :                 "Received {} shard statuses from pageserver {}, setting it to Active",
     402              :                 tenant_shards.len(),
     403              :                 node_id
     404              :             );
     405              : 
     406              :             for (tenant_shard_id, conf_opt) in tenant_shards {
     407              :                 let shard_observations = observed.entry(tenant_shard_id).or_default();
     408              :                 shard_observations.push((node_id, conf_opt));
     409              :             }
     410              :         }
     411              : 
     412              :         // List of tenants for which we will attempt to notify compute of their location at startup
     413              :         let mut compute_notifications = Vec::new();
     414              : 
     415              :         // Populate intent and observed states for all tenants, based on reported state on pageservers
     416              :         tracing::info!("Populating tenant shards' states from initial pageserver scan...");
     417              :         let shard_count = {
     418              :             let mut locked = self.inner.write().unwrap();
     419              :             let (nodes, tenants, scheduler) = locked.parts_mut();
     420              : 
     421              :             // Mark nodes online if they responded to us: nodes are offline by default after a restart.
     422              :             let mut new_nodes = (**nodes).clone();
     423              :             for (node_id, node) in new_nodes.iter_mut() {
     424              :                 if let Some(utilization) = nodes_online.get(node_id) {
     425              :                     node.set_availability(NodeAvailability::Active(UtilizationScore(
     426              :                         utilization.utilization_score,
     427              :                     )));
     428              :                     scheduler.node_upsert(node);
     429              :                 }
     430              :             }
     431              :             *nodes = Arc::new(new_nodes);
     432              : 
     433              :             for (tenant_shard_id, shard_observations) in observed {
     434              :                 for (node_id, observed_loc) in shard_observations {
     435              :                     let Some(tenant_shard) = tenants.get_mut(&tenant_shard_id) else {
     436              :                         cleanup.push((tenant_shard_id, node_id));
     437              :                         continue;
     438              :                     };
     439              :                     tenant_shard
     440              :                         .observed
     441              :                         .locations
     442              :                         .insert(node_id, ObservedStateLocation { conf: observed_loc });
     443              :                 }
     444              :             }
     445              : 
     446              :             // Populate each tenant's intent state
     447              :             let mut schedule_context = ScheduleContext::default();
     448              :             for (tenant_shard_id, tenant_shard) in tenants.iter_mut() {
     449              :                 if tenant_shard_id.shard_number == ShardNumber(0) {
     450              :                     // Reset scheduling context each time we advance to the next Tenant
     451              :                     schedule_context = ScheduleContext::default();
     452              :                 }
     453              : 
     454              :                 tenant_shard.intent_from_observed(scheduler);
     455              :                 if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
     456              :                     // Non-fatal error: we are unable to properly schedule the tenant, perhaps because
     457              :                     // not enough pageservers are available.  The tenant may well still be available
     458              :                     // to clients.
     459              :                     tracing::error!("Failed to schedule tenant {tenant_shard_id} at startup: {e}");
     460              :                 } else {
     461              :                     // If we're both intending and observed to be attached at a particular node, we will
     462              :                     // emit a compute notification for this. In the case where our observed state does not
     463              :                     // yet match our intent, we will eventually reconcile, and that will emit a compute notification.
     464              :                     if let Some(attached_at) = tenant_shard.stably_attached() {
     465              :                         compute_notifications.push((
     466              :                             *tenant_shard_id,
     467              :                             attached_at,
     468              :                             tenant_shard.shard.stripe_size,
     469              :                         ));
     470              :                     }
     471              :                 }
     472              :             }
     473              : 
     474              :             tenants.len()
     475              :         };
     476              : 
     477              :         // TODO: if any tenant's intent now differs from its loaded generation_pageserver, we should clear that
     478              :         // generation_pageserver in the database.
     479              : 
     480              :         // Emit compute hook notifications for all tenants which are already stably attached.  Other tenants
     481              :         // will emit compute hook notifications when they reconcile.
     482              :         //
     483              :         // Ordering: our calls to notify_background synchronously establish a relative order for these notifications vs. any later
     484              :         // calls into the ComputeHook for the same tenant: we can leave these to run to completion in the background and any later
     485              :         // calls will be correctly ordered wrt these.
     486              :         //
     487              :         // Concurrency: we call notify_background for all tenants, which will create O(N) tokio tasks, but almost all of them
     488              :         // will just wait on the ComputeHook::API_CONCURRENCY semaphore immediately, so very cheap until they get that semaphore
     489              :         // unit and start doing I/O.
     490              :         tracing::info!(
     491              :             "Sending {} compute notifications",
     492              :             compute_notifications.len()
     493              :         );
     494              :         self.compute_hook.notify_background(
     495              :             compute_notifications,
     496              :             bg_compute_notify_result_tx.clone(),
     497              :             &self.cancel,
     498              :         );
     499              : 
     500              :         // Finally, now that the service is up and running, launch reconcile operations for any tenants
     501              :         // which require it: under normal circumstances this should only include tenants that were in some
     502              :         // transient state before we restarted, or any tenants whose compute hooks failed above.
     503              :         tracing::info!("Checking for shards in need of reconciliation...");
     504              :         let reconcile_tasks = self.reconcile_all();
     505              :         // We will not wait for these reconciliation tasks to run here: we're now done with startup and
     506              :         // normal operations may proceed.
     507              : 
     508              :         // Clean up any tenants that were found on pageservers but are not known to us.  Do this in the
     509              :         // background because it does not need to complete in order to proceed with other work.
     510              :         if !cleanup.is_empty() {
     511              :             tracing::info!("Cleaning up {} locations in the background", cleanup.len());
     512              :             tokio::task::spawn({
     513              :                 let cleanup_self = self.clone();
     514            0 :                 async move { cleanup_self.cleanup_locations(cleanup).await }
     515              :             });
     516              :         }
     517              : 
     518              :         tracing::info!("Startup complete, spawned {reconcile_tasks} reconciliation tasks ({shard_count} shards total)");
     519              :     }
     520              : 
     521            0 :     async fn initial_heartbeat_round<'a>(
     522            0 :         &self,
     523            0 :         node_ids: impl Iterator<Item = &'a NodeId>,
     524            0 :     ) -> HashMap<NodeId, PageserverUtilization> {
     525            0 :         assert!(!self.startup_complete.is_ready());
     526              : 
     527            0 :         let all_nodes = {
     528            0 :             let locked = self.inner.read().unwrap();
     529            0 :             locked.nodes.clone()
     530            0 :         };
     531            0 : 
     532            0 :         let mut nodes_to_heartbeat = HashMap::new();
     533            0 :         for node_id in node_ids {
     534            0 :             match all_nodes.get(node_id) {
     535            0 :                 Some(node) => {
     536            0 :                     nodes_to_heartbeat.insert(*node_id, node.clone());
     537            0 :                 }
     538              :                 None => {
     539            0 :                     tracing::warn!("Node {node_id} was removed during start-up");
     540              :                 }
     541              :             }
     542              :         }
     543              : 
     544            0 :         tracing::info!("Sending initial heartbeats...");
     545            0 :         let res = self
     546            0 :             .heartbeater
     547            0 :             .heartbeat(Arc::new(nodes_to_heartbeat))
     548            0 :             .await;
     549              : 
     550            0 :         let mut online_nodes = HashMap::new();
     551            0 :         if let Ok(deltas) = res {
     552            0 :             for (node_id, status) in deltas.0 {
     553            0 :                 match status {
     554            0 :                     PageserverState::Available { utilization, .. } => {
     555            0 :                         online_nodes.insert(node_id, utilization);
     556            0 :                     }
     557            0 :                     PageserverState::Offline => {}
     558              :                 }
     559              :             }
     560            0 :         }
     561              : 
     562            0 :         online_nodes
     563            0 :     }
     564              : 
     565              :     /// Used during [`Self::startup_reconcile`]: issue GETs to all nodes concurrently, with a deadline.
     566              :     ///
     567              :     /// The result includes only nodes which responded within the deadline
     568            0 :     async fn scan_node_locations(
     569            0 :         &self,
     570            0 :         deadline: Instant,
     571            0 :     ) -> HashMap<NodeId, LocationConfigListResponse> {
     572            0 :         let nodes = {
     573            0 :             let locked = self.inner.read().unwrap();
     574            0 :             locked.nodes.clone()
     575            0 :         };
     576            0 : 
     577            0 :         let mut node_results = HashMap::new();
     578            0 : 
     579            0 :         let mut node_list_futs = FuturesUnordered::new();
     580            0 : 
     581            0 :         tracing::info!("Scanning shards on {} nodes...", nodes.len());
     582            0 :         for node in nodes.values() {
     583            0 :             node_list_futs.push({
     584            0 :                 async move {
     585            0 :                     tracing::info!("Scanning shards on node {node}...");
     586            0 :                     let timeout = Duration::from_secs(1);
     587            0 :                     let response = node
     588            0 :                         .with_client_retries(
     589            0 :                             |client| async move { client.list_location_config().await },
     590            0 :                             &self.config.jwt_token,
     591            0 :                             1,
     592            0 :                             5,
     593            0 :                             timeout,
     594            0 :                             &self.cancel,
     595            0 :                         )
     596            0 :                         .await;
     597            0 :                     (node.get_id(), response)
     598            0 :                 }
     599            0 :             });
     600            0 :         }
     601              : 
     602              :         loop {
     603            0 :             let (node_id, result) = tokio::select! {
     604              :                 next = node_list_futs.next() => {
     605              :                     match next {
     606              :                         Some(result) => result,
     607              :                         None =>{
     608              :                             // We got results for all our nodes
     609              :                             break;
     610              :                         }
     611              : 
     612              :                     }
     613              :                 },
     614              :                 _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
     615              :                     // Give up waiting for anyone who hasn't responded: we will yield the results that we have
     616              :                     tracing::info!("Reached deadline while waiting for nodes to respond to location listing requests");
     617              :                     break;
     618              :                 }
     619              :             };
     620              : 
     621            0 :             let Some(list_response) = result else {
     622            0 :                 tracing::info!("Shutdown during startup_reconcile");
     623            0 :                 break;
     624              :             };
     625              : 
     626            0 :             match list_response {
     627            0 :                 Err(e) => {
     628            0 :                     tracing::warn!("Could not scan node {} ({e})", node_id);
     629              :                 }
     630            0 :                 Ok(listing) => {
     631            0 :                     node_results.insert(node_id, listing);
     632            0 :                 }
     633              :             }
     634              :         }
     635              : 
     636            0 :         node_results
     637            0 :     }
     638              : 
     639              :     /// Used during [`Self::startup_reconcile`]: detach a list of unknown-to-us tenants from pageservers.
     640              :     ///
     641              :     /// This is safe to run in the background, because if we don't have this TenantShardId in our map of
     642              :     /// tenants, then it is probably something incompletely deleted before: we will not fight with any
     643              :     /// other task trying to attach it.
     644            0 :     #[instrument(skip_all)]
     645              :     async fn cleanup_locations(&self, cleanup: Vec<(TenantShardId, NodeId)>) {
     646              :         let nodes = self.inner.read().unwrap().nodes.clone();
     647              : 
     648              :         for (tenant_shard_id, node_id) in cleanup {
     649              :             // A node reported a tenant_shard_id which is unknown to us: detach it.
     650              :             let Some(node) = nodes.get(&node_id) else {
     651              :                 // This is legitimate; we run in the background and [`Self::startup_reconcile`] might have identified
     652              :                 // a location to clean up on a node that has since been removed.
     653              :                 tracing::info!(
     654              :                     "Not cleaning up location {node_id}/{tenant_shard_id}: node not found"
     655              :                 );
     656              :                 continue;
     657              :             };
     658              : 
     659              :             if self.cancel.is_cancelled() {
     660              :                 break;
     661              :             }
     662              : 
     663              :             let client = PageserverClient::new(
     664              :                 node.get_id(),
     665              :                 node.base_url(),
     666              :                 self.config.jwt_token.as_deref(),
     667              :             );
     668              :             match client
     669              :                 .location_config(
     670              :                     tenant_shard_id,
     671              :                     LocationConfig {
     672              :                         mode: LocationConfigMode::Detached,
     673              :                         generation: None,
     674              :                         secondary_conf: None,
     675              :                         shard_number: tenant_shard_id.shard_number.0,
     676              :                         shard_count: tenant_shard_id.shard_count.literal(),
     677              :                         shard_stripe_size: 0,
     678              :                         tenant_conf: models::TenantConfig::default(),
     679              :                     },
     680              :                     None,
     681              :                     false,
     682              :                 )
     683              :                 .await
     684              :             {
     685              :                 Ok(()) => {
     686              :                     tracing::info!(
     687              :                         "Detached unknown shard {tenant_shard_id} on pageserver {node_id}"
     688              :                     );
     689              :                 }
     690              :                 Err(e) => {
     691              :                     // Non-fatal error: leaving a tenant shard behind that we are not managing shouldn't
     692              :                     // break anything.
     693              :                     tracing::error!(
     694              :                         "Failed to detach unknkown shard {tenant_shard_id} on pageserver {node_id}: {e}"
     695              :                     );
     696              :                 }
     697              :             }
     698              :         }
     699              :     }
     700              : 
     701              :     /// Long running background task that periodically wakes up and looks for shards that need
     702              :     /// reconciliation.  Reconciliation is fallible, so any reconciliation tasks that fail during
     703              :     /// e.g. a tenant create/attach/migrate must eventually be retried: this task is responsible
     704              :     /// for those retries.
     705            0 :     #[instrument(skip_all)]
     706              :     async fn background_reconcile(self: &Arc<Self>) {
     707              :         self.startup_complete.clone().wait().await;
     708              : 
     709              :         const BACKGROUND_RECONCILE_PERIOD: Duration = Duration::from_secs(20);
     710              : 
     711              :         let mut interval = tokio::time::interval(BACKGROUND_RECONCILE_PERIOD);
     712              :         while !self.cancel.is_cancelled() {
     713              :             tokio::select! {
     714              :               _ = interval.tick() => {
     715              :                 let reconciles_spawned = self.reconcile_all();
     716              :                 if reconciles_spawned == 0 {
     717              :                     // Run optimizer only when we didn't find any other work to do
     718              :                     let optimizations = self.optimize_all().await;
     719              :                     if optimizations == 0 {
     720              :                         // Run new splits only when no optimizations are pending
     721              :                         self.autosplit_tenants().await;
     722              :                     }
     723              :                 }
     724              :             }
     725              :               _ = self.cancel.cancelled() => return
     726              :             }
     727              :         }
     728              :     }
     729            0 :     #[instrument(skip_all)]
     730              :     async fn spawn_heartbeat_driver(&self) {
     731              :         self.startup_complete.clone().wait().await;
     732              : 
     733              :         const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
     734              : 
     735              :         let mut interval = tokio::time::interval(HEARTBEAT_INTERVAL);
     736              :         while !self.cancel.is_cancelled() {
     737              :             tokio::select! {
     738              :               _ = interval.tick() => { }
     739              :               _ = self.cancel.cancelled() => return
     740              :             };
     741              : 
     742              :             let nodes = {
     743              :                 let locked = self.inner.read().unwrap();
     744              :                 locked.nodes.clone()
     745              :             };
     746              : 
     747              :             let res = self.heartbeater.heartbeat(nodes).await;
     748              :             if let Ok(deltas) = res {
     749              :                 for (node_id, state) in deltas.0 {
     750              :                     let new_availability = match state {
     751              :                         PageserverState::Available { utilization, .. } => NodeAvailability::Active(
     752              :                             UtilizationScore(utilization.utilization_score),
     753              :                         ),
     754              :                         PageserverState::Offline => NodeAvailability::Offline,
     755              :                     };
     756              :                     let res = self
     757              :                         .node_configure(node_id, Some(new_availability), None)
     758              :                         .await;
     759              : 
     760              :                     match res {
     761              :                         Ok(()) => {}
     762              :                         Err(ApiError::NotFound(_)) => {
     763              :                             // This should be rare, but legitimate since the heartbeats are done
     764              :                             // on a snapshot of the nodes.
     765              :                             tracing::info!("Node {} was not found after heartbeat round", node_id);
     766              :                         }
     767              :                         Err(err) => {
     768              :                             tracing::error!(
     769              :                                 "Failed to update node {} after heartbeat round: {}",
     770              :                                 node_id,
     771              :                                 err
     772              :                             );
     773              :                         }
     774              :                     }
     775              :                 }
     776              :             }
     777              :         }
     778              :     }
     779              : 
     780              :     /// Apply the contents of a [`ReconcileResult`] to our in-memory state: if the reconciliation
     781              :     /// was successful and intent hasn't changed since the Reconciler was spawned, this will update
     782              :     /// the observed state of the tenant such that subsequent calls to [`TenantShard::get_reconcile_needed`]
     783              :     /// will indicate that reconciliation is not needed.
     784            0 :     #[instrument(skip_all, fields(
     785              :         tenant_id=%result.tenant_shard_id.tenant_id, shard_id=%result.tenant_shard_id.shard_slug(),
     786              :         sequence=%result.sequence
     787            0 :     ))]
     788              :     fn process_result(&self, result: ReconcileResult) {
     789              :         let mut locked = self.inner.write().unwrap();
     790              :         let Some(tenant) = locked.tenants.get_mut(&result.tenant_shard_id) else {
     791              :             // A reconciliation result might race with removing a tenant: drop results for
     792              :             // tenants that aren't in our map.
     793              :             return;
     794              :         };
     795              : 
     796              :         // Usually generation should only be updated via this path, so the max() isn't
     797              :         // needed, but it is used to handle out-of-band updates via. e.g. test hook.
     798              :         tenant.generation = std::cmp::max(tenant.generation, result.generation);
     799              : 
     800              :         // If the reconciler signals that it failed to notify compute, set this state on
     801              :         // the shard so that a future [`TenantShard::maybe_reconcile`] will try again.
     802              :         tenant.pending_compute_notification = result.pending_compute_notification;
     803              : 
     804              :         // Let the TenantShard know it is idle.
     805              :         tenant.reconcile_complete(result.sequence);
     806              : 
     807              :         match result.result {
     808              :             Ok(()) => {
     809              :                 for (node_id, loc) in &result.observed.locations {
     810              :                     if let Some(conf) = &loc.conf {
     811              :                         tracing::info!("Updating observed location {}: {:?}", node_id, conf);
     812              :                     } else {
     813              :                         tracing::info!("Setting observed location {} to None", node_id,)
     814              :                     }
     815              :                 }
     816              :                 tenant.observed = result.observed;
     817              :                 tenant.waiter.advance(result.sequence);
     818              :             }
     819              :             Err(e) => {
     820              :                 match e {
     821              :                     ReconcileError::Cancel => {
     822              :                         tracing::info!("Reconciler was cancelled");
     823              :                     }
     824              :                     ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
     825              :                         // This might be due to the reconciler getting cancelled, or it might
     826              :                         // be due to the `Node` being marked offline.
     827              :                         tracing::info!("Reconciler cancelled during pageserver API call");
     828              :                     }
     829              :                     _ => {
     830              :                         tracing::warn!("Reconcile error: {}", e);
     831              :                     }
     832              :                 }
     833              : 
     834              :                 // Ordering: populate last_error before advancing error_seq,
     835              :                 // so that waiters will see the correct error after waiting.
     836              :                 tenant.set_last_error(result.sequence, e);
     837              : 
     838              :                 for (node_id, o) in result.observed.locations {
     839              :                     tenant.observed.locations.insert(node_id, o);
     840              :                 }
     841              :             }
     842              :         }
     843              : 
     844              :         // Maybe some other work can proceed now that this job finished.
     845              :         if self.reconciler_concurrency.available_permits() > 0 {
     846              :             while let Ok(tenant_shard_id) = locked.delayed_reconcile_rx.try_recv() {
     847              :                 let (nodes, tenants, _scheduler) = locked.parts_mut();
     848              :                 if let Some(shard) = tenants.get_mut(&tenant_shard_id) {
     849              :                     shard.delayed_reconcile = false;
     850              :                     self.maybe_reconcile_shard(shard, nodes);
     851              :                 }
     852              : 
     853              :                 if self.reconciler_concurrency.available_permits() == 0 {
     854              :                     break;
     855              :                 }
     856              :             }
     857              :         }
     858              :     }
     859              : 
     860            0 :     async fn process_results(
     861            0 :         &self,
     862            0 :         mut result_rx: tokio::sync::mpsc::UnboundedReceiver<ReconcileResult>,
     863            0 :         mut bg_compute_hook_result_rx: tokio::sync::mpsc::Receiver<
     864            0 :             Result<(), (TenantShardId, NotifyError)>,
     865            0 :         >,
     866            0 :     ) {
     867            0 :         loop {
     868            0 :             // Wait for the next result, or for cancellation
     869            0 :             tokio::select! {
     870              :                 r = result_rx.recv() => {
     871              :                     match r {
     872              :                         Some(result) => {self.process_result(result);},
     873              :                         None => {break;}
     874              :                     }
     875              :                 }
     876            0 :                 _ = async{
     877            0 :                     match bg_compute_hook_result_rx.recv().await {
     878            0 :                         Some(result) => {
     879            0 :                             if let Err((tenant_shard_id, notify_error)) = result {
     880            0 :                                 tracing::warn!("Marking shard {tenant_shard_id} for notification retry, due to error {notify_error}");
     881            0 :                                 let mut locked = self.inner.write().unwrap();
     882            0 :                                 if let Some(shard) = locked.tenants.get_mut(&tenant_shard_id) {
     883            0 :                                     shard.pending_compute_notification = true;
     884            0 :                                 }
     885              : 
     886            0 :                             }
     887              :                         },
     888              :                         None => {
     889              :                             // This channel is dead, but we don't want to terminate the outer loop{}: just wait for shutdown
     890            0 :                             self.cancel.cancelled().await;
     891              :                         }
     892              :                     }
     893            0 :                 } => {},
     894              :                 _ = self.cancel.cancelled() => {
     895              :                     break;
     896              :                 }
     897            0 :             };
     898            0 :         }
     899              : 
     900              :         // We should only fall through on shutdown
     901            0 :         assert!(self.cancel.is_cancelled());
     902            0 :     }
     903              : 
     904            0 :     async fn process_aborts(
     905            0 :         &self,
     906            0 :         mut abort_rx: tokio::sync::mpsc::UnboundedReceiver<TenantShardSplitAbort>,
     907            0 :     ) {
     908              :         loop {
     909              :             // Wait for the next result, or for cancellation
     910            0 :             let op = tokio::select! {
     911              :                 r = abort_rx.recv() => {
     912              :                     match r {
     913              :                         Some(op) => {op},
     914              :                         None => {break;}
     915              :                     }
     916              :                 }
     917              :                 _ = self.cancel.cancelled() => {
     918              :                     break;
     919              :                 }
     920              :             };
     921              : 
     922              :             // Retry until shutdown: we must keep this request object alive until it is properly
     923              :             // processed, as it holds a lock guard that prevents other operations trying to do things
     924              :             // to the tenant while it is in a weird part-split state.
     925            0 :             while !self.cancel.is_cancelled() {
     926            0 :                 match self.abort_tenant_shard_split(&op).await {
     927            0 :                     Ok(_) => break,
     928            0 :                     Err(e) => {
     929            0 :                         tracing::warn!(
     930            0 :                             "Failed to abort shard split on {}, will retry: {e}",
     931              :                             op.tenant_id
     932              :                         );
     933              : 
     934              :                         // If a node is unavailable, we hope that it has been properly marked Offline
     935              :                         // when we retry, so that the abort op will succeed.  If the abort op is failing
     936              :                         // for some other reason, we will keep retrying forever, or until a human notices
     937              :                         // and does something about it (either fixing a pageserver or restarting the controller).
     938            0 :                         tokio::time::timeout(Duration::from_secs(5), self.cancel.cancelled())
     939            0 :                             .await
     940            0 :                             .ok();
     941              :                     }
     942              :                 }
     943              :             }
     944              :         }
     945            0 :     }
     946              : 
     947            0 :     pub async fn spawn(config: Config, persistence: Arc<Persistence>) -> anyhow::Result<Arc<Self>> {
     948            0 :         let (result_tx, result_rx) = tokio::sync::mpsc::unbounded_channel();
     949            0 :         let (abort_tx, abort_rx) = tokio::sync::mpsc::unbounded_channel();
     950            0 : 
     951            0 :         tracing::info!("Loading nodes from database...");
     952            0 :         let nodes = persistence
     953            0 :             .list_nodes()
     954            0 :             .await?
     955            0 :             .into_iter()
     956            0 :             .map(Node::from_persistent)
     957            0 :             .collect::<Vec<_>>();
     958            0 :         let nodes: HashMap<NodeId, Node> = nodes.into_iter().map(|n| (n.get_id(), n)).collect();
     959            0 :         tracing::info!("Loaded {} nodes from database.", nodes.len());
     960              : 
     961            0 :         tracing::info!("Loading shards from database...");
     962            0 :         let mut tenant_shard_persistence = persistence.list_tenant_shards().await?;
     963            0 :         tracing::info!(
     964            0 :             "Loaded {} shards from database.",
     965            0 :             tenant_shard_persistence.len()
     966              :         );
     967              : 
     968              :         // If any shard splits were in progress, reset the database state to abort them
     969            0 :         let mut tenant_shard_count_min_max: HashMap<TenantId, (ShardCount, ShardCount)> =
     970            0 :             HashMap::new();
     971            0 :         for tsp in &mut tenant_shard_persistence {
     972            0 :             let shard = tsp.get_shard_identity()?;
     973            0 :             let tenant_shard_id = tsp.get_tenant_shard_id()?;
     974            0 :             let entry = tenant_shard_count_min_max
     975            0 :                 .entry(tenant_shard_id.tenant_id)
     976            0 :                 .or_insert_with(|| (shard.count, shard.count));
     977            0 :             entry.0 = std::cmp::min(entry.0, shard.count);
     978            0 :             entry.1 = std::cmp::max(entry.1, shard.count);
     979              :         }
     980              : 
     981            0 :         for (tenant_id, (count_min, count_max)) in tenant_shard_count_min_max {
     982            0 :             if count_min != count_max {
     983              :                 // Aborting the split in the database and dropping the child shards is sufficient: the reconciliation in
     984              :                 // [`Self::startup_reconcile`] will implicitly drop the child shards on remote pageservers, or they'll
     985              :                 // be dropped later in [`Self::node_activate_reconcile`] if it isn't available right now.
     986            0 :                 tracing::info!("Aborting shard split {tenant_id} {count_min:?} -> {count_max:?}");
     987            0 :                 let abort_status = persistence.abort_shard_split(tenant_id, count_max).await?;
     988              : 
     989              :                 // We may never see the Complete status here: if the split was complete, we wouldn't have
     990              :                 // identified this tenant has having mismatching min/max counts.
     991            0 :                 assert!(matches!(abort_status, AbortShardSplitStatus::Aborted));
     992              : 
     993              :                 // Clear the splitting status in-memory, to reflect that we just aborted in the database
     994            0 :                 tenant_shard_persistence.iter_mut().for_each(|tsp| {
     995            0 :                     // Set idle split state on those shards that we will retain.
     996            0 :                     let tsp_tenant_id = TenantId::from_str(tsp.tenant_id.as_str()).unwrap();
     997            0 :                     if tsp_tenant_id == tenant_id
     998            0 :                         && tsp.get_shard_identity().unwrap().count == count_min
     999            0 :                     {
    1000            0 :                         tsp.splitting = SplitState::Idle;
    1001            0 :                     } else if tsp_tenant_id == tenant_id {
    1002              :                         // Leave the splitting state on the child shards: this will be used next to
    1003              :                         // drop them.
    1004            0 :                         tracing::info!(
    1005            0 :                             "Shard {tsp_tenant_id} will be dropped after shard split abort",
    1006              :                         );
    1007            0 :                     }
    1008            0 :                 });
    1009            0 : 
    1010            0 :                 // Drop shards for this tenant which we didn't just mark idle (i.e. child shards of the aborted split)
    1011            0 :                 tenant_shard_persistence.retain(|tsp| {
    1012            0 :                     TenantId::from_str(tsp.tenant_id.as_str()).unwrap() != tenant_id
    1013            0 :                         || tsp.splitting == SplitState::Idle
    1014            0 :                 });
    1015            0 :             }
    1016              :         }
    1017              : 
    1018            0 :         let mut tenants = BTreeMap::new();
    1019            0 : 
    1020            0 :         let mut scheduler = Scheduler::new(nodes.values());
    1021            0 : 
    1022            0 :         #[cfg(feature = "testing")]
    1023            0 :         {
    1024            0 :             // Hack: insert scheduler state for all nodes referenced by shards, as compatibility
    1025            0 :             // tests only store the shards, not the nodes.  The nodes will be loaded shortly
    1026            0 :             // after when pageservers start up and register.
    1027            0 :             let mut node_ids = HashSet::new();
    1028            0 :             for tsp in &tenant_shard_persistence {
    1029            0 :                 if let Some(node_id) = tsp.generation_pageserver {
    1030            0 :                     node_ids.insert(node_id);
    1031            0 :                 }
    1032              :             }
    1033            0 :             for node_id in node_ids {
    1034            0 :                 tracing::info!("Creating node {} in scheduler for tests", node_id);
    1035            0 :                 let node = Node::new(
    1036            0 :                     NodeId(node_id as u64),
    1037            0 :                     "".to_string(),
    1038            0 :                     123,
    1039            0 :                     "".to_string(),
    1040            0 :                     123,
    1041            0 :                 );
    1042            0 : 
    1043            0 :                 scheduler.node_upsert(&node);
    1044              :             }
    1045              :         }
    1046            0 :         for tsp in tenant_shard_persistence {
    1047            0 :             let tenant_shard_id = tsp.get_tenant_shard_id()?;
    1048              : 
    1049              :             // We will populate intent properly later in [`Self::startup_reconcile`], initially populate
    1050              :             // it with what we can infer: the node for which a generation was most recently issued.
    1051            0 :             let mut intent = IntentState::new();
    1052            0 :             if let Some(generation_pageserver) = tsp.generation_pageserver {
    1053            0 :                 intent.set_attached(&mut scheduler, Some(NodeId(generation_pageserver as u64)));
    1054            0 :             }
    1055            0 :             let new_tenant = TenantShard::from_persistent(tsp, intent)?;
    1056              : 
    1057            0 :             tenants.insert(tenant_shard_id, new_tenant);
    1058              :         }
    1059              : 
    1060            0 :         let (startup_completion, startup_complete) = utils::completion::channel();
    1061            0 : 
    1062            0 :         // This channel is continuously consumed by process_results, so doesn't need to be very large.
    1063            0 :         let (bg_compute_notify_result_tx, bg_compute_notify_result_rx) =
    1064            0 :             tokio::sync::mpsc::channel(512);
    1065            0 : 
    1066            0 :         let (delayed_reconcile_tx, delayed_reconcile_rx) =
    1067            0 :             tokio::sync::mpsc::channel(MAX_DELAYED_RECONCILES);
    1068            0 : 
    1069            0 :         let cancel = CancellationToken::new();
    1070            0 :         let heartbeater = Heartbeater::new(
    1071            0 :             config.jwt_token.clone(),
    1072            0 :             config.max_unavailable_interval,
    1073            0 :             cancel.clone(),
    1074            0 :         );
    1075            0 :         let this = Arc::new(Self {
    1076            0 :             inner: Arc::new(std::sync::RwLock::new(ServiceState::new(
    1077            0 :                 nodes,
    1078            0 :                 tenants,
    1079            0 :                 scheduler,
    1080            0 :                 delayed_reconcile_rx,
    1081            0 :             ))),
    1082            0 :             config: config.clone(),
    1083            0 :             persistence,
    1084            0 :             compute_hook: Arc::new(ComputeHook::new(config.clone())),
    1085            0 :             result_tx,
    1086            0 :             heartbeater,
    1087            0 :             reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
    1088            0 :                 config.reconciler_concurrency,
    1089            0 :             )),
    1090            0 :             delayed_reconcile_tx,
    1091            0 :             abort_tx,
    1092            0 :             startup_complete: startup_complete.clone(),
    1093            0 :             cancel,
    1094            0 :             gate: Gate::default(),
    1095            0 :             tenant_op_locks: Default::default(),
    1096            0 :             node_op_locks: Default::default(),
    1097            0 :         });
    1098            0 : 
    1099            0 :         let result_task_this = this.clone();
    1100            0 :         tokio::task::spawn(async move {
    1101              :             // Block shutdown until we're done (we must respect self.cancel)
    1102            0 :             if let Ok(_gate) = result_task_this.gate.enter() {
    1103            0 :                 result_task_this
    1104            0 :                     .process_results(result_rx, bg_compute_notify_result_rx)
    1105            0 :                     .await
    1106            0 :             }
    1107            0 :         });
    1108            0 : 
    1109            0 :         tokio::task::spawn({
    1110            0 :             let this = this.clone();
    1111            0 :             async move {
    1112              :                 // Block shutdown until we're done (we must respect self.cancel)
    1113            0 :                 if let Ok(_gate) = this.gate.enter() {
    1114            0 :                     this.process_aborts(abort_rx).await
    1115            0 :                 }
    1116            0 :             }
    1117            0 :         });
    1118            0 : 
    1119            0 :         tokio::task::spawn({
    1120            0 :             let this = this.clone();
    1121            0 :             async move {
    1122            0 :                 if let Ok(_gate) = this.gate.enter() {
    1123            0 :                     loop {
    1124            0 :                         tokio::select! {
    1125              :                             _ = this.cancel.cancelled() => {
    1126              :                                 break;
    1127              :                             },
    1128              :                             _ = tokio::time::sleep(Duration::from_secs(60)) => {}
    1129            0 :                         };
    1130            0 :                         this.tenant_op_locks.housekeeping();
    1131            0 :                     }
    1132            0 :                 }
    1133            0 :             }
    1134            0 :         });
    1135            0 : 
    1136            0 :         tokio::task::spawn({
    1137            0 :             let this = this.clone();
    1138            0 :             // We will block the [`Service::startup_complete`] barrier until [`Self::startup_reconcile`]
    1139            0 :             // is done.
    1140            0 :             let startup_completion = startup_completion.clone();
    1141            0 :             async move {
    1142              :                 // Block shutdown until we're done (we must respect self.cancel)
    1143            0 :                 let Ok(_gate) = this.gate.enter() else {
    1144            0 :                     return;
    1145              :                 };
    1146              : 
    1147            0 :                 this.startup_reconcile(bg_compute_notify_result_tx).await;
    1148            0 :                 drop(startup_completion);
    1149            0 :             }
    1150            0 :         });
    1151            0 : 
    1152            0 :         tokio::task::spawn({
    1153            0 :             let this = this.clone();
    1154            0 :             let startup_complete = startup_complete.clone();
    1155            0 :             async move {
    1156            0 :                 startup_complete.wait().await;
    1157            0 :                 this.background_reconcile().await;
    1158            0 :             }
    1159            0 :         });
    1160            0 : 
    1161            0 :         tokio::task::spawn({
    1162            0 :             let this = this.clone();
    1163            0 :             let startup_complete = startup_complete.clone();
    1164            0 :             async move {
    1165            0 :                 startup_complete.wait().await;
    1166            0 :                 this.spawn_heartbeat_driver().await;
    1167            0 :             }
    1168            0 :         });
    1169            0 : 
    1170            0 :         Ok(this)
    1171            0 :     }
    1172              : 
    1173            0 :     pub(crate) async fn attach_hook(
    1174            0 :         &self,
    1175            0 :         attach_req: AttachHookRequest,
    1176            0 :     ) -> anyhow::Result<AttachHookResponse> {
    1177            0 :         // This is a test hook.  To enable using it on tenants that were created directly with
    1178            0 :         // the pageserver API (not via this service), we will auto-create any missing tenant
    1179            0 :         // shards with default state.
    1180            0 :         let insert = {
    1181            0 :             let locked = self.inner.write().unwrap();
    1182            0 :             !locked.tenants.contains_key(&attach_req.tenant_shard_id)
    1183            0 :         };
    1184            0 :         if insert {
    1185            0 :             let tsp = TenantShardPersistence {
    1186            0 :                 tenant_id: attach_req.tenant_shard_id.tenant_id.to_string(),
    1187            0 :                 shard_number: attach_req.tenant_shard_id.shard_number.0 as i32,
    1188            0 :                 shard_count: attach_req.tenant_shard_id.shard_count.literal() as i32,
    1189            0 :                 shard_stripe_size: 0,
    1190            0 :                 generation: Some(0),
    1191            0 :                 generation_pageserver: None,
    1192            0 :                 placement_policy: serde_json::to_string(&PlacementPolicy::Attached(0)).unwrap(),
    1193            0 :                 config: serde_json::to_string(&TenantConfig::default()).unwrap(),
    1194            0 :                 splitting: SplitState::default(),
    1195            0 :                 scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    1196            0 :                     .unwrap(),
    1197            0 :             };
    1198            0 : 
    1199            0 :             match self.persistence.insert_tenant_shards(vec![tsp]).await {
    1200            0 :                 Err(e) => match e {
    1201              :                     DatabaseError::Query(diesel::result::Error::DatabaseError(
    1202              :                         DatabaseErrorKind::UniqueViolation,
    1203              :                         _,
    1204              :                     )) => {
    1205            0 :                         tracing::info!(
    1206            0 :                             "Raced with another request to insert tenant {}",
    1207              :                             attach_req.tenant_shard_id
    1208              :                         )
    1209              :                     }
    1210            0 :                     _ => return Err(e.into()),
    1211              :                 },
    1212              :                 Ok(()) => {
    1213            0 :                     tracing::info!("Inserted shard {} in database", attach_req.tenant_shard_id);
    1214              : 
    1215            0 :                     let mut locked = self.inner.write().unwrap();
    1216            0 :                     locked.tenants.insert(
    1217            0 :                         attach_req.tenant_shard_id,
    1218            0 :                         TenantShard::new(
    1219            0 :                             attach_req.tenant_shard_id,
    1220            0 :                             ShardIdentity::unsharded(),
    1221            0 :                             PlacementPolicy::Attached(0),
    1222            0 :                         ),
    1223            0 :                     );
    1224            0 :                     tracing::info!("Inserted shard {} in memory", attach_req.tenant_shard_id);
    1225              :                 }
    1226              :             }
    1227            0 :         }
    1228              : 
    1229            0 :         let new_generation = if let Some(req_node_id) = attach_req.node_id {
    1230            0 :             let maybe_tenant_conf = {
    1231            0 :                 let locked = self.inner.write().unwrap();
    1232            0 :                 locked
    1233            0 :                     .tenants
    1234            0 :                     .get(&attach_req.tenant_shard_id)
    1235            0 :                     .map(|t| t.config.clone())
    1236            0 :             };
    1237            0 : 
    1238            0 :             match maybe_tenant_conf {
    1239            0 :                 Some(conf) => {
    1240            0 :                     let new_generation = self
    1241            0 :                         .persistence
    1242            0 :                         .increment_generation(attach_req.tenant_shard_id, req_node_id)
    1243            0 :                         .await?;
    1244              : 
    1245              :                     // Persist the placement policy update. This is required
    1246              :                     // when we reattaching a detached tenant.
    1247            0 :                     self.persistence
    1248            0 :                         .update_tenant_shard(
    1249            0 :                             TenantFilter::Shard(attach_req.tenant_shard_id),
    1250            0 :                             Some(PlacementPolicy::Attached(0)),
    1251            0 :                             Some(conf),
    1252            0 :                             None,
    1253            0 :                             None,
    1254            0 :                         )
    1255            0 :                         .await?;
    1256            0 :                     Some(new_generation)
    1257              :                 }
    1258              :                 None => {
    1259            0 :                     anyhow::bail!("Attach hook handling raced with tenant removal")
    1260              :                 }
    1261              :             }
    1262              :         } else {
    1263            0 :             self.persistence.detach(attach_req.tenant_shard_id).await?;
    1264            0 :             None
    1265              :         };
    1266              : 
    1267            0 :         let mut locked = self.inner.write().unwrap();
    1268            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    1269            0 : 
    1270            0 :         let tenant_shard = tenants
    1271            0 :             .get_mut(&attach_req.tenant_shard_id)
    1272            0 :             .expect("Checked for existence above");
    1273              : 
    1274            0 :         if let Some(new_generation) = new_generation {
    1275            0 :             tenant_shard.generation = Some(new_generation);
    1276            0 :             tenant_shard.policy = PlacementPolicy::Attached(0);
    1277            0 :         } else {
    1278              :             // This is a detach notification.  We must update placement policy to avoid re-attaching
    1279              :             // during background scheduling/reconciliation, or during storage controller restart.
    1280            0 :             assert!(attach_req.node_id.is_none());
    1281            0 :             tenant_shard.policy = PlacementPolicy::Detached;
    1282              :         }
    1283              : 
    1284            0 :         if let Some(attaching_pageserver) = attach_req.node_id.as_ref() {
    1285            0 :             tracing::info!(
    1286              :                 tenant_id = %attach_req.tenant_shard_id,
    1287              :                 ps_id = %attaching_pageserver,
    1288              :                 generation = ?tenant_shard.generation,
    1289            0 :                 "issuing",
    1290              :             );
    1291            0 :         } else if let Some(ps_id) = tenant_shard.intent.get_attached() {
    1292            0 :             tracing::info!(
    1293              :                 tenant_id = %attach_req.tenant_shard_id,
    1294              :                 %ps_id,
    1295              :                 generation = ?tenant_shard.generation,
    1296            0 :                 "dropping",
    1297              :             );
    1298              :         } else {
    1299            0 :             tracing::info!(
    1300              :             tenant_id = %attach_req.tenant_shard_id,
    1301            0 :             "no-op: tenant already has no pageserver");
    1302              :         }
    1303            0 :         tenant_shard
    1304            0 :             .intent
    1305            0 :             .set_attached(scheduler, attach_req.node_id);
    1306            0 : 
    1307            0 :         tracing::info!(
    1308            0 :             "attach_hook: tenant {} set generation {:?}, pageserver {}",
    1309            0 :             attach_req.tenant_shard_id,
    1310            0 :             tenant_shard.generation,
    1311            0 :             // TODO: this is an odd number of 0xf's
    1312            0 :             attach_req.node_id.unwrap_or(utils::id::NodeId(0xfffffff))
    1313              :         );
    1314              : 
    1315              :         // Trick the reconciler into not doing anything for this tenant: this helps
    1316              :         // tests that manually configure a tenant on the pagesrever, and then call this
    1317              :         // attach hook: they don't want background reconciliation to modify what they
    1318              :         // did to the pageserver.
    1319              :         #[cfg(feature = "testing")]
    1320              :         {
    1321            0 :             if let Some(node_id) = attach_req.node_id {
    1322            0 :                 tenant_shard.observed.locations = HashMap::from([(
    1323            0 :                     node_id,
    1324            0 :                     ObservedStateLocation {
    1325            0 :                         conf: Some(attached_location_conf(
    1326            0 :                             tenant_shard.generation.unwrap(),
    1327            0 :                             &tenant_shard.shard,
    1328            0 :                             &tenant_shard.config,
    1329            0 :                             false,
    1330            0 :                         )),
    1331            0 :                     },
    1332            0 :                 )]);
    1333            0 :             } else {
    1334            0 :                 tenant_shard.observed.locations.clear();
    1335            0 :             }
    1336              :         }
    1337              : 
    1338            0 :         Ok(AttachHookResponse {
    1339            0 :             gen: attach_req
    1340            0 :                 .node_id
    1341            0 :                 .map(|_| tenant_shard.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap()),
    1342            0 :         })
    1343            0 :     }
    1344              : 
    1345            0 :     pub(crate) fn inspect(&self, inspect_req: InspectRequest) -> InspectResponse {
    1346            0 :         let locked = self.inner.read().unwrap();
    1347            0 : 
    1348            0 :         let tenant_shard = locked.tenants.get(&inspect_req.tenant_shard_id);
    1349            0 : 
    1350            0 :         InspectResponse {
    1351            0 :             attachment: tenant_shard.and_then(|s| {
    1352            0 :                 s.intent
    1353            0 :                     .get_attached()
    1354            0 :                     .map(|ps| (s.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap(), ps))
    1355            0 :             }),
    1356            0 :         }
    1357            0 :     }
    1358              : 
    1359              :     // When the availability state of a node transitions to active, we must do a full reconciliation
    1360              :     // of LocationConfigs on that node.  This is because while a node was offline:
    1361              :     // - we might have proceeded through startup_reconcile without checking for extraneous LocationConfigs on this node
    1362              :     // - aborting a tenant shard split might have left rogue child shards behind on this node.
    1363              :     //
    1364              :     // This function must complete _before_ setting a `Node` to Active: once it is set to Active, other
    1365              :     // Reconcilers might communicate with the node, and these must not overlap with the work we do in
    1366              :     // this function.
    1367              :     //
    1368              :     // The reconciliation logic in here is very similar to what [`Self::startup_reconcile`] does, but
    1369              :     // for written for a single node rather than as a batch job for all nodes.
    1370            0 :     #[tracing::instrument(skip_all, fields(node_id=%node.get_id()))]
    1371              :     async fn node_activate_reconcile(
    1372              :         &self,
    1373              :         mut node: Node,
    1374              :         _lock: &WrappedWriteGuard<NodeOperations>,
    1375              :     ) -> Result<(), ApiError> {
    1376              :         // This Node is a mutable local copy: we will set it active so that we can use its
    1377              :         // API client to reconcile with the node.  The Node in [`Self::nodes`] will get updated
    1378              :         // later.
    1379              :         node.set_availability(NodeAvailability::Active(UtilizationScore::worst()));
    1380              : 
    1381              :         let configs = match node
    1382              :             .with_client_retries(
    1383            0 :                 |client| async move { client.list_location_config().await },
    1384              :                 &self.config.jwt_token,
    1385              :                 1,
    1386              :                 5,
    1387              :                 SHORT_RECONCILE_TIMEOUT,
    1388              :                 &self.cancel,
    1389              :             )
    1390              :             .await
    1391              :         {
    1392              :             None => {
    1393              :                 // We're shutting down (the Node's cancellation token can't have fired, because
    1394              :                 // we're the only scope that has a reference to it, and we didn't fire it).
    1395              :                 return Err(ApiError::ShuttingDown);
    1396              :             }
    1397              :             Some(Err(e)) => {
    1398              :                 // This node didn't succeed listing its locations: it may not proceed to active state
    1399              :                 // as it is apparently unavailable.
    1400              :                 return Err(ApiError::PreconditionFailed(
    1401              :                     format!("Failed to query node location configs, cannot activate ({e})").into(),
    1402              :                 ));
    1403              :             }
    1404              :             Some(Ok(configs)) => configs,
    1405              :         };
    1406              :         tracing::info!("Loaded {} LocationConfigs", configs.tenant_shards.len());
    1407              : 
    1408              :         let mut cleanup = Vec::new();
    1409              :         {
    1410              :             let mut locked = self.inner.write().unwrap();
    1411              : 
    1412              :             for (tenant_shard_id, observed_loc) in configs.tenant_shards {
    1413              :                 let Some(tenant_shard) = locked.tenants.get_mut(&tenant_shard_id) else {
    1414              :                     cleanup.push(tenant_shard_id);
    1415              :                     continue;
    1416              :                 };
    1417              :                 tenant_shard
    1418              :                     .observed
    1419              :                     .locations
    1420              :                     .insert(node.get_id(), ObservedStateLocation { conf: observed_loc });
    1421              :             }
    1422              :         }
    1423              : 
    1424              :         for tenant_shard_id in cleanup {
    1425              :             tracing::info!("Detaching {tenant_shard_id}");
    1426              :             match node
    1427              :                 .with_client_retries(
    1428            0 :                     |client| async move {
    1429            0 :                         let config = LocationConfig {
    1430            0 :                             mode: LocationConfigMode::Detached,
    1431            0 :                             generation: None,
    1432            0 :                             secondary_conf: None,
    1433            0 :                             shard_number: tenant_shard_id.shard_number.0,
    1434            0 :                             shard_count: tenant_shard_id.shard_count.literal(),
    1435            0 :                             shard_stripe_size: 0,
    1436            0 :                             tenant_conf: models::TenantConfig::default(),
    1437            0 :                         };
    1438            0 :                         client
    1439            0 :                             .location_config(tenant_shard_id, config, None, false)
    1440            0 :                             .await
    1441            0 :                     },
    1442              :                     &self.config.jwt_token,
    1443              :                     1,
    1444              :                     5,
    1445              :                     SHORT_RECONCILE_TIMEOUT,
    1446              :                     &self.cancel,
    1447              :                 )
    1448              :                 .await
    1449              :             {
    1450              :                 None => {
    1451              :                     // We're shutting down (the Node's cancellation token can't have fired, because
    1452              :                     // we're the only scope that has a reference to it, and we didn't fire it).
    1453              :                     return Err(ApiError::ShuttingDown);
    1454              :                 }
    1455              :                 Some(Err(e)) => {
    1456              :                     // Do not let the node proceed to Active state if it is not responsive to requests
    1457              :                     // to detach.  This could happen if e.g. a shutdown bug in the pageserver is preventing
    1458              :                     // detach completing: we should not let this node back into the set of nodes considered
    1459              :                     // okay for scheduling.
    1460              :                     return Err(ApiError::Conflict(format!(
    1461              :                         "Node {node} failed to detach {tenant_shard_id}: {e}"
    1462              :                     )));
    1463              :                 }
    1464              :                 Some(Ok(_)) => {}
    1465              :             };
    1466              :         }
    1467              : 
    1468              :         Ok(())
    1469              :     }
    1470              : 
    1471            0 :     pub(crate) async fn re_attach(
    1472            0 :         &self,
    1473            0 :         reattach_req: ReAttachRequest,
    1474            0 :     ) -> Result<ReAttachResponse, ApiError> {
    1475            0 :         if let Some(register_req) = reattach_req.register {
    1476            0 :             self.node_register(register_req).await?;
    1477            0 :         }
    1478              : 
    1479              :         // Ordering: we must persist generation number updates before making them visible in the in-memory state
    1480            0 :         let incremented_generations = self.persistence.re_attach(reattach_req.node_id).await?;
    1481              : 
    1482            0 :         tracing::info!(
    1483              :             node_id=%reattach_req.node_id,
    1484            0 :             "Incremented {} tenant shards' generations",
    1485            0 :             incremented_generations.len()
    1486              :         );
    1487              : 
    1488              :         // Apply the updated generation to our in-memory state, and
    1489              :         // gather discover secondary locations.
    1490            0 :         let mut locked = self.inner.write().unwrap();
    1491            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    1492            0 : 
    1493            0 :         let mut response = ReAttachResponse {
    1494            0 :             tenants: Vec::new(),
    1495            0 :         };
    1496              : 
    1497              :         // TODO: cancel/restart any running reconciliation for this tenant, it might be trying
    1498              :         // to call location_conf API with an old generation.  Wait for cancellation to complete
    1499              :         // before responding to this request.  Requires well implemented CancellationToken logic
    1500              :         // all the way to where we call location_conf.  Even then, there can still be a location_conf
    1501              :         // request in flight over the network: TODO handle that by making location_conf API refuse
    1502              :         // to go backward in generations.
    1503              : 
    1504              :         // Scan through all shards, applying updates for ones where we updated generation
    1505              :         // and identifying shards that intend to have a secondary location on this node.
    1506            0 :         for (tenant_shard_id, shard) in tenants {
    1507            0 :             if let Some(new_gen) = incremented_generations.get(tenant_shard_id) {
    1508            0 :                 let new_gen = *new_gen;
    1509            0 :                 response.tenants.push(ReAttachResponseTenant {
    1510            0 :                     id: *tenant_shard_id,
    1511            0 :                     gen: Some(new_gen.into().unwrap()),
    1512            0 :                     // A tenant is only put into multi or stale modes in the middle of a [`Reconciler::live_migrate`]
    1513            0 :                     // execution.  If a pageserver is restarted during that process, then the reconcile pass will
    1514            0 :                     // fail, and start from scratch, so it doesn't make sense for us to try and preserve
    1515            0 :                     // the stale/multi states at this point.
    1516            0 :                     mode: LocationConfigMode::AttachedSingle,
    1517            0 :                 });
    1518            0 : 
    1519            0 :                 shard.generation = std::cmp::max(shard.generation, Some(new_gen));
    1520            0 :                 if let Some(observed) = shard.observed.locations.get_mut(&reattach_req.node_id) {
    1521              :                     // Why can we update `observed` even though we're not sure our response will be received
    1522              :                     // by the pageserver?  Because the pageserver will not proceed with startup until
    1523              :                     // it has processed response: if it loses it, we'll see another request and increment
    1524              :                     // generation again, avoiding any uncertainty about dirtiness of tenant's state.
    1525            0 :                     if let Some(conf) = observed.conf.as_mut() {
    1526            0 :                         conf.generation = new_gen.into();
    1527            0 :                     }
    1528            0 :                 } else {
    1529            0 :                     // This node has no observed state for the shard: perhaps it was offline
    1530            0 :                     // when the pageserver restarted.  Insert a None, so that the Reconciler
    1531            0 :                     // will be prompted to learn the location's state before it makes changes.
    1532            0 :                     shard
    1533            0 :                         .observed
    1534            0 :                         .locations
    1535            0 :                         .insert(reattach_req.node_id, ObservedStateLocation { conf: None });
    1536            0 :                 }
    1537            0 :             } else if shard.intent.get_secondary().contains(&reattach_req.node_id) {
    1538            0 :                 // Ordering: pageserver will not accept /location_config requests until it has
    1539            0 :                 // finished processing the response from re-attach.  So we can update our in-memory state
    1540            0 :                 // now, and be confident that we are not stamping on the result of some later location config.
    1541            0 :                 // TODO: however, we are not strictly ordered wrt ReconcileResults queue,
    1542            0 :                 // so we might update observed state here, and then get over-written by some racing
    1543            0 :                 // ReconcileResult.  The impact is low however, since we have set state on pageserver something
    1544            0 :                 // that matches intent, so worst case if we race then we end up doing a spurious reconcile.
    1545            0 : 
    1546            0 :                 response.tenants.push(ReAttachResponseTenant {
    1547            0 :                     id: *tenant_shard_id,
    1548            0 :                     gen: None,
    1549            0 :                     mode: LocationConfigMode::Secondary,
    1550            0 :                 });
    1551            0 : 
    1552            0 :                 // We must not update observed, because we have no guarantee that our
    1553            0 :                 // response will be received by the pageserver. This could leave it
    1554            0 :                 // falsely dirty, but the resulting reconcile should be idempotent.
    1555            0 :             }
    1556              :         }
    1557              : 
    1558              :         // We consider a node Active once we have composed a re-attach response, but we
    1559              :         // do not call [`Self::node_activate_reconcile`]: the handling of the re-attach response
    1560              :         // implicitly synchronizes the LocationConfigs on the node.
    1561              :         //
    1562              :         // Setting a node active unblocks any Reconcilers that might write to the location config API,
    1563              :         // but those requests will not be accepted by the node until it has finished processing
    1564              :         // the re-attach response.
    1565            0 :         if let Some(node) = nodes.get(&reattach_req.node_id) {
    1566            0 :             if !node.is_available() {
    1567            0 :                 let mut new_nodes = (**nodes).clone();
    1568            0 :                 if let Some(node) = new_nodes.get_mut(&reattach_req.node_id) {
    1569            0 :                     node.set_availability(NodeAvailability::Active(UtilizationScore::worst()));
    1570            0 :                     scheduler.node_upsert(node);
    1571            0 :                 }
    1572            0 :                 let new_nodes = Arc::new(new_nodes);
    1573            0 :                 *nodes = new_nodes;
    1574            0 :             }
    1575            0 :         }
    1576              : 
    1577            0 :         Ok(response)
    1578            0 :     }
    1579              : 
    1580            0 :     pub(crate) fn validate(&self, validate_req: ValidateRequest) -> ValidateResponse {
    1581            0 :         let locked = self.inner.read().unwrap();
    1582            0 : 
    1583            0 :         let mut response = ValidateResponse {
    1584            0 :             tenants: Vec::new(),
    1585            0 :         };
    1586              : 
    1587            0 :         for req_tenant in validate_req.tenants {
    1588            0 :             if let Some(tenant_shard) = locked.tenants.get(&req_tenant.id) {
    1589            0 :                 let valid = tenant_shard.generation == Some(Generation::new(req_tenant.gen));
    1590            0 :                 tracing::info!(
    1591            0 :                     "handle_validate: {}(gen {}): valid={valid} (latest {:?})",
    1592              :                     req_tenant.id,
    1593              :                     req_tenant.gen,
    1594              :                     tenant_shard.generation
    1595              :                 );
    1596            0 :                 response.tenants.push(ValidateResponseTenant {
    1597            0 :                     id: req_tenant.id,
    1598            0 :                     valid,
    1599            0 :                 });
    1600            0 :             } else {
    1601            0 :                 // After tenant deletion, we may approve any validation.  This avoids
    1602            0 :                 // spurious warnings on the pageserver if it has pending LSN updates
    1603            0 :                 // at the point a deletion happens.
    1604            0 :                 response.tenants.push(ValidateResponseTenant {
    1605            0 :                     id: req_tenant.id,
    1606            0 :                     valid: true,
    1607            0 :                 });
    1608            0 :             }
    1609              :         }
    1610            0 :         response
    1611            0 :     }
    1612              : 
    1613            0 :     pub(crate) async fn tenant_create(
    1614            0 :         &self,
    1615            0 :         create_req: TenantCreateRequest,
    1616            0 :     ) -> Result<TenantCreateResponse, ApiError> {
    1617            0 :         let tenant_id = create_req.new_tenant_id.tenant_id;
    1618              : 
    1619              :         // Exclude any concurrent attempts to create/access the same tenant ID
    1620            0 :         let _tenant_lock = trace_exclusive_lock(
    1621            0 :             &self.tenant_op_locks,
    1622            0 :             create_req.new_tenant_id.tenant_id,
    1623            0 :             TenantOperations::Create,
    1624            0 :         )
    1625            0 :         .await;
    1626            0 :         let (response, waiters) = self.do_tenant_create(create_req).await?;
    1627              : 
    1628            0 :         if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    1629              :             // Avoid deadlock: reconcile may fail while notifying compute, if the cloud control plane refuses to
    1630              :             // accept compute notifications while it is in the process of creating.  Reconciliation will
    1631              :             // be retried in the background.
    1632            0 :             tracing::warn!(%tenant_id, "Reconcile not done yet while creating tenant ({e})");
    1633            0 :         }
    1634            0 :         Ok(response)
    1635            0 :     }
    1636              : 
    1637            0 :     pub(crate) async fn do_tenant_create(
    1638            0 :         &self,
    1639            0 :         create_req: TenantCreateRequest,
    1640            0 :     ) -> Result<(TenantCreateResponse, Vec<ReconcilerWaiter>), ApiError> {
    1641            0 :         let placement_policy = create_req
    1642            0 :             .placement_policy
    1643            0 :             .clone()
    1644            0 :             // As a default, zero secondaries is convenient for tests that don't choose a policy.
    1645            0 :             .unwrap_or(PlacementPolicy::Attached(0));
    1646              : 
    1647              :         // This service expects to handle sharding itself: it is an error to try and directly create
    1648              :         // a particular shard here.
    1649            0 :         let tenant_id = if !create_req.new_tenant_id.is_unsharded() {
    1650            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!(
    1651            0 :                 "Attempted to create a specific shard, this API is for creating the whole tenant"
    1652            0 :             )));
    1653              :         } else {
    1654            0 :             create_req.new_tenant_id.tenant_id
    1655            0 :         };
    1656            0 : 
    1657            0 :         tracing::info!(
    1658            0 :             "Creating tenant {}, shard_count={:?}",
    1659              :             create_req.new_tenant_id,
    1660              :             create_req.shard_parameters.count,
    1661              :         );
    1662              : 
    1663            0 :         let create_ids = (0..create_req.shard_parameters.count.count())
    1664            0 :             .map(|i| TenantShardId {
    1665            0 :                 tenant_id,
    1666            0 :                 shard_number: ShardNumber(i),
    1667            0 :                 shard_count: create_req.shard_parameters.count,
    1668            0 :             })
    1669            0 :             .collect::<Vec<_>>();
    1670              : 
    1671              :         // If the caller specifies a None generation, it means "start from default".  This is different
    1672              :         // to [`Self::tenant_location_config`], where a None generation is used to represent
    1673              :         // an incompletely-onboarded tenant.
    1674            0 :         let initial_generation = if matches!(placement_policy, PlacementPolicy::Secondary) {
    1675            0 :             tracing::info!(
    1676            0 :                 "tenant_create: secondary mode, generation is_some={}",
    1677            0 :                 create_req.generation.is_some()
    1678              :             );
    1679            0 :             create_req.generation.map(Generation::new)
    1680              :         } else {
    1681            0 :             tracing::info!(
    1682            0 :                 "tenant_create: not secondary mode, generation is_some={}",
    1683            0 :                 create_req.generation.is_some()
    1684              :             );
    1685            0 :             Some(
    1686            0 :                 create_req
    1687            0 :                     .generation
    1688            0 :                     .map(Generation::new)
    1689            0 :                     .unwrap_or(INITIAL_GENERATION),
    1690            0 :             )
    1691              :         };
    1692              : 
    1693              :         // Ordering: we persist tenant shards before creating them on the pageserver.  This enables a caller
    1694              :         // to clean up after themselves by issuing a tenant deletion if something goes wrong and we restart
    1695              :         // during the creation, rather than risking leaving orphan objects in S3.
    1696            0 :         let persist_tenant_shards = create_ids
    1697            0 :             .iter()
    1698            0 :             .map(|tenant_shard_id| TenantShardPersistence {
    1699            0 :                 tenant_id: tenant_shard_id.tenant_id.to_string(),
    1700            0 :                 shard_number: tenant_shard_id.shard_number.0 as i32,
    1701            0 :                 shard_count: tenant_shard_id.shard_count.literal() as i32,
    1702            0 :                 shard_stripe_size: create_req.shard_parameters.stripe_size.0 as i32,
    1703            0 :                 generation: initial_generation.map(|g| g.into().unwrap() as i32),
    1704            0 :                 // The pageserver is not known until scheduling happens: we will set this column when
    1705            0 :                 // incrementing the generation the first time we attach to a pageserver.
    1706            0 :                 generation_pageserver: None,
    1707            0 :                 placement_policy: serde_json::to_string(&placement_policy).unwrap(),
    1708            0 :                 config: serde_json::to_string(&create_req.config).unwrap(),
    1709            0 :                 splitting: SplitState::default(),
    1710            0 :                 scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    1711            0 :                     .unwrap(),
    1712            0 :             })
    1713            0 :             .collect();
    1714            0 : 
    1715            0 :         match self
    1716            0 :             .persistence
    1717            0 :             .insert_tenant_shards(persist_tenant_shards)
    1718            0 :             .await
    1719              :         {
    1720            0 :             Ok(_) => {}
    1721              :             Err(DatabaseError::Query(diesel::result::Error::DatabaseError(
    1722              :                 DatabaseErrorKind::UniqueViolation,
    1723              :                 _,
    1724              :             ))) => {
    1725              :                 // Unique key violation: this is probably a retry.  Because the shard count is part of the unique key,
    1726              :                 // if we see a unique key violation it means that the creation request's shard count matches the previous
    1727              :                 // creation's shard count.
    1728            0 :                 tracing::info!("Tenant shards already present in database, proceeding with idempotent creation...");
    1729              :             }
    1730              :             // Any other database error is unexpected and a bug.
    1731            0 :             Err(e) => return Err(ApiError::InternalServerError(anyhow::anyhow!(e))),
    1732              :         };
    1733              : 
    1734            0 :         let mut schedule_context = ScheduleContext::default();
    1735              : 
    1736            0 :         let (waiters, response_shards) = {
    1737            0 :             let mut locked = self.inner.write().unwrap();
    1738            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    1739            0 : 
    1740            0 :             let mut response_shards = Vec::new();
    1741            0 :             let mut schcedule_error = None;
    1742              : 
    1743            0 :             for tenant_shard_id in create_ids {
    1744            0 :                 tracing::info!("Creating shard {tenant_shard_id}...");
    1745              : 
    1746              :                 use std::collections::btree_map::Entry;
    1747            0 :                 match tenants.entry(tenant_shard_id) {
    1748            0 :                     Entry::Occupied(mut entry) => {
    1749            0 :                         tracing::info!(
    1750            0 :                             "Tenant shard {tenant_shard_id} already exists while creating"
    1751              :                         );
    1752              : 
    1753              :                         // TODO: schedule() should take an anti-affinity expression that pushes
    1754              :                         // attached and secondary locations (independently) away frorm those
    1755              :                         // pageservers also holding a shard for this tenant.
    1756              : 
    1757            0 :                         entry
    1758            0 :                             .get_mut()
    1759            0 :                             .schedule(scheduler, &mut schedule_context)
    1760            0 :                             .map_err(|e| {
    1761            0 :                                 ApiError::Conflict(format!(
    1762            0 :                                     "Failed to schedule shard {tenant_shard_id}: {e}"
    1763            0 :                                 ))
    1764            0 :                             })?;
    1765              : 
    1766            0 :                         if let Some(node_id) = entry.get().intent.get_attached() {
    1767            0 :                             let generation = entry
    1768            0 :                                 .get()
    1769            0 :                                 .generation
    1770            0 :                                 .expect("Generation is set when in attached mode");
    1771            0 :                             response_shards.push(TenantCreateResponseShard {
    1772            0 :                                 shard_id: tenant_shard_id,
    1773            0 :                                 node_id: *node_id,
    1774            0 :                                 generation: generation.into().unwrap(),
    1775            0 :                             });
    1776            0 :                         }
    1777              : 
    1778            0 :                         continue;
    1779              :                     }
    1780            0 :                     Entry::Vacant(entry) => {
    1781            0 :                         let state = entry.insert(TenantShard::new(
    1782            0 :                             tenant_shard_id,
    1783            0 :                             ShardIdentity::from_params(
    1784            0 :                                 tenant_shard_id.shard_number,
    1785            0 :                                 &create_req.shard_parameters,
    1786            0 :                             ),
    1787            0 :                             placement_policy.clone(),
    1788            0 :                         ));
    1789            0 : 
    1790            0 :                         state.generation = initial_generation;
    1791            0 :                         state.config = create_req.config.clone();
    1792            0 :                         if let Err(e) = state.schedule(scheduler, &mut schedule_context) {
    1793            0 :                             schcedule_error = Some(e);
    1794            0 :                         }
    1795              : 
    1796              :                         // Only include shards in result if we are attaching: the purpose
    1797              :                         // of the response is to tell the caller where the shards are attached.
    1798            0 :                         if let Some(node_id) = state.intent.get_attached() {
    1799            0 :                             let generation = state
    1800            0 :                                 .generation
    1801            0 :                                 .expect("Generation is set when in attached mode");
    1802            0 :                             response_shards.push(TenantCreateResponseShard {
    1803            0 :                                 shard_id: tenant_shard_id,
    1804            0 :                                 node_id: *node_id,
    1805            0 :                                 generation: generation.into().unwrap(),
    1806            0 :                             });
    1807            0 :                         }
    1808              :                     }
    1809              :                 };
    1810              :             }
    1811              : 
    1812              :             // If we failed to schedule shards, then they are still created in the controller,
    1813              :             // but we return an error to the requester to avoid a silent failure when someone
    1814              :             // tries to e.g. create a tenant whose placement policy requires more nodes than
    1815              :             // are present in the system.  We do this here rather than in the above loop, to
    1816              :             // avoid situations where we only create a subset of shards in the tenant.
    1817            0 :             if let Some(e) = schcedule_error {
    1818            0 :                 return Err(ApiError::Conflict(format!(
    1819            0 :                     "Failed to schedule shard(s): {e}"
    1820            0 :                 )));
    1821            0 :             }
    1822            0 : 
    1823            0 :             let waiters = tenants
    1824            0 :                 .range_mut(TenantShardId::tenant_range(tenant_id))
    1825            0 :                 .filter_map(|(_shard_id, shard)| self.maybe_reconcile_shard(shard, nodes))
    1826            0 :                 .collect::<Vec<_>>();
    1827            0 :             (waiters, response_shards)
    1828            0 :         };
    1829            0 : 
    1830            0 :         Ok((
    1831            0 :             TenantCreateResponse {
    1832            0 :                 shards: response_shards,
    1833            0 :             },
    1834            0 :             waiters,
    1835            0 :         ))
    1836            0 :     }
    1837              : 
    1838              :     /// Helper for functions that reconcile a number of shards, and would like to do a timeout-bounded
    1839              :     /// wait for reconciliation to complete before responding.
    1840            0 :     async fn await_waiters(
    1841            0 :         &self,
    1842            0 :         waiters: Vec<ReconcilerWaiter>,
    1843            0 :         timeout: Duration,
    1844            0 :     ) -> Result<(), ReconcileWaitError> {
    1845            0 :         let deadline = Instant::now().checked_add(timeout).unwrap();
    1846            0 :         for waiter in waiters {
    1847            0 :             let timeout = deadline.duration_since(Instant::now());
    1848            0 :             waiter.wait_timeout(timeout).await?;
    1849              :         }
    1850              : 
    1851            0 :         Ok(())
    1852            0 :     }
    1853              : 
    1854              :     /// Part of [`Self::tenant_location_config`]: dissect an incoming location config request,
    1855              :     /// and transform it into either a tenant creation of a series of shard updates.
    1856              :     ///
    1857              :     /// If the incoming request makes no changes, a [`TenantCreateOrUpdate::Update`] result will
    1858              :     /// still be returned.
    1859            0 :     fn tenant_location_config_prepare(
    1860            0 :         &self,
    1861            0 :         tenant_id: TenantId,
    1862            0 :         req: TenantLocationConfigRequest,
    1863            0 :     ) -> TenantCreateOrUpdate {
    1864            0 :         let mut updates = Vec::new();
    1865            0 :         let mut locked = self.inner.write().unwrap();
    1866            0 :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    1867            0 :         let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    1868              : 
    1869              :         // Use location config mode as an indicator of policy.
    1870            0 :         let placement_policy = match req.config.mode {
    1871            0 :             LocationConfigMode::Detached => PlacementPolicy::Detached,
    1872            0 :             LocationConfigMode::Secondary => PlacementPolicy::Secondary,
    1873              :             LocationConfigMode::AttachedMulti
    1874              :             | LocationConfigMode::AttachedSingle
    1875              :             | LocationConfigMode::AttachedStale => {
    1876            0 :                 if nodes.len() > 1 {
    1877            0 :                     PlacementPolicy::Attached(1)
    1878              :                 } else {
    1879              :                     // Convenience for dev/test: if we just have one pageserver, import
    1880              :                     // tenants into non-HA mode so that scheduling will succeed.
    1881            0 :                     PlacementPolicy::Attached(0)
    1882              :                 }
    1883              :             }
    1884              :         };
    1885              : 
    1886            0 :         let mut create = true;
    1887            0 :         for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    1888              :             // Saw an existing shard: this is not a creation
    1889            0 :             create = false;
    1890              : 
    1891              :             // Shards may have initially been created by a Secondary request, where we
    1892              :             // would have left generation as None.
    1893              :             //
    1894              :             // We only update generation the first time we see an attached-mode request,
    1895              :             // and if there is no existing generation set. The caller is responsible for
    1896              :             // ensuring that no non-storage-controller pageserver ever uses a higher
    1897              :             // generation than they passed in here.
    1898              :             use LocationConfigMode::*;
    1899            0 :             let set_generation = match req.config.mode {
    1900            0 :                 AttachedMulti | AttachedSingle | AttachedStale if shard.generation.is_none() => {
    1901            0 :                     req.config.generation.map(Generation::new)
    1902              :                 }
    1903            0 :                 _ => None,
    1904              :             };
    1905              : 
    1906            0 :             updates.push(ShardUpdate {
    1907            0 :                 tenant_shard_id: *shard_id,
    1908            0 :                 placement_policy: placement_policy.clone(),
    1909            0 :                 tenant_config: req.config.tenant_conf.clone(),
    1910            0 :                 generation: set_generation,
    1911            0 :             });
    1912              :         }
    1913              : 
    1914            0 :         if create {
    1915              :             use LocationConfigMode::*;
    1916            0 :             let generation = match req.config.mode {
    1917            0 :                 AttachedMulti | AttachedSingle | AttachedStale => req.config.generation,
    1918              :                 // If a caller provided a generation in a non-attached request, ignore it
    1919              :                 // and leave our generation as None: this enables a subsequent update to set
    1920              :                 // the generation when setting an attached mode for the first time.
    1921            0 :                 _ => None,
    1922              :             };
    1923              : 
    1924            0 :             TenantCreateOrUpdate::Create(
    1925            0 :                 // Synthesize a creation request
    1926            0 :                 TenantCreateRequest {
    1927            0 :                     new_tenant_id: tenant_shard_id,
    1928            0 :                     generation,
    1929            0 :                     shard_parameters: ShardParameters {
    1930            0 :                         count: tenant_shard_id.shard_count,
    1931            0 :                         // We only import un-sharded or single-sharded tenants, so stripe
    1932            0 :                         // size can be made up arbitrarily here.
    1933            0 :                         stripe_size: ShardParameters::DEFAULT_STRIPE_SIZE,
    1934            0 :                     },
    1935            0 :                     placement_policy: Some(placement_policy),
    1936            0 :                     config: req.config.tenant_conf,
    1937            0 :                 },
    1938            0 :             )
    1939              :         } else {
    1940            0 :             assert!(!updates.is_empty());
    1941            0 :             TenantCreateOrUpdate::Update(updates)
    1942              :         }
    1943            0 :     }
    1944              : 
    1945              :     /// This API is used by the cloud control plane to migrate unsharded tenants that it created
    1946              :     /// directly with pageservers into this service.
    1947              :     ///
    1948              :     /// Cloud control plane MUST NOT continue issuing GENERATION NUMBERS for this tenant once it
    1949              :     /// has attempted to call this API. Failure to oblige to this rule may lead to S3 corruption.
    1950              :     /// Think of the first attempt to call this API as a transfer of absolute authority over the
    1951              :     /// tenant's source of generation numbers.
    1952              :     ///
    1953              :     /// The mode in this request coarse-grained control of tenants:
    1954              :     /// - Call with mode Attached* to upsert the tenant.
    1955              :     /// - Call with mode Secondary to either onboard a tenant without attaching it, or
    1956              :     ///   to set an existing tenant to PolicyMode::Secondary
    1957              :     /// - Call with mode Detached to switch to PolicyMode::Detached
    1958            0 :     pub(crate) async fn tenant_location_config(
    1959            0 :         &self,
    1960            0 :         tenant_shard_id: TenantShardId,
    1961            0 :         req: TenantLocationConfigRequest,
    1962            0 :     ) -> Result<TenantLocationConfigResponse, ApiError> {
    1963              :         // We require an exclusive lock, because we are updating both persistent and in-memory state
    1964            0 :         let _tenant_lock = trace_exclusive_lock(
    1965            0 :             &self.tenant_op_locks,
    1966            0 :             tenant_shard_id.tenant_id,
    1967            0 :             TenantOperations::LocationConfig,
    1968            0 :         )
    1969            0 :         .await;
    1970              : 
    1971            0 :         if !tenant_shard_id.is_unsharded() {
    1972            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!(
    1973            0 :                 "This API is for importing single-sharded or unsharded tenants"
    1974            0 :             )));
    1975            0 :         }
    1976            0 : 
    1977            0 :         // First check if this is a creation or an update
    1978            0 :         let create_or_update = self.tenant_location_config_prepare(tenant_shard_id.tenant_id, req);
    1979            0 : 
    1980            0 :         let mut result = TenantLocationConfigResponse {
    1981            0 :             shards: Vec::new(),
    1982            0 :             stripe_size: None,
    1983            0 :         };
    1984            0 :         let waiters = match create_or_update {
    1985            0 :             TenantCreateOrUpdate::Create(create_req) => {
    1986            0 :                 let (create_resp, waiters) = self.do_tenant_create(create_req).await?;
    1987            0 :                 result.shards = create_resp
    1988            0 :                     .shards
    1989            0 :                     .into_iter()
    1990            0 :                     .map(|s| TenantShardLocation {
    1991            0 :                         node_id: s.node_id,
    1992            0 :                         shard_id: s.shard_id,
    1993            0 :                     })
    1994            0 :                     .collect();
    1995            0 :                 waiters
    1996              :             }
    1997            0 :             TenantCreateOrUpdate::Update(updates) => {
    1998            0 :                 // Persist updates
    1999            0 :                 // Ordering: write to the database before applying changes in-memory, so that
    2000            0 :                 // we will not appear time-travel backwards on a restart.
    2001            0 :                 let mut schedule_context = ScheduleContext::default();
    2002              :                 for ShardUpdate {
    2003            0 :                     tenant_shard_id,
    2004            0 :                     placement_policy,
    2005            0 :                     tenant_config,
    2006            0 :                     generation,
    2007            0 :                 } in &updates
    2008              :                 {
    2009            0 :                     self.persistence
    2010            0 :                         .update_tenant_shard(
    2011            0 :                             TenantFilter::Shard(*tenant_shard_id),
    2012            0 :                             Some(placement_policy.clone()),
    2013            0 :                             Some(tenant_config.clone()),
    2014            0 :                             *generation,
    2015            0 :                             None,
    2016            0 :                         )
    2017            0 :                         .await?;
    2018              :                 }
    2019              : 
    2020              :                 // Apply updates in-memory
    2021            0 :                 let mut waiters = Vec::new();
    2022            0 :                 {
    2023            0 :                     let mut locked = self.inner.write().unwrap();
    2024            0 :                     let (nodes, tenants, scheduler) = locked.parts_mut();
    2025              : 
    2026              :                     for ShardUpdate {
    2027            0 :                         tenant_shard_id,
    2028            0 :                         placement_policy,
    2029            0 :                         tenant_config,
    2030            0 :                         generation: update_generation,
    2031            0 :                     } in updates
    2032              :                     {
    2033            0 :                         let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    2034            0 :                             tracing::warn!("Shard {tenant_shard_id} removed while updating");
    2035            0 :                             continue;
    2036              :                         };
    2037              : 
    2038              :                         // Update stripe size
    2039            0 :                         if result.stripe_size.is_none() && shard.shard.count.count() > 1 {
    2040            0 :                             result.stripe_size = Some(shard.shard.stripe_size);
    2041            0 :                         }
    2042              : 
    2043            0 :                         shard.policy = placement_policy;
    2044            0 :                         shard.config = tenant_config;
    2045            0 :                         if let Some(generation) = update_generation {
    2046            0 :                             shard.generation = Some(generation);
    2047            0 :                         }
    2048              : 
    2049            0 :                         shard.schedule(scheduler, &mut schedule_context)?;
    2050              : 
    2051            0 :                         let maybe_waiter = self.maybe_reconcile_shard(shard, nodes);
    2052            0 :                         if let Some(waiter) = maybe_waiter {
    2053            0 :                             waiters.push(waiter);
    2054            0 :                         }
    2055              : 
    2056            0 :                         if let Some(node_id) = shard.intent.get_attached() {
    2057            0 :                             result.shards.push(TenantShardLocation {
    2058            0 :                                 shard_id: tenant_shard_id,
    2059            0 :                                 node_id: *node_id,
    2060            0 :                             })
    2061            0 :                         }
    2062              :                     }
    2063              :                 }
    2064            0 :                 waiters
    2065              :             }
    2066              :         };
    2067              : 
    2068            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    2069              :             // Do not treat a reconcile error as fatal: we have already applied any requested
    2070              :             // Intent changes, and the reconcile can fail for external reasons like unavailable
    2071              :             // compute notification API.  In these cases, it is important that we do not
    2072              :             // cause the cloud control plane to retry forever on this API.
    2073            0 :             tracing::warn!(
    2074            0 :                 "Failed to reconcile after /location_config: {e}, returning success anyway"
    2075              :             );
    2076            0 :         }
    2077              : 
    2078              :         // Logging the full result is useful because it lets us cross-check what the cloud control
    2079              :         // plane's tenant_shards table should contain.
    2080            0 :         tracing::info!("Complete, returning {result:?}");
    2081              : 
    2082            0 :         Ok(result)
    2083            0 :     }
    2084              : 
    2085            0 :     pub(crate) async fn tenant_config_set(&self, req: TenantConfigRequest) -> Result<(), ApiError> {
    2086              :         // We require an exclusive lock, because we are updating persistent and in-memory state
    2087            0 :         let _tenant_lock = trace_exclusive_lock(
    2088            0 :             &self.tenant_op_locks,
    2089            0 :             req.tenant_id,
    2090            0 :             TenantOperations::ConfigSet,
    2091            0 :         )
    2092            0 :         .await;
    2093              : 
    2094            0 :         let tenant_id = req.tenant_id;
    2095            0 :         let config = req.config;
    2096            0 : 
    2097            0 :         self.persistence
    2098            0 :             .update_tenant_shard(
    2099            0 :                 TenantFilter::Tenant(req.tenant_id),
    2100            0 :                 None,
    2101            0 :                 Some(config.clone()),
    2102            0 :                 None,
    2103            0 :                 None,
    2104            0 :             )
    2105            0 :             .await?;
    2106              : 
    2107            0 :         let waiters = {
    2108            0 :             let mut waiters = Vec::new();
    2109            0 :             let mut locked = self.inner.write().unwrap();
    2110            0 :             let (nodes, tenants, _scheduler) = locked.parts_mut();
    2111            0 :             for (_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    2112            0 :                 shard.config = config.clone();
    2113            0 :                 if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
    2114            0 :                     waiters.push(waiter);
    2115            0 :                 }
    2116              :             }
    2117            0 :             waiters
    2118              :         };
    2119              : 
    2120            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    2121              :             // Treat this as success because we have stored the configuration.  If e.g.
    2122              :             // a node was unavailable at this time, it should not stop us accepting a
    2123              :             // configuration change.
    2124            0 :             tracing::warn!(%tenant_id, "Accepted configuration update but reconciliation failed: {e}");
    2125            0 :         }
    2126              : 
    2127            0 :         Ok(())
    2128            0 :     }
    2129              : 
    2130            0 :     pub(crate) fn tenant_config_get(
    2131            0 :         &self,
    2132            0 :         tenant_id: TenantId,
    2133            0 :     ) -> Result<HashMap<&str, serde_json::Value>, ApiError> {
    2134            0 :         let config = {
    2135            0 :             let locked = self.inner.read().unwrap();
    2136            0 : 
    2137            0 :             match locked
    2138            0 :                 .tenants
    2139            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    2140            0 :                 .next()
    2141              :             {
    2142            0 :                 Some((_tenant_shard_id, shard)) => shard.config.clone(),
    2143              :                 None => {
    2144            0 :                     return Err(ApiError::NotFound(
    2145            0 :                         anyhow::anyhow!("Tenant not found").into(),
    2146            0 :                     ))
    2147              :                 }
    2148              :             }
    2149              :         };
    2150              : 
    2151              :         // Unlike the pageserver, we do not have a set of global defaults: the config is
    2152              :         // entirely per-tenant.  Therefore the distinction between `tenant_specific_overrides`
    2153              :         // and `effective_config` in the response is meaningless, but we retain that syntax
    2154              :         // in order to remain compatible with the pageserver API.
    2155              : 
    2156            0 :         let response = HashMap::from([
    2157              :             (
    2158              :                 "tenant_specific_overrides",
    2159            0 :                 serde_json::to_value(&config)
    2160            0 :                     .context("serializing tenant specific overrides")
    2161            0 :                     .map_err(ApiError::InternalServerError)?,
    2162              :             ),
    2163              :             (
    2164            0 :                 "effective_config",
    2165            0 :                 serde_json::to_value(&config)
    2166            0 :                     .context("serializing effective config")
    2167            0 :                     .map_err(ApiError::InternalServerError)?,
    2168              :             ),
    2169              :         ]);
    2170              : 
    2171            0 :         Ok(response)
    2172            0 :     }
    2173              : 
    2174            0 :     pub(crate) async fn tenant_time_travel_remote_storage(
    2175            0 :         &self,
    2176            0 :         time_travel_req: &TenantTimeTravelRequest,
    2177            0 :         tenant_id: TenantId,
    2178            0 :         timestamp: Cow<'_, str>,
    2179            0 :         done_if_after: Cow<'_, str>,
    2180            0 :     ) -> Result<(), ApiError> {
    2181            0 :         let _tenant_lock = trace_exclusive_lock(
    2182            0 :             &self.tenant_op_locks,
    2183            0 :             tenant_id,
    2184            0 :             TenantOperations::TimeTravelRemoteStorage,
    2185            0 :         )
    2186            0 :         .await;
    2187              : 
    2188            0 :         let node = {
    2189            0 :             let locked = self.inner.read().unwrap();
    2190              :             // Just a sanity check to prevent misuse: the API expects that the tenant is fully
    2191              :             // detached everywhere, and nothing writes to S3 storage. Here, we verify that,
    2192              :             // but only at the start of the process, so it's really just to prevent operator
    2193              :             // mistakes.
    2194            0 :             for (shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
    2195            0 :                 if shard.intent.get_attached().is_some() || !shard.intent.get_secondary().is_empty()
    2196              :                 {
    2197            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    2198            0 :                         "We want tenant to be attached in shard with tenant_shard_id={shard_id}"
    2199            0 :                     )));
    2200            0 :                 }
    2201            0 :                 let maybe_attached = shard
    2202            0 :                     .observed
    2203            0 :                     .locations
    2204            0 :                     .iter()
    2205            0 :                     .filter_map(|(node_id, observed_location)| {
    2206            0 :                         observed_location
    2207            0 :                             .conf
    2208            0 :                             .as_ref()
    2209            0 :                             .map(|loc| (node_id, observed_location, loc.mode))
    2210            0 :                     })
    2211            0 :                     .find(|(_, _, mode)| *mode != LocationConfigMode::Detached);
    2212            0 :                 if let Some((node_id, _observed_location, mode)) = maybe_attached {
    2213            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!("We observed attached={mode:?} tenant in node_id={node_id} shard with tenant_shard_id={shard_id}")));
    2214            0 :                 }
    2215              :             }
    2216            0 :             let scheduler = &locked.scheduler;
    2217              :             // Right now we only perform the operation on a single node without parallelization
    2218              :             // TODO fan out the operation to multiple nodes for better performance
    2219            0 :             let node_id = scheduler.schedule_shard(&[], &ScheduleContext::default())?;
    2220            0 :             let node = locked
    2221            0 :                 .nodes
    2222            0 :                 .get(&node_id)
    2223            0 :                 .expect("Pageservers may not be deleted while lock is active");
    2224            0 :             node.clone()
    2225            0 :         };
    2226            0 : 
    2227            0 :         // The shard count is encoded in the remote storage's URL, so we need to handle all historically used shard counts
    2228            0 :         let mut counts = time_travel_req
    2229            0 :             .shard_counts
    2230            0 :             .iter()
    2231            0 :             .copied()
    2232            0 :             .collect::<HashSet<_>>()
    2233            0 :             .into_iter()
    2234            0 :             .collect::<Vec<_>>();
    2235            0 :         counts.sort_unstable();
    2236              : 
    2237            0 :         for count in counts {
    2238            0 :             let shard_ids = (0..count.count())
    2239            0 :                 .map(|i| TenantShardId {
    2240            0 :                     tenant_id,
    2241            0 :                     shard_number: ShardNumber(i),
    2242            0 :                     shard_count: count,
    2243            0 :                 })
    2244            0 :                 .collect::<Vec<_>>();
    2245            0 :             for tenant_shard_id in shard_ids {
    2246            0 :                 let client = PageserverClient::new(
    2247            0 :                     node.get_id(),
    2248            0 :                     node.base_url(),
    2249            0 :                     self.config.jwt_token.as_deref(),
    2250            0 :                 );
    2251            0 : 
    2252            0 :                 tracing::info!("Doing time travel recovery for shard {tenant_shard_id}",);
    2253              : 
    2254            0 :                 client
    2255            0 :                         .tenant_time_travel_remote_storage(
    2256            0 :                             tenant_shard_id,
    2257            0 :                             &timestamp,
    2258            0 :                             &done_if_after,
    2259            0 :                         )
    2260            0 :                         .await
    2261            0 :                         .map_err(|e| {
    2262            0 :                             ApiError::InternalServerError(anyhow::anyhow!(
    2263            0 :                                 "Error doing time travel recovery for shard {tenant_shard_id} on node {}: {e}",
    2264            0 :                                 node
    2265            0 :                             ))
    2266            0 :                         })?;
    2267              :             }
    2268              :         }
    2269            0 :         Ok(())
    2270            0 :     }
    2271              : 
    2272            0 :     pub(crate) async fn tenant_secondary_download(
    2273            0 :         &self,
    2274            0 :         tenant_id: TenantId,
    2275            0 :         wait: Option<Duration>,
    2276            0 :     ) -> Result<(StatusCode, SecondaryProgress), ApiError> {
    2277            0 :         let _tenant_lock = trace_shared_lock(
    2278            0 :             &self.tenant_op_locks,
    2279            0 :             tenant_id,
    2280            0 :             TenantOperations::SecondaryDownload,
    2281            0 :         )
    2282            0 :         .await;
    2283              : 
    2284              :         // Acquire lock and yield the collection of shard-node tuples which we will send requests onward to
    2285            0 :         let targets = {
    2286            0 :             let locked = self.inner.read().unwrap();
    2287            0 :             let mut targets = Vec::new();
    2288              : 
    2289            0 :             for (tenant_shard_id, shard) in
    2290            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    2291              :             {
    2292            0 :                 for node_id in shard.intent.get_secondary() {
    2293            0 :                     let node = locked
    2294            0 :                         .nodes
    2295            0 :                         .get(node_id)
    2296            0 :                         .expect("Pageservers may not be deleted while referenced");
    2297            0 : 
    2298            0 :                     targets.push((*tenant_shard_id, node.clone()));
    2299            0 :                 }
    2300              :             }
    2301            0 :             targets
    2302            0 :         };
    2303            0 : 
    2304            0 :         // Issue concurrent requests to all shards' locations
    2305            0 :         let mut futs = FuturesUnordered::new();
    2306            0 :         for (tenant_shard_id, node) in targets {
    2307            0 :             let client = PageserverClient::new(
    2308            0 :                 node.get_id(),
    2309            0 :                 node.base_url(),
    2310            0 :                 self.config.jwt_token.as_deref(),
    2311            0 :             );
    2312            0 :             futs.push(async move {
    2313            0 :                 let result = client
    2314            0 :                     .tenant_secondary_download(tenant_shard_id, wait)
    2315            0 :                     .await;
    2316            0 :                 (result, node, tenant_shard_id)
    2317            0 :             })
    2318              :         }
    2319              : 
    2320              :         // Handle any errors returned by pageservers.  This includes cases like this request racing with
    2321              :         // a scheduling operation, such that the tenant shard we're calling doesn't exist on that pageserver any more, as
    2322              :         // well as more general cases like 503s, 500s, or timeouts.
    2323            0 :         let mut aggregate_progress = SecondaryProgress::default();
    2324            0 :         let mut aggregate_status: Option<StatusCode> = None;
    2325            0 :         let mut error: Option<mgmt_api::Error> = None;
    2326            0 :         while let Some((result, node, tenant_shard_id)) = futs.next().await {
    2327            0 :             match result {
    2328            0 :                 Err(e) => {
    2329            0 :                     // Secondary downloads are always advisory: if something fails, we nevertheless report success, so that whoever
    2330            0 :                     // is calling us will proceed with whatever migration they're doing, albeit with a slightly less warm cache
    2331            0 :                     // than they had hoped for.
    2332            0 :                     tracing::warn!("Secondary download error from pageserver {node}: {e}",);
    2333            0 :                     error = Some(e)
    2334              :                 }
    2335            0 :                 Ok((status_code, progress)) => {
    2336            0 :                     tracing::info!(%tenant_shard_id, "Shard status={status_code} progress: {progress:?}");
    2337            0 :                     aggregate_progress.layers_downloaded += progress.layers_downloaded;
    2338            0 :                     aggregate_progress.layers_total += progress.layers_total;
    2339            0 :                     aggregate_progress.bytes_downloaded += progress.bytes_downloaded;
    2340            0 :                     aggregate_progress.bytes_total += progress.bytes_total;
    2341            0 :                     aggregate_progress.heatmap_mtime =
    2342            0 :                         std::cmp::max(aggregate_progress.heatmap_mtime, progress.heatmap_mtime);
    2343            0 :                     aggregate_status = match aggregate_status {
    2344            0 :                         None => Some(status_code),
    2345            0 :                         Some(StatusCode::OK) => Some(status_code),
    2346            0 :                         Some(cur) => {
    2347            0 :                             // Other status codes (e.g. 202) -- do not overwrite.
    2348            0 :                             Some(cur)
    2349              :                         }
    2350              :                     };
    2351              :                 }
    2352              :             }
    2353              :         }
    2354              : 
    2355              :         // If any of the shards return 202, indicate our result as 202.
    2356            0 :         match aggregate_status {
    2357              :             None => {
    2358            0 :                 match error {
    2359            0 :                     Some(e) => {
    2360            0 :                         // No successes, and an error: surface it
    2361            0 :                         Err(ApiError::Conflict(format!("Error from pageserver: {e}")))
    2362              :                     }
    2363              :                     None => {
    2364              :                         // No shards found
    2365            0 :                         Err(ApiError::NotFound(
    2366            0 :                             anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    2367            0 :                         ))
    2368              :                     }
    2369              :                 }
    2370              :             }
    2371            0 :             Some(aggregate_status) => Ok((aggregate_status, aggregate_progress)),
    2372              :         }
    2373            0 :     }
    2374              : 
    2375            0 :     pub(crate) async fn tenant_delete(&self, tenant_id: TenantId) -> Result<StatusCode, ApiError> {
    2376            0 :         let _tenant_lock =
    2377            0 :             trace_exclusive_lock(&self.tenant_op_locks, tenant_id, TenantOperations::Delete).await;
    2378              : 
    2379            0 :         self.ensure_attached_wait(tenant_id).await?;
    2380              : 
    2381              :         // TODO: refactor into helper
    2382            0 :         let targets = {
    2383            0 :             let locked = self.inner.read().unwrap();
    2384            0 :             let mut targets = Vec::new();
    2385              : 
    2386            0 :             for (tenant_shard_id, shard) in
    2387            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    2388            0 :             {
    2389            0 :                 let node_id = shard.intent.get_attached().ok_or_else(|| {
    2390            0 :                     ApiError::InternalServerError(anyhow::anyhow!("Shard not scheduled"))
    2391            0 :                 })?;
    2392            0 :                 let node = locked
    2393            0 :                     .nodes
    2394            0 :                     .get(&node_id)
    2395            0 :                     .expect("Pageservers may not be deleted while referenced");
    2396            0 : 
    2397            0 :                 targets.push((*tenant_shard_id, node.clone()));
    2398              :             }
    2399            0 :             targets
    2400            0 :         };
    2401            0 : 
    2402            0 :         // Phase 1: delete on the pageservers
    2403            0 :         let mut any_pending = false;
    2404            0 :         for (tenant_shard_id, node) in targets {
    2405            0 :             let client = PageserverClient::new(
    2406            0 :                 node.get_id(),
    2407            0 :                 node.base_url(),
    2408            0 :                 self.config.jwt_token.as_deref(),
    2409            0 :             );
    2410              :             // TODO: this, like many other places, requires proper retry handling for 503, timeout: those should not
    2411              :             // surface immediately as an error to our caller.
    2412            0 :             let status = client.tenant_delete(tenant_shard_id).await.map_err(|e| {
    2413            0 :                 ApiError::InternalServerError(anyhow::anyhow!(
    2414            0 :                     "Error deleting shard {tenant_shard_id} on node {node}: {e}",
    2415            0 :                 ))
    2416            0 :             })?;
    2417            0 :             tracing::info!(
    2418            0 :                 "Shard {tenant_shard_id} on node {node}, delete returned {}",
    2419              :                 status
    2420              :             );
    2421            0 :             if status == StatusCode::ACCEPTED {
    2422            0 :                 any_pending = true;
    2423            0 :             }
    2424              :         }
    2425              : 
    2426            0 :         if any_pending {
    2427              :             // Caller should call us again later.  When we eventually see 404s from
    2428              :             // all the shards, we may proceed to delete our records of the tenant.
    2429            0 :             tracing::info!(
    2430            0 :                 "Tenant {} has some shards pending deletion, returning 202",
    2431              :                 tenant_id
    2432              :             );
    2433            0 :             return Ok(StatusCode::ACCEPTED);
    2434            0 :         }
    2435            0 : 
    2436            0 :         // Fall through: deletion of the tenant on pageservers is complete, we may proceed to drop
    2437            0 :         // our in-memory state and database state.
    2438            0 : 
    2439            0 :         // Ordering: we delete persistent state first: if we then
    2440            0 :         // crash, we will drop the in-memory state.
    2441            0 : 
    2442            0 :         // Drop persistent state.
    2443            0 :         self.persistence.delete_tenant(tenant_id).await?;
    2444              : 
    2445              :         // Drop in-memory state
    2446              :         {
    2447            0 :             let mut locked = self.inner.write().unwrap();
    2448            0 :             let (_nodes, tenants, scheduler) = locked.parts_mut();
    2449              : 
    2450              :             // Dereference Scheduler from shards before dropping them
    2451            0 :             for (_tenant_shard_id, shard) in
    2452            0 :                 tenants.range_mut(TenantShardId::tenant_range(tenant_id))
    2453            0 :             {
    2454            0 :                 shard.intent.clear(scheduler);
    2455            0 :             }
    2456              : 
    2457            0 :             tenants.retain(|tenant_shard_id, _shard| tenant_shard_id.tenant_id != tenant_id);
    2458            0 :             tracing::info!(
    2459            0 :                 "Deleted tenant {tenant_id}, now have {} tenants",
    2460            0 :                 locked.tenants.len()
    2461              :             );
    2462              :         };
    2463              : 
    2464              :         // Success is represented as 404, to imitate the existing pageserver deletion API
    2465            0 :         Ok(StatusCode::NOT_FOUND)
    2466            0 :     }
    2467              : 
    2468              :     /// Naming: this configures the storage controller's policies for a tenant, whereas [`Self::tenant_config_set`] is "set the TenantConfig"
    2469              :     /// for a tenant.  The TenantConfig is passed through to pageservers, whereas this function modifies
    2470              :     /// the tenant's policies (configuration) within the storage controller
    2471            0 :     pub(crate) async fn tenant_update_policy(
    2472            0 :         &self,
    2473            0 :         tenant_id: TenantId,
    2474            0 :         req: TenantPolicyRequest,
    2475            0 :     ) -> Result<(), ApiError> {
    2476              :         // We require an exclusive lock, because we are updating persistent and in-memory state
    2477            0 :         let _tenant_lock = trace_exclusive_lock(
    2478            0 :             &self.tenant_op_locks,
    2479            0 :             tenant_id,
    2480            0 :             TenantOperations::UpdatePolicy,
    2481            0 :         )
    2482            0 :         .await;
    2483              : 
    2484            0 :         failpoint_support::sleep_millis_async!("tenant-update-policy-exclusive-lock");
    2485              : 
    2486              :         let TenantPolicyRequest {
    2487            0 :             placement,
    2488            0 :             scheduling,
    2489            0 :         } = req;
    2490            0 : 
    2491            0 :         self.persistence
    2492            0 :             .update_tenant_shard(
    2493            0 :                 TenantFilter::Tenant(tenant_id),
    2494            0 :                 placement.clone(),
    2495            0 :                 None,
    2496            0 :                 None,
    2497            0 :                 scheduling,
    2498            0 :             )
    2499            0 :             .await?;
    2500              : 
    2501            0 :         let mut schedule_context = ScheduleContext::default();
    2502            0 :         let mut locked = self.inner.write().unwrap();
    2503            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    2504            0 :         for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    2505            0 :             if let Some(placement) = &placement {
    2506            0 :                 shard.policy = placement.clone();
    2507            0 : 
    2508            0 :                 tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
    2509            0 :                                "Updated placement policy to {placement:?}");
    2510            0 :             }
    2511              : 
    2512            0 :             if let Some(scheduling) = &scheduling {
    2513            0 :                 shard.set_scheduling_policy(*scheduling);
    2514            0 : 
    2515            0 :                 tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
    2516            0 :                                "Updated scheduling policy to {scheduling:?}");
    2517            0 :             }
    2518              : 
    2519              :             // In case scheduling is being switched back on, try it now.
    2520            0 :             shard.schedule(scheduler, &mut schedule_context).ok();
    2521            0 :             self.maybe_reconcile_shard(shard, nodes);
    2522              :         }
    2523              : 
    2524            0 :         Ok(())
    2525            0 :     }
    2526              : 
    2527            0 :     pub(crate) async fn tenant_timeline_create(
    2528            0 :         &self,
    2529            0 :         tenant_id: TenantId,
    2530            0 :         mut create_req: TimelineCreateRequest,
    2531            0 :     ) -> Result<TimelineInfo, ApiError> {
    2532            0 :         tracing::info!(
    2533            0 :             "Creating timeline {}/{}",
    2534              :             tenant_id,
    2535              :             create_req.new_timeline_id,
    2536              :         );
    2537              : 
    2538            0 :         let _tenant_lock = trace_shared_lock(
    2539            0 :             &self.tenant_op_locks,
    2540            0 :             tenant_id,
    2541            0 :             TenantOperations::TimelineCreate,
    2542            0 :         )
    2543            0 :         .await;
    2544              : 
    2545            0 :         self.ensure_attached_wait(tenant_id).await?;
    2546              : 
    2547            0 :         let mut targets = {
    2548            0 :             let locked = self.inner.read().unwrap();
    2549            0 :             let mut targets = Vec::new();
    2550              : 
    2551            0 :             for (tenant_shard_id, shard) in
    2552            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    2553            0 :             {
    2554            0 :                 let node_id = shard.intent.get_attached().ok_or_else(|| {
    2555            0 :                     ApiError::InternalServerError(anyhow::anyhow!("Shard not scheduled"))
    2556            0 :                 })?;
    2557            0 :                 let node = locked
    2558            0 :                     .nodes
    2559            0 :                     .get(&node_id)
    2560            0 :                     .expect("Pageservers may not be deleted while referenced");
    2561            0 : 
    2562            0 :                 targets.push((*tenant_shard_id, node.clone()));
    2563              :             }
    2564            0 :             targets
    2565            0 :         };
    2566            0 : 
    2567            0 :         if targets.is_empty() {
    2568            0 :             return Err(ApiError::NotFound(
    2569            0 :                 anyhow::anyhow!("Tenant not found").into(),
    2570            0 :             ));
    2571            0 :         };
    2572            0 :         let shard_zero = targets.remove(0);
    2573              : 
    2574            0 :         async fn create_one(
    2575            0 :             tenant_shard_id: TenantShardId,
    2576            0 :             node: Node,
    2577            0 :             jwt: Option<String>,
    2578            0 :             create_req: TimelineCreateRequest,
    2579            0 :         ) -> Result<TimelineInfo, ApiError> {
    2580            0 :             tracing::info!(
    2581            0 :                 "Creating timeline on shard {}/{}, attached to node {node}",
    2582              :                 tenant_shard_id,
    2583              :                 create_req.new_timeline_id,
    2584              :             );
    2585            0 :             let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
    2586            0 : 
    2587            0 :             client
    2588            0 :                 .timeline_create(tenant_shard_id, &create_req)
    2589            0 :                 .await
    2590            0 :                 .map_err(|e| passthrough_api_error(&node, e))
    2591            0 :         }
    2592              : 
    2593              :         // Because the caller might not provide an explicit LSN, we must do the creation first on a single shard, and then
    2594              :         // use whatever LSN that shard picked when creating on subsequent shards.  We arbitrarily use shard zero as the shard
    2595              :         // that will get the first creation request, and propagate the LSN to all the >0 shards.
    2596            0 :         let timeline_info = create_one(
    2597            0 :             shard_zero.0,
    2598            0 :             shard_zero.1,
    2599            0 :             self.config.jwt_token.clone(),
    2600            0 :             create_req.clone(),
    2601            0 :         )
    2602            0 :         .await?;
    2603              : 
    2604              :         // Propagate the LSN that shard zero picked, if caller didn't provide one
    2605            0 :         if create_req.ancestor_timeline_id.is_some() && create_req.ancestor_start_lsn.is_none() {
    2606            0 :             create_req.ancestor_start_lsn = timeline_info.ancestor_lsn;
    2607            0 :         }
    2608              : 
    2609              :         // Create timeline on remaining shards with number >0
    2610            0 :         if !targets.is_empty() {
    2611              :             // If we had multiple shards, issue requests for the remainder now.
    2612            0 :             let jwt = self.config.jwt_token.clone();
    2613            0 :             self.tenant_for_shards(targets, |tenant_shard_id: TenantShardId, node: Node| {
    2614            0 :                 let create_req = create_req.clone();
    2615            0 :                 Box::pin(create_one(tenant_shard_id, node, jwt.clone(), create_req))
    2616            0 :             })
    2617            0 :             .await?;
    2618            0 :         }
    2619              : 
    2620            0 :         Ok(timeline_info)
    2621            0 :     }
    2622              : 
    2623              :     /// Helper for concurrently calling a pageserver API on a number of shards, such as timeline creation.
    2624              :     ///
    2625              :     /// On success, the returned vector contains exactly the same number of elements as the input `locations`.
    2626            0 :     async fn tenant_for_shards<F, R>(
    2627            0 :         &self,
    2628            0 :         locations: Vec<(TenantShardId, Node)>,
    2629            0 :         mut req_fn: F,
    2630            0 :     ) -> Result<Vec<R>, ApiError>
    2631            0 :     where
    2632            0 :         F: FnMut(
    2633            0 :             TenantShardId,
    2634            0 :             Node,
    2635            0 :         )
    2636            0 :             -> std::pin::Pin<Box<dyn futures::Future<Output = Result<R, ApiError>> + Send>>,
    2637            0 :     {
    2638            0 :         let mut futs = FuturesUnordered::new();
    2639            0 :         let mut results = Vec::with_capacity(locations.len());
    2640              : 
    2641            0 :         for (tenant_shard_id, node) in locations {
    2642            0 :             futs.push(req_fn(tenant_shard_id, node));
    2643            0 :         }
    2644              : 
    2645            0 :         while let Some(r) = futs.next().await {
    2646            0 :             results.push(r?);
    2647              :         }
    2648              : 
    2649            0 :         Ok(results)
    2650            0 :     }
    2651              : 
    2652              :     /// Concurrently invoke a pageserver API call on many shards at once
    2653            0 :     pub(crate) async fn tenant_for_shards_api<T, O, F>(
    2654            0 :         &self,
    2655            0 :         locations: Vec<(TenantShardId, Node)>,
    2656            0 :         op: O,
    2657            0 :         warn_threshold: u32,
    2658            0 :         max_retries: u32,
    2659            0 :         timeout: Duration,
    2660            0 :         cancel: &CancellationToken,
    2661            0 :     ) -> Vec<mgmt_api::Result<T>>
    2662            0 :     where
    2663            0 :         O: Fn(TenantShardId, PageserverClient) -> F + Copy,
    2664            0 :         F: std::future::Future<Output = mgmt_api::Result<T>>,
    2665            0 :     {
    2666            0 :         let mut futs = FuturesUnordered::new();
    2667            0 :         let mut results = Vec::with_capacity(locations.len());
    2668              : 
    2669            0 :         for (tenant_shard_id, node) in locations {
    2670            0 :             futs.push(async move {
    2671            0 :                 node.with_client_retries(
    2672            0 :                     |client| op(tenant_shard_id, client),
    2673            0 :                     &self.config.jwt_token,
    2674            0 :                     warn_threshold,
    2675            0 :                     max_retries,
    2676            0 :                     timeout,
    2677            0 :                     cancel,
    2678            0 :                 )
    2679            0 :                 .await
    2680            0 :             });
    2681            0 :         }
    2682              : 
    2683            0 :         while let Some(r) = futs.next().await {
    2684            0 :             let r = r.unwrap_or(Err(mgmt_api::Error::Cancelled));
    2685            0 :             results.push(r);
    2686            0 :         }
    2687              : 
    2688            0 :         results
    2689            0 :     }
    2690              : 
    2691            0 :     pub(crate) async fn tenant_timeline_delete(
    2692            0 :         &self,
    2693            0 :         tenant_id: TenantId,
    2694            0 :         timeline_id: TimelineId,
    2695            0 :     ) -> Result<StatusCode, ApiError> {
    2696            0 :         tracing::info!("Deleting timeline {}/{}", tenant_id, timeline_id,);
    2697            0 :         let _tenant_lock = trace_shared_lock(
    2698            0 :             &self.tenant_op_locks,
    2699            0 :             tenant_id,
    2700            0 :             TenantOperations::TimelineDelete,
    2701            0 :         )
    2702            0 :         .await;
    2703              : 
    2704            0 :         self.ensure_attached_wait(tenant_id).await?;
    2705              : 
    2706            0 :         let mut targets = {
    2707            0 :             let locked = self.inner.read().unwrap();
    2708            0 :             let mut targets = Vec::new();
    2709              : 
    2710            0 :             for (tenant_shard_id, shard) in
    2711            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    2712            0 :             {
    2713            0 :                 let node_id = shard.intent.get_attached().ok_or_else(|| {
    2714            0 :                     ApiError::InternalServerError(anyhow::anyhow!("Shard not scheduled"))
    2715            0 :                 })?;
    2716            0 :                 let node = locked
    2717            0 :                     .nodes
    2718            0 :                     .get(&node_id)
    2719            0 :                     .expect("Pageservers may not be deleted while referenced");
    2720            0 : 
    2721            0 :                 targets.push((*tenant_shard_id, node.clone()));
    2722              :             }
    2723            0 :             targets
    2724            0 :         };
    2725            0 : 
    2726            0 :         if targets.is_empty() {
    2727            0 :             return Err(ApiError::NotFound(
    2728            0 :                 anyhow::anyhow!("Tenant not found").into(),
    2729            0 :             ));
    2730            0 :         }
    2731            0 :         let shard_zero = targets.remove(0);
    2732              : 
    2733            0 :         async fn delete_one(
    2734            0 :             tenant_shard_id: TenantShardId,
    2735            0 :             timeline_id: TimelineId,
    2736            0 :             node: Node,
    2737            0 :             jwt: Option<String>,
    2738            0 :         ) -> Result<StatusCode, ApiError> {
    2739            0 :             tracing::info!(
    2740            0 :                 "Deleting timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
    2741              :             );
    2742              : 
    2743            0 :             let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
    2744            0 :             client
    2745            0 :                 .timeline_delete(tenant_shard_id, timeline_id)
    2746            0 :                 .await
    2747            0 :                 .map_err(|e| {
    2748            0 :                     ApiError::InternalServerError(anyhow::anyhow!(
    2749            0 :                     "Error deleting timeline {timeline_id} on {tenant_shard_id} on node {node}: {e}",
    2750            0 :                 ))
    2751            0 :                 })
    2752            0 :         }
    2753              : 
    2754            0 :         let statuses = self
    2755            0 :             .tenant_for_shards(targets, |tenant_shard_id: TenantShardId, node: Node| {
    2756            0 :                 Box::pin(delete_one(
    2757            0 :                     tenant_shard_id,
    2758            0 :                     timeline_id,
    2759            0 :                     node,
    2760            0 :                     self.config.jwt_token.clone(),
    2761            0 :                 ))
    2762            0 :             })
    2763            0 :             .await?;
    2764              : 
    2765              :         // If any shards >0 haven't finished deletion yet, don't start deletion on shard zero
    2766            0 :         if statuses.iter().any(|s| s != &StatusCode::NOT_FOUND) {
    2767            0 :             return Ok(StatusCode::ACCEPTED);
    2768            0 :         }
    2769              : 
    2770              :         // Delete shard zero last: this is not strictly necessary, but since a caller's GET on a timeline will be routed
    2771              :         // to shard zero, it gives a more obvious behavior that a GET returns 404 once the deletion is done.
    2772            0 :         let shard_zero_status = delete_one(
    2773            0 :             shard_zero.0,
    2774            0 :             timeline_id,
    2775            0 :             shard_zero.1,
    2776            0 :             self.config.jwt_token.clone(),
    2777            0 :         )
    2778            0 :         .await?;
    2779              : 
    2780            0 :         Ok(shard_zero_status)
    2781            0 :     }
    2782              : 
    2783              :     /// When you need to send an HTTP request to the pageserver that holds shard0 of a tenant, this
    2784              :     /// function looks up and returns node. If the tenant isn't found, returns Err(ApiError::NotFound)
    2785            0 :     pub(crate) fn tenant_shard0_node(
    2786            0 :         &self,
    2787            0 :         tenant_id: TenantId,
    2788            0 :     ) -> Result<(Node, TenantShardId), ApiError> {
    2789            0 :         let locked = self.inner.read().unwrap();
    2790            0 :         let Some((tenant_shard_id, shard)) = locked
    2791            0 :             .tenants
    2792            0 :             .range(TenantShardId::tenant_range(tenant_id))
    2793            0 :             .next()
    2794              :         else {
    2795            0 :             return Err(ApiError::NotFound(
    2796            0 :                 anyhow::anyhow!("Tenant {tenant_id} not found").into(),
    2797            0 :             ));
    2798              :         };
    2799              : 
    2800              :         // TODO: should use the ID last published to compute_hook, rather than the intent: the intent might
    2801              :         // point to somewhere we haven't attached yet.
    2802            0 :         let Some(node_id) = shard.intent.get_attached() else {
    2803            0 :             tracing::warn!(
    2804            0 :                 tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
    2805            0 :                 "Shard not scheduled (policy {:?}), cannot generate pass-through URL",
    2806              :                 shard.policy
    2807              :             );
    2808            0 :             return Err(ApiError::Conflict(
    2809            0 :                 "Cannot call timeline API on non-attached tenant".to_string(),
    2810            0 :             ));
    2811              :         };
    2812              : 
    2813            0 :         let Some(node) = locked.nodes.get(node_id) else {
    2814              :             // This should never happen
    2815            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    2816            0 :                 "Shard refers to nonexistent node"
    2817            0 :             )));
    2818              :         };
    2819              : 
    2820            0 :         Ok((node.clone(), *tenant_shard_id))
    2821            0 :     }
    2822              : 
    2823            0 :     pub(crate) fn tenant_locate(
    2824            0 :         &self,
    2825            0 :         tenant_id: TenantId,
    2826            0 :     ) -> Result<TenantLocateResponse, ApiError> {
    2827            0 :         let locked = self.inner.read().unwrap();
    2828            0 :         tracing::info!("Locating shards for tenant {tenant_id}");
    2829              : 
    2830            0 :         let mut result = Vec::new();
    2831            0 :         let mut shard_params: Option<ShardParameters> = None;
    2832              : 
    2833            0 :         for (tenant_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    2834              :         {
    2835            0 :             let node_id =
    2836            0 :                 shard
    2837            0 :                     .intent
    2838            0 :                     .get_attached()
    2839            0 :                     .ok_or(ApiError::BadRequest(anyhow::anyhow!(
    2840            0 :                         "Cannot locate a tenant that is not attached"
    2841            0 :                     )))?;
    2842              : 
    2843            0 :             let node = locked
    2844            0 :                 .nodes
    2845            0 :                 .get(&node_id)
    2846            0 :                 .expect("Pageservers may not be deleted while referenced");
    2847            0 : 
    2848            0 :             result.push(node.shard_location(*tenant_shard_id));
    2849            0 : 
    2850            0 :             match &shard_params {
    2851            0 :                 None => {
    2852            0 :                     shard_params = Some(ShardParameters {
    2853            0 :                         stripe_size: shard.shard.stripe_size,
    2854            0 :                         count: shard.shard.count,
    2855            0 :                     });
    2856            0 :                 }
    2857            0 :                 Some(params) => {
    2858            0 :                     if params.stripe_size != shard.shard.stripe_size {
    2859              :                         // This should never happen.  We enforce at runtime because it's simpler than
    2860              :                         // adding an extra per-tenant data structure to store the things that should be the same
    2861            0 :                         return Err(ApiError::InternalServerError(anyhow::anyhow!(
    2862            0 :                             "Inconsistent shard stripe size parameters!"
    2863            0 :                         )));
    2864            0 :                     }
    2865              :                 }
    2866              :             }
    2867              :         }
    2868              : 
    2869            0 :         if result.is_empty() {
    2870            0 :             return Err(ApiError::NotFound(
    2871            0 :                 anyhow::anyhow!("No shards for this tenant ID found").into(),
    2872            0 :             ));
    2873            0 :         }
    2874            0 :         let shard_params = shard_params.expect("result is non-empty, therefore this is set");
    2875            0 :         tracing::info!(
    2876            0 :             "Located tenant {} with params {:?} on shards {}",
    2877            0 :             tenant_id,
    2878            0 :             shard_params,
    2879            0 :             result
    2880            0 :                 .iter()
    2881            0 :                 .map(|s| format!("{:?}", s))
    2882            0 :                 .collect::<Vec<_>>()
    2883            0 :                 .join(",")
    2884              :         );
    2885              : 
    2886            0 :         Ok(TenantLocateResponse {
    2887            0 :             shards: result,
    2888            0 :             shard_params,
    2889            0 :         })
    2890            0 :     }
    2891              : 
    2892              :     /// Returns None if the input iterator of shards does not include a shard with number=0
    2893            0 :     fn tenant_describe_impl<'a>(
    2894            0 :         &self,
    2895            0 :         shards: impl Iterator<Item = &'a TenantShard>,
    2896            0 :     ) -> Option<TenantDescribeResponse> {
    2897            0 :         let mut shard_zero = None;
    2898            0 :         let mut describe_shards = Vec::new();
    2899              : 
    2900            0 :         for shard in shards {
    2901            0 :             if shard.tenant_shard_id.is_shard_zero() {
    2902            0 :                 shard_zero = Some(shard);
    2903            0 :             }
    2904              : 
    2905            0 :             describe_shards.push(TenantDescribeResponseShard {
    2906            0 :                 tenant_shard_id: shard.tenant_shard_id,
    2907            0 :                 node_attached: *shard.intent.get_attached(),
    2908            0 :                 node_secondary: shard.intent.get_secondary().to_vec(),
    2909            0 :                 last_error: shard
    2910            0 :                     .last_error
    2911            0 :                     .lock()
    2912            0 :                     .unwrap()
    2913            0 :                     .as_ref()
    2914            0 :                     .map(|e| format!("{e}"))
    2915            0 :                     .unwrap_or("".to_string())
    2916            0 :                     .clone(),
    2917            0 :                 is_reconciling: shard.reconciler.is_some(),
    2918            0 :                 is_pending_compute_notification: shard.pending_compute_notification,
    2919            0 :                 is_splitting: matches!(shard.splitting, SplitState::Splitting),
    2920            0 :                 scheduling_policy: *shard.get_scheduling_policy(),
    2921              :             })
    2922              :         }
    2923              : 
    2924            0 :         let shard_zero = shard_zero?;
    2925              : 
    2926            0 :         Some(TenantDescribeResponse {
    2927            0 :             tenant_id: shard_zero.tenant_shard_id.tenant_id,
    2928            0 :             shards: describe_shards,
    2929            0 :             stripe_size: shard_zero.shard.stripe_size,
    2930            0 :             policy: shard_zero.policy.clone(),
    2931            0 :             config: shard_zero.config.clone(),
    2932            0 :         })
    2933            0 :     }
    2934              : 
    2935            0 :     pub(crate) fn tenant_describe(
    2936            0 :         &self,
    2937            0 :         tenant_id: TenantId,
    2938            0 :     ) -> Result<TenantDescribeResponse, ApiError> {
    2939            0 :         let locked = self.inner.read().unwrap();
    2940            0 : 
    2941            0 :         self.tenant_describe_impl(
    2942            0 :             locked
    2943            0 :                 .tenants
    2944            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    2945            0 :                 .map(|(_k, v)| v),
    2946            0 :         )
    2947            0 :         .ok_or_else(|| ApiError::NotFound(anyhow::anyhow!("Tenant {tenant_id} not found").into()))
    2948            0 :     }
    2949              : 
    2950            0 :     pub(crate) fn tenant_list(&self) -> Vec<TenantDescribeResponse> {
    2951            0 :         let locked = self.inner.read().unwrap();
    2952            0 : 
    2953            0 :         let mut result = Vec::new();
    2954            0 :         for (_tenant_id, tenant_shards) in
    2955            0 :             &locked.tenants.iter().group_by(|(id, _shard)| id.tenant_id)
    2956            0 :         {
    2957            0 :             result.push(
    2958            0 :                 self.tenant_describe_impl(tenant_shards.map(|(_k, v)| v))
    2959            0 :                     .expect("Groups are always non-empty"),
    2960            0 :             );
    2961            0 :         }
    2962              : 
    2963            0 :         result
    2964            0 :     }
    2965              : 
    2966            0 :     #[instrument(skip_all, fields(tenant_id=%op.tenant_id))]
    2967              :     async fn abort_tenant_shard_split(
    2968              :         &self,
    2969              :         op: &TenantShardSplitAbort,
    2970              :     ) -> Result<(), TenantShardSplitAbortError> {
    2971              :         // Cleaning up a split:
    2972              :         // - Parent shards are not destroyed during a split, just detached.
    2973              :         // - Failed pageserver split API calls can leave the remote node with just the parent attached,
    2974              :         //   just the children attached, or both.
    2975              :         //
    2976              :         // Therefore our work to do is to:
    2977              :         // 1. Clean up storage controller's internal state to just refer to parents, no children
    2978              :         // 2. Call out to pageservers to ensure that children are detached
    2979              :         // 3. Call out to pageservers to ensure that parents are attached.
    2980              :         //
    2981              :         // Crash safety:
    2982              :         // - If the storage controller stops running during this cleanup *after* clearing the splitting state
    2983              :         //   from our database, then [`Self::startup_reconcile`] will regard child attachments as garbage
    2984              :         //   and detach them.
    2985              :         // - TODO: If the storage controller stops running during this cleanup *before* clearing the splitting state
    2986              :         //   from our database, then we will re-enter this cleanup routine on startup.
    2987              : 
    2988              :         let TenantShardSplitAbort {
    2989              :             tenant_id,
    2990              :             new_shard_count,
    2991              :             new_stripe_size,
    2992              :             ..
    2993              :         } = op;
    2994              : 
    2995              :         // First abort persistent state, if any exists.
    2996              :         match self
    2997              :             .persistence
    2998              :             .abort_shard_split(*tenant_id, *new_shard_count)
    2999              :             .await?
    3000              :         {
    3001              :             AbortShardSplitStatus::Aborted => {
    3002              :                 // Proceed to roll back any child shards created on pageservers
    3003              :             }
    3004              :             AbortShardSplitStatus::Complete => {
    3005              :                 // The split completed (we might hit that path if e.g. our database transaction
    3006              :                 // to write the completion landed in the database, but we dropped connection
    3007              :                 // before seeing the result).
    3008              :                 //
    3009              :                 // We must update in-memory state to reflect the successful split.
    3010              :                 self.tenant_shard_split_commit_inmem(
    3011              :                     *tenant_id,
    3012              :                     *new_shard_count,
    3013              :                     *new_stripe_size,
    3014              :                 );
    3015              :                 return Ok(());
    3016              :             }
    3017              :         }
    3018              : 
    3019              :         // Clean up in-memory state, and accumulate the list of child locations that need detaching
    3020              :         let detach_locations: Vec<(Node, TenantShardId)> = {
    3021              :             let mut detach_locations = Vec::new();
    3022              :             let mut locked = self.inner.write().unwrap();
    3023              :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3024              : 
    3025              :             for (tenant_shard_id, shard) in
    3026              :                 tenants.range_mut(TenantShardId::tenant_range(op.tenant_id))
    3027              :             {
    3028              :                 if shard.shard.count == op.new_shard_count {
    3029              :                     // Surprising: the phase of [`Self::do_tenant_shard_split`] which inserts child shards in-memory
    3030              :                     // is infallible, so if we got an error we shouldn't have got that far.
    3031              :                     tracing::warn!(
    3032              :                         "During split abort, child shard {tenant_shard_id} found in-memory"
    3033              :                     );
    3034              :                     continue;
    3035              :                 }
    3036              : 
    3037              :                 // Add the children of this shard to this list of things to detach
    3038              :                 if let Some(node_id) = shard.intent.get_attached() {
    3039              :                     for child_id in tenant_shard_id.split(*new_shard_count) {
    3040              :                         detach_locations.push((
    3041              :                             nodes
    3042              :                                 .get(node_id)
    3043              :                                 .expect("Intent references nonexistent node")
    3044              :                                 .clone(),
    3045              :                             child_id,
    3046              :                         ));
    3047              :                     }
    3048              :                 } else {
    3049              :                     tracing::warn!(
    3050              :                         "During split abort, shard {tenant_shard_id} has no attached location"
    3051              :                     );
    3052              :                 }
    3053              : 
    3054              :                 tracing::info!("Restoring parent shard {tenant_shard_id}");
    3055              :                 shard.splitting = SplitState::Idle;
    3056              :                 if let Err(e) = shard.schedule(scheduler, &mut ScheduleContext::default()) {
    3057              :                     // If this shard can't be scheduled now (perhaps due to offline nodes or
    3058              :                     // capacity issues), that must not prevent us rolling back a split.  In this
    3059              :                     // case it should be eventually scheduled in the background.
    3060              :                     tracing::warn!("Failed to schedule {tenant_shard_id} during shard abort: {e}")
    3061              :                 }
    3062              : 
    3063              :                 self.maybe_reconcile_shard(shard, nodes);
    3064              :             }
    3065              : 
    3066              :             // We don't expect any new_shard_count shards to exist here, but drop them just in case
    3067            0 :             tenants.retain(|_id, s| s.shard.count != *new_shard_count);
    3068              : 
    3069              :             detach_locations
    3070              :         };
    3071              : 
    3072              :         for (node, child_id) in detach_locations {
    3073              :             if !node.is_available() {
    3074              :                 // An unavailable node cannot be cleaned up now: to avoid blocking forever, we will permit this, and
    3075              :                 // rely on the reconciliation that happens when a node transitions to Active to clean up. Since we have
    3076              :                 // removed child shards from our in-memory state and database, the reconciliation will implicitly remove
    3077              :                 // them from the node.
    3078              :                 tracing::warn!("Node {node} unavailable, can't clean up during split abort. It will be cleaned up when it is reactivated.");
    3079              :                 continue;
    3080              :             }
    3081              : 
    3082              :             // Detach the remote child.  If the pageserver split API call is still in progress, this call will get
    3083              :             // a 503 and retry, up to our limit.
    3084              :             tracing::info!("Detaching {child_id} on {node}...");
    3085              :             match node
    3086              :                 .with_client_retries(
    3087            0 :                     |client| async move {
    3088            0 :                         let config = LocationConfig {
    3089            0 :                             mode: LocationConfigMode::Detached,
    3090            0 :                             generation: None,
    3091            0 :                             secondary_conf: None,
    3092            0 :                             shard_number: child_id.shard_number.0,
    3093            0 :                             shard_count: child_id.shard_count.literal(),
    3094            0 :                             // Stripe size and tenant config don't matter when detaching
    3095            0 :                             shard_stripe_size: 0,
    3096            0 :                             tenant_conf: TenantConfig::default(),
    3097            0 :                         };
    3098            0 : 
    3099            0 :                         client.location_config(child_id, config, None, false).await
    3100            0 :                     },
    3101              :                     &self.config.jwt_token,
    3102              :                     1,
    3103              :                     10,
    3104              :                     Duration::from_secs(5),
    3105              :                     &self.cancel,
    3106              :                 )
    3107              :                 .await
    3108              :             {
    3109              :                 Some(Ok(_)) => {}
    3110              :                 Some(Err(e)) => {
    3111              :                     // We failed to communicate with the remote node.  This is problematic: we may be
    3112              :                     // leaving it with a rogue child shard.
    3113              :                     tracing::warn!(
    3114              :                         "Failed to detach child {child_id} from node {node} during abort"
    3115              :                     );
    3116              :                     return Err(e.into());
    3117              :                 }
    3118              :                 None => {
    3119              :                     // Cancellation: we were shutdown or the node went offline. Shutdown is fine, we'll
    3120              :                     // clean up on restart. The node going offline requires a retry.
    3121              :                     return Err(TenantShardSplitAbortError::Unavailable);
    3122              :                 }
    3123              :             };
    3124              :         }
    3125              : 
    3126              :         tracing::info!("Successfully aborted split");
    3127              :         Ok(())
    3128              :     }
    3129              : 
    3130              :     /// Infallible final stage of [`Self::tenant_shard_split`]: update the contents
    3131              :     /// of the tenant map to reflect the child shards that exist after the split.
    3132            0 :     fn tenant_shard_split_commit_inmem(
    3133            0 :         &self,
    3134            0 :         tenant_id: TenantId,
    3135            0 :         new_shard_count: ShardCount,
    3136            0 :         new_stripe_size: Option<ShardStripeSize>,
    3137            0 :     ) -> (
    3138            0 :         TenantShardSplitResponse,
    3139            0 :         Vec<(TenantShardId, NodeId, ShardStripeSize)>,
    3140            0 :         Vec<ReconcilerWaiter>,
    3141            0 :     ) {
    3142            0 :         let mut response = TenantShardSplitResponse {
    3143            0 :             new_shards: Vec::new(),
    3144            0 :         };
    3145            0 :         let mut child_locations = Vec::new();
    3146            0 :         let mut waiters = Vec::new();
    3147            0 : 
    3148            0 :         {
    3149            0 :             let mut locked = self.inner.write().unwrap();
    3150            0 : 
    3151            0 :             let parent_ids = locked
    3152            0 :                 .tenants
    3153            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    3154            0 :                 .map(|(shard_id, _)| *shard_id)
    3155            0 :                 .collect::<Vec<_>>();
    3156            0 : 
    3157            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3158            0 :             for parent_id in parent_ids {
    3159            0 :                 let child_ids = parent_id.split(new_shard_count);
    3160              : 
    3161            0 :                 let (pageserver, generation, policy, parent_ident, config) = {
    3162            0 :                     let mut old_state = tenants
    3163            0 :                         .remove(&parent_id)
    3164            0 :                         .expect("It was present, we just split it");
    3165            0 : 
    3166            0 :                     // A non-splitting state is impossible, because [`Self::tenant_shard_split`] holds
    3167            0 :                     // a TenantId lock and passes it through to [`TenantShardSplitAbort`] in case of cleanup:
    3168            0 :                     // nothing else can clear this.
    3169            0 :                     assert!(matches!(old_state.splitting, SplitState::Splitting));
    3170              : 
    3171            0 :                     let old_attached = old_state.intent.get_attached().unwrap();
    3172            0 :                     old_state.intent.clear(scheduler);
    3173            0 :                     let generation = old_state.generation.expect("Shard must have been attached");
    3174            0 :                     (
    3175            0 :                         old_attached,
    3176            0 :                         generation,
    3177            0 :                         old_state.policy,
    3178            0 :                         old_state.shard,
    3179            0 :                         old_state.config,
    3180            0 :                     )
    3181            0 :                 };
    3182            0 : 
    3183            0 :                 let mut schedule_context = ScheduleContext::default();
    3184            0 :                 for child in child_ids {
    3185            0 :                     let mut child_shard = parent_ident;
    3186            0 :                     child_shard.number = child.shard_number;
    3187            0 :                     child_shard.count = child.shard_count;
    3188            0 :                     if let Some(stripe_size) = new_stripe_size {
    3189            0 :                         child_shard.stripe_size = stripe_size;
    3190            0 :                     }
    3191              : 
    3192            0 :                     let mut child_observed: HashMap<NodeId, ObservedStateLocation> = HashMap::new();
    3193            0 :                     child_observed.insert(
    3194            0 :                         pageserver,
    3195            0 :                         ObservedStateLocation {
    3196            0 :                             conf: Some(attached_location_conf(
    3197            0 :                                 generation,
    3198            0 :                                 &child_shard,
    3199            0 :                                 &config,
    3200            0 :                                 matches!(policy, PlacementPolicy::Attached(n) if n > 0),
    3201              :                             )),
    3202              :                         },
    3203              :                     );
    3204              : 
    3205            0 :                     let mut child_state = TenantShard::new(child, child_shard, policy.clone());
    3206            0 :                     child_state.intent = IntentState::single(scheduler, Some(pageserver));
    3207            0 :                     child_state.observed = ObservedState {
    3208            0 :                         locations: child_observed,
    3209            0 :                     };
    3210            0 :                     child_state.generation = Some(generation);
    3211            0 :                     child_state.config = config.clone();
    3212            0 : 
    3213            0 :                     // The child's TenantShard::splitting is intentionally left at the default value of Idle,
    3214            0 :                     // as at this point in the split process we have succeeded and this part is infallible:
    3215            0 :                     // we will never need to do any special recovery from this state.
    3216            0 : 
    3217            0 :                     child_locations.push((child, pageserver, child_shard.stripe_size));
    3218              : 
    3219            0 :                     if let Err(e) = child_state.schedule(scheduler, &mut schedule_context) {
    3220              :                         // This is not fatal, because we've implicitly already got an attached
    3221              :                         // location for the child shard.  Failure here just means we couldn't
    3222              :                         // find a secondary (e.g. because cluster is overloaded).
    3223            0 :                         tracing::warn!("Failed to schedule child shard {child}: {e}");
    3224            0 :                     }
    3225              :                     // In the background, attach secondary locations for the new shards
    3226            0 :                     if let Some(waiter) = self.maybe_reconcile_shard(&mut child_state, nodes) {
    3227            0 :                         waiters.push(waiter);
    3228            0 :                     }
    3229              : 
    3230            0 :                     tenants.insert(child, child_state);
    3231            0 :                     response.new_shards.push(child);
    3232              :                 }
    3233              :             }
    3234            0 :             (response, child_locations, waiters)
    3235            0 :         }
    3236            0 :     }
    3237              : 
    3238            0 :     async fn tenant_shard_split_start_secondaries(
    3239            0 :         &self,
    3240            0 :         tenant_id: TenantId,
    3241            0 :         waiters: Vec<ReconcilerWaiter>,
    3242            0 :     ) {
    3243              :         // Wait for initial reconcile of child shards, this creates the secondary locations
    3244            0 :         if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    3245              :             // This is not a failure to split: it's some issue reconciling the new child shards, perhaps
    3246              :             // their secondaries couldn't be attached.
    3247            0 :             tracing::warn!("Failed to reconcile after split: {e}");
    3248            0 :             return;
    3249            0 :         }
    3250              : 
    3251              :         // Take the state lock to discover the attached & secondary intents for all shards
    3252            0 :         let (attached, secondary) = {
    3253            0 :             let locked = self.inner.read().unwrap();
    3254            0 :             let mut attached = Vec::new();
    3255            0 :             let mut secondary = Vec::new();
    3256              : 
    3257            0 :             for (tenant_shard_id, shard) in
    3258            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    3259              :             {
    3260            0 :                 let Some(node_id) = shard.intent.get_attached() else {
    3261              :                     // Unexpected.  Race with a PlacementPolicy change?
    3262            0 :                     tracing::warn!(
    3263            0 :                         "No attached node on {tenant_shard_id} immediately after shard split!"
    3264              :                     );
    3265            0 :                     continue;
    3266              :                 };
    3267              : 
    3268            0 :                 let Some(secondary_node_id) = shard.intent.get_secondary().first() else {
    3269              :                     // No secondary location.  Nothing for us to do.
    3270            0 :                     continue;
    3271              :                 };
    3272              : 
    3273            0 :                 let attached_node = locked
    3274            0 :                     .nodes
    3275            0 :                     .get(node_id)
    3276            0 :                     .expect("Pageservers may not be deleted while referenced");
    3277            0 : 
    3278            0 :                 let secondary_node = locked
    3279            0 :                     .nodes
    3280            0 :                     .get(secondary_node_id)
    3281            0 :                     .expect("Pageservers may not be deleted while referenced");
    3282            0 : 
    3283            0 :                 attached.push((*tenant_shard_id, attached_node.clone()));
    3284            0 :                 secondary.push((*tenant_shard_id, secondary_node.clone()));
    3285              :             }
    3286            0 :             (attached, secondary)
    3287            0 :         };
    3288            0 : 
    3289            0 :         if secondary.is_empty() {
    3290              :             // No secondary locations; nothing for us to do
    3291            0 :             return;
    3292            0 :         }
    3293              : 
    3294            0 :         for result in self
    3295            0 :             .tenant_for_shards_api(
    3296            0 :                 attached,
    3297            0 :                 |tenant_shard_id, client| async move {
    3298            0 :                     client.tenant_heatmap_upload(tenant_shard_id).await
    3299            0 :                 },
    3300            0 :                 1,
    3301            0 :                 1,
    3302            0 :                 SHORT_RECONCILE_TIMEOUT,
    3303            0 :                 &self.cancel,
    3304            0 :             )
    3305            0 :             .await
    3306              :         {
    3307            0 :             if let Err(e) = result {
    3308            0 :                 tracing::warn!("Error calling heatmap upload after shard split: {e}");
    3309            0 :                 return;
    3310            0 :             }
    3311              :         }
    3312              : 
    3313            0 :         for result in self
    3314            0 :             .tenant_for_shards_api(
    3315            0 :                 secondary,
    3316            0 :                 |tenant_shard_id, client| async move {
    3317            0 :                     client
    3318            0 :                         .tenant_secondary_download(tenant_shard_id, Some(Duration::ZERO))
    3319            0 :                         .await
    3320            0 :                 },
    3321            0 :                 1,
    3322            0 :                 1,
    3323            0 :                 SHORT_RECONCILE_TIMEOUT,
    3324            0 :                 &self.cancel,
    3325            0 :             )
    3326            0 :             .await
    3327              :         {
    3328            0 :             if let Err(e) = result {
    3329            0 :                 tracing::warn!("Error calling secondary download after shard split: {e}");
    3330            0 :                 return;
    3331            0 :             }
    3332              :         }
    3333            0 :     }
    3334              : 
    3335            0 :     pub(crate) async fn tenant_shard_split(
    3336            0 :         &self,
    3337            0 :         tenant_id: TenantId,
    3338            0 :         split_req: TenantShardSplitRequest,
    3339            0 :     ) -> Result<TenantShardSplitResponse, ApiError> {
    3340              :         // TODO: return 503 if we get stuck waiting for this lock
    3341              :         // (issue https://github.com/neondatabase/neon/issues/7108)
    3342            0 :         let _tenant_lock = trace_exclusive_lock(
    3343            0 :             &self.tenant_op_locks,
    3344            0 :             tenant_id,
    3345            0 :             TenantOperations::ShardSplit,
    3346            0 :         )
    3347            0 :         .await;
    3348              : 
    3349            0 :         let new_shard_count = ShardCount::new(split_req.new_shard_count);
    3350            0 :         let new_stripe_size = split_req.new_stripe_size;
    3351              : 
    3352              :         // Validate the request and construct parameters.  This phase is fallible, but does not require
    3353              :         // rollback on errors, as it does no I/O and mutates no state.
    3354            0 :         let shard_split_params = match self.prepare_tenant_shard_split(tenant_id, split_req)? {
    3355            0 :             ShardSplitAction::NoOp(resp) => return Ok(resp),
    3356            0 :             ShardSplitAction::Split(params) => params,
    3357              :         };
    3358              : 
    3359              :         // Execute this split: this phase mutates state and does remote I/O on pageservers.  If it fails,
    3360              :         // we must roll back.
    3361            0 :         let r = self
    3362            0 :             .do_tenant_shard_split(tenant_id, shard_split_params)
    3363            0 :             .await;
    3364              : 
    3365            0 :         let (response, waiters) = match r {
    3366            0 :             Ok(r) => r,
    3367            0 :             Err(e) => {
    3368            0 :                 // Split might be part-done, we must do work to abort it.
    3369            0 :                 tracing::warn!("Enqueuing background abort of split on {tenant_id}");
    3370            0 :                 self.abort_tx
    3371            0 :                     .send(TenantShardSplitAbort {
    3372            0 :                         tenant_id,
    3373            0 :                         new_shard_count,
    3374            0 :                         new_stripe_size,
    3375            0 :                         _tenant_lock,
    3376            0 :                     })
    3377            0 :                     // Ignore error sending: that just means we're shutting down: aborts are ephemeral so it's fine to drop it.
    3378            0 :                     .ok();
    3379            0 :                 return Err(e);
    3380              :             }
    3381              :         };
    3382              : 
    3383              :         // The split is now complete.  As an optimization, we will trigger all the child shards to upload
    3384              :         // a heatmap immediately, and all their secondary locations to start downloading: this avoids waiting
    3385              :         // for the background heatmap/download interval before secondaries get warm enough to migrate shards
    3386              :         // in [`Self::optimize_all`]
    3387            0 :         self.tenant_shard_split_start_secondaries(tenant_id, waiters)
    3388            0 :             .await;
    3389            0 :         Ok(response)
    3390            0 :     }
    3391              : 
    3392            0 :     fn prepare_tenant_shard_split(
    3393            0 :         &self,
    3394            0 :         tenant_id: TenantId,
    3395            0 :         split_req: TenantShardSplitRequest,
    3396            0 :     ) -> Result<ShardSplitAction, ApiError> {
    3397            0 :         fail::fail_point!("shard-split-validation", |_| Err(ApiError::BadRequest(
    3398            0 :             anyhow::anyhow!("failpoint")
    3399            0 :         )));
    3400              : 
    3401            0 :         let mut policy = None;
    3402            0 :         let mut config = None;
    3403            0 :         let mut shard_ident = None;
    3404              :         // Validate input, and calculate which shards we will create
    3405            0 :         let (old_shard_count, targets) =
    3406              :             {
    3407            0 :                 let locked = self.inner.read().unwrap();
    3408            0 : 
    3409            0 :                 let pageservers = locked.nodes.clone();
    3410            0 : 
    3411            0 :                 let mut targets = Vec::new();
    3412            0 : 
    3413            0 :                 // In case this is a retry, count how many already-split shards we found
    3414            0 :                 let mut children_found = Vec::new();
    3415            0 :                 let mut old_shard_count = None;
    3416              : 
    3417            0 :                 for (tenant_shard_id, shard) in
    3418            0 :                     locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    3419              :                 {
    3420            0 :                     match shard.shard.count.count().cmp(&split_req.new_shard_count) {
    3421              :                         Ordering::Equal => {
    3422              :                             //  Already split this
    3423            0 :                             children_found.push(*tenant_shard_id);
    3424            0 :                             continue;
    3425              :                         }
    3426              :                         Ordering::Greater => {
    3427            0 :                             return Err(ApiError::BadRequest(anyhow::anyhow!(
    3428            0 :                                 "Requested count {} but already have shards at count {}",
    3429            0 :                                 split_req.new_shard_count,
    3430            0 :                                 shard.shard.count.count()
    3431            0 :                             )));
    3432              :                         }
    3433            0 :                         Ordering::Less => {
    3434            0 :                             // Fall through: this shard has lower count than requested,
    3435            0 :                             // is a candidate for splitting.
    3436            0 :                         }
    3437            0 :                     }
    3438            0 : 
    3439            0 :                     match old_shard_count {
    3440            0 :                         None => old_shard_count = Some(shard.shard.count),
    3441            0 :                         Some(old_shard_count) => {
    3442            0 :                             if old_shard_count != shard.shard.count {
    3443              :                                 // We may hit this case if a caller asked for two splits to
    3444              :                                 // different sizes, before the first one is complete.
    3445              :                                 // e.g. 1->2, 2->4, where the 4 call comes while we have a mixture
    3446              :                                 // of shard_count=1 and shard_count=2 shards in the map.
    3447            0 :                                 return Err(ApiError::Conflict(
    3448            0 :                                     "Cannot split, currently mid-split".to_string(),
    3449            0 :                                 ));
    3450            0 :                             }
    3451              :                         }
    3452              :                     }
    3453            0 :                     if policy.is_none() {
    3454            0 :                         policy = Some(shard.policy.clone());
    3455            0 :                     }
    3456            0 :                     if shard_ident.is_none() {
    3457            0 :                         shard_ident = Some(shard.shard);
    3458            0 :                     }
    3459            0 :                     if config.is_none() {
    3460            0 :                         config = Some(shard.config.clone());
    3461            0 :                     }
    3462              : 
    3463            0 :                     if tenant_shard_id.shard_count.count() == split_req.new_shard_count {
    3464            0 :                         tracing::info!(
    3465            0 :                             "Tenant shard {} already has shard count {}",
    3466              :                             tenant_shard_id,
    3467              :                             split_req.new_shard_count
    3468              :                         );
    3469            0 :                         continue;
    3470            0 :                     }
    3471              : 
    3472            0 :                     let node_id = shard.intent.get_attached().ok_or(ApiError::BadRequest(
    3473            0 :                         anyhow::anyhow!("Cannot split a tenant that is not attached"),
    3474            0 :                     ))?;
    3475              : 
    3476            0 :                     let node = pageservers
    3477            0 :                         .get(&node_id)
    3478            0 :                         .expect("Pageservers may not be deleted while referenced");
    3479            0 : 
    3480            0 :                     targets.push(ShardSplitTarget {
    3481            0 :                         parent_id: *tenant_shard_id,
    3482            0 :                         node: node.clone(),
    3483            0 :                         child_ids: tenant_shard_id
    3484            0 :                             .split(ShardCount::new(split_req.new_shard_count)),
    3485            0 :                     });
    3486              :                 }
    3487              : 
    3488            0 :                 if targets.is_empty() {
    3489            0 :                     if children_found.len() == split_req.new_shard_count as usize {
    3490            0 :                         return Ok(ShardSplitAction::NoOp(TenantShardSplitResponse {
    3491            0 :                             new_shards: children_found,
    3492            0 :                         }));
    3493              :                     } else {
    3494              :                         // No shards found to split, and no existing children found: the
    3495              :                         // tenant doesn't exist at all.
    3496            0 :                         return Err(ApiError::NotFound(
    3497            0 :                             anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    3498            0 :                         ));
    3499              :                     }
    3500            0 :                 }
    3501            0 : 
    3502            0 :                 (old_shard_count, targets)
    3503            0 :             };
    3504            0 : 
    3505            0 :         // unwrap safety: we would have returned above if we didn't find at least one shard to split
    3506            0 :         let old_shard_count = old_shard_count.unwrap();
    3507            0 :         let shard_ident = if let Some(new_stripe_size) = split_req.new_stripe_size {
    3508              :             // This ShardIdentity will be used as the template for all children, so this implicitly
    3509              :             // applies the new stripe size to the children.
    3510            0 :             let mut shard_ident = shard_ident.unwrap();
    3511            0 :             if shard_ident.count.count() > 1 && shard_ident.stripe_size != new_stripe_size {
    3512            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)));
    3513            0 :             }
    3514            0 : 
    3515            0 :             shard_ident.stripe_size = new_stripe_size;
    3516            0 :             tracing::info!("applied  stripe size {}", shard_ident.stripe_size.0);
    3517            0 :             shard_ident
    3518              :         } else {
    3519            0 :             shard_ident.unwrap()
    3520              :         };
    3521            0 :         let policy = policy.unwrap();
    3522            0 :         let config = config.unwrap();
    3523            0 : 
    3524            0 :         Ok(ShardSplitAction::Split(ShardSplitParams {
    3525            0 :             old_shard_count,
    3526            0 :             new_shard_count: ShardCount::new(split_req.new_shard_count),
    3527            0 :             new_stripe_size: split_req.new_stripe_size,
    3528            0 :             targets,
    3529            0 :             policy,
    3530            0 :             config,
    3531            0 :             shard_ident,
    3532            0 :         }))
    3533            0 :     }
    3534              : 
    3535            0 :     async fn do_tenant_shard_split(
    3536            0 :         &self,
    3537            0 :         tenant_id: TenantId,
    3538            0 :         params: ShardSplitParams,
    3539            0 :     ) -> Result<(TenantShardSplitResponse, Vec<ReconcilerWaiter>), ApiError> {
    3540            0 :         // FIXME: we have dropped self.inner lock, and not yet written anything to the database: another
    3541            0 :         // request could occur here, deleting or mutating the tenant.  begin_shard_split checks that the
    3542            0 :         // parent shards exist as expected, but it would be neater to do the above pre-checks within the
    3543            0 :         // same database transaction rather than pre-check in-memory and then maybe-fail the database write.
    3544            0 :         // (https://github.com/neondatabase/neon/issues/6676)
    3545            0 : 
    3546            0 :         let ShardSplitParams {
    3547            0 :             old_shard_count,
    3548            0 :             new_shard_count,
    3549            0 :             new_stripe_size,
    3550            0 :             mut targets,
    3551            0 :             policy,
    3552            0 :             config,
    3553            0 :             shard_ident,
    3554            0 :         } = params;
    3555              : 
    3556              :         // Drop any secondary locations: pageservers do not support splitting these, and in any case the
    3557              :         // end-state for a split tenant will usually be to have secondary locations on different nodes.
    3558              :         // The reconciliation calls in this block also implicitly cancel+barrier wrt any ongoing reconciliation
    3559              :         // at the time of split.
    3560            0 :         let waiters = {
    3561            0 :             let mut locked = self.inner.write().unwrap();
    3562            0 :             let mut waiters = Vec::new();
    3563            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3564            0 :             for target in &mut targets {
    3565            0 :                 let Some(shard) = tenants.get_mut(&target.parent_id) else {
    3566              :                     // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
    3567            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3568            0 :                         "Shard {} not found",
    3569            0 :                         target.parent_id
    3570            0 :                     )));
    3571              :                 };
    3572              : 
    3573            0 :                 if shard.intent.get_attached() != &Some(target.node.get_id()) {
    3574              :                     // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
    3575            0 :                     return Err(ApiError::Conflict(format!(
    3576            0 :                         "Shard {} unexpectedly rescheduled during split",
    3577            0 :                         target.parent_id
    3578            0 :                     )));
    3579            0 :                 }
    3580            0 : 
    3581            0 :                 // Irrespective of PlacementPolicy, clear secondary locations from intent
    3582            0 :                 shard.intent.clear_secondary(scheduler);
    3583              : 
    3584              :                 // Run Reconciler to execute detach fo secondary locations.
    3585            0 :                 if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
    3586            0 :                     waiters.push(waiter);
    3587            0 :                 }
    3588              :             }
    3589            0 :             waiters
    3590            0 :         };
    3591            0 :         self.await_waiters(waiters, RECONCILE_TIMEOUT).await?;
    3592              : 
    3593              :         // Before creating any new child shards in memory or on the pageservers, persist them: this
    3594              :         // enables us to ensure that we will always be able to clean up if something goes wrong.  This also
    3595              :         // acts as the protection against two concurrent attempts to split: one of them will get a database
    3596              :         // error trying to insert the child shards.
    3597            0 :         let mut child_tsps = Vec::new();
    3598            0 :         for target in &targets {
    3599            0 :             let mut this_child_tsps = Vec::new();
    3600            0 :             for child in &target.child_ids {
    3601            0 :                 let mut child_shard = shard_ident;
    3602            0 :                 child_shard.number = child.shard_number;
    3603            0 :                 child_shard.count = child.shard_count;
    3604            0 : 
    3605            0 :                 tracing::info!(
    3606            0 :                     "Create child shard persistence with stripe size {}",
    3607              :                     shard_ident.stripe_size.0
    3608              :                 );
    3609              : 
    3610            0 :                 this_child_tsps.push(TenantShardPersistence {
    3611            0 :                     tenant_id: child.tenant_id.to_string(),
    3612            0 :                     shard_number: child.shard_number.0 as i32,
    3613            0 :                     shard_count: child.shard_count.literal() as i32,
    3614            0 :                     shard_stripe_size: shard_ident.stripe_size.0 as i32,
    3615            0 :                     // Note: this generation is a placeholder, [`Persistence::begin_shard_split`] will
    3616            0 :                     // populate the correct generation as part of its transaction, to protect us
    3617            0 :                     // against racing with changes in the state of the parent.
    3618            0 :                     generation: None,
    3619            0 :                     generation_pageserver: Some(target.node.get_id().0 as i64),
    3620            0 :                     placement_policy: serde_json::to_string(&policy).unwrap(),
    3621            0 :                     config: serde_json::to_string(&config).unwrap(),
    3622            0 :                     splitting: SplitState::Splitting,
    3623            0 : 
    3624            0 :                     // Scheduling policies do not carry through to children
    3625            0 :                     scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    3626            0 :                         .unwrap(),
    3627            0 :                 });
    3628              :             }
    3629              : 
    3630            0 :             child_tsps.push((target.parent_id, this_child_tsps));
    3631              :         }
    3632              : 
    3633            0 :         if let Err(e) = self
    3634            0 :             .persistence
    3635            0 :             .begin_shard_split(old_shard_count, tenant_id, child_tsps)
    3636            0 :             .await
    3637              :         {
    3638            0 :             match e {
    3639              :                 DatabaseError::Query(diesel::result::Error::DatabaseError(
    3640              :                     DatabaseErrorKind::UniqueViolation,
    3641              :                     _,
    3642              :                 )) => {
    3643              :                     // Inserting a child shard violated a unique constraint: we raced with another call to
    3644              :                     // this function
    3645            0 :                     tracing::warn!("Conflicting attempt to split {tenant_id}: {e}");
    3646            0 :                     return Err(ApiError::Conflict("Tenant is already splitting".into()));
    3647              :                 }
    3648            0 :                 _ => return Err(ApiError::InternalServerError(e.into())),
    3649              :             }
    3650            0 :         }
    3651            0 :         fail::fail_point!("shard-split-post-begin", |_| Err(
    3652            0 :             ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
    3653            0 :         ));
    3654              : 
    3655              :         // Now that I have persisted the splitting state, apply it in-memory.  This is infallible, so
    3656              :         // callers may assume that if splitting is set in memory, then it was persisted, and if splitting
    3657              :         // is not set in memory, then it was not persisted.
    3658              :         {
    3659            0 :             let mut locked = self.inner.write().unwrap();
    3660            0 :             for target in &targets {
    3661            0 :                 if let Some(parent_shard) = locked.tenants.get_mut(&target.parent_id) {
    3662            0 :                     parent_shard.splitting = SplitState::Splitting;
    3663            0 :                     // Put the observed state to None, to reflect that it is indeterminate once we start the
    3664            0 :                     // split operation.
    3665            0 :                     parent_shard
    3666            0 :                         .observed
    3667            0 :                         .locations
    3668            0 :                         .insert(target.node.get_id(), ObservedStateLocation { conf: None });
    3669            0 :                 }
    3670              :             }
    3671              :         }
    3672              : 
    3673              :         // TODO: issue split calls concurrently (this only matters once we're splitting
    3674              :         // N>1 shards into M shards -- initially we're usually splitting 1 shard into N).
    3675              : 
    3676            0 :         for target in &targets {
    3677              :             let ShardSplitTarget {
    3678            0 :                 parent_id,
    3679            0 :                 node,
    3680            0 :                 child_ids,
    3681            0 :             } = target;
    3682            0 :             let client = PageserverClient::new(
    3683            0 :                 node.get_id(),
    3684            0 :                 node.base_url(),
    3685            0 :                 self.config.jwt_token.as_deref(),
    3686            0 :             );
    3687            0 :             let response = client
    3688            0 :                 .tenant_shard_split(
    3689            0 :                     *parent_id,
    3690            0 :                     TenantShardSplitRequest {
    3691            0 :                         new_shard_count: new_shard_count.literal(),
    3692            0 :                         new_stripe_size,
    3693            0 :                     },
    3694            0 :                 )
    3695            0 :                 .await
    3696            0 :                 .map_err(|e| ApiError::Conflict(format!("Failed to split {}: {}", parent_id, e)))?;
    3697              : 
    3698            0 :             fail::fail_point!("shard-split-post-remote", |_| Err(ApiError::Conflict(
    3699            0 :                 "failpoint".to_string()
    3700            0 :             )));
    3701              : 
    3702            0 :             tracing::info!(
    3703            0 :                 "Split {} into {}",
    3704            0 :                 parent_id,
    3705            0 :                 response
    3706            0 :                     .new_shards
    3707            0 :                     .iter()
    3708            0 :                     .map(|s| format!("{:?}", s))
    3709            0 :                     .collect::<Vec<_>>()
    3710            0 :                     .join(",")
    3711              :             );
    3712              : 
    3713            0 :             if &response.new_shards != child_ids {
    3714              :                 // This should never happen: the pageserver should agree with us on how shard splits work.
    3715            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3716            0 :                     "Splitting shard {} resulted in unexpected IDs: {:?} (expected {:?})",
    3717            0 :                     parent_id,
    3718            0 :                     response.new_shards,
    3719            0 :                     child_ids
    3720            0 :                 )));
    3721            0 :             }
    3722              :         }
    3723              : 
    3724              :         // TODO: if the pageserver restarted concurrently with our split API call,
    3725              :         // the actual generation of the child shard might differ from the generation
    3726              :         // we expect it to have.  In order for our in-database generation to end up
    3727              :         // correct, we should carry the child generation back in the response and apply it here
    3728              :         // in complete_shard_split (and apply the correct generation in memory)
    3729              :         // (or, we can carry generation in the request and reject the request if
    3730              :         //  it doesn't match, but that requires more retry logic on this side)
    3731              : 
    3732            0 :         self.persistence
    3733            0 :             .complete_shard_split(tenant_id, old_shard_count)
    3734            0 :             .await?;
    3735              : 
    3736            0 :         fail::fail_point!("shard-split-post-complete", |_| Err(
    3737            0 :             ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
    3738            0 :         ));
    3739              : 
    3740              :         // Replace all the shards we just split with their children: this phase is infallible.
    3741            0 :         let (response, child_locations, waiters) =
    3742            0 :             self.tenant_shard_split_commit_inmem(tenant_id, new_shard_count, new_stripe_size);
    3743            0 : 
    3744            0 :         // Send compute notifications for all the new shards
    3745            0 :         let mut failed_notifications = Vec::new();
    3746            0 :         for (child_id, child_ps, stripe_size) in child_locations {
    3747            0 :             if let Err(e) = self
    3748            0 :                 .compute_hook
    3749            0 :                 .notify(child_id, child_ps, stripe_size, &self.cancel)
    3750            0 :                 .await
    3751              :             {
    3752            0 :                 tracing::warn!("Failed to update compute of {}->{} during split, proceeding anyway to complete split ({e})",
    3753              :                         child_id, child_ps);
    3754            0 :                 failed_notifications.push(child_id);
    3755            0 :             }
    3756              :         }
    3757              : 
    3758              :         // If we failed any compute notifications, make a note to retry later.
    3759            0 :         if !failed_notifications.is_empty() {
    3760            0 :             let mut locked = self.inner.write().unwrap();
    3761            0 :             for failed in failed_notifications {
    3762            0 :                 if let Some(shard) = locked.tenants.get_mut(&failed) {
    3763            0 :                     shard.pending_compute_notification = true;
    3764            0 :                 }
    3765              :             }
    3766            0 :         }
    3767              : 
    3768            0 :         Ok((response, waiters))
    3769            0 :     }
    3770              : 
    3771            0 :     pub(crate) async fn tenant_shard_migrate(
    3772            0 :         &self,
    3773            0 :         tenant_shard_id: TenantShardId,
    3774            0 :         migrate_req: TenantShardMigrateRequest,
    3775            0 :     ) -> Result<TenantShardMigrateResponse, ApiError> {
    3776            0 :         let waiter = {
    3777            0 :             let mut locked = self.inner.write().unwrap();
    3778            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3779              : 
    3780            0 :             let Some(node) = nodes.get(&migrate_req.node_id) else {
    3781            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    3782            0 :                     "Node {} not found",
    3783            0 :                     migrate_req.node_id
    3784            0 :                 )));
    3785              :             };
    3786              : 
    3787            0 :             if !node.is_available() {
    3788              :                 // Warn but proceed: the caller may intend to manually adjust the placement of
    3789              :                 // a shard even if the node is down, e.g. if intervening during an incident.
    3790            0 :                 tracing::warn!("Migrating to unavailable node {node}");
    3791            0 :             }
    3792              : 
    3793            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    3794            0 :                 return Err(ApiError::NotFound(
    3795            0 :                     anyhow::anyhow!("Tenant shard not found").into(),
    3796            0 :                 ));
    3797              :             };
    3798              : 
    3799            0 :             if shard.intent.get_attached() == &Some(migrate_req.node_id) {
    3800              :                 // No-op case: we will still proceed to wait for reconciliation in case it is
    3801              :                 // incomplete from an earlier update to the intent.
    3802            0 :                 tracing::info!("Migrating: intent is unchanged {:?}", shard.intent);
    3803              :             } else {
    3804            0 :                 let old_attached = *shard.intent.get_attached();
    3805            0 : 
    3806            0 :                 match shard.policy {
    3807            0 :                     PlacementPolicy::Attached(n) => {
    3808            0 :                         // If our new attached node was a secondary, it no longer should be.
    3809            0 :                         shard.intent.remove_secondary(scheduler, migrate_req.node_id);
    3810              : 
    3811              :                         // If we were already attached to something, demote that to a secondary
    3812            0 :                         if let Some(old_attached) = old_attached {
    3813            0 :                             if n > 0 {
    3814              :                                 // Remove other secondaries to make room for the location we'll demote
    3815            0 :                                 while shard.intent.get_secondary().len() >= n {
    3816            0 :                                     shard.intent.pop_secondary(scheduler);
    3817            0 :                                 }
    3818              : 
    3819            0 :                                 shard.intent.push_secondary(scheduler, old_attached);
    3820            0 :                             }
    3821            0 :                         }
    3822              : 
    3823            0 :                         shard.intent.set_attached(scheduler, Some(migrate_req.node_id));
    3824              :                     }
    3825            0 :                     PlacementPolicy::Secondary => {
    3826            0 :                         shard.intent.clear(scheduler);
    3827            0 :                         shard.intent.push_secondary(scheduler, migrate_req.node_id);
    3828            0 :                     }
    3829              :                     PlacementPolicy::Detached => {
    3830            0 :                         return Err(ApiError::BadRequest(anyhow::anyhow!(
    3831            0 :                             "Cannot migrate a tenant that is PlacementPolicy::Detached: configure it to an attached policy first"
    3832            0 :                         )))
    3833              :                     }
    3834              :                 }
    3835              : 
    3836            0 :                 tracing::info!("Migrating: new intent {:?}", shard.intent);
    3837            0 :                 shard.sequence = shard.sequence.next();
    3838              :             }
    3839              : 
    3840            0 :             self.maybe_reconcile_shard(shard, nodes)
    3841              :         };
    3842              : 
    3843            0 :         if let Some(waiter) = waiter {
    3844            0 :             waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
    3845              :         } else {
    3846            0 :             tracing::info!("Migration is a no-op");
    3847              :         }
    3848              : 
    3849            0 :         Ok(TenantShardMigrateResponse {})
    3850            0 :     }
    3851              : 
    3852              :     /// This is for debug/support only: we simply drop all state for a tenant, without
    3853              :     /// detaching or deleting it on pageservers.
    3854            0 :     pub(crate) async fn tenant_drop(&self, tenant_id: TenantId) -> Result<(), ApiError> {
    3855            0 :         self.persistence.delete_tenant(tenant_id).await?;
    3856              : 
    3857            0 :         let mut locked = self.inner.write().unwrap();
    3858            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    3859            0 :         let mut shards = Vec::new();
    3860            0 :         for (tenant_shard_id, _) in tenants.range(TenantShardId::tenant_range(tenant_id)) {
    3861            0 :             shards.push(*tenant_shard_id);
    3862            0 :         }
    3863              : 
    3864            0 :         for shard_id in shards {
    3865            0 :             if let Some(mut shard) = tenants.remove(&shard_id) {
    3866            0 :                 shard.intent.clear(scheduler);
    3867            0 :             }
    3868              :         }
    3869              : 
    3870            0 :         Ok(())
    3871            0 :     }
    3872              : 
    3873              :     /// This is for debug/support only: assuming tenant data is already present in S3, we "create" a
    3874              :     /// tenant with a very high generation number so that it will see the existing data.
    3875            0 :     pub(crate) async fn tenant_import(
    3876            0 :         &self,
    3877            0 :         tenant_id: TenantId,
    3878            0 :     ) -> Result<TenantCreateResponse, ApiError> {
    3879            0 :         // Pick an arbitrary available pageserver to use for scanning the tenant in remote storage
    3880            0 :         let maybe_node = {
    3881            0 :             self.inner
    3882            0 :                 .read()
    3883            0 :                 .unwrap()
    3884            0 :                 .nodes
    3885            0 :                 .values()
    3886            0 :                 .find(|n| n.is_available())
    3887            0 :                 .cloned()
    3888              :         };
    3889            0 :         let Some(node) = maybe_node else {
    3890            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!("No nodes available")));
    3891              :         };
    3892              : 
    3893            0 :         let client = PageserverClient::new(
    3894            0 :             node.get_id(),
    3895            0 :             node.base_url(),
    3896            0 :             self.config.jwt_token.as_deref(),
    3897            0 :         );
    3898              : 
    3899            0 :         let scan_result = client
    3900            0 :             .tenant_scan_remote_storage(tenant_id)
    3901            0 :             .await
    3902            0 :             .map_err(|e| passthrough_api_error(&node, e))?;
    3903              : 
    3904              :         // A post-split tenant may contain a mixture of shard counts in remote storage: pick the highest count.
    3905            0 :         let Some(shard_count) = scan_result
    3906            0 :             .shards
    3907            0 :             .iter()
    3908            0 :             .map(|s| s.tenant_shard_id.shard_count)
    3909            0 :             .max()
    3910              :         else {
    3911            0 :             return Err(ApiError::NotFound(
    3912            0 :                 anyhow::anyhow!("No shards found").into(),
    3913            0 :             ));
    3914              :         };
    3915              : 
    3916              :         // Ideally we would set each newly imported shard's generation independently, but for correctness it is sufficient
    3917              :         // to
    3918            0 :         let generation = scan_result
    3919            0 :             .shards
    3920            0 :             .iter()
    3921            0 :             .map(|s| s.generation)
    3922            0 :             .max()
    3923            0 :             .expect("We already validated >0 shards");
    3924            0 : 
    3925            0 :         // FIXME: we have no way to recover the shard stripe size from contents of remote storage: this will
    3926            0 :         // only work if they were using the default stripe size.
    3927            0 :         let stripe_size = ShardParameters::DEFAULT_STRIPE_SIZE;
    3928              : 
    3929            0 :         let (response, waiters) = self
    3930            0 :             .do_tenant_create(TenantCreateRequest {
    3931            0 :                 new_tenant_id: TenantShardId::unsharded(tenant_id),
    3932            0 :                 generation,
    3933            0 : 
    3934            0 :                 shard_parameters: ShardParameters {
    3935            0 :                     count: shard_count,
    3936            0 :                     stripe_size,
    3937            0 :                 },
    3938            0 :                 placement_policy: Some(PlacementPolicy::Attached(0)), // No secondaries, for convenient debug/hacking
    3939            0 : 
    3940            0 :                 // There is no way to know what the tenant's config was: revert to defaults
    3941            0 :                 config: TenantConfig::default(),
    3942            0 :             })
    3943            0 :             .await?;
    3944              : 
    3945            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    3946              :             // Since this is a debug/support operation, all kinds of weird issues are possible (e.g. this
    3947              :             // tenant doesn't exist in the control plane), so don't fail the request if it can't fully
    3948              :             // reconcile, as reconciliation includes notifying compute.
    3949            0 :             tracing::warn!(%tenant_id, "Reconcile not done yet while importing tenant ({e})");
    3950            0 :         }
    3951              : 
    3952            0 :         Ok(response)
    3953            0 :     }
    3954              : 
    3955              :     /// For debug/support: a full JSON dump of TenantShards.  Returns a response so that
    3956              :     /// we don't have to make TenantShard clonable in the return path.
    3957            0 :     pub(crate) fn tenants_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
    3958            0 :         let serialized = {
    3959            0 :             let locked = self.inner.read().unwrap();
    3960            0 :             let result = locked.tenants.values().collect::<Vec<_>>();
    3961            0 :             serde_json::to_string(&result).map_err(|e| ApiError::InternalServerError(e.into()))?
    3962              :         };
    3963              : 
    3964            0 :         hyper::Response::builder()
    3965            0 :             .status(hyper::StatusCode::OK)
    3966            0 :             .header(hyper::header::CONTENT_TYPE, "application/json")
    3967            0 :             .body(hyper::Body::from(serialized))
    3968            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))
    3969            0 :     }
    3970              : 
    3971              :     /// Check the consistency of in-memory state vs. persistent state, and check that the
    3972              :     /// scheduler's statistics are up to date.
    3973              :     ///
    3974              :     /// These consistency checks expect an **idle** system.  If changes are going on while
    3975              :     /// we run, then we can falsely indicate a consistency issue.  This is sufficient for end-of-test
    3976              :     /// checks, but not suitable for running continuously in the background in the field.
    3977            0 :     pub(crate) async fn consistency_check(&self) -> Result<(), ApiError> {
    3978            0 :         let (mut expect_nodes, mut expect_shards) = {
    3979            0 :             let locked = self.inner.read().unwrap();
    3980            0 : 
    3981            0 :             locked
    3982            0 :                 .scheduler
    3983            0 :                 .consistency_check(locked.nodes.values(), locked.tenants.values())
    3984            0 :                 .context("Scheduler checks")
    3985            0 :                 .map_err(ApiError::InternalServerError)?;
    3986              : 
    3987            0 :             let expect_nodes = locked
    3988            0 :                 .nodes
    3989            0 :                 .values()
    3990            0 :                 .map(|n| n.to_persistent())
    3991            0 :                 .collect::<Vec<_>>();
    3992            0 : 
    3993            0 :             let expect_shards = locked
    3994            0 :                 .tenants
    3995            0 :                 .values()
    3996            0 :                 .map(|t| t.to_persistent())
    3997            0 :                 .collect::<Vec<_>>();
    3998              : 
    3999              :             // This method can only validate the state of an idle system: if a reconcile is in
    4000              :             // progress, fail out early to avoid giving false errors on state that won't match
    4001              :             // between database and memory under a ReconcileResult is processed.
    4002            0 :             for t in locked.tenants.values() {
    4003            0 :                 if t.reconciler.is_some() {
    4004            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4005            0 :                         "Shard {} reconciliation in progress",
    4006            0 :                         t.tenant_shard_id
    4007            0 :                     )));
    4008            0 :                 }
    4009              :             }
    4010              : 
    4011            0 :             (expect_nodes, expect_shards)
    4012              :         };
    4013              : 
    4014            0 :         let mut nodes = self.persistence.list_nodes().await?;
    4015            0 :         expect_nodes.sort_by_key(|n| n.node_id);
    4016            0 :         nodes.sort_by_key(|n| n.node_id);
    4017            0 : 
    4018            0 :         if nodes != expect_nodes {
    4019            0 :             tracing::error!("Consistency check failed on nodes.");
    4020            0 :             tracing::error!(
    4021            0 :                 "Nodes in memory: {}",
    4022            0 :                 serde_json::to_string(&expect_nodes)
    4023            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    4024              :             );
    4025            0 :             tracing::error!(
    4026            0 :                 "Nodes in database: {}",
    4027            0 :                 serde_json::to_string(&nodes)
    4028            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    4029              :             );
    4030            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4031            0 :                 "Node consistency failure"
    4032            0 :             )));
    4033            0 :         }
    4034              : 
    4035            0 :         let mut shards = self.persistence.list_tenant_shards().await?;
    4036            0 :         shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
    4037            0 :         expect_shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
    4038            0 : 
    4039            0 :         if shards != expect_shards {
    4040            0 :             tracing::error!("Consistency check failed on shards.");
    4041            0 :             tracing::error!(
    4042            0 :                 "Shards in memory: {}",
    4043            0 :                 serde_json::to_string(&expect_shards)
    4044            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    4045              :             );
    4046            0 :             tracing::error!(
    4047            0 :                 "Shards in database: {}",
    4048            0 :                 serde_json::to_string(&shards)
    4049            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    4050              :             );
    4051            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4052            0 :                 "Shard consistency failure"
    4053            0 :             )));
    4054            0 :         }
    4055            0 : 
    4056            0 :         Ok(())
    4057            0 :     }
    4058              : 
    4059              :     /// For debug/support: a JSON dump of the [`Scheduler`].  Returns a response so that
    4060              :     /// we don't have to make TenantShard clonable in the return path.
    4061            0 :     pub(crate) fn scheduler_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
    4062            0 :         let serialized = {
    4063            0 :             let locked = self.inner.read().unwrap();
    4064            0 :             serde_json::to_string(&locked.scheduler)
    4065            0 :                 .map_err(|e| ApiError::InternalServerError(e.into()))?
    4066              :         };
    4067              : 
    4068            0 :         hyper::Response::builder()
    4069            0 :             .status(hyper::StatusCode::OK)
    4070            0 :             .header(hyper::header::CONTENT_TYPE, "application/json")
    4071            0 :             .body(hyper::Body::from(serialized))
    4072            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))
    4073            0 :     }
    4074              : 
    4075              :     /// This is for debug/support only: we simply drop all state for a tenant, without
    4076              :     /// detaching or deleting it on pageservers.  We do not try and re-schedule any
    4077              :     /// tenants that were on this node.
    4078              :     ///
    4079              :     /// TODO: proper node deletion API that unhooks things more gracefully
    4080            0 :     pub(crate) async fn node_drop(&self, node_id: NodeId) -> Result<(), ApiError> {
    4081            0 :         self.persistence.delete_node(node_id).await?;
    4082              : 
    4083            0 :         let mut locked = self.inner.write().unwrap();
    4084              : 
    4085            0 :         for shard in locked.tenants.values_mut() {
    4086            0 :             shard.deref_node(node_id);
    4087            0 :         }
    4088              : 
    4089            0 :         let mut nodes = (*locked.nodes).clone();
    4090            0 :         nodes.remove(&node_id);
    4091            0 :         locked.nodes = Arc::new(nodes);
    4092            0 : 
    4093            0 :         locked.scheduler.node_remove(node_id);
    4094            0 : 
    4095            0 :         Ok(())
    4096            0 :     }
    4097              : 
    4098            0 :     pub(crate) async fn node_list(&self) -> Result<Vec<Node>, ApiError> {
    4099            0 :         let nodes = {
    4100            0 :             self.inner
    4101            0 :                 .read()
    4102            0 :                 .unwrap()
    4103            0 :                 .nodes
    4104            0 :                 .values()
    4105            0 :                 .cloned()
    4106            0 :                 .collect::<Vec<_>>()
    4107            0 :         };
    4108            0 : 
    4109            0 :         Ok(nodes)
    4110            0 :     }
    4111              : 
    4112            0 :     pub(crate) async fn node_register(
    4113            0 :         &self,
    4114            0 :         register_req: NodeRegisterRequest,
    4115            0 :     ) -> Result<(), ApiError> {
    4116            0 :         let _node_lock = trace_exclusive_lock(
    4117            0 :             &self.node_op_locks,
    4118            0 :             register_req.node_id,
    4119            0 :             NodeOperations::Register,
    4120            0 :         )
    4121            0 :         .await;
    4122              : 
    4123              :         {
    4124            0 :             let locked = self.inner.read().unwrap();
    4125            0 :             if let Some(node) = locked.nodes.get(&register_req.node_id) {
    4126              :                 // Note that we do not do a total equality of the struct, because we don't require
    4127              :                 // the availability/scheduling states to agree for a POST to be idempotent.
    4128            0 :                 if node.registration_match(&register_req) {
    4129            0 :                     tracing::info!(
    4130            0 :                         "Node {} re-registered with matching address",
    4131              :                         register_req.node_id
    4132              :                     );
    4133            0 :                     return Ok(());
    4134              :                 } else {
    4135              :                     // TODO: decide if we want to allow modifying node addresses without removing and re-adding
    4136              :                     // the node.  Safest/simplest thing is to refuse it, and usually we deploy with
    4137              :                     // a fixed address through the lifetime of a node.
    4138            0 :                     tracing::warn!(
    4139            0 :                         "Node {} tried to register with different address",
    4140              :                         register_req.node_id
    4141              :                     );
    4142            0 :                     return Err(ApiError::Conflict(
    4143            0 :                         "Node is already registered with different address".to_string(),
    4144            0 :                     ));
    4145              :                 }
    4146            0 :             }
    4147            0 :         }
    4148            0 : 
    4149            0 :         // We do not require that a node is actually online when registered (it will start life
    4150            0 :         // with it's  availability set to Offline), but we _do_ require that its DNS record exists. We're
    4151            0 :         // therefore not immune to asymmetric L3 connectivity issues, but we are protected against nodes
    4152            0 :         // that register themselves with a broken DNS config.  We check only the HTTP hostname, because
    4153            0 :         // the postgres hostname might only be resolvable to clients (e.g. if we're on a different VPC than clients).
    4154            0 :         if tokio::net::lookup_host(format!(
    4155            0 :             "{}:{}",
    4156            0 :             register_req.listen_http_addr, register_req.listen_http_port
    4157            0 :         ))
    4158            0 :         .await
    4159            0 :         .is_err()
    4160              :         {
    4161              :             // If we have a transient DNS issue, it's up to the caller to retry their registration.  Because
    4162              :             // we can't robustly distinguish between an intermittent issue and a totally bogus DNS situation,
    4163              :             // we return a soft 503 error, to encourage callers to retry past transient issues.
    4164            0 :             return Err(ApiError::ResourceUnavailable(
    4165            0 :                 format!(
    4166            0 :                     "Node {} tried to register with unknown DNS name '{}'",
    4167            0 :                     register_req.node_id, register_req.listen_http_addr
    4168            0 :                 )
    4169            0 :                 .into(),
    4170            0 :             ));
    4171            0 :         }
    4172            0 : 
    4173            0 :         // Ordering: we must persist the new node _before_ adding it to in-memory state.
    4174            0 :         // This ensures that before we use it for anything or expose it via any external
    4175            0 :         // API, it is guaranteed to be available after a restart.
    4176            0 :         let new_node = Node::new(
    4177            0 :             register_req.node_id,
    4178            0 :             register_req.listen_http_addr,
    4179            0 :             register_req.listen_http_port,
    4180            0 :             register_req.listen_pg_addr,
    4181            0 :             register_req.listen_pg_port,
    4182            0 :         );
    4183            0 : 
    4184            0 :         // TODO: idempotency if the node already exists in the database
    4185            0 :         self.persistence.insert_node(&new_node).await?;
    4186              : 
    4187            0 :         let mut locked = self.inner.write().unwrap();
    4188            0 :         let mut new_nodes = (*locked.nodes).clone();
    4189            0 : 
    4190            0 :         locked.scheduler.node_upsert(&new_node);
    4191            0 :         new_nodes.insert(register_req.node_id, new_node);
    4192            0 : 
    4193            0 :         locked.nodes = Arc::new(new_nodes);
    4194            0 : 
    4195            0 :         tracing::info!(
    4196            0 :             "Registered pageserver {}, now have {} pageservers",
    4197            0 :             register_req.node_id,
    4198            0 :             locked.nodes.len()
    4199              :         );
    4200            0 :         Ok(())
    4201            0 :     }
    4202              : 
    4203            0 :     pub(crate) async fn node_configure(
    4204            0 :         &self,
    4205            0 :         node_id: NodeId,
    4206            0 :         availability: Option<NodeAvailability>,
    4207            0 :         scheduling: Option<NodeSchedulingPolicy>,
    4208            0 :     ) -> Result<(), ApiError> {
    4209            0 :         let _node_lock =
    4210            0 :             trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Configure).await;
    4211              : 
    4212            0 :         if let Some(scheduling) = scheduling {
    4213              :             // Scheduling is a persistent part of Node: we must write updates to the database before
    4214              :             // applying them in memory
    4215            0 :             self.persistence.update_node(node_id, scheduling).await?;
    4216            0 :         }
    4217              : 
    4218              :         // If we're activating a node, then before setting it active we must reconcile any shard locations
    4219              :         // on that node, in case it is out of sync, e.g. due to being unavailable during controller startup,
    4220              :         // by calling [`Self::node_activate_reconcile`]
    4221              :         //
    4222              :         // The transition we calculate here remains valid later in the function because we hold the op lock on the node:
    4223              :         // nothing else can mutate its availability while we run.
    4224            0 :         let availability_transition = if let Some(input_availability) = availability {
    4225            0 :             let (activate_node, availability_transition) = {
    4226            0 :                 let locked = self.inner.read().unwrap();
    4227            0 :                 let Some(node) = locked.nodes.get(&node_id) else {
    4228            0 :                     return Err(ApiError::NotFound(
    4229            0 :                         anyhow::anyhow!("Node {} not registered", node_id).into(),
    4230            0 :                     ));
    4231              :                 };
    4232              : 
    4233            0 :                 (
    4234            0 :                     node.clone(),
    4235            0 :                     node.get_availability_transition(input_availability),
    4236            0 :                 )
    4237              :             };
    4238              : 
    4239            0 :             if matches!(availability_transition, AvailabilityTransition::ToActive) {
    4240            0 :                 self.node_activate_reconcile(activate_node, &_node_lock)
    4241            0 :                     .await?;
    4242            0 :             }
    4243            0 :             availability_transition
    4244              :         } else {
    4245            0 :             AvailabilityTransition::Unchanged
    4246              :         };
    4247              : 
    4248              :         // Apply changes from the request to our in-memory state for the Node
    4249            0 :         let mut locked = self.inner.write().unwrap();
    4250            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    4251            0 : 
    4252            0 :         let mut new_nodes = (**nodes).clone();
    4253              : 
    4254            0 :         let Some(node) = new_nodes.get_mut(&node_id) else {
    4255            0 :             return Err(ApiError::NotFound(
    4256            0 :                 anyhow::anyhow!("Node not registered").into(),
    4257            0 :             ));
    4258              :         };
    4259              : 
    4260            0 :         if let Some(availability) = &availability {
    4261            0 :             node.set_availability(*availability);
    4262            0 :         }
    4263              : 
    4264            0 :         if let Some(scheduling) = scheduling {
    4265            0 :             node.set_scheduling(scheduling);
    4266            0 : 
    4267            0 :             // TODO: once we have a background scheduling ticker for fill/drain, kick it
    4268            0 :             // to wake up and start working.
    4269            0 :         }
    4270              : 
    4271              :         // Update the scheduler, in case the elegibility of the node for new shards has changed
    4272            0 :         scheduler.node_upsert(node);
    4273            0 : 
    4274            0 :         let new_nodes = Arc::new(new_nodes);
    4275            0 : 
    4276            0 :         // Modify scheduling state for any Tenants that are affected by a change in the node's availability state.
    4277            0 :         match availability_transition {
    4278              :             AvailabilityTransition::ToOffline => {
    4279            0 :                 tracing::info!("Node {} transition to offline", node_id);
    4280            0 :                 let mut tenants_affected: usize = 0;
    4281              : 
    4282            0 :                 for (tenant_shard_id, tenant_shard) in tenants {
    4283            0 :                     if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
    4284            0 :                         // When a node goes offline, we set its observed configuration to None, indicating unknown: we will
    4285            0 :                         // not assume our knowledge of the node's configuration is accurate until it comes back online
    4286            0 :                         observed_loc.conf = None;
    4287            0 :                     }
    4288              : 
    4289            0 :                     if new_nodes.len() == 1 {
    4290              :                         // Special case for single-node cluster: there is no point trying to reschedule
    4291              :                         // any tenant shards: avoid doing so, in order to avoid spewing warnings about
    4292              :                         // failures to schedule them.
    4293            0 :                         continue;
    4294            0 :                     }
    4295            0 : 
    4296            0 :                     if tenant_shard.intent.demote_attached(node_id) {
    4297            0 :                         tenant_shard.sequence = tenant_shard.sequence.next();
    4298            0 : 
    4299            0 :                         // TODO: populate a ScheduleContext including all shards in the same tenant_id (only matters
    4300            0 :                         // for tenants without secondary locations: if they have a secondary location, then this
    4301            0 :                         // schedule() call is just promoting an existing secondary)
    4302            0 :                         let mut schedule_context = ScheduleContext::default();
    4303            0 : 
    4304            0 :                         match tenant_shard.schedule(scheduler, &mut schedule_context) {
    4305            0 :                             Err(e) => {
    4306            0 :                                 // It is possible that some tenants will become unschedulable when too many pageservers
    4307            0 :                                 // go offline: in this case there isn't much we can do other than make the issue observable.
    4308            0 :                                 // TODO: give TenantShard a scheduling error attribute to be queried later.
    4309            0 :                                 tracing::warn!(%tenant_shard_id, "Scheduling error when marking pageserver {} offline: {e}", node_id);
    4310              :                             }
    4311              :                             Ok(()) => {
    4312            0 :                                 if self
    4313            0 :                                     .maybe_reconcile_shard(tenant_shard, &new_nodes)
    4314            0 :                                     .is_some()
    4315            0 :                                 {
    4316            0 :                                     tenants_affected += 1;
    4317            0 :                                 };
    4318              :                             }
    4319              :                         }
    4320            0 :                     }
    4321              :                 }
    4322            0 :                 tracing::info!(
    4323            0 :                     "Launched {} reconciler tasks for tenants affected by node {} going offline",
    4324              :                     tenants_affected,
    4325              :                     node_id
    4326              :                 )
    4327              :             }
    4328              :             AvailabilityTransition::ToActive => {
    4329            0 :                 tracing::info!("Node {} transition to active", node_id);
    4330              :                 // When a node comes back online, we must reconcile any tenant that has a None observed
    4331              :                 // location on the node.
    4332            0 :                 for tenant_shard in locked.tenants.values_mut() {
    4333            0 :                     if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
    4334            0 :                         if observed_loc.conf.is_none() {
    4335            0 :                             self.maybe_reconcile_shard(tenant_shard, &new_nodes);
    4336            0 :                         }
    4337            0 :                     }
    4338              :                 }
    4339              : 
    4340              :                 // TODO: in the background, we should balance work back onto this pageserver
    4341              :             }
    4342              :             AvailabilityTransition::Unchanged => {
    4343            0 :                 tracing::debug!("Node {} no change during config", node_id);
    4344              :             }
    4345              :         }
    4346              : 
    4347            0 :         locked.nodes = new_nodes;
    4348            0 : 
    4349            0 :         Ok(())
    4350            0 :     }
    4351              : 
    4352              :     /// Helper for methods that will try and call pageserver APIs for
    4353              :     /// a tenant, such as timeline CRUD: they cannot proceed unless the tenant
    4354              :     /// is attached somewhere.
    4355            0 :     fn ensure_attached_schedule(
    4356            0 :         &self,
    4357            0 :         mut locked: std::sync::RwLockWriteGuard<'_, ServiceState>,
    4358            0 :         tenant_id: TenantId,
    4359            0 :     ) -> Result<Vec<ReconcilerWaiter>, anyhow::Error> {
    4360            0 :         let mut waiters = Vec::new();
    4361            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    4362            0 : 
    4363            0 :         let mut schedule_context = ScheduleContext::default();
    4364            0 :         for (tenant_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    4365            0 :             shard.schedule(scheduler, &mut schedule_context)?;
    4366              : 
    4367              :             // The shard's policies may not result in an attached location being scheduled: this
    4368              :             // is an error because our caller needs it attached somewhere.
    4369            0 :             if shard.intent.get_attached().is_none() {
    4370            0 :                 return Err(anyhow::anyhow!(
    4371            0 :                     "Tenant {tenant_id} not scheduled to be attached"
    4372            0 :                 ));
    4373            0 :             };
    4374            0 : 
    4375            0 :             if shard.stably_attached().is_some() {
    4376              :                 // We do not require the shard to be totally up to date on reconciliation: we just require
    4377              :                 // that it has been attached on the intended node.   Other dirty state such as unattached secondary
    4378              :                 // locations, or compute hook notifications can be ignored.
    4379            0 :                 continue;
    4380            0 :             }
    4381              : 
    4382            0 :             if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
    4383            0 :                 tracing::info!("Waiting for shard {tenant_shard_id} to reconcile, in order to ensure it is attached");
    4384            0 :                 waiters.push(waiter);
    4385            0 :             }
    4386              :         }
    4387            0 :         Ok(waiters)
    4388            0 :     }
    4389              : 
    4390            0 :     async fn ensure_attached_wait(&self, tenant_id: TenantId) -> Result<(), ApiError> {
    4391            0 :         let ensure_waiters = {
    4392            0 :             let locked = self.inner.write().unwrap();
    4393              : 
    4394              :             // Check if the tenant is splitting: in this case, even if it is attached,
    4395              :             // we must act as if it is not: this blocks e.g. timeline creation/deletion
    4396              :             // operations during the split.
    4397            0 :             for (_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
    4398            0 :                 if !matches!(shard.splitting, SplitState::Idle) {
    4399            0 :                     return Err(ApiError::ResourceUnavailable(
    4400            0 :                         "Tenant shards are currently splitting".into(),
    4401            0 :                     ));
    4402            0 :                 }
    4403              :             }
    4404              : 
    4405            0 :             self.ensure_attached_schedule(locked, tenant_id)
    4406            0 :                 .map_err(ApiError::InternalServerError)?
    4407              :         };
    4408              : 
    4409            0 :         let deadline = Instant::now().checked_add(Duration::from_secs(5)).unwrap();
    4410            0 :         for waiter in ensure_waiters {
    4411            0 :             let timeout = deadline.duration_since(Instant::now());
    4412            0 :             waiter.wait_timeout(timeout).await?;
    4413              :         }
    4414              : 
    4415            0 :         Ok(())
    4416            0 :     }
    4417              : 
    4418              :     /// Wrap [`TenantShard`] reconciliation methods with acquisition of [`Gate`] and [`ReconcileUnits`],
    4419            0 :     fn maybe_reconcile_shard(
    4420            0 :         &self,
    4421            0 :         shard: &mut TenantShard,
    4422            0 :         nodes: &Arc<HashMap<NodeId, Node>>,
    4423            0 :     ) -> Option<ReconcilerWaiter> {
    4424            0 :         let reconcile_needed = shard.get_reconcile_needed(nodes);
    4425            0 : 
    4426            0 :         match reconcile_needed {
    4427            0 :             ReconcileNeeded::No => return None,
    4428            0 :             ReconcileNeeded::WaitExisting(waiter) => return Some(waiter),
    4429            0 :             ReconcileNeeded::Yes => {
    4430            0 :                 // Fall through to try and acquire units for spawning reconciler
    4431            0 :             }
    4432              :         };
    4433              : 
    4434            0 :         let units = match self.reconciler_concurrency.clone().try_acquire_owned() {
    4435            0 :             Ok(u) => ReconcileUnits::new(u),
    4436              :             Err(_) => {
    4437            0 :                 tracing::info!(tenant_id=%shard.tenant_shard_id.tenant_id, shard_id=%shard.tenant_shard_id.shard_slug(),
    4438            0 :                     "Concurrency limited: enqueued for reconcile later");
    4439            0 :                 if !shard.delayed_reconcile {
    4440            0 :                     match self.delayed_reconcile_tx.try_send(shard.tenant_shard_id) {
    4441            0 :                         Err(TrySendError::Closed(_)) => {
    4442            0 :                             // Weird mid-shutdown case?
    4443            0 :                         }
    4444              :                         Err(TrySendError::Full(_)) => {
    4445              :                             // It is safe to skip sending our ID in the channel: we will eventually get retried by the background reconcile task.
    4446            0 :                             tracing::warn!(
    4447            0 :                                 "Many shards are waiting to reconcile: delayed_reconcile queue is full"
    4448              :                             );
    4449              :                         }
    4450            0 :                         Ok(()) => {
    4451            0 :                             shard.delayed_reconcile = true;
    4452            0 :                         }
    4453              :                     }
    4454            0 :                 }
    4455              : 
    4456              :                 // We won't spawn a reconciler, but we will construct a waiter that waits for the shard's sequence
    4457              :                 // number to advance.  When this function is eventually called again and succeeds in getting units,
    4458              :                 // it will spawn a reconciler that makes this waiter complete.
    4459            0 :                 return Some(shard.future_reconcile_waiter());
    4460              :             }
    4461              :         };
    4462              : 
    4463            0 :         let Ok(gate_guard) = self.gate.enter() else {
    4464              :             // Gate closed: we're shutting down, drop out.
    4465            0 :             return None;
    4466              :         };
    4467              : 
    4468            0 :         shard.spawn_reconciler(
    4469            0 :             &self.result_tx,
    4470            0 :             nodes,
    4471            0 :             &self.compute_hook,
    4472            0 :             &self.config,
    4473            0 :             &self.persistence,
    4474            0 :             units,
    4475            0 :             gate_guard,
    4476            0 :             &self.cancel,
    4477            0 :         )
    4478            0 :     }
    4479              : 
    4480              :     /// Check all tenants for pending reconciliation work, and reconcile those in need.
    4481              :     /// Additionally, reschedule tenants that require it.
    4482              :     ///
    4483              :     /// Returns how many reconciliation tasks were started, or `1` if no reconciles were
    4484              :     /// spawned but some _would_ have been spawned if `reconciler_concurrency` units where
    4485              :     /// available.  A return value of 0 indicates that everything is fully reconciled already.
    4486            0 :     fn reconcile_all(&self) -> usize {
    4487            0 :         let mut locked = self.inner.write().unwrap();
    4488            0 :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    4489            0 :         let pageservers = nodes.clone();
    4490            0 : 
    4491            0 :         let mut schedule_context = ScheduleContext::default();
    4492            0 : 
    4493            0 :         let mut reconciles_spawned = 0;
    4494            0 :         for (tenant_shard_id, shard) in tenants.iter_mut() {
    4495            0 :             if tenant_shard_id.is_shard_zero() {
    4496            0 :                 schedule_context = ScheduleContext::default();
    4497            0 :             }
    4498              : 
    4499              :             // Skip checking if this shard is already enqueued for reconciliation
    4500            0 :             if shard.delayed_reconcile && self.reconciler_concurrency.available_permits() == 0 {
    4501              :                 // If there is something delayed, then return a nonzero count so that
    4502              :                 // callers like reconcile_all_now do not incorrectly get the impression
    4503              :                 // that the system is in a quiescent state.
    4504            0 :                 reconciles_spawned = std::cmp::max(1, reconciles_spawned);
    4505            0 :                 continue;
    4506            0 :             }
    4507            0 : 
    4508            0 :             // Eventual consistency: if an earlier reconcile job failed, and the shard is still
    4509            0 :             // dirty, spawn another rone
    4510            0 :             if self.maybe_reconcile_shard(shard, &pageservers).is_some() {
    4511            0 :                 reconciles_spawned += 1;
    4512            0 :             }
    4513              : 
    4514            0 :             schedule_context.avoid(&shard.intent.all_pageservers());
    4515              :         }
    4516              : 
    4517            0 :         reconciles_spawned
    4518            0 :     }
    4519              : 
    4520              :     /// `optimize` in this context means identifying shards which have valid scheduled locations, but
    4521              :     /// could be scheduled somewhere better:
    4522              :     /// - Cutting over to a secondary if the node with the secondary is more lightly loaded
    4523              :     ///    * e.g. after a node fails then recovers, to move some work back to it
    4524              :     /// - Cutting over to a secondary if it improves the spread of shard attachments within a tenant
    4525              :     ///    * e.g. after a shard split, the initial attached locations will all be on the node where
    4526              :     ///      we did the split, but are probably better placed elsewhere.
    4527              :     /// - Creating new secondary locations if it improves the spreading of a sharded tenant
    4528              :     ///    * e.g. after a shard split, some locations will be on the same node (where the split
    4529              :     ///     happened), and will probably be better placed elsewhere.
    4530              :     ///
    4531              :     /// To put it more briefly: whereas the scheduler respects soft constraints in a ScheduleContext at
    4532              :     /// the time of scheduling, this function looks for cases where a better-scoring location is available
    4533              :     /// according to those same soft constraints.
    4534            0 :     async fn optimize_all(&self) -> usize {
    4535            0 :         // Limit on how many shards' optmizations each call to this function will execute.  Combined
    4536            0 :         // with the frequency of background calls, this acts as an implicit rate limit that runs a small
    4537            0 :         // trickle of optimizations in the background, rather than executing a large number in parallel
    4538            0 :         // when a change occurs.
    4539            0 :         const MAX_OPTIMIZATIONS_EXEC_PER_PASS: usize = 2;
    4540            0 : 
    4541            0 :         // Synchronous prepare: scan shards for possible scheduling optimizations
    4542            0 :         let candidate_work = self.optimize_all_plan();
    4543            0 :         let candidate_work_len = candidate_work.len();
    4544              : 
    4545              :         // Asynchronous validate: I/O to pageservers to make sure shards are in a good state to apply validation
    4546            0 :         let validated_work = self.optimize_all_validate(candidate_work).await;
    4547              : 
    4548            0 :         let was_work_filtered = validated_work.len() != candidate_work_len;
    4549            0 : 
    4550            0 :         // Synchronous apply: update the shards' intent states according to validated optimisations
    4551            0 :         let mut reconciles_spawned = 0;
    4552            0 :         let mut optimizations_applied = 0;
    4553            0 :         let mut locked = self.inner.write().unwrap();
    4554            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    4555            0 :         for (tenant_shard_id, optimization) in validated_work {
    4556            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    4557              :                 // Shard was dropped between planning and execution;
    4558            0 :                 continue;
    4559              :             };
    4560            0 :             if shard.apply_optimization(scheduler, optimization) {
    4561            0 :                 optimizations_applied += 1;
    4562            0 :                 if self.maybe_reconcile_shard(shard, nodes).is_some() {
    4563            0 :                     reconciles_spawned += 1;
    4564            0 :                 }
    4565            0 :             }
    4566              : 
    4567            0 :             if optimizations_applied >= MAX_OPTIMIZATIONS_EXEC_PER_PASS {
    4568            0 :                 break;
    4569            0 :             }
    4570              :         }
    4571              : 
    4572            0 :         if was_work_filtered {
    4573            0 :             // If we filtered any work out during validation, ensure we return a nonzero value to indicate
    4574            0 :             // to callers that the system is not in a truly quiet state, it's going to do some work as soon
    4575            0 :             // as these validations start passing.
    4576            0 :             reconciles_spawned = std::cmp::max(reconciles_spawned, 1);
    4577            0 :         }
    4578              : 
    4579            0 :         reconciles_spawned
    4580            0 :     }
    4581              : 
    4582            0 :     fn optimize_all_plan(&self) -> Vec<(TenantShardId, ScheduleOptimization)> {
    4583            0 :         let mut schedule_context = ScheduleContext::default();
    4584            0 : 
    4585            0 :         let mut tenant_shards: Vec<&TenantShard> = Vec::new();
    4586            0 : 
    4587            0 :         // How many candidate optimizations we will generate, before evaluating them for readniess: setting
    4588            0 :         // this higher than the execution limit gives us a chance to execute some work even if the first
    4589            0 :         // few optimizations we find are not ready.
    4590            0 :         const MAX_OPTIMIZATIONS_PLAN_PER_PASS: usize = 8;
    4591            0 : 
    4592            0 :         let mut work = Vec::new();
    4593            0 : 
    4594            0 :         let mut locked = self.inner.write().unwrap();
    4595            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    4596            0 :         for (tenant_shard_id, shard) in tenants.iter() {
    4597            0 :             if tenant_shard_id.is_shard_zero() {
    4598            0 :                 // Reset accumulators on the first shard in a tenant
    4599            0 :                 schedule_context = ScheduleContext::default();
    4600            0 :                 schedule_context.mode = ScheduleMode::Speculative;
    4601            0 :                 tenant_shards.clear();
    4602            0 :             }
    4603              : 
    4604            0 :             if work.len() >= MAX_OPTIMIZATIONS_PLAN_PER_PASS {
    4605            0 :                 break;
    4606            0 :             }
    4607            0 : 
    4608            0 :             match shard.get_scheduling_policy() {
    4609            0 :                 ShardSchedulingPolicy::Active => {
    4610            0 :                     // Ok to do optimization
    4611            0 :                 }
    4612              :                 ShardSchedulingPolicy::Essential
    4613              :                 | ShardSchedulingPolicy::Pause
    4614              :                 | ShardSchedulingPolicy::Stop => {
    4615              :                     // Policy prevents optimizing this shard.
    4616            0 :                     continue;
    4617              :                 }
    4618              :             }
    4619              : 
    4620              :             // Accumulate the schedule context for all the shards in a tenant: we must have
    4621              :             // the total view of all shards before we can try to optimize any of them.
    4622            0 :             schedule_context.avoid(&shard.intent.all_pageservers());
    4623            0 :             if let Some(attached) = shard.intent.get_attached() {
    4624            0 :                 schedule_context.push_attached(*attached);
    4625            0 :             }
    4626            0 :             tenant_shards.push(shard);
    4627            0 : 
    4628            0 :             // Once we have seen the last shard in the tenant, proceed to search across all shards
    4629            0 :             // in the tenant for optimizations
    4630            0 :             if shard.shard.number.0 == shard.shard.count.count() - 1 {
    4631            0 :                 if tenant_shards.iter().any(|s| s.reconciler.is_some()) {
    4632              :                     // Do not start any optimizations while another change to the tenant is ongoing: this
    4633              :                     // is not necessary for correctness, but simplifies operations and implicitly throttles
    4634              :                     // optimization changes to happen in a "trickle" over time.
    4635            0 :                     continue;
    4636            0 :                 }
    4637            0 : 
    4638            0 :                 if tenant_shards.iter().any(|s| {
    4639            0 :                     !matches!(s.splitting, SplitState::Idle)
    4640            0 :                         || matches!(s.policy, PlacementPolicy::Detached)
    4641            0 :                 }) {
    4642              :                     // Never attempt to optimize a tenant that is currently being split, or
    4643              :                     // a tenant that is meant to be detached
    4644            0 :                     continue;
    4645            0 :                 }
    4646              : 
    4647              :                 // TODO: optimization calculations are relatively expensive: create some fast-path for
    4648              :                 // the common idle case (avoiding the search on tenants that we have recently checked)
    4649              : 
    4650            0 :                 for shard in &tenant_shards {
    4651            0 :                     if let Some(optimization) =
    4652              :                         // If idle, maybe ptimize attachments: if a shard has a secondary location that is preferable to
    4653              :                         // its primary location based on soft constraints, cut it over.
    4654            0 :                         shard.optimize_attachment(nodes, &schedule_context)
    4655              :                     {
    4656            0 :                         work.push((shard.tenant_shard_id, optimization));
    4657            0 :                         break;
    4658            0 :                     } else if let Some(optimization) =
    4659              :                         // If idle, maybe optimize secondary locations: if a shard has a secondary location that would be
    4660              :                         // better placed on another node, based on ScheduleContext, then adjust it.  This
    4661              :                         // covers cases like after a shard split, where we might have too many shards
    4662              :                         // in the same tenant with secondary locations on the node where they originally split.
    4663            0 :                         shard.optimize_secondary(scheduler, &schedule_context)
    4664              :                     {
    4665            0 :                         work.push((shard.tenant_shard_id, optimization));
    4666            0 :                         break;
    4667            0 :                     }
    4668              : 
    4669              :                     // TODO: extend this mechanism to prefer attaching on nodes with fewer attached
    4670              :                     // tenants (i.e. extend schedule state to distinguish attached from secondary counts),
    4671              :                     // for the total number of attachments on a node (not just within a tenant.)
    4672              :                 }
    4673            0 :             }
    4674              :         }
    4675              : 
    4676            0 :         work
    4677            0 :     }
    4678              : 
    4679            0 :     async fn optimize_all_validate(
    4680            0 :         &self,
    4681            0 :         candidate_work: Vec<(TenantShardId, ScheduleOptimization)>,
    4682            0 :     ) -> Vec<(TenantShardId, ScheduleOptimization)> {
    4683            0 :         // Take a clone of the node map to use outside the lock in async validation phase
    4684            0 :         let validation_nodes = { self.inner.read().unwrap().nodes.clone() };
    4685            0 : 
    4686            0 :         let mut want_secondary_status = Vec::new();
    4687            0 : 
    4688            0 :         // Validate our plans: this is an async phase where we may do I/O to pageservers to
    4689            0 :         // check that the state of locations is acceptable to run the optimization, such as
    4690            0 :         // checking that a secondary location is sufficiently warmed-up to cleanly cut over
    4691            0 :         // in a live migration.
    4692            0 :         let mut validated_work = Vec::new();
    4693            0 :         for (tenant_shard_id, optimization) in candidate_work {
    4694            0 :             match optimization.action {
    4695              :                 ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    4696              :                     old_attached_node_id: _,
    4697            0 :                     new_attached_node_id,
    4698            0 :                 }) => {
    4699            0 :                     match validation_nodes.get(&new_attached_node_id) {
    4700            0 :                         None => {
    4701            0 :                             // Node was dropped between planning and validation
    4702            0 :                         }
    4703            0 :                         Some(node) => {
    4704            0 :                             if !node.is_available() {
    4705            0 :                                 tracing::info!("Skipping optimization migration of {tenant_shard_id} to {new_attached_node_id} because node unavailable");
    4706            0 :                             } else {
    4707            0 :                                 // Accumulate optimizations that require fetching secondary status, so that we can execute these
    4708            0 :                                 // remote API requests concurrently.
    4709            0 :                                 want_secondary_status.push((
    4710            0 :                                     tenant_shard_id,
    4711            0 :                                     node.clone(),
    4712            0 :                                     optimization,
    4713            0 :                                 ));
    4714            0 :                             }
    4715              :                         }
    4716              :                     }
    4717              :                 }
    4718              :                 ScheduleOptimizationAction::ReplaceSecondary(_) => {
    4719              :                     // No extra checks needed to replace a secondary: this does not interrupt client access
    4720            0 :                     validated_work.push((tenant_shard_id, optimization))
    4721              :                 }
    4722              :             };
    4723              :         }
    4724              : 
    4725              :         // Call into pageserver API to find out if the destination secondary location is warm enough for a reasonably smooth migration: we
    4726              :         // do this so that we avoid spawning a Reconciler that would have to wait minutes/hours for a destination to warm up: that reconciler
    4727              :         // would hold a precious reconcile semaphore unit the whole time it was waiting for the destination to warm up.
    4728            0 :         let results = self
    4729            0 :             .tenant_for_shards_api(
    4730            0 :                 want_secondary_status
    4731            0 :                     .iter()
    4732            0 :                     .map(|i| (i.0, i.1.clone()))
    4733            0 :                     .collect(),
    4734            0 :                 |tenant_shard_id, client| async move {
    4735            0 :                     client.tenant_secondary_status(tenant_shard_id).await
    4736            0 :                 },
    4737            0 :                 1,
    4738            0 :                 1,
    4739            0 :                 SHORT_RECONCILE_TIMEOUT,
    4740            0 :                 &self.cancel,
    4741            0 :             )
    4742            0 :             .await;
    4743              : 
    4744            0 :         for ((tenant_shard_id, node, optimization), secondary_status) in
    4745            0 :             want_secondary_status.into_iter().zip(results.into_iter())
    4746              :         {
    4747            0 :             match secondary_status {
    4748            0 :                 Err(e) => {
    4749            0 :                     tracing::info!("Skipping migration of {tenant_shard_id} to {node}, error querying secondary: {e}");
    4750              :                 }
    4751            0 :                 Ok(progress) => {
    4752            0 :                     // We require secondary locations to have less than 10GiB of downloads pending before we will use
    4753            0 :                     // them in an optimization
    4754            0 :                     const DOWNLOAD_FRESHNESS_THRESHOLD: u64 = 10 * 1024 * 1024 * 1024;
    4755            0 : 
    4756            0 :                     if progress.heatmap_mtime.is_none()
    4757            0 :                         || progress.bytes_total < DOWNLOAD_FRESHNESS_THRESHOLD
    4758            0 :                             && progress.bytes_downloaded != progress.bytes_total
    4759            0 :                         || progress.bytes_total - progress.bytes_downloaded
    4760            0 :                             > DOWNLOAD_FRESHNESS_THRESHOLD
    4761              :                     {
    4762            0 :                         tracing::info!("Skipping migration of {tenant_shard_id} to {node} because secondary isn't ready: {progress:?}");
    4763              :                     } else {
    4764              :                         // Location looks ready: proceed
    4765            0 :                         tracing::info!(
    4766            0 :                             "{tenant_shard_id} secondary on {node} is warm enough for migration: {progress:?}"
    4767              :                         );
    4768            0 :                         validated_work.push((tenant_shard_id, optimization))
    4769              :                     }
    4770              :                 }
    4771              :             }
    4772              :         }
    4773              : 
    4774            0 :         validated_work
    4775            0 :     }
    4776              : 
    4777              :     /// Look for shards which are oversized and in need of splitting
    4778            0 :     async fn autosplit_tenants(self: &Arc<Self>) {
    4779            0 :         let Some(split_threshold) = self.config.split_threshold else {
    4780              :             // Auto-splitting is disabled
    4781            0 :             return;
    4782              :         };
    4783              : 
    4784            0 :         let nodes = self.inner.read().unwrap().nodes.clone();
    4785            0 : 
    4786            0 :         const SPLIT_TO_MAX: ShardCount = ShardCount::new(8);
    4787            0 : 
    4788            0 :         let mut top_n = Vec::new();
    4789            0 : 
    4790            0 :         // Call into each node to look for big tenants
    4791            0 :         let top_n_request = TopTenantShardsRequest {
    4792            0 :             // We currently split based on logical size, for simplicity: logical size is a signal of
    4793            0 :             // the user's intent to run a large database, whereas physical/resident size can be symptoms
    4794            0 :             // of compaction issues.  Eventually we should switch to using resident size to bound the
    4795            0 :             // disk space impact of one shard.
    4796            0 :             order_by: models::TenantSorting::MaxLogicalSize,
    4797            0 :             limit: 10,
    4798            0 :             where_shards_lt: Some(SPLIT_TO_MAX),
    4799            0 :             where_gt: Some(split_threshold),
    4800            0 :         };
    4801            0 :         for node in nodes.values() {
    4802            0 :             let request_ref = &top_n_request;
    4803            0 :             match node
    4804            0 :                 .with_client_retries(
    4805            0 :                     |client| async move {
    4806            0 :                         let request = request_ref.clone();
    4807            0 :                         client.top_tenant_shards(request.clone()).await
    4808            0 :                     },
    4809            0 :                     &self.config.jwt_token,
    4810            0 :                     3,
    4811            0 :                     3,
    4812            0 :                     Duration::from_secs(5),
    4813            0 :                     &self.cancel,
    4814            0 :                 )
    4815            0 :                 .await
    4816              :             {
    4817            0 :                 Some(Ok(node_top_n)) => {
    4818            0 :                     top_n.extend(node_top_n.shards.into_iter());
    4819            0 :                 }
    4820              :                 Some(Err(mgmt_api::Error::Cancelled)) => {
    4821            0 :                     continue;
    4822              :                 }
    4823            0 :                 Some(Err(e)) => {
    4824            0 :                     tracing::warn!("Failed to fetch top N tenants from {node}: {e}");
    4825            0 :                     continue;
    4826              :                 }
    4827              :                 None => {
    4828              :                     // Node is shutting down
    4829            0 :                     continue;
    4830              :                 }
    4831              :             };
    4832              :         }
    4833              : 
    4834              :         // Pick the biggest tenant to split first
    4835            0 :         top_n.sort_by_key(|i| i.resident_size);
    4836            0 :         let Some(split_candidate) = top_n.into_iter().next() else {
    4837            0 :             tracing::debug!("No split-elegible shards found");
    4838            0 :             return;
    4839              :         };
    4840              : 
    4841              :         // We spawn a task to run this, so it's exactly like some external API client requesting it.  We don't
    4842              :         // want to block the background reconcile loop on this.
    4843            0 :         tracing::info!("Auto-splitting tenant for size threshold {split_threshold}: current size {split_candidate:?}");
    4844              : 
    4845            0 :         let this = self.clone();
    4846            0 :         tokio::spawn(
    4847            0 :             async move {
    4848            0 :                 match this
    4849            0 :                     .tenant_shard_split(
    4850            0 :                         split_candidate.id.tenant_id,
    4851            0 :                         TenantShardSplitRequest {
    4852            0 :                             // Always split to the max number of shards: this avoids stepping through
    4853            0 :                             // intervening shard counts and encountering the overrhead of a split+cleanup
    4854            0 :                             // each time as a tenant grows, and is not too expensive because our max shard
    4855            0 :                             // count is relatively low anyway.
    4856            0 :                             // This policy will be adjusted in future once we support higher shard count.
    4857            0 :                             new_shard_count: SPLIT_TO_MAX.literal(),
    4858            0 :                             new_stripe_size: Some(ShardParameters::DEFAULT_STRIPE_SIZE),
    4859            0 :                         },
    4860            0 :                     )
    4861            0 :                     .await
    4862              :                 {
    4863              :                     Ok(_) => {
    4864            0 :                         tracing::info!("Successful auto-split");
    4865              :                     }
    4866            0 :                     Err(e) => {
    4867            0 :                         tracing::error!("Auto-split failed: {e}");
    4868              :                     }
    4869              :                 }
    4870            0 :             }
    4871            0 :             .instrument(tracing::info_span!("auto_split", tenant_id=%split_candidate.id.tenant_id)),
    4872              :         );
    4873            0 :     }
    4874              : 
    4875              :     /// Useful for tests: run whatever work a background [`Self::reconcile_all`] would have done, but
    4876              :     /// also wait for any generated Reconcilers to complete.  Calling this until it returns zero should
    4877              :     /// put the system into a quiescent state where future background reconciliations won't do anything.
    4878            0 :     pub(crate) async fn reconcile_all_now(&self) -> Result<usize, ReconcileWaitError> {
    4879            0 :         let reconciles_spawned = self.reconcile_all();
    4880            0 :         let reconciles_spawned = if reconciles_spawned == 0 {
    4881              :             // Only optimize when we are otherwise idle
    4882            0 :             self.optimize_all().await
    4883              :         } else {
    4884            0 :             reconciles_spawned
    4885              :         };
    4886              : 
    4887            0 :         let waiters = {
    4888            0 :             let mut waiters = Vec::new();
    4889            0 :             let locked = self.inner.read().unwrap();
    4890            0 :             for (_tenant_shard_id, shard) in locked.tenants.iter() {
    4891            0 :                 if let Some(waiter) = shard.get_waiter() {
    4892            0 :                     waiters.push(waiter);
    4893            0 :                 }
    4894              :             }
    4895            0 :             waiters
    4896            0 :         };
    4897            0 : 
    4898            0 :         let waiter_count = waiters.len();
    4899            0 :         match self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    4900            0 :             Ok(()) => {}
    4901            0 :             Err(ReconcileWaitError::Failed(_, reconcile_error))
    4902            0 :                 if matches!(*reconcile_error, ReconcileError::Cancel) =>
    4903            0 :             {
    4904            0 :                 // Ignore reconciler cancel errors: this reconciler might have shut down
    4905            0 :                 // because some other change superceded it.  We will return a nonzero number,
    4906            0 :                 // so the caller knows they might have to call again to quiesce the system.
    4907            0 :             }
    4908            0 :             Err(e) => {
    4909            0 :                 return Err(e);
    4910              :             }
    4911              :         };
    4912              : 
    4913            0 :         tracing::info!(
    4914            0 :             "{} reconciles in reconcile_all, {} waiters",
    4915              :             reconciles_spawned,
    4916              :             waiter_count
    4917              :         );
    4918              : 
    4919            0 :         Ok(std::cmp::max(waiter_count, reconciles_spawned))
    4920            0 :     }
    4921              : 
    4922            0 :     pub async fn shutdown(&self) {
    4923            0 :         // Note that this already stops processing any results from reconciles: so
    4924            0 :         // we do not expect that our [`TenantShard`] objects will reach a neat
    4925            0 :         // final state.
    4926            0 :         self.cancel.cancel();
    4927            0 : 
    4928            0 :         // The cancellation tokens in [`crate::reconciler::Reconciler`] are children
    4929            0 :         // of our cancellation token, so we do not need to explicitly cancel each of
    4930            0 :         // them.
    4931            0 : 
    4932            0 :         // Background tasks and reconcilers hold gate guards: this waits for them all
    4933            0 :         // to complete.
    4934            0 :         self.gate.close().await;
    4935            0 :     }
    4936              : }
        

Generated by: LCOV version 2.1-beta