LCOV - code coverage report
Current view: top level - pageserver/src/tenant - mgr.rs (source / functions) Coverage Total Hit
Test: 49aa928ec5b4b510172d8b5c6d154da28e70a46c.info Lines: 16.5 % 1284 212
Test Date: 2024-11-13 18:23:39 Functions: 10.6 % 161 17

            Line data    Source code
       1              : //! This module acts as a switchboard to access different repositories managed by this
       2              : //! page server.
       3              : 
       4              : use camino::{Utf8DirEntry, Utf8Path, Utf8PathBuf};
       5              : use futures::StreamExt;
       6              : use itertools::Itertools;
       7              : use pageserver_api::key::Key;
       8              : use pageserver_api::models::LocationConfigMode;
       9              : use pageserver_api::shard::{
      10              :     ShardCount, ShardIdentity, ShardIndex, ShardNumber, ShardStripeSize, TenantShardId,
      11              : };
      12              : use pageserver_api::upcall_api::ReAttachResponseTenant;
      13              : use rand::{distributions::Alphanumeric, Rng};
      14              : use remote_storage::TimeoutOrCancel;
      15              : use std::borrow::Cow;
      16              : use std::cmp::Ordering;
      17              : use std::collections::{BTreeMap, HashMap, HashSet};
      18              : use std::ops::Deref;
      19              : use std::sync::Arc;
      20              : use std::time::Duration;
      21              : use sysinfo::SystemExt;
      22              : use tokio::fs;
      23              : 
      24              : use anyhow::Context;
      25              : use once_cell::sync::Lazy;
      26              : use tokio::task::JoinSet;
      27              : use tokio_util::sync::CancellationToken;
      28              : use tracing::*;
      29              : 
      30              : use utils::{backoff, completion, crashsafe};
      31              : 
      32              : use crate::config::PageServerConf;
      33              : use crate::context::{DownloadBehavior, RequestContext};
      34              : use crate::controller_upcall_client::{
      35              :     ControlPlaneGenerationsApi, ControllerUpcallClient, RetryForeverError,
      36              : };
      37              : use crate::deletion_queue::DeletionQueueClient;
      38              : use crate::http::routes::ACTIVE_TENANT_TIMEOUT;
      39              : use crate::metrics::{TENANT, TENANT_MANAGER as METRICS};
      40              : use crate::task_mgr::{TaskKind, BACKGROUND_RUNTIME};
      41              : use crate::tenant::config::{
      42              :     AttachedLocationConfig, AttachmentMode, LocationConf, LocationMode, SecondaryLocationConfig,
      43              : };
      44              : use crate::tenant::span::debug_assert_current_span_has_tenant_id;
      45              : use crate::tenant::storage_layer::inmemory_layer;
      46              : use crate::tenant::timeline::ShutdownMode;
      47              : use crate::tenant::{AttachedTenantConf, GcError, LoadConfigError, SpawnMode, Tenant, TenantState};
      48              : use crate::virtual_file::MaybeFatalIo;
      49              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX};
      50              : 
      51              : use utils::crashsafe::path_with_suffix_extension;
      52              : use utils::fs_ext::PathExt;
      53              : use utils::generation::Generation;
      54              : use utils::id::{TenantId, TimelineId};
      55              : 
      56              : use super::remote_timeline_client::remote_tenant_path;
      57              : use super::secondary::SecondaryTenant;
      58              : use super::timeline::detach_ancestor::{self, PreparedTimelineDetach};
      59              : use super::{GlobalShutDown, TenantSharedResources};
      60              : 
      61              : /// For a tenant that appears in TenantsMap, it may either be
      62              : /// - `Attached`: has a full Tenant object, is elegible to service
      63              : ///    reads and ingest WAL.
      64              : /// - `Secondary`: is only keeping a local cache warm.
      65              : ///
      66              : /// Secondary is a totally distinct state rather than being a mode of a `Tenant`, because
      67              : /// that way we avoid having to carefully switch a tenant's ingestion etc on and off during
      68              : /// its lifetime, and we can preserve some important safety invariants like `Tenant` always
      69              : /// having a properly acquired generation (Secondary doesn't need a generation)
      70              : #[derive(Clone)]
      71              : pub(crate) enum TenantSlot {
      72              :     Attached(Arc<Tenant>),
      73              :     Secondary(Arc<SecondaryTenant>),
      74              :     /// In this state, other administrative operations acting on the TenantId should
      75              :     /// block, or return a retry indicator equivalent to HTTP 503.
      76              :     InProgress(utils::completion::Barrier),
      77              : }
      78              : 
      79              : impl std::fmt::Debug for TenantSlot {
      80            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      81            0 :         match self {
      82            0 :             Self::Attached(tenant) => write!(f, "Attached({})", tenant.current_state()),
      83            0 :             Self::Secondary(_) => write!(f, "Secondary"),
      84            0 :             Self::InProgress(_) => write!(f, "InProgress"),
      85              :         }
      86            0 :     }
      87              : }
      88              : 
      89              : impl TenantSlot {
      90              :     /// Return the `Tenant` in this slot if attached, else None
      91            0 :     fn get_attached(&self) -> Option<&Arc<Tenant>> {
      92            0 :         match self {
      93            0 :             Self::Attached(t) => Some(t),
      94            0 :             Self::Secondary(_) => None,
      95            0 :             Self::InProgress(_) => None,
      96              :         }
      97            0 :     }
      98              : }
      99              : 
     100              : /// The tenants known to the pageserver.
     101              : /// The enum variants are used to distinguish the different states that the pageserver can be in.
     102              : pub(crate) enum TenantsMap {
     103              :     /// [`init_tenant_mgr`] is not done yet.
     104              :     Initializing,
     105              :     /// [`init_tenant_mgr`] is done, all on-disk tenants have been loaded.
     106              :     /// New tenants can be added using [`tenant_map_acquire_slot`].
     107              :     Open(BTreeMap<TenantShardId, TenantSlot>),
     108              :     /// The pageserver has entered shutdown mode via [`TenantManager::shutdown`].
     109              :     /// Existing tenants are still accessible, but no new tenants can be created.
     110              :     ShuttingDown(BTreeMap<TenantShardId, TenantSlot>),
     111              : }
     112              : 
     113              : /// When resolving a TenantId to a shard, we may be looking for the 0th
     114              : /// shard, or we might be looking for whichever shard holds a particular page.
     115              : #[derive(Copy, Clone)]
     116              : pub(crate) enum ShardSelector {
     117              :     /// Only return the 0th shard, if it is present.  If a non-0th shard is present,
     118              :     /// ignore it.
     119              :     Zero,
     120              :     /// Pick the shard that holds this key
     121              :     Page(Key),
     122              :     /// The shard ID is known: pick the given shard
     123              :     Known(ShardIndex),
     124              : }
     125              : 
     126              : /// A convenience for use with the re_attach ControllerUpcallClient function: rather
     127              : /// than the serializable struct, we build this enum that encapsulates
     128              : /// the invariant that attached tenants always have generations.
     129              : ///
     130              : /// This represents the subset of a LocationConfig that we receive during re-attach.
     131              : pub(crate) enum TenantStartupMode {
     132              :     Attached((AttachmentMode, Generation)),
     133              :     Secondary,
     134              : }
     135              : 
     136              : impl TenantStartupMode {
     137              :     /// Return the generation & mode that should be used when starting
     138              :     /// this tenant.
     139              :     ///
     140              :     /// If this returns None, the re-attach struct is in an invalid state and
     141              :     /// should be ignored in the response.
     142            0 :     fn from_reattach_tenant(rart: ReAttachResponseTenant) -> Option<Self> {
     143            0 :         match (rart.mode, rart.gen) {
     144            0 :             (LocationConfigMode::Detached, _) => None,
     145            0 :             (LocationConfigMode::Secondary, _) => Some(Self::Secondary),
     146            0 :             (LocationConfigMode::AttachedMulti, Some(g)) => {
     147            0 :                 Some(Self::Attached((AttachmentMode::Multi, Generation::new(g))))
     148              :             }
     149            0 :             (LocationConfigMode::AttachedSingle, Some(g)) => {
     150            0 :                 Some(Self::Attached((AttachmentMode::Single, Generation::new(g))))
     151              :             }
     152            0 :             (LocationConfigMode::AttachedStale, Some(g)) => {
     153            0 :                 Some(Self::Attached((AttachmentMode::Stale, Generation::new(g))))
     154              :             }
     155              :             _ => {
     156            0 :                 tracing::warn!(
     157            0 :                     "Received invalid re-attach state for tenant {}: {rart:?}",
     158              :                     rart.id
     159              :                 );
     160            0 :                 None
     161              :             }
     162              :         }
     163            0 :     }
     164              : }
     165              : 
     166              : /// Result type for looking up a TenantId to a specific shard
     167              : pub(crate) enum ShardResolveResult {
     168              :     NotFound,
     169              :     Found(Arc<Tenant>),
     170              :     // Wait for this barrrier, then query again
     171              :     InProgress(utils::completion::Barrier),
     172              : }
     173              : 
     174              : impl TenantsMap {
     175              :     /// Convenience function for typical usage, where we want to get a `Tenant` object, for
     176              :     /// working with attached tenants.  If the TenantId is in the map but in Secondary state,
     177              :     /// None is returned.
     178            0 :     pub(crate) fn get(&self, tenant_shard_id: &TenantShardId) -> Option<&Arc<Tenant>> {
     179            0 :         match self {
     180            0 :             TenantsMap::Initializing => None,
     181            0 :             TenantsMap::Open(m) | TenantsMap::ShuttingDown(m) => {
     182            0 :                 m.get(tenant_shard_id).and_then(|slot| slot.get_attached())
     183              :             }
     184              :         }
     185            0 :     }
     186              : 
     187              :     #[cfg(all(debug_assertions, not(test)))]
     188            0 :     pub(crate) fn len(&self) -> usize {
     189            0 :         match self {
     190            0 :             TenantsMap::Initializing => 0,
     191            0 :             TenantsMap::Open(m) | TenantsMap::ShuttingDown(m) => m.len(),
     192              :         }
     193            0 :     }
     194              : }
     195              : 
     196              : /// Precursor to deletion of a tenant dir: we do a fast rename to a tmp path, and then
     197              : /// the slower actual deletion in the background.
     198              : ///
     199              : /// This is "safe" in that that it won't leave behind a partially deleted directory
     200              : /// at the original path, because we rename with TEMP_FILE_SUFFIX before starting deleting
     201              : /// the contents.
     202              : ///
     203              : /// This is pageserver-specific, as it relies on future processes after a crash to check
     204              : /// for TEMP_FILE_SUFFIX when loading things.
     205            0 : async fn safe_rename_tenant_dir(path: impl AsRef<Utf8Path>) -> std::io::Result<Utf8PathBuf> {
     206            0 :     let parent = path
     207            0 :         .as_ref()
     208            0 :         .parent()
     209            0 :         // It is invalid to call this function with a relative path.  Tenant directories
     210            0 :         // should always have a parent.
     211            0 :         .ok_or(std::io::Error::new(
     212            0 :             std::io::ErrorKind::InvalidInput,
     213            0 :             "Path must be absolute",
     214            0 :         ))?;
     215            0 :     let rand_suffix = rand::thread_rng()
     216            0 :         .sample_iter(&Alphanumeric)
     217            0 :         .take(8)
     218            0 :         .map(char::from)
     219            0 :         .collect::<String>()
     220            0 :         + TEMP_FILE_SUFFIX;
     221            0 :     let tmp_path = path_with_suffix_extension(&path, &rand_suffix);
     222            0 :     fs::rename(path.as_ref(), &tmp_path).await?;
     223            0 :     fs::File::open(parent)
     224            0 :         .await?
     225            0 :         .sync_all()
     226            0 :         .await
     227            0 :         .maybe_fatal_err("safe_rename_tenant_dir")?;
     228            0 :     Ok(tmp_path)
     229            0 : }
     230              : 
     231              : /// See [`Self::spawn`].
     232              : #[derive(Clone, Default)]
     233              : pub struct BackgroundPurges(tokio_util::task::TaskTracker);
     234              : 
     235              : impl BackgroundPurges {
     236              :     /// When we have moved a tenant's content to a temporary directory, we may delete it lazily in
     237              :     /// the background, and thereby avoid blocking any API requests on this deletion completing.
     238              :     ///
     239              :     /// Although we are cleaning up the tenant, this task is not meant to be bound by the lifetime of the tenant in memory.
     240              :     /// Thus the [`BackgroundPurges`] type to keep track of these tasks.
     241            0 :     pub fn spawn(&self, tmp_path: Utf8PathBuf) {
     242            0 :         // because on shutdown we close and wait, we are misusing TaskTracker a bit.
     243            0 :         //
     244            0 :         // so first acquire a token, then check if the tracker has been closed. the tracker might get closed
     245            0 :         // right after, but at least the shutdown will wait for what we are spawning next.
     246            0 :         let token = self.0.token();
     247            0 : 
     248            0 :         if self.0.is_closed() {
     249            0 :             warn!(
     250              :                 %tmp_path,
     251            0 :                 "trying to spawn background purge during shutdown, ignoring"
     252              :             );
     253            0 :             return;
     254            0 :         }
     255              : 
     256            0 :         let span = info_span!(parent: None, "background_purge", %tmp_path);
     257              : 
     258            0 :         let task = move || {
     259            0 :             let _token = token;
     260            0 :             let _entered = span.entered();
     261            0 :             if let Err(error) = std::fs::remove_dir_all(tmp_path.as_path()) {
     262              :                 // should we fatal_io_error here?
     263            0 :                 warn!(%error, "failed to purge tenant directory");
     264            0 :             }
     265            0 :         };
     266              : 
     267            0 :         BACKGROUND_RUNTIME.spawn_blocking(task);
     268            0 :     }
     269              : 
     270              :     /// When this future completes, all background purges have completed.
     271              :     /// The first poll of the future will already lock out new background purges spawned via [`Self::spawn`].
     272              :     ///
     273              :     /// Concurrent calls will coalesce.
     274              :     ///
     275              :     /// # Cancellation-Safety
     276              :     ///
     277              :     /// If this future is dropped before polled to completion, concurrent and subsequent
     278              :     /// instances of this future will continue to be correct.
     279            0 :     #[instrument(skip_all)]
     280              :     pub async fn shutdown(&self) {
     281              :         // forbid new tasks (can be called many times)
     282              :         self.0.close();
     283              :         self.0.wait().await;
     284              :     }
     285              : }
     286              : 
     287              : static TENANTS: Lazy<std::sync::RwLock<TenantsMap>> =
     288            2 :     Lazy::new(|| std::sync::RwLock::new(TenantsMap::Initializing));
     289              : 
     290              : /// Responsible for storing and mutating the collection of all tenants
     291              : /// that this pageserver has state for.
     292              : ///
     293              : /// Every Tenant and SecondaryTenant instance lives inside the TenantManager.
     294              : ///
     295              : /// The most important role of the TenantManager is to prevent conflicts: e.g. trying to attach
     296              : /// the same tenant twice concurrently, or trying to configure the same tenant into secondary
     297              : /// and attached modes concurrently.
     298              : pub struct TenantManager {
     299              :     conf: &'static PageServerConf,
     300              :     // TODO: currently this is a &'static pointing to TENANTs.  When we finish refactoring
     301              :     // out of that static variable, the TenantManager can own this.
     302              :     // See https://github.com/neondatabase/neon/issues/5796
     303              :     tenants: &'static std::sync::RwLock<TenantsMap>,
     304              :     resources: TenantSharedResources,
     305              : 
     306              :     // Long-running operations that happen outside of a [`Tenant`] lifetime should respect this token.
     307              :     // This is for edge cases like tenant deletion.  In normal cases (within a Tenant lifetime),
     308              :     // tenants have their own cancellation tokens, which we fire individually in [`Self::shutdown`], or
     309              :     // when the tenant detaches.
     310              :     cancel: CancellationToken,
     311              : 
     312              :     background_purges: BackgroundPurges,
     313              : }
     314              : 
     315            0 : fn emergency_generations(
     316            0 :     tenant_confs: &HashMap<TenantShardId, Result<LocationConf, LoadConfigError>>,
     317            0 : ) -> HashMap<TenantShardId, TenantStartupMode> {
     318            0 :     tenant_confs
     319            0 :         .iter()
     320            0 :         .filter_map(|(tid, lc)| {
     321            0 :             let lc = match lc {
     322            0 :                 Ok(lc) => lc,
     323            0 :                 Err(_) => return None,
     324              :             };
     325              :             Some((
     326            0 :                 *tid,
     327            0 :                 match &lc.mode {
     328            0 :                     LocationMode::Attached(alc) => {
     329            0 :                         TenantStartupMode::Attached((alc.attach_mode, alc.generation))
     330              :                     }
     331            0 :                     LocationMode::Secondary(_) => TenantStartupMode::Secondary,
     332              :                 },
     333              :             ))
     334            0 :         })
     335            0 :         .collect()
     336            0 : }
     337              : 
     338            0 : async fn init_load_generations(
     339            0 :     conf: &'static PageServerConf,
     340            0 :     tenant_confs: &HashMap<TenantShardId, Result<LocationConf, LoadConfigError>>,
     341            0 :     resources: &TenantSharedResources,
     342            0 :     cancel: &CancellationToken,
     343            0 : ) -> anyhow::Result<Option<HashMap<TenantShardId, TenantStartupMode>>> {
     344            0 :     let generations = if conf.control_plane_emergency_mode {
     345            0 :         error!(
     346            0 :             "Emergency mode!  Tenants will be attached unsafely using their last known generation"
     347              :         );
     348            0 :         emergency_generations(tenant_confs)
     349            0 :     } else if let Some(client) = ControllerUpcallClient::new(conf, cancel) {
     350            0 :         info!("Calling control plane API to re-attach tenants");
     351              :         // If we are configured to use the control plane API, then it is the source of truth for what tenants to load.
     352            0 :         match client.re_attach(conf).await {
     353            0 :             Ok(tenants) => tenants
     354            0 :                 .into_iter()
     355            0 :                 .flat_map(|(id, rart)| {
     356            0 :                     TenantStartupMode::from_reattach_tenant(rart).map(|tsm| (id, tsm))
     357            0 :                 })
     358            0 :                 .collect(),
     359              :             Err(RetryForeverError::ShuttingDown) => {
     360            0 :                 anyhow::bail!("Shut down while waiting for control plane re-attach response")
     361              :             }
     362              :         }
     363              :     } else {
     364            0 :         info!("Control plane API not configured, tenant generations are disabled");
     365            0 :         return Ok(None);
     366              :     };
     367              : 
     368              :     // The deletion queue needs to know about the startup attachment state to decide which (if any) stored
     369              :     // deletion list entries may still be valid.  We provide that by pushing a recovery operation into
     370              :     // the queue. Sequential processing of te queue ensures that recovery is done before any new tenant deletions
     371              :     // are processed, even though we don't block on recovery completing here.
     372            0 :     let attached_tenants = generations
     373            0 :         .iter()
     374            0 :         .flat_map(|(id, start_mode)| {
     375            0 :             match start_mode {
     376            0 :                 TenantStartupMode::Attached((_mode, generation)) => Some(generation),
     377            0 :                 TenantStartupMode::Secondary => None,
     378              :             }
     379            0 :             .map(|gen| (*id, *gen))
     380            0 :         })
     381            0 :         .collect();
     382            0 :     resources.deletion_queue_client.recover(attached_tenants)?;
     383              : 
     384            0 :     Ok(Some(generations))
     385            0 : }
     386              : 
     387              : /// Given a directory discovered in the pageserver's tenants/ directory, attempt
     388              : /// to load a tenant config from it.
     389              : ///
     390              : /// If we cleaned up something expected (like an empty dir or a temp dir), return None.
     391            0 : fn load_tenant_config(
     392            0 :     conf: &'static PageServerConf,
     393            0 :     tenant_shard_id: TenantShardId,
     394            0 :     dentry: Utf8DirEntry,
     395            0 : ) -> Option<Result<LocationConf, LoadConfigError>> {
     396            0 :     let tenant_dir_path = dentry.path().to_path_buf();
     397            0 :     if crate::is_temporary(&tenant_dir_path) {
     398            0 :         info!("Found temporary tenant directory, removing: {tenant_dir_path}");
     399              :         // No need to use safe_remove_tenant_dir_all because this is already
     400              :         // a temporary path
     401            0 :         std::fs::remove_dir_all(&tenant_dir_path).fatal_err("delete temporary tenant dir");
     402            0 :         return None;
     403            0 :     }
     404            0 : 
     405            0 :     // This case happens if we crash during attachment before writing a config into the dir
     406            0 :     let is_empty = tenant_dir_path
     407            0 :         .is_empty_dir()
     408            0 :         .fatal_err("Checking for empty tenant dir");
     409            0 :     if is_empty {
     410            0 :         info!("removing empty tenant directory {tenant_dir_path:?}");
     411            0 :         std::fs::remove_dir(&tenant_dir_path).fatal_err("delete empty tenant dir");
     412            0 :         return None;
     413            0 :     }
     414            0 : 
     415            0 :     Some(Tenant::load_tenant_config(conf, &tenant_shard_id))
     416            0 : }
     417              : 
     418              : /// Initial stage of load: walk the local tenants directory, clean up any temp files,
     419              : /// and load configurations for the tenants we found.
     420              : ///
     421              : /// Do this in parallel, because we expect 10k+ tenants, so serial execution can take
     422              : /// seconds even on reasonably fast drives.
     423            0 : async fn init_load_tenant_configs(
     424            0 :     conf: &'static PageServerConf,
     425            0 : ) -> HashMap<TenantShardId, Result<LocationConf, LoadConfigError>> {
     426            0 :     let tenants_dir = conf.tenants_path();
     427              : 
     428            0 :     let dentries = tokio::task::spawn_blocking(move || -> Vec<Utf8DirEntry> {
     429            0 :         let context = format!("read tenants dir {tenants_dir}");
     430            0 :         let dir_entries = tenants_dir.read_dir_utf8().fatal_err(&context);
     431            0 : 
     432            0 :         dir_entries
     433            0 :             .collect::<Result<Vec<_>, std::io::Error>>()
     434            0 :             .fatal_err(&context)
     435            0 :     })
     436            0 :     .await
     437            0 :     .expect("Config load task panicked");
     438            0 : 
     439            0 :     let mut configs = HashMap::new();
     440            0 : 
     441            0 :     let mut join_set = JoinSet::new();
     442            0 :     for dentry in dentries {
     443            0 :         let tenant_shard_id = match dentry.file_name().parse::<TenantShardId>() {
     444            0 :             Ok(id) => id,
     445              :             Err(_) => {
     446            0 :                 warn!(
     447            0 :                     "Invalid tenant path (garbage in our repo directory?): '{}'",
     448            0 :                     dentry.file_name()
     449              :                 );
     450            0 :                 continue;
     451              :             }
     452              :         };
     453              : 
     454            0 :         join_set.spawn_blocking(move || {
     455            0 :             (
     456            0 :                 tenant_shard_id,
     457            0 :                 load_tenant_config(conf, tenant_shard_id, dentry),
     458            0 :             )
     459            0 :         });
     460            0 :     }
     461              : 
     462            0 :     while let Some(r) = join_set.join_next().await {
     463            0 :         let (tenant_shard_id, tenant_config) = r.expect("Panic in config load task");
     464            0 :         if let Some(tenant_config) = tenant_config {
     465            0 :             configs.insert(tenant_shard_id, tenant_config);
     466            0 :         }
     467              :     }
     468              : 
     469            0 :     configs
     470            0 : }
     471              : 
     472            0 : #[derive(Debug, thiserror::Error)]
     473              : pub(crate) enum DeleteTenantError {
     474              :     #[error("Tenant map slot error {0}")]
     475              :     SlotError(#[from] TenantSlotError),
     476              : 
     477              :     #[error("Cancelled")]
     478              :     Cancelled,
     479              : 
     480              :     #[error(transparent)]
     481              :     Other(#[from] anyhow::Error),
     482              : }
     483              : 
     484              : /// Initialize repositories with locally available timelines.
     485              : /// Timelines that are only partially available locally (remote storage has more data than this pageserver)
     486              : /// are scheduled for download and added to the tenant once download is completed.
     487            0 : #[instrument(skip_all)]
     488              : pub async fn init_tenant_mgr(
     489              :     conf: &'static PageServerConf,
     490              :     background_purges: BackgroundPurges,
     491              :     resources: TenantSharedResources,
     492              :     init_order: InitializationOrder,
     493              :     cancel: CancellationToken,
     494              : ) -> anyhow::Result<TenantManager> {
     495              :     let mut tenants = BTreeMap::new();
     496              : 
     497              :     let ctx = RequestContext::todo_child(TaskKind::Startup, DownloadBehavior::Warn);
     498              : 
     499              :     // Initialize dynamic limits that depend on system resources
     500              :     let system_memory =
     501              :         sysinfo::System::new_with_specifics(sysinfo::RefreshKind::new().with_memory())
     502              :             .total_memory();
     503              :     let max_ephemeral_layer_bytes =
     504              :         conf.ephemeral_bytes_per_memory_kb as u64 * (system_memory / 1024);
     505              :     tracing::info!("Initialized ephemeral layer size limit to {max_ephemeral_layer_bytes}, for {system_memory} bytes of memory");
     506              :     inmemory_layer::GLOBAL_RESOURCES.max_dirty_bytes.store(
     507              :         max_ephemeral_layer_bytes,
     508              :         std::sync::atomic::Ordering::Relaxed,
     509              :     );
     510              : 
     511              :     // Scan local filesystem for attached tenants
     512              :     let tenant_configs = init_load_tenant_configs(conf).await;
     513              : 
     514              :     // Determine which tenants are to be secondary or attached, and in which generation
     515              :     let tenant_modes = init_load_generations(conf, &tenant_configs, &resources, &cancel).await?;
     516              : 
     517              :     tracing::info!(
     518              :         "Attaching {} tenants at startup, warming up {} at a time",
     519              :         tenant_configs.len(),
     520              :         conf.concurrent_tenant_warmup.initial_permits()
     521              :     );
     522              :     TENANT.startup_scheduled.inc_by(tenant_configs.len() as u64);
     523              : 
     524              :     // Accumulate futures for writing tenant configs, so that we can execute in parallel
     525              :     let mut config_write_futs = Vec::new();
     526              : 
     527              :     // Update the location configs according to the re-attach response and persist them to disk
     528              :     tracing::info!("Updating {} location configs", tenant_configs.len());
     529              :     for (tenant_shard_id, location_conf) in tenant_configs {
     530              :         let tenant_dir_path = conf.tenant_path(&tenant_shard_id);
     531              : 
     532              :         let mut location_conf = match location_conf {
     533              :             Ok(l) => l,
     534              :             Err(e) => {
     535              :                 // This should only happen in the case of a serialization bug or critical local I/O error: we cannot load this tenant
     536              :                 error!(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), "Failed to load tenant config, failed to {e:#}");
     537              :                 continue;
     538              :             }
     539              :         };
     540              : 
     541              :         // FIXME: if we were attached, and get demoted to secondary on re-attach, we
     542              :         // don't have a place to get a config.
     543              :         // (https://github.com/neondatabase/neon/issues/5377)
     544              :         const DEFAULT_SECONDARY_CONF: SecondaryLocationConfig =
     545              :             SecondaryLocationConfig { warm: true };
     546              : 
     547              :         if let Some(tenant_modes) = &tenant_modes {
     548              :             // We have a generation map: treat it as the authority for whether
     549              :             // this tenant is really attached.
     550              :             match tenant_modes.get(&tenant_shard_id) {
     551              :                 None => {
     552              :                     info!(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), "Detaching tenant, control plane omitted it in re-attach response");
     553              : 
     554              :                     match safe_rename_tenant_dir(&tenant_dir_path).await {
     555              :                         Ok(tmp_path) => {
     556              :                             background_purges.spawn(tmp_path);
     557              :                         }
     558              :                         Err(e) => {
     559              :                             error!(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
     560              :                             "Failed to move detached tenant directory '{tenant_dir_path}': {e:?}");
     561              :                         }
     562              :                     };
     563              : 
     564              :                     // We deleted local content: move on to next tenant, don't try and spawn this one.
     565              :                     continue;
     566              :                 }
     567              :                 Some(TenantStartupMode::Secondary) => {
     568              :                     if !matches!(location_conf.mode, LocationMode::Secondary(_)) {
     569              :                         location_conf.mode = LocationMode::Secondary(DEFAULT_SECONDARY_CONF);
     570              :                     }
     571              :                 }
     572              :                 Some(TenantStartupMode::Attached((attach_mode, generation))) => {
     573              :                     let old_gen_higher = match &location_conf.mode {
     574              :                         LocationMode::Attached(AttachedLocationConfig {
     575              :                             generation: old_generation,
     576              :                             attach_mode: _attach_mode,
     577              :                         }) => {
     578              :                             if old_generation > generation {
     579              :                                 Some(old_generation)
     580              :                             } else {
     581              :                                 None
     582              :                             }
     583              :                         }
     584              :                         _ => None,
     585              :                     };
     586              :                     if let Some(old_generation) = old_gen_higher {
     587              :                         tracing::error!(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
     588              :                             "Control plane gave decreasing generation ({generation:?}) in re-attach response for tenant that was attached in generation {:?}, demoting to secondary",
     589              :                             old_generation
     590              :                         );
     591              : 
     592              :                         // We cannot safely attach this tenant given a bogus generation number, but let's avoid throwing away
     593              :                         // local disk content: demote to secondary rather than detaching.
     594              :                         location_conf.mode = LocationMode::Secondary(DEFAULT_SECONDARY_CONF);
     595              :                     } else {
     596              :                         location_conf.attach_in_generation(*attach_mode, *generation);
     597              :                     }
     598              :                 }
     599              :             }
     600              :         } else {
     601              :             // Legacy mode: no generation information, any tenant present
     602              :             // on local disk may activate
     603              :             info!(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), "Starting tenant in legacy mode, no generation",);
     604              :         };
     605              : 
     606              :         // Presence of a generation number implies attachment: attach the tenant
     607              :         // if it wasn't already, and apply the generation number.
     608            0 :         config_write_futs.push(async move {
     609            0 :             let r = Tenant::persist_tenant_config(conf, &tenant_shard_id, &location_conf).await;
     610            0 :             (tenant_shard_id, location_conf, r)
     611            0 :         });
     612              :     }
     613              : 
     614              :     // Execute config writes with concurrency, to avoid bottlenecking on local FS write latency
     615              :     tracing::info!(
     616              :         "Writing {} location config files...",
     617              :         config_write_futs.len()
     618              :     );
     619              :     let config_write_results = futures::stream::iter(config_write_futs)
     620              :         .buffer_unordered(16)
     621              :         .collect::<Vec<_>>()
     622              :         .await;
     623              : 
     624              :     tracing::info!(
     625              :         "Spawning {} tenant shard locations...",
     626              :         config_write_results.len()
     627              :     );
     628              :     // For those shards that have live configurations, construct `Tenant` or `SecondaryTenant` objects and start them running
     629              :     for (tenant_shard_id, location_conf, config_write_result) in config_write_results {
     630              :         // Writing a config to local disk is foundational to startup up tenants: panic if we can't.
     631              :         config_write_result.fatal_err("write tenant shard config file");
     632              : 
     633              :         let tenant_dir_path = conf.tenant_path(&tenant_shard_id);
     634              :         let shard_identity = location_conf.shard;
     635              :         let slot = match location_conf.mode {
     636              :             LocationMode::Attached(attached_conf) => TenantSlot::Attached(
     637              :                 tenant_spawn(
     638              :                     conf,
     639              :                     tenant_shard_id,
     640              :                     &tenant_dir_path,
     641              :                     resources.clone(),
     642              :                     AttachedTenantConf::new(location_conf.tenant_conf, attached_conf),
     643              :                     shard_identity,
     644              :                     Some(init_order.clone()),
     645              :                     SpawnMode::Lazy,
     646              :                     &ctx,
     647              :                 )
     648              :                 .expect("global shutdown during init_tenant_mgr cannot happen"),
     649              :             ),
     650              :             LocationMode::Secondary(secondary_conf) => {
     651              :                 info!(
     652              :                     tenant_id = %tenant_shard_id.tenant_id,
     653              :                     shard_id = %tenant_shard_id.shard_slug(),
     654              :                     "Starting secondary tenant"
     655              :                 );
     656              :                 TenantSlot::Secondary(SecondaryTenant::new(
     657              :                     tenant_shard_id,
     658              :                     shard_identity,
     659              :                     location_conf.tenant_conf,
     660              :                     &secondary_conf,
     661              :                 ))
     662              :             }
     663              :         };
     664              : 
     665              :         METRICS.slot_inserted(&slot);
     666              :         tenants.insert(tenant_shard_id, slot);
     667              :     }
     668              : 
     669              :     info!("Processed {} local tenants at startup", tenants.len());
     670              : 
     671              :     let mut tenants_map = TENANTS.write().unwrap();
     672              :     assert!(matches!(&*tenants_map, &TenantsMap::Initializing));
     673              : 
     674              :     *tenants_map = TenantsMap::Open(tenants);
     675              : 
     676              :     Ok(TenantManager {
     677              :         conf,
     678              :         tenants: &TENANTS,
     679              :         resources,
     680              :         cancel: CancellationToken::new(),
     681              :         background_purges,
     682              :     })
     683              : }
     684              : 
     685              : /// Wrapper for Tenant::spawn that checks invariants before running
     686              : #[allow(clippy::too_many_arguments)]
     687            0 : fn tenant_spawn(
     688            0 :     conf: &'static PageServerConf,
     689            0 :     tenant_shard_id: TenantShardId,
     690            0 :     tenant_path: &Utf8Path,
     691            0 :     resources: TenantSharedResources,
     692            0 :     location_conf: AttachedTenantConf,
     693            0 :     shard_identity: ShardIdentity,
     694            0 :     init_order: Option<InitializationOrder>,
     695            0 :     mode: SpawnMode,
     696            0 :     ctx: &RequestContext,
     697            0 : ) -> Result<Arc<Tenant>, GlobalShutDown> {
     698            0 :     // All these conditions should have been satisfied by our caller: the tenant dir exists, is a well formed
     699            0 :     // path, and contains a configuration file.  Assertions that do synchronous I/O are limited to debug mode
     700            0 :     // to avoid impacting prod runtime performance.
     701            0 :     assert!(!crate::is_temporary(tenant_path));
     702            0 :     debug_assert!(tenant_path.is_dir());
     703            0 :     debug_assert!(conf
     704            0 :         .tenant_location_config_path(&tenant_shard_id)
     705            0 :         .try_exists()
     706            0 :         .unwrap());
     707              : 
     708            0 :     Tenant::spawn(
     709            0 :         conf,
     710            0 :         tenant_shard_id,
     711            0 :         resources,
     712            0 :         location_conf,
     713            0 :         shard_identity,
     714            0 :         init_order,
     715            0 :         mode,
     716            0 :         ctx,
     717            0 :     )
     718            0 : }
     719              : 
     720            2 : async fn shutdown_all_tenants0(tenants: &std::sync::RwLock<TenantsMap>) {
     721            2 :     let mut join_set = JoinSet::new();
     722            0 : 
     723            0 :     #[cfg(all(debug_assertions, not(test)))]
     724            0 :     {
     725            0 :         // Check that our metrics properly tracked the size of the tenants map.  This is a convenient location to check,
     726            0 :         // as it happens implicitly at the end of tests etc.
     727            0 :         let m = tenants.read().unwrap();
     728            0 :         debug_assert_eq!(METRICS.slots_total(), m.len() as u64);
     729              :     }
     730              : 
     731              :     // Atomically, 1. create the shutdown tasks and 2. prevent creation of new tenants.
     732            2 :     let (total_in_progress, total_attached) = {
     733            2 :         let mut m = tenants.write().unwrap();
     734            2 :         match &mut *m {
     735              :             TenantsMap::Initializing => {
     736            0 :                 *m = TenantsMap::ShuttingDown(BTreeMap::default());
     737            0 :                 info!("tenants map is empty");
     738            0 :                 return;
     739              :             }
     740            2 :             TenantsMap::Open(tenants) => {
     741            2 :                 let mut shutdown_state = BTreeMap::new();
     742            2 :                 let mut total_in_progress = 0;
     743            2 :                 let mut total_attached = 0;
     744              : 
     745            2 :                 for (tenant_shard_id, v) in std::mem::take(tenants).into_iter() {
     746            2 :                     match v {
     747            0 :                         TenantSlot::Attached(t) => {
     748            0 :                             shutdown_state.insert(tenant_shard_id, TenantSlot::Attached(t.clone()));
     749            0 :                             join_set.spawn(
     750            0 :                                 async move {
     751            0 :                                     let res = {
     752            0 :                                         let (_guard, shutdown_progress) = completion::channel();
     753            0 :                                         t.shutdown(shutdown_progress, ShutdownMode::FreezeAndFlush).await
     754              :                                     };
     755              : 
     756            0 :                                     if let Err(other_progress) = res {
     757              :                                         // join the another shutdown in progress
     758            0 :                                         other_progress.wait().await;
     759            0 :                                     }
     760              : 
     761              :                                     // we cannot afford per tenant logging here, because if s3 is degraded, we are
     762              :                                     // going to log too many lines
     763            0 :                                     debug!("tenant successfully stopped");
     764            0 :                                 }
     765            0 :                                 .instrument(info_span!("shutdown", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug())),
     766              :                             );
     767              : 
     768            0 :                             total_attached += 1;
     769              :                         }
     770            0 :                         TenantSlot::Secondary(state) => {
     771            0 :                             // We don't need to wait for this individually per-tenant: the
     772            0 :                             // downloader task will be waited on eventually, this cancel
     773            0 :                             // is just to encourage it to drop out if it is doing work
     774            0 :                             // for this tenant right now.
     775            0 :                             state.cancel.cancel();
     776            0 : 
     777            0 :                             shutdown_state.insert(tenant_shard_id, TenantSlot::Secondary(state));
     778            0 :                         }
     779            2 :                         TenantSlot::InProgress(notify) => {
     780            2 :                             // InProgress tenants are not visible in TenantsMap::ShuttingDown: we will
     781            2 :                             // wait for their notifications to fire in this function.
     782            2 :                             join_set.spawn(async move {
     783            2 :                                 notify.wait().await;
     784            2 :                             });
     785            2 : 
     786            2 :                             total_in_progress += 1;
     787            2 :                         }
     788              :                     }
     789              :                 }
     790            2 :                 *m = TenantsMap::ShuttingDown(shutdown_state);
     791            2 :                 (total_in_progress, total_attached)
     792              :             }
     793              :             TenantsMap::ShuttingDown(_) => {
     794            0 :                 error!("already shutting down, this function isn't supposed to be called more than once");
     795            0 :                 return;
     796              :             }
     797              :         }
     798              :     };
     799              : 
     800            2 :     let started_at = std::time::Instant::now();
     801            2 : 
     802            2 :     info!(
     803            0 :         "Waiting for {} InProgress tenants and {} Attached tenants to shut down",
     804              :         total_in_progress, total_attached
     805              :     );
     806              : 
     807            2 :     let total = join_set.len();
     808            2 :     let mut panicked = 0;
     809            2 :     let mut buffering = true;
     810              :     const BUFFER_FOR: std::time::Duration = std::time::Duration::from_millis(500);
     811            2 :     let mut buffered = std::pin::pin!(tokio::time::sleep(BUFFER_FOR));
     812              : 
     813            6 :     while !join_set.is_empty() {
     814            4 :         tokio::select! {
     815            4 :             Some(joined) = join_set.join_next() => {
     816            0 :                 match joined {
     817            2 :                     Ok(()) => {},
     818            0 :                     Err(join_error) if join_error.is_cancelled() => {
     819            0 :                         unreachable!("we are not cancelling any of the tasks");
     820              :                     }
     821            0 :                     Err(join_error) if join_error.is_panic() => {
     822            0 :                         // cannot really do anything, as this panic is likely a bug
     823            0 :                         panicked += 1;
     824            0 :                     }
     825            0 :                     Err(join_error) => {
     826            0 :                         warn!("unknown kind of JoinError: {join_error}");
     827              :                     }
     828              :                 }
     829            2 :                 if !buffering {
     830            2 :                     // buffer so that every 500ms since the first update (or starting) we'll log
     831            2 :                     // how far away we are; this is because we will get SIGKILL'd at 10s, and we
     832            2 :                     // are not able to log *then*.
     833            2 :                     buffering = true;
     834            2 :                     buffered.as_mut().reset(tokio::time::Instant::now() + BUFFER_FOR);
     835            2 :                 }
     836              :             },
     837            4 :             _ = &mut buffered, if buffering => {
     838            2 :                 buffering = false;
     839            2 :                 info!(remaining = join_set.len(), total, elapsed_ms = started_at.elapsed().as_millis(), "waiting for tenants to shutdown");
     840              :             }
     841              :         }
     842              :     }
     843              : 
     844            2 :     if panicked > 0 {
     845            0 :         warn!(
     846              :             panicked,
     847            0 :             total, "observed panicks while shutting down tenants"
     848              :         );
     849            2 :     }
     850              : 
     851              :     // caller will log how long we took
     852            2 : }
     853              : 
     854            0 : #[derive(thiserror::Error, Debug)]
     855              : pub(crate) enum UpsertLocationError {
     856              :     #[error("Bad config request: {0}")]
     857              :     BadRequest(anyhow::Error),
     858              : 
     859              :     #[error("Cannot change config in this state: {0}")]
     860              :     Unavailable(#[from] TenantMapError),
     861              : 
     862              :     #[error("Tenant is already being modified")]
     863              :     InProgress,
     864              : 
     865              :     #[error("Failed to flush: {0}")]
     866              :     Flush(anyhow::Error),
     867              : 
     868              :     /// This error variant is for unexpected situations (soft assertions) where the system is in an unexpected state.
     869              :     #[error("Internal error: {0}")]
     870              :     InternalError(anyhow::Error),
     871              : }
     872              : 
     873              : impl TenantManager {
     874              :     /// Convenience function so that anyone with a TenantManager can get at the global configuration, without
     875              :     /// having to pass it around everywhere as a separate object.
     876            0 :     pub(crate) fn get_conf(&self) -> &'static PageServerConf {
     877            0 :         self.conf
     878            0 :     }
     879              : 
     880              :     /// Gets the attached tenant from the in-memory data, erroring if it's absent, in secondary mode, or currently
     881              :     /// undergoing a state change (i.e. slot is InProgress).
     882              :     ///
     883              :     /// The return Tenant is not guaranteed to be active: check its status after obtaing it, or
     884              :     /// use [`Tenant::wait_to_become_active`] before using it if you will do I/O on it.
     885            0 :     pub(crate) fn get_attached_tenant_shard(
     886            0 :         &self,
     887            0 :         tenant_shard_id: TenantShardId,
     888            0 :     ) -> Result<Arc<Tenant>, GetTenantError> {
     889            0 :         let locked = self.tenants.read().unwrap();
     890              : 
     891            0 :         let peek_slot = tenant_map_peek_slot(&locked, &tenant_shard_id, TenantSlotPeekMode::Read)?;
     892              : 
     893            0 :         match peek_slot {
     894            0 :             Some(TenantSlot::Attached(tenant)) => Ok(Arc::clone(tenant)),
     895            0 :             Some(TenantSlot::InProgress(_)) => Err(GetTenantError::NotActive(tenant_shard_id)),
     896              :             None | Some(TenantSlot::Secondary(_)) => {
     897            0 :                 Err(GetTenantError::NotFound(tenant_shard_id.tenant_id))
     898              :             }
     899              :         }
     900            0 :     }
     901              : 
     902            0 :     pub(crate) fn get_secondary_tenant_shard(
     903            0 :         &self,
     904            0 :         tenant_shard_id: TenantShardId,
     905            0 :     ) -> Option<Arc<SecondaryTenant>> {
     906            0 :         let locked = self.tenants.read().unwrap();
     907            0 : 
     908            0 :         let peek_slot = tenant_map_peek_slot(&locked, &tenant_shard_id, TenantSlotPeekMode::Read)
     909            0 :             .ok()
     910            0 :             .flatten();
     911              : 
     912            0 :         match peek_slot {
     913            0 :             Some(TenantSlot::Secondary(s)) => Some(s.clone()),
     914            0 :             _ => None,
     915              :         }
     916            0 :     }
     917              : 
     918              :     /// Whether the `TenantManager` is responsible for the tenant shard
     919            0 :     pub(crate) fn manages_tenant_shard(&self, tenant_shard_id: TenantShardId) -> bool {
     920            0 :         let locked = self.tenants.read().unwrap();
     921            0 : 
     922            0 :         let peek_slot = tenant_map_peek_slot(&locked, &tenant_shard_id, TenantSlotPeekMode::Read)
     923            0 :             .ok()
     924            0 :             .flatten();
     925            0 : 
     926            0 :         peek_slot.is_some()
     927            0 :     }
     928              : 
     929            0 :     #[instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
     930              :     pub(crate) async fn upsert_location(
     931              :         &self,
     932              :         tenant_shard_id: TenantShardId,
     933              :         new_location_config: LocationConf,
     934              :         flush: Option<Duration>,
     935              :         mut spawn_mode: SpawnMode,
     936              :         ctx: &RequestContext,
     937              :     ) -> Result<Option<Arc<Tenant>>, UpsertLocationError> {
     938              :         debug_assert_current_span_has_tenant_id();
     939              :         info!("configuring tenant location to state {new_location_config:?}");
     940              : 
     941              :         enum FastPathModified {
     942              :             Attached(Arc<Tenant>),
     943              :             Secondary(Arc<SecondaryTenant>),
     944              :         }
     945              : 
     946              :         // Special case fast-path for updates to existing slots: if our upsert is only updating configuration,
     947              :         // then we do not need to set the slot to InProgress, we can just call into the
     948              :         // existng tenant.
     949              :         let fast_path_taken = {
     950              :             let locked = self.tenants.read().unwrap();
     951              :             let peek_slot =
     952              :                 tenant_map_peek_slot(&locked, &tenant_shard_id, TenantSlotPeekMode::Write)?;
     953              :             match (&new_location_config.mode, peek_slot) {
     954              :                 (LocationMode::Attached(attach_conf), Some(TenantSlot::Attached(tenant))) => {
     955              :                     match attach_conf.generation.cmp(&tenant.generation) {
     956              :                         Ordering::Equal => {
     957              :                             // A transition from Attached to Attached in the same generation, we may
     958              :                             // take our fast path and just provide the updated configuration
     959              :                             // to the tenant.
     960              :                             tenant.set_new_location_config(
     961              :                                 AttachedTenantConf::try_from(new_location_config.clone())
     962              :                                     .map_err(UpsertLocationError::BadRequest)?,
     963              :                             );
     964              : 
     965              :                             Some(FastPathModified::Attached(tenant.clone()))
     966              :                         }
     967              :                         Ordering::Less => {
     968              :                             return Err(UpsertLocationError::BadRequest(anyhow::anyhow!(
     969              :                                 "Generation {:?} is less than existing {:?}",
     970              :                                 attach_conf.generation,
     971              :                                 tenant.generation
     972              :                             )));
     973              :                         }
     974              :                         Ordering::Greater => {
     975              :                             // Generation advanced, fall through to general case of replacing `Tenant` object
     976              :                             None
     977              :                         }
     978              :                     }
     979              :                 }
     980              :                 (
     981              :                     LocationMode::Secondary(secondary_conf),
     982              :                     Some(TenantSlot::Secondary(secondary_tenant)),
     983              :                 ) => {
     984              :                     secondary_tenant.set_config(secondary_conf);
     985              :                     secondary_tenant.set_tenant_conf(&new_location_config.tenant_conf);
     986              :                     Some(FastPathModified::Secondary(secondary_tenant.clone()))
     987              :                 }
     988              :                 _ => {
     989              :                     // Not an Attached->Attached transition, fall through to general case
     990              :                     None
     991              :                 }
     992              :             }
     993              :         };
     994              : 
     995              :         // Fast-path continued: having dropped out of the self.tenants lock, do the async
     996              :         // phase of writing config and/or waiting for flush, before returning.
     997              :         match fast_path_taken {
     998              :             Some(FastPathModified::Attached(tenant)) => {
     999              :                 Tenant::persist_tenant_config(self.conf, &tenant_shard_id, &new_location_config)
    1000              :                     .await
    1001              :                     .fatal_err("write tenant shard config");
    1002              : 
    1003              :                 // Transition to AttachedStale means we may well hold a valid generation
    1004              :                 // still, and have been requested to go stale as part of a migration.  If
    1005              :                 // the caller set `flush`, then flush to remote storage.
    1006              :                 if let LocationMode::Attached(AttachedLocationConfig {
    1007              :                     generation: _,
    1008              :                     attach_mode: AttachmentMode::Stale,
    1009              :                 }) = &new_location_config.mode
    1010              :                 {
    1011              :                     if let Some(flush_timeout) = flush {
    1012              :                         match tokio::time::timeout(flush_timeout, tenant.flush_remote()).await {
    1013              :                             Ok(Err(e)) => {
    1014              :                                 return Err(UpsertLocationError::Flush(e));
    1015              :                             }
    1016              :                             Ok(Ok(_)) => return Ok(Some(tenant)),
    1017              :                             Err(_) => {
    1018              :                                 tracing::warn!(
    1019              :                                 timeout_ms = flush_timeout.as_millis(),
    1020              :                                 "Timed out waiting for flush to remote storage, proceeding anyway."
    1021              :                             )
    1022              :                             }
    1023              :                         }
    1024              :                     }
    1025              :                 }
    1026              : 
    1027              :                 return Ok(Some(tenant));
    1028              :             }
    1029              :             Some(FastPathModified::Secondary(_secondary_tenant)) => {
    1030              :                 Tenant::persist_tenant_config(self.conf, &tenant_shard_id, &new_location_config)
    1031              :                     .await
    1032              :                     .fatal_err("write tenant shard config");
    1033              : 
    1034              :                 return Ok(None);
    1035              :             }
    1036              :             None => {
    1037              :                 // Proceed with the general case procedure, where we will shutdown & remove any existing
    1038              :                 // slot contents and replace with a fresh one
    1039              :             }
    1040              :         };
    1041              : 
    1042              :         // General case for upserts to TenantsMap, excluding the case above: we will substitute an
    1043              :         // InProgress value to the slot while we make whatever changes are required.  The state for
    1044              :         // the tenant is inaccessible to the outside world while we are doing this, but that is sensible:
    1045              :         // the state is ill-defined while we're in transition.  Transitions are async, but fast: we do
    1046              :         // not do significant I/O, and shutdowns should be prompt via cancellation tokens.
    1047              :         let mut slot_guard = tenant_map_acquire_slot(&tenant_shard_id, TenantSlotAcquireMode::Any)
    1048            0 :             .map_err(|e| match e {
    1049              :                 TenantSlotError::NotFound(_) => {
    1050            0 :                     unreachable!("Called with mode Any")
    1051              :                 }
    1052            0 :                 TenantSlotError::InProgress => UpsertLocationError::InProgress,
    1053            0 :                 TenantSlotError::MapState(s) => UpsertLocationError::Unavailable(s),
    1054            0 :             })?;
    1055              : 
    1056              :         match slot_guard.get_old_value() {
    1057              :             Some(TenantSlot::Attached(tenant)) => {
    1058              :                 // The case where we keep a Tenant alive was covered above in the special case
    1059              :                 // for Attached->Attached transitions in the same generation.  By this point,
    1060              :                 // if we see an attached tenant we know it will be discarded and should be
    1061              :                 // shut down.
    1062              :                 let (_guard, progress) = utils::completion::channel();
    1063              : 
    1064              :                 match tenant.get_attach_mode() {
    1065              :                     AttachmentMode::Single | AttachmentMode::Multi => {
    1066              :                         // Before we leave our state as the presumed holder of the latest generation,
    1067              :                         // flush any outstanding deletions to reduce the risk of leaking objects.
    1068              :                         self.resources.deletion_queue_client.flush_advisory()
    1069              :                     }
    1070              :                     AttachmentMode::Stale => {
    1071              :                         // If we're stale there's not point trying to flush deletions
    1072              :                     }
    1073              :                 };
    1074              : 
    1075              :                 info!("Shutting down attached tenant");
    1076              :                 match tenant.shutdown(progress, ShutdownMode::Hard).await {
    1077              :                     Ok(()) => {}
    1078              :                     Err(barrier) => {
    1079              :                         info!("Shutdown already in progress, waiting for it to complete");
    1080              :                         barrier.wait().await;
    1081              :                     }
    1082              :                 }
    1083              :                 slot_guard.drop_old_value().expect("We just shut it down");
    1084              : 
    1085              :                 // Edge case: if we were called with SpawnMode::Create, but a Tenant already existed, then
    1086              :                 // the caller thinks they're creating but the tenant already existed.  We must switch to
    1087              :                 // Eager mode so that when starting this Tenant we properly probe remote storage for timelines,
    1088              :                 // rather than assuming it to be empty.
    1089              :                 spawn_mode = SpawnMode::Eager;
    1090              :             }
    1091              :             Some(TenantSlot::Secondary(state)) => {
    1092              :                 info!("Shutting down secondary tenant");
    1093              :                 state.shutdown().await;
    1094              :             }
    1095              :             Some(TenantSlot::InProgress(_)) => {
    1096              :                 // This should never happen: acquire_slot should error out
    1097              :                 // if the contents of a slot were InProgress.
    1098              :                 return Err(UpsertLocationError::InternalError(anyhow::anyhow!(
    1099              :                     "Acquired an InProgress slot, this is a bug."
    1100              :                 )));
    1101              :             }
    1102              :             None => {
    1103              :                 // Slot was vacant, nothing needs shutting down.
    1104              :             }
    1105              :         }
    1106              : 
    1107              :         let tenant_path = self.conf.tenant_path(&tenant_shard_id);
    1108              :         let timelines_path = self.conf.timelines_path(&tenant_shard_id);
    1109              : 
    1110              :         // Directory structure is the same for attached and secondary modes:
    1111              :         // create it if it doesn't exist.  Timeline load/creation expects the
    1112              :         // timelines/ subdir to already exist.
    1113              :         //
    1114              :         // Does not need to be fsync'd because local storage is just a cache.
    1115              :         tokio::fs::create_dir_all(&timelines_path)
    1116              :             .await
    1117              :             .fatal_err("create timelines/ dir");
    1118              : 
    1119              :         // Before activating either secondary or attached mode, persist the
    1120              :         // configuration, so that on restart we will re-attach (or re-start
    1121              :         // secondary) on the tenant.
    1122              :         Tenant::persist_tenant_config(self.conf, &tenant_shard_id, &new_location_config)
    1123              :             .await
    1124              :             .fatal_err("write tenant shard config");
    1125              : 
    1126              :         let new_slot = match &new_location_config.mode {
    1127              :             LocationMode::Secondary(secondary_config) => {
    1128              :                 let shard_identity = new_location_config.shard;
    1129              :                 TenantSlot::Secondary(SecondaryTenant::new(
    1130              :                     tenant_shard_id,
    1131              :                     shard_identity,
    1132              :                     new_location_config.tenant_conf,
    1133              :                     secondary_config,
    1134              :                 ))
    1135              :             }
    1136              :             LocationMode::Attached(_attach_config) => {
    1137              :                 let shard_identity = new_location_config.shard;
    1138              : 
    1139              :                 // Testing hack: if we are configured with no control plane, then drop the generation
    1140              :                 // from upserts.  This enables creating generation-less tenants even though neon_local
    1141              :                 // always uses generations when calling the location conf API.
    1142              :                 let attached_conf = if cfg!(feature = "testing") {
    1143              :                     let mut conf = AttachedTenantConf::try_from(new_location_config)
    1144              :                         .map_err(UpsertLocationError::BadRequest)?;
    1145              :                     if self.conf.control_plane_api.is_none() {
    1146              :                         conf.location.generation = Generation::none();
    1147              :                     }
    1148              :                     conf
    1149              :                 } else {
    1150              :                     AttachedTenantConf::try_from(new_location_config)
    1151              :                         .map_err(UpsertLocationError::BadRequest)?
    1152              :                 };
    1153              : 
    1154              :                 let tenant = tenant_spawn(
    1155              :                     self.conf,
    1156              :                     tenant_shard_id,
    1157              :                     &tenant_path,
    1158              :                     self.resources.clone(),
    1159              :                     attached_conf,
    1160              :                     shard_identity,
    1161              :                     None,
    1162              :                     spawn_mode,
    1163              :                     ctx,
    1164              :                 )
    1165            0 :                 .map_err(|_: GlobalShutDown| {
    1166            0 :                     UpsertLocationError::Unavailable(TenantMapError::ShuttingDown)
    1167            0 :                 })?;
    1168              : 
    1169              :                 TenantSlot::Attached(tenant)
    1170              :             }
    1171              :         };
    1172              : 
    1173              :         let attached_tenant = if let TenantSlot::Attached(tenant) = &new_slot {
    1174              :             Some(tenant.clone())
    1175              :         } else {
    1176              :             None
    1177              :         };
    1178              : 
    1179              :         match slot_guard.upsert(new_slot) {
    1180              :             Err(TenantSlotUpsertError::InternalError(e)) => {
    1181              :                 Err(UpsertLocationError::InternalError(anyhow::anyhow!(e)))
    1182              :             }
    1183              :             Err(TenantSlotUpsertError::MapState(e)) => Err(UpsertLocationError::Unavailable(e)),
    1184              :             Err(TenantSlotUpsertError::ShuttingDown((new_slot, _completion))) => {
    1185              :                 // If we just called tenant_spawn() on a new tenant, and can't insert it into our map, then
    1186              :                 // we must not leak it: this would violate the invariant that after shutdown_all_tenants, all tenants
    1187              :                 // are shutdown.
    1188              :                 //
    1189              :                 // We must shut it down inline here.
    1190              :                 match new_slot {
    1191              :                     TenantSlot::InProgress(_) => {
    1192              :                         // Unreachable because we never insert an InProgress
    1193              :                         unreachable!()
    1194              :                     }
    1195              :                     TenantSlot::Attached(tenant) => {
    1196              :                         let (_guard, progress) = utils::completion::channel();
    1197              :                         info!("Shutting down just-spawned tenant, because tenant manager is shut down");
    1198              :                         match tenant.shutdown(progress, ShutdownMode::Hard).await {
    1199              :                             Ok(()) => {
    1200              :                                 info!("Finished shutting down just-spawned tenant");
    1201              :                             }
    1202              :                             Err(barrier) => {
    1203              :                                 info!("Shutdown already in progress, waiting for it to complete");
    1204              :                                 barrier.wait().await;
    1205              :                             }
    1206              :                         }
    1207              :                     }
    1208              :                     TenantSlot::Secondary(secondary_tenant) => {
    1209              :                         secondary_tenant.shutdown().await;
    1210              :                     }
    1211              :                 }
    1212              : 
    1213              :                 Err(UpsertLocationError::Unavailable(
    1214              :                     TenantMapError::ShuttingDown,
    1215              :                 ))
    1216              :             }
    1217              :             Ok(()) => Ok(attached_tenant),
    1218              :         }
    1219              :     }
    1220              : 
    1221              :     /// Resetting a tenant is equivalent to detaching it, then attaching it again with the same
    1222              :     /// LocationConf that was last used to attach it.  Optionally, the local file cache may be
    1223              :     /// dropped before re-attaching.
    1224              :     ///
    1225              :     /// This is not part of a tenant's normal lifecycle: it is used for debug/support, in situations
    1226              :     /// where an issue is identified that would go away with a restart of the tenant.
    1227              :     ///
    1228              :     /// This does not have any special "force" shutdown of a tenant: it relies on the tenant's tasks
    1229              :     /// to respect the cancellation tokens used in normal shutdown().
    1230            0 :     #[instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), %drop_cache))]
    1231              :     pub(crate) async fn reset_tenant(
    1232              :         &self,
    1233              :         tenant_shard_id: TenantShardId,
    1234              :         drop_cache: bool,
    1235              :         ctx: &RequestContext,
    1236              :     ) -> anyhow::Result<()> {
    1237              :         let mut slot_guard = tenant_map_acquire_slot(&tenant_shard_id, TenantSlotAcquireMode::Any)?;
    1238              :         let Some(old_slot) = slot_guard.get_old_value() else {
    1239              :             anyhow::bail!("Tenant not found when trying to reset");
    1240              :         };
    1241              : 
    1242              :         let Some(tenant) = old_slot.get_attached() else {
    1243              :             slot_guard.revert();
    1244              :             anyhow::bail!("Tenant is not in attached state");
    1245              :         };
    1246              : 
    1247              :         let (_guard, progress) = utils::completion::channel();
    1248              :         match tenant.shutdown(progress, ShutdownMode::Hard).await {
    1249              :             Ok(()) => {
    1250              :                 slot_guard.drop_old_value()?;
    1251              :             }
    1252              :             Err(_barrier) => {
    1253              :                 slot_guard.revert();
    1254              :                 anyhow::bail!("Cannot reset Tenant, already shutting down");
    1255              :             }
    1256              :         }
    1257              : 
    1258              :         let tenant_path = self.conf.tenant_path(&tenant_shard_id);
    1259              :         let timelines_path = self.conf.timelines_path(&tenant_shard_id);
    1260              :         let config = Tenant::load_tenant_config(self.conf, &tenant_shard_id)?;
    1261              : 
    1262              :         if drop_cache {
    1263              :             tracing::info!("Dropping local file cache");
    1264              : 
    1265              :             match tokio::fs::read_dir(&timelines_path).await {
    1266              :                 Err(e) => {
    1267              :                     tracing::warn!("Failed to list timelines while dropping cache: {}", e);
    1268              :                 }
    1269              :                 Ok(mut entries) => {
    1270              :                     while let Some(entry) = entries.next_entry().await? {
    1271              :                         tokio::fs::remove_dir_all(entry.path()).await?;
    1272              :                     }
    1273              :                 }
    1274              :             }
    1275              :         }
    1276              : 
    1277              :         let shard_identity = config.shard;
    1278              :         let tenant = tenant_spawn(
    1279              :             self.conf,
    1280              :             tenant_shard_id,
    1281              :             &tenant_path,
    1282              :             self.resources.clone(),
    1283              :             AttachedTenantConf::try_from(config)?,
    1284              :             shard_identity,
    1285              :             None,
    1286              :             SpawnMode::Eager,
    1287              :             ctx,
    1288              :         )?;
    1289              : 
    1290              :         slot_guard.upsert(TenantSlot::Attached(tenant))?;
    1291              : 
    1292              :         Ok(())
    1293              :     }
    1294              : 
    1295            0 :     pub(crate) fn get_attached_active_tenant_shards(&self) -> Vec<Arc<Tenant>> {
    1296            0 :         let locked = self.tenants.read().unwrap();
    1297            0 :         match &*locked {
    1298            0 :             TenantsMap::Initializing => Vec::new(),
    1299            0 :             TenantsMap::Open(map) | TenantsMap::ShuttingDown(map) => map
    1300            0 :                 .values()
    1301            0 :                 .filter_map(|slot| {
    1302            0 :                     slot.get_attached()
    1303            0 :                         .and_then(|t| if t.is_active() { Some(t.clone()) } else { None })
    1304            0 :                 })
    1305            0 :                 .collect(),
    1306              :         }
    1307            0 :     }
    1308              :     // Do some synchronous work for all tenant slots in Secondary state.  The provided
    1309              :     // callback should be small and fast, as it will be called inside the global
    1310              :     // TenantsMap lock.
    1311            0 :     pub(crate) fn foreach_secondary_tenants<F>(&self, mut func: F)
    1312            0 :     where
    1313            0 :         // TODO: let the callback return a hint to drop out of the loop early
    1314            0 :         F: FnMut(&TenantShardId, &Arc<SecondaryTenant>),
    1315            0 :     {
    1316            0 :         let locked = self.tenants.read().unwrap();
    1317              : 
    1318            0 :         let map = match &*locked {
    1319            0 :             TenantsMap::Initializing | TenantsMap::ShuttingDown(_) => return,
    1320            0 :             TenantsMap::Open(m) => m,
    1321              :         };
    1322              : 
    1323            0 :         for (tenant_id, slot) in map {
    1324            0 :             if let TenantSlot::Secondary(state) = slot {
    1325              :                 // Only expose secondary tenants that are not currently shutting down
    1326            0 :                 if !state.cancel.is_cancelled() {
    1327            0 :                     func(tenant_id, state)
    1328            0 :                 }
    1329            0 :             }
    1330              :         }
    1331            0 :     }
    1332              : 
    1333              :     /// Total list of all tenant slots: this includes attached, secondary, and InProgress.
    1334            0 :     pub(crate) fn list(&self) -> Vec<(TenantShardId, TenantSlot)> {
    1335            0 :         let locked = self.tenants.read().unwrap();
    1336            0 :         match &*locked {
    1337            0 :             TenantsMap::Initializing => Vec::new(),
    1338            0 :             TenantsMap::Open(map) | TenantsMap::ShuttingDown(map) => {
    1339            0 :                 map.iter().map(|(k, v)| (*k, v.clone())).collect()
    1340              :             }
    1341              :         }
    1342            0 :     }
    1343              : 
    1344            0 :     pub(crate) fn get(&self, tenant_shard_id: TenantShardId) -> Option<TenantSlot> {
    1345            0 :         let locked = self.tenants.read().unwrap();
    1346            0 :         match &*locked {
    1347            0 :             TenantsMap::Initializing => None,
    1348            0 :             TenantsMap::Open(map) | TenantsMap::ShuttingDown(map) => {
    1349            0 :                 map.get(&tenant_shard_id).cloned()
    1350              :             }
    1351              :         }
    1352            0 :     }
    1353              : 
    1354              :     /// If a tenant is attached, detach it.  Then remove its data from remote storage.
    1355              :     ///
    1356              :     /// A tenant is considered deleted once it is gone from remote storage.  It is the caller's
    1357              :     /// responsibility to avoid trying to attach the tenant again or use it any way once deletion
    1358              :     /// has started: this operation is not atomic, and must be retried until it succeeds.
    1359              :     ///
    1360              :     /// As a special case, if an unsharded tenant ID is given for a sharded tenant, it will remove
    1361              :     /// all tenant shards in remote storage (removing all paths with the tenant prefix). The storage
    1362              :     /// controller uses this to purge all remote tenant data, including any stale parent shards that
    1363              :     /// may remain after splits. Ideally, this special case would be handled elsewhere. See:
    1364              :     /// <https://github.com/neondatabase/neon/pull/9394>.
    1365            0 :     pub(crate) async fn delete_tenant(
    1366            0 :         &self,
    1367            0 :         tenant_shard_id: TenantShardId,
    1368            0 :     ) -> Result<(), DeleteTenantError> {
    1369            0 :         super::span::debug_assert_current_span_has_tenant_id();
    1370              : 
    1371            0 :         async fn delete_local(
    1372            0 :             conf: &PageServerConf,
    1373            0 :             background_purges: &BackgroundPurges,
    1374            0 :             tenant_shard_id: &TenantShardId,
    1375            0 :         ) -> anyhow::Result<()> {
    1376            0 :             let local_tenant_directory = conf.tenant_path(tenant_shard_id);
    1377            0 :             let tmp_dir = safe_rename_tenant_dir(&local_tenant_directory)
    1378            0 :                 .await
    1379            0 :                 .with_context(|| {
    1380            0 :                     format!("local tenant directory {local_tenant_directory:?} rename")
    1381            0 :                 })?;
    1382            0 :             background_purges.spawn(tmp_dir);
    1383            0 :             Ok(())
    1384            0 :         }
    1385              : 
    1386            0 :         let slot_guard = tenant_map_acquire_slot(&tenant_shard_id, TenantSlotAcquireMode::Any)?;
    1387            0 :         match &slot_guard.old_value {
    1388            0 :             Some(TenantSlot::Attached(tenant)) => {
    1389            0 :                 // Legacy deletion flow: the tenant remains attached, goes to Stopping state, and
    1390            0 :                 // deletion will be resumed across restarts.
    1391            0 :                 let tenant = tenant.clone();
    1392            0 :                 let (_guard, progress) = utils::completion::channel();
    1393            0 :                 match tenant.shutdown(progress, ShutdownMode::Hard).await {
    1394            0 :                     Ok(()) => {}
    1395            0 :                     Err(barrier) => {
    1396            0 :                         info!("Shutdown already in progress, waiting for it to complete");
    1397            0 :                         barrier.wait().await;
    1398              :                     }
    1399              :                 }
    1400            0 :                 delete_local(self.conf, &self.background_purges, &tenant_shard_id).await?;
    1401              :             }
    1402            0 :             Some(TenantSlot::Secondary(secondary_tenant)) => {
    1403            0 :                 secondary_tenant.shutdown().await;
    1404              : 
    1405            0 :                 delete_local(self.conf, &self.background_purges, &tenant_shard_id).await?;
    1406              :             }
    1407            0 :             Some(TenantSlot::InProgress(_)) => unreachable!(),
    1408            0 :             None => {}
    1409              :         };
    1410              : 
    1411              :         // Fall through: local state for this tenant is no longer present, proceed with remote delete.
    1412              :         // - We use a retry wrapper here so that common transient S3 errors (e.g. 503, 429) do not result
    1413              :         //   in 500 responses to delete requests.
    1414              :         // - We keep the `SlotGuard` during this I/O, so that if a concurrent delete request comes in, it will
    1415              :         //   503/retry, rather than kicking off a wasteful concurrent deletion.
    1416              :         // NB: this also deletes partial prefixes, i.e. a <tenant_id> path will delete all
    1417              :         // <tenant_id>_<shard_id>/* objects. See method comment for why.
    1418            0 :         backoff::retry(
    1419            0 :             || async move {
    1420            0 :                 self.resources
    1421            0 :                     .remote_storage
    1422            0 :                     .delete_prefix(&remote_tenant_path(&tenant_shard_id), &self.cancel)
    1423            0 :                     .await
    1424            0 :             },
    1425            0 :             |_| false, // backoff::retry handles cancellation
    1426            0 :             1,
    1427            0 :             3,
    1428            0 :             &format!("delete_tenant[tenant_shard_id={tenant_shard_id}]"),
    1429            0 :             &self.cancel,
    1430            0 :         )
    1431            0 :         .await
    1432            0 :         .unwrap_or(Err(TimeoutOrCancel::Cancel.into()))
    1433            0 :         .map_err(|err| {
    1434            0 :             if TimeoutOrCancel::caused_by_cancel(&err) {
    1435            0 :                 return DeleteTenantError::Cancelled;
    1436            0 :             }
    1437            0 :             DeleteTenantError::Other(err)
    1438            0 :         })
    1439            0 :     }
    1440              : 
    1441            0 :     #[instrument(skip_all, fields(tenant_id=%tenant.get_tenant_shard_id().tenant_id, shard_id=%tenant.get_tenant_shard_id().shard_slug(), new_shard_count=%new_shard_count.literal()))]
    1442              :     pub(crate) async fn shard_split(
    1443              :         &self,
    1444              :         tenant: Arc<Tenant>,
    1445              :         new_shard_count: ShardCount,
    1446              :         new_stripe_size: Option<ShardStripeSize>,
    1447              :         ctx: &RequestContext,
    1448              :     ) -> anyhow::Result<Vec<TenantShardId>> {
    1449              :         let tenant_shard_id = *tenant.get_tenant_shard_id();
    1450              :         let r = self
    1451              :             .do_shard_split(tenant, new_shard_count, new_stripe_size, ctx)
    1452              :             .await;
    1453              :         if r.is_err() {
    1454              :             // Shard splitting might have left the original shard in a partially shut down state (it
    1455              :             // stops the shard's remote timeline client).  Reset it to ensure we leave things in
    1456              :             // a working state.
    1457              :             if self.get(tenant_shard_id).is_some() {
    1458              :                 tracing::warn!("Resetting after shard split failure");
    1459              :                 if let Err(e) = self.reset_tenant(tenant_shard_id, false, ctx).await {
    1460              :                     // Log this error because our return value will still be the original error, not this one.  This is
    1461              :                     // a severe error: if this happens, we might be leaving behind a tenant that is not fully functional
    1462              :                     // (e.g. has uploads disabled).  We can't do anything else: if reset fails then shutting the tenant down or
    1463              :                     // setting it broken probably won't help either.
    1464              :                     tracing::error!("Failed to reset: {e}");
    1465              :                 }
    1466              :             }
    1467              :         }
    1468              : 
    1469              :         r
    1470              :     }
    1471              : 
    1472            0 :     pub(crate) async fn do_shard_split(
    1473            0 :         &self,
    1474            0 :         tenant: Arc<Tenant>,
    1475            0 :         new_shard_count: ShardCount,
    1476            0 :         new_stripe_size: Option<ShardStripeSize>,
    1477            0 :         ctx: &RequestContext,
    1478            0 :     ) -> anyhow::Result<Vec<TenantShardId>> {
    1479            0 :         let tenant_shard_id = *tenant.get_tenant_shard_id();
    1480            0 : 
    1481            0 :         // Validate the incoming request
    1482            0 :         if new_shard_count.count() <= tenant_shard_id.shard_count.count() {
    1483            0 :             anyhow::bail!("Requested shard count is not an increase");
    1484            0 :         }
    1485            0 :         let expansion_factor = new_shard_count.count() / tenant_shard_id.shard_count.count();
    1486            0 :         if !expansion_factor.is_power_of_two() {
    1487            0 :             anyhow::bail!("Requested split is not a power of two");
    1488            0 :         }
    1489              : 
    1490            0 :         if let Some(new_stripe_size) = new_stripe_size {
    1491            0 :             if tenant.get_shard_stripe_size() != new_stripe_size
    1492            0 :                 && tenant_shard_id.shard_count.count() > 1
    1493              :             {
    1494              :                 // This tenant already has multiple shards, it is illegal to try and change its stripe size
    1495            0 :                 anyhow::bail!(
    1496            0 :                     "Shard stripe size may not be modified once tenant has multiple shards"
    1497            0 :                 );
    1498            0 :             }
    1499            0 :         }
    1500              : 
    1501              :         // Plan: identify what the new child shards will be
    1502            0 :         let child_shards = tenant_shard_id.split(new_shard_count);
    1503            0 :         tracing::info!(
    1504            0 :             "Shard {} splits into: {}",
    1505            0 :             tenant_shard_id.to_index(),
    1506            0 :             child_shards
    1507            0 :                 .iter()
    1508            0 :                 .map(|id| format!("{}", id.to_index()))
    1509            0 :                 .join(",")
    1510              :         );
    1511              : 
    1512            0 :         fail::fail_point!("shard-split-pre-prepare", |_| Err(anyhow::anyhow!(
    1513            0 :             "failpoint"
    1514            0 :         )));
    1515              : 
    1516            0 :         let parent_shard_identity = tenant.shard_identity;
    1517            0 :         let parent_tenant_conf = tenant.get_tenant_conf();
    1518            0 :         let parent_generation = tenant.generation;
    1519              : 
    1520              :         // Phase 1: Write out child shards' remote index files, in the parent tenant's current generation
    1521            0 :         if let Err(e) = tenant.split_prepare(&child_shards).await {
    1522              :             // If [`Tenant::split_prepare`] fails, we must reload the tenant, because it might
    1523              :             // have been left in a partially-shut-down state.
    1524            0 :             tracing::warn!("Failed to prepare for split: {e}, reloading Tenant before returning");
    1525            0 :             return Err(e);
    1526            0 :         }
    1527            0 : 
    1528            0 :         fail::fail_point!("shard-split-post-prepare", |_| Err(anyhow::anyhow!(
    1529            0 :             "failpoint"
    1530            0 :         )));
    1531              : 
    1532            0 :         self.resources.deletion_queue_client.flush_advisory();
    1533            0 : 
    1534            0 :         // Phase 2: Put the parent shard to InProgress and grab a reference to the parent Tenant
    1535            0 :         drop(tenant);
    1536            0 :         let mut parent_slot_guard =
    1537            0 :             tenant_map_acquire_slot(&tenant_shard_id, TenantSlotAcquireMode::Any)?;
    1538            0 :         let parent = match parent_slot_guard.get_old_value() {
    1539            0 :             Some(TenantSlot::Attached(t)) => t,
    1540            0 :             Some(TenantSlot::Secondary(_)) => anyhow::bail!("Tenant location in secondary mode"),
    1541              :             Some(TenantSlot::InProgress(_)) => {
    1542              :                 // tenant_map_acquire_slot never returns InProgress, if a slot was InProgress
    1543              :                 // it would return an error.
    1544            0 :                 unreachable!()
    1545              :             }
    1546              :             None => {
    1547              :                 // We don't actually need the parent shard to still be attached to do our work, but it's
    1548              :                 // a weird enough situation that the caller probably didn't want us to continue working
    1549              :                 // if they had detached the tenant they requested the split on.
    1550            0 :                 anyhow::bail!("Detached parent shard in the middle of split!")
    1551              :             }
    1552              :         };
    1553            0 :         fail::fail_point!("shard-split-pre-hardlink", |_| Err(anyhow::anyhow!(
    1554            0 :             "failpoint"
    1555            0 :         )));
    1556              :         // Optimization: hardlink layers from the parent into the children, so that they don't have to
    1557              :         // re-download & duplicate the data referenced in their initial IndexPart
    1558            0 :         self.shard_split_hardlink(parent, child_shards.clone())
    1559            0 :             .await?;
    1560            0 :         fail::fail_point!("shard-split-post-hardlink", |_| Err(anyhow::anyhow!(
    1561            0 :             "failpoint"
    1562            0 :         )));
    1563              : 
    1564              :         // Take a snapshot of where the parent's WAL ingest had got to: we will wait for
    1565              :         // child shards to reach this point.
    1566            0 :         let mut target_lsns = HashMap::new();
    1567            0 :         for timeline in parent.timelines.lock().unwrap().clone().values() {
    1568            0 :             target_lsns.insert(timeline.timeline_id, timeline.get_last_record_lsn());
    1569            0 :         }
    1570              : 
    1571              :         // TODO: we should have the parent shard stop its WAL ingest here, it's a waste of resources
    1572              :         // and could slow down the children trying to catch up.
    1573              : 
    1574              :         // Phase 3: Spawn the child shards
    1575            0 :         for child_shard in &child_shards {
    1576            0 :             let mut child_shard_identity = parent_shard_identity;
    1577            0 :             if let Some(new_stripe_size) = new_stripe_size {
    1578            0 :                 child_shard_identity.stripe_size = new_stripe_size;
    1579            0 :             }
    1580            0 :             child_shard_identity.count = child_shard.shard_count;
    1581            0 :             child_shard_identity.number = child_shard.shard_number;
    1582            0 : 
    1583            0 :             let child_location_conf = LocationConf {
    1584            0 :                 mode: LocationMode::Attached(AttachedLocationConfig {
    1585            0 :                     generation: parent_generation,
    1586            0 :                     attach_mode: AttachmentMode::Single,
    1587            0 :                 }),
    1588            0 :                 shard: child_shard_identity,
    1589            0 :                 tenant_conf: parent_tenant_conf.clone(),
    1590            0 :             };
    1591            0 : 
    1592            0 :             self.upsert_location(
    1593            0 :                 *child_shard,
    1594            0 :                 child_location_conf,
    1595            0 :                 None,
    1596            0 :                 SpawnMode::Eager,
    1597            0 :                 ctx,
    1598            0 :             )
    1599            0 :             .await?;
    1600              :         }
    1601              : 
    1602            0 :         fail::fail_point!("shard-split-post-child-conf", |_| Err(anyhow::anyhow!(
    1603            0 :             "failpoint"
    1604            0 :         )));
    1605              : 
    1606              :         // Phase 4: wait for child chards WAL ingest to catch up to target LSN
    1607            0 :         for child_shard_id in &child_shards {
    1608            0 :             let child_shard_id = *child_shard_id;
    1609            0 :             let child_shard = {
    1610            0 :                 let locked = self.tenants.read().unwrap();
    1611            0 :                 let peek_slot =
    1612            0 :                     tenant_map_peek_slot(&locked, &child_shard_id, TenantSlotPeekMode::Read)?;
    1613            0 :                 peek_slot.and_then(|s| s.get_attached()).cloned()
    1614              :             };
    1615            0 :             if let Some(t) = child_shard {
    1616              :                 // Wait for the child shard to become active: this should be very quick because it only
    1617              :                 // has to download the index_part that we just uploaded when creating it.
    1618            0 :                 if let Err(e) = t.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await {
    1619              :                     // This is not fatal: we have durably created the child shard.  It just makes the
    1620              :                     // split operation less seamless for clients, as we will may detach the parent
    1621              :                     // shard before the child shards are fully ready to serve requests.
    1622            0 :                     tracing::warn!("Failed to wait for shard {child_shard_id} to activate: {e}");
    1623            0 :                     continue;
    1624            0 :                 }
    1625            0 : 
    1626            0 :                 let timelines = t.timelines.lock().unwrap().clone();
    1627            0 :                 for timeline in timelines.values() {
    1628            0 :                     let Some(target_lsn) = target_lsns.get(&timeline.timeline_id) else {
    1629            0 :                         continue;
    1630              :                     };
    1631              : 
    1632            0 :                     tracing::info!(
    1633            0 :                         "Waiting for child shard {}/{} to reach target lsn {}...",
    1634            0 :                         child_shard_id,
    1635            0 :                         timeline.timeline_id,
    1636              :                         target_lsn
    1637              :                     );
    1638              : 
    1639            0 :                     fail::fail_point!("shard-split-lsn-wait", |_| Err(anyhow::anyhow!(
    1640            0 :                         "failpoint"
    1641            0 :                     )));
    1642            0 :                     if let Err(e) = timeline
    1643            0 :                         .wait_lsn(
    1644            0 :                             *target_lsn,
    1645            0 :                             crate::tenant::timeline::WaitLsnWaiter::Tenant,
    1646            0 :                             ctx,
    1647            0 :                         )
    1648            0 :                         .await
    1649              :                     {
    1650              :                         // Failure here might mean shutdown, in any case this part is an optimization
    1651              :                         // and we shouldn't hold up the split operation.
    1652            0 :                         tracing::warn!(
    1653            0 :                             "Failed to wait for timeline {} to reach lsn {target_lsn}: {e}",
    1654            0 :                             timeline.timeline_id
    1655              :                         );
    1656              :                     } else {
    1657            0 :                         tracing::info!(
    1658            0 :                             "Child shard {}/{} reached target lsn {}",
    1659            0 :                             child_shard_id,
    1660            0 :                             timeline.timeline_id,
    1661              :                             target_lsn
    1662              :                         );
    1663              :                     }
    1664              :                 }
    1665            0 :             }
    1666              :         }
    1667              : 
    1668              :         // Phase 5: Shut down the parent shard, and erase it from disk
    1669            0 :         let (_guard, progress) = completion::channel();
    1670            0 :         match parent.shutdown(progress, ShutdownMode::Hard).await {
    1671            0 :             Ok(()) => {}
    1672            0 :             Err(other) => {
    1673            0 :                 other.wait().await;
    1674              :             }
    1675              :         }
    1676            0 :         let local_tenant_directory = self.conf.tenant_path(&tenant_shard_id);
    1677            0 :         let tmp_path = safe_rename_tenant_dir(&local_tenant_directory)
    1678            0 :             .await
    1679            0 :             .with_context(|| format!("local tenant directory {local_tenant_directory:?} rename"))?;
    1680            0 :         self.background_purges.spawn(tmp_path);
    1681            0 : 
    1682            0 :         fail::fail_point!("shard-split-pre-finish", |_| Err(anyhow::anyhow!(
    1683            0 :             "failpoint"
    1684            0 :         )));
    1685              : 
    1686            0 :         parent_slot_guard.drop_old_value()?;
    1687              : 
    1688              :         // Phase 6: Release the InProgress on the parent shard
    1689            0 :         drop(parent_slot_guard);
    1690            0 : 
    1691            0 :         Ok(child_shards)
    1692            0 :     }
    1693              : 
    1694              :     /// Part of [`Self::shard_split`]: hard link parent shard layers into child shards, as an optimization
    1695              :     /// to avoid the children downloading them again.
    1696              :     ///
    1697              :     /// For each resident layer in the parent shard, we will hard link it into all of the child shards.
    1698            0 :     async fn shard_split_hardlink(
    1699            0 :         &self,
    1700            0 :         parent_shard: &Tenant,
    1701            0 :         child_shards: Vec<TenantShardId>,
    1702            0 :     ) -> anyhow::Result<()> {
    1703            0 :         debug_assert_current_span_has_tenant_id();
    1704            0 : 
    1705            0 :         let parent_path = self.conf.tenant_path(parent_shard.get_tenant_shard_id());
    1706            0 :         let (parent_timelines, parent_layers) = {
    1707            0 :             let mut parent_layers = Vec::new();
    1708            0 :             let timelines = parent_shard.timelines.lock().unwrap().clone();
    1709            0 :             let parent_timelines = timelines.keys().cloned().collect::<Vec<_>>();
    1710            0 :             for timeline in timelines.values() {
    1711            0 :                 tracing::info!(timeline_id=%timeline.timeline_id, "Loading list of layers to hardlink");
    1712            0 :                 let layers = timeline.layers.read().await;
    1713              : 
    1714            0 :                 for layer in layers.likely_resident_layers() {
    1715            0 :                     let relative_path = layer
    1716            0 :                         .local_path()
    1717            0 :                         .strip_prefix(&parent_path)
    1718            0 :                         .context("Removing prefix from parent layer path")?;
    1719            0 :                     parent_layers.push(relative_path.to_owned());
    1720              :                 }
    1721              :             }
    1722            0 :             debug_assert!(
    1723            0 :                 !parent_layers.is_empty(),
    1724            0 :                 "shutdown cannot empty the layermap"
    1725              :             );
    1726            0 :             (parent_timelines, parent_layers)
    1727            0 :         };
    1728            0 : 
    1729            0 :         let mut child_prefixes = Vec::new();
    1730            0 :         let mut create_dirs = Vec::new();
    1731              : 
    1732            0 :         for child in child_shards {
    1733            0 :             let child_prefix = self.conf.tenant_path(&child);
    1734            0 :             create_dirs.push(child_prefix.clone());
    1735            0 :             create_dirs.extend(
    1736            0 :                 parent_timelines
    1737            0 :                     .iter()
    1738            0 :                     .map(|t| self.conf.timeline_path(&child, t)),
    1739            0 :             );
    1740            0 : 
    1741            0 :             child_prefixes.push(child_prefix);
    1742            0 :         }
    1743              : 
    1744              :         // Since we will do a large number of small filesystem metadata operations, batch them into
    1745              :         // spawn_blocking calls rather than doing each one as a tokio::fs round-trip.
    1746            0 :         let span = tracing::Span::current();
    1747            0 :         let jh = tokio::task::spawn_blocking(move || -> anyhow::Result<usize> {
    1748            0 :             // Run this synchronous code in the same log context as the outer function that spawned it.
    1749            0 :             let _span = span.enter();
    1750            0 : 
    1751            0 :             tracing::info!("Creating {} directories", create_dirs.len());
    1752            0 :             for dir in &create_dirs {
    1753            0 :                 if let Err(e) = std::fs::create_dir_all(dir) {
    1754              :                     // Ignore AlreadyExists errors, drop out on all other errors
    1755            0 :                     match e.kind() {
    1756            0 :                         std::io::ErrorKind::AlreadyExists => {}
    1757              :                         _ => {
    1758            0 :                             return Err(anyhow::anyhow!(e).context(format!("Creating {dir}")));
    1759              :                         }
    1760              :                     }
    1761            0 :                 }
    1762              :             }
    1763              : 
    1764            0 :             for child_prefix in child_prefixes {
    1765            0 :                 tracing::info!(
    1766            0 :                     "Hard-linking {} parent layers into child path {}",
    1767            0 :                     parent_layers.len(),
    1768              :                     child_prefix
    1769              :                 );
    1770            0 :                 for relative_layer in &parent_layers {
    1771            0 :                     let parent_path = parent_path.join(relative_layer);
    1772            0 :                     let child_path = child_prefix.join(relative_layer);
    1773            0 :                     if let Err(e) = std::fs::hard_link(&parent_path, &child_path) {
    1774            0 :                         match e.kind() {
    1775            0 :                             std::io::ErrorKind::AlreadyExists => {}
    1776              :                             std::io::ErrorKind::NotFound => {
    1777            0 :                                 tracing::info!(
    1778            0 :                                     "Layer {} not found during hard-linking, evicted during split?",
    1779              :                                     relative_layer
    1780              :                                 );
    1781              :                             }
    1782              :                             _ => {
    1783            0 :                                 return Err(anyhow::anyhow!(e).context(format!(
    1784            0 :                                     "Hard linking {relative_layer} into {child_prefix}"
    1785            0 :                                 )))
    1786              :                             }
    1787              :                         }
    1788            0 :                     }
    1789              :                 }
    1790              :             }
    1791              : 
    1792              :             // Durability is not required for correctness, but if we crashed during split and
    1793              :             // then came restarted with empty timeline dirs, it would be very inefficient to
    1794              :             // re-populate from remote storage.
    1795            0 :             tracing::info!("fsyncing {} directories", create_dirs.len());
    1796            0 :             for dir in create_dirs {
    1797            0 :                 if let Err(e) = crashsafe::fsync(&dir) {
    1798              :                     // Something removed a newly created timeline dir out from underneath us?  Extremely
    1799              :                     // unexpected, but not worth panic'ing over as this whole function is just an
    1800              :                     // optimization.
    1801            0 :                     tracing::warn!("Failed to fsync directory {dir}: {e}")
    1802            0 :                 }
    1803              :             }
    1804              : 
    1805            0 :             Ok(parent_layers.len())
    1806            0 :         });
    1807            0 : 
    1808            0 :         match jh.await {
    1809            0 :             Ok(Ok(layer_count)) => {
    1810            0 :                 tracing::info!(count = layer_count, "Hard linked layers into child shards");
    1811              :             }
    1812            0 :             Ok(Err(e)) => {
    1813            0 :                 // This is an optimization, so we tolerate failure.
    1814            0 :                 tracing::warn!("Error hard-linking layers, proceeding anyway: {e}")
    1815              :             }
    1816            0 :             Err(e) => {
    1817            0 :                 // This is something totally unexpected like a panic, so bail out.
    1818            0 :                 anyhow::bail!("Error joining hard linking task: {e}");
    1819              :             }
    1820              :         }
    1821              : 
    1822            0 :         Ok(())
    1823            0 :     }
    1824              : 
    1825              :     ///
    1826              :     /// Shut down all tenants. This runs as part of pageserver shutdown.
    1827              :     ///
    1828              :     /// NB: We leave the tenants in the map, so that they remain accessible through
    1829              :     /// the management API until we shut it down. If we removed the shut-down tenants
    1830              :     /// from the tenants map, the management API would return 404 for these tenants,
    1831              :     /// because TenantsMap::get() now returns `None`.
    1832              :     /// That could be easily misinterpreted by control plane, the consumer of the
    1833              :     /// management API. For example, it could attach the tenant on a different pageserver.
    1834              :     /// We would then be in split-brain once this pageserver restarts.
    1835            0 :     #[instrument(skip_all)]
    1836              :     pub(crate) async fn shutdown(&self) {
    1837              :         self.cancel.cancel();
    1838              : 
    1839              :         shutdown_all_tenants0(self.tenants).await
    1840              :     }
    1841              : 
    1842            0 :     pub(crate) async fn detach_tenant(
    1843            0 :         &self,
    1844            0 :         conf: &'static PageServerConf,
    1845            0 :         tenant_shard_id: TenantShardId,
    1846            0 :         deletion_queue_client: &DeletionQueueClient,
    1847            0 :     ) -> Result<(), TenantStateError> {
    1848            0 :         let tmp_path = self
    1849            0 :             .detach_tenant0(conf, tenant_shard_id, deletion_queue_client)
    1850            0 :             .await?;
    1851            0 :         self.background_purges.spawn(tmp_path);
    1852            0 : 
    1853            0 :         Ok(())
    1854            0 :     }
    1855              : 
    1856            0 :     async fn detach_tenant0(
    1857            0 :         &self,
    1858            0 :         conf: &'static PageServerConf,
    1859            0 :         tenant_shard_id: TenantShardId,
    1860            0 :         deletion_queue_client: &DeletionQueueClient,
    1861            0 :     ) -> Result<Utf8PathBuf, TenantStateError> {
    1862            0 :         let tenant_dir_rename_operation = |tenant_id_to_clean: TenantShardId| async move {
    1863            0 :             let local_tenant_directory = conf.tenant_path(&tenant_id_to_clean);
    1864            0 :             safe_rename_tenant_dir(&local_tenant_directory)
    1865            0 :                 .await
    1866            0 :                 .with_context(|| {
    1867            0 :                     format!("local tenant directory {local_tenant_directory:?} rename")
    1868            0 :                 })
    1869            0 :         };
    1870              : 
    1871            0 :         let removal_result = remove_tenant_from_memory(
    1872            0 :             self.tenants,
    1873            0 :             tenant_shard_id,
    1874            0 :             tenant_dir_rename_operation(tenant_shard_id),
    1875            0 :         )
    1876            0 :         .await;
    1877              : 
    1878              :         // Flush pending deletions, so that they have a good chance of passing validation
    1879              :         // before this tenant is potentially re-attached elsewhere.
    1880            0 :         deletion_queue_client.flush_advisory();
    1881            0 : 
    1882            0 :         removal_result
    1883            0 :     }
    1884              : 
    1885            0 :     pub(crate) fn list_tenants(
    1886            0 :         &self,
    1887            0 :     ) -> Result<Vec<(TenantShardId, TenantState, Generation)>, TenantMapListError> {
    1888            0 :         let tenants = self.tenants.read().unwrap();
    1889            0 :         let m = match &*tenants {
    1890            0 :             TenantsMap::Initializing => return Err(TenantMapListError::Initializing),
    1891            0 :             TenantsMap::Open(m) | TenantsMap::ShuttingDown(m) => m,
    1892            0 :         };
    1893            0 :         Ok(m.iter()
    1894            0 :             .filter_map(|(id, tenant)| match tenant {
    1895            0 :                 TenantSlot::Attached(tenant) => {
    1896            0 :                     Some((*id, tenant.current_state(), tenant.generation()))
    1897              :                 }
    1898            0 :                 TenantSlot::Secondary(_) => None,
    1899            0 :                 TenantSlot::InProgress(_) => None,
    1900            0 :             })
    1901            0 :             .collect())
    1902            0 :     }
    1903              : 
    1904              :     /// Completes an earlier prepared timeline detach ancestor.
    1905            0 :     pub(crate) async fn complete_detaching_timeline_ancestor(
    1906            0 :         &self,
    1907            0 :         tenant_shard_id: TenantShardId,
    1908            0 :         timeline_id: TimelineId,
    1909            0 :         prepared: PreparedTimelineDetach,
    1910            0 :         mut attempt: detach_ancestor::Attempt,
    1911            0 :         ctx: &RequestContext,
    1912            0 :     ) -> Result<HashSet<TimelineId>, detach_ancestor::Error> {
    1913              :         use detach_ancestor::Error;
    1914              : 
    1915            0 :         let slot_guard =
    1916            0 :             tenant_map_acquire_slot(&tenant_shard_id, TenantSlotAcquireMode::MustExist).map_err(
    1917            0 :                 |e| {
    1918              :                     use TenantSlotError::*;
    1919              : 
    1920            0 :                     match e {
    1921            0 :                         MapState(TenantMapError::ShuttingDown) => Error::ShuttingDown,
    1922            0 :                         NotFound(_) | InProgress | MapState(_) => Error::DetachReparent(e.into()),
    1923              :                     }
    1924            0 :                 },
    1925            0 :             )?;
    1926              : 
    1927            0 :         let tenant = {
    1928            0 :             let old_slot = slot_guard
    1929            0 :                 .get_old_value()
    1930            0 :                 .as_ref()
    1931            0 :                 .expect("requested MustExist");
    1932              : 
    1933            0 :             let Some(tenant) = old_slot.get_attached() else {
    1934            0 :                 return Err(Error::DetachReparent(anyhow::anyhow!(
    1935            0 :                     "Tenant is not in attached state"
    1936            0 :                 )));
    1937              :             };
    1938              : 
    1939            0 :             if !tenant.is_active() {
    1940            0 :                 return Err(Error::DetachReparent(anyhow::anyhow!(
    1941            0 :                     "Tenant is not active"
    1942            0 :                 )));
    1943            0 :             }
    1944            0 : 
    1945            0 :             tenant.clone()
    1946              :         };
    1947              : 
    1948            0 :         let timeline = tenant
    1949            0 :             .get_timeline(timeline_id, true)
    1950            0 :             .map_err(Error::NotFound)?;
    1951              : 
    1952            0 :         let resp = timeline
    1953            0 :             .detach_from_ancestor_and_reparent(&tenant, prepared, ctx)
    1954            0 :             .await?;
    1955              : 
    1956            0 :         let mut slot_guard = slot_guard;
    1957              : 
    1958            0 :         let tenant = if resp.reset_tenant_required() {
    1959            0 :             attempt.before_reset_tenant();
    1960            0 : 
    1961            0 :             let (_guard, progress) = utils::completion::channel();
    1962            0 :             match tenant.shutdown(progress, ShutdownMode::Flush).await {
    1963            0 :                 Ok(()) => {
    1964            0 :                     slot_guard.drop_old_value().expect("it was just shutdown");
    1965            0 :                 }
    1966            0 :                 Err(_barrier) => {
    1967            0 :                     slot_guard.revert();
    1968            0 :                     // this really should not happen, at all, unless a shutdown without acquiring
    1969            0 :                     // tenant slot was already going? regardless, on restart the attempt tracking
    1970            0 :                     // will reset to retryable.
    1971            0 :                     return Err(Error::ShuttingDown);
    1972              :                 }
    1973              :             }
    1974              : 
    1975            0 :             let tenant_path = self.conf.tenant_path(&tenant_shard_id);
    1976            0 :             let config = Tenant::load_tenant_config(self.conf, &tenant_shard_id)
    1977            0 :                 .map_err(|e| Error::DetachReparent(e.into()))?;
    1978              : 
    1979            0 :             let shard_identity = config.shard;
    1980            0 :             let tenant = tenant_spawn(
    1981            0 :                 self.conf,
    1982            0 :                 tenant_shard_id,
    1983            0 :                 &tenant_path,
    1984            0 :                 self.resources.clone(),
    1985            0 :                 AttachedTenantConf::try_from(config).map_err(Error::DetachReparent)?,
    1986            0 :                 shard_identity,
    1987            0 :                 None,
    1988            0 :                 SpawnMode::Eager,
    1989            0 :                 ctx,
    1990            0 :             )
    1991            0 :             .map_err(|_| Error::ShuttingDown)?;
    1992              : 
    1993              :             {
    1994            0 :                 let mut g = tenant.ongoing_timeline_detach.lock().unwrap();
    1995            0 :                 assert!(
    1996            0 :                     g.is_none(),
    1997            0 :                     "there cannot be any new timeline detach ancestor on newly created tenant"
    1998              :                 );
    1999            0 :                 *g = Some((attempt.timeline_id, attempt.new_barrier()));
    2000            0 :             }
    2001            0 : 
    2002            0 :             // if we bail out here, we will not allow a new attempt, which should be fine.
    2003            0 :             // pageserver should be shutting down regardless? tenant_reset would help, unless it
    2004            0 :             // runs into the same problem.
    2005            0 :             slot_guard
    2006            0 :                 .upsert(TenantSlot::Attached(tenant.clone()))
    2007            0 :                 .map_err(|e| match e {
    2008            0 :                     TenantSlotUpsertError::ShuttingDown(_) => Error::ShuttingDown,
    2009            0 :                     other => Error::DetachReparent(other.into()),
    2010            0 :                 })?;
    2011            0 :             tenant
    2012              :         } else {
    2013            0 :             tracing::info!("skipping tenant_reset as no changes made required it");
    2014            0 :             tenant
    2015              :         };
    2016              : 
    2017            0 :         if let Some(reparented) = resp.completed() {
    2018              :             // finally ask the restarted tenant to complete the detach
    2019              :             //
    2020              :             // rationale for 9999s: we don't really have a timetable here; if retried, the caller
    2021              :             // will get an 503.
    2022            0 :             tenant
    2023            0 :                 .wait_to_become_active(std::time::Duration::from_secs(9999))
    2024            0 :                 .await
    2025            0 :                 .map_err(|e| {
    2026              :                     use pageserver_api::models::TenantState;
    2027              :                     use GetActiveTenantError::{Cancelled, WillNotBecomeActive};
    2028            0 :                     match e {
    2029              :                         Cancelled | WillNotBecomeActive(TenantState::Stopping { .. }) => {
    2030            0 :                             Error::ShuttingDown
    2031              :                         }
    2032            0 :                         other => Error::Complete(other.into()),
    2033              :                     }
    2034            0 :                 })?;
    2035              : 
    2036            0 :             utils::pausable_failpoint!(
    2037            0 :                 "timeline-detach-ancestor::after_activating_before_finding-pausable"
    2038            0 :             );
    2039              : 
    2040            0 :             let timeline = tenant
    2041            0 :                 .get_timeline(attempt.timeline_id, true)
    2042            0 :                 .map_err(Error::NotFound)?;
    2043              : 
    2044            0 :             timeline
    2045            0 :                 .complete_detaching_timeline_ancestor(&tenant, attempt, ctx)
    2046            0 :                 .await
    2047            0 :                 .map(|()| reparented)
    2048              :         } else {
    2049              :             // at least the latest versions have now been downloaded and refreshed; be ready to
    2050              :             // retry another time.
    2051            0 :             Err(Error::FailedToReparentAll)
    2052              :         }
    2053            0 :     }
    2054              : 
    2055              :     /// A page service client sends a TenantId, and to look up the correct Tenant we must
    2056              :     /// resolve this to a fully qualified TenantShardId.
    2057              :     ///
    2058              :     /// During shard splits: we shall see parent shards in InProgress state and skip them, and
    2059              :     /// instead match on child shards which should appear in Attached state.  Very early in a shard
    2060              :     /// split, or in other cases where a shard is InProgress, we will return our own InProgress result
    2061              :     /// to instruct the caller to wait for that to finish before querying again.
    2062            0 :     pub(crate) fn resolve_attached_shard(
    2063            0 :         &self,
    2064            0 :         tenant_id: &TenantId,
    2065            0 :         selector: ShardSelector,
    2066            0 :     ) -> ShardResolveResult {
    2067            0 :         let tenants = self.tenants.read().unwrap();
    2068            0 :         let mut want_shard = None;
    2069            0 :         let mut any_in_progress = None;
    2070            0 : 
    2071            0 :         match &*tenants {
    2072            0 :             TenantsMap::Initializing => ShardResolveResult::NotFound,
    2073            0 :             TenantsMap::Open(m) | TenantsMap::ShuttingDown(m) => {
    2074            0 :                 for slot in m.range(TenantShardId::tenant_range(*tenant_id)) {
    2075              :                     // Ignore all slots that don't contain an attached tenant
    2076            0 :                     let tenant = match &slot.1 {
    2077            0 :                         TenantSlot::Attached(t) => t,
    2078            0 :                         TenantSlot::InProgress(barrier) => {
    2079            0 :                             // We might still find a usable shard, but in case we don't, remember that
    2080            0 :                             // we saw at least one InProgress slot, so that we can distinguish this case
    2081            0 :                             // from a simple NotFound in our return value.
    2082            0 :                             any_in_progress = Some(barrier.clone());
    2083            0 :                             continue;
    2084              :                         }
    2085            0 :                         _ => continue,
    2086              :                     };
    2087              : 
    2088            0 :                     match selector {
    2089            0 :                         ShardSelector::Zero if slot.0.shard_number == ShardNumber(0) => {
    2090            0 :                             return ShardResolveResult::Found(tenant.clone())
    2091              :                         }
    2092            0 :                         ShardSelector::Page(key) => {
    2093            0 :                             // First slot we see for this tenant, calculate the expected shard number
    2094            0 :                             // for the key: we will use this for checking if this and subsequent
    2095            0 :                             // slots contain the key, rather than recalculating the hash each time.
    2096            0 :                             if want_shard.is_none() {
    2097            0 :                                 want_shard = Some(tenant.shard_identity.get_shard_number(&key));
    2098            0 :                             }
    2099              : 
    2100            0 :                             if Some(tenant.shard_identity.number) == want_shard {
    2101            0 :                                 return ShardResolveResult::Found(tenant.clone());
    2102            0 :                             }
    2103              :                         }
    2104            0 :                         ShardSelector::Known(shard)
    2105            0 :                             if tenant.shard_identity.shard_index() == shard =>
    2106            0 :                         {
    2107            0 :                             return ShardResolveResult::Found(tenant.clone());
    2108              :                         }
    2109            0 :                         _ => continue,
    2110              :                     }
    2111              :                 }
    2112              : 
    2113              :                 // Fall through: we didn't find a slot that was in Attached state & matched our selector.  If
    2114              :                 // we found one or more InProgress slot, indicate to caller that they should retry later.  Otherwise
    2115              :                 // this requested shard simply isn't found.
    2116            0 :                 if let Some(barrier) = any_in_progress {
    2117            0 :                     ShardResolveResult::InProgress(barrier)
    2118              :                 } else {
    2119            0 :                     ShardResolveResult::NotFound
    2120              :                 }
    2121              :             }
    2122              :         }
    2123            0 :     }
    2124              : 
    2125              :     /// Calculate the tenant shards' contributions to this pageserver's utilization metrics.  The
    2126              :     /// returned values are:
    2127              :     ///  - the number of bytes of local disk space this pageserver's shards are requesting, i.e.
    2128              :     ///    how much space they would use if not impacted by disk usage eviction.
    2129              :     ///  - the number of tenant shards currently on this pageserver, including attached
    2130              :     ///    and secondary.
    2131              :     ///
    2132              :     /// This function is quite expensive: callers are expected to cache the result and
    2133              :     /// limit how often they call it.
    2134            0 :     pub(crate) fn calculate_utilization(&self) -> Result<(u64, u32), TenantMapListError> {
    2135            0 :         let tenants = self.tenants.read().unwrap();
    2136            0 :         let m = match &*tenants {
    2137            0 :             TenantsMap::Initializing => return Err(TenantMapListError::Initializing),
    2138            0 :             TenantsMap::Open(m) | TenantsMap::ShuttingDown(m) => m,
    2139            0 :         };
    2140            0 :         let shard_count = m.len();
    2141            0 :         let mut wanted_bytes = 0;
    2142              : 
    2143            0 :         for tenant_slot in m.values() {
    2144            0 :             match tenant_slot {
    2145            0 :                 TenantSlot::InProgress(_barrier) => {
    2146            0 :                     // While a slot is being changed, we can't know how much storage it wants.  This
    2147            0 :                     // means this function's output can fluctuate if a lot of changes are going on
    2148            0 :                     // (such as transitions from secondary to attached).
    2149            0 :                     //
    2150            0 :                     // We could wait for the barrier and retry, but it's important that the utilization
    2151            0 :                     // API is responsive, and the data quality impact is not very significant.
    2152            0 :                     continue;
    2153              :                 }
    2154            0 :                 TenantSlot::Attached(tenant) => {
    2155            0 :                     wanted_bytes += tenant.local_storage_wanted();
    2156            0 :                 }
    2157            0 :                 TenantSlot::Secondary(secondary) => {
    2158            0 :                     let progress = secondary.progress.lock().unwrap();
    2159            0 :                     wanted_bytes += if progress.heatmap_mtime.is_some() {
    2160              :                         // If we have heatmap info, then we will 'want' the sum
    2161              :                         // of the size of layers in the heatmap: this is how much space
    2162              :                         // we would use if not doing any eviction.
    2163            0 :                         progress.bytes_total
    2164              :                     } else {
    2165              :                         // In the absence of heatmap info, assume that the secondary location simply
    2166              :                         // needs as much space as it is currently using.
    2167            0 :                         secondary.resident_size_metric.get()
    2168              :                     }
    2169              :                 }
    2170              :             }
    2171              :         }
    2172              : 
    2173            0 :         Ok((wanted_bytes, shard_count as u32))
    2174            0 :     }
    2175              : 
    2176            0 :     #[instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), %timeline_id))]
    2177              :     pub(crate) async fn immediate_gc(
    2178              :         &self,
    2179              :         tenant_shard_id: TenantShardId,
    2180              :         timeline_id: TimelineId,
    2181              :         gc_req: TimelineGcRequest,
    2182              :         cancel: CancellationToken,
    2183              :         ctx: &RequestContext,
    2184              :     ) -> Result<GcResult, ApiError> {
    2185              :         let tenant = {
    2186              :             let guard = self.tenants.read().unwrap();
    2187              :             guard
    2188              :                 .get(&tenant_shard_id)
    2189              :                 .cloned()
    2190            0 :                 .with_context(|| format!("tenant {tenant_shard_id}"))
    2191            0 :                 .map_err(|e| ApiError::NotFound(e.into()))?
    2192              :         };
    2193              : 
    2194            0 :         let gc_horizon = gc_req.gc_horizon.unwrap_or_else(|| tenant.get_gc_horizon());
    2195              :         // Use tenant's pitr setting
    2196              :         let pitr = tenant.get_pitr_interval();
    2197              : 
    2198              :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    2199              : 
    2200              :         // Run in task_mgr to avoid race with tenant_detach operation
    2201              :         let ctx: RequestContext =
    2202              :             ctx.detached_child(TaskKind::GarbageCollector, DownloadBehavior::Download);
    2203              : 
    2204            0 :         let _gate_guard = tenant.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
    2205              : 
    2206              :         fail::fail_point!("immediate_gc_task_pre");
    2207              : 
    2208              :         #[allow(unused_mut)]
    2209              :         let mut result = tenant
    2210              :             .gc_iteration(Some(timeline_id), gc_horizon, pitr, &cancel, &ctx)
    2211              :             .await;
    2212              :         // FIXME: `gc_iteration` can return an error for multiple reasons; we should handle it
    2213              :         // better once the types support it.
    2214              : 
    2215              :         #[cfg(feature = "testing")]
    2216              :         {
    2217              :             // we need to synchronize with drop completion for python tests without polling for
    2218              :             // log messages
    2219              :             if let Ok(result) = result.as_mut() {
    2220              :                 let mut js = tokio::task::JoinSet::new();
    2221              :                 for layer in std::mem::take(&mut result.doomed_layers) {
    2222              :                     js.spawn(layer.wait_drop());
    2223              :                 }
    2224              :                 tracing::info!(
    2225              :                     total = js.len(),
    2226              :                     "starting to wait for the gc'd layers to be dropped"
    2227              :                 );
    2228              :                 while let Some(res) = js.join_next().await {
    2229              :                     res.expect("wait_drop should not panic");
    2230              :                 }
    2231              :             }
    2232              : 
    2233              :             let timeline = tenant.get_timeline(timeline_id, false).ok();
    2234            0 :             let rtc = timeline.as_ref().map(|x| &x.remote_client);
    2235              : 
    2236              :             if let Some(rtc) = rtc {
    2237              :                 // layer drops schedule actions on remote timeline client to actually do the
    2238              :                 // deletions; don't care about the shutdown error, just exit fast
    2239              :                 drop(rtc.wait_completion().await);
    2240              :             }
    2241              :         }
    2242              : 
    2243            0 :         result.map_err(|e| match e {
    2244            0 :             GcError::TenantCancelled | GcError::TimelineCancelled => ApiError::ShuttingDown,
    2245              :             GcError::TimelineNotFound => {
    2246            0 :                 ApiError::NotFound(anyhow::anyhow!("Timeline not found").into())
    2247              :             }
    2248            0 :             other => ApiError::InternalServerError(anyhow::anyhow!(other)),
    2249            0 :         })
    2250              :     }
    2251              : }
    2252              : 
    2253            0 : #[derive(Debug, thiserror::Error)]
    2254              : pub(crate) enum GetTenantError {
    2255              :     /// NotFound is a TenantId rather than TenantShardId, because this error type is used from
    2256              :     /// getters that use a TenantId and a ShardSelector, not just getters that target a specific shard.
    2257              :     #[error("Tenant {0} not found")]
    2258              :     NotFound(TenantId),
    2259              : 
    2260              :     #[error("Tenant {0} is not active")]
    2261              :     NotActive(TenantShardId),
    2262              : 
    2263              :     // Initializing or shutting down: cannot authoritatively say whether we have this tenant
    2264              :     #[error("Tenant map is not available: {0}")]
    2265              :     MapState(#[from] TenantMapError),
    2266              : }
    2267              : 
    2268            0 : #[derive(thiserror::Error, Debug)]
    2269              : pub(crate) enum GetActiveTenantError {
    2270              :     /// We may time out either while TenantSlot is InProgress, or while the Tenant
    2271              :     /// is in a non-Active state
    2272              :     #[error(
    2273              :         "Timed out waiting {wait_time:?} for tenant active state. Latest state: {latest_state:?}"
    2274              :     )]
    2275              :     WaitForActiveTimeout {
    2276              :         latest_state: Option<TenantState>,
    2277              :         wait_time: Duration,
    2278              :     },
    2279              : 
    2280              :     /// The TenantSlot is absent, or in secondary mode
    2281              :     #[error(transparent)]
    2282              :     NotFound(#[from] GetTenantError),
    2283              : 
    2284              :     /// Cancellation token fired while we were waiting
    2285              :     #[error("cancelled")]
    2286              :     Cancelled,
    2287              : 
    2288              :     /// Tenant exists, but is in a state that cannot become active (e.g. Stopping, Broken)
    2289              :     #[error("will not become active.  Current state: {0}")]
    2290              :     WillNotBecomeActive(TenantState),
    2291              : 
    2292              :     /// Broken is logically a subset of WillNotBecomeActive, but a distinct error is useful as
    2293              :     /// WillNotBecomeActive is a permitted error under some circumstances, whereas broken should
    2294              :     /// never happen.
    2295              :     #[error("Tenant is broken: {0}")]
    2296              :     Broken(String),
    2297              : 
    2298              :     #[error("reconnect to switch tenant id")]
    2299              :     SwitchedTenant,
    2300              : }
    2301              : 
    2302            0 : #[derive(Debug, thiserror::Error)]
    2303              : pub(crate) enum DeleteTimelineError {
    2304              :     #[error("Tenant {0}")]
    2305              :     Tenant(#[from] GetTenantError),
    2306              : 
    2307              :     #[error("Timeline {0}")]
    2308              :     Timeline(#[from] crate::tenant::DeleteTimelineError),
    2309              : }
    2310              : 
    2311            0 : #[derive(Debug, thiserror::Error)]
    2312              : pub(crate) enum TenantStateError {
    2313              :     #[error("Tenant {0} is stopping")]
    2314              :     IsStopping(TenantShardId),
    2315              :     #[error(transparent)]
    2316              :     SlotError(#[from] TenantSlotError),
    2317              :     #[error(transparent)]
    2318              :     SlotUpsertError(#[from] TenantSlotUpsertError),
    2319              :     #[error(transparent)]
    2320              :     Other(#[from] anyhow::Error),
    2321              : }
    2322              : 
    2323            0 : #[derive(Debug, thiserror::Error)]
    2324              : pub(crate) enum TenantMapListError {
    2325              :     #[error("tenant map is still initiailizing")]
    2326              :     Initializing,
    2327              : }
    2328              : 
    2329            0 : #[derive(Debug, thiserror::Error)]
    2330              : pub(crate) enum TenantMapInsertError {
    2331              :     #[error(transparent)]
    2332              :     SlotError(#[from] TenantSlotError),
    2333              :     #[error(transparent)]
    2334              :     SlotUpsertError(#[from] TenantSlotUpsertError),
    2335              :     #[error(transparent)]
    2336              :     Other(#[from] anyhow::Error),
    2337              : }
    2338              : 
    2339              : /// Superset of TenantMapError: issues that can occur when acquiring a slot
    2340              : /// for a particular tenant ID.
    2341            0 : #[derive(Debug, thiserror::Error)]
    2342              : pub(crate) enum TenantSlotError {
    2343              :     /// When acquiring a slot with the expectation that the tenant already exists.
    2344              :     #[error("Tenant {0} not found")]
    2345              :     NotFound(TenantShardId),
    2346              : 
    2347              :     // Tried to read a slot that is currently being mutated by another administrative
    2348              :     // operation.
    2349              :     #[error("tenant has a state change in progress, try again later")]
    2350              :     InProgress,
    2351              : 
    2352              :     #[error(transparent)]
    2353              :     MapState(#[from] TenantMapError),
    2354              : }
    2355              : 
    2356              : /// Superset of TenantMapError: issues that can occur when using a SlotGuard
    2357              : /// to insert a new value.
    2358            0 : #[derive(thiserror::Error)]
    2359              : pub(crate) enum TenantSlotUpsertError {
    2360              :     /// An error where the slot is in an unexpected state, indicating a code bug
    2361              :     #[error("Internal error updating Tenant")]
    2362              :     InternalError(Cow<'static, str>),
    2363              : 
    2364              :     #[error(transparent)]
    2365              :     MapState(TenantMapError),
    2366              : 
    2367              :     // If we encounter TenantManager shutdown during upsert, we must carry the Completion
    2368              :     // from the SlotGuard, so that the caller can hold it while they clean up: otherwise
    2369              :     // TenantManager shutdown might race ahead before we're done cleaning up any Tenant that
    2370              :     // was protected by the SlotGuard.
    2371              :     #[error("Shutting down")]
    2372              :     ShuttingDown((TenantSlot, utils::completion::Completion)),
    2373              : }
    2374              : 
    2375              : impl std::fmt::Debug for TenantSlotUpsertError {
    2376            0 :     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    2377            0 :         match self {
    2378            0 :             Self::InternalError(reason) => write!(f, "Internal Error {reason}"),
    2379            0 :             Self::MapState(map_error) => write!(f, "Tenant map state: {map_error:?}"),
    2380            0 :             Self::ShuttingDown(_completion) => write!(f, "Tenant map shutting down"),
    2381              :         }
    2382            0 :     }
    2383              : }
    2384              : 
    2385            0 : #[derive(Debug, thiserror::Error)]
    2386              : enum TenantSlotDropError {
    2387              :     /// It is only legal to drop a TenantSlot if its contents are fully shut down
    2388              :     #[error("Tenant was not shut down")]
    2389              :     NotShutdown,
    2390              : }
    2391              : 
    2392              : /// Errors that can happen any time we are walking the tenant map to try and acquire
    2393              : /// the TenantSlot for a particular tenant.
    2394            0 : #[derive(Debug, thiserror::Error)]
    2395              : pub(crate) enum TenantMapError {
    2396              :     // Tried to read while initializing
    2397              :     #[error("tenant map is still initializing")]
    2398              :     StillInitializing,
    2399              : 
    2400              :     // Tried to read while shutting down
    2401              :     #[error("tenant map is shutting down")]
    2402              :     ShuttingDown,
    2403              : }
    2404              : 
    2405              : /// Guards a particular tenant_id's content in the TenantsMap.
    2406              : ///
    2407              : /// While this structure exists, the TenantsMap will contain a [`TenantSlot::InProgress`]
    2408              : /// for this tenant, which acts as a marker for any operations targeting
    2409              : /// this tenant to retry later, or wait for the InProgress state to end.
    2410              : ///
    2411              : /// This structure enforces the important invariant that we do not have overlapping
    2412              : /// tasks that will try use local storage for a the same tenant ID: we enforce that
    2413              : /// the previous contents of a slot have been shut down before the slot can be
    2414              : /// left empty or used for something else
    2415              : ///
    2416              : /// Holders of a SlotGuard should explicitly dispose of it, using either `upsert`
    2417              : /// to provide a new value, or `revert` to put the slot back into its initial
    2418              : /// state.  If the SlotGuard is dropped without calling either of these, then
    2419              : /// we will leave the slot empty if our `old_value` is already shut down, else
    2420              : /// we will replace the slot with `old_value` (equivalent to doing a revert).
    2421              : ///
    2422              : /// The `old_value` may be dropped before the SlotGuard is dropped, by calling
    2423              : /// `drop_old_value`.  It is an error to call this without shutting down
    2424              : /// the conents of `old_value`.
    2425              : pub(crate) struct SlotGuard {
    2426              :     tenant_shard_id: TenantShardId,
    2427              :     old_value: Option<TenantSlot>,
    2428              :     upserted: bool,
    2429              : 
    2430              :     /// [`TenantSlot::InProgress`] carries the corresponding Barrier: it will
    2431              :     /// release any waiters as soon as this SlotGuard is dropped.
    2432              :     completion: utils::completion::Completion,
    2433              : }
    2434              : 
    2435              : impl SlotGuard {
    2436            2 :     fn new(
    2437            2 :         tenant_shard_id: TenantShardId,
    2438            2 :         old_value: Option<TenantSlot>,
    2439            2 :         completion: utils::completion::Completion,
    2440            2 :     ) -> Self {
    2441            2 :         Self {
    2442            2 :             tenant_shard_id,
    2443            2 :             old_value,
    2444            2 :             upserted: false,
    2445            2 :             completion,
    2446            2 :         }
    2447            2 :     }
    2448              : 
    2449              :     /// Get any value that was present in the slot before we acquired ownership
    2450              :     /// of it: in state transitions, this will be the old state.
    2451              :     ///
    2452              :     // FIXME: get_ prefix
    2453              :     // FIXME: this should be .as_ref() -- unsure why no clippy
    2454            2 :     fn get_old_value(&self) -> &Option<TenantSlot> {
    2455            2 :         &self.old_value
    2456            2 :     }
    2457              : 
    2458              :     /// Emplace a new value in the slot.  This consumes the guard, and after
    2459              :     /// returning, the slot is no longer protected from concurrent changes.
    2460            0 :     fn upsert(mut self, new_value: TenantSlot) -> Result<(), TenantSlotUpsertError> {
    2461            0 :         if !self.old_value_is_shutdown() {
    2462              :             // This is a bug: callers should never try to drop an old value without
    2463              :             // shutting it down
    2464            0 :             return Err(TenantSlotUpsertError::InternalError(
    2465            0 :                 "Old TenantSlot value not shut down".into(),
    2466            0 :             ));
    2467            0 :         }
    2468              : 
    2469            0 :         let replaced = {
    2470            0 :             let mut locked = TENANTS.write().unwrap();
    2471            0 : 
    2472            0 :             if let TenantSlot::InProgress(_) = new_value {
    2473              :                 // It is never expected to try and upsert InProgress via this path: it should
    2474              :                 // only be written via the tenant_map_acquire_slot path.  If we hit this it's a bug.
    2475            0 :                 return Err(TenantSlotUpsertError::InternalError(
    2476            0 :                     "Attempt to upsert an InProgress state".into(),
    2477            0 :                 ));
    2478            0 :             }
    2479              : 
    2480            0 :             let m = match &mut *locked {
    2481              :                 TenantsMap::Initializing => {
    2482            0 :                     return Err(TenantSlotUpsertError::MapState(
    2483            0 :                         TenantMapError::StillInitializing,
    2484            0 :                     ))
    2485              :                 }
    2486              :                 TenantsMap::ShuttingDown(_) => {
    2487            0 :                     return Err(TenantSlotUpsertError::ShuttingDown((
    2488            0 :                         new_value,
    2489            0 :                         self.completion.clone(),
    2490            0 :                     )));
    2491              :                 }
    2492            0 :                 TenantsMap::Open(m) => m,
    2493            0 :             };
    2494            0 : 
    2495            0 :             METRICS.slot_inserted(&new_value);
    2496            0 : 
    2497            0 :             let replaced = m.insert(self.tenant_shard_id, new_value);
    2498            0 :             self.upserted = true;
    2499            0 :             if let Some(replaced) = replaced.as_ref() {
    2500            0 :                 METRICS.slot_removed(replaced);
    2501            0 :             }
    2502              : 
    2503            0 :             replaced
    2504              :         };
    2505              : 
    2506              :         // Sanity check: on an upsert we should always be replacing an InProgress marker
    2507            0 :         match replaced {
    2508              :             Some(TenantSlot::InProgress(_)) => {
    2509              :                 // Expected case: we find our InProgress in the map: nothing should have
    2510              :                 // replaced it because the code that acquires slots will not grant another
    2511              :                 // one for the same TenantId.
    2512            0 :                 Ok(())
    2513              :             }
    2514              :             None => {
    2515            0 :                 METRICS.unexpected_errors.inc();
    2516            0 :                 error!(
    2517              :                     tenant_shard_id = %self.tenant_shard_id,
    2518            0 :                     "Missing InProgress marker during tenant upsert, this is a bug."
    2519              :                 );
    2520            0 :                 Err(TenantSlotUpsertError::InternalError(
    2521            0 :                     "Missing InProgress marker during tenant upsert".into(),
    2522            0 :                 ))
    2523              :             }
    2524            0 :             Some(slot) => {
    2525            0 :                 METRICS.unexpected_errors.inc();
    2526            0 :                 error!(tenant_shard_id=%self.tenant_shard_id, "Unexpected contents of TenantSlot during upsert, this is a bug.  Contents: {:?}", slot);
    2527            0 :                 Err(TenantSlotUpsertError::InternalError(
    2528            0 :                     "Unexpected contents of TenantSlot".into(),
    2529            0 :                 ))
    2530              :             }
    2531              :         }
    2532            0 :     }
    2533              : 
    2534              :     /// Replace the InProgress slot with whatever was in the guard when we started
    2535            0 :     fn revert(mut self) {
    2536            0 :         if let Some(value) = self.old_value.take() {
    2537            0 :             match self.upsert(value) {
    2538            0 :                 Err(TenantSlotUpsertError::InternalError(_)) => {
    2539            0 :                     // We already logged the error, nothing else we can do.
    2540            0 :                 }
    2541              :                 Err(
    2542              :                     TenantSlotUpsertError::MapState(_) | TenantSlotUpsertError::ShuttingDown(_),
    2543            0 :                 ) => {
    2544            0 :                     // If the map is shutting down, we need not replace anything
    2545            0 :                 }
    2546            0 :                 Ok(()) => {}
    2547              :             }
    2548            0 :         }
    2549            0 :     }
    2550              : 
    2551              :     /// We may never drop our old value until it is cleanly shut down: otherwise we might leave
    2552              :     /// rogue background tasks that would write to the local tenant directory that this guard
    2553              :     /// is responsible for protecting
    2554            2 :     fn old_value_is_shutdown(&self) -> bool {
    2555            2 :         match self.old_value.as_ref() {
    2556            2 :             Some(TenantSlot::Attached(tenant)) => tenant.gate.close_complete(),
    2557            0 :             Some(TenantSlot::Secondary(secondary_tenant)) => secondary_tenant.gate.close_complete(),
    2558              :             Some(TenantSlot::InProgress(_)) => {
    2559              :                 // A SlotGuard cannot be constructed for a slot that was already InProgress
    2560            0 :                 unreachable!()
    2561              :             }
    2562            0 :             None => true,
    2563              :         }
    2564            2 :     }
    2565              : 
    2566              :     /// The guard holder is done with the old value of the slot: they are obliged to already
    2567              :     /// shut it down before we reach this point.
    2568            2 :     fn drop_old_value(&mut self) -> Result<(), TenantSlotDropError> {
    2569            2 :         if !self.old_value_is_shutdown() {
    2570            0 :             Err(TenantSlotDropError::NotShutdown)
    2571              :         } else {
    2572            2 :             self.old_value.take();
    2573            2 :             Ok(())
    2574              :         }
    2575            2 :     }
    2576              : }
    2577              : 
    2578              : impl Drop for SlotGuard {
    2579            2 :     fn drop(&mut self) {
    2580            2 :         if self.upserted {
    2581            0 :             return;
    2582            2 :         }
    2583            2 :         // Our old value is already shutdown, or it never existed: it is safe
    2584            2 :         // for us to fully release the TenantSlot back into an empty state
    2585            2 : 
    2586            2 :         let mut locked = TENANTS.write().unwrap();
    2587              : 
    2588            2 :         let m = match &mut *locked {
    2589              :             TenantsMap::Initializing => {
    2590              :                 // There is no map, this should never happen.
    2591            2 :                 return;
    2592              :             }
    2593              :             TenantsMap::ShuttingDown(_) => {
    2594              :                 // When we transition to shutdown, InProgress elements are removed
    2595              :                 // from the map, so we do not need to clean up our Inprogress marker.
    2596              :                 // See [`shutdown_all_tenants0`]
    2597            0 :                 return;
    2598              :             }
    2599            0 :             TenantsMap::Open(m) => m,
    2600              :         };
    2601              : 
    2602              :         use std::collections::btree_map::Entry;
    2603            0 :         match m.entry(self.tenant_shard_id) {
    2604            0 :             Entry::Occupied(mut entry) => {
    2605            0 :                 if !matches!(entry.get(), TenantSlot::InProgress(_)) {
    2606            0 :                     METRICS.unexpected_errors.inc();
    2607            0 :                     error!(tenant_shard_id=%self.tenant_shard_id, "Unexpected contents of TenantSlot during drop, this is a bug.  Contents: {:?}", entry.get());
    2608            0 :                 }
    2609              : 
    2610            0 :                 if self.old_value_is_shutdown() {
    2611            0 :                     METRICS.slot_removed(entry.get());
    2612            0 :                     entry.remove();
    2613            0 :                 } else {
    2614            0 :                     let inserting = self.old_value.take().unwrap();
    2615            0 :                     METRICS.slot_inserted(&inserting);
    2616            0 :                     let replaced = entry.insert(inserting);
    2617            0 :                     METRICS.slot_removed(&replaced);
    2618            0 :                 }
    2619              :             }
    2620              :             Entry::Vacant(_) => {
    2621            0 :                 METRICS.unexpected_errors.inc();
    2622            0 :                 error!(
    2623              :                     tenant_shard_id = %self.tenant_shard_id,
    2624            0 :                     "Missing InProgress marker during SlotGuard drop, this is a bug."
    2625              :                 );
    2626              :             }
    2627              :         }
    2628            2 :     }
    2629              : }
    2630              : 
    2631              : enum TenantSlotPeekMode {
    2632              :     /// In Read mode, peek will be permitted to see the slots even if the pageserver is shutting down
    2633              :     Read,
    2634              :     /// In Write mode, trying to peek at a slot while the pageserver is shutting down is an error
    2635              :     Write,
    2636              : }
    2637              : 
    2638            0 : fn tenant_map_peek_slot<'a>(
    2639            0 :     tenants: &'a std::sync::RwLockReadGuard<'a, TenantsMap>,
    2640            0 :     tenant_shard_id: &TenantShardId,
    2641            0 :     mode: TenantSlotPeekMode,
    2642            0 : ) -> Result<Option<&'a TenantSlot>, TenantMapError> {
    2643            0 :     match tenants.deref() {
    2644            0 :         TenantsMap::Initializing => Err(TenantMapError::StillInitializing),
    2645            0 :         TenantsMap::ShuttingDown(m) => match mode {
    2646              :             TenantSlotPeekMode::Read => Ok(Some(
    2647              :                 // When reading in ShuttingDown state, we must translate None results
    2648              :                 // into a ShuttingDown error, because absence of a tenant shard ID in the map
    2649              :                 // isn't a reliable indicator of the tenant being gone: it might have been
    2650              :                 // InProgress when shutdown started, and cleaned up from that state such
    2651              :                 // that it's now no longer in the map.  Callers will have to wait until
    2652              :                 // we next start up to get a proper answer.  This avoids incorrect 404 API responses.
    2653            0 :                 m.get(tenant_shard_id).ok_or(TenantMapError::ShuttingDown)?,
    2654              :             )),
    2655            0 :             TenantSlotPeekMode::Write => Err(TenantMapError::ShuttingDown),
    2656              :         },
    2657            0 :         TenantsMap::Open(m) => Ok(m.get(tenant_shard_id)),
    2658              :     }
    2659            0 : }
    2660              : 
    2661              : enum TenantSlotAcquireMode {
    2662              :     /// Acquire the slot irrespective of current state, or whether it already exists
    2663              :     Any,
    2664              :     /// Return an error if trying to acquire a slot and it doesn't already exist
    2665              :     MustExist,
    2666              : }
    2667              : 
    2668            0 : fn tenant_map_acquire_slot(
    2669            0 :     tenant_shard_id: &TenantShardId,
    2670            0 :     mode: TenantSlotAcquireMode,
    2671            0 : ) -> Result<SlotGuard, TenantSlotError> {
    2672            0 :     tenant_map_acquire_slot_impl(tenant_shard_id, &TENANTS, mode)
    2673            0 : }
    2674              : 
    2675            2 : fn tenant_map_acquire_slot_impl(
    2676            2 :     tenant_shard_id: &TenantShardId,
    2677            2 :     tenants: &std::sync::RwLock<TenantsMap>,
    2678            2 :     mode: TenantSlotAcquireMode,
    2679            2 : ) -> Result<SlotGuard, TenantSlotError> {
    2680              :     use TenantSlotAcquireMode::*;
    2681            2 :     METRICS.tenant_slot_writes.inc();
    2682            2 : 
    2683            2 :     let mut locked = tenants.write().unwrap();
    2684            2 :     let span = tracing::info_span!("acquire_slot", tenant_id=%tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug());
    2685            2 :     let _guard = span.enter();
    2686              : 
    2687            2 :     let m = match &mut *locked {
    2688            0 :         TenantsMap::Initializing => return Err(TenantMapError::StillInitializing.into()),
    2689            0 :         TenantsMap::ShuttingDown(_) => return Err(TenantMapError::ShuttingDown.into()),
    2690            2 :         TenantsMap::Open(m) => m,
    2691              :     };
    2692              : 
    2693              :     use std::collections::btree_map::Entry;
    2694              : 
    2695            2 :     let entry = m.entry(*tenant_shard_id);
    2696            2 : 
    2697            2 :     match entry {
    2698            0 :         Entry::Vacant(v) => match mode {
    2699              :             MustExist => {
    2700            0 :                 tracing::debug!("Vacant && MustExist: return NotFound");
    2701            0 :                 Err(TenantSlotError::NotFound(*tenant_shard_id))
    2702              :             }
    2703              :             _ => {
    2704            0 :                 let (completion, barrier) = utils::completion::channel();
    2705            0 :                 let inserting = TenantSlot::InProgress(barrier);
    2706            0 :                 METRICS.slot_inserted(&inserting);
    2707            0 :                 v.insert(inserting);
    2708            0 :                 tracing::debug!("Vacant, inserted InProgress");
    2709            0 :                 Ok(SlotGuard::new(*tenant_shard_id, None, completion))
    2710              :             }
    2711              :         },
    2712            2 :         Entry::Occupied(mut o) => {
    2713            2 :             // Apply mode-driven checks
    2714            2 :             match (o.get(), mode) {
    2715              :                 (TenantSlot::InProgress(_), _) => {
    2716            0 :                     tracing::debug!("Occupied, failing for InProgress");
    2717            0 :                     Err(TenantSlotError::InProgress)
    2718              :                 }
    2719              :                 _ => {
    2720              :                     // Happy case: the slot was not in any state that violated our mode
    2721            2 :                     let (completion, barrier) = utils::completion::channel();
    2722            2 :                     let in_progress = TenantSlot::InProgress(barrier);
    2723            2 :                     METRICS.slot_inserted(&in_progress);
    2724            2 :                     let old_value = o.insert(in_progress);
    2725            2 :                     METRICS.slot_removed(&old_value);
    2726            2 :                     tracing::debug!("Occupied, replaced with InProgress");
    2727            2 :                     Ok(SlotGuard::new(
    2728            2 :                         *tenant_shard_id,
    2729            2 :                         Some(old_value),
    2730            2 :                         completion,
    2731            2 :                     ))
    2732              :                 }
    2733              :             }
    2734              :         }
    2735              :     }
    2736            2 : }
    2737              : 
    2738              : /// Stops and removes the tenant from memory, if it's not [`TenantState::Stopping`] already, bails otherwise.
    2739              : /// Allows to remove other tenant resources manually, via `tenant_cleanup`.
    2740              : /// If the cleanup fails, tenant will stay in memory in [`TenantState::Broken`] state, and another removal
    2741              : /// operation would be needed to remove it.
    2742            2 : async fn remove_tenant_from_memory<V, F>(
    2743            2 :     tenants: &std::sync::RwLock<TenantsMap>,
    2744            2 :     tenant_shard_id: TenantShardId,
    2745            2 :     tenant_cleanup: F,
    2746            2 : ) -> Result<V, TenantStateError>
    2747            2 : where
    2748            2 :     F: std::future::Future<Output = anyhow::Result<V>>,
    2749            2 : {
    2750            2 :     let mut slot_guard =
    2751            2 :         tenant_map_acquire_slot_impl(&tenant_shard_id, tenants, TenantSlotAcquireMode::MustExist)?;
    2752              : 
    2753              :     // allow pageserver shutdown to await for our completion
    2754            2 :     let (_guard, progress) = completion::channel();
    2755              : 
    2756              :     // The SlotGuard allows us to manipulate the Tenant object without fear of some
    2757              :     // concurrent API request doing something else for the same tenant ID.
    2758            2 :     let attached_tenant = match slot_guard.get_old_value() {
    2759            2 :         Some(TenantSlot::Attached(tenant)) => {
    2760            2 :             // whenever we remove a tenant from memory, we don't want to flush and wait for upload
    2761            2 :             let shutdown_mode = ShutdownMode::Hard;
    2762            2 : 
    2763            2 :             // shutdown is sure to transition tenant to stopping, and wait for all tasks to complete, so
    2764            2 :             // that we can continue safely to cleanup.
    2765            2 :             match tenant.shutdown(progress, shutdown_mode).await {
    2766            2 :                 Ok(()) => {}
    2767            0 :                 Err(_other) => {
    2768            0 :                     // if pageserver shutdown or other detach/ignore is already ongoing, we don't want to
    2769            0 :                     // wait for it but return an error right away because these are distinct requests.
    2770            0 :                     slot_guard.revert();
    2771            0 :                     return Err(TenantStateError::IsStopping(tenant_shard_id));
    2772              :                 }
    2773              :             }
    2774            2 :             Some(tenant)
    2775              :         }
    2776            0 :         Some(TenantSlot::Secondary(secondary_state)) => {
    2777            0 :             tracing::info!("Shutting down in secondary mode");
    2778            0 :             secondary_state.shutdown().await;
    2779            0 :             None
    2780              :         }
    2781              :         Some(TenantSlot::InProgress(_)) => {
    2782              :             // Acquiring a slot guarantees its old value was not InProgress
    2783            0 :             unreachable!();
    2784              :         }
    2785            0 :         None => None,
    2786              :     };
    2787              : 
    2788            2 :     match tenant_cleanup
    2789            2 :         .await
    2790            2 :         .with_context(|| format!("Failed to run cleanup for tenant {tenant_shard_id}"))
    2791              :     {
    2792            2 :         Ok(hook_value) => {
    2793            2 :             // Success: drop the old TenantSlot::Attached.
    2794            2 :             slot_guard
    2795            2 :                 .drop_old_value()
    2796            2 :                 .expect("We just called shutdown");
    2797            2 : 
    2798            2 :             Ok(hook_value)
    2799              :         }
    2800            0 :         Err(e) => {
    2801              :             // If we had a Tenant, set it to Broken and put it back in the TenantsMap
    2802            0 :             if let Some(attached_tenant) = attached_tenant {
    2803            0 :                 attached_tenant.set_broken(e.to_string()).await;
    2804            0 :             }
    2805              :             // Leave the broken tenant in the map
    2806            0 :             slot_guard.revert();
    2807            0 : 
    2808            0 :             Err(TenantStateError::Other(e))
    2809              :         }
    2810              :     }
    2811            2 : }
    2812              : 
    2813              : use {
    2814              :     crate::tenant::gc_result::GcResult, pageserver_api::models::TimelineGcRequest,
    2815              :     utils::http::error::ApiError,
    2816              : };
    2817              : 
    2818              : #[cfg(test)]
    2819              : mod tests {
    2820              :     use std::collections::BTreeMap;
    2821              :     use std::sync::Arc;
    2822              :     use tracing::Instrument;
    2823              : 
    2824              :     use crate::tenant::mgr::TenantSlot;
    2825              : 
    2826              :     use super::{super::harness::TenantHarness, TenantsMap};
    2827              : 
    2828              :     #[tokio::test(start_paused = true)]
    2829            2 :     async fn shutdown_awaits_in_progress_tenant() {
    2830            2 :         // Test that if an InProgress tenant is in the map during shutdown, the shutdown will gracefully
    2831            2 :         // wait for it to complete before proceeding.
    2832            2 : 
    2833            2 :         let h = TenantHarness::create("shutdown_awaits_in_progress_tenant")
    2834            2 :             .await
    2835            2 :             .unwrap();
    2836           20 :         let (t, _ctx) = h.load().await;
    2837            2 : 
    2838            2 :         // harness loads it to active, which is forced and nothing is running on the tenant
    2839            2 : 
    2840            2 :         let id = t.tenant_shard_id();
    2841            2 : 
    2842            2 :         // tenant harness configures the logging and we cannot escape it
    2843            2 :         let span = h.span();
    2844            2 :         let _e = span.enter();
    2845            2 : 
    2846            2 :         let tenants = BTreeMap::from([(id, TenantSlot::Attached(t.clone()))]);
    2847            2 :         let tenants = Arc::new(std::sync::RwLock::new(TenantsMap::Open(tenants)));
    2848            2 : 
    2849            2 :         // Invoke remove_tenant_from_memory with a cleanup hook that blocks until we manually
    2850            2 :         // permit it to proceed: that will stick the tenant in InProgress
    2851            2 : 
    2852            2 :         let (until_cleanup_completed, can_complete_cleanup) = utils::completion::channel();
    2853            2 :         let (until_cleanup_started, cleanup_started) = utils::completion::channel();
    2854            2 :         let mut remove_tenant_from_memory_task = {
    2855            2 :             let jh = tokio::spawn({
    2856            2 :                 let tenants = tenants.clone();
    2857            2 :                 async move {
    2858            2 :                     let cleanup = async move {
    2859            2 :                         drop(until_cleanup_started);
    2860            2 :                         can_complete_cleanup.wait().await;
    2861            2 :                         anyhow::Ok(())
    2862            2 :                     };
    2863            2 :                     super::remove_tenant_from_memory(&tenants, id, cleanup).await
    2864            2 :                 }
    2865            2 :                 .instrument(h.span())
    2866            2 :             });
    2867            2 : 
    2868            2 :             // now the long cleanup should be in place, with the stopping state
    2869            2 :             cleanup_started.wait().await;
    2870            2 :             jh
    2871            2 :         };
    2872            2 : 
    2873            2 :         let mut shutdown_task = {
    2874            2 :             let (until_shutdown_started, shutdown_started) = utils::completion::channel();
    2875            2 : 
    2876            2 :             let shutdown_task = tokio::spawn(async move {
    2877            2 :                 drop(until_shutdown_started);
    2878            4 :                 super::shutdown_all_tenants0(&tenants).await;
    2879            2 :             });
    2880            2 : 
    2881            2 :             shutdown_started.wait().await;
    2882            2 :             shutdown_task
    2883            2 :         };
    2884            2 : 
    2885            2 :         let long_time = std::time::Duration::from_secs(15);
    2886            2 :         tokio::select! {
    2887            2 :             _ = &mut shutdown_task => unreachable!("shutdown should block on remove_tenant_from_memory completing"),
    2888            2 :             _ = &mut remove_tenant_from_memory_task => unreachable!("remove_tenant_from_memory_task should not complete until explicitly unblocked"),
    2889            2 :             _ = tokio::time::sleep(long_time) => {},
    2890            2 :         }
    2891            2 : 
    2892            2 :         drop(until_cleanup_completed);
    2893            2 : 
    2894            2 :         // Now that we allow it to proceed, shutdown should complete immediately
    2895            2 :         remove_tenant_from_memory_task.await.unwrap().unwrap();
    2896            2 :         shutdown_task.await.unwrap();
    2897            2 :     }
    2898              : }
        

Generated by: LCOV version 2.1-beta