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