LCOV - code coverage report
Current view: top level - pageserver/src/tenant - mgr.rs (source / functions) Coverage Total Hit
Test: 42f947419473a288706e86ecdf7c2863d760d5d7.info Lines: 17.1 % 1219 208
Test Date: 2024-08-02 21:34:27 Functions: 10.3 % 165 17

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

Generated by: LCOV version 2.1-beta