LCOV - code coverage report
Current view: top level - pageserver/src/tenant - mgr.rs (source / functions) Coverage Total Hit
Test: 75747cdbffeb0b6d2a2a311584368de68cd9aadc.info Lines: 16.7 % 1219 203
Test Date: 2024-06-24 06:52:57 Functions: 10.4 % 163 17

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

Generated by: LCOV version 2.1-beta