LCOV - code coverage report
Current view: top level - pageserver/src/tenant - mgr.rs (source / functions) Coverage Total Hit
Test: 5187d4b6d9cfe1c429baf0147b0578521d04e1ed.info Lines: 16.8 % 1211 203
Test Date: 2024-06-26 21:48:01 Functions: 10.2 % 166 17

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

Generated by: LCOV version 2.1-beta