LCOV - code coverage report
Current view: top level - pageserver/src/tenant - mgr.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 15.7 % 1190 187
Test Date: 2025-07-16 12:29:03 Functions: 14.4 % 111 16

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

Generated by: LCOV version 2.1-beta