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