LCOV - code coverage report
Current view: top level - pageserver/src/tenant - mgr.rs (source / functions) Coverage Total Hit
Test: 2b0730d767f560e20b6748f57465922aa8bb805e.info Lines: 16.3 % 1301 212
Test Date: 2024-09-25 14:04:07 Functions: 10.4 % 163 17

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

Generated by: LCOV version 2.1-beta