Line data Source code
1 : //!
2 : //! Timeline repository implementation that keeps old data in files on disk, and
3 : //! the recent changes in memory. See tenant/*_layer.rs files.
4 : //! The functions here are responsible for locating the correct layer for the
5 : //! get/put call, walking back the timeline branching history as needed.
6 : //!
7 : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
8 : //! directory. See docs/pageserver-storage.md for how the files are managed.
9 : //! In addition to the layer files, there is a metadata file in the same
10 : //! directory that contains information about the timeline, in particular its
11 : //! parent timeline, and the last LSN that has been written to disk.
12 : //!
13 :
14 : use anyhow::{bail, Context};
15 : use arc_swap::ArcSwap;
16 : use camino::Utf8Path;
17 : use camino::Utf8PathBuf;
18 : use enumset::EnumSet;
19 : use futures::stream::FuturesUnordered;
20 : use futures::FutureExt;
21 : use futures::StreamExt;
22 : use pageserver_api::models;
23 : use pageserver_api::models::AuxFilePolicy;
24 : use pageserver_api::models::TimelineState;
25 : use pageserver_api::models::TopTenantShardItem;
26 : use pageserver_api::models::WalRedoManagerStatus;
27 : use pageserver_api::shard::ShardIdentity;
28 : use pageserver_api::shard::ShardStripeSize;
29 : use pageserver_api::shard::TenantShardId;
30 : use remote_storage::DownloadError;
31 : use remote_storage::GenericRemoteStorage;
32 : use remote_storage::TimeoutOrCancel;
33 : use std::fmt;
34 : use std::time::SystemTime;
35 : use storage_broker::BrokerClientChannel;
36 : use tokio::io::BufReader;
37 : use tokio::sync::watch;
38 : use tokio::task::JoinSet;
39 : use tokio_util::sync::CancellationToken;
40 : use tracing::*;
41 : use utils::backoff;
42 : use utils::completion;
43 : use utils::crashsafe::path_with_suffix_extension;
44 : use utils::failpoint_support;
45 : use utils::fs_ext;
46 : use utils::pausable_failpoint;
47 : use utils::sync::gate::Gate;
48 : use utils::sync::gate::GateGuard;
49 : use utils::timeout::timeout_cancellable;
50 : use utils::timeout::TimeoutCancellableError;
51 : use utils::zstd::create_zst_tarball;
52 : use utils::zstd::extract_zst_tarball;
53 :
54 : use self::config::AttachedLocationConfig;
55 : use self::config::AttachmentMode;
56 : use self::config::LocationConf;
57 : use self::config::TenantConf;
58 : use self::delete::DeleteTenantFlow;
59 : use self::metadata::TimelineMetadata;
60 : use self::mgr::GetActiveTenantError;
61 : use self::mgr::GetTenantError;
62 : use self::mgr::TenantsMap;
63 : use self::remote_timeline_client::upload::upload_index_part;
64 : use self::remote_timeline_client::RemoteTimelineClient;
65 : use self::timeline::uninit::TimelineCreateGuard;
66 : use self::timeline::uninit::TimelineExclusionError;
67 : use self::timeline::uninit::UninitializedTimeline;
68 : use self::timeline::EvictionTaskTenantState;
69 : use self::timeline::GcCutoffs;
70 : use self::timeline::TimelineResources;
71 : use self::timeline::WaitLsnError;
72 : use crate::config::PageServerConf;
73 : use crate::context::{DownloadBehavior, RequestContext};
74 : use crate::deletion_queue::DeletionQueueClient;
75 : use crate::deletion_queue::DeletionQueueError;
76 : use crate::import_datadir;
77 : use crate::is_uninit_mark;
78 : use crate::metrics::TENANT;
79 : use crate::metrics::{
80 : remove_tenant_metrics, BROKEN_TENANTS_SET, TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
81 : };
82 : use crate::repository::GcResult;
83 : use crate::task_mgr;
84 : use crate::task_mgr::TaskKind;
85 : use crate::tenant::config::LocationMode;
86 : use crate::tenant::config::TenantConfOpt;
87 : pub use crate::tenant::remote_timeline_client::index::IndexPart;
88 : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
89 : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
90 : use crate::tenant::remote_timeline_client::INITDB_PATH;
91 : use crate::tenant::storage_layer::DeltaLayer;
92 : use crate::tenant::storage_layer::ImageLayer;
93 : use crate::InitializationOrder;
94 : use std::collections::hash_map::Entry;
95 : use std::collections::BTreeSet;
96 : use std::collections::HashMap;
97 : use std::collections::HashSet;
98 : use std::fmt::Debug;
99 : use std::fmt::Display;
100 : use std::fs;
101 : use std::fs::File;
102 : use std::ops::Bound::Included;
103 : use std::sync::atomic::AtomicU64;
104 : use std::sync::atomic::Ordering;
105 : use std::sync::Arc;
106 : use std::sync::Mutex;
107 : use std::time::{Duration, Instant};
108 :
109 : use crate::span;
110 : use crate::tenant::timeline::delete::DeleteTimelineFlow;
111 : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
112 : use crate::virtual_file::VirtualFile;
113 : use crate::walredo::PostgresRedoManager;
114 : use crate::TEMP_FILE_SUFFIX;
115 : use once_cell::sync::Lazy;
116 : pub use pageserver_api::models::TenantState;
117 : use tokio::sync::Semaphore;
118 :
119 0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
120 : use utils::{
121 : crashsafe,
122 : generation::Generation,
123 : id::TimelineId,
124 : lsn::{Lsn, RecordLsn},
125 : };
126 :
127 : pub mod blob_io;
128 : pub mod block_io;
129 : pub mod vectored_blob_io;
130 :
131 : pub mod disk_btree;
132 : pub(crate) mod ephemeral_file;
133 : pub mod layer_map;
134 :
135 : pub mod metadata;
136 : pub mod remote_timeline_client;
137 : pub mod storage_layer;
138 :
139 : pub mod config;
140 : pub mod delete;
141 : pub mod mgr;
142 : pub mod secondary;
143 : pub mod tasks;
144 : pub mod upload_queue;
145 :
146 : pub(crate) mod timeline;
147 :
148 : pub mod size;
149 :
150 : pub(crate) mod throttle;
151 :
152 : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
153 : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
154 :
155 : // re-export for use in walreceiver
156 : pub use crate::tenant::timeline::WalReceiverInfo;
157 :
158 : /// The "tenants" part of `tenants/<tenant>/timelines...`
159 : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
160 :
161 : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
162 : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
163 :
164 : pub const TENANT_DELETED_MARKER_FILE_NAME: &str = "deleted";
165 :
166 : /// References to shared objects that are passed into each tenant, such
167 : /// as the shared remote storage client and process initialization state.
168 : #[derive(Clone)]
169 : pub struct TenantSharedResources {
170 : pub broker_client: storage_broker::BrokerClientChannel,
171 : pub remote_storage: GenericRemoteStorage,
172 : pub deletion_queue_client: DeletionQueueClient,
173 : }
174 :
175 : /// A [`Tenant`] is really an _attached_ tenant. The configuration
176 : /// for an attached tenant is a subset of the [`LocationConf`], represented
177 : /// in this struct.
178 : pub(super) struct AttachedTenantConf {
179 : tenant_conf: TenantConfOpt,
180 : location: AttachedLocationConfig,
181 : }
182 :
183 : impl AttachedTenantConf {
184 0 : fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
185 0 : Self {
186 0 : tenant_conf,
187 0 : location,
188 0 : }
189 0 : }
190 :
191 165 : fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
192 165 : match &location_conf.mode {
193 165 : LocationMode::Attached(attach_conf) => Ok(Self {
194 165 : tenant_conf: location_conf.tenant_conf,
195 165 : location: *attach_conf,
196 165 : }),
197 : LocationMode::Secondary(_) => {
198 0 : anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
199 : }
200 : }
201 165 : }
202 : }
203 : struct TimelinePreload {
204 : timeline_id: TimelineId,
205 : client: RemoteTimelineClient,
206 : index_part: Result<MaybeDeletedIndexPart, DownloadError>,
207 : }
208 :
209 : pub(crate) struct TenantPreload {
210 : deleting: bool,
211 : timelines: HashMap<TimelineId, TimelinePreload>,
212 : }
213 :
214 : /// When we spawn a tenant, there is a special mode for tenant creation that
215 : /// avoids trying to read anything from remote storage.
216 : pub(crate) enum SpawnMode {
217 : /// Activate as soon as possible
218 : Eager,
219 : /// Lazy activation in the background, with the option to skip the queue if the need comes up
220 : Lazy,
221 : /// Tenant has been created during the lifetime of this process
222 : Create,
223 : }
224 :
225 : ///
226 : /// Tenant consists of multiple timelines. Keep them in a hash table.
227 : ///
228 : pub struct Tenant {
229 : // Global pageserver config parameters
230 : pub conf: &'static PageServerConf,
231 :
232 : /// The value creation timestamp, used to measure activation delay, see:
233 : /// <https://github.com/neondatabase/neon/issues/4025>
234 : constructed_at: Instant,
235 :
236 : state: watch::Sender<TenantState>,
237 :
238 : // Overridden tenant-specific config parameters.
239 : // We keep TenantConfOpt sturct here to preserve the information
240 : // about parameters that are not set.
241 : // This is necessary to allow global config updates.
242 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
243 :
244 : tenant_shard_id: TenantShardId,
245 :
246 : // The detailed sharding information, beyond the number/count in tenant_shard_id
247 : shard_identity: ShardIdentity,
248 :
249 : /// The remote storage generation, used to protect S3 objects from split-brain.
250 : /// Does not change over the lifetime of the [`Tenant`] object.
251 : ///
252 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
253 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
254 : generation: Generation,
255 :
256 : timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
257 :
258 : /// During timeline creation, we first insert the TimelineId to the
259 : /// creating map, then `timelines`, then remove it from the creating map.
260 : /// **Lock order**: if acquring both, acquire`timelines` before `timelines_creating`
261 : timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
262 :
263 : // This mutex prevents creation of new timelines during GC.
264 : // Adding yet another mutex (in addition to `timelines`) is needed because holding
265 : // `timelines` mutex during all GC iteration
266 : // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
267 : // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
268 : // timeout...
269 : gc_cs: tokio::sync::Mutex<()>,
270 : walredo_mgr: Option<Arc<WalRedoManager>>,
271 :
272 : // provides access to timeline data sitting in the remote storage
273 : pub(crate) remote_storage: GenericRemoteStorage,
274 :
275 : // Access to global deletion queue for when this tenant wants to schedule a deletion
276 : deletion_queue_client: DeletionQueueClient,
277 :
278 : /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
279 : cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
280 : cached_synthetic_tenant_size: Arc<AtomicU64>,
281 :
282 : eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
283 :
284 : /// If the tenant is in Activating state, notify this to encourage it
285 : /// to proceed to Active as soon as possible, rather than waiting for lazy
286 : /// background warmup.
287 : pub(crate) activate_now_sem: tokio::sync::Semaphore,
288 :
289 : pub(crate) delete_progress: Arc<tokio::sync::Mutex<DeleteTenantFlow>>,
290 :
291 : // Cancellation token fires when we have entered shutdown(). This is a parent of
292 : // Timelines' cancellation token.
293 : pub(crate) cancel: CancellationToken,
294 :
295 : // Users of the Tenant such as the page service must take this Gate to avoid
296 : // trying to use a Tenant which is shutting down.
297 : pub(crate) gate: Gate,
298 :
299 : /// Throttle applied at the top of [`Timeline::get`].
300 : /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
301 : pub(crate) timeline_get_throttle:
302 : Arc<throttle::Throttle<&'static crate::metrics::tenant_throttling::TimelineGet>>,
303 :
304 : /// An ongoing timeline detach must be checked during attempts to GC or compact a timeline.
305 : ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
306 : }
307 :
308 : impl std::fmt::Debug for Tenant {
309 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310 0 : write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
311 0 : }
312 : }
313 :
314 : pub(crate) enum WalRedoManager {
315 : Prod(PostgresRedoManager),
316 : #[cfg(test)]
317 : Test(harness::TestRedoManager),
318 : }
319 :
320 : impl From<PostgresRedoManager> for WalRedoManager {
321 0 : fn from(mgr: PostgresRedoManager) -> Self {
322 0 : Self::Prod(mgr)
323 0 : }
324 : }
325 :
326 : #[cfg(test)]
327 : impl From<harness::TestRedoManager> for WalRedoManager {
328 157 : fn from(mgr: harness::TestRedoManager) -> Self {
329 157 : Self::Test(mgr)
330 157 : }
331 : }
332 :
333 : impl WalRedoManager {
334 0 : pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
335 0 : match self {
336 0 : Self::Prod(mgr) => mgr.maybe_quiesce(idle_timeout),
337 0 : #[cfg(test)]
338 0 : Self::Test(_) => {
339 0 : // Not applicable to test redo manager
340 0 : }
341 0 : }
342 0 : }
343 :
344 : /// # Cancel-Safety
345 : ///
346 : /// This method is cancellation-safe.
347 18 : pub async fn request_redo(
348 18 : &self,
349 18 : key: crate::repository::Key,
350 18 : lsn: Lsn,
351 18 : base_img: Option<(Lsn, bytes::Bytes)>,
352 18 : records: Vec<(Lsn, crate::walrecord::NeonWalRecord)>,
353 18 : pg_version: u32,
354 18 : ) -> anyhow::Result<bytes::Bytes> {
355 18 : match self {
356 0 : Self::Prod(mgr) => {
357 0 : mgr.request_redo(key, lsn, base_img, records, pg_version)
358 0 : .await
359 : }
360 : #[cfg(test)]
361 18 : Self::Test(mgr) => {
362 18 : mgr.request_redo(key, lsn, base_img, records, pg_version)
363 0 : .await
364 : }
365 : }
366 18 : }
367 :
368 0 : pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
369 0 : match self {
370 0 : WalRedoManager::Prod(m) => Some(m.status()),
371 0 : #[cfg(test)]
372 0 : WalRedoManager::Test(_) => None,
373 0 : }
374 0 : }
375 : }
376 :
377 0 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
378 : pub enum GetTimelineError {
379 : #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
380 : NotActive {
381 : tenant_id: TenantShardId,
382 : timeline_id: TimelineId,
383 : state: TimelineState,
384 : },
385 : #[error("Timeline {tenant_id}/{timeline_id} was not found")]
386 : NotFound {
387 : tenant_id: TenantShardId,
388 : timeline_id: TimelineId,
389 : },
390 : }
391 :
392 0 : #[derive(Debug, thiserror::Error)]
393 : pub enum LoadLocalTimelineError {
394 : #[error("FailedToLoad")]
395 : Load(#[source] anyhow::Error),
396 : #[error("FailedToResumeDeletion")]
397 : ResumeDeletion(#[source] anyhow::Error),
398 : }
399 :
400 0 : #[derive(thiserror::Error)]
401 : pub enum DeleteTimelineError {
402 : #[error("NotFound")]
403 : NotFound,
404 :
405 : #[error("HasChildren")]
406 : HasChildren(Vec<TimelineId>),
407 :
408 : #[error("Timeline deletion is already in progress")]
409 : AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
410 :
411 : #[error(transparent)]
412 : Other(#[from] anyhow::Error),
413 : }
414 :
415 : impl Debug for DeleteTimelineError {
416 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
417 0 : match self {
418 0 : Self::NotFound => write!(f, "NotFound"),
419 0 : Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
420 0 : Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
421 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
422 : }
423 0 : }
424 : }
425 :
426 : pub enum SetStoppingError {
427 : AlreadyStopping(completion::Barrier),
428 : Broken,
429 : }
430 :
431 : impl Debug for SetStoppingError {
432 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433 0 : match self {
434 0 : Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
435 0 : Self::Broken => write!(f, "Broken"),
436 : }
437 0 : }
438 : }
439 :
440 0 : #[derive(thiserror::Error, Debug)]
441 : pub enum CreateTimelineError {
442 : #[error("creation of timeline with the given ID is in progress")]
443 : AlreadyCreating,
444 : #[error("timeline already exists with different parameters")]
445 : Conflict,
446 : #[error(transparent)]
447 : AncestorLsn(anyhow::Error),
448 : #[error("ancestor timeline is not active")]
449 : AncestorNotActive,
450 : #[error("tenant shutting down")]
451 : ShuttingDown,
452 : #[error(transparent)]
453 : Other(#[from] anyhow::Error),
454 : }
455 :
456 : #[derive(thiserror::Error, Debug)]
457 : enum InitdbError {
458 : Other(anyhow::Error),
459 : Cancelled,
460 : Spawn(std::io::Result<()>),
461 : Failed(std::process::ExitStatus, Vec<u8>),
462 : }
463 :
464 : impl fmt::Display for InitdbError {
465 0 : fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
466 0 : match self {
467 0 : InitdbError::Cancelled => write!(f, "Operation was cancelled"),
468 0 : InitdbError::Spawn(e) => write!(f, "Spawn error: {:?}", e),
469 0 : InitdbError::Failed(status, stderr) => write!(
470 0 : f,
471 0 : "Command failed with status {:?}: {}",
472 0 : status,
473 0 : String::from_utf8_lossy(stderr)
474 0 : ),
475 0 : InitdbError::Other(e) => write!(f, "Error: {:?}", e),
476 : }
477 0 : }
478 : }
479 :
480 : impl From<std::io::Error> for InitdbError {
481 0 : fn from(error: std::io::Error) -> Self {
482 0 : InitdbError::Spawn(Err(error))
483 0 : }
484 : }
485 :
486 : enum CreateTimelineCause {
487 : Load,
488 : Delete,
489 : }
490 :
491 0 : #[derive(thiserror::Error, Debug)]
492 : pub(crate) enum GcError {
493 : // The tenant is shutting down
494 : #[error("tenant shutting down")]
495 : TenantCancelled,
496 :
497 : // The tenant is shutting down
498 : #[error("timeline shutting down")]
499 : TimelineCancelled,
500 :
501 : // The tenant is in a state inelegible to run GC
502 : #[error("not active")]
503 : NotActive,
504 :
505 : // A requested GC cutoff LSN was invalid, for example it tried to move backwards
506 : #[error("not active")]
507 : BadLsn { why: String },
508 :
509 : // A remote storage error while scheduling updates after compaction
510 : #[error(transparent)]
511 : Remote(anyhow::Error),
512 :
513 : // An error reading while calculating GC cutoffs
514 : #[error(transparent)]
515 : GcCutoffs(PageReconstructError),
516 :
517 : // If GC was invoked for a particular timeline, this error means it didn't exist
518 : #[error("timeline not found")]
519 : TimelineNotFound,
520 : }
521 :
522 : impl From<PageReconstructError> for GcError {
523 0 : fn from(value: PageReconstructError) -> Self {
524 0 : match value {
525 0 : PageReconstructError::Cancelled => Self::TimelineCancelled,
526 0 : other => Self::GcCutoffs(other),
527 : }
528 0 : }
529 : }
530 :
531 : impl Tenant {
532 : /// Yet another helper for timeline initialization.
533 : ///
534 : /// - Initializes the Timeline struct and inserts it into the tenant's hash map
535 : /// - Scans the local timeline directory for layer files and builds the layer map
536 : /// - Downloads remote index file and adds remote files to the layer map
537 : /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
538 : ///
539 : /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
540 : /// it is marked as Active.
541 : #[allow(clippy::too_many_arguments)]
542 6 : async fn timeline_init_and_sync(
543 6 : &self,
544 6 : timeline_id: TimelineId,
545 6 : resources: TimelineResources,
546 6 : index_part: Option<IndexPart>,
547 6 : metadata: TimelineMetadata,
548 6 : ancestor: Option<Arc<Timeline>>,
549 6 : last_aux_file_policy: Option<AuxFilePolicy>,
550 6 : _ctx: &RequestContext,
551 6 : ) -> anyhow::Result<()> {
552 6 : let tenant_id = self.tenant_shard_id;
553 :
554 6 : let timeline = self.create_timeline_struct(
555 6 : timeline_id,
556 6 : &metadata,
557 6 : ancestor.clone(),
558 6 : resources,
559 6 : CreateTimelineCause::Load,
560 6 : // This could be derived from ancestor branch + index part. Though the only caller of `timeline_init_and_sync` is `load_remote_timeline`,
561 6 : // there will potentially be other caller of this function in the future, and we don't know whether `index_part` or `ancestor` takes precedence.
562 6 : // Therefore, we pass this field explicitly for now, and remove it once we fully migrate to aux file v2.
563 6 : last_aux_file_policy,
564 6 : )?;
565 6 : let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
566 6 : anyhow::ensure!(
567 6 : disk_consistent_lsn.is_valid(),
568 0 : "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
569 : );
570 6 : assert_eq!(
571 6 : disk_consistent_lsn,
572 6 : metadata.disk_consistent_lsn(),
573 0 : "these are used interchangeably"
574 : );
575 :
576 6 : if let Some(index_part) = index_part.as_ref() {
577 6 : timeline.remote_client.init_upload_queue(index_part)?;
578 :
579 6 : timeline
580 6 : .last_aux_file_policy
581 6 : .store(index_part.last_aux_file_policy());
582 : } else {
583 : // No data on the remote storage, but we have local metadata file. We can end up
584 : // here with timeline_create being interrupted before finishing index part upload.
585 : // By doing what we do here, the index part upload is retried.
586 : // If control plane retries timeline creation in the meantime, the mgmt API handler
587 : // for timeline creation will coalesce on the upload we queue here.
588 :
589 : // FIXME: this branch should be dead code as we no longer write local metadata.
590 :
591 0 : timeline
592 0 : .remote_client
593 0 : .init_upload_queue_for_empty_remote(&metadata)?;
594 0 : timeline
595 0 : .remote_client
596 0 : .schedule_index_upload_for_full_metadata_update(&metadata)?;
597 : }
598 :
599 6 : timeline
600 6 : .load_layer_map(disk_consistent_lsn, index_part)
601 5 : .await
602 6 : .with_context(|| {
603 0 : format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
604 6 : })?;
605 :
606 : {
607 : // avoiding holding it across awaits
608 6 : let mut timelines_accessor = self.timelines.lock().unwrap();
609 6 : match timelines_accessor.entry(timeline_id) {
610 : // We should never try and load the same timeline twice during startup
611 : Entry::Occupied(_) => {
612 0 : unreachable!(
613 0 : "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
614 0 : );
615 : }
616 6 : Entry::Vacant(v) => {
617 6 : v.insert(Arc::clone(&timeline));
618 6 : timeline.maybe_spawn_flush_loop();
619 6 : }
620 6 : }
621 6 : };
622 6 :
623 6 : // Sanity check: a timeline should have some content.
624 6 : anyhow::ensure!(
625 6 : ancestor.is_some()
626 4 : || timeline
627 4 : .layers
628 4 : .read()
629 0 : .await
630 4 : .layer_map()
631 4 : .iter_historic_layers()
632 4 : .next()
633 4 : .is_some(),
634 0 : "Timeline has no ancestor and no layer files"
635 : );
636 :
637 6 : Ok(())
638 6 : }
639 :
640 : /// Attach a tenant that's available in cloud storage.
641 : ///
642 : /// This returns quickly, after just creating the in-memory object
643 : /// Tenant struct and launching a background task to download
644 : /// the remote index files. On return, the tenant is most likely still in
645 : /// Attaching state, and it will become Active once the background task
646 : /// finishes. You can use wait_until_active() to wait for the task to
647 : /// complete.
648 : ///
649 : #[allow(clippy::too_many_arguments)]
650 0 : pub(crate) fn spawn(
651 0 : conf: &'static PageServerConf,
652 0 : tenant_shard_id: TenantShardId,
653 0 : resources: TenantSharedResources,
654 0 : attached_conf: AttachedTenantConf,
655 0 : shard_identity: ShardIdentity,
656 0 : init_order: Option<InitializationOrder>,
657 0 : tenants: &'static std::sync::RwLock<TenantsMap>,
658 0 : mode: SpawnMode,
659 0 : ctx: &RequestContext,
660 0 : ) -> anyhow::Result<Arc<Tenant>> {
661 0 : let wal_redo_manager = Arc::new(WalRedoManager::from(PostgresRedoManager::new(
662 0 : conf,
663 0 : tenant_shard_id,
664 0 : )));
665 0 :
666 0 : let TenantSharedResources {
667 0 : broker_client,
668 0 : remote_storage,
669 0 : deletion_queue_client,
670 0 : } = resources;
671 0 :
672 0 : let attach_mode = attached_conf.location.attach_mode;
673 0 : let generation = attached_conf.location.generation;
674 0 :
675 0 : let tenant = Arc::new(Tenant::new(
676 0 : TenantState::Attaching,
677 0 : conf,
678 0 : attached_conf,
679 0 : shard_identity,
680 0 : Some(wal_redo_manager),
681 0 : tenant_shard_id,
682 0 : remote_storage.clone(),
683 0 : deletion_queue_client,
684 0 : ));
685 0 :
686 0 : // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
687 0 : // we shut down while attaching.
688 0 : let attach_gate_guard = tenant
689 0 : .gate
690 0 : .enter()
691 0 : .expect("We just created the Tenant: nothing else can have shut it down yet");
692 0 :
693 0 : // Do all the hard work in the background
694 0 : let tenant_clone = Arc::clone(&tenant);
695 0 : let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
696 0 : task_mgr::spawn(
697 0 : &tokio::runtime::Handle::current(),
698 0 : TaskKind::Attach,
699 0 : Some(tenant_shard_id),
700 0 : None,
701 0 : "attach tenant",
702 : false,
703 0 : async move {
704 0 :
705 0 : info!(
706 : ?attach_mode,
707 0 : "Attaching tenant"
708 : );
709 :
710 0 : let _gate_guard = attach_gate_guard;
711 0 :
712 0 : // Is this tenant being spawned as part of process startup?
713 0 : let starting_up = init_order.is_some();
714 : scopeguard::defer! {
715 : if starting_up {
716 : TENANT.startup_complete.inc();
717 : }
718 : }
719 :
720 : // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
721 : enum BrokenVerbosity {
722 : Error,
723 : Info
724 : }
725 0 : let make_broken =
726 0 : |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
727 0 : match verbosity {
728 : BrokenVerbosity::Info => {
729 0 : info!("attach cancelled, setting tenant state to Broken: {err}");
730 : },
731 : BrokenVerbosity::Error => {
732 0 : error!("attach failed, setting tenant state to Broken: {err:?}");
733 : }
734 : }
735 0 : t.state.send_modify(|state| {
736 0 : // The Stopping case is for when we have passed control on to DeleteTenantFlow:
737 0 : // if it errors, we will call make_broken when tenant is already in Stopping.
738 0 : assert!(
739 0 : matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
740 0 : "the attach task owns the tenant state until activation is complete"
741 : );
742 :
743 0 : *state = TenantState::broken_from_reason(err.to_string());
744 0 : });
745 0 : };
746 :
747 0 : let mut init_order = init_order;
748 0 : // take the completion because initial tenant loading will complete when all of
749 0 : // these tasks complete.
750 0 : let _completion = init_order
751 0 : .as_mut()
752 0 : .and_then(|x| x.initial_tenant_load.take());
753 0 : let remote_load_completion = init_order
754 0 : .as_mut()
755 0 : .and_then(|x| x.initial_tenant_load_remote.take());
756 :
757 : enum AttachType<'a> {
758 : /// We are attaching this tenant lazily in the background.
759 : Warmup {
760 : _permit: tokio::sync::SemaphorePermit<'a>,
761 : during_startup: bool
762 : },
763 : /// We are attaching this tenant as soon as we can, because for example an
764 : /// endpoint tried to access it.
765 : OnDemand,
766 : /// During normal operations after startup, we are attaching a tenant, and
767 : /// eager attach was requested.
768 : Normal,
769 : }
770 :
771 0 : let attach_type = if matches!(mode, SpawnMode::Lazy) {
772 : // Before doing any I/O, wait for at least one of:
773 : // - A client attempting to access to this tenant (on-demand loading)
774 : // - A permit becoming available in the warmup semaphore (background warmup)
775 :
776 : tokio::select!(
777 : permit = tenant_clone.activate_now_sem.acquire() => {
778 : let _ = permit.expect("activate_now_sem is never closed");
779 : tracing::info!("Activating tenant (on-demand)");
780 : AttachType::OnDemand
781 : },
782 : permit = conf.concurrent_tenant_warmup.inner().acquire() => {
783 : let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
784 : tracing::info!("Activating tenant (warmup)");
785 : AttachType::Warmup {
786 : _permit,
787 : during_startup: init_order.is_some()
788 : }
789 : }
790 : _ = tenant_clone.cancel.cancelled() => {
791 : // This is safe, but should be pretty rare: it is interesting if a tenant
792 : // stayed in Activating for such a long time that shutdown found it in
793 : // that state.
794 : tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
795 : // Make the tenant broken so that set_stopping will not hang waiting for it to leave
796 : // the Attaching state. This is an over-reaction (nothing really broke, the tenant is
797 : // just shutting down), but ensures progress.
798 : make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
799 : return Ok(());
800 : },
801 : )
802 : } else {
803 : // SpawnMode::{Create,Eager} always cause jumping ahead of the
804 : // concurrent_tenant_warmup queue
805 0 : AttachType::Normal
806 : };
807 :
808 0 : let preload = match &mode {
809 : SpawnMode::Create => {
810 0 : None
811 : },
812 : SpawnMode::Eager | SpawnMode::Lazy => {
813 0 : let _preload_timer = TENANT.preload.start_timer();
814 0 : let res = tenant_clone
815 0 : .preload(&remote_storage, task_mgr::shutdown_token())
816 0 : .await;
817 0 : match res {
818 0 : Ok(p) => Some(p),
819 0 : Err(e) => {
820 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
821 0 : return Ok(());
822 : }
823 : }
824 : }
825 :
826 : };
827 :
828 : // Remote preload is complete.
829 0 : drop(remote_load_completion);
830 :
831 0 : let pending_deletion = {
832 0 : match DeleteTenantFlow::should_resume_deletion(
833 0 : conf,
834 0 : preload.as_ref().map(|p| p.deleting).unwrap_or(false),
835 0 : &tenant_clone,
836 0 : )
837 0 : .await
838 : {
839 0 : Ok(should_resume_deletion) => should_resume_deletion,
840 0 : Err(err) => {
841 0 : make_broken(&tenant_clone, anyhow::anyhow!(err), BrokenVerbosity::Error);
842 0 : return Ok(());
843 : }
844 : }
845 : };
846 :
847 0 : info!("pending_deletion {}", pending_deletion.is_some());
848 :
849 0 : if let Some(deletion) = pending_deletion {
850 : // as we are no longer loading, signal completion by dropping
851 : // the completion while we resume deletion
852 0 : drop(_completion);
853 0 : let background_jobs_can_start =
854 0 : init_order.as_ref().map(|x| &x.background_jobs_can_start);
855 0 : if let Some(background) = background_jobs_can_start {
856 0 : info!("waiting for backgound jobs barrier");
857 0 : background.clone().wait().await;
858 0 : info!("ready for backgound jobs barrier");
859 0 : }
860 :
861 0 : let deleted = DeleteTenantFlow::resume_from_attach(
862 0 : deletion,
863 0 : &tenant_clone,
864 0 : preload,
865 0 : tenants,
866 0 : &ctx,
867 0 : )
868 0 : .await;
869 :
870 0 : if let Err(e) = deleted {
871 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
872 0 : }
873 :
874 0 : return Ok(());
875 0 : }
876 :
877 : // We will time the duration of the attach phase unless this is a creation (attach will do no work)
878 0 : let attached = {
879 0 : let _attach_timer = match mode {
880 0 : SpawnMode::Create => None,
881 0 : SpawnMode::Eager | SpawnMode::Lazy => Some(TENANT.attach.start_timer()),
882 : };
883 0 : tenant_clone.attach(preload, mode, &ctx).await
884 : };
885 :
886 0 : match attached {
887 : Ok(()) => {
888 0 : info!("attach finished, activating");
889 0 : tenant_clone.activate(broker_client, None, &ctx);
890 : }
891 0 : Err(e) => {
892 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
893 0 : }
894 : }
895 :
896 : // If we are doing an opportunistic warmup attachment at startup, initialize
897 : // logical size at the same time. This is better than starting a bunch of idle tenants
898 : // with cold caches and then coming back later to initialize their logical sizes.
899 : //
900 : // It also prevents the warmup proccess competing with the concurrency limit on
901 : // logical size calculations: if logical size calculation semaphore is saturated,
902 : // then warmup will wait for that before proceeding to the next tenant.
903 0 : if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
904 0 : let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
905 0 : tracing::info!("Waiting for initial logical sizes while warming up...");
906 0 : while futs.next().await.is_some() {}
907 0 : tracing::info!("Warm-up complete");
908 0 : }
909 :
910 0 : Ok(())
911 0 : }
912 0 : .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
913 : );
914 0 : Ok(tenant)
915 0 : }
916 :
917 314 : #[instrument(skip_all)]
918 : pub(crate) async fn preload(
919 : self: &Arc<Self>,
920 : remote_storage: &GenericRemoteStorage,
921 : cancel: CancellationToken,
922 : ) -> anyhow::Result<TenantPreload> {
923 : span::debug_assert_current_span_has_tenant_id();
924 : // Get list of remote timelines
925 : // download index files for every tenant timeline
926 : info!("listing remote timelines");
927 : let (remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
928 : remote_storage,
929 : self.tenant_shard_id,
930 : cancel.clone(),
931 : )
932 : .await?;
933 :
934 : let deleting = other_keys.contains(TENANT_DELETED_MARKER_FILE_NAME);
935 : info!(
936 : "found {} timelines, deleting={}",
937 : remote_timeline_ids.len(),
938 : deleting
939 : );
940 :
941 : for k in other_keys {
942 : if k != TENANT_DELETED_MARKER_FILE_NAME {
943 : warn!("Unexpected non timeline key {k}");
944 : }
945 : }
946 :
947 : Ok(TenantPreload {
948 : deleting,
949 : timelines: Self::load_timeline_metadata(
950 : self,
951 : remote_timeline_ids,
952 : remote_storage,
953 : cancel,
954 : )
955 : .await?,
956 : })
957 : }
958 :
959 : ///
960 : /// Background task that downloads all data for a tenant and brings it to Active state.
961 : ///
962 : /// No background tasks are started as part of this routine.
963 : ///
964 157 : async fn attach(
965 157 : self: &Arc<Tenant>,
966 157 : preload: Option<TenantPreload>,
967 157 : mode: SpawnMode,
968 157 : ctx: &RequestContext,
969 157 : ) -> anyhow::Result<()> {
970 157 : span::debug_assert_current_span_has_tenant_id();
971 157 :
972 157 : failpoint_support::sleep_millis_async!("before-attaching-tenant");
973 :
974 157 : let preload = match (preload, mode) {
975 157 : (Some(p), _) => p,
976 0 : (None, SpawnMode::Create) => TenantPreload {
977 0 : deleting: false,
978 0 : timelines: HashMap::new(),
979 0 : },
980 : (None, _) => {
981 0 : anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
982 : }
983 : };
984 :
985 157 : let mut timelines_to_resume_deletions = vec![];
986 157 :
987 157 : let mut remote_index_and_client = HashMap::new();
988 157 : let mut timeline_ancestors = HashMap::new();
989 157 : let mut existent_timelines = HashSet::new();
990 163 : for (timeline_id, preload) in preload.timelines {
991 6 : let index_part = match preload.index_part {
992 6 : Ok(i) => {
993 6 : debug!("remote index part exists for timeline {timeline_id}");
994 : // We found index_part on the remote, this is the standard case.
995 6 : existent_timelines.insert(timeline_id);
996 6 : i
997 : }
998 : Err(DownloadError::NotFound) => {
999 : // There is no index_part on the remote. We only get here
1000 : // if there is some prefix for the timeline in the remote storage.
1001 : // This can e.g. be the initdb.tar.zst archive, maybe a
1002 : // remnant from a prior incomplete creation or deletion attempt.
1003 : // Delete the local directory as the deciding criterion for a
1004 : // timeline's existence is presence of index_part.
1005 0 : info!(%timeline_id, "index_part not found on remote");
1006 0 : continue;
1007 : }
1008 0 : Err(e) => {
1009 0 : // Some (possibly ephemeral) error happened during index_part download.
1010 0 : // Pretend the timeline exists to not delete the timeline directory,
1011 0 : // as it might be a temporary issue and we don't want to re-download
1012 0 : // everything after it resolves.
1013 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
1014 :
1015 0 : existent_timelines.insert(timeline_id);
1016 0 : continue;
1017 : }
1018 : };
1019 6 : match index_part {
1020 6 : MaybeDeletedIndexPart::IndexPart(index_part) => {
1021 6 : timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
1022 6 : remote_index_and_client.insert(timeline_id, (index_part, preload.client));
1023 6 : }
1024 0 : MaybeDeletedIndexPart::Deleted(index_part) => {
1025 0 : info!(
1026 0 : "timeline {} is deleted, picking to resume deletion",
1027 : timeline_id
1028 : );
1029 0 : timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
1030 : }
1031 : }
1032 : }
1033 :
1034 : // For every timeline, download the metadata file, scan the local directory,
1035 : // and build a layer map that contains an entry for each remote and local
1036 : // layer file.
1037 157 : let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
1038 163 : for (timeline_id, remote_metadata) in sorted_timelines {
1039 6 : let (index_part, remote_client) = remote_index_and_client
1040 6 : .remove(&timeline_id)
1041 6 : .expect("just put it in above");
1042 6 :
1043 6 : // TODO again handle early failure
1044 6 : self.load_remote_timeline(
1045 6 : timeline_id,
1046 6 : index_part,
1047 6 : remote_metadata,
1048 6 : TimelineResources {
1049 6 : remote_client,
1050 6 : timeline_get_throttle: self.timeline_get_throttle.clone(),
1051 6 : },
1052 6 : ctx,
1053 6 : )
1054 8 : .await
1055 6 : .with_context(|| {
1056 0 : format!(
1057 0 : "failed to load remote timeline {} for tenant {}",
1058 0 : timeline_id, self.tenant_shard_id
1059 0 : )
1060 6 : })?;
1061 : }
1062 :
1063 : // Walk through deleted timelines, resume deletion
1064 157 : for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
1065 0 : remote_timeline_client
1066 0 : .init_upload_queue_stopped_to_continue_deletion(&index_part)
1067 0 : .context("init queue stopped")
1068 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1069 :
1070 0 : DeleteTimelineFlow::resume_deletion(
1071 0 : Arc::clone(self),
1072 0 : timeline_id,
1073 0 : &index_part.metadata,
1074 0 : remote_timeline_client,
1075 0 : )
1076 0 : .instrument(tracing::info_span!("timeline_delete", %timeline_id))
1077 0 : .await
1078 0 : .context("resume_deletion")
1079 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1080 : }
1081 :
1082 : // The local filesystem contents are a cache of what's in the remote IndexPart;
1083 : // IndexPart is the source of truth.
1084 157 : self.clean_up_timelines(&existent_timelines)?;
1085 :
1086 157 : fail::fail_point!("attach-before-activate", |_| {
1087 0 : anyhow::bail!("attach-before-activate");
1088 157 : });
1089 157 : failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
1090 :
1091 157 : info!("Done");
1092 :
1093 157 : Ok(())
1094 157 : }
1095 :
1096 : /// Check for any local timeline directories that are temporary, or do not correspond to a
1097 : /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
1098 : /// if a timeline was deleted while the tenant was attached to a different pageserver.
1099 157 : fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
1100 157 : let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
1101 :
1102 157 : let entries = match timelines_dir.read_dir_utf8() {
1103 157 : Ok(d) => d,
1104 0 : Err(e) => {
1105 0 : if e.kind() == std::io::ErrorKind::NotFound {
1106 0 : return Ok(());
1107 : } else {
1108 0 : return Err(e).context("list timelines directory for tenant");
1109 : }
1110 : }
1111 : };
1112 :
1113 165 : for entry in entries {
1114 8 : let entry = entry.context("read timeline dir entry")?;
1115 8 : let entry_path = entry.path();
1116 :
1117 8 : let purge = if crate::is_temporary(entry_path)
1118 : // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
1119 8 : || is_uninit_mark(entry_path)
1120 8 : || crate::is_delete_mark(entry_path)
1121 : {
1122 0 : true
1123 : } else {
1124 8 : match TimelineId::try_from(entry_path.file_name()) {
1125 8 : Ok(i) => {
1126 8 : // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
1127 8 : !existent_timelines.contains(&i)
1128 : }
1129 0 : Err(e) => {
1130 0 : tracing::warn!(
1131 0 : "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
1132 : );
1133 : // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
1134 0 : false
1135 : }
1136 : }
1137 : };
1138 :
1139 8 : if purge {
1140 2 : tracing::info!("Purging stale timeline dentry {entry_path}");
1141 2 : if let Err(e) = match entry.file_type() {
1142 2 : Ok(t) => if t.is_dir() {
1143 2 : std::fs::remove_dir_all(entry_path)
1144 : } else {
1145 0 : std::fs::remove_file(entry_path)
1146 : }
1147 2 : .or_else(fs_ext::ignore_not_found),
1148 0 : Err(e) => Err(e),
1149 : } {
1150 0 : tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
1151 2 : }
1152 6 : }
1153 : }
1154 :
1155 157 : Ok(())
1156 157 : }
1157 :
1158 : /// Get sum of all remote timelines sizes
1159 : ///
1160 : /// This function relies on the index_part instead of listing the remote storage
1161 0 : pub fn remote_size(&self) -> u64 {
1162 0 : let mut size = 0;
1163 :
1164 0 : for timeline in self.list_timelines() {
1165 0 : size += timeline.remote_client.get_remote_physical_size();
1166 0 : }
1167 :
1168 0 : size
1169 0 : }
1170 :
1171 12 : #[instrument(skip_all, fields(timeline_id=%timeline_id))]
1172 : async fn load_remote_timeline(
1173 : &self,
1174 : timeline_id: TimelineId,
1175 : index_part: IndexPart,
1176 : remote_metadata: TimelineMetadata,
1177 : resources: TimelineResources,
1178 : ctx: &RequestContext,
1179 : ) -> anyhow::Result<()> {
1180 : span::debug_assert_current_span_has_tenant_id();
1181 :
1182 : info!("downloading index file for timeline {}", timeline_id);
1183 : tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
1184 : .await
1185 : .context("Failed to create new timeline directory")?;
1186 :
1187 : let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
1188 : let timelines = self.timelines.lock().unwrap();
1189 : Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
1190 0 : || {
1191 0 : anyhow::anyhow!(
1192 0 : "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
1193 0 : )
1194 0 : },
1195 : )?))
1196 : } else {
1197 : None
1198 : };
1199 :
1200 : let last_aux_file_policy = index_part.last_aux_file_policy();
1201 :
1202 : self.timeline_init_and_sync(
1203 : timeline_id,
1204 : resources,
1205 : Some(index_part),
1206 : remote_metadata,
1207 : ancestor,
1208 : last_aux_file_policy,
1209 : ctx,
1210 : )
1211 : .await
1212 : }
1213 :
1214 : /// Create a placeholder Tenant object for a broken tenant
1215 0 : pub fn create_broken_tenant(
1216 0 : conf: &'static PageServerConf,
1217 0 : tenant_shard_id: TenantShardId,
1218 0 : remote_storage: GenericRemoteStorage,
1219 0 : reason: String,
1220 0 : ) -> Arc<Tenant> {
1221 0 : Arc::new(Tenant::new(
1222 0 : TenantState::Broken {
1223 0 : reason,
1224 0 : backtrace: String::new(),
1225 0 : },
1226 0 : conf,
1227 0 : AttachedTenantConf::try_from(LocationConf::default()).unwrap(),
1228 0 : // Shard identity isn't meaningful for a broken tenant: it's just a placeholder
1229 0 : // to occupy the slot for this TenantShardId.
1230 0 : ShardIdentity::broken(tenant_shard_id.shard_number, tenant_shard_id.shard_count),
1231 0 : None,
1232 0 : tenant_shard_id,
1233 0 : remote_storage,
1234 0 : DeletionQueueClient::broken(),
1235 0 : ))
1236 0 : }
1237 :
1238 157 : async fn load_timeline_metadata(
1239 157 : self: &Arc<Tenant>,
1240 157 : timeline_ids: HashSet<TimelineId>,
1241 157 : remote_storage: &GenericRemoteStorage,
1242 157 : cancel: CancellationToken,
1243 157 : ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
1244 157 : let mut part_downloads = JoinSet::new();
1245 163 : for timeline_id in timeline_ids {
1246 6 : let client = RemoteTimelineClient::new(
1247 6 : remote_storage.clone(),
1248 6 : self.deletion_queue_client.clone(),
1249 6 : self.conf,
1250 6 : self.tenant_shard_id,
1251 6 : timeline_id,
1252 6 : self.generation,
1253 6 : );
1254 6 : let cancel_clone = cancel.clone();
1255 6 : part_downloads.spawn(
1256 6 : async move {
1257 6 : debug!("starting index part download");
1258 :
1259 23 : let index_part = client.download_index_file(&cancel_clone).await;
1260 :
1261 6 : debug!("finished index part download");
1262 :
1263 6 : Result::<_, anyhow::Error>::Ok(TimelinePreload {
1264 6 : client,
1265 6 : timeline_id,
1266 6 : index_part,
1267 6 : })
1268 6 : }
1269 6 : .map(move |res| {
1270 6 : res.with_context(|| format!("download index part for timeline {timeline_id}"))
1271 6 : })
1272 6 : .instrument(info_span!("download_index_part", %timeline_id)),
1273 : );
1274 : }
1275 :
1276 157 : let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
1277 :
1278 163 : loop {
1279 163 : tokio::select!(
1280 : next = part_downloads.join_next() => {
1281 : match next {
1282 : Some(result) => {
1283 : let preload_result = result.context("join preload task")?;
1284 : let preload = preload_result?;
1285 : timeline_preloads.insert(preload.timeline_id, preload);
1286 : },
1287 : None => {
1288 : break;
1289 : }
1290 : }
1291 : },
1292 : _ = cancel.cancelled() => {
1293 : anyhow::bail!("Cancelled while waiting for remote index download")
1294 : }
1295 163 : )
1296 163 : }
1297 :
1298 157 : Ok(timeline_preloads)
1299 157 : }
1300 :
1301 4 : pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
1302 4 : self.tenant_shard_id
1303 4 : }
1304 :
1305 : /// Get Timeline handle for given Neon timeline ID.
1306 : /// This function is idempotent. It doesn't change internal state in any way.
1307 222 : pub fn get_timeline(
1308 222 : &self,
1309 222 : timeline_id: TimelineId,
1310 222 : active_only: bool,
1311 222 : ) -> Result<Arc<Timeline>, GetTimelineError> {
1312 222 : let timelines_accessor = self.timelines.lock().unwrap();
1313 222 : let timeline = timelines_accessor
1314 222 : .get(&timeline_id)
1315 222 : .ok_or(GetTimelineError::NotFound {
1316 222 : tenant_id: self.tenant_shard_id,
1317 222 : timeline_id,
1318 222 : })?;
1319 :
1320 220 : if active_only && !timeline.is_active() {
1321 0 : Err(GetTimelineError::NotActive {
1322 0 : tenant_id: self.tenant_shard_id,
1323 0 : timeline_id,
1324 0 : state: timeline.current_state(),
1325 0 : })
1326 : } else {
1327 220 : Ok(Arc::clone(timeline))
1328 : }
1329 222 : }
1330 :
1331 : /// Lists timelines the tenant contains.
1332 : /// Up to tenant's implementation to omit certain timelines that ar not considered ready for use.
1333 8 : pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
1334 8 : self.timelines
1335 8 : .lock()
1336 8 : .unwrap()
1337 8 : .values()
1338 8 : .map(Arc::clone)
1339 8 : .collect()
1340 8 : }
1341 :
1342 0 : pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
1343 0 : self.timelines.lock().unwrap().keys().cloned().collect()
1344 0 : }
1345 :
1346 : /// This is used to create the initial 'main' timeline during bootstrapping,
1347 : /// or when importing a new base backup. The caller is expected to load an
1348 : /// initial image of the datadir to the new timeline after this.
1349 : ///
1350 : /// Until that happens, the on-disk state is invalid (disk_consistent_lsn=Lsn(0))
1351 : /// and the timeline will fail to load at a restart.
1352 : ///
1353 : /// For tests, use `DatadirModification::init_empty_test_timeline` + `commit` to setup the
1354 : /// minimum amount of keys required to get a writable timeline.
1355 : /// (Without it, `put` might fail due to `repartition` failing.)
1356 149 : pub(crate) async fn create_empty_timeline(
1357 149 : &self,
1358 149 : new_timeline_id: TimelineId,
1359 149 : initdb_lsn: Lsn,
1360 149 : pg_version: u32,
1361 149 : _ctx: &RequestContext,
1362 149 : ) -> anyhow::Result<UninitializedTimeline> {
1363 149 : anyhow::ensure!(
1364 149 : self.is_active(),
1365 0 : "Cannot create empty timelines on inactive tenant"
1366 : );
1367 :
1368 : // Protect against concurrent attempts to use this TimelineId
1369 149 : let create_guard = self.create_timeline_create_guard(new_timeline_id)?;
1370 :
1371 147 : let new_metadata = TimelineMetadata::new(
1372 147 : // Initialize disk_consistent LSN to 0, The caller must import some data to
1373 147 : // make it valid, before calling finish_creation()
1374 147 : Lsn(0),
1375 147 : None,
1376 147 : None,
1377 147 : Lsn(0),
1378 147 : initdb_lsn,
1379 147 : initdb_lsn,
1380 147 : pg_version,
1381 147 : );
1382 147 : self.prepare_new_timeline(
1383 147 : new_timeline_id,
1384 147 : &new_metadata,
1385 147 : create_guard,
1386 147 : initdb_lsn,
1387 147 : None,
1388 147 : None,
1389 147 : )
1390 0 : .await
1391 149 : }
1392 :
1393 : /// Helper for unit tests to create an empty timeline.
1394 : ///
1395 : /// The timeline is has state value `Active` but its background loops are not running.
1396 : // This makes the various functions which anyhow::ensure! for Active state work in tests.
1397 : // Our current tests don't need the background loops.
1398 : #[cfg(test)]
1399 139 : pub async fn create_test_timeline(
1400 139 : &self,
1401 139 : new_timeline_id: TimelineId,
1402 139 : initdb_lsn: Lsn,
1403 139 : pg_version: u32,
1404 139 : ctx: &RequestContext,
1405 139 : ) -> anyhow::Result<Arc<Timeline>> {
1406 139 : let uninit_tl = self
1407 139 : .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
1408 1 : .await?;
1409 138 : let tline = uninit_tl.raw_timeline().expect("we just created it");
1410 138 : assert_eq!(tline.get_last_record_lsn(), Lsn(0));
1411 :
1412 : // Setup minimum keys required for the timeline to be usable.
1413 138 : let mut modification = tline.begin_modification(initdb_lsn);
1414 138 : modification
1415 138 : .init_empty_test_timeline()
1416 138 : .context("init_empty_test_timeline")?;
1417 138 : modification
1418 138 : .commit(ctx)
1419 132 : .await
1420 138 : .context("commit init_empty_test_timeline modification")?;
1421 :
1422 : // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
1423 138 : tline.maybe_spawn_flush_loop();
1424 138 : tline.freeze_and_flush().await.context("freeze_and_flush")?;
1425 :
1426 : // Make sure the freeze_and_flush reaches remote storage.
1427 138 : tline.remote_client.wait_completion().await.unwrap();
1428 :
1429 138 : let tl = uninit_tl.finish_creation()?;
1430 : // The non-test code would call tl.activate() here.
1431 138 : tl.set_state(TimelineState::Active);
1432 138 : Ok(tl)
1433 139 : }
1434 :
1435 : /// Helper for unit tests to create a timeline with some pre-loaded states.
1436 : #[cfg(test)]
1437 : #[allow(clippy::too_many_arguments)]
1438 17 : pub async fn create_test_timeline_with_layers(
1439 17 : &self,
1440 17 : new_timeline_id: TimelineId,
1441 17 : initdb_lsn: Lsn,
1442 17 : pg_version: u32,
1443 17 : ctx: &RequestContext,
1444 17 : delta_layer_desc: Vec<Vec<(pageserver_api::key::Key, Lsn, crate::repository::Value)>>,
1445 17 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
1446 17 : end_lsn: Lsn,
1447 17 : ) -> anyhow::Result<Arc<Timeline>> {
1448 17 : let tline = self
1449 17 : .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
1450 42 : .await?;
1451 16 : tline.force_advance_lsn(end_lsn);
1452 44 : for deltas in delta_layer_desc {
1453 28 : tline
1454 28 : .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
1455 84 : .await?;
1456 : }
1457 48 : for (lsn, images) in image_layer_desc {
1458 32 : tline
1459 32 : .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
1460 132 : .await?;
1461 : }
1462 16 : Ok(tline)
1463 17 : }
1464 :
1465 : /// Create a new timeline.
1466 : ///
1467 : /// Returns the new timeline ID and reference to its Timeline object.
1468 : ///
1469 : /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
1470 : /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
1471 : #[allow(clippy::too_many_arguments)]
1472 0 : pub(crate) async fn create_timeline(
1473 0 : self: &Arc<Tenant>,
1474 0 : new_timeline_id: TimelineId,
1475 0 : ancestor_timeline_id: Option<TimelineId>,
1476 0 : mut ancestor_start_lsn: Option<Lsn>,
1477 0 : pg_version: u32,
1478 0 : load_existing_initdb: Option<TimelineId>,
1479 0 : broker_client: storage_broker::BrokerClientChannel,
1480 0 : ctx: &RequestContext,
1481 0 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
1482 0 : if !self.is_active() {
1483 0 : if matches!(self.current_state(), TenantState::Stopping { .. }) {
1484 0 : return Err(CreateTimelineError::ShuttingDown);
1485 : } else {
1486 0 : return Err(CreateTimelineError::Other(anyhow::anyhow!(
1487 0 : "Cannot create timelines on inactive tenant"
1488 0 : )));
1489 : }
1490 0 : }
1491 :
1492 0 : let _gate = self
1493 0 : .gate
1494 0 : .enter()
1495 0 : .map_err(|_| CreateTimelineError::ShuttingDown)?;
1496 :
1497 : // Get exclusive access to the timeline ID: this ensures that it does not already exist,
1498 : // and that no other creation attempts will be allowed in while we are working.
1499 0 : let create_guard = match self.create_timeline_create_guard(new_timeline_id) {
1500 0 : Ok(m) => m,
1501 : Err(TimelineExclusionError::AlreadyCreating) => {
1502 : // Creation is in progress, we cannot create it again, and we cannot
1503 : // check if this request matches the existing one, so caller must try
1504 : // again later.
1505 0 : return Err(CreateTimelineError::AlreadyCreating);
1506 : }
1507 0 : Err(TimelineExclusionError::Other(e)) => {
1508 0 : return Err(CreateTimelineError::Other(e));
1509 : }
1510 0 : Err(TimelineExclusionError::AlreadyExists(existing)) => {
1511 0 : debug!("timeline {new_timeline_id} already exists");
1512 :
1513 : // Idempotency: creating the same timeline twice is not an error, unless
1514 : // the second creation has different parameters.
1515 0 : if existing.get_ancestor_timeline_id() != ancestor_timeline_id
1516 0 : || existing.pg_version != pg_version
1517 0 : || (ancestor_start_lsn.is_some()
1518 0 : && ancestor_start_lsn != Some(existing.get_ancestor_lsn()))
1519 : {
1520 0 : return Err(CreateTimelineError::Conflict);
1521 0 : }
1522 0 :
1523 0 : // Wait for uploads to complete, so that when we return Ok, the timeline
1524 0 : // is known to be durable on remote storage. Just like we do at the end of
1525 0 : // this function, after we have created the timeline ourselves.
1526 0 : //
1527 0 : // We only really care that the initial version of `index_part.json` has
1528 0 : // been uploaded. That's enough to remember that the timeline
1529 0 : // exists. However, there is no function to wait specifically for that so
1530 0 : // we just wait for all in-progress uploads to finish.
1531 0 : existing
1532 0 : .remote_client
1533 0 : .wait_completion()
1534 0 : .await
1535 0 : .context("wait for timeline uploads to complete")?;
1536 :
1537 0 : return Ok(existing);
1538 : }
1539 : };
1540 :
1541 : pausable_failpoint!("timeline-creation-after-uninit");
1542 :
1543 0 : let loaded_timeline = match ancestor_timeline_id {
1544 0 : Some(ancestor_timeline_id) => {
1545 0 : let ancestor_timeline = self
1546 0 : .get_timeline(ancestor_timeline_id, false)
1547 0 : .context("Cannot branch off the timeline that's not present in pageserver")?;
1548 :
1549 : // instead of waiting around, just deny the request because ancestor is not yet
1550 : // ready for other purposes either.
1551 0 : if !ancestor_timeline.is_active() {
1552 0 : return Err(CreateTimelineError::AncestorNotActive);
1553 0 : }
1554 :
1555 0 : if let Some(lsn) = ancestor_start_lsn.as_mut() {
1556 0 : *lsn = lsn.align();
1557 0 :
1558 0 : let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
1559 0 : if ancestor_ancestor_lsn > *lsn {
1560 : // can we safely just branch from the ancestor instead?
1561 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
1562 0 : "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
1563 0 : lsn,
1564 0 : ancestor_timeline_id,
1565 0 : ancestor_ancestor_lsn,
1566 0 : )));
1567 0 : }
1568 0 :
1569 0 : // Wait for the WAL to arrive and be processed on the parent branch up
1570 0 : // to the requested branch point. The repository code itself doesn't
1571 0 : // require it, but if we start to receive WAL on the new timeline,
1572 0 : // decoding the new WAL might need to look up previous pages, relation
1573 0 : // sizes etc. and that would get confused if the previous page versions
1574 0 : // are not in the repository yet.
1575 0 : ancestor_timeline
1576 0 : .wait_lsn(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
1577 0 : .await
1578 0 : .map_err(|e| match e {
1579 0 : e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
1580 0 : CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
1581 : }
1582 0 : WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
1583 0 : })?;
1584 0 : }
1585 :
1586 0 : self.branch_timeline(
1587 0 : &ancestor_timeline,
1588 0 : new_timeline_id,
1589 0 : ancestor_start_lsn,
1590 0 : create_guard,
1591 0 : ctx,
1592 0 : )
1593 0 : .await?
1594 : }
1595 : None => {
1596 0 : self.bootstrap_timeline(
1597 0 : new_timeline_id,
1598 0 : pg_version,
1599 0 : load_existing_initdb,
1600 0 : create_guard,
1601 0 : ctx,
1602 0 : )
1603 0 : .await?
1604 : }
1605 : };
1606 :
1607 : // At this point we have dropped our guard on [`Self::timelines_creating`], and
1608 : // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet. We must
1609 : // not send a success to the caller until it is. The same applies to handling retries,
1610 : // see the handling of [`TimelineExclusionError::AlreadyExists`] above.
1611 0 : let kind = ancestor_timeline_id
1612 0 : .map(|_| "branched")
1613 0 : .unwrap_or("bootstrapped");
1614 0 : loaded_timeline
1615 0 : .remote_client
1616 0 : .wait_completion()
1617 0 : .await
1618 0 : .with_context(|| format!("wait for {} timeline initial uploads to complete", kind))?;
1619 :
1620 0 : loaded_timeline.activate(self.clone(), broker_client, None, ctx);
1621 0 :
1622 0 : Ok(loaded_timeline)
1623 0 : }
1624 :
1625 0 : pub(crate) async fn delete_timeline(
1626 0 : self: Arc<Self>,
1627 0 : timeline_id: TimelineId,
1628 0 : ) -> Result<(), DeleteTimelineError> {
1629 0 : DeleteTimelineFlow::run(&self, timeline_id, false).await?;
1630 :
1631 0 : Ok(())
1632 0 : }
1633 :
1634 : /// perform one garbage collection iteration, removing old data files from disk.
1635 : /// this function is periodically called by gc task.
1636 : /// also it can be explicitly requested through page server api 'do_gc' command.
1637 : ///
1638 : /// `target_timeline_id` specifies the timeline to GC, or None for all.
1639 : ///
1640 : /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
1641 : /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
1642 : /// the amount of history, as LSN difference from current latest LSN on each timeline.
1643 : /// `pitr` specifies the same as a time difference from the current time. The effective
1644 : /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
1645 : /// requires more history to be retained.
1646 : //
1647 754 : pub(crate) async fn gc_iteration(
1648 754 : &self,
1649 754 : target_timeline_id: Option<TimelineId>,
1650 754 : horizon: u64,
1651 754 : pitr: Duration,
1652 754 : cancel: &CancellationToken,
1653 754 : ctx: &RequestContext,
1654 754 : ) -> Result<GcResult, GcError> {
1655 754 : // Don't start doing work during shutdown
1656 754 : if let TenantState::Stopping { .. } = self.current_state() {
1657 0 : return Ok(GcResult::default());
1658 754 : }
1659 754 :
1660 754 : // there is a global allowed_error for this
1661 754 : if !self.is_active() {
1662 0 : return Err(GcError::NotActive);
1663 754 : }
1664 754 :
1665 754 : {
1666 754 : let conf = self.tenant_conf.load();
1667 754 :
1668 754 : if !conf.location.may_delete_layers_hint() {
1669 0 : info!("Skipping GC in location state {:?}", conf.location);
1670 0 : return Ok(GcResult::default());
1671 754 : }
1672 754 : }
1673 754 :
1674 754 : self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
1675 749 : .await
1676 754 : }
1677 :
1678 : /// Perform one compaction iteration.
1679 : /// This function is periodically called by compactor task.
1680 : /// Also it can be explicitly requested per timeline through page server
1681 : /// api's 'compact' command.
1682 0 : async fn compaction_iteration(
1683 0 : &self,
1684 0 : cancel: &CancellationToken,
1685 0 : ctx: &RequestContext,
1686 0 : ) -> anyhow::Result<(), timeline::CompactionError> {
1687 0 : // Don't start doing work during shutdown, or when broken, we do not need those in the logs
1688 0 : if !self.is_active() {
1689 0 : return Ok(());
1690 0 : }
1691 0 :
1692 0 : {
1693 0 : let conf = self.tenant_conf.load();
1694 0 : if !conf.location.may_delete_layers_hint() || !conf.location.may_upload_layers_hint() {
1695 0 : info!("Skipping compaction in location state {:?}", conf.location);
1696 0 : return Ok(());
1697 0 : }
1698 0 : }
1699 0 :
1700 0 : // Scan through the hashmap and collect a list of all the timelines,
1701 0 : // while holding the lock. Then drop the lock and actually perform the
1702 0 : // compactions. We don't want to block everything else while the
1703 0 : // compaction runs.
1704 0 : let timelines_to_compact = {
1705 0 : let timelines = self.timelines.lock().unwrap();
1706 0 : let timelines_to_compact = timelines
1707 0 : .iter()
1708 0 : .filter_map(|(timeline_id, timeline)| {
1709 0 : if timeline.is_active() {
1710 0 : Some((*timeline_id, timeline.clone()))
1711 : } else {
1712 0 : None
1713 : }
1714 0 : })
1715 0 : .collect::<Vec<_>>();
1716 0 : drop(timelines);
1717 0 : timelines_to_compact
1718 : };
1719 :
1720 0 : for (timeline_id, timeline) in &timelines_to_compact {
1721 0 : timeline
1722 0 : .compact(cancel, EnumSet::empty(), ctx)
1723 0 : .instrument(info_span!("compact_timeline", %timeline_id))
1724 0 : .await?;
1725 : }
1726 :
1727 0 : Ok(())
1728 0 : }
1729 :
1730 : // Call through to all timelines to freeze ephemeral layers if needed. Usually
1731 : // this happens during ingest: this background housekeeping is for freezing layers
1732 : // that are open but haven't been written to for some time.
1733 0 : async fn ingest_housekeeping(&self) {
1734 0 : // Scan through the hashmap and collect a list of all the timelines,
1735 0 : // while holding the lock. Then drop the lock and actually perform the
1736 0 : // compactions. We don't want to block everything else while the
1737 0 : // compaction runs.
1738 0 : let timelines = {
1739 0 : self.timelines
1740 0 : .lock()
1741 0 : .unwrap()
1742 0 : .values()
1743 0 : .filter_map(|timeline| {
1744 0 : if timeline.is_active() {
1745 0 : Some(timeline.clone())
1746 : } else {
1747 0 : None
1748 : }
1749 0 : })
1750 0 : .collect::<Vec<_>>()
1751 : };
1752 :
1753 0 : for timeline in &timelines {
1754 0 : timeline.maybe_freeze_ephemeral_layer().await;
1755 : }
1756 0 : }
1757 :
1758 2417 : pub fn current_state(&self) -> TenantState {
1759 2417 : self.state.borrow().clone()
1760 2417 : }
1761 :
1762 1657 : pub fn is_active(&self) -> bool {
1763 1657 : self.current_state() == TenantState::Active
1764 1657 : }
1765 :
1766 0 : pub fn generation(&self) -> Generation {
1767 0 : self.generation
1768 0 : }
1769 :
1770 0 : pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
1771 0 : self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
1772 0 : }
1773 :
1774 : /// Changes tenant status to active, unless shutdown was already requested.
1775 : ///
1776 : /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
1777 : /// to delay background jobs. Background jobs can be started right away when None is given.
1778 0 : fn activate(
1779 0 : self: &Arc<Self>,
1780 0 : broker_client: BrokerClientChannel,
1781 0 : background_jobs_can_start: Option<&completion::Barrier>,
1782 0 : ctx: &RequestContext,
1783 0 : ) {
1784 0 : span::debug_assert_current_span_has_tenant_id();
1785 0 :
1786 0 : let mut activating = false;
1787 0 : self.state.send_modify(|current_state| {
1788 0 : use pageserver_api::models::ActivatingFrom;
1789 0 : match &*current_state {
1790 : TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
1791 0 : panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
1792 : }
1793 0 : TenantState::Loading => {
1794 0 : *current_state = TenantState::Activating(ActivatingFrom::Loading);
1795 0 : }
1796 0 : TenantState::Attaching => {
1797 0 : *current_state = TenantState::Activating(ActivatingFrom::Attaching);
1798 0 : }
1799 : }
1800 0 : debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
1801 0 : activating = true;
1802 0 : // Continue outside the closure. We need to grab timelines.lock()
1803 0 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
1804 0 : });
1805 0 :
1806 0 : if activating {
1807 0 : let timelines_accessor = self.timelines.lock().unwrap();
1808 0 : let timelines_to_activate = timelines_accessor
1809 0 : .values()
1810 0 : .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
1811 0 :
1812 0 : // Spawn gc and compaction loops. The loops will shut themselves
1813 0 : // down when they notice that the tenant is inactive.
1814 0 : tasks::start_background_loops(self, background_jobs_can_start);
1815 0 :
1816 0 : let mut activated_timelines = 0;
1817 :
1818 0 : for timeline in timelines_to_activate {
1819 0 : timeline.activate(
1820 0 : self.clone(),
1821 0 : broker_client.clone(),
1822 0 : background_jobs_can_start,
1823 0 : ctx,
1824 0 : );
1825 0 : activated_timelines += 1;
1826 0 : }
1827 :
1828 0 : self.state.send_modify(move |current_state| {
1829 0 : assert!(
1830 0 : matches!(current_state, TenantState::Activating(_)),
1831 0 : "set_stopping and set_broken wait for us to leave Activating state",
1832 : );
1833 0 : *current_state = TenantState::Active;
1834 0 :
1835 0 : let elapsed = self.constructed_at.elapsed();
1836 0 : let total_timelines = timelines_accessor.len();
1837 0 :
1838 0 : // log a lot of stuff, because some tenants sometimes suffer from user-visible
1839 0 : // times to activate. see https://github.com/neondatabase/neon/issues/4025
1840 0 : info!(
1841 0 : since_creation_millis = elapsed.as_millis(),
1842 0 : tenant_id = %self.tenant_shard_id.tenant_id,
1843 0 : shard_id = %self.tenant_shard_id.shard_slug(),
1844 0 : activated_timelines,
1845 0 : total_timelines,
1846 0 : post_state = <&'static str>::from(&*current_state),
1847 0 : "activation attempt finished"
1848 : );
1849 :
1850 0 : TENANT.activation.observe(elapsed.as_secs_f64());
1851 0 : });
1852 0 : }
1853 0 : }
1854 :
1855 : /// Shutdown the tenant and join all of the spawned tasks.
1856 : ///
1857 : /// The method caters for all use-cases:
1858 : /// - pageserver shutdown (freeze_and_flush == true)
1859 : /// - detach + ignore (freeze_and_flush == false)
1860 : ///
1861 : /// This will attempt to shutdown even if tenant is broken.
1862 : ///
1863 : /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
1864 : /// If the tenant is already shutting down, we return a clone of the first shutdown call's
1865 : /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
1866 : /// the ongoing shutdown.
1867 6 : async fn shutdown(
1868 6 : &self,
1869 6 : shutdown_progress: completion::Barrier,
1870 6 : shutdown_mode: timeline::ShutdownMode,
1871 6 : ) -> Result<(), completion::Barrier> {
1872 6 : span::debug_assert_current_span_has_tenant_id();
1873 :
1874 : // Set tenant (and its timlines) to Stoppping state.
1875 : //
1876 : // Since we can only transition into Stopping state after activation is complete,
1877 : // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
1878 : //
1879 : // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
1880 : // 1. Lock out any new requests to the tenants.
1881 : // 2. Signal cancellation to WAL receivers (we wait on it below).
1882 : // 3. Signal cancellation for other tenant background loops.
1883 : // 4. ???
1884 : //
1885 : // The waiting for the cancellation is not done uniformly.
1886 : // We certainly wait for WAL receivers to shut down.
1887 : // That is necessary so that no new data comes in before the freeze_and_flush.
1888 : // But the tenant background loops are joined-on in our caller.
1889 : // It's mesed up.
1890 : // we just ignore the failure to stop
1891 :
1892 : // If we're still attaching, fire the cancellation token early to drop out: this
1893 : // will prevent us flushing, but ensures timely shutdown if some I/O during attach
1894 : // is very slow.
1895 6 : if matches!(self.current_state(), TenantState::Attaching) {
1896 0 : self.cancel.cancel();
1897 6 : }
1898 :
1899 6 : match self.set_stopping(shutdown_progress, false, false).await {
1900 6 : Ok(()) => {}
1901 0 : Err(SetStoppingError::Broken) => {
1902 0 : // assume that this is acceptable
1903 0 : }
1904 0 : Err(SetStoppingError::AlreadyStopping(other)) => {
1905 0 : // give caller the option to wait for this this shutdown
1906 0 : info!("Tenant::shutdown: AlreadyStopping");
1907 0 : return Err(other);
1908 : }
1909 : };
1910 :
1911 6 : let mut js = tokio::task::JoinSet::new();
1912 6 : {
1913 6 : let timelines = self.timelines.lock().unwrap();
1914 6 : timelines.values().for_each(|timeline| {
1915 6 : let timeline = Arc::clone(timeline);
1916 6 : let timeline_id = timeline.timeline_id;
1917 6 : let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
1918 15 : js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
1919 6 : })
1920 6 : };
1921 6 : // test_long_timeline_create_then_tenant_delete is leaning on this message
1922 6 : tracing::info!("Waiting for timelines...");
1923 12 : while let Some(res) = js.join_next().await {
1924 0 : match res {
1925 6 : Ok(()) => {}
1926 0 : Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
1927 0 : Err(je) if je.is_panic() => { /* logged already */ }
1928 0 : Err(je) => warn!("unexpected JoinError: {je:?}"),
1929 : }
1930 : }
1931 :
1932 : // We cancel the Tenant's cancellation token _after_ the timelines have all shut down. This permits
1933 : // them to continue to do work during their shutdown methods, e.g. flushing data.
1934 6 : tracing::debug!("Cancelling CancellationToken");
1935 6 : self.cancel.cancel();
1936 6 :
1937 6 : // shutdown all tenant and timeline tasks: gc, compaction, page service
1938 6 : // No new tasks will be started for this tenant because it's in `Stopping` state.
1939 6 : //
1940 6 : // this will additionally shutdown and await all timeline tasks.
1941 6 : tracing::debug!("Waiting for tasks...");
1942 6 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
1943 :
1944 : // Wait for any in-flight operations to complete
1945 6 : self.gate.close().await;
1946 :
1947 6 : remove_tenant_metrics(&self.tenant_shard_id);
1948 6 :
1949 6 : Ok(())
1950 6 : }
1951 :
1952 : /// Change tenant status to Stopping, to mark that it is being shut down.
1953 : ///
1954 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
1955 : ///
1956 : /// This function is not cancel-safe!
1957 : ///
1958 : /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
1959 : /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
1960 6 : async fn set_stopping(
1961 6 : &self,
1962 6 : progress: completion::Barrier,
1963 6 : allow_transition_from_loading: bool,
1964 6 : allow_transition_from_attaching: bool,
1965 6 : ) -> Result<(), SetStoppingError> {
1966 6 : let mut rx = self.state.subscribe();
1967 6 :
1968 6 : // cannot stop before we're done activating, so wait out until we're done activating
1969 6 : rx.wait_for(|state| match state {
1970 0 : TenantState::Attaching if allow_transition_from_attaching => true,
1971 : TenantState::Activating(_) | TenantState::Attaching => {
1972 0 : info!(
1973 0 : "waiting for {} to turn Active|Broken|Stopping",
1974 0 : <&'static str>::from(state)
1975 : );
1976 0 : false
1977 : }
1978 0 : TenantState::Loading => allow_transition_from_loading,
1979 6 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
1980 6 : })
1981 0 : .await
1982 6 : .expect("cannot drop self.state while on a &self method");
1983 6 :
1984 6 : // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
1985 6 : let mut err = None;
1986 6 : let stopping = self.state.send_if_modified(|current_state| match current_state {
1987 : TenantState::Activating(_) => {
1988 0 : unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
1989 : }
1990 : TenantState::Attaching => {
1991 0 : if !allow_transition_from_attaching {
1992 0 : unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
1993 0 : };
1994 0 : *current_state = TenantState::Stopping { progress };
1995 0 : true
1996 : }
1997 : TenantState::Loading => {
1998 0 : if !allow_transition_from_loading {
1999 0 : unreachable!("3we ensured above that we're done with activation, and, there is no re-activation")
2000 0 : };
2001 0 : *current_state = TenantState::Stopping { progress };
2002 0 : true
2003 : }
2004 : TenantState::Active => {
2005 : // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
2006 : // are created after the transition to Stopping. That's harmless, as the Timelines
2007 : // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
2008 6 : *current_state = TenantState::Stopping { progress };
2009 6 : // Continue stopping outside the closure. We need to grab timelines.lock()
2010 6 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
2011 6 : true
2012 : }
2013 0 : TenantState::Broken { reason, .. } => {
2014 0 : info!(
2015 0 : "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
2016 : );
2017 0 : err = Some(SetStoppingError::Broken);
2018 0 : false
2019 : }
2020 0 : TenantState::Stopping { progress } => {
2021 0 : info!("Tenant is already in Stopping state");
2022 0 : err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
2023 0 : false
2024 : }
2025 6 : });
2026 6 : match (stopping, err) {
2027 6 : (true, None) => {} // continue
2028 0 : (false, Some(err)) => return Err(err),
2029 0 : (true, Some(_)) => unreachable!(
2030 0 : "send_if_modified closure must error out if not transitioning to Stopping"
2031 0 : ),
2032 0 : (false, None) => unreachable!(
2033 0 : "send_if_modified closure must return true if transitioning to Stopping"
2034 0 : ),
2035 : }
2036 :
2037 6 : let timelines_accessor = self.timelines.lock().unwrap();
2038 6 : let not_broken_timelines = timelines_accessor
2039 6 : .values()
2040 6 : .filter(|timeline| !timeline.is_broken());
2041 12 : for timeline in not_broken_timelines {
2042 6 : timeline.set_state(TimelineState::Stopping);
2043 6 : }
2044 6 : Ok(())
2045 6 : }
2046 :
2047 : /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
2048 : /// `remove_tenant_from_memory`
2049 : ///
2050 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
2051 : ///
2052 : /// In tests, we also use this to set tenants to Broken state on purpose.
2053 0 : pub(crate) async fn set_broken(&self, reason: String) {
2054 0 : let mut rx = self.state.subscribe();
2055 0 :
2056 0 : // The load & attach routines own the tenant state until it has reached `Active`.
2057 0 : // So, wait until it's done.
2058 0 : rx.wait_for(|state| match state {
2059 : TenantState::Activating(_) | TenantState::Loading | TenantState::Attaching => {
2060 0 : info!(
2061 0 : "waiting for {} to turn Active|Broken|Stopping",
2062 0 : <&'static str>::from(state)
2063 : );
2064 0 : false
2065 : }
2066 0 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
2067 0 : })
2068 0 : .await
2069 0 : .expect("cannot drop self.state while on a &self method");
2070 0 :
2071 0 : // we now know we're done activating, let's see whether this task is the winner to transition into Broken
2072 0 : self.set_broken_no_wait(reason)
2073 0 : }
2074 :
2075 0 : pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
2076 0 : let reason = reason.to_string();
2077 0 : self.state.send_modify(|current_state| {
2078 0 : match *current_state {
2079 : TenantState::Activating(_) | TenantState::Loading | TenantState::Attaching => {
2080 0 : unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
2081 : }
2082 : TenantState::Active => {
2083 0 : if cfg!(feature = "testing") {
2084 0 : warn!("Changing Active tenant to Broken state, reason: {}", reason);
2085 0 : *current_state = TenantState::broken_from_reason(reason);
2086 : } else {
2087 0 : unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
2088 : }
2089 : }
2090 : TenantState::Broken { .. } => {
2091 0 : warn!("Tenant is already in Broken state");
2092 : }
2093 : // This is the only "expected" path, any other path is a bug.
2094 : TenantState::Stopping { .. } => {
2095 0 : warn!(
2096 0 : "Marking Stopping tenant as Broken state, reason: {}",
2097 : reason
2098 : );
2099 0 : *current_state = TenantState::broken_from_reason(reason);
2100 : }
2101 : }
2102 0 : });
2103 0 : }
2104 :
2105 0 : pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
2106 0 : self.state.subscribe()
2107 0 : }
2108 :
2109 : /// The activate_now semaphore is initialized with zero units. As soon as
2110 : /// we add a unit, waiters will be able to acquire a unit and proceed.
2111 0 : pub(crate) fn activate_now(&self) {
2112 0 : self.activate_now_sem.add_permits(1);
2113 0 : }
2114 :
2115 0 : pub(crate) async fn wait_to_become_active(
2116 0 : &self,
2117 0 : timeout: Duration,
2118 0 : ) -> Result<(), GetActiveTenantError> {
2119 0 : let mut receiver = self.state.subscribe();
2120 0 : loop {
2121 0 : let current_state = receiver.borrow_and_update().clone();
2122 0 : match current_state {
2123 : TenantState::Loading | TenantState::Attaching | TenantState::Activating(_) => {
2124 : // in these states, there's a chance that we can reach ::Active
2125 0 : self.activate_now();
2126 0 : match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
2127 0 : Ok(r) => {
2128 0 : r.map_err(
2129 0 : |_e: tokio::sync::watch::error::RecvError|
2130 : // Tenant existed but was dropped: report it as non-existent
2131 0 : GetActiveTenantError::NotFound(GetTenantError::NotFound(self.tenant_shard_id.tenant_id))
2132 0 : )?
2133 : }
2134 : Err(TimeoutCancellableError::Cancelled) => {
2135 0 : return Err(GetActiveTenantError::Cancelled);
2136 : }
2137 : Err(TimeoutCancellableError::Timeout) => {
2138 0 : return Err(GetActiveTenantError::WaitForActiveTimeout {
2139 0 : latest_state: Some(self.current_state()),
2140 0 : wait_time: timeout,
2141 0 : });
2142 : }
2143 : }
2144 : }
2145 : TenantState::Active { .. } => {
2146 0 : return Ok(());
2147 : }
2148 0 : TenantState::Broken { reason, .. } => {
2149 0 : // This is fatal, and reported distinctly from the general case of "will never be active" because
2150 0 : // it's logically a 500 to external API users (broken is always a bug).
2151 0 : return Err(GetActiveTenantError::Broken(reason));
2152 : }
2153 : TenantState::Stopping { .. } => {
2154 : // There's no chance the tenant can transition back into ::Active
2155 0 : return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
2156 : }
2157 : }
2158 : }
2159 0 : }
2160 :
2161 0 : pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
2162 0 : self.tenant_conf.load().location.attach_mode
2163 0 : }
2164 :
2165 : /// For API access: generate a LocationConfig equivalent to the one that would be used to
2166 : /// create a Tenant in the same state. Do not use this in hot paths: it's for relatively
2167 : /// rare external API calls, like a reconciliation at startup.
2168 0 : pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
2169 0 : let conf = self.tenant_conf.load();
2170 :
2171 0 : let location_config_mode = match conf.location.attach_mode {
2172 0 : AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
2173 0 : AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
2174 0 : AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
2175 : };
2176 :
2177 : // We have a pageserver TenantConf, we need the API-facing TenantConfig.
2178 0 : let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
2179 0 :
2180 0 : models::LocationConfig {
2181 0 : mode: location_config_mode,
2182 0 : generation: self.generation.into(),
2183 0 : secondary_conf: None,
2184 0 : shard_number: self.shard_identity.number.0,
2185 0 : shard_count: self.shard_identity.count.literal(),
2186 0 : shard_stripe_size: self.shard_identity.stripe_size.0,
2187 0 : tenant_conf: tenant_config,
2188 0 : }
2189 0 : }
2190 :
2191 0 : pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
2192 0 : &self.tenant_shard_id
2193 0 : }
2194 :
2195 0 : pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
2196 0 : self.shard_identity.stripe_size
2197 0 : }
2198 :
2199 0 : pub(crate) fn get_generation(&self) -> Generation {
2200 0 : self.generation
2201 0 : }
2202 :
2203 : /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
2204 : /// and can leave the tenant in a bad state if it fails. The caller is responsible for
2205 : /// resetting this tenant to a valid state if we fail.
2206 0 : pub(crate) async fn split_prepare(
2207 0 : &self,
2208 0 : child_shards: &Vec<TenantShardId>,
2209 0 : ) -> anyhow::Result<()> {
2210 0 : let timelines = self.timelines.lock().unwrap().clone();
2211 0 : for timeline in timelines.values() {
2212 : // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
2213 : // to ensure that they do not start a split if currently in the process of doing these.
2214 :
2215 : // Upload an index from the parent: this is partly to provide freshness for the
2216 : // child tenants that will copy it, and partly for general ease-of-debugging: there will
2217 : // always be a parent shard index in the same generation as we wrote the child shard index.
2218 0 : timeline
2219 0 : .remote_client
2220 0 : .schedule_index_upload_for_file_changes()?;
2221 0 : timeline.remote_client.wait_completion().await?;
2222 :
2223 : // Shut down the timeline's remote client: this means that the indices we write
2224 : // for child shards will not be invalidated by the parent shard deleting layers.
2225 0 : timeline.remote_client.shutdown().await;
2226 :
2227 : // Download methods can still be used after shutdown, as they don't flow through the remote client's
2228 : // queue. In principal the RemoteTimelineClient could provide this without downloading it, but this
2229 : // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
2230 : // we use here really is the remotely persistent one).
2231 0 : let result = timeline.remote_client
2232 0 : .download_index_file(&self.cancel)
2233 0 : .instrument(info_span!("download_index_file", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))
2234 0 : .await?;
2235 0 : let index_part = match result {
2236 : MaybeDeletedIndexPart::Deleted(_) => {
2237 0 : anyhow::bail!("Timeline deletion happened concurrently with split")
2238 : }
2239 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
2240 : };
2241 :
2242 0 : for child_shard in child_shards {
2243 0 : upload_index_part(
2244 0 : &self.remote_storage,
2245 0 : child_shard,
2246 0 : &timeline.timeline_id,
2247 0 : self.generation,
2248 0 : &index_part,
2249 0 : &self.cancel,
2250 0 : )
2251 0 : .await?;
2252 : }
2253 : }
2254 :
2255 0 : Ok(())
2256 0 : }
2257 :
2258 0 : pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
2259 0 : let mut result = TopTenantShardItem {
2260 0 : id: self.tenant_shard_id,
2261 0 : resident_size: 0,
2262 0 : physical_size: 0,
2263 0 : max_logical_size: 0,
2264 0 : };
2265 :
2266 0 : for timeline in self.timelines.lock().unwrap().values() {
2267 0 : result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
2268 0 :
2269 0 : result.physical_size += timeline
2270 0 : .remote_client
2271 0 : .metrics
2272 0 : .remote_physical_size_gauge
2273 0 : .get();
2274 0 : result.max_logical_size = std::cmp::max(
2275 0 : result.max_logical_size,
2276 0 : timeline.metrics.current_logical_size_gauge.get(),
2277 0 : );
2278 0 : }
2279 :
2280 0 : result
2281 0 : }
2282 : }
2283 :
2284 : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
2285 : /// perform a topological sort, so that the parent of each timeline comes
2286 : /// before the children.
2287 : /// E extracts the ancestor from T
2288 : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
2289 157 : fn tree_sort_timelines<T, E>(
2290 157 : timelines: HashMap<TimelineId, T>,
2291 157 : extractor: E,
2292 157 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
2293 157 : where
2294 157 : E: Fn(&T) -> Option<TimelineId>,
2295 157 : {
2296 157 : let mut result = Vec::with_capacity(timelines.len());
2297 157 :
2298 157 : let mut now = Vec::with_capacity(timelines.len());
2299 157 : // (ancestor, children)
2300 157 : let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
2301 157 : HashMap::with_capacity(timelines.len());
2302 :
2303 163 : for (timeline_id, value) in timelines {
2304 6 : if let Some(ancestor_id) = extractor(&value) {
2305 2 : let children = later.entry(ancestor_id).or_default();
2306 2 : children.push((timeline_id, value));
2307 4 : } else {
2308 4 : now.push((timeline_id, value));
2309 4 : }
2310 : }
2311 :
2312 163 : while let Some((timeline_id, metadata)) = now.pop() {
2313 6 : result.push((timeline_id, metadata));
2314 : // All children of this can be loaded now
2315 6 : if let Some(mut children) = later.remove(&timeline_id) {
2316 2 : now.append(&mut children);
2317 4 : }
2318 : }
2319 :
2320 : // All timelines should be visited now. Unless there were timelines with missing ancestors.
2321 157 : if !later.is_empty() {
2322 0 : for (missing_id, orphan_ids) in later {
2323 0 : for (orphan_id, _) in orphan_ids {
2324 0 : error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
2325 : }
2326 : }
2327 0 : bail!("could not load tenant because some timelines are missing ancestors");
2328 157 : }
2329 157 :
2330 157 : Ok(result)
2331 157 : }
2332 :
2333 : impl Tenant {
2334 0 : pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
2335 0 : self.tenant_conf.load().tenant_conf.clone()
2336 0 : }
2337 :
2338 0 : pub fn effective_config(&self) -> TenantConf {
2339 0 : self.tenant_specific_overrides()
2340 0 : .merge(self.conf.default_tenant_conf.clone())
2341 0 : }
2342 :
2343 0 : pub fn get_checkpoint_distance(&self) -> u64 {
2344 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2345 0 : tenant_conf
2346 0 : .checkpoint_distance
2347 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
2348 0 : }
2349 :
2350 0 : pub fn get_checkpoint_timeout(&self) -> Duration {
2351 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2352 0 : tenant_conf
2353 0 : .checkpoint_timeout
2354 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
2355 0 : }
2356 :
2357 0 : pub fn get_compaction_target_size(&self) -> u64 {
2358 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2359 0 : tenant_conf
2360 0 : .compaction_target_size
2361 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
2362 0 : }
2363 :
2364 0 : pub fn get_compaction_period(&self) -> Duration {
2365 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2366 0 : tenant_conf
2367 0 : .compaction_period
2368 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
2369 0 : }
2370 :
2371 0 : pub fn get_compaction_threshold(&self) -> usize {
2372 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2373 0 : tenant_conf
2374 0 : .compaction_threshold
2375 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
2376 0 : }
2377 :
2378 0 : pub fn get_gc_horizon(&self) -> u64 {
2379 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2380 0 : tenant_conf
2381 0 : .gc_horizon
2382 0 : .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
2383 0 : }
2384 :
2385 0 : pub fn get_gc_period(&self) -> Duration {
2386 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2387 0 : tenant_conf
2388 0 : .gc_period
2389 0 : .unwrap_or(self.conf.default_tenant_conf.gc_period)
2390 0 : }
2391 :
2392 0 : pub fn get_image_creation_threshold(&self) -> usize {
2393 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2394 0 : tenant_conf
2395 0 : .image_creation_threshold
2396 0 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
2397 0 : }
2398 :
2399 0 : pub fn get_pitr_interval(&self) -> Duration {
2400 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2401 0 : tenant_conf
2402 0 : .pitr_interval
2403 0 : .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
2404 0 : }
2405 :
2406 0 : pub fn get_trace_read_requests(&self) -> bool {
2407 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2408 0 : tenant_conf
2409 0 : .trace_read_requests
2410 0 : .unwrap_or(self.conf.default_tenant_conf.trace_read_requests)
2411 0 : }
2412 :
2413 0 : pub fn get_min_resident_size_override(&self) -> Option<u64> {
2414 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2415 0 : tenant_conf
2416 0 : .min_resident_size_override
2417 0 : .or(self.conf.default_tenant_conf.min_resident_size_override)
2418 0 : }
2419 :
2420 0 : pub fn get_heatmap_period(&self) -> Option<Duration> {
2421 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2422 0 : let heatmap_period = tenant_conf
2423 0 : .heatmap_period
2424 0 : .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
2425 0 : if heatmap_period.is_zero() {
2426 0 : None
2427 : } else {
2428 0 : Some(heatmap_period)
2429 : }
2430 0 : }
2431 :
2432 0 : pub fn get_lsn_lease_length(&self) -> Duration {
2433 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2434 0 : tenant_conf
2435 0 : .lsn_lease_length
2436 0 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
2437 0 : }
2438 :
2439 0 : pub fn set_new_tenant_config(&self, new_tenant_conf: TenantConfOpt) {
2440 0 : // Use read-copy-update in order to avoid overwriting the location config
2441 0 : // state if this races with [`Tenant::set_new_location_config`]. Note that
2442 0 : // this race is not possible if both request types come from the storage
2443 0 : // controller (as they should!) because an exclusive op lock is required
2444 0 : // on the storage controller side.
2445 0 : self.tenant_conf.rcu(|inner| {
2446 0 : Arc::new(AttachedTenantConf {
2447 0 : tenant_conf: new_tenant_conf.clone(),
2448 0 : location: inner.location,
2449 0 : })
2450 0 : });
2451 0 :
2452 0 : self.tenant_conf_updated(&new_tenant_conf);
2453 0 : // Don't hold self.timelines.lock() during the notifies.
2454 0 : // There's no risk of deadlock right now, but there could be if we consolidate
2455 0 : // mutexes in struct Timeline in the future.
2456 0 : let timelines = self.list_timelines();
2457 0 : for timeline in timelines {
2458 0 : timeline.tenant_conf_updated(&new_tenant_conf);
2459 0 : }
2460 0 : }
2461 :
2462 8 : pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
2463 8 : let new_tenant_conf = new_conf.tenant_conf.clone();
2464 8 :
2465 8 : self.tenant_conf.store(Arc::new(new_conf));
2466 8 :
2467 8 : self.tenant_conf_updated(&new_tenant_conf);
2468 8 : // Don't hold self.timelines.lock() during the notifies.
2469 8 : // There's no risk of deadlock right now, but there could be if we consolidate
2470 8 : // mutexes in struct Timeline in the future.
2471 8 : let timelines = self.list_timelines();
2472 16 : for timeline in timelines {
2473 8 : timeline.tenant_conf_updated(&new_tenant_conf);
2474 8 : }
2475 8 : }
2476 :
2477 165 : fn get_timeline_get_throttle_config(
2478 165 : psconf: &'static PageServerConf,
2479 165 : overrides: &TenantConfOpt,
2480 165 : ) -> throttle::Config {
2481 165 : overrides
2482 165 : .timeline_get_throttle
2483 165 : .clone()
2484 165 : .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
2485 165 : }
2486 :
2487 8 : pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
2488 8 : let conf = Self::get_timeline_get_throttle_config(self.conf, new_conf);
2489 8 : self.timeline_get_throttle.reconfigure(conf)
2490 8 : }
2491 :
2492 : /// Helper function to create a new Timeline struct.
2493 : ///
2494 : /// The returned Timeline is in Loading state. The caller is responsible for
2495 : /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
2496 : /// map.
2497 : ///
2498 : /// `validate_ancestor == false` is used when a timeline is created for deletion
2499 : /// and we might not have the ancestor present anymore which is fine for to be
2500 : /// deleted timelines.
2501 379 : fn create_timeline_struct(
2502 379 : &self,
2503 379 : new_timeline_id: TimelineId,
2504 379 : new_metadata: &TimelineMetadata,
2505 379 : ancestor: Option<Arc<Timeline>>,
2506 379 : resources: TimelineResources,
2507 379 : cause: CreateTimelineCause,
2508 379 : last_aux_file_policy: Option<AuxFilePolicy>,
2509 379 : ) -> anyhow::Result<Arc<Timeline>> {
2510 379 : let state = match cause {
2511 : CreateTimelineCause::Load => {
2512 379 : let ancestor_id = new_metadata.ancestor_timeline();
2513 379 : anyhow::ensure!(
2514 379 : ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
2515 0 : "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
2516 : );
2517 379 : TimelineState::Loading
2518 : }
2519 0 : CreateTimelineCause::Delete => TimelineState::Stopping,
2520 : };
2521 :
2522 379 : let pg_version = new_metadata.pg_version();
2523 379 :
2524 379 : let timeline = Timeline::new(
2525 379 : self.conf,
2526 379 : Arc::clone(&self.tenant_conf),
2527 379 : new_metadata,
2528 379 : ancestor,
2529 379 : new_timeline_id,
2530 379 : self.tenant_shard_id,
2531 379 : self.generation,
2532 379 : self.shard_identity,
2533 379 : self.walredo_mgr.clone(),
2534 379 : resources,
2535 379 : pg_version,
2536 379 : state,
2537 379 : last_aux_file_policy,
2538 379 : self.cancel.child_token(),
2539 379 : );
2540 379 :
2541 379 : Ok(timeline)
2542 379 : }
2543 :
2544 : // Allow too_many_arguments because a constructor's argument list naturally grows with the
2545 : // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
2546 : #[allow(clippy::too_many_arguments)]
2547 157 : fn new(
2548 157 : state: TenantState,
2549 157 : conf: &'static PageServerConf,
2550 157 : attached_conf: AttachedTenantConf,
2551 157 : shard_identity: ShardIdentity,
2552 157 : walredo_mgr: Option<Arc<WalRedoManager>>,
2553 157 : tenant_shard_id: TenantShardId,
2554 157 : remote_storage: GenericRemoteStorage,
2555 157 : deletion_queue_client: DeletionQueueClient,
2556 157 : ) -> Tenant {
2557 157 : let (state, mut rx) = watch::channel(state);
2558 157 :
2559 157 : tokio::spawn(async move {
2560 157 : // reflect tenant state in metrics:
2561 157 : // - global per tenant state: TENANT_STATE_METRIC
2562 157 : // - "set" of broken tenants: BROKEN_TENANTS_SET
2563 157 : //
2564 157 : // set of broken tenants should not have zero counts so that it remains accessible for
2565 157 : // alerting.
2566 157 :
2567 157 : let tid = tenant_shard_id.to_string();
2568 157 : let shard_id = tenant_shard_id.shard_slug().to_string();
2569 157 : let set_key = &[tid.as_str(), shard_id.as_str()][..];
2570 157 :
2571 311 : fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
2572 311 : ([state.into()], matches!(state, TenantState::Broken { .. }))
2573 311 : }
2574 157 :
2575 157 : let mut tuple = inspect_state(&rx.borrow_and_update());
2576 157 :
2577 157 : let is_broken = tuple.1;
2578 157 : let mut counted_broken = if is_broken {
2579 : // add the id to the set right away, there should not be any updates on the channel
2580 : // after before tenant is removed, if ever
2581 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
2582 0 : true
2583 : } else {
2584 157 : false
2585 : };
2586 :
2587 311 : loop {
2588 311 : let labels = &tuple.0;
2589 311 : let current = TENANT_STATE_METRIC.with_label_values(labels);
2590 311 : current.inc();
2591 311 :
2592 311 : if rx.changed().await.is_err() {
2593 : // tenant has been dropped
2594 16 : current.dec();
2595 16 : drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
2596 16 : break;
2597 154 : }
2598 154 :
2599 154 : current.dec();
2600 154 : tuple = inspect_state(&rx.borrow_and_update());
2601 154 :
2602 154 : let is_broken = tuple.1;
2603 154 : if is_broken && !counted_broken {
2604 0 : counted_broken = true;
2605 0 : // insert the tenant_id (back) into the set while avoiding needless counter
2606 0 : // access
2607 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
2608 154 : }
2609 : }
2610 157 : });
2611 157 :
2612 157 : Tenant {
2613 157 : tenant_shard_id,
2614 157 : shard_identity,
2615 157 : generation: attached_conf.location.generation,
2616 157 : conf,
2617 157 : // using now here is good enough approximation to catch tenants with really long
2618 157 : // activation times.
2619 157 : constructed_at: Instant::now(),
2620 157 : timelines: Mutex::new(HashMap::new()),
2621 157 : timelines_creating: Mutex::new(HashSet::new()),
2622 157 : gc_cs: tokio::sync::Mutex::new(()),
2623 157 : walredo_mgr,
2624 157 : remote_storage,
2625 157 : deletion_queue_client,
2626 157 : state,
2627 157 : cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
2628 157 : cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
2629 157 : eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
2630 157 : activate_now_sem: tokio::sync::Semaphore::new(0),
2631 157 : delete_progress: Arc::new(tokio::sync::Mutex::new(DeleteTenantFlow::default())),
2632 157 : cancel: CancellationToken::default(),
2633 157 : gate: Gate::default(),
2634 157 : timeline_get_throttle: Arc::new(throttle::Throttle::new(
2635 157 : Tenant::get_timeline_get_throttle_config(conf, &attached_conf.tenant_conf),
2636 157 : &crate::metrics::tenant_throttling::TIMELINE_GET,
2637 157 : )),
2638 157 : tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
2639 157 : ongoing_timeline_detach: std::sync::Mutex::default(),
2640 157 : }
2641 157 : }
2642 :
2643 : /// Locate and load config
2644 0 : pub(super) fn load_tenant_config(
2645 0 : conf: &'static PageServerConf,
2646 0 : tenant_shard_id: &TenantShardId,
2647 0 : ) -> anyhow::Result<LocationConf> {
2648 0 : let legacy_config_path = conf.tenant_config_path(tenant_shard_id);
2649 0 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
2650 0 :
2651 0 : if config_path.exists() {
2652 : // New-style config takes precedence
2653 0 : let deserialized = Self::read_config(&config_path)?;
2654 0 : Ok(toml_edit::de::from_document::<LocationConf>(deserialized)?)
2655 0 : } else if legacy_config_path.exists() {
2656 : // Upgrade path: found an old-style configuration only
2657 0 : let deserialized = Self::read_config(&legacy_config_path)?;
2658 :
2659 0 : let mut tenant_conf = TenantConfOpt::default();
2660 0 : for (key, item) in deserialized.iter() {
2661 0 : match key {
2662 0 : "tenant_config" => {
2663 0 : tenant_conf = TenantConfOpt::try_from(item.to_owned()).context(format!("Failed to parse config from file '{legacy_config_path}' as pageserver config"))?;
2664 : }
2665 0 : _ => bail!(
2666 0 : "config file {legacy_config_path} has unrecognized pageserver option '{key}'"
2667 0 : ),
2668 : }
2669 : }
2670 :
2671 : // Legacy configs are implicitly in attached state, and do not support sharding
2672 0 : Ok(LocationConf::attached_single(
2673 0 : tenant_conf,
2674 0 : Generation::none(),
2675 0 : &models::ShardParameters::default(),
2676 0 : ))
2677 : } else {
2678 : // FIXME If the config file is not found, assume that we're attaching
2679 : // a detached tenant and config is passed via attach command.
2680 : // https://github.com/neondatabase/neon/issues/1555
2681 : // OR: we're loading after incomplete deletion that managed to remove config.
2682 0 : info!(
2683 0 : "tenant config not found in {} or {}",
2684 : config_path, legacy_config_path
2685 : );
2686 0 : Ok(LocationConf::default())
2687 : }
2688 0 : }
2689 :
2690 0 : fn read_config(path: &Utf8Path) -> anyhow::Result<toml_edit::Document> {
2691 0 : info!("loading tenant configuration from {path}");
2692 :
2693 : // load and parse file
2694 0 : let config = fs::read_to_string(path)
2695 0 : .with_context(|| format!("Failed to load config from path '{path}'"))?;
2696 :
2697 0 : config
2698 0 : .parse::<toml_edit::Document>()
2699 0 : .with_context(|| format!("Failed to parse config from file '{path}' as toml file"))
2700 0 : }
2701 :
2702 0 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
2703 : pub(super) async fn persist_tenant_config(
2704 : conf: &'static PageServerConf,
2705 : tenant_shard_id: &TenantShardId,
2706 : location_conf: &LocationConf,
2707 : ) -> anyhow::Result<()> {
2708 : let legacy_config_path = conf.tenant_config_path(tenant_shard_id);
2709 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
2710 :
2711 : Self::persist_tenant_config_at(
2712 : tenant_shard_id,
2713 : &config_path,
2714 : &legacy_config_path,
2715 : location_conf,
2716 : )
2717 : .await
2718 : }
2719 :
2720 0 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
2721 : pub(super) async fn persist_tenant_config_at(
2722 : tenant_shard_id: &TenantShardId,
2723 : config_path: &Utf8Path,
2724 : legacy_config_path: &Utf8Path,
2725 : location_conf: &LocationConf,
2726 : ) -> anyhow::Result<()> {
2727 : if let LocationMode::Attached(attach_conf) = &location_conf.mode {
2728 : // The modern-style LocationConf config file requires a generation to be set. In case someone
2729 : // is running a pageserver without the infrastructure to set generations, write out the legacy-style
2730 : // config file that only contains TenantConf.
2731 : //
2732 : // This will eventually be removed in https://github.com/neondatabase/neon/issues/5388
2733 :
2734 : if attach_conf.generation.is_none() {
2735 : tracing::info!(
2736 : "Running without generations, writing legacy-style tenant config file"
2737 : );
2738 : Self::persist_tenant_config_legacy(
2739 : tenant_shard_id,
2740 : legacy_config_path,
2741 : &location_conf.tenant_conf,
2742 : )
2743 : .await?;
2744 :
2745 : return Ok(());
2746 : }
2747 : }
2748 :
2749 : debug!("persisting tenantconf to {config_path}");
2750 :
2751 : let mut conf_content = r#"# This file contains a specific per-tenant's config.
2752 : # It is read in case of pageserver restart.
2753 : "#
2754 : .to_string();
2755 :
2756 0 : fail::fail_point!("tenant-config-before-write", |_| {
2757 0 : anyhow::bail!("tenant-config-before-write");
2758 0 : });
2759 :
2760 : // Convert the config to a toml file.
2761 : conf_content += &toml_edit::ser::to_string_pretty(&location_conf)?;
2762 :
2763 : let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
2764 :
2765 : let tenant_shard_id = *tenant_shard_id;
2766 : let config_path = config_path.to_owned();
2767 : let conf_content = conf_content.into_bytes();
2768 : VirtualFile::crashsafe_overwrite(config_path.clone(), temp_path, conf_content)
2769 : .await
2770 0 : .with_context(|| format!("write tenant {tenant_shard_id} config to {config_path}"))?;
2771 :
2772 : Ok(())
2773 : }
2774 :
2775 0 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
2776 : async fn persist_tenant_config_legacy(
2777 : tenant_shard_id: &TenantShardId,
2778 : target_config_path: &Utf8Path,
2779 : tenant_conf: &TenantConfOpt,
2780 : ) -> anyhow::Result<()> {
2781 : debug!("persisting tenantconf to {target_config_path}");
2782 :
2783 : let mut conf_content = r#"# This file contains a specific per-tenant's config.
2784 : # It is read in case of pageserver restart.
2785 :
2786 : [tenant_config]
2787 : "#
2788 : .to_string();
2789 :
2790 : // Convert the config to a toml file.
2791 : conf_content += &toml_edit::ser::to_string(&tenant_conf)?;
2792 :
2793 : let temp_path = path_with_suffix_extension(target_config_path, TEMP_FILE_SUFFIX);
2794 :
2795 : let tenant_shard_id = *tenant_shard_id;
2796 : let target_config_path = target_config_path.to_owned();
2797 : let conf_content = conf_content.into_bytes();
2798 : VirtualFile::crashsafe_overwrite(target_config_path.clone(), temp_path, conf_content)
2799 : .await
2800 0 : .with_context(|| {
2801 0 : format!("write tenant {tenant_shard_id} config to {target_config_path}")
2802 0 : })?;
2803 : Ok(())
2804 : }
2805 :
2806 : //
2807 : // How garbage collection works:
2808 : //
2809 : // +--bar------------->
2810 : // /
2811 : // +----+-----foo---------------->
2812 : // /
2813 : // ----main--+-------------------------->
2814 : // \
2815 : // +-----baz-------->
2816 : //
2817 : //
2818 : // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
2819 : // `gc_infos` are being refreshed
2820 : // 2. Scan collected timelines, and on each timeline, make note of the
2821 : // all the points where other timelines have been branched off.
2822 : // We will refrain from removing page versions at those LSNs.
2823 : // 3. For each timeline, scan all layer files on the timeline.
2824 : // Remove all files for which a newer file exists and which
2825 : // don't cover any branch point LSNs.
2826 : //
2827 : // TODO:
2828 : // - if a relation has a non-incremental persistent layer on a child branch, then we
2829 : // don't need to keep that in the parent anymore. But currently
2830 : // we do.
2831 754 : async fn gc_iteration_internal(
2832 754 : &self,
2833 754 : target_timeline_id: Option<TimelineId>,
2834 754 : horizon: u64,
2835 754 : pitr: Duration,
2836 754 : cancel: &CancellationToken,
2837 754 : ctx: &RequestContext,
2838 754 : ) -> Result<GcResult, GcError> {
2839 754 : let mut totals: GcResult = Default::default();
2840 754 : let now = Instant::now();
2841 :
2842 754 : let gc_timelines = self
2843 754 : .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
2844 749 : .await?;
2845 :
2846 754 : failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
2847 :
2848 : // If there is nothing to GC, we don't want any messages in the INFO log.
2849 754 : if !gc_timelines.is_empty() {
2850 754 : info!("{} timelines need GC", gc_timelines.len());
2851 : } else {
2852 0 : debug!("{} timelines need GC", gc_timelines.len());
2853 : }
2854 :
2855 : // Perform GC for each timeline.
2856 : //
2857 : // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
2858 : // branch creation task, which requires the GC lock. A GC iteration can run concurrently
2859 : // with branch creation.
2860 : //
2861 : // See comments in [`Tenant::branch_timeline`] for more information about why branch
2862 : // creation task can run concurrently with timeline's GC iteration.
2863 1508 : for timeline in gc_timelines {
2864 754 : if cancel.is_cancelled() {
2865 : // We were requested to shut down. Stop and return with the progress we
2866 : // made.
2867 0 : break;
2868 754 : }
2869 754 : let result = match timeline.gc().await {
2870 : Err(GcError::TimelineCancelled) => {
2871 0 : if target_timeline_id.is_some() {
2872 : // If we were targetting this specific timeline, surface cancellation to caller
2873 0 : return Err(GcError::TimelineCancelled);
2874 : } else {
2875 : // A timeline may be shutting down independently of the tenant's lifecycle: we should
2876 : // skip past this and proceed to try GC on other timelines.
2877 0 : continue;
2878 : }
2879 : }
2880 754 : r => r?,
2881 : };
2882 754 : totals += result;
2883 : }
2884 :
2885 754 : totals.elapsed = now.elapsed();
2886 754 : Ok(totals)
2887 754 : }
2888 :
2889 : /// Refreshes the Timeline::gc_info for all timelines, returning the
2890 : /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
2891 : /// [`Tenant::get_gc_horizon`].
2892 : ///
2893 : /// This is usually executed as part of periodic gc, but can now be triggered more often.
2894 0 : pub(crate) async fn refresh_gc_info(
2895 0 : &self,
2896 0 : cancel: &CancellationToken,
2897 0 : ctx: &RequestContext,
2898 0 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
2899 0 : // since this method can now be called at different rates than the configured gc loop, it
2900 0 : // might be that these configuration values get applied faster than what it was previously,
2901 0 : // since these were only read from the gc task.
2902 0 : let horizon = self.get_gc_horizon();
2903 0 : let pitr = self.get_pitr_interval();
2904 0 :
2905 0 : // refresh all timelines
2906 0 : let target_timeline_id = None;
2907 0 :
2908 0 : self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
2909 0 : .await
2910 0 : }
2911 :
2912 754 : async fn refresh_gc_info_internal(
2913 754 : &self,
2914 754 : target_timeline_id: Option<TimelineId>,
2915 754 : horizon: u64,
2916 754 : pitr: Duration,
2917 754 : cancel: &CancellationToken,
2918 754 : ctx: &RequestContext,
2919 754 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
2920 754 : // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
2921 754 : // currently visible timelines.
2922 754 : let timelines = self
2923 754 : .timelines
2924 754 : .lock()
2925 754 : .unwrap()
2926 754 : .values()
2927 3310 : .filter(|tl| match target_timeline_id.as_ref() {
2928 3310 : Some(target) => &tl.timeline_id == target,
2929 0 : None => true,
2930 3310 : })
2931 754 : .cloned()
2932 754 : .collect::<Vec<_>>();
2933 754 :
2934 754 : let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
2935 754 : HashMap::with_capacity(timelines.len());
2936 :
2937 754 : for timeline in timelines.iter() {
2938 754 : let cutoff = timeline
2939 754 : .get_last_record_lsn()
2940 754 : .checked_sub(horizon)
2941 754 : .unwrap_or(Lsn(0));
2942 :
2943 754 : let cutoffs = timeline.find_gc_cutoffs(cutoff, pitr, cancel, ctx).await?;
2944 754 : let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
2945 754 : assert!(old.is_none());
2946 : }
2947 :
2948 754 : if !self.is_active() || self.cancel.is_cancelled() {
2949 0 : return Err(GcError::TenantCancelled);
2950 754 : }
2951 :
2952 : // grab mutex to prevent new timelines from being created here; avoid doing long operations
2953 : // because that will stall branch creation.
2954 754 : let gc_cs = self.gc_cs.lock().await;
2955 :
2956 : // Scan all timelines. For each timeline, remember the timeline ID and
2957 : // the branch point where it was created.
2958 754 : let (all_branchpoints, timelines): (BTreeSet<(TimelineId, Lsn)>, _) = {
2959 754 : let timelines = self.timelines.lock().unwrap();
2960 754 : let mut all_branchpoints = BTreeSet::new();
2961 754 : let timelines = {
2962 754 : if let Some(target_timeline_id) = target_timeline_id.as_ref() {
2963 754 : if timelines.get(target_timeline_id).is_none() {
2964 0 : return Err(GcError::TimelineNotFound);
2965 754 : }
2966 0 : };
2967 :
2968 754 : timelines
2969 754 : .iter()
2970 3310 : .map(|(_timeline_id, timeline_entry)| {
2971 2556 : if let Some(ancestor_timeline_id) =
2972 3310 : &timeline_entry.get_ancestor_timeline_id()
2973 : {
2974 : // If target_timeline is specified, we only need to know branchpoints of its children
2975 2556 : if let Some(timeline_id) = target_timeline_id {
2976 2556 : if ancestor_timeline_id == &timeline_id {
2977 6 : all_branchpoints.insert((
2978 6 : *ancestor_timeline_id,
2979 6 : timeline_entry.get_ancestor_lsn(),
2980 6 : ));
2981 2550 : }
2982 : }
2983 : // Collect branchpoints for all timelines
2984 0 : else {
2985 0 : all_branchpoints.insert((
2986 0 : *ancestor_timeline_id,
2987 0 : timeline_entry.get_ancestor_lsn(),
2988 0 : ));
2989 0 : }
2990 754 : }
2991 :
2992 3310 : timeline_entry.clone()
2993 3310 : })
2994 754 : .collect::<Vec<_>>()
2995 754 : };
2996 754 : (all_branchpoints, timelines)
2997 754 : };
2998 754 :
2999 754 : // Ok, we now know all the branch points.
3000 754 : // Update the GC information for each timeline.
3001 754 : let mut gc_timelines = Vec::with_capacity(timelines.len());
3002 4064 : for timeline in timelines {
3003 : // If target_timeline is specified, ignore all other timelines
3004 3310 : if let Some(target_timeline_id) = target_timeline_id {
3005 3310 : if timeline.timeline_id != target_timeline_id {
3006 2556 : continue;
3007 754 : }
3008 0 : }
3009 :
3010 754 : let branchpoints: Vec<Lsn> = all_branchpoints
3011 754 : .range((
3012 754 : Included((timeline.timeline_id, Lsn(0))),
3013 754 : Included((timeline.timeline_id, Lsn(u64::MAX))),
3014 754 : ))
3015 754 : .map(|&x| x.1)
3016 754 : .collect();
3017 754 :
3018 754 : {
3019 754 : let mut target = timeline.gc_info.write().unwrap();
3020 754 :
3021 754 : let now = SystemTime::now();
3022 754 : target.leases.retain(|_, lease| !lease.is_expired(&now));
3023 754 :
3024 754 : match gc_cutoffs.remove(&timeline.timeline_id) {
3025 754 : Some(cutoffs) => {
3026 754 : target.retain_lsns = branchpoints;
3027 754 : target.cutoffs = cutoffs;
3028 754 : }
3029 0 : None => {
3030 0 : // reasons for this being unavailable:
3031 0 : // - this timeline was created while we were finding cutoffs
3032 0 : // - lsn for timestamp search fails for this timeline repeatedly
3033 0 : //
3034 0 : // in both cases, refreshing the branchpoints is correct.
3035 0 : target.retain_lsns = branchpoints;
3036 0 : }
3037 : };
3038 : }
3039 :
3040 754 : gc_timelines.push(timeline);
3041 : }
3042 754 : drop(gc_cs);
3043 754 : Ok(gc_timelines)
3044 754 : }
3045 :
3046 : /// A substitute for `branch_timeline` for use in unit tests.
3047 : /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
3048 : /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
3049 : /// timeline background tasks are launched, except the flush loop.
3050 : #[cfg(test)]
3051 228 : async fn branch_timeline_test(
3052 228 : &self,
3053 228 : src_timeline: &Arc<Timeline>,
3054 228 : dst_id: TimelineId,
3055 228 : ancestor_lsn: Option<Lsn>,
3056 228 : ctx: &RequestContext,
3057 228 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
3058 228 : let create_guard = self.create_timeline_create_guard(dst_id).unwrap();
3059 228 : let tl = self
3060 228 : .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, create_guard, ctx)
3061 4 : .await?;
3062 224 : tl.set_state(TimelineState::Active);
3063 224 : Ok(tl)
3064 228 : }
3065 :
3066 : /// Helper for unit tests to branch a timeline with some pre-loaded states.
3067 : #[cfg(test)]
3068 : #[allow(clippy::too_many_arguments)]
3069 4 : pub async fn branch_timeline_test_with_layers(
3070 4 : &self,
3071 4 : src_timeline: &Arc<Timeline>,
3072 4 : dst_id: TimelineId,
3073 4 : ancestor_lsn: Option<Lsn>,
3074 4 : ctx: &RequestContext,
3075 4 : delta_layer_desc: Vec<Vec<(pageserver_api::key::Key, Lsn, crate::repository::Value)>>,
3076 4 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
3077 4 : end_lsn: Lsn,
3078 4 : ) -> anyhow::Result<Arc<Timeline>> {
3079 4 : let tline = self
3080 4 : .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
3081 0 : .await?;
3082 4 : let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
3083 4 : ancestor_lsn
3084 : } else {
3085 0 : tline.get_last_record_lsn()
3086 : };
3087 4 : assert!(end_lsn >= ancestor_lsn);
3088 4 : tline.force_advance_lsn(end_lsn);
3089 4 : for deltas in delta_layer_desc {
3090 0 : tline
3091 0 : .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
3092 0 : .await?;
3093 : }
3094 8 : for (lsn, images) in image_layer_desc {
3095 4 : tline
3096 4 : .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
3097 14 : .await?;
3098 : }
3099 4 : Ok(tline)
3100 4 : }
3101 :
3102 : /// Branch an existing timeline.
3103 : ///
3104 : /// The caller is responsible for activating the returned timeline.
3105 0 : async fn branch_timeline(
3106 0 : &self,
3107 0 : src_timeline: &Arc<Timeline>,
3108 0 : dst_id: TimelineId,
3109 0 : start_lsn: Option<Lsn>,
3110 0 : timeline_create_guard: TimelineCreateGuard<'_>,
3111 0 : ctx: &RequestContext,
3112 0 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
3113 0 : self.branch_timeline_impl(src_timeline, dst_id, start_lsn, timeline_create_guard, ctx)
3114 0 : .await
3115 0 : }
3116 :
3117 228 : async fn branch_timeline_impl(
3118 228 : &self,
3119 228 : src_timeline: &Arc<Timeline>,
3120 228 : dst_id: TimelineId,
3121 228 : start_lsn: Option<Lsn>,
3122 228 : timeline_create_guard: TimelineCreateGuard<'_>,
3123 228 : _ctx: &RequestContext,
3124 228 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
3125 228 : let src_id = src_timeline.timeline_id;
3126 :
3127 : // We will validate our ancestor LSN in this function. Acquire the GC lock so that
3128 : // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
3129 : // valid while we are creating the branch.
3130 228 : let _gc_cs = self.gc_cs.lock().await;
3131 :
3132 : // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
3133 228 : let start_lsn = start_lsn.unwrap_or_else(|| {
3134 2 : let lsn = src_timeline.get_last_record_lsn();
3135 2 : info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
3136 2 : lsn
3137 228 : });
3138 228 :
3139 228 : // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
3140 228 : // horizon on the source timeline
3141 228 : //
3142 228 : // We check it against both the planned GC cutoff stored in 'gc_info',
3143 228 : // and the 'latest_gc_cutoff' of the last GC that was performed. The
3144 228 : // planned GC cutoff in 'gc_info' is normally larger than
3145 228 : // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
3146 228 : // changed the GC settings for the tenant to make the PITR window
3147 228 : // larger, but some of the data was already removed by an earlier GC
3148 228 : // iteration.
3149 228 :
3150 228 : // check against last actual 'latest_gc_cutoff' first
3151 228 : let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
3152 228 : src_timeline
3153 228 : .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
3154 228 : .context(format!(
3155 228 : "invalid branch start lsn: less than latest GC cutoff {}",
3156 228 : *latest_gc_cutoff_lsn,
3157 228 : ))
3158 228 : .map_err(CreateTimelineError::AncestorLsn)?;
3159 :
3160 : // and then the planned GC cutoff
3161 : {
3162 224 : let gc_info = src_timeline.gc_info.read().unwrap();
3163 224 : let cutoff = gc_info.min_cutoff();
3164 224 : if start_lsn < cutoff {
3165 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
3166 0 : "invalid branch start lsn: less than planned GC cutoff {cutoff}"
3167 0 : )));
3168 224 : }
3169 224 : }
3170 224 :
3171 224 : //
3172 224 : // The branch point is valid, and we are still holding the 'gc_cs' lock
3173 224 : // so that GC cannot advance the GC cutoff until we are finished.
3174 224 : // Proceed with the branch creation.
3175 224 : //
3176 224 :
3177 224 : // Determine prev-LSN for the new timeline. We can only determine it if
3178 224 : // the timeline was branched at the current end of the source timeline.
3179 224 : let RecordLsn {
3180 224 : last: src_last,
3181 224 : prev: src_prev,
3182 224 : } = src_timeline.get_last_record_rlsn();
3183 224 : let dst_prev = if src_last == start_lsn {
3184 214 : Some(src_prev)
3185 : } else {
3186 10 : None
3187 : };
3188 :
3189 : // Create the metadata file, noting the ancestor of the new timeline.
3190 : // There is initially no data in it, but all the read-calls know to look
3191 : // into the ancestor.
3192 224 : let metadata = TimelineMetadata::new(
3193 224 : start_lsn,
3194 224 : dst_prev,
3195 224 : Some(src_id),
3196 224 : start_lsn,
3197 224 : *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
3198 224 : src_timeline.initdb_lsn,
3199 224 : src_timeline.pg_version,
3200 224 : );
3201 :
3202 224 : let uninitialized_timeline = self
3203 224 : .prepare_new_timeline(
3204 224 : dst_id,
3205 224 : &metadata,
3206 224 : timeline_create_guard,
3207 224 : start_lsn + 1,
3208 224 : Some(Arc::clone(src_timeline)),
3209 224 : src_timeline.last_aux_file_policy.load(),
3210 224 : )
3211 0 : .await?;
3212 :
3213 224 : let new_timeline = uninitialized_timeline.finish_creation()?;
3214 :
3215 : // Root timeline gets its layers during creation and uploads them along with the metadata.
3216 : // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
3217 : // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
3218 : // could get incorrect information and remove more layers, than needed.
3219 : // See also https://github.com/neondatabase/neon/issues/3865
3220 224 : new_timeline
3221 224 : .remote_client
3222 224 : .schedule_index_upload_for_full_metadata_update(&metadata)
3223 224 : .context("branch initial metadata upload")?;
3224 :
3225 224 : Ok(new_timeline)
3226 228 : }
3227 :
3228 : /// For unit tests, make this visible so that other modules can directly create timelines
3229 : #[cfg(test)]
3230 4 : #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
3231 : pub(crate) async fn bootstrap_timeline_test(
3232 : &self,
3233 : timeline_id: TimelineId,
3234 : pg_version: u32,
3235 : load_existing_initdb: Option<TimelineId>,
3236 : ctx: &RequestContext,
3237 : ) -> anyhow::Result<Arc<Timeline>> {
3238 : let create_guard = self.create_timeline_create_guard(timeline_id).unwrap();
3239 : self.bootstrap_timeline(
3240 : timeline_id,
3241 : pg_version,
3242 : load_existing_initdb,
3243 : create_guard,
3244 : ctx,
3245 : )
3246 : .await
3247 : }
3248 :
3249 0 : async fn upload_initdb(
3250 0 : &self,
3251 0 : timelines_path: &Utf8PathBuf,
3252 0 : pgdata_path: &Utf8PathBuf,
3253 0 : timeline_id: &TimelineId,
3254 0 : ) -> anyhow::Result<()> {
3255 0 : let temp_path = timelines_path.join(format!(
3256 0 : "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
3257 0 : ));
3258 :
3259 : scopeguard::defer! {
3260 : if let Err(e) = fs::remove_file(&temp_path) {
3261 : error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
3262 : }
3263 : }
3264 :
3265 0 : let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
3266 : const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
3267 0 : if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
3268 0 : warn!(
3269 0 : "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
3270 : );
3271 0 : }
3272 :
3273 : pausable_failpoint!("before-initdb-upload");
3274 :
3275 0 : backoff::retry(
3276 0 : || async {
3277 0 : self::remote_timeline_client::upload_initdb_dir(
3278 0 : &self.remote_storage,
3279 0 : &self.tenant_shard_id.tenant_id,
3280 0 : timeline_id,
3281 0 : pgdata_zstd.try_clone().await?,
3282 0 : tar_zst_size,
3283 0 : &self.cancel,
3284 0 : )
3285 0 : .await
3286 0 : },
3287 0 : |_| false,
3288 0 : 3,
3289 0 : u32::MAX,
3290 0 : "persist_initdb_tar_zst",
3291 0 : &self.cancel,
3292 0 : )
3293 0 : .await
3294 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
3295 0 : .and_then(|x| x)
3296 0 : }
3297 :
3298 : /// - run initdb to init temporary instance and get bootstrap data
3299 : /// - after initialization completes, tar up the temp dir and upload it to S3.
3300 : ///
3301 : /// The caller is responsible for activating the returned timeline.
3302 2 : async fn bootstrap_timeline(
3303 2 : &self,
3304 2 : timeline_id: TimelineId,
3305 2 : pg_version: u32,
3306 2 : load_existing_initdb: Option<TimelineId>,
3307 2 : timeline_create_guard: TimelineCreateGuard<'_>,
3308 2 : ctx: &RequestContext,
3309 2 : ) -> anyhow::Result<Arc<Timeline>> {
3310 2 : // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
3311 2 : // temporary directory for basebackup files for the given timeline.
3312 2 :
3313 2 : let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
3314 2 : let pgdata_path = path_with_suffix_extension(
3315 2 : timelines_path.join(format!("basebackup-{timeline_id}")),
3316 2 : TEMP_FILE_SUFFIX,
3317 2 : );
3318 2 :
3319 2 : // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
3320 2 : // we won't race with other creations or existent timelines with the same path.
3321 2 : if pgdata_path.exists() {
3322 0 : fs::remove_dir_all(&pgdata_path).with_context(|| {
3323 0 : format!("Failed to remove already existing initdb directory: {pgdata_path}")
3324 0 : })?;
3325 2 : }
3326 :
3327 : // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
3328 : scopeguard::defer! {
3329 : if let Err(e) = fs::remove_dir_all(&pgdata_path) {
3330 : // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
3331 : error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
3332 : }
3333 : }
3334 2 : if let Some(existing_initdb_timeline_id) = load_existing_initdb {
3335 2 : if existing_initdb_timeline_id != timeline_id {
3336 0 : let source_path = &remote_initdb_archive_path(
3337 0 : &self.tenant_shard_id.tenant_id,
3338 0 : &existing_initdb_timeline_id,
3339 0 : );
3340 0 : let dest_path =
3341 0 : &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
3342 0 :
3343 0 : // if this fails, it will get retried by retried control plane requests
3344 0 : self.remote_storage
3345 0 : .copy_object(source_path, dest_path, &self.cancel)
3346 0 : .await
3347 0 : .context("copy initdb tar")?;
3348 2 : }
3349 2 : let (initdb_tar_zst_path, initdb_tar_zst) =
3350 2 : self::remote_timeline_client::download_initdb_tar_zst(
3351 2 : self.conf,
3352 2 : &self.remote_storage,
3353 2 : &self.tenant_shard_id,
3354 2 : &existing_initdb_timeline_id,
3355 2 : &self.cancel,
3356 2 : )
3357 738 : .await
3358 2 : .context("download initdb tar")?;
3359 :
3360 : scopeguard::defer! {
3361 : if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
3362 : error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
3363 : }
3364 : }
3365 :
3366 2 : let buf_read =
3367 2 : BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
3368 2 : extract_zst_tarball(&pgdata_path, buf_read)
3369 11012 : .await
3370 2 : .context("extract initdb tar")?;
3371 : } else {
3372 : // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
3373 0 : run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel).await?;
3374 :
3375 : // Upload the created data dir to S3
3376 0 : if self.tenant_shard_id().is_shard_zero() {
3377 0 : self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
3378 0 : .await?;
3379 0 : }
3380 : }
3381 2 : let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
3382 2 :
3383 2 : // Import the contents of the data directory at the initial checkpoint
3384 2 : // LSN, and any WAL after that.
3385 2 : // Initdb lsn will be equal to last_record_lsn which will be set after import.
3386 2 : // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
3387 2 : let new_metadata = TimelineMetadata::new(
3388 2 : Lsn(0),
3389 2 : None,
3390 2 : None,
3391 2 : Lsn(0),
3392 2 : pgdata_lsn,
3393 2 : pgdata_lsn,
3394 2 : pg_version,
3395 2 : );
3396 2 : let raw_timeline = self
3397 2 : .prepare_new_timeline(
3398 2 : timeline_id,
3399 2 : &new_metadata,
3400 2 : timeline_create_guard,
3401 2 : pgdata_lsn,
3402 2 : None,
3403 2 : None,
3404 2 : )
3405 0 : .await?;
3406 :
3407 2 : let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
3408 2 : let unfinished_timeline = raw_timeline.raw_timeline()?;
3409 :
3410 : // Flush the new layer files to disk, before we make the timeline as available to
3411 : // the outside world.
3412 : //
3413 : // Flush loop needs to be spawned in order to be able to flush.
3414 2 : unfinished_timeline.maybe_spawn_flush_loop();
3415 2 :
3416 2 : import_datadir::import_timeline_from_postgres_datadir(
3417 2 : unfinished_timeline,
3418 2 : &pgdata_path,
3419 2 : pgdata_lsn,
3420 2 : ctx,
3421 2 : )
3422 9482 : .await
3423 2 : .with_context(|| {
3424 0 : format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
3425 2 : })?;
3426 :
3427 2 : fail::fail_point!("before-checkpoint-new-timeline", |_| {
3428 0 : anyhow::bail!("failpoint before-checkpoint-new-timeline");
3429 2 : });
3430 :
3431 2 : unfinished_timeline
3432 2 : .freeze_and_flush()
3433 2 : .await
3434 2 : .with_context(|| {
3435 0 : format!(
3436 0 : "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
3437 0 : )
3438 2 : })?;
3439 :
3440 : // All done!
3441 2 : let timeline = raw_timeline.finish_creation()?;
3442 :
3443 2 : Ok(timeline)
3444 2 : }
3445 :
3446 : /// Call this before constructing a timeline, to build its required structures
3447 373 : fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
3448 373 : let remote_client = RemoteTimelineClient::new(
3449 373 : self.remote_storage.clone(),
3450 373 : self.deletion_queue_client.clone(),
3451 373 : self.conf,
3452 373 : self.tenant_shard_id,
3453 373 : timeline_id,
3454 373 : self.generation,
3455 373 : );
3456 373 : TimelineResources {
3457 373 : remote_client,
3458 373 : timeline_get_throttle: self.timeline_get_throttle.clone(),
3459 373 : }
3460 373 : }
3461 :
3462 : /// Creates intermediate timeline structure and its files.
3463 : ///
3464 : /// An empty layer map is initialized, and new data and WAL can be imported starting
3465 : /// at 'disk_consistent_lsn'. After any initial data has been imported, call
3466 : /// `finish_creation` to insert the Timeline into the timelines map.
3467 373 : async fn prepare_new_timeline<'a>(
3468 373 : &'a self,
3469 373 : new_timeline_id: TimelineId,
3470 373 : new_metadata: &TimelineMetadata,
3471 373 : create_guard: TimelineCreateGuard<'a>,
3472 373 : start_lsn: Lsn,
3473 373 : ancestor: Option<Arc<Timeline>>,
3474 373 : last_aux_file_policy: Option<AuxFilePolicy>,
3475 373 : ) -> anyhow::Result<UninitializedTimeline> {
3476 373 : let tenant_shard_id = self.tenant_shard_id;
3477 373 :
3478 373 : let resources = self.build_timeline_resources(new_timeline_id);
3479 373 : resources
3480 373 : .remote_client
3481 373 : .init_upload_queue_for_empty_remote(new_metadata)?;
3482 :
3483 373 : let timeline_struct = self
3484 373 : .create_timeline_struct(
3485 373 : new_timeline_id,
3486 373 : new_metadata,
3487 373 : ancestor,
3488 373 : resources,
3489 373 : CreateTimelineCause::Load,
3490 373 : last_aux_file_policy,
3491 373 : )
3492 373 : .context("Failed to create timeline data structure")?;
3493 :
3494 373 : timeline_struct.init_empty_layer_map(start_lsn);
3495 :
3496 373 : if let Err(e) = self
3497 373 : .create_timeline_files(&create_guard.timeline_path)
3498 0 : .await
3499 : {
3500 1 : error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
3501 1 : cleanup_timeline_directory(create_guard);
3502 1 : return Err(e);
3503 372 : }
3504 372 :
3505 372 : debug!(
3506 0 : "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
3507 : );
3508 :
3509 372 : Ok(UninitializedTimeline::new(
3510 372 : self,
3511 372 : new_timeline_id,
3512 372 : Some((timeline_struct, create_guard)),
3513 372 : ))
3514 373 : }
3515 :
3516 373 : async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
3517 373 : crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
3518 :
3519 372 : fail::fail_point!("after-timeline-dir-creation", |_| {
3520 0 : anyhow::bail!("failpoint after-timeline-dir-creation");
3521 372 : });
3522 :
3523 372 : Ok(())
3524 373 : }
3525 :
3526 : /// Get a guard that provides exclusive access to the timeline directory, preventing
3527 : /// concurrent attempts to create the same timeline.
3528 379 : fn create_timeline_create_guard(
3529 379 : &self,
3530 379 : timeline_id: TimelineId,
3531 379 : ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
3532 379 : let tenant_shard_id = self.tenant_shard_id;
3533 379 :
3534 379 : let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
3535 :
3536 379 : let create_guard = TimelineCreateGuard::new(self, timeline_id, timeline_path.clone())?;
3537 :
3538 : // At this stage, we have got exclusive access to in-memory state for this timeline ID
3539 : // for creation.
3540 : // A timeline directory should never exist on disk already:
3541 : // - a previous failed creation would have cleaned up after itself
3542 : // - a pageserver restart would clean up timeline directories that don't have valid remote state
3543 : //
3544 : // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
3545 : // this error may indicate a bug in cleanup on failed creations.
3546 377 : if timeline_path.exists() {
3547 0 : return Err(TimelineExclusionError::Other(anyhow::anyhow!(
3548 0 : "Timeline directory already exists! This is a bug."
3549 0 : )));
3550 377 : }
3551 377 :
3552 377 : Ok(create_guard)
3553 379 : }
3554 :
3555 : /// Gathers inputs from all of the timelines to produce a sizing model input.
3556 : ///
3557 : /// Future is cancellation safe. Only one calculation can be running at once per tenant.
3558 0 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
3559 : pub async fn gather_size_inputs(
3560 : &self,
3561 : // `max_retention_period` overrides the cutoff that is used to calculate the size
3562 : // (only if it is shorter than the real cutoff).
3563 : max_retention_period: Option<u64>,
3564 : cause: LogicalSizeCalculationCause,
3565 : cancel: &CancellationToken,
3566 : ctx: &RequestContext,
3567 : ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
3568 : let logical_sizes_at_once = self
3569 : .conf
3570 : .concurrent_tenant_size_logical_size_queries
3571 : .inner();
3572 :
3573 : // TODO: Having a single mutex block concurrent reads is not great for performance.
3574 : //
3575 : // But the only case where we need to run multiple of these at once is when we
3576 : // request a size for a tenant manually via API, while another background calculation
3577 : // is in progress (which is not a common case).
3578 : //
3579 : // See more for on the issue #2748 condenced out of the initial PR review.
3580 : let mut shared_cache = tokio::select! {
3581 : locked = self.cached_logical_sizes.lock() => locked,
3582 : _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
3583 : _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
3584 : };
3585 :
3586 : size::gather_inputs(
3587 : self,
3588 : logical_sizes_at_once,
3589 : max_retention_period,
3590 : &mut shared_cache,
3591 : cause,
3592 : cancel,
3593 : ctx,
3594 : )
3595 : .await
3596 : }
3597 :
3598 : /// Calculate synthetic tenant size and cache the result.
3599 : /// This is periodically called by background worker.
3600 : /// result is cached in tenant struct
3601 0 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
3602 : pub async fn calculate_synthetic_size(
3603 : &self,
3604 : cause: LogicalSizeCalculationCause,
3605 : cancel: &CancellationToken,
3606 : ctx: &RequestContext,
3607 : ) -> Result<u64, size::CalculateSyntheticSizeError> {
3608 : let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
3609 :
3610 : let size = inputs.calculate();
3611 :
3612 : self.set_cached_synthetic_size(size);
3613 :
3614 : Ok(size)
3615 : }
3616 :
3617 : /// Cache given synthetic size and update the metric value
3618 0 : pub fn set_cached_synthetic_size(&self, size: u64) {
3619 0 : self.cached_synthetic_tenant_size
3620 0 : .store(size, Ordering::Relaxed);
3621 0 :
3622 0 : // Only shard zero should be calculating synthetic sizes
3623 0 : debug_assert!(self.shard_identity.is_shard_zero());
3624 :
3625 0 : TENANT_SYNTHETIC_SIZE_METRIC
3626 0 : .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
3627 0 : .unwrap()
3628 0 : .set(size);
3629 0 : }
3630 :
3631 0 : pub fn cached_synthetic_size(&self) -> u64 {
3632 0 : self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
3633 0 : }
3634 :
3635 : /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
3636 : ///
3637 : /// This function can take a long time: callers should wrap it in a timeout if calling
3638 : /// from an external API handler.
3639 : ///
3640 : /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
3641 : /// still bounded by tenant/timeline shutdown.
3642 0 : #[tracing::instrument(skip_all)]
3643 : pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
3644 : let timelines = self.timelines.lock().unwrap().clone();
3645 :
3646 0 : async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
3647 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
3648 0 : timeline.freeze_and_flush().await?;
3649 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
3650 0 : timeline.remote_client.wait_completion().await?;
3651 :
3652 0 : Ok(())
3653 0 : }
3654 :
3655 : // We do not use a JoinSet for these tasks, because we don't want them to be
3656 : // aborted when this function's future is cancelled: they should stay alive
3657 : // holding their GateGuard until they complete, to ensure their I/Os complete
3658 : // before Timeline shutdown completes.
3659 : let mut results = FuturesUnordered::new();
3660 :
3661 : for (_timeline_id, timeline) in timelines {
3662 : // Run each timeline's flush in a task holding the timeline's gate: this
3663 : // means that if this function's future is cancelled, the Timeline shutdown
3664 : // will still wait for any I/O in here to complete.
3665 : let Ok(gate) = timeline.gate.enter() else {
3666 : continue;
3667 : };
3668 0 : let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
3669 : results.push(jh);
3670 : }
3671 :
3672 : while let Some(r) = results.next().await {
3673 : if let Err(e) = r {
3674 : if !e.is_cancelled() && !e.is_panic() {
3675 : tracing::error!("unexpected join error: {e:?}");
3676 : }
3677 : }
3678 : }
3679 :
3680 : // The flushes we did above were just writes, but the Tenant might have had
3681 : // pending deletions as well from recent compaction/gc: we want to flush those
3682 : // as well. This requires flushing the global delete queue. This is cheap
3683 : // because it's typically a no-op.
3684 : match self.deletion_queue_client.flush_execute().await {
3685 : Ok(_) => {}
3686 : Err(DeletionQueueError::ShuttingDown) => {}
3687 : }
3688 :
3689 : Ok(())
3690 : }
3691 :
3692 0 : pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
3693 0 : self.tenant_conf.load().tenant_conf.clone()
3694 0 : }
3695 : }
3696 :
3697 : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
3698 : /// to get bootstrap data for timeline initialization.
3699 0 : async fn run_initdb(
3700 0 : conf: &'static PageServerConf,
3701 0 : initdb_target_dir: &Utf8Path,
3702 0 : pg_version: u32,
3703 0 : cancel: &CancellationToken,
3704 0 : ) -> Result<(), InitdbError> {
3705 0 : let initdb_bin_path = conf
3706 0 : .pg_bin_dir(pg_version)
3707 0 : .map_err(InitdbError::Other)?
3708 0 : .join("initdb");
3709 0 : let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
3710 0 : info!(
3711 0 : "running {} in {}, libdir: {}",
3712 : initdb_bin_path, initdb_target_dir, initdb_lib_dir,
3713 : );
3714 :
3715 0 : let _permit = INIT_DB_SEMAPHORE.acquire().await;
3716 :
3717 0 : let initdb_command = tokio::process::Command::new(&initdb_bin_path)
3718 0 : .args(["-D", initdb_target_dir.as_ref()])
3719 0 : .args(["-U", &conf.superuser])
3720 0 : .args(["-E", "utf8"])
3721 0 : .arg("--no-instructions")
3722 0 : .arg("--no-sync")
3723 0 : .env_clear()
3724 0 : .env("LD_LIBRARY_PATH", &initdb_lib_dir)
3725 0 : .env("DYLD_LIBRARY_PATH", &initdb_lib_dir)
3726 0 : .stdin(std::process::Stdio::null())
3727 0 : // stdout invocation produces the same output every time, we don't need it
3728 0 : .stdout(std::process::Stdio::null())
3729 0 : // we would be interested in the stderr output, if there was any
3730 0 : .stderr(std::process::Stdio::piped())
3731 0 : .spawn()?;
3732 :
3733 : // Ideally we'd select here with the cancellation token, but the problem is that
3734 : // we can't safely terminate initdb: it launches processes of its own, and killing
3735 : // initdb doesn't kill them. After we return from this function, we want the target
3736 : // directory to be able to be cleaned up.
3737 : // See https://github.com/neondatabase/neon/issues/6385
3738 0 : let initdb_output = initdb_command.wait_with_output().await?;
3739 0 : if !initdb_output.status.success() {
3740 0 : return Err(InitdbError::Failed(
3741 0 : initdb_output.status,
3742 0 : initdb_output.stderr,
3743 0 : ));
3744 0 : }
3745 0 :
3746 0 : // This isn't true cancellation support, see above. Still return an error to
3747 0 : // excercise the cancellation code path.
3748 0 : if cancel.is_cancelled() {
3749 0 : return Err(InitdbError::Cancelled);
3750 0 : }
3751 0 :
3752 0 : Ok(())
3753 0 : }
3754 :
3755 : /// Dump contents of a layer file to stdout.
3756 0 : pub async fn dump_layerfile_from_path(
3757 0 : path: &Utf8Path,
3758 0 : verbose: bool,
3759 0 : ctx: &RequestContext,
3760 0 : ) -> anyhow::Result<()> {
3761 : use std::os::unix::fs::FileExt;
3762 :
3763 : // All layer files start with a two-byte "magic" value, to identify the kind of
3764 : // file.
3765 0 : let file = File::open(path)?;
3766 0 : let mut header_buf = [0u8; 2];
3767 0 : file.read_exact_at(&mut header_buf, 0)?;
3768 :
3769 0 : match u16::from_be_bytes(header_buf) {
3770 : crate::IMAGE_FILE_MAGIC => {
3771 0 : ImageLayer::new_for_path(path, file)?
3772 0 : .dump(verbose, ctx)
3773 0 : .await?
3774 : }
3775 : crate::DELTA_FILE_MAGIC => {
3776 0 : DeltaLayer::new_for_path(path, file)?
3777 0 : .dump(verbose, ctx)
3778 0 : .await?
3779 : }
3780 0 : magic => bail!("unrecognized magic identifier: {:?}", magic),
3781 : }
3782 :
3783 0 : Ok(())
3784 0 : }
3785 :
3786 : #[cfg(test)]
3787 : pub(crate) mod harness {
3788 : use bytes::{Bytes, BytesMut};
3789 : use once_cell::sync::OnceCell;
3790 : use pageserver_api::models::ShardParameters;
3791 : use pageserver_api::shard::ShardIndex;
3792 : use utils::logging;
3793 :
3794 : use crate::deletion_queue::mock::MockDeletionQueue;
3795 : use crate::walredo::apply_neon;
3796 : use crate::{repository::Key, walrecord::NeonWalRecord};
3797 :
3798 : use super::*;
3799 : use hex_literal::hex;
3800 : use utils::id::TenantId;
3801 :
3802 : pub const TIMELINE_ID: TimelineId =
3803 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
3804 : pub const NEW_TIMELINE_ID: TimelineId =
3805 : TimelineId::from_array(hex!("AA223344556677881122334455667788"));
3806 :
3807 : /// Convenience function to create a page image with given string as the only content
3808 5028404 : pub fn test_img(s: &str) -> Bytes {
3809 5028404 : let mut buf = BytesMut::new();
3810 5028404 : buf.extend_from_slice(s.as_bytes());
3811 5028404 : buf.resize(64, 0);
3812 5028404 :
3813 5028404 : buf.freeze()
3814 5028404 : }
3815 :
3816 : impl From<TenantConf> for TenantConfOpt {
3817 157 : fn from(tenant_conf: TenantConf) -> Self {
3818 157 : Self {
3819 157 : checkpoint_distance: Some(tenant_conf.checkpoint_distance),
3820 157 : checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
3821 157 : compaction_target_size: Some(tenant_conf.compaction_target_size),
3822 157 : compaction_period: Some(tenant_conf.compaction_period),
3823 157 : compaction_threshold: Some(tenant_conf.compaction_threshold),
3824 157 : compaction_algorithm: Some(tenant_conf.compaction_algorithm),
3825 157 : gc_horizon: Some(tenant_conf.gc_horizon),
3826 157 : gc_period: Some(tenant_conf.gc_period),
3827 157 : image_creation_threshold: Some(tenant_conf.image_creation_threshold),
3828 157 : pitr_interval: Some(tenant_conf.pitr_interval),
3829 157 : walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
3830 157 : lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
3831 157 : max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
3832 157 : trace_read_requests: Some(tenant_conf.trace_read_requests),
3833 157 : eviction_policy: Some(tenant_conf.eviction_policy),
3834 157 : min_resident_size_override: tenant_conf.min_resident_size_override,
3835 157 : evictions_low_residence_duration_metric_threshold: Some(
3836 157 : tenant_conf.evictions_low_residence_duration_metric_threshold,
3837 157 : ),
3838 157 : heatmap_period: Some(tenant_conf.heatmap_period),
3839 157 : lazy_slru_download: Some(tenant_conf.lazy_slru_download),
3840 157 : timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
3841 157 : image_layer_creation_check_threshold: Some(
3842 157 : tenant_conf.image_layer_creation_check_threshold,
3843 157 : ),
3844 157 : switch_aux_file_policy: Some(tenant_conf.switch_aux_file_policy),
3845 157 : lsn_lease_length: Some(tenant_conf.lsn_lease_length),
3846 157 : lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
3847 157 : }
3848 157 : }
3849 : }
3850 :
3851 : pub struct TenantHarness {
3852 : pub conf: &'static PageServerConf,
3853 : pub tenant_conf: TenantConf,
3854 : pub tenant_shard_id: TenantShardId,
3855 : pub generation: Generation,
3856 : pub shard: ShardIndex,
3857 : pub remote_storage: GenericRemoteStorage,
3858 : pub remote_fs_dir: Utf8PathBuf,
3859 : pub deletion_queue: MockDeletionQueue,
3860 : }
3861 :
3862 : static LOG_HANDLE: OnceCell<()> = OnceCell::new();
3863 :
3864 163 : pub(crate) fn setup_logging() {
3865 163 : LOG_HANDLE.get_or_init(|| {
3866 151 : logging::init(
3867 151 : logging::LogFormat::Test,
3868 151 : // enable it in case the tests exercise code paths that use
3869 151 : // debug_assert_current_span_has_tenant_and_timeline_id
3870 151 : logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
3871 151 : logging::Output::Stdout,
3872 151 : )
3873 151 : .expect("Failed to init test logging")
3874 163 : });
3875 163 : }
3876 :
3877 : impl TenantHarness {
3878 157 : pub fn create_custom(
3879 157 : test_name: &'static str,
3880 157 : tenant_conf: TenantConf,
3881 157 : tenant_id: TenantId,
3882 157 : shard_identity: ShardIdentity,
3883 157 : generation: Generation,
3884 157 : ) -> anyhow::Result<Self> {
3885 157 : setup_logging();
3886 157 :
3887 157 : let repo_dir = PageServerConf::test_repo_dir(test_name);
3888 157 : let _ = fs::remove_dir_all(&repo_dir);
3889 157 : fs::create_dir_all(&repo_dir)?;
3890 :
3891 157 : let conf = PageServerConf::dummy_conf(repo_dir);
3892 157 : // Make a static copy of the config. This can never be free'd, but that's
3893 157 : // OK in a test.
3894 157 : let conf: &'static PageServerConf = Box::leak(Box::new(conf));
3895 157 :
3896 157 : let shard = shard_identity.shard_index();
3897 157 : let tenant_shard_id = TenantShardId {
3898 157 : tenant_id,
3899 157 : shard_number: shard.shard_number,
3900 157 : shard_count: shard.shard_count,
3901 157 : };
3902 157 : fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
3903 157 : fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
3904 :
3905 : use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
3906 157 : let remote_fs_dir = conf.workdir.join("localfs");
3907 157 : std::fs::create_dir_all(&remote_fs_dir).unwrap();
3908 157 : let config = RemoteStorageConfig {
3909 157 : storage: RemoteStorageKind::LocalFs(remote_fs_dir.clone()),
3910 157 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
3911 157 : };
3912 157 : let remote_storage = GenericRemoteStorage::from_config(&config).unwrap();
3913 157 : let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
3914 157 :
3915 157 : Ok(Self {
3916 157 : conf,
3917 157 : tenant_conf,
3918 157 : tenant_shard_id,
3919 157 : generation,
3920 157 : shard,
3921 157 : remote_storage,
3922 157 : remote_fs_dir,
3923 157 : deletion_queue,
3924 157 : })
3925 157 : }
3926 :
3927 145 : pub fn create(test_name: &'static str) -> anyhow::Result<Self> {
3928 145 : // Disable automatic GC and compaction to make the unit tests more deterministic.
3929 145 : // The tests perform them manually if needed.
3930 145 : let tenant_conf = TenantConf {
3931 145 : gc_period: Duration::ZERO,
3932 145 : compaction_period: Duration::ZERO,
3933 145 : ..TenantConf::default()
3934 145 : };
3935 145 : let tenant_id = TenantId::generate();
3936 145 : let shard = ShardIdentity::unsharded();
3937 145 : Self::create_custom(
3938 145 : test_name,
3939 145 : tenant_conf,
3940 145 : tenant_id,
3941 145 : shard,
3942 145 : Generation::new(0xdeadbeef),
3943 145 : )
3944 145 : }
3945 :
3946 18 : pub fn span(&self) -> tracing::Span {
3947 18 : info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
3948 18 : }
3949 :
3950 157 : pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
3951 157 : let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
3952 157 : (
3953 157 : self.do_try_load(&ctx)
3954 628 : .await
3955 157 : .expect("failed to load test tenant"),
3956 157 : ctx,
3957 157 : )
3958 157 : }
3959 :
3960 314 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
3961 : pub(crate) async fn do_try_load(
3962 : &self,
3963 : ctx: &RequestContext,
3964 : ) -> anyhow::Result<Arc<Tenant>> {
3965 : let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
3966 :
3967 : let tenant = Arc::new(Tenant::new(
3968 : TenantState::Loading,
3969 : self.conf,
3970 : AttachedTenantConf::try_from(LocationConf::attached_single(
3971 : TenantConfOpt::from(self.tenant_conf.clone()),
3972 : self.generation,
3973 : &ShardParameters::default(),
3974 : ))
3975 : .unwrap(),
3976 : // This is a legacy/test code path: sharding isn't supported here.
3977 : ShardIdentity::unsharded(),
3978 : Some(walredo_mgr),
3979 : self.tenant_shard_id,
3980 : self.remote_storage.clone(),
3981 : self.deletion_queue.new_client(),
3982 : ));
3983 :
3984 : let preload = tenant
3985 : .preload(&self.remote_storage, CancellationToken::new())
3986 : .await?;
3987 : tenant.attach(Some(preload), SpawnMode::Eager, ctx).await?;
3988 :
3989 : tenant.state.send_replace(TenantState::Active);
3990 : for timeline in tenant.timelines.lock().unwrap().values() {
3991 : timeline.set_state(TimelineState::Active);
3992 : }
3993 : Ok(tenant)
3994 : }
3995 :
3996 2 : pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
3997 2 : self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
3998 2 : }
3999 : }
4000 :
4001 : // Mock WAL redo manager that doesn't do much
4002 : pub(crate) struct TestRedoManager;
4003 :
4004 : impl TestRedoManager {
4005 : /// # Cancel-Safety
4006 : ///
4007 : /// This method is cancellation-safe.
4008 18 : pub async fn request_redo(
4009 18 : &self,
4010 18 : key: Key,
4011 18 : lsn: Lsn,
4012 18 : base_img: Option<(Lsn, Bytes)>,
4013 18 : records: Vec<(Lsn, NeonWalRecord)>,
4014 18 : _pg_version: u32,
4015 18 : ) -> anyhow::Result<Bytes> {
4016 28 : let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
4017 18 : if records_neon {
4018 : // For Neon wal records, we can decode without spawning postgres, so do so.
4019 18 : let base_img = base_img.expect("Neon WAL redo requires base image").1;
4020 18 : let mut page = BytesMut::new();
4021 18 : page.extend_from_slice(&base_img);
4022 46 : for (record_lsn, record) in records {
4023 28 : apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
4024 : }
4025 18 : Ok(page.freeze())
4026 : } else {
4027 : // We never spawn a postgres walredo process in unit tests: just log what we might have done.
4028 0 : let s = format!(
4029 0 : "redo for {} to get to {}, with {} and {} records",
4030 0 : key,
4031 0 : lsn,
4032 0 : if base_img.is_some() {
4033 0 : "base image"
4034 : } else {
4035 0 : "no base image"
4036 : },
4037 0 : records.len()
4038 0 : );
4039 0 : println!("{s}");
4040 0 :
4041 0 : Ok(test_img(&s))
4042 : }
4043 18 : }
4044 : }
4045 : }
4046 :
4047 : #[cfg(test)]
4048 : mod tests {
4049 : use std::collections::BTreeMap;
4050 :
4051 : use super::*;
4052 : use crate::keyspace::KeySpaceAccum;
4053 : use crate::pgdatadir_mapping::AuxFilesDirectory;
4054 : use crate::repository::{Key, Value};
4055 : use crate::tenant::harness::*;
4056 : use crate::tenant::timeline::CompactFlags;
4057 : use crate::walrecord::NeonWalRecord;
4058 : use crate::DEFAULT_PG_VERSION;
4059 : use bytes::{Bytes, BytesMut};
4060 : use hex_literal::hex;
4061 : use itertools::Itertools;
4062 : use pageserver_api::key::{AUX_FILES_KEY, AUX_KEY_PREFIX, NON_INHERITED_RANGE};
4063 : use pageserver_api::keyspace::KeySpace;
4064 : use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
4065 : use rand::{thread_rng, Rng};
4066 : use storage_layer::PersistentLayerKey;
4067 : use tests::storage_layer::ValuesReconstructState;
4068 : use tests::timeline::{GetVectoredError, ShutdownMode};
4069 : use utils::bin_ser::BeSer;
4070 : use utils::id::TenantId;
4071 :
4072 : static TEST_KEY: Lazy<Key> =
4073 18 : Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
4074 :
4075 : #[tokio::test]
4076 2 : async fn test_basic() -> anyhow::Result<()> {
4077 8 : let (tenant, ctx) = TenantHarness::create("test_basic")?.load().await;
4078 2 : let tline = tenant
4079 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
4080 6 : .await?;
4081 2 :
4082 2 : let mut writer = tline.writer().await;
4083 2 : writer
4084 2 : .put(
4085 2 : *TEST_KEY,
4086 2 : Lsn(0x10),
4087 2 : &Value::Image(test_img("foo at 0x10")),
4088 2 : &ctx,
4089 2 : )
4090 2 : .await?;
4091 2 : writer.finish_write(Lsn(0x10));
4092 2 : drop(writer);
4093 2 :
4094 2 : let mut writer = tline.writer().await;
4095 2 : writer
4096 2 : .put(
4097 2 : *TEST_KEY,
4098 2 : Lsn(0x20),
4099 2 : &Value::Image(test_img("foo at 0x20")),
4100 2 : &ctx,
4101 2 : )
4102 2 : .await?;
4103 2 : writer.finish_write(Lsn(0x20));
4104 2 : drop(writer);
4105 2 :
4106 2 : assert_eq!(
4107 2 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
4108 2 : test_img("foo at 0x10")
4109 2 : );
4110 2 : assert_eq!(
4111 2 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
4112 2 : test_img("foo at 0x10")
4113 2 : );
4114 2 : assert_eq!(
4115 2 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
4116 2 : test_img("foo at 0x20")
4117 2 : );
4118 2 :
4119 2 : Ok(())
4120 2 : }
4121 :
4122 : #[tokio::test]
4123 2 : async fn no_duplicate_timelines() -> anyhow::Result<()> {
4124 2 : let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")?
4125 2 : .load()
4126 8 : .await;
4127 2 : let _ = tenant
4128 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4129 6 : .await?;
4130 2 :
4131 2 : match tenant
4132 2 : .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4133 2 : .await
4134 2 : {
4135 2 : Ok(_) => panic!("duplicate timeline creation should fail"),
4136 2 : Err(e) => assert_eq!(e.to_string(), "Already exists".to_string()),
4137 2 : }
4138 2 :
4139 2 : Ok(())
4140 2 : }
4141 :
4142 : /// Convenience function to create a page image with given string as the only content
4143 10 : pub fn test_value(s: &str) -> Value {
4144 10 : let mut buf = BytesMut::new();
4145 10 : buf.extend_from_slice(s.as_bytes());
4146 10 : Value::Image(buf.freeze())
4147 10 : }
4148 :
4149 : ///
4150 : /// Test branch creation
4151 : ///
4152 : #[tokio::test]
4153 2 : async fn test_branch() -> anyhow::Result<()> {
4154 2 : use std::str::from_utf8;
4155 2 :
4156 8 : let (tenant, ctx) = TenantHarness::create("test_branch")?.load().await;
4157 2 : let tline = tenant
4158 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4159 6 : .await?;
4160 2 : let mut writer = tline.writer().await;
4161 2 :
4162 2 : #[allow(non_snake_case)]
4163 2 : let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
4164 2 : #[allow(non_snake_case)]
4165 2 : let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
4166 2 :
4167 2 : // Insert a value on the timeline
4168 2 : writer
4169 2 : .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
4170 2 : .await?;
4171 2 : writer
4172 2 : .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
4173 2 : .await?;
4174 2 : writer.finish_write(Lsn(0x20));
4175 2 :
4176 2 : writer
4177 2 : .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
4178 2 : .await?;
4179 2 : writer.finish_write(Lsn(0x30));
4180 2 : writer
4181 2 : .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
4182 2 : .await?;
4183 2 : writer.finish_write(Lsn(0x40));
4184 2 :
4185 2 : //assert_current_logical_size(&tline, Lsn(0x40));
4186 2 :
4187 2 : // Branch the history, modify relation differently on the new timeline
4188 2 : tenant
4189 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
4190 2 : .await?;
4191 2 : let newtline = tenant
4192 2 : .get_timeline(NEW_TIMELINE_ID, true)
4193 2 : .expect("Should have a local timeline");
4194 2 : let mut new_writer = newtline.writer().await;
4195 2 : new_writer
4196 2 : .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
4197 2 : .await?;
4198 2 : new_writer.finish_write(Lsn(0x40));
4199 2 :
4200 2 : // Check page contents on both branches
4201 2 : assert_eq!(
4202 2 : from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
4203 2 : "foo at 0x40"
4204 2 : );
4205 2 : assert_eq!(
4206 2 : from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
4207 2 : "bar at 0x40"
4208 2 : );
4209 2 : assert_eq!(
4210 2 : from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
4211 2 : "foobar at 0x20"
4212 2 : );
4213 2 :
4214 2 : //assert_current_logical_size(&tline, Lsn(0x40));
4215 2 :
4216 2 : Ok(())
4217 2 : }
4218 :
4219 20 : async fn make_some_layers(
4220 20 : tline: &Timeline,
4221 20 : start_lsn: Lsn,
4222 20 : ctx: &RequestContext,
4223 20 : ) -> anyhow::Result<()> {
4224 20 : let mut lsn = start_lsn;
4225 : {
4226 20 : let mut writer = tline.writer().await;
4227 : // Create a relation on the timeline
4228 20 : writer
4229 20 : .put(
4230 20 : *TEST_KEY,
4231 20 : lsn,
4232 20 : &Value::Image(test_img(&format!("foo at {}", lsn))),
4233 20 : ctx,
4234 20 : )
4235 10 : .await?;
4236 20 : writer.finish_write(lsn);
4237 20 : lsn += 0x10;
4238 20 : writer
4239 20 : .put(
4240 20 : *TEST_KEY,
4241 20 : lsn,
4242 20 : &Value::Image(test_img(&format!("foo at {}", lsn))),
4243 20 : ctx,
4244 20 : )
4245 0 : .await?;
4246 20 : writer.finish_write(lsn);
4247 20 : lsn += 0x10;
4248 20 : }
4249 20 : tline.freeze_and_flush().await?;
4250 : {
4251 20 : let mut writer = tline.writer().await;
4252 20 : writer
4253 20 : .put(
4254 20 : *TEST_KEY,
4255 20 : lsn,
4256 20 : &Value::Image(test_img(&format!("foo at {}", lsn))),
4257 20 : ctx,
4258 20 : )
4259 10 : .await?;
4260 20 : writer.finish_write(lsn);
4261 20 : lsn += 0x10;
4262 20 : writer
4263 20 : .put(
4264 20 : *TEST_KEY,
4265 20 : lsn,
4266 20 : &Value::Image(test_img(&format!("foo at {}", lsn))),
4267 20 : ctx,
4268 20 : )
4269 0 : .await?;
4270 20 : writer.finish_write(lsn);
4271 20 : }
4272 20 : tline.freeze_and_flush().await.map_err(|e| e.into())
4273 20 : }
4274 :
4275 : #[tokio::test]
4276 2 : async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
4277 2 : let (tenant, ctx) =
4278 2 : TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")?
4279 2 : .load()
4280 8 : .await;
4281 2 : let tline = tenant
4282 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4283 6 : .await?;
4284 6 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4285 2 :
4286 2 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
4287 2 : // FIXME: this doesn't actually remove any layer currently, given how the flushing
4288 2 : // and compaction works. But it does set the 'cutoff' point so that the cross check
4289 2 : // below should fail.
4290 2 : tenant
4291 2 : .gc_iteration(
4292 2 : Some(TIMELINE_ID),
4293 2 : 0x10,
4294 2 : Duration::ZERO,
4295 2 : &CancellationToken::new(),
4296 2 : &ctx,
4297 2 : )
4298 2 : .await?;
4299 2 :
4300 2 : // try to branch at lsn 25, should fail because we already garbage collected the data
4301 2 : match tenant
4302 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
4303 2 : .await
4304 2 : {
4305 2 : Ok(_) => panic!("branching should have failed"),
4306 2 : Err(err) => {
4307 2 : let CreateTimelineError::AncestorLsn(err) = err else {
4308 2 : panic!("wrong error type")
4309 2 : };
4310 2 : assert!(err.to_string().contains("invalid branch start lsn"));
4311 2 : assert!(err
4312 2 : .source()
4313 2 : .unwrap()
4314 2 : .to_string()
4315 2 : .contains("we might've already garbage collected needed data"))
4316 2 : }
4317 2 : }
4318 2 :
4319 2 : Ok(())
4320 2 : }
4321 :
4322 : #[tokio::test]
4323 2 : async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
4324 2 : let (tenant, ctx) =
4325 2 : TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")?
4326 2 : .load()
4327 8 : .await;
4328 2 :
4329 2 : let tline = tenant
4330 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
4331 6 : .await?;
4332 2 : // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
4333 2 : match tenant
4334 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
4335 2 : .await
4336 2 : {
4337 2 : Ok(_) => panic!("branching should have failed"),
4338 2 : Err(err) => {
4339 2 : let CreateTimelineError::AncestorLsn(err) = err else {
4340 2 : panic!("wrong error type");
4341 2 : };
4342 2 : assert!(&err.to_string().contains("invalid branch start lsn"));
4343 2 : assert!(&err
4344 2 : .source()
4345 2 : .unwrap()
4346 2 : .to_string()
4347 2 : .contains("is earlier than latest GC horizon"));
4348 2 : }
4349 2 : }
4350 2 :
4351 2 : Ok(())
4352 2 : }
4353 :
4354 : /*
4355 : // FIXME: This currently fails to error out. Calling GC doesn't currently
4356 : // remove the old value, we'd need to work a little harder
4357 : #[tokio::test]
4358 : async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
4359 : let repo =
4360 : RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
4361 : .load();
4362 :
4363 : let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
4364 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4365 :
4366 : repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
4367 : let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
4368 : assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
4369 : match tline.get(*TEST_KEY, Lsn(0x25)) {
4370 : Ok(_) => panic!("request for page should have failed"),
4371 : Err(err) => assert!(err.to_string().contains("not found at")),
4372 : }
4373 : Ok(())
4374 : }
4375 : */
4376 :
4377 : #[tokio::test]
4378 2 : async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
4379 2 : let (tenant, ctx) =
4380 2 : TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")?
4381 2 : .load()
4382 8 : .await;
4383 2 : let tline = tenant
4384 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4385 6 : .await?;
4386 6 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4387 2 :
4388 2 : tenant
4389 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
4390 2 : .await?;
4391 2 : let newtline = tenant
4392 2 : .get_timeline(NEW_TIMELINE_ID, true)
4393 2 : .expect("Should have a local timeline");
4394 2 :
4395 6 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
4396 2 :
4397 2 : tline.set_broken("test".to_owned());
4398 2 :
4399 2 : tenant
4400 2 : .gc_iteration(
4401 2 : Some(TIMELINE_ID),
4402 2 : 0x10,
4403 2 : Duration::ZERO,
4404 2 : &CancellationToken::new(),
4405 2 : &ctx,
4406 2 : )
4407 2 : .await?;
4408 2 :
4409 2 : // The branchpoints should contain all timelines, even ones marked
4410 2 : // as Broken.
4411 2 : {
4412 2 : let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
4413 2 : assert_eq!(branchpoints.len(), 1);
4414 2 : assert_eq!(branchpoints[0], Lsn(0x40));
4415 2 : }
4416 2 :
4417 2 : // You can read the key from the child branch even though the parent is
4418 2 : // Broken, as long as you don't need to access data from the parent.
4419 2 : assert_eq!(
4420 4 : newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
4421 2 : test_img(&format!("foo at {}", Lsn(0x70)))
4422 2 : );
4423 2 :
4424 2 : // This needs to traverse to the parent, and fails.
4425 2 : let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
4426 2 : assert!(err.to_string().starts_with(&format!(
4427 2 : "Bad state on timeline {}: Broken",
4428 2 : tline.timeline_id
4429 2 : )));
4430 2 :
4431 2 : Ok(())
4432 2 : }
4433 :
4434 : #[tokio::test]
4435 2 : async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
4436 2 : let (tenant, ctx) =
4437 2 : TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")?
4438 2 : .load()
4439 8 : .await;
4440 2 : let tline = tenant
4441 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4442 6 : .await?;
4443 6 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4444 2 :
4445 2 : tenant
4446 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
4447 2 : .await?;
4448 2 : let newtline = tenant
4449 2 : .get_timeline(NEW_TIMELINE_ID, true)
4450 2 : .expect("Should have a local timeline");
4451 2 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
4452 2 : tenant
4453 2 : .gc_iteration(
4454 2 : Some(TIMELINE_ID),
4455 2 : 0x10,
4456 2 : Duration::ZERO,
4457 2 : &CancellationToken::new(),
4458 2 : &ctx,
4459 2 : )
4460 2 : .await?;
4461 4 : assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
4462 2 :
4463 2 : Ok(())
4464 2 : }
4465 : #[tokio::test]
4466 2 : async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
4467 2 : let (tenant, ctx) =
4468 2 : TenantHarness::create("test_parent_keeps_data_forever_after_branching")?
4469 2 : .load()
4470 8 : .await;
4471 2 : let tline = tenant
4472 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4473 6 : .await?;
4474 6 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4475 2 :
4476 2 : tenant
4477 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
4478 2 : .await?;
4479 2 : let newtline = tenant
4480 2 : .get_timeline(NEW_TIMELINE_ID, true)
4481 2 : .expect("Should have a local timeline");
4482 2 :
4483 6 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
4484 2 :
4485 2 : // run gc on parent
4486 2 : tenant
4487 2 : .gc_iteration(
4488 2 : Some(TIMELINE_ID),
4489 2 : 0x10,
4490 2 : Duration::ZERO,
4491 2 : &CancellationToken::new(),
4492 2 : &ctx,
4493 2 : )
4494 2 : .await?;
4495 2 :
4496 2 : // Check that the data is still accessible on the branch.
4497 2 : assert_eq!(
4498 7 : newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
4499 2 : test_img(&format!("foo at {}", Lsn(0x40)))
4500 2 : );
4501 2 :
4502 2 : Ok(())
4503 2 : }
4504 :
4505 : #[tokio::test]
4506 2 : async fn timeline_load() -> anyhow::Result<()> {
4507 2 : const TEST_NAME: &str = "timeline_load";
4508 2 : let harness = TenantHarness::create(TEST_NAME)?;
4509 2 : {
4510 8 : let (tenant, ctx) = harness.load().await;
4511 2 : let tline = tenant
4512 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
4513 6 : .await?;
4514 6 : make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
4515 2 : // so that all uploads finish & we can call harness.load() below again
4516 2 : tenant
4517 2 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
4518 2 : .instrument(harness.span())
4519 2 : .await
4520 2 : .ok()
4521 2 : .unwrap();
4522 2 : }
4523 2 :
4524 7 : let (tenant, _ctx) = harness.load().await;
4525 2 : tenant
4526 2 : .get_timeline(TIMELINE_ID, true)
4527 2 : .expect("cannot load timeline");
4528 2 :
4529 2 : Ok(())
4530 2 : }
4531 :
4532 : #[tokio::test]
4533 2 : async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
4534 2 : const TEST_NAME: &str = "timeline_load_with_ancestor";
4535 2 : let harness = TenantHarness::create(TEST_NAME)?;
4536 2 : // create two timelines
4537 2 : {
4538 8 : let (tenant, ctx) = harness.load().await;
4539 2 : let tline = tenant
4540 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4541 6 : .await?;
4542 2 :
4543 6 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4544 2 :
4545 2 : let child_tline = tenant
4546 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
4547 2 : .await?;
4548 2 : child_tline.set_state(TimelineState::Active);
4549 2 :
4550 2 : let newtline = tenant
4551 2 : .get_timeline(NEW_TIMELINE_ID, true)
4552 2 : .expect("Should have a local timeline");
4553 2 :
4554 6 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
4555 2 :
4556 2 : // so that all uploads finish & we can call harness.load() below again
4557 2 : tenant
4558 2 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
4559 2 : .instrument(harness.span())
4560 4 : .await
4561 2 : .ok()
4562 2 : .unwrap();
4563 2 : }
4564 2 :
4565 2 : // check that both of them are initially unloaded
4566 9 : let (tenant, _ctx) = harness.load().await;
4567 2 :
4568 2 : // check that both, child and ancestor are loaded
4569 2 : let _child_tline = tenant
4570 2 : .get_timeline(NEW_TIMELINE_ID, true)
4571 2 : .expect("cannot get child timeline loaded");
4572 2 :
4573 2 : let _ancestor_tline = tenant
4574 2 : .get_timeline(TIMELINE_ID, true)
4575 2 : .expect("cannot get ancestor timeline loaded");
4576 2 :
4577 2 : Ok(())
4578 2 : }
4579 :
4580 : #[tokio::test]
4581 2 : async fn delta_layer_dumping() -> anyhow::Result<()> {
4582 2 : use storage_layer::AsLayerDesc;
4583 8 : let (tenant, ctx) = TenantHarness::create("test_layer_dumping")?.load().await;
4584 2 : let tline = tenant
4585 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4586 6 : .await?;
4587 6 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4588 2 :
4589 2 : let layer_map = tline.layers.read().await;
4590 2 : let level0_deltas = layer_map
4591 2 : .layer_map()
4592 2 : .get_level0_deltas()?
4593 2 : .into_iter()
4594 4 : .map(|desc| layer_map.get_from_desc(&desc))
4595 2 : .collect::<Vec<_>>();
4596 2 :
4597 2 : assert!(!level0_deltas.is_empty());
4598 2 :
4599 6 : for delta in level0_deltas {
4600 2 : // Ensure we are dumping a delta layer here
4601 4 : assert!(delta.layer_desc().is_delta);
4602 8 : delta.dump(true, &ctx).await.unwrap();
4603 2 : }
4604 2 :
4605 2 : Ok(())
4606 2 : }
4607 :
4608 : #[tokio::test]
4609 2 : async fn test_images() -> anyhow::Result<()> {
4610 8 : let (tenant, ctx) = TenantHarness::create("test_images")?.load().await;
4611 2 : let tline = tenant
4612 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
4613 6 : .await?;
4614 2 :
4615 2 : let mut writer = tline.writer().await;
4616 2 : writer
4617 2 : .put(
4618 2 : *TEST_KEY,
4619 2 : Lsn(0x10),
4620 2 : &Value::Image(test_img("foo at 0x10")),
4621 2 : &ctx,
4622 2 : )
4623 2 : .await?;
4624 2 : writer.finish_write(Lsn(0x10));
4625 2 : drop(writer);
4626 2 :
4627 2 : tline.freeze_and_flush().await?;
4628 2 : tline
4629 2 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
4630 2 : .await?;
4631 2 :
4632 2 : let mut writer = tline.writer().await;
4633 2 : writer
4634 2 : .put(
4635 2 : *TEST_KEY,
4636 2 : Lsn(0x20),
4637 2 : &Value::Image(test_img("foo at 0x20")),
4638 2 : &ctx,
4639 2 : )
4640 2 : .await?;
4641 2 : writer.finish_write(Lsn(0x20));
4642 2 : drop(writer);
4643 2 :
4644 2 : tline.freeze_and_flush().await?;
4645 2 : tline
4646 2 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
4647 2 : .await?;
4648 2 :
4649 2 : let mut writer = tline.writer().await;
4650 2 : writer
4651 2 : .put(
4652 2 : *TEST_KEY,
4653 2 : Lsn(0x30),
4654 2 : &Value::Image(test_img("foo at 0x30")),
4655 2 : &ctx,
4656 2 : )
4657 2 : .await?;
4658 2 : writer.finish_write(Lsn(0x30));
4659 2 : drop(writer);
4660 2 :
4661 2 : tline.freeze_and_flush().await?;
4662 2 : tline
4663 2 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
4664 2 : .await?;
4665 2 :
4666 2 : let mut writer = tline.writer().await;
4667 2 : writer
4668 2 : .put(
4669 2 : *TEST_KEY,
4670 2 : Lsn(0x40),
4671 2 : &Value::Image(test_img("foo at 0x40")),
4672 2 : &ctx,
4673 2 : )
4674 2 : .await?;
4675 2 : writer.finish_write(Lsn(0x40));
4676 2 : drop(writer);
4677 2 :
4678 2 : tline.freeze_and_flush().await?;
4679 2 : tline
4680 2 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
4681 2 : .await?;
4682 2 :
4683 2 : assert_eq!(
4684 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
4685 2 : test_img("foo at 0x10")
4686 2 : );
4687 2 : assert_eq!(
4688 3 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
4689 2 : test_img("foo at 0x10")
4690 2 : );
4691 2 : assert_eq!(
4692 2 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
4693 2 : test_img("foo at 0x20")
4694 2 : );
4695 2 : assert_eq!(
4696 4 : tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
4697 2 : test_img("foo at 0x30")
4698 2 : );
4699 2 : assert_eq!(
4700 4 : tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
4701 2 : test_img("foo at 0x40")
4702 2 : );
4703 2 :
4704 2 : Ok(())
4705 2 : }
4706 :
4707 4 : async fn bulk_insert_compact_gc(
4708 4 : tenant: &Tenant,
4709 4 : timeline: &Arc<Timeline>,
4710 4 : ctx: &RequestContext,
4711 4 : lsn: Lsn,
4712 4 : repeat: usize,
4713 4 : key_count: usize,
4714 4 : ) -> anyhow::Result<()> {
4715 4 : let compact = true;
4716 72774 : bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
4717 4 : }
4718 :
4719 8 : async fn bulk_insert_maybe_compact_gc(
4720 8 : tenant: &Tenant,
4721 8 : timeline: &Arc<Timeline>,
4722 8 : ctx: &RequestContext,
4723 8 : mut lsn: Lsn,
4724 8 : repeat: usize,
4725 8 : key_count: usize,
4726 8 : compact: bool,
4727 8 : ) -> anyhow::Result<()> {
4728 8 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
4729 8 : let mut blknum = 0;
4730 8 :
4731 8 : // Enforce that key range is monotonously increasing
4732 8 : let mut keyspace = KeySpaceAccum::new();
4733 8 :
4734 8 : let cancel = CancellationToken::new();
4735 8 :
4736 8 : for _ in 0..repeat {
4737 400 : for _ in 0..key_count {
4738 4000000 : test_key.field6 = blknum;
4739 4000000 : let mut writer = timeline.writer().await;
4740 4000000 : writer
4741 4000000 : .put(
4742 4000000 : test_key,
4743 4000000 : lsn,
4744 4000000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
4745 4000000 : ctx,
4746 4000000 : )
4747 2600 : .await?;
4748 4000000 : writer.finish_write(lsn);
4749 4000000 : drop(writer);
4750 4000000 :
4751 4000000 : keyspace.add_key(test_key);
4752 4000000 :
4753 4000000 : lsn = Lsn(lsn.0 + 0x10);
4754 4000000 : blknum += 1;
4755 : }
4756 :
4757 400 : timeline.freeze_and_flush().await?;
4758 400 : if compact {
4759 : // this requires timeline to be &Arc<Timeline>
4760 40174 : timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
4761 200 : }
4762 :
4763 : // this doesn't really need to use the timeline_id target, but it is closer to what it
4764 : // originally was.
4765 400 : let res = tenant
4766 400 : .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
4767 400 : .await?;
4768 :
4769 400 : assert_eq!(res.layers_removed, 0, "this never removes anything");
4770 : }
4771 :
4772 8 : Ok(())
4773 8 : }
4774 :
4775 : //
4776 : // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
4777 : // Repeat 50 times.
4778 : //
4779 : #[tokio::test]
4780 2 : async fn test_bulk_insert() -> anyhow::Result<()> {
4781 2 : let harness = TenantHarness::create("test_bulk_insert")?;
4782 8 : let (tenant, ctx) = harness.load().await;
4783 2 : let tline = tenant
4784 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
4785 6 : .await?;
4786 2 :
4787 2 : let lsn = Lsn(0x10);
4788 36387 : bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
4789 2 :
4790 2 : Ok(())
4791 2 : }
4792 :
4793 : // Test the vectored get real implementation against a simple sequential implementation.
4794 : //
4795 : // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
4796 : // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
4797 : // grow to the right on the X axis.
4798 : // [Delta]
4799 : // [Delta]
4800 : // [Delta]
4801 : // [Delta]
4802 : // ------------ Image ---------------
4803 : //
4804 : // After layer generation we pick the ranges to query as follows:
4805 : // 1. The beginning of each delta layer
4806 : // 2. At the seam between two adjacent delta layers
4807 : //
4808 : // There's one major downside to this test: delta layers only contains images,
4809 : // so the search can stop at the first delta layer and doesn't traverse any deeper.
4810 : #[tokio::test]
4811 2 : async fn test_get_vectored() -> anyhow::Result<()> {
4812 2 : let harness = TenantHarness::create("test_get_vectored")?;
4813 8 : let (tenant, ctx) = harness.load().await;
4814 2 : let tline = tenant
4815 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
4816 6 : .await?;
4817 2 :
4818 2 : let lsn = Lsn(0x10);
4819 36387 : bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
4820 2 :
4821 2 : let guard = tline.layers.read().await;
4822 2 : guard.layer_map().dump(true, &ctx).await?;
4823 2 :
4824 2 : let mut reads = Vec::new();
4825 2 : let mut prev = None;
4826 12 : guard.layer_map().iter_historic_layers().for_each(|desc| {
4827 12 : if !desc.is_delta() {
4828 2 : prev = Some(desc.clone());
4829 2 : return;
4830 10 : }
4831 10 :
4832 10 : let start = desc.key_range.start;
4833 10 : let end = desc
4834 10 : .key_range
4835 10 : .start
4836 10 : .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
4837 10 : reads.push(KeySpace {
4838 10 : ranges: vec![start..end],
4839 10 : });
4840 2 :
4841 10 : if let Some(prev) = &prev {
4842 10 : if !prev.is_delta() {
4843 10 : return;
4844 2 : }
4845 0 :
4846 0 : let first_range = Key {
4847 0 : field6: prev.key_range.end.field6 - 4,
4848 0 : ..prev.key_range.end
4849 0 : }..prev.key_range.end;
4850 0 :
4851 0 : let second_range = desc.key_range.start..Key {
4852 0 : field6: desc.key_range.start.field6 + 4,
4853 0 : ..desc.key_range.start
4854 0 : };
4855 0 :
4856 0 : reads.push(KeySpace {
4857 0 : ranges: vec![first_range, second_range],
4858 0 : });
4859 2 : };
4860 2 :
4861 2 : prev = Some(desc.clone());
4862 12 : });
4863 2 :
4864 2 : drop(guard);
4865 2 :
4866 2 : // Pick a big LSN such that we query over all the changes.
4867 2 : let reads_lsn = Lsn(u64::MAX - 1);
4868 2 :
4869 12 : for read in reads {
4870 10 : info!("Doing vectored read on {:?}", read);
4871 2 :
4872 10 : let vectored_res = tline
4873 10 : .get_vectored_impl(
4874 10 : read.clone(),
4875 10 : reads_lsn,
4876 10 : &mut ValuesReconstructState::new(),
4877 10 : &ctx,
4878 10 : )
4879 25 : .await;
4880 10 : tline
4881 10 : .validate_get_vectored_impl(&vectored_res, read, reads_lsn, &ctx)
4882 19 : .await;
4883 2 : }
4884 2 :
4885 2 : Ok(())
4886 2 : }
4887 :
4888 : #[tokio::test]
4889 2 : async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
4890 2 : let harness = TenantHarness::create("test_get_vectored_aux_files")?;
4891 2 :
4892 8 : let (tenant, ctx) = harness.load().await;
4893 2 : let tline = tenant
4894 2 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
4895 2 : .await?;
4896 2 : let tline = tline.raw_timeline().unwrap();
4897 2 :
4898 2 : let mut modification = tline.begin_modification(Lsn(0x1000));
4899 2 : modification.put_file("foo/bar1", b"content1", &ctx).await?;
4900 2 : modification.set_lsn(Lsn(0x1008))?;
4901 2 : modification.put_file("foo/bar2", b"content2", &ctx).await?;
4902 2 : modification.commit(&ctx).await?;
4903 2 :
4904 2 : let child_timeline_id = TimelineId::generate();
4905 2 : tenant
4906 2 : .branch_timeline_test(
4907 2 : tline,
4908 2 : child_timeline_id,
4909 2 : Some(tline.get_last_record_lsn()),
4910 2 : &ctx,
4911 2 : )
4912 2 : .await?;
4913 2 :
4914 2 : let child_timeline = tenant
4915 2 : .get_timeline(child_timeline_id, true)
4916 2 : .expect("Should have the branched timeline");
4917 2 :
4918 2 : let aux_keyspace = KeySpace {
4919 2 : ranges: vec![NON_INHERITED_RANGE],
4920 2 : };
4921 2 : let read_lsn = child_timeline.get_last_record_lsn();
4922 2 :
4923 2 : let vectored_res = child_timeline
4924 2 : .get_vectored_impl(
4925 2 : aux_keyspace.clone(),
4926 2 : read_lsn,
4927 2 : &mut ValuesReconstructState::new(),
4928 2 : &ctx,
4929 2 : )
4930 2 : .await;
4931 2 :
4932 2 : child_timeline
4933 2 : .validate_get_vectored_impl(&vectored_res, aux_keyspace, read_lsn, &ctx)
4934 2 : .await;
4935 2 :
4936 2 : let images = vectored_res?;
4937 2 : assert!(images.is_empty());
4938 2 : Ok(())
4939 2 : }
4940 :
4941 : // Test that vectored get handles layer gaps correctly
4942 : // by advancing into the next ancestor timeline if required.
4943 : //
4944 : // The test generates timelines that look like the diagram below.
4945 : // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
4946 : // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
4947 : //
4948 : // ```
4949 : //-------------------------------+
4950 : // ... |
4951 : // [ L1 ] |
4952 : // [ / L1 ] | Child Timeline
4953 : // ... |
4954 : // ------------------------------+
4955 : // [ X L1 ] | Parent Timeline
4956 : // ------------------------------+
4957 : // ```
4958 : #[tokio::test]
4959 2 : async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
4960 2 : let tenant_conf = TenantConf {
4961 2 : // Make compaction deterministic
4962 2 : gc_period: Duration::ZERO,
4963 2 : compaction_period: Duration::ZERO,
4964 2 : // Encourage creation of L1 layers
4965 2 : checkpoint_distance: 16 * 1024,
4966 2 : compaction_target_size: 8 * 1024,
4967 2 : ..TenantConf::default()
4968 2 : };
4969 2 :
4970 2 : let harness = TenantHarness::create_custom(
4971 2 : "test_get_vectored_key_gap",
4972 2 : tenant_conf,
4973 2 : TenantId::generate(),
4974 2 : ShardIdentity::unsharded(),
4975 2 : Generation::new(0xdeadbeef),
4976 2 : )?;
4977 8 : let (tenant, ctx) = harness.load().await;
4978 2 :
4979 2 : let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
4980 2 : let gap_at_key = current_key.add(100);
4981 2 : let mut current_lsn = Lsn(0x10);
4982 2 :
4983 2 : const KEY_COUNT: usize = 10_000;
4984 2 :
4985 2 : let timeline_id = TimelineId::generate();
4986 2 : let current_timeline = tenant
4987 2 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
4988 6 : .await?;
4989 2 :
4990 2 : current_lsn += 0x100;
4991 2 :
4992 2 : let mut writer = current_timeline.writer().await;
4993 2 : writer
4994 2 : .put(
4995 2 : gap_at_key,
4996 2 : current_lsn,
4997 2 : &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
4998 2 : &ctx,
4999 2 : )
5000 2 : .await?;
5001 2 : writer.finish_write(current_lsn);
5002 2 : drop(writer);
5003 2 :
5004 2 : let mut latest_lsns = HashMap::new();
5005 2 : latest_lsns.insert(gap_at_key, current_lsn);
5006 2 :
5007 2 : current_timeline.freeze_and_flush().await?;
5008 2 :
5009 2 : let child_timeline_id = TimelineId::generate();
5010 2 :
5011 2 : tenant
5012 2 : .branch_timeline_test(
5013 2 : ¤t_timeline,
5014 2 : child_timeline_id,
5015 2 : Some(current_lsn),
5016 2 : &ctx,
5017 2 : )
5018 2 : .await?;
5019 2 : let child_timeline = tenant
5020 2 : .get_timeline(child_timeline_id, true)
5021 2 : .expect("Should have the branched timeline");
5022 2 :
5023 20002 : for i in 0..KEY_COUNT {
5024 20000 : if current_key == gap_at_key {
5025 2 : current_key = current_key.next();
5026 2 : continue;
5027 19998 : }
5028 19998 :
5029 19998 : current_lsn += 0x10;
5030 2 :
5031 19998 : let mut writer = child_timeline.writer().await;
5032 19998 : writer
5033 19998 : .put(
5034 19998 : current_key,
5035 19998 : current_lsn,
5036 19998 : &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
5037 19998 : &ctx,
5038 19998 : )
5039 73 : .await?;
5040 19998 : writer.finish_write(current_lsn);
5041 19998 : drop(writer);
5042 19998 :
5043 19998 : latest_lsns.insert(current_key, current_lsn);
5044 19998 : current_key = current_key.next();
5045 19998 :
5046 19998 : // Flush every now and then to encourage layer file creation.
5047 19998 : if i % 500 == 0 {
5048 44 : child_timeline.freeze_and_flush().await?;
5049 19958 : }
5050 2 : }
5051 2 :
5052 2 : child_timeline.freeze_and_flush().await?;
5053 2 : let mut flags = EnumSet::new();
5054 2 : flags.insert(CompactFlags::ForceRepartition);
5055 2 : child_timeline
5056 2 : .compact(&CancellationToken::new(), flags, &ctx)
5057 2184 : .await?;
5058 2 :
5059 2 : let key_near_end = {
5060 2 : let mut tmp = current_key;
5061 2 : tmp.field6 -= 10;
5062 2 : tmp
5063 2 : };
5064 2 :
5065 2 : let key_near_gap = {
5066 2 : let mut tmp = gap_at_key;
5067 2 : tmp.field6 -= 10;
5068 2 : tmp
5069 2 : };
5070 2 :
5071 2 : let read = KeySpace {
5072 2 : ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
5073 2 : };
5074 2 : let results = child_timeline
5075 2 : .get_vectored_impl(
5076 2 : read.clone(),
5077 2 : current_lsn,
5078 2 : &mut ValuesReconstructState::new(),
5079 2 : &ctx,
5080 2 : )
5081 15 : .await?;
5082 2 :
5083 44 : for (key, img_res) in results {
5084 42 : let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
5085 42 : assert_eq!(img_res?, expected);
5086 2 : }
5087 2 :
5088 2 : Ok(())
5089 2 : }
5090 :
5091 : // Test that vectored get descends into ancestor timelines correctly and
5092 : // does not return an image that's newer than requested.
5093 : //
5094 : // The diagram below ilustrates an interesting case. We have a parent timeline
5095 : // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
5096 : // from the child timeline, so the parent timeline must be visited. When advacing into
5097 : // the child timeline, the read path needs to remember what the requested Lsn was in
5098 : // order to avoid returning an image that's too new. The test below constructs such
5099 : // a timeline setup and does a few queries around the Lsn of each page image.
5100 : // ```
5101 : // LSN
5102 : // ^
5103 : // |
5104 : // |
5105 : // 500 | --------------------------------------> branch point
5106 : // 400 | X
5107 : // 300 | X
5108 : // 200 | --------------------------------------> requested lsn
5109 : // 100 | X
5110 : // |---------------------------------------> Key
5111 : // |
5112 : // ------> requested key
5113 : //
5114 : // Legend:
5115 : // * X - page images
5116 : // ```
5117 : #[tokio::test]
5118 2 : async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
5119 2 : let harness = TenantHarness::create("test_get_vectored_on_lsn_axis")?;
5120 8 : let (tenant, ctx) = harness.load().await;
5121 2 :
5122 2 : let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5123 2 : let end_key = start_key.add(1000);
5124 2 : let child_gap_at_key = start_key.add(500);
5125 2 : let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
5126 2 :
5127 2 : let mut current_lsn = Lsn(0x10);
5128 2 :
5129 2 : let timeline_id = TimelineId::generate();
5130 2 : let parent_timeline = tenant
5131 2 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
5132 6 : .await?;
5133 2 :
5134 2 : current_lsn += 0x100;
5135 2 :
5136 8 : for _ in 0..3 {
5137 6 : let mut key = start_key;
5138 6006 : while key < end_key {
5139 6000 : current_lsn += 0x10;
5140 6000 :
5141 6000 : let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
5142 2 :
5143 6000 : let mut writer = parent_timeline.writer().await;
5144 6000 : writer
5145 6000 : .put(
5146 6000 : key,
5147 6000 : current_lsn,
5148 6000 : &Value::Image(test_img(&image_value)),
5149 6000 : &ctx,
5150 6000 : )
5151 6 : .await?;
5152 6000 : writer.finish_write(current_lsn);
5153 6000 :
5154 6000 : if key == child_gap_at_key {
5155 6 : parent_gap_lsns.insert(current_lsn, image_value);
5156 5994 : }
5157 2 :
5158 6000 : key = key.next();
5159 2 : }
5160 2 :
5161 6 : parent_timeline.freeze_and_flush().await?;
5162 2 : }
5163 2 :
5164 2 : let child_timeline_id = TimelineId::generate();
5165 2 :
5166 2 : let child_timeline = tenant
5167 2 : .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
5168 2 : .await?;
5169 2 :
5170 2 : let mut key = start_key;
5171 2002 : while key < end_key {
5172 2000 : if key == child_gap_at_key {
5173 2 : key = key.next();
5174 2 : continue;
5175 1998 : }
5176 1998 :
5177 1998 : current_lsn += 0x10;
5178 2 :
5179 1998 : let mut writer = child_timeline.writer().await;
5180 1998 : writer
5181 1998 : .put(
5182 1998 : key,
5183 1998 : current_lsn,
5184 1998 : &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
5185 1998 : &ctx,
5186 1998 : )
5187 17 : .await?;
5188 1998 : writer.finish_write(current_lsn);
5189 1998 :
5190 1998 : key = key.next();
5191 2 : }
5192 2 :
5193 2 : child_timeline.freeze_and_flush().await?;
5194 2 :
5195 2 : let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
5196 2 : let mut query_lsns = Vec::new();
5197 6 : for image_lsn in parent_gap_lsns.keys().rev() {
5198 36 : for offset in lsn_offsets {
5199 30 : query_lsns.push(Lsn(image_lsn
5200 30 : .0
5201 30 : .checked_add_signed(offset)
5202 30 : .expect("Shouldn't overflow")));
5203 30 : }
5204 2 : }
5205 2 :
5206 32 : for query_lsn in query_lsns {
5207 30 : let results = child_timeline
5208 30 : .get_vectored_impl(
5209 30 : KeySpace {
5210 30 : ranges: vec![child_gap_at_key..child_gap_at_key.next()],
5211 30 : },
5212 30 : query_lsn,
5213 30 : &mut ValuesReconstructState::new(),
5214 30 : &ctx,
5215 30 : )
5216 29 : .await;
5217 2 :
5218 30 : let expected_item = parent_gap_lsns
5219 30 : .iter()
5220 30 : .rev()
5221 68 : .find(|(lsn, _)| **lsn <= query_lsn);
5222 30 :
5223 30 : info!(
5224 2 : "Doing vectored read at LSN {}. Expecting image to be: {:?}",
5225 2 : query_lsn, expected_item
5226 2 : );
5227 2 :
5228 30 : match expected_item {
5229 26 : Some((_, img_value)) => {
5230 26 : let key_results = results.expect("No vectored get error expected");
5231 26 : let key_result = &key_results[&child_gap_at_key];
5232 26 : let returned_img = key_result
5233 26 : .as_ref()
5234 26 : .expect("No page reconstruct error expected");
5235 26 :
5236 26 : info!(
5237 2 : "Vectored read at LSN {} returned image {}",
5238 0 : query_lsn,
5239 0 : std::str::from_utf8(returned_img)?
5240 2 : );
5241 26 : assert_eq!(*returned_img, test_img(img_value));
5242 2 : }
5243 2 : None => {
5244 4 : assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
5245 2 : }
5246 2 : }
5247 2 : }
5248 2 :
5249 2 : Ok(())
5250 2 : }
5251 :
5252 : #[tokio::test]
5253 2 : async fn test_random_updates() -> anyhow::Result<()> {
5254 2 : let names_algorithms = [
5255 2 : ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
5256 2 : ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
5257 2 : ];
5258 6 : for (name, algorithm) in names_algorithms {
5259 17755 : test_random_updates_algorithm(name, algorithm).await?;
5260 2 : }
5261 2 : Ok(())
5262 2 : }
5263 :
5264 4 : async fn test_random_updates_algorithm(
5265 4 : name: &'static str,
5266 4 : compaction_algorithm: CompactionAlgorithm,
5267 4 : ) -> anyhow::Result<()> {
5268 4 : let mut harness = TenantHarness::create(name)?;
5269 4 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
5270 4 : kind: compaction_algorithm,
5271 4 : };
5272 16 : let (tenant, ctx) = harness.load().await;
5273 4 : let tline = tenant
5274 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5275 11 : .await?;
5276 :
5277 : const NUM_KEYS: usize = 1000;
5278 4 : let cancel = CancellationToken::new();
5279 4 :
5280 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5281 4 : let mut test_key_end = test_key;
5282 4 : test_key_end.field6 = NUM_KEYS as u32;
5283 4 : tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
5284 4 :
5285 4 : let mut keyspace = KeySpaceAccum::new();
5286 4 :
5287 4 : // Track when each page was last modified. Used to assert that
5288 4 : // a read sees the latest page version.
5289 4 : let mut updated = [Lsn(0); NUM_KEYS];
5290 4 :
5291 4 : let mut lsn = Lsn(0x10);
5292 : #[allow(clippy::needless_range_loop)]
5293 4004 : for blknum in 0..NUM_KEYS {
5294 4000 : lsn = Lsn(lsn.0 + 0x10);
5295 4000 : test_key.field6 = blknum as u32;
5296 4000 : let mut writer = tline.writer().await;
5297 4000 : writer
5298 4000 : .put(
5299 4000 : test_key,
5300 4000 : lsn,
5301 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5302 4000 : &ctx,
5303 4000 : )
5304 4 : .await?;
5305 4000 : writer.finish_write(lsn);
5306 4000 : updated[blknum] = lsn;
5307 4000 : drop(writer);
5308 4000 :
5309 4000 : keyspace.add_key(test_key);
5310 : }
5311 :
5312 204 : for _ in 0..50 {
5313 200200 : for _ in 0..NUM_KEYS {
5314 200000 : lsn = Lsn(lsn.0 + 0x10);
5315 200000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
5316 200000 : test_key.field6 = blknum as u32;
5317 200000 : let mut writer = tline.writer().await;
5318 200000 : writer
5319 200000 : .put(
5320 200000 : test_key,
5321 200000 : lsn,
5322 200000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5323 200000 : &ctx,
5324 200000 : )
5325 198 : .await?;
5326 200000 : writer.finish_write(lsn);
5327 200000 : drop(writer);
5328 200000 : updated[blknum] = lsn;
5329 : }
5330 :
5331 : // Read all the blocks
5332 200000 : for (blknum, last_lsn) in updated.iter().enumerate() {
5333 200000 : test_key.field6 = blknum as u32;
5334 200000 : assert_eq!(
5335 200000 : tline.get(test_key, lsn, &ctx).await?,
5336 200000 : test_img(&format!("{} at {}", blknum, last_lsn))
5337 : );
5338 : }
5339 :
5340 : // Perform a cycle of flush, and GC
5341 203 : tline.freeze_and_flush().await?;
5342 200 : tenant
5343 200 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
5344 197 : .await?;
5345 : }
5346 :
5347 4 : Ok(())
5348 4 : }
5349 :
5350 : #[tokio::test]
5351 2 : async fn test_traverse_branches() -> anyhow::Result<()> {
5352 2 : let (tenant, ctx) = TenantHarness::create("test_traverse_branches")?
5353 2 : .load()
5354 8 : .await;
5355 2 : let mut tline = tenant
5356 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5357 6 : .await?;
5358 2 :
5359 2 : const NUM_KEYS: usize = 1000;
5360 2 :
5361 2 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5362 2 :
5363 2 : let mut keyspace = KeySpaceAccum::new();
5364 2 :
5365 2 : let cancel = CancellationToken::new();
5366 2 :
5367 2 : // Track when each page was last modified. Used to assert that
5368 2 : // a read sees the latest page version.
5369 2 : let mut updated = [Lsn(0); NUM_KEYS];
5370 2 :
5371 2 : let mut lsn = Lsn(0x10);
5372 2 : #[allow(clippy::needless_range_loop)]
5373 2002 : for blknum in 0..NUM_KEYS {
5374 2000 : lsn = Lsn(lsn.0 + 0x10);
5375 2000 : test_key.field6 = blknum as u32;
5376 2000 : let mut writer = tline.writer().await;
5377 2000 : writer
5378 2000 : .put(
5379 2000 : test_key,
5380 2000 : lsn,
5381 2000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5382 2000 : &ctx,
5383 2000 : )
5384 2 : .await?;
5385 2000 : writer.finish_write(lsn);
5386 2000 : updated[blknum] = lsn;
5387 2000 : drop(writer);
5388 2000 :
5389 2000 : keyspace.add_key(test_key);
5390 2 : }
5391 2 :
5392 102 : for _ in 0..50 {
5393 100 : let new_tline_id = TimelineId::generate();
5394 100 : tenant
5395 100 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
5396 2 : .await?;
5397 100 : tline = tenant
5398 100 : .get_timeline(new_tline_id, true)
5399 100 : .expect("Should have the branched timeline");
5400 2 :
5401 100100 : for _ in 0..NUM_KEYS {
5402 100000 : lsn = Lsn(lsn.0 + 0x10);
5403 100000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
5404 100000 : test_key.field6 = blknum as u32;
5405 100000 : let mut writer = tline.writer().await;
5406 100000 : writer
5407 100000 : .put(
5408 100000 : test_key,
5409 100000 : lsn,
5410 100000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5411 100000 : &ctx,
5412 100000 : )
5413 851 : .await?;
5414 100000 : println!("updating {} at {}", blknum, lsn);
5415 100000 : writer.finish_write(lsn);
5416 100000 : drop(writer);
5417 100000 : updated[blknum] = lsn;
5418 2 : }
5419 2 :
5420 2 : // Read all the blocks
5421 100000 : for (blknum, last_lsn) in updated.iter().enumerate() {
5422 100000 : test_key.field6 = blknum as u32;
5423 100000 : assert_eq!(
5424 100000 : tline.get(test_key, lsn, &ctx).await?,
5425 100000 : test_img(&format!("{} at {}", blknum, last_lsn))
5426 2 : );
5427 2 : }
5428 2 :
5429 2 : // Perform a cycle of flush, compact, and GC
5430 103 : tline.freeze_and_flush().await?;
5431 13144 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
5432 100 : tenant
5433 100 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
5434 98 : .await?;
5435 2 : }
5436 2 :
5437 2 : Ok(())
5438 2 : }
5439 :
5440 : #[tokio::test]
5441 2 : async fn test_traverse_ancestors() -> anyhow::Result<()> {
5442 2 : let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")?
5443 2 : .load()
5444 8 : .await;
5445 2 : let mut tline = tenant
5446 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5447 6 : .await?;
5448 2 :
5449 2 : const NUM_KEYS: usize = 100;
5450 2 : const NUM_TLINES: usize = 50;
5451 2 :
5452 2 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5453 2 : // Track page mutation lsns across different timelines.
5454 2 : let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
5455 2 :
5456 2 : let mut lsn = Lsn(0x10);
5457 2 :
5458 2 : #[allow(clippy::needless_range_loop)]
5459 102 : for idx in 0..NUM_TLINES {
5460 100 : let new_tline_id = TimelineId::generate();
5461 100 : tenant
5462 100 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
5463 2 : .await?;
5464 100 : tline = tenant
5465 100 : .get_timeline(new_tline_id, true)
5466 100 : .expect("Should have the branched timeline");
5467 2 :
5468 10100 : for _ in 0..NUM_KEYS {
5469 10000 : lsn = Lsn(lsn.0 + 0x10);
5470 10000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
5471 10000 : test_key.field6 = blknum as u32;
5472 10000 : let mut writer = tline.writer().await;
5473 10000 : writer
5474 10000 : .put(
5475 10000 : test_key,
5476 10000 : lsn,
5477 10000 : &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
5478 10000 : &ctx,
5479 10000 : )
5480 88 : .await?;
5481 10000 : println!("updating [{}][{}] at {}", idx, blknum, lsn);
5482 10000 : writer.finish_write(lsn);
5483 10000 : drop(writer);
5484 10000 : updated[idx][blknum] = lsn;
5485 2 : }
5486 2 : }
5487 2 :
5488 2 : // Read pages from leaf timeline across all ancestors.
5489 100 : for (idx, lsns) in updated.iter().enumerate() {
5490 10000 : for (blknum, lsn) in lsns.iter().enumerate() {
5491 2 : // Skip empty mutations.
5492 10000 : if lsn.0 == 0 {
5493 3717 : continue;
5494 6283 : }
5495 6283 : println!("checking [{idx}][{blknum}] at {lsn}");
5496 6283 : test_key.field6 = blknum as u32;
5497 6283 : assert_eq!(
5498 6283 : tline.get(test_key, *lsn, &ctx).await?,
5499 6283 : test_img(&format!("{idx} {blknum} at {lsn}"))
5500 2 : );
5501 2 : }
5502 2 : }
5503 2 : Ok(())
5504 2 : }
5505 :
5506 : #[tokio::test]
5507 2 : async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
5508 2 : let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")?
5509 2 : .load()
5510 8 : .await;
5511 2 :
5512 2 : let initdb_lsn = Lsn(0x20);
5513 2 : let utline = tenant
5514 2 : .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
5515 2 : .await?;
5516 2 : let tline = utline.raw_timeline().unwrap();
5517 2 :
5518 2 : // Spawn flush loop now so that we can set the `expect_initdb_optimization`
5519 2 : tline.maybe_spawn_flush_loop();
5520 2 :
5521 2 : // Make sure the timeline has the minimum set of required keys for operation.
5522 2 : // The only operation you can always do on an empty timeline is to `put` new data.
5523 2 : // Except if you `put` at `initdb_lsn`.
5524 2 : // In that case, there's an optimization to directly create image layers instead of delta layers.
5525 2 : // It uses `repartition()`, which assumes some keys to be present.
5526 2 : // Let's make sure the test timeline can handle that case.
5527 2 : {
5528 2 : let mut state = tline.flush_loop_state.lock().unwrap();
5529 2 : assert_eq!(
5530 2 : timeline::FlushLoopState::Running {
5531 2 : expect_initdb_optimization: false,
5532 2 : initdb_optimization_count: 0,
5533 2 : },
5534 2 : *state
5535 2 : );
5536 2 : *state = timeline::FlushLoopState::Running {
5537 2 : expect_initdb_optimization: true,
5538 2 : initdb_optimization_count: 0,
5539 2 : };
5540 2 : }
5541 2 :
5542 2 : // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
5543 2 : // As explained above, the optimization requires some keys to be present.
5544 2 : // As per `create_empty_timeline` documentation, use init_empty to set them.
5545 2 : // This is what `create_test_timeline` does, by the way.
5546 2 : let mut modification = tline.begin_modification(initdb_lsn);
5547 2 : modification
5548 2 : .init_empty_test_timeline()
5549 2 : .context("init_empty_test_timeline")?;
5550 2 : modification
5551 2 : .commit(&ctx)
5552 2 : .await
5553 2 : .context("commit init_empty_test_timeline modification")?;
5554 2 :
5555 2 : // Do the flush. The flush code will check the expectations that we set above.
5556 2 : tline.freeze_and_flush().await?;
5557 2 :
5558 2 : // assert freeze_and_flush exercised the initdb optimization
5559 2 : {
5560 2 : let state = tline.flush_loop_state.lock().unwrap();
5561 2 : let timeline::FlushLoopState::Running {
5562 2 : expect_initdb_optimization,
5563 2 : initdb_optimization_count,
5564 2 : } = *state
5565 2 : else {
5566 2 : panic!("unexpected state: {:?}", *state);
5567 2 : };
5568 2 : assert!(expect_initdb_optimization);
5569 2 : assert!(initdb_optimization_count > 0);
5570 2 : }
5571 2 : Ok(())
5572 2 : }
5573 :
5574 : #[tokio::test]
5575 2 : async fn test_create_guard_crash() -> anyhow::Result<()> {
5576 2 : let name = "test_create_guard_crash";
5577 2 : let harness = TenantHarness::create(name)?;
5578 2 : {
5579 8 : let (tenant, ctx) = harness.load().await;
5580 2 : let tline = tenant
5581 2 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
5582 2 : .await?;
5583 2 : // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
5584 2 : let raw_tline = tline.raw_timeline().unwrap();
5585 2 : raw_tline
5586 2 : .shutdown(super::timeline::ShutdownMode::Hard)
5587 2 : .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
5588 2 : .await;
5589 2 : std::mem::forget(tline);
5590 2 : }
5591 2 :
5592 8 : let (tenant, _) = harness.load().await;
5593 2 : match tenant.get_timeline(TIMELINE_ID, false) {
5594 2 : Ok(_) => panic!("timeline should've been removed during load"),
5595 2 : Err(e) => {
5596 2 : assert_eq!(
5597 2 : e,
5598 2 : GetTimelineError::NotFound {
5599 2 : tenant_id: tenant.tenant_shard_id,
5600 2 : timeline_id: TIMELINE_ID,
5601 2 : }
5602 2 : )
5603 2 : }
5604 2 : }
5605 2 :
5606 2 : assert!(!harness
5607 2 : .conf
5608 2 : .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
5609 2 : .exists());
5610 2 :
5611 2 : Ok(())
5612 2 : }
5613 :
5614 : #[tokio::test]
5615 2 : async fn test_read_at_max_lsn() -> anyhow::Result<()> {
5616 2 : let names_algorithms = [
5617 2 : ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
5618 2 : ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
5619 2 : ];
5620 6 : for (name, algorithm) in names_algorithms {
5621 32937 : test_read_at_max_lsn_algorithm(name, algorithm).await?;
5622 2 : }
5623 2 : Ok(())
5624 2 : }
5625 :
5626 4 : async fn test_read_at_max_lsn_algorithm(
5627 4 : name: &'static str,
5628 4 : compaction_algorithm: CompactionAlgorithm,
5629 4 : ) -> anyhow::Result<()> {
5630 4 : let mut harness = TenantHarness::create(name)?;
5631 4 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
5632 4 : kind: compaction_algorithm,
5633 4 : };
5634 16 : let (tenant, ctx) = harness.load().await;
5635 4 : let tline = tenant
5636 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
5637 11 : .await?;
5638 :
5639 4 : let lsn = Lsn(0x10);
5640 4 : let compact = false;
5641 32600 : bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
5642 :
5643 4 : let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5644 4 : let read_lsn = Lsn(u64::MAX - 1);
5645 :
5646 310 : let result = tline.get(test_key, read_lsn, &ctx).await;
5647 4 : assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
5648 :
5649 4 : Ok(())
5650 4 : }
5651 :
5652 : #[tokio::test]
5653 2 : async fn test_metadata_scan() -> anyhow::Result<()> {
5654 2 : let harness = TenantHarness::create("test_metadata_scan")?;
5655 8 : let (tenant, ctx) = harness.load().await;
5656 2 : let tline = tenant
5657 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5658 5 : .await?;
5659 2 :
5660 2 : const NUM_KEYS: usize = 1000;
5661 2 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
5662 2 :
5663 2 : let cancel = CancellationToken::new();
5664 2 :
5665 2 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
5666 2 : base_key.field1 = AUX_KEY_PREFIX;
5667 2 : let mut test_key = base_key;
5668 2 :
5669 2 : // Track when each page was last modified. Used to assert that
5670 2 : // a read sees the latest page version.
5671 2 : let mut updated = [Lsn(0); NUM_KEYS];
5672 2 :
5673 2 : let mut lsn = Lsn(0x10);
5674 2 : #[allow(clippy::needless_range_loop)]
5675 2002 : for blknum in 0..NUM_KEYS {
5676 2000 : lsn = Lsn(lsn.0 + 0x10);
5677 2000 : test_key.field6 = (blknum * STEP) as u32;
5678 2000 : let mut writer = tline.writer().await;
5679 2000 : writer
5680 2000 : .put(
5681 2000 : test_key,
5682 2000 : lsn,
5683 2000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5684 2000 : &ctx,
5685 2000 : )
5686 2 : .await?;
5687 2000 : writer.finish_write(lsn);
5688 2000 : updated[blknum] = lsn;
5689 2000 : drop(writer);
5690 2 : }
5691 2 :
5692 2 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
5693 2 :
5694 24 : for iter in 0..=10 {
5695 2 : // Read all the blocks
5696 22000 : for (blknum, last_lsn) in updated.iter().enumerate() {
5697 22000 : test_key.field6 = (blknum * STEP) as u32;
5698 22000 : assert_eq!(
5699 22000 : tline.get(test_key, lsn, &ctx).await?,
5700 22000 : test_img(&format!("{} at {}", blknum, last_lsn))
5701 2 : );
5702 2 : }
5703 2 :
5704 22 : let mut cnt = 0;
5705 22000 : for (key, value) in tline
5706 22 : .get_vectored_impl(
5707 22 : keyspace.clone(),
5708 22 : lsn,
5709 22 : &mut ValuesReconstructState::default(),
5710 22 : &ctx,
5711 22 : )
5712 5616 : .await?
5713 2 : {
5714 22000 : let blknum = key.field6 as usize;
5715 22000 : let value = value?;
5716 22000 : assert!(blknum % STEP == 0);
5717 22000 : let blknum = blknum / STEP;
5718 22000 : assert_eq!(
5719 22000 : value,
5720 22000 : test_img(&format!("{} at {}", blknum, updated[blknum]))
5721 22000 : );
5722 22000 : cnt += 1;
5723 2 : }
5724 2 :
5725 22 : assert_eq!(cnt, NUM_KEYS);
5726 2 :
5727 22022 : for _ in 0..NUM_KEYS {
5728 22000 : lsn = Lsn(lsn.0 + 0x10);
5729 22000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
5730 22000 : test_key.field6 = (blknum * STEP) as u32;
5731 22000 : let mut writer = tline.writer().await;
5732 22000 : writer
5733 22000 : .put(
5734 22000 : test_key,
5735 22000 : lsn,
5736 22000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5737 22000 : &ctx,
5738 22000 : )
5739 156 : .await?;
5740 22000 : writer.finish_write(lsn);
5741 22000 : drop(writer);
5742 22000 : updated[blknum] = lsn;
5743 2 : }
5744 2 :
5745 2 : // Perform two cycles of flush, compact, and GC
5746 66 : for round in 0..2 {
5747 44 : tline.freeze_and_flush().await?;
5748 44 : tline
5749 44 : .compact(
5750 44 : &cancel,
5751 44 : if iter % 5 == 0 && round == 0 {
5752 6 : let mut flags = EnumSet::new();
5753 6 : flags.insert(CompactFlags::ForceImageLayerCreation);
5754 6 : flags.insert(CompactFlags::ForceRepartition);
5755 6 : flags
5756 2 : } else {
5757 38 : EnumSet::empty()
5758 2 : },
5759 44 : &ctx,
5760 2 : )
5761 8908 : .await?;
5762 44 : tenant
5763 44 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
5764 44 : .await?;
5765 2 : }
5766 2 : }
5767 2 :
5768 2 : Ok(())
5769 2 : }
5770 :
5771 : #[tokio::test]
5772 2 : async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
5773 2 : let harness = TenantHarness::create("test_metadata_compaction_trigger")?;
5774 8 : let (tenant, ctx) = harness.load().await;
5775 2 : let tline = tenant
5776 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5777 5 : .await?;
5778 2 :
5779 2 : let cancel = CancellationToken::new();
5780 2 :
5781 2 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
5782 2 : base_key.field1 = AUX_KEY_PREFIX;
5783 2 : let test_key = base_key;
5784 2 : let mut lsn = Lsn(0x10);
5785 2 :
5786 42 : for _ in 0..20 {
5787 40 : lsn = Lsn(lsn.0 + 0x10);
5788 40 : let mut writer = tline.writer().await;
5789 40 : writer
5790 40 : .put(
5791 40 : test_key,
5792 40 : lsn,
5793 40 : &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
5794 40 : &ctx,
5795 40 : )
5796 20 : .await?;
5797 40 : writer.finish_write(lsn);
5798 40 : drop(writer);
5799 40 : tline.freeze_and_flush().await?; // force create a delta layer
5800 2 : }
5801 2 :
5802 2 : let before_num_l0_delta_files = tline
5803 2 : .layers
5804 2 : .read()
5805 2 : .await
5806 2 : .layer_map()
5807 2 : .get_level0_deltas()?
5808 2 : .len();
5809 2 :
5810 110 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
5811 2 :
5812 2 : let after_num_l0_delta_files = tline
5813 2 : .layers
5814 2 : .read()
5815 2 : .await
5816 2 : .layer_map()
5817 2 : .get_level0_deltas()?
5818 2 : .len();
5819 2 :
5820 2 : assert!(after_num_l0_delta_files < before_num_l0_delta_files, "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}");
5821 2 :
5822 2 : assert_eq!(
5823 4 : tline.get(test_key, lsn, &ctx).await?,
5824 2 : test_img(&format!("{} at {}", 0, lsn))
5825 2 : );
5826 2 :
5827 2 : Ok(())
5828 2 : }
5829 :
5830 : #[tokio::test]
5831 2 : async fn test_branch_copies_dirty_aux_file_flag() {
5832 2 : let harness = TenantHarness::create("test_branch_copies_dirty_aux_file_flag").unwrap();
5833 2 :
5834 2 : // the default aux file policy to switch is v1 if not set by the admins
5835 2 : assert_eq!(
5836 2 : harness.tenant_conf.switch_aux_file_policy,
5837 2 : AuxFilePolicy::V1
5838 2 : );
5839 8 : let (tenant, ctx) = harness.load().await;
5840 2 :
5841 2 : let mut lsn = Lsn(0x08);
5842 2 :
5843 2 : let tline: Arc<Timeline> = tenant
5844 2 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
5845 6 : .await
5846 2 : .unwrap();
5847 2 :
5848 2 : // no aux file is written at this point, so the persistent flag should be unset
5849 2 : assert_eq!(tline.last_aux_file_policy.load(), None);
5850 2 :
5851 2 : {
5852 2 : lsn += 8;
5853 2 : let mut modification = tline.begin_modification(lsn);
5854 2 : modification
5855 2 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
5856 4 : .await
5857 2 : .unwrap();
5858 2 : modification.commit(&ctx).await.unwrap();
5859 2 : }
5860 2 :
5861 2 : // there is no tenant manager to pass the configuration through, so lets mimic it
5862 2 : tenant.set_new_location_config(
5863 2 : AttachedTenantConf::try_from(LocationConf::attached_single(
5864 2 : TenantConfOpt {
5865 2 : switch_aux_file_policy: Some(AuxFilePolicy::V2),
5866 2 : ..Default::default()
5867 2 : },
5868 2 : tenant.generation,
5869 2 : &pageserver_api::models::ShardParameters::default(),
5870 2 : ))
5871 2 : .unwrap(),
5872 2 : );
5873 2 :
5874 2 : assert_eq!(
5875 2 : tline.get_switch_aux_file_policy(),
5876 2 : AuxFilePolicy::V2,
5877 2 : "wanted state has been updated"
5878 2 : );
5879 2 : assert_eq!(
5880 2 : tline.last_aux_file_policy.load(),
5881 2 : Some(AuxFilePolicy::V1),
5882 2 : "aux file is written with switch_aux_file_policy unset (which is v1), so we should keep v1"
5883 2 : );
5884 2 :
5885 2 : // we can read everything from the storage
5886 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
5887 2 : assert_eq!(
5888 2 : files.get("pg_logical/mappings/test1"),
5889 2 : Some(&bytes::Bytes::from_static(b"first"))
5890 2 : );
5891 2 :
5892 2 : {
5893 2 : lsn += 8;
5894 2 : let mut modification = tline.begin_modification(lsn);
5895 2 : modification
5896 2 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
5897 2 : .await
5898 2 : .unwrap();
5899 2 : modification.commit(&ctx).await.unwrap();
5900 2 : }
5901 2 :
5902 2 : assert_eq!(
5903 2 : tline.last_aux_file_policy.load(),
5904 2 : Some(AuxFilePolicy::V1),
5905 2 : "keep v1 storage format when new files are written"
5906 2 : );
5907 2 :
5908 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
5909 2 : assert_eq!(
5910 2 : files.get("pg_logical/mappings/test2"),
5911 2 : Some(&bytes::Bytes::from_static(b"second"))
5912 2 : );
5913 2 :
5914 2 : let child = tenant
5915 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
5916 2 : .await
5917 2 : .unwrap();
5918 2 :
5919 2 : // child copies the last flag even if that is not on remote storage yet
5920 2 : assert_eq!(child.get_switch_aux_file_policy(), AuxFilePolicy::V2);
5921 2 : assert_eq!(child.last_aux_file_policy.load(), Some(AuxFilePolicy::V1));
5922 2 :
5923 2 : let files = child.list_aux_files(lsn, &ctx).await.unwrap();
5924 2 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
5925 2 : assert_eq!(files.get("pg_logical/mappings/test2"), None);
5926 2 :
5927 2 : // even if we crash here without flushing parent timeline with it's new
5928 2 : // last_aux_file_policy we are safe, because child was never meant to access ancestor's
5929 2 : // files. the ancestor can even switch back to V1 because of a migration safely.
5930 2 : }
5931 :
5932 : #[tokio::test]
5933 2 : async fn aux_file_policy_switch() {
5934 2 : let mut harness = TenantHarness::create("aux_file_policy_switch").unwrap();
5935 2 : harness.tenant_conf.switch_aux_file_policy = AuxFilePolicy::CrossValidation; // set to cross-validation mode
5936 8 : let (tenant, ctx) = harness.load().await;
5937 2 :
5938 2 : let mut lsn = Lsn(0x08);
5939 2 :
5940 2 : let tline: Arc<Timeline> = tenant
5941 2 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
5942 6 : .await
5943 2 : .unwrap();
5944 2 :
5945 2 : assert_eq!(
5946 2 : tline.last_aux_file_policy.load(),
5947 2 : None,
5948 2 : "no aux file is written so it should be unset"
5949 2 : );
5950 2 :
5951 2 : {
5952 2 : lsn += 8;
5953 2 : let mut modification = tline.begin_modification(lsn);
5954 2 : modification
5955 2 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
5956 4 : .await
5957 2 : .unwrap();
5958 2 : modification.commit(&ctx).await.unwrap();
5959 2 : }
5960 2 :
5961 2 : // there is no tenant manager to pass the configuration through, so lets mimic it
5962 2 : tenant.set_new_location_config(
5963 2 : AttachedTenantConf::try_from(LocationConf::attached_single(
5964 2 : TenantConfOpt {
5965 2 : switch_aux_file_policy: Some(AuxFilePolicy::V2),
5966 2 : ..Default::default()
5967 2 : },
5968 2 : tenant.generation,
5969 2 : &pageserver_api::models::ShardParameters::default(),
5970 2 : ))
5971 2 : .unwrap(),
5972 2 : );
5973 2 :
5974 2 : assert_eq!(
5975 2 : tline.get_switch_aux_file_policy(),
5976 2 : AuxFilePolicy::V2,
5977 2 : "wanted state has been updated"
5978 2 : );
5979 2 : assert_eq!(
5980 2 : tline.last_aux_file_policy.load(),
5981 2 : Some(AuxFilePolicy::CrossValidation),
5982 2 : "dirty index_part.json reflected state is yet to be updated"
5983 2 : );
5984 2 :
5985 2 : // we can still read the auxfile v1 before we ingest anything new
5986 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
5987 2 : assert_eq!(
5988 2 : files.get("pg_logical/mappings/test1"),
5989 2 : Some(&bytes::Bytes::from_static(b"first"))
5990 2 : );
5991 2 :
5992 2 : {
5993 2 : lsn += 8;
5994 2 : let mut modification = tline.begin_modification(lsn);
5995 2 : modification
5996 2 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
5997 2 : .await
5998 2 : .unwrap();
5999 2 : modification.commit(&ctx).await.unwrap();
6000 2 : }
6001 2 :
6002 2 : assert_eq!(
6003 2 : tline.last_aux_file_policy.load(),
6004 2 : Some(AuxFilePolicy::V2),
6005 2 : "ingesting a file should apply the wanted switch state when applicable"
6006 2 : );
6007 2 :
6008 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6009 2 : assert_eq!(
6010 2 : files.get("pg_logical/mappings/test1"),
6011 2 : Some(&bytes::Bytes::from_static(b"first")),
6012 2 : "cross validation writes to both v1 and v2 so this should be available in v2"
6013 2 : );
6014 2 : assert_eq!(
6015 2 : files.get("pg_logical/mappings/test2"),
6016 2 : Some(&bytes::Bytes::from_static(b"second"))
6017 2 : );
6018 2 :
6019 2 : // mimic again by trying to flip it from V2 to V1 (not switched to while ingesting a file)
6020 2 : tenant.set_new_location_config(
6021 2 : AttachedTenantConf::try_from(LocationConf::attached_single(
6022 2 : TenantConfOpt {
6023 2 : switch_aux_file_policy: Some(AuxFilePolicy::V1),
6024 2 : ..Default::default()
6025 2 : },
6026 2 : tenant.generation,
6027 2 : &pageserver_api::models::ShardParameters::default(),
6028 2 : ))
6029 2 : .unwrap(),
6030 2 : );
6031 2 :
6032 2 : {
6033 2 : lsn += 8;
6034 2 : let mut modification = tline.begin_modification(lsn);
6035 2 : modification
6036 2 : .put_file("pg_logical/mappings/test2", b"third", &ctx)
6037 2 : .await
6038 2 : .unwrap();
6039 2 : modification.commit(&ctx).await.unwrap();
6040 2 : }
6041 2 :
6042 2 : assert_eq!(
6043 2 : tline.get_switch_aux_file_policy(),
6044 2 : AuxFilePolicy::V1,
6045 2 : "wanted state has been updated again, even if invalid request"
6046 2 : );
6047 2 :
6048 2 : assert_eq!(
6049 2 : tline.last_aux_file_policy.load(),
6050 2 : Some(AuxFilePolicy::V2),
6051 2 : "ingesting a file should apply the wanted switch state when applicable"
6052 2 : );
6053 2 :
6054 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6055 2 : assert_eq!(
6056 2 : files.get("pg_logical/mappings/test1"),
6057 2 : Some(&bytes::Bytes::from_static(b"first"))
6058 2 : );
6059 2 : assert_eq!(
6060 2 : files.get("pg_logical/mappings/test2"),
6061 2 : Some(&bytes::Bytes::from_static(b"third"))
6062 2 : );
6063 2 :
6064 2 : // mimic again by trying to flip it from from V1 to V2 (not switched to while ingesting a file)
6065 2 : tenant.set_new_location_config(
6066 2 : AttachedTenantConf::try_from(LocationConf::attached_single(
6067 2 : TenantConfOpt {
6068 2 : switch_aux_file_policy: Some(AuxFilePolicy::V2),
6069 2 : ..Default::default()
6070 2 : },
6071 2 : tenant.generation,
6072 2 : &pageserver_api::models::ShardParameters::default(),
6073 2 : ))
6074 2 : .unwrap(),
6075 2 : );
6076 2 :
6077 2 : {
6078 2 : lsn += 8;
6079 2 : let mut modification = tline.begin_modification(lsn);
6080 2 : modification
6081 2 : .put_file("pg_logical/mappings/test3", b"last", &ctx)
6082 2 : .await
6083 2 : .unwrap();
6084 2 : modification.commit(&ctx).await.unwrap();
6085 2 : }
6086 2 :
6087 2 : assert_eq!(tline.get_switch_aux_file_policy(), AuxFilePolicy::V2);
6088 2 :
6089 2 : assert_eq!(tline.last_aux_file_policy.load(), Some(AuxFilePolicy::V2));
6090 2 :
6091 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6092 2 : assert_eq!(
6093 2 : files.get("pg_logical/mappings/test1"),
6094 2 : Some(&bytes::Bytes::from_static(b"first"))
6095 2 : );
6096 2 : assert_eq!(
6097 2 : files.get("pg_logical/mappings/test2"),
6098 2 : Some(&bytes::Bytes::from_static(b"third"))
6099 2 : );
6100 2 : assert_eq!(
6101 2 : files.get("pg_logical/mappings/test3"),
6102 2 : Some(&bytes::Bytes::from_static(b"last"))
6103 2 : );
6104 2 : }
6105 :
6106 : #[tokio::test]
6107 2 : async fn aux_file_policy_force_switch() {
6108 2 : let mut harness = TenantHarness::create("aux_file_policy_force_switch").unwrap();
6109 2 : harness.tenant_conf.switch_aux_file_policy = AuxFilePolicy::V1;
6110 8 : let (tenant, ctx) = harness.load().await;
6111 2 :
6112 2 : let mut lsn = Lsn(0x08);
6113 2 :
6114 2 : let tline: Arc<Timeline> = tenant
6115 2 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
6116 6 : .await
6117 2 : .unwrap();
6118 2 :
6119 2 : assert_eq!(
6120 2 : tline.last_aux_file_policy.load(),
6121 2 : None,
6122 2 : "no aux file is written so it should be unset"
6123 2 : );
6124 2 :
6125 2 : {
6126 2 : lsn += 8;
6127 2 : let mut modification = tline.begin_modification(lsn);
6128 2 : modification
6129 2 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
6130 4 : .await
6131 2 : .unwrap();
6132 2 : modification.commit(&ctx).await.unwrap();
6133 2 : }
6134 2 :
6135 2 : tline.do_switch_aux_policy(AuxFilePolicy::V2).unwrap();
6136 2 :
6137 2 : assert_eq!(
6138 2 : tline.last_aux_file_policy.load(),
6139 2 : Some(AuxFilePolicy::V2),
6140 2 : "dirty index_part.json reflected state is yet to be updated"
6141 2 : );
6142 2 :
6143 2 : // lose all data from v1
6144 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6145 2 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
6146 2 :
6147 2 : {
6148 2 : lsn += 8;
6149 2 : let mut modification = tline.begin_modification(lsn);
6150 2 : modification
6151 2 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
6152 2 : .await
6153 2 : .unwrap();
6154 2 : modification.commit(&ctx).await.unwrap();
6155 2 : }
6156 2 :
6157 2 : // read data ingested in v2
6158 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6159 2 : assert_eq!(
6160 2 : files.get("pg_logical/mappings/test2"),
6161 2 : Some(&bytes::Bytes::from_static(b"second"))
6162 2 : );
6163 2 : // lose all data from v1
6164 2 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
6165 2 : }
6166 :
6167 : #[tokio::test]
6168 2 : async fn aux_file_policy_auto_detect() {
6169 2 : let mut harness = TenantHarness::create("aux_file_policy_auto_detect").unwrap();
6170 2 : harness.tenant_conf.switch_aux_file_policy = AuxFilePolicy::V2; // set to cross-validation mode
6171 8 : let (tenant, ctx) = harness.load().await;
6172 2 :
6173 2 : let mut lsn = Lsn(0x08);
6174 2 :
6175 2 : let tline: Arc<Timeline> = tenant
6176 2 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
6177 5 : .await
6178 2 : .unwrap();
6179 2 :
6180 2 : assert_eq!(
6181 2 : tline.last_aux_file_policy.load(),
6182 2 : None,
6183 2 : "no aux file is written so it should be unset"
6184 2 : );
6185 2 :
6186 2 : {
6187 2 : lsn += 8;
6188 2 : let mut modification = tline.begin_modification(lsn);
6189 2 : let buf = AuxFilesDirectory::ser(&AuxFilesDirectory {
6190 2 : files: vec![(
6191 2 : "test_file".to_string(),
6192 2 : Bytes::copy_from_slice(b"test_file"),
6193 2 : )]
6194 2 : .into_iter()
6195 2 : .collect(),
6196 2 : })
6197 2 : .unwrap();
6198 2 : modification.put_for_test(AUX_FILES_KEY, Value::Image(Bytes::from(buf)));
6199 2 : modification.commit(&ctx).await.unwrap();
6200 2 : }
6201 2 :
6202 2 : {
6203 2 : lsn += 8;
6204 2 : let mut modification = tline.begin_modification(lsn);
6205 2 : modification
6206 2 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
6207 2 : .await
6208 2 : .unwrap();
6209 2 : modification.commit(&ctx).await.unwrap();
6210 2 : }
6211 2 :
6212 2 : assert_eq!(
6213 2 : tline.last_aux_file_policy.load(),
6214 2 : Some(AuxFilePolicy::V1),
6215 2 : "keep using v1 because there are aux files writting with v1"
6216 2 : );
6217 2 :
6218 2 : // we can still read the auxfile v1
6219 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6220 2 : assert_eq!(
6221 2 : files.get("pg_logical/mappings/test1"),
6222 2 : Some(&bytes::Bytes::from_static(b"first"))
6223 2 : );
6224 2 : assert_eq!(
6225 2 : files.get("test_file"),
6226 2 : Some(&bytes::Bytes::from_static(b"test_file"))
6227 2 : );
6228 2 : }
6229 :
6230 : #[tokio::test]
6231 2 : async fn test_metadata_image_creation() -> anyhow::Result<()> {
6232 2 : let harness = TenantHarness::create("test_metadata_image_creation")?;
6233 8 : let (tenant, ctx) = harness.load().await;
6234 2 : let tline = tenant
6235 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6236 4 : .await?;
6237 2 :
6238 2 : const NUM_KEYS: usize = 1000;
6239 2 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
6240 2 :
6241 2 : let cancel = CancellationToken::new();
6242 2 :
6243 2 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
6244 2 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
6245 2 : let mut test_key = base_key;
6246 2 : let mut lsn = Lsn(0x10);
6247 2 :
6248 8 : async fn scan_with_statistics(
6249 8 : tline: &Timeline,
6250 8 : keyspace: &KeySpace,
6251 8 : lsn: Lsn,
6252 8 : ctx: &RequestContext,
6253 8 : ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
6254 8 : let mut reconstruct_state = ValuesReconstructState::default();
6255 8 : let res = tline
6256 8 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
6257 1669 : .await?;
6258 8 : Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
6259 8 : }
6260 2 :
6261 2 : #[allow(clippy::needless_range_loop)]
6262 2002 : for blknum in 0..NUM_KEYS {
6263 2000 : lsn = Lsn(lsn.0 + 0x10);
6264 2000 : test_key.field6 = (blknum * STEP) as u32;
6265 2000 : let mut writer = tline.writer().await;
6266 2000 : writer
6267 2000 : .put(
6268 2000 : test_key,
6269 2000 : lsn,
6270 2000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6271 2000 : &ctx,
6272 2000 : )
6273 2 : .await?;
6274 2000 : writer.finish_write(lsn);
6275 2000 : drop(writer);
6276 2 : }
6277 2 :
6278 2 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
6279 2 :
6280 22 : for iter in 1..=10 {
6281 20020 : for _ in 0..NUM_KEYS {
6282 20000 : lsn = Lsn(lsn.0 + 0x10);
6283 20000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
6284 20000 : test_key.field6 = (blknum * STEP) as u32;
6285 20000 : let mut writer = tline.writer().await;
6286 20000 : writer
6287 20000 : .put(
6288 20000 : test_key,
6289 20000 : lsn,
6290 20000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6291 20000 : &ctx,
6292 20000 : )
6293 19 : .await?;
6294 20000 : writer.finish_write(lsn);
6295 20000 : drop(writer);
6296 2 : }
6297 2 :
6298 20 : tline.freeze_and_flush().await?;
6299 2 :
6300 20 : if iter % 5 == 0 {
6301 4 : let (_, before_delta_file_accessed) =
6302 1660 : scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
6303 4 : tline
6304 4 : .compact(
6305 4 : &cancel,
6306 4 : {
6307 4 : let mut flags = EnumSet::new();
6308 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
6309 4 : flags.insert(CompactFlags::ForceRepartition);
6310 4 : flags
6311 4 : },
6312 4 : &ctx,
6313 4 : )
6314 6519 : .await?;
6315 4 : let (_, after_delta_file_accessed) =
6316 9 : scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
6317 4 : assert!(after_delta_file_accessed < before_delta_file_accessed, "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}");
6318 2 : // Given that we already produced an image layer, there should be no delta layer needed for the scan, but still setting a low threshold there for unforeseen circumstances.
6319 4 : assert!(
6320 4 : after_delta_file_accessed <= 2,
6321 2 : "after_delta_file_accessed={after_delta_file_accessed}"
6322 2 : );
6323 16 : }
6324 2 : }
6325 2 :
6326 2 : Ok(())
6327 2 : }
6328 :
6329 : #[tokio::test]
6330 3 : async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
6331 3 : let harness = TenantHarness::create("test_vectored_missing_data_key_reads")?;
6332 12 : let (tenant, ctx) = harness.load().await;
6333 3 :
6334 3 : let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
6335 3 : let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
6336 3 : let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
6337 3 :
6338 3 : let tline = tenant
6339 3 : .create_test_timeline_with_layers(
6340 3 : TIMELINE_ID,
6341 3 : Lsn(0x10),
6342 3 : DEFAULT_PG_VERSION,
6343 3 : &ctx,
6344 3 : Vec::new(), // delta layers
6345 3 : vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
6346 3 : Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
6347 3 : )
6348 13 : .await?;
6349 3 : tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
6350 3 :
6351 3 : let child = tenant
6352 2 : .branch_timeline_test_with_layers(
6353 2 : &tline,
6354 2 : NEW_TIMELINE_ID,
6355 2 : Some(Lsn(0x20)),
6356 2 : &ctx,
6357 2 : Vec::new(), // delta layers
6358 2 : vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
6359 2 : Lsn(0x30),
6360 2 : )
6361 7 : .await
6362 3 : .unwrap();
6363 2 :
6364 12 : async fn get_vectored_impl_wrapper(
6365 12 : tline: &Arc<Timeline>,
6366 12 : key: Key,
6367 12 : lsn: Lsn,
6368 12 : ctx: &RequestContext,
6369 12 : ) -> Result<Option<Bytes>, GetVectoredError> {
6370 12 : let mut reconstruct_state = ValuesReconstructState::new();
6371 12 : let mut res = tline
6372 12 : .get_vectored_impl(
6373 12 : KeySpace::single(key..key.next()),
6374 12 : lsn,
6375 12 : &mut reconstruct_state,
6376 12 : ctx,
6377 12 : )
6378 12 : .await?;
6379 6 : Ok(res.pop_last().map(|(k, v)| {
6380 6 : assert_eq!(k, key);
6381 6 : v.unwrap()
6382 6 : }))
6383 12 : }
6384 2 :
6385 2 : let lsn = Lsn(0x30);
6386 3 :
6387 3 : // test vectored get on parent timeline
6388 3 : assert_eq!(
6389 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
6390 3 : Some(test_img("data key 1"))
6391 3 : );
6392 3 : assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
6393 3 : .await
6394 3 : .unwrap_err()
6395 2 : .is_missing_key_error());
6396 3 : assert!(
6397 2 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
6398 3 : .await
6399 3 : .unwrap_err()
6400 2 : .is_missing_key_error()
6401 3 : );
6402 3 :
6403 3 : // test vectored get on child timeline
6404 3 : assert_eq!(
6405 3 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
6406 3 : Some(test_img("data key 1"))
6407 3 : );
6408 3 : assert_eq!(
6409 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
6410 3 : Some(test_img("data key 2"))
6411 3 : );
6412 3 : assert!(
6413 2 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
6414 3 : .await
6415 3 : .unwrap_err()
6416 2 : .is_missing_key_error()
6417 3 : );
6418 3 :
6419 3 : Ok(())
6420 3 : }
6421 :
6422 : #[tokio::test]
6423 2 : async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
6424 2 : let harness = TenantHarness::create("test_vectored_missing_data_key_reads")?;
6425 8 : let (tenant, ctx) = harness.load().await;
6426 2 :
6427 2 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
6428 2 : let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
6429 2 : let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
6430 2 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
6431 2 :
6432 2 : let tline = tenant
6433 2 : .create_test_timeline_with_layers(
6434 2 : TIMELINE_ID,
6435 2 : Lsn(0x10),
6436 2 : DEFAULT_PG_VERSION,
6437 2 : &ctx,
6438 2 : Vec::new(), // delta layers
6439 2 : vec![(Lsn(0x20), vec![(base_key, test_img("metadata key 1"))])], // image layers
6440 2 : Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
6441 2 : )
6442 13 : .await?;
6443 2 :
6444 2 : let child = tenant
6445 2 : .branch_timeline_test_with_layers(
6446 2 : &tline,
6447 2 : NEW_TIMELINE_ID,
6448 2 : Some(Lsn(0x20)),
6449 2 : &ctx,
6450 2 : Vec::new(), // delta layers
6451 2 : vec![(
6452 2 : Lsn(0x30),
6453 2 : vec![(base_key_child, test_img("metadata key 2"))],
6454 2 : )], // image layers
6455 2 : Lsn(0x30),
6456 2 : )
6457 7 : .await
6458 2 : .unwrap();
6459 2 :
6460 12 : async fn get_vectored_impl_wrapper(
6461 12 : tline: &Arc<Timeline>,
6462 12 : key: Key,
6463 12 : lsn: Lsn,
6464 12 : ctx: &RequestContext,
6465 12 : ) -> Result<Option<Bytes>, GetVectoredError> {
6466 12 : let mut reconstruct_state = ValuesReconstructState::new();
6467 12 : let mut res = tline
6468 12 : .get_vectored_impl(
6469 12 : KeySpace::single(key..key.next()),
6470 12 : lsn,
6471 12 : &mut reconstruct_state,
6472 12 : ctx,
6473 12 : )
6474 8 : .await?;
6475 12 : Ok(res.pop_last().map(|(k, v)| {
6476 4 : assert_eq!(k, key);
6477 4 : v.unwrap()
6478 12 : }))
6479 12 : }
6480 2 :
6481 2 : let lsn = Lsn(0x30);
6482 2 :
6483 2 : // test vectored get on parent timeline
6484 2 : assert_eq!(
6485 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
6486 2 : Some(test_img("metadata key 1"))
6487 2 : );
6488 2 : assert_eq!(
6489 2 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
6490 2 : None
6491 2 : );
6492 2 : assert_eq!(
6493 2 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
6494 2 : None
6495 2 : );
6496 2 :
6497 2 : // test vectored get on child timeline
6498 2 : assert_eq!(
6499 2 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
6500 2 : None
6501 2 : );
6502 2 : assert_eq!(
6503 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
6504 2 : Some(test_img("metadata key 2"))
6505 2 : );
6506 2 : assert_eq!(
6507 2 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
6508 2 : None
6509 2 : );
6510 2 :
6511 2 : Ok(())
6512 2 : }
6513 :
6514 12 : async fn get_vectored_impl_wrapper(
6515 12 : tline: &Arc<Timeline>,
6516 12 : key: Key,
6517 12 : lsn: Lsn,
6518 12 : ctx: &RequestContext,
6519 12 : ) -> Result<Option<Bytes>, GetVectoredError> {
6520 12 : let mut reconstruct_state = ValuesReconstructState::new();
6521 12 : let mut res = tline
6522 12 : .get_vectored_impl(
6523 12 : KeySpace::single(key..key.next()),
6524 12 : lsn,
6525 12 : &mut reconstruct_state,
6526 12 : ctx,
6527 12 : )
6528 13 : .await?;
6529 12 : Ok(res.pop_last().map(|(k, v)| {
6530 8 : assert_eq!(k, key);
6531 8 : v.unwrap()
6532 12 : }))
6533 12 : }
6534 :
6535 : #[tokio::test]
6536 2 : async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
6537 2 : let harness = TenantHarness::create("test_metadata_tombstone_reads")?;
6538 8 : let (tenant, ctx) = harness.load().await;
6539 2 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
6540 2 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
6541 2 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
6542 2 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
6543 2 :
6544 2 : // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
6545 2 : // Lsn 0x30 key0, key3, no key1+key2
6546 2 : // Lsn 0x20 key1+key2 tomestones
6547 2 : // Lsn 0x10 key1 in image, key2 in delta
6548 2 : let tline = tenant
6549 2 : .create_test_timeline_with_layers(
6550 2 : TIMELINE_ID,
6551 2 : Lsn(0x10),
6552 2 : DEFAULT_PG_VERSION,
6553 2 : &ctx,
6554 2 : // delta layers
6555 2 : vec![
6556 2 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
6557 2 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
6558 2 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
6559 2 : ],
6560 2 : // image layers
6561 2 : vec![
6562 2 : (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
6563 2 : (
6564 2 : Lsn(0x30),
6565 2 : vec![
6566 2 : (key0, test_img("metadata key 0")),
6567 2 : (key3, test_img("metadata key 3")),
6568 2 : ],
6569 2 : ),
6570 2 : ],
6571 2 : Lsn(0x30),
6572 2 : )
6573 39 : .await?;
6574 2 :
6575 2 : let lsn = Lsn(0x30);
6576 2 : let old_lsn = Lsn(0x20);
6577 2 :
6578 2 : assert_eq!(
6579 4 : get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
6580 2 : Some(test_img("metadata key 0"))
6581 2 : );
6582 2 : assert_eq!(
6583 2 : get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
6584 2 : None,
6585 2 : );
6586 2 : assert_eq!(
6587 2 : get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
6588 2 : None,
6589 2 : );
6590 2 : assert_eq!(
6591 4 : get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
6592 2 : Some(Bytes::new()),
6593 2 : );
6594 2 : assert_eq!(
6595 4 : get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
6596 2 : Some(Bytes::new()),
6597 2 : );
6598 2 : assert_eq!(
6599 2 : get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
6600 2 : Some(test_img("metadata key 3"))
6601 2 : );
6602 2 :
6603 2 : Ok(())
6604 2 : }
6605 :
6606 : #[tokio::test]
6607 2 : async fn test_metadata_tombstone_image_creation() {
6608 2 : let harness = TenantHarness::create("test_metadata_tombstone_image_creation").unwrap();
6609 8 : let (tenant, ctx) = harness.load().await;
6610 2 :
6611 2 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
6612 2 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
6613 2 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
6614 2 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
6615 2 :
6616 2 : let tline = tenant
6617 2 : .create_test_timeline_with_layers(
6618 2 : TIMELINE_ID,
6619 2 : Lsn(0x10),
6620 2 : DEFAULT_PG_VERSION,
6621 2 : &ctx,
6622 2 : // delta layers
6623 2 : vec![
6624 2 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
6625 2 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
6626 2 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
6627 2 : vec![
6628 2 : (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
6629 2 : (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
6630 2 : ],
6631 2 : ],
6632 2 : // image layers
6633 2 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
6634 2 : Lsn(0x30),
6635 2 : )
6636 36 : .await
6637 2 : .unwrap();
6638 2 :
6639 2 : let cancel = CancellationToken::new();
6640 2 :
6641 2 : tline
6642 2 : .compact(
6643 2 : &cancel,
6644 2 : {
6645 2 : let mut flags = EnumSet::new();
6646 2 : flags.insert(CompactFlags::ForceImageLayerCreation);
6647 2 : flags.insert(CompactFlags::ForceRepartition);
6648 2 : flags
6649 2 : },
6650 2 : &ctx,
6651 2 : )
6652 49 : .await
6653 2 : .unwrap();
6654 2 :
6655 2 : // Image layers are created at last_record_lsn
6656 2 : let images = tline
6657 2 : .inspect_image_layers(Lsn(0x30), &ctx)
6658 8 : .await
6659 2 : .unwrap()
6660 2 : .into_iter()
6661 20 : .filter(|(k, _)| k.is_metadata_key())
6662 2 : .collect::<Vec<_>>();
6663 2 : assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
6664 2 : }
6665 :
6666 : #[tokio::test]
6667 2 : async fn test_metadata_tombstone_empty_image_creation() {
6668 2 : let harness =
6669 2 : TenantHarness::create("test_metadata_tombstone_empty_image_creation").unwrap();
6670 8 : let (tenant, ctx) = harness.load().await;
6671 2 :
6672 2 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
6673 2 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
6674 2 :
6675 2 : let tline = tenant
6676 2 : .create_test_timeline_with_layers(
6677 2 : TIMELINE_ID,
6678 2 : Lsn(0x10),
6679 2 : DEFAULT_PG_VERSION,
6680 2 : &ctx,
6681 2 : // delta layers
6682 2 : vec![
6683 2 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
6684 2 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
6685 2 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
6686 2 : ],
6687 2 : // image layers
6688 2 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
6689 2 : Lsn(0x30),
6690 2 : )
6691 30 : .await
6692 2 : .unwrap();
6693 2 :
6694 2 : let cancel = CancellationToken::new();
6695 2 :
6696 2 : tline
6697 2 : .compact(
6698 2 : &cancel,
6699 2 : {
6700 2 : let mut flags = EnumSet::new();
6701 2 : flags.insert(CompactFlags::ForceImageLayerCreation);
6702 2 : flags.insert(CompactFlags::ForceRepartition);
6703 2 : flags
6704 2 : },
6705 2 : &ctx,
6706 2 : )
6707 37 : .await
6708 2 : .unwrap();
6709 2 :
6710 2 : // Image layers are created at last_record_lsn
6711 2 : let images = tline
6712 2 : .inspect_image_layers(Lsn(0x30), &ctx)
6713 4 : .await
6714 2 : .unwrap()
6715 2 : .into_iter()
6716 16 : .filter(|(k, _)| k.is_metadata_key())
6717 2 : .collect::<Vec<_>>();
6718 2 : assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
6719 2 : }
6720 :
6721 : #[tokio::test]
6722 2 : async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
6723 2 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_images")?;
6724 8 : let (tenant, ctx) = harness.load().await;
6725 2 :
6726 62 : fn get_key(id: u32) -> Key {
6727 62 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
6728 62 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
6729 62 : key.field6 = id;
6730 62 : key
6731 62 : }
6732 2 :
6733 2 : // We create one bottom-most image layer, a delta layer D1 crossing the GC horizon, D2 below the horizon, and D3 above the horizon.
6734 2 : //
6735 2 : // | D1 | | D3 |
6736 2 : // -| |-- gc horizon -----------------
6737 2 : // | | | D2 |
6738 2 : // --------- img layer ------------------
6739 2 : //
6740 2 : // What we should expact from this compaction is:
6741 2 : // | Part of D1 | | D3 |
6742 2 : // --------- img layer with D1+D2 at GC horizon------------------
6743 2 :
6744 2 : // img layer at 0x10
6745 2 : let img_layer = (0..10)
6746 20 : .map(|id| (get_key(id), test_img(&format!("value {id}@0x10"))))
6747 2 : .collect_vec();
6748 2 :
6749 2 : let delta1 = vec![
6750 2 : // TODO: we should test a real delta record here, which requires us to add a variant of NeonWalRecord for testing purpose.
6751 2 : (
6752 2 : get_key(1),
6753 2 : Lsn(0x20),
6754 2 : Value::Image(test_img("value 1@0x20")),
6755 2 : ),
6756 2 : (
6757 2 : get_key(2),
6758 2 : Lsn(0x30),
6759 2 : Value::Image(test_img("value 2@0x30")),
6760 2 : ),
6761 2 : (
6762 2 : get_key(3),
6763 2 : Lsn(0x40),
6764 2 : Value::Image(test_img("value 3@0x40")),
6765 2 : ),
6766 2 : ];
6767 2 : let delta2 = vec![
6768 2 : (
6769 2 : get_key(5),
6770 2 : Lsn(0x20),
6771 2 : Value::Image(test_img("value 5@0x20")),
6772 2 : ),
6773 2 : (
6774 2 : get_key(6),
6775 2 : Lsn(0x20),
6776 2 : Value::Image(test_img("value 6@0x20")),
6777 2 : ),
6778 2 : ];
6779 2 : let delta3 = vec![
6780 2 : (
6781 2 : get_key(8),
6782 2 : Lsn(0x40),
6783 2 : Value::Image(test_img("value 8@0x40")),
6784 2 : ),
6785 2 : (
6786 2 : get_key(9),
6787 2 : Lsn(0x40),
6788 2 : Value::Image(test_img("value 9@0x40")),
6789 2 : ),
6790 2 : ];
6791 2 :
6792 2 : let tline = tenant
6793 2 : .create_test_timeline_with_layers(
6794 2 : TIMELINE_ID,
6795 2 : Lsn(0x10),
6796 2 : DEFAULT_PG_VERSION,
6797 2 : &ctx,
6798 2 : vec![delta1, delta2, delta3], // delta layers
6799 2 : vec![(Lsn(0x10), img_layer)], // image layers
6800 2 : Lsn(0x50),
6801 2 : )
6802 48 : .await?;
6803 2 : {
6804 2 : // Update GC info
6805 2 : let mut guard = tline.gc_info.write().unwrap();
6806 2 : guard.cutoffs.pitr = Lsn(0x30);
6807 2 : guard.cutoffs.horizon = Lsn(0x30);
6808 2 : }
6809 2 :
6810 2 : let cancel = CancellationToken::new();
6811 64 : tline.compact_with_gc(&cancel, &ctx).await.unwrap();
6812 2 :
6813 2 : // Check if the image layer at the GC horizon contains exactly what we want
6814 2 : let image_at_gc_horizon = tline
6815 2 : .inspect_image_layers(Lsn(0x30), &ctx)
6816 5 : .await
6817 2 : .unwrap()
6818 2 : .into_iter()
6819 36 : .filter(|(k, _)| k.is_metadata_key())
6820 2 : .collect::<Vec<_>>();
6821 2 :
6822 2 : assert_eq!(image_at_gc_horizon.len(), 10);
6823 2 : let expected_lsn = [0x10, 0x20, 0x30, 0x10, 0x10, 0x20, 0x20, 0x10, 0x10, 0x10];
6824 22 : for idx in 0..10 {
6825 20 : assert_eq!(
6826 20 : image_at_gc_horizon[idx],
6827 20 : (
6828 20 : get_key(idx as u32),
6829 20 : test_img(&format!("value {idx}@{:#x}", expected_lsn[idx]))
6830 20 : )
6831 20 : );
6832 2 : }
6833 2 :
6834 2 : // Check if old layers are removed / new layers have the expected LSN
6835 2 : let mut all_layers = tline.inspect_historic_layers().await.unwrap();
6836 4 : all_layers.sort_by(|k1, k2| {
6837 4 : (
6838 4 : k1.is_delta,
6839 4 : k1.key_range.start,
6840 4 : k1.key_range.end,
6841 4 : k1.lsn_range.start,
6842 4 : k1.lsn_range.end,
6843 4 : )
6844 4 : .cmp(&(
6845 4 : k2.is_delta,
6846 4 : k2.key_range.start,
6847 4 : k2.key_range.end,
6848 4 : k2.lsn_range.start,
6849 4 : k2.lsn_range.end,
6850 4 : ))
6851 4 : });
6852 2 : assert_eq!(
6853 2 : all_layers,
6854 2 : vec![
6855 2 : // Image layer at GC horizon
6856 2 : PersistentLayerKey {
6857 2 : key_range: Key::MIN..get_key(10),
6858 2 : lsn_range: Lsn(0x30)..Lsn(0x31),
6859 2 : is_delta: false
6860 2 : },
6861 2 : // The delta layer that is cut in the middle
6862 2 : PersistentLayerKey {
6863 2 : key_range: Key::MIN..get_key(9),
6864 2 : lsn_range: Lsn(0x30)..Lsn(0x41),
6865 2 : is_delta: true
6866 2 : },
6867 2 : // The delta layer we created and should not be picked for the compaction
6868 2 : PersistentLayerKey {
6869 2 : key_range: get_key(8)..get_key(10),
6870 2 : lsn_range: Lsn(0x40)..Lsn(0x41),
6871 2 : is_delta: true
6872 2 : }
6873 2 : ]
6874 2 : );
6875 2 :
6876 2 : Ok(())
6877 2 : }
6878 :
6879 : #[tokio::test]
6880 2 : async fn test_neon_test_record() -> anyhow::Result<()> {
6881 2 : let harness = TenantHarness::create("test_neon_test_record")?;
6882 8 : let (tenant, ctx) = harness.load().await;
6883 2 :
6884 24 : fn get_key(id: u32) -> Key {
6885 24 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
6886 24 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
6887 24 : key.field6 = id;
6888 24 : key
6889 24 : }
6890 2 :
6891 2 : let delta1 = vec![
6892 2 : (
6893 2 : get_key(1),
6894 2 : Lsn(0x20),
6895 2 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
6896 2 : ),
6897 2 : (
6898 2 : get_key(1),
6899 2 : Lsn(0x30),
6900 2 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
6901 2 : ),
6902 2 : (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
6903 2 : (
6904 2 : get_key(2),
6905 2 : Lsn(0x20),
6906 2 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
6907 2 : ),
6908 2 : (
6909 2 : get_key(2),
6910 2 : Lsn(0x30),
6911 2 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
6912 2 : ),
6913 2 : (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
6914 2 : (
6915 2 : get_key(3),
6916 2 : Lsn(0x20),
6917 2 : Value::WalRecord(NeonWalRecord::wal_clear()),
6918 2 : ),
6919 2 : (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
6920 2 : (
6921 2 : get_key(4),
6922 2 : Lsn(0x20),
6923 2 : Value::WalRecord(NeonWalRecord::wal_init()),
6924 2 : ),
6925 2 : ];
6926 2 : let image1 = vec![(get_key(1), "0x10".into())];
6927 2 :
6928 2 : let tline = tenant
6929 2 : .create_test_timeline_with_layers(
6930 2 : TIMELINE_ID,
6931 2 : Lsn(0x10),
6932 2 : DEFAULT_PG_VERSION,
6933 2 : &ctx,
6934 2 : vec![delta1], // delta layers
6935 2 : vec![(Lsn(0x10), image1)], // image layers
6936 2 : Lsn(0x50),
6937 2 : )
6938 18 : .await?;
6939 2 :
6940 2 : assert_eq!(
6941 8 : tline.get(get_key(1), Lsn(0x50), &ctx).await?,
6942 2 : Bytes::from_static(b"0x10,0x20,0x30")
6943 2 : );
6944 2 : assert_eq!(
6945 2 : tline.get(get_key(2), Lsn(0x50), &ctx).await?,
6946 2 : Bytes::from_static(b"0x10,0x20,0x30")
6947 2 : );
6948 2 : // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
6949 2 : // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
6950 2 :
6951 2 : Ok(())
6952 2 : }
6953 :
6954 : #[tokio::test]
6955 2 : async fn test_lsn_lease() -> anyhow::Result<()> {
6956 8 : let (tenant, ctx) = TenantHarness::create("test_lsn_lease")?.load().await;
6957 2 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6958 2 :
6959 2 : let end_lsn = Lsn(0x100);
6960 2 : let image_layers = (0x20..=0x90)
6961 2 : .step_by(0x10)
6962 16 : .map(|n| {
6963 16 : (
6964 16 : Lsn(n),
6965 16 : vec![(key, test_img(&format!("data key at {:x}", n)))],
6966 16 : )
6967 16 : })
6968 2 : .collect();
6969 2 :
6970 2 : let timeline = tenant
6971 2 : .create_test_timeline_with_layers(
6972 2 : TIMELINE_ID,
6973 2 : Lsn(0x10),
6974 2 : DEFAULT_PG_VERSION,
6975 2 : &ctx,
6976 2 : Vec::new(),
6977 2 : image_layers,
6978 2 : end_lsn,
6979 2 : )
6980 61 : .await?;
6981 2 :
6982 2 : let leased_lsns = [0x30, 0x50, 0x70];
6983 2 : let mut leases = Vec::new();
6984 6 : let _: anyhow::Result<_> = leased_lsns.iter().try_for_each(|n| {
6985 6 : leases.push(timeline.make_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)?);
6986 6 : Ok(())
6987 6 : });
6988 2 :
6989 2 : // Renewing with shorter lease should not change the lease.
6990 2 : let updated_lease_0 =
6991 2 : timeline.make_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)?;
6992 2 : assert_eq!(updated_lease_0.valid_until, leases[0].valid_until);
6993 2 :
6994 2 : // Renewing with a long lease should renew lease with later expiration time.
6995 2 : let updated_lease_1 = timeline.make_lsn_lease(
6996 2 : Lsn(leased_lsns[1]),
6997 2 : timeline.get_lsn_lease_length() * 2,
6998 2 : &ctx,
6999 2 : )?;
7000 2 :
7001 2 : assert!(updated_lease_1.valid_until > leases[1].valid_until);
7002 2 :
7003 2 : // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
7004 2 : info!(
7005 2 : "latest_gc_cutoff_lsn: {}",
7006 0 : *timeline.get_latest_gc_cutoff_lsn()
7007 2 : );
7008 2 : timeline.force_set_disk_consistent_lsn(end_lsn);
7009 2 :
7010 2 : let res = tenant
7011 2 : .gc_iteration(
7012 2 : Some(TIMELINE_ID),
7013 2 : 0,
7014 2 : Duration::ZERO,
7015 2 : &CancellationToken::new(),
7016 2 : &ctx,
7017 2 : )
7018 2 : .await?;
7019 2 :
7020 2 : // Keeping everything <= Lsn(0x80) b/c leases:
7021 2 : // 0/10: initdb layer
7022 2 : // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
7023 2 : assert_eq!(res.layers_needed_by_leases, 7);
7024 2 : // Keeping 0/90 b/c it is the latest layer.
7025 2 : assert_eq!(res.layers_not_updated, 1);
7026 2 : // Removed 0/80.
7027 2 : assert_eq!(res.layers_removed, 1);
7028 2 :
7029 2 : // Make lease on a already GC-ed LSN.
7030 2 : // 0/80 does not have a valid lease + is below latest_gc_cutoff
7031 2 : assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
7032 2 : let res = timeline.make_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx);
7033 2 : assert!(res.is_err());
7034 2 :
7035 2 : // Should still be able to renew a currently valid lease
7036 2 : // Assumption: original lease to is still valid for 0/50.
7037 2 : let _ =
7038 2 : timeline.make_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)?;
7039 2 :
7040 2 : Ok(())
7041 2 : }
7042 : }
|