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