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

Generated by: LCOV version 2.1-beta