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

Generated by: LCOV version 2.1-beta