Line data Source code
1 : pub(crate) mod analysis;
2 : pub(crate) mod compaction;
3 : pub mod delete;
4 : pub(crate) mod detach_ancestor;
5 : mod eviction_task;
6 : pub(crate) mod handle;
7 : mod heatmap_layers_downloader;
8 : pub(crate) mod import_pgdata;
9 : mod init;
10 : pub mod layer_manager;
11 : pub(crate) mod logical_size;
12 : pub mod offload;
13 : pub mod span;
14 : pub mod uninit;
15 : mod walreceiver;
16 :
17 : use std::array;
18 : use std::cmp::{max, min};
19 : use std::collections::btree_map::Entry;
20 : use std::collections::{BTreeMap, HashMap, HashSet};
21 : use std::ops::{ControlFlow, Deref, Range};
22 : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as AtomicOrdering};
23 : use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak};
24 : use std::time::{Duration, Instant, SystemTime};
25 :
26 : use anyhow::{Context, Result, anyhow, bail, ensure};
27 : use arc_swap::{ArcSwap, ArcSwapOption};
28 : use bytes::Bytes;
29 : use camino::Utf8Path;
30 : use chrono::{DateTime, Utc};
31 : use compaction::{CompactionOutcome, GcCompactionCombinedSettings};
32 : use enumset::EnumSet;
33 : use fail::fail_point;
34 : use futures::stream::FuturesUnordered;
35 : use futures::{FutureExt, StreamExt};
36 : use handle::ShardTimelineId;
37 : use layer_manager::Shutdown;
38 : use offload::OffloadError;
39 : use once_cell::sync::Lazy;
40 : use pageserver_api::config::tenant_conf_defaults::DEFAULT_PITR_INTERVAL;
41 : use pageserver_api::key::{
42 : KEY_SIZE, Key, METADATA_KEY_BEGIN_PREFIX, METADATA_KEY_END_PREFIX, NON_INHERITED_RANGE,
43 : SPARSE_RANGE,
44 : };
45 : use pageserver_api::keyspace::{KeySpaceAccum, KeySpaceRandomAccum, SparseKeyPartitioning};
46 : use pageserver_api::models::{
47 : CompactKeyRange, CompactLsnRange, CompactionAlgorithm, CompactionAlgorithmSettings,
48 : DetachBehavior, DownloadRemoteLayersTaskInfo, DownloadRemoteLayersTaskSpawnRequest,
49 : EvictionPolicy, InMemoryLayerInfo, LayerMapInfo, LsnLease, PageTraceEvent, RelSizeMigration,
50 : TimelineState,
51 : };
52 : use pageserver_api::reltag::{BlockNumber, RelTag};
53 : use pageserver_api::shard::{ShardIdentity, ShardIndex, ShardNumber, TenantShardId};
54 : #[cfg(test)]
55 : use pageserver_api::value::Value;
56 : use postgres_connection::PgConnectionConfig;
57 : use postgres_ffi::v14::xlog_utils;
58 : use postgres_ffi::{WAL_SEGMENT_SIZE, to_pg_timestamp};
59 : use rand::Rng;
60 : use remote_storage::DownloadError;
61 : use serde_with::serde_as;
62 : use storage_broker::BrokerClientChannel;
63 : use tokio::runtime::Handle;
64 : use tokio::sync::mpsc::Sender;
65 : use tokio::sync::{Notify, oneshot, watch};
66 : use tokio_util::sync::CancellationToken;
67 : use tracing::*;
68 : use utils::generation::Generation;
69 : use utils::guard_arc_swap::GuardArcSwap;
70 : use utils::id::TimelineId;
71 : use utils::logging::{MonitorSlowFutureCallback, monitor_slow_future};
72 : use utils::lsn::{AtomicLsn, Lsn, RecordLsn};
73 : use utils::postgres_client::PostgresClientProtocol;
74 : use utils::rate_limit::RateLimit;
75 : use utils::seqwait::SeqWait;
76 : use utils::simple_rcu::{Rcu, RcuReadGuard};
77 : use utils::sync::gate::{Gate, GateGuard};
78 : use utils::{completion, critical, fs_ext, pausable_failpoint};
79 : use wal_decoder::serialized_batch::{SerializedValueBatch, ValueMeta};
80 :
81 : use self::delete::DeleteTimelineFlow;
82 : pub(super) use self::eviction_task::EvictionTaskTenantState;
83 : use self::eviction_task::EvictionTaskTimelineState;
84 : use self::layer_manager::LayerManager;
85 : use self::logical_size::LogicalSize;
86 : use self::walreceiver::{WalReceiver, WalReceiverConf};
87 : use super::remote_timeline_client::index::{GcCompactionState, IndexPart};
88 : use super::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
89 : use super::secondary::heatmap::HeatMapLayer;
90 : use super::storage_layer::{LayerFringe, LayerVisibilityHint, ReadableLayer};
91 : use super::tasks::log_compaction_error;
92 : use super::upload_queue::NotInitialized;
93 : use super::{
94 : AttachedTenantConf, GcError, HeatMapTimeline, MaybeOffloaded,
95 : debug_assert_current_span_has_tenant_and_timeline_id,
96 : };
97 : use crate::aux_file::AuxFileSizeEstimator;
98 : use crate::config::PageServerConf;
99 : use crate::context::{DownloadBehavior, RequestContext};
100 : use crate::disk_usage_eviction_task::{DiskUsageEvictionInfo, EvictionCandidate, finite_f32};
101 : use crate::keyspace::{KeyPartitioning, KeySpace};
102 : use crate::l0_flush::{self, L0FlushGlobalState};
103 : use crate::metrics::{
104 : DELTAS_PER_READ_GLOBAL, LAYERS_PER_READ_AMORTIZED_GLOBAL, LAYERS_PER_READ_BATCH_GLOBAL,
105 : LAYERS_PER_READ_GLOBAL, ScanLatencyOngoingRecording, TimelineMetrics,
106 : };
107 : use crate::page_service::TenantManagerTypes;
108 : use crate::pgdatadir_mapping::{
109 : CalculateLogicalSizeError, CollectKeySpaceError, DirectoryKind, LsnForTimestamp,
110 : MAX_AUX_FILE_V2_DELTAS, MetricsUpdate,
111 : };
112 : use crate::task_mgr::TaskKind;
113 : use crate::tenant::config::AttachmentMode;
114 : use crate::tenant::gc_result::GcResult;
115 : use crate::tenant::layer_map::{LayerMap, SearchResult};
116 : use crate::tenant::metadata::TimelineMetadata;
117 : use crate::tenant::storage_layer::delta_layer::DeltaEntry;
118 : use crate::tenant::storage_layer::inmemory_layer::IndexEntry;
119 : use crate::tenant::storage_layer::{
120 : AsLayerDesc, BatchLayerWriter, DeltaLayerWriter, EvictionError, ImageLayerName,
121 : ImageLayerWriter, InMemoryLayer, IoConcurrency, Layer, LayerAccessStatsReset, LayerName,
122 : PersistentLayerDesc, PersistentLayerKey, ResidentLayer, ValueReconstructSituation,
123 : ValueReconstructState, ValuesReconstructState,
124 : };
125 : use crate::tenant::tasks::BackgroundLoopKind;
126 : use crate::tenant::timeline::logical_size::CurrentLogicalSize;
127 : use crate::virtual_file::{MaybeFatalIo, VirtualFile};
128 : use crate::walingest::WalLagCooldown;
129 : use crate::{ZERO_PAGE, task_mgr, walredo};
130 :
131 : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
132 : pub(crate) enum FlushLoopState {
133 : NotStarted,
134 : Running {
135 : #[cfg(test)]
136 : expect_initdb_optimization: bool,
137 : #[cfg(test)]
138 : initdb_optimization_count: usize,
139 : },
140 : Exited,
141 : }
142 :
143 : #[derive(Debug, Copy, Clone, PartialEq, Eq)]
144 : pub enum ImageLayerCreationMode {
145 : /// Try to create image layers based on `time_for_new_image_layer`. Used in compaction code path.
146 : Try,
147 : /// Force creating the image layers if possible. For now, no image layers will be created
148 : /// for metadata keys. Used in compaction code path with force flag enabled.
149 : Force,
150 : /// Initial ingestion of the data, and no data should be dropped in this function. This
151 : /// means that no metadata keys should be included in the partitions. Used in flush frozen layer
152 : /// code path.
153 : Initial,
154 : }
155 :
156 : #[derive(Clone, Debug, Default)]
157 : pub enum LastImageLayerCreationStatus {
158 : Incomplete {
159 : /// The last key of the partition (exclusive) that was processed in the last
160 : /// image layer creation attempt. We will continue from this key in the next
161 : /// attempt.
162 : last_key: Key,
163 : },
164 : Complete,
165 : #[default]
166 : Initial,
167 : }
168 :
169 : impl std::fmt::Display for ImageLayerCreationMode {
170 1145 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 1145 : write!(f, "{:?}", self)
172 1145 : }
173 : }
174 :
175 : /// Temporary function for immutable storage state refactor, ensures we are dropping mutex guard instead of other things.
176 : /// Can be removed after all refactors are done.
177 56 : fn drop_rlock<T>(rlock: tokio::sync::RwLockReadGuard<T>) {
178 56 : drop(rlock)
179 56 : }
180 :
181 : /// Temporary function for immutable storage state refactor, ensures we are dropping mutex guard instead of other things.
182 : /// Can be removed after all refactors are done.
183 1201 : fn drop_wlock<T>(rlock: tokio::sync::RwLockWriteGuard<'_, T>) {
184 1201 : drop(rlock)
185 1201 : }
186 :
187 : /// The outward-facing resources required to build a Timeline
188 : pub struct TimelineResources {
189 : pub remote_client: RemoteTimelineClient,
190 : pub pagestream_throttle: Arc<crate::tenant::throttle::Throttle>,
191 : pub pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
192 : pub l0_compaction_trigger: Arc<Notify>,
193 : pub l0_flush_global_state: l0_flush::L0FlushGlobalState,
194 : }
195 :
196 : /// The relation size cache caches relation sizes at the end of the timeline. It speeds up WAL
197 : /// ingestion considerably, because WAL ingestion needs to check on most records if the record
198 : /// implicitly extends the relation. At startup, `complete_as_of` is initialized to the current end
199 : /// of the timeline (disk_consistent_lsn). It's used on reads of relation sizes to check if the
200 : /// value can be used to also update the cache, see [`Timeline::update_cached_rel_size`].
201 : pub(crate) struct RelSizeCache {
202 : pub(crate) complete_as_of: Lsn,
203 : pub(crate) map: HashMap<RelTag, (Lsn, BlockNumber)>,
204 : }
205 :
206 : pub struct Timeline {
207 : pub(crate) conf: &'static PageServerConf,
208 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
209 :
210 : myself: Weak<Self>,
211 :
212 : pub(crate) tenant_shard_id: TenantShardId,
213 : pub timeline_id: TimelineId,
214 :
215 : /// The generation of the tenant that instantiated us: this is used for safety when writing remote objects.
216 : /// Never changes for the lifetime of this [`Timeline`] object.
217 : ///
218 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
219 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
220 : pub(crate) generation: Generation,
221 :
222 : /// The detailed sharding information from our parent Tenant. This enables us to map keys
223 : /// to shards, and is constant through the lifetime of this Timeline.
224 : shard_identity: ShardIdentity,
225 :
226 : pub pg_version: u32,
227 :
228 : /// The tuple has two elements.
229 : /// 1. `LayerFileManager` keeps track of the various physical representations of the layer files (inmem, local, remote).
230 : /// 2. `LayerMap`, the acceleration data structure for `get_reconstruct_data`.
231 : ///
232 : /// `LayerMap` maps out the `(PAGE,LSN) / (KEY,LSN)` space, which is composed of `(KeyRange, LsnRange)` rectangles.
233 : /// We describe these rectangles through the `PersistentLayerDesc` struct.
234 : ///
235 : /// When we want to reconstruct a page, we first find the `PersistentLayerDesc`'s that we need for page reconstruction,
236 : /// using `LayerMap`. Then, we use `LayerFileManager` to get the `PersistentLayer`'s that correspond to the
237 : /// `PersistentLayerDesc`'s.
238 : ///
239 : /// Hence, it's important to keep things coherent. The `LayerFileManager` must always have an entry for all
240 : /// `PersistentLayerDesc`'s in the `LayerMap`. If it doesn't, `LayerFileManager::get_from_desc` will panic at
241 : /// runtime, e.g., during page reconstruction.
242 : ///
243 : /// In the future, we'll be able to split up the tuple of LayerMap and `LayerFileManager`,
244 : /// so that e.g. on-demand-download/eviction, and layer spreading, can operate just on `LayerFileManager`.
245 : pub(crate) layers: tokio::sync::RwLock<LayerManager>,
246 :
247 : last_freeze_at: AtomicLsn,
248 : // Atomic would be more appropriate here.
249 : last_freeze_ts: RwLock<Instant>,
250 :
251 : pub(crate) standby_horizon: AtomicLsn,
252 :
253 : // WAL redo manager. `None` only for broken tenants.
254 : walredo_mgr: Option<Arc<super::WalRedoManager>>,
255 :
256 : /// Remote storage client.
257 : /// See [`remote_timeline_client`](super::remote_timeline_client) module comment for details.
258 : pub(crate) remote_client: Arc<RemoteTimelineClient>,
259 :
260 : // What page versions do we hold in the repository? If we get a
261 : // request > last_record_lsn, we need to wait until we receive all
262 : // the WAL up to the request. The SeqWait provides functions for
263 : // that. TODO: If we get a request for an old LSN, such that the
264 : // versions have already been garbage collected away, we should
265 : // throw an error, but we don't track that currently.
266 : //
267 : // last_record_lsn.load().last points to the end of last processed WAL record.
268 : //
269 : // We also remember the starting point of the previous record in
270 : // 'last_record_lsn.load().prev'. It's used to set the xl_prev pointer of the
271 : // first WAL record when the node is started up. But here, we just
272 : // keep track of it.
273 : last_record_lsn: SeqWait<RecordLsn, Lsn>,
274 :
275 : // All WAL records have been processed and stored durably on files on
276 : // local disk, up to this LSN. On crash and restart, we need to re-process
277 : // the WAL starting from this point.
278 : //
279 : // Some later WAL records might have been processed and also flushed to disk
280 : // already, so don't be surprised to see some, but there's no guarantee on
281 : // them yet.
282 : disk_consistent_lsn: AtomicLsn,
283 :
284 : // Parent timeline that this timeline was branched from, and the LSN
285 : // of the branch point.
286 : ancestor_timeline: Option<Arc<Timeline>>,
287 : ancestor_lsn: Lsn,
288 :
289 : // The LSN of gc-compaction that was last applied to this timeline.
290 : gc_compaction_state: ArcSwap<Option<GcCompactionState>>,
291 :
292 : pub(crate) metrics: Arc<TimelineMetrics>,
293 :
294 : // `Timeline` doesn't write these metrics itself, but it manages the lifetime. Code
295 : // in `crate::page_service` writes these metrics.
296 : pub(crate) query_metrics: crate::metrics::SmgrQueryTimePerTimeline,
297 :
298 : directory_metrics_inited: [AtomicBool; DirectoryKind::KINDS_NUM],
299 : directory_metrics: [AtomicU64; DirectoryKind::KINDS_NUM],
300 :
301 : /// Ensures layers aren't frozen by checkpointer between
302 : /// [`Timeline::get_layer_for_write`] and layer reads.
303 : /// Locked automatically by [`TimelineWriter`] and checkpointer.
304 : /// Must always be acquired before the layer map/individual layer lock
305 : /// to avoid deadlock.
306 : ///
307 : /// The state is cleared upon freezing.
308 : write_lock: tokio::sync::Mutex<Option<TimelineWriterState>>,
309 :
310 : /// Used to avoid multiple `flush_loop` tasks running
311 : pub(super) flush_loop_state: Mutex<FlushLoopState>,
312 :
313 : /// layer_flush_start_tx can be used to wake up the layer-flushing task.
314 : /// - The u64 value is a counter, incremented every time a new flush cycle is requested.
315 : /// The flush cycle counter is sent back on the layer_flush_done channel when
316 : /// the flush finishes. You can use that to wait for the flush to finish.
317 : /// - The LSN is updated to max() of its current value and the latest disk_consistent_lsn
318 : /// read by whoever sends an update
319 : layer_flush_start_tx: tokio::sync::watch::Sender<(u64, Lsn)>,
320 : /// to be notified when layer flushing has finished, subscribe to the layer_flush_done channel
321 : layer_flush_done_tx: tokio::sync::watch::Sender<(u64, Result<(), FlushLayerError>)>,
322 :
323 : // The LSN at which we have executed GC: whereas [`Self::gc_info`] records the LSN at which
324 : // we _intend_ to GC (i.e. the PITR cutoff), this LSN records where we actually last did it.
325 : // Because PITR interval is mutable, it's possible for this LSN to be earlier or later than
326 : // the planned GC cutoff.
327 : pub applied_gc_cutoff_lsn: Rcu<Lsn>,
328 :
329 : pub(crate) gc_compaction_layer_update_lock: tokio::sync::RwLock<()>,
330 :
331 : // List of child timelines and their branch points. This is needed to avoid
332 : // garbage collecting data that is still needed by the child timelines.
333 : pub(crate) gc_info: std::sync::RwLock<GcInfo>,
334 :
335 : pub(crate) last_image_layer_creation_status: ArcSwap<LastImageLayerCreationStatus>,
336 :
337 : // It may change across major versions so for simplicity
338 : // keep it after running initdb for a timeline.
339 : // It is needed in checks when we want to error on some operations
340 : // when they are requested for pre-initdb lsn.
341 : // It can be unified with latest_gc_cutoff_lsn under some "first_valid_lsn",
342 : // though let's keep them both for better error visibility.
343 : pub initdb_lsn: Lsn,
344 :
345 : /// The repartitioning result. Allows a single writer and multiple readers.
346 : pub(crate) partitioning: GuardArcSwap<((KeyPartitioning, SparseKeyPartitioning), Lsn)>,
347 :
348 : /// Configuration: how often should the partitioning be recalculated.
349 : repartition_threshold: u64,
350 :
351 : last_image_layer_creation_check_at: AtomicLsn,
352 : last_image_layer_creation_check_instant: std::sync::Mutex<Option<Instant>>,
353 :
354 : /// Current logical size of the "datadir", at the last LSN.
355 : current_logical_size: LogicalSize,
356 :
357 : /// Information about the last processed message by the WAL receiver,
358 : /// or None if WAL receiver has not received anything for this timeline
359 : /// yet.
360 : pub last_received_wal: Mutex<Option<WalReceiverInfo>>,
361 : pub walreceiver: Mutex<Option<WalReceiver>>,
362 :
363 : /// Relation size cache
364 : pub(crate) rel_size_cache: RwLock<RelSizeCache>,
365 :
366 : download_all_remote_layers_task_info: RwLock<Option<DownloadRemoteLayersTaskInfo>>,
367 :
368 : state: watch::Sender<TimelineState>,
369 :
370 : /// Prevent two tasks from deleting the timeline at the same time. If held, the
371 : /// timeline is being deleted. If 'true', the timeline has already been deleted.
372 : pub delete_progress: TimelineDeleteProgress,
373 :
374 : eviction_task_timeline_state: tokio::sync::Mutex<EvictionTaskTimelineState>,
375 :
376 : /// Load or creation time information about the disk_consistent_lsn and when the loading
377 : /// happened. Used for consumption metrics.
378 : pub(crate) loaded_at: (Lsn, SystemTime),
379 :
380 : /// Gate to prevent shutdown completing while I/O is still happening to this timeline's data
381 : pub(crate) gate: Gate,
382 :
383 : /// Cancellation token scoped to this timeline: anything doing long-running work relating
384 : /// to the timeline should drop out when this token fires.
385 : pub(crate) cancel: CancellationToken,
386 :
387 : /// Make sure we only have one running compaction at a time in tests.
388 : ///
389 : /// Must only be taken in two places:
390 : /// - [`Timeline::compact`] (this file)
391 : /// - [`delete::delete_local_timeline_directory`]
392 : ///
393 : /// Timeline deletion will acquire both compaction and gc locks in whatever order.
394 : compaction_lock: tokio::sync::Mutex<()>,
395 :
396 : /// If true, the last compaction failed.
397 : compaction_failed: AtomicBool,
398 :
399 : /// Notifies the tenant compaction loop that there is pending L0 compaction work.
400 : l0_compaction_trigger: Arc<Notify>,
401 :
402 : /// Make sure we only have one running gc at a time.
403 : ///
404 : /// Must only be taken in two places:
405 : /// - [`Timeline::gc`] (this file)
406 : /// - [`delete::delete_local_timeline_directory`]
407 : ///
408 : /// Timeline deletion will acquire both compaction and gc locks in whatever order.
409 : gc_lock: tokio::sync::Mutex<()>,
410 :
411 : /// Cloned from [`super::Tenant::pagestream_throttle`] on construction.
412 : pub(crate) pagestream_throttle: Arc<crate::tenant::throttle::Throttle>,
413 :
414 : /// Size estimator for aux file v2
415 : pub(crate) aux_file_size_estimator: AuxFileSizeEstimator,
416 :
417 : /// Some test cases directly place keys into the timeline without actually modifying the directory
418 : /// keys (i.e., DB_DIR). The test cases creating such keys will put the keyspaces here, so that
419 : /// these keys won't get garbage-collected during compaction/GC. This field only modifies the dense
420 : /// keyspace return value of `collect_keyspace`. For sparse keyspaces, use AUX keys for testing, and
421 : /// in the future, add `extra_test_sparse_keyspace` if necessary.
422 : #[cfg(test)]
423 : pub(crate) extra_test_dense_keyspace: ArcSwap<KeySpace>,
424 :
425 : pub(crate) l0_flush_global_state: L0FlushGlobalState,
426 :
427 : pub(crate) handles: handle::PerTimelineState<TenantManagerTypes>,
428 :
429 : pub(crate) attach_wal_lag_cooldown: Arc<OnceLock<WalLagCooldown>>,
430 :
431 : /// Cf. [`crate::tenant::CreateTimelineIdempotency`].
432 : pub(crate) create_idempotency: crate::tenant::CreateTimelineIdempotency,
433 :
434 : /// If Some, collects GetPage metadata for an ongoing PageTrace.
435 : pub(crate) page_trace: ArcSwapOption<Sender<PageTraceEvent>>,
436 :
437 : pub(super) previous_heatmap: ArcSwapOption<PreviousHeatmap>,
438 :
439 : /// May host a background Tokio task which downloads all the layers from the current
440 : /// heatmap on demand.
441 : heatmap_layers_downloader: Mutex<Option<heatmap_layers_downloader::HeatmapLayersDownloader>>,
442 :
443 : pub(crate) rel_size_v2_status: ArcSwapOption<RelSizeMigration>,
444 :
445 : wait_lsn_log_slow: tokio::sync::Semaphore,
446 : }
447 :
448 : pub(crate) enum PreviousHeatmap {
449 : Active {
450 : heatmap: HeatMapTimeline,
451 : read_at: std::time::Instant,
452 : // End LSN covered by the heatmap if known
453 : end_lsn: Option<Lsn>,
454 : },
455 : Obsolete,
456 : }
457 :
458 : pub type TimelineDeleteProgress = Arc<tokio::sync::Mutex<DeleteTimelineFlow>>;
459 :
460 : pub struct WalReceiverInfo {
461 : pub wal_source_connconf: PgConnectionConfig,
462 : pub last_received_msg_lsn: Lsn,
463 : pub last_received_msg_ts: u128,
464 : }
465 :
466 : /// Information about how much history needs to be retained, needed by
467 : /// Garbage Collection.
468 : #[derive(Default)]
469 : pub(crate) struct GcInfo {
470 : /// Specific LSNs that are needed.
471 : ///
472 : /// Currently, this includes all points where child branches have
473 : /// been forked off from. In the future, could also include
474 : /// explicit user-defined snapshot points.
475 : pub(crate) retain_lsns: Vec<(Lsn, TimelineId, MaybeOffloaded)>,
476 :
477 : /// The cutoff coordinates, which are combined by selecting the minimum.
478 : pub(crate) cutoffs: GcCutoffs,
479 :
480 : /// Leases granted to particular LSNs.
481 : pub(crate) leases: BTreeMap<Lsn, LsnLease>,
482 :
483 : /// Whether our branch point is within our ancestor's PITR interval (for cost estimation)
484 : pub(crate) within_ancestor_pitr: bool,
485 : }
486 :
487 : impl GcInfo {
488 600 : pub(crate) fn min_cutoff(&self) -> Lsn {
489 600 : self.cutoffs.select_min()
490 600 : }
491 :
492 464 : pub(super) fn insert_child(
493 464 : &mut self,
494 464 : child_id: TimelineId,
495 464 : child_lsn: Lsn,
496 464 : is_offloaded: MaybeOffloaded,
497 464 : ) {
498 464 : self.retain_lsns.push((child_lsn, child_id, is_offloaded));
499 464 : self.retain_lsns.sort_by_key(|i| i.0);
500 464 : }
501 :
502 8 : pub(super) fn remove_child_maybe_offloaded(
503 8 : &mut self,
504 8 : child_id: TimelineId,
505 8 : maybe_offloaded: MaybeOffloaded,
506 8 : ) -> bool {
507 8 : // Remove at most one element. Needed for correctness if there is two live `Timeline` objects referencing
508 8 : // the same timeline. Shouldn't but maybe can occur when Arc's live longer than intended.
509 8 : let mut removed = false;
510 12 : self.retain_lsns.retain(|i| {
511 12 : if removed {
512 4 : return true;
513 8 : }
514 8 : let remove = i.1 == child_id && i.2 == maybe_offloaded;
515 8 : removed |= remove;
516 8 : !remove
517 12 : });
518 8 : removed
519 8 : }
520 :
521 8 : pub(super) fn remove_child_not_offloaded(&mut self, child_id: TimelineId) -> bool {
522 8 : self.remove_child_maybe_offloaded(child_id, MaybeOffloaded::No)
523 8 : }
524 :
525 0 : pub(super) fn remove_child_offloaded(&mut self, child_id: TimelineId) -> bool {
526 0 : self.remove_child_maybe_offloaded(child_id, MaybeOffloaded::Yes)
527 0 : }
528 464 : pub(crate) fn lsn_covered_by_lease(&self, lsn: Lsn) -> bool {
529 464 : self.leases.contains_key(&lsn)
530 464 : }
531 : }
532 :
533 : /// The `GcInfo` component describing which Lsns need to be retained. Functionally, this
534 : /// is a single number (the oldest LSN which we must retain), but it internally distinguishes
535 : /// between time-based and space-based retention for observability and consumption metrics purposes.
536 : #[derive(Debug, Clone)]
537 : pub(crate) struct GcCutoffs {
538 : /// Calculated from the [`pageserver_api::models::TenantConfig::gc_horizon`], this LSN indicates how much
539 : /// history we must keep to retain a specified number of bytes of WAL.
540 : pub(crate) space: Lsn,
541 :
542 : /// Calculated from [`pageserver_api::models::TenantConfig::pitr_interval`], this LSN indicates how much
543 : /// history we must keep to enable reading back at least the PITR interval duration.
544 : pub(crate) time: Lsn,
545 : }
546 :
547 : impl Default for GcCutoffs {
548 904 : fn default() -> Self {
549 904 : Self {
550 904 : space: Lsn::INVALID,
551 904 : time: Lsn::INVALID,
552 904 : }
553 904 : }
554 : }
555 :
556 : impl GcCutoffs {
557 600 : fn select_min(&self) -> Lsn {
558 600 : std::cmp::min(self.space, self.time)
559 600 : }
560 : }
561 :
562 : pub(crate) struct TimelineVisitOutcome {
563 : completed_keyspace: KeySpace,
564 : image_covered_keyspace: KeySpace,
565 : }
566 :
567 : /// An error happened in a get() operation.
568 : #[derive(thiserror::Error, Debug)]
569 : pub(crate) enum PageReconstructError {
570 : #[error(transparent)]
571 : Other(anyhow::Error),
572 :
573 : #[error("Ancestor LSN wait error: {0}")]
574 : AncestorLsnTimeout(WaitLsnError),
575 :
576 : #[error("timeline shutting down")]
577 : Cancelled,
578 :
579 : /// An error happened replaying WAL records
580 : #[error(transparent)]
581 : WalRedo(anyhow::Error),
582 :
583 : #[error("{0}")]
584 : MissingKey(MissingKeyError),
585 : }
586 :
587 : impl From<anyhow::Error> for PageReconstructError {
588 0 : fn from(value: anyhow::Error) -> Self {
589 0 : // with walingest.rs many PageReconstructError are wrapped in as anyhow::Error
590 0 : match value.downcast::<PageReconstructError>() {
591 0 : Ok(pre) => pre,
592 0 : Err(other) => PageReconstructError::Other(other),
593 : }
594 0 : }
595 : }
596 :
597 : impl From<utils::bin_ser::DeserializeError> for PageReconstructError {
598 0 : fn from(value: utils::bin_ser::DeserializeError) -> Self {
599 0 : PageReconstructError::Other(anyhow::Error::new(value).context("deserialization failure"))
600 0 : }
601 : }
602 :
603 : impl From<layer_manager::Shutdown> for PageReconstructError {
604 0 : fn from(_: layer_manager::Shutdown) -> Self {
605 0 : PageReconstructError::Cancelled
606 0 : }
607 : }
608 :
609 : impl GetVectoredError {
610 : #[cfg(test)]
611 12 : pub(crate) fn is_missing_key_error(&self) -> bool {
612 12 : matches!(self, Self::MissingKey(_))
613 12 : }
614 : }
615 :
616 : impl From<layer_manager::Shutdown> for GetVectoredError {
617 0 : fn from(_: layer_manager::Shutdown) -> Self {
618 0 : GetVectoredError::Cancelled
619 0 : }
620 : }
621 :
622 : /// A layer identifier when used in the [`ReadPath`] structure. This enum is for observability purposes
623 : /// only and not used by the "real read path".
624 : pub enum ReadPathLayerId {
625 : PersistentLayer(PersistentLayerKey),
626 : InMemoryLayer(Range<Lsn>),
627 : }
628 :
629 : impl std::fmt::Display for ReadPathLayerId {
630 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
631 0 : match self {
632 0 : ReadPathLayerId::PersistentLayer(key) => write!(f, "{}", key),
633 0 : ReadPathLayerId::InMemoryLayer(range) => {
634 0 : write!(f, "in-mem {}..{}", range.start, range.end)
635 : }
636 : }
637 0 : }
638 : }
639 : pub struct ReadPath {
640 : keyspace: KeySpace,
641 : lsn: Lsn,
642 : path: Vec<(ReadPathLayerId, KeySpace, Range<Lsn>)>,
643 : }
644 :
645 : impl ReadPath {
646 1255388 : pub fn new(keyspace: KeySpace, lsn: Lsn) -> Self {
647 1255388 : Self {
648 1255388 : keyspace,
649 1255388 : lsn,
650 1255388 : path: Vec::new(),
651 1255388 : }
652 1255388 : }
653 :
654 1693249 : pub fn record_layer_visit(
655 1693249 : &mut self,
656 1693249 : layer_to_read: &ReadableLayer,
657 1693249 : keyspace_to_read: &KeySpace,
658 1693249 : lsn_range: &Range<Lsn>,
659 1693249 : ) {
660 1693249 : let id = match layer_to_read {
661 479854 : ReadableLayer::PersistentLayer(layer) => {
662 479854 : ReadPathLayerId::PersistentLayer(layer.layer_desc().key())
663 : }
664 1213395 : ReadableLayer::InMemoryLayer(layer) => {
665 1213395 : ReadPathLayerId::InMemoryLayer(layer.get_lsn_range())
666 : }
667 : };
668 1693249 : self.path
669 1693249 : .push((id, keyspace_to_read.clone(), lsn_range.clone()));
670 1693249 : }
671 : }
672 :
673 : impl std::fmt::Display for ReadPath {
674 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
675 0 : writeln!(f, "Read path for {} at lsn {}:", self.keyspace, self.lsn)?;
676 0 : for (idx, (layer_id, keyspace, lsn_range)) in self.path.iter().enumerate() {
677 0 : writeln!(
678 0 : f,
679 0 : "{}: {} {}..{} {}",
680 0 : idx, layer_id, lsn_range.start, lsn_range.end, keyspace
681 0 : )?;
682 : }
683 0 : Ok(())
684 0 : }
685 : }
686 :
687 : #[derive(thiserror::Error)]
688 : pub struct MissingKeyError {
689 : key: Key,
690 : shard: ShardNumber,
691 : cont_lsn: Lsn,
692 : request_lsn: Lsn,
693 : ancestor_lsn: Option<Lsn>,
694 : /// Debug information about the read path if there's an error
695 : read_path: Option<ReadPath>,
696 : backtrace: Option<std::backtrace::Backtrace>,
697 : }
698 :
699 : impl std::fmt::Debug for MissingKeyError {
700 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
701 0 : write!(f, "{}", self)
702 0 : }
703 : }
704 :
705 : impl std::fmt::Display for MissingKeyError {
706 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
707 0 : write!(
708 0 : f,
709 0 : "could not find data for key {} (shard {:?}) at LSN {}, request LSN {}",
710 0 : self.key, self.shard, self.cont_lsn, self.request_lsn
711 0 : )?;
712 :
713 0 : if let Some(ref ancestor_lsn) = self.ancestor_lsn {
714 0 : write!(f, ", ancestor {}", ancestor_lsn)?;
715 0 : }
716 :
717 0 : if let Some(ref read_path) = self.read_path {
718 0 : write!(f, "\n{}", read_path)?;
719 0 : }
720 :
721 0 : if let Some(ref backtrace) = self.backtrace {
722 0 : write!(f, "\n{}", backtrace)?;
723 0 : }
724 :
725 0 : Ok(())
726 0 : }
727 : }
728 :
729 : impl PageReconstructError {
730 : /// Returns true if this error indicates a tenant/timeline shutdown alike situation
731 0 : pub(crate) fn is_stopping(&self) -> bool {
732 : use PageReconstructError::*;
733 0 : match self {
734 0 : Cancelled => true,
735 0 : Other(_) | AncestorLsnTimeout(_) | WalRedo(_) | MissingKey(_) => false,
736 : }
737 0 : }
738 : }
739 :
740 : #[derive(thiserror::Error, Debug)]
741 : pub(crate) enum CreateImageLayersError {
742 : #[error("timeline shutting down")]
743 : Cancelled,
744 :
745 : #[error("read failed")]
746 : GetVectoredError(#[source] GetVectoredError),
747 :
748 : #[error("reconstruction failed")]
749 : PageReconstructError(#[source] PageReconstructError),
750 :
751 : #[error(transparent)]
752 : Other(#[from] anyhow::Error),
753 : }
754 :
755 : impl From<layer_manager::Shutdown> for CreateImageLayersError {
756 0 : fn from(_: layer_manager::Shutdown) -> Self {
757 0 : CreateImageLayersError::Cancelled
758 0 : }
759 : }
760 :
761 : #[derive(thiserror::Error, Debug, Clone)]
762 : pub(crate) enum FlushLayerError {
763 : /// Timeline cancellation token was cancelled
764 : #[error("timeline shutting down")]
765 : Cancelled,
766 :
767 : /// We tried to flush a layer while the Timeline is in an unexpected state
768 : #[error("cannot flush frozen layers when flush_loop is not running, state is {0:?}")]
769 : NotRunning(FlushLoopState),
770 :
771 : // Arc<> the following non-clonable error types: we must be Clone-able because the flush error is propagated from the flush
772 : // loop via a watch channel, where we can only borrow it.
773 : #[error("create image layers (shared)")]
774 : CreateImageLayersError(Arc<CreateImageLayersError>),
775 :
776 : #[error("other (shared)")]
777 : Other(#[from] Arc<anyhow::Error>),
778 : }
779 :
780 : impl FlushLayerError {
781 : // When crossing from generic anyhow errors to this error type, we explicitly check
782 : // for timeline cancellation to avoid logging inoffensive shutdown errors as warn/err.
783 0 : fn from_anyhow(timeline: &Timeline, err: anyhow::Error) -> Self {
784 0 : let cancelled = timeline.cancel.is_cancelled()
785 : // The upload queue might have been shut down before the official cancellation of the timeline.
786 0 : || err
787 0 : .downcast_ref::<NotInitialized>()
788 0 : .map(NotInitialized::is_stopping)
789 0 : .unwrap_or_default();
790 0 : if cancelled {
791 0 : Self::Cancelled
792 : } else {
793 0 : Self::Other(Arc::new(err))
794 : }
795 0 : }
796 : }
797 :
798 : impl From<layer_manager::Shutdown> for FlushLayerError {
799 0 : fn from(_: layer_manager::Shutdown) -> Self {
800 0 : FlushLayerError::Cancelled
801 0 : }
802 : }
803 :
804 : #[derive(thiserror::Error, Debug)]
805 : pub(crate) enum GetVectoredError {
806 : #[error("timeline shutting down")]
807 : Cancelled,
808 :
809 : #[error("requested too many keys: {0} > {}", Timeline::MAX_GET_VECTORED_KEYS)]
810 : Oversized(u64),
811 :
812 : #[error("requested at invalid LSN: {0}")]
813 : InvalidLsn(Lsn),
814 :
815 : #[error("requested key not found: {0}")]
816 : MissingKey(MissingKeyError),
817 :
818 : #[error("ancestry walk")]
819 : GetReadyAncestorError(#[source] GetReadyAncestorError),
820 :
821 : #[error(transparent)]
822 : Other(#[from] anyhow::Error),
823 : }
824 :
825 : impl From<GetReadyAncestorError> for GetVectoredError {
826 4 : fn from(value: GetReadyAncestorError) -> Self {
827 : use GetReadyAncestorError::*;
828 4 : match value {
829 0 : Cancelled => GetVectoredError::Cancelled,
830 : AncestorLsnTimeout(_) | BadState { .. } => {
831 4 : GetVectoredError::GetReadyAncestorError(value)
832 : }
833 : }
834 4 : }
835 : }
836 :
837 : #[derive(thiserror::Error, Debug)]
838 : pub(crate) enum GetReadyAncestorError {
839 : #[error("ancestor LSN wait error")]
840 : AncestorLsnTimeout(#[from] WaitLsnError),
841 :
842 : #[error("bad state on timeline {timeline_id}: {state:?}")]
843 : BadState {
844 : timeline_id: TimelineId,
845 : state: TimelineState,
846 : },
847 :
848 : #[error("cancelled")]
849 : Cancelled,
850 : }
851 :
852 : #[derive(Clone, Copy)]
853 : pub enum LogicalSizeCalculationCause {
854 : Initial,
855 : ConsumptionMetricsSyntheticSize,
856 : EvictionTaskImitation,
857 : TenantSizeHandler,
858 : }
859 :
860 : pub enum GetLogicalSizePriority {
861 : User,
862 : Background,
863 : }
864 :
865 0 : #[derive(Debug, enumset::EnumSetType)]
866 : pub(crate) enum CompactFlags {
867 : ForceRepartition,
868 : ForceImageLayerCreation,
869 : ForceL0Compaction,
870 : OnlyL0Compaction,
871 : EnhancedGcBottomMostCompaction,
872 : DryRun,
873 : /// Disables compaction yielding e.g. due to high L0 count. This is set e.g. when requesting
874 : /// compaction via HTTP API.
875 : NoYield,
876 : }
877 :
878 : #[serde_with::serde_as]
879 0 : #[derive(Debug, Clone, serde::Deserialize)]
880 : pub(crate) struct CompactRequest {
881 : pub compact_key_range: Option<CompactKeyRange>,
882 : pub compact_lsn_range: Option<CompactLsnRange>,
883 : /// Whether the compaction job should be scheduled.
884 : #[serde(default)]
885 : pub scheduled: bool,
886 : /// Whether the compaction job should be split across key ranges.
887 : #[serde(default)]
888 : pub sub_compaction: bool,
889 : /// Max job size for each subcompaction job.
890 : pub sub_compaction_max_job_size_mb: Option<u64>,
891 : }
892 :
893 : #[derive(Debug, Clone, Default)]
894 : pub(crate) struct CompactOptions {
895 : pub flags: EnumSet<CompactFlags>,
896 : /// If set, the compaction will only compact the key range specified by this option.
897 : /// This option is only used by GC compaction. For the full explanation, see [`compaction::GcCompactJob`].
898 : pub compact_key_range: Option<CompactKeyRange>,
899 : /// If set, the compaction will only compact the LSN within this value.
900 : /// This option is only used by GC compaction. For the full explanation, see [`compaction::GcCompactJob`].
901 : pub compact_lsn_range: Option<CompactLsnRange>,
902 : /// Enable sub-compaction (split compaction job across key ranges).
903 : /// This option is only used by GC compaction.
904 : pub sub_compaction: bool,
905 : /// Set job size for the GC compaction.
906 : /// This option is only used by GC compaction.
907 : pub sub_compaction_max_job_size_mb: Option<u64>,
908 : }
909 :
910 : impl std::fmt::Debug for Timeline {
911 0 : fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
912 0 : write!(f, "Timeline<{}>", self.timeline_id)
913 0 : }
914 : }
915 :
916 : #[derive(thiserror::Error, Debug)]
917 : pub(crate) enum WaitLsnError {
918 : // Called on a timeline which is shutting down
919 : #[error("Shutdown")]
920 : Shutdown,
921 :
922 : // Called on an timeline not in active state or shutting down
923 : #[error("Bad timeline state: {0:?}")]
924 : BadState(TimelineState),
925 :
926 : // Timeout expired while waiting for LSN to catch up with goal.
927 : #[error("{0}")]
928 : Timeout(String),
929 : }
930 :
931 : // The impls below achieve cancellation mapping for errors.
932 : // Perhaps there's a way of achieving this with less cruft.
933 :
934 : impl From<CreateImageLayersError> for CompactionError {
935 0 : fn from(e: CreateImageLayersError) -> Self {
936 0 : match e {
937 0 : CreateImageLayersError::Cancelled => CompactionError::ShuttingDown,
938 0 : CreateImageLayersError::Other(e) => {
939 0 : CompactionError::Other(e.context("create image layers"))
940 : }
941 0 : _ => CompactionError::Other(e.into()),
942 : }
943 0 : }
944 : }
945 :
946 : impl From<CreateImageLayersError> for FlushLayerError {
947 0 : fn from(e: CreateImageLayersError) -> Self {
948 0 : match e {
949 0 : CreateImageLayersError::Cancelled => FlushLayerError::Cancelled,
950 0 : any => FlushLayerError::CreateImageLayersError(Arc::new(any)),
951 : }
952 0 : }
953 : }
954 :
955 : impl From<PageReconstructError> for CreateImageLayersError {
956 0 : fn from(e: PageReconstructError) -> Self {
957 0 : match e {
958 0 : PageReconstructError::Cancelled => CreateImageLayersError::Cancelled,
959 0 : _ => CreateImageLayersError::PageReconstructError(e),
960 : }
961 0 : }
962 : }
963 :
964 : impl From<GetVectoredError> for CreateImageLayersError {
965 0 : fn from(e: GetVectoredError) -> Self {
966 0 : match e {
967 0 : GetVectoredError::Cancelled => CreateImageLayersError::Cancelled,
968 0 : _ => CreateImageLayersError::GetVectoredError(e),
969 : }
970 0 : }
971 : }
972 :
973 : impl From<GetVectoredError> for PageReconstructError {
974 12 : fn from(e: GetVectoredError) -> Self {
975 12 : match e {
976 0 : GetVectoredError::Cancelled => PageReconstructError::Cancelled,
977 0 : GetVectoredError::InvalidLsn(_) => PageReconstructError::Other(anyhow!("Invalid LSN")),
978 0 : err @ GetVectoredError::Oversized(_) => PageReconstructError::Other(err.into()),
979 8 : GetVectoredError::MissingKey(err) => PageReconstructError::MissingKey(err),
980 4 : GetVectoredError::GetReadyAncestorError(err) => PageReconstructError::from(err),
981 0 : GetVectoredError::Other(err) => PageReconstructError::Other(err),
982 : }
983 12 : }
984 : }
985 :
986 : impl From<GetReadyAncestorError> for PageReconstructError {
987 4 : fn from(e: GetReadyAncestorError) -> Self {
988 : use GetReadyAncestorError::*;
989 4 : match e {
990 0 : AncestorLsnTimeout(wait_err) => PageReconstructError::AncestorLsnTimeout(wait_err),
991 4 : bad_state @ BadState { .. } => PageReconstructError::Other(anyhow::anyhow!(bad_state)),
992 0 : Cancelled => PageReconstructError::Cancelled,
993 : }
994 4 : }
995 : }
996 :
997 : pub(crate) enum WaitLsnTimeout {
998 : Custom(Duration),
999 : // Use the [`PageServerConf::wait_lsn_timeout`] default
1000 : Default,
1001 : }
1002 :
1003 : pub(crate) enum WaitLsnWaiter<'a> {
1004 : Timeline(&'a Timeline),
1005 : Tenant,
1006 : PageService,
1007 : HttpEndpoint,
1008 : }
1009 :
1010 : /// Argument to [`Timeline::shutdown`].
1011 : #[derive(Debug, Clone, Copy)]
1012 : pub(crate) enum ShutdownMode {
1013 : /// Graceful shutdown, may do a lot of I/O as we flush any open layers to disk and then
1014 : /// also to remote storage. This method can easily take multiple seconds for a busy timeline.
1015 : ///
1016 : /// While we are flushing, we continue to accept read I/O for LSNs ingested before
1017 : /// the call to [`Timeline::shutdown`].
1018 : FreezeAndFlush,
1019 : /// Only flush the layers to the remote storage without freezing any open layers. Flush the deletion
1020 : /// queue. This is the mode used by ancestor detach and any other operations that reloads a tenant
1021 : /// but not increasing the generation number. Note that this mode cannot be used at tenant shutdown,
1022 : /// as flushing the deletion queue at that time will cause shutdown-in-progress errors.
1023 : Reload,
1024 : /// Shut down immediately, without waiting for any open layers to flush.
1025 : Hard,
1026 : }
1027 :
1028 : enum ImageLayerCreationOutcome {
1029 : /// We generated an image layer
1030 : Generated {
1031 : unfinished_image_layer: ImageLayerWriter,
1032 : },
1033 : /// The key range is empty
1034 : Empty,
1035 : /// (Only used in metadata image layer creation), after reading the metadata keys, we decide to skip
1036 : /// the image layer creation.
1037 : Skip,
1038 : }
1039 :
1040 : /// Public interface functions
1041 : impl Timeline {
1042 : /// Get the LSN where this branch was created
1043 8 : pub(crate) fn get_ancestor_lsn(&self) -> Lsn {
1044 8 : self.ancestor_lsn
1045 8 : }
1046 :
1047 : /// Get the ancestor's timeline id
1048 24 : pub(crate) fn get_ancestor_timeline_id(&self) -> Option<TimelineId> {
1049 24 : self.ancestor_timeline
1050 24 : .as_ref()
1051 24 : .map(|ancestor| ancestor.timeline_id)
1052 24 : }
1053 :
1054 : /// Get the ancestor timeline
1055 4 : pub(crate) fn ancestor_timeline(&self) -> Option<&Arc<Timeline>> {
1056 4 : self.ancestor_timeline.as_ref()
1057 4 : }
1058 :
1059 : /// Get the bytes written since the PITR cutoff on this branch, and
1060 : /// whether this branch's ancestor_lsn is within its parent's PITR.
1061 0 : pub(crate) fn get_pitr_history_stats(&self) -> (u64, bool) {
1062 0 : let gc_info = self.gc_info.read().unwrap();
1063 0 : let history = self
1064 0 : .get_last_record_lsn()
1065 0 : .checked_sub(gc_info.cutoffs.time)
1066 0 : .unwrap_or(Lsn(0))
1067 0 : .0;
1068 0 : (history, gc_info.within_ancestor_pitr)
1069 0 : }
1070 :
1071 : /// Read timeline's GC cutoff: this is the LSN at which GC has started to happen
1072 1707106 : pub(crate) fn get_applied_gc_cutoff_lsn(&self) -> RcuReadGuard<Lsn> {
1073 1707106 : self.applied_gc_cutoff_lsn.read()
1074 1707106 : }
1075 :
1076 : /// Read timeline's planned GC cutoff: this is the logical end of history that users
1077 : /// are allowed to read (based on configured PITR), even if physically we have more history.
1078 0 : pub(crate) fn get_gc_cutoff_lsn(&self) -> Lsn {
1079 0 : self.gc_info.read().unwrap().cutoffs.time
1080 0 : }
1081 :
1082 : /// Look up given page version.
1083 : ///
1084 : /// If a remote layer file is needed, it is downloaded as part of this
1085 : /// call.
1086 : ///
1087 : /// This method enforces [`Self::pagestream_throttle`] internally.
1088 : ///
1089 : /// NOTE: It is considered an error to 'get' a key that doesn't exist. The
1090 : /// abstraction above this needs to store suitable metadata to track what
1091 : /// data exists with what keys, in separate metadata entries. If a
1092 : /// non-existent key is requested, we may incorrectly return a value from
1093 : /// an ancestor branch, for example, or waste a lot of cycles chasing the
1094 : /// non-existing key.
1095 : ///
1096 : /// # Cancel-Safety
1097 : ///
1098 : /// This method is cancellation-safe.
1099 : #[inline(always)]
1100 1215212 : pub(crate) async fn get(
1101 1215212 : &self,
1102 1215212 : key: Key,
1103 1215212 : lsn: Lsn,
1104 1215212 : ctx: &RequestContext,
1105 1215212 : ) -> Result<Bytes, PageReconstructError> {
1106 1215212 : if !lsn.is_valid() {
1107 0 : return Err(PageReconstructError::Other(anyhow::anyhow!("Invalid LSN")));
1108 1215212 : }
1109 1215212 :
1110 1215212 : // This check is debug-only because of the cost of hashing, and because it's a double-check: we
1111 1215212 : // already checked the key against the shard_identity when looking up the Timeline from
1112 1215212 : // page_service.
1113 1215212 : debug_assert!(!self.shard_identity.is_key_disposable(&key));
1114 :
1115 1215212 : let keyspace = KeySpace {
1116 1215212 : ranges: vec![key..key.next()],
1117 1215212 : };
1118 1215212 :
1119 1215212 : let mut reconstruct_state = ValuesReconstructState::new(IoConcurrency::sequential());
1120 :
1121 1215212 : let vectored_res = self
1122 1215212 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
1123 1215212 : .await;
1124 :
1125 1215212 : let key_value = vectored_res?.pop_first();
1126 1215200 : match key_value {
1127 1215176 : Some((got_key, value)) => {
1128 1215176 : if got_key != key {
1129 0 : error!(
1130 0 : "Expected {}, but singular vectored get returned {}",
1131 : key, got_key
1132 : );
1133 0 : Err(PageReconstructError::Other(anyhow!(
1134 0 : "Singular vectored get returned wrong key"
1135 0 : )))
1136 : } else {
1137 1215176 : value
1138 : }
1139 : }
1140 24 : None => Err(PageReconstructError::MissingKey(MissingKeyError {
1141 24 : key,
1142 24 : shard: self.shard_identity.get_shard_number(&key),
1143 24 : cont_lsn: Lsn(0),
1144 24 : request_lsn: lsn,
1145 24 : ancestor_lsn: None,
1146 24 : backtrace: None,
1147 24 : read_path: None,
1148 24 : })),
1149 : }
1150 1215212 : }
1151 :
1152 : pub(crate) const MAX_GET_VECTORED_KEYS: u64 = 32;
1153 : pub(crate) const LAYERS_VISITED_WARN_THRESHOLD: u32 = 100;
1154 :
1155 : /// Look up multiple page versions at a given LSN
1156 : ///
1157 : /// This naive implementation will be replaced with a more efficient one
1158 : /// which actually vectorizes the read path.
1159 39432 : pub(crate) async fn get_vectored(
1160 39432 : &self,
1161 39432 : keyspace: KeySpace,
1162 39432 : lsn: Lsn,
1163 39432 : io_concurrency: super::storage_layer::IoConcurrency,
1164 39432 : ctx: &RequestContext,
1165 39432 : ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
1166 39432 : if !lsn.is_valid() {
1167 0 : return Err(GetVectoredError::InvalidLsn(lsn));
1168 39432 : }
1169 39432 :
1170 39432 : let key_count = keyspace.total_raw_size().try_into().unwrap();
1171 39432 : if key_count > Timeline::MAX_GET_VECTORED_KEYS {
1172 0 : return Err(GetVectoredError::Oversized(key_count));
1173 39432 : }
1174 :
1175 78864 : for range in &keyspace.ranges {
1176 39432 : let mut key = range.start;
1177 79380 : while key != range.end {
1178 39948 : assert!(!self.shard_identity.is_key_disposable(&key));
1179 39948 : key = key.next();
1180 : }
1181 : }
1182 :
1183 39432 : trace!(
1184 0 : "get vectored request for {:?}@{} from task kind {:?}",
1185 0 : keyspace,
1186 0 : lsn,
1187 0 : ctx.task_kind(),
1188 : );
1189 :
1190 39432 : let start = crate::metrics::GET_VECTORED_LATENCY
1191 39432 : .for_task_kind(ctx.task_kind())
1192 39432 : .map(|metric| (metric, Instant::now()));
1193 :
1194 39432 : let res = self
1195 39432 : .get_vectored_impl(
1196 39432 : keyspace.clone(),
1197 39432 : lsn,
1198 39432 : &mut ValuesReconstructState::new(io_concurrency),
1199 39432 : ctx,
1200 39432 : )
1201 39432 : .await;
1202 :
1203 39432 : if let Some((metric, start)) = start {
1204 0 : let elapsed = start.elapsed();
1205 0 : metric.observe(elapsed.as_secs_f64());
1206 39432 : }
1207 :
1208 39432 : res
1209 39432 : }
1210 :
1211 : /// Scan the keyspace and return all existing key-values in the keyspace. This currently uses vectored
1212 : /// get underlying. Normal vectored get would throw an error when a key in the keyspace is not found
1213 : /// during the search, but for the scan interface, it returns all existing key-value pairs, and does
1214 : /// not expect each single key in the key space will be found. The semantics is closer to the RocksDB
1215 : /// scan iterator interface. We could optimize this interface later to avoid some checks in the vectored
1216 : /// get path to maintain and split the probing and to-be-probe keyspace. We also need to ensure that
1217 : /// the scan operation will not cause OOM in the future.
1218 24 : pub(crate) async fn scan(
1219 24 : &self,
1220 24 : keyspace: KeySpace,
1221 24 : lsn: Lsn,
1222 24 : ctx: &RequestContext,
1223 24 : io_concurrency: super::storage_layer::IoConcurrency,
1224 24 : ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
1225 24 : if !lsn.is_valid() {
1226 0 : return Err(GetVectoredError::InvalidLsn(lsn));
1227 24 : }
1228 24 :
1229 24 : trace!(
1230 0 : "key-value scan request for {:?}@{} from task kind {:?}",
1231 0 : keyspace,
1232 0 : lsn,
1233 0 : ctx.task_kind()
1234 : );
1235 :
1236 : // We should generalize this into Keyspace::contains in the future.
1237 48 : for range in &keyspace.ranges {
1238 24 : if range.start.field1 < METADATA_KEY_BEGIN_PREFIX
1239 24 : || range.end.field1 > METADATA_KEY_END_PREFIX
1240 : {
1241 0 : return Err(GetVectoredError::Other(anyhow::anyhow!(
1242 0 : "only metadata keyspace can be scanned"
1243 0 : )));
1244 24 : }
1245 : }
1246 :
1247 24 : let start = crate::metrics::SCAN_LATENCY
1248 24 : .for_task_kind(ctx.task_kind())
1249 24 : .map(ScanLatencyOngoingRecording::start_recording);
1250 :
1251 24 : let vectored_res = self
1252 24 : .get_vectored_impl(
1253 24 : keyspace.clone(),
1254 24 : lsn,
1255 24 : &mut ValuesReconstructState::new(io_concurrency),
1256 24 : ctx,
1257 24 : )
1258 24 : .await;
1259 :
1260 24 : if let Some(recording) = start {
1261 0 : recording.observe();
1262 24 : }
1263 :
1264 24 : vectored_res
1265 24 : }
1266 :
1267 1255388 : pub(super) async fn get_vectored_impl(
1268 1255388 : &self,
1269 1255388 : keyspace: KeySpace,
1270 1255388 : lsn: Lsn,
1271 1255388 : reconstruct_state: &mut ValuesReconstructState,
1272 1255388 : ctx: &RequestContext,
1273 1255388 : ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
1274 1255388 : let read_path = if self.conf.enable_read_path_debugging || ctx.read_path_debug() {
1275 1255388 : Some(ReadPath::new(keyspace.clone(), lsn))
1276 : } else {
1277 0 : None
1278 : };
1279 1255388 : reconstruct_state.read_path = read_path;
1280 :
1281 1255388 : let traversal_res: Result<(), _> = self
1282 1255388 : .get_vectored_reconstruct_data(keyspace.clone(), lsn, reconstruct_state, ctx)
1283 1255388 : .await;
1284 1255388 : if let Err(err) = traversal_res {
1285 : // Wait for all the spawned IOs to complete.
1286 : // See comments on `spawn_io` inside `storage_layer` for more details.
1287 32 : let mut collect_futs = std::mem::take(&mut reconstruct_state.keys)
1288 32 : .into_values()
1289 32 : .map(|state| state.collect_pending_ios())
1290 32 : .collect::<FuturesUnordered<_>>();
1291 32 : while collect_futs.next().await.is_some() {}
1292 32 : return Err(err);
1293 1255356 : };
1294 1255356 :
1295 1255356 : let layers_visited = reconstruct_state.get_layers_visited();
1296 1255356 :
1297 1255356 : let futs = FuturesUnordered::new();
1298 1336060 : for (key, state) in std::mem::take(&mut reconstruct_state.keys) {
1299 1336060 : futs.push({
1300 1336060 : let walredo_self = self.myself.upgrade().expect("&self method holds the arc");
1301 1336060 : async move {
1302 1336060 : assert_eq!(state.situation, ValueReconstructSituation::Complete);
1303 :
1304 1336060 : let converted = match state.collect_pending_ios().await {
1305 1336060 : Ok(ok) => ok,
1306 0 : Err(err) => {
1307 0 : return (key, Err(err));
1308 : }
1309 : };
1310 1336060 : DELTAS_PER_READ_GLOBAL.observe(converted.num_deltas() as f64);
1311 1336060 :
1312 1336060 : // The walredo module expects the records to be descending in terms of Lsn.
1313 1336060 : // And we submit the IOs in that order, so, there shuold be no need to sort here.
1314 1336060 : debug_assert!(
1315 1336060 : converted
1316 1336060 : .records
1317 1336060 : .is_sorted_by_key(|(lsn, _)| std::cmp::Reverse(*lsn)),
1318 0 : "{converted:?}"
1319 : );
1320 :
1321 : (
1322 1336060 : key,
1323 1336060 : walredo_self.reconstruct_value(key, lsn, converted).await,
1324 : )
1325 1336060 : }
1326 1336060 : });
1327 1336060 : }
1328 :
1329 1255356 : let results = futs
1330 1255356 : .collect::<BTreeMap<Key, Result<Bytes, PageReconstructError>>>()
1331 1255356 : .await;
1332 :
1333 : // For aux file keys (v1 or v2) the vectored read path does not return an error
1334 : // when they're missing. Instead they are omitted from the resulting btree
1335 : // (this is a requirement, not a bug). Skip updating the metric in these cases
1336 : // to avoid infinite results.
1337 1255356 : if !results.is_empty() {
1338 1254864 : if layers_visited >= Self::LAYERS_VISITED_WARN_THRESHOLD {
1339 0 : static LOG_PACER: Lazy<Mutex<RateLimit>> =
1340 0 : Lazy::new(|| Mutex::new(RateLimit::new(Duration::from_secs(60))));
1341 0 : LOG_PACER.lock().unwrap().call(|| {
1342 0 : let num_keys = keyspace.total_raw_size();
1343 0 : let num_pages = results.len();
1344 0 : tracing::info!(
1345 0 : shard_id = %self.tenant_shard_id.shard_slug(),
1346 0 : lsn = %lsn,
1347 0 : "Vectored read for {keyspace} visited {layers_visited} layers. Returned {num_pages}/{num_keys} pages.",
1348 : );
1349 0 : });
1350 1254864 : }
1351 :
1352 : // Records the number of layers visited in a few different ways:
1353 : //
1354 : // * LAYERS_PER_READ: all layers count towards every read in the batch, because each
1355 : // layer directly affects its observed latency.
1356 : //
1357 : // * LAYERS_PER_READ_BATCH: all layers count towards each batch, to get the per-batch
1358 : // layer visits and access cost.
1359 : //
1360 : // * LAYERS_PER_READ_AMORTIZED: the average layer count per read, to get the amortized
1361 : // read amplification after batching.
1362 1254864 : let layers_visited = layers_visited as f64;
1363 1254864 : let avg_layers_visited = layers_visited / results.len() as f64;
1364 1254864 : LAYERS_PER_READ_BATCH_GLOBAL.observe(layers_visited);
1365 2590924 : for _ in &results {
1366 1336060 : self.metrics.layers_per_read.observe(layers_visited);
1367 1336060 : LAYERS_PER_READ_GLOBAL.observe(layers_visited);
1368 1336060 : LAYERS_PER_READ_AMORTIZED_GLOBAL.observe(avg_layers_visited);
1369 1336060 : }
1370 492 : }
1371 :
1372 1255356 : Ok(results)
1373 1255388 : }
1374 :
1375 : /// Get last or prev record separately. Same as get_last_record_rlsn().last/prev.
1376 548918 : pub(crate) fn get_last_record_lsn(&self) -> Lsn {
1377 548918 : self.last_record_lsn.load().last
1378 548918 : }
1379 :
1380 0 : pub(crate) fn get_prev_record_lsn(&self) -> Lsn {
1381 0 : self.last_record_lsn.load().prev
1382 0 : }
1383 :
1384 : /// Atomically get both last and prev.
1385 456 : pub(crate) fn get_last_record_rlsn(&self) -> RecordLsn {
1386 456 : self.last_record_lsn.load()
1387 456 : }
1388 :
1389 : /// Subscribe to callers of wait_lsn(). The value of the channel is None if there are no
1390 : /// wait_lsn() calls in progress, and Some(Lsn) if there is an active waiter for wait_lsn().
1391 0 : pub(crate) fn subscribe_for_wait_lsn_updates(&self) -> watch::Receiver<Option<Lsn>> {
1392 0 : self.last_record_lsn.status_receiver()
1393 0 : }
1394 :
1395 896 : pub(crate) fn get_disk_consistent_lsn(&self) -> Lsn {
1396 896 : self.disk_consistent_lsn.load()
1397 896 : }
1398 :
1399 : /// remote_consistent_lsn from the perspective of the tenant's current generation,
1400 : /// not validated with control plane yet.
1401 : /// See [`Self::get_remote_consistent_lsn_visible`].
1402 0 : pub(crate) fn get_remote_consistent_lsn_projected(&self) -> Option<Lsn> {
1403 0 : self.remote_client.remote_consistent_lsn_projected()
1404 0 : }
1405 :
1406 : /// remote_consistent_lsn which the tenant is guaranteed not to go backward from,
1407 : /// i.e. a value of remote_consistent_lsn_projected which has undergone
1408 : /// generation validation in the deletion queue.
1409 0 : pub(crate) fn get_remote_consistent_lsn_visible(&self) -> Option<Lsn> {
1410 0 : self.remote_client.remote_consistent_lsn_visible()
1411 0 : }
1412 :
1413 : /// The sum of the file size of all historic layers in the layer map.
1414 : /// This method makes no distinction between local and remote layers.
1415 : /// Hence, the result **does not represent local filesystem usage**.
1416 0 : pub(crate) async fn layer_size_sum(&self) -> u64 {
1417 0 : let guard = self.layers.read().await;
1418 0 : guard.layer_size_sum()
1419 0 : }
1420 :
1421 0 : pub(crate) fn resident_physical_size(&self) -> u64 {
1422 0 : self.metrics.resident_physical_size_get()
1423 0 : }
1424 :
1425 0 : pub(crate) fn get_directory_metrics(&self) -> [u64; DirectoryKind::KINDS_NUM] {
1426 0 : array::from_fn(|idx| self.directory_metrics[idx].load(AtomicOrdering::Relaxed))
1427 0 : }
1428 :
1429 : ///
1430 : /// Wait until WAL has been received and processed up to this LSN.
1431 : ///
1432 : /// You should call this before any of the other get_* or list_* functions. Calling
1433 : /// those functions with an LSN that has been processed yet is an error.
1434 : ///
1435 451114 : pub(crate) async fn wait_lsn(
1436 451114 : &self,
1437 451114 : lsn: Lsn,
1438 451114 : who_is_waiting: WaitLsnWaiter<'_>,
1439 451114 : timeout: WaitLsnTimeout,
1440 451114 : ctx: &RequestContext, /* Prepare for use by cancellation */
1441 451114 : ) -> Result<(), WaitLsnError> {
1442 451114 : let state = self.current_state();
1443 451114 : if self.cancel.is_cancelled() || matches!(state, TimelineState::Stopping) {
1444 0 : return Err(WaitLsnError::Shutdown);
1445 451114 : } else if !matches!(state, TimelineState::Active) {
1446 0 : return Err(WaitLsnError::BadState(state));
1447 451114 : }
1448 451114 :
1449 451114 : if cfg!(debug_assertions) {
1450 451114 : match ctx.task_kind() {
1451 : TaskKind::WalReceiverManager
1452 : | TaskKind::WalReceiverConnectionHandler
1453 : | TaskKind::WalReceiverConnectionPoller => {
1454 0 : let is_myself = match who_is_waiting {
1455 0 : WaitLsnWaiter::Timeline(waiter) => {
1456 0 : Weak::ptr_eq(&waiter.myself, &self.myself)
1457 : }
1458 : WaitLsnWaiter::Tenant
1459 : | WaitLsnWaiter::PageService
1460 0 : | WaitLsnWaiter::HttpEndpoint => unreachable!(
1461 0 : "tenant or page_service context are not expected to have task kind {:?}",
1462 0 : ctx.task_kind()
1463 0 : ),
1464 : };
1465 0 : if is_myself {
1466 0 : if let Err(current) = self.last_record_lsn.would_wait_for(lsn) {
1467 : // walingest is the only one that can advance last_record_lsn; it should make sure to never reach here
1468 0 : panic!(
1469 0 : "this timeline's walingest task is calling wait_lsn({lsn}) but we only have last_record_lsn={current}; would deadlock"
1470 0 : );
1471 0 : }
1472 0 : } else {
1473 0 : // if another timeline's is waiting for us, there's no deadlock risk because
1474 0 : // our walreceiver task can make progress independent of theirs
1475 0 : }
1476 : }
1477 451114 : _ => {}
1478 : }
1479 0 : }
1480 :
1481 451114 : let timeout = match timeout {
1482 0 : WaitLsnTimeout::Custom(t) => t,
1483 451114 : WaitLsnTimeout::Default => self.conf.wait_lsn_timeout,
1484 : };
1485 :
1486 451114 : let timer = crate::metrics::WAIT_LSN_TIME.start_timer();
1487 451114 : let start_finish_counterpair_guard = self.metrics.wait_lsn_start_finish_counterpair.guard();
1488 451114 :
1489 451114 : let wait_for_timeout = self.last_record_lsn.wait_for_timeout(lsn, timeout);
1490 451114 : let wait_for_timeout = std::pin::pin!(wait_for_timeout);
1491 451114 : // Use threshold of 1 because even 1 second of wait for ingest is very much abnormal.
1492 451114 : let log_slow_threshold = Duration::from_secs(1);
1493 451114 : // Use period of 10 to avoid flooding logs during an outage that affects all timelines.
1494 451114 : let log_slow_period = Duration::from_secs(10);
1495 451114 : let mut logging_permit = None;
1496 451114 : let wait_for_timeout = monitor_slow_future(
1497 451114 : log_slow_threshold,
1498 451114 : log_slow_period,
1499 451114 : wait_for_timeout,
1500 451114 : |MonitorSlowFutureCallback {
1501 : ready,
1502 : is_slow,
1503 : elapsed_total,
1504 : elapsed_since_last_callback,
1505 451114 : }| {
1506 451114 : self.metrics
1507 451114 : .wait_lsn_in_progress_micros
1508 451114 : .inc_by(u64::try_from(elapsed_since_last_callback.as_micros()).unwrap());
1509 451114 : if !is_slow {
1510 451114 : return;
1511 0 : }
1512 0 : // It's slow, see if we should log it.
1513 0 : // (We limit the logging to one per invocation per timeline to avoid excessive
1514 0 : // logging during an extended broker / networking outage that affects all timelines.)
1515 0 : if logging_permit.is_none() {
1516 0 : logging_permit = self.wait_lsn_log_slow.try_acquire().ok();
1517 0 : }
1518 0 : if logging_permit.is_none() {
1519 0 : return;
1520 0 : }
1521 0 : // We log it.
1522 0 : if ready {
1523 0 : info!(
1524 0 : "slow wait_lsn completed after {:.3}s",
1525 0 : elapsed_total.as_secs_f64()
1526 : );
1527 : } else {
1528 0 : info!(
1529 0 : "slow wait_lsn still running for {:.3}s",
1530 0 : elapsed_total.as_secs_f64()
1531 : );
1532 : }
1533 451114 : },
1534 451114 : );
1535 451114 : let res = wait_for_timeout.await;
1536 : // don't count the time spent waiting for lock below, and also in walreceiver.status(), towards the wait_lsn_time_histo
1537 451114 : drop(logging_permit);
1538 451114 : drop(start_finish_counterpair_guard);
1539 451114 : drop(timer);
1540 451114 : match res {
1541 451114 : Ok(()) => Ok(()),
1542 0 : Err(e) => {
1543 : use utils::seqwait::SeqWaitError::*;
1544 0 : match e {
1545 0 : Shutdown => Err(WaitLsnError::Shutdown),
1546 : Timeout => {
1547 0 : let walreceiver_status = self.walreceiver_status();
1548 0 : Err(WaitLsnError::Timeout(format!(
1549 0 : "Timed out while waiting for WAL record at LSN {} to arrive, last_record_lsn {} disk consistent LSN={}, WalReceiver status: {}",
1550 0 : lsn,
1551 0 : self.get_last_record_lsn(),
1552 0 : self.get_disk_consistent_lsn(),
1553 0 : walreceiver_status,
1554 0 : )))
1555 : }
1556 : }
1557 : }
1558 : }
1559 451114 : }
1560 :
1561 0 : pub(crate) fn walreceiver_status(&self) -> String {
1562 0 : match &*self.walreceiver.lock().unwrap() {
1563 0 : None => "stopping or stopped".to_string(),
1564 0 : Some(walreceiver) => match walreceiver.status() {
1565 0 : Some(status) => status.to_human_readable_string(),
1566 0 : None => "Not active".to_string(),
1567 : },
1568 : }
1569 0 : }
1570 :
1571 : /// Check that it is valid to request operations with that lsn.
1572 464 : pub(crate) fn check_lsn_is_in_scope(
1573 464 : &self,
1574 464 : lsn: Lsn,
1575 464 : latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
1576 464 : ) -> anyhow::Result<()> {
1577 464 : ensure!(
1578 464 : lsn >= **latest_gc_cutoff_lsn,
1579 8 : "LSN {} is earlier than latest GC cutoff {} (we might've already garbage collected needed data)",
1580 8 : lsn,
1581 8 : **latest_gc_cutoff_lsn,
1582 : );
1583 456 : Ok(())
1584 464 : }
1585 :
1586 : /// Initializes an LSN lease. The function will return an error if the requested LSN is less than the `latest_gc_cutoff_lsn`.
1587 20 : pub(crate) fn init_lsn_lease(
1588 20 : &self,
1589 20 : lsn: Lsn,
1590 20 : length: Duration,
1591 20 : ctx: &RequestContext,
1592 20 : ) -> anyhow::Result<LsnLease> {
1593 20 : self.make_lsn_lease(lsn, length, true, ctx)
1594 20 : }
1595 :
1596 : /// Renews a lease at a particular LSN. The requested LSN is not validated against the `latest_gc_cutoff_lsn` when we are in the grace period.
1597 8 : pub(crate) fn renew_lsn_lease(
1598 8 : &self,
1599 8 : lsn: Lsn,
1600 8 : length: Duration,
1601 8 : ctx: &RequestContext,
1602 8 : ) -> anyhow::Result<LsnLease> {
1603 8 : self.make_lsn_lease(lsn, length, false, ctx)
1604 8 : }
1605 :
1606 : /// Obtains a temporary lease blocking garbage collection for the given LSN.
1607 : ///
1608 : /// If we are in `AttachedSingle` mode and is not blocked by the lsn lease deadline, this function will error
1609 : /// if the requesting LSN is less than the `latest_gc_cutoff_lsn` and there is no existing request present.
1610 : ///
1611 : /// If there is an existing lease in the map, the lease will be renewed only if the request extends the lease.
1612 : /// The returned lease is therefore the maximum between the existing lease and the requesting lease.
1613 28 : fn make_lsn_lease(
1614 28 : &self,
1615 28 : lsn: Lsn,
1616 28 : length: Duration,
1617 28 : init: bool,
1618 28 : _ctx: &RequestContext,
1619 28 : ) -> anyhow::Result<LsnLease> {
1620 24 : let lease = {
1621 : // Normalize the requested LSN to be aligned, and move to the first record
1622 : // if it points to the beginning of the page (header).
1623 28 : let lsn = xlog_utils::normalize_lsn(lsn, WAL_SEGMENT_SIZE);
1624 28 :
1625 28 : let mut gc_info = self.gc_info.write().unwrap();
1626 28 : let planned_cutoff = gc_info.min_cutoff();
1627 28 :
1628 28 : let valid_until = SystemTime::now() + length;
1629 28 :
1630 28 : let entry = gc_info.leases.entry(lsn);
1631 28 :
1632 28 : match entry {
1633 12 : Entry::Occupied(mut occupied) => {
1634 12 : let existing_lease = occupied.get_mut();
1635 12 : if valid_until > existing_lease.valid_until {
1636 4 : existing_lease.valid_until = valid_until;
1637 4 : let dt: DateTime<Utc> = valid_until.into();
1638 4 : info!("lease extended to {}", dt);
1639 : } else {
1640 8 : let dt: DateTime<Utc> = existing_lease.valid_until.into();
1641 8 : info!("existing lease covers greater length, valid until {}", dt);
1642 : }
1643 :
1644 12 : existing_lease.clone()
1645 : }
1646 16 : Entry::Vacant(vacant) => {
1647 : // Reject already GC-ed LSN if we are in AttachedSingle and
1648 : // not blocked by the lsn lease deadline.
1649 16 : let validate = {
1650 16 : let conf = self.tenant_conf.load();
1651 16 : conf.location.attach_mode == AttachmentMode::Single
1652 16 : && !conf.is_gc_blocked_by_lsn_lease_deadline()
1653 : };
1654 :
1655 16 : if init || validate {
1656 16 : let latest_gc_cutoff_lsn = self.get_applied_gc_cutoff_lsn();
1657 16 : if lsn < *latest_gc_cutoff_lsn {
1658 4 : bail!(
1659 4 : "tried to request an lsn lease for an lsn below the latest gc cutoff. requested at {} gc cutoff {}",
1660 4 : lsn,
1661 4 : *latest_gc_cutoff_lsn
1662 4 : );
1663 12 : }
1664 12 : if lsn < planned_cutoff {
1665 0 : bail!(
1666 0 : "tried to request an lsn lease for an lsn below the planned gc cutoff. requested at {} planned gc cutoff {}",
1667 0 : lsn,
1668 0 : planned_cutoff
1669 0 : );
1670 12 : }
1671 0 : }
1672 :
1673 12 : let dt: DateTime<Utc> = valid_until.into();
1674 12 : info!("lease created, valid until {}", dt);
1675 12 : vacant.insert(LsnLease { valid_until }).clone()
1676 : }
1677 : }
1678 : };
1679 :
1680 24 : Ok(lease)
1681 28 : }
1682 :
1683 : /// Freeze the current open in-memory layer. It will be written to disk on next iteration.
1684 : /// Returns the flush request ID which can be awaited with wait_flush_completion().
1685 : #[instrument(skip(self), fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%self.timeline_id))]
1686 : pub(crate) async fn freeze(&self) -> Result<u64, FlushLayerError> {
1687 : self.freeze0().await
1688 : }
1689 :
1690 : /// Freeze and flush the open in-memory layer, waiting for it to be written to disk.
1691 : #[instrument(skip(self), fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%self.timeline_id))]
1692 : pub(crate) async fn freeze_and_flush(&self) -> Result<(), FlushLayerError> {
1693 : self.freeze_and_flush0().await
1694 : }
1695 :
1696 : /// Freeze the current open in-memory layer. It will be written to disk on next iteration.
1697 : /// Returns the flush request ID which can be awaited with wait_flush_completion().
1698 2252 : pub(crate) async fn freeze0(&self) -> Result<u64, FlushLayerError> {
1699 2252 : let mut g = self.write_lock.lock().await;
1700 2252 : let to_lsn = self.get_last_record_lsn();
1701 2252 : self.freeze_inmem_layer_at(to_lsn, &mut g).await
1702 2252 : }
1703 :
1704 : // This exists to provide a non-span creating version of `freeze_and_flush` we can call without
1705 : // polluting the span hierarchy.
1706 2252 : pub(crate) async fn freeze_and_flush0(&self) -> Result<(), FlushLayerError> {
1707 2252 : let token = self.freeze0().await?;
1708 2252 : self.wait_flush_completion(token).await
1709 2252 : }
1710 :
1711 : // Check if an open ephemeral layer should be closed: this provides
1712 : // background enforcement of checkpoint interval if there is no active WAL receiver, to avoid keeping
1713 : // an ephemeral layer open forever when idle. It also freezes layers if the global limit on
1714 : // ephemeral layer bytes has been breached.
1715 0 : pub(super) async fn maybe_freeze_ephemeral_layer(&self) {
1716 0 : let Ok(mut write_guard) = self.write_lock.try_lock() else {
1717 : // If the write lock is held, there is an active wal receiver: rolling open layers
1718 : // is their responsibility while they hold this lock.
1719 0 : return;
1720 : };
1721 :
1722 : // FIXME: why not early exit? because before #7927 the state would had been cleared every
1723 : // time, and this was missed.
1724 : // if write_guard.is_none() { return; }
1725 :
1726 0 : let Ok(layers_guard) = self.layers.try_read() else {
1727 : // Don't block if the layer lock is busy
1728 0 : return;
1729 : };
1730 :
1731 0 : let Ok(lm) = layers_guard.layer_map() else {
1732 0 : return;
1733 : };
1734 :
1735 0 : let Some(open_layer) = &lm.open_layer else {
1736 : // If there is no open layer, we have no layer freezing to do. However, we might need to generate
1737 : // some updates to disk_consistent_lsn and remote_consistent_lsn, in case we ingested some WAL regions
1738 : // that didn't result in writes to this shard.
1739 :
1740 : // Must not hold the layers lock while waiting for a flush.
1741 0 : drop(layers_guard);
1742 0 :
1743 0 : let last_record_lsn = self.get_last_record_lsn();
1744 0 : let disk_consistent_lsn = self.get_disk_consistent_lsn();
1745 0 : if last_record_lsn > disk_consistent_lsn {
1746 : // We have no open layer, but disk_consistent_lsn is behind the last record: this indicates
1747 : // we are a sharded tenant and have skipped some WAL
1748 0 : let last_freeze_ts = *self.last_freeze_ts.read().unwrap();
1749 0 : if last_freeze_ts.elapsed() >= self.get_checkpoint_timeout() {
1750 : // Only do this if have been layer-less longer than get_checkpoint_timeout, so that a shard
1751 : // without any data ingested (yet) doesn't write a remote index as soon as it
1752 : // sees its LSN advance: we only do this if we've been layer-less
1753 : // for some time.
1754 0 : tracing::debug!(
1755 0 : "Advancing disk_consistent_lsn past WAL ingest gap {} -> {}",
1756 : disk_consistent_lsn,
1757 : last_record_lsn
1758 : );
1759 :
1760 : // The flush loop will update remote consistent LSN as well as disk consistent LSN.
1761 : // We know there is no open layer, so we can request freezing without actually
1762 : // freezing anything. This is true even if we have dropped the layers_guard, we
1763 : // still hold the write_guard.
1764 0 : let _ = async {
1765 0 : let token = self
1766 0 : .freeze_inmem_layer_at(last_record_lsn, &mut write_guard)
1767 0 : .await?;
1768 0 : self.wait_flush_completion(token).await
1769 0 : }
1770 0 : .await;
1771 0 : }
1772 0 : }
1773 :
1774 0 : return;
1775 : };
1776 :
1777 0 : let Some(current_size) = open_layer.try_len() else {
1778 : // Unexpected: since we hold the write guard, nobody else should be writing to this layer, so
1779 : // read lock to get size should always succeed.
1780 0 : tracing::warn!("Lock conflict while reading size of open layer");
1781 0 : return;
1782 : };
1783 :
1784 0 : let current_lsn = self.get_last_record_lsn();
1785 :
1786 0 : let checkpoint_distance_override = open_layer.tick().await;
1787 :
1788 0 : if let Some(size_override) = checkpoint_distance_override {
1789 0 : if current_size > size_override {
1790 : // This is not harmful, but it only happens in relatively rare cases where
1791 : // time-based checkpoints are not happening fast enough to keep the amount of
1792 : // ephemeral data within configured limits. It's a sign of stress on the system.
1793 0 : tracing::info!(
1794 0 : "Early-rolling open layer at size {current_size} (limit {size_override}) due to dirty data pressure"
1795 : );
1796 0 : }
1797 0 : }
1798 :
1799 0 : let checkpoint_distance =
1800 0 : checkpoint_distance_override.unwrap_or(self.get_checkpoint_distance());
1801 0 :
1802 0 : if self.should_roll(
1803 0 : current_size,
1804 0 : current_size,
1805 0 : checkpoint_distance,
1806 0 : self.get_last_record_lsn(),
1807 0 : self.last_freeze_at.load(),
1808 0 : open_layer.get_opened_at(),
1809 0 : ) {
1810 0 : match open_layer.info() {
1811 0 : InMemoryLayerInfo::Frozen { lsn_start, lsn_end } => {
1812 0 : // We may reach this point if the layer was already frozen by not yet flushed: flushing
1813 0 : // happens asynchronously in the background.
1814 0 : tracing::debug!(
1815 0 : "Not freezing open layer, it's already frozen ({lsn_start}..{lsn_end})"
1816 : );
1817 : }
1818 : InMemoryLayerInfo::Open { .. } => {
1819 : // Upgrade to a write lock and freeze the layer
1820 0 : drop(layers_guard);
1821 0 : let res = self
1822 0 : .freeze_inmem_layer_at(current_lsn, &mut write_guard)
1823 0 : .await;
1824 :
1825 0 : if let Err(e) = res {
1826 0 : tracing::info!(
1827 0 : "failed to flush frozen layer after background freeze: {e:#}"
1828 : );
1829 0 : }
1830 : }
1831 : }
1832 0 : }
1833 0 : }
1834 :
1835 : /// Checks if the internal state of the timeline is consistent with it being able to be offloaded.
1836 : ///
1837 : /// This is neccessary but not sufficient for offloading of the timeline as it might have
1838 : /// child timelines that are not offloaded yet.
1839 0 : pub(crate) fn can_offload(&self) -> (bool, &'static str) {
1840 0 : if self.remote_client.is_archived() != Some(true) {
1841 0 : return (false, "the timeline is not archived");
1842 0 : }
1843 0 : if !self.remote_client.no_pending_work() {
1844 : // if the remote client is still processing some work, we can't offload
1845 0 : return (false, "the upload queue is not drained yet");
1846 0 : }
1847 0 :
1848 0 : (true, "ok")
1849 0 : }
1850 :
1851 : /// Outermost timeline compaction operation; downloads needed layers. Returns whether we have pending
1852 : /// compaction tasks.
1853 728 : pub(crate) async fn compact(
1854 728 : self: &Arc<Self>,
1855 728 : cancel: &CancellationToken,
1856 728 : flags: EnumSet<CompactFlags>,
1857 728 : ctx: &RequestContext,
1858 728 : ) -> Result<CompactionOutcome, CompactionError> {
1859 728 : let res = self
1860 728 : .compact_with_options(
1861 728 : cancel,
1862 728 : CompactOptions {
1863 728 : flags,
1864 728 : compact_key_range: None,
1865 728 : compact_lsn_range: None,
1866 728 : sub_compaction: false,
1867 728 : sub_compaction_max_job_size_mb: None,
1868 728 : },
1869 728 : ctx,
1870 728 : )
1871 728 : .await;
1872 728 : if let Err(err) = &res {
1873 0 : log_compaction_error(err, None, cancel.is_cancelled());
1874 728 : }
1875 728 : res
1876 728 : }
1877 :
1878 : /// Outermost timeline compaction operation; downloads needed layers.
1879 : ///
1880 : /// NB: the cancellation token is usually from a background task, but can also come from a
1881 : /// request task.
1882 728 : pub(crate) async fn compact_with_options(
1883 728 : self: &Arc<Self>,
1884 728 : cancel: &CancellationToken,
1885 728 : options: CompactOptions,
1886 728 : ctx: &RequestContext,
1887 728 : ) -> Result<CompactionOutcome, CompactionError> {
1888 728 : // Acquire the compaction lock and task semaphore.
1889 728 : //
1890 728 : // L0-only compaction uses a separate semaphore (if enabled) to make sure it isn't starved
1891 728 : // out by other background tasks (including image compaction). We request this via
1892 728 : // `BackgroundLoopKind::L0Compaction`.
1893 728 : //
1894 728 : // If this is a regular compaction pass, and L0-only compaction is enabled in the config,
1895 728 : // then we should yield for immediate L0 compaction if necessary while we're waiting for the
1896 728 : // background task semaphore. There's no point yielding otherwise, since we'd just end up
1897 728 : // right back here.
1898 728 : let is_l0_only = options.flags.contains(CompactFlags::OnlyL0Compaction);
1899 728 : let semaphore_kind = match is_l0_only && self.get_compaction_l0_semaphore() {
1900 0 : true => BackgroundLoopKind::L0Compaction,
1901 728 : false => BackgroundLoopKind::Compaction,
1902 : };
1903 728 : let yield_for_l0 = !is_l0_only
1904 728 : && self.get_compaction_l0_first()
1905 728 : && !options.flags.contains(CompactFlags::NoYield);
1906 :
1907 728 : let acquire = async move {
1908 725 : let guard = self.compaction_lock.lock().await;
1909 725 : let permit = super::tasks::acquire_concurrency_permit(semaphore_kind, ctx).await;
1910 725 : (guard, permit)
1911 725 : };
1912 :
1913 728 : let (_guard, _permit) = tokio::select! {
1914 728 : (guard, permit) = acquire => (guard, permit),
1915 728 : _ = self.l0_compaction_trigger.notified(), if yield_for_l0 => {
1916 3 : return Ok(CompactionOutcome::YieldForL0);
1917 : }
1918 728 : _ = self.cancel.cancelled() => return Ok(CompactionOutcome::Skipped),
1919 728 : _ = cancel.cancelled() => return Ok(CompactionOutcome::Skipped),
1920 : };
1921 :
1922 725 : let last_record_lsn = self.get_last_record_lsn();
1923 725 :
1924 725 : // Last record Lsn could be zero in case the timeline was just created
1925 725 : if !last_record_lsn.is_valid() {
1926 0 : warn!(
1927 0 : "Skipping compaction for potentially just initialized timeline, it has invalid last record lsn: {last_record_lsn}"
1928 : );
1929 0 : return Ok(CompactionOutcome::Skipped);
1930 725 : }
1931 :
1932 725 : let result = match self.get_compaction_algorithm_settings().kind {
1933 : CompactionAlgorithm::Tiered => {
1934 0 : self.compact_tiered(cancel, ctx).await?;
1935 0 : Ok(CompactionOutcome::Done)
1936 : }
1937 725 : CompactionAlgorithm::Legacy => self.compact_legacy(cancel, options, ctx).await,
1938 : };
1939 :
1940 : // Signal compaction failure to avoid L0 flush stalls when it's broken.
1941 0 : match &result {
1942 725 : Ok(_) => self.compaction_failed.store(false, AtomicOrdering::Relaxed),
1943 0 : Err(e) if e.is_cancel() => {}
1944 0 : Err(CompactionError::ShuttingDown) => {
1945 0 : // Covered by the `Err(e) if e.is_cancel()` branch.
1946 0 : }
1947 0 : Err(CompactionError::AlreadyRunning(_)) => {
1948 0 : // Covered by the `Err(e) if e.is_cancel()` branch.
1949 0 : }
1950 : Err(CompactionError::Other(_)) => {
1951 0 : self.compaction_failed.store(true, AtomicOrdering::Relaxed)
1952 : }
1953 : Err(CompactionError::CollectKeySpaceError(_)) => {
1954 : // Cancelled errors are covered by the `Err(e) if e.is_cancel()` branch.
1955 0 : self.compaction_failed.store(true, AtomicOrdering::Relaxed)
1956 : }
1957 : // Don't change the current value on offload failure or shutdown. We don't want to
1958 : // abruptly stall nor resume L0 flushes in these cases.
1959 0 : Err(CompactionError::Offload(_)) => {}
1960 : };
1961 :
1962 725 : result
1963 728 : }
1964 :
1965 : /// Mutate the timeline with a [`TimelineWriter`].
1966 10266392 : pub(crate) async fn writer(&self) -> TimelineWriter<'_> {
1967 10266392 : TimelineWriter {
1968 10266392 : tl: self,
1969 10266392 : write_guard: self.write_lock.lock().await,
1970 : }
1971 10266392 : }
1972 :
1973 0 : pub(crate) fn activate(
1974 0 : self: &Arc<Self>,
1975 0 : parent: Arc<crate::tenant::Tenant>,
1976 0 : broker_client: BrokerClientChannel,
1977 0 : background_jobs_can_start: Option<&completion::Barrier>,
1978 0 : ctx: &RequestContext,
1979 0 : ) {
1980 0 : if self.tenant_shard_id.is_shard_zero() {
1981 0 : // Logical size is only maintained accurately on shard zero.
1982 0 : self.spawn_initial_logical_size_computation_task(ctx);
1983 0 : }
1984 0 : self.launch_wal_receiver(ctx, broker_client);
1985 0 : self.set_state(TimelineState::Active);
1986 0 : self.launch_eviction_task(parent, background_jobs_can_start);
1987 0 : }
1988 :
1989 : /// After this function returns, there are no timeline-scoped tasks are left running.
1990 : ///
1991 : /// The preferred pattern for is:
1992 : /// - in any spawned tasks, keep Timeline::guard open + Timeline::cancel / child token
1993 : /// - if early shutdown (not just cancellation) of a sub-tree of tasks is required,
1994 : /// go the extra mile and keep track of JoinHandles
1995 : /// - Keep track of JoinHandles using a passed-down `Arc<Mutex<Option<JoinSet>>>` or similar,
1996 : /// instead of spawning directly on a runtime. It is a more composable / testable pattern.
1997 : ///
1998 : /// For legacy reasons, we still have multiple tasks spawned using
1999 : /// `task_mgr::spawn(X, Some(tenant_id), Some(timeline_id))`.
2000 : /// We refer to these as "timeline-scoped task_mgr tasks".
2001 : /// Some of these tasks are already sensitive to Timeline::cancel while others are
2002 : /// not sensitive to Timeline::cancel and instead respect [`task_mgr::shutdown_token`]
2003 : /// or [`task_mgr::shutdown_watcher`].
2004 : /// We want to gradually convert the code base away from these.
2005 : ///
2006 : /// Here is an inventory of timeline-scoped task_mgr tasks that are still sensitive to
2007 : /// `task_mgr::shutdown_{token,watcher}` (there are also tenant-scoped and global-scoped
2008 : /// ones that aren't mentioned here):
2009 : /// - [`TaskKind::TimelineDeletionWorker`]
2010 : /// - NB: also used for tenant deletion
2011 : /// - [`TaskKind::RemoteUploadTask`]`
2012 : /// - [`TaskKind::InitialLogicalSizeCalculation`]
2013 : /// - [`TaskKind::DownloadAllRemoteLayers`] (can we get rid of it?)
2014 : // Inventory of timeline-scoped task_mgr tasks that use spawn but aren't sensitive:
2015 : /// - [`TaskKind::Eviction`]
2016 : /// - [`TaskKind::LayerFlushTask`]
2017 : /// - [`TaskKind::OndemandLogicalSizeCalculation`]
2018 : /// - [`TaskKind::GarbageCollector`] (immediate_gc is timeline-scoped)
2019 20 : pub(crate) async fn shutdown(&self, mode: ShutdownMode) {
2020 20 : debug_assert_current_span_has_tenant_and_timeline_id();
2021 20 :
2022 20 : // Regardless of whether we're going to try_freeze_and_flush
2023 20 : // or not, stop ingesting any more data. Walreceiver only provides
2024 20 : // cancellation but no "wait until gone", because it uses the Timeline::gate.
2025 20 : // So, only after the self.gate.close() below will we know for sure that
2026 20 : // no walreceiver tasks are left.
2027 20 : // For `try_freeze_and_flush=true`, this means that we might still be ingesting
2028 20 : // data during the call to `self.freeze_and_flush()` below.
2029 20 : // That's not ideal, but, we don't have the concept of a ChildGuard,
2030 20 : // which is what we'd need to properly model early shutdown of the walreceiver
2031 20 : // task sub-tree before the other Timeline task sub-trees.
2032 20 : let walreceiver = self.walreceiver.lock().unwrap().take();
2033 20 : tracing::debug!(
2034 0 : is_some = walreceiver.is_some(),
2035 0 : "Waiting for WalReceiverManager..."
2036 : );
2037 20 : if let Some(walreceiver) = walreceiver {
2038 0 : walreceiver.cancel();
2039 20 : }
2040 : // ... and inform any waiters for newer LSNs that there won't be any.
2041 20 : self.last_record_lsn.shutdown();
2042 20 :
2043 20 : if let ShutdownMode::FreezeAndFlush = mode {
2044 12 : let do_flush = if let Some((open, frozen)) = self
2045 12 : .layers
2046 12 : .read()
2047 12 : .await
2048 12 : .layer_map()
2049 12 : .map(|lm| (lm.open_layer.is_some(), lm.frozen_layers.len()))
2050 12 : .ok()
2051 12 : .filter(|(open, frozen)| *open || *frozen > 0)
2052 : {
2053 0 : if self.remote_client.is_archived() == Some(true) {
2054 : // No point flushing on shutdown for an archived timeline: it is not important
2055 : // to have it nice and fresh after our restart, and trying to flush here might
2056 : // race with trying to offload it (which also stops the flush loop)
2057 0 : false
2058 : } else {
2059 0 : tracing::info!(?open, frozen, "flushing and freezing on shutdown");
2060 0 : true
2061 : }
2062 : } else {
2063 : // this is double-shutdown, it'll be a no-op
2064 12 : true
2065 : };
2066 :
2067 : // we shut down walreceiver above, so, we won't add anything more
2068 : // to the InMemoryLayer; freeze it and wait for all frozen layers
2069 : // to reach the disk & upload queue, then shut the upload queue and
2070 : // wait for it to drain.
2071 12 : if do_flush {
2072 12 : match self.freeze_and_flush().await {
2073 : Ok(_) => {
2074 : // drain the upload queue
2075 : // if we did not wait for completion here, it might be our shutdown process
2076 : // didn't wait for remote uploads to complete at all, as new tasks can forever
2077 : // be spawned.
2078 : //
2079 : // what is problematic is the shutting down of RemoteTimelineClient, because
2080 : // obviously it does not make sense to stop while we wait for it, but what
2081 : // about corner cases like s3 suddenly hanging up?
2082 12 : self.remote_client.shutdown().await;
2083 : }
2084 : Err(FlushLayerError::Cancelled) => {
2085 : // this is likely the second shutdown, ignore silently.
2086 : // TODO: this can be removed once https://github.com/neondatabase/neon/issues/5080
2087 0 : debug_assert!(self.cancel.is_cancelled());
2088 : }
2089 0 : Err(e) => {
2090 0 : // Non-fatal. Shutdown is infallible. Failures to flush just mean that
2091 0 : // we have some extra WAL replay to do next time the timeline starts.
2092 0 : warn!("failed to freeze and flush: {e:#}");
2093 : }
2094 : }
2095 :
2096 : // `self.remote_client.shutdown().await` above should have already flushed everything from the queue, but
2097 : // we also do a final check here to ensure that the queue is empty.
2098 12 : if !self.remote_client.no_pending_work() {
2099 0 : warn!(
2100 0 : "still have pending work in remote upload queue, but continuing shutting down anyways"
2101 : );
2102 12 : }
2103 0 : }
2104 8 : }
2105 :
2106 20 : if let ShutdownMode::Reload = mode {
2107 : // drain the upload queue
2108 4 : self.remote_client.shutdown().await;
2109 4 : if !self.remote_client.no_pending_work() {
2110 0 : warn!(
2111 0 : "still have pending work in remote upload queue, but continuing shutting down anyways"
2112 : );
2113 4 : }
2114 16 : }
2115 :
2116 : // Signal any subscribers to our cancellation token to drop out
2117 20 : tracing::debug!("Cancelling CancellationToken");
2118 20 : self.cancel.cancel();
2119 20 :
2120 20 : // If we have a background task downloading heatmap layers stop it.
2121 20 : // The background downloads are sensitive to timeline cancellation (done above),
2122 20 : // so the drain will be immediate.
2123 20 : self.stop_and_drain_heatmap_layers_download().await;
2124 :
2125 : // Ensure Prevent new page service requests from starting.
2126 20 : self.handles.shutdown();
2127 20 :
2128 20 : // Transition the remote_client into a state where it's only useful for timeline deletion.
2129 20 : // (The deletion use case is why we can't just hook up remote_client to Self::cancel).)
2130 20 : self.remote_client.stop();
2131 20 :
2132 20 : // As documented in remote_client.stop()'s doc comment, it's our responsibility
2133 20 : // to shut down the upload queue tasks.
2134 20 : // TODO: fix that, task management should be encapsulated inside remote_client.
2135 20 : task_mgr::shutdown_tasks(
2136 20 : Some(TaskKind::RemoteUploadTask),
2137 20 : Some(self.tenant_shard_id),
2138 20 : Some(self.timeline_id),
2139 20 : )
2140 20 : .await;
2141 :
2142 : // TODO: work toward making this a no-op. See this function's doc comment for more context.
2143 20 : tracing::debug!("Waiting for tasks...");
2144 20 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), Some(self.timeline_id)).await;
2145 :
2146 : {
2147 : // Allow any remaining in-memory layers to do cleanup -- until that, they hold the gate
2148 : // open.
2149 20 : let mut write_guard = self.write_lock.lock().await;
2150 20 : self.layers.write().await.shutdown(&mut write_guard);
2151 20 : }
2152 20 :
2153 20 : // Finally wait until any gate-holders are complete.
2154 20 : //
2155 20 : // TODO: once above shutdown_tasks is a no-op, we can close the gate before calling shutdown_tasks
2156 20 : // and use a TBD variant of shutdown_tasks that asserts that there were no tasks left.
2157 20 : self.gate.close().await;
2158 :
2159 20 : self.metrics.shutdown();
2160 20 : }
2161 :
2162 908 : pub(crate) fn set_state(&self, new_state: TimelineState) {
2163 908 : match (self.current_state(), new_state) {
2164 908 : (equal_state_1, equal_state_2) if equal_state_1 == equal_state_2 => {
2165 4 : info!("Ignoring new state, equal to the existing one: {equal_state_2:?}");
2166 : }
2167 0 : (st, TimelineState::Loading) => {
2168 0 : error!("ignoring transition from {st:?} into Loading state");
2169 : }
2170 0 : (TimelineState::Broken { .. }, new_state) => {
2171 0 : error!("Ignoring state update {new_state:?} for broken timeline");
2172 : }
2173 : (TimelineState::Stopping, TimelineState::Active) => {
2174 0 : error!("Not activating a Stopping timeline");
2175 : }
2176 904 : (_, new_state) => {
2177 904 : self.state.send_replace(new_state);
2178 904 : }
2179 : }
2180 908 : }
2181 :
2182 4 : pub(crate) fn set_broken(&self, reason: String) {
2183 4 : let backtrace_str: String = format!("{}", std::backtrace::Backtrace::force_capture());
2184 4 : let broken_state = TimelineState::Broken {
2185 4 : reason,
2186 4 : backtrace: backtrace_str,
2187 4 : };
2188 4 : self.set_state(broken_state);
2189 4 :
2190 4 : // Although the Broken state is not equivalent to shutdown() (shutdown will be called
2191 4 : // later when this tenant is detach or the process shuts down), firing the cancellation token
2192 4 : // here avoids the need for other tasks to watch for the Broken state explicitly.
2193 4 : self.cancel.cancel();
2194 4 : }
2195 :
2196 453227 : pub(crate) fn current_state(&self) -> TimelineState {
2197 453227 : self.state.borrow().clone()
2198 453227 : }
2199 :
2200 12 : pub(crate) fn is_broken(&self) -> bool {
2201 12 : matches!(&*self.state.borrow(), TimelineState::Broken { .. })
2202 12 : }
2203 :
2204 472 : pub(crate) fn is_active(&self) -> bool {
2205 472 : self.current_state() == TimelineState::Active
2206 472 : }
2207 :
2208 0 : pub(crate) fn is_archived(&self) -> Option<bool> {
2209 0 : self.remote_client.is_archived()
2210 0 : }
2211 :
2212 733 : pub(crate) fn is_stopping(&self) -> bool {
2213 733 : self.current_state() == TimelineState::Stopping
2214 733 : }
2215 :
2216 0 : pub(crate) fn subscribe_for_state_updates(&self) -> watch::Receiver<TimelineState> {
2217 0 : self.state.subscribe()
2218 0 : }
2219 :
2220 451118 : pub(crate) async fn wait_to_become_active(
2221 451118 : &self,
2222 451118 : _ctx: &RequestContext, // Prepare for use by cancellation
2223 451118 : ) -> Result<(), TimelineState> {
2224 451118 : let mut receiver = self.state.subscribe();
2225 : loop {
2226 451118 : let current_state = receiver.borrow().clone();
2227 451118 : match current_state {
2228 : TimelineState::Loading => {
2229 0 : receiver
2230 0 : .changed()
2231 0 : .await
2232 0 : .expect("holding a reference to self");
2233 : }
2234 : TimelineState::Active { .. } => {
2235 451114 : return Ok(());
2236 : }
2237 : TimelineState::Broken { .. } | TimelineState::Stopping => {
2238 : // There's no chance the timeline can transition back into ::Active
2239 4 : return Err(current_state);
2240 : }
2241 : }
2242 : }
2243 451118 : }
2244 :
2245 0 : pub(crate) async fn layer_map_info(
2246 0 : &self,
2247 0 : reset: LayerAccessStatsReset,
2248 0 : ) -> Result<LayerMapInfo, layer_manager::Shutdown> {
2249 0 : let guard = self.layers.read().await;
2250 0 : let layer_map = guard.layer_map()?;
2251 0 : let mut in_memory_layers = Vec::with_capacity(layer_map.frozen_layers.len() + 1);
2252 0 : if let Some(open_layer) = &layer_map.open_layer {
2253 0 : in_memory_layers.push(open_layer.info());
2254 0 : }
2255 0 : for frozen_layer in &layer_map.frozen_layers {
2256 0 : in_memory_layers.push(frozen_layer.info());
2257 0 : }
2258 :
2259 0 : let historic_layers = layer_map
2260 0 : .iter_historic_layers()
2261 0 : .map(|desc| guard.get_from_desc(&desc).info(reset))
2262 0 : .collect();
2263 0 :
2264 0 : Ok(LayerMapInfo {
2265 0 : in_memory_layers,
2266 0 : historic_layers,
2267 0 : })
2268 0 : }
2269 :
2270 : #[instrument(skip_all, fields(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id))]
2271 : pub(crate) async fn download_layer(
2272 : &self,
2273 : layer_file_name: &LayerName,
2274 : ctx: &RequestContext,
2275 : ) -> Result<Option<bool>, super::storage_layer::layer::DownloadError> {
2276 : let Some(layer) = self
2277 : .find_layer(layer_file_name)
2278 : .await
2279 0 : .map_err(|e| match e {
2280 0 : layer_manager::Shutdown => {
2281 0 : super::storage_layer::layer::DownloadError::TimelineShutdown
2282 0 : }
2283 0 : })?
2284 : else {
2285 : return Ok(None);
2286 : };
2287 :
2288 : layer.download(ctx).await?;
2289 :
2290 : Ok(Some(true))
2291 : }
2292 :
2293 : /// Evict just one layer.
2294 : ///
2295 : /// Returns `Ok(None)` in the case where the layer could not be found by its `layer_file_name`.
2296 0 : pub(crate) async fn evict_layer(
2297 0 : &self,
2298 0 : layer_file_name: &LayerName,
2299 0 : ) -> anyhow::Result<Option<bool>> {
2300 0 : let _gate = self
2301 0 : .gate
2302 0 : .enter()
2303 0 : .map_err(|_| anyhow::anyhow!("Shutting down"))?;
2304 :
2305 0 : let Some(local_layer) = self.find_layer(layer_file_name).await? else {
2306 0 : return Ok(None);
2307 : };
2308 :
2309 : // curl has this by default
2310 0 : let timeout = std::time::Duration::from_secs(120);
2311 0 :
2312 0 : match local_layer.evict_and_wait(timeout).await {
2313 0 : Ok(()) => Ok(Some(true)),
2314 0 : Err(EvictionError::NotFound) => Ok(Some(false)),
2315 0 : Err(EvictionError::Downloaded) => Ok(Some(false)),
2316 0 : Err(EvictionError::Timeout) => Ok(Some(false)),
2317 : }
2318 0 : }
2319 :
2320 9606020 : fn should_roll(
2321 9606020 : &self,
2322 9606020 : layer_size: u64,
2323 9606020 : projected_layer_size: u64,
2324 9606020 : checkpoint_distance: u64,
2325 9606020 : projected_lsn: Lsn,
2326 9606020 : last_freeze_at: Lsn,
2327 9606020 : opened_at: Instant,
2328 9606020 : ) -> bool {
2329 9606020 : let distance = projected_lsn.widening_sub(last_freeze_at);
2330 9606020 :
2331 9606020 : // Rolling the open layer can be triggered by:
2332 9606020 : // 1. The distance from the last LSN we rolled at. This bounds the amount of WAL that
2333 9606020 : // the safekeepers need to store. For sharded tenants, we multiply by shard count to
2334 9606020 : // account for how writes are distributed across shards: we expect each node to consume
2335 9606020 : // 1/count of the LSN on average.
2336 9606020 : // 2. The size of the currently open layer.
2337 9606020 : // 3. The time since the last roll. It helps safekeepers to regard pageserver as caught
2338 9606020 : // up and suspend activity.
2339 9606020 : if distance >= checkpoint_distance as i128 * self.shard_identity.count.count() as i128 {
2340 0 : info!(
2341 0 : "Will roll layer at {} with layer size {} due to LSN distance ({})",
2342 : projected_lsn, layer_size, distance
2343 : );
2344 :
2345 0 : true
2346 9606020 : } else if projected_layer_size >= checkpoint_distance {
2347 : // NB: this check is relied upon by:
2348 160 : let _ = IndexEntry::validate_checkpoint_distance;
2349 160 : info!(
2350 0 : "Will roll layer at {} with layer size {} due to layer size ({})",
2351 : projected_lsn, layer_size, projected_layer_size
2352 : );
2353 :
2354 160 : true
2355 9605860 : } else if distance > 0 && opened_at.elapsed() >= self.get_checkpoint_timeout() {
2356 0 : info!(
2357 0 : "Will roll layer at {} with layer size {} due to time since first write to the layer ({:?})",
2358 0 : projected_lsn,
2359 0 : layer_size,
2360 0 : opened_at.elapsed()
2361 : );
2362 :
2363 0 : true
2364 : } else {
2365 9605860 : false
2366 : }
2367 9606020 : }
2368 : }
2369 :
2370 : /// Number of times we will compute partition within a checkpoint distance.
2371 : const REPARTITION_FREQ_IN_CHECKPOINT_DISTANCE: u64 = 10;
2372 :
2373 : // Private functions
2374 : impl Timeline {
2375 24 : pub(crate) fn get_lsn_lease_length(&self) -> Duration {
2376 24 : let tenant_conf = self.tenant_conf.load();
2377 24 : tenant_conf
2378 24 : .tenant_conf
2379 24 : .lsn_lease_length
2380 24 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
2381 24 : }
2382 :
2383 0 : pub(crate) fn get_lsn_lease_length_for_ts(&self) -> Duration {
2384 0 : let tenant_conf = self.tenant_conf.load();
2385 0 : tenant_conf
2386 0 : .tenant_conf
2387 0 : .lsn_lease_length_for_ts
2388 0 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length_for_ts)
2389 0 : }
2390 :
2391 0 : pub(crate) fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
2392 0 : let tenant_conf = self.tenant_conf.load();
2393 0 : tenant_conf.is_gc_blocked_by_lsn_lease_deadline()
2394 0 : }
2395 :
2396 0 : pub(crate) fn get_lazy_slru_download(&self) -> bool {
2397 0 : let tenant_conf = self.tenant_conf.load();
2398 0 : tenant_conf
2399 0 : .tenant_conf
2400 0 : .lazy_slru_download
2401 0 : .unwrap_or(self.conf.default_tenant_conf.lazy_slru_download)
2402 0 : }
2403 :
2404 9609010 : fn get_checkpoint_distance(&self) -> u64 {
2405 9609010 : let tenant_conf = self.tenant_conf.load();
2406 9609010 : tenant_conf
2407 9609010 : .tenant_conf
2408 9609010 : .checkpoint_distance
2409 9609010 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
2410 9609010 : }
2411 :
2412 9605860 : fn get_checkpoint_timeout(&self) -> Duration {
2413 9605860 : let tenant_conf = self.tenant_conf.load();
2414 9605860 : tenant_conf
2415 9605860 : .tenant_conf
2416 9605860 : .checkpoint_timeout
2417 9605860 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
2418 9605860 : }
2419 :
2420 5032 : fn get_compaction_period(&self) -> Duration {
2421 5032 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2422 5032 : tenant_conf
2423 5032 : .compaction_period
2424 5032 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
2425 5032 : }
2426 :
2427 1333 : fn get_compaction_target_size(&self) -> u64 {
2428 1333 : let tenant_conf = self.tenant_conf.load();
2429 1333 : tenant_conf
2430 1333 : .tenant_conf
2431 1333 : .compaction_target_size
2432 1333 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
2433 1333 : }
2434 :
2435 3137 : fn get_compaction_threshold(&self) -> usize {
2436 3137 : let tenant_conf = self.tenant_conf.load();
2437 3137 : tenant_conf
2438 3137 : .tenant_conf
2439 3137 : .compaction_threshold
2440 3137 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
2441 3137 : }
2442 :
2443 : /// Returns `true` if the rel_size_v2 config is enabled. NOTE: the write path and read path
2444 : /// should look at `get_rel_size_v2_status()` to get the actual status of the timeline. It is
2445 : /// possible that the index part persists the state while the config doesn't get persisted.
2446 3892 : pub(crate) fn get_rel_size_v2_enabled(&self) -> bool {
2447 3892 : let tenant_conf = self.tenant_conf.load();
2448 3892 : tenant_conf
2449 3892 : .tenant_conf
2450 3892 : .rel_size_v2_enabled
2451 3892 : .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
2452 3892 : }
2453 :
2454 4384 : pub(crate) fn get_rel_size_v2_status(&self) -> RelSizeMigration {
2455 4384 : self.rel_size_v2_status
2456 4384 : .load()
2457 4384 : .as_ref()
2458 4384 : .map(|s| s.as_ref().clone())
2459 4384 : .unwrap_or(RelSizeMigration::Legacy)
2460 4384 : }
2461 :
2462 56 : fn get_compaction_upper_limit(&self) -> usize {
2463 56 : let tenant_conf = self.tenant_conf.load();
2464 56 : tenant_conf
2465 56 : .tenant_conf
2466 56 : .compaction_upper_limit
2467 56 : .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
2468 56 : }
2469 :
2470 728 : pub fn get_compaction_l0_first(&self) -> bool {
2471 728 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2472 728 : tenant_conf
2473 728 : .compaction_l0_first
2474 728 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
2475 728 : }
2476 :
2477 0 : pub fn get_compaction_l0_semaphore(&self) -> bool {
2478 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2479 0 : tenant_conf
2480 0 : .compaction_l0_semaphore
2481 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_semaphore)
2482 0 : }
2483 :
2484 2516 : fn get_l0_flush_delay_threshold(&self) -> Option<usize> {
2485 : // By default, delay L0 flushes at 3x the compaction threshold. The compaction threshold
2486 : // defaults to 10, and L0 compaction is generally able to keep L0 counts below 30.
2487 : const DEFAULT_L0_FLUSH_DELAY_FACTOR: usize = 3;
2488 :
2489 : // If compaction is disabled, don't delay.
2490 2516 : if self.get_compaction_period() == Duration::ZERO {
2491 2516 : return None;
2492 0 : }
2493 0 :
2494 0 : let compaction_threshold = self.get_compaction_threshold();
2495 0 : let tenant_conf = self.tenant_conf.load();
2496 0 : let l0_flush_delay_threshold = tenant_conf
2497 0 : .tenant_conf
2498 0 : .l0_flush_delay_threshold
2499 0 : .or(self.conf.default_tenant_conf.l0_flush_delay_threshold)
2500 0 : .unwrap_or(DEFAULT_L0_FLUSH_DELAY_FACTOR * compaction_threshold);
2501 0 :
2502 0 : // 0 disables backpressure.
2503 0 : if l0_flush_delay_threshold == 0 {
2504 0 : return None;
2505 0 : }
2506 0 :
2507 0 : // Clamp the flush delay threshold to the compaction threshold; it doesn't make sense to
2508 0 : // backpressure flushes below this.
2509 0 : // TODO: the tenant config should have validation to prevent this instead.
2510 0 : debug_assert!(l0_flush_delay_threshold >= compaction_threshold);
2511 0 : Some(max(l0_flush_delay_threshold, compaction_threshold))
2512 2516 : }
2513 :
2514 2516 : fn get_l0_flush_stall_threshold(&self) -> Option<usize> {
2515 : // Disable L0 stalls by default. Stalling can cause unavailability if L0 compaction isn't
2516 : // responsive, and it can e.g. block on other compaction via the compaction semaphore or
2517 : // sibling timelines. We need more confidence before enabling this.
2518 : const DEFAULT_L0_FLUSH_STALL_FACTOR: usize = 0; // TODO: default to e.g. 5
2519 :
2520 : // If compaction is disabled, don't stall.
2521 2516 : if self.get_compaction_period() == Duration::ZERO {
2522 2516 : return None;
2523 0 : }
2524 0 :
2525 0 : // If compaction is failing, don't stall and try to keep the tenant alive. This may not be a
2526 0 : // good idea: read amp can grow unbounded, leading to terrible performance, and we may take
2527 0 : // on unbounded compaction debt that can take a long time to fix once compaction comes back
2528 0 : // online. At least we'll delay flushes, slowing down the growth and buying some time.
2529 0 : if self.compaction_failed.load(AtomicOrdering::Relaxed) {
2530 0 : return None;
2531 0 : }
2532 0 :
2533 0 : let compaction_threshold = self.get_compaction_threshold();
2534 0 : let tenant_conf = self.tenant_conf.load();
2535 0 : let l0_flush_stall_threshold = tenant_conf
2536 0 : .tenant_conf
2537 0 : .l0_flush_stall_threshold
2538 0 : .or(self.conf.default_tenant_conf.l0_flush_stall_threshold);
2539 0 :
2540 0 : // Tests sometimes set compaction_threshold=1 to generate lots of layer files, and don't
2541 0 : // handle the 20-second compaction delay. Some (e.g. `test_backward_compatibility`) can't
2542 0 : // easily adjust the L0 backpressure settings, so just disable stalls in this case.
2543 0 : if cfg!(feature = "testing")
2544 0 : && compaction_threshold == 1
2545 0 : && l0_flush_stall_threshold.is_none()
2546 : {
2547 0 : return None;
2548 0 : }
2549 0 :
2550 0 : let l0_flush_stall_threshold = l0_flush_stall_threshold
2551 0 : .unwrap_or(DEFAULT_L0_FLUSH_STALL_FACTOR * compaction_threshold);
2552 0 :
2553 0 : // 0 disables backpressure.
2554 0 : if l0_flush_stall_threshold == 0 {
2555 0 : return None;
2556 0 : }
2557 0 :
2558 0 : // Clamp the flush stall threshold to the compaction threshold; it doesn't make sense to
2559 0 : // backpressure flushes below this.
2560 0 : // TODO: the tenant config should have validation to prevent this instead.
2561 0 : debug_assert!(l0_flush_stall_threshold >= compaction_threshold);
2562 0 : Some(max(l0_flush_stall_threshold, compaction_threshold))
2563 2516 : }
2564 :
2565 2356 : fn get_l0_flush_wait_upload(&self) -> bool {
2566 2356 : let tenant_conf = self.tenant_conf.load();
2567 2356 : tenant_conf
2568 2356 : .tenant_conf
2569 2356 : .l0_flush_wait_upload
2570 2356 : .unwrap_or(self.conf.default_tenant_conf.l0_flush_wait_upload)
2571 2356 : }
2572 :
2573 28 : fn get_image_creation_threshold(&self) -> usize {
2574 28 : let tenant_conf = self.tenant_conf.load();
2575 28 : tenant_conf
2576 28 : .tenant_conf
2577 28 : .image_creation_threshold
2578 28 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
2579 28 : }
2580 :
2581 725 : fn get_compaction_algorithm_settings(&self) -> CompactionAlgorithmSettings {
2582 725 : let tenant_conf = &self.tenant_conf.load();
2583 725 : tenant_conf
2584 725 : .tenant_conf
2585 725 : .compaction_algorithm
2586 725 : .as_ref()
2587 725 : .unwrap_or(&self.conf.default_tenant_conf.compaction_algorithm)
2588 725 : .clone()
2589 725 : }
2590 :
2591 0 : fn get_eviction_policy(&self) -> EvictionPolicy {
2592 0 : let tenant_conf = self.tenant_conf.load();
2593 0 : tenant_conf
2594 0 : .tenant_conf
2595 0 : .eviction_policy
2596 0 : .unwrap_or(self.conf.default_tenant_conf.eviction_policy)
2597 0 : }
2598 :
2599 904 : fn get_evictions_low_residence_duration_metric_threshold(
2600 904 : tenant_conf: &pageserver_api::models::TenantConfig,
2601 904 : default_tenant_conf: &pageserver_api::config::TenantConfigToml,
2602 904 : ) -> Duration {
2603 904 : tenant_conf
2604 904 : .evictions_low_residence_duration_metric_threshold
2605 904 : .unwrap_or(default_tenant_conf.evictions_low_residence_duration_metric_threshold)
2606 904 : }
2607 :
2608 1145 : fn get_image_layer_creation_check_threshold(&self) -> u8 {
2609 1145 : let tenant_conf = self.tenant_conf.load();
2610 1145 : tenant_conf
2611 1145 : .tenant_conf
2612 1145 : .image_layer_creation_check_threshold
2613 1145 : .unwrap_or(
2614 1145 : self.conf
2615 1145 : .default_tenant_conf
2616 1145 : .image_layer_creation_check_threshold,
2617 1145 : )
2618 1145 : }
2619 :
2620 0 : fn get_gc_compaction_settings(&self) -> GcCompactionCombinedSettings {
2621 0 : let tenant_conf = &self.tenant_conf.load();
2622 0 : let gc_compaction_enabled = tenant_conf
2623 0 : .tenant_conf
2624 0 : .gc_compaction_enabled
2625 0 : .unwrap_or(self.conf.default_tenant_conf.gc_compaction_enabled);
2626 0 : let gc_compaction_initial_threshold_kb = tenant_conf
2627 0 : .tenant_conf
2628 0 : .gc_compaction_initial_threshold_kb
2629 0 : .unwrap_or(
2630 0 : self.conf
2631 0 : .default_tenant_conf
2632 0 : .gc_compaction_initial_threshold_kb,
2633 0 : );
2634 0 : let gc_compaction_ratio_percent = tenant_conf
2635 0 : .tenant_conf
2636 0 : .gc_compaction_ratio_percent
2637 0 : .unwrap_or(self.conf.default_tenant_conf.gc_compaction_ratio_percent);
2638 0 : GcCompactionCombinedSettings {
2639 0 : gc_compaction_enabled,
2640 0 : gc_compaction_initial_threshold_kb,
2641 0 : gc_compaction_ratio_percent,
2642 0 : }
2643 0 : }
2644 :
2645 0 : fn get_image_creation_preempt_threshold(&self) -> usize {
2646 0 : let tenant_conf = self.tenant_conf.load();
2647 0 : tenant_conf
2648 0 : .tenant_conf
2649 0 : .image_creation_preempt_threshold
2650 0 : .unwrap_or(
2651 0 : self.conf
2652 0 : .default_tenant_conf
2653 0 : .image_creation_preempt_threshold,
2654 0 : )
2655 0 : }
2656 :
2657 : /// Resolve the effective WAL receiver protocol to use for this tenant.
2658 : ///
2659 : /// Priority order is:
2660 : /// 1. Tenant config override
2661 : /// 2. Default value for tenant config override
2662 : /// 3. Pageserver config override
2663 : /// 4. Pageserver config default
2664 0 : pub fn resolve_wal_receiver_protocol(&self) -> PostgresClientProtocol {
2665 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2666 0 : tenant_conf
2667 0 : .wal_receiver_protocol_override
2668 0 : .or(self.conf.default_tenant_conf.wal_receiver_protocol_override)
2669 0 : .unwrap_or(self.conf.wal_receiver_protocol)
2670 0 : }
2671 :
2672 0 : pub(super) fn tenant_conf_updated(&self, new_conf: &AttachedTenantConf) {
2673 0 : // NB: Most tenant conf options are read by background loops, so,
2674 0 : // changes will automatically be picked up.
2675 0 :
2676 0 : // The threshold is embedded in the metric. So, we need to update it.
2677 0 : {
2678 0 : let new_threshold = Self::get_evictions_low_residence_duration_metric_threshold(
2679 0 : &new_conf.tenant_conf,
2680 0 : &self.conf.default_tenant_conf,
2681 0 : );
2682 0 :
2683 0 : let tenant_id_str = self.tenant_shard_id.tenant_id.to_string();
2684 0 : let shard_id_str = format!("{}", self.tenant_shard_id.shard_slug());
2685 0 :
2686 0 : let timeline_id_str = self.timeline_id.to_string();
2687 0 :
2688 0 : self.remote_client.update_config(&new_conf.location);
2689 0 :
2690 0 : self.metrics
2691 0 : .evictions_with_low_residence_duration
2692 0 : .write()
2693 0 : .unwrap()
2694 0 : .change_threshold(
2695 0 : &tenant_id_str,
2696 0 : &shard_id_str,
2697 0 : &timeline_id_str,
2698 0 : new_threshold,
2699 0 : );
2700 0 : }
2701 0 : }
2702 :
2703 : /// Open a Timeline handle.
2704 : ///
2705 : /// Loads the metadata for the timeline into memory, but not the layer map.
2706 : #[allow(clippy::too_many_arguments)]
2707 904 : pub(super) fn new(
2708 904 : conf: &'static PageServerConf,
2709 904 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
2710 904 : metadata: &TimelineMetadata,
2711 904 : previous_heatmap: Option<PreviousHeatmap>,
2712 904 : ancestor: Option<Arc<Timeline>>,
2713 904 : timeline_id: TimelineId,
2714 904 : tenant_shard_id: TenantShardId,
2715 904 : generation: Generation,
2716 904 : shard_identity: ShardIdentity,
2717 904 : walredo_mgr: Option<Arc<super::WalRedoManager>>,
2718 904 : resources: TimelineResources,
2719 904 : pg_version: u32,
2720 904 : state: TimelineState,
2721 904 : attach_wal_lag_cooldown: Arc<OnceLock<WalLagCooldown>>,
2722 904 : create_idempotency: crate::tenant::CreateTimelineIdempotency,
2723 904 : gc_compaction_state: Option<GcCompactionState>,
2724 904 : rel_size_v2_status: Option<RelSizeMigration>,
2725 904 : cancel: CancellationToken,
2726 904 : ) -> Arc<Self> {
2727 904 : let disk_consistent_lsn = metadata.disk_consistent_lsn();
2728 904 : let (state, _) = watch::channel(state);
2729 904 :
2730 904 : let (layer_flush_start_tx, _) = tokio::sync::watch::channel((0, disk_consistent_lsn));
2731 904 : let (layer_flush_done_tx, _) = tokio::sync::watch::channel((0, Ok(())));
2732 904 :
2733 904 : let evictions_low_residence_duration_metric_threshold = {
2734 904 : let loaded_tenant_conf = tenant_conf.load();
2735 904 : Self::get_evictions_low_residence_duration_metric_threshold(
2736 904 : &loaded_tenant_conf.tenant_conf,
2737 904 : &conf.default_tenant_conf,
2738 904 : )
2739 : };
2740 :
2741 904 : if let Some(ancestor) = &ancestor {
2742 460 : let mut ancestor_gc_info = ancestor.gc_info.write().unwrap();
2743 460 : // If we construct an explicit timeline object, it's obviously not offloaded
2744 460 : let is_offloaded = MaybeOffloaded::No;
2745 460 : ancestor_gc_info.insert_child(timeline_id, metadata.ancestor_lsn(), is_offloaded);
2746 460 : }
2747 :
2748 904 : Arc::new_cyclic(|myself| {
2749 904 : let metrics = Arc::new(TimelineMetrics::new(
2750 904 : &tenant_shard_id,
2751 904 : &timeline_id,
2752 904 : crate::metrics::EvictionsWithLowResidenceDurationBuilder::new(
2753 904 : "mtime",
2754 904 : evictions_low_residence_duration_metric_threshold,
2755 904 : ),
2756 904 : ));
2757 904 : let aux_file_metrics = metrics.aux_file_size_gauge.clone();
2758 :
2759 904 : let mut result = Timeline {
2760 904 : conf,
2761 904 : tenant_conf,
2762 904 : myself: myself.clone(),
2763 904 : timeline_id,
2764 904 : tenant_shard_id,
2765 904 : generation,
2766 904 : shard_identity,
2767 904 : pg_version,
2768 904 : layers: Default::default(),
2769 904 : gc_compaction_layer_update_lock: tokio::sync::RwLock::new(()),
2770 904 :
2771 904 : walredo_mgr,
2772 904 : walreceiver: Mutex::new(None),
2773 904 :
2774 904 : remote_client: Arc::new(resources.remote_client),
2775 904 :
2776 904 : // initialize in-memory 'last_record_lsn' from 'disk_consistent_lsn'.
2777 904 : last_record_lsn: SeqWait::new(RecordLsn {
2778 904 : last: disk_consistent_lsn,
2779 904 : prev: metadata.prev_record_lsn().unwrap_or(Lsn(0)),
2780 904 : }),
2781 904 : disk_consistent_lsn: AtomicLsn::new(disk_consistent_lsn.0),
2782 904 :
2783 904 : gc_compaction_state: ArcSwap::new(Arc::new(gc_compaction_state)),
2784 904 :
2785 904 : last_freeze_at: AtomicLsn::new(disk_consistent_lsn.0),
2786 904 : last_freeze_ts: RwLock::new(Instant::now()),
2787 904 :
2788 904 : loaded_at: (disk_consistent_lsn, SystemTime::now()),
2789 904 :
2790 904 : ancestor_timeline: ancestor,
2791 904 : ancestor_lsn: metadata.ancestor_lsn(),
2792 904 :
2793 904 : metrics,
2794 904 :
2795 904 : query_metrics: crate::metrics::SmgrQueryTimePerTimeline::new(
2796 904 : &tenant_shard_id,
2797 904 : &timeline_id,
2798 904 : resources.pagestream_throttle_metrics,
2799 904 : ),
2800 904 :
2801 7232 : directory_metrics: array::from_fn(|_| AtomicU64::new(0)),
2802 7232 : directory_metrics_inited: array::from_fn(|_| AtomicBool::new(false)),
2803 904 :
2804 904 : flush_loop_state: Mutex::new(FlushLoopState::NotStarted),
2805 904 :
2806 904 : layer_flush_start_tx,
2807 904 : layer_flush_done_tx,
2808 904 :
2809 904 : write_lock: tokio::sync::Mutex::new(None),
2810 904 :
2811 904 : gc_info: std::sync::RwLock::new(GcInfo::default()),
2812 904 :
2813 904 : last_image_layer_creation_status: ArcSwap::new(Arc::new(
2814 904 : LastImageLayerCreationStatus::default(),
2815 904 : )),
2816 904 :
2817 904 : applied_gc_cutoff_lsn: Rcu::new(metadata.latest_gc_cutoff_lsn()),
2818 904 : initdb_lsn: metadata.initdb_lsn(),
2819 904 :
2820 904 : current_logical_size: if disk_consistent_lsn.is_valid() {
2821 : // we're creating timeline data with some layer files existing locally,
2822 : // need to recalculate timeline's logical size based on data in the layers.
2823 468 : LogicalSize::deferred_initial(disk_consistent_lsn)
2824 : } else {
2825 : // we're creating timeline data without any layers existing locally,
2826 : // initial logical size is 0.
2827 436 : LogicalSize::empty_initial()
2828 : },
2829 :
2830 904 : partitioning: GuardArcSwap::new((
2831 904 : (KeyPartitioning::new(), KeyPartitioning::new().into_sparse()),
2832 904 : Lsn(0),
2833 904 : )),
2834 904 : repartition_threshold: 0,
2835 904 : last_image_layer_creation_check_at: AtomicLsn::new(0),
2836 904 : last_image_layer_creation_check_instant: Mutex::new(None),
2837 904 :
2838 904 : last_received_wal: Mutex::new(None),
2839 904 : rel_size_cache: RwLock::new(RelSizeCache {
2840 904 : complete_as_of: disk_consistent_lsn,
2841 904 : map: HashMap::new(),
2842 904 : }),
2843 904 :
2844 904 : download_all_remote_layers_task_info: RwLock::new(None),
2845 904 :
2846 904 : state,
2847 904 :
2848 904 : eviction_task_timeline_state: tokio::sync::Mutex::new(
2849 904 : EvictionTaskTimelineState::default(),
2850 904 : ),
2851 904 : delete_progress: TimelineDeleteProgress::default(),
2852 904 :
2853 904 : cancel,
2854 904 : gate: Gate::default(),
2855 904 :
2856 904 : compaction_lock: tokio::sync::Mutex::default(),
2857 904 : compaction_failed: AtomicBool::default(),
2858 904 : l0_compaction_trigger: resources.l0_compaction_trigger,
2859 904 : gc_lock: tokio::sync::Mutex::default(),
2860 904 :
2861 904 : standby_horizon: AtomicLsn::new(0),
2862 904 :
2863 904 : pagestream_throttle: resources.pagestream_throttle,
2864 904 :
2865 904 : aux_file_size_estimator: AuxFileSizeEstimator::new(aux_file_metrics),
2866 904 :
2867 904 : #[cfg(test)]
2868 904 : extra_test_dense_keyspace: ArcSwap::new(Arc::new(KeySpace::default())),
2869 904 :
2870 904 : l0_flush_global_state: resources.l0_flush_global_state,
2871 904 :
2872 904 : handles: Default::default(),
2873 904 :
2874 904 : attach_wal_lag_cooldown,
2875 904 :
2876 904 : create_idempotency,
2877 904 :
2878 904 : page_trace: Default::default(),
2879 904 :
2880 904 : previous_heatmap: ArcSwapOption::from_pointee(previous_heatmap),
2881 904 :
2882 904 : heatmap_layers_downloader: Mutex::new(None),
2883 904 :
2884 904 : rel_size_v2_status: ArcSwapOption::from_pointee(rel_size_v2_status),
2885 904 :
2886 904 : wait_lsn_log_slow: tokio::sync::Semaphore::new(1),
2887 904 : };
2888 904 :
2889 904 : result.repartition_threshold =
2890 904 : result.get_checkpoint_distance() / REPARTITION_FREQ_IN_CHECKPOINT_DISTANCE;
2891 904 :
2892 904 : result
2893 904 : .metrics
2894 904 : .last_record_lsn_gauge
2895 904 : .set(disk_consistent_lsn.0 as i64);
2896 904 : result
2897 904 : })
2898 904 : }
2899 :
2900 1312 : pub(super) fn maybe_spawn_flush_loop(self: &Arc<Self>) {
2901 1312 : let Ok(guard) = self.gate.enter() else {
2902 0 : info!("cannot start flush loop when the timeline gate has already been closed");
2903 0 : return;
2904 : };
2905 1312 : let mut flush_loop_state = self.flush_loop_state.lock().unwrap();
2906 1312 : match *flush_loop_state {
2907 892 : FlushLoopState::NotStarted => (),
2908 : FlushLoopState::Running { .. } => {
2909 420 : info!(
2910 0 : "skipping attempt to start flush_loop twice {}/{}",
2911 0 : self.tenant_shard_id, self.timeline_id
2912 : );
2913 420 : return;
2914 : }
2915 : FlushLoopState::Exited => {
2916 0 : info!(
2917 0 : "ignoring attempt to restart exited flush_loop {}/{}",
2918 0 : self.tenant_shard_id, self.timeline_id
2919 : );
2920 0 : return;
2921 : }
2922 : }
2923 :
2924 892 : let layer_flush_start_rx = self.layer_flush_start_tx.subscribe();
2925 892 : let self_clone = Arc::clone(self);
2926 892 :
2927 892 : debug!("spawning flush loop");
2928 892 : *flush_loop_state = FlushLoopState::Running {
2929 892 : #[cfg(test)]
2930 892 : expect_initdb_optimization: false,
2931 892 : #[cfg(test)]
2932 892 : initdb_optimization_count: 0,
2933 892 : };
2934 892 : task_mgr::spawn(
2935 892 : task_mgr::BACKGROUND_RUNTIME.handle(),
2936 892 : task_mgr::TaskKind::LayerFlushTask,
2937 892 : self.tenant_shard_id,
2938 892 : Some(self.timeline_id),
2939 892 : "layer flush task",
2940 892 : async move {
2941 892 : let _guard = guard;
2942 892 : let background_ctx = RequestContext::todo_child(TaskKind::LayerFlushTask, DownloadBehavior::Error).with_scope_timeline(&self_clone);
2943 892 : self_clone.flush_loop(layer_flush_start_rx, &background_ctx).await;
2944 20 : let mut flush_loop_state = self_clone.flush_loop_state.lock().unwrap();
2945 20 : assert!(matches!(*flush_loop_state, FlushLoopState::Running{..}));
2946 20 : *flush_loop_state = FlushLoopState::Exited;
2947 20 : Ok(())
2948 20 : }
2949 892 : .instrument(info_span!(parent: None, "layer flush task", tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id))
2950 : );
2951 1312 : }
2952 :
2953 0 : pub(crate) fn update_gc_compaction_state(
2954 0 : &self,
2955 0 : gc_compaction_state: GcCompactionState,
2956 0 : ) -> anyhow::Result<()> {
2957 0 : self.gc_compaction_state
2958 0 : .store(Arc::new(Some(gc_compaction_state.clone())));
2959 0 : self.remote_client
2960 0 : .schedule_index_upload_for_gc_compaction_state_update(gc_compaction_state)
2961 0 : }
2962 :
2963 0 : pub(crate) fn update_rel_size_v2_status(
2964 0 : &self,
2965 0 : rel_size_v2_status: RelSizeMigration,
2966 0 : ) -> anyhow::Result<()> {
2967 0 : self.rel_size_v2_status
2968 0 : .store(Some(Arc::new(rel_size_v2_status.clone())));
2969 0 : self.remote_client
2970 0 : .schedule_index_upload_for_rel_size_v2_status_update(rel_size_v2_status)
2971 0 : }
2972 :
2973 0 : pub(crate) fn get_gc_compaction_state(&self) -> Option<GcCompactionState> {
2974 0 : self.gc_compaction_state.load_full().as_ref().clone()
2975 0 : }
2976 :
2977 : /// Creates and starts the wal receiver.
2978 : ///
2979 : /// This function is expected to be called at most once per Timeline's lifecycle
2980 : /// when the timeline is activated.
2981 0 : fn launch_wal_receiver(
2982 0 : self: &Arc<Self>,
2983 0 : ctx: &RequestContext,
2984 0 : broker_client: BrokerClientChannel,
2985 0 : ) {
2986 0 : info!(
2987 0 : "launching WAL receiver for timeline {} of tenant {}",
2988 0 : self.timeline_id, self.tenant_shard_id
2989 : );
2990 :
2991 0 : let tenant_conf = self.tenant_conf.load();
2992 0 : let wal_connect_timeout = tenant_conf
2993 0 : .tenant_conf
2994 0 : .walreceiver_connect_timeout
2995 0 : .unwrap_or(self.conf.default_tenant_conf.walreceiver_connect_timeout);
2996 0 : let lagging_wal_timeout = tenant_conf
2997 0 : .tenant_conf
2998 0 : .lagging_wal_timeout
2999 0 : .unwrap_or(self.conf.default_tenant_conf.lagging_wal_timeout);
3000 0 : let max_lsn_wal_lag = tenant_conf
3001 0 : .tenant_conf
3002 0 : .max_lsn_wal_lag
3003 0 : .unwrap_or(self.conf.default_tenant_conf.max_lsn_wal_lag);
3004 0 :
3005 0 : let mut guard = self.walreceiver.lock().unwrap();
3006 0 : assert!(
3007 0 : guard.is_none(),
3008 0 : "multiple launches / re-launches of WAL receiver are not supported"
3009 : );
3010 0 : *guard = Some(WalReceiver::start(
3011 0 : Arc::clone(self),
3012 0 : WalReceiverConf {
3013 0 : protocol: self.resolve_wal_receiver_protocol(),
3014 0 : wal_connect_timeout,
3015 0 : lagging_wal_timeout,
3016 0 : max_lsn_wal_lag,
3017 0 : auth_token: crate::config::SAFEKEEPER_AUTH_TOKEN.get().cloned(),
3018 0 : availability_zone: self.conf.availability_zone.clone(),
3019 0 : ingest_batch_size: self.conf.ingest_batch_size,
3020 0 : validate_wal_contiguity: self.conf.validate_wal_contiguity,
3021 0 : },
3022 0 : broker_client,
3023 0 : ctx,
3024 0 : ));
3025 0 : }
3026 :
3027 : /// Initialize with an empty layer map. Used when creating a new timeline.
3028 892 : pub(super) fn init_empty_layer_map(&self, start_lsn: Lsn) {
3029 892 : let mut layers = self.layers.try_write().expect(
3030 892 : "in the context where we call this function, no other task has access to the object",
3031 892 : );
3032 892 : layers
3033 892 : .open_mut()
3034 892 : .expect("in this context the LayerManager must still be open")
3035 892 : .initialize_empty(Lsn(start_lsn.0));
3036 892 : }
3037 :
3038 : /// Scan the timeline directory, cleanup, populate the layer map, and schedule uploads for local-only
3039 : /// files.
3040 12 : pub(super) async fn load_layer_map(
3041 12 : &self,
3042 12 : disk_consistent_lsn: Lsn,
3043 12 : index_part: IndexPart,
3044 12 : ) -> anyhow::Result<()> {
3045 : use LayerName::*;
3046 : use init::Decision::*;
3047 : use init::{Discovered, DismissedLayer};
3048 :
3049 12 : let mut guard = self.layers.write().await;
3050 :
3051 12 : let timer = self.metrics.load_layer_map_histo.start_timer();
3052 12 :
3053 12 : // Scan timeline directory and create ImageLayerName and DeltaFilename
3054 12 : // structs representing all files on disk
3055 12 : let timeline_path = self
3056 12 : .conf
3057 12 : .timeline_path(&self.tenant_shard_id, &self.timeline_id);
3058 12 : let conf = self.conf;
3059 12 : let span = tracing::Span::current();
3060 12 :
3061 12 : // Copy to move into the task we're about to spawn
3062 12 : let this = self.myself.upgrade().expect("&self method holds the arc");
3063 :
3064 12 : let (loaded_layers, needs_cleanup, total_physical_size) = tokio::task::spawn_blocking({
3065 12 : move || {
3066 12 : let _g = span.entered();
3067 12 : let discovered = init::scan_timeline_dir(&timeline_path)?;
3068 12 : let mut discovered_layers = Vec::with_capacity(discovered.len());
3069 12 : let mut unrecognized_files = Vec::new();
3070 12 :
3071 12 : let mut path = timeline_path;
3072 :
3073 44 : for discovered in discovered {
3074 32 : let (name, kind) = match discovered {
3075 32 : Discovered::Layer(layer_file_name, local_metadata) => {
3076 32 : discovered_layers.push((layer_file_name, local_metadata));
3077 32 : continue;
3078 : }
3079 0 : Discovered::IgnoredBackup(path) => {
3080 0 : std::fs::remove_file(path)
3081 0 : .or_else(fs_ext::ignore_not_found)
3082 0 : .fatal_err("Removing .old file");
3083 0 : continue;
3084 : }
3085 0 : Discovered::Unknown(file_name) => {
3086 0 : // we will later error if there are any
3087 0 : unrecognized_files.push(file_name);
3088 0 : continue;
3089 : }
3090 0 : Discovered::Ephemeral(name) => (name, "old ephemeral file"),
3091 0 : Discovered::Temporary(name) => (name, "temporary timeline file"),
3092 0 : Discovered::TemporaryDownload(name) => (name, "temporary download"),
3093 : };
3094 0 : path.push(Utf8Path::new(&name));
3095 0 : init::cleanup(&path, kind)?;
3096 0 : path.pop();
3097 : }
3098 :
3099 12 : if !unrecognized_files.is_empty() {
3100 : // assume that if there are any there are many many.
3101 0 : let n = unrecognized_files.len();
3102 0 : let first = &unrecognized_files[..n.min(10)];
3103 0 : anyhow::bail!(
3104 0 : "unrecognized files in timeline dir (total {n}), first 10: {first:?}"
3105 0 : );
3106 12 : }
3107 12 :
3108 12 : let decided = init::reconcile(discovered_layers, &index_part, disk_consistent_lsn);
3109 12 :
3110 12 : let mut loaded_layers = Vec::new();
3111 12 : let mut needs_cleanup = Vec::new();
3112 12 : let mut total_physical_size = 0;
3113 :
3114 44 : for (name, decision) in decided {
3115 32 : let decision = match decision {
3116 32 : Ok(decision) => decision,
3117 0 : Err(DismissedLayer::Future { local }) => {
3118 0 : if let Some(local) = local {
3119 0 : init::cleanup_future_layer(
3120 0 : &local.local_path,
3121 0 : &name,
3122 0 : disk_consistent_lsn,
3123 0 : )?;
3124 0 : }
3125 0 : needs_cleanup.push(name);
3126 0 : continue;
3127 : }
3128 0 : Err(DismissedLayer::LocalOnly(local)) => {
3129 0 : init::cleanup_local_only_file(&name, &local)?;
3130 : // this file never existed remotely, we will have to do rework
3131 0 : continue;
3132 : }
3133 0 : Err(DismissedLayer::BadMetadata(local)) => {
3134 0 : init::cleanup_local_file_for_remote(&local)?;
3135 : // this file never existed remotely, we will have to do rework
3136 0 : continue;
3137 : }
3138 : };
3139 :
3140 32 : match &name {
3141 24 : Delta(d) => assert!(d.lsn_range.end <= disk_consistent_lsn + 1),
3142 8 : Image(i) => assert!(i.lsn <= disk_consistent_lsn),
3143 : }
3144 :
3145 32 : tracing::debug!(layer=%name, ?decision, "applied");
3146 :
3147 32 : let layer = match decision {
3148 32 : Resident { local, remote } => {
3149 32 : total_physical_size += local.file_size;
3150 32 : Layer::for_resident(conf, &this, local.local_path, name, remote)
3151 32 : .drop_eviction_guard()
3152 : }
3153 0 : Evicted(remote) => Layer::for_evicted(conf, &this, name, remote),
3154 : };
3155 :
3156 32 : loaded_layers.push(layer);
3157 : }
3158 12 : Ok((loaded_layers, needs_cleanup, total_physical_size))
3159 12 : }
3160 12 : })
3161 12 : .await
3162 12 : .map_err(anyhow::Error::new)
3163 12 : .and_then(|x| x)?;
3164 :
3165 12 : let num_layers = loaded_layers.len();
3166 12 :
3167 12 : guard
3168 12 : .open_mut()
3169 12 : .expect("layermanager must be open during init")
3170 12 : .initialize_local_layers(loaded_layers, disk_consistent_lsn + 1);
3171 12 :
3172 12 : self.remote_client
3173 12 : .schedule_layer_file_deletion(&needs_cleanup)?;
3174 12 : self.remote_client
3175 12 : .schedule_index_upload_for_file_changes()?;
3176 : // This barrier orders above DELETEs before any later operations.
3177 : // This is critical because code executing after the barrier might
3178 : // create again objects with the same key that we just scheduled for deletion.
3179 : // For example, if we just scheduled deletion of an image layer "from the future",
3180 : // later compaction might run again and re-create the same image layer.
3181 : // "from the future" here means an image layer whose LSN is > IndexPart::disk_consistent_lsn.
3182 : // "same" here means same key range and LSN.
3183 : //
3184 : // Without a barrier between above DELETEs and the re-creation's PUTs,
3185 : // the upload queue may execute the PUT first, then the DELETE.
3186 : // In our example, we will end up with an IndexPart referencing a non-existent object.
3187 : //
3188 : // 1. a future image layer is created and uploaded
3189 : // 2. ps restart
3190 : // 3. the future layer from (1) is deleted during load layer map
3191 : // 4. image layer is re-created and uploaded
3192 : // 5. deletion queue would like to delete (1) but actually deletes (4)
3193 : // 6. delete by name works as expected, but it now deletes the wrong (later) version
3194 : //
3195 : // See https://github.com/neondatabase/neon/issues/5878
3196 : //
3197 : // NB: generation numbers naturally protect against this because they disambiguate
3198 : // (1) and (4)
3199 : // TODO: this is basically a no-op now, should we remove it?
3200 12 : self.remote_client.schedule_barrier()?;
3201 : // Tenant::create_timeline will wait for these uploads to happen before returning, or
3202 : // on retry.
3203 :
3204 : // Now that we have the full layer map, we may calculate the visibility of layers within it (a global scan)
3205 12 : drop(guard); // drop write lock, update_layer_visibility will take a read lock.
3206 12 : self.update_layer_visibility().await?;
3207 :
3208 12 : info!(
3209 0 : "loaded layer map with {} layers at {}, total physical size: {}",
3210 : num_layers, disk_consistent_lsn, total_physical_size
3211 : );
3212 :
3213 12 : timer.stop_and_record();
3214 12 : Ok(())
3215 12 : }
3216 :
3217 : /// Retrieve current logical size of the timeline.
3218 : ///
3219 : /// The size could be lagging behind the actual number, in case
3220 : /// the initial size calculation has not been run (gets triggered on the first size access).
3221 : ///
3222 : /// return size and boolean flag that shows if the size is exact
3223 0 : pub(crate) fn get_current_logical_size(
3224 0 : self: &Arc<Self>,
3225 0 : priority: GetLogicalSizePriority,
3226 0 : ctx: &RequestContext,
3227 0 : ) -> logical_size::CurrentLogicalSize {
3228 0 : if !self.tenant_shard_id.is_shard_zero() {
3229 : // Logical size is only accurately maintained on shard zero: when called elsewhere, for example
3230 : // when HTTP API is serving a GET for timeline zero, return zero
3231 0 : return logical_size::CurrentLogicalSize::Approximate(logical_size::Approximate::zero());
3232 0 : }
3233 0 :
3234 0 : let current_size = self.current_logical_size.current_size();
3235 0 : debug!("Current size: {current_size:?}");
3236 :
3237 0 : match (current_size.accuracy(), priority) {
3238 0 : (logical_size::Accuracy::Exact, _) => (), // nothing to do
3239 0 : (logical_size::Accuracy::Approximate, GetLogicalSizePriority::Background) => {
3240 0 : // background task will eventually deliver an exact value, we're in no rush
3241 0 : }
3242 : (logical_size::Accuracy::Approximate, GetLogicalSizePriority::User) => {
3243 : // background task is not ready, but user is asking for it now;
3244 : // => make the background task skip the line
3245 : // (The alternative would be to calculate the size here, but,
3246 : // it can actually take a long time if the user has a lot of rels.
3247 : // And we'll inevitable need it again; So, let the background task do the work.)
3248 0 : match self
3249 0 : .current_logical_size
3250 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore
3251 0 : .get()
3252 : {
3253 0 : Some(cancel) => cancel.cancel(),
3254 : None => {
3255 0 : match self.current_state() {
3256 0 : TimelineState::Broken { .. } | TimelineState::Stopping => {
3257 0 : // Can happen when timeline detail endpoint is used when deletion is ongoing (or its broken).
3258 0 : // Don't make noise.
3259 0 : }
3260 : TimelineState::Loading => {
3261 : // Import does not return an activated timeline.
3262 0 : info!(
3263 0 : "discarding priority boost for logical size calculation because timeline is not yet active"
3264 : );
3265 : }
3266 : TimelineState::Active => {
3267 : // activation should be setting the once cell
3268 0 : warn!(
3269 0 : "unexpected: cancel_wait_for_background_loop_concurrency_limit_semaphore not set, priority-boosting of logical size calculation will not work"
3270 : );
3271 0 : debug_assert!(false);
3272 : }
3273 : }
3274 : }
3275 : }
3276 : }
3277 : }
3278 :
3279 0 : if let CurrentLogicalSize::Approximate(_) = ¤t_size {
3280 0 : if ctx.task_kind() == TaskKind::WalReceiverConnectionHandler {
3281 0 : let first = self
3282 0 : .current_logical_size
3283 0 : .did_return_approximate_to_walreceiver
3284 0 : .compare_exchange(
3285 0 : false,
3286 0 : true,
3287 0 : AtomicOrdering::Relaxed,
3288 0 : AtomicOrdering::Relaxed,
3289 0 : )
3290 0 : .is_ok();
3291 0 : if first {
3292 0 : crate::metrics::initial_logical_size::TIMELINES_WHERE_WALRECEIVER_GOT_APPROXIMATE_SIZE.inc();
3293 0 : }
3294 0 : }
3295 0 : }
3296 :
3297 0 : current_size
3298 0 : }
3299 :
3300 0 : fn spawn_initial_logical_size_computation_task(self: &Arc<Self>, ctx: &RequestContext) {
3301 0 : let Some(initial_part_end) = self.current_logical_size.initial_part_end else {
3302 : // nothing to do for freshly created timelines;
3303 0 : assert_eq!(
3304 0 : self.current_logical_size.current_size().accuracy(),
3305 0 : logical_size::Accuracy::Exact,
3306 0 : );
3307 0 : self.current_logical_size.initialized.add_permits(1);
3308 0 : return;
3309 : };
3310 :
3311 0 : let cancel_wait_for_background_loop_concurrency_limit_semaphore = CancellationToken::new();
3312 0 : let token = cancel_wait_for_background_loop_concurrency_limit_semaphore.clone();
3313 0 : self.current_logical_size
3314 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore.set(token)
3315 0 : .expect("initial logical size calculation task must be spawned exactly once per Timeline object");
3316 0 :
3317 0 : let self_clone = Arc::clone(self);
3318 0 : let background_ctx = ctx.detached_child(
3319 0 : TaskKind::InitialLogicalSizeCalculation,
3320 0 : DownloadBehavior::Download,
3321 0 : );
3322 0 : task_mgr::spawn(
3323 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
3324 0 : task_mgr::TaskKind::InitialLogicalSizeCalculation,
3325 0 : self.tenant_shard_id,
3326 0 : Some(self.timeline_id),
3327 0 : "initial size calculation",
3328 : // NB: don't log errors here, task_mgr will do that.
3329 0 : async move {
3330 0 : self_clone
3331 0 : .initial_logical_size_calculation_task(
3332 0 : initial_part_end,
3333 0 : cancel_wait_for_background_loop_concurrency_limit_semaphore,
3334 0 : background_ctx,
3335 0 : )
3336 0 : .await;
3337 0 : Ok(())
3338 0 : }
3339 0 : .instrument(info_span!(parent: None, "initial_size_calculation", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%self.timeline_id)),
3340 : );
3341 0 : }
3342 :
3343 : /// # Cancellation
3344 : ///
3345 : /// This method is sensitive to `Timeline::cancel`.
3346 : ///
3347 : /// It is _not_ sensitive to task_mgr::shutdown_token().
3348 : ///
3349 : /// # Cancel-Safety
3350 : ///
3351 : /// It does Timeline IO, hence this should be polled to completion because
3352 : /// we could be leaving in-flight IOs behind, which is safe, but annoying
3353 : /// to reason about.
3354 0 : async fn initial_logical_size_calculation_task(
3355 0 : self: Arc<Self>,
3356 0 : initial_part_end: Lsn,
3357 0 : skip_concurrency_limiter: CancellationToken,
3358 0 : background_ctx: RequestContext,
3359 0 : ) {
3360 0 : scopeguard::defer! {
3361 0 : // Irrespective of the outcome of this operation, we should unblock anyone waiting for it.
3362 0 : self.current_logical_size.initialized.add_permits(1);
3363 0 : }
3364 0 :
3365 0 : let try_once = |attempt: usize| {
3366 0 : let background_ctx = &background_ctx;
3367 0 : let self_ref = &self;
3368 0 : let skip_concurrency_limiter = &skip_concurrency_limiter;
3369 0 : async move {
3370 0 : let wait_for_permit = super::tasks::acquire_concurrency_permit(
3371 0 : BackgroundLoopKind::InitialLogicalSizeCalculation,
3372 0 : background_ctx,
3373 0 : );
3374 :
3375 : use crate::metrics::initial_logical_size::StartCircumstances;
3376 0 : let (_maybe_permit, circumstances) = tokio::select! {
3377 0 : permit = wait_for_permit => {
3378 0 : (Some(permit), StartCircumstances::AfterBackgroundTasksRateLimit)
3379 : }
3380 0 : _ = self_ref.cancel.cancelled() => {
3381 0 : return Err(CalculateLogicalSizeError::Cancelled);
3382 : }
3383 0 : () = skip_concurrency_limiter.cancelled() => {
3384 : // Some action that is part of a end user interaction requested logical size
3385 : // => break out of the rate limit
3386 : // TODO: ideally we'd not run on BackgroundRuntime but the requester's runtime;
3387 : // but then again what happens if they cancel; also, we should just be using
3388 : // one runtime across the entire process, so, let's leave this for now.
3389 0 : (None, StartCircumstances::SkippedConcurrencyLimiter)
3390 : }
3391 : };
3392 :
3393 0 : let metrics_guard = if attempt == 1 {
3394 0 : crate::metrics::initial_logical_size::START_CALCULATION.first(circumstances)
3395 : } else {
3396 0 : crate::metrics::initial_logical_size::START_CALCULATION.retry(circumstances)
3397 : };
3398 :
3399 0 : let io_concurrency = IoConcurrency::spawn_from_conf(
3400 0 : self_ref.conf,
3401 0 : self_ref
3402 0 : .gate
3403 0 : .enter()
3404 0 : .map_err(|_| CalculateLogicalSizeError::Cancelled)?,
3405 : );
3406 :
3407 0 : let calculated_size = self_ref
3408 0 : .logical_size_calculation_task(
3409 0 : initial_part_end,
3410 0 : LogicalSizeCalculationCause::Initial,
3411 0 : background_ctx,
3412 0 : )
3413 0 : .await?;
3414 :
3415 0 : self_ref
3416 0 : .trigger_aux_file_size_computation(
3417 0 : initial_part_end,
3418 0 : background_ctx,
3419 0 : io_concurrency,
3420 0 : )
3421 0 : .await?;
3422 :
3423 : // TODO: add aux file size to logical size
3424 :
3425 0 : Ok((calculated_size, metrics_guard))
3426 0 : }
3427 0 : };
3428 :
3429 0 : let retrying = async {
3430 0 : let mut attempt = 0;
3431 : loop {
3432 0 : attempt += 1;
3433 0 :
3434 0 : match try_once(attempt).await {
3435 0 : Ok(res) => return ControlFlow::Continue(res),
3436 0 : Err(CalculateLogicalSizeError::Cancelled) => return ControlFlow::Break(()),
3437 : Err(
3438 0 : e @ (CalculateLogicalSizeError::Decode(_)
3439 0 : | CalculateLogicalSizeError::PageRead(_)),
3440 0 : ) => {
3441 0 : warn!(attempt, "initial size calculation failed: {e:?}");
3442 : // exponential back-off doesn't make sense at these long intervals;
3443 : // use fixed retry interval with generous jitter instead
3444 0 : let sleep_duration = Duration::from_secs(
3445 0 : u64::try_from(
3446 0 : // 1hour base
3447 0 : (60_i64 * 60_i64)
3448 0 : // 10min jitter
3449 0 : + rand::thread_rng().gen_range(-10 * 60..10 * 60),
3450 0 : )
3451 0 : .expect("10min < 1hour"),
3452 0 : );
3453 0 : tokio::select! {
3454 0 : _ = tokio::time::sleep(sleep_duration) => {}
3455 0 : _ = self.cancel.cancelled() => return ControlFlow::Break(()),
3456 : }
3457 : }
3458 : }
3459 : }
3460 0 : };
3461 :
3462 0 : let (calculated_size, metrics_guard) = match retrying.await {
3463 0 : ControlFlow::Continue(calculated_size) => calculated_size,
3464 0 : ControlFlow::Break(()) => return,
3465 : };
3466 :
3467 : // we cannot query current_logical_size.current_size() to know the current
3468 : // *negative* value, only truncated to u64.
3469 0 : let added = self
3470 0 : .current_logical_size
3471 0 : .size_added_after_initial
3472 0 : .load(AtomicOrdering::Relaxed);
3473 0 :
3474 0 : let sum = calculated_size.saturating_add_signed(added);
3475 0 :
3476 0 : // set the gauge value before it can be set in `update_current_logical_size`.
3477 0 : self.metrics.current_logical_size_gauge.set(sum);
3478 0 :
3479 0 : self.current_logical_size
3480 0 : .initial_logical_size
3481 0 : .set((calculated_size, metrics_guard.calculation_result_saved()))
3482 0 : .ok()
3483 0 : .expect("only this task sets it");
3484 0 : }
3485 :
3486 0 : pub(crate) fn spawn_ondemand_logical_size_calculation(
3487 0 : self: &Arc<Self>,
3488 0 : lsn: Lsn,
3489 0 : cause: LogicalSizeCalculationCause,
3490 0 : ctx: RequestContext,
3491 0 : ) -> oneshot::Receiver<Result<u64, CalculateLogicalSizeError>> {
3492 0 : let (sender, receiver) = oneshot::channel();
3493 0 : let self_clone = Arc::clone(self);
3494 0 : // XXX if our caller loses interest, i.e., ctx is cancelled,
3495 0 : // we should stop the size calculation work and return an error.
3496 0 : // That would require restructuring this function's API to
3497 0 : // return the result directly, instead of a Receiver for the result.
3498 0 : let ctx = ctx.detached_child(
3499 0 : TaskKind::OndemandLogicalSizeCalculation,
3500 0 : DownloadBehavior::Download,
3501 0 : );
3502 0 : task_mgr::spawn(
3503 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
3504 0 : task_mgr::TaskKind::OndemandLogicalSizeCalculation,
3505 0 : self.tenant_shard_id,
3506 0 : Some(self.timeline_id),
3507 0 : "ondemand logical size calculation",
3508 0 : async move {
3509 0 : let res = self_clone
3510 0 : .logical_size_calculation_task(lsn, cause, &ctx)
3511 0 : .await;
3512 0 : let _ = sender.send(res).ok();
3513 0 : Ok(()) // Receiver is responsible for handling errors
3514 0 : }
3515 0 : .in_current_span(),
3516 0 : );
3517 0 : receiver
3518 0 : }
3519 :
3520 : #[instrument(skip_all)]
3521 : async fn logical_size_calculation_task(
3522 : self: &Arc<Self>,
3523 : lsn: Lsn,
3524 : cause: LogicalSizeCalculationCause,
3525 : ctx: &RequestContext,
3526 : ) -> Result<u64, CalculateLogicalSizeError> {
3527 : crate::span::debug_assert_current_span_has_tenant_and_timeline_id();
3528 : // We should never be calculating logical sizes on shard !=0, because these shards do not have
3529 : // accurate relation sizes, and they do not emit consumption metrics.
3530 : debug_assert!(self.tenant_shard_id.is_shard_zero());
3531 :
3532 : let guard = self
3533 : .gate
3534 : .enter()
3535 0 : .map_err(|_| CalculateLogicalSizeError::Cancelled)?;
3536 :
3537 : self.calculate_logical_size(lsn, cause, &guard, ctx).await
3538 : }
3539 :
3540 : /// Calculate the logical size of the database at the latest LSN.
3541 : ///
3542 : /// NOTE: counted incrementally, includes ancestors. This can be a slow operation,
3543 : /// especially if we need to download remote layers.
3544 0 : async fn calculate_logical_size(
3545 0 : &self,
3546 0 : up_to_lsn: Lsn,
3547 0 : cause: LogicalSizeCalculationCause,
3548 0 : _guard: &GateGuard,
3549 0 : ctx: &RequestContext,
3550 0 : ) -> Result<u64, CalculateLogicalSizeError> {
3551 0 : info!(
3552 0 : "Calculating logical size for timeline {} at {}",
3553 : self.timeline_id, up_to_lsn
3554 : );
3555 :
3556 0 : if let Err(()) = pausable_failpoint!("timeline-calculate-logical-size-pause", &self.cancel)
3557 : {
3558 0 : return Err(CalculateLogicalSizeError::Cancelled);
3559 0 : }
3560 :
3561 : // See if we've already done the work for initial size calculation.
3562 : // This is a short-cut for timelines that are mostly unused.
3563 0 : if let Some(size) = self.current_logical_size.initialized_size(up_to_lsn) {
3564 0 : return Ok(size);
3565 0 : }
3566 0 : let storage_time_metrics = match cause {
3567 : LogicalSizeCalculationCause::Initial
3568 : | LogicalSizeCalculationCause::ConsumptionMetricsSyntheticSize
3569 0 : | LogicalSizeCalculationCause::TenantSizeHandler => &self.metrics.logical_size_histo,
3570 : LogicalSizeCalculationCause::EvictionTaskImitation => {
3571 0 : &self.metrics.imitate_logical_size_histo
3572 : }
3573 : };
3574 0 : let timer = storage_time_metrics.start_timer();
3575 0 : let logical_size = self
3576 0 : .get_current_logical_size_non_incremental(up_to_lsn, ctx)
3577 0 : .await?;
3578 0 : debug!("calculated logical size: {logical_size}");
3579 0 : timer.stop_and_record();
3580 0 : Ok(logical_size)
3581 0 : }
3582 :
3583 : /// Update current logical size, adding `delta' to the old value.
3584 541140 : fn update_current_logical_size(&self, delta: i64) {
3585 541140 : let logical_size = &self.current_logical_size;
3586 541140 : logical_size.increment_size(delta);
3587 541140 :
3588 541140 : // Also set the value in the prometheus gauge. Note that
3589 541140 : // there is a race condition here: if this is is called by two
3590 541140 : // threads concurrently, the prometheus gauge might be set to
3591 541140 : // one value while current_logical_size is set to the
3592 541140 : // other.
3593 541140 : match logical_size.current_size() {
3594 541140 : CurrentLogicalSize::Exact(ref new_current_size) => self
3595 541140 : .metrics
3596 541140 : .current_logical_size_gauge
3597 541140 : .set(new_current_size.into()),
3598 0 : CurrentLogicalSize::Approximate(_) => {
3599 0 : // don't update the gauge yet, this allows us not to update the gauge back and
3600 0 : // forth between the initial size calculation task.
3601 0 : }
3602 : }
3603 541140 : }
3604 :
3605 5988 : pub(crate) fn update_directory_entries_count(&self, kind: DirectoryKind, count: MetricsUpdate) {
3606 5988 : // TODO: this directory metrics is not correct -- we could have multiple reldirs in the system
3607 5988 : // for each of the database, but we only store one value, and therefore each pgdirmodification
3608 5988 : // would overwrite the previous value if they modify different databases.
3609 5988 :
3610 5988 : match count {
3611 2144 : MetricsUpdate::Set(count) => {
3612 2144 : self.directory_metrics[kind.offset()].store(count, AtomicOrdering::Relaxed);
3613 2144 : self.directory_metrics_inited[kind.offset()].store(true, AtomicOrdering::Relaxed);
3614 2144 : }
3615 3840 : MetricsUpdate::Add(count) => {
3616 3840 : // TODO: these operations are not atomic; but we only have one writer to the metrics, so
3617 3840 : // it's fine.
3618 3840 : if self.directory_metrics_inited[kind.offset()].load(AtomicOrdering::Relaxed) {
3619 3840 : // The metrics has been initialized with `MetricsUpdate::Set` before, so we can add/sub
3620 3840 : // the value reliably.
3621 3840 : self.directory_metrics[kind.offset()].fetch_add(count, AtomicOrdering::Relaxed);
3622 3840 : }
3623 : // Otherwise, ignore this update
3624 : }
3625 4 : MetricsUpdate::Sub(count) => {
3626 4 : // TODO: these operations are not atomic; but we only have one writer to the metrics, so
3627 4 : // it's fine.
3628 4 : if self.directory_metrics_inited[kind.offset()].load(AtomicOrdering::Relaxed) {
3629 4 : // The metrics has been initialized with `MetricsUpdate::Set` before.
3630 4 : // The operation could overflow so we need to normalize the value.
3631 4 : let prev_val =
3632 4 : self.directory_metrics[kind.offset()].load(AtomicOrdering::Relaxed);
3633 4 : let res = prev_val.saturating_sub(count);
3634 4 : self.directory_metrics[kind.offset()].store(res, AtomicOrdering::Relaxed);
3635 4 : }
3636 : // Otherwise, ignore this update
3637 : }
3638 : };
3639 :
3640 : // TODO: remove this, there's no place in the code that updates this aux metrics.
3641 5988 : let aux_metric =
3642 5988 : self.directory_metrics[DirectoryKind::AuxFiles.offset()].load(AtomicOrdering::Relaxed);
3643 5988 :
3644 5988 : let sum_of_entries = self
3645 5988 : .directory_metrics
3646 5988 : .iter()
3647 47904 : .map(|v| v.load(AtomicOrdering::Relaxed))
3648 5988 : .sum();
3649 : // Set a high general threshold and a lower threshold for the auxiliary files,
3650 : // as we can have large numbers of relations in the db directory.
3651 : const SUM_THRESHOLD: u64 = 5000;
3652 : const AUX_THRESHOLD: u64 = 1000;
3653 5988 : if sum_of_entries >= SUM_THRESHOLD || aux_metric >= AUX_THRESHOLD {
3654 0 : self.metrics
3655 0 : .directory_entries_count_gauge
3656 0 : .set(sum_of_entries);
3657 5988 : } else if let Some(metric) = Lazy::get(&self.metrics.directory_entries_count_gauge) {
3658 0 : metric.set(sum_of_entries);
3659 5988 : }
3660 5988 : }
3661 :
3662 0 : async fn find_layer(
3663 0 : &self,
3664 0 : layer_name: &LayerName,
3665 0 : ) -> Result<Option<Layer>, layer_manager::Shutdown> {
3666 0 : let guard = self.layers.read().await;
3667 0 : let layer = guard
3668 0 : .layer_map()?
3669 0 : .iter_historic_layers()
3670 0 : .find(|l| &l.layer_name() == layer_name)
3671 0 : .map(|found| guard.get_from_desc(&found));
3672 0 : Ok(layer)
3673 0 : }
3674 :
3675 0 : pub(super) fn should_keep_previous_heatmap(&self, new_heatmap_end_lsn: Lsn) -> bool {
3676 0 : let crnt = self.previous_heatmap.load();
3677 0 : match crnt.as_deref() {
3678 0 : Some(PreviousHeatmap::Active { end_lsn, .. }) => match end_lsn {
3679 0 : Some(crnt_end_lsn) => *crnt_end_lsn > new_heatmap_end_lsn,
3680 0 : None => true,
3681 : },
3682 0 : Some(PreviousHeatmap::Obsolete) => false,
3683 0 : None => false,
3684 : }
3685 0 : }
3686 :
3687 : /// The timeline heatmap is a hint to secondary locations from the primary location,
3688 : /// indicating which layers are currently on-disk on the primary.
3689 : ///
3690 : /// None is returned if the Timeline is in a state where uploading a heatmap
3691 : /// doesn't make sense, such as shutting down or initializing. The caller
3692 : /// should treat this as a cue to simply skip doing any heatmap uploading
3693 : /// for this timeline.
3694 32 : pub(crate) async fn generate_heatmap(&self) -> Option<HeatMapTimeline> {
3695 32 : if !self.is_active() {
3696 0 : return None;
3697 32 : }
3698 :
3699 32 : let guard = self.layers.read().await;
3700 :
3701 : // Firstly, if there's any heatmap left over from when this location
3702 : // was a secondary, take that into account. Keep layers that are:
3703 : // * present in the layer map
3704 : // * visible
3705 : // * non-resident
3706 : // * not evicted since we read the heatmap
3707 : //
3708 : // Without this, a new cold, attached location would clobber the previous
3709 : // heatamp.
3710 32 : let previous_heatmap = self.previous_heatmap.load();
3711 32 : let visible_non_resident = match previous_heatmap.as_deref() {
3712 : Some(PreviousHeatmap::Active {
3713 24 : heatmap, read_at, ..
3714 92 : }) => Some(heatmap.all_layers().filter_map(|hl| {
3715 92 : let desc: PersistentLayerDesc = hl.name.clone().into();
3716 92 : let layer = guard.try_get_from_key(&desc.key())?;
3717 :
3718 92 : if layer.visibility() == LayerVisibilityHint::Covered {
3719 0 : return None;
3720 92 : }
3721 92 :
3722 92 : if layer.is_likely_resident() {
3723 40 : return None;
3724 52 : }
3725 52 :
3726 52 : if layer.last_evicted_at().happened_after(*read_at) {
3727 12 : return None;
3728 40 : }
3729 40 :
3730 40 : Some((desc, hl.metadata.clone(), hl.access_time, hl.cold))
3731 92 : })),
3732 0 : Some(PreviousHeatmap::Obsolete) => None,
3733 8 : None => None,
3734 : };
3735 :
3736 : // Secondly, all currently visible, resident layers are included.
3737 72 : let resident = guard.likely_resident_layers().filter_map(|layer| {
3738 72 : match layer.visibility() {
3739 : LayerVisibilityHint::Visible => {
3740 : // Layer is visible to one or more read LSNs: elegible for inclusion in layer map
3741 68 : let last_activity_ts = layer.latest_activity();
3742 68 : Some((
3743 68 : layer.layer_desc().clone(),
3744 68 : layer.metadata(),
3745 68 : last_activity_ts,
3746 68 : false, // these layers are not cold
3747 68 : ))
3748 : }
3749 : LayerVisibilityHint::Covered => {
3750 : // Layer is resident but unlikely to be read: not elegible for inclusion in heatmap.
3751 4 : None
3752 : }
3753 : }
3754 72 : });
3755 :
3756 32 : let mut layers = match visible_non_resident {
3757 24 : Some(non_resident) => {
3758 24 : let mut non_resident = non_resident.peekable();
3759 24 : if non_resident.peek().is_none() {
3760 8 : tracing::info!(timeline_id=%self.timeline_id, "Previous heatmap now obsolete");
3761 8 : self.previous_heatmap
3762 8 : .store(Some(PreviousHeatmap::Obsolete.into()));
3763 16 : }
3764 :
3765 24 : non_resident.chain(resident).collect::<Vec<_>>()
3766 : }
3767 8 : None => resident.collect::<Vec<_>>(),
3768 : };
3769 :
3770 : // Sort layers in order of which to download first. For a large set of layers to download, we
3771 : // want to prioritize those layers which are most likely to still be in the resident many minutes
3772 : // or hours later:
3773 : // - Cold layers go last for convenience when a human inspects the heatmap.
3774 : // - Download L0s last, because they churn the fastest: L0s on a fast-writing tenant might
3775 : // only exist for a few minutes before being compacted into L1s.
3776 : // - For L1 & image layers, download most recent LSNs first: the older the LSN, the sooner
3777 : // the layer is likely to be covered by an image layer during compaction.
3778 234 : layers.sort_by_key(|(desc, _meta, _atime, cold)| {
3779 234 : std::cmp::Reverse((
3780 234 : *cold,
3781 234 : !LayerMap::is_l0(&desc.key_range, desc.is_delta),
3782 234 : desc.lsn_range.end,
3783 234 : ))
3784 234 : });
3785 32 :
3786 32 : let layers = layers
3787 32 : .into_iter()
3788 108 : .map(|(desc, meta, atime, cold)| {
3789 108 : HeatMapLayer::new(desc.layer_name(), meta, atime, cold)
3790 108 : })
3791 32 : .collect();
3792 32 :
3793 32 : Some(HeatMapTimeline::new(self.timeline_id, layers))
3794 32 : }
3795 :
3796 0 : pub(super) async fn generate_unarchival_heatmap(&self, end_lsn: Lsn) -> PreviousHeatmap {
3797 0 : let guard = self.layers.read().await;
3798 :
3799 0 : let now = SystemTime::now();
3800 0 : let mut heatmap_layers = Vec::default();
3801 0 : for vl in guard.visible_layers() {
3802 0 : if vl.layer_desc().get_lsn_range().start >= end_lsn {
3803 0 : continue;
3804 0 : }
3805 0 :
3806 0 : let hl = HeatMapLayer {
3807 0 : name: vl.layer_desc().layer_name(),
3808 0 : metadata: vl.metadata(),
3809 0 : access_time: now,
3810 0 : cold: true,
3811 0 : };
3812 0 : heatmap_layers.push(hl);
3813 : }
3814 :
3815 0 : tracing::info!(
3816 0 : "Generating unarchival heatmap with {} layers",
3817 0 : heatmap_layers.len()
3818 : );
3819 :
3820 0 : let heatmap = HeatMapTimeline::new(self.timeline_id, heatmap_layers);
3821 0 : PreviousHeatmap::Active {
3822 0 : heatmap,
3823 0 : read_at: Instant::now(),
3824 0 : end_lsn: Some(end_lsn),
3825 0 : }
3826 0 : }
3827 :
3828 : /// Returns true if the given lsn is or was an ancestor branchpoint.
3829 0 : pub(crate) fn is_ancestor_lsn(&self, lsn: Lsn) -> bool {
3830 0 : // upon timeline detach, we set the ancestor_lsn to Lsn::INVALID and the store the original
3831 0 : // branchpoint in the value in IndexPart::lineage
3832 0 : self.ancestor_lsn == lsn
3833 0 : || (self.ancestor_lsn == Lsn::INVALID
3834 0 : && self.remote_client.is_previous_ancestor_lsn(lsn))
3835 0 : }
3836 : }
3837 :
3838 : impl Timeline {
3839 : #[allow(clippy::doc_lazy_continuation)]
3840 : /// Get the data needed to reconstruct all keys in the provided keyspace
3841 : ///
3842 : /// The algorithm is as follows:
3843 : /// 1. While some keys are still not done and there's a timeline to visit:
3844 : /// 2. Visit the timeline (see [`Timeline::get_vectored_reconstruct_data_timeline`]:
3845 : /// 2.1: Build the fringe for the current keyspace
3846 : /// 2.2 Visit the newest layer from the fringe to collect all values for the range it
3847 : /// intersects
3848 : /// 2.3. Pop the timeline from the fringe
3849 : /// 2.4. If the fringe is empty, go back to 1
3850 1255388 : async fn get_vectored_reconstruct_data(
3851 1255388 : &self,
3852 1255388 : mut keyspace: KeySpace,
3853 1255388 : request_lsn: Lsn,
3854 1255388 : reconstruct_state: &mut ValuesReconstructState,
3855 1255388 : ctx: &RequestContext,
3856 1255388 : ) -> Result<(), GetVectoredError> {
3857 1255388 : let mut timeline_owned: Arc<Timeline>;
3858 1255388 : let mut timeline = self;
3859 1255388 :
3860 1255388 : let mut cont_lsn = Lsn(request_lsn.0 + 1);
3861 :
3862 1255384 : let missing_keyspace = loop {
3863 1706502 : if self.cancel.is_cancelled() {
3864 0 : return Err(GetVectoredError::Cancelled);
3865 1706502 : }
3866 :
3867 : let TimelineVisitOutcome {
3868 1706502 : completed_keyspace: completed,
3869 1706502 : image_covered_keyspace,
3870 1706502 : } = Self::get_vectored_reconstruct_data_timeline(
3871 1706502 : timeline,
3872 1706502 : keyspace.clone(),
3873 1706502 : cont_lsn,
3874 1706502 : reconstruct_state,
3875 1706502 : &self.cancel,
3876 1706502 : ctx,
3877 1706502 : )
3878 1706502 : .await?;
3879 :
3880 1706502 : keyspace.remove_overlapping_with(&completed);
3881 1706502 :
3882 1706502 : // Do not descend into the ancestor timeline for aux files.
3883 1706502 : // We don't return a blanket [`GetVectoredError::MissingKey`] to avoid
3884 1706502 : // stalling compaction.
3885 1706502 : keyspace.remove_overlapping_with(&KeySpace {
3886 1706502 : ranges: vec![NON_INHERITED_RANGE, Key::sparse_non_inherited_keyspace()],
3887 1706502 : });
3888 1706502 :
3889 1706502 : // Keyspace is fully retrieved
3890 1706502 : if keyspace.is_empty() {
3891 1254876 : break None;
3892 451626 : }
3893 :
3894 451626 : let Some(ancestor_timeline) = timeline.ancestor_timeline.as_ref() else {
3895 : // Not fully retrieved but no ancestor timeline.
3896 508 : break Some(keyspace);
3897 : };
3898 :
3899 : // Now we see if there are keys covered by the image layer but does not exist in the
3900 : // image layer, which means that the key does not exist.
3901 :
3902 : // The block below will stop the vectored search if any of the keys encountered an image layer
3903 : // which did not contain a snapshot for said key. Since we have already removed all completed
3904 : // keys from `keyspace`, we expect there to be no overlap between it and the image covered key
3905 : // space. If that's not the case, we had at least one key encounter a gap in the image layer
3906 : // and stop the search as a result of that.
3907 451118 : let mut removed = keyspace.remove_overlapping_with(&image_covered_keyspace);
3908 451118 : // Do not fire missing key error and end early for sparse keys. Note that we hava already removed
3909 451118 : // non-inherited keyspaces before, so we can safely do a full `SPARSE_RANGE` remove instead of
3910 451118 : // figuring out what is the inherited key range and do a fine-grained pruning.
3911 451118 : removed.remove_overlapping_with(&KeySpace {
3912 451118 : ranges: vec![SPARSE_RANGE],
3913 451118 : });
3914 451118 : if !removed.is_empty() {
3915 0 : break Some(removed);
3916 451118 : }
3917 451118 : // If we reached this point, `remove_overlapping_with` should not have made any change to the
3918 451118 : // keyspace.
3919 451118 :
3920 451118 : // Take the min to avoid reconstructing a page with data newer than request Lsn.
3921 451118 : cont_lsn = std::cmp::min(Lsn(request_lsn.0 + 1), Lsn(timeline.ancestor_lsn.0 + 1));
3922 451118 : timeline_owned = timeline
3923 451118 : .get_ready_ancestor_timeline(ancestor_timeline, ctx)
3924 451118 : .await?;
3925 451114 : timeline = &*timeline_owned;
3926 : };
3927 :
3928 : // Remove sparse keys from the keyspace so that it doesn't fire errors.
3929 1255384 : let missing_keyspace = if let Some(missing_keyspace) = missing_keyspace {
3930 508 : let mut missing_keyspace = missing_keyspace;
3931 508 : missing_keyspace.remove_overlapping_with(&KeySpace {
3932 508 : ranges: vec![SPARSE_RANGE],
3933 508 : });
3934 508 : if missing_keyspace.is_empty() {
3935 480 : None
3936 : } else {
3937 28 : Some(missing_keyspace)
3938 : }
3939 : } else {
3940 1254876 : None
3941 : };
3942 :
3943 1255384 : if let Some(missing_keyspace) = missing_keyspace {
3944 28 : return Err(GetVectoredError::MissingKey(MissingKeyError {
3945 28 : key: missing_keyspace.start().unwrap(), /* better if we can store the full keyspace */
3946 28 : shard: self
3947 28 : .shard_identity
3948 28 : .get_shard_number(&missing_keyspace.start().unwrap()),
3949 28 : cont_lsn,
3950 28 : request_lsn,
3951 28 : ancestor_lsn: Some(timeline.ancestor_lsn),
3952 28 : backtrace: None,
3953 28 : read_path: std::mem::take(&mut reconstruct_state.read_path),
3954 28 : }));
3955 1255356 : }
3956 1255356 :
3957 1255356 : Ok(())
3958 1255388 : }
3959 :
3960 : /// Collect the reconstruct data for a keyspace from the specified timeline.
3961 : ///
3962 : /// Maintain a fringe [`LayerFringe`] which tracks all the layers that intersect
3963 : /// the current keyspace. The current keyspace of the search at any given timeline
3964 : /// is the original keyspace minus all the keys that have been completed minus
3965 : /// any keys for which we couldn't find an intersecting layer. It's not tracked explicitly,
3966 : /// but if you merge all the keyspaces in the fringe, you get the "current keyspace".
3967 : ///
3968 : /// This is basically a depth-first search visitor implementation where a vertex
3969 : /// is the (layer, lsn range, key space) tuple. The fringe acts as the stack.
3970 : ///
3971 : /// At each iteration pop the top of the fringe (the layer with the highest Lsn)
3972 : /// and get all the required reconstruct data from the layer in one go.
3973 : ///
3974 : /// Returns the completed keyspace and the keyspaces with image coverage. The caller
3975 : /// decides how to deal with these two keyspaces.
3976 1706502 : async fn get_vectored_reconstruct_data_timeline(
3977 1706502 : timeline: &Timeline,
3978 1706502 : keyspace: KeySpace,
3979 1706502 : mut cont_lsn: Lsn,
3980 1706502 : reconstruct_state: &mut ValuesReconstructState,
3981 1706502 : cancel: &CancellationToken,
3982 1706502 : ctx: &RequestContext,
3983 1706502 : ) -> Result<TimelineVisitOutcome, GetVectoredError> {
3984 1706502 : let mut unmapped_keyspace = keyspace.clone();
3985 1706502 : let mut fringe = LayerFringe::new();
3986 1706502 :
3987 1706502 : let mut completed_keyspace = KeySpace::default();
3988 1706502 : let mut image_covered_keyspace = KeySpaceRandomAccum::new();
3989 1706502 :
3990 1706502 : // Prevent GC from progressing while visiting the current timeline.
3991 1706502 : // If we are GC-ing because a new image layer was added while traversing
3992 1706502 : // the timeline, then it will remove layers that are required for fulfilling
3993 1706502 : // the current get request (read-path cannot "look back" and notice the new
3994 1706502 : // image layer).
3995 1706502 : let _gc_cutoff_holder = timeline.get_applied_gc_cutoff_lsn();
3996 :
3997 : // See `compaction::compact_with_gc` for why we need this.
3998 1706502 : let _guard = timeline.gc_compaction_layer_update_lock.read().await;
3999 :
4000 : loop {
4001 3399751 : if cancel.is_cancelled() {
4002 0 : return Err(GetVectoredError::Cancelled);
4003 3399751 : }
4004 3399751 :
4005 3399751 : let (keys_done_last_step, keys_with_image_coverage) =
4006 3399751 : reconstruct_state.consume_done_keys();
4007 3399751 : unmapped_keyspace.remove_overlapping_with(&keys_done_last_step);
4008 3399751 : completed_keyspace.merge(&keys_done_last_step);
4009 3399751 : if let Some(keys_with_image_coverage) = keys_with_image_coverage {
4010 45100 : unmapped_keyspace
4011 45100 : .remove_overlapping_with(&KeySpace::single(keys_with_image_coverage.clone()));
4012 45100 : image_covered_keyspace.add_range(keys_with_image_coverage);
4013 3354651 : }
4014 :
4015 : // Do not descent any further if the last layer we visited
4016 : // completed all keys in the keyspace it inspected. This is not
4017 : // required for correctness, but avoids visiting extra layers
4018 : // which turns out to be a perf bottleneck in some cases.
4019 3399751 : if !unmapped_keyspace.is_empty() {
4020 2148915 : let guard = timeline.layers.read().await;
4021 2148915 : let layers = guard.layer_map()?;
4022 :
4023 2150311 : for range in unmapped_keyspace.ranges.iter() {
4024 2150311 : let results = layers.range_search(range.clone(), cont_lsn);
4025 2150311 :
4026 2150311 : results
4027 2150311 : .found
4028 2150311 : .into_iter()
4029 2150311 : .map(|(SearchResult { layer, lsn_floor }, keyspace_accum)| {
4030 1694185 : (
4031 1694185 : guard.upgrade(layer),
4032 1694185 : keyspace_accum.to_keyspace(),
4033 1694185 : lsn_floor..cont_lsn,
4034 1694185 : )
4035 2150311 : })
4036 2150311 : .for_each(|(layer, keyspace, lsn_range)| {
4037 1694185 : fringe.update(layer, keyspace, lsn_range)
4038 2150311 : });
4039 2150311 : }
4040 :
4041 : // It's safe to drop the layer map lock after planning the next round of reads.
4042 : // The fringe keeps readable handles for the layers which are safe to read even
4043 : // if layers were compacted or flushed.
4044 : //
4045 : // The more interesting consideration is: "Why is the read algorithm still correct
4046 : // if the layer map changes while it is operating?". Doing a vectored read on a
4047 : // timeline boils down to pushing an imaginary lsn boundary downwards for each range
4048 : // covered by the read. The layer map tells us how to move the lsn downwards for a
4049 : // range at *a particular point in time*. It is fine for the answer to be different
4050 : // at two different time points.
4051 2148915 : drop(guard);
4052 1250836 : }
4053 :
4054 3399751 : if let Some((layer_to_read, keyspace_to_read, lsn_range)) = fringe.next_layer() {
4055 1693249 : if let Some(ref mut read_path) = reconstruct_state.read_path {
4056 1693249 : read_path.record_layer_visit(&layer_to_read, &keyspace_to_read, &lsn_range);
4057 1693249 : }
4058 1693249 : let next_cont_lsn = lsn_range.start;
4059 1693249 : layer_to_read
4060 1693249 : .get_values_reconstruct_data(
4061 1693249 : keyspace_to_read.clone(),
4062 1693249 : lsn_range,
4063 1693249 : reconstruct_state,
4064 1693249 : ctx,
4065 1693249 : )
4066 1693249 : .await?;
4067 :
4068 1693249 : unmapped_keyspace = keyspace_to_read;
4069 1693249 : cont_lsn = next_cont_lsn;
4070 1693249 :
4071 1693249 : reconstruct_state.on_layer_visited(&layer_to_read);
4072 : } else {
4073 1706502 : break;
4074 1706502 : }
4075 1706502 : }
4076 1706502 :
4077 1706502 : Ok(TimelineVisitOutcome {
4078 1706502 : completed_keyspace,
4079 1706502 : image_covered_keyspace: image_covered_keyspace.consume_keyspace(),
4080 1706502 : })
4081 1706502 : }
4082 :
4083 451118 : async fn get_ready_ancestor_timeline(
4084 451118 : &self,
4085 451118 : ancestor: &Arc<Timeline>,
4086 451118 : ctx: &RequestContext,
4087 451118 : ) -> Result<Arc<Timeline>, GetReadyAncestorError> {
4088 451118 : // It's possible that the ancestor timeline isn't active yet, or
4089 451118 : // is active but hasn't yet caught up to the branch point. Wait
4090 451118 : // for it.
4091 451118 : //
4092 451118 : // This cannot happen while the pageserver is running normally,
4093 451118 : // because you cannot create a branch from a point that isn't
4094 451118 : // present in the pageserver yet. However, we don't wait for the
4095 451118 : // branch point to be uploaded to cloud storage before creating
4096 451118 : // a branch. I.e., the branch LSN need not be remote consistent
4097 451118 : // for the branching operation to succeed.
4098 451118 : //
4099 451118 : // Hence, if we try to load a tenant in such a state where
4100 451118 : // 1. the existence of the branch was persisted (in IndexPart and/or locally)
4101 451118 : // 2. but the ancestor state is behind branch_lsn because it was not yet persisted
4102 451118 : // then we will need to wait for the ancestor timeline to
4103 451118 : // re-stream WAL up to branch_lsn before we access it.
4104 451118 : //
4105 451118 : // How can a tenant get in such a state?
4106 451118 : // - ungraceful pageserver process exit
4107 451118 : // - detach+attach => this is a bug, https://github.com/neondatabase/neon/issues/4219
4108 451118 : //
4109 451118 : // NB: this could be avoided by requiring
4110 451118 : // branch_lsn >= remote_consistent_lsn
4111 451118 : // during branch creation.
4112 451118 : match ancestor.wait_to_become_active(ctx).await {
4113 451114 : Ok(()) => {}
4114 : Err(TimelineState::Stopping) => {
4115 : // If an ancestor is stopping, it means the tenant is stopping: handle this the same as if this timeline was stopping.
4116 0 : return Err(GetReadyAncestorError::Cancelled);
4117 : }
4118 4 : Err(state) => {
4119 4 : return Err(GetReadyAncestorError::BadState {
4120 4 : timeline_id: ancestor.timeline_id,
4121 4 : state,
4122 4 : });
4123 : }
4124 : }
4125 451114 : ancestor
4126 451114 : .wait_lsn(
4127 451114 : self.ancestor_lsn,
4128 451114 : WaitLsnWaiter::Timeline(self),
4129 451114 : WaitLsnTimeout::Default,
4130 451114 : ctx,
4131 451114 : )
4132 451114 : .await
4133 451114 : .map_err(|e| match e {
4134 0 : e @ WaitLsnError::Timeout(_) => GetReadyAncestorError::AncestorLsnTimeout(e),
4135 0 : WaitLsnError::Shutdown => GetReadyAncestorError::Cancelled,
4136 0 : WaitLsnError::BadState(state) => GetReadyAncestorError::BadState {
4137 0 : timeline_id: ancestor.timeline_id,
4138 0 : state,
4139 0 : },
4140 451114 : })?;
4141 :
4142 451114 : Ok(ancestor.clone())
4143 451118 : }
4144 :
4145 594312 : pub(crate) fn get_shard_identity(&self) -> &ShardIdentity {
4146 594312 : &self.shard_identity
4147 594312 : }
4148 :
4149 : #[inline(always)]
4150 0 : pub(crate) fn shard_timeline_id(&self) -> ShardTimelineId {
4151 0 : ShardTimelineId {
4152 0 : shard_index: ShardIndex {
4153 0 : shard_number: self.shard_identity.number,
4154 0 : shard_count: self.shard_identity.count,
4155 0 : },
4156 0 : timeline_id: self.timeline_id,
4157 0 : }
4158 0 : }
4159 :
4160 : /// Returns a non-frozen open in-memory layer for ingestion.
4161 : ///
4162 : /// Takes a witness of timeline writer state lock being held, because it makes no sense to call
4163 : /// this function without holding the mutex.
4164 2604 : async fn get_layer_for_write(
4165 2604 : &self,
4166 2604 : lsn: Lsn,
4167 2604 : _guard: &tokio::sync::MutexGuard<'_, Option<TimelineWriterState>>,
4168 2604 : ctx: &RequestContext,
4169 2604 : ) -> anyhow::Result<Arc<InMemoryLayer>> {
4170 2604 : let mut guard = self.layers.write().await;
4171 :
4172 2604 : let last_record_lsn = self.get_last_record_lsn();
4173 2604 : ensure!(
4174 2604 : lsn > last_record_lsn,
4175 0 : "cannot modify relation after advancing last_record_lsn (incoming_lsn={}, last_record_lsn={})",
4176 : lsn,
4177 : last_record_lsn,
4178 : );
4179 :
4180 2604 : let layer = guard
4181 2604 : .open_mut()?
4182 2604 : .get_layer_for_write(
4183 2604 : lsn,
4184 2604 : self.conf,
4185 2604 : self.timeline_id,
4186 2604 : self.tenant_shard_id,
4187 2604 : &self.gate,
4188 2604 : &self.cancel,
4189 2604 : ctx,
4190 2604 : )
4191 2604 : .await?;
4192 2604 : Ok(layer)
4193 2604 : }
4194 :
4195 10558196 : pub(crate) fn finish_write(&self, new_lsn: Lsn) {
4196 10558196 : assert!(new_lsn.is_aligned());
4197 :
4198 10558196 : self.metrics.last_record_lsn_gauge.set(new_lsn.0 as i64);
4199 10558196 : self.last_record_lsn.advance(new_lsn);
4200 10558196 : }
4201 :
4202 : /// Freeze any existing open in-memory layer and unconditionally notify the flush loop.
4203 : ///
4204 : /// Unconditional flush loop notification is given because in sharded cases we will want to
4205 : /// leave an Lsn gap. Unsharded tenants do not have Lsn gaps.
4206 2412 : async fn freeze_inmem_layer_at(
4207 2412 : &self,
4208 2412 : at: Lsn,
4209 2412 : write_lock: &mut tokio::sync::MutexGuard<'_, Option<TimelineWriterState>>,
4210 2412 : ) -> Result<u64, FlushLayerError> {
4211 2412 : let frozen = {
4212 2412 : let mut guard = self.layers.write().await;
4213 2412 : guard
4214 2412 : .open_mut()?
4215 2412 : .try_freeze_in_memory_layer(at, &self.last_freeze_at, write_lock, &self.metrics)
4216 2412 : .await
4217 : };
4218 :
4219 2412 : if frozen {
4220 2356 : let now = Instant::now();
4221 2356 : *(self.last_freeze_ts.write().unwrap()) = now;
4222 2356 : }
4223 :
4224 : // Increment the flush cycle counter and wake up the flush task.
4225 : // Remember the new value, so that when we listen for the flush
4226 : // to finish, we know when the flush that we initiated has
4227 : // finished, instead of some other flush that was started earlier.
4228 2412 : let mut my_flush_request = 0;
4229 2412 :
4230 2412 : let flush_loop_state = { *self.flush_loop_state.lock().unwrap() };
4231 2412 : if !matches!(flush_loop_state, FlushLoopState::Running { .. }) {
4232 0 : return Err(FlushLayerError::NotRunning(flush_loop_state));
4233 2412 : }
4234 2412 :
4235 2412 : self.layer_flush_start_tx.send_modify(|(counter, lsn)| {
4236 2412 : my_flush_request = *counter + 1;
4237 2412 : *counter = my_flush_request;
4238 2412 : *lsn = std::cmp::max(at, *lsn);
4239 2412 : });
4240 2412 :
4241 2412 : assert_ne!(my_flush_request, 0);
4242 :
4243 2412 : Ok(my_flush_request)
4244 2412 : }
4245 :
4246 : /// Layer flusher task's main loop.
4247 892 : async fn flush_loop(
4248 892 : self: &Arc<Self>,
4249 892 : mut layer_flush_start_rx: tokio::sync::watch::Receiver<(u64, Lsn)>,
4250 892 : ctx: &RequestContext,
4251 892 : ) {
4252 : // Subscribe to L0 delta layer updates, for compaction backpressure.
4253 892 : let mut watch_l0 = match self.layers.read().await.layer_map() {
4254 892 : Ok(lm) => lm.watch_level0_deltas(),
4255 0 : Err(Shutdown) => return,
4256 : };
4257 :
4258 892 : info!("started flush loop");
4259 : loop {
4260 3262 : tokio::select! {
4261 3262 : _ = self.cancel.cancelled() => {
4262 20 : info!("shutting down layer flush task due to Timeline::cancel");
4263 20 : break;
4264 : },
4265 3262 : _ = layer_flush_start_rx.changed() => {}
4266 2370 : }
4267 2370 : trace!("waking up");
4268 2370 : let (flush_counter, frozen_to_lsn) = *layer_flush_start_rx.borrow();
4269 2370 :
4270 2370 : // The highest LSN to which we flushed in the loop over frozen layers
4271 2370 : let mut flushed_to_lsn = Lsn(0);
4272 :
4273 2370 : let result = loop {
4274 4726 : if self.cancel.is_cancelled() {
4275 0 : info!("dropping out of flush loop for timeline shutdown");
4276 : // Note: we do not bother transmitting into [`layer_flush_done_tx`], because
4277 : // anyone waiting on that will respect self.cancel as well: they will stop
4278 : // waiting at the same time we as drop out of this loop.
4279 0 : return;
4280 4726 : }
4281 4726 :
4282 4726 : // Break to notify potential waiters as soon as we've flushed the requested LSN. If
4283 4726 : // more requests have arrived in the meanwhile, we'll resume flushing afterwards.
4284 4726 : if flushed_to_lsn >= frozen_to_lsn {
4285 2314 : break Ok(());
4286 2412 : }
4287 :
4288 : // Fetch the next layer to flush, if any.
4289 2412 : let (layer, l0_count, frozen_count, frozen_size) = {
4290 2412 : let layers = self.layers.read().await;
4291 2412 : let Ok(lm) = layers.layer_map() else {
4292 0 : info!("dropping out of flush loop for timeline shutdown");
4293 0 : return;
4294 : };
4295 2412 : let l0_count = lm.level0_deltas().len();
4296 2412 : let frozen_count = lm.frozen_layers.len();
4297 2412 : let frozen_size: u64 = lm
4298 2412 : .frozen_layers
4299 2412 : .iter()
4300 2412 : .map(|l| l.estimated_in_mem_size())
4301 2412 : .sum();
4302 2412 : let layer = lm.frozen_layers.front().cloned();
4303 2412 : (layer, l0_count, frozen_count, frozen_size)
4304 2412 : // drop 'layers' lock
4305 2412 : };
4306 2412 : let Some(layer) = layer else {
4307 56 : break Ok(());
4308 : };
4309 :
4310 : // Stall flushes to backpressure if compaction can't keep up. This is propagated up
4311 : // to WAL ingestion by having ephemeral layer rolls wait for flushes.
4312 2356 : if let Some(stall_threshold) = self.get_l0_flush_stall_threshold() {
4313 0 : if l0_count >= stall_threshold {
4314 0 : warn!(
4315 0 : "stalling layer flushes for compaction backpressure at {l0_count} \
4316 0 : L0 layers ({frozen_count} frozen layers with {frozen_size} bytes)"
4317 : );
4318 0 : let stall_timer = self
4319 0 : .metrics
4320 0 : .flush_delay_histo
4321 0 : .start_timer()
4322 0 : .record_on_drop();
4323 0 : tokio::select! {
4324 0 : result = watch_l0.wait_for(|l0| *l0 < stall_threshold) => {
4325 0 : if let Ok(l0) = result.as_deref() {
4326 0 : let delay = stall_timer.elapsed().as_secs_f64();
4327 0 : info!("resuming layer flushes at {l0} L0 layers after {delay:.3}s");
4328 0 : }
4329 : },
4330 0 : _ = self.cancel.cancelled() => {},
4331 : }
4332 0 : continue; // check again
4333 0 : }
4334 2356 : }
4335 :
4336 : // Flush the layer.
4337 2356 : let flush_timer = self.metrics.flush_time_histo.start_timer();
4338 2356 : match self.flush_frozen_layer(layer, ctx).await {
4339 2356 : Ok(layer_lsn) => flushed_to_lsn = max(flushed_to_lsn, layer_lsn),
4340 : Err(FlushLayerError::Cancelled) => {
4341 0 : info!("dropping out of flush loop for timeline shutdown");
4342 0 : return;
4343 : }
4344 0 : err @ Err(
4345 0 : FlushLayerError::NotRunning(_)
4346 0 : | FlushLayerError::Other(_)
4347 0 : | FlushLayerError::CreateImageLayersError(_),
4348 0 : ) => {
4349 0 : error!("could not flush frozen layer: {err:?}");
4350 0 : break err.map(|_| ());
4351 : }
4352 : }
4353 2356 : let flush_duration = flush_timer.stop_and_record();
4354 2356 :
4355 2356 : // Notify the tenant compaction loop if L0 compaction is needed.
4356 2356 : let l0_count = *watch_l0.borrow();
4357 2356 : if l0_count >= self.get_compaction_threshold() {
4358 956 : self.l0_compaction_trigger.notify_one();
4359 1400 : }
4360 :
4361 : // Delay the next flush to backpressure if compaction can't keep up. We delay by the
4362 : // flush duration such that the flush takes 2x as long. This is propagated up to WAL
4363 : // ingestion by having ephemeral layer rolls wait for flushes.
4364 2356 : if let Some(delay_threshold) = self.get_l0_flush_delay_threshold() {
4365 0 : if l0_count >= delay_threshold {
4366 0 : let delay = flush_duration.as_secs_f64();
4367 0 : info!(
4368 0 : "delaying layer flush by {delay:.3}s for compaction backpressure at \
4369 0 : {l0_count} L0 layers ({frozen_count} frozen layers with {frozen_size} bytes)"
4370 : );
4371 0 : let _delay_timer = self
4372 0 : .metrics
4373 0 : .flush_delay_histo
4374 0 : .start_timer()
4375 0 : .record_on_drop();
4376 0 : tokio::select! {
4377 0 : _ = tokio::time::sleep(flush_duration) => {},
4378 0 : _ = watch_l0.wait_for(|l0| *l0 < delay_threshold) => {},
4379 0 : _ = self.cancel.cancelled() => {},
4380 : }
4381 0 : }
4382 2356 : }
4383 : };
4384 :
4385 : // Unsharded tenants should never advance their LSN beyond the end of the
4386 : // highest layer they write: such gaps between layer data and the frozen LSN
4387 : // are only legal on sharded tenants.
4388 2370 : debug_assert!(
4389 2370 : self.shard_identity.count.count() > 1
4390 2370 : || flushed_to_lsn >= frozen_to_lsn
4391 56 : || !flushed_to_lsn.is_valid()
4392 : );
4393 :
4394 2370 : if flushed_to_lsn < frozen_to_lsn && self.shard_identity.count.count() > 1 {
4395 : // If our layer flushes didn't carry disk_consistent_lsn up to the `to_lsn` advertised
4396 : // to us via layer_flush_start_rx, then advance it here.
4397 : //
4398 : // This path is only taken for tenants with multiple shards: single sharded tenants should
4399 : // never encounter a gap in the wal.
4400 0 : let old_disk_consistent_lsn = self.disk_consistent_lsn.load();
4401 0 : tracing::debug!(
4402 0 : "Advancing disk_consistent_lsn across layer gap {old_disk_consistent_lsn}->{frozen_to_lsn}"
4403 : );
4404 0 : if self.set_disk_consistent_lsn(frozen_to_lsn) {
4405 0 : if let Err(e) = self.schedule_uploads(frozen_to_lsn, vec![]) {
4406 0 : tracing::warn!(
4407 0 : "Failed to schedule metadata upload after updating disk_consistent_lsn: {e}"
4408 : );
4409 0 : }
4410 0 : }
4411 2370 : }
4412 :
4413 : // Notify any listeners that we're done
4414 2370 : let _ = self
4415 2370 : .layer_flush_done_tx
4416 2370 : .send_replace((flush_counter, result));
4417 : }
4418 20 : }
4419 :
4420 : /// Waits any flush request created by [`Self::freeze_inmem_layer_at`] to complete.
4421 2252 : async fn wait_flush_completion(&self, request: u64) -> Result<(), FlushLayerError> {
4422 2252 : let mut rx = self.layer_flush_done_tx.subscribe();
4423 : loop {
4424 : {
4425 4572 : let (last_result_counter, last_result) = &*rx.borrow();
4426 4572 : if *last_result_counter >= request {
4427 2252 : if let Err(err) = last_result {
4428 : // We already logged the original error in
4429 : // flush_loop. We cannot propagate it to the caller
4430 : // here, because it might not be Cloneable
4431 0 : return Err(err.clone());
4432 : } else {
4433 2252 : return Ok(());
4434 : }
4435 2320 : }
4436 2320 : }
4437 2320 : trace!("waiting for flush to complete");
4438 2320 : tokio::select! {
4439 2320 : rx_e = rx.changed() => {
4440 2320 : rx_e.map_err(|_| FlushLayerError::NotRunning(*self.flush_loop_state.lock().unwrap()))?;
4441 : },
4442 : // Cancellation safety: we are not leaving an I/O in-flight for the flush, we're just ignoring
4443 : // the notification from [`flush_loop`] that it completed.
4444 2320 : _ = self.cancel.cancelled() => {
4445 0 : tracing::info!("Cancelled layer flush due on timeline shutdown");
4446 0 : return Ok(())
4447 : }
4448 : };
4449 2320 : trace!("done")
4450 : }
4451 2252 : }
4452 :
4453 : /// Flush one frozen in-memory layer to disk, as a new delta layer.
4454 : ///
4455 : /// Return value is the last lsn (inclusive) of the layer that was frozen.
4456 : #[instrument(skip_all, fields(layer=%frozen_layer))]
4457 : async fn flush_frozen_layer(
4458 : self: &Arc<Self>,
4459 : frozen_layer: Arc<InMemoryLayer>,
4460 : ctx: &RequestContext,
4461 : ) -> Result<Lsn, FlushLayerError> {
4462 : debug_assert_current_span_has_tenant_and_timeline_id();
4463 :
4464 : // As a special case, when we have just imported an image into the repository,
4465 : // instead of writing out a L0 delta layer, we directly write out image layer
4466 : // files instead. This is possible as long as *all* the data imported into the
4467 : // repository have the same LSN.
4468 : let lsn_range = frozen_layer.get_lsn_range();
4469 :
4470 : // Whether to directly create image layers for this flush, or flush them as delta layers
4471 : let create_image_layer =
4472 : lsn_range.start == self.initdb_lsn && lsn_range.end == Lsn(self.initdb_lsn.0 + 1);
4473 :
4474 : #[cfg(test)]
4475 : {
4476 : match &mut *self.flush_loop_state.lock().unwrap() {
4477 : FlushLoopState::NotStarted | FlushLoopState::Exited => {
4478 : panic!("flush loop not running")
4479 : }
4480 : FlushLoopState::Running {
4481 : expect_initdb_optimization,
4482 : initdb_optimization_count,
4483 : ..
4484 : } => {
4485 : if create_image_layer {
4486 : *initdb_optimization_count += 1;
4487 : } else {
4488 : assert!(!*expect_initdb_optimization, "expected initdb optimization");
4489 : }
4490 : }
4491 : }
4492 : }
4493 :
4494 : let (layers_to_upload, delta_layer_to_add) = if create_image_layer {
4495 : // Note: The 'ctx' in use here has DownloadBehavior::Error. We should not
4496 : // require downloading anything during initial import.
4497 : let ((rel_partition, metadata_partition), _lsn) = self
4498 : .repartition(
4499 : self.initdb_lsn,
4500 : self.get_compaction_target_size(),
4501 : EnumSet::empty(),
4502 : ctx,
4503 : )
4504 : .await
4505 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e.into()))?;
4506 :
4507 : if self.cancel.is_cancelled() {
4508 : return Err(FlushLayerError::Cancelled);
4509 : }
4510 :
4511 : // Ensure that we have a single call to `create_image_layers` with a combined dense keyspace.
4512 : // So that the key ranges don't overlap.
4513 : let mut partitions = KeyPartitioning::default();
4514 : partitions.parts.extend(rel_partition.parts);
4515 : if !metadata_partition.parts.is_empty() {
4516 : assert_eq!(
4517 : metadata_partition.parts.len(),
4518 : 1,
4519 : "currently sparse keyspace should only contain a single metadata keyspace"
4520 : );
4521 : // Safety: create_image_layers treat sparse keyspaces differently that it does not scan
4522 : // every single key within the keyspace, and therefore, it's safe to force converting it
4523 : // into a dense keyspace before calling this function.
4524 : partitions
4525 : .parts
4526 : .extend(metadata_partition.into_dense().parts);
4527 : }
4528 :
4529 : let mut layers_to_upload = Vec::new();
4530 : let (generated_image_layers, is_complete) = self
4531 : .create_image_layers(
4532 : &partitions,
4533 : self.initdb_lsn,
4534 : ImageLayerCreationMode::Initial,
4535 : ctx,
4536 : LastImageLayerCreationStatus::Initial,
4537 : false, // don't yield for L0, we're flushing L0
4538 : )
4539 : .await?;
4540 : debug_assert!(
4541 : matches!(is_complete, LastImageLayerCreationStatus::Complete),
4542 : "init image generation mode must fully cover the keyspace"
4543 : );
4544 : layers_to_upload.extend(generated_image_layers);
4545 :
4546 : (layers_to_upload, None)
4547 : } else {
4548 : // Normal case, write out a L0 delta layer file.
4549 : // `create_delta_layer` will not modify the layer map.
4550 : // We will remove frozen layer and add delta layer in one atomic operation later.
4551 : let Some(layer) = self
4552 : .create_delta_layer(&frozen_layer, None, ctx)
4553 : .await
4554 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e))?
4555 : else {
4556 : panic!("delta layer cannot be empty if no filter is applied");
4557 : };
4558 : (
4559 : // FIXME: even though we have a single image and single delta layer assumption
4560 : // we push them to vec
4561 : vec![layer.clone()],
4562 : Some(layer),
4563 : )
4564 : };
4565 :
4566 : pausable_failpoint!("flush-layer-cancel-after-writing-layer-out-pausable");
4567 :
4568 : if self.cancel.is_cancelled() {
4569 : return Err(FlushLayerError::Cancelled);
4570 : }
4571 :
4572 : let disk_consistent_lsn = Lsn(lsn_range.end.0 - 1);
4573 :
4574 : // The new on-disk layers are now in the layer map. We can remove the
4575 : // in-memory layer from the map now. The flushed layer is stored in
4576 : // the mapping in `create_delta_layer`.
4577 : {
4578 : let mut guard = self.layers.write().await;
4579 :
4580 : guard.open_mut()?.finish_flush_l0_layer(
4581 : delta_layer_to_add.as_ref(),
4582 : &frozen_layer,
4583 : &self.metrics,
4584 : );
4585 :
4586 : if self.set_disk_consistent_lsn(disk_consistent_lsn) {
4587 : // Schedule remote uploads that will reflect our new disk_consistent_lsn
4588 : self.schedule_uploads(disk_consistent_lsn, layers_to_upload)
4589 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e))?;
4590 : }
4591 : // release lock on 'layers'
4592 : };
4593 :
4594 : // Backpressure mechanism: wait with continuation of the flush loop until we have uploaded all layer files.
4595 : // This makes us refuse ingest until the new layers have been persisted to the remote
4596 : // TODO: remove this, and rely on l0_flush_{delay,stall}_threshold instead.
4597 : if self.get_l0_flush_wait_upload() {
4598 : let start = Instant::now();
4599 : self.remote_client
4600 : .wait_completion()
4601 : .await
4602 0 : .map_err(|e| match e {
4603 : WaitCompletionError::UploadQueueShutDownOrStopped
4604 : | WaitCompletionError::NotInitialized(
4605 : NotInitialized::ShuttingDown | NotInitialized::Stopped,
4606 0 : ) => FlushLayerError::Cancelled,
4607 : WaitCompletionError::NotInitialized(NotInitialized::Uninitialized) => {
4608 0 : FlushLayerError::Other(anyhow!(e).into())
4609 : }
4610 0 : })?;
4611 : let duration = start.elapsed().as_secs_f64();
4612 : self.metrics.flush_wait_upload_time_gauge_add(duration);
4613 : }
4614 :
4615 : // FIXME: between create_delta_layer and the scheduling of the upload in `update_metadata_file`,
4616 : // a compaction can delete the file and then it won't be available for uploads any more.
4617 : // We still schedule the upload, resulting in an error, but ideally we'd somehow avoid this
4618 : // race situation.
4619 : // See https://github.com/neondatabase/neon/issues/4526
4620 : pausable_failpoint!("flush-frozen-pausable");
4621 :
4622 : // This failpoint is used by another test case `test_pageserver_recovery`.
4623 : fail_point!("flush-frozen-exit");
4624 :
4625 : Ok(Lsn(lsn_range.end.0 - 1))
4626 : }
4627 :
4628 : /// Return true if the value changed
4629 : ///
4630 : /// This function must only be used from the layer flush task.
4631 2356 : fn set_disk_consistent_lsn(&self, new_value: Lsn) -> bool {
4632 2356 : let old_value = self.disk_consistent_lsn.fetch_max(new_value);
4633 2356 : assert!(
4634 2356 : new_value >= old_value,
4635 0 : "disk_consistent_lsn must be growing monotonously at runtime; current {old_value}, offered {new_value}"
4636 : );
4637 :
4638 2356 : self.metrics
4639 2356 : .disk_consistent_lsn_gauge
4640 2356 : .set(new_value.0 as i64);
4641 2356 : new_value != old_value
4642 2356 : }
4643 :
4644 : /// Update metadata file
4645 2456 : fn schedule_uploads(
4646 2456 : &self,
4647 2456 : disk_consistent_lsn: Lsn,
4648 2456 : layers_to_upload: impl IntoIterator<Item = ResidentLayer>,
4649 2456 : ) -> anyhow::Result<()> {
4650 2456 : // We can only save a valid 'prev_record_lsn' value on disk if we
4651 2456 : // flushed *all* in-memory changes to disk. We only track
4652 2456 : // 'prev_record_lsn' in memory for the latest processed record, so we
4653 2456 : // don't remember what the correct value that corresponds to some old
4654 2456 : // LSN is. But if we flush everything, then the value corresponding
4655 2456 : // current 'last_record_lsn' is correct and we can store it on disk.
4656 2456 : let RecordLsn {
4657 2456 : last: last_record_lsn,
4658 2456 : prev: prev_record_lsn,
4659 2456 : } = self.last_record_lsn.load();
4660 2456 : let ondisk_prev_record_lsn = if disk_consistent_lsn == last_record_lsn {
4661 2203 : Some(prev_record_lsn)
4662 : } else {
4663 253 : None
4664 : };
4665 :
4666 2456 : let update = crate::tenant::metadata::MetadataUpdate::new(
4667 2456 : disk_consistent_lsn,
4668 2456 : ondisk_prev_record_lsn,
4669 2456 : *self.applied_gc_cutoff_lsn.read(),
4670 2456 : );
4671 2456 :
4672 2456 : fail_point!("checkpoint-before-saving-metadata", |x| bail!(
4673 0 : "{}",
4674 0 : x.unwrap()
4675 2456 : ));
4676 :
4677 4836 : for layer in layers_to_upload {
4678 2380 : self.remote_client.schedule_layer_file_upload(layer)?;
4679 : }
4680 2456 : self.remote_client
4681 2456 : .schedule_index_upload_for_metadata_update(&update)?;
4682 :
4683 2456 : Ok(())
4684 2456 : }
4685 :
4686 0 : pub(crate) async fn preserve_initdb_archive(&self) -> anyhow::Result<()> {
4687 0 : self.remote_client
4688 0 : .preserve_initdb_archive(
4689 0 : &self.tenant_shard_id.tenant_id,
4690 0 : &self.timeline_id,
4691 0 : &self.cancel,
4692 0 : )
4693 0 : .await
4694 0 : }
4695 :
4696 : // Write out the given frozen in-memory layer as a new L0 delta file. This L0 file will not be tracked
4697 : // in layer map immediately. The caller is responsible to put it into the layer map.
4698 1936 : async fn create_delta_layer(
4699 1936 : self: &Arc<Self>,
4700 1936 : frozen_layer: &Arc<InMemoryLayer>,
4701 1936 : key_range: Option<Range<Key>>,
4702 1936 : ctx: &RequestContext,
4703 1936 : ) -> anyhow::Result<Option<ResidentLayer>> {
4704 1936 : let self_clone = Arc::clone(self);
4705 1936 : let frozen_layer = Arc::clone(frozen_layer);
4706 1936 : let ctx = ctx.attached_child();
4707 1936 : let work = async move {
4708 1936 : let Some((desc, path)) = frozen_layer
4709 1936 : .write_to_disk(&ctx, key_range, self_clone.l0_flush_global_state.inner())
4710 1936 : .await?
4711 : else {
4712 0 : return Ok(None);
4713 : };
4714 1936 : let new_delta = Layer::finish_creating(self_clone.conf, &self_clone, desc, &path)?;
4715 :
4716 : // The write_to_disk() above calls writer.finish() which already did the fsync of the inodes.
4717 : // We just need to fsync the directory in which these inodes are linked,
4718 : // which we know to be the timeline directory.
4719 : //
4720 : // We use fatal_err() below because the after write_to_disk returns with success,
4721 : // the in-memory state of the filesystem already has the layer file in its final place,
4722 : // and subsequent pageserver code could think it's durable while it really isn't.
4723 1936 : let timeline_dir = VirtualFile::open(
4724 1936 : &self_clone
4725 1936 : .conf
4726 1936 : .timeline_path(&self_clone.tenant_shard_id, &self_clone.timeline_id),
4727 1936 : &ctx,
4728 1936 : )
4729 1936 : .await
4730 1936 : .fatal_err("VirtualFile::open for timeline dir fsync");
4731 1936 : timeline_dir
4732 1936 : .sync_all()
4733 1936 : .await
4734 1936 : .fatal_err("VirtualFile::sync_all timeline dir");
4735 1936 : anyhow::Ok(Some(new_delta))
4736 1936 : };
4737 : // Before tokio-epoll-uring, we ran write_to_disk & the sync_all inside spawn_blocking.
4738 : // Preserve that behavior to maintain the same behavior for `virtual_file_io_engine=std-fs`.
4739 : use crate::virtual_file::io_engine::IoEngine;
4740 1936 : match crate::virtual_file::io_engine::get() {
4741 0 : IoEngine::NotSet => panic!("io engine not set"),
4742 : IoEngine::StdFs => {
4743 968 : let span = tracing::info_span!("blocking");
4744 968 : tokio::task::spawn_blocking({
4745 968 : move || Handle::current().block_on(work.instrument(span))
4746 968 : })
4747 968 : .await
4748 968 : .context("spawn_blocking")
4749 968 : .and_then(|x| x)
4750 : }
4751 : #[cfg(target_os = "linux")]
4752 968 : IoEngine::TokioEpollUring => work.await,
4753 : }
4754 1936 : }
4755 :
4756 1145 : async fn repartition(
4757 1145 : &self,
4758 1145 : lsn: Lsn,
4759 1145 : partition_size: u64,
4760 1145 : flags: EnumSet<CompactFlags>,
4761 1145 : ctx: &RequestContext,
4762 1145 : ) -> Result<((KeyPartitioning, SparseKeyPartitioning), Lsn), CompactionError> {
4763 1145 : let Ok(mut guard) = self.partitioning.try_write_guard() else {
4764 : // NB: there are two callers, one is the compaction task, of which there is only one per struct Tenant and hence Timeline.
4765 : // The other is the initdb optimization in flush_frozen_layer, used by `boostrap_timeline`, which runs before `.activate()`
4766 : // and hence before the compaction task starts.
4767 0 : return Err(CompactionError::Other(anyhow!(
4768 0 : "repartition() called concurrently"
4769 0 : )));
4770 : };
4771 1145 : let ((dense_partition, sparse_partition), partition_lsn) = &*guard.read();
4772 1145 : if lsn < *partition_lsn {
4773 0 : return Err(CompactionError::Other(anyhow!(
4774 0 : "repartition() called with LSN going backwards, this should not happen"
4775 0 : )));
4776 1145 : }
4777 1145 :
4778 1145 : let distance = lsn.0 - partition_lsn.0;
4779 1145 : if *partition_lsn != Lsn(0)
4780 521 : && distance <= self.repartition_threshold
4781 521 : && !flags.contains(CompactFlags::ForceRepartition)
4782 : {
4783 493 : debug!(
4784 : distance,
4785 : threshold = self.repartition_threshold,
4786 0 : "no repartitioning needed"
4787 : );
4788 493 : return Ok((
4789 493 : (dense_partition.clone(), sparse_partition.clone()),
4790 493 : *partition_lsn,
4791 493 : ));
4792 652 : }
4793 :
4794 652 : let (dense_ks, sparse_ks) = self.collect_keyspace(lsn, ctx).await?;
4795 652 : let dense_partitioning = dense_ks.partition(&self.shard_identity, partition_size);
4796 652 : let sparse_partitioning = SparseKeyPartitioning {
4797 652 : parts: vec![sparse_ks],
4798 652 : }; // no partitioning for metadata keys for now
4799 652 : let result = ((dense_partitioning, sparse_partitioning), lsn);
4800 652 : guard.write(result.clone());
4801 652 : Ok(result)
4802 1145 : }
4803 :
4804 : // Is it time to create a new image layer for the given partition? True if we want to generate.
4805 28 : async fn time_for_new_image_layer(&self, partition: &KeySpace, lsn: Lsn) -> bool {
4806 28 : let threshold = self.get_image_creation_threshold();
4807 :
4808 28 : let guard = self.layers.read().await;
4809 28 : let Ok(layers) = guard.layer_map() else {
4810 0 : return false;
4811 : };
4812 :
4813 28 : let mut max_deltas = 0;
4814 56 : for part_range in &partition.ranges {
4815 28 : let image_coverage = layers.image_coverage(part_range, lsn);
4816 56 : for (img_range, last_img) in image_coverage {
4817 28 : let img_lsn = if let Some(last_img) = last_img {
4818 0 : last_img.get_lsn_range().end
4819 : } else {
4820 28 : Lsn(0)
4821 : };
4822 : // Let's consider an example:
4823 : //
4824 : // delta layer with LSN range 71-81
4825 : // delta layer with LSN range 81-91
4826 : // delta layer with LSN range 91-101
4827 : // image layer at LSN 100
4828 : //
4829 : // If 'lsn' is still 100, i.e. no new WAL has been processed since the last image layer,
4830 : // there's no need to create a new one. We check this case explicitly, to avoid passing
4831 : // a bogus range to count_deltas below, with start > end. It's even possible that there
4832 : // are some delta layers *later* than current 'lsn', if more WAL was processed and flushed
4833 : // after we read last_record_lsn, which is passed here in the 'lsn' argument.
4834 28 : if img_lsn < lsn {
4835 28 : let num_deltas =
4836 28 : layers.count_deltas(&img_range, &(img_lsn..lsn), Some(threshold));
4837 28 :
4838 28 : max_deltas = max_deltas.max(num_deltas);
4839 28 : if num_deltas >= threshold {
4840 0 : debug!(
4841 0 : "key range {}-{}, has {} deltas on this timeline in LSN range {}..{}",
4842 : img_range.start, img_range.end, num_deltas, img_lsn, lsn
4843 : );
4844 0 : return true;
4845 28 : }
4846 0 : }
4847 : }
4848 : }
4849 :
4850 28 : debug!(
4851 : max_deltas,
4852 0 : "none of the partitioned ranges had >= {threshold} deltas"
4853 : );
4854 28 : false
4855 28 : }
4856 :
4857 : /// Create image layers for Postgres data. Assumes the caller passes a partition that is not too large,
4858 : /// so that at most one image layer will be produced from this function.
4859 : #[allow(clippy::too_many_arguments)]
4860 472 : async fn create_image_layer_for_rel_blocks(
4861 472 : self: &Arc<Self>,
4862 472 : partition: &KeySpace,
4863 472 : mut image_layer_writer: ImageLayerWriter,
4864 472 : lsn: Lsn,
4865 472 : ctx: &RequestContext,
4866 472 : img_range: Range<Key>,
4867 472 : io_concurrency: IoConcurrency,
4868 472 : ) -> Result<ImageLayerCreationOutcome, CreateImageLayersError> {
4869 472 : let mut wrote_keys = false;
4870 472 :
4871 472 : let mut key_request_accum = KeySpaceAccum::new();
4872 3128 : for range in &partition.ranges {
4873 2656 : let mut key = range.start;
4874 5756 : while key < range.end {
4875 : // Decide whether to retain this key: usually we do, but sharded tenants may
4876 : // need to drop keys that don't belong to them. If we retain the key, add it
4877 : // to `key_request_accum` for later issuing a vectored get
4878 3100 : if self.shard_identity.is_key_disposable(&key) {
4879 0 : debug!(
4880 0 : "Dropping key {} during compaction (it belongs on shard {:?})",
4881 0 : key,
4882 0 : self.shard_identity.get_shard_number(&key)
4883 : );
4884 3100 : } else {
4885 3100 : key_request_accum.add_key(key);
4886 3100 : }
4887 :
4888 3100 : let last_key_in_range = key.next() == range.end;
4889 3100 : key = key.next();
4890 3100 :
4891 3100 : // Maybe flush `key_rest_accum`
4892 3100 : if key_request_accum.raw_size() >= Timeline::MAX_GET_VECTORED_KEYS
4893 3100 : || (last_key_in_range && key_request_accum.raw_size() > 0)
4894 : {
4895 2656 : let results = self
4896 2656 : .get_vectored(
4897 2656 : key_request_accum.consume_keyspace(),
4898 2656 : lsn,
4899 2656 : io_concurrency.clone(),
4900 2656 : ctx,
4901 2656 : )
4902 2656 : .await?;
4903 :
4904 2656 : if self.cancel.is_cancelled() {
4905 0 : return Err(CreateImageLayersError::Cancelled);
4906 2656 : }
4907 :
4908 5756 : for (img_key, img) in results {
4909 3100 : let img = match img {
4910 3100 : Ok(img) => img,
4911 0 : Err(err) => {
4912 0 : // If we fail to reconstruct a VM or FSM page, we can zero the
4913 0 : // page without losing any actual user data. That seems better
4914 0 : // than failing repeatedly and getting stuck.
4915 0 : //
4916 0 : // We had a bug at one point, where we truncated the FSM and VM
4917 0 : // in the pageserver, but the Postgres didn't know about that
4918 0 : // and continued to generate incremental WAL records for pages
4919 0 : // that didn't exist in the pageserver. Trying to replay those
4920 0 : // WAL records failed to find the previous image of the page.
4921 0 : // This special case allows us to recover from that situation.
4922 0 : // See https://github.com/neondatabase/neon/issues/2601.
4923 0 : //
4924 0 : // Unfortunately we cannot do this for the main fork, or for
4925 0 : // any metadata keys, keys, as that would lead to actual data
4926 0 : // loss.
4927 0 : if img_key.is_rel_fsm_block_key() || img_key.is_rel_vm_block_key() {
4928 0 : warn!(
4929 0 : "could not reconstruct FSM or VM key {img_key}, filling with zeros: {err:?}"
4930 : );
4931 0 : ZERO_PAGE.clone()
4932 : } else {
4933 0 : return Err(CreateImageLayersError::from(err));
4934 : }
4935 : }
4936 : };
4937 :
4938 : // Write all the keys we just read into our new image layer.
4939 3100 : image_layer_writer.put_image(img_key, img, ctx).await?;
4940 3100 : wrote_keys = true;
4941 : }
4942 444 : }
4943 : }
4944 : }
4945 :
4946 472 : if wrote_keys {
4947 : // Normal path: we have written some data into the new image layer for this
4948 : // partition, so flush it to disk.
4949 472 : info!(
4950 0 : "produced image layer for rel {}",
4951 0 : ImageLayerName {
4952 0 : key_range: img_range.clone(),
4953 0 : lsn
4954 0 : },
4955 : );
4956 472 : Ok(ImageLayerCreationOutcome::Generated {
4957 472 : unfinished_image_layer: image_layer_writer,
4958 472 : })
4959 : } else {
4960 0 : tracing::debug!("no data in range {}-{}", img_range.start, img_range.end);
4961 0 : Ok(ImageLayerCreationOutcome::Empty)
4962 : }
4963 472 : }
4964 :
4965 : /// Create an image layer for metadata keys. This function produces one image layer for all metadata
4966 : /// keys for now. Because metadata keys cannot exceed basebackup size limit, the image layer for it
4967 : /// would not be too large to fit in a single image layer.
4968 : ///
4969 : /// Creating image layers for metadata keys are different from relational keys. Firstly, instead of
4970 : /// iterating each key and get an image for each of them, we do a `vectored_get` scan over the sparse
4971 : /// keyspace to get all images in one run. Secondly, we use a different image layer generation metrics
4972 : /// for metadata keys than relational keys, which is the number of delta files visited during the scan.
4973 : #[allow(clippy::too_many_arguments)]
4974 452 : async fn create_image_layer_for_metadata_keys(
4975 452 : self: &Arc<Self>,
4976 452 : partition: &KeySpace,
4977 452 : mut image_layer_writer: ImageLayerWriter,
4978 452 : lsn: Lsn,
4979 452 : ctx: &RequestContext,
4980 452 : img_range: Range<Key>,
4981 452 : mode: ImageLayerCreationMode,
4982 452 : io_concurrency: IoConcurrency,
4983 452 : ) -> Result<ImageLayerCreationOutcome, CreateImageLayersError> {
4984 452 : // Metadata keys image layer creation.
4985 452 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
4986 452 : let begin = Instant::now();
4987 : // Directly use `get_vectored_impl` to skip the max_vectored_read_key limit check. Note that the keyspace should
4988 : // not contain too many keys, otherwise this takes a lot of memory.
4989 452 : let data = self
4990 452 : .get_vectored_impl(partition.clone(), lsn, &mut reconstruct_state, ctx)
4991 452 : .await?;
4992 452 : let (data, total_kb_retrieved, total_keys_retrieved) = {
4993 452 : let mut new_data = BTreeMap::new();
4994 452 : let mut total_kb_retrieved = 0;
4995 452 : let mut total_keys_retrieved = 0;
4996 20476 : for (k, v) in data {
4997 20024 : let v = v?;
4998 20024 : total_kb_retrieved += KEY_SIZE + v.len();
4999 20024 : total_keys_retrieved += 1;
5000 20024 : new_data.insert(k, v);
5001 : }
5002 452 : (new_data, total_kb_retrieved / 1024, total_keys_retrieved)
5003 452 : };
5004 452 : let delta_files_accessed = reconstruct_state.get_delta_layers_visited();
5005 452 : let elapsed = begin.elapsed();
5006 452 :
5007 452 : let trigger_generation = delta_files_accessed as usize >= MAX_AUX_FILE_V2_DELTAS;
5008 452 : info!(
5009 0 : "metadata key compaction: trigger_generation={trigger_generation}, delta_files_accessed={delta_files_accessed}, total_kb_retrieved={total_kb_retrieved}, total_keys_retrieved={total_keys_retrieved}, read_time={}s",
5010 0 : elapsed.as_secs_f64()
5011 : );
5012 :
5013 452 : if !trigger_generation && mode == ImageLayerCreationMode::Try {
5014 4 : return Ok(ImageLayerCreationOutcome::Skip);
5015 448 : }
5016 448 : if self.cancel.is_cancelled() {
5017 0 : return Err(CreateImageLayersError::Cancelled);
5018 448 : }
5019 448 : let mut wrote_any_image = false;
5020 20472 : for (k, v) in data {
5021 20024 : if v.is_empty() {
5022 : // the key has been deleted, it does not need an image
5023 : // in metadata keyspace, an empty image == tombstone
5024 16 : continue;
5025 20008 : }
5026 20008 : wrote_any_image = true;
5027 20008 :
5028 20008 : // No need to handle sharding b/c metadata keys are always on the 0-th shard.
5029 20008 :
5030 20008 : // TODO: split image layers to avoid too large layer files. Too large image files are not handled
5031 20008 : // on the normal data path either.
5032 20008 : image_layer_writer.put_image(k, v, ctx).await?;
5033 : }
5034 :
5035 448 : if wrote_any_image {
5036 : // Normal path: we have written some data into the new image layer for this
5037 : // partition, so flush it to disk.
5038 24 : info!(
5039 0 : "created image layer for metadata {}",
5040 0 : ImageLayerName {
5041 0 : key_range: img_range.clone(),
5042 0 : lsn
5043 0 : }
5044 : );
5045 24 : Ok(ImageLayerCreationOutcome::Generated {
5046 24 : unfinished_image_layer: image_layer_writer,
5047 24 : })
5048 : } else {
5049 424 : tracing::debug!("no data in range {}-{}", img_range.start, img_range.end);
5050 424 : Ok(ImageLayerCreationOutcome::Empty)
5051 : }
5052 452 : }
5053 :
5054 : /// Predicate function which indicates whether we should check if new image layers
5055 : /// are required. Since checking if new image layers are required is expensive in
5056 : /// terms of CPU, we only do it in the following cases:
5057 : /// 1. If the timeline has ingested sufficient WAL to justify the cost
5058 : /// 2. If enough time has passed since the last check:
5059 : /// 1. For large tenants, we wish to perform the check more often since they
5060 : /// suffer from the lack of image layers
5061 : /// 2. For small tenants (that can mostly fit in RAM), we use a much longer interval
5062 1145 : fn should_check_if_image_layers_required(self: &Arc<Timeline>, lsn: Lsn) -> bool {
5063 : const LARGE_TENANT_THRESHOLD: u64 = 2 * 1024 * 1024 * 1024;
5064 :
5065 1145 : let last_checks_at = self.last_image_layer_creation_check_at.load();
5066 1145 : let distance = lsn
5067 1145 : .checked_sub(last_checks_at)
5068 1145 : .expect("Attempt to compact with LSN going backwards");
5069 1145 : let min_distance =
5070 1145 : self.get_image_layer_creation_check_threshold() as u64 * self.get_checkpoint_distance();
5071 1145 :
5072 1145 : let distance_based_decision = distance.0 >= min_distance;
5073 1145 :
5074 1145 : let mut time_based_decision = false;
5075 1145 : let mut last_check_instant = self.last_image_layer_creation_check_instant.lock().unwrap();
5076 1145 : if let CurrentLogicalSize::Exact(logical_size) = self.current_logical_size.current_size() {
5077 941 : let check_required_after = if Into::<u64>::into(&logical_size) >= LARGE_TENANT_THRESHOLD
5078 : {
5079 0 : self.get_checkpoint_timeout()
5080 : } else {
5081 941 : Duration::from_secs(3600 * 48)
5082 : };
5083 :
5084 941 : time_based_decision = match *last_check_instant {
5085 521 : Some(last_check) => {
5086 521 : let elapsed = last_check.elapsed();
5087 521 : elapsed >= check_required_after
5088 : }
5089 420 : None => true,
5090 : };
5091 204 : }
5092 :
5093 : // Do the expensive delta layer counting only if this timeline has ingested sufficient
5094 : // WAL since the last check or a checkpoint timeout interval has elapsed since the last
5095 : // check.
5096 1145 : let decision = distance_based_decision || time_based_decision;
5097 :
5098 1145 : if decision {
5099 424 : self.last_image_layer_creation_check_at.store(lsn);
5100 424 : *last_check_instant = Some(Instant::now());
5101 721 : }
5102 :
5103 1145 : decision
5104 1145 : }
5105 :
5106 : /// Returns the image layers generated and an enum indicating whether the process is fully completed.
5107 : /// true = we have generate all image layers, false = we preempt the process for L0 compaction.
5108 : #[tracing::instrument(skip_all, fields(%lsn, %mode))]
5109 : async fn create_image_layers(
5110 : self: &Arc<Timeline>,
5111 : partitioning: &KeyPartitioning,
5112 : lsn: Lsn,
5113 : mode: ImageLayerCreationMode,
5114 : ctx: &RequestContext,
5115 : last_status: LastImageLayerCreationStatus,
5116 : yield_for_l0: bool,
5117 : ) -> Result<(Vec<ResidentLayer>, LastImageLayerCreationStatus), CreateImageLayersError> {
5118 : let timer = self.metrics.create_images_time_histo.start_timer();
5119 :
5120 : if partitioning.parts.is_empty() {
5121 : warn!("no partitions to create image layers for");
5122 : return Ok((vec![], LastImageLayerCreationStatus::Complete));
5123 : }
5124 :
5125 : // We need to avoid holes between generated image layers.
5126 : // Otherwise LayerMap::image_layer_exists will return false if key range of some layer is covered by more than one
5127 : // image layer with hole between them. In this case such layer can not be utilized by GC.
5128 : //
5129 : // How such hole between partitions can appear?
5130 : // if we have relation with relid=1 and size 100 and relation with relid=2 with size 200 then result of
5131 : // KeySpace::partition may contain partitions <100000000..100000099> and <200000000..200000199>.
5132 : // If there is delta layer <100000000..300000000> then it never be garbage collected because
5133 : // image layers <100000000..100000099> and <200000000..200000199> are not completely covering it.
5134 : let mut start = Key::MIN;
5135 :
5136 : let check_for_image_layers =
5137 : if let LastImageLayerCreationStatus::Incomplete { last_key } = last_status {
5138 : info!(
5139 : "resuming image layer creation: last_status=incomplete, continue from {}",
5140 : last_key
5141 : );
5142 : true
5143 : } else {
5144 : self.should_check_if_image_layers_required(lsn)
5145 : };
5146 :
5147 : let mut batch_image_writer = BatchLayerWriter::new(self.conf).await?;
5148 :
5149 : let mut all_generated = true;
5150 :
5151 : let mut partition_processed = 0;
5152 : let mut total_partitions = partitioning.parts.len();
5153 : let mut last_partition_processed = None;
5154 : let mut partition_parts = partitioning.parts.clone();
5155 :
5156 : if let LastImageLayerCreationStatus::Incomplete { last_key } = last_status {
5157 : // We need to skip the partitions that have already been processed.
5158 : let mut found = false;
5159 : for (i, partition) in partition_parts.iter().enumerate() {
5160 : if last_key <= partition.end().unwrap() {
5161 : // ```plain
5162 : // |------|--------|----------|------|
5163 : // ^last_key
5164 : // ^start from this partition
5165 : // ```
5166 : // Why `i+1` instead of `i`?
5167 : // It is possible that the user did some writes after the previous image layer creation attempt so that
5168 : // a relation grows in size, and the last_key is now in the middle of the partition. In this case, we
5169 : // still want to skip this partition, so that we can make progress and avoid generating image layers over
5170 : // the same partition. Doing a mod to ensure we don't end up with an empty vec.
5171 : if i + 1 >= total_partitions {
5172 : // In general, this case should not happen -- if last_key is on the last partition, the previous
5173 : // iteration of image layer creation should return a complete status.
5174 : break; // with found=false
5175 : }
5176 : partition_parts = partition_parts.split_off(i + 1); // Remove the first i + 1 elements
5177 : total_partitions = partition_parts.len();
5178 : // Update the start key to the partition start.
5179 : start = partition_parts[0].start().unwrap();
5180 : found = true;
5181 : break;
5182 : }
5183 : }
5184 : if !found {
5185 : // Last key is within the last partition, or larger than all partitions.
5186 : return Ok((vec![], LastImageLayerCreationStatus::Complete));
5187 : }
5188 : }
5189 :
5190 : for partition in partition_parts.iter() {
5191 : if self.cancel.is_cancelled() {
5192 : return Err(CreateImageLayersError::Cancelled);
5193 : }
5194 : partition_processed += 1;
5195 : let img_range = start..partition.ranges.last().unwrap().end;
5196 : let compact_metadata = partition.overlaps(&Key::metadata_key_range());
5197 : if compact_metadata {
5198 : for range in &partition.ranges {
5199 : assert!(
5200 : range.start.field1 >= METADATA_KEY_BEGIN_PREFIX
5201 : && range.end.field1 <= METADATA_KEY_END_PREFIX,
5202 : "metadata keys must be partitioned separately"
5203 : );
5204 : }
5205 : if mode == ImageLayerCreationMode::Try && !check_for_image_layers {
5206 : // Skip compaction if there are not enough updates. Metadata compaction will do a scan and
5207 : // might mess up with evictions.
5208 : start = img_range.end;
5209 : continue;
5210 : }
5211 : // For initial and force modes, we always generate image layers for metadata keys.
5212 : } else if let ImageLayerCreationMode::Try = mode {
5213 : // check_for_image_layers = false -> skip
5214 : // check_for_image_layers = true -> check time_for_new_image_layer -> skip/generate
5215 : if !check_for_image_layers || !self.time_for_new_image_layer(partition, lsn).await {
5216 : start = img_range.end;
5217 : continue;
5218 : }
5219 : }
5220 : if let ImageLayerCreationMode::Force = mode {
5221 : // When forced to create image layers, we might try and create them where they already
5222 : // exist. This mode is only used in tests/debug.
5223 : let layers = self.layers.read().await;
5224 : if layers.contains_key(&PersistentLayerKey {
5225 : key_range: img_range.clone(),
5226 : lsn_range: PersistentLayerDesc::image_layer_lsn_range(lsn),
5227 : is_delta: false,
5228 : }) {
5229 : // TODO: this can be processed with the BatchLayerWriter::finish_with_discard
5230 : // in the future.
5231 : tracing::info!(
5232 : "Skipping image layer at {lsn} {}..{}, already exists",
5233 : img_range.start,
5234 : img_range.end
5235 : );
5236 : start = img_range.end;
5237 : continue;
5238 : }
5239 : }
5240 :
5241 : let image_layer_writer = ImageLayerWriter::new(
5242 : self.conf,
5243 : self.timeline_id,
5244 : self.tenant_shard_id,
5245 : &img_range,
5246 : lsn,
5247 : ctx,
5248 : )
5249 : .await?;
5250 :
5251 0 : fail_point!("image-layer-writer-fail-before-finish", |_| {
5252 0 : Err(CreateImageLayersError::Other(anyhow::anyhow!(
5253 0 : "failpoint image-layer-writer-fail-before-finish"
5254 0 : )))
5255 0 : });
5256 :
5257 : let io_concurrency = IoConcurrency::spawn_from_conf(
5258 : self.conf,
5259 : self.gate
5260 : .enter()
5261 0 : .map_err(|_| CreateImageLayersError::Cancelled)?,
5262 : );
5263 :
5264 : let outcome = if !compact_metadata {
5265 : self.create_image_layer_for_rel_blocks(
5266 : partition,
5267 : image_layer_writer,
5268 : lsn,
5269 : ctx,
5270 : img_range.clone(),
5271 : io_concurrency,
5272 : )
5273 : .await?
5274 : } else {
5275 : self.create_image_layer_for_metadata_keys(
5276 : partition,
5277 : image_layer_writer,
5278 : lsn,
5279 : ctx,
5280 : img_range.clone(),
5281 : mode,
5282 : io_concurrency,
5283 : )
5284 : .await?
5285 : };
5286 : match outcome {
5287 : ImageLayerCreationOutcome::Empty => {
5288 : // No data in this partition, so we don't need to create an image layer (for now).
5289 : // The next image layer should cover this key range, so we don't advance the `start`
5290 : // key.
5291 : }
5292 : ImageLayerCreationOutcome::Generated {
5293 : unfinished_image_layer,
5294 : } => {
5295 : batch_image_writer.add_unfinished_image_writer(
5296 : unfinished_image_layer,
5297 : img_range.clone(),
5298 : lsn,
5299 : );
5300 : // The next image layer should be generated right after this one.
5301 : start = img_range.end;
5302 : }
5303 : ImageLayerCreationOutcome::Skip => {
5304 : // We don't need to create an image layer for this partition.
5305 : // The next image layer should NOT cover this range, otherwise
5306 : // the keyspace becomes empty (reads don't go past image layers).
5307 : start = img_range.end;
5308 : }
5309 : }
5310 :
5311 : if let ImageLayerCreationMode::Try = mode {
5312 : // We have at least made some progress
5313 : if yield_for_l0 && batch_image_writer.pending_layer_num() >= 1 {
5314 : // The `Try` mode is currently only used on the compaction path. We want to avoid
5315 : // image layer generation taking too long time and blocking L0 compaction. So in this
5316 : // mode, we also inspect the current number of L0 layers and skip image layer generation
5317 : // if there are too many of them.
5318 : let image_preempt_threshold = self.get_image_creation_preempt_threshold()
5319 : * self.get_compaction_threshold();
5320 : // TODO: currently we do not respect `get_image_creation_preempt_threshold` and always yield
5321 : // when there is a single timeline with more than L0 threshold L0 layers. As long as the
5322 : // `get_image_creation_preempt_threshold` is set to a value greater than 0, we will yield for L0 compaction.
5323 : if image_preempt_threshold != 0 {
5324 : let should_yield = self
5325 : .l0_compaction_trigger
5326 : .notified()
5327 : .now_or_never()
5328 : .is_some();
5329 : if should_yield {
5330 : tracing::info!(
5331 : "preempt image layer generation at {lsn} when processing partition {}..{}: too many L0 layers",
5332 : partition.start().unwrap(),
5333 : partition.end().unwrap()
5334 : );
5335 : last_partition_processed = Some(partition.clone());
5336 : all_generated = false;
5337 : break;
5338 : }
5339 : }
5340 : }
5341 : }
5342 : }
5343 :
5344 : let image_layers = batch_image_writer.finish(self, ctx).await?;
5345 :
5346 : let mut guard = self.layers.write().await;
5347 :
5348 : // FIXME: we could add the images to be uploaded *before* returning from here, but right
5349 : // now they are being scheduled outside of write lock; current way is inconsistent with
5350 : // compaction lock order.
5351 : guard
5352 : .open_mut()?
5353 : .track_new_image_layers(&image_layers, &self.metrics);
5354 : drop_wlock(guard);
5355 : let duration = timer.stop_and_record();
5356 :
5357 : // Creating image layers may have caused some previously visible layers to be covered
5358 : if !image_layers.is_empty() {
5359 : self.update_layer_visibility().await?;
5360 : }
5361 :
5362 : let total_layer_size = image_layers
5363 : .iter()
5364 496 : .map(|l| l.metadata().file_size)
5365 : .sum::<u64>();
5366 :
5367 : if !image_layers.is_empty() {
5368 : info!(
5369 : "created {} image layers ({} bytes) in {}s, processed {} out of {} partitions",
5370 : image_layers.len(),
5371 : total_layer_size,
5372 : duration.as_secs_f64(),
5373 : partition_processed,
5374 : total_partitions
5375 : );
5376 : }
5377 :
5378 : Ok((
5379 : image_layers,
5380 : if all_generated {
5381 : LastImageLayerCreationStatus::Complete
5382 : } else {
5383 : LastImageLayerCreationStatus::Incomplete {
5384 : last_key: if let Some(last_partition_processed) = last_partition_processed {
5385 : last_partition_processed.end().unwrap_or(Key::MIN)
5386 : } else {
5387 : // This branch should be unreachable, but in case it happens, we can just return the start key.
5388 : Key::MIN
5389 : },
5390 : }
5391 : },
5392 : ))
5393 : }
5394 :
5395 : /// Wait until the background initial logical size calculation is complete, or
5396 : /// this Timeline is shut down. Calling this function will cause the initial
5397 : /// logical size calculation to skip waiting for the background jobs barrier.
5398 0 : pub(crate) async fn await_initial_logical_size(self: Arc<Self>) {
5399 0 : if !self.shard_identity.is_shard_zero() {
5400 : // We don't populate logical size on shard >0: skip waiting for it.
5401 0 : return;
5402 0 : }
5403 0 :
5404 0 : if self.remote_client.is_deleting() {
5405 : // The timeline was created in a deletion-resume state, we don't expect logical size to be populated
5406 0 : return;
5407 0 : }
5408 0 :
5409 0 : if self.current_logical_size.current_size().is_exact() {
5410 : // root timelines are initialized with exact count, but never start the background
5411 : // calculation
5412 0 : return;
5413 0 : }
5414 :
5415 0 : if let Some(await_bg_cancel) = self
5416 0 : .current_logical_size
5417 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore
5418 0 : .get()
5419 0 : {
5420 0 : await_bg_cancel.cancel();
5421 0 : } else {
5422 : // We should not wait if we were not able to explicitly instruct
5423 : // the logical size cancellation to skip the concurrency limit semaphore.
5424 : // TODO: this is an unexpected case. We should restructure so that it
5425 : // can't happen.
5426 0 : tracing::warn!(
5427 0 : "await_initial_logical_size: can't get semaphore cancel token, skipping"
5428 : );
5429 0 : debug_assert!(false);
5430 : }
5431 :
5432 0 : tokio::select!(
5433 0 : _ = self.current_logical_size.initialized.acquire() => {},
5434 0 : _ = self.cancel.cancelled() => {}
5435 : )
5436 0 : }
5437 :
5438 : /// Detach this timeline from its ancestor by copying all of ancestors layers as this
5439 : /// Timelines layers up to the ancestor_lsn.
5440 : ///
5441 : /// Requires a timeline that:
5442 : /// - has an ancestor to detach from
5443 : /// - the ancestor does not have an ancestor -- follows from the original RFC limitations, not
5444 : /// a technical requirement
5445 : ///
5446 : /// After the operation has been started, it cannot be canceled. Upon restart it needs to be
5447 : /// polled again until completion.
5448 : ///
5449 : /// During the operation all timelines sharing the data with this timeline will be reparented
5450 : /// from our ancestor to be branches of this timeline.
5451 0 : pub(crate) async fn prepare_to_detach_from_ancestor(
5452 0 : self: &Arc<Timeline>,
5453 0 : tenant: &crate::tenant::Tenant,
5454 0 : options: detach_ancestor::Options,
5455 0 : behavior: DetachBehavior,
5456 0 : ctx: &RequestContext,
5457 0 : ) -> Result<detach_ancestor::Progress, detach_ancestor::Error> {
5458 0 : detach_ancestor::prepare(self, tenant, behavior, options, ctx).await
5459 0 : }
5460 :
5461 : /// Second step of detach from ancestor; detaches the `self` from it's current ancestor and
5462 : /// reparents any reparentable children of previous ancestor.
5463 : ///
5464 : /// This method is to be called while holding the TenantManager's tenant slot, so during this
5465 : /// method we cannot be deleted nor can any timeline be deleted. After this method returns
5466 : /// successfully, tenant must be reloaded.
5467 : ///
5468 : /// Final step will be to [`Self::complete_detaching_timeline_ancestor`] after optionally
5469 : /// resetting the tenant.
5470 0 : pub(crate) async fn detach_from_ancestor_and_reparent(
5471 0 : self: &Arc<Timeline>,
5472 0 : tenant: &crate::tenant::Tenant,
5473 0 : prepared: detach_ancestor::PreparedTimelineDetach,
5474 0 : ancestor_timeline_id: TimelineId,
5475 0 : ancestor_lsn: Lsn,
5476 0 : behavior: DetachBehavior,
5477 0 : ctx: &RequestContext,
5478 0 : ) -> Result<detach_ancestor::DetachingAndReparenting, detach_ancestor::Error> {
5479 0 : detach_ancestor::detach_and_reparent(
5480 0 : self,
5481 0 : tenant,
5482 0 : prepared,
5483 0 : ancestor_timeline_id,
5484 0 : ancestor_lsn,
5485 0 : behavior,
5486 0 : ctx,
5487 0 : )
5488 0 : .await
5489 0 : }
5490 :
5491 : /// Final step which unblocks the GC.
5492 : ///
5493 : /// The tenant must've been reset if ancestry was modified previously (in tenant manager).
5494 0 : pub(crate) async fn complete_detaching_timeline_ancestor(
5495 0 : self: &Arc<Timeline>,
5496 0 : tenant: &crate::tenant::Tenant,
5497 0 : attempt: detach_ancestor::Attempt,
5498 0 : ctx: &RequestContext,
5499 0 : ) -> Result<(), detach_ancestor::Error> {
5500 0 : detach_ancestor::complete(self, tenant, attempt, ctx).await
5501 0 : }
5502 : }
5503 :
5504 : impl Drop for Timeline {
5505 20 : fn drop(&mut self) {
5506 20 : if let Some(ancestor) = &self.ancestor_timeline {
5507 : // This lock should never be poisoned, but in case it is we do a .map() instead of
5508 : // an unwrap(), to avoid panicking in a destructor and thereby aborting the process.
5509 8 : if let Ok(mut gc_info) = ancestor.gc_info.write() {
5510 8 : if !gc_info.remove_child_not_offloaded(self.timeline_id) {
5511 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
5512 0 : "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
5513 8 : }
5514 0 : }
5515 12 : }
5516 20 : info!(
5517 0 : "Timeline {} for tenant {} is being dropped",
5518 : self.timeline_id, self.tenant_shard_id.tenant_id
5519 : );
5520 20 : }
5521 : }
5522 :
5523 : /// Top-level failure to compact.
5524 : #[derive(Debug, thiserror::Error)]
5525 : pub(crate) enum CompactionError {
5526 : #[error("The timeline or pageserver is shutting down")]
5527 : ShuttingDown,
5528 : /// Compaction tried to offload a timeline and failed
5529 : #[error("Failed to offload timeline: {0}")]
5530 : Offload(OffloadError),
5531 : /// Compaction cannot be done right now; page reconstruction and so on.
5532 : #[error("Failed to collect keyspace: {0}")]
5533 : CollectKeySpaceError(#[from] CollectKeySpaceError),
5534 : #[error(transparent)]
5535 : Other(anyhow::Error),
5536 : #[error("Compaction already running: {0}")]
5537 : AlreadyRunning(&'static str),
5538 : }
5539 :
5540 : impl CompactionError {
5541 : /// Errors that can be ignored, i.e., cancel and shutdown.
5542 0 : pub fn is_cancel(&self) -> bool {
5543 0 : matches!(
5544 0 : self,
5545 : Self::ShuttingDown
5546 : | Self::AlreadyRunning(_)
5547 : | Self::CollectKeySpaceError(CollectKeySpaceError::Cancelled)
5548 : | Self::CollectKeySpaceError(CollectKeySpaceError::PageRead(
5549 : PageReconstructError::Cancelled
5550 : ))
5551 : | Self::Offload(OffloadError::Cancelled)
5552 : )
5553 0 : }
5554 :
5555 : /// Critical errors that indicate data corruption.
5556 0 : pub fn is_critical(&self) -> bool {
5557 0 : matches!(
5558 0 : self,
5559 : Self::CollectKeySpaceError(
5560 : CollectKeySpaceError::Decode(_)
5561 : | CollectKeySpaceError::PageRead(
5562 : PageReconstructError::MissingKey(_) | PageReconstructError::WalRedo(_),
5563 : )
5564 : )
5565 : )
5566 0 : }
5567 : }
5568 :
5569 : impl From<OffloadError> for CompactionError {
5570 0 : fn from(e: OffloadError) -> Self {
5571 0 : match e {
5572 0 : OffloadError::Cancelled => Self::ShuttingDown,
5573 0 : _ => Self::Offload(e),
5574 : }
5575 0 : }
5576 : }
5577 :
5578 : impl From<super::upload_queue::NotInitialized> for CompactionError {
5579 0 : fn from(value: super::upload_queue::NotInitialized) -> Self {
5580 0 : match value {
5581 : super::upload_queue::NotInitialized::Uninitialized => {
5582 0 : CompactionError::Other(anyhow::anyhow!(value))
5583 : }
5584 : super::upload_queue::NotInitialized::ShuttingDown
5585 0 : | super::upload_queue::NotInitialized::Stopped => CompactionError::ShuttingDown,
5586 : }
5587 0 : }
5588 : }
5589 :
5590 : impl From<super::storage_layer::layer::DownloadError> for CompactionError {
5591 0 : fn from(e: super::storage_layer::layer::DownloadError) -> Self {
5592 0 : match e {
5593 : super::storage_layer::layer::DownloadError::TimelineShutdown
5594 : | super::storage_layer::layer::DownloadError::DownloadCancelled => {
5595 0 : CompactionError::ShuttingDown
5596 : }
5597 : super::storage_layer::layer::DownloadError::ContextAndConfigReallyDeniesDownloads
5598 : | super::storage_layer::layer::DownloadError::DownloadRequired
5599 : | super::storage_layer::layer::DownloadError::NotFile(_)
5600 : | super::storage_layer::layer::DownloadError::DownloadFailed
5601 : | super::storage_layer::layer::DownloadError::PreStatFailed(_) => {
5602 0 : CompactionError::Other(anyhow::anyhow!(e))
5603 : }
5604 : #[cfg(test)]
5605 : super::storage_layer::layer::DownloadError::Failpoint(_) => {
5606 0 : CompactionError::Other(anyhow::anyhow!(e))
5607 : }
5608 : }
5609 0 : }
5610 : }
5611 :
5612 : impl From<layer_manager::Shutdown> for CompactionError {
5613 0 : fn from(_: layer_manager::Shutdown) -> Self {
5614 0 : CompactionError::ShuttingDown
5615 0 : }
5616 : }
5617 :
5618 : #[serde_as]
5619 392 : #[derive(serde::Serialize)]
5620 : struct RecordedDuration(#[serde_as(as = "serde_with::DurationMicroSeconds")] Duration);
5621 :
5622 : #[derive(Default)]
5623 : enum DurationRecorder {
5624 : #[default]
5625 : NotStarted,
5626 : Recorded(RecordedDuration, tokio::time::Instant),
5627 : }
5628 :
5629 : impl DurationRecorder {
5630 1005 : fn till_now(&self) -> DurationRecorder {
5631 1005 : match self {
5632 : DurationRecorder::NotStarted => {
5633 0 : panic!("must only call on recorded measurements")
5634 : }
5635 1005 : DurationRecorder::Recorded(_, ended) => {
5636 1005 : let now = tokio::time::Instant::now();
5637 1005 : DurationRecorder::Recorded(RecordedDuration(now - *ended), now)
5638 1005 : }
5639 1005 : }
5640 1005 : }
5641 392 : fn into_recorded(self) -> Option<RecordedDuration> {
5642 392 : match self {
5643 0 : DurationRecorder::NotStarted => None,
5644 392 : DurationRecorder::Recorded(recorded, _) => Some(recorded),
5645 : }
5646 392 : }
5647 : }
5648 :
5649 : /// Descriptor for a delta layer used in testing infra. The start/end key/lsn range of the
5650 : /// delta layer might be different from the min/max key/lsn in the delta layer. Therefore,
5651 : /// the layer descriptor requires the user to provide the ranges, which should cover all
5652 : /// keys specified in the `data` field.
5653 : #[cfg(test)]
5654 : #[derive(Clone)]
5655 : pub struct DeltaLayerTestDesc {
5656 : pub lsn_range: Range<Lsn>,
5657 : pub key_range: Range<Key>,
5658 : pub data: Vec<(Key, Lsn, Value)>,
5659 : }
5660 :
5661 : #[cfg(test)]
5662 : #[derive(Clone)]
5663 : pub struct InMemoryLayerTestDesc {
5664 : pub lsn_range: Range<Lsn>,
5665 : pub data: Vec<(Key, Lsn, Value)>,
5666 : pub is_open: bool,
5667 : }
5668 :
5669 : #[cfg(test)]
5670 : impl DeltaLayerTestDesc {
5671 8 : pub fn new(lsn_range: Range<Lsn>, key_range: Range<Key>, data: Vec<(Key, Lsn, Value)>) -> Self {
5672 8 : Self {
5673 8 : lsn_range,
5674 8 : key_range,
5675 8 : data,
5676 8 : }
5677 8 : }
5678 :
5679 176 : pub fn new_with_inferred_key_range(
5680 176 : lsn_range: Range<Lsn>,
5681 176 : data: Vec<(Key, Lsn, Value)>,
5682 176 : ) -> Self {
5683 440 : let key_min = data.iter().map(|(key, _, _)| key).min().unwrap();
5684 440 : let key_max = data.iter().map(|(key, _, _)| key).max().unwrap();
5685 176 : Self {
5686 176 : key_range: (*key_min)..(key_max.next()),
5687 176 : lsn_range,
5688 176 : data,
5689 176 : }
5690 176 : }
5691 :
5692 20 : pub(crate) fn layer_name(&self) -> LayerName {
5693 20 : LayerName::Delta(super::storage_layer::DeltaLayerName {
5694 20 : key_range: self.key_range.clone(),
5695 20 : lsn_range: self.lsn_range.clone(),
5696 20 : })
5697 20 : }
5698 : }
5699 :
5700 : impl Timeline {
5701 56 : async fn finish_compact_batch(
5702 56 : self: &Arc<Self>,
5703 56 : new_deltas: &[ResidentLayer],
5704 56 : new_images: &[ResidentLayer],
5705 56 : layers_to_remove: &[Layer],
5706 56 : ) -> Result<(), CompactionError> {
5707 56 : let mut guard = tokio::select! {
5708 56 : guard = self.layers.write() => guard,
5709 56 : _ = self.cancel.cancelled() => {
5710 0 : return Err(CompactionError::ShuttingDown);
5711 : }
5712 : };
5713 :
5714 56 : let mut duplicated_layers = HashSet::new();
5715 56 :
5716 56 : let mut insert_layers = Vec::with_capacity(new_deltas.len());
5717 :
5718 672 : for l in new_deltas {
5719 616 : if guard.contains(l.as_ref()) {
5720 : // expected in tests
5721 0 : tracing::error!(layer=%l, "duplicated L1 layer");
5722 :
5723 : // good ways to cause a duplicate: we repeatedly error after taking the writelock
5724 : // `guard` on self.layers. as of writing this, there are no error returns except
5725 : // for compact_level0_phase1 creating an L0, which does not happen in practice
5726 : // because we have not implemented L0 => L0 compaction.
5727 0 : duplicated_layers.insert(l.layer_desc().key());
5728 616 : } else if LayerMap::is_l0(&l.layer_desc().key_range, l.layer_desc().is_delta) {
5729 0 : return Err(CompactionError::Other(anyhow::anyhow!(
5730 0 : "compaction generates a L0 layer file as output, which will cause infinite compaction."
5731 0 : )));
5732 616 : } else {
5733 616 : insert_layers.push(l.clone());
5734 616 : }
5735 : }
5736 :
5737 : // only remove those inputs which were not outputs
5738 56 : let remove_layers: Vec<Layer> = layers_to_remove
5739 56 : .iter()
5740 804 : .filter(|l| !duplicated_layers.contains(&l.layer_desc().key()))
5741 56 : .cloned()
5742 56 : .collect();
5743 56 :
5744 56 : if !new_images.is_empty() {
5745 0 : guard
5746 0 : .open_mut()?
5747 0 : .track_new_image_layers(new_images, &self.metrics);
5748 56 : }
5749 :
5750 56 : guard
5751 56 : .open_mut()?
5752 56 : .finish_compact_l0(&remove_layers, &insert_layers, &self.metrics);
5753 56 :
5754 56 : self.remote_client
5755 56 : .schedule_compaction_update(&remove_layers, new_deltas)?;
5756 :
5757 56 : drop_wlock(guard);
5758 56 :
5759 56 : Ok(())
5760 56 : }
5761 :
5762 0 : async fn rewrite_layers(
5763 0 : self: &Arc<Self>,
5764 0 : mut replace_layers: Vec<(Layer, ResidentLayer)>,
5765 0 : mut drop_layers: Vec<Layer>,
5766 0 : ) -> Result<(), CompactionError> {
5767 0 : let mut guard = self.layers.write().await;
5768 :
5769 : // Trim our lists in case our caller (compaction) raced with someone else (GC) removing layers: we want
5770 : // to avoid double-removing, and avoid rewriting something that was removed.
5771 0 : replace_layers.retain(|(l, _)| guard.contains(l));
5772 0 : drop_layers.retain(|l| guard.contains(l));
5773 0 :
5774 0 : guard
5775 0 : .open_mut()?
5776 0 : .rewrite_layers(&replace_layers, &drop_layers, &self.metrics);
5777 0 :
5778 0 : let upload_layers: Vec<_> = replace_layers.into_iter().map(|r| r.1).collect();
5779 0 :
5780 0 : self.remote_client
5781 0 : .schedule_compaction_update(&drop_layers, &upload_layers)?;
5782 :
5783 0 : Ok(())
5784 0 : }
5785 :
5786 : /// Schedules the uploads of the given image layers
5787 725 : fn upload_new_image_layers(
5788 725 : self: &Arc<Self>,
5789 725 : new_images: impl IntoIterator<Item = ResidentLayer>,
5790 725 : ) -> Result<(), super::upload_queue::NotInitialized> {
5791 777 : for layer in new_images {
5792 52 : self.remote_client.schedule_layer_file_upload(layer)?;
5793 : }
5794 : // should any new image layer been created, not uploading index_part will
5795 : // result in a mismatch between remote_physical_size and layermap calculated
5796 : // size, which will fail some tests, but should not be an issue otherwise.
5797 725 : self.remote_client
5798 725 : .schedule_index_upload_for_file_changes()?;
5799 725 : Ok(())
5800 725 : }
5801 :
5802 0 : async fn find_gc_time_cutoff(
5803 0 : &self,
5804 0 : now: SystemTime,
5805 0 : pitr: Duration,
5806 0 : cancel: &CancellationToken,
5807 0 : ctx: &RequestContext,
5808 0 : ) -> Result<Option<Lsn>, PageReconstructError> {
5809 0 : debug_assert_current_span_has_tenant_and_timeline_id();
5810 0 : if self.shard_identity.is_shard_zero() {
5811 : // Shard Zero has SLRU data and can calculate the PITR time -> LSN mapping itself
5812 0 : let time_range = if pitr == Duration::ZERO {
5813 0 : humantime::parse_duration(DEFAULT_PITR_INTERVAL).expect("constant is invalid")
5814 : } else {
5815 0 : pitr
5816 : };
5817 :
5818 : // If PITR is so large or `now` is so small that this underflows, we will retain no history (highly unexpected case)
5819 0 : let time_cutoff = now.checked_sub(time_range).unwrap_or(now);
5820 0 : let timestamp = to_pg_timestamp(time_cutoff);
5821 :
5822 0 : let time_cutoff = match self.find_lsn_for_timestamp(timestamp, cancel, ctx).await? {
5823 0 : LsnForTimestamp::Present(lsn) => Some(lsn),
5824 0 : LsnForTimestamp::Future(lsn) => {
5825 0 : // The timestamp is in the future. That sounds impossible,
5826 0 : // but what it really means is that there hasn't been
5827 0 : // any commits since the cutoff timestamp.
5828 0 : //
5829 0 : // In this case we should use the LSN of the most recent commit,
5830 0 : // which is implicitly the last LSN in the log.
5831 0 : debug!("future({})", lsn);
5832 0 : Some(self.get_last_record_lsn())
5833 : }
5834 0 : LsnForTimestamp::Past(lsn) => {
5835 0 : debug!("past({})", lsn);
5836 0 : None
5837 : }
5838 0 : LsnForTimestamp::NoData(lsn) => {
5839 0 : debug!("nodata({})", lsn);
5840 0 : None
5841 : }
5842 : };
5843 0 : Ok(time_cutoff)
5844 : } else {
5845 : // Shards other than shard zero cannot do timestamp->lsn lookups, and must instead learn their GC cutoff
5846 : // from shard zero's index. The index doesn't explicitly tell us the time cutoff, but we may assume that
5847 : // the point up to which shard zero's last_gc_cutoff has advanced will either be the time cutoff, or a
5848 : // space cutoff that we would also have respected ourselves.
5849 0 : match self
5850 0 : .remote_client
5851 0 : .download_foreign_index(ShardNumber(0), cancel)
5852 0 : .await
5853 : {
5854 0 : Ok((index_part, index_generation, _index_mtime)) => {
5855 0 : tracing::info!(
5856 0 : "GC loaded shard zero metadata (gen {index_generation:?}): latest_gc_cutoff_lsn: {}",
5857 0 : index_part.metadata.latest_gc_cutoff_lsn()
5858 : );
5859 0 : Ok(Some(index_part.metadata.latest_gc_cutoff_lsn()))
5860 : }
5861 : Err(DownloadError::NotFound) => {
5862 : // This is unexpected, because during timeline creations shard zero persists to remote
5863 : // storage before other shards are called, and during timeline deletion non-zeroth shards are
5864 : // deleted before the zeroth one. However, it should be harmless: if we somehow end up in this
5865 : // state, then shard zero should _eventually_ write an index when it GCs.
5866 0 : tracing::warn!("GC couldn't find shard zero's index for timeline");
5867 0 : Ok(None)
5868 : }
5869 0 : Err(e) => {
5870 0 : // TODO: this function should return a different error type than page reconstruct error
5871 0 : Err(PageReconstructError::Other(anyhow::anyhow!(e)))
5872 : }
5873 : }
5874 :
5875 : // TODO: after reading shard zero's GC cutoff, we should validate its generation with the storage
5876 : // controller. Otherwise, it is possible that we see the GC cutoff go backwards while shard zero
5877 : // is going through a migration if we read the old location's index and it has GC'd ahead of the
5878 : // new location. This is legal in principle, but problematic in practice because it might result
5879 : // in a timeline creation succeeding on shard zero ('s new location) but then failing on other shards
5880 : // because they have GC'd past the branch point.
5881 : }
5882 0 : }
5883 :
5884 : /// Find the Lsns above which layer files need to be retained on
5885 : /// garbage collection.
5886 : ///
5887 : /// We calculate two cutoffs, one based on time and one based on WAL size. `pitr`
5888 : /// controls the time cutoff (or ZERO to disable time-based retention), and `space_cutoff` controls
5889 : /// the space-based retention.
5890 : ///
5891 : /// This function doesn't simply to calculate time & space based retention: it treats time-based
5892 : /// retention as authoritative if enabled, and falls back to space-based retention if calculating
5893 : /// the LSN for a time point isn't possible. Therefore the GcCutoffs::horizon in the response might
5894 : /// be different to the `space_cutoff` input. Callers should treat the min() of the two cutoffs
5895 : /// in the response as the GC cutoff point for the timeline.
5896 : #[instrument(skip_all, fields(timeline_id=%self.timeline_id))]
5897 : pub(super) async fn find_gc_cutoffs(
5898 : &self,
5899 : now: SystemTime,
5900 : space_cutoff: Lsn,
5901 : pitr: Duration,
5902 : cancel: &CancellationToken,
5903 : ctx: &RequestContext,
5904 : ) -> Result<GcCutoffs, PageReconstructError> {
5905 : let _timer = self
5906 : .metrics
5907 : .find_gc_cutoffs_histo
5908 : .start_timer()
5909 : .record_on_drop();
5910 :
5911 : pausable_failpoint!("Timeline::find_gc_cutoffs-pausable");
5912 :
5913 : if cfg!(test) {
5914 : // Unit tests which specify zero PITR interval expect to avoid doing any I/O for timestamp lookup
5915 : if pitr == Duration::ZERO {
5916 : return Ok(GcCutoffs {
5917 : time: self.get_last_record_lsn(),
5918 : space: space_cutoff,
5919 : });
5920 : }
5921 : }
5922 :
5923 : // Calculate a time-based limit on how much to retain:
5924 : // - if PITR interval is set, then this is our cutoff.
5925 : // - if PITR interval is not set, then we do a lookup
5926 : // based on DEFAULT_PITR_INTERVAL, so that size-based retention does not result in keeping history around permanently on idle databases.
5927 : let time_cutoff = self.find_gc_time_cutoff(now, pitr, cancel, ctx).await?;
5928 :
5929 : Ok(match (pitr, time_cutoff) {
5930 : (Duration::ZERO, Some(time_cutoff)) => {
5931 : // PITR is not set. Retain the size-based limit, or the default time retention,
5932 : // whichever requires less data.
5933 : GcCutoffs {
5934 : time: self.get_last_record_lsn(),
5935 : space: std::cmp::max(time_cutoff, space_cutoff),
5936 : }
5937 : }
5938 : (Duration::ZERO, None) => {
5939 : // PITR is not set, and time lookup failed
5940 : GcCutoffs {
5941 : time: self.get_last_record_lsn(),
5942 : space: space_cutoff,
5943 : }
5944 : }
5945 : (_, None) => {
5946 : // PITR interval is set & we didn't look up a timestamp successfully. Conservatively assume PITR
5947 : // cannot advance beyond what was already GC'd, and respect space-based retention
5948 : GcCutoffs {
5949 : time: *self.get_applied_gc_cutoff_lsn(),
5950 : space: space_cutoff,
5951 : }
5952 : }
5953 : (_, Some(time_cutoff)) => {
5954 : // PITR interval is set and we looked up timestamp successfully. Ignore
5955 : // size based retention and make time cutoff authoritative
5956 : GcCutoffs {
5957 : time: time_cutoff,
5958 : space: time_cutoff,
5959 : }
5960 : }
5961 : })
5962 : }
5963 :
5964 : /// Garbage collect layer files on a timeline that are no longer needed.
5965 : ///
5966 : /// Currently, we don't make any attempt at removing unneeded page versions
5967 : /// within a layer file. We can only remove the whole file if it's fully
5968 : /// obsolete.
5969 8 : pub(super) async fn gc(&self) -> Result<GcResult, GcError> {
5970 : // this is most likely the background tasks, but it might be the spawned task from
5971 : // immediate_gc
5972 8 : let _g = tokio::select! {
5973 8 : guard = self.gc_lock.lock() => guard,
5974 8 : _ = self.cancel.cancelled() => return Ok(GcResult::default()),
5975 : };
5976 8 : let timer = self.metrics.garbage_collect_histo.start_timer();
5977 8 :
5978 8 : fail_point!("before-timeline-gc");
5979 8 :
5980 8 : // Is the timeline being deleted?
5981 8 : if self.is_stopping() {
5982 0 : return Err(GcError::TimelineCancelled);
5983 8 : }
5984 8 :
5985 8 : let (space_cutoff, time_cutoff, retain_lsns, max_lsn_with_valid_lease) = {
5986 8 : let gc_info = self.gc_info.read().unwrap();
5987 8 :
5988 8 : let space_cutoff = min(gc_info.cutoffs.space, self.get_disk_consistent_lsn());
5989 8 : let time_cutoff = gc_info.cutoffs.time;
5990 8 : let retain_lsns = gc_info
5991 8 : .retain_lsns
5992 8 : .iter()
5993 8 : .map(|(lsn, _child_id, _is_offloaded)| *lsn)
5994 8 : .collect();
5995 8 :
5996 8 : // Gets the maximum LSN that holds the valid lease.
5997 8 : //
5998 8 : // Caveat: `refresh_gc_info` is in charged of updating the lease map.
5999 8 : // Here, we do not check for stale leases again.
6000 8 : let max_lsn_with_valid_lease = gc_info.leases.last_key_value().map(|(lsn, _)| *lsn);
6001 8 :
6002 8 : (
6003 8 : space_cutoff,
6004 8 : time_cutoff,
6005 8 : retain_lsns,
6006 8 : max_lsn_with_valid_lease,
6007 8 : )
6008 8 : };
6009 8 :
6010 8 : let mut new_gc_cutoff = Lsn::min(space_cutoff, time_cutoff);
6011 8 : let standby_horizon = self.standby_horizon.load();
6012 8 : // Hold GC for the standby, but as a safety guard do it only within some
6013 8 : // reasonable lag.
6014 8 : if standby_horizon != Lsn::INVALID {
6015 0 : if let Some(standby_lag) = new_gc_cutoff.checked_sub(standby_horizon) {
6016 : const MAX_ALLOWED_STANDBY_LAG: u64 = 10u64 << 30; // 10 GB
6017 0 : if standby_lag.0 < MAX_ALLOWED_STANDBY_LAG {
6018 0 : new_gc_cutoff = Lsn::min(standby_horizon, new_gc_cutoff);
6019 0 : trace!("holding off GC for standby apply LSN {}", standby_horizon);
6020 : } else {
6021 0 : warn!(
6022 0 : "standby is lagging for more than {}MB, not holding gc for it",
6023 0 : MAX_ALLOWED_STANDBY_LAG / 1024 / 1024
6024 : )
6025 : }
6026 0 : }
6027 8 : }
6028 :
6029 : // Reset standby horizon to ignore it if it is not updated till next GC.
6030 : // It is an easy way to unset it when standby disappears without adding
6031 : // more conf options.
6032 8 : self.standby_horizon.store(Lsn::INVALID);
6033 8 : self.metrics
6034 8 : .standby_horizon_gauge
6035 8 : .set(Lsn::INVALID.0 as i64);
6036 :
6037 8 : let res = self
6038 8 : .gc_timeline(
6039 8 : space_cutoff,
6040 8 : time_cutoff,
6041 8 : retain_lsns,
6042 8 : max_lsn_with_valid_lease,
6043 8 : new_gc_cutoff,
6044 8 : )
6045 8 : .instrument(
6046 8 : info_span!("gc_timeline", timeline_id = %self.timeline_id, cutoff = %new_gc_cutoff),
6047 : )
6048 8 : .await?;
6049 :
6050 : // only record successes
6051 8 : timer.stop_and_record();
6052 8 :
6053 8 : Ok(res)
6054 8 : }
6055 :
6056 8 : async fn gc_timeline(
6057 8 : &self,
6058 8 : space_cutoff: Lsn,
6059 8 : time_cutoff: Lsn,
6060 8 : retain_lsns: Vec<Lsn>,
6061 8 : max_lsn_with_valid_lease: Option<Lsn>,
6062 8 : new_gc_cutoff: Lsn,
6063 8 : ) -> Result<GcResult, GcError> {
6064 8 : // FIXME: if there is an ongoing detach_from_ancestor, we should just skip gc
6065 8 :
6066 8 : let now = SystemTime::now();
6067 8 : let mut result: GcResult = GcResult::default();
6068 8 :
6069 8 : // Nothing to GC. Return early.
6070 8 : let latest_gc_cutoff = *self.get_applied_gc_cutoff_lsn();
6071 8 : if latest_gc_cutoff >= new_gc_cutoff {
6072 0 : info!(
6073 0 : "Nothing to GC: new_gc_cutoff_lsn {new_gc_cutoff}, latest_gc_cutoff_lsn {latest_gc_cutoff}",
6074 : );
6075 0 : return Ok(result);
6076 8 : }
6077 :
6078 : // We need to ensure that no one tries to read page versions or create
6079 : // branches at a point before latest_gc_cutoff_lsn. See branch_timeline()
6080 : // for details. This will block until the old value is no longer in use.
6081 : //
6082 : // The GC cutoff should only ever move forwards.
6083 8 : let waitlist = {
6084 8 : let write_guard = self.applied_gc_cutoff_lsn.lock_for_write();
6085 8 : if *write_guard > new_gc_cutoff {
6086 0 : return Err(GcError::BadLsn {
6087 0 : why: format!(
6088 0 : "Cannot move GC cutoff LSN backwards (was {}, new {})",
6089 0 : *write_guard, new_gc_cutoff
6090 0 : ),
6091 0 : });
6092 8 : }
6093 8 :
6094 8 : write_guard.store_and_unlock(new_gc_cutoff)
6095 8 : };
6096 8 : waitlist.wait().await;
6097 :
6098 8 : info!("GC starting");
6099 :
6100 8 : debug!("retain_lsns: {:?}", retain_lsns);
6101 :
6102 8 : let mut layers_to_remove = Vec::new();
6103 :
6104 : // Scan all layers in the timeline (remote or on-disk).
6105 : //
6106 : // Garbage collect the layer if all conditions are satisfied:
6107 : // 1. it is older than cutoff LSN;
6108 : // 2. it is older than PITR interval;
6109 : // 3. it doesn't need to be retained for 'retain_lsns';
6110 : // 4. it does not need to be kept for LSNs holding valid leases.
6111 : // 5. newer on-disk image layers cover the layer's whole key range
6112 : //
6113 : // TODO holding a write lock is too agressive and avoidable
6114 8 : let mut guard = self.layers.write().await;
6115 8 : let layers = guard.layer_map()?;
6116 48 : 'outer: for l in layers.iter_historic_layers() {
6117 48 : result.layers_total += 1;
6118 48 :
6119 48 : // 1. Is it newer than GC horizon cutoff point?
6120 48 : if l.get_lsn_range().end > space_cutoff {
6121 4 : info!(
6122 0 : "keeping {} because it's newer than space_cutoff {}",
6123 0 : l.layer_name(),
6124 : space_cutoff,
6125 : );
6126 4 : result.layers_needed_by_cutoff += 1;
6127 4 : continue 'outer;
6128 44 : }
6129 44 :
6130 44 : // 2. It is newer than PiTR cutoff point?
6131 44 : if l.get_lsn_range().end > time_cutoff {
6132 0 : info!(
6133 0 : "keeping {} because it's newer than time_cutoff {}",
6134 0 : l.layer_name(),
6135 : time_cutoff,
6136 : );
6137 0 : result.layers_needed_by_pitr += 1;
6138 0 : continue 'outer;
6139 44 : }
6140 :
6141 : // 3. Is it needed by a child branch?
6142 : // NOTE With that we would keep data that
6143 : // might be referenced by child branches forever.
6144 : // We can track this in child timeline GC and delete parent layers when
6145 : // they are no longer needed. This might be complicated with long inheritance chains.
6146 : //
6147 : // TODO Vec is not a great choice for `retain_lsns`
6148 44 : for retain_lsn in &retain_lsns {
6149 : // start_lsn is inclusive
6150 0 : if &l.get_lsn_range().start <= retain_lsn {
6151 0 : info!(
6152 0 : "keeping {} because it's still might be referenced by child branch forked at {} is_dropped: xx is_incremental: {}",
6153 0 : l.layer_name(),
6154 0 : retain_lsn,
6155 0 : l.is_incremental(),
6156 : );
6157 0 : result.layers_needed_by_branches += 1;
6158 0 : continue 'outer;
6159 0 : }
6160 : }
6161 :
6162 : // 4. Is there a valid lease that requires us to keep this layer?
6163 44 : if let Some(lsn) = &max_lsn_with_valid_lease {
6164 : // keep if layer start <= any of the lease
6165 36 : if &l.get_lsn_range().start <= lsn {
6166 28 : info!(
6167 0 : "keeping {} because there is a valid lease preventing GC at {}",
6168 0 : l.layer_name(),
6169 : lsn,
6170 : );
6171 28 : result.layers_needed_by_leases += 1;
6172 28 : continue 'outer;
6173 8 : }
6174 8 : }
6175 :
6176 : // 5. Is there a later on-disk layer for this relation?
6177 : //
6178 : // The end-LSN is exclusive, while disk_consistent_lsn is
6179 : // inclusive. For example, if disk_consistent_lsn is 100, it is
6180 : // OK for a delta layer to have end LSN 101, but if the end LSN
6181 : // is 102, then it might not have been fully flushed to disk
6182 : // before crash.
6183 : //
6184 : // For example, imagine that the following layers exist:
6185 : //
6186 : // 1000 - image (A)
6187 : // 1000-2000 - delta (B)
6188 : // 2000 - image (C)
6189 : // 2000-3000 - delta (D)
6190 : // 3000 - image (E)
6191 : //
6192 : // If GC horizon is at 2500, we can remove layers A and B, but
6193 : // we cannot remove C, even though it's older than 2500, because
6194 : // the delta layer 2000-3000 depends on it.
6195 16 : if !layers
6196 16 : .image_layer_exists(&l.get_key_range(), &(l.get_lsn_range().end..new_gc_cutoff))
6197 : {
6198 12 : info!("keeping {} because it is the latest layer", l.layer_name());
6199 12 : result.layers_not_updated += 1;
6200 12 : continue 'outer;
6201 4 : }
6202 4 :
6203 4 : // We didn't find any reason to keep this file, so remove it.
6204 4 : info!(
6205 0 : "garbage collecting {} is_dropped: xx is_incremental: {}",
6206 0 : l.layer_name(),
6207 0 : l.is_incremental(),
6208 : );
6209 4 : layers_to_remove.push(l);
6210 : }
6211 :
6212 8 : if !layers_to_remove.is_empty() {
6213 : // Persist the new GC cutoff value before we actually remove anything.
6214 : // This unconditionally schedules also an index_part.json update, even though, we will
6215 : // be doing one a bit later with the unlinked gc'd layers.
6216 4 : let disk_consistent_lsn = self.disk_consistent_lsn.load();
6217 4 : self.schedule_uploads(disk_consistent_lsn, None)
6218 4 : .map_err(|e| {
6219 0 : if self.cancel.is_cancelled() {
6220 0 : GcError::TimelineCancelled
6221 : } else {
6222 0 : GcError::Remote(e)
6223 : }
6224 4 : })?;
6225 :
6226 4 : let gc_layers = layers_to_remove
6227 4 : .iter()
6228 4 : .map(|x| guard.get_from_desc(x))
6229 4 : .collect::<Vec<Layer>>();
6230 4 :
6231 4 : result.layers_removed = gc_layers.len() as u64;
6232 4 :
6233 4 : self.remote_client.schedule_gc_update(&gc_layers)?;
6234 :
6235 4 : guard.open_mut()?.finish_gc_timeline(&gc_layers);
6236 4 :
6237 4 : #[cfg(feature = "testing")]
6238 4 : {
6239 4 : result.doomed_layers = gc_layers;
6240 4 : }
6241 4 : }
6242 :
6243 8 : info!(
6244 0 : "GC completed removing {} layers, cutoff {}",
6245 : result.layers_removed, new_gc_cutoff
6246 : );
6247 :
6248 8 : result.elapsed = now.elapsed().unwrap_or(Duration::ZERO);
6249 8 : Ok(result)
6250 8 : }
6251 :
6252 : /// Reconstruct a value, using the given base image and WAL records in 'data'.
6253 1340140 : async fn reconstruct_value(
6254 1340140 : &self,
6255 1340140 : key: Key,
6256 1340140 : request_lsn: Lsn,
6257 1340140 : mut data: ValueReconstructState,
6258 1340140 : ) -> Result<Bytes, PageReconstructError> {
6259 1340140 : // Perform WAL redo if needed
6260 1340140 : data.records.reverse();
6261 1340140 :
6262 1340140 : // If we have a page image, and no WAL, we're all set
6263 1340140 : if data.records.is_empty() {
6264 1338464 : if let Some((img_lsn, img)) = &data.img {
6265 1338464 : trace!(
6266 0 : "found page image for key {} at {}, no WAL redo required, req LSN {}",
6267 : key, img_lsn, request_lsn,
6268 : );
6269 1338464 : Ok(img.clone())
6270 : } else {
6271 0 : Err(PageReconstructError::from(anyhow!(
6272 0 : "base image for {key} at {request_lsn} not found"
6273 0 : )))
6274 : }
6275 : } else {
6276 : // We need to do WAL redo.
6277 : //
6278 : // If we don't have a base image, then the oldest WAL record better initialize
6279 : // the page
6280 1676 : if data.img.is_none() && !data.records.first().unwrap().1.will_init() {
6281 0 : Err(PageReconstructError::from(anyhow!(
6282 0 : "Base image for {} at {} not found, but got {} WAL records",
6283 0 : key,
6284 0 : request_lsn,
6285 0 : data.records.len()
6286 0 : )))
6287 : } else {
6288 1676 : if data.img.is_some() {
6289 1536 : trace!(
6290 0 : "found {} WAL records and a base image for {} at {}, performing WAL redo",
6291 0 : data.records.len(),
6292 : key,
6293 : request_lsn
6294 : );
6295 : } else {
6296 140 : trace!(
6297 0 : "found {} WAL records that will init the page for {} at {}, performing WAL redo",
6298 0 : data.records.len(),
6299 : key,
6300 : request_lsn
6301 : );
6302 : };
6303 1676 : let res = self
6304 1676 : .walredo_mgr
6305 1676 : .as_ref()
6306 1676 : .context("timeline has no walredo manager")
6307 1676 : .map_err(PageReconstructError::WalRedo)?
6308 1676 : .request_redo(key, request_lsn, data.img, data.records, self.pg_version)
6309 1676 : .await;
6310 1676 : let img = match res {
6311 1676 : Ok(img) => img,
6312 0 : Err(walredo::Error::Cancelled) => return Err(PageReconstructError::Cancelled),
6313 0 : Err(walredo::Error::Other(err)) => {
6314 0 : critical!("walredo failure during page reconstruction: {err:?}");
6315 0 : return Err(PageReconstructError::WalRedo(
6316 0 : err.context("reconstruct a page image"),
6317 0 : ));
6318 : }
6319 : };
6320 1676 : Ok(img)
6321 : }
6322 : }
6323 1340140 : }
6324 :
6325 0 : pub(crate) async fn spawn_download_all_remote_layers(
6326 0 : self: Arc<Self>,
6327 0 : request: DownloadRemoteLayersTaskSpawnRequest,
6328 0 : ctx: &RequestContext,
6329 0 : ) -> Result<DownloadRemoteLayersTaskInfo, DownloadRemoteLayersTaskInfo> {
6330 : use pageserver_api::models::DownloadRemoteLayersTaskState;
6331 :
6332 : // this is not really needed anymore; it has tests which really check the return value from
6333 : // http api. it would be better not to maintain this anymore.
6334 :
6335 0 : let mut status_guard = self.download_all_remote_layers_task_info.write().unwrap();
6336 0 : if let Some(st) = &*status_guard {
6337 0 : match &st.state {
6338 : DownloadRemoteLayersTaskState::Running => {
6339 0 : return Err(st.clone());
6340 : }
6341 : DownloadRemoteLayersTaskState::ShutDown
6342 0 : | DownloadRemoteLayersTaskState::Completed => {
6343 0 : *status_guard = None;
6344 0 : }
6345 : }
6346 0 : }
6347 :
6348 0 : let self_clone = Arc::clone(&self);
6349 0 : let task_ctx = ctx.detached_child(
6350 0 : TaskKind::DownloadAllRemoteLayers,
6351 0 : DownloadBehavior::Download,
6352 0 : );
6353 0 : let task_id = task_mgr::spawn(
6354 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
6355 0 : task_mgr::TaskKind::DownloadAllRemoteLayers,
6356 0 : self.tenant_shard_id,
6357 0 : Some(self.timeline_id),
6358 0 : "download all remote layers task",
6359 0 : async move {
6360 0 : self_clone.download_all_remote_layers(request, &task_ctx).await;
6361 0 : let mut status_guard = self_clone.download_all_remote_layers_task_info.write().unwrap();
6362 0 : match &mut *status_guard {
6363 : None => {
6364 0 : warn!("tasks status is supposed to be Some(), since we are running");
6365 : }
6366 0 : Some(st) => {
6367 0 : let exp_task_id = format!("{}", task_mgr::current_task_id().unwrap());
6368 0 : if st.task_id != exp_task_id {
6369 0 : warn!("task id changed while we were still running, expecting {} but have {}", exp_task_id, st.task_id);
6370 0 : } else {
6371 0 : st.state = DownloadRemoteLayersTaskState::Completed;
6372 0 : }
6373 : }
6374 : };
6375 0 : Ok(())
6376 0 : }
6377 0 : .instrument(info_span!(parent: None, "download_all_remote_layers", tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id))
6378 : );
6379 :
6380 0 : let initial_info = DownloadRemoteLayersTaskInfo {
6381 0 : task_id: format!("{task_id}"),
6382 0 : state: DownloadRemoteLayersTaskState::Running,
6383 0 : total_layer_count: 0,
6384 0 : successful_download_count: 0,
6385 0 : failed_download_count: 0,
6386 0 : };
6387 0 : *status_guard = Some(initial_info.clone());
6388 0 :
6389 0 : Ok(initial_info)
6390 0 : }
6391 :
6392 0 : async fn download_all_remote_layers(
6393 0 : self: &Arc<Self>,
6394 0 : request: DownloadRemoteLayersTaskSpawnRequest,
6395 0 : ctx: &RequestContext,
6396 0 : ) {
6397 : use pageserver_api::models::DownloadRemoteLayersTaskState;
6398 :
6399 0 : let remaining = {
6400 0 : let guard = self.layers.read().await;
6401 0 : let Ok(lm) = guard.layer_map() else {
6402 : // technically here we could look into iterating accessible layers, but downloading
6403 : // all layers of a shutdown timeline makes no sense regardless.
6404 0 : tracing::info!("attempted to download all layers of shutdown timeline");
6405 0 : return;
6406 : };
6407 0 : lm.iter_historic_layers()
6408 0 : .map(|desc| guard.get_from_desc(&desc))
6409 0 : .collect::<Vec<_>>()
6410 0 : };
6411 0 : let total_layer_count = remaining.len();
6412 :
6413 : macro_rules! lock_status {
6414 : ($st:ident) => {
6415 : let mut st = self.download_all_remote_layers_task_info.write().unwrap();
6416 : let st = st
6417 : .as_mut()
6418 : .expect("this function is only called after the task has been spawned");
6419 : assert_eq!(
6420 : st.task_id,
6421 : format!(
6422 : "{}",
6423 : task_mgr::current_task_id().expect("we run inside a task_mgr task")
6424 : )
6425 : );
6426 : let $st = st;
6427 : };
6428 : }
6429 :
6430 : {
6431 0 : lock_status!(st);
6432 0 : st.total_layer_count = total_layer_count as u64;
6433 0 : }
6434 0 :
6435 0 : let mut remaining = remaining.into_iter();
6436 0 : let mut have_remaining = true;
6437 0 : let mut js = tokio::task::JoinSet::new();
6438 0 :
6439 0 : let cancel = task_mgr::shutdown_token();
6440 0 :
6441 0 : let limit = request.max_concurrent_downloads;
6442 :
6443 : loop {
6444 0 : while js.len() < limit.get() && have_remaining && !cancel.is_cancelled() {
6445 0 : let Some(next) = remaining.next() else {
6446 0 : have_remaining = false;
6447 0 : break;
6448 : };
6449 :
6450 0 : let span = tracing::info_span!("download", layer = %next);
6451 :
6452 0 : let ctx = ctx.attached_child();
6453 0 : js.spawn(
6454 0 : async move {
6455 0 : let res = next.download(&ctx).await;
6456 0 : (next, res)
6457 0 : }
6458 0 : .instrument(span),
6459 0 : );
6460 0 : }
6461 :
6462 0 : while let Some(res) = js.join_next().await {
6463 0 : match res {
6464 : Ok((_, Ok(_))) => {
6465 0 : lock_status!(st);
6466 0 : st.successful_download_count += 1;
6467 : }
6468 0 : Ok((layer, Err(e))) => {
6469 0 : tracing::error!(%layer, "download failed: {e:#}");
6470 0 : lock_status!(st);
6471 0 : st.failed_download_count += 1;
6472 : }
6473 0 : Err(je) if je.is_cancelled() => unreachable!("not used here"),
6474 0 : Err(je) if je.is_panic() => {
6475 0 : lock_status!(st);
6476 0 : st.failed_download_count += 1;
6477 : }
6478 0 : Err(je) => tracing::warn!("unknown joinerror: {je:?}"),
6479 : }
6480 : }
6481 :
6482 0 : if js.is_empty() && (!have_remaining || cancel.is_cancelled()) {
6483 0 : break;
6484 0 : }
6485 : }
6486 :
6487 : {
6488 0 : lock_status!(st);
6489 0 : st.state = DownloadRemoteLayersTaskState::Completed;
6490 : }
6491 0 : }
6492 :
6493 0 : pub(crate) fn get_download_all_remote_layers_task_info(
6494 0 : &self,
6495 0 : ) -> Option<DownloadRemoteLayersTaskInfo> {
6496 0 : self.download_all_remote_layers_task_info
6497 0 : .read()
6498 0 : .unwrap()
6499 0 : .clone()
6500 0 : }
6501 : }
6502 :
6503 : impl Timeline {
6504 : /// Returns non-remote layers for eviction.
6505 0 : pub(crate) async fn get_local_layers_for_disk_usage_eviction(&self) -> DiskUsageEvictionInfo {
6506 0 : let guard = self.layers.read().await;
6507 0 : let mut max_layer_size: Option<u64> = None;
6508 0 :
6509 0 : let resident_layers = guard
6510 0 : .likely_resident_layers()
6511 0 : .map(|layer| {
6512 0 : let file_size = layer.layer_desc().file_size;
6513 0 : max_layer_size = max_layer_size.map_or(Some(file_size), |m| Some(m.max(file_size)));
6514 0 :
6515 0 : let last_activity_ts = layer.latest_activity();
6516 0 :
6517 0 : EvictionCandidate {
6518 0 : layer: layer.to_owned().into(),
6519 0 : last_activity_ts,
6520 0 : relative_last_activity: finite_f32::FiniteF32::ZERO,
6521 0 : visibility: layer.visibility(),
6522 0 : }
6523 0 : })
6524 0 : .collect();
6525 0 :
6526 0 : DiskUsageEvictionInfo {
6527 0 : max_layer_size,
6528 0 : resident_layers,
6529 0 : }
6530 0 : }
6531 :
6532 3748 : pub(crate) fn get_shard_index(&self) -> ShardIndex {
6533 3748 : ShardIndex {
6534 3748 : shard_number: self.tenant_shard_id.shard_number,
6535 3748 : shard_count: self.tenant_shard_id.shard_count,
6536 3748 : }
6537 3748 : }
6538 :
6539 : /// Persistently blocks gc for `Manual` reason.
6540 : ///
6541 : /// Returns true if no such block existed before, false otherwise.
6542 0 : pub(crate) async fn block_gc(&self, tenant: &super::Tenant) -> anyhow::Result<bool> {
6543 : use crate::tenant::remote_timeline_client::index::GcBlockingReason;
6544 0 : assert_eq!(self.tenant_shard_id, tenant.tenant_shard_id);
6545 0 : tenant.gc_block.insert(self, GcBlockingReason::Manual).await
6546 0 : }
6547 :
6548 : /// Persistently unblocks gc for `Manual` reason.
6549 0 : pub(crate) async fn unblock_gc(&self, tenant: &super::Tenant) -> anyhow::Result<()> {
6550 : use crate::tenant::remote_timeline_client::index::GcBlockingReason;
6551 0 : assert_eq!(self.tenant_shard_id, tenant.tenant_shard_id);
6552 0 : tenant.gc_block.remove(self, GcBlockingReason::Manual).await
6553 0 : }
6554 :
6555 : #[cfg(test)]
6556 100 : pub(super) fn force_advance_lsn(self: &Arc<Timeline>, new_lsn: Lsn) {
6557 100 : self.last_record_lsn.advance(new_lsn);
6558 100 : }
6559 :
6560 : #[cfg(test)]
6561 4 : pub(super) fn force_set_disk_consistent_lsn(&self, new_value: Lsn) {
6562 4 : self.disk_consistent_lsn.store(new_value);
6563 4 : }
6564 :
6565 : /// Force create an image layer and place it into the layer map.
6566 : ///
6567 : /// DO NOT use this function directly. Use [`Tenant::branch_timeline_test_with_layers`]
6568 : /// or [`Tenant::create_test_timeline_with_layers`] to ensure all these layers are
6569 : /// placed into the layer map in one run AND be validated.
6570 : #[cfg(test)]
6571 128 : pub(super) async fn force_create_image_layer(
6572 128 : self: &Arc<Timeline>,
6573 128 : lsn: Lsn,
6574 128 : mut images: Vec<(Key, Bytes)>,
6575 128 : check_start_lsn: Option<Lsn>,
6576 128 : ctx: &RequestContext,
6577 128 : ) -> anyhow::Result<()> {
6578 128 : let last_record_lsn = self.get_last_record_lsn();
6579 128 : assert!(
6580 128 : lsn <= last_record_lsn,
6581 0 : "advance last record lsn before inserting a layer, lsn={lsn}, last_record_lsn={last_record_lsn}"
6582 : );
6583 128 : if let Some(check_start_lsn) = check_start_lsn {
6584 128 : assert!(lsn >= check_start_lsn);
6585 0 : }
6586 380 : images.sort_unstable_by(|(ka, _), (kb, _)| ka.cmp(kb));
6587 128 : let min_key = *images.first().map(|(k, _)| k).unwrap();
6588 128 : let end_key = images.last().map(|(k, _)| k).unwrap().next();
6589 128 : let mut image_layer_writer = ImageLayerWriter::new(
6590 128 : self.conf,
6591 128 : self.timeline_id,
6592 128 : self.tenant_shard_id,
6593 128 : &(min_key..end_key),
6594 128 : lsn,
6595 128 : ctx,
6596 128 : )
6597 128 : .await?;
6598 636 : for (key, img) in images {
6599 508 : image_layer_writer.put_image(key, img, ctx).await?;
6600 : }
6601 128 : let (desc, path) = image_layer_writer.finish(ctx).await?;
6602 128 : let image_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
6603 128 : info!("force created image layer {}", image_layer.local_path());
6604 : {
6605 128 : let mut guard = self.layers.write().await;
6606 128 : guard
6607 128 : .open_mut()
6608 128 : .unwrap()
6609 128 : .force_insert_layer(image_layer.clone());
6610 128 : }
6611 128 :
6612 128 : // Update remote_timeline_client state to reflect existence of this layer
6613 128 : self.remote_client
6614 128 : .schedule_layer_file_upload(image_layer)
6615 128 : .unwrap();
6616 128 :
6617 128 : Ok(())
6618 128 : }
6619 :
6620 : /// Force create a delta layer and place it into the layer map.
6621 : ///
6622 : /// DO NOT use this function directly. Use [`Tenant::branch_timeline_test_with_layers`]
6623 : /// or [`Tenant::create_test_timeline_with_layers`] to ensure all these layers are
6624 : /// placed into the layer map in one run AND be validated.
6625 : #[cfg(test)]
6626 184 : pub(super) async fn force_create_delta_layer(
6627 184 : self: &Arc<Timeline>,
6628 184 : mut deltas: DeltaLayerTestDesc,
6629 184 : check_start_lsn: Option<Lsn>,
6630 184 : ctx: &RequestContext,
6631 184 : ) -> anyhow::Result<()> {
6632 184 : let last_record_lsn = self.get_last_record_lsn();
6633 184 : deltas
6634 184 : .data
6635 264 : .sort_unstable_by(|(ka, la, _), (kb, lb, _)| (ka, la).cmp(&(kb, lb)));
6636 184 : assert!(deltas.data.first().unwrap().0 >= deltas.key_range.start);
6637 184 : assert!(deltas.data.last().unwrap().0 < deltas.key_range.end);
6638 632 : for (_, lsn, _) in &deltas.data {
6639 448 : assert!(deltas.lsn_range.start <= *lsn && *lsn < deltas.lsn_range.end);
6640 : }
6641 184 : assert!(
6642 184 : deltas.lsn_range.end <= last_record_lsn,
6643 0 : "advance last record lsn before inserting a layer, end_lsn={}, last_record_lsn={}",
6644 : deltas.lsn_range.end,
6645 : last_record_lsn
6646 : );
6647 184 : if let Some(check_start_lsn) = check_start_lsn {
6648 184 : assert!(deltas.lsn_range.start >= check_start_lsn);
6649 0 : }
6650 184 : let mut delta_layer_writer = DeltaLayerWriter::new(
6651 184 : self.conf,
6652 184 : self.timeline_id,
6653 184 : self.tenant_shard_id,
6654 184 : deltas.key_range.start,
6655 184 : deltas.lsn_range,
6656 184 : ctx,
6657 184 : )
6658 184 : .await?;
6659 632 : for (key, lsn, val) in deltas.data {
6660 448 : delta_layer_writer.put_value(key, lsn, val, ctx).await?;
6661 : }
6662 184 : let (desc, path) = delta_layer_writer.finish(deltas.key_range.end, ctx).await?;
6663 184 : let delta_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
6664 184 : info!("force created delta layer {}", delta_layer.local_path());
6665 : {
6666 184 : let mut guard = self.layers.write().await;
6667 184 : guard
6668 184 : .open_mut()
6669 184 : .unwrap()
6670 184 : .force_insert_layer(delta_layer.clone());
6671 184 : }
6672 184 :
6673 184 : // Update remote_timeline_client state to reflect existence of this layer
6674 184 : self.remote_client
6675 184 : .schedule_layer_file_upload(delta_layer)
6676 184 : .unwrap();
6677 184 :
6678 184 : Ok(())
6679 184 : }
6680 :
6681 : /// Force create an in-memory layer and place them into the layer map.
6682 : #[cfg(test)]
6683 8 : pub(super) async fn force_create_in_memory_layer(
6684 8 : self: &Arc<Timeline>,
6685 8 : mut in_memory: InMemoryLayerTestDesc,
6686 8 : check_start_lsn: Option<Lsn>,
6687 8 : ctx: &RequestContext,
6688 8 : ) -> anyhow::Result<()> {
6689 : use utils::bin_ser::BeSer;
6690 :
6691 : // Validate LSNs
6692 8 : if let Some(check_start_lsn) = check_start_lsn {
6693 8 : assert!(in_memory.lsn_range.start >= check_start_lsn);
6694 0 : }
6695 :
6696 8 : let last_record_lsn = self.get_last_record_lsn();
6697 8 : let layer_end_lsn = if in_memory.is_open {
6698 4 : in_memory
6699 4 : .data
6700 4 : .iter()
6701 40 : .map(|(_key, lsn, _value)| lsn)
6702 4 : .max()
6703 4 : .cloned()
6704 : } else {
6705 4 : Some(in_memory.lsn_range.end)
6706 : };
6707 :
6708 8 : if let Some(end) = layer_end_lsn {
6709 8 : assert!(
6710 8 : end <= last_record_lsn,
6711 0 : "advance last record lsn before inserting a layer, end_lsn={}, last_record_lsn={}",
6712 : end,
6713 : last_record_lsn,
6714 : );
6715 0 : }
6716 :
6717 80 : in_memory.data.iter().for_each(|(_key, lsn, _value)| {
6718 80 : assert!(*lsn >= in_memory.lsn_range.start);
6719 80 : assert!(*lsn < in_memory.lsn_range.end);
6720 80 : });
6721 8 :
6722 8 : // Build the batch
6723 8 : in_memory
6724 8 : .data
6725 72 : .sort_unstable_by(|(ka, la, _), (kb, lb, _)| (ka, la).cmp(&(kb, lb)));
6726 8 :
6727 8 : let data = in_memory
6728 8 : .data
6729 8 : .into_iter()
6730 80 : .map(|(key, lsn, value)| {
6731 80 : let value_size = value.serialized_size().unwrap() as usize;
6732 80 : (key.to_compact(), lsn, value_size, value)
6733 80 : })
6734 8 : .collect::<Vec<_>>();
6735 8 :
6736 8 : let batch = SerializedValueBatch::from_values(data);
6737 :
6738 : // Create the in-memory layer and write the batch into it
6739 8 : let layer = InMemoryLayer::create(
6740 8 : self.conf,
6741 8 : self.timeline_id,
6742 8 : self.tenant_shard_id,
6743 8 : in_memory.lsn_range.start,
6744 8 : &self.gate,
6745 8 : // TODO: if we ever use this function in production code, we need to pass the real cancellation token
6746 8 : &CancellationToken::new(),
6747 8 : ctx,
6748 8 : )
6749 8 : .await
6750 8 : .unwrap();
6751 8 :
6752 8 : layer.put_batch(batch, ctx).await.unwrap();
6753 8 : if !in_memory.is_open {
6754 4 : layer.freeze(in_memory.lsn_range.end).await;
6755 4 : }
6756 :
6757 8 : info!("force created in-memory layer {:?}", in_memory.lsn_range);
6758 :
6759 : // Link the layer to the layer map
6760 : {
6761 8 : let mut guard = self.layers.write().await;
6762 8 : let layer_map = guard.open_mut().unwrap();
6763 8 : layer_map.force_insert_in_memory_layer(Arc::new(layer));
6764 8 : }
6765 8 :
6766 8 : Ok(())
6767 8 : }
6768 :
6769 : /// Return all keys at the LSN in the image layers
6770 : #[cfg(test)]
6771 12 : pub(crate) async fn inspect_image_layers(
6772 12 : self: &Arc<Timeline>,
6773 12 : lsn: Lsn,
6774 12 : ctx: &RequestContext,
6775 12 : io_concurrency: IoConcurrency,
6776 12 : ) -> anyhow::Result<Vec<(Key, Bytes)>> {
6777 12 : let mut all_data = Vec::new();
6778 12 : let guard = self.layers.read().await;
6779 68 : for layer in guard.layer_map()?.iter_historic_layers() {
6780 68 : if !layer.is_delta() && layer.image_layer_lsn() == lsn {
6781 16 : let layer = guard.get_from_desc(&layer);
6782 16 : let mut reconstruct_data = ValuesReconstructState::new(io_concurrency.clone());
6783 16 : layer
6784 16 : .get_values_reconstruct_data(
6785 16 : KeySpace::single(Key::MIN..Key::MAX),
6786 16 : lsn..Lsn(lsn.0 + 1),
6787 16 : &mut reconstruct_data,
6788 16 : ctx,
6789 16 : )
6790 16 : .await?;
6791 132 : for (k, v) in std::mem::take(&mut reconstruct_data.keys) {
6792 132 : let v = v.collect_pending_ios().await?;
6793 132 : all_data.push((k, v.img.unwrap().1));
6794 : }
6795 52 : }
6796 : }
6797 12 : all_data.sort();
6798 12 : Ok(all_data)
6799 12 : }
6800 :
6801 : /// Get all historic layer descriptors in the layer map
6802 : #[cfg(test)]
6803 48 : pub(crate) async fn inspect_historic_layers(
6804 48 : self: &Arc<Timeline>,
6805 48 : ) -> anyhow::Result<Vec<super::storage_layer::PersistentLayerKey>> {
6806 48 : let mut layers = Vec::new();
6807 48 : let guard = self.layers.read().await;
6808 228 : for layer in guard.layer_map()?.iter_historic_layers() {
6809 228 : layers.push(layer.key());
6810 228 : }
6811 48 : Ok(layers)
6812 48 : }
6813 :
6814 : #[cfg(test)]
6815 20 : pub(crate) fn add_extra_test_dense_keyspace(&self, ks: KeySpace) {
6816 20 : let mut keyspace = self.extra_test_dense_keyspace.load().as_ref().clone();
6817 20 : keyspace.merge(&ks);
6818 20 : self.extra_test_dense_keyspace.store(Arc::new(keyspace));
6819 20 : }
6820 : }
6821 :
6822 : /// Tracking writes ingestion does to a particular in-memory layer.
6823 : ///
6824 : /// Cleared upon freezing a layer.
6825 : pub(crate) struct TimelineWriterState {
6826 : open_layer: Arc<InMemoryLayer>,
6827 : current_size: u64,
6828 : // Previous Lsn which passed through
6829 : prev_lsn: Option<Lsn>,
6830 : // Largest Lsn which passed through the current writer
6831 : max_lsn: Option<Lsn>,
6832 : // Cached details of the last freeze. Avoids going trough the atomic/lock on every put.
6833 : cached_last_freeze_at: Lsn,
6834 : }
6835 :
6836 : impl TimelineWriterState {
6837 2604 : fn new(open_layer: Arc<InMemoryLayer>, current_size: u64, last_freeze_at: Lsn) -> Self {
6838 2604 : Self {
6839 2604 : open_layer,
6840 2604 : current_size,
6841 2604 : prev_lsn: None,
6842 2604 : max_lsn: None,
6843 2604 : cached_last_freeze_at: last_freeze_at,
6844 2604 : }
6845 2604 : }
6846 : }
6847 :
6848 : /// Various functions to mutate the timeline.
6849 : // TODO Currently, Deref is used to allow easy access to read methods from this trait.
6850 : // This is probably considered a bad practice in Rust and should be fixed eventually,
6851 : // but will cause large code changes.
6852 : pub(crate) struct TimelineWriter<'a> {
6853 : tl: &'a Timeline,
6854 : write_guard: tokio::sync::MutexGuard<'a, Option<TimelineWriterState>>,
6855 : }
6856 :
6857 : impl Deref for TimelineWriter<'_> {
6858 : type Target = Timeline;
6859 :
6860 19796508 : fn deref(&self) -> &Self::Target {
6861 19796508 : self.tl
6862 19796508 : }
6863 : }
6864 :
6865 : #[derive(PartialEq)]
6866 : enum OpenLayerAction {
6867 : Roll,
6868 : Open,
6869 : None,
6870 : }
6871 :
6872 : impl TimelineWriter<'_> {
6873 9608476 : async fn handle_open_layer_action(
6874 9608476 : &mut self,
6875 9608476 : at: Lsn,
6876 9608476 : action: OpenLayerAction,
6877 9608476 : ctx: &RequestContext,
6878 9608476 : ) -> anyhow::Result<&Arc<InMemoryLayer>> {
6879 9608476 : match action {
6880 : OpenLayerAction::Roll => {
6881 160 : let freeze_at = self.write_guard.as_ref().unwrap().max_lsn.unwrap();
6882 160 : self.roll_layer(freeze_at).await?;
6883 160 : self.open_layer(at, ctx).await?;
6884 : }
6885 2444 : OpenLayerAction::Open => self.open_layer(at, ctx).await?,
6886 : OpenLayerAction::None => {
6887 9605872 : assert!(self.write_guard.is_some());
6888 : }
6889 : }
6890 :
6891 9608476 : Ok(&self.write_guard.as_ref().unwrap().open_layer)
6892 9608476 : }
6893 :
6894 2604 : async fn open_layer(&mut self, at: Lsn, ctx: &RequestContext) -> anyhow::Result<()> {
6895 2604 : let layer = self
6896 2604 : .tl
6897 2604 : .get_layer_for_write(at, &self.write_guard, ctx)
6898 2604 : .await?;
6899 2604 : let initial_size = layer.size().await?;
6900 :
6901 2604 : let last_freeze_at = self.last_freeze_at.load();
6902 2604 : self.write_guard.replace(TimelineWriterState::new(
6903 2604 : layer,
6904 2604 : initial_size,
6905 2604 : last_freeze_at,
6906 2604 : ));
6907 2604 :
6908 2604 : Ok(())
6909 2604 : }
6910 :
6911 160 : async fn roll_layer(&mut self, freeze_at: Lsn) -> Result<(), FlushLayerError> {
6912 160 : let current_size = self.write_guard.as_ref().unwrap().current_size;
6913 :
6914 : // If layer flushes are backpressured due to compaction not keeping up, wait for the flush
6915 : // to propagate the backpressure up into WAL ingestion.
6916 160 : let l0_count = self
6917 160 : .tl
6918 160 : .layers
6919 160 : .read()
6920 160 : .await
6921 160 : .layer_map()?
6922 160 : .level0_deltas()
6923 160 : .len();
6924 160 : let wait_thresholds = [
6925 160 : self.get_l0_flush_delay_threshold(),
6926 160 : self.get_l0_flush_stall_threshold(),
6927 160 : ];
6928 160 : let wait_threshold = wait_thresholds.into_iter().flatten().min();
6929 :
6930 : // self.write_guard will be taken by the freezing
6931 160 : let flush_id = self
6932 160 : .tl
6933 160 : .freeze_inmem_layer_at(freeze_at, &mut self.write_guard)
6934 160 : .await?;
6935 :
6936 160 : assert!(self.write_guard.is_none());
6937 :
6938 160 : if let Some(wait_threshold) = wait_threshold {
6939 0 : if l0_count >= wait_threshold {
6940 0 : debug!(
6941 0 : "layer roll waiting for flush due to compaction backpressure at {l0_count} L0 layers"
6942 : );
6943 0 : self.tl.wait_flush_completion(flush_id).await?;
6944 0 : }
6945 160 : }
6946 :
6947 160 : if current_size >= self.get_checkpoint_distance() * 2 {
6948 0 : warn!("Flushed oversized open layer with size {}", current_size)
6949 160 : }
6950 :
6951 160 : Ok(())
6952 160 : }
6953 :
6954 9608476 : fn get_open_layer_action(&self, lsn: Lsn, new_value_size: u64) -> OpenLayerAction {
6955 9608476 : let state = &*self.write_guard;
6956 9608476 : let Some(state) = &state else {
6957 2444 : return OpenLayerAction::Open;
6958 : };
6959 :
6960 : #[cfg(feature = "testing")]
6961 9606032 : if state.cached_last_freeze_at < self.tl.last_freeze_at.load() {
6962 : // this check and assertion are not really needed because
6963 : // LayerManager::try_freeze_in_memory_layer will always clear out the
6964 : // TimelineWriterState if something is frozen. however, we can advance last_freeze_at when there
6965 : // is no TimelineWriterState.
6966 0 : assert!(
6967 0 : state.open_layer.end_lsn.get().is_some(),
6968 0 : "our open_layer must be outdated"
6969 : );
6970 :
6971 : // this would be a memory leak waiting to happen because the in-memory layer always has
6972 : // an index
6973 0 : panic!("BUG: TimelineWriterState held on to frozen in-memory layer.");
6974 9606032 : }
6975 9606032 :
6976 9606032 : if state.prev_lsn == Some(lsn) {
6977 : // Rolling mid LSN is not supported by [downstream code].
6978 : // Hence, only roll at LSN boundaries.
6979 : //
6980 : // [downstream code]: https://github.com/neondatabase/neon/pull/7993#discussion_r1633345422
6981 12 : return OpenLayerAction::None;
6982 9606020 : }
6983 9606020 :
6984 9606020 : if state.current_size == 0 {
6985 : // Don't roll empty layers
6986 0 : return OpenLayerAction::None;
6987 9606020 : }
6988 9606020 :
6989 9606020 : if self.tl.should_roll(
6990 9606020 : state.current_size,
6991 9606020 : state.current_size + new_value_size,
6992 9606020 : self.get_checkpoint_distance(),
6993 9606020 : lsn,
6994 9606020 : state.cached_last_freeze_at,
6995 9606020 : state.open_layer.get_opened_at(),
6996 9606020 : ) {
6997 160 : OpenLayerAction::Roll
6998 : } else {
6999 9605860 : OpenLayerAction::None
7000 : }
7001 9608476 : }
7002 :
7003 : /// Put a batch of keys at the specified Lsns.
7004 9608472 : pub(crate) async fn put_batch(
7005 9608472 : &mut self,
7006 9608472 : batch: SerializedValueBatch,
7007 9608472 : ctx: &RequestContext,
7008 9608472 : ) -> anyhow::Result<()> {
7009 9608472 : if !batch.has_data() {
7010 0 : return Ok(());
7011 9608472 : }
7012 9608472 :
7013 9608472 : // In debug builds, assert that we don't write any keys that don't belong to this shard.
7014 9608472 : // We don't assert this in release builds, since key ownership policies may change over
7015 9608472 : // time. Stray keys will be removed during compaction.
7016 9608472 : if cfg!(debug_assertions) {
7017 19789888 : for metadata in &batch.metadata {
7018 10181416 : if let ValueMeta::Serialized(metadata) = metadata {
7019 10181416 : let key = Key::from_compact(metadata.key);
7020 10181416 : assert!(
7021 10181416 : self.shard_identity.is_key_local(&key)
7022 0 : || self.shard_identity.is_key_global(&key),
7023 0 : "key {key} does not belong on shard {}",
7024 0 : self.shard_identity.shard_index()
7025 : );
7026 0 : }
7027 : }
7028 0 : }
7029 :
7030 9608472 : let batch_max_lsn = batch.max_lsn;
7031 9608472 : let buf_size: u64 = batch.buffer_size() as u64;
7032 9608472 :
7033 9608472 : let action = self.get_open_layer_action(batch_max_lsn, buf_size);
7034 9608472 : let layer = self
7035 9608472 : .handle_open_layer_action(batch_max_lsn, action, ctx)
7036 9608472 : .await?;
7037 :
7038 9608472 : let res = layer.put_batch(batch, ctx).await;
7039 :
7040 9608472 : if res.is_ok() {
7041 9608472 : // Update the current size only when the entire write was ok.
7042 9608472 : // In case of failures, we may have had partial writes which
7043 9608472 : // render the size tracking out of sync. That's ok because
7044 9608472 : // the checkpoint distance should be significantly smaller
7045 9608472 : // than the S3 single shot upload limit of 5GiB.
7046 9608472 : let state = self.write_guard.as_mut().unwrap();
7047 9608472 :
7048 9608472 : state.current_size += buf_size;
7049 9608472 : state.prev_lsn = Some(batch_max_lsn);
7050 9608472 : state.max_lsn = std::cmp::max(state.max_lsn, Some(batch_max_lsn));
7051 9608472 : }
7052 :
7053 9608472 : res
7054 9608472 : }
7055 :
7056 : #[cfg(test)]
7057 : /// Test helper, for tests that would like to poke individual values without composing a batch
7058 8780308 : pub(crate) async fn put(
7059 8780308 : &mut self,
7060 8780308 : key: Key,
7061 8780308 : lsn: Lsn,
7062 8780308 : value: &Value,
7063 8780308 : ctx: &RequestContext,
7064 8780308 : ) -> anyhow::Result<()> {
7065 : use utils::bin_ser::BeSer;
7066 8780308 : if !key.is_valid_key_on_write_path() {
7067 0 : bail!(
7068 0 : "the request contains data not supported by pageserver at TimelineWriter::put: {}",
7069 0 : key
7070 0 : );
7071 8780308 : }
7072 8780308 : let val_ser_size = value.serialized_size().unwrap() as usize;
7073 8780308 : let batch = SerializedValueBatch::from_values(vec![(
7074 8780308 : key.to_compact(),
7075 8780308 : lsn,
7076 8780308 : val_ser_size,
7077 8780308 : value.clone(),
7078 8780308 : )]);
7079 8780308 :
7080 8780308 : self.put_batch(batch, ctx).await
7081 8780308 : }
7082 :
7083 4 : pub(crate) async fn delete_batch(
7084 4 : &mut self,
7085 4 : batch: &[(Range<Key>, Lsn)],
7086 4 : ctx: &RequestContext,
7087 4 : ) -> anyhow::Result<()> {
7088 4 : if let Some((_, lsn)) = batch.first() {
7089 4 : let action = self.get_open_layer_action(*lsn, 0);
7090 4 : let layer = self.handle_open_layer_action(*lsn, action, ctx).await?;
7091 4 : layer.put_tombstones(batch).await?;
7092 0 : }
7093 :
7094 4 : Ok(())
7095 4 : }
7096 :
7097 : /// Track the end of the latest digested WAL record.
7098 : /// Remember the (end of) last valid WAL record remembered in the timeline.
7099 : ///
7100 : /// Call this after you have finished writing all the WAL up to 'lsn'.
7101 : ///
7102 : /// 'lsn' must be aligned. This wakes up any wait_lsn() callers waiting for
7103 : /// the 'lsn' or anything older. The previous last record LSN is stored alongside
7104 : /// the latest and can be read.
7105 10558196 : pub(crate) fn finish_write(&self, new_lsn: Lsn) {
7106 10558196 : self.tl.finish_write(new_lsn);
7107 10558196 : }
7108 :
7109 541140 : pub(crate) fn update_current_logical_size(&self, delta: i64) {
7110 541140 : self.tl.update_current_logical_size(delta)
7111 541140 : }
7112 : }
7113 :
7114 : // We need TimelineWriter to be send in upcoming conversion of
7115 : // Timeline::layers to tokio::sync::RwLock.
7116 : #[test]
7117 4 : fn is_send() {
7118 4 : fn _assert_send<T: Send>() {}
7119 4 : _assert_send::<TimelineWriter<'_>>();
7120 4 : }
7121 :
7122 : #[cfg(test)]
7123 : mod tests {
7124 : use std::sync::Arc;
7125 :
7126 : use pageserver_api::key::Key;
7127 : use pageserver_api::value::Value;
7128 : use std::iter::Iterator;
7129 : use tracing::Instrument;
7130 : use utils::id::TimelineId;
7131 : use utils::lsn::Lsn;
7132 :
7133 : use super::HeatMapTimeline;
7134 : use crate::context::RequestContextBuilder;
7135 : use crate::tenant::harness::{TenantHarness, test_img};
7136 : use crate::tenant::layer_map::LayerMap;
7137 : use crate::tenant::storage_layer::{Layer, LayerName, LayerVisibilityHint};
7138 : use crate::tenant::timeline::{DeltaLayerTestDesc, EvictionError};
7139 : use crate::tenant::{PreviousHeatmap, Timeline};
7140 :
7141 20 : fn assert_heatmaps_have_same_layers(lhs: &HeatMapTimeline, rhs: &HeatMapTimeline) {
7142 20 : assert_eq!(lhs.all_layers().count(), rhs.all_layers().count());
7143 20 : let lhs_rhs = lhs.all_layers().zip(rhs.all_layers());
7144 100 : for (l, r) in lhs_rhs {
7145 80 : assert_eq!(l.name, r.name);
7146 80 : assert_eq!(l.metadata, r.metadata);
7147 : }
7148 20 : }
7149 :
7150 : #[tokio::test]
7151 4 : async fn test_heatmap_generation() {
7152 4 : let harness = TenantHarness::create("heatmap_generation").await.unwrap();
7153 4 :
7154 4 : let covered_delta = DeltaLayerTestDesc::new_with_inferred_key_range(
7155 4 : Lsn(0x10)..Lsn(0x20),
7156 4 : vec![(
7157 4 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
7158 4 : Lsn(0x11),
7159 4 : Value::Image(test_img("foo")),
7160 4 : )],
7161 4 : );
7162 4 : let visible_delta = DeltaLayerTestDesc::new_with_inferred_key_range(
7163 4 : Lsn(0x10)..Lsn(0x20),
7164 4 : vec![(
7165 4 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
7166 4 : Lsn(0x11),
7167 4 : Value::Image(test_img("foo")),
7168 4 : )],
7169 4 : );
7170 4 : let l0_delta = DeltaLayerTestDesc::new(
7171 4 : Lsn(0x20)..Lsn(0x30),
7172 4 : Key::from_hex("000000000000000000000000000000000000").unwrap()
7173 4 : ..Key::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(),
7174 4 : vec![(
7175 4 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
7176 4 : Lsn(0x25),
7177 4 : Value::Image(test_img("foo")),
7178 4 : )],
7179 4 : );
7180 4 : let delta_layers = vec![
7181 4 : covered_delta.clone(),
7182 4 : visible_delta.clone(),
7183 4 : l0_delta.clone(),
7184 4 : ];
7185 4 :
7186 4 : let image_layer = (
7187 4 : Lsn(0x40),
7188 4 : vec![(
7189 4 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
7190 4 : test_img("bar"),
7191 4 : )],
7192 4 : );
7193 4 : let image_layers = vec![image_layer];
7194 4 :
7195 4 : let (tenant, ctx) = harness.load().await;
7196 4 : let timeline = tenant
7197 4 : .create_test_timeline_with_layers(
7198 4 : TimelineId::generate(),
7199 4 : Lsn(0x10),
7200 4 : 14,
7201 4 : &ctx,
7202 4 : Vec::new(), // in-memory layers
7203 4 : delta_layers,
7204 4 : image_layers,
7205 4 : Lsn(0x100),
7206 4 : )
7207 4 : .await
7208 4 : .unwrap();
7209 4 : let ctx = &ctx.with_scope_timeline(&timeline);
7210 4 :
7211 4 : // Layer visibility is an input to heatmap generation, so refresh it first
7212 4 : timeline.update_layer_visibility().await.unwrap();
7213 4 :
7214 4 : let heatmap = timeline
7215 4 : .generate_heatmap()
7216 4 : .await
7217 4 : .expect("Infallible while timeline is not shut down");
7218 4 :
7219 4 : assert_eq!(heatmap.timeline_id, timeline.timeline_id);
7220 4 :
7221 4 : // L0 should come last
7222 4 : let heatmap_layers = heatmap.all_layers().collect::<Vec<_>>();
7223 4 : assert_eq!(heatmap_layers.last().unwrap().name, l0_delta.layer_name());
7224 4 :
7225 4 : let mut last_lsn = Lsn::MAX;
7226 20 : for layer in heatmap_layers {
7227 4 : // Covered layer should be omitted
7228 16 : assert!(layer.name != covered_delta.layer_name());
7229 4 :
7230 16 : let layer_lsn = match &layer.name {
7231 8 : LayerName::Delta(d) => d.lsn_range.end,
7232 8 : LayerName::Image(i) => i.lsn,
7233 4 : };
7234 4 :
7235 4 : // Apart from L0s, newest Layers should come first
7236 16 : if !LayerMap::is_l0(layer.name.key_range(), layer.name.is_delta()) {
7237 12 : assert!(layer_lsn <= last_lsn);
7238 12 : last_lsn = layer_lsn;
7239 4 : }
7240 4 : }
7241 4 :
7242 4 : // Evict all the layers and stash the old heatmap in the timeline.
7243 4 : // This simulates a migration to a cold secondary location.
7244 4 :
7245 4 : let guard = timeline.layers.read().await;
7246 4 : let mut all_layers = Vec::new();
7247 4 : let forever = std::time::Duration::from_secs(120);
7248 20 : for layer in guard.likely_resident_layers() {
7249 20 : all_layers.push(layer.clone());
7250 20 : layer.evict_and_wait(forever).await.unwrap();
7251 4 : }
7252 4 : drop(guard);
7253 4 :
7254 4 : timeline
7255 4 : .previous_heatmap
7256 4 : .store(Some(Arc::new(PreviousHeatmap::Active {
7257 4 : heatmap: heatmap.clone(),
7258 4 : read_at: std::time::Instant::now(),
7259 4 : end_lsn: None,
7260 4 : })));
7261 4 :
7262 4 : // Generate a new heatmap and assert that it contains the same layers as the old one.
7263 4 : let post_migration_heatmap = timeline.generate_heatmap().await.unwrap();
7264 4 : assert_heatmaps_have_same_layers(&heatmap, &post_migration_heatmap);
7265 4 :
7266 4 : // Download each layer one by one. Generate the heatmap at each step and check
7267 4 : // that it's stable.
7268 24 : for layer in all_layers {
7269 20 : if layer.visibility() == LayerVisibilityHint::Covered {
7270 4 : continue;
7271 16 : }
7272 16 :
7273 16 : eprintln!("Downloading {layer} and re-generating heatmap");
7274 16 :
7275 16 : let ctx = &RequestContextBuilder::extend(ctx)
7276 16 : .download_behavior(crate::context::DownloadBehavior::Download)
7277 16 : .build();
7278 4 :
7279 16 : let _resident = layer
7280 16 : .download_and_keep_resident(ctx)
7281 16 : .instrument(tracing::info_span!(
7282 16 : parent: None,
7283 4 : "download_layer",
7284 4 : tenant_id = %timeline.tenant_shard_id.tenant_id,
7285 0 : shard_id = %timeline.tenant_shard_id.shard_slug(),
7286 0 : timeline_id = %timeline.timeline_id
7287 4 : ))
7288 16 : .await
7289 16 : .unwrap();
7290 4 :
7291 16 : let post_download_heatmap = timeline.generate_heatmap().await.unwrap();
7292 16 : assert_heatmaps_have_same_layers(&heatmap, &post_download_heatmap);
7293 4 : }
7294 4 :
7295 4 : // Everything from the post-migration heatmap is now resident.
7296 4 : // Check that we drop it from memory.
7297 4 : assert!(matches!(
7298 4 : timeline.previous_heatmap.load().as_deref(),
7299 4 : Some(PreviousHeatmap::Obsolete)
7300 4 : ));
7301 4 : }
7302 :
7303 : #[tokio::test]
7304 4 : async fn test_previous_heatmap_obsoletion() {
7305 4 : let harness = TenantHarness::create("heatmap_previous_heatmap_obsoletion")
7306 4 : .await
7307 4 : .unwrap();
7308 4 :
7309 4 : let l0_delta = DeltaLayerTestDesc::new(
7310 4 : Lsn(0x20)..Lsn(0x30),
7311 4 : Key::from_hex("000000000000000000000000000000000000").unwrap()
7312 4 : ..Key::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(),
7313 4 : vec![(
7314 4 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
7315 4 : Lsn(0x25),
7316 4 : Value::Image(test_img("foo")),
7317 4 : )],
7318 4 : );
7319 4 :
7320 4 : let image_layer = (
7321 4 : Lsn(0x40),
7322 4 : vec![(
7323 4 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
7324 4 : test_img("bar"),
7325 4 : )],
7326 4 : );
7327 4 :
7328 4 : let delta_layers = vec![l0_delta];
7329 4 : let image_layers = vec![image_layer];
7330 4 :
7331 4 : let (tenant, ctx) = harness.load().await;
7332 4 : let timeline = tenant
7333 4 : .create_test_timeline_with_layers(
7334 4 : TimelineId::generate(),
7335 4 : Lsn(0x10),
7336 4 : 14,
7337 4 : &ctx,
7338 4 : Vec::new(), // in-memory layers
7339 4 : delta_layers,
7340 4 : image_layers,
7341 4 : Lsn(0x100),
7342 4 : )
7343 4 : .await
7344 4 : .unwrap();
7345 4 :
7346 4 : // Layer visibility is an input to heatmap generation, so refresh it first
7347 4 : timeline.update_layer_visibility().await.unwrap();
7348 4 :
7349 4 : let heatmap = timeline
7350 4 : .generate_heatmap()
7351 4 : .await
7352 4 : .expect("Infallible while timeline is not shut down");
7353 4 :
7354 4 : // Both layers should be in the heatmap
7355 4 : assert!(heatmap.all_layers().count() > 0);
7356 4 :
7357 4 : // Now simulate a migration.
7358 4 : timeline
7359 4 : .previous_heatmap
7360 4 : .store(Some(Arc::new(PreviousHeatmap::Active {
7361 4 : heatmap: heatmap.clone(),
7362 4 : read_at: std::time::Instant::now(),
7363 4 : end_lsn: None,
7364 4 : })));
7365 4 :
7366 4 : // Evict all the layers in the previous heatmap
7367 4 : let guard = timeline.layers.read().await;
7368 4 : let forever = std::time::Duration::from_secs(120);
7369 12 : for layer in guard.likely_resident_layers() {
7370 12 : layer.evict_and_wait(forever).await.unwrap();
7371 4 : }
7372 4 : drop(guard);
7373 4 :
7374 4 : // Generate a new heatmap and check that the previous heatmap
7375 4 : // has been marked obsolete.
7376 4 : let post_eviction_heatmap = timeline
7377 4 : .generate_heatmap()
7378 4 : .await
7379 4 : .expect("Infallible while timeline is not shut down");
7380 4 :
7381 4 : assert_eq!(post_eviction_heatmap.all_layers().count(), 0);
7382 4 : assert!(matches!(
7383 4 : timeline.previous_heatmap.load().as_deref(),
7384 4 : Some(PreviousHeatmap::Obsolete)
7385 4 : ));
7386 4 : }
7387 :
7388 : #[tokio::test]
7389 4 : async fn two_layer_eviction_attempts_at_the_same_time() {
7390 4 : let harness = TenantHarness::create("two_layer_eviction_attempts_at_the_same_time")
7391 4 : .await
7392 4 : .unwrap();
7393 4 :
7394 4 : let (tenant, ctx) = harness.load().await;
7395 4 : let timeline = tenant
7396 4 : .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
7397 4 : .await
7398 4 : .unwrap();
7399 4 :
7400 4 : let layer = find_some_layer(&timeline).await;
7401 4 : let layer = layer
7402 4 : .keep_resident()
7403 4 : .await
7404 4 : .expect("no download => no downloading errors")
7405 4 : .drop_eviction_guard();
7406 4 :
7407 4 : let forever = std::time::Duration::from_secs(120);
7408 4 :
7409 4 : let first = layer.evict_and_wait(forever);
7410 4 : let second = layer.evict_and_wait(forever);
7411 4 :
7412 4 : let (first, second) = tokio::join!(first, second);
7413 4 :
7414 4 : let res = layer.keep_resident().await;
7415 4 : assert!(res.is_none(), "{res:?}");
7416 4 :
7417 4 : match (first, second) {
7418 4 : (Ok(()), Ok(())) => {
7419 4 : // because there are no more timeline locks being taken on eviction path, we can
7420 4 : // witness all three outcomes here.
7421 4 : }
7422 4 : (Ok(()), Err(EvictionError::NotFound)) | (Err(EvictionError::NotFound), Ok(())) => {
7423 0 : // if one completes before the other, this is fine just as well.
7424 0 : }
7425 4 : other => unreachable!("unexpected {:?}", other),
7426 4 : }
7427 4 : }
7428 :
7429 4 : async fn find_some_layer(timeline: &Timeline) -> Layer {
7430 4 : let layers = timeline.layers.read().await;
7431 4 : let desc = layers
7432 4 : .layer_map()
7433 4 : .unwrap()
7434 4 : .iter_historic_layers()
7435 4 : .next()
7436 4 : .expect("must find one layer to evict");
7437 4 :
7438 4 : layers.get_from_desc(&desc)
7439 4 : }
7440 : }
|