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::RemoteTimelineClient;
88 : use super::remote_timeline_client::index::{GcCompactionState, IndexPart};
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 1149 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 1149 : write!(f, "{:?}", self)
172 1149 : }
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 1205 : fn drop_wlock<T>(rlock: tokio::sync::RwLockWriteGuard<'_, T>) {
184 1205 : drop(rlock)
185 1205 : }
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 612 : pub(crate) fn min_cutoff(&self) -> Lsn {
489 612 : self.cutoffs.select_min()
490 612 : }
491 :
492 476 : pub(super) fn insert_child(
493 476 : &mut self,
494 476 : child_id: TimelineId,
495 476 : child_lsn: Lsn,
496 476 : is_offloaded: MaybeOffloaded,
497 476 : ) {
498 476 : self.retain_lsns.push((child_lsn, child_id, is_offloaded));
499 476 : self.retain_lsns.sort_by_key(|i| i.0);
500 476 : }
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 476 : pub(crate) fn lsn_covered_by_lease(&self, lsn: Lsn) -> bool {
529 476 : self.leases.contains_key(&lsn)
530 476 : }
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 920 : fn default() -> Self {
549 920 : Self {
550 920 : space: Lsn::INVALID,
551 920 : time: Lsn::INVALID,
552 920 : }
553 920 : }
554 : }
555 :
556 : impl GcCutoffs {
557 612 : fn select_min(&self) -> Lsn {
558 612 : std::cmp::min(self.space, self.time)
559 612 : }
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 1255445 : pub fn new(keyspace: KeySpace, lsn: Lsn) -> Self {
647 1255445 : Self {
648 1255445 : keyspace,
649 1255445 : lsn,
650 1255445 : path: Vec::new(),
651 1255445 : }
652 1255445 : }
653 :
654 1694134 : pub fn record_layer_visit(
655 1694134 : &mut self,
656 1694134 : layer_to_read: &ReadableLayer,
657 1694134 : keyspace_to_read: &KeySpace,
658 1694134 : lsn_range: &Range<Lsn>,
659 1694134 : ) {
660 1694134 : let id = match layer_to_read {
661 480752 : ReadableLayer::PersistentLayer(layer) => {
662 480752 : ReadPathLayerId::PersistentLayer(layer.layer_desc().key())
663 : }
664 1213382 : ReadableLayer::InMemoryLayer(layer) => {
665 1213382 : ReadPathLayerId::InMemoryLayer(layer.get_lsn_range())
666 : }
667 : };
668 1694134 : self.path
669 1694134 : .push((id, keyspace_to_read.clone(), lsn_range.clone()));
670 1694134 : }
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 88 : pub(crate) fn get_ancestor_lsn(&self) -> Lsn {
1044 88 : self.ancestor_lsn
1045 88 : }
1046 :
1047 : /// Get the ancestor's timeline id
1048 152 : pub(crate) fn get_ancestor_timeline_id(&self) -> Option<TimelineId> {
1049 152 : self.ancestor_timeline
1050 152 : .as_ref()
1051 152 : .map(|ancestor| ancestor.timeline_id)
1052 152 : }
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 1706547 : pub(crate) fn get_applied_gc_cutoff_lsn(&self) -> RcuReadGuard<Lsn> {
1073 1706547 : self.applied_gc_cutoff_lsn.read()
1074 1706547 : }
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 1215241 : pub(crate) async fn get(
1101 1215241 : &self,
1102 1215241 : key: Key,
1103 1215241 : lsn: Lsn,
1104 1215241 : ctx: &RequestContext,
1105 1215241 : ) -> Result<Bytes, PageReconstructError> {
1106 1215241 : if !lsn.is_valid() {
1107 0 : return Err(PageReconstructError::Other(anyhow::anyhow!("Invalid LSN")));
1108 1215241 : }
1109 1215241 :
1110 1215241 : // This check is debug-only because of the cost of hashing, and because it's a double-check: we
1111 1215241 : // already checked the key against the shard_identity when looking up the Timeline from
1112 1215241 : // page_service.
1113 1215241 : debug_assert!(!self.shard_identity.is_key_disposable(&key));
1114 :
1115 1215241 : let keyspace = KeySpace {
1116 1215241 : ranges: vec![key..key.next()],
1117 1215241 : };
1118 1215241 :
1119 1215241 : let mut reconstruct_state = ValuesReconstructState::new(IoConcurrency::sequential());
1120 :
1121 1215241 : let vectored_res = self
1122 1215241 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
1123 1215241 : .await;
1124 :
1125 1215241 : let key_value = vectored_res?.pop_first();
1126 1215229 : match key_value {
1127 1215205 : Some((got_key, value)) => {
1128 1215205 : 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 1215205 : 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 1215241 : }
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 39456 : pub(crate) async fn get_vectored(
1160 39456 : &self,
1161 39456 : keyspace: KeySpace,
1162 39456 : lsn: Lsn,
1163 39456 : io_concurrency: super::storage_layer::IoConcurrency,
1164 39456 : ctx: &RequestContext,
1165 39456 : ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
1166 39456 : if !lsn.is_valid() {
1167 0 : return Err(GetVectoredError::InvalidLsn(lsn));
1168 39456 : }
1169 39456 :
1170 39456 : let key_count = keyspace.total_raw_size().try_into().unwrap();
1171 39456 : if key_count > Timeline::MAX_GET_VECTORED_KEYS {
1172 0 : return Err(GetVectoredError::Oversized(key_count));
1173 39456 : }
1174 :
1175 78912 : for range in &keyspace.ranges {
1176 39456 : let mut key = range.start;
1177 79432 : while key != range.end {
1178 39976 : assert!(!self.shard_identity.is_key_disposable(&key));
1179 39976 : key = key.next();
1180 : }
1181 : }
1182 :
1183 39456 : trace!(
1184 0 : "get vectored request for {:?}@{} from task kind {:?}",
1185 0 : keyspace,
1186 0 : lsn,
1187 0 : ctx.task_kind(),
1188 : );
1189 :
1190 39456 : let start = crate::metrics::GET_VECTORED_LATENCY
1191 39456 : .for_task_kind(ctx.task_kind())
1192 39456 : .map(|metric| (metric, Instant::now()));
1193 :
1194 39456 : let res = self
1195 39456 : .get_vectored_impl(
1196 39456 : keyspace.clone(),
1197 39456 : lsn,
1198 39456 : &mut ValuesReconstructState::new(io_concurrency),
1199 39456 : ctx,
1200 39456 : )
1201 39456 : .await;
1202 :
1203 39456 : if let Some((metric, start)) = start {
1204 0 : let elapsed = start.elapsed();
1205 0 : metric.observe(elapsed.as_secs_f64());
1206 39456 : }
1207 :
1208 39456 : res
1209 39456 : }
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 1255445 : pub(super) async fn get_vectored_impl(
1268 1255445 : &self,
1269 1255445 : keyspace: KeySpace,
1270 1255445 : lsn: Lsn,
1271 1255445 : reconstruct_state: &mut ValuesReconstructState,
1272 1255445 : ctx: &RequestContext,
1273 1255445 : ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
1274 1255445 : let read_path = if self.conf.enable_read_path_debugging || ctx.read_path_debug() {
1275 1255445 : Some(ReadPath::new(keyspace.clone(), lsn))
1276 : } else {
1277 0 : None
1278 : };
1279 1255445 : reconstruct_state.read_path = read_path;
1280 :
1281 1255445 : let traversal_res: Result<(), _> = self
1282 1255445 : .get_vectored_reconstruct_data(keyspace.clone(), lsn, reconstruct_state, ctx)
1283 1255445 : .await;
1284 1255445 : 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 1255413 : };
1294 1255413 :
1295 1255413 : let layers_visited = reconstruct_state.get_layers_visited();
1296 1255413 :
1297 1255413 : let futs = FuturesUnordered::new();
1298 1336117 : for (key, state) in std::mem::take(&mut reconstruct_state.keys) {
1299 1336117 : futs.push({
1300 1336117 : let walredo_self = self.myself.upgrade().expect("&self method holds the arc");
1301 1336117 : async move {
1302 1336117 : assert_eq!(state.situation, ValueReconstructSituation::Complete);
1303 :
1304 1336117 : let converted = match state.collect_pending_ios().await {
1305 1336117 : Ok(ok) => ok,
1306 0 : Err(err) => {
1307 0 : return (key, Err(err));
1308 : }
1309 : };
1310 1336117 : DELTAS_PER_READ_GLOBAL.observe(converted.num_deltas() as f64);
1311 1336117 :
1312 1336117 : // The walredo module expects the records to be descending in terms of Lsn.
1313 1336117 : // And we submit the IOs in that order, so, there shuold be no need to sort here.
1314 1336117 : debug_assert!(
1315 1336117 : converted
1316 1336117 : .records
1317 1336117 : .is_sorted_by_key(|(lsn, _)| std::cmp::Reverse(*lsn)),
1318 0 : "{converted:?}"
1319 : );
1320 :
1321 : (
1322 1336117 : key,
1323 1336117 : walredo_self.reconstruct_value(key, lsn, converted).await,
1324 : )
1325 1336117 : }
1326 1336117 : });
1327 1336117 : }
1328 :
1329 1255413 : let results = futs
1330 1255413 : .collect::<BTreeMap<Key, Result<Bytes, PageReconstructError>>>()
1331 1255413 : .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 1255413 : if !results.is_empty() {
1338 1254917 : 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 1254917 : }
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 1254917 : let layers_visited = layers_visited as f64;
1363 1254917 : let avg_layers_visited = layers_visited / results.len() as f64;
1364 1254917 : LAYERS_PER_READ_BATCH_GLOBAL.observe(layers_visited);
1365 2591034 : for _ in &results {
1366 1336117 : self.metrics.layers_per_read.observe(layers_visited);
1367 1336117 : LAYERS_PER_READ_GLOBAL.observe(layers_visited);
1368 1336117 : LAYERS_PER_READ_AMORTIZED_GLOBAL.observe(avg_layers_visited);
1369 1336117 : }
1370 496 : }
1371 :
1372 1255413 : Ok(results)
1373 1255445 : }
1374 :
1375 : /// Get last or prev record separately. Same as get_last_record_rlsn().last/prev.
1376 549062 : pub(crate) fn get_last_record_lsn(&self) -> Lsn {
1377 549062 : self.last_record_lsn.load().last
1378 549062 : }
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 468 : pub(crate) fn get_last_record_rlsn(&self) -> RecordLsn {
1386 468 : self.last_record_lsn.load()
1387 468 : }
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 912 : pub(crate) fn get_disk_consistent_lsn(&self) -> Lsn {
1396 912 : self.disk_consistent_lsn.load()
1397 912 : }
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 450454 : pub(crate) async fn wait_lsn(
1436 450454 : &self,
1437 450454 : lsn: Lsn,
1438 450454 : who_is_waiting: WaitLsnWaiter<'_>,
1439 450454 : timeout: WaitLsnTimeout,
1440 450454 : ctx: &RequestContext, /* Prepare for use by cancellation */
1441 450454 : ) -> Result<(), WaitLsnError> {
1442 450454 : let state = self.current_state();
1443 450454 : if self.cancel.is_cancelled() || matches!(state, TimelineState::Stopping) {
1444 0 : return Err(WaitLsnError::Shutdown);
1445 450454 : } else if !matches!(state, TimelineState::Active) {
1446 0 : return Err(WaitLsnError::BadState(state));
1447 450454 : }
1448 450454 :
1449 450454 : if cfg!(debug_assertions) {
1450 450454 : 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 450454 : _ => {}
1478 : }
1479 0 : }
1480 :
1481 450454 : let timeout = match timeout {
1482 0 : WaitLsnTimeout::Custom(t) => t,
1483 450454 : WaitLsnTimeout::Default => self.conf.wait_lsn_timeout,
1484 : };
1485 :
1486 450454 : let timer = crate::metrics::WAIT_LSN_TIME.start_timer();
1487 450454 : let start_finish_counterpair_guard = self.metrics.wait_lsn_start_finish_counterpair.guard();
1488 450454 :
1489 450454 : let wait_for_timeout = self.last_record_lsn.wait_for_timeout(lsn, timeout);
1490 450454 : let wait_for_timeout = std::pin::pin!(wait_for_timeout);
1491 450454 : // Use threshold of 1 because even 1 second of wait for ingest is very much abnormal.
1492 450454 : let log_slow_threshold = Duration::from_secs(1);
1493 450454 : // Use period of 10 to avoid flooding logs during an outage that affects all timelines.
1494 450454 : let log_slow_period = Duration::from_secs(10);
1495 450454 : let mut logging_permit = None;
1496 450454 : let wait_for_timeout = monitor_slow_future(
1497 450454 : log_slow_threshold,
1498 450454 : log_slow_period,
1499 450454 : wait_for_timeout,
1500 450454 : |MonitorSlowFutureCallback {
1501 : ready,
1502 : is_slow,
1503 : elapsed_total,
1504 : elapsed_since_last_callback,
1505 450454 : }| {
1506 450454 : self.metrics
1507 450454 : .wait_lsn_in_progress_micros
1508 450454 : .inc_by(u64::try_from(elapsed_since_last_callback.as_micros()).unwrap());
1509 450454 : if !is_slow {
1510 450454 : 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 450454 : },
1534 450454 : );
1535 450454 : 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 450454 : drop(logging_permit);
1538 450454 : drop(start_finish_counterpair_guard);
1539 450454 : drop(timer);
1540 450454 : match res {
1541 450454 : 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 450454 : }
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 476 : pub(crate) fn check_lsn_is_in_scope(
1573 476 : &self,
1574 476 : lsn: Lsn,
1575 476 : latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
1576 476 : ) -> anyhow::Result<()> {
1577 476 : ensure!(
1578 476 : 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 468 : Ok(())
1584 476 : }
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 2256 : pub(crate) async fn freeze0(&self) -> Result<u64, FlushLayerError> {
1699 2256 : let mut g = self.write_lock.lock().await;
1700 2256 : let to_lsn = self.get_last_record_lsn();
1701 2256 : self.freeze_inmem_layer_at(to_lsn, &mut g).await
1702 2256 : }
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 2256 : pub(crate) async fn freeze_and_flush0(&self) -> Result<(), FlushLayerError> {
1707 2256 : let token = self.freeze0().await?;
1708 2256 : self.wait_flush_completion(token).await
1709 2256 : }
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 10266396 : pub(crate) async fn writer(&self) -> TimelineWriter<'_> {
1967 10266396 : TimelineWriter {
1968 10266396 : tl: self,
1969 10266396 : write_guard: self.write_lock.lock().await,
1970 : }
1971 10266396 : }
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 924 : pub(crate) fn set_state(&self, new_state: TimelineState) {
2163 924 : match (self.current_state(), new_state) {
2164 924 : (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 920 : (_, new_state) => {
2177 920 : self.state.send_replace(new_state);
2178 920 : }
2179 : }
2180 924 : }
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 452615 : pub(crate) fn current_state(&self) -> TimelineState {
2197 452615 : self.state.borrow().clone()
2198 452615 : }
2199 :
2200 12 : pub(crate) fn is_broken(&self) -> bool {
2201 12 : matches!(&*self.state.borrow(), TimelineState::Broken { .. })
2202 12 : }
2203 :
2204 504 : pub(crate) fn is_active(&self) -> bool {
2205 504 : self.current_state() == TimelineState::Active
2206 504 : }
2207 :
2208 32 : pub(crate) fn is_archived(&self) -> Option<bool> {
2209 32 : self.remote_client.is_archived()
2210 32 : }
2211 :
2212 32 : pub(crate) fn is_invisible(&self) -> Option<bool> {
2213 32 : self.remote_client.is_invisible()
2214 32 : }
2215 :
2216 733 : pub(crate) fn is_stopping(&self) -> bool {
2217 733 : self.current_state() == TimelineState::Stopping
2218 733 : }
2219 :
2220 0 : pub(crate) fn subscribe_for_state_updates(&self) -> watch::Receiver<TimelineState> {
2221 0 : self.state.subscribe()
2222 0 : }
2223 :
2224 450458 : pub(crate) async fn wait_to_become_active(
2225 450458 : &self,
2226 450458 : _ctx: &RequestContext, // Prepare for use by cancellation
2227 450458 : ) -> Result<(), TimelineState> {
2228 450458 : let mut receiver = self.state.subscribe();
2229 : loop {
2230 450458 : let current_state = receiver.borrow().clone();
2231 450458 : match current_state {
2232 : TimelineState::Loading => {
2233 0 : receiver
2234 0 : .changed()
2235 0 : .await
2236 0 : .expect("holding a reference to self");
2237 : }
2238 : TimelineState::Active { .. } => {
2239 450454 : return Ok(());
2240 : }
2241 : TimelineState::Broken { .. } | TimelineState::Stopping => {
2242 : // There's no chance the timeline can transition back into ::Active
2243 4 : return Err(current_state);
2244 : }
2245 : }
2246 : }
2247 450458 : }
2248 :
2249 0 : pub(crate) async fn layer_map_info(
2250 0 : &self,
2251 0 : reset: LayerAccessStatsReset,
2252 0 : ) -> Result<LayerMapInfo, layer_manager::Shutdown> {
2253 0 : let guard = self.layers.read().await;
2254 0 : let layer_map = guard.layer_map()?;
2255 0 : let mut in_memory_layers = Vec::with_capacity(layer_map.frozen_layers.len() + 1);
2256 0 : if let Some(open_layer) = &layer_map.open_layer {
2257 0 : in_memory_layers.push(open_layer.info());
2258 0 : }
2259 0 : for frozen_layer in &layer_map.frozen_layers {
2260 0 : in_memory_layers.push(frozen_layer.info());
2261 0 : }
2262 :
2263 0 : let historic_layers = layer_map
2264 0 : .iter_historic_layers()
2265 0 : .map(|desc| guard.get_from_desc(&desc).info(reset))
2266 0 : .collect();
2267 0 :
2268 0 : Ok(LayerMapInfo {
2269 0 : in_memory_layers,
2270 0 : historic_layers,
2271 0 : })
2272 0 : }
2273 :
2274 : #[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))]
2275 : pub(crate) async fn download_layer(
2276 : &self,
2277 : layer_file_name: &LayerName,
2278 : ctx: &RequestContext,
2279 : ) -> Result<Option<bool>, super::storage_layer::layer::DownloadError> {
2280 : let Some(layer) = self
2281 : .find_layer(layer_file_name)
2282 : .await
2283 0 : .map_err(|e| match e {
2284 0 : layer_manager::Shutdown => {
2285 0 : super::storage_layer::layer::DownloadError::TimelineShutdown
2286 0 : }
2287 0 : })?
2288 : else {
2289 : return Ok(None);
2290 : };
2291 :
2292 : layer.download(ctx).await?;
2293 :
2294 : Ok(Some(true))
2295 : }
2296 :
2297 : /// Evict just one layer.
2298 : ///
2299 : /// Returns `Ok(None)` in the case where the layer could not be found by its `layer_file_name`.
2300 0 : pub(crate) async fn evict_layer(
2301 0 : &self,
2302 0 : layer_file_name: &LayerName,
2303 0 : ) -> anyhow::Result<Option<bool>> {
2304 0 : let _gate = self
2305 0 : .gate
2306 0 : .enter()
2307 0 : .map_err(|_| anyhow::anyhow!("Shutting down"))?;
2308 :
2309 0 : let Some(local_layer) = self.find_layer(layer_file_name).await? else {
2310 0 : return Ok(None);
2311 : };
2312 :
2313 : // curl has this by default
2314 0 : let timeout = std::time::Duration::from_secs(120);
2315 0 :
2316 0 : match local_layer.evict_and_wait(timeout).await {
2317 0 : Ok(()) => Ok(Some(true)),
2318 0 : Err(EvictionError::NotFound) => Ok(Some(false)),
2319 0 : Err(EvictionError::Downloaded) => Ok(Some(false)),
2320 0 : Err(EvictionError::Timeout) => Ok(Some(false)),
2321 : }
2322 0 : }
2323 :
2324 9606020 : fn should_roll(
2325 9606020 : &self,
2326 9606020 : layer_size: u64,
2327 9606020 : projected_layer_size: u64,
2328 9606020 : checkpoint_distance: u64,
2329 9606020 : projected_lsn: Lsn,
2330 9606020 : last_freeze_at: Lsn,
2331 9606020 : opened_at: Instant,
2332 9606020 : ) -> bool {
2333 9606020 : let distance = projected_lsn.widening_sub(last_freeze_at);
2334 9606020 :
2335 9606020 : // Rolling the open layer can be triggered by:
2336 9606020 : // 1. The distance from the last LSN we rolled at. This bounds the amount of WAL that
2337 9606020 : // the safekeepers need to store. For sharded tenants, we multiply by shard count to
2338 9606020 : // account for how writes are distributed across shards: we expect each node to consume
2339 9606020 : // 1/count of the LSN on average.
2340 9606020 : // 2. The size of the currently open layer.
2341 9606020 : // 3. The time since the last roll. It helps safekeepers to regard pageserver as caught
2342 9606020 : // up and suspend activity.
2343 9606020 : if distance >= checkpoint_distance as i128 * self.shard_identity.count.count() as i128 {
2344 0 : info!(
2345 0 : "Will roll layer at {} with layer size {} due to LSN distance ({})",
2346 : projected_lsn, layer_size, distance
2347 : );
2348 :
2349 0 : true
2350 9606020 : } else if projected_layer_size >= checkpoint_distance {
2351 : // NB: this check is relied upon by:
2352 160 : let _ = IndexEntry::validate_checkpoint_distance;
2353 160 : info!(
2354 0 : "Will roll layer at {} with layer size {} due to layer size ({})",
2355 : projected_lsn, layer_size, projected_layer_size
2356 : );
2357 :
2358 160 : true
2359 9605860 : } else if distance > 0 && opened_at.elapsed() >= self.get_checkpoint_timeout() {
2360 0 : info!(
2361 0 : "Will roll layer at {} with layer size {} due to time since first write to the layer ({:?})",
2362 0 : projected_lsn,
2363 0 : layer_size,
2364 0 : opened_at.elapsed()
2365 : );
2366 :
2367 0 : true
2368 : } else {
2369 9605860 : false
2370 : }
2371 9606020 : }
2372 : }
2373 :
2374 : /// Number of times we will compute partition within a checkpoint distance.
2375 : const REPARTITION_FREQ_IN_CHECKPOINT_DISTANCE: u64 = 10;
2376 :
2377 : // Private functions
2378 : impl Timeline {
2379 24 : pub(crate) fn get_lsn_lease_length(&self) -> Duration {
2380 24 : let tenant_conf = self.tenant_conf.load();
2381 24 : tenant_conf
2382 24 : .tenant_conf
2383 24 : .lsn_lease_length
2384 24 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
2385 24 : }
2386 :
2387 0 : pub(crate) fn get_lsn_lease_length_for_ts(&self) -> Duration {
2388 0 : let tenant_conf = self.tenant_conf.load();
2389 0 : tenant_conf
2390 0 : .tenant_conf
2391 0 : .lsn_lease_length_for_ts
2392 0 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length_for_ts)
2393 0 : }
2394 :
2395 0 : pub(crate) fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
2396 0 : let tenant_conf = self.tenant_conf.load();
2397 0 : tenant_conf.is_gc_blocked_by_lsn_lease_deadline()
2398 0 : }
2399 :
2400 0 : pub(crate) fn get_lazy_slru_download(&self) -> bool {
2401 0 : let tenant_conf = self.tenant_conf.load();
2402 0 : tenant_conf
2403 0 : .tenant_conf
2404 0 : .lazy_slru_download
2405 0 : .unwrap_or(self.conf.default_tenant_conf.lazy_slru_download)
2406 0 : }
2407 :
2408 9609030 : fn get_checkpoint_distance(&self) -> u64 {
2409 9609030 : let tenant_conf = self.tenant_conf.load();
2410 9609030 : tenant_conf
2411 9609030 : .tenant_conf
2412 9609030 : .checkpoint_distance
2413 9609030 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
2414 9609030 : }
2415 :
2416 9605860 : fn get_checkpoint_timeout(&self) -> Duration {
2417 9605860 : let tenant_conf = self.tenant_conf.load();
2418 9605860 : tenant_conf
2419 9605860 : .tenant_conf
2420 9605860 : .checkpoint_timeout
2421 9605860 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
2422 9605860 : }
2423 :
2424 5040 : fn get_compaction_period(&self) -> Duration {
2425 5040 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2426 5040 : tenant_conf
2427 5040 : .compaction_period
2428 5040 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
2429 5040 : }
2430 :
2431 1337 : fn get_compaction_target_size(&self) -> u64 {
2432 1337 : let tenant_conf = self.tenant_conf.load();
2433 1337 : tenant_conf
2434 1337 : .tenant_conf
2435 1337 : .compaction_target_size
2436 1337 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
2437 1337 : }
2438 :
2439 3149 : fn get_compaction_threshold(&self) -> usize {
2440 3149 : let tenant_conf = self.tenant_conf.load();
2441 3149 : tenant_conf
2442 3149 : .tenant_conf
2443 3149 : .compaction_threshold
2444 3149 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
2445 3149 : }
2446 :
2447 : /// Returns `true` if the rel_size_v2 config is enabled. NOTE: the write path and read path
2448 : /// should look at `get_rel_size_v2_status()` to get the actual status of the timeline. It is
2449 : /// possible that the index part persists the state while the config doesn't get persisted.
2450 3892 : pub(crate) fn get_rel_size_v2_enabled(&self) -> bool {
2451 3892 : let tenant_conf = self.tenant_conf.load();
2452 3892 : tenant_conf
2453 3892 : .tenant_conf
2454 3892 : .rel_size_v2_enabled
2455 3892 : .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
2456 3892 : }
2457 :
2458 4396 : pub(crate) fn get_rel_size_v2_status(&self) -> RelSizeMigration {
2459 4396 : self.rel_size_v2_status
2460 4396 : .load()
2461 4396 : .as_ref()
2462 4396 : .map(|s| s.as_ref().clone())
2463 4396 : .unwrap_or(RelSizeMigration::Legacy)
2464 4396 : }
2465 :
2466 56 : fn get_compaction_upper_limit(&self) -> usize {
2467 56 : let tenant_conf = self.tenant_conf.load();
2468 56 : tenant_conf
2469 56 : .tenant_conf
2470 56 : .compaction_upper_limit
2471 56 : .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
2472 56 : }
2473 :
2474 728 : pub fn get_compaction_l0_first(&self) -> bool {
2475 728 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2476 728 : tenant_conf
2477 728 : .compaction_l0_first
2478 728 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
2479 728 : }
2480 :
2481 0 : pub fn get_compaction_l0_semaphore(&self) -> bool {
2482 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2483 0 : tenant_conf
2484 0 : .compaction_l0_semaphore
2485 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_semaphore)
2486 0 : }
2487 :
2488 2520 : fn get_l0_flush_delay_threshold(&self) -> Option<usize> {
2489 : // By default, delay L0 flushes at 3x the compaction threshold. The compaction threshold
2490 : // defaults to 10, and L0 compaction is generally able to keep L0 counts below 30.
2491 : const DEFAULT_L0_FLUSH_DELAY_FACTOR: usize = 3;
2492 :
2493 : // If compaction is disabled, don't delay.
2494 2520 : if self.get_compaction_period() == Duration::ZERO {
2495 2516 : return None;
2496 4 : }
2497 4 :
2498 4 : let compaction_threshold = self.get_compaction_threshold();
2499 4 : let tenant_conf = self.tenant_conf.load();
2500 4 : let l0_flush_delay_threshold = tenant_conf
2501 4 : .tenant_conf
2502 4 : .l0_flush_delay_threshold
2503 4 : .or(self.conf.default_tenant_conf.l0_flush_delay_threshold)
2504 4 : .unwrap_or(DEFAULT_L0_FLUSH_DELAY_FACTOR * compaction_threshold);
2505 4 :
2506 4 : // 0 disables backpressure.
2507 4 : if l0_flush_delay_threshold == 0 {
2508 0 : return None;
2509 4 : }
2510 4 :
2511 4 : // Clamp the flush delay threshold to the compaction threshold; it doesn't make sense to
2512 4 : // backpressure flushes below this.
2513 4 : // TODO: the tenant config should have validation to prevent this instead.
2514 4 : debug_assert!(l0_flush_delay_threshold >= compaction_threshold);
2515 4 : Some(max(l0_flush_delay_threshold, compaction_threshold))
2516 2520 : }
2517 :
2518 2520 : fn get_l0_flush_stall_threshold(&self) -> Option<usize> {
2519 : // Disable L0 stalls by default. Stalling can cause unavailability if L0 compaction isn't
2520 : // responsive, and it can e.g. block on other compaction via the compaction semaphore or
2521 : // sibling timelines. We need more confidence before enabling this.
2522 : const DEFAULT_L0_FLUSH_STALL_FACTOR: usize = 0; // TODO: default to e.g. 5
2523 :
2524 : // If compaction is disabled, don't stall.
2525 2520 : if self.get_compaction_period() == Duration::ZERO {
2526 2516 : return None;
2527 4 : }
2528 4 :
2529 4 : // If compaction is failing, don't stall and try to keep the tenant alive. This may not be a
2530 4 : // good idea: read amp can grow unbounded, leading to terrible performance, and we may take
2531 4 : // on unbounded compaction debt that can take a long time to fix once compaction comes back
2532 4 : // online. At least we'll delay flushes, slowing down the growth and buying some time.
2533 4 : if self.compaction_failed.load(AtomicOrdering::Relaxed) {
2534 0 : return None;
2535 4 : }
2536 4 :
2537 4 : let compaction_threshold = self.get_compaction_threshold();
2538 4 : let tenant_conf = self.tenant_conf.load();
2539 4 : let l0_flush_stall_threshold = tenant_conf
2540 4 : .tenant_conf
2541 4 : .l0_flush_stall_threshold
2542 4 : .or(self.conf.default_tenant_conf.l0_flush_stall_threshold);
2543 4 :
2544 4 : // Tests sometimes set compaction_threshold=1 to generate lots of layer files, and don't
2545 4 : // handle the 20-second compaction delay. Some (e.g. `test_backward_compatibility`) can't
2546 4 : // easily adjust the L0 backpressure settings, so just disable stalls in this case.
2547 4 : if cfg!(feature = "testing")
2548 4 : && compaction_threshold == 1
2549 0 : && l0_flush_stall_threshold.is_none()
2550 : {
2551 0 : return None;
2552 4 : }
2553 4 :
2554 4 : let l0_flush_stall_threshold = l0_flush_stall_threshold
2555 4 : .unwrap_or(DEFAULT_L0_FLUSH_STALL_FACTOR * compaction_threshold);
2556 4 :
2557 4 : // 0 disables backpressure.
2558 4 : if l0_flush_stall_threshold == 0 {
2559 4 : return None;
2560 0 : }
2561 0 :
2562 0 : // Clamp the flush stall threshold to the compaction threshold; it doesn't make sense to
2563 0 : // backpressure flushes below this.
2564 0 : // TODO: the tenant config should have validation to prevent this instead.
2565 0 : debug_assert!(l0_flush_stall_threshold >= compaction_threshold);
2566 0 : Some(max(l0_flush_stall_threshold, compaction_threshold))
2567 2520 : }
2568 :
2569 28 : fn get_image_creation_threshold(&self) -> usize {
2570 28 : let tenant_conf = self.tenant_conf.load();
2571 28 : tenant_conf
2572 28 : .tenant_conf
2573 28 : .image_creation_threshold
2574 28 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
2575 28 : }
2576 :
2577 725 : fn get_compaction_algorithm_settings(&self) -> CompactionAlgorithmSettings {
2578 725 : let tenant_conf = &self.tenant_conf.load();
2579 725 : tenant_conf
2580 725 : .tenant_conf
2581 725 : .compaction_algorithm
2582 725 : .as_ref()
2583 725 : .unwrap_or(&self.conf.default_tenant_conf.compaction_algorithm)
2584 725 : .clone()
2585 725 : }
2586 :
2587 0 : fn get_eviction_policy(&self) -> EvictionPolicy {
2588 0 : let tenant_conf = self.tenant_conf.load();
2589 0 : tenant_conf
2590 0 : .tenant_conf
2591 0 : .eviction_policy
2592 0 : .unwrap_or(self.conf.default_tenant_conf.eviction_policy)
2593 0 : }
2594 :
2595 920 : fn get_evictions_low_residence_duration_metric_threshold(
2596 920 : tenant_conf: &pageserver_api::models::TenantConfig,
2597 920 : default_tenant_conf: &pageserver_api::config::TenantConfigToml,
2598 920 : ) -> Duration {
2599 920 : tenant_conf
2600 920 : .evictions_low_residence_duration_metric_threshold
2601 920 : .unwrap_or(default_tenant_conf.evictions_low_residence_duration_metric_threshold)
2602 920 : }
2603 :
2604 1149 : fn get_image_layer_creation_check_threshold(&self) -> u8 {
2605 1149 : let tenant_conf = self.tenant_conf.load();
2606 1149 : tenant_conf
2607 1149 : .tenant_conf
2608 1149 : .image_layer_creation_check_threshold
2609 1149 : .unwrap_or(
2610 1149 : self.conf
2611 1149 : .default_tenant_conf
2612 1149 : .image_layer_creation_check_threshold,
2613 1149 : )
2614 1149 : }
2615 :
2616 0 : fn get_gc_compaction_settings(&self) -> GcCompactionCombinedSettings {
2617 0 : let tenant_conf = &self.tenant_conf.load();
2618 0 : let gc_compaction_enabled = tenant_conf
2619 0 : .tenant_conf
2620 0 : .gc_compaction_enabled
2621 0 : .unwrap_or(self.conf.default_tenant_conf.gc_compaction_enabled);
2622 0 : let gc_compaction_initial_threshold_kb = tenant_conf
2623 0 : .tenant_conf
2624 0 : .gc_compaction_initial_threshold_kb
2625 0 : .unwrap_or(
2626 0 : self.conf
2627 0 : .default_tenant_conf
2628 0 : .gc_compaction_initial_threshold_kb,
2629 0 : );
2630 0 : let gc_compaction_ratio_percent = tenant_conf
2631 0 : .tenant_conf
2632 0 : .gc_compaction_ratio_percent
2633 0 : .unwrap_or(self.conf.default_tenant_conf.gc_compaction_ratio_percent);
2634 0 : GcCompactionCombinedSettings {
2635 0 : gc_compaction_enabled,
2636 0 : gc_compaction_initial_threshold_kb,
2637 0 : gc_compaction_ratio_percent,
2638 0 : }
2639 0 : }
2640 :
2641 0 : fn get_image_creation_preempt_threshold(&self) -> usize {
2642 0 : let tenant_conf = self.tenant_conf.load();
2643 0 : tenant_conf
2644 0 : .tenant_conf
2645 0 : .image_creation_preempt_threshold
2646 0 : .unwrap_or(
2647 0 : self.conf
2648 0 : .default_tenant_conf
2649 0 : .image_creation_preempt_threshold,
2650 0 : )
2651 0 : }
2652 :
2653 : /// Resolve the effective WAL receiver protocol to use for this tenant.
2654 : ///
2655 : /// Priority order is:
2656 : /// 1. Tenant config override
2657 : /// 2. Default value for tenant config override
2658 : /// 3. Pageserver config override
2659 : /// 4. Pageserver config default
2660 0 : pub fn resolve_wal_receiver_protocol(&self) -> PostgresClientProtocol {
2661 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2662 0 : tenant_conf
2663 0 : .wal_receiver_protocol_override
2664 0 : .or(self.conf.default_tenant_conf.wal_receiver_protocol_override)
2665 0 : .unwrap_or(self.conf.wal_receiver_protocol)
2666 0 : }
2667 :
2668 0 : pub(super) fn tenant_conf_updated(&self, new_conf: &AttachedTenantConf) {
2669 0 : // NB: Most tenant conf options are read by background loops, so,
2670 0 : // changes will automatically be picked up.
2671 0 :
2672 0 : // The threshold is embedded in the metric. So, we need to update it.
2673 0 : {
2674 0 : let new_threshold = Self::get_evictions_low_residence_duration_metric_threshold(
2675 0 : &new_conf.tenant_conf,
2676 0 : &self.conf.default_tenant_conf,
2677 0 : );
2678 0 :
2679 0 : let tenant_id_str = self.tenant_shard_id.tenant_id.to_string();
2680 0 : let shard_id_str = format!("{}", self.tenant_shard_id.shard_slug());
2681 0 :
2682 0 : let timeline_id_str = self.timeline_id.to_string();
2683 0 :
2684 0 : self.remote_client.update_config(&new_conf.location);
2685 0 :
2686 0 : self.metrics
2687 0 : .evictions_with_low_residence_duration
2688 0 : .write()
2689 0 : .unwrap()
2690 0 : .change_threshold(
2691 0 : &tenant_id_str,
2692 0 : &shard_id_str,
2693 0 : &timeline_id_str,
2694 0 : new_threshold,
2695 0 : );
2696 0 : }
2697 0 : }
2698 :
2699 : /// Open a Timeline handle.
2700 : ///
2701 : /// Loads the metadata for the timeline into memory, but not the layer map.
2702 : #[allow(clippy::too_many_arguments)]
2703 920 : pub(super) fn new(
2704 920 : conf: &'static PageServerConf,
2705 920 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
2706 920 : metadata: &TimelineMetadata,
2707 920 : previous_heatmap: Option<PreviousHeatmap>,
2708 920 : ancestor: Option<Arc<Timeline>>,
2709 920 : timeline_id: TimelineId,
2710 920 : tenant_shard_id: TenantShardId,
2711 920 : generation: Generation,
2712 920 : shard_identity: ShardIdentity,
2713 920 : walredo_mgr: Option<Arc<super::WalRedoManager>>,
2714 920 : resources: TimelineResources,
2715 920 : pg_version: u32,
2716 920 : state: TimelineState,
2717 920 : attach_wal_lag_cooldown: Arc<OnceLock<WalLagCooldown>>,
2718 920 : create_idempotency: crate::tenant::CreateTimelineIdempotency,
2719 920 : gc_compaction_state: Option<GcCompactionState>,
2720 920 : rel_size_v2_status: Option<RelSizeMigration>,
2721 920 : cancel: CancellationToken,
2722 920 : ) -> Arc<Self> {
2723 920 : let disk_consistent_lsn = metadata.disk_consistent_lsn();
2724 920 : let (state, _) = watch::channel(state);
2725 920 :
2726 920 : let (layer_flush_start_tx, _) = tokio::sync::watch::channel((0, disk_consistent_lsn));
2727 920 : let (layer_flush_done_tx, _) = tokio::sync::watch::channel((0, Ok(())));
2728 920 :
2729 920 : let evictions_low_residence_duration_metric_threshold = {
2730 920 : let loaded_tenant_conf = tenant_conf.load();
2731 920 : Self::get_evictions_low_residence_duration_metric_threshold(
2732 920 : &loaded_tenant_conf.tenant_conf,
2733 920 : &conf.default_tenant_conf,
2734 920 : )
2735 : };
2736 :
2737 920 : if let Some(ancestor) = &ancestor {
2738 472 : let mut ancestor_gc_info = ancestor.gc_info.write().unwrap();
2739 472 : // If we construct an explicit timeline object, it's obviously not offloaded
2740 472 : let is_offloaded = MaybeOffloaded::No;
2741 472 : ancestor_gc_info.insert_child(timeline_id, metadata.ancestor_lsn(), is_offloaded);
2742 472 : }
2743 :
2744 920 : Arc::new_cyclic(|myself| {
2745 920 : let metrics = Arc::new(TimelineMetrics::new(
2746 920 : &tenant_shard_id,
2747 920 : &timeline_id,
2748 920 : crate::metrics::EvictionsWithLowResidenceDurationBuilder::new(
2749 920 : "mtime",
2750 920 : evictions_low_residence_duration_metric_threshold,
2751 920 : ),
2752 920 : ));
2753 920 : let aux_file_metrics = metrics.aux_file_size_gauge.clone();
2754 :
2755 920 : let mut result = Timeline {
2756 920 : conf,
2757 920 : tenant_conf,
2758 920 : myself: myself.clone(),
2759 920 : timeline_id,
2760 920 : tenant_shard_id,
2761 920 : generation,
2762 920 : shard_identity,
2763 920 : pg_version,
2764 920 : layers: Default::default(),
2765 920 : gc_compaction_layer_update_lock: tokio::sync::RwLock::new(()),
2766 920 :
2767 920 : walredo_mgr,
2768 920 : walreceiver: Mutex::new(None),
2769 920 :
2770 920 : remote_client: Arc::new(resources.remote_client),
2771 920 :
2772 920 : // initialize in-memory 'last_record_lsn' from 'disk_consistent_lsn'.
2773 920 : last_record_lsn: SeqWait::new(RecordLsn {
2774 920 : last: disk_consistent_lsn,
2775 920 : prev: metadata.prev_record_lsn().unwrap_or(Lsn(0)),
2776 920 : }),
2777 920 : disk_consistent_lsn: AtomicLsn::new(disk_consistent_lsn.0),
2778 920 :
2779 920 : gc_compaction_state: ArcSwap::new(Arc::new(gc_compaction_state)),
2780 920 :
2781 920 : last_freeze_at: AtomicLsn::new(disk_consistent_lsn.0),
2782 920 : last_freeze_ts: RwLock::new(Instant::now()),
2783 920 :
2784 920 : loaded_at: (disk_consistent_lsn, SystemTime::now()),
2785 920 :
2786 920 : ancestor_timeline: ancestor,
2787 920 : ancestor_lsn: metadata.ancestor_lsn(),
2788 920 :
2789 920 : metrics,
2790 920 :
2791 920 : query_metrics: crate::metrics::SmgrQueryTimePerTimeline::new(
2792 920 : &tenant_shard_id,
2793 920 : &timeline_id,
2794 920 : resources.pagestream_throttle_metrics,
2795 920 : ),
2796 920 :
2797 7360 : directory_metrics: array::from_fn(|_| AtomicU64::new(0)),
2798 7360 : directory_metrics_inited: array::from_fn(|_| AtomicBool::new(false)),
2799 920 :
2800 920 : flush_loop_state: Mutex::new(FlushLoopState::NotStarted),
2801 920 :
2802 920 : layer_flush_start_tx,
2803 920 : layer_flush_done_tx,
2804 920 :
2805 920 : write_lock: tokio::sync::Mutex::new(None),
2806 920 :
2807 920 : gc_info: std::sync::RwLock::new(GcInfo::default()),
2808 920 :
2809 920 : last_image_layer_creation_status: ArcSwap::new(Arc::new(
2810 920 : LastImageLayerCreationStatus::default(),
2811 920 : )),
2812 920 :
2813 920 : applied_gc_cutoff_lsn: Rcu::new(metadata.latest_gc_cutoff_lsn()),
2814 920 : initdb_lsn: metadata.initdb_lsn(),
2815 920 :
2816 920 : current_logical_size: if disk_consistent_lsn.is_valid() {
2817 : // we're creating timeline data with some layer files existing locally,
2818 : // need to recalculate timeline's logical size based on data in the layers.
2819 480 : LogicalSize::deferred_initial(disk_consistent_lsn)
2820 : } else {
2821 : // we're creating timeline data without any layers existing locally,
2822 : // initial logical size is 0.
2823 440 : LogicalSize::empty_initial()
2824 : },
2825 :
2826 920 : partitioning: GuardArcSwap::new((
2827 920 : (KeyPartitioning::new(), KeyPartitioning::new().into_sparse()),
2828 920 : Lsn(0),
2829 920 : )),
2830 920 : repartition_threshold: 0,
2831 920 : last_image_layer_creation_check_at: AtomicLsn::new(0),
2832 920 : last_image_layer_creation_check_instant: Mutex::new(None),
2833 920 :
2834 920 : last_received_wal: Mutex::new(None),
2835 920 : rel_size_cache: RwLock::new(RelSizeCache {
2836 920 : complete_as_of: disk_consistent_lsn,
2837 920 : map: HashMap::new(),
2838 920 : }),
2839 920 :
2840 920 : download_all_remote_layers_task_info: RwLock::new(None),
2841 920 :
2842 920 : state,
2843 920 :
2844 920 : eviction_task_timeline_state: tokio::sync::Mutex::new(
2845 920 : EvictionTaskTimelineState::default(),
2846 920 : ),
2847 920 : delete_progress: TimelineDeleteProgress::default(),
2848 920 :
2849 920 : cancel,
2850 920 : gate: Gate::default(),
2851 920 :
2852 920 : compaction_lock: tokio::sync::Mutex::default(),
2853 920 : compaction_failed: AtomicBool::default(),
2854 920 : l0_compaction_trigger: resources.l0_compaction_trigger,
2855 920 : gc_lock: tokio::sync::Mutex::default(),
2856 920 :
2857 920 : standby_horizon: AtomicLsn::new(0),
2858 920 :
2859 920 : pagestream_throttle: resources.pagestream_throttle,
2860 920 :
2861 920 : aux_file_size_estimator: AuxFileSizeEstimator::new(aux_file_metrics),
2862 920 :
2863 920 : #[cfg(test)]
2864 920 : extra_test_dense_keyspace: ArcSwap::new(Arc::new(KeySpace::default())),
2865 920 :
2866 920 : l0_flush_global_state: resources.l0_flush_global_state,
2867 920 :
2868 920 : handles: Default::default(),
2869 920 :
2870 920 : attach_wal_lag_cooldown,
2871 920 :
2872 920 : create_idempotency,
2873 920 :
2874 920 : page_trace: Default::default(),
2875 920 :
2876 920 : previous_heatmap: ArcSwapOption::from_pointee(previous_heatmap),
2877 920 :
2878 920 : heatmap_layers_downloader: Mutex::new(None),
2879 920 :
2880 920 : rel_size_v2_status: ArcSwapOption::from_pointee(rel_size_v2_status),
2881 920 :
2882 920 : wait_lsn_log_slow: tokio::sync::Semaphore::new(1),
2883 920 : };
2884 920 :
2885 920 : result.repartition_threshold =
2886 920 : result.get_checkpoint_distance() / REPARTITION_FREQ_IN_CHECKPOINT_DISTANCE;
2887 920 :
2888 920 : result
2889 920 : .metrics
2890 920 : .last_record_lsn_gauge
2891 920 : .set(disk_consistent_lsn.0 as i64);
2892 920 : result
2893 920 : })
2894 920 : }
2895 :
2896 1332 : pub(super) fn maybe_spawn_flush_loop(self: &Arc<Self>) {
2897 1332 : let Ok(guard) = self.gate.enter() else {
2898 0 : info!("cannot start flush loop when the timeline gate has already been closed");
2899 0 : return;
2900 : };
2901 1332 : let mut flush_loop_state = self.flush_loop_state.lock().unwrap();
2902 1332 : match *flush_loop_state {
2903 908 : FlushLoopState::NotStarted => (),
2904 : FlushLoopState::Running { .. } => {
2905 424 : info!(
2906 0 : "skipping attempt to start flush_loop twice {}/{}",
2907 0 : self.tenant_shard_id, self.timeline_id
2908 : );
2909 424 : return;
2910 : }
2911 : FlushLoopState::Exited => {
2912 0 : info!(
2913 0 : "ignoring attempt to restart exited flush_loop {}/{}",
2914 0 : self.tenant_shard_id, self.timeline_id
2915 : );
2916 0 : return;
2917 : }
2918 : }
2919 :
2920 908 : let layer_flush_start_rx = self.layer_flush_start_tx.subscribe();
2921 908 : let self_clone = Arc::clone(self);
2922 908 :
2923 908 : debug!("spawning flush loop");
2924 908 : *flush_loop_state = FlushLoopState::Running {
2925 908 : #[cfg(test)]
2926 908 : expect_initdb_optimization: false,
2927 908 : #[cfg(test)]
2928 908 : initdb_optimization_count: 0,
2929 908 : };
2930 908 : task_mgr::spawn(
2931 908 : task_mgr::BACKGROUND_RUNTIME.handle(),
2932 908 : task_mgr::TaskKind::LayerFlushTask,
2933 908 : self.tenant_shard_id,
2934 908 : Some(self.timeline_id),
2935 908 : "layer flush task",
2936 908 : async move {
2937 908 : let _guard = guard;
2938 908 : let background_ctx = RequestContext::todo_child(TaskKind::LayerFlushTask, DownloadBehavior::Error).with_scope_timeline(&self_clone);
2939 908 : self_clone.flush_loop(layer_flush_start_rx, &background_ctx).await;
2940 20 : let mut flush_loop_state = self_clone.flush_loop_state.lock().unwrap();
2941 20 : assert!(matches!(*flush_loop_state, FlushLoopState::Running{..}));
2942 20 : *flush_loop_state = FlushLoopState::Exited;
2943 20 : Ok(())
2944 20 : }
2945 908 : .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))
2946 : );
2947 1332 : }
2948 :
2949 0 : pub(crate) fn update_gc_compaction_state(
2950 0 : &self,
2951 0 : gc_compaction_state: GcCompactionState,
2952 0 : ) -> anyhow::Result<()> {
2953 0 : self.gc_compaction_state
2954 0 : .store(Arc::new(Some(gc_compaction_state.clone())));
2955 0 : self.remote_client
2956 0 : .schedule_index_upload_for_gc_compaction_state_update(gc_compaction_state)
2957 0 : }
2958 :
2959 0 : pub(crate) fn update_rel_size_v2_status(
2960 0 : &self,
2961 0 : rel_size_v2_status: RelSizeMigration,
2962 0 : ) -> anyhow::Result<()> {
2963 0 : self.rel_size_v2_status
2964 0 : .store(Some(Arc::new(rel_size_v2_status.clone())));
2965 0 : self.remote_client
2966 0 : .schedule_index_upload_for_rel_size_v2_status_update(rel_size_v2_status)
2967 0 : }
2968 :
2969 0 : pub(crate) fn get_gc_compaction_state(&self) -> Option<GcCompactionState> {
2970 0 : self.gc_compaction_state.load_full().as_ref().clone()
2971 0 : }
2972 :
2973 : /// Creates and starts the wal receiver.
2974 : ///
2975 : /// This function is expected to be called at most once per Timeline's lifecycle
2976 : /// when the timeline is activated.
2977 0 : fn launch_wal_receiver(
2978 0 : self: &Arc<Self>,
2979 0 : ctx: &RequestContext,
2980 0 : broker_client: BrokerClientChannel,
2981 0 : ) {
2982 0 : info!(
2983 0 : "launching WAL receiver for timeline {} of tenant {}",
2984 0 : self.timeline_id, self.tenant_shard_id
2985 : );
2986 :
2987 0 : let tenant_conf = self.tenant_conf.load();
2988 0 : let wal_connect_timeout = tenant_conf
2989 0 : .tenant_conf
2990 0 : .walreceiver_connect_timeout
2991 0 : .unwrap_or(self.conf.default_tenant_conf.walreceiver_connect_timeout);
2992 0 : let lagging_wal_timeout = tenant_conf
2993 0 : .tenant_conf
2994 0 : .lagging_wal_timeout
2995 0 : .unwrap_or(self.conf.default_tenant_conf.lagging_wal_timeout);
2996 0 : let max_lsn_wal_lag = tenant_conf
2997 0 : .tenant_conf
2998 0 : .max_lsn_wal_lag
2999 0 : .unwrap_or(self.conf.default_tenant_conf.max_lsn_wal_lag);
3000 0 :
3001 0 : let mut guard = self.walreceiver.lock().unwrap();
3002 0 : assert!(
3003 0 : guard.is_none(),
3004 0 : "multiple launches / re-launches of WAL receiver are not supported"
3005 : );
3006 0 : *guard = Some(WalReceiver::start(
3007 0 : Arc::clone(self),
3008 0 : WalReceiverConf {
3009 0 : protocol: self.resolve_wal_receiver_protocol(),
3010 0 : wal_connect_timeout,
3011 0 : lagging_wal_timeout,
3012 0 : max_lsn_wal_lag,
3013 0 : auth_token: crate::config::SAFEKEEPER_AUTH_TOKEN.get().cloned(),
3014 0 : availability_zone: self.conf.availability_zone.clone(),
3015 0 : ingest_batch_size: self.conf.ingest_batch_size,
3016 0 : validate_wal_contiguity: self.conf.validate_wal_contiguity,
3017 0 : },
3018 0 : broker_client,
3019 0 : ctx,
3020 0 : ));
3021 0 : }
3022 :
3023 : /// Initialize with an empty layer map. Used when creating a new timeline.
3024 908 : pub(super) fn init_empty_layer_map(&self, start_lsn: Lsn) {
3025 908 : let mut layers = self.layers.try_write().expect(
3026 908 : "in the context where we call this function, no other task has access to the object",
3027 908 : );
3028 908 : layers
3029 908 : .open_mut()
3030 908 : .expect("in this context the LayerManager must still be open")
3031 908 : .initialize_empty(Lsn(start_lsn.0));
3032 908 : }
3033 :
3034 : /// Scan the timeline directory, cleanup, populate the layer map, and schedule uploads for local-only
3035 : /// files.
3036 12 : pub(super) async fn load_layer_map(
3037 12 : &self,
3038 12 : disk_consistent_lsn: Lsn,
3039 12 : index_part: IndexPart,
3040 12 : ) -> anyhow::Result<()> {
3041 : use LayerName::*;
3042 : use init::Decision::*;
3043 : use init::{Discovered, DismissedLayer};
3044 :
3045 12 : let mut guard = self.layers.write().await;
3046 :
3047 12 : let timer = self.metrics.load_layer_map_histo.start_timer();
3048 12 :
3049 12 : // Scan timeline directory and create ImageLayerName and DeltaFilename
3050 12 : // structs representing all files on disk
3051 12 : let timeline_path = self
3052 12 : .conf
3053 12 : .timeline_path(&self.tenant_shard_id, &self.timeline_id);
3054 12 : let conf = self.conf;
3055 12 : let span = tracing::Span::current();
3056 12 :
3057 12 : // Copy to move into the task we're about to spawn
3058 12 : let this = self.myself.upgrade().expect("&self method holds the arc");
3059 :
3060 12 : let (loaded_layers, needs_cleanup, total_physical_size) = tokio::task::spawn_blocking({
3061 12 : move || {
3062 12 : let _g = span.entered();
3063 12 : let discovered = init::scan_timeline_dir(&timeline_path)?;
3064 12 : let mut discovered_layers = Vec::with_capacity(discovered.len());
3065 12 : let mut unrecognized_files = Vec::new();
3066 12 :
3067 12 : let mut path = timeline_path;
3068 :
3069 44 : for discovered in discovered {
3070 32 : let (name, kind) = match discovered {
3071 32 : Discovered::Layer(layer_file_name, local_metadata) => {
3072 32 : discovered_layers.push((layer_file_name, local_metadata));
3073 32 : continue;
3074 : }
3075 0 : Discovered::IgnoredBackup(path) => {
3076 0 : std::fs::remove_file(path)
3077 0 : .or_else(fs_ext::ignore_not_found)
3078 0 : .fatal_err("Removing .old file");
3079 0 : continue;
3080 : }
3081 0 : Discovered::Unknown(file_name) => {
3082 0 : // we will later error if there are any
3083 0 : unrecognized_files.push(file_name);
3084 0 : continue;
3085 : }
3086 0 : Discovered::Ephemeral(name) => (name, "old ephemeral file"),
3087 0 : Discovered::Temporary(name) => (name, "temporary timeline file"),
3088 0 : Discovered::TemporaryDownload(name) => (name, "temporary download"),
3089 : };
3090 0 : path.push(Utf8Path::new(&name));
3091 0 : init::cleanup(&path, kind)?;
3092 0 : path.pop();
3093 : }
3094 :
3095 12 : if !unrecognized_files.is_empty() {
3096 : // assume that if there are any there are many many.
3097 0 : let n = unrecognized_files.len();
3098 0 : let first = &unrecognized_files[..n.min(10)];
3099 0 : anyhow::bail!(
3100 0 : "unrecognized files in timeline dir (total {n}), first 10: {first:?}"
3101 0 : );
3102 12 : }
3103 12 :
3104 12 : let decided = init::reconcile(discovered_layers, &index_part, disk_consistent_lsn);
3105 12 :
3106 12 : let mut loaded_layers = Vec::new();
3107 12 : let mut needs_cleanup = Vec::new();
3108 12 : let mut total_physical_size = 0;
3109 :
3110 44 : for (name, decision) in decided {
3111 32 : let decision = match decision {
3112 32 : Ok(decision) => decision,
3113 0 : Err(DismissedLayer::Future { local }) => {
3114 0 : if let Some(local) = local {
3115 0 : init::cleanup_future_layer(
3116 0 : &local.local_path,
3117 0 : &name,
3118 0 : disk_consistent_lsn,
3119 0 : )?;
3120 0 : }
3121 0 : needs_cleanup.push(name);
3122 0 : continue;
3123 : }
3124 0 : Err(DismissedLayer::LocalOnly(local)) => {
3125 0 : init::cleanup_local_only_file(&name, &local)?;
3126 : // this file never existed remotely, we will have to do rework
3127 0 : continue;
3128 : }
3129 0 : Err(DismissedLayer::BadMetadata(local)) => {
3130 0 : init::cleanup_local_file_for_remote(&local)?;
3131 : // this file never existed remotely, we will have to do rework
3132 0 : continue;
3133 : }
3134 : };
3135 :
3136 32 : match &name {
3137 24 : Delta(d) => assert!(d.lsn_range.end <= disk_consistent_lsn + 1),
3138 8 : Image(i) => assert!(i.lsn <= disk_consistent_lsn),
3139 : }
3140 :
3141 32 : tracing::debug!(layer=%name, ?decision, "applied");
3142 :
3143 32 : let layer = match decision {
3144 32 : Resident { local, remote } => {
3145 32 : total_physical_size += local.file_size;
3146 32 : Layer::for_resident(conf, &this, local.local_path, name, remote)
3147 32 : .drop_eviction_guard()
3148 : }
3149 0 : Evicted(remote) => Layer::for_evicted(conf, &this, name, remote),
3150 : };
3151 :
3152 32 : loaded_layers.push(layer);
3153 : }
3154 12 : Ok((loaded_layers, needs_cleanup, total_physical_size))
3155 12 : }
3156 12 : })
3157 12 : .await
3158 12 : .map_err(anyhow::Error::new)
3159 12 : .and_then(|x| x)?;
3160 :
3161 12 : let num_layers = loaded_layers.len();
3162 12 :
3163 12 : guard
3164 12 : .open_mut()
3165 12 : .expect("layermanager must be open during init")
3166 12 : .initialize_local_layers(loaded_layers, disk_consistent_lsn + 1);
3167 12 :
3168 12 : self.remote_client
3169 12 : .schedule_layer_file_deletion(&needs_cleanup)?;
3170 12 : self.remote_client
3171 12 : .schedule_index_upload_for_file_changes()?;
3172 : // This barrier orders above DELETEs before any later operations.
3173 : // This is critical because code executing after the barrier might
3174 : // create again objects with the same key that we just scheduled for deletion.
3175 : // For example, if we just scheduled deletion of an image layer "from the future",
3176 : // later compaction might run again and re-create the same image layer.
3177 : // "from the future" here means an image layer whose LSN is > IndexPart::disk_consistent_lsn.
3178 : // "same" here means same key range and LSN.
3179 : //
3180 : // Without a barrier between above DELETEs and the re-creation's PUTs,
3181 : // the upload queue may execute the PUT first, then the DELETE.
3182 : // In our example, we will end up with an IndexPart referencing a non-existent object.
3183 : //
3184 : // 1. a future image layer is created and uploaded
3185 : // 2. ps restart
3186 : // 3. the future layer from (1) is deleted during load layer map
3187 : // 4. image layer is re-created and uploaded
3188 : // 5. deletion queue would like to delete (1) but actually deletes (4)
3189 : // 6. delete by name works as expected, but it now deletes the wrong (later) version
3190 : //
3191 : // See https://github.com/neondatabase/neon/issues/5878
3192 : //
3193 : // NB: generation numbers naturally protect against this because they disambiguate
3194 : // (1) and (4)
3195 : // TODO: this is basically a no-op now, should we remove it?
3196 12 : self.remote_client.schedule_barrier()?;
3197 : // Tenant::create_timeline will wait for these uploads to happen before returning, or
3198 : // on retry.
3199 :
3200 : // Now that we have the full layer map, we may calculate the visibility of layers within it (a global scan)
3201 12 : drop(guard); // drop write lock, update_layer_visibility will take a read lock.
3202 12 : self.update_layer_visibility().await?;
3203 :
3204 12 : info!(
3205 0 : "loaded layer map with {} layers at {}, total physical size: {}",
3206 : num_layers, disk_consistent_lsn, total_physical_size
3207 : );
3208 :
3209 12 : timer.stop_and_record();
3210 12 : Ok(())
3211 12 : }
3212 :
3213 : /// Retrieve current logical size of the timeline.
3214 : ///
3215 : /// The size could be lagging behind the actual number, in case
3216 : /// the initial size calculation has not been run (gets triggered on the first size access).
3217 : ///
3218 : /// return size and boolean flag that shows if the size is exact
3219 0 : pub(crate) fn get_current_logical_size(
3220 0 : self: &Arc<Self>,
3221 0 : priority: GetLogicalSizePriority,
3222 0 : ctx: &RequestContext,
3223 0 : ) -> logical_size::CurrentLogicalSize {
3224 0 : if !self.tenant_shard_id.is_shard_zero() {
3225 : // Logical size is only accurately maintained on shard zero: when called elsewhere, for example
3226 : // when HTTP API is serving a GET for timeline zero, return zero
3227 0 : return logical_size::CurrentLogicalSize::Approximate(logical_size::Approximate::zero());
3228 0 : }
3229 0 :
3230 0 : let current_size = self.current_logical_size.current_size();
3231 0 : debug!("Current size: {current_size:?}");
3232 :
3233 0 : match (current_size.accuracy(), priority) {
3234 0 : (logical_size::Accuracy::Exact, _) => (), // nothing to do
3235 0 : (logical_size::Accuracy::Approximate, GetLogicalSizePriority::Background) => {
3236 0 : // background task will eventually deliver an exact value, we're in no rush
3237 0 : }
3238 : (logical_size::Accuracy::Approximate, GetLogicalSizePriority::User) => {
3239 : // background task is not ready, but user is asking for it now;
3240 : // => make the background task skip the line
3241 : // (The alternative would be to calculate the size here, but,
3242 : // it can actually take a long time if the user has a lot of rels.
3243 : // And we'll inevitable need it again; So, let the background task do the work.)
3244 0 : match self
3245 0 : .current_logical_size
3246 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore
3247 0 : .get()
3248 : {
3249 0 : Some(cancel) => cancel.cancel(),
3250 : None => {
3251 0 : match self.current_state() {
3252 0 : TimelineState::Broken { .. } | TimelineState::Stopping => {
3253 0 : // Can happen when timeline detail endpoint is used when deletion is ongoing (or its broken).
3254 0 : // Don't make noise.
3255 0 : }
3256 : TimelineState::Loading => {
3257 : // Import does not return an activated timeline.
3258 0 : info!(
3259 0 : "discarding priority boost for logical size calculation because timeline is not yet active"
3260 : );
3261 : }
3262 : TimelineState::Active => {
3263 : // activation should be setting the once cell
3264 0 : warn!(
3265 0 : "unexpected: cancel_wait_for_background_loop_concurrency_limit_semaphore not set, priority-boosting of logical size calculation will not work"
3266 : );
3267 0 : debug_assert!(false);
3268 : }
3269 : }
3270 : }
3271 : }
3272 : }
3273 : }
3274 :
3275 0 : if let CurrentLogicalSize::Approximate(_) = ¤t_size {
3276 0 : if ctx.task_kind() == TaskKind::WalReceiverConnectionHandler {
3277 0 : let first = self
3278 0 : .current_logical_size
3279 0 : .did_return_approximate_to_walreceiver
3280 0 : .compare_exchange(
3281 0 : false,
3282 0 : true,
3283 0 : AtomicOrdering::Relaxed,
3284 0 : AtomicOrdering::Relaxed,
3285 0 : )
3286 0 : .is_ok();
3287 0 : if first {
3288 0 : crate::metrics::initial_logical_size::TIMELINES_WHERE_WALRECEIVER_GOT_APPROXIMATE_SIZE.inc();
3289 0 : }
3290 0 : }
3291 0 : }
3292 :
3293 0 : current_size
3294 0 : }
3295 :
3296 0 : fn spawn_initial_logical_size_computation_task(self: &Arc<Self>, ctx: &RequestContext) {
3297 0 : let Some(initial_part_end) = self.current_logical_size.initial_part_end else {
3298 : // nothing to do for freshly created timelines;
3299 0 : assert_eq!(
3300 0 : self.current_logical_size.current_size().accuracy(),
3301 0 : logical_size::Accuracy::Exact,
3302 0 : );
3303 0 : self.current_logical_size.initialized.add_permits(1);
3304 0 : return;
3305 : };
3306 :
3307 0 : let cancel_wait_for_background_loop_concurrency_limit_semaphore = CancellationToken::new();
3308 0 : let token = cancel_wait_for_background_loop_concurrency_limit_semaphore.clone();
3309 0 : self.current_logical_size
3310 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore.set(token)
3311 0 : .expect("initial logical size calculation task must be spawned exactly once per Timeline object");
3312 0 :
3313 0 : let self_clone = Arc::clone(self);
3314 0 : let background_ctx = ctx.detached_child(
3315 0 : TaskKind::InitialLogicalSizeCalculation,
3316 0 : DownloadBehavior::Download,
3317 0 : );
3318 0 : task_mgr::spawn(
3319 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
3320 0 : task_mgr::TaskKind::InitialLogicalSizeCalculation,
3321 0 : self.tenant_shard_id,
3322 0 : Some(self.timeline_id),
3323 0 : "initial size calculation",
3324 : // NB: don't log errors here, task_mgr will do that.
3325 0 : async move {
3326 0 : self_clone
3327 0 : .initial_logical_size_calculation_task(
3328 0 : initial_part_end,
3329 0 : cancel_wait_for_background_loop_concurrency_limit_semaphore,
3330 0 : background_ctx,
3331 0 : )
3332 0 : .await;
3333 0 : Ok(())
3334 0 : }
3335 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)),
3336 : );
3337 0 : }
3338 :
3339 : /// # Cancellation
3340 : ///
3341 : /// This method is sensitive to `Timeline::cancel`.
3342 : ///
3343 : /// It is _not_ sensitive to task_mgr::shutdown_token().
3344 : ///
3345 : /// # Cancel-Safety
3346 : ///
3347 : /// It does Timeline IO, hence this should be polled to completion because
3348 : /// we could be leaving in-flight IOs behind, which is safe, but annoying
3349 : /// to reason about.
3350 0 : async fn initial_logical_size_calculation_task(
3351 0 : self: Arc<Self>,
3352 0 : initial_part_end: Lsn,
3353 0 : skip_concurrency_limiter: CancellationToken,
3354 0 : background_ctx: RequestContext,
3355 0 : ) {
3356 0 : scopeguard::defer! {
3357 0 : // Irrespective of the outcome of this operation, we should unblock anyone waiting for it.
3358 0 : self.current_logical_size.initialized.add_permits(1);
3359 0 : }
3360 0 :
3361 0 : let try_once = |attempt: usize| {
3362 0 : let background_ctx = &background_ctx;
3363 0 : let self_ref = &self;
3364 0 : let skip_concurrency_limiter = &skip_concurrency_limiter;
3365 0 : async move {
3366 0 : let wait_for_permit = super::tasks::acquire_concurrency_permit(
3367 0 : BackgroundLoopKind::InitialLogicalSizeCalculation,
3368 0 : background_ctx,
3369 0 : );
3370 :
3371 : use crate::metrics::initial_logical_size::StartCircumstances;
3372 0 : let (_maybe_permit, circumstances) = tokio::select! {
3373 0 : permit = wait_for_permit => {
3374 0 : (Some(permit), StartCircumstances::AfterBackgroundTasksRateLimit)
3375 : }
3376 0 : _ = self_ref.cancel.cancelled() => {
3377 0 : return Err(CalculateLogicalSizeError::Cancelled);
3378 : }
3379 0 : () = skip_concurrency_limiter.cancelled() => {
3380 : // Some action that is part of a end user interaction requested logical size
3381 : // => break out of the rate limit
3382 : // TODO: ideally we'd not run on BackgroundRuntime but the requester's runtime;
3383 : // but then again what happens if they cancel; also, we should just be using
3384 : // one runtime across the entire process, so, let's leave this for now.
3385 0 : (None, StartCircumstances::SkippedConcurrencyLimiter)
3386 : }
3387 : };
3388 :
3389 0 : let metrics_guard = if attempt == 1 {
3390 0 : crate::metrics::initial_logical_size::START_CALCULATION.first(circumstances)
3391 : } else {
3392 0 : crate::metrics::initial_logical_size::START_CALCULATION.retry(circumstances)
3393 : };
3394 :
3395 0 : let io_concurrency = IoConcurrency::spawn_from_conf(
3396 0 : self_ref.conf,
3397 0 : self_ref
3398 0 : .gate
3399 0 : .enter()
3400 0 : .map_err(|_| CalculateLogicalSizeError::Cancelled)?,
3401 : );
3402 :
3403 0 : let calculated_size = self_ref
3404 0 : .logical_size_calculation_task(
3405 0 : initial_part_end,
3406 0 : LogicalSizeCalculationCause::Initial,
3407 0 : background_ctx,
3408 0 : )
3409 0 : .await?;
3410 :
3411 0 : self_ref
3412 0 : .trigger_aux_file_size_computation(
3413 0 : initial_part_end,
3414 0 : background_ctx,
3415 0 : io_concurrency,
3416 0 : )
3417 0 : .await?;
3418 :
3419 : // TODO: add aux file size to logical size
3420 :
3421 0 : Ok((calculated_size, metrics_guard))
3422 0 : }
3423 0 : };
3424 :
3425 0 : let retrying = async {
3426 0 : let mut attempt = 0;
3427 : loop {
3428 0 : attempt += 1;
3429 0 :
3430 0 : match try_once(attempt).await {
3431 0 : Ok(res) => return ControlFlow::Continue(res),
3432 0 : Err(CalculateLogicalSizeError::Cancelled) => return ControlFlow::Break(()),
3433 : Err(
3434 0 : e @ (CalculateLogicalSizeError::Decode(_)
3435 0 : | CalculateLogicalSizeError::PageRead(_)),
3436 0 : ) => {
3437 0 : warn!(attempt, "initial size calculation failed: {e:?}");
3438 : // exponential back-off doesn't make sense at these long intervals;
3439 : // use fixed retry interval with generous jitter instead
3440 0 : let sleep_duration = Duration::from_secs(
3441 0 : u64::try_from(
3442 0 : // 1hour base
3443 0 : (60_i64 * 60_i64)
3444 0 : // 10min jitter
3445 0 : + rand::thread_rng().gen_range(-10 * 60..10 * 60),
3446 0 : )
3447 0 : .expect("10min < 1hour"),
3448 0 : );
3449 0 : tokio::select! {
3450 0 : _ = tokio::time::sleep(sleep_duration) => {}
3451 0 : _ = self.cancel.cancelled() => return ControlFlow::Break(()),
3452 : }
3453 : }
3454 : }
3455 : }
3456 0 : };
3457 :
3458 0 : let (calculated_size, metrics_guard) = match retrying.await {
3459 0 : ControlFlow::Continue(calculated_size) => calculated_size,
3460 0 : ControlFlow::Break(()) => return,
3461 : };
3462 :
3463 : // we cannot query current_logical_size.current_size() to know the current
3464 : // *negative* value, only truncated to u64.
3465 0 : let added = self
3466 0 : .current_logical_size
3467 0 : .size_added_after_initial
3468 0 : .load(AtomicOrdering::Relaxed);
3469 0 :
3470 0 : let sum = calculated_size.saturating_add_signed(added);
3471 0 :
3472 0 : // set the gauge value before it can be set in `update_current_logical_size`.
3473 0 : self.metrics.current_logical_size_gauge.set(sum);
3474 0 :
3475 0 : self.current_logical_size
3476 0 : .initial_logical_size
3477 0 : .set((calculated_size, metrics_guard.calculation_result_saved()))
3478 0 : .ok()
3479 0 : .expect("only this task sets it");
3480 0 : }
3481 :
3482 28 : pub(crate) fn spawn_ondemand_logical_size_calculation(
3483 28 : self: &Arc<Self>,
3484 28 : lsn: Lsn,
3485 28 : cause: LogicalSizeCalculationCause,
3486 28 : ctx: RequestContext,
3487 28 : ) -> oneshot::Receiver<Result<u64, CalculateLogicalSizeError>> {
3488 28 : let (sender, receiver) = oneshot::channel();
3489 28 : let self_clone = Arc::clone(self);
3490 28 : // XXX if our caller loses interest, i.e., ctx is cancelled,
3491 28 : // we should stop the size calculation work and return an error.
3492 28 : // That would require restructuring this function's API to
3493 28 : // return the result directly, instead of a Receiver for the result.
3494 28 : let ctx = ctx.detached_child(
3495 28 : TaskKind::OndemandLogicalSizeCalculation,
3496 28 : DownloadBehavior::Download,
3497 28 : );
3498 28 : task_mgr::spawn(
3499 28 : task_mgr::BACKGROUND_RUNTIME.handle(),
3500 28 : task_mgr::TaskKind::OndemandLogicalSizeCalculation,
3501 28 : self.tenant_shard_id,
3502 28 : Some(self.timeline_id),
3503 28 : "ondemand logical size calculation",
3504 28 : async move {
3505 28 : let res = self_clone
3506 28 : .logical_size_calculation_task(lsn, cause, &ctx)
3507 28 : .await;
3508 28 : let _ = sender.send(res).ok();
3509 28 : Ok(()) // Receiver is responsible for handling errors
3510 28 : }
3511 28 : .in_current_span(),
3512 28 : );
3513 28 : receiver
3514 28 : }
3515 :
3516 : #[instrument(skip_all)]
3517 : async fn logical_size_calculation_task(
3518 : self: &Arc<Self>,
3519 : lsn: Lsn,
3520 : cause: LogicalSizeCalculationCause,
3521 : ctx: &RequestContext,
3522 : ) -> Result<u64, CalculateLogicalSizeError> {
3523 : crate::span::debug_assert_current_span_has_tenant_and_timeline_id();
3524 : // We should never be calculating logical sizes on shard !=0, because these shards do not have
3525 : // accurate relation sizes, and they do not emit consumption metrics.
3526 : debug_assert!(self.tenant_shard_id.is_shard_zero());
3527 :
3528 : let guard = self
3529 : .gate
3530 : .enter()
3531 0 : .map_err(|_| CalculateLogicalSizeError::Cancelled)?;
3532 :
3533 : self.calculate_logical_size(lsn, cause, &guard, ctx).await
3534 : }
3535 :
3536 : /// Calculate the logical size of the database at the latest LSN.
3537 : ///
3538 : /// NOTE: counted incrementally, includes ancestors. This can be a slow operation,
3539 : /// especially if we need to download remote layers.
3540 28 : async fn calculate_logical_size(
3541 28 : &self,
3542 28 : up_to_lsn: Lsn,
3543 28 : cause: LogicalSizeCalculationCause,
3544 28 : _guard: &GateGuard,
3545 28 : ctx: &RequestContext,
3546 28 : ) -> Result<u64, CalculateLogicalSizeError> {
3547 28 : info!(
3548 0 : "Calculating logical size for timeline {} at {}",
3549 : self.timeline_id, up_to_lsn
3550 : );
3551 :
3552 28 : if let Err(()) = pausable_failpoint!("timeline-calculate-logical-size-pause", &self.cancel)
3553 : {
3554 0 : return Err(CalculateLogicalSizeError::Cancelled);
3555 28 : }
3556 :
3557 : // See if we've already done the work for initial size calculation.
3558 : // This is a short-cut for timelines that are mostly unused.
3559 28 : if let Some(size) = self.current_logical_size.initialized_size(up_to_lsn) {
3560 0 : return Ok(size);
3561 28 : }
3562 28 : let storage_time_metrics = match cause {
3563 : LogicalSizeCalculationCause::Initial
3564 : | LogicalSizeCalculationCause::ConsumptionMetricsSyntheticSize
3565 0 : | LogicalSizeCalculationCause::TenantSizeHandler => &self.metrics.logical_size_histo,
3566 : LogicalSizeCalculationCause::EvictionTaskImitation => {
3567 28 : &self.metrics.imitate_logical_size_histo
3568 : }
3569 : };
3570 28 : let timer = storage_time_metrics.start_timer();
3571 28 : let logical_size = self
3572 28 : .get_current_logical_size_non_incremental(up_to_lsn, ctx)
3573 28 : .await?;
3574 28 : debug!("calculated logical size: {logical_size}");
3575 28 : timer.stop_and_record();
3576 28 : Ok(logical_size)
3577 28 : }
3578 :
3579 : /// Update current logical size, adding `delta' to the old value.
3580 541140 : fn update_current_logical_size(&self, delta: i64) {
3581 541140 : let logical_size = &self.current_logical_size;
3582 541140 : logical_size.increment_size(delta);
3583 541140 :
3584 541140 : // Also set the value in the prometheus gauge. Note that
3585 541140 : // there is a race condition here: if this is is called by two
3586 541140 : // threads concurrently, the prometheus gauge might be set to
3587 541140 : // one value while current_logical_size is set to the
3588 541140 : // other.
3589 541140 : match logical_size.current_size() {
3590 541140 : CurrentLogicalSize::Exact(ref new_current_size) => self
3591 541140 : .metrics
3592 541140 : .current_logical_size_gauge
3593 541140 : .set(new_current_size.into()),
3594 0 : CurrentLogicalSize::Approximate(_) => {
3595 0 : // don't update the gauge yet, this allows us not to update the gauge back and
3596 0 : // forth between the initial size calculation task.
3597 0 : }
3598 : }
3599 541140 : }
3600 :
3601 6008 : pub(crate) fn update_directory_entries_count(&self, kind: DirectoryKind, count: MetricsUpdate) {
3602 6008 : // TODO: this directory metrics is not correct -- we could have multiple reldirs in the system
3603 6008 : // for each of the database, but we only store one value, and therefore each pgdirmodification
3604 6008 : // would overwrite the previous value if they modify different databases.
3605 6008 :
3606 6008 : match count {
3607 2164 : MetricsUpdate::Set(count) => {
3608 2164 : self.directory_metrics[kind.offset()].store(count, AtomicOrdering::Relaxed);
3609 2164 : self.directory_metrics_inited[kind.offset()].store(true, AtomicOrdering::Relaxed);
3610 2164 : }
3611 3840 : MetricsUpdate::Add(count) => {
3612 3840 : // TODO: these operations are not atomic; but we only have one writer to the metrics, so
3613 3840 : // it's fine.
3614 3840 : if self.directory_metrics_inited[kind.offset()].load(AtomicOrdering::Relaxed) {
3615 3840 : // The metrics has been initialized with `MetricsUpdate::Set` before, so we can add/sub
3616 3840 : // the value reliably.
3617 3840 : self.directory_metrics[kind.offset()].fetch_add(count, AtomicOrdering::Relaxed);
3618 3840 : }
3619 : // Otherwise, ignore this update
3620 : }
3621 4 : MetricsUpdate::Sub(count) => {
3622 4 : // TODO: these operations are not atomic; but we only have one writer to the metrics, so
3623 4 : // it's fine.
3624 4 : if self.directory_metrics_inited[kind.offset()].load(AtomicOrdering::Relaxed) {
3625 4 : // The metrics has been initialized with `MetricsUpdate::Set` before.
3626 4 : // The operation could overflow so we need to normalize the value.
3627 4 : let prev_val =
3628 4 : self.directory_metrics[kind.offset()].load(AtomicOrdering::Relaxed);
3629 4 : let res = prev_val.saturating_sub(count);
3630 4 : self.directory_metrics[kind.offset()].store(res, AtomicOrdering::Relaxed);
3631 4 : }
3632 : // Otherwise, ignore this update
3633 : }
3634 : };
3635 :
3636 : // TODO: remove this, there's no place in the code that updates this aux metrics.
3637 6008 : let aux_metric =
3638 6008 : self.directory_metrics[DirectoryKind::AuxFiles.offset()].load(AtomicOrdering::Relaxed);
3639 6008 :
3640 6008 : let sum_of_entries = self
3641 6008 : .directory_metrics
3642 6008 : .iter()
3643 48064 : .map(|v| v.load(AtomicOrdering::Relaxed))
3644 6008 : .sum();
3645 : // Set a high general threshold and a lower threshold for the auxiliary files,
3646 : // as we can have large numbers of relations in the db directory.
3647 : const SUM_THRESHOLD: u64 = 5000;
3648 : const AUX_THRESHOLD: u64 = 1000;
3649 6008 : if sum_of_entries >= SUM_THRESHOLD || aux_metric >= AUX_THRESHOLD {
3650 0 : self.metrics
3651 0 : .directory_entries_count_gauge
3652 0 : .set(sum_of_entries);
3653 6008 : } else if let Some(metric) = Lazy::get(&self.metrics.directory_entries_count_gauge) {
3654 0 : metric.set(sum_of_entries);
3655 6008 : }
3656 6008 : }
3657 :
3658 0 : async fn find_layer(
3659 0 : &self,
3660 0 : layer_name: &LayerName,
3661 0 : ) -> Result<Option<Layer>, layer_manager::Shutdown> {
3662 0 : let guard = self.layers.read().await;
3663 0 : let layer = guard
3664 0 : .layer_map()?
3665 0 : .iter_historic_layers()
3666 0 : .find(|l| &l.layer_name() == layer_name)
3667 0 : .map(|found| guard.get_from_desc(&found));
3668 0 : Ok(layer)
3669 0 : }
3670 :
3671 0 : pub(super) fn should_keep_previous_heatmap(&self, new_heatmap_end_lsn: Lsn) -> bool {
3672 0 : let crnt = self.previous_heatmap.load();
3673 0 : match crnt.as_deref() {
3674 0 : Some(PreviousHeatmap::Active { end_lsn, .. }) => match end_lsn {
3675 0 : Some(crnt_end_lsn) => *crnt_end_lsn > new_heatmap_end_lsn,
3676 0 : None => true,
3677 : },
3678 0 : Some(PreviousHeatmap::Obsolete) => false,
3679 0 : None => false,
3680 : }
3681 0 : }
3682 :
3683 : /// The timeline heatmap is a hint to secondary locations from the primary location,
3684 : /// indicating which layers are currently on-disk on the primary.
3685 : ///
3686 : /// None is returned if the Timeline is in a state where uploading a heatmap
3687 : /// doesn't make sense, such as shutting down or initializing. The caller
3688 : /// should treat this as a cue to simply skip doing any heatmap uploading
3689 : /// for this timeline.
3690 32 : pub(crate) async fn generate_heatmap(&self) -> Option<HeatMapTimeline> {
3691 32 : if !self.is_active() {
3692 0 : return None;
3693 32 : }
3694 :
3695 32 : let guard = self.layers.read().await;
3696 :
3697 : // Firstly, if there's any heatmap left over from when this location
3698 : // was a secondary, take that into account. Keep layers that are:
3699 : // * present in the layer map
3700 : // * visible
3701 : // * non-resident
3702 : // * not evicted since we read the heatmap
3703 : //
3704 : // Without this, a new cold, attached location would clobber the previous
3705 : // heatamp.
3706 32 : let previous_heatmap = self.previous_heatmap.load();
3707 32 : let visible_non_resident = match previous_heatmap.as_deref() {
3708 : Some(PreviousHeatmap::Active {
3709 24 : heatmap, read_at, ..
3710 92 : }) => Some(heatmap.all_layers().filter_map(|hl| {
3711 92 : let desc: PersistentLayerDesc = hl.name.clone().into();
3712 92 : let layer = guard.try_get_from_key(&desc.key())?;
3713 :
3714 92 : if layer.visibility() == LayerVisibilityHint::Covered {
3715 0 : return None;
3716 92 : }
3717 92 :
3718 92 : if layer.is_likely_resident() {
3719 40 : return None;
3720 52 : }
3721 52 :
3722 52 : if layer.last_evicted_at().happened_after(*read_at) {
3723 12 : return None;
3724 40 : }
3725 40 :
3726 40 : Some((desc, hl.metadata.clone(), hl.access_time, hl.cold))
3727 92 : })),
3728 0 : Some(PreviousHeatmap::Obsolete) => None,
3729 8 : None => None,
3730 : };
3731 :
3732 : // Secondly, all currently visible, resident layers are included.
3733 72 : let resident = guard.likely_resident_layers().filter_map(|layer| {
3734 72 : match layer.visibility() {
3735 : LayerVisibilityHint::Visible => {
3736 : // Layer is visible to one or more read LSNs: elegible for inclusion in layer map
3737 68 : let last_activity_ts = layer.latest_activity();
3738 68 : Some((
3739 68 : layer.layer_desc().clone(),
3740 68 : layer.metadata(),
3741 68 : last_activity_ts,
3742 68 : false, // these layers are not cold
3743 68 : ))
3744 : }
3745 : LayerVisibilityHint::Covered => {
3746 : // Layer is resident but unlikely to be read: not elegible for inclusion in heatmap.
3747 4 : None
3748 : }
3749 : }
3750 72 : });
3751 :
3752 32 : let mut layers = match visible_non_resident {
3753 24 : Some(non_resident) => {
3754 24 : let mut non_resident = non_resident.peekable();
3755 24 : if non_resident.peek().is_none() {
3756 8 : tracing::info!(timeline_id=%self.timeline_id, "Previous heatmap now obsolete");
3757 8 : self.previous_heatmap
3758 8 : .store(Some(PreviousHeatmap::Obsolete.into()));
3759 16 : }
3760 :
3761 24 : non_resident.chain(resident).collect::<Vec<_>>()
3762 : }
3763 8 : None => resident.collect::<Vec<_>>(),
3764 : };
3765 :
3766 : // Sort layers in order of which to download first. For a large set of layers to download, we
3767 : // want to prioritize those layers which are most likely to still be in the resident many minutes
3768 : // or hours later:
3769 : // - Cold layers go last for convenience when a human inspects the heatmap.
3770 : // - Download L0s last, because they churn the fastest: L0s on a fast-writing tenant might
3771 : // only exist for a few minutes before being compacted into L1s.
3772 : // - For L1 & image layers, download most recent LSNs first: the older the LSN, the sooner
3773 : // the layer is likely to be covered by an image layer during compaction.
3774 244 : layers.sort_by_key(|(desc, _meta, _atime, cold)| {
3775 244 : std::cmp::Reverse((
3776 244 : *cold,
3777 244 : !LayerMap::is_l0(&desc.key_range, desc.is_delta),
3778 244 : desc.lsn_range.end,
3779 244 : ))
3780 244 : });
3781 32 :
3782 32 : let layers = layers
3783 32 : .into_iter()
3784 108 : .map(|(desc, meta, atime, cold)| {
3785 108 : HeatMapLayer::new(desc.layer_name(), meta, atime, cold)
3786 108 : })
3787 32 : .collect();
3788 32 :
3789 32 : Some(HeatMapTimeline::new(self.timeline_id, layers))
3790 32 : }
3791 :
3792 0 : pub(super) async fn generate_unarchival_heatmap(&self, end_lsn: Lsn) -> PreviousHeatmap {
3793 0 : let guard = self.layers.read().await;
3794 :
3795 0 : let now = SystemTime::now();
3796 0 : let mut heatmap_layers = Vec::default();
3797 0 : for vl in guard.visible_layers() {
3798 0 : if vl.layer_desc().get_lsn_range().start >= end_lsn {
3799 0 : continue;
3800 0 : }
3801 0 :
3802 0 : let hl = HeatMapLayer {
3803 0 : name: vl.layer_desc().layer_name(),
3804 0 : metadata: vl.metadata(),
3805 0 : access_time: now,
3806 0 : cold: true,
3807 0 : };
3808 0 : heatmap_layers.push(hl);
3809 : }
3810 :
3811 0 : tracing::info!(
3812 0 : "Generating unarchival heatmap with {} layers",
3813 0 : heatmap_layers.len()
3814 : );
3815 :
3816 0 : let heatmap = HeatMapTimeline::new(self.timeline_id, heatmap_layers);
3817 0 : PreviousHeatmap::Active {
3818 0 : heatmap,
3819 0 : read_at: Instant::now(),
3820 0 : end_lsn: Some(end_lsn),
3821 0 : }
3822 0 : }
3823 :
3824 : /// Returns true if the given lsn is or was an ancestor branchpoint.
3825 0 : pub(crate) fn is_ancestor_lsn(&self, lsn: Lsn) -> bool {
3826 0 : // upon timeline detach, we set the ancestor_lsn to Lsn::INVALID and the store the original
3827 0 : // branchpoint in the value in IndexPart::lineage
3828 0 : self.ancestor_lsn == lsn
3829 0 : || (self.ancestor_lsn == Lsn::INVALID
3830 0 : && self.remote_client.is_previous_ancestor_lsn(lsn))
3831 0 : }
3832 : }
3833 :
3834 : impl Timeline {
3835 : #[allow(clippy::doc_lazy_continuation)]
3836 : /// Get the data needed to reconstruct all keys in the provided keyspace
3837 : ///
3838 : /// The algorithm is as follows:
3839 : /// 1. While some keys are still not done and there's a timeline to visit:
3840 : /// 2. Visit the timeline (see [`Timeline::get_vectored_reconstruct_data_timeline`]:
3841 : /// 2.1: Build the fringe for the current keyspace
3842 : /// 2.2 Visit the newest layer from the fringe to collect all values for the range it
3843 : /// intersects
3844 : /// 2.3. Pop the timeline from the fringe
3845 : /// 2.4. If the fringe is empty, go back to 1
3846 1255445 : async fn get_vectored_reconstruct_data(
3847 1255445 : &self,
3848 1255445 : mut keyspace: KeySpace,
3849 1255445 : request_lsn: Lsn,
3850 1255445 : reconstruct_state: &mut ValuesReconstructState,
3851 1255445 : ctx: &RequestContext,
3852 1255445 : ) -> Result<(), GetVectoredError> {
3853 1255445 : let mut timeline_owned: Arc<Timeline>;
3854 1255445 : let mut timeline = self;
3855 1255445 :
3856 1255445 : let mut cont_lsn = Lsn(request_lsn.0 + 1);
3857 :
3858 1255441 : let missing_keyspace = loop {
3859 1705899 : if self.cancel.is_cancelled() {
3860 0 : return Err(GetVectoredError::Cancelled);
3861 1705899 : }
3862 :
3863 : let TimelineVisitOutcome {
3864 1705899 : completed_keyspace: completed,
3865 1705899 : image_covered_keyspace,
3866 1705899 : } = Self::get_vectored_reconstruct_data_timeline(
3867 1705899 : timeline,
3868 1705899 : keyspace.clone(),
3869 1705899 : cont_lsn,
3870 1705899 : reconstruct_state,
3871 1705899 : &self.cancel,
3872 1705899 : ctx,
3873 1705899 : )
3874 1705899 : .await?;
3875 :
3876 1705899 : keyspace.remove_overlapping_with(&completed);
3877 1705899 :
3878 1705899 : // Do not descend into the ancestor timeline for aux files.
3879 1705899 : // We don't return a blanket [`GetVectoredError::MissingKey`] to avoid
3880 1705899 : // stalling compaction.
3881 1705899 : keyspace.remove_overlapping_with(&KeySpace {
3882 1705899 : ranges: vec![NON_INHERITED_RANGE, Key::sparse_non_inherited_keyspace()],
3883 1705899 : });
3884 1705899 :
3885 1705899 : // Keyspace is fully retrieved
3886 1705899 : if keyspace.is_empty() {
3887 1254929 : break None;
3888 450970 : }
3889 :
3890 450970 : let Some(ancestor_timeline) = timeline.ancestor_timeline.as_ref() else {
3891 : // Not fully retrieved but no ancestor timeline.
3892 512 : break Some(keyspace);
3893 : };
3894 :
3895 : // Now we see if there are keys covered by the image layer but does not exist in the
3896 : // image layer, which means that the key does not exist.
3897 :
3898 : // The block below will stop the vectored search if any of the keys encountered an image layer
3899 : // which did not contain a snapshot for said key. Since we have already removed all completed
3900 : // keys from `keyspace`, we expect there to be no overlap between it and the image covered key
3901 : // space. If that's not the case, we had at least one key encounter a gap in the image layer
3902 : // and stop the search as a result of that.
3903 450458 : let mut removed = keyspace.remove_overlapping_with(&image_covered_keyspace);
3904 450458 : // Do not fire missing key error and end early for sparse keys. Note that we hava already removed
3905 450458 : // non-inherited keyspaces before, so we can safely do a full `SPARSE_RANGE` remove instead of
3906 450458 : // figuring out what is the inherited key range and do a fine-grained pruning.
3907 450458 : removed.remove_overlapping_with(&KeySpace {
3908 450458 : ranges: vec![SPARSE_RANGE],
3909 450458 : });
3910 450458 : if !removed.is_empty() {
3911 0 : break Some(removed);
3912 450458 : }
3913 450458 : // If we reached this point, `remove_overlapping_with` should not have made any change to the
3914 450458 : // keyspace.
3915 450458 :
3916 450458 : // Take the min to avoid reconstructing a page with data newer than request Lsn.
3917 450458 : cont_lsn = std::cmp::min(Lsn(request_lsn.0 + 1), Lsn(timeline.ancestor_lsn.0 + 1));
3918 450458 : timeline_owned = timeline
3919 450458 : .get_ready_ancestor_timeline(ancestor_timeline, ctx)
3920 450458 : .await?;
3921 450454 : timeline = &*timeline_owned;
3922 : };
3923 :
3924 : // Remove sparse keys from the keyspace so that it doesn't fire errors.
3925 1255441 : let missing_keyspace = if let Some(missing_keyspace) = missing_keyspace {
3926 512 : let mut missing_keyspace = missing_keyspace;
3927 512 : missing_keyspace.remove_overlapping_with(&KeySpace {
3928 512 : ranges: vec![SPARSE_RANGE],
3929 512 : });
3930 512 : if missing_keyspace.is_empty() {
3931 484 : None
3932 : } else {
3933 28 : Some(missing_keyspace)
3934 : }
3935 : } else {
3936 1254929 : None
3937 : };
3938 :
3939 1255441 : if let Some(missing_keyspace) = missing_keyspace {
3940 28 : return Err(GetVectoredError::MissingKey(MissingKeyError {
3941 28 : key: missing_keyspace.start().unwrap(), /* better if we can store the full keyspace */
3942 28 : shard: self
3943 28 : .shard_identity
3944 28 : .get_shard_number(&missing_keyspace.start().unwrap()),
3945 28 : cont_lsn,
3946 28 : request_lsn,
3947 28 : ancestor_lsn: Some(timeline.ancestor_lsn),
3948 28 : backtrace: None,
3949 28 : read_path: std::mem::take(&mut reconstruct_state.read_path),
3950 28 : }));
3951 1255413 : }
3952 1255413 :
3953 1255413 : Ok(())
3954 1255445 : }
3955 :
3956 : /// Collect the reconstruct data for a keyspace from the specified timeline.
3957 : ///
3958 : /// Maintain a fringe [`LayerFringe`] which tracks all the layers that intersect
3959 : /// the current keyspace. The current keyspace of the search at any given timeline
3960 : /// is the original keyspace minus all the keys that have been completed minus
3961 : /// any keys for which we couldn't find an intersecting layer. It's not tracked explicitly,
3962 : /// but if you merge all the keyspaces in the fringe, you get the "current keyspace".
3963 : ///
3964 : /// This is basically a depth-first search visitor implementation where a vertex
3965 : /// is the (layer, lsn range, key space) tuple. The fringe acts as the stack.
3966 : ///
3967 : /// At each iteration pop the top of the fringe (the layer with the highest Lsn)
3968 : /// and get all the required reconstruct data from the layer in one go.
3969 : ///
3970 : /// Returns the completed keyspace and the keyspaces with image coverage. The caller
3971 : /// decides how to deal with these two keyspaces.
3972 1705899 : async fn get_vectored_reconstruct_data_timeline(
3973 1705899 : timeline: &Timeline,
3974 1705899 : keyspace: KeySpace,
3975 1705899 : mut cont_lsn: Lsn,
3976 1705899 : reconstruct_state: &mut ValuesReconstructState,
3977 1705899 : cancel: &CancellationToken,
3978 1705899 : ctx: &RequestContext,
3979 1705899 : ) -> Result<TimelineVisitOutcome, GetVectoredError> {
3980 1705899 : let mut unmapped_keyspace = keyspace.clone();
3981 1705899 : let mut fringe = LayerFringe::new();
3982 1705899 :
3983 1705899 : let mut completed_keyspace = KeySpace::default();
3984 1705899 : let mut image_covered_keyspace = KeySpaceRandomAccum::new();
3985 1705899 :
3986 1705899 : // Prevent GC from progressing while visiting the current timeline.
3987 1705899 : // If we are GC-ing because a new image layer was added while traversing
3988 1705899 : // the timeline, then it will remove layers that are required for fulfilling
3989 1705899 : // the current get request (read-path cannot "look back" and notice the new
3990 1705899 : // image layer).
3991 1705899 : let _gc_cutoff_holder = timeline.get_applied_gc_cutoff_lsn();
3992 :
3993 : // See `compaction::compact_with_gc` for why we need this.
3994 1705899 : let _guard = timeline.gc_compaction_layer_update_lock.read().await;
3995 :
3996 : loop {
3997 3400033 : if cancel.is_cancelled() {
3998 0 : return Err(GetVectoredError::Cancelled);
3999 3400033 : }
4000 3400033 :
4001 3400033 : let (keys_done_last_step, keys_with_image_coverage) =
4002 3400033 : reconstruct_state.consume_done_keys();
4003 3400033 : unmapped_keyspace.remove_overlapping_with(&keys_done_last_step);
4004 3400033 : completed_keyspace.merge(&keys_done_last_step);
4005 3400033 : if let Some(keys_with_image_coverage) = keys_with_image_coverage {
4006 45128 : unmapped_keyspace
4007 45128 : .remove_overlapping_with(&KeySpace::single(keys_with_image_coverage.clone()));
4008 45128 : image_covered_keyspace.add_range(keys_with_image_coverage);
4009 3354905 : }
4010 :
4011 : // Do not descent any further if the last layer we visited
4012 : // completed all keys in the keyspace it inspected. This is not
4013 : // required for correctness, but avoids visiting extra layers
4014 : // which turns out to be a perf bottleneck in some cases.
4015 3400033 : if !unmapped_keyspace.is_empty() {
4016 2149144 : let guard = timeline.layers.read().await;
4017 2149144 : let layers = guard.layer_map()?;
4018 :
4019 2150552 : for range in unmapped_keyspace.ranges.iter() {
4020 2150552 : let results = layers.range_search(range.clone(), cont_lsn);
4021 2150552 :
4022 2150552 : results
4023 2150552 : .found
4024 2150552 : .into_iter()
4025 2150552 : .map(|(SearchResult { layer, lsn_floor }, keyspace_accum)| {
4026 1695078 : (
4027 1695078 : guard.upgrade(layer),
4028 1695078 : keyspace_accum.to_keyspace(),
4029 1695078 : lsn_floor..cont_lsn,
4030 1695078 : )
4031 2150552 : })
4032 2150552 : .for_each(|(layer, keyspace, lsn_range)| {
4033 1695078 : fringe.update(layer, keyspace, lsn_range)
4034 2150552 : });
4035 2150552 : }
4036 :
4037 : // It's safe to drop the layer map lock after planning the next round of reads.
4038 : // The fringe keeps readable handles for the layers which are safe to read even
4039 : // if layers were compacted or flushed.
4040 : //
4041 : // The more interesting consideration is: "Why is the read algorithm still correct
4042 : // if the layer map changes while it is operating?". Doing a vectored read on a
4043 : // timeline boils down to pushing an imaginary lsn boundary downwards for each range
4044 : // covered by the read. The layer map tells us how to move the lsn downwards for a
4045 : // range at *a particular point in time*. It is fine for the answer to be different
4046 : // at two different time points.
4047 2149144 : drop(guard);
4048 1250889 : }
4049 :
4050 3400033 : if let Some((layer_to_read, keyspace_to_read, lsn_range)) = fringe.next_layer() {
4051 1694134 : if let Some(ref mut read_path) = reconstruct_state.read_path {
4052 1694134 : read_path.record_layer_visit(&layer_to_read, &keyspace_to_read, &lsn_range);
4053 1694134 : }
4054 1694134 : let next_cont_lsn = lsn_range.start;
4055 1694134 : layer_to_read
4056 1694134 : .get_values_reconstruct_data(
4057 1694134 : keyspace_to_read.clone(),
4058 1694134 : lsn_range,
4059 1694134 : reconstruct_state,
4060 1694134 : ctx,
4061 1694134 : )
4062 1694134 : .await?;
4063 :
4064 1694134 : unmapped_keyspace = keyspace_to_read;
4065 1694134 : cont_lsn = next_cont_lsn;
4066 1694134 :
4067 1694134 : reconstruct_state.on_layer_visited(&layer_to_read);
4068 : } else {
4069 1705899 : break;
4070 1705899 : }
4071 1705899 : }
4072 1705899 :
4073 1705899 : Ok(TimelineVisitOutcome {
4074 1705899 : completed_keyspace,
4075 1705899 : image_covered_keyspace: image_covered_keyspace.consume_keyspace(),
4076 1705899 : })
4077 1705899 : }
4078 :
4079 450458 : async fn get_ready_ancestor_timeline(
4080 450458 : &self,
4081 450458 : ancestor: &Arc<Timeline>,
4082 450458 : ctx: &RequestContext,
4083 450458 : ) -> Result<Arc<Timeline>, GetReadyAncestorError> {
4084 450458 : // It's possible that the ancestor timeline isn't active yet, or
4085 450458 : // is active but hasn't yet caught up to the branch point. Wait
4086 450458 : // for it.
4087 450458 : //
4088 450458 : // This cannot happen while the pageserver is running normally,
4089 450458 : // because you cannot create a branch from a point that isn't
4090 450458 : // present in the pageserver yet. However, we don't wait for the
4091 450458 : // branch point to be uploaded to cloud storage before creating
4092 450458 : // a branch. I.e., the branch LSN need not be remote consistent
4093 450458 : // for the branching operation to succeed.
4094 450458 : //
4095 450458 : // Hence, if we try to load a tenant in such a state where
4096 450458 : // 1. the existence of the branch was persisted (in IndexPart and/or locally)
4097 450458 : // 2. but the ancestor state is behind branch_lsn because it was not yet persisted
4098 450458 : // then we will need to wait for the ancestor timeline to
4099 450458 : // re-stream WAL up to branch_lsn before we access it.
4100 450458 : //
4101 450458 : // How can a tenant get in such a state?
4102 450458 : // - ungraceful pageserver process exit
4103 450458 : // - detach+attach => this is a bug, https://github.com/neondatabase/neon/issues/4219
4104 450458 : //
4105 450458 : // NB: this could be avoided by requiring
4106 450458 : // branch_lsn >= remote_consistent_lsn
4107 450458 : // during branch creation.
4108 450458 : match ancestor.wait_to_become_active(ctx).await {
4109 450454 : Ok(()) => {}
4110 : Err(TimelineState::Stopping) => {
4111 : // If an ancestor is stopping, it means the tenant is stopping: handle this the same as if this timeline was stopping.
4112 0 : return Err(GetReadyAncestorError::Cancelled);
4113 : }
4114 4 : Err(state) => {
4115 4 : return Err(GetReadyAncestorError::BadState {
4116 4 : timeline_id: ancestor.timeline_id,
4117 4 : state,
4118 4 : });
4119 : }
4120 : }
4121 450454 : ancestor
4122 450454 : .wait_lsn(
4123 450454 : self.ancestor_lsn,
4124 450454 : WaitLsnWaiter::Timeline(self),
4125 450454 : WaitLsnTimeout::Default,
4126 450454 : ctx,
4127 450454 : )
4128 450454 : .await
4129 450454 : .map_err(|e| match e {
4130 0 : e @ WaitLsnError::Timeout(_) => GetReadyAncestorError::AncestorLsnTimeout(e),
4131 0 : WaitLsnError::Shutdown => GetReadyAncestorError::Cancelled,
4132 0 : WaitLsnError::BadState(state) => GetReadyAncestorError::BadState {
4133 0 : timeline_id: ancestor.timeline_id,
4134 0 : state,
4135 0 : },
4136 450454 : })?;
4137 :
4138 450454 : Ok(ancestor.clone())
4139 450458 : }
4140 :
4141 594312 : pub(crate) fn get_shard_identity(&self) -> &ShardIdentity {
4142 594312 : &self.shard_identity
4143 594312 : }
4144 :
4145 : #[inline(always)]
4146 0 : pub(crate) fn shard_timeline_id(&self) -> ShardTimelineId {
4147 0 : ShardTimelineId {
4148 0 : shard_index: ShardIndex {
4149 0 : shard_number: self.shard_identity.number,
4150 0 : shard_count: self.shard_identity.count,
4151 0 : },
4152 0 : timeline_id: self.timeline_id,
4153 0 : }
4154 0 : }
4155 :
4156 : /// Returns a non-frozen open in-memory layer for ingestion.
4157 : ///
4158 : /// Takes a witness of timeline writer state lock being held, because it makes no sense to call
4159 : /// this function without holding the mutex.
4160 2608 : async fn get_layer_for_write(
4161 2608 : &self,
4162 2608 : lsn: Lsn,
4163 2608 : _guard: &tokio::sync::MutexGuard<'_, Option<TimelineWriterState>>,
4164 2608 : ctx: &RequestContext,
4165 2608 : ) -> anyhow::Result<Arc<InMemoryLayer>> {
4166 2608 : let mut guard = self.layers.write().await;
4167 :
4168 2608 : let last_record_lsn = self.get_last_record_lsn();
4169 2608 : ensure!(
4170 2608 : lsn > last_record_lsn,
4171 0 : "cannot modify relation after advancing last_record_lsn (incoming_lsn={}, last_record_lsn={})",
4172 : lsn,
4173 : last_record_lsn,
4174 : );
4175 :
4176 2608 : let layer = guard
4177 2608 : .open_mut()?
4178 2608 : .get_layer_for_write(
4179 2608 : lsn,
4180 2608 : self.conf,
4181 2608 : self.timeline_id,
4182 2608 : self.tenant_shard_id,
4183 2608 : &self.gate,
4184 2608 : &self.cancel,
4185 2608 : ctx,
4186 2608 : )
4187 2608 : .await?;
4188 2608 : Ok(layer)
4189 2608 : }
4190 :
4191 10558200 : pub(crate) fn finish_write(&self, new_lsn: Lsn) {
4192 10558200 : assert!(new_lsn.is_aligned());
4193 :
4194 10558200 : self.metrics.last_record_lsn_gauge.set(new_lsn.0 as i64);
4195 10558200 : self.last_record_lsn.advance(new_lsn);
4196 10558200 : }
4197 :
4198 : /// Freeze any existing open in-memory layer and unconditionally notify the flush loop.
4199 : ///
4200 : /// Unconditional flush loop notification is given because in sharded cases we will want to
4201 : /// leave an Lsn gap. Unsharded tenants do not have Lsn gaps.
4202 2416 : async fn freeze_inmem_layer_at(
4203 2416 : &self,
4204 2416 : at: Lsn,
4205 2416 : write_lock: &mut tokio::sync::MutexGuard<'_, Option<TimelineWriterState>>,
4206 2416 : ) -> Result<u64, FlushLayerError> {
4207 2416 : let frozen = {
4208 2416 : let mut guard = self.layers.write().await;
4209 2416 : guard
4210 2416 : .open_mut()?
4211 2416 : .try_freeze_in_memory_layer(at, &self.last_freeze_at, write_lock, &self.metrics)
4212 2416 : .await
4213 : };
4214 :
4215 2416 : if frozen {
4216 2360 : let now = Instant::now();
4217 2360 : *(self.last_freeze_ts.write().unwrap()) = now;
4218 2360 : }
4219 :
4220 : // Increment the flush cycle counter and wake up the flush task.
4221 : // Remember the new value, so that when we listen for the flush
4222 : // to finish, we know when the flush that we initiated has
4223 : // finished, instead of some other flush that was started earlier.
4224 2416 : let mut my_flush_request = 0;
4225 2416 :
4226 2416 : let flush_loop_state = { *self.flush_loop_state.lock().unwrap() };
4227 2416 : if !matches!(flush_loop_state, FlushLoopState::Running { .. }) {
4228 0 : return Err(FlushLayerError::NotRunning(flush_loop_state));
4229 2416 : }
4230 2416 :
4231 2416 : self.layer_flush_start_tx.send_modify(|(counter, lsn)| {
4232 2416 : my_flush_request = *counter + 1;
4233 2416 : *counter = my_flush_request;
4234 2416 : *lsn = std::cmp::max(at, *lsn);
4235 2416 : });
4236 2416 :
4237 2416 : assert_ne!(my_flush_request, 0);
4238 :
4239 2416 : Ok(my_flush_request)
4240 2416 : }
4241 :
4242 : /// Layer flusher task's main loop.
4243 908 : async fn flush_loop(
4244 908 : self: &Arc<Self>,
4245 908 : mut layer_flush_start_rx: tokio::sync::watch::Receiver<(u64, Lsn)>,
4246 908 : ctx: &RequestContext,
4247 908 : ) {
4248 : // Subscribe to L0 delta layer updates, for compaction backpressure.
4249 908 : let mut watch_l0 = match self.layers.read().await.layer_map() {
4250 908 : Ok(lm) => lm.watch_level0_deltas(),
4251 0 : Err(Shutdown) => return,
4252 : };
4253 :
4254 908 : info!("started flush loop");
4255 : loop {
4256 3288 : tokio::select! {
4257 3288 : _ = self.cancel.cancelled() => {
4258 20 : info!("shutting down layer flush task due to Timeline::cancel");
4259 20 : break;
4260 : },
4261 3288 : _ = layer_flush_start_rx.changed() => {}
4262 2380 : }
4263 2380 : trace!("waking up");
4264 2380 : let (flush_counter, frozen_to_lsn) = *layer_flush_start_rx.borrow();
4265 2380 :
4266 2380 : // The highest LSN to which we flushed in the loop over frozen layers
4267 2380 : let mut flushed_to_lsn = Lsn(0);
4268 :
4269 2380 : let result = loop {
4270 4740 : if self.cancel.is_cancelled() {
4271 0 : info!("dropping out of flush loop for timeline shutdown");
4272 : // Note: we do not bother transmitting into [`layer_flush_done_tx`], because
4273 : // anyone waiting on that will respect self.cancel as well: they will stop
4274 : // waiting at the same time we as drop out of this loop.
4275 0 : return;
4276 4740 : }
4277 4740 :
4278 4740 : // Break to notify potential waiters as soon as we've flushed the requested LSN. If
4279 4740 : // more requests have arrived in the meanwhile, we'll resume flushing afterwards.
4280 4740 : if flushed_to_lsn >= frozen_to_lsn {
4281 2324 : break Ok(());
4282 2416 : }
4283 :
4284 : // Fetch the next layer to flush, if any.
4285 2416 : let (layer, l0_count, frozen_count, frozen_size) = {
4286 2416 : let layers = self.layers.read().await;
4287 2416 : let Ok(lm) = layers.layer_map() else {
4288 0 : info!("dropping out of flush loop for timeline shutdown");
4289 0 : return;
4290 : };
4291 2416 : let l0_count = lm.level0_deltas().len();
4292 2416 : let frozen_count = lm.frozen_layers.len();
4293 2416 : let frozen_size: u64 = lm
4294 2416 : .frozen_layers
4295 2416 : .iter()
4296 2416 : .map(|l| l.estimated_in_mem_size())
4297 2416 : .sum();
4298 2416 : let layer = lm.frozen_layers.front().cloned();
4299 2416 : (layer, l0_count, frozen_count, frozen_size)
4300 2416 : // drop 'layers' lock
4301 2416 : };
4302 2416 : let Some(layer) = layer else {
4303 56 : break Ok(());
4304 : };
4305 :
4306 : // Stall flushes to backpressure if compaction can't keep up. This is propagated up
4307 : // to WAL ingestion by having ephemeral layer rolls wait for flushes.
4308 2360 : if let Some(stall_threshold) = self.get_l0_flush_stall_threshold() {
4309 0 : if l0_count >= stall_threshold {
4310 0 : warn!(
4311 0 : "stalling layer flushes for compaction backpressure at {l0_count} \
4312 0 : L0 layers ({frozen_count} frozen layers with {frozen_size} bytes)"
4313 : );
4314 0 : let stall_timer = self
4315 0 : .metrics
4316 0 : .flush_delay_histo
4317 0 : .start_timer()
4318 0 : .record_on_drop();
4319 0 : tokio::select! {
4320 0 : result = watch_l0.wait_for(|l0| *l0 < stall_threshold) => {
4321 0 : if let Ok(l0) = result.as_deref() {
4322 0 : let delay = stall_timer.elapsed().as_secs_f64();
4323 0 : info!("resuming layer flushes at {l0} L0 layers after {delay:.3}s");
4324 0 : }
4325 : },
4326 0 : _ = self.cancel.cancelled() => {},
4327 : }
4328 0 : continue; // check again
4329 0 : }
4330 2360 : }
4331 :
4332 : // Flush the layer.
4333 2360 : let flush_timer = self.metrics.flush_time_histo.start_timer();
4334 2360 : match self.flush_frozen_layer(layer, ctx).await {
4335 2360 : Ok(layer_lsn) => flushed_to_lsn = max(flushed_to_lsn, layer_lsn),
4336 : Err(FlushLayerError::Cancelled) => {
4337 0 : info!("dropping out of flush loop for timeline shutdown");
4338 0 : return;
4339 : }
4340 0 : err @ Err(
4341 0 : FlushLayerError::NotRunning(_)
4342 0 : | FlushLayerError::Other(_)
4343 0 : | FlushLayerError::CreateImageLayersError(_),
4344 0 : ) => {
4345 0 : error!("could not flush frozen layer: {err:?}");
4346 0 : break err.map(|_| ());
4347 : }
4348 : }
4349 2360 : let flush_duration = flush_timer.stop_and_record();
4350 2360 :
4351 2360 : // Notify the tenant compaction loop if L0 compaction is needed.
4352 2360 : let l0_count = *watch_l0.borrow();
4353 2360 : if l0_count >= self.get_compaction_threshold() {
4354 956 : self.l0_compaction_trigger.notify_one();
4355 1404 : }
4356 :
4357 : // Delay the next flush to backpressure if compaction can't keep up. We delay by the
4358 : // flush duration such that the flush takes 2x as long. This is propagated up to WAL
4359 : // ingestion by having ephemeral layer rolls wait for flushes.
4360 2360 : if let Some(delay_threshold) = self.get_l0_flush_delay_threshold() {
4361 4 : if l0_count >= delay_threshold {
4362 0 : let delay = flush_duration.as_secs_f64();
4363 0 : info!(
4364 0 : "delaying layer flush by {delay:.3}s for compaction backpressure at \
4365 0 : {l0_count} L0 layers ({frozen_count} frozen layers with {frozen_size} bytes)"
4366 : );
4367 0 : let _delay_timer = self
4368 0 : .metrics
4369 0 : .flush_delay_histo
4370 0 : .start_timer()
4371 0 : .record_on_drop();
4372 0 : tokio::select! {
4373 0 : _ = tokio::time::sleep(flush_duration) => {},
4374 0 : _ = watch_l0.wait_for(|l0| *l0 < delay_threshold) => {},
4375 0 : _ = self.cancel.cancelled() => {},
4376 : }
4377 4 : }
4378 2356 : }
4379 : };
4380 :
4381 : // Unsharded tenants should never advance their LSN beyond the end of the
4382 : // highest layer they write: such gaps between layer data and the frozen LSN
4383 : // are only legal on sharded tenants.
4384 2380 : debug_assert!(
4385 2380 : self.shard_identity.count.count() > 1
4386 2380 : || flushed_to_lsn >= frozen_to_lsn
4387 56 : || !flushed_to_lsn.is_valid()
4388 : );
4389 :
4390 2380 : if flushed_to_lsn < frozen_to_lsn && self.shard_identity.count.count() > 1 {
4391 : // If our layer flushes didn't carry disk_consistent_lsn up to the `to_lsn` advertised
4392 : // to us via layer_flush_start_rx, then advance it here.
4393 : //
4394 : // This path is only taken for tenants with multiple shards: single sharded tenants should
4395 : // never encounter a gap in the wal.
4396 0 : let old_disk_consistent_lsn = self.disk_consistent_lsn.load();
4397 0 : tracing::debug!(
4398 0 : "Advancing disk_consistent_lsn across layer gap {old_disk_consistent_lsn}->{frozen_to_lsn}"
4399 : );
4400 0 : if self.set_disk_consistent_lsn(frozen_to_lsn) {
4401 0 : if let Err(e) = self.schedule_uploads(frozen_to_lsn, vec![]) {
4402 0 : tracing::warn!(
4403 0 : "Failed to schedule metadata upload after updating disk_consistent_lsn: {e}"
4404 : );
4405 0 : }
4406 0 : }
4407 2380 : }
4408 :
4409 : // Notify any listeners that we're done
4410 2380 : let _ = self
4411 2380 : .layer_flush_done_tx
4412 2380 : .send_replace((flush_counter, result));
4413 : }
4414 20 : }
4415 :
4416 : /// Waits any flush request created by [`Self::freeze_inmem_layer_at`] to complete.
4417 2256 : async fn wait_flush_completion(&self, request: u64) -> Result<(), FlushLayerError> {
4418 2256 : let mut rx = self.layer_flush_done_tx.subscribe();
4419 : loop {
4420 : {
4421 4580 : let (last_result_counter, last_result) = &*rx.borrow();
4422 4580 : if *last_result_counter >= request {
4423 2256 : if let Err(err) = last_result {
4424 : // We already logged the original error in
4425 : // flush_loop. We cannot propagate it to the caller
4426 : // here, because it might not be Cloneable
4427 0 : return Err(err.clone());
4428 : } else {
4429 2256 : return Ok(());
4430 : }
4431 2324 : }
4432 2324 : }
4433 2324 : trace!("waiting for flush to complete");
4434 2324 : tokio::select! {
4435 2324 : rx_e = rx.changed() => {
4436 2324 : rx_e.map_err(|_| FlushLayerError::NotRunning(*self.flush_loop_state.lock().unwrap()))?;
4437 : },
4438 : // Cancellation safety: we are not leaving an I/O in-flight for the flush, we're just ignoring
4439 : // the notification from [`flush_loop`] that it completed.
4440 2324 : _ = self.cancel.cancelled() => {
4441 0 : tracing::info!("Cancelled layer flush due on timeline shutdown");
4442 0 : return Ok(())
4443 : }
4444 : };
4445 2324 : trace!("done")
4446 : }
4447 2256 : }
4448 :
4449 : /// Flush one frozen in-memory layer to disk, as a new delta layer.
4450 : ///
4451 : /// Return value is the last lsn (inclusive) of the layer that was frozen.
4452 : #[instrument(skip_all, fields(layer=%frozen_layer))]
4453 : async fn flush_frozen_layer(
4454 : self: &Arc<Self>,
4455 : frozen_layer: Arc<InMemoryLayer>,
4456 : ctx: &RequestContext,
4457 : ) -> Result<Lsn, FlushLayerError> {
4458 : debug_assert_current_span_has_tenant_and_timeline_id();
4459 :
4460 : // As a special case, when we have just imported an image into the repository,
4461 : // instead of writing out a L0 delta layer, we directly write out image layer
4462 : // files instead. This is possible as long as *all* the data imported into the
4463 : // repository have the same LSN.
4464 : let lsn_range = frozen_layer.get_lsn_range();
4465 :
4466 : // Whether to directly create image layers for this flush, or flush them as delta layers
4467 : let create_image_layer =
4468 : lsn_range.start == self.initdb_lsn && lsn_range.end == Lsn(self.initdb_lsn.0 + 1);
4469 :
4470 : #[cfg(test)]
4471 : {
4472 : match &mut *self.flush_loop_state.lock().unwrap() {
4473 : FlushLoopState::NotStarted | FlushLoopState::Exited => {
4474 : panic!("flush loop not running")
4475 : }
4476 : FlushLoopState::Running {
4477 : expect_initdb_optimization,
4478 : initdb_optimization_count,
4479 : ..
4480 : } => {
4481 : if create_image_layer {
4482 : *initdb_optimization_count += 1;
4483 : } else {
4484 : assert!(!*expect_initdb_optimization, "expected initdb optimization");
4485 : }
4486 : }
4487 : }
4488 : }
4489 :
4490 : let (layers_to_upload, delta_layer_to_add) = if create_image_layer {
4491 : // Note: The 'ctx' in use here has DownloadBehavior::Error. We should not
4492 : // require downloading anything during initial import.
4493 : let ((rel_partition, metadata_partition), _lsn) = self
4494 : .repartition(
4495 : self.initdb_lsn,
4496 : self.get_compaction_target_size(),
4497 : EnumSet::empty(),
4498 : ctx,
4499 : )
4500 : .await
4501 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e.into()))?;
4502 :
4503 : if self.cancel.is_cancelled() {
4504 : return Err(FlushLayerError::Cancelled);
4505 : }
4506 :
4507 : // Ensure that we have a single call to `create_image_layers` with a combined dense keyspace.
4508 : // So that the key ranges don't overlap.
4509 : let mut partitions = KeyPartitioning::default();
4510 : partitions.parts.extend(rel_partition.parts);
4511 : if !metadata_partition.parts.is_empty() {
4512 : assert_eq!(
4513 : metadata_partition.parts.len(),
4514 : 1,
4515 : "currently sparse keyspace should only contain a single metadata keyspace"
4516 : );
4517 : // Safety: create_image_layers treat sparse keyspaces differently that it does not scan
4518 : // every single key within the keyspace, and therefore, it's safe to force converting it
4519 : // into a dense keyspace before calling this function.
4520 : partitions
4521 : .parts
4522 : .extend(metadata_partition.into_dense().parts);
4523 : }
4524 :
4525 : let mut layers_to_upload = Vec::new();
4526 : let (generated_image_layers, is_complete) = self
4527 : .create_image_layers(
4528 : &partitions,
4529 : self.initdb_lsn,
4530 : ImageLayerCreationMode::Initial,
4531 : ctx,
4532 : LastImageLayerCreationStatus::Initial,
4533 : false, // don't yield for L0, we're flushing L0
4534 : )
4535 : .await?;
4536 : debug_assert!(
4537 : matches!(is_complete, LastImageLayerCreationStatus::Complete),
4538 : "init image generation mode must fully cover the keyspace"
4539 : );
4540 : layers_to_upload.extend(generated_image_layers);
4541 :
4542 : (layers_to_upload, None)
4543 : } else {
4544 : // Normal case, write out a L0 delta layer file.
4545 : // `create_delta_layer` will not modify the layer map.
4546 : // We will remove frozen layer and add delta layer in one atomic operation later.
4547 : let Some(layer) = self
4548 : .create_delta_layer(&frozen_layer, None, ctx)
4549 : .await
4550 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e))?
4551 : else {
4552 : panic!("delta layer cannot be empty if no filter is applied");
4553 : };
4554 : (
4555 : // FIXME: even though we have a single image and single delta layer assumption
4556 : // we push them to vec
4557 : vec![layer.clone()],
4558 : Some(layer),
4559 : )
4560 : };
4561 :
4562 : pausable_failpoint!("flush-layer-cancel-after-writing-layer-out-pausable");
4563 :
4564 : if self.cancel.is_cancelled() {
4565 : return Err(FlushLayerError::Cancelled);
4566 : }
4567 :
4568 : let disk_consistent_lsn = Lsn(lsn_range.end.0 - 1);
4569 :
4570 : // The new on-disk layers are now in the layer map. We can remove the
4571 : // in-memory layer from the map now. The flushed layer is stored in
4572 : // the mapping in `create_delta_layer`.
4573 : {
4574 : let mut guard = self.layers.write().await;
4575 :
4576 : guard.open_mut()?.finish_flush_l0_layer(
4577 : delta_layer_to_add.as_ref(),
4578 : &frozen_layer,
4579 : &self.metrics,
4580 : );
4581 :
4582 : if self.set_disk_consistent_lsn(disk_consistent_lsn) {
4583 : // Schedule remote uploads that will reflect our new disk_consistent_lsn
4584 : self.schedule_uploads(disk_consistent_lsn, layers_to_upload)
4585 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e))?;
4586 : }
4587 : // release lock on 'layers'
4588 : };
4589 :
4590 : // FIXME: between create_delta_layer and the scheduling of the upload in `update_metadata_file`,
4591 : // a compaction can delete the file and then it won't be available for uploads any more.
4592 : // We still schedule the upload, resulting in an error, but ideally we'd somehow avoid this
4593 : // race situation.
4594 : // See https://github.com/neondatabase/neon/issues/4526
4595 : pausable_failpoint!("flush-frozen-pausable");
4596 :
4597 : // This failpoint is used by another test case `test_pageserver_recovery`.
4598 : fail_point!("flush-frozen-exit");
4599 :
4600 : Ok(Lsn(lsn_range.end.0 - 1))
4601 : }
4602 :
4603 : /// Return true if the value changed
4604 : ///
4605 : /// This function must only be used from the layer flush task.
4606 2360 : fn set_disk_consistent_lsn(&self, new_value: Lsn) -> bool {
4607 2360 : let old_value = self.disk_consistent_lsn.fetch_max(new_value);
4608 2360 : assert!(
4609 2360 : new_value >= old_value,
4610 0 : "disk_consistent_lsn must be growing monotonously at runtime; current {old_value}, offered {new_value}"
4611 : );
4612 :
4613 2360 : self.metrics
4614 2360 : .disk_consistent_lsn_gauge
4615 2360 : .set(new_value.0 as i64);
4616 2360 : new_value != old_value
4617 2360 : }
4618 :
4619 : /// Update metadata file
4620 2460 : fn schedule_uploads(
4621 2460 : &self,
4622 2460 : disk_consistent_lsn: Lsn,
4623 2460 : layers_to_upload: impl IntoIterator<Item = ResidentLayer>,
4624 2460 : ) -> anyhow::Result<()> {
4625 2460 : // We can only save a valid 'prev_record_lsn' value on disk if we
4626 2460 : // flushed *all* in-memory changes to disk. We only track
4627 2460 : // 'prev_record_lsn' in memory for the latest processed record, so we
4628 2460 : // don't remember what the correct value that corresponds to some old
4629 2460 : // LSN is. But if we flush everything, then the value corresponding
4630 2460 : // current 'last_record_lsn' is correct and we can store it on disk.
4631 2460 : let RecordLsn {
4632 2460 : last: last_record_lsn,
4633 2460 : prev: prev_record_lsn,
4634 2460 : } = self.last_record_lsn.load();
4635 2460 : let ondisk_prev_record_lsn = if disk_consistent_lsn == last_record_lsn {
4636 2205 : Some(prev_record_lsn)
4637 : } else {
4638 255 : None
4639 : };
4640 :
4641 2460 : let update = crate::tenant::metadata::MetadataUpdate::new(
4642 2460 : disk_consistent_lsn,
4643 2460 : ondisk_prev_record_lsn,
4644 2460 : *self.applied_gc_cutoff_lsn.read(),
4645 2460 : );
4646 2460 :
4647 2460 : fail_point!("checkpoint-before-saving-metadata", |x| bail!(
4648 0 : "{}",
4649 0 : x.unwrap()
4650 2460 : ));
4651 :
4652 4844 : for layer in layers_to_upload {
4653 2384 : self.remote_client.schedule_layer_file_upload(layer)?;
4654 : }
4655 2460 : self.remote_client
4656 2460 : .schedule_index_upload_for_metadata_update(&update)?;
4657 :
4658 2460 : Ok(())
4659 2460 : }
4660 :
4661 0 : pub(crate) async fn preserve_initdb_archive(&self) -> anyhow::Result<()> {
4662 0 : self.remote_client
4663 0 : .preserve_initdb_archive(
4664 0 : &self.tenant_shard_id.tenant_id,
4665 0 : &self.timeline_id,
4666 0 : &self.cancel,
4667 0 : )
4668 0 : .await
4669 0 : }
4670 :
4671 : // Write out the given frozen in-memory layer as a new L0 delta file. This L0 file will not be tracked
4672 : // in layer map immediately. The caller is responsible to put it into the layer map.
4673 1936 : async fn create_delta_layer(
4674 1936 : self: &Arc<Self>,
4675 1936 : frozen_layer: &Arc<InMemoryLayer>,
4676 1936 : key_range: Option<Range<Key>>,
4677 1936 : ctx: &RequestContext,
4678 1936 : ) -> anyhow::Result<Option<ResidentLayer>> {
4679 1936 : let self_clone = Arc::clone(self);
4680 1936 : let frozen_layer = Arc::clone(frozen_layer);
4681 1936 : let ctx = ctx.attached_child();
4682 1936 : let work = async move {
4683 1936 : let Some((desc, path)) = frozen_layer
4684 1936 : .write_to_disk(&ctx, key_range, self_clone.l0_flush_global_state.inner())
4685 1936 : .await?
4686 : else {
4687 0 : return Ok(None);
4688 : };
4689 1936 : let new_delta = Layer::finish_creating(self_clone.conf, &self_clone, desc, &path)?;
4690 :
4691 : // The write_to_disk() above calls writer.finish() which already did the fsync of the inodes.
4692 : // We just need to fsync the directory in which these inodes are linked,
4693 : // which we know to be the timeline directory.
4694 : //
4695 : // We use fatal_err() below because the after write_to_disk returns with success,
4696 : // the in-memory state of the filesystem already has the layer file in its final place,
4697 : // and subsequent pageserver code could think it's durable while it really isn't.
4698 1936 : let timeline_dir = VirtualFile::open(
4699 1936 : &self_clone
4700 1936 : .conf
4701 1936 : .timeline_path(&self_clone.tenant_shard_id, &self_clone.timeline_id),
4702 1936 : &ctx,
4703 1936 : )
4704 1936 : .await
4705 1936 : .fatal_err("VirtualFile::open for timeline dir fsync");
4706 1936 : timeline_dir
4707 1936 : .sync_all()
4708 1936 : .await
4709 1936 : .fatal_err("VirtualFile::sync_all timeline dir");
4710 1936 : anyhow::Ok(Some(new_delta))
4711 1936 : };
4712 : // Before tokio-epoll-uring, we ran write_to_disk & the sync_all inside spawn_blocking.
4713 : // Preserve that behavior to maintain the same behavior for `virtual_file_io_engine=std-fs`.
4714 : use crate::virtual_file::io_engine::IoEngine;
4715 1936 : match crate::virtual_file::io_engine::get() {
4716 0 : IoEngine::NotSet => panic!("io engine not set"),
4717 : IoEngine::StdFs => {
4718 968 : let span = tracing::info_span!("blocking");
4719 968 : tokio::task::spawn_blocking({
4720 968 : move || Handle::current().block_on(work.instrument(span))
4721 968 : })
4722 968 : .await
4723 968 : .context("spawn_blocking")
4724 968 : .and_then(|x| x)
4725 : }
4726 : #[cfg(target_os = "linux")]
4727 968 : IoEngine::TokioEpollUring => work.await,
4728 : }
4729 1936 : }
4730 :
4731 1149 : async fn repartition(
4732 1149 : &self,
4733 1149 : lsn: Lsn,
4734 1149 : partition_size: u64,
4735 1149 : flags: EnumSet<CompactFlags>,
4736 1149 : ctx: &RequestContext,
4737 1149 : ) -> Result<((KeyPartitioning, SparseKeyPartitioning), Lsn), CompactionError> {
4738 1149 : let Ok(mut guard) = self.partitioning.try_write_guard() else {
4739 : // NB: there are two callers, one is the compaction task, of which there is only one per struct Tenant and hence Timeline.
4740 : // The other is the initdb optimization in flush_frozen_layer, used by `boostrap_timeline`, which runs before `.activate()`
4741 : // and hence before the compaction task starts.
4742 0 : return Err(CompactionError::Other(anyhow!(
4743 0 : "repartition() called concurrently"
4744 0 : )));
4745 : };
4746 1149 : let ((dense_partition, sparse_partition), partition_lsn) = &*guard.read();
4747 1149 : if lsn < *partition_lsn {
4748 0 : return Err(CompactionError::Other(anyhow!(
4749 0 : "repartition() called with LSN going backwards, this should not happen"
4750 0 : )));
4751 1149 : }
4752 1149 :
4753 1149 : let distance = lsn.0 - partition_lsn.0;
4754 1149 : if *partition_lsn != Lsn(0)
4755 521 : && distance <= self.repartition_threshold
4756 521 : && !flags.contains(CompactFlags::ForceRepartition)
4757 : {
4758 493 : debug!(
4759 : distance,
4760 : threshold = self.repartition_threshold,
4761 0 : "no repartitioning needed"
4762 : );
4763 493 : return Ok((
4764 493 : (dense_partition.clone(), sparse_partition.clone()),
4765 493 : *partition_lsn,
4766 493 : ));
4767 656 : }
4768 :
4769 656 : let (dense_ks, sparse_ks) = self.collect_keyspace(lsn, ctx).await?;
4770 656 : let dense_partitioning = dense_ks.partition(&self.shard_identity, partition_size);
4771 656 : let sparse_partitioning = SparseKeyPartitioning {
4772 656 : parts: vec![sparse_ks],
4773 656 : }; // no partitioning for metadata keys for now
4774 656 : let result = ((dense_partitioning, sparse_partitioning), lsn);
4775 656 : guard.write(result.clone());
4776 656 : Ok(result)
4777 1149 : }
4778 :
4779 : // Is it time to create a new image layer for the given partition? True if we want to generate.
4780 28 : async fn time_for_new_image_layer(&self, partition: &KeySpace, lsn: Lsn) -> bool {
4781 28 : let threshold = self.get_image_creation_threshold();
4782 :
4783 28 : let guard = self.layers.read().await;
4784 28 : let Ok(layers) = guard.layer_map() else {
4785 0 : return false;
4786 : };
4787 :
4788 28 : let mut max_deltas = 0;
4789 56 : for part_range in &partition.ranges {
4790 28 : let image_coverage = layers.image_coverage(part_range, lsn);
4791 56 : for (img_range, last_img) in image_coverage {
4792 28 : let img_lsn = if let Some(last_img) = last_img {
4793 0 : last_img.get_lsn_range().end
4794 : } else {
4795 28 : Lsn(0)
4796 : };
4797 : // Let's consider an example:
4798 : //
4799 : // delta layer with LSN range 71-81
4800 : // delta layer with LSN range 81-91
4801 : // delta layer with LSN range 91-101
4802 : // image layer at LSN 100
4803 : //
4804 : // If 'lsn' is still 100, i.e. no new WAL has been processed since the last image layer,
4805 : // there's no need to create a new one. We check this case explicitly, to avoid passing
4806 : // a bogus range to count_deltas below, with start > end. It's even possible that there
4807 : // are some delta layers *later* than current 'lsn', if more WAL was processed and flushed
4808 : // after we read last_record_lsn, which is passed here in the 'lsn' argument.
4809 28 : if img_lsn < lsn {
4810 28 : let num_deltas =
4811 28 : layers.count_deltas(&img_range, &(img_lsn..lsn), Some(threshold));
4812 28 :
4813 28 : max_deltas = max_deltas.max(num_deltas);
4814 28 : if num_deltas >= threshold {
4815 0 : debug!(
4816 0 : "key range {}-{}, has {} deltas on this timeline in LSN range {}..{}",
4817 : img_range.start, img_range.end, num_deltas, img_lsn, lsn
4818 : );
4819 0 : return true;
4820 28 : }
4821 0 : }
4822 : }
4823 : }
4824 :
4825 28 : debug!(
4826 : max_deltas,
4827 0 : "none of the partitioned ranges had >= {threshold} deltas"
4828 : );
4829 28 : false
4830 28 : }
4831 :
4832 : /// Create image layers for Postgres data. Assumes the caller passes a partition that is not too large,
4833 : /// so that at most one image layer will be produced from this function.
4834 : #[allow(clippy::too_many_arguments)]
4835 476 : async fn create_image_layer_for_rel_blocks(
4836 476 : self: &Arc<Self>,
4837 476 : partition: &KeySpace,
4838 476 : mut image_layer_writer: ImageLayerWriter,
4839 476 : lsn: Lsn,
4840 476 : ctx: &RequestContext,
4841 476 : img_range: Range<Key>,
4842 476 : io_concurrency: IoConcurrency,
4843 476 : ) -> Result<ImageLayerCreationOutcome, CreateImageLayersError> {
4844 476 : let mut wrote_keys = false;
4845 476 :
4846 476 : let mut key_request_accum = KeySpaceAccum::new();
4847 3156 : for range in &partition.ranges {
4848 2680 : let mut key = range.start;
4849 5808 : while key < range.end {
4850 : // Decide whether to retain this key: usually we do, but sharded tenants may
4851 : // need to drop keys that don't belong to them. If we retain the key, add it
4852 : // to `key_request_accum` for later issuing a vectored get
4853 3128 : if self.shard_identity.is_key_disposable(&key) {
4854 0 : debug!(
4855 0 : "Dropping key {} during compaction (it belongs on shard {:?})",
4856 0 : key,
4857 0 : self.shard_identity.get_shard_number(&key)
4858 : );
4859 3128 : } else {
4860 3128 : key_request_accum.add_key(key);
4861 3128 : }
4862 :
4863 3128 : let last_key_in_range = key.next() == range.end;
4864 3128 : key = key.next();
4865 3128 :
4866 3128 : // Maybe flush `key_rest_accum`
4867 3128 : if key_request_accum.raw_size() >= Timeline::MAX_GET_VECTORED_KEYS
4868 3128 : || (last_key_in_range && key_request_accum.raw_size() > 0)
4869 : {
4870 2680 : let results = self
4871 2680 : .get_vectored(
4872 2680 : key_request_accum.consume_keyspace(),
4873 2680 : lsn,
4874 2680 : io_concurrency.clone(),
4875 2680 : ctx,
4876 2680 : )
4877 2680 : .await?;
4878 :
4879 2680 : if self.cancel.is_cancelled() {
4880 0 : return Err(CreateImageLayersError::Cancelled);
4881 2680 : }
4882 :
4883 5808 : for (img_key, img) in results {
4884 3128 : let img = match img {
4885 3128 : Ok(img) => img,
4886 0 : Err(err) => {
4887 0 : // If we fail to reconstruct a VM or FSM page, we can zero the
4888 0 : // page without losing any actual user data. That seems better
4889 0 : // than failing repeatedly and getting stuck.
4890 0 : //
4891 0 : // We had a bug at one point, where we truncated the FSM and VM
4892 0 : // in the pageserver, but the Postgres didn't know about that
4893 0 : // and continued to generate incremental WAL records for pages
4894 0 : // that didn't exist in the pageserver. Trying to replay those
4895 0 : // WAL records failed to find the previous image of the page.
4896 0 : // This special case allows us to recover from that situation.
4897 0 : // See https://github.com/neondatabase/neon/issues/2601.
4898 0 : //
4899 0 : // Unfortunately we cannot do this for the main fork, or for
4900 0 : // any metadata keys, keys, as that would lead to actual data
4901 0 : // loss.
4902 0 : if img_key.is_rel_fsm_block_key() || img_key.is_rel_vm_block_key() {
4903 0 : warn!(
4904 0 : "could not reconstruct FSM or VM key {img_key}, filling with zeros: {err:?}"
4905 : );
4906 0 : ZERO_PAGE.clone()
4907 : } else {
4908 0 : return Err(CreateImageLayersError::from(err));
4909 : }
4910 : }
4911 : };
4912 :
4913 : // Write all the keys we just read into our new image layer.
4914 3128 : image_layer_writer.put_image(img_key, img, ctx).await?;
4915 3128 : wrote_keys = true;
4916 : }
4917 448 : }
4918 : }
4919 : }
4920 :
4921 476 : if wrote_keys {
4922 : // Normal path: we have written some data into the new image layer for this
4923 : // partition, so flush it to disk.
4924 476 : info!(
4925 0 : "produced image layer for rel {}",
4926 0 : ImageLayerName {
4927 0 : key_range: img_range.clone(),
4928 0 : lsn
4929 0 : },
4930 : );
4931 476 : Ok(ImageLayerCreationOutcome::Generated {
4932 476 : unfinished_image_layer: image_layer_writer,
4933 476 : })
4934 : } else {
4935 0 : tracing::debug!("no data in range {}-{}", img_range.start, img_range.end);
4936 0 : Ok(ImageLayerCreationOutcome::Empty)
4937 : }
4938 476 : }
4939 :
4940 : /// Create an image layer for metadata keys. This function produces one image layer for all metadata
4941 : /// keys for now. Because metadata keys cannot exceed basebackup size limit, the image layer for it
4942 : /// would not be too large to fit in a single image layer.
4943 : ///
4944 : /// Creating image layers for metadata keys are different from relational keys. Firstly, instead of
4945 : /// iterating each key and get an image for each of them, we do a `vectored_get` scan over the sparse
4946 : /// keyspace to get all images in one run. Secondly, we use a different image layer generation metrics
4947 : /// for metadata keys than relational keys, which is the number of delta files visited during the scan.
4948 : #[allow(clippy::too_many_arguments)]
4949 456 : async fn create_image_layer_for_metadata_keys(
4950 456 : self: &Arc<Self>,
4951 456 : partition: &KeySpace,
4952 456 : mut image_layer_writer: ImageLayerWriter,
4953 456 : lsn: Lsn,
4954 456 : ctx: &RequestContext,
4955 456 : img_range: Range<Key>,
4956 456 : mode: ImageLayerCreationMode,
4957 456 : io_concurrency: IoConcurrency,
4958 456 : ) -> Result<ImageLayerCreationOutcome, CreateImageLayersError> {
4959 456 : // Metadata keys image layer creation.
4960 456 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
4961 456 : let begin = Instant::now();
4962 : // Directly use `get_vectored_impl` to skip the max_vectored_read_key limit check. Note that the keyspace should
4963 : // not contain too many keys, otherwise this takes a lot of memory.
4964 456 : let data = self
4965 456 : .get_vectored_impl(partition.clone(), lsn, &mut reconstruct_state, ctx)
4966 456 : .await?;
4967 456 : let (data, total_kb_retrieved, total_keys_retrieved) = {
4968 456 : let mut new_data = BTreeMap::new();
4969 456 : let mut total_kb_retrieved = 0;
4970 456 : let mut total_keys_retrieved = 0;
4971 20480 : for (k, v) in data {
4972 20024 : let v = v?;
4973 20024 : total_kb_retrieved += KEY_SIZE + v.len();
4974 20024 : total_keys_retrieved += 1;
4975 20024 : new_data.insert(k, v);
4976 : }
4977 456 : (new_data, total_kb_retrieved / 1024, total_keys_retrieved)
4978 456 : };
4979 456 : let delta_files_accessed = reconstruct_state.get_delta_layers_visited();
4980 456 : let elapsed = begin.elapsed();
4981 456 :
4982 456 : let trigger_generation = delta_files_accessed as usize >= MAX_AUX_FILE_V2_DELTAS;
4983 456 : info!(
4984 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",
4985 0 : elapsed.as_secs_f64()
4986 : );
4987 :
4988 456 : if !trigger_generation && mode == ImageLayerCreationMode::Try {
4989 4 : return Ok(ImageLayerCreationOutcome::Skip);
4990 452 : }
4991 452 : if self.cancel.is_cancelled() {
4992 0 : return Err(CreateImageLayersError::Cancelled);
4993 452 : }
4994 452 : let mut wrote_any_image = false;
4995 20476 : for (k, v) in data {
4996 20024 : if v.is_empty() {
4997 : // the key has been deleted, it does not need an image
4998 : // in metadata keyspace, an empty image == tombstone
4999 16 : continue;
5000 20008 : }
5001 20008 : wrote_any_image = true;
5002 20008 :
5003 20008 : // No need to handle sharding b/c metadata keys are always on the 0-th shard.
5004 20008 :
5005 20008 : // TODO: split image layers to avoid too large layer files. Too large image files are not handled
5006 20008 : // on the normal data path either.
5007 20008 : image_layer_writer.put_image(k, v, ctx).await?;
5008 : }
5009 :
5010 452 : if wrote_any_image {
5011 : // Normal path: we have written some data into the new image layer for this
5012 : // partition, so flush it to disk.
5013 24 : info!(
5014 0 : "created image layer for metadata {}",
5015 0 : ImageLayerName {
5016 0 : key_range: img_range.clone(),
5017 0 : lsn
5018 0 : }
5019 : );
5020 24 : Ok(ImageLayerCreationOutcome::Generated {
5021 24 : unfinished_image_layer: image_layer_writer,
5022 24 : })
5023 : } else {
5024 428 : tracing::debug!("no data in range {}-{}", img_range.start, img_range.end);
5025 428 : Ok(ImageLayerCreationOutcome::Empty)
5026 : }
5027 456 : }
5028 :
5029 : /// Predicate function which indicates whether we should check if new image layers
5030 : /// are required. Since checking if new image layers are required is expensive in
5031 : /// terms of CPU, we only do it in the following cases:
5032 : /// 1. If the timeline has ingested sufficient WAL to justify the cost
5033 : /// 2. If enough time has passed since the last check:
5034 : /// 1. For large tenants, we wish to perform the check more often since they
5035 : /// suffer from the lack of image layers
5036 : /// 2. For small tenants (that can mostly fit in RAM), we use a much longer interval
5037 1149 : fn should_check_if_image_layers_required(self: &Arc<Timeline>, lsn: Lsn) -> bool {
5038 : const LARGE_TENANT_THRESHOLD: u64 = 2 * 1024 * 1024 * 1024;
5039 :
5040 1149 : let last_checks_at = self.last_image_layer_creation_check_at.load();
5041 1149 : let distance = lsn
5042 1149 : .checked_sub(last_checks_at)
5043 1149 : .expect("Attempt to compact with LSN going backwards");
5044 1149 : let min_distance =
5045 1149 : self.get_image_layer_creation_check_threshold() as u64 * self.get_checkpoint_distance();
5046 1149 :
5047 1149 : let distance_based_decision = distance.0 >= min_distance;
5048 1149 :
5049 1149 : let mut time_based_decision = false;
5050 1149 : let mut last_check_instant = self.last_image_layer_creation_check_instant.lock().unwrap();
5051 1149 : if let CurrentLogicalSize::Exact(logical_size) = self.current_logical_size.current_size() {
5052 945 : let check_required_after = if Into::<u64>::into(&logical_size) >= LARGE_TENANT_THRESHOLD
5053 : {
5054 0 : self.get_checkpoint_timeout()
5055 : } else {
5056 945 : Duration::from_secs(3600 * 48)
5057 : };
5058 :
5059 945 : time_based_decision = match *last_check_instant {
5060 521 : Some(last_check) => {
5061 521 : let elapsed = last_check.elapsed();
5062 521 : elapsed >= check_required_after
5063 : }
5064 424 : None => true,
5065 : };
5066 204 : }
5067 :
5068 : // Do the expensive delta layer counting only if this timeline has ingested sufficient
5069 : // WAL since the last check or a checkpoint timeout interval has elapsed since the last
5070 : // check.
5071 1149 : let decision = distance_based_decision || time_based_decision;
5072 :
5073 1149 : if decision {
5074 428 : self.last_image_layer_creation_check_at.store(lsn);
5075 428 : *last_check_instant = Some(Instant::now());
5076 721 : }
5077 :
5078 1149 : decision
5079 1149 : }
5080 :
5081 : /// Returns the image layers generated and an enum indicating whether the process is fully completed.
5082 : /// true = we have generate all image layers, false = we preempt the process for L0 compaction.
5083 : #[tracing::instrument(skip_all, fields(%lsn, %mode))]
5084 : async fn create_image_layers(
5085 : self: &Arc<Timeline>,
5086 : partitioning: &KeyPartitioning,
5087 : lsn: Lsn,
5088 : mode: ImageLayerCreationMode,
5089 : ctx: &RequestContext,
5090 : last_status: LastImageLayerCreationStatus,
5091 : yield_for_l0: bool,
5092 : ) -> Result<(Vec<ResidentLayer>, LastImageLayerCreationStatus), CreateImageLayersError> {
5093 : let timer = self.metrics.create_images_time_histo.start_timer();
5094 :
5095 : if partitioning.parts.is_empty() {
5096 : warn!("no partitions to create image layers for");
5097 : return Ok((vec![], LastImageLayerCreationStatus::Complete));
5098 : }
5099 :
5100 : // We need to avoid holes between generated image layers.
5101 : // Otherwise LayerMap::image_layer_exists will return false if key range of some layer is covered by more than one
5102 : // image layer with hole between them. In this case such layer can not be utilized by GC.
5103 : //
5104 : // How such hole between partitions can appear?
5105 : // if we have relation with relid=1 and size 100 and relation with relid=2 with size 200 then result of
5106 : // KeySpace::partition may contain partitions <100000000..100000099> and <200000000..200000199>.
5107 : // If there is delta layer <100000000..300000000> then it never be garbage collected because
5108 : // image layers <100000000..100000099> and <200000000..200000199> are not completely covering it.
5109 : let mut start = Key::MIN;
5110 :
5111 : let check_for_image_layers =
5112 : if let LastImageLayerCreationStatus::Incomplete { last_key } = last_status {
5113 : info!(
5114 : "resuming image layer creation: last_status=incomplete, continue from {}",
5115 : last_key
5116 : );
5117 : true
5118 : } else {
5119 : self.should_check_if_image_layers_required(lsn)
5120 : };
5121 :
5122 : let mut batch_image_writer = BatchLayerWriter::new(self.conf).await?;
5123 :
5124 : let mut all_generated = true;
5125 :
5126 : let mut partition_processed = 0;
5127 : let mut total_partitions = partitioning.parts.len();
5128 : let mut last_partition_processed = None;
5129 : let mut partition_parts = partitioning.parts.clone();
5130 :
5131 : if let LastImageLayerCreationStatus::Incomplete { last_key } = last_status {
5132 : // We need to skip the partitions that have already been processed.
5133 : let mut found = false;
5134 : for (i, partition) in partition_parts.iter().enumerate() {
5135 : if last_key <= partition.end().unwrap() {
5136 : // ```plain
5137 : // |------|--------|----------|------|
5138 : // ^last_key
5139 : // ^start from this partition
5140 : // ```
5141 : // Why `i+1` instead of `i`?
5142 : // It is possible that the user did some writes after the previous image layer creation attempt so that
5143 : // a relation grows in size, and the last_key is now in the middle of the partition. In this case, we
5144 : // still want to skip this partition, so that we can make progress and avoid generating image layers over
5145 : // the same partition. Doing a mod to ensure we don't end up with an empty vec.
5146 : if i + 1 >= total_partitions {
5147 : // In general, this case should not happen -- if last_key is on the last partition, the previous
5148 : // iteration of image layer creation should return a complete status.
5149 : break; // with found=false
5150 : }
5151 : partition_parts = partition_parts.split_off(i + 1); // Remove the first i + 1 elements
5152 : total_partitions = partition_parts.len();
5153 : // Update the start key to the partition start.
5154 : start = partition_parts[0].start().unwrap();
5155 : found = true;
5156 : break;
5157 : }
5158 : }
5159 : if !found {
5160 : // Last key is within the last partition, or larger than all partitions.
5161 : return Ok((vec![], LastImageLayerCreationStatus::Complete));
5162 : }
5163 : }
5164 :
5165 : for partition in partition_parts.iter() {
5166 : if self.cancel.is_cancelled() {
5167 : return Err(CreateImageLayersError::Cancelled);
5168 : }
5169 : partition_processed += 1;
5170 : let img_range = start..partition.ranges.last().unwrap().end;
5171 : let compact_metadata = partition.overlaps(&Key::metadata_key_range());
5172 : if compact_metadata {
5173 : for range in &partition.ranges {
5174 : assert!(
5175 : range.start.field1 >= METADATA_KEY_BEGIN_PREFIX
5176 : && range.end.field1 <= METADATA_KEY_END_PREFIX,
5177 : "metadata keys must be partitioned separately"
5178 : );
5179 : }
5180 : if mode == ImageLayerCreationMode::Try && !check_for_image_layers {
5181 : // Skip compaction if there are not enough updates. Metadata compaction will do a scan and
5182 : // might mess up with evictions.
5183 : start = img_range.end;
5184 : continue;
5185 : }
5186 : // For initial and force modes, we always generate image layers for metadata keys.
5187 : } else if let ImageLayerCreationMode::Try = mode {
5188 : // check_for_image_layers = false -> skip
5189 : // check_for_image_layers = true -> check time_for_new_image_layer -> skip/generate
5190 : if !check_for_image_layers || !self.time_for_new_image_layer(partition, lsn).await {
5191 : start = img_range.end;
5192 : continue;
5193 : }
5194 : }
5195 : if let ImageLayerCreationMode::Force = mode {
5196 : // When forced to create image layers, we might try and create them where they already
5197 : // exist. This mode is only used in tests/debug.
5198 : let layers = self.layers.read().await;
5199 : if layers.contains_key(&PersistentLayerKey {
5200 : key_range: img_range.clone(),
5201 : lsn_range: PersistentLayerDesc::image_layer_lsn_range(lsn),
5202 : is_delta: false,
5203 : }) {
5204 : // TODO: this can be processed with the BatchLayerWriter::finish_with_discard
5205 : // in the future.
5206 : tracing::info!(
5207 : "Skipping image layer at {lsn} {}..{}, already exists",
5208 : img_range.start,
5209 : img_range.end
5210 : );
5211 : start = img_range.end;
5212 : continue;
5213 : }
5214 : }
5215 :
5216 : let image_layer_writer = ImageLayerWriter::new(
5217 : self.conf,
5218 : self.timeline_id,
5219 : self.tenant_shard_id,
5220 : &img_range,
5221 : lsn,
5222 : ctx,
5223 : )
5224 : .await?;
5225 :
5226 0 : fail_point!("image-layer-writer-fail-before-finish", |_| {
5227 0 : Err(CreateImageLayersError::Other(anyhow::anyhow!(
5228 0 : "failpoint image-layer-writer-fail-before-finish"
5229 0 : )))
5230 0 : });
5231 :
5232 : let io_concurrency = IoConcurrency::spawn_from_conf(
5233 : self.conf,
5234 : self.gate
5235 : .enter()
5236 0 : .map_err(|_| CreateImageLayersError::Cancelled)?,
5237 : );
5238 :
5239 : let outcome = if !compact_metadata {
5240 : self.create_image_layer_for_rel_blocks(
5241 : partition,
5242 : image_layer_writer,
5243 : lsn,
5244 : ctx,
5245 : img_range.clone(),
5246 : io_concurrency,
5247 : )
5248 : .await?
5249 : } else {
5250 : self.create_image_layer_for_metadata_keys(
5251 : partition,
5252 : image_layer_writer,
5253 : lsn,
5254 : ctx,
5255 : img_range.clone(),
5256 : mode,
5257 : io_concurrency,
5258 : )
5259 : .await?
5260 : };
5261 : match outcome {
5262 : ImageLayerCreationOutcome::Empty => {
5263 : // No data in this partition, so we don't need to create an image layer (for now).
5264 : // The next image layer should cover this key range, so we don't advance the `start`
5265 : // key.
5266 : }
5267 : ImageLayerCreationOutcome::Generated {
5268 : unfinished_image_layer,
5269 : } => {
5270 : batch_image_writer.add_unfinished_image_writer(
5271 : unfinished_image_layer,
5272 : img_range.clone(),
5273 : lsn,
5274 : );
5275 : // The next image layer should be generated right after this one.
5276 : start = img_range.end;
5277 : }
5278 : ImageLayerCreationOutcome::Skip => {
5279 : // We don't need to create an image layer for this partition.
5280 : // The next image layer should NOT cover this range, otherwise
5281 : // the keyspace becomes empty (reads don't go past image layers).
5282 : start = img_range.end;
5283 : }
5284 : }
5285 :
5286 : if let ImageLayerCreationMode::Try = mode {
5287 : // We have at least made some progress
5288 : if yield_for_l0 && batch_image_writer.pending_layer_num() >= 1 {
5289 : // The `Try` mode is currently only used on the compaction path. We want to avoid
5290 : // image layer generation taking too long time and blocking L0 compaction. So in this
5291 : // mode, we also inspect the current number of L0 layers and skip image layer generation
5292 : // if there are too many of them.
5293 : let image_preempt_threshold = self.get_image_creation_preempt_threshold()
5294 : * self.get_compaction_threshold();
5295 : // TODO: currently we do not respect `get_image_creation_preempt_threshold` and always yield
5296 : // when there is a single timeline with more than L0 threshold L0 layers. As long as the
5297 : // `get_image_creation_preempt_threshold` is set to a value greater than 0, we will yield for L0 compaction.
5298 : if image_preempt_threshold != 0 {
5299 : let should_yield = self
5300 : .l0_compaction_trigger
5301 : .notified()
5302 : .now_or_never()
5303 : .is_some();
5304 : if should_yield {
5305 : tracing::info!(
5306 : "preempt image layer generation at {lsn} when processing partition {}..{}: too many L0 layers",
5307 : partition.start().unwrap(),
5308 : partition.end().unwrap()
5309 : );
5310 : last_partition_processed = Some(partition.clone());
5311 : all_generated = false;
5312 : break;
5313 : }
5314 : }
5315 : }
5316 : }
5317 : }
5318 :
5319 : let image_layers = batch_image_writer.finish(self, ctx).await?;
5320 :
5321 : let mut guard = self.layers.write().await;
5322 :
5323 : // FIXME: we could add the images to be uploaded *before* returning from here, but right
5324 : // now they are being scheduled outside of write lock; current way is inconsistent with
5325 : // compaction lock order.
5326 : guard
5327 : .open_mut()?
5328 : .track_new_image_layers(&image_layers, &self.metrics);
5329 : drop_wlock(guard);
5330 : let duration = timer.stop_and_record();
5331 :
5332 : // Creating image layers may have caused some previously visible layers to be covered
5333 : if !image_layers.is_empty() {
5334 : self.update_layer_visibility().await?;
5335 : }
5336 :
5337 : let total_layer_size = image_layers
5338 : .iter()
5339 500 : .map(|l| l.metadata().file_size)
5340 : .sum::<u64>();
5341 :
5342 : if !image_layers.is_empty() {
5343 : info!(
5344 : "created {} image layers ({} bytes) in {}s, processed {} out of {} partitions",
5345 : image_layers.len(),
5346 : total_layer_size,
5347 : duration.as_secs_f64(),
5348 : partition_processed,
5349 : total_partitions
5350 : );
5351 : }
5352 :
5353 : Ok((
5354 : image_layers,
5355 : if all_generated {
5356 : LastImageLayerCreationStatus::Complete
5357 : } else {
5358 : LastImageLayerCreationStatus::Incomplete {
5359 : last_key: if let Some(last_partition_processed) = last_partition_processed {
5360 : last_partition_processed.end().unwrap_or(Key::MIN)
5361 : } else {
5362 : // This branch should be unreachable, but in case it happens, we can just return the start key.
5363 : Key::MIN
5364 : },
5365 : }
5366 : },
5367 : ))
5368 : }
5369 :
5370 : /// Wait until the background initial logical size calculation is complete, or
5371 : /// this Timeline is shut down. Calling this function will cause the initial
5372 : /// logical size calculation to skip waiting for the background jobs barrier.
5373 0 : pub(crate) async fn await_initial_logical_size(self: Arc<Self>) {
5374 0 : if !self.shard_identity.is_shard_zero() {
5375 : // We don't populate logical size on shard >0: skip waiting for it.
5376 0 : return;
5377 0 : }
5378 0 :
5379 0 : if self.remote_client.is_deleting() {
5380 : // The timeline was created in a deletion-resume state, we don't expect logical size to be populated
5381 0 : return;
5382 0 : }
5383 0 :
5384 0 : if self.current_logical_size.current_size().is_exact() {
5385 : // root timelines are initialized with exact count, but never start the background
5386 : // calculation
5387 0 : return;
5388 0 : }
5389 :
5390 0 : if let Some(await_bg_cancel) = self
5391 0 : .current_logical_size
5392 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore
5393 0 : .get()
5394 0 : {
5395 0 : await_bg_cancel.cancel();
5396 0 : } else {
5397 : // We should not wait if we were not able to explicitly instruct
5398 : // the logical size cancellation to skip the concurrency limit semaphore.
5399 : // TODO: this is an unexpected case. We should restructure so that it
5400 : // can't happen.
5401 0 : tracing::warn!(
5402 0 : "await_initial_logical_size: can't get semaphore cancel token, skipping"
5403 : );
5404 0 : debug_assert!(false);
5405 : }
5406 :
5407 0 : tokio::select!(
5408 0 : _ = self.current_logical_size.initialized.acquire() => {},
5409 0 : _ = self.cancel.cancelled() => {}
5410 : )
5411 0 : }
5412 :
5413 : /// Detach this timeline from its ancestor by copying all of ancestors layers as this
5414 : /// Timelines layers up to the ancestor_lsn.
5415 : ///
5416 : /// Requires a timeline that:
5417 : /// - has an ancestor to detach from
5418 : /// - the ancestor does not have an ancestor -- follows from the original RFC limitations, not
5419 : /// a technical requirement
5420 : ///
5421 : /// After the operation has been started, it cannot be canceled. Upon restart it needs to be
5422 : /// polled again until completion.
5423 : ///
5424 : /// During the operation all timelines sharing the data with this timeline will be reparented
5425 : /// from our ancestor to be branches of this timeline.
5426 0 : pub(crate) async fn prepare_to_detach_from_ancestor(
5427 0 : self: &Arc<Timeline>,
5428 0 : tenant: &crate::tenant::Tenant,
5429 0 : options: detach_ancestor::Options,
5430 0 : behavior: DetachBehavior,
5431 0 : ctx: &RequestContext,
5432 0 : ) -> Result<detach_ancestor::Progress, detach_ancestor::Error> {
5433 0 : detach_ancestor::prepare(self, tenant, behavior, options, ctx).await
5434 0 : }
5435 :
5436 : /// Second step of detach from ancestor; detaches the `self` from it's current ancestor and
5437 : /// reparents any reparentable children of previous ancestor.
5438 : ///
5439 : /// This method is to be called while holding the TenantManager's tenant slot, so during this
5440 : /// method we cannot be deleted nor can any timeline be deleted. After this method returns
5441 : /// successfully, tenant must be reloaded.
5442 : ///
5443 : /// Final step will be to [`Self::complete_detaching_timeline_ancestor`] after optionally
5444 : /// resetting the tenant.
5445 0 : pub(crate) async fn detach_from_ancestor_and_reparent(
5446 0 : self: &Arc<Timeline>,
5447 0 : tenant: &crate::tenant::Tenant,
5448 0 : prepared: detach_ancestor::PreparedTimelineDetach,
5449 0 : ancestor_timeline_id: TimelineId,
5450 0 : ancestor_lsn: Lsn,
5451 0 : behavior: DetachBehavior,
5452 0 : ctx: &RequestContext,
5453 0 : ) -> Result<detach_ancestor::DetachingAndReparenting, detach_ancestor::Error> {
5454 0 : detach_ancestor::detach_and_reparent(
5455 0 : self,
5456 0 : tenant,
5457 0 : prepared,
5458 0 : ancestor_timeline_id,
5459 0 : ancestor_lsn,
5460 0 : behavior,
5461 0 : ctx,
5462 0 : )
5463 0 : .await
5464 0 : }
5465 :
5466 : /// Final step which unblocks the GC.
5467 : ///
5468 : /// The tenant must've been reset if ancestry was modified previously (in tenant manager).
5469 0 : pub(crate) async fn complete_detaching_timeline_ancestor(
5470 0 : self: &Arc<Timeline>,
5471 0 : tenant: &crate::tenant::Tenant,
5472 0 : attempt: detach_ancestor::Attempt,
5473 0 : ctx: &RequestContext,
5474 0 : ) -> Result<(), detach_ancestor::Error> {
5475 0 : detach_ancestor::complete(self, tenant, attempt, ctx).await
5476 0 : }
5477 : }
5478 :
5479 : impl Drop for Timeline {
5480 20 : fn drop(&mut self) {
5481 20 : if let Some(ancestor) = &self.ancestor_timeline {
5482 : // This lock should never be poisoned, but in case it is we do a .map() instead of
5483 : // an unwrap(), to avoid panicking in a destructor and thereby aborting the process.
5484 8 : if let Ok(mut gc_info) = ancestor.gc_info.write() {
5485 8 : if !gc_info.remove_child_not_offloaded(self.timeline_id) {
5486 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
5487 0 : "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
5488 8 : }
5489 0 : }
5490 12 : }
5491 20 : info!(
5492 0 : "Timeline {} for tenant {} is being dropped",
5493 : self.timeline_id, self.tenant_shard_id.tenant_id
5494 : );
5495 20 : }
5496 : }
5497 :
5498 : /// Top-level failure to compact.
5499 : #[derive(Debug, thiserror::Error)]
5500 : pub(crate) enum CompactionError {
5501 : #[error("The timeline or pageserver is shutting down")]
5502 : ShuttingDown,
5503 : /// Compaction tried to offload a timeline and failed
5504 : #[error("Failed to offload timeline: {0}")]
5505 : Offload(OffloadError),
5506 : /// Compaction cannot be done right now; page reconstruction and so on.
5507 : #[error("Failed to collect keyspace: {0}")]
5508 : CollectKeySpaceError(#[from] CollectKeySpaceError),
5509 : #[error(transparent)]
5510 : Other(anyhow::Error),
5511 : #[error("Compaction already running: {0}")]
5512 : AlreadyRunning(&'static str),
5513 : }
5514 :
5515 : impl CompactionError {
5516 : /// Errors that can be ignored, i.e., cancel and shutdown.
5517 0 : pub fn is_cancel(&self) -> bool {
5518 0 : matches!(
5519 0 : self,
5520 : Self::ShuttingDown
5521 : | Self::AlreadyRunning(_)
5522 : | Self::CollectKeySpaceError(CollectKeySpaceError::Cancelled)
5523 : | Self::CollectKeySpaceError(CollectKeySpaceError::PageRead(
5524 : PageReconstructError::Cancelled
5525 : ))
5526 : | Self::Offload(OffloadError::Cancelled)
5527 : )
5528 0 : }
5529 :
5530 : /// Critical errors that indicate data corruption.
5531 0 : pub fn is_critical(&self) -> bool {
5532 0 : matches!(
5533 0 : self,
5534 : Self::CollectKeySpaceError(
5535 : CollectKeySpaceError::Decode(_)
5536 : | CollectKeySpaceError::PageRead(
5537 : PageReconstructError::MissingKey(_) | PageReconstructError::WalRedo(_),
5538 : )
5539 : )
5540 : )
5541 0 : }
5542 : }
5543 :
5544 : impl From<OffloadError> for CompactionError {
5545 0 : fn from(e: OffloadError) -> Self {
5546 0 : match e {
5547 0 : OffloadError::Cancelled => Self::ShuttingDown,
5548 0 : _ => Self::Offload(e),
5549 : }
5550 0 : }
5551 : }
5552 :
5553 : impl From<super::upload_queue::NotInitialized> for CompactionError {
5554 0 : fn from(value: super::upload_queue::NotInitialized) -> Self {
5555 0 : match value {
5556 : super::upload_queue::NotInitialized::Uninitialized => {
5557 0 : CompactionError::Other(anyhow::anyhow!(value))
5558 : }
5559 : super::upload_queue::NotInitialized::ShuttingDown
5560 0 : | super::upload_queue::NotInitialized::Stopped => CompactionError::ShuttingDown,
5561 : }
5562 0 : }
5563 : }
5564 :
5565 : impl From<super::storage_layer::layer::DownloadError> for CompactionError {
5566 0 : fn from(e: super::storage_layer::layer::DownloadError) -> Self {
5567 0 : match e {
5568 : super::storage_layer::layer::DownloadError::TimelineShutdown
5569 : | super::storage_layer::layer::DownloadError::DownloadCancelled => {
5570 0 : CompactionError::ShuttingDown
5571 : }
5572 : super::storage_layer::layer::DownloadError::ContextAndConfigReallyDeniesDownloads
5573 : | super::storage_layer::layer::DownloadError::DownloadRequired
5574 : | super::storage_layer::layer::DownloadError::NotFile(_)
5575 : | super::storage_layer::layer::DownloadError::DownloadFailed
5576 : | super::storage_layer::layer::DownloadError::PreStatFailed(_) => {
5577 0 : CompactionError::Other(anyhow::anyhow!(e))
5578 : }
5579 : #[cfg(test)]
5580 : super::storage_layer::layer::DownloadError::Failpoint(_) => {
5581 0 : CompactionError::Other(anyhow::anyhow!(e))
5582 : }
5583 : }
5584 0 : }
5585 : }
5586 :
5587 : impl From<layer_manager::Shutdown> for CompactionError {
5588 0 : fn from(_: layer_manager::Shutdown) -> Self {
5589 0 : CompactionError::ShuttingDown
5590 0 : }
5591 : }
5592 :
5593 : #[serde_as]
5594 392 : #[derive(serde::Serialize)]
5595 : struct RecordedDuration(#[serde_as(as = "serde_with::DurationMicroSeconds")] Duration);
5596 :
5597 : #[derive(Default)]
5598 : enum DurationRecorder {
5599 : #[default]
5600 : NotStarted,
5601 : Recorded(RecordedDuration, tokio::time::Instant),
5602 : }
5603 :
5604 : impl DurationRecorder {
5605 1005 : fn till_now(&self) -> DurationRecorder {
5606 1005 : match self {
5607 : DurationRecorder::NotStarted => {
5608 0 : panic!("must only call on recorded measurements")
5609 : }
5610 1005 : DurationRecorder::Recorded(_, ended) => {
5611 1005 : let now = tokio::time::Instant::now();
5612 1005 : DurationRecorder::Recorded(RecordedDuration(now - *ended), now)
5613 1005 : }
5614 1005 : }
5615 1005 : }
5616 392 : fn into_recorded(self) -> Option<RecordedDuration> {
5617 392 : match self {
5618 0 : DurationRecorder::NotStarted => None,
5619 392 : DurationRecorder::Recorded(recorded, _) => Some(recorded),
5620 : }
5621 392 : }
5622 : }
5623 :
5624 : /// Descriptor for a delta layer used in testing infra. The start/end key/lsn range of the
5625 : /// delta layer might be different from the min/max key/lsn in the delta layer. Therefore,
5626 : /// the layer descriptor requires the user to provide the ranges, which should cover all
5627 : /// keys specified in the `data` field.
5628 : #[cfg(test)]
5629 : #[derive(Clone)]
5630 : pub struct DeltaLayerTestDesc {
5631 : pub lsn_range: Range<Lsn>,
5632 : pub key_range: Range<Key>,
5633 : pub data: Vec<(Key, Lsn, Value)>,
5634 : }
5635 :
5636 : #[cfg(test)]
5637 : #[derive(Clone)]
5638 : pub struct InMemoryLayerTestDesc {
5639 : pub lsn_range: Range<Lsn>,
5640 : pub data: Vec<(Key, Lsn, Value)>,
5641 : pub is_open: bool,
5642 : }
5643 :
5644 : #[cfg(test)]
5645 : impl DeltaLayerTestDesc {
5646 8 : pub fn new(lsn_range: Range<Lsn>, key_range: Range<Key>, data: Vec<(Key, Lsn, Value)>) -> Self {
5647 8 : Self {
5648 8 : lsn_range,
5649 8 : key_range,
5650 8 : data,
5651 8 : }
5652 8 : }
5653 :
5654 176 : pub fn new_with_inferred_key_range(
5655 176 : lsn_range: Range<Lsn>,
5656 176 : data: Vec<(Key, Lsn, Value)>,
5657 176 : ) -> Self {
5658 440 : let key_min = data.iter().map(|(key, _, _)| key).min().unwrap();
5659 440 : let key_max = data.iter().map(|(key, _, _)| key).max().unwrap();
5660 176 : Self {
5661 176 : key_range: (*key_min)..(key_max.next()),
5662 176 : lsn_range,
5663 176 : data,
5664 176 : }
5665 176 : }
5666 :
5667 20 : pub(crate) fn layer_name(&self) -> LayerName {
5668 20 : LayerName::Delta(super::storage_layer::DeltaLayerName {
5669 20 : key_range: self.key_range.clone(),
5670 20 : lsn_range: self.lsn_range.clone(),
5671 20 : })
5672 20 : }
5673 : }
5674 :
5675 : impl Timeline {
5676 56 : async fn finish_compact_batch(
5677 56 : self: &Arc<Self>,
5678 56 : new_deltas: &[ResidentLayer],
5679 56 : new_images: &[ResidentLayer],
5680 56 : layers_to_remove: &[Layer],
5681 56 : ) -> Result<(), CompactionError> {
5682 56 : let mut guard = tokio::select! {
5683 56 : guard = self.layers.write() => guard,
5684 56 : _ = self.cancel.cancelled() => {
5685 0 : return Err(CompactionError::ShuttingDown);
5686 : }
5687 : };
5688 :
5689 56 : let mut duplicated_layers = HashSet::new();
5690 56 :
5691 56 : let mut insert_layers = Vec::with_capacity(new_deltas.len());
5692 :
5693 672 : for l in new_deltas {
5694 616 : if guard.contains(l.as_ref()) {
5695 : // expected in tests
5696 0 : tracing::error!(layer=%l, "duplicated L1 layer");
5697 :
5698 : // good ways to cause a duplicate: we repeatedly error after taking the writelock
5699 : // `guard` on self.layers. as of writing this, there are no error returns except
5700 : // for compact_level0_phase1 creating an L0, which does not happen in practice
5701 : // because we have not implemented L0 => L0 compaction.
5702 0 : duplicated_layers.insert(l.layer_desc().key());
5703 616 : } else if LayerMap::is_l0(&l.layer_desc().key_range, l.layer_desc().is_delta) {
5704 0 : return Err(CompactionError::Other(anyhow::anyhow!(
5705 0 : "compaction generates a L0 layer file as output, which will cause infinite compaction."
5706 0 : )));
5707 616 : } else {
5708 616 : insert_layers.push(l.clone());
5709 616 : }
5710 : }
5711 :
5712 : // only remove those inputs which were not outputs
5713 56 : let remove_layers: Vec<Layer> = layers_to_remove
5714 56 : .iter()
5715 804 : .filter(|l| !duplicated_layers.contains(&l.layer_desc().key()))
5716 56 : .cloned()
5717 56 : .collect();
5718 56 :
5719 56 : if !new_images.is_empty() {
5720 0 : guard
5721 0 : .open_mut()?
5722 0 : .track_new_image_layers(new_images, &self.metrics);
5723 56 : }
5724 :
5725 56 : guard
5726 56 : .open_mut()?
5727 56 : .finish_compact_l0(&remove_layers, &insert_layers, &self.metrics);
5728 56 :
5729 56 : self.remote_client
5730 56 : .schedule_compaction_update(&remove_layers, new_deltas)?;
5731 :
5732 56 : drop_wlock(guard);
5733 56 :
5734 56 : Ok(())
5735 56 : }
5736 :
5737 0 : async fn rewrite_layers(
5738 0 : self: &Arc<Self>,
5739 0 : mut replace_layers: Vec<(Layer, ResidentLayer)>,
5740 0 : mut drop_layers: Vec<Layer>,
5741 0 : ) -> Result<(), CompactionError> {
5742 0 : let mut guard = self.layers.write().await;
5743 :
5744 : // Trim our lists in case our caller (compaction) raced with someone else (GC) removing layers: we want
5745 : // to avoid double-removing, and avoid rewriting something that was removed.
5746 0 : replace_layers.retain(|(l, _)| guard.contains(l));
5747 0 : drop_layers.retain(|l| guard.contains(l));
5748 0 :
5749 0 : guard
5750 0 : .open_mut()?
5751 0 : .rewrite_layers(&replace_layers, &drop_layers, &self.metrics);
5752 0 :
5753 0 : let upload_layers: Vec<_> = replace_layers.into_iter().map(|r| r.1).collect();
5754 0 :
5755 0 : self.remote_client
5756 0 : .schedule_compaction_update(&drop_layers, &upload_layers)?;
5757 :
5758 0 : Ok(())
5759 0 : }
5760 :
5761 : /// Schedules the uploads of the given image layers
5762 725 : fn upload_new_image_layers(
5763 725 : self: &Arc<Self>,
5764 725 : new_images: impl IntoIterator<Item = ResidentLayer>,
5765 725 : ) -> Result<(), super::upload_queue::NotInitialized> {
5766 777 : for layer in new_images {
5767 52 : self.remote_client.schedule_layer_file_upload(layer)?;
5768 : }
5769 : // should any new image layer been created, not uploading index_part will
5770 : // result in a mismatch between remote_physical_size and layermap calculated
5771 : // size, which will fail some tests, but should not be an issue otherwise.
5772 725 : self.remote_client
5773 725 : .schedule_index_upload_for_file_changes()?;
5774 725 : Ok(())
5775 725 : }
5776 :
5777 0 : async fn find_gc_time_cutoff(
5778 0 : &self,
5779 0 : now: SystemTime,
5780 0 : pitr: Duration,
5781 0 : cancel: &CancellationToken,
5782 0 : ctx: &RequestContext,
5783 0 : ) -> Result<Option<Lsn>, PageReconstructError> {
5784 0 : debug_assert_current_span_has_tenant_and_timeline_id();
5785 0 : if self.shard_identity.is_shard_zero() {
5786 : // Shard Zero has SLRU data and can calculate the PITR time -> LSN mapping itself
5787 0 : let time_range = if pitr == Duration::ZERO {
5788 0 : humantime::parse_duration(DEFAULT_PITR_INTERVAL).expect("constant is invalid")
5789 : } else {
5790 0 : pitr
5791 : };
5792 :
5793 : // If PITR is so large or `now` is so small that this underflows, we will retain no history (highly unexpected case)
5794 0 : let time_cutoff = now.checked_sub(time_range).unwrap_or(now);
5795 0 : let timestamp = to_pg_timestamp(time_cutoff);
5796 :
5797 0 : let time_cutoff = match self.find_lsn_for_timestamp(timestamp, cancel, ctx).await? {
5798 0 : LsnForTimestamp::Present(lsn) => Some(lsn),
5799 0 : LsnForTimestamp::Future(lsn) => {
5800 0 : // The timestamp is in the future. That sounds impossible,
5801 0 : // but what it really means is that there hasn't been
5802 0 : // any commits since the cutoff timestamp.
5803 0 : //
5804 0 : // In this case we should use the LSN of the most recent commit,
5805 0 : // which is implicitly the last LSN in the log.
5806 0 : debug!("future({})", lsn);
5807 0 : Some(self.get_last_record_lsn())
5808 : }
5809 0 : LsnForTimestamp::Past(lsn) => {
5810 0 : debug!("past({})", lsn);
5811 0 : None
5812 : }
5813 0 : LsnForTimestamp::NoData(lsn) => {
5814 0 : debug!("nodata({})", lsn);
5815 0 : None
5816 : }
5817 : };
5818 0 : Ok(time_cutoff)
5819 : } else {
5820 : // Shards other than shard zero cannot do timestamp->lsn lookups, and must instead learn their GC cutoff
5821 : // from shard zero's index. The index doesn't explicitly tell us the time cutoff, but we may assume that
5822 : // the point up to which shard zero's last_gc_cutoff has advanced will either be the time cutoff, or a
5823 : // space cutoff that we would also have respected ourselves.
5824 0 : match self
5825 0 : .remote_client
5826 0 : .download_foreign_index(ShardNumber(0), cancel)
5827 0 : .await
5828 : {
5829 0 : Ok((index_part, index_generation, _index_mtime)) => {
5830 0 : tracing::info!(
5831 0 : "GC loaded shard zero metadata (gen {index_generation:?}): latest_gc_cutoff_lsn: {}",
5832 0 : index_part.metadata.latest_gc_cutoff_lsn()
5833 : );
5834 0 : Ok(Some(index_part.metadata.latest_gc_cutoff_lsn()))
5835 : }
5836 : Err(DownloadError::NotFound) => {
5837 : // This is unexpected, because during timeline creations shard zero persists to remote
5838 : // storage before other shards are called, and during timeline deletion non-zeroth shards are
5839 : // deleted before the zeroth one. However, it should be harmless: if we somehow end up in this
5840 : // state, then shard zero should _eventually_ write an index when it GCs.
5841 0 : tracing::warn!("GC couldn't find shard zero's index for timeline");
5842 0 : Ok(None)
5843 : }
5844 0 : Err(e) => {
5845 0 : // TODO: this function should return a different error type than page reconstruct error
5846 0 : Err(PageReconstructError::Other(anyhow::anyhow!(e)))
5847 : }
5848 : }
5849 :
5850 : // TODO: after reading shard zero's GC cutoff, we should validate its generation with the storage
5851 : // controller. Otherwise, it is possible that we see the GC cutoff go backwards while shard zero
5852 : // is going through a migration if we read the old location's index and it has GC'd ahead of the
5853 : // new location. This is legal in principle, but problematic in practice because it might result
5854 : // in a timeline creation succeeding on shard zero ('s new location) but then failing on other shards
5855 : // because they have GC'd past the branch point.
5856 : }
5857 0 : }
5858 :
5859 : /// Find the Lsns above which layer files need to be retained on
5860 : /// garbage collection.
5861 : ///
5862 : /// We calculate two cutoffs, one based on time and one based on WAL size. `pitr`
5863 : /// controls the time cutoff (or ZERO to disable time-based retention), and `space_cutoff` controls
5864 : /// the space-based retention.
5865 : ///
5866 : /// This function doesn't simply to calculate time & space based retention: it treats time-based
5867 : /// retention as authoritative if enabled, and falls back to space-based retention if calculating
5868 : /// the LSN for a time point isn't possible. Therefore the GcCutoffs::horizon in the response might
5869 : /// be different to the `space_cutoff` input. Callers should treat the min() of the two cutoffs
5870 : /// in the response as the GC cutoff point for the timeline.
5871 : #[instrument(skip_all, fields(timeline_id=%self.timeline_id))]
5872 : pub(super) async fn find_gc_cutoffs(
5873 : &self,
5874 : now: SystemTime,
5875 : space_cutoff: Lsn,
5876 : pitr: Duration,
5877 : cancel: &CancellationToken,
5878 : ctx: &RequestContext,
5879 : ) -> Result<GcCutoffs, PageReconstructError> {
5880 : let _timer = self
5881 : .metrics
5882 : .find_gc_cutoffs_histo
5883 : .start_timer()
5884 : .record_on_drop();
5885 :
5886 : pausable_failpoint!("Timeline::find_gc_cutoffs-pausable");
5887 :
5888 : if cfg!(test) {
5889 : // Unit tests which specify zero PITR interval expect to avoid doing any I/O for timestamp lookup
5890 : if pitr == Duration::ZERO {
5891 : return Ok(GcCutoffs {
5892 : time: self.get_last_record_lsn(),
5893 : space: space_cutoff,
5894 : });
5895 : }
5896 : }
5897 :
5898 : // Calculate a time-based limit on how much to retain:
5899 : // - if PITR interval is set, then this is our cutoff.
5900 : // - if PITR interval is not set, then we do a lookup
5901 : // based on DEFAULT_PITR_INTERVAL, so that size-based retention does not result in keeping history around permanently on idle databases.
5902 : let time_cutoff = self.find_gc_time_cutoff(now, pitr, cancel, ctx).await?;
5903 :
5904 : Ok(match (pitr, time_cutoff) {
5905 : (Duration::ZERO, Some(time_cutoff)) => {
5906 : // PITR is not set. Retain the size-based limit, or the default time retention,
5907 : // whichever requires less data.
5908 : GcCutoffs {
5909 : time: self.get_last_record_lsn(),
5910 : space: std::cmp::max(time_cutoff, space_cutoff),
5911 : }
5912 : }
5913 : (Duration::ZERO, None) => {
5914 : // PITR is not set, and time lookup failed
5915 : GcCutoffs {
5916 : time: self.get_last_record_lsn(),
5917 : space: space_cutoff,
5918 : }
5919 : }
5920 : (_, None) => {
5921 : // PITR interval is set & we didn't look up a timestamp successfully. Conservatively assume PITR
5922 : // cannot advance beyond what was already GC'd, and respect space-based retention
5923 : GcCutoffs {
5924 : time: *self.get_applied_gc_cutoff_lsn(),
5925 : space: space_cutoff,
5926 : }
5927 : }
5928 : (_, Some(time_cutoff)) => {
5929 : // PITR interval is set and we looked up timestamp successfully. Ignore
5930 : // size based retention and make time cutoff authoritative
5931 : GcCutoffs {
5932 : time: time_cutoff,
5933 : space: time_cutoff,
5934 : }
5935 : }
5936 : })
5937 : }
5938 :
5939 : /// Garbage collect layer files on a timeline that are no longer needed.
5940 : ///
5941 : /// Currently, we don't make any attempt at removing unneeded page versions
5942 : /// within a layer file. We can only remove the whole file if it's fully
5943 : /// obsolete.
5944 8 : pub(super) async fn gc(&self) -> Result<GcResult, GcError> {
5945 : // this is most likely the background tasks, but it might be the spawned task from
5946 : // immediate_gc
5947 8 : let _g = tokio::select! {
5948 8 : guard = self.gc_lock.lock() => guard,
5949 8 : _ = self.cancel.cancelled() => return Ok(GcResult::default()),
5950 : };
5951 8 : let timer = self.metrics.garbage_collect_histo.start_timer();
5952 8 :
5953 8 : fail_point!("before-timeline-gc");
5954 8 :
5955 8 : // Is the timeline being deleted?
5956 8 : if self.is_stopping() {
5957 0 : return Err(GcError::TimelineCancelled);
5958 8 : }
5959 8 :
5960 8 : let (space_cutoff, time_cutoff, retain_lsns, max_lsn_with_valid_lease) = {
5961 8 : let gc_info = self.gc_info.read().unwrap();
5962 8 :
5963 8 : let space_cutoff = min(gc_info.cutoffs.space, self.get_disk_consistent_lsn());
5964 8 : let time_cutoff = gc_info.cutoffs.time;
5965 8 : let retain_lsns = gc_info
5966 8 : .retain_lsns
5967 8 : .iter()
5968 8 : .map(|(lsn, _child_id, _is_offloaded)| *lsn)
5969 8 : .collect();
5970 8 :
5971 8 : // Gets the maximum LSN that holds the valid lease.
5972 8 : //
5973 8 : // Caveat: `refresh_gc_info` is in charged of updating the lease map.
5974 8 : // Here, we do not check for stale leases again.
5975 8 : let max_lsn_with_valid_lease = gc_info.leases.last_key_value().map(|(lsn, _)| *lsn);
5976 8 :
5977 8 : (
5978 8 : space_cutoff,
5979 8 : time_cutoff,
5980 8 : retain_lsns,
5981 8 : max_lsn_with_valid_lease,
5982 8 : )
5983 8 : };
5984 8 :
5985 8 : let mut new_gc_cutoff = Lsn::min(space_cutoff, time_cutoff);
5986 8 : let standby_horizon = self.standby_horizon.load();
5987 8 : // Hold GC for the standby, but as a safety guard do it only within some
5988 8 : // reasonable lag.
5989 8 : if standby_horizon != Lsn::INVALID {
5990 0 : if let Some(standby_lag) = new_gc_cutoff.checked_sub(standby_horizon) {
5991 : const MAX_ALLOWED_STANDBY_LAG: u64 = 10u64 << 30; // 10 GB
5992 0 : if standby_lag.0 < MAX_ALLOWED_STANDBY_LAG {
5993 0 : new_gc_cutoff = Lsn::min(standby_horizon, new_gc_cutoff);
5994 0 : trace!("holding off GC for standby apply LSN {}", standby_horizon);
5995 : } else {
5996 0 : warn!(
5997 0 : "standby is lagging for more than {}MB, not holding gc for it",
5998 0 : MAX_ALLOWED_STANDBY_LAG / 1024 / 1024
5999 : )
6000 : }
6001 0 : }
6002 8 : }
6003 :
6004 : // Reset standby horizon to ignore it if it is not updated till next GC.
6005 : // It is an easy way to unset it when standby disappears without adding
6006 : // more conf options.
6007 8 : self.standby_horizon.store(Lsn::INVALID);
6008 8 : self.metrics
6009 8 : .standby_horizon_gauge
6010 8 : .set(Lsn::INVALID.0 as i64);
6011 :
6012 8 : let res = self
6013 8 : .gc_timeline(
6014 8 : space_cutoff,
6015 8 : time_cutoff,
6016 8 : retain_lsns,
6017 8 : max_lsn_with_valid_lease,
6018 8 : new_gc_cutoff,
6019 8 : )
6020 8 : .instrument(
6021 8 : info_span!("gc_timeline", timeline_id = %self.timeline_id, cutoff = %new_gc_cutoff),
6022 : )
6023 8 : .await?;
6024 :
6025 : // only record successes
6026 8 : timer.stop_and_record();
6027 8 :
6028 8 : Ok(res)
6029 8 : }
6030 :
6031 8 : async fn gc_timeline(
6032 8 : &self,
6033 8 : space_cutoff: Lsn,
6034 8 : time_cutoff: Lsn,
6035 8 : retain_lsns: Vec<Lsn>,
6036 8 : max_lsn_with_valid_lease: Option<Lsn>,
6037 8 : new_gc_cutoff: Lsn,
6038 8 : ) -> Result<GcResult, GcError> {
6039 8 : // FIXME: if there is an ongoing detach_from_ancestor, we should just skip gc
6040 8 :
6041 8 : let now = SystemTime::now();
6042 8 : let mut result: GcResult = GcResult::default();
6043 8 :
6044 8 : // Nothing to GC. Return early.
6045 8 : let latest_gc_cutoff = *self.get_applied_gc_cutoff_lsn();
6046 8 : if latest_gc_cutoff >= new_gc_cutoff {
6047 0 : info!(
6048 0 : "Nothing to GC: new_gc_cutoff_lsn {new_gc_cutoff}, latest_gc_cutoff_lsn {latest_gc_cutoff}",
6049 : );
6050 0 : return Ok(result);
6051 8 : }
6052 :
6053 : // We need to ensure that no one tries to read page versions or create
6054 : // branches at a point before latest_gc_cutoff_lsn. See branch_timeline()
6055 : // for details. This will block until the old value is no longer in use.
6056 : //
6057 : // The GC cutoff should only ever move forwards.
6058 8 : let waitlist = {
6059 8 : let write_guard = self.applied_gc_cutoff_lsn.lock_for_write();
6060 8 : if *write_guard > new_gc_cutoff {
6061 0 : return Err(GcError::BadLsn {
6062 0 : why: format!(
6063 0 : "Cannot move GC cutoff LSN backwards (was {}, new {})",
6064 0 : *write_guard, new_gc_cutoff
6065 0 : ),
6066 0 : });
6067 8 : }
6068 8 :
6069 8 : write_guard.store_and_unlock(new_gc_cutoff)
6070 8 : };
6071 8 : waitlist.wait().await;
6072 :
6073 8 : info!("GC starting");
6074 :
6075 8 : debug!("retain_lsns: {:?}", retain_lsns);
6076 :
6077 8 : let mut layers_to_remove = Vec::new();
6078 :
6079 : // Scan all layers in the timeline (remote or on-disk).
6080 : //
6081 : // Garbage collect the layer if all conditions are satisfied:
6082 : // 1. it is older than cutoff LSN;
6083 : // 2. it is older than PITR interval;
6084 : // 3. it doesn't need to be retained for 'retain_lsns';
6085 : // 4. it does not need to be kept for LSNs holding valid leases.
6086 : // 5. newer on-disk image layers cover the layer's whole key range
6087 : //
6088 : // TODO holding a write lock is too agressive and avoidable
6089 8 : let mut guard = self.layers.write().await;
6090 8 : let layers = guard.layer_map()?;
6091 48 : 'outer: for l in layers.iter_historic_layers() {
6092 48 : result.layers_total += 1;
6093 48 :
6094 48 : // 1. Is it newer than GC horizon cutoff point?
6095 48 : if l.get_lsn_range().end > space_cutoff {
6096 4 : info!(
6097 0 : "keeping {} because it's newer than space_cutoff {}",
6098 0 : l.layer_name(),
6099 : space_cutoff,
6100 : );
6101 4 : result.layers_needed_by_cutoff += 1;
6102 4 : continue 'outer;
6103 44 : }
6104 44 :
6105 44 : // 2. It is newer than PiTR cutoff point?
6106 44 : if l.get_lsn_range().end > time_cutoff {
6107 0 : info!(
6108 0 : "keeping {} because it's newer than time_cutoff {}",
6109 0 : l.layer_name(),
6110 : time_cutoff,
6111 : );
6112 0 : result.layers_needed_by_pitr += 1;
6113 0 : continue 'outer;
6114 44 : }
6115 :
6116 : // 3. Is it needed by a child branch?
6117 : // NOTE With that we would keep data that
6118 : // might be referenced by child branches forever.
6119 : // We can track this in child timeline GC and delete parent layers when
6120 : // they are no longer needed. This might be complicated with long inheritance chains.
6121 : //
6122 : // TODO Vec is not a great choice for `retain_lsns`
6123 44 : for retain_lsn in &retain_lsns {
6124 : // start_lsn is inclusive
6125 0 : if &l.get_lsn_range().start <= retain_lsn {
6126 0 : info!(
6127 0 : "keeping {} because it's still might be referenced by child branch forked at {} is_dropped: xx is_incremental: {}",
6128 0 : l.layer_name(),
6129 0 : retain_lsn,
6130 0 : l.is_incremental(),
6131 : );
6132 0 : result.layers_needed_by_branches += 1;
6133 0 : continue 'outer;
6134 0 : }
6135 : }
6136 :
6137 : // 4. Is there a valid lease that requires us to keep this layer?
6138 44 : if let Some(lsn) = &max_lsn_with_valid_lease {
6139 : // keep if layer start <= any of the lease
6140 36 : if &l.get_lsn_range().start <= lsn {
6141 28 : info!(
6142 0 : "keeping {} because there is a valid lease preventing GC at {}",
6143 0 : l.layer_name(),
6144 : lsn,
6145 : );
6146 28 : result.layers_needed_by_leases += 1;
6147 28 : continue 'outer;
6148 8 : }
6149 8 : }
6150 :
6151 : // 5. Is there a later on-disk layer for this relation?
6152 : //
6153 : // The end-LSN is exclusive, while disk_consistent_lsn is
6154 : // inclusive. For example, if disk_consistent_lsn is 100, it is
6155 : // OK for a delta layer to have end LSN 101, but if the end LSN
6156 : // is 102, then it might not have been fully flushed to disk
6157 : // before crash.
6158 : //
6159 : // For example, imagine that the following layers exist:
6160 : //
6161 : // 1000 - image (A)
6162 : // 1000-2000 - delta (B)
6163 : // 2000 - image (C)
6164 : // 2000-3000 - delta (D)
6165 : // 3000 - image (E)
6166 : //
6167 : // If GC horizon is at 2500, we can remove layers A and B, but
6168 : // we cannot remove C, even though it's older than 2500, because
6169 : // the delta layer 2000-3000 depends on it.
6170 16 : if !layers
6171 16 : .image_layer_exists(&l.get_key_range(), &(l.get_lsn_range().end..new_gc_cutoff))
6172 : {
6173 12 : info!("keeping {} because it is the latest layer", l.layer_name());
6174 12 : result.layers_not_updated += 1;
6175 12 : continue 'outer;
6176 4 : }
6177 4 :
6178 4 : // We didn't find any reason to keep this file, so remove it.
6179 4 : info!(
6180 0 : "garbage collecting {} is_dropped: xx is_incremental: {}",
6181 0 : l.layer_name(),
6182 0 : l.is_incremental(),
6183 : );
6184 4 : layers_to_remove.push(l);
6185 : }
6186 :
6187 8 : if !layers_to_remove.is_empty() {
6188 : // Persist the new GC cutoff value before we actually remove anything.
6189 : // This unconditionally schedules also an index_part.json update, even though, we will
6190 : // be doing one a bit later with the unlinked gc'd layers.
6191 4 : let disk_consistent_lsn = self.disk_consistent_lsn.load();
6192 4 : self.schedule_uploads(disk_consistent_lsn, None)
6193 4 : .map_err(|e| {
6194 0 : if self.cancel.is_cancelled() {
6195 0 : GcError::TimelineCancelled
6196 : } else {
6197 0 : GcError::Remote(e)
6198 : }
6199 4 : })?;
6200 :
6201 4 : let gc_layers = layers_to_remove
6202 4 : .iter()
6203 4 : .map(|x| guard.get_from_desc(x))
6204 4 : .collect::<Vec<Layer>>();
6205 4 :
6206 4 : result.layers_removed = gc_layers.len() as u64;
6207 4 :
6208 4 : self.remote_client.schedule_gc_update(&gc_layers)?;
6209 :
6210 4 : guard.open_mut()?.finish_gc_timeline(&gc_layers);
6211 4 :
6212 4 : #[cfg(feature = "testing")]
6213 4 : {
6214 4 : result.doomed_layers = gc_layers;
6215 4 : }
6216 4 : }
6217 :
6218 8 : info!(
6219 0 : "GC completed removing {} layers, cutoff {}",
6220 : result.layers_removed, new_gc_cutoff
6221 : );
6222 :
6223 8 : result.elapsed = now.elapsed().unwrap_or(Duration::ZERO);
6224 8 : Ok(result)
6225 8 : }
6226 :
6227 : /// Reconstruct a value, using the given base image and WAL records in 'data'.
6228 1340197 : async fn reconstruct_value(
6229 1340197 : &self,
6230 1340197 : key: Key,
6231 1340197 : request_lsn: Lsn,
6232 1340197 : mut data: ValueReconstructState,
6233 1340197 : ) -> Result<Bytes, PageReconstructError> {
6234 1340197 : // Perform WAL redo if needed
6235 1340197 : data.records.reverse();
6236 1340197 :
6237 1340197 : // If we have a page image, and no WAL, we're all set
6238 1340197 : if data.records.is_empty() {
6239 1338521 : if let Some((img_lsn, img)) = &data.img {
6240 1338521 : trace!(
6241 0 : "found page image for key {} at {}, no WAL redo required, req LSN {}",
6242 : key, img_lsn, request_lsn,
6243 : );
6244 1338521 : Ok(img.clone())
6245 : } else {
6246 0 : Err(PageReconstructError::from(anyhow!(
6247 0 : "base image for {key} at {request_lsn} not found"
6248 0 : )))
6249 : }
6250 : } else {
6251 : // We need to do WAL redo.
6252 : //
6253 : // If we don't have a base image, then the oldest WAL record better initialize
6254 : // the page
6255 1676 : if data.img.is_none() && !data.records.first().unwrap().1.will_init() {
6256 0 : Err(PageReconstructError::from(anyhow!(
6257 0 : "Base image for {} at {} not found, but got {} WAL records",
6258 0 : key,
6259 0 : request_lsn,
6260 0 : data.records.len()
6261 0 : )))
6262 : } else {
6263 1676 : if data.img.is_some() {
6264 1536 : trace!(
6265 0 : "found {} WAL records and a base image for {} at {}, performing WAL redo",
6266 0 : data.records.len(),
6267 : key,
6268 : request_lsn
6269 : );
6270 : } else {
6271 140 : trace!(
6272 0 : "found {} WAL records that will init the page for {} at {}, performing WAL redo",
6273 0 : data.records.len(),
6274 : key,
6275 : request_lsn
6276 : );
6277 : };
6278 1676 : let res = self
6279 1676 : .walredo_mgr
6280 1676 : .as_ref()
6281 1676 : .context("timeline has no walredo manager")
6282 1676 : .map_err(PageReconstructError::WalRedo)?
6283 1676 : .request_redo(key, request_lsn, data.img, data.records, self.pg_version)
6284 1676 : .await;
6285 1676 : let img = match res {
6286 1676 : Ok(img) => img,
6287 0 : Err(walredo::Error::Cancelled) => return Err(PageReconstructError::Cancelled),
6288 0 : Err(walredo::Error::Other(err)) => {
6289 0 : critical!("walredo failure during page reconstruction: {err:?}");
6290 0 : return Err(PageReconstructError::WalRedo(
6291 0 : err.context("reconstruct a page image"),
6292 0 : ));
6293 : }
6294 : };
6295 1676 : Ok(img)
6296 : }
6297 : }
6298 1340197 : }
6299 :
6300 0 : pub(crate) async fn spawn_download_all_remote_layers(
6301 0 : self: Arc<Self>,
6302 0 : request: DownloadRemoteLayersTaskSpawnRequest,
6303 0 : ctx: &RequestContext,
6304 0 : ) -> Result<DownloadRemoteLayersTaskInfo, DownloadRemoteLayersTaskInfo> {
6305 : use pageserver_api::models::DownloadRemoteLayersTaskState;
6306 :
6307 : // this is not really needed anymore; it has tests which really check the return value from
6308 : // http api. it would be better not to maintain this anymore.
6309 :
6310 0 : let mut status_guard = self.download_all_remote_layers_task_info.write().unwrap();
6311 0 : if let Some(st) = &*status_guard {
6312 0 : match &st.state {
6313 : DownloadRemoteLayersTaskState::Running => {
6314 0 : return Err(st.clone());
6315 : }
6316 : DownloadRemoteLayersTaskState::ShutDown
6317 0 : | DownloadRemoteLayersTaskState::Completed => {
6318 0 : *status_guard = None;
6319 0 : }
6320 : }
6321 0 : }
6322 :
6323 0 : let self_clone = Arc::clone(&self);
6324 0 : let task_ctx = ctx.detached_child(
6325 0 : TaskKind::DownloadAllRemoteLayers,
6326 0 : DownloadBehavior::Download,
6327 0 : );
6328 0 : let task_id = task_mgr::spawn(
6329 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
6330 0 : task_mgr::TaskKind::DownloadAllRemoteLayers,
6331 0 : self.tenant_shard_id,
6332 0 : Some(self.timeline_id),
6333 0 : "download all remote layers task",
6334 0 : async move {
6335 0 : self_clone.download_all_remote_layers(request, &task_ctx).await;
6336 0 : let mut status_guard = self_clone.download_all_remote_layers_task_info.write().unwrap();
6337 0 : match &mut *status_guard {
6338 : None => {
6339 0 : warn!("tasks status is supposed to be Some(), since we are running");
6340 : }
6341 0 : Some(st) => {
6342 0 : let exp_task_id = format!("{}", task_mgr::current_task_id().unwrap());
6343 0 : if st.task_id != exp_task_id {
6344 0 : warn!("task id changed while we were still running, expecting {} but have {}", exp_task_id, st.task_id);
6345 0 : } else {
6346 0 : st.state = DownloadRemoteLayersTaskState::Completed;
6347 0 : }
6348 : }
6349 : };
6350 0 : Ok(())
6351 0 : }
6352 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))
6353 : );
6354 :
6355 0 : let initial_info = DownloadRemoteLayersTaskInfo {
6356 0 : task_id: format!("{task_id}"),
6357 0 : state: DownloadRemoteLayersTaskState::Running,
6358 0 : total_layer_count: 0,
6359 0 : successful_download_count: 0,
6360 0 : failed_download_count: 0,
6361 0 : };
6362 0 : *status_guard = Some(initial_info.clone());
6363 0 :
6364 0 : Ok(initial_info)
6365 0 : }
6366 :
6367 0 : async fn download_all_remote_layers(
6368 0 : self: &Arc<Self>,
6369 0 : request: DownloadRemoteLayersTaskSpawnRequest,
6370 0 : ctx: &RequestContext,
6371 0 : ) {
6372 : use pageserver_api::models::DownloadRemoteLayersTaskState;
6373 :
6374 0 : let remaining = {
6375 0 : let guard = self.layers.read().await;
6376 0 : let Ok(lm) = guard.layer_map() else {
6377 : // technically here we could look into iterating accessible layers, but downloading
6378 : // all layers of a shutdown timeline makes no sense regardless.
6379 0 : tracing::info!("attempted to download all layers of shutdown timeline");
6380 0 : return;
6381 : };
6382 0 : lm.iter_historic_layers()
6383 0 : .map(|desc| guard.get_from_desc(&desc))
6384 0 : .collect::<Vec<_>>()
6385 0 : };
6386 0 : let total_layer_count = remaining.len();
6387 :
6388 : macro_rules! lock_status {
6389 : ($st:ident) => {
6390 : let mut st = self.download_all_remote_layers_task_info.write().unwrap();
6391 : let st = st
6392 : .as_mut()
6393 : .expect("this function is only called after the task has been spawned");
6394 : assert_eq!(
6395 : st.task_id,
6396 : format!(
6397 : "{}",
6398 : task_mgr::current_task_id().expect("we run inside a task_mgr task")
6399 : )
6400 : );
6401 : let $st = st;
6402 : };
6403 : }
6404 :
6405 : {
6406 0 : lock_status!(st);
6407 0 : st.total_layer_count = total_layer_count as u64;
6408 0 : }
6409 0 :
6410 0 : let mut remaining = remaining.into_iter();
6411 0 : let mut have_remaining = true;
6412 0 : let mut js = tokio::task::JoinSet::new();
6413 0 :
6414 0 : let cancel = task_mgr::shutdown_token();
6415 0 :
6416 0 : let limit = request.max_concurrent_downloads;
6417 :
6418 : loop {
6419 0 : while js.len() < limit.get() && have_remaining && !cancel.is_cancelled() {
6420 0 : let Some(next) = remaining.next() else {
6421 0 : have_remaining = false;
6422 0 : break;
6423 : };
6424 :
6425 0 : let span = tracing::info_span!("download", layer = %next);
6426 :
6427 0 : let ctx = ctx.attached_child();
6428 0 : js.spawn(
6429 0 : async move {
6430 0 : let res = next.download(&ctx).await;
6431 0 : (next, res)
6432 0 : }
6433 0 : .instrument(span),
6434 0 : );
6435 0 : }
6436 :
6437 0 : while let Some(res) = js.join_next().await {
6438 0 : match res {
6439 : Ok((_, Ok(_))) => {
6440 0 : lock_status!(st);
6441 0 : st.successful_download_count += 1;
6442 : }
6443 0 : Ok((layer, Err(e))) => {
6444 0 : tracing::error!(%layer, "download failed: {e:#}");
6445 0 : lock_status!(st);
6446 0 : st.failed_download_count += 1;
6447 : }
6448 0 : Err(je) if je.is_cancelled() => unreachable!("not used here"),
6449 0 : Err(je) if je.is_panic() => {
6450 0 : lock_status!(st);
6451 0 : st.failed_download_count += 1;
6452 : }
6453 0 : Err(je) => tracing::warn!("unknown joinerror: {je:?}"),
6454 : }
6455 : }
6456 :
6457 0 : if js.is_empty() && (!have_remaining || cancel.is_cancelled()) {
6458 0 : break;
6459 0 : }
6460 : }
6461 :
6462 : {
6463 0 : lock_status!(st);
6464 0 : st.state = DownloadRemoteLayersTaskState::Completed;
6465 : }
6466 0 : }
6467 :
6468 0 : pub(crate) fn get_download_all_remote_layers_task_info(
6469 0 : &self,
6470 0 : ) -> Option<DownloadRemoteLayersTaskInfo> {
6471 0 : self.download_all_remote_layers_task_info
6472 0 : .read()
6473 0 : .unwrap()
6474 0 : .clone()
6475 0 : }
6476 : }
6477 :
6478 : impl Timeline {
6479 : /// Returns non-remote layers for eviction.
6480 0 : pub(crate) async fn get_local_layers_for_disk_usage_eviction(&self) -> DiskUsageEvictionInfo {
6481 0 : let guard = self.layers.read().await;
6482 0 : let mut max_layer_size: Option<u64> = None;
6483 0 :
6484 0 : let resident_layers = guard
6485 0 : .likely_resident_layers()
6486 0 : .map(|layer| {
6487 0 : let file_size = layer.layer_desc().file_size;
6488 0 : max_layer_size = max_layer_size.map_or(Some(file_size), |m| Some(m.max(file_size)));
6489 0 :
6490 0 : let last_activity_ts = layer.latest_activity();
6491 0 :
6492 0 : EvictionCandidate {
6493 0 : layer: layer.to_owned().into(),
6494 0 : last_activity_ts,
6495 0 : relative_last_activity: finite_f32::FiniteF32::ZERO,
6496 0 : visibility: layer.visibility(),
6497 0 : }
6498 0 : })
6499 0 : .collect();
6500 0 :
6501 0 : DiskUsageEvictionInfo {
6502 0 : max_layer_size,
6503 0 : resident_layers,
6504 0 : }
6505 0 : }
6506 :
6507 3752 : pub(crate) fn get_shard_index(&self) -> ShardIndex {
6508 3752 : ShardIndex {
6509 3752 : shard_number: self.tenant_shard_id.shard_number,
6510 3752 : shard_count: self.tenant_shard_id.shard_count,
6511 3752 : }
6512 3752 : }
6513 :
6514 : /// Persistently blocks gc for `Manual` reason.
6515 : ///
6516 : /// Returns true if no such block existed before, false otherwise.
6517 0 : pub(crate) async fn block_gc(&self, tenant: &super::Tenant) -> anyhow::Result<bool> {
6518 : use crate::tenant::remote_timeline_client::index::GcBlockingReason;
6519 0 : assert_eq!(self.tenant_shard_id, tenant.tenant_shard_id);
6520 0 : tenant.gc_block.insert(self, GcBlockingReason::Manual).await
6521 0 : }
6522 :
6523 : /// Persistently unblocks gc for `Manual` reason.
6524 0 : pub(crate) async fn unblock_gc(&self, tenant: &super::Tenant) -> anyhow::Result<()> {
6525 : use crate::tenant::remote_timeline_client::index::GcBlockingReason;
6526 0 : assert_eq!(self.tenant_shard_id, tenant.tenant_shard_id);
6527 0 : tenant.gc_block.remove(self, GcBlockingReason::Manual).await
6528 0 : }
6529 :
6530 : #[cfg(test)]
6531 116 : pub(super) fn force_advance_lsn(self: &Arc<Timeline>, new_lsn: Lsn) {
6532 116 : self.last_record_lsn.advance(new_lsn);
6533 116 : }
6534 :
6535 : #[cfg(test)]
6536 4 : pub(super) fn force_set_disk_consistent_lsn(&self, new_value: Lsn) {
6537 4 : self.disk_consistent_lsn.store(new_value);
6538 4 : }
6539 :
6540 : /// Force create an image layer and place it into the layer map.
6541 : ///
6542 : /// DO NOT use this function directly. Use [`Tenant::branch_timeline_test_with_layers`]
6543 : /// or [`Tenant::create_test_timeline_with_layers`] to ensure all these layers are
6544 : /// placed into the layer map in one run AND be validated.
6545 : #[cfg(test)]
6546 128 : pub(super) async fn force_create_image_layer(
6547 128 : self: &Arc<Timeline>,
6548 128 : lsn: Lsn,
6549 128 : mut images: Vec<(Key, Bytes)>,
6550 128 : check_start_lsn: Option<Lsn>,
6551 128 : ctx: &RequestContext,
6552 128 : ) -> anyhow::Result<()> {
6553 128 : let last_record_lsn = self.get_last_record_lsn();
6554 128 : assert!(
6555 128 : lsn <= last_record_lsn,
6556 0 : "advance last record lsn before inserting a layer, lsn={lsn}, last_record_lsn={last_record_lsn}"
6557 : );
6558 128 : if let Some(check_start_lsn) = check_start_lsn {
6559 128 : assert!(lsn >= check_start_lsn);
6560 0 : }
6561 380 : images.sort_unstable_by(|(ka, _), (kb, _)| ka.cmp(kb));
6562 128 : let min_key = *images.first().map(|(k, _)| k).unwrap();
6563 128 : let end_key = images.last().map(|(k, _)| k).unwrap().next();
6564 128 : let mut image_layer_writer = ImageLayerWriter::new(
6565 128 : self.conf,
6566 128 : self.timeline_id,
6567 128 : self.tenant_shard_id,
6568 128 : &(min_key..end_key),
6569 128 : lsn,
6570 128 : ctx,
6571 128 : )
6572 128 : .await?;
6573 636 : for (key, img) in images {
6574 508 : image_layer_writer.put_image(key, img, ctx).await?;
6575 : }
6576 128 : let (desc, path) = image_layer_writer.finish(ctx).await?;
6577 128 : let image_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
6578 128 : info!("force created image layer {}", image_layer.local_path());
6579 : {
6580 128 : let mut guard = self.layers.write().await;
6581 128 : guard
6582 128 : .open_mut()
6583 128 : .unwrap()
6584 128 : .force_insert_layer(image_layer.clone());
6585 128 : }
6586 128 :
6587 128 : // Update remote_timeline_client state to reflect existence of this layer
6588 128 : self.remote_client
6589 128 : .schedule_layer_file_upload(image_layer)
6590 128 : .unwrap();
6591 128 :
6592 128 : Ok(())
6593 128 : }
6594 :
6595 : /// Force create a delta layer and place it into the layer map.
6596 : ///
6597 : /// DO NOT use this function directly. Use [`Tenant::branch_timeline_test_with_layers`]
6598 : /// or [`Tenant::create_test_timeline_with_layers`] to ensure all these layers are
6599 : /// placed into the layer map in one run AND be validated.
6600 : #[cfg(test)]
6601 184 : pub(super) async fn force_create_delta_layer(
6602 184 : self: &Arc<Timeline>,
6603 184 : mut deltas: DeltaLayerTestDesc,
6604 184 : check_start_lsn: Option<Lsn>,
6605 184 : ctx: &RequestContext,
6606 184 : ) -> anyhow::Result<()> {
6607 184 : let last_record_lsn = self.get_last_record_lsn();
6608 184 : deltas
6609 184 : .data
6610 264 : .sort_unstable_by(|(ka, la, _), (kb, lb, _)| (ka, la).cmp(&(kb, lb)));
6611 184 : assert!(deltas.data.first().unwrap().0 >= deltas.key_range.start);
6612 184 : assert!(deltas.data.last().unwrap().0 < deltas.key_range.end);
6613 632 : for (_, lsn, _) in &deltas.data {
6614 448 : assert!(deltas.lsn_range.start <= *lsn && *lsn < deltas.lsn_range.end);
6615 : }
6616 184 : assert!(
6617 184 : deltas.lsn_range.end <= last_record_lsn,
6618 0 : "advance last record lsn before inserting a layer, end_lsn={}, last_record_lsn={}",
6619 : deltas.lsn_range.end,
6620 : last_record_lsn
6621 : );
6622 184 : if let Some(check_start_lsn) = check_start_lsn {
6623 184 : assert!(deltas.lsn_range.start >= check_start_lsn);
6624 0 : }
6625 184 : let mut delta_layer_writer = DeltaLayerWriter::new(
6626 184 : self.conf,
6627 184 : self.timeline_id,
6628 184 : self.tenant_shard_id,
6629 184 : deltas.key_range.start,
6630 184 : deltas.lsn_range,
6631 184 : ctx,
6632 184 : )
6633 184 : .await?;
6634 632 : for (key, lsn, val) in deltas.data {
6635 448 : delta_layer_writer.put_value(key, lsn, val, ctx).await?;
6636 : }
6637 184 : let (desc, path) = delta_layer_writer.finish(deltas.key_range.end, ctx).await?;
6638 184 : let delta_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
6639 184 : info!("force created delta layer {}", delta_layer.local_path());
6640 : {
6641 184 : let mut guard = self.layers.write().await;
6642 184 : guard
6643 184 : .open_mut()
6644 184 : .unwrap()
6645 184 : .force_insert_layer(delta_layer.clone());
6646 184 : }
6647 184 :
6648 184 : // Update remote_timeline_client state to reflect existence of this layer
6649 184 : self.remote_client
6650 184 : .schedule_layer_file_upload(delta_layer)
6651 184 : .unwrap();
6652 184 :
6653 184 : Ok(())
6654 184 : }
6655 :
6656 : /// Force create an in-memory layer and place them into the layer map.
6657 : #[cfg(test)]
6658 8 : pub(super) async fn force_create_in_memory_layer(
6659 8 : self: &Arc<Timeline>,
6660 8 : mut in_memory: InMemoryLayerTestDesc,
6661 8 : check_start_lsn: Option<Lsn>,
6662 8 : ctx: &RequestContext,
6663 8 : ) -> anyhow::Result<()> {
6664 : use utils::bin_ser::BeSer;
6665 :
6666 : // Validate LSNs
6667 8 : if let Some(check_start_lsn) = check_start_lsn {
6668 8 : assert!(in_memory.lsn_range.start >= check_start_lsn);
6669 0 : }
6670 :
6671 8 : let last_record_lsn = self.get_last_record_lsn();
6672 8 : let layer_end_lsn = if in_memory.is_open {
6673 4 : in_memory
6674 4 : .data
6675 4 : .iter()
6676 40 : .map(|(_key, lsn, _value)| lsn)
6677 4 : .max()
6678 4 : .cloned()
6679 : } else {
6680 4 : Some(in_memory.lsn_range.end)
6681 : };
6682 :
6683 8 : if let Some(end) = layer_end_lsn {
6684 8 : assert!(
6685 8 : end <= last_record_lsn,
6686 0 : "advance last record lsn before inserting a layer, end_lsn={}, last_record_lsn={}",
6687 : end,
6688 : last_record_lsn,
6689 : );
6690 0 : }
6691 :
6692 80 : in_memory.data.iter().for_each(|(_key, lsn, _value)| {
6693 80 : assert!(*lsn >= in_memory.lsn_range.start);
6694 80 : assert!(*lsn < in_memory.lsn_range.end);
6695 80 : });
6696 8 :
6697 8 : // Build the batch
6698 8 : in_memory
6699 8 : .data
6700 72 : .sort_unstable_by(|(ka, la, _), (kb, lb, _)| (ka, la).cmp(&(kb, lb)));
6701 8 :
6702 8 : let data = in_memory
6703 8 : .data
6704 8 : .into_iter()
6705 80 : .map(|(key, lsn, value)| {
6706 80 : let value_size = value.serialized_size().unwrap() as usize;
6707 80 : (key.to_compact(), lsn, value_size, value)
6708 80 : })
6709 8 : .collect::<Vec<_>>();
6710 8 :
6711 8 : let batch = SerializedValueBatch::from_values(data);
6712 :
6713 : // Create the in-memory layer and write the batch into it
6714 8 : let layer = InMemoryLayer::create(
6715 8 : self.conf,
6716 8 : self.timeline_id,
6717 8 : self.tenant_shard_id,
6718 8 : in_memory.lsn_range.start,
6719 8 : &self.gate,
6720 8 : // TODO: if we ever use this function in production code, we need to pass the real cancellation token
6721 8 : &CancellationToken::new(),
6722 8 : ctx,
6723 8 : )
6724 8 : .await
6725 8 : .unwrap();
6726 8 :
6727 8 : layer.put_batch(batch, ctx).await.unwrap();
6728 8 : if !in_memory.is_open {
6729 4 : layer.freeze(in_memory.lsn_range.end).await;
6730 4 : }
6731 :
6732 8 : info!("force created in-memory layer {:?}", in_memory.lsn_range);
6733 :
6734 : // Link the layer to the layer map
6735 : {
6736 8 : let mut guard = self.layers.write().await;
6737 8 : let layer_map = guard.open_mut().unwrap();
6738 8 : layer_map.force_insert_in_memory_layer(Arc::new(layer));
6739 8 : }
6740 8 :
6741 8 : Ok(())
6742 8 : }
6743 :
6744 : /// Return all keys at the LSN in the image layers
6745 : #[cfg(test)]
6746 12 : pub(crate) async fn inspect_image_layers(
6747 12 : self: &Arc<Timeline>,
6748 12 : lsn: Lsn,
6749 12 : ctx: &RequestContext,
6750 12 : io_concurrency: IoConcurrency,
6751 12 : ) -> anyhow::Result<Vec<(Key, Bytes)>> {
6752 12 : let mut all_data = Vec::new();
6753 12 : let guard = self.layers.read().await;
6754 68 : for layer in guard.layer_map()?.iter_historic_layers() {
6755 68 : if !layer.is_delta() && layer.image_layer_lsn() == lsn {
6756 16 : let layer = guard.get_from_desc(&layer);
6757 16 : let mut reconstruct_data = ValuesReconstructState::new(io_concurrency.clone());
6758 16 : layer
6759 16 : .get_values_reconstruct_data(
6760 16 : KeySpace::single(Key::MIN..Key::MAX),
6761 16 : lsn..Lsn(lsn.0 + 1),
6762 16 : &mut reconstruct_data,
6763 16 : ctx,
6764 16 : )
6765 16 : .await?;
6766 132 : for (k, v) in std::mem::take(&mut reconstruct_data.keys) {
6767 132 : let v = v.collect_pending_ios().await?;
6768 132 : all_data.push((k, v.img.unwrap().1));
6769 : }
6770 52 : }
6771 : }
6772 12 : all_data.sort();
6773 12 : Ok(all_data)
6774 12 : }
6775 :
6776 : /// Get all historic layer descriptors in the layer map
6777 : #[cfg(test)]
6778 48 : pub(crate) async fn inspect_historic_layers(
6779 48 : self: &Arc<Timeline>,
6780 48 : ) -> anyhow::Result<Vec<super::storage_layer::PersistentLayerKey>> {
6781 48 : let mut layers = Vec::new();
6782 48 : let guard = self.layers.read().await;
6783 228 : for layer in guard.layer_map()?.iter_historic_layers() {
6784 228 : layers.push(layer.key());
6785 228 : }
6786 48 : Ok(layers)
6787 48 : }
6788 :
6789 : #[cfg(test)]
6790 20 : pub(crate) fn add_extra_test_dense_keyspace(&self, ks: KeySpace) {
6791 20 : let mut keyspace = self.extra_test_dense_keyspace.load().as_ref().clone();
6792 20 : keyspace.merge(&ks);
6793 20 : self.extra_test_dense_keyspace.store(Arc::new(keyspace));
6794 20 : }
6795 : }
6796 :
6797 : /// Tracking writes ingestion does to a particular in-memory layer.
6798 : ///
6799 : /// Cleared upon freezing a layer.
6800 : pub(crate) struct TimelineWriterState {
6801 : open_layer: Arc<InMemoryLayer>,
6802 : current_size: u64,
6803 : // Previous Lsn which passed through
6804 : prev_lsn: Option<Lsn>,
6805 : // Largest Lsn which passed through the current writer
6806 : max_lsn: Option<Lsn>,
6807 : // Cached details of the last freeze. Avoids going trough the atomic/lock on every put.
6808 : cached_last_freeze_at: Lsn,
6809 : }
6810 :
6811 : impl TimelineWriterState {
6812 2608 : fn new(open_layer: Arc<InMemoryLayer>, current_size: u64, last_freeze_at: Lsn) -> Self {
6813 2608 : Self {
6814 2608 : open_layer,
6815 2608 : current_size,
6816 2608 : prev_lsn: None,
6817 2608 : max_lsn: None,
6818 2608 : cached_last_freeze_at: last_freeze_at,
6819 2608 : }
6820 2608 : }
6821 : }
6822 :
6823 : /// Various functions to mutate the timeline.
6824 : // TODO Currently, Deref is used to allow easy access to read methods from this trait.
6825 : // This is probably considered a bad practice in Rust and should be fixed eventually,
6826 : // but will cause large code changes.
6827 : pub(crate) struct TimelineWriter<'a> {
6828 : tl: &'a Timeline,
6829 : write_guard: tokio::sync::MutexGuard<'a, Option<TimelineWriterState>>,
6830 : }
6831 :
6832 : impl Deref for TimelineWriter<'_> {
6833 : type Target = Timeline;
6834 :
6835 19796560 : fn deref(&self) -> &Self::Target {
6836 19796560 : self.tl
6837 19796560 : }
6838 : }
6839 :
6840 : #[derive(PartialEq)]
6841 : enum OpenLayerAction {
6842 : Roll,
6843 : Open,
6844 : None,
6845 : }
6846 :
6847 : impl TimelineWriter<'_> {
6848 9608480 : async fn handle_open_layer_action(
6849 9608480 : &mut self,
6850 9608480 : at: Lsn,
6851 9608480 : action: OpenLayerAction,
6852 9608480 : ctx: &RequestContext,
6853 9608480 : ) -> anyhow::Result<&Arc<InMemoryLayer>> {
6854 9608480 : match action {
6855 : OpenLayerAction::Roll => {
6856 160 : let freeze_at = self.write_guard.as_ref().unwrap().max_lsn.unwrap();
6857 160 : self.roll_layer(freeze_at).await?;
6858 160 : self.open_layer(at, ctx).await?;
6859 : }
6860 2448 : OpenLayerAction::Open => self.open_layer(at, ctx).await?,
6861 : OpenLayerAction::None => {
6862 9605872 : assert!(self.write_guard.is_some());
6863 : }
6864 : }
6865 :
6866 9608480 : Ok(&self.write_guard.as_ref().unwrap().open_layer)
6867 9608480 : }
6868 :
6869 2608 : async fn open_layer(&mut self, at: Lsn, ctx: &RequestContext) -> anyhow::Result<()> {
6870 2608 : let layer = self
6871 2608 : .tl
6872 2608 : .get_layer_for_write(at, &self.write_guard, ctx)
6873 2608 : .await?;
6874 2608 : let initial_size = layer.size().await?;
6875 :
6876 2608 : let last_freeze_at = self.last_freeze_at.load();
6877 2608 : self.write_guard.replace(TimelineWriterState::new(
6878 2608 : layer,
6879 2608 : initial_size,
6880 2608 : last_freeze_at,
6881 2608 : ));
6882 2608 :
6883 2608 : Ok(())
6884 2608 : }
6885 :
6886 160 : async fn roll_layer(&mut self, freeze_at: Lsn) -> Result<(), FlushLayerError> {
6887 160 : let current_size = self.write_guard.as_ref().unwrap().current_size;
6888 :
6889 : // If layer flushes are backpressured due to compaction not keeping up, wait for the flush
6890 : // to propagate the backpressure up into WAL ingestion.
6891 160 : let l0_count = self
6892 160 : .tl
6893 160 : .layers
6894 160 : .read()
6895 160 : .await
6896 160 : .layer_map()?
6897 160 : .level0_deltas()
6898 160 : .len();
6899 160 : let wait_thresholds = [
6900 160 : self.get_l0_flush_delay_threshold(),
6901 160 : self.get_l0_flush_stall_threshold(),
6902 160 : ];
6903 160 : let wait_threshold = wait_thresholds.into_iter().flatten().min();
6904 :
6905 : // self.write_guard will be taken by the freezing
6906 160 : let flush_id = self
6907 160 : .tl
6908 160 : .freeze_inmem_layer_at(freeze_at, &mut self.write_guard)
6909 160 : .await?;
6910 :
6911 160 : assert!(self.write_guard.is_none());
6912 :
6913 160 : if let Some(wait_threshold) = wait_threshold {
6914 0 : if l0_count >= wait_threshold {
6915 0 : debug!(
6916 0 : "layer roll waiting for flush due to compaction backpressure at {l0_count} L0 layers"
6917 : );
6918 0 : self.tl.wait_flush_completion(flush_id).await?;
6919 0 : }
6920 160 : }
6921 :
6922 160 : if current_size >= self.get_checkpoint_distance() * 2 {
6923 0 : warn!("Flushed oversized open layer with size {}", current_size)
6924 160 : }
6925 :
6926 160 : Ok(())
6927 160 : }
6928 :
6929 9608480 : fn get_open_layer_action(&self, lsn: Lsn, new_value_size: u64) -> OpenLayerAction {
6930 9608480 : let state = &*self.write_guard;
6931 9608480 : let Some(state) = &state else {
6932 2448 : return OpenLayerAction::Open;
6933 : };
6934 :
6935 : #[cfg(feature = "testing")]
6936 9606032 : if state.cached_last_freeze_at < self.tl.last_freeze_at.load() {
6937 : // this check and assertion are not really needed because
6938 : // LayerManager::try_freeze_in_memory_layer will always clear out the
6939 : // TimelineWriterState if something is frozen. however, we can advance last_freeze_at when there
6940 : // is no TimelineWriterState.
6941 0 : assert!(
6942 0 : state.open_layer.end_lsn.get().is_some(),
6943 0 : "our open_layer must be outdated"
6944 : );
6945 :
6946 : // this would be a memory leak waiting to happen because the in-memory layer always has
6947 : // an index
6948 0 : panic!("BUG: TimelineWriterState held on to frozen in-memory layer.");
6949 9606032 : }
6950 9606032 :
6951 9606032 : if state.prev_lsn == Some(lsn) {
6952 : // Rolling mid LSN is not supported by [downstream code].
6953 : // Hence, only roll at LSN boundaries.
6954 : //
6955 : // [downstream code]: https://github.com/neondatabase/neon/pull/7993#discussion_r1633345422
6956 12 : return OpenLayerAction::None;
6957 9606020 : }
6958 9606020 :
6959 9606020 : if state.current_size == 0 {
6960 : // Don't roll empty layers
6961 0 : return OpenLayerAction::None;
6962 9606020 : }
6963 9606020 :
6964 9606020 : if self.tl.should_roll(
6965 9606020 : state.current_size,
6966 9606020 : state.current_size + new_value_size,
6967 9606020 : self.get_checkpoint_distance(),
6968 9606020 : lsn,
6969 9606020 : state.cached_last_freeze_at,
6970 9606020 : state.open_layer.get_opened_at(),
6971 9606020 : ) {
6972 160 : OpenLayerAction::Roll
6973 : } else {
6974 9605860 : OpenLayerAction::None
6975 : }
6976 9608480 : }
6977 :
6978 : /// Put a batch of keys at the specified Lsns.
6979 9608476 : pub(crate) async fn put_batch(
6980 9608476 : &mut self,
6981 9608476 : batch: SerializedValueBatch,
6982 9608476 : ctx: &RequestContext,
6983 9608476 : ) -> anyhow::Result<()> {
6984 9608476 : if !batch.has_data() {
6985 0 : return Ok(());
6986 9608476 : }
6987 9608476 :
6988 9608476 : // In debug builds, assert that we don't write any keys that don't belong to this shard.
6989 9608476 : // We don't assert this in release builds, since key ownership policies may change over
6990 9608476 : // time. Stray keys will be removed during compaction.
6991 9608476 : if cfg!(debug_assertions) {
6992 19789920 : for metadata in &batch.metadata {
6993 10181444 : if let ValueMeta::Serialized(metadata) = metadata {
6994 10181444 : let key = Key::from_compact(metadata.key);
6995 10181444 : assert!(
6996 10181444 : self.shard_identity.is_key_local(&key)
6997 0 : || self.shard_identity.is_key_global(&key),
6998 0 : "key {key} does not belong on shard {}",
6999 0 : self.shard_identity.shard_index()
7000 : );
7001 0 : }
7002 : }
7003 0 : }
7004 :
7005 9608476 : let batch_max_lsn = batch.max_lsn;
7006 9608476 : let buf_size: u64 = batch.buffer_size() as u64;
7007 9608476 :
7008 9608476 : let action = self.get_open_layer_action(batch_max_lsn, buf_size);
7009 9608476 : let layer = self
7010 9608476 : .handle_open_layer_action(batch_max_lsn, action, ctx)
7011 9608476 : .await?;
7012 :
7013 9608476 : let res = layer.put_batch(batch, ctx).await;
7014 :
7015 9608476 : if res.is_ok() {
7016 9608476 : // Update the current size only when the entire write was ok.
7017 9608476 : // In case of failures, we may have had partial writes which
7018 9608476 : // render the size tracking out of sync. That's ok because
7019 9608476 : // the checkpoint distance should be significantly smaller
7020 9608476 : // than the S3 single shot upload limit of 5GiB.
7021 9608476 : let state = self.write_guard.as_mut().unwrap();
7022 9608476 :
7023 9608476 : state.current_size += buf_size;
7024 9608476 : state.prev_lsn = Some(batch_max_lsn);
7025 9608476 : state.max_lsn = std::cmp::max(state.max_lsn, Some(batch_max_lsn));
7026 9608476 : }
7027 :
7028 9608476 : res
7029 9608476 : }
7030 :
7031 : #[cfg(test)]
7032 : /// Test helper, for tests that would like to poke individual values without composing a batch
7033 8780308 : pub(crate) async fn put(
7034 8780308 : &mut self,
7035 8780308 : key: Key,
7036 8780308 : lsn: Lsn,
7037 8780308 : value: &Value,
7038 8780308 : ctx: &RequestContext,
7039 8780308 : ) -> anyhow::Result<()> {
7040 : use utils::bin_ser::BeSer;
7041 8780308 : if !key.is_valid_key_on_write_path() {
7042 0 : bail!(
7043 0 : "the request contains data not supported by pageserver at TimelineWriter::put: {}",
7044 0 : key
7045 0 : );
7046 8780308 : }
7047 8780308 : let val_ser_size = value.serialized_size().unwrap() as usize;
7048 8780308 : let batch = SerializedValueBatch::from_values(vec![(
7049 8780308 : key.to_compact(),
7050 8780308 : lsn,
7051 8780308 : val_ser_size,
7052 8780308 : value.clone(),
7053 8780308 : )]);
7054 8780308 :
7055 8780308 : self.put_batch(batch, ctx).await
7056 8780308 : }
7057 :
7058 4 : pub(crate) async fn delete_batch(
7059 4 : &mut self,
7060 4 : batch: &[(Range<Key>, Lsn)],
7061 4 : ctx: &RequestContext,
7062 4 : ) -> anyhow::Result<()> {
7063 4 : if let Some((_, lsn)) = batch.first() {
7064 4 : let action = self.get_open_layer_action(*lsn, 0);
7065 4 : let layer = self.handle_open_layer_action(*lsn, action, ctx).await?;
7066 4 : layer.put_tombstones(batch).await?;
7067 0 : }
7068 :
7069 4 : Ok(())
7070 4 : }
7071 :
7072 : /// Track the end of the latest digested WAL record.
7073 : /// Remember the (end of) last valid WAL record remembered in the timeline.
7074 : ///
7075 : /// Call this after you have finished writing all the WAL up to 'lsn'.
7076 : ///
7077 : /// 'lsn' must be aligned. This wakes up any wait_lsn() callers waiting for
7078 : /// the 'lsn' or anything older. The previous last record LSN is stored alongside
7079 : /// the latest and can be read.
7080 10558200 : pub(crate) fn finish_write(&self, new_lsn: Lsn) {
7081 10558200 : self.tl.finish_write(new_lsn);
7082 10558200 : }
7083 :
7084 541140 : pub(crate) fn update_current_logical_size(&self, delta: i64) {
7085 541140 : self.tl.update_current_logical_size(delta)
7086 541140 : }
7087 : }
7088 :
7089 : // We need TimelineWriter to be send in upcoming conversion of
7090 : // Timeline::layers to tokio::sync::RwLock.
7091 : #[test]
7092 4 : fn is_send() {
7093 4 : fn _assert_send<T: Send>() {}
7094 4 : _assert_send::<TimelineWriter<'_>>();
7095 4 : }
7096 :
7097 : #[cfg(test)]
7098 : mod tests {
7099 : use std::sync::Arc;
7100 :
7101 : use pageserver_api::key::Key;
7102 : use pageserver_api::value::Value;
7103 : use std::iter::Iterator;
7104 : use tracing::Instrument;
7105 : use utils::id::TimelineId;
7106 : use utils::lsn::Lsn;
7107 :
7108 : use super::HeatMapTimeline;
7109 : use crate::context::RequestContextBuilder;
7110 : use crate::tenant::harness::{TenantHarness, test_img};
7111 : use crate::tenant::layer_map::LayerMap;
7112 : use crate::tenant::storage_layer::{Layer, LayerName, LayerVisibilityHint};
7113 : use crate::tenant::timeline::{DeltaLayerTestDesc, EvictionError};
7114 : use crate::tenant::{PreviousHeatmap, Timeline};
7115 :
7116 20 : fn assert_heatmaps_have_same_layers(lhs: &HeatMapTimeline, rhs: &HeatMapTimeline) {
7117 20 : assert_eq!(lhs.all_layers().count(), rhs.all_layers().count());
7118 20 : let lhs_rhs = lhs.all_layers().zip(rhs.all_layers());
7119 100 : for (l, r) in lhs_rhs {
7120 80 : assert_eq!(l.name, r.name);
7121 80 : assert_eq!(l.metadata, r.metadata);
7122 : }
7123 20 : }
7124 :
7125 : #[tokio::test]
7126 4 : async fn test_heatmap_generation() {
7127 4 : let harness = TenantHarness::create("heatmap_generation").await.unwrap();
7128 4 :
7129 4 : let covered_delta = DeltaLayerTestDesc::new_with_inferred_key_range(
7130 4 : Lsn(0x10)..Lsn(0x20),
7131 4 : vec![(
7132 4 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
7133 4 : Lsn(0x11),
7134 4 : Value::Image(test_img("foo")),
7135 4 : )],
7136 4 : );
7137 4 : let visible_delta = DeltaLayerTestDesc::new_with_inferred_key_range(
7138 4 : Lsn(0x10)..Lsn(0x20),
7139 4 : vec![(
7140 4 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
7141 4 : Lsn(0x11),
7142 4 : Value::Image(test_img("foo")),
7143 4 : )],
7144 4 : );
7145 4 : let l0_delta = DeltaLayerTestDesc::new(
7146 4 : Lsn(0x20)..Lsn(0x30),
7147 4 : Key::from_hex("000000000000000000000000000000000000").unwrap()
7148 4 : ..Key::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(),
7149 4 : vec![(
7150 4 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
7151 4 : Lsn(0x25),
7152 4 : Value::Image(test_img("foo")),
7153 4 : )],
7154 4 : );
7155 4 : let delta_layers = vec![
7156 4 : covered_delta.clone(),
7157 4 : visible_delta.clone(),
7158 4 : l0_delta.clone(),
7159 4 : ];
7160 4 :
7161 4 : let image_layer = (
7162 4 : Lsn(0x40),
7163 4 : vec![(
7164 4 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
7165 4 : test_img("bar"),
7166 4 : )],
7167 4 : );
7168 4 : let image_layers = vec![image_layer];
7169 4 :
7170 4 : let (tenant, ctx) = harness.load().await;
7171 4 : let timeline = tenant
7172 4 : .create_test_timeline_with_layers(
7173 4 : TimelineId::generate(),
7174 4 : Lsn(0x10),
7175 4 : 14,
7176 4 : &ctx,
7177 4 : Vec::new(), // in-memory layers
7178 4 : delta_layers,
7179 4 : image_layers,
7180 4 : Lsn(0x100),
7181 4 : )
7182 4 : .await
7183 4 : .unwrap();
7184 4 : let ctx = &ctx.with_scope_timeline(&timeline);
7185 4 :
7186 4 : // Layer visibility is an input to heatmap generation, so refresh it first
7187 4 : timeline.update_layer_visibility().await.unwrap();
7188 4 :
7189 4 : let heatmap = timeline
7190 4 : .generate_heatmap()
7191 4 : .await
7192 4 : .expect("Infallible while timeline is not shut down");
7193 4 :
7194 4 : assert_eq!(heatmap.timeline_id, timeline.timeline_id);
7195 4 :
7196 4 : // L0 should come last
7197 4 : let heatmap_layers = heatmap.all_layers().collect::<Vec<_>>();
7198 4 : assert_eq!(heatmap_layers.last().unwrap().name, l0_delta.layer_name());
7199 4 :
7200 4 : let mut last_lsn = Lsn::MAX;
7201 20 : for layer in heatmap_layers {
7202 4 : // Covered layer should be omitted
7203 16 : assert!(layer.name != covered_delta.layer_name());
7204 4 :
7205 16 : let layer_lsn = match &layer.name {
7206 8 : LayerName::Delta(d) => d.lsn_range.end,
7207 8 : LayerName::Image(i) => i.lsn,
7208 4 : };
7209 4 :
7210 4 : // Apart from L0s, newest Layers should come first
7211 16 : if !LayerMap::is_l0(layer.name.key_range(), layer.name.is_delta()) {
7212 12 : assert!(layer_lsn <= last_lsn);
7213 12 : last_lsn = layer_lsn;
7214 4 : }
7215 4 : }
7216 4 :
7217 4 : // Evict all the layers and stash the old heatmap in the timeline.
7218 4 : // This simulates a migration to a cold secondary location.
7219 4 :
7220 4 : let guard = timeline.layers.read().await;
7221 4 : let mut all_layers = Vec::new();
7222 4 : let forever = std::time::Duration::from_secs(120);
7223 20 : for layer in guard.likely_resident_layers() {
7224 20 : all_layers.push(layer.clone());
7225 20 : layer.evict_and_wait(forever).await.unwrap();
7226 4 : }
7227 4 : drop(guard);
7228 4 :
7229 4 : timeline
7230 4 : .previous_heatmap
7231 4 : .store(Some(Arc::new(PreviousHeatmap::Active {
7232 4 : heatmap: heatmap.clone(),
7233 4 : read_at: std::time::Instant::now(),
7234 4 : end_lsn: None,
7235 4 : })));
7236 4 :
7237 4 : // Generate a new heatmap and assert that it contains the same layers as the old one.
7238 4 : let post_migration_heatmap = timeline.generate_heatmap().await.unwrap();
7239 4 : assert_heatmaps_have_same_layers(&heatmap, &post_migration_heatmap);
7240 4 :
7241 4 : // Download each layer one by one. Generate the heatmap at each step and check
7242 4 : // that it's stable.
7243 24 : for layer in all_layers {
7244 20 : if layer.visibility() == LayerVisibilityHint::Covered {
7245 4 : continue;
7246 16 : }
7247 16 :
7248 16 : eprintln!("Downloading {layer} and re-generating heatmap");
7249 16 :
7250 16 : let ctx = &RequestContextBuilder::extend(ctx)
7251 16 : .download_behavior(crate::context::DownloadBehavior::Download)
7252 16 : .build();
7253 4 :
7254 16 : let _resident = layer
7255 16 : .download_and_keep_resident(ctx)
7256 16 : .instrument(tracing::info_span!(
7257 16 : parent: None,
7258 4 : "download_layer",
7259 4 : tenant_id = %timeline.tenant_shard_id.tenant_id,
7260 0 : shard_id = %timeline.tenant_shard_id.shard_slug(),
7261 0 : timeline_id = %timeline.timeline_id
7262 4 : ))
7263 16 : .await
7264 16 : .unwrap();
7265 4 :
7266 16 : let post_download_heatmap = timeline.generate_heatmap().await.unwrap();
7267 16 : assert_heatmaps_have_same_layers(&heatmap, &post_download_heatmap);
7268 4 : }
7269 4 :
7270 4 : // Everything from the post-migration heatmap is now resident.
7271 4 : // Check that we drop it from memory.
7272 4 : assert!(matches!(
7273 4 : timeline.previous_heatmap.load().as_deref(),
7274 4 : Some(PreviousHeatmap::Obsolete)
7275 4 : ));
7276 4 : }
7277 :
7278 : #[tokio::test]
7279 4 : async fn test_previous_heatmap_obsoletion() {
7280 4 : let harness = TenantHarness::create("heatmap_previous_heatmap_obsoletion")
7281 4 : .await
7282 4 : .unwrap();
7283 4 :
7284 4 : let l0_delta = DeltaLayerTestDesc::new(
7285 4 : Lsn(0x20)..Lsn(0x30),
7286 4 : Key::from_hex("000000000000000000000000000000000000").unwrap()
7287 4 : ..Key::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(),
7288 4 : vec![(
7289 4 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
7290 4 : Lsn(0x25),
7291 4 : Value::Image(test_img("foo")),
7292 4 : )],
7293 4 : );
7294 4 :
7295 4 : let image_layer = (
7296 4 : Lsn(0x40),
7297 4 : vec![(
7298 4 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
7299 4 : test_img("bar"),
7300 4 : )],
7301 4 : );
7302 4 :
7303 4 : let delta_layers = vec![l0_delta];
7304 4 : let image_layers = vec![image_layer];
7305 4 :
7306 4 : let (tenant, ctx) = harness.load().await;
7307 4 : let timeline = tenant
7308 4 : .create_test_timeline_with_layers(
7309 4 : TimelineId::generate(),
7310 4 : Lsn(0x10),
7311 4 : 14,
7312 4 : &ctx,
7313 4 : Vec::new(), // in-memory layers
7314 4 : delta_layers,
7315 4 : image_layers,
7316 4 : Lsn(0x100),
7317 4 : )
7318 4 : .await
7319 4 : .unwrap();
7320 4 :
7321 4 : // Layer visibility is an input to heatmap generation, so refresh it first
7322 4 : timeline.update_layer_visibility().await.unwrap();
7323 4 :
7324 4 : let heatmap = timeline
7325 4 : .generate_heatmap()
7326 4 : .await
7327 4 : .expect("Infallible while timeline is not shut down");
7328 4 :
7329 4 : // Both layers should be in the heatmap
7330 4 : assert!(heatmap.all_layers().count() > 0);
7331 4 :
7332 4 : // Now simulate a migration.
7333 4 : timeline
7334 4 : .previous_heatmap
7335 4 : .store(Some(Arc::new(PreviousHeatmap::Active {
7336 4 : heatmap: heatmap.clone(),
7337 4 : read_at: std::time::Instant::now(),
7338 4 : end_lsn: None,
7339 4 : })));
7340 4 :
7341 4 : // Evict all the layers in the previous heatmap
7342 4 : let guard = timeline.layers.read().await;
7343 4 : let forever = std::time::Duration::from_secs(120);
7344 12 : for layer in guard.likely_resident_layers() {
7345 12 : layer.evict_and_wait(forever).await.unwrap();
7346 4 : }
7347 4 : drop(guard);
7348 4 :
7349 4 : // Generate a new heatmap and check that the previous heatmap
7350 4 : // has been marked obsolete.
7351 4 : let post_eviction_heatmap = timeline
7352 4 : .generate_heatmap()
7353 4 : .await
7354 4 : .expect("Infallible while timeline is not shut down");
7355 4 :
7356 4 : assert_eq!(post_eviction_heatmap.all_layers().count(), 0);
7357 4 : assert!(matches!(
7358 4 : timeline.previous_heatmap.load().as_deref(),
7359 4 : Some(PreviousHeatmap::Obsolete)
7360 4 : ));
7361 4 : }
7362 :
7363 : #[tokio::test]
7364 4 : async fn two_layer_eviction_attempts_at_the_same_time() {
7365 4 : let harness = TenantHarness::create("two_layer_eviction_attempts_at_the_same_time")
7366 4 : .await
7367 4 : .unwrap();
7368 4 :
7369 4 : let (tenant, ctx) = harness.load().await;
7370 4 : let timeline = tenant
7371 4 : .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
7372 4 : .await
7373 4 : .unwrap();
7374 4 :
7375 4 : let layer = find_some_layer(&timeline).await;
7376 4 : let layer = layer
7377 4 : .keep_resident()
7378 4 : .await
7379 4 : .expect("no download => no downloading errors")
7380 4 : .drop_eviction_guard();
7381 4 :
7382 4 : let forever = std::time::Duration::from_secs(120);
7383 4 :
7384 4 : let first = layer.evict_and_wait(forever);
7385 4 : let second = layer.evict_and_wait(forever);
7386 4 :
7387 4 : let (first, second) = tokio::join!(first, second);
7388 4 :
7389 4 : let res = layer.keep_resident().await;
7390 4 : assert!(res.is_none(), "{res:?}");
7391 4 :
7392 4 : match (first, second) {
7393 4 : (Ok(()), Ok(())) => {
7394 4 : // because there are no more timeline locks being taken on eviction path, we can
7395 4 : // witness all three outcomes here.
7396 4 : }
7397 4 : (Ok(()), Err(EvictionError::NotFound)) | (Err(EvictionError::NotFound), Ok(())) => {
7398 0 : // if one completes before the other, this is fine just as well.
7399 0 : }
7400 4 : other => unreachable!("unexpected {:?}", other),
7401 4 : }
7402 4 : }
7403 :
7404 4 : async fn find_some_layer(timeline: &Timeline) -> Layer {
7405 4 : let layers = timeline.layers.read().await;
7406 4 : let desc = layers
7407 4 : .layer_map()
7408 4 : .unwrap()
7409 4 : .iter_historic_layers()
7410 4 : .next()
7411 4 : .expect("must find one layer to evict");
7412 4 :
7413 4 : layers.get_from_desc(&desc)
7414 4 : }
7415 : }
|