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

Generated by: LCOV version 2.1-beta