Line data Source code
1 : //! This module manages synchronizing local FS with remote storage.
2 : //!
3 : //! # Overview
4 : //!
5 : //! * [`RemoteTimelineClient`] provides functions related to upload/download of a particular timeline.
6 : //! It contains a queue of pending uploads, and manages the queue, performing uploads in parallel
7 : //! when it's safe to do so.
8 : //!
9 : //! * Stand-alone function, [`list_remote_timelines`], to get list of timelines of a tenant.
10 : //!
11 : //! These functions use the low-level remote storage client, [`remote_storage::RemoteStorage`].
12 : //!
13 : //! # APIs & How To Use Them
14 : //!
15 : //! There is a [RemoteTimelineClient] for each [Timeline][`crate::tenant::Timeline`] in the system,
16 : //! unless the pageserver is configured without remote storage.
17 : //!
18 : //! We allocate the client instance in [Timeline][`crate::tenant::Timeline`], i.e.,
19 : //! either in [`crate::tenant::mgr`] during startup or when creating a new
20 : //! timeline.
21 : //! However, the client does not become ready for use until we've initialized its upload queue:
22 : //!
23 : //! - For timelines that already have some state on the remote storage, we use
24 : //! [`RemoteTimelineClient::init_upload_queue`] .
25 : //! - For newly created timelines, we use
26 : //! [`RemoteTimelineClient::init_upload_queue_for_empty_remote`].
27 : //!
28 : //! The former takes the remote's [`IndexPart`] as an argument, possibly retrieved
29 : //! using [`list_remote_timelines`]. We'll elaborate on [`IndexPart`] in the next section.
30 : //!
31 : //! Whenever we've created/updated/deleted a file in a timeline directory, we schedule
32 : //! the corresponding remote operation with the timeline's [`RemoteTimelineClient`]:
33 : //!
34 : //! - [`RemoteTimelineClient::schedule_layer_file_upload`] when we've created a new layer file.
35 : //! - [`RemoteTimelineClient::schedule_index_upload_for_metadata_update`] when we've updated the timeline metadata file.
36 : //! - [`RemoteTimelineClient::schedule_index_upload_for_file_changes`] to upload an updated index file, after we've scheduled file uploads
37 : //! - [`RemoteTimelineClient::schedule_layer_file_deletion`] when we've deleted one or more layer files.
38 : //!
39 : //! Internally, these functions create [`UploadOp`]s and put them in a queue.
40 : //!
41 : //! There are also APIs for downloading files.
42 : //! These are not part of the aforementioned queuing and will not be discussed
43 : //! further here, except in the section covering tenant attach.
44 : //!
45 : //! # Remote Storage Structure & [`IndexPart`] Index File
46 : //!
47 : //! The "directory structure" in the remote storage mirrors the local directory structure, with paths
48 : //! like `tenants/<tenant_id>/timelines/<timeline_id>/<layer filename>`.
49 : //! Yet instead of keeping the `metadata` file remotely, we wrap it with more
50 : //! data in an "index file" aka [`IndexPart`], containing the list of **all** remote
51 : //! files for a given timeline.
52 : //! If a file is not referenced from [`IndexPart`], it's not part of the remote storage state.
53 : //!
54 : //! Having the `IndexPart` also avoids expensive and slow `S3 list` commands.
55 : //!
56 : //! # Consistency
57 : //!
58 : //! To have a consistent remote structure, it's important that uploads and
59 : //! deletions are performed in the right order. For example, the index file
60 : //! contains a list of layer files, so it must not be uploaded until all the
61 : //! layer files that are in its list have been successfully uploaded.
62 : //!
63 : //! The contract between client and its user is that the user is responsible of
64 : //! scheduling operations in an order that keeps the remote consistent as
65 : //! described above.
66 : //!
67 : //! From the user's perspective, the operations are executed sequentially.
68 : //! Internally, the client knows which operations can be performed in parallel,
69 : //! and which operations act like a "barrier" that require preceding operations
70 : //! to finish. The calling code just needs to call the schedule-functions in the
71 : //! correct order, and the client will parallelize the operations in a way that
72 : //! is safe. For more details, see `UploadOp::can_bypass`.
73 : //!
74 : //! All of this relies on the following invariants:
75 : //!
76 : //! - We rely on read-after write consistency in the remote storage.
77 : //! - Layer files are immutable.
78 : //!
79 : //! NB: Pageserver assumes that it has exclusive write access to the tenant in remote
80 : //! storage. Different tenants can be attached to different pageservers, but if the
81 : //! same tenant is attached to two pageservers at the same time, they will overwrite
82 : //! each other's index file updates, and confusion will ensue. There's no interlock or
83 : //! mechanism to detect that in the pageserver, we rely on the control plane to ensure
84 : //! that that doesn't happen.
85 : //!
86 : //! ## Implementation Note
87 : //!
88 : //! The *actual* remote state lags behind the *desired* remote state while
89 : //! there are in-flight operations.
90 : //! We keep track of the desired remote state in [`UploadQueueInitialized::dirty`].
91 : //! It is initialized based on the [`IndexPart`] that was passed during init
92 : //! and updated with every `schedule_*` function call.
93 : //! All this is necessary necessary to compute the future [`IndexPart`]s
94 : //! when scheduling an operation while other operations that also affect the
95 : //! remote [`IndexPart`] are in flight.
96 : //!
97 : //! # Retries & Error Handling
98 : //!
99 : //! The client retries operations indefinitely, using exponential back-off.
100 : //! There is no way to force a retry, i.e., interrupt the back-off.
101 : //! This could be built easily.
102 : //!
103 : //! # Cancellation
104 : //!
105 : //! The operations execute as plain [`task_mgr`] tasks, scoped to
106 : //! the client's tenant and timeline.
107 : //! Dropping the client will drop queued operations but not executing operations.
108 : //! These will complete unless the `task_mgr` tasks are cancelled using `task_mgr`
109 : //! APIs, e.g., during pageserver shutdown, timeline delete, or tenant detach.
110 : //!
111 : //! # Completion
112 : //!
113 : //! Once an operation has completed, we update [`UploadQueueInitialized::clean`] immediately,
114 : //! and submit a request through the DeletionQueue to update
115 : //! [`UploadQueueInitialized::visible_remote_consistent_lsn`] after it has
116 : //! validated that our generation is not stale. It is this visible value
117 : //! that is advertized to safekeepers as a signal that that they can
118 : //! delete the WAL up to that LSN.
119 : //!
120 : //! The [`RemoteTimelineClient::wait_completion`] method can be used to wait
121 : //! for all pending operations to complete. It does not prevent more
122 : //! operations from getting scheduled.
123 : //!
124 : //! # Crash Consistency
125 : //!
126 : //! We do not persist the upload queue state.
127 : //! If we drop the client, or crash, all unfinished operations are lost.
128 : //!
129 : //! To recover, the following steps need to be taken:
130 : //! - Retrieve the current remote [`IndexPart`]. This gives us a
131 : //! consistent remote state, assuming the user scheduled the operations in
132 : //! the correct order.
133 : //! - Initiate upload queue with that [`IndexPart`].
134 : //! - Reschedule all lost operations by comparing the local filesystem state
135 : //! and remote state as per [`IndexPart`]. This is done in
136 : //! [`TenantShard::timeline_init_and_sync`].
137 : //!
138 : //! Note that if we crash during file deletion between the index update
139 : //! that removes the file from the list of files, and deleting the remote file,
140 : //! the file is leaked in the remote storage. Similarly, if a new file is created
141 : //! and uploaded, but the pageserver dies permanently before updating the
142 : //! remote index file, the new file is leaked in remote storage. We accept and
143 : //! tolerate that for now.
144 : //! Note further that we cannot easily fix this by scheduling deletes for every
145 : //! file that is present only on the remote, because we cannot distinguish the
146 : //! following two cases:
147 : //! - (1) We had the file locally, deleted it locally, scheduled a remote delete,
148 : //! but crashed before it finished remotely.
149 : //! - (2) We never had the file locally because we haven't on-demand downloaded
150 : //! it yet.
151 : //!
152 : //! # Downloads
153 : //!
154 : //! In addition to the upload queue, [`RemoteTimelineClient`] has functions for
155 : //! downloading files from the remote storage. Downloads are performed immediately
156 : //! against the `RemoteStorage`, independently of the upload queue.
157 : //!
158 : //! When we attach a tenant, we perform the following steps:
159 : //! - create `Tenant` object in `TenantState::Attaching` state
160 : //! - List timelines that are present in remote storage, and for each:
161 : //! - download their remote [`IndexPart`]s
162 : //! - create `Timeline` struct and a `RemoteTimelineClient`
163 : //! - initialize the client's upload queue with its `IndexPart`
164 : //! - schedule uploads for layers that are only present locally.
165 : //! - After the above is done for each timeline, open the tenant for business by
166 : //! transitioning it from `TenantState::Attaching` to `TenantState::Active` state.
167 : //! This starts the timelines' WAL-receivers and the tenant's GC & Compaction loops.
168 : //!
169 : //! # Operating Without Remote Storage
170 : //!
171 : //! If no remote storage configuration is provided, the [`RemoteTimelineClient`] is
172 : //! not created and the uploads are skipped.
173 : //!
174 : //! [`TenantShard::timeline_init_and_sync`]: super::TenantShard::timeline_init_and_sync
175 : //! [`Timeline::load_layer_map`]: super::Timeline::load_layer_map
176 :
177 : pub(crate) mod download;
178 : pub mod index;
179 : pub mod manifest;
180 : pub(crate) mod upload;
181 :
182 : use std::collections::{HashMap, HashSet, VecDeque};
183 : use std::ops::DerefMut;
184 : use std::sync::atomic::{AtomicU32, Ordering};
185 : use std::sync::{Arc, Mutex, OnceLock};
186 : use std::time::Duration;
187 :
188 : use anyhow::Context;
189 : use camino::Utf8Path;
190 : use chrono::{NaiveDateTime, Utc};
191 : pub(crate) use download::{
192 : download_index_part, download_initdb_tar_zst, download_tenant_manifest, is_temp_download_file,
193 : list_remote_tenant_shards, list_remote_timelines,
194 : };
195 : use index::GcCompactionState;
196 : pub(crate) use index::LayerFileMetadata;
197 : use pageserver_api::models::{RelSizeMigration, TimelineArchivalState, TimelineVisibilityState};
198 : use pageserver_api::shard::{ShardIndex, TenantShardId};
199 : use regex::Regex;
200 : use remote_storage::{
201 : DownloadError, GenericRemoteStorage, ListingMode, RemotePath, TimeoutOrCancel,
202 : };
203 : use scopeguard::ScopeGuard;
204 : use tokio_util::sync::CancellationToken;
205 : use tracing::{Instrument, debug, error, info, info_span, instrument, warn};
206 : pub(crate) use upload::upload_initdb_dir;
207 : use utils::backoff::{
208 : self, DEFAULT_BASE_BACKOFF_SECONDS, DEFAULT_MAX_BACKOFF_SECONDS, exponential_backoff,
209 : };
210 : use utils::id::{TenantId, TimelineId};
211 : use utils::lsn::Lsn;
212 : use utils::pausable_failpoint;
213 : use utils::shard::ShardNumber;
214 :
215 : use self::index::IndexPart;
216 : use super::config::AttachedLocationConfig;
217 : use super::metadata::MetadataUpdate;
218 : use super::storage_layer::{Layer, LayerName, ResidentLayer};
219 : use super::timeline::import_pgdata;
220 : use super::upload_queue::{NotInitialized, SetDeletedFlagProgress};
221 : use super::{DeleteTimelineError, Generation};
222 : use crate::config::PageServerConf;
223 : use crate::context::RequestContext;
224 : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
225 : use crate::metrics::{
226 : MeasureRemoteOp, REMOTE_ONDEMAND_DOWNLOADED_BYTES, REMOTE_ONDEMAND_DOWNLOADED_LAYERS,
227 : RemoteOpFileKind, RemoteOpKind, RemoteTimelineClientMetrics,
228 : RemoteTimelineClientMetricsCallTrackSize,
229 : };
230 : use crate::task_mgr::{BACKGROUND_RUNTIME, TaskKind, shutdown_token};
231 : use crate::tenant::metadata::TimelineMetadata;
232 : use crate::tenant::remote_timeline_client::download::download_retry;
233 : use crate::tenant::storage_layer::AsLayerDesc;
234 : use crate::tenant::upload_queue::{
235 : Delete, OpType, UploadOp, UploadQueue, UploadQueueInitialized, UploadQueueStopped,
236 : UploadQueueStoppedDeletable, UploadTask,
237 : };
238 : use crate::tenant::{TIMELINES_SEGMENT_NAME, debug_assert_current_span_has_tenant_and_timeline_id};
239 : use crate::{TENANT_HEATMAP_BASENAME, task_mgr};
240 :
241 : // Occasional network issues and such can cause remote operations to fail, and
242 : // that's expected. If a download fails, we log it at info-level, and retry.
243 : // But after FAILED_DOWNLOAD_WARN_THRESHOLD retries, we start to log it at WARN
244 : // level instead, as repeated failures can mean a more serious problem. If it
245 : // fails more than FAILED_DOWNLOAD_RETRIES times, we give up
246 : pub(crate) const FAILED_DOWNLOAD_WARN_THRESHOLD: u32 = 3;
247 : pub(crate) const FAILED_REMOTE_OP_RETRIES: u32 = 10;
248 :
249 : // Similarly log failed uploads and deletions at WARN level, after this many
250 : // retries. Uploads and deletions are retried forever, though.
251 : pub(crate) const FAILED_UPLOAD_WARN_THRESHOLD: u32 = 3;
252 :
253 : pub(crate) const INITDB_PATH: &str = "initdb.tar.zst";
254 :
255 : pub(crate) const INITDB_PRESERVED_PATH: &str = "initdb-preserved.tar.zst";
256 :
257 : /// Default buffer size when interfacing with [`tokio::fs::File`].
258 : pub(crate) const BUFFER_SIZE: usize = 32 * 1024;
259 :
260 : /// Doing non-essential flushes of deletion queue is subject to this timeout, after
261 : /// which we warn and skip.
262 : const DELETION_QUEUE_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);
263 :
264 : pub enum MaybeDeletedIndexPart {
265 : IndexPart(IndexPart),
266 : Deleted(IndexPart),
267 : }
268 :
269 : #[derive(Debug, thiserror::Error)]
270 : pub enum PersistIndexPartWithDeletedFlagError {
271 : #[error("another task is already setting the deleted_flag, started at {0:?}")]
272 : AlreadyInProgress(NaiveDateTime),
273 : #[error("the deleted_flag was already set, value is {0:?}")]
274 : AlreadyDeleted(NaiveDateTime),
275 : #[error(transparent)]
276 : Other(#[from] anyhow::Error),
277 : }
278 :
279 : #[derive(Debug, thiserror::Error)]
280 : pub enum WaitCompletionError {
281 : #[error(transparent)]
282 : NotInitialized(NotInitialized),
283 : #[error("wait_completion aborted because upload queue was stopped")]
284 : UploadQueueShutDownOrStopped,
285 : }
286 :
287 : #[derive(Debug, thiserror::Error)]
288 : #[error("Upload queue either in unexpected state or hasn't downloaded manifest yet")]
289 : pub struct UploadQueueNotReadyError;
290 :
291 : #[derive(Debug, thiserror::Error)]
292 : pub enum ShutdownIfArchivedError {
293 : #[error(transparent)]
294 : NotInitialized(NotInitialized),
295 : #[error("timeline is not archived")]
296 : NotArchived,
297 : }
298 :
299 : /// Behavioral modes that enable seamless live migration.
300 : ///
301 : /// See docs/rfcs/028-pageserver-migration.md to understand how these fit in.
302 : struct RemoteTimelineClientConfig {
303 : /// If this is false, then update to remote_consistent_lsn are dropped rather
304 : /// than being submitted to DeletionQueue for validation. This behavior is
305 : /// used when a tenant attachment is known to have a stale generation number,
306 : /// such that validation attempts will always fail. This is not necessary
307 : /// for correctness, but avoids spamming error statistics with failed validations
308 : /// when doing migrations of tenants.
309 : process_remote_consistent_lsn_updates: bool,
310 :
311 : /// If this is true, then object deletions are held in a buffer in RemoteTimelineClient
312 : /// rather than being submitted to the DeletionQueue. This behavior is used when a tenant
313 : /// is known to be multi-attached, in order to avoid disrupting other attached tenants
314 : /// whose generations' metadata refers to the deleted objects.
315 : block_deletions: bool,
316 : }
317 :
318 : /// RemoteTimelineClientConfig's state is entirely driven by LocationConf, but we do
319 : /// not carry the entire LocationConf structure: it's much more than we need. The From
320 : /// impl extracts the subset of the LocationConf that is interesting to RemoteTimelineClient.
321 : impl From<&AttachedLocationConfig> for RemoteTimelineClientConfig {
322 2844 : fn from(lc: &AttachedLocationConfig) -> Self {
323 2844 : Self {
324 2844 : block_deletions: !lc.may_delete_layers_hint(),
325 2844 : process_remote_consistent_lsn_updates: lc.may_upload_layers_hint(),
326 2844 : }
327 2844 : }
328 : }
329 :
330 : /// A client for accessing a timeline's data in remote storage.
331 : ///
332 : /// This takes care of managing the number of connections, and balancing them
333 : /// across tenants. This also handles retries of failed uploads.
334 : ///
335 : /// Upload and delete requests are ordered so that before a deletion is
336 : /// performed, we wait for all preceding uploads to finish. This ensures sure
337 : /// that if you perform a compaction operation that reshuffles data in layer
338 : /// files, we don't have a transient state where the old files have already been
339 : /// deleted, but new files have not yet been uploaded.
340 : ///
341 : /// Similarly, this enforces an order between index-file uploads, and layer
342 : /// uploads. Before an index-file upload is performed, all preceding layer
343 : /// uploads must be finished.
344 : ///
345 : /// This also maintains a list of remote files, and automatically includes that
346 : /// in the index part file, whenever timeline metadata is uploaded.
347 : ///
348 : /// Downloads are not queued, they are performed immediately.
349 : pub(crate) struct RemoteTimelineClient {
350 : conf: &'static PageServerConf,
351 :
352 : runtime: tokio::runtime::Handle,
353 :
354 : tenant_shard_id: TenantShardId,
355 : timeline_id: TimelineId,
356 : generation: Generation,
357 :
358 : upload_queue: Mutex<UploadQueue>,
359 :
360 : pub(crate) metrics: Arc<RemoteTimelineClientMetrics>,
361 :
362 : storage_impl: GenericRemoteStorage,
363 :
364 : deletion_queue_client: DeletionQueueClient,
365 :
366 : /// Subset of tenant configuration used to control upload behaviors during migrations
367 : config: std::sync::RwLock<RemoteTimelineClientConfig>,
368 :
369 : cancel: CancellationToken,
370 : }
371 :
372 : impl Drop for RemoteTimelineClient {
373 120 : fn drop(&mut self) {
374 120 : debug!("dropping RemoteTimelineClient");
375 120 : }
376 : }
377 :
378 : impl RemoteTimelineClient {
379 : ///
380 : /// Create a remote storage client for given timeline
381 : ///
382 : /// Note: the caller must initialize the upload queue before any uploads can be scheduled,
383 : /// by calling init_upload_queue.
384 : ///
385 2784 : pub(crate) fn new(
386 2784 : remote_storage: GenericRemoteStorage,
387 2784 : deletion_queue_client: DeletionQueueClient,
388 2784 : conf: &'static PageServerConf,
389 2784 : tenant_shard_id: TenantShardId,
390 2784 : timeline_id: TimelineId,
391 2784 : generation: Generation,
392 2784 : location_conf: &AttachedLocationConfig,
393 2784 : ) -> RemoteTimelineClient {
394 2784 : RemoteTimelineClient {
395 2784 : conf,
396 2784 : runtime: if cfg!(test) {
397 : // remote_timeline_client.rs tests rely on current-thread runtime
398 2784 : tokio::runtime::Handle::current()
399 : } else {
400 0 : BACKGROUND_RUNTIME.handle().clone()
401 : },
402 2784 : tenant_shard_id,
403 2784 : timeline_id,
404 2784 : generation,
405 2784 : storage_impl: remote_storage,
406 2784 : deletion_queue_client,
407 2784 : upload_queue: Mutex::new(UploadQueue::Uninitialized),
408 2784 : metrics: Arc::new(RemoteTimelineClientMetrics::new(
409 2784 : &tenant_shard_id,
410 2784 : &timeline_id,
411 2784 : )),
412 2784 : config: std::sync::RwLock::new(RemoteTimelineClientConfig::from(location_conf)),
413 2784 : cancel: CancellationToken::new(),
414 2784 : }
415 2784 : }
416 :
417 : /// Initialize the upload queue for a remote storage that already received
418 : /// an index file upload, i.e., it's not empty.
419 : /// The given `index_part` must be the one on the remote.
420 36 : pub fn init_upload_queue(&self, index_part: &IndexPart) -> anyhow::Result<()> {
421 36 : // Set the maximum number of inprogress tasks to the remote storage concurrency. There's
422 36 : // certainly no point in starting more upload tasks than this.
423 36 : let inprogress_limit = self
424 36 : .conf
425 36 : .remote_storage_config
426 36 : .as_ref()
427 36 : .map_or(0, |r| r.concurrency_limit());
428 36 : let mut upload_queue = self.upload_queue.lock().unwrap();
429 36 : upload_queue.initialize_with_current_remote_index_part(index_part, inprogress_limit)?;
430 36 : self.update_remote_physical_size_gauge(Some(index_part));
431 36 : info!(
432 0 : "initialized upload queue from remote index with {} layer files",
433 0 : index_part.layer_metadata.len()
434 : );
435 36 : Ok(())
436 36 : }
437 :
438 : /// Initialize the upload queue for the case where the remote storage is empty,
439 : /// i.e., it doesn't have an `IndexPart`.
440 : ///
441 : /// `rel_size_v2_status` needs to be carried over during branching, and that's why
442 : /// it's passed in here.
443 2748 : pub fn init_upload_queue_for_empty_remote(
444 2748 : &self,
445 2748 : local_metadata: &TimelineMetadata,
446 2748 : rel_size_v2_status: Option<RelSizeMigration>,
447 2748 : ) -> anyhow::Result<()> {
448 2748 : // Set the maximum number of inprogress tasks to the remote storage concurrency. There's
449 2748 : // certainly no point in starting more upload tasks than this.
450 2748 : let inprogress_limit = self
451 2748 : .conf
452 2748 : .remote_storage_config
453 2748 : .as_ref()
454 2748 : .map_or(0, |r| r.concurrency_limit());
455 2748 : let mut upload_queue = self.upload_queue.lock().unwrap();
456 2748 : let initialized_queue =
457 2748 : upload_queue.initialize_empty_remote(local_metadata, inprogress_limit)?;
458 2748 : initialized_queue.dirty.rel_size_migration = rel_size_v2_status;
459 2748 : self.update_remote_physical_size_gauge(None);
460 2748 : info!("initialized upload queue as empty");
461 2748 : Ok(())
462 2748 : }
463 :
464 : /// Initialize the queue in stopped state. Used in startup path
465 : /// to continue deletion operation interrupted by pageserver crash or restart.
466 0 : pub fn init_upload_queue_stopped_to_continue_deletion(
467 0 : &self,
468 0 : index_part: &IndexPart,
469 0 : ) -> anyhow::Result<()> {
470 : // FIXME: consider newtype for DeletedIndexPart.
471 0 : let deleted_at = index_part.deleted_at.ok_or(anyhow::anyhow!(
472 0 : "bug: it is responsibility of the caller to provide index part from MaybeDeletedIndexPart::Deleted"
473 0 : ))?;
474 0 : let inprogress_limit = self
475 0 : .conf
476 0 : .remote_storage_config
477 0 : .as_ref()
478 0 : .map_or(0, |r| r.concurrency_limit());
479 0 :
480 0 : let mut upload_queue = self.upload_queue.lock().unwrap();
481 0 : upload_queue.initialize_with_current_remote_index_part(index_part, inprogress_limit)?;
482 0 : self.update_remote_physical_size_gauge(Some(index_part));
483 0 : self.stop_impl(&mut upload_queue);
484 0 :
485 0 : upload_queue
486 0 : .stopped_mut()
487 0 : .expect("stopped above")
488 0 : .deleted_at = SetDeletedFlagProgress::Successful(deleted_at);
489 0 :
490 0 : Ok(())
491 0 : }
492 :
493 : /// Notify this client of a change to its parent tenant's config, as this may cause us to
494 : /// take action (unblocking deletions when transitioning from AttachedMulti to AttachedSingle)
495 0 : pub(super) fn update_config(&self, location_conf: &AttachedLocationConfig) {
496 0 : let new_conf = RemoteTimelineClientConfig::from(location_conf);
497 0 : let unblocked = !new_conf.block_deletions;
498 0 :
499 0 : // Update config before draining deletions, so that we don't race with more being
500 0 : // inserted. This can result in deletions happening our of order, but that does not
501 0 : // violate any invariants: deletions only need to be ordered relative to upload of the index
502 0 : // that dereferences the deleted objects, and we are not changing that order.
503 0 : *self.config.write().unwrap() = new_conf;
504 0 :
505 0 : if unblocked {
506 : // If we may now delete layers, drain any that were blocked in our old
507 : // configuration state
508 0 : let mut queue_locked = self.upload_queue.lock().unwrap();
509 :
510 0 : if let Ok(queue) = queue_locked.initialized_mut() {
511 0 : let blocked_deletions = std::mem::take(&mut queue.blocked_deletions);
512 0 : for d in blocked_deletions {
513 0 : if let Err(e) = self.deletion_queue_client.push_layers(
514 0 : self.tenant_shard_id,
515 0 : self.timeline_id,
516 0 : self.generation,
517 0 : d.layers,
518 0 : ) {
519 : // This could happen if the pageserver is shut down while a tenant
520 : // is transitioning from a deletion-blocked state: we will leak some
521 : // S3 objects in this case.
522 0 : warn!("Failed to drain blocked deletions: {}", e);
523 0 : break;
524 0 : }
525 : }
526 0 : }
527 0 : }
528 0 : }
529 :
530 : /// Returns `None` if nothing is yet uplodaded, `Some(disk_consistent_lsn)` otherwise.
531 0 : pub fn remote_consistent_lsn_projected(&self) -> Option<Lsn> {
532 0 : match &mut *self.upload_queue.lock().unwrap() {
533 0 : UploadQueue::Uninitialized => None,
534 0 : UploadQueue::Initialized(q) => q.get_last_remote_consistent_lsn_projected(),
535 0 : UploadQueue::Stopped(UploadQueueStopped::Uninitialized) => None,
536 0 : UploadQueue::Stopped(UploadQueueStopped::Deletable(q)) => q
537 0 : .upload_queue_for_deletion
538 0 : .get_last_remote_consistent_lsn_projected(),
539 : }
540 0 : }
541 :
542 0 : pub fn remote_consistent_lsn_visible(&self) -> Option<Lsn> {
543 0 : match &mut *self.upload_queue.lock().unwrap() {
544 0 : UploadQueue::Uninitialized => None,
545 0 : UploadQueue::Initialized(q) => Some(q.get_last_remote_consistent_lsn_visible()),
546 0 : UploadQueue::Stopped(UploadQueueStopped::Uninitialized) => None,
547 0 : UploadQueue::Stopped(UploadQueueStopped::Deletable(q)) => Some(
548 0 : q.upload_queue_for_deletion
549 0 : .get_last_remote_consistent_lsn_visible(),
550 0 : ),
551 : }
552 0 : }
553 :
554 : /// Returns true if this timeline was previously detached at this Lsn and the remote timeline
555 : /// client is currently initialized.
556 0 : pub(crate) fn is_previous_ancestor_lsn(&self, lsn: Lsn) -> bool {
557 0 : self.upload_queue
558 0 : .lock()
559 0 : .unwrap()
560 0 : .initialized_mut()
561 0 : .map(|uq| uq.clean.0.lineage.is_previous_ancestor_lsn(lsn))
562 0 : .unwrap_or(false)
563 0 : }
564 :
565 : /// Returns whether the timeline is archived.
566 : /// Return None if the remote index_part hasn't been downloaded yet.
567 96 : pub(crate) fn is_archived(&self) -> Option<bool> {
568 96 : self.upload_queue
569 96 : .lock()
570 96 : .unwrap()
571 96 : .initialized_mut()
572 96 : .map(|q| q.clean.0.archived_at.is_some())
573 96 : .ok()
574 96 : }
575 :
576 : /// Returns true if the timeline is invisible in synthetic size calculations.
577 96 : pub(crate) fn is_invisible(&self) -> Option<bool> {
578 96 : self.upload_queue
579 96 : .lock()
580 96 : .unwrap()
581 96 : .initialized_mut()
582 96 : .map(|q| q.clean.0.marked_invisible_at.is_some())
583 96 : .ok()
584 96 : }
585 :
586 : /// Returns `Ok(Some(timestamp))` if the timeline has been archived, `Ok(None)` if the timeline hasn't been archived.
587 : ///
588 : /// Return Err(_) if the remote index_part hasn't been downloaded yet, or the timeline hasn't been stopped yet.
589 12 : pub(crate) fn archived_at_stopped_queue(
590 12 : &self,
591 12 : ) -> Result<Option<NaiveDateTime>, UploadQueueNotReadyError> {
592 12 : self.upload_queue
593 12 : .lock()
594 12 : .unwrap()
595 12 : .stopped_mut()
596 12 : .map(|q| q.upload_queue_for_deletion.clean.0.archived_at)
597 12 : .map_err(|_| UploadQueueNotReadyError)
598 12 : }
599 :
600 11689 : fn update_remote_physical_size_gauge(&self, current_remote_index_part: Option<&IndexPart>) {
601 11689 : let size: u64 = if let Some(current_remote_index_part) = current_remote_index_part {
602 8941 : current_remote_index_part
603 8941 : .layer_metadata
604 8941 : .values()
605 105728 : .map(|ilmd| ilmd.file_size)
606 8941 : .sum()
607 : } else {
608 2748 : 0
609 : };
610 11689 : self.metrics.remote_physical_size_gauge.set(size);
611 11689 : }
612 :
613 12 : pub fn get_remote_physical_size(&self) -> u64 {
614 12 : self.metrics.remote_physical_size_gauge.get()
615 12 : }
616 :
617 : //
618 : // Download operations.
619 : //
620 : // These don't use the per-timeline queue. They do use the global semaphore in
621 : // S3Bucket, to limit the total number of concurrent operations, though.
622 : //
623 :
624 : /// Download index file
625 120 : pub async fn download_index_file(
626 120 : &self,
627 120 : cancel: &CancellationToken,
628 120 : ) -> Result<MaybeDeletedIndexPart, DownloadError> {
629 120 : let _unfinished_gauge_guard = self.metrics.call_begin(
630 120 : &RemoteOpFileKind::Index,
631 120 : &RemoteOpKind::Download,
632 120 : crate::metrics::RemoteTimelineClientMetricsCallTrackSize::DontTrackSize {
633 120 : reason: "no need for a downloads gauge",
634 120 : },
635 120 : );
636 :
637 120 : let (index_part, index_generation, index_last_modified) = download::download_index_part(
638 120 : &self.storage_impl,
639 120 : &self.tenant_shard_id,
640 120 : &self.timeline_id,
641 120 : self.generation,
642 120 : cancel,
643 120 : )
644 120 : .measure_remote_op(
645 120 : Option::<TaskKind>::None,
646 120 : RemoteOpFileKind::Index,
647 120 : RemoteOpKind::Download,
648 120 : Arc::clone(&self.metrics),
649 120 : )
650 120 : .await?;
651 :
652 : // Defense in depth: monotonicity of generation numbers is an important correctness guarantee, so when we see a very
653 : // old index, we do extra checks in case this is the result of backward time-travel of the generation number (e.g.
654 : // in case of a bug in the service that issues generation numbers). Indices are allowed to be old, but we expect that
655 : // when we load an old index we are loading the _latest_ index: if we are asked to load an old index and there is
656 : // also a newer index available, that is surprising.
657 : const INDEX_AGE_CHECKS_THRESHOLD: Duration = Duration::from_secs(14 * 24 * 3600);
658 120 : let index_age = index_last_modified.elapsed().unwrap_or_else(|e| {
659 0 : if e.duration() > Duration::from_secs(5) {
660 : // We only warn if the S3 clock and our local clock are >5s out: because this is a low resolution
661 : // timestamp, it is common to be out by at least 1 second.
662 0 : tracing::warn!("Index has modification time in the future: {e}");
663 0 : }
664 0 : Duration::ZERO
665 120 : });
666 120 : if index_age > INDEX_AGE_CHECKS_THRESHOLD {
667 0 : tracing::info!(
668 : ?index_generation,
669 0 : age = index_age.as_secs_f64(),
670 0 : "Loaded an old index, checking for other indices..."
671 : );
672 :
673 : // Find the highest-generation index
674 0 : let (_latest_index_part, latest_index_generation, latest_index_mtime) =
675 0 : download::download_index_part(
676 0 : &self.storage_impl,
677 0 : &self.tenant_shard_id,
678 0 : &self.timeline_id,
679 0 : Generation::MAX,
680 0 : cancel,
681 0 : )
682 0 : .await?;
683 :
684 0 : if latest_index_generation > index_generation {
685 : // Unexpected! Why are we loading such an old index if a more recent one exists?
686 : // We will refuse to proceed, as there is no reasonable scenario where this should happen, but
687 : // there _is_ a clear bug/corruption scenario where it would happen (controller sets the generation
688 : // backwards).
689 0 : tracing::error!(
690 : ?index_generation,
691 : ?latest_index_generation,
692 : ?latest_index_mtime,
693 0 : "Found a newer index while loading an old one"
694 : );
695 0 : return Err(DownloadError::Fatal(
696 0 : "Index age exceeds threshold and a newer index exists".into(),
697 0 : ));
698 0 : }
699 120 : }
700 :
701 120 : if index_part.deleted_at.is_some() {
702 0 : Ok(MaybeDeletedIndexPart::Deleted(index_part))
703 : } else {
704 120 : Ok(MaybeDeletedIndexPart::IndexPart(index_part))
705 : }
706 120 : }
707 :
708 : /// Download a (layer) file from `path`, into local filesystem.
709 : ///
710 : /// 'layer_metadata' is the metadata from the remote index file.
711 : ///
712 : /// On success, returns the size of the downloaded file.
713 84 : pub async fn download_layer_file(
714 84 : &self,
715 84 : layer_file_name: &LayerName,
716 84 : layer_metadata: &LayerFileMetadata,
717 84 : local_path: &Utf8Path,
718 84 : gate: &utils::sync::gate::Gate,
719 84 : cancel: &CancellationToken,
720 84 : ctx: &RequestContext,
721 84 : ) -> Result<u64, DownloadError> {
722 84 : let downloaded_size = {
723 84 : let _unfinished_gauge_guard = self.metrics.call_begin(
724 84 : &RemoteOpFileKind::Layer,
725 84 : &RemoteOpKind::Download,
726 84 : crate::metrics::RemoteTimelineClientMetricsCallTrackSize::DontTrackSize {
727 84 : reason: "no need for a downloads gauge",
728 84 : },
729 84 : );
730 84 : download::download_layer_file(
731 84 : self.conf,
732 84 : &self.storage_impl,
733 84 : self.tenant_shard_id,
734 84 : self.timeline_id,
735 84 : layer_file_name,
736 84 : layer_metadata,
737 84 : local_path,
738 84 : gate,
739 84 : cancel,
740 84 : ctx,
741 84 : )
742 84 : .measure_remote_op(
743 84 : Some(ctx.task_kind()),
744 84 : RemoteOpFileKind::Layer,
745 84 : RemoteOpKind::Download,
746 84 : Arc::clone(&self.metrics),
747 84 : )
748 84 : .await?
749 : };
750 :
751 84 : REMOTE_ONDEMAND_DOWNLOADED_LAYERS.inc();
752 84 : REMOTE_ONDEMAND_DOWNLOADED_BYTES.inc_by(downloaded_size);
753 84 :
754 84 : Ok(downloaded_size)
755 84 : }
756 :
757 : //
758 : // Upload operations.
759 : //
760 :
761 : /// Launch an index-file upload operation in the background, with
762 : /// fully updated metadata.
763 : ///
764 : /// This should only be used to upload initial metadata to remote storage.
765 : ///
766 : /// The upload will be added to the queue immediately, but it
767 : /// won't be performed until all previously scheduled layer file
768 : /// upload operations have completed successfully. This is to
769 : /// ensure that when the index file claims that layers X, Y and Z
770 : /// exist in remote storage, they really do. To wait for the upload
771 : /// to complete, use `wait_completion`.
772 : ///
773 : /// If there were any changes to the list of files, i.e. if any
774 : /// layer file uploads were scheduled, since the last index file
775 : /// upload, those will be included too.
776 1416 : pub fn schedule_index_upload_for_full_metadata_update(
777 1416 : self: &Arc<Self>,
778 1416 : metadata: &TimelineMetadata,
779 1416 : ) -> anyhow::Result<()> {
780 1416 : let mut guard = self.upload_queue.lock().unwrap();
781 1416 : let upload_queue = guard.initialized_mut()?;
782 :
783 : // As documented in the struct definition, it's ok for latest_metadata to be
784 : // ahead of what's _actually_ on the remote during index upload.
785 1416 : upload_queue.dirty.metadata = metadata.clone();
786 1416 :
787 1416 : self.schedule_index_upload(upload_queue);
788 1416 :
789 1416 : Ok(())
790 1416 : }
791 :
792 : /// Launch an index-file upload operation in the background, with only parts of the metadata
793 : /// updated.
794 : ///
795 : /// This is the regular way of updating metadata on layer flushes or Gc.
796 : ///
797 : /// Using this lighter update mechanism allows for reparenting and detaching without changes to
798 : /// `index_part.json`, while being more clear on what values update regularly.
799 7404 : pub(crate) fn schedule_index_upload_for_metadata_update(
800 7404 : self: &Arc<Self>,
801 7404 : update: &MetadataUpdate,
802 7404 : ) -> anyhow::Result<()> {
803 7404 : let mut guard = self.upload_queue.lock().unwrap();
804 7404 : let upload_queue = guard.initialized_mut()?;
805 :
806 7404 : upload_queue.dirty.metadata.apply(update);
807 7404 :
808 7404 : // Defense in depth: if we somehow generated invalid metadata, do not persist it.
809 7404 : upload_queue
810 7404 : .dirty
811 7404 : .validate()
812 7404 : .map_err(|e| anyhow::anyhow!(e))?;
813 :
814 7404 : self.schedule_index_upload(upload_queue);
815 7404 :
816 7404 : Ok(())
817 7404 : }
818 :
819 : /// Launch an index-file upload operation in the background, with only the `archived_at` field updated.
820 : ///
821 : /// Returns whether it is required to wait for the queue to be empty to ensure that the change is uploaded,
822 : /// so either if the change is already sitting in the queue, but not commited yet, or the change has not
823 : /// been in the queue yet.
824 12 : pub(crate) fn schedule_index_upload_for_timeline_archival_state(
825 12 : self: &Arc<Self>,
826 12 : state: TimelineArchivalState,
827 12 : ) -> anyhow::Result<bool> {
828 12 : let mut guard = self.upload_queue.lock().unwrap();
829 12 : let upload_queue = guard.initialized_mut()?;
830 :
831 : /// Returns Some(_) if a change is needed, and Some(true) if it's a
832 : /// change needed to set archived_at.
833 24 : fn need_change(
834 24 : archived_at: &Option<NaiveDateTime>,
835 24 : state: TimelineArchivalState,
836 24 : ) -> Option<bool> {
837 24 : match (archived_at, state) {
838 : (Some(_), TimelineArchivalState::Archived)
839 : | (None, TimelineArchivalState::Unarchived) => {
840 : // Nothing to do
841 0 : tracing::info!("intended state matches present state");
842 0 : None
843 : }
844 24 : (None, TimelineArchivalState::Archived) => Some(true),
845 0 : (Some(_), TimelineArchivalState::Unarchived) => Some(false),
846 : }
847 24 : }
848 12 : let need_upload_scheduled = need_change(&upload_queue.dirty.archived_at, state);
849 :
850 12 : if let Some(archived_at_set) = need_upload_scheduled {
851 12 : let intended_archived_at = archived_at_set.then(|| Utc::now().naive_utc());
852 12 : upload_queue.dirty.archived_at = intended_archived_at;
853 12 : self.schedule_index_upload(upload_queue);
854 12 : }
855 :
856 12 : let need_wait = need_change(&upload_queue.clean.0.archived_at, state).is_some();
857 12 : Ok(need_wait)
858 12 : }
859 :
860 12 : pub(crate) fn schedule_index_upload_for_timeline_invisible_state(
861 12 : self: &Arc<Self>,
862 12 : state: TimelineVisibilityState,
863 12 : ) -> anyhow::Result<()> {
864 12 : let mut guard = self.upload_queue.lock().unwrap();
865 12 : let upload_queue = guard.initialized_mut()?;
866 :
867 12 : fn need_change(
868 12 : marked_invisible_at: &Option<NaiveDateTime>,
869 12 : state: TimelineVisibilityState,
870 12 : ) -> Option<bool> {
871 12 : match (marked_invisible_at, state) {
872 0 : (Some(_), TimelineVisibilityState::Invisible) => Some(false),
873 12 : (None, TimelineVisibilityState::Invisible) => Some(true),
874 0 : (Some(_), TimelineVisibilityState::Visible) => Some(false),
875 0 : (None, TimelineVisibilityState::Visible) => Some(true),
876 : }
877 12 : }
878 :
879 12 : let need_upload_scheduled = need_change(&upload_queue.dirty.marked_invisible_at, state);
880 :
881 12 : if let Some(marked_invisible_at_set) = need_upload_scheduled {
882 12 : let intended_marked_invisible_at =
883 12 : marked_invisible_at_set.then(|| Utc::now().naive_utc());
884 12 : upload_queue.dirty.marked_invisible_at = intended_marked_invisible_at;
885 12 : self.schedule_index_upload(upload_queue);
886 12 : }
887 :
888 12 : Ok(())
889 12 : }
890 :
891 : /// Shuts the timeline client down, but only if the timeline is archived.
892 : ///
893 : /// This function and [`Self::schedule_index_upload_for_timeline_archival_state`] use the
894 : /// same lock to prevent races between unarchival and offloading: unarchival requires the
895 : /// upload queue to be initialized, and leaves behind an upload queue where either dirty
896 : /// or clean has archived_at of `None`. offloading leaves behind an uninitialized upload
897 : /// queue.
898 12 : pub(crate) async fn shutdown_if_archived(
899 12 : self: &Arc<Self>,
900 12 : ) -> Result<(), ShutdownIfArchivedError> {
901 12 : {
902 12 : let mut guard = self.upload_queue.lock().unwrap();
903 12 : let upload_queue = guard
904 12 : .initialized_mut()
905 12 : .map_err(ShutdownIfArchivedError::NotInitialized)?;
906 :
907 12 : match (
908 12 : upload_queue.dirty.archived_at.is_none(),
909 12 : upload_queue.clean.0.archived_at.is_none(),
910 12 : ) {
911 : // The expected case: the timeline is archived and we don't want to unarchive
912 12 : (false, false) => {}
913 : (true, false) => {
914 0 : tracing::info!("can't shut down timeline: timeline slated for unarchival");
915 0 : return Err(ShutdownIfArchivedError::NotArchived);
916 : }
917 0 : (dirty_archived, true) => {
918 0 : tracing::info!(%dirty_archived, "can't shut down timeline: timeline not archived in remote storage");
919 0 : return Err(ShutdownIfArchivedError::NotArchived);
920 : }
921 : }
922 :
923 : // Set the shutting_down flag while the guard from the archival check is held.
924 : // This prevents a race with unarchival, as initialized_mut will not return
925 : // an upload queue from this point.
926 : // Also launch the queued tasks like shutdown() does.
927 12 : if !upload_queue.shutting_down {
928 12 : upload_queue.shutting_down = true;
929 12 : upload_queue.queued_operations.push_back(UploadOp::Shutdown);
930 12 : // this operation is not counted similar to Barrier
931 12 : self.launch_queued_tasks(upload_queue);
932 12 : }
933 : }
934 :
935 12 : self.shutdown().await;
936 :
937 12 : Ok(())
938 12 : }
939 :
940 : /// Launch an index-file upload operation in the background, setting `import_pgdata` field.
941 0 : pub(crate) fn schedule_index_upload_for_import_pgdata_state_update(
942 0 : self: &Arc<Self>,
943 0 : state: Option<import_pgdata::index_part_format::Root>,
944 0 : ) -> anyhow::Result<()> {
945 0 : let mut guard = self.upload_queue.lock().unwrap();
946 0 : let upload_queue = guard.initialized_mut()?;
947 0 : upload_queue.dirty.import_pgdata = state;
948 0 : self.schedule_index_upload(upload_queue);
949 0 : Ok(())
950 0 : }
951 :
952 : /// Launch an index-file upload operation in the background, setting `gc_compaction_state` field.
953 0 : pub(crate) fn schedule_index_upload_for_gc_compaction_state_update(
954 0 : self: &Arc<Self>,
955 0 : gc_compaction_state: GcCompactionState,
956 0 : ) -> anyhow::Result<()> {
957 0 : let mut guard = self.upload_queue.lock().unwrap();
958 0 : let upload_queue = guard.initialized_mut()?;
959 0 : upload_queue.dirty.gc_compaction = Some(gc_compaction_state);
960 0 : self.schedule_index_upload(upload_queue);
961 0 : Ok(())
962 0 : }
963 :
964 : /// Launch an index-file upload operation in the background, setting `rel_size_v2_status` field.
965 0 : pub(crate) fn schedule_index_upload_for_rel_size_v2_status_update(
966 0 : self: &Arc<Self>,
967 0 : rel_size_v2_status: RelSizeMigration,
968 0 : ) -> anyhow::Result<()> {
969 0 : let mut guard = self.upload_queue.lock().unwrap();
970 0 : let upload_queue = guard.initialized_mut()?;
971 0 : upload_queue.dirty.rel_size_migration = Some(rel_size_v2_status);
972 0 : // TODO: allow this operation to bypass the validation check because we might upload the index part
973 0 : // with no layers but the flag updated. For now, we just modify the index part in memory and the next
974 0 : // upload will include the flag.
975 0 : // self.schedule_index_upload(upload_queue);
976 0 : Ok(())
977 0 : }
978 :
979 : ///
980 : /// Launch an index-file upload operation in the background, if necessary.
981 : ///
982 : /// Use this function to schedule the update of the index file after
983 : /// scheduling file uploads or deletions. If no file uploads or deletions
984 : /// have been scheduled since the last index file upload, this does
985 : /// nothing.
986 : ///
987 : /// Like schedule_index_upload_for_metadata_update(), this merely adds
988 : /// the upload to the upload queue and returns quickly.
989 2220 : pub fn schedule_index_upload_for_file_changes(self: &Arc<Self>) -> Result<(), NotInitialized> {
990 2220 : let mut guard = self.upload_queue.lock().unwrap();
991 2220 : let upload_queue = guard.initialized_mut()?;
992 :
993 2220 : if upload_queue.latest_files_changes_since_metadata_upload_scheduled > 0 {
994 84 : self.schedule_index_upload(upload_queue);
995 2136 : }
996 :
997 2220 : Ok(())
998 2220 : }
999 :
1000 : /// Only used in the `patch_index_part` HTTP API to force trigger an index upload.
1001 0 : pub fn force_schedule_index_upload(self: &Arc<Self>) -> Result<(), NotInitialized> {
1002 0 : let mut guard = self.upload_queue.lock().unwrap();
1003 0 : let upload_queue = guard.initialized_mut()?;
1004 0 : self.schedule_index_upload(upload_queue);
1005 0 : Ok(())
1006 0 : }
1007 :
1008 : /// Launch an index-file upload operation in the background (internal function)
1009 9360 : fn schedule_index_upload(self: &Arc<Self>, upload_queue: &mut UploadQueueInitialized) {
1010 9360 : let disk_consistent_lsn = upload_queue.dirty.metadata.disk_consistent_lsn();
1011 9360 : // fix up the duplicated field
1012 9360 : upload_queue.dirty.disk_consistent_lsn = disk_consistent_lsn;
1013 9360 :
1014 9360 : // make sure it serializes before doing it in perform_upload_task so that it doesn't
1015 9360 : // look like a retryable error
1016 9360 : let void = std::io::sink();
1017 9360 : serde_json::to_writer(void, &upload_queue.dirty).expect("serialize index_part.json");
1018 9360 :
1019 9360 : let index_part = &upload_queue.dirty;
1020 9360 :
1021 9360 : info!(
1022 0 : "scheduling metadata upload up to consistent LSN {disk_consistent_lsn} with {} files ({} changed)",
1023 0 : index_part.layer_metadata.len(),
1024 : upload_queue.latest_files_changes_since_metadata_upload_scheduled,
1025 : );
1026 :
1027 9360 : let op = UploadOp::UploadMetadata {
1028 9360 : uploaded: Box::new(index_part.clone()),
1029 9360 : };
1030 9360 : self.metric_begin(&op);
1031 9360 : upload_queue.queued_operations.push_back(op);
1032 9360 : upload_queue.latest_files_changes_since_metadata_upload_scheduled = 0;
1033 9360 :
1034 9360 : // Launch the task immediately, if possible
1035 9360 : self.launch_queued_tasks(upload_queue);
1036 9360 : }
1037 :
1038 : /// Reparent this timeline to a new parent.
1039 : ///
1040 : /// A retryable step of timeline ancestor detach.
1041 0 : pub(crate) async fn schedule_reparenting_and_wait(
1042 0 : self: &Arc<Self>,
1043 0 : new_parent: &TimelineId,
1044 0 : ) -> anyhow::Result<()> {
1045 0 : let receiver = {
1046 0 : let mut guard = self.upload_queue.lock().unwrap();
1047 0 : let upload_queue = guard.initialized_mut()?;
1048 :
1049 0 : let Some(prev) = upload_queue.dirty.metadata.ancestor_timeline() else {
1050 0 : return Err(anyhow::anyhow!(
1051 0 : "cannot reparent without a current ancestor"
1052 0 : ));
1053 : };
1054 :
1055 0 : let uploaded = &upload_queue.clean.0.metadata;
1056 0 :
1057 0 : if uploaded.ancestor_timeline().is_none() && !uploaded.ancestor_lsn().is_valid() {
1058 : // nothing to do
1059 0 : None
1060 : } else {
1061 0 : upload_queue.dirty.metadata.reparent(new_parent);
1062 0 : upload_queue.dirty.lineage.record_previous_ancestor(&prev);
1063 0 :
1064 0 : self.schedule_index_upload(upload_queue);
1065 0 :
1066 0 : Some(self.schedule_barrier0(upload_queue))
1067 : }
1068 : };
1069 :
1070 0 : if let Some(receiver) = receiver {
1071 0 : Self::wait_completion0(receiver).await?;
1072 0 : }
1073 0 : Ok(())
1074 0 : }
1075 :
1076 : /// Schedules uploading a new version of `index_part.json` with the given layers added,
1077 : /// detaching from ancestor and waits for it to complete.
1078 : ///
1079 : /// This is used with `Timeline::detach_ancestor` functionality.
1080 0 : pub(crate) async fn schedule_adding_existing_layers_to_index_detach_and_wait(
1081 0 : self: &Arc<Self>,
1082 0 : layers: &[Layer],
1083 0 : adopted: (TimelineId, Lsn),
1084 0 : ) -> anyhow::Result<()> {
1085 0 : let barrier = {
1086 0 : let mut guard = self.upload_queue.lock().unwrap();
1087 0 : let upload_queue = guard.initialized_mut()?;
1088 :
1089 0 : if upload_queue.clean.0.lineage.detached_previous_ancestor() == Some(adopted) {
1090 0 : None
1091 : } else {
1092 0 : upload_queue.dirty.metadata.detach_from_ancestor(&adopted);
1093 0 : upload_queue.dirty.lineage.record_detaching(&adopted);
1094 :
1095 0 : for layer in layers {
1096 0 : let prev = upload_queue
1097 0 : .dirty
1098 0 : .layer_metadata
1099 0 : .insert(layer.layer_desc().layer_name(), layer.metadata());
1100 0 : assert!(prev.is_none(), "copied layer existed already {layer}");
1101 : }
1102 :
1103 0 : self.schedule_index_upload(upload_queue);
1104 0 :
1105 0 : Some(self.schedule_barrier0(upload_queue))
1106 : }
1107 : };
1108 :
1109 0 : if let Some(barrier) = barrier {
1110 0 : Self::wait_completion0(barrier).await?;
1111 0 : }
1112 0 : Ok(())
1113 0 : }
1114 :
1115 : /// Adds a gc blocking reason for this timeline if one does not exist already.
1116 : ///
1117 : /// A retryable step of timeline detach ancestor.
1118 : ///
1119 : /// Returns a future which waits until the completion of the upload.
1120 0 : pub(crate) fn schedule_insert_gc_block_reason(
1121 0 : self: &Arc<Self>,
1122 0 : reason: index::GcBlockingReason,
1123 0 : ) -> Result<impl std::future::Future<Output = Result<(), WaitCompletionError>>, NotInitialized>
1124 0 : {
1125 0 : let maybe_barrier = {
1126 0 : let mut guard = self.upload_queue.lock().unwrap();
1127 0 : let upload_queue = guard.initialized_mut()?;
1128 :
1129 0 : if let index::GcBlockingReason::DetachAncestor = reason {
1130 0 : if upload_queue.dirty.metadata.ancestor_timeline().is_none() {
1131 0 : drop(guard);
1132 0 : panic!("cannot start detach ancestor if there is nothing to detach from");
1133 0 : }
1134 0 : }
1135 :
1136 0 : let wanted = |x: Option<&index::GcBlocking>| x.is_some_and(|x| x.blocked_by(reason));
1137 :
1138 0 : let current = upload_queue.dirty.gc_blocking.as_ref();
1139 0 : let uploaded = upload_queue.clean.0.gc_blocking.as_ref();
1140 0 :
1141 0 : match (current, uploaded) {
1142 0 : (x, y) if wanted(x) && wanted(y) => None,
1143 0 : (x, y) if wanted(x) && !wanted(y) => Some(self.schedule_barrier0(upload_queue)),
1144 : // Usual case: !wanted(x) && !wanted(y)
1145 : //
1146 : // Unusual: !wanted(x) && wanted(y) which means we have two processes waiting to
1147 : // turn on and off some reason.
1148 0 : (x, y) => {
1149 0 : if !wanted(x) && wanted(y) {
1150 : // this could be avoided by having external in-memory synchronization, like
1151 : // timeline detach ancestor
1152 0 : warn!(
1153 : ?reason,
1154 : op = "insert",
1155 0 : "unexpected: two racing processes to enable and disable a gc blocking reason"
1156 : );
1157 0 : }
1158 :
1159 : // at this point, the metadata must always show that there is a parent
1160 0 : upload_queue.dirty.gc_blocking = current
1161 0 : .map(|x| x.with_reason(reason))
1162 0 : .or_else(|| Some(index::GcBlocking::started_now_for(reason)));
1163 0 : self.schedule_index_upload(upload_queue);
1164 0 : Some(self.schedule_barrier0(upload_queue))
1165 : }
1166 : }
1167 : };
1168 :
1169 0 : Ok(async move {
1170 0 : if let Some(barrier) = maybe_barrier {
1171 0 : Self::wait_completion0(barrier).await?;
1172 0 : }
1173 0 : Ok(())
1174 0 : })
1175 0 : }
1176 :
1177 : /// Removes a gc blocking reason for this timeline if one exists.
1178 : ///
1179 : /// A retryable step of timeline detach ancestor.
1180 : ///
1181 : /// Returns a future which waits until the completion of the upload.
1182 0 : pub(crate) fn schedule_remove_gc_block_reason(
1183 0 : self: &Arc<Self>,
1184 0 : reason: index::GcBlockingReason,
1185 0 : ) -> Result<impl std::future::Future<Output = Result<(), WaitCompletionError>>, NotInitialized>
1186 0 : {
1187 0 : let maybe_barrier = {
1188 0 : let mut guard = self.upload_queue.lock().unwrap();
1189 0 : let upload_queue = guard.initialized_mut()?;
1190 :
1191 0 : if let index::GcBlockingReason::DetachAncestor = reason {
1192 0 : if !upload_queue.clean.0.lineage.is_detached_from_ancestor() {
1193 0 : drop(guard);
1194 0 : panic!("cannot complete timeline_ancestor_detach while not detached");
1195 0 : }
1196 0 : }
1197 :
1198 0 : let wanted = |x: Option<&index::GcBlocking>| {
1199 0 : x.is_none() || x.is_some_and(|b| !b.blocked_by(reason))
1200 0 : };
1201 :
1202 0 : let current = upload_queue.dirty.gc_blocking.as_ref();
1203 0 : let uploaded = upload_queue.clean.0.gc_blocking.as_ref();
1204 0 :
1205 0 : match (current, uploaded) {
1206 0 : (x, y) if wanted(x) && wanted(y) => None,
1207 0 : (x, y) if wanted(x) && !wanted(y) => Some(self.schedule_barrier0(upload_queue)),
1208 0 : (x, y) => {
1209 0 : if !wanted(x) && wanted(y) {
1210 0 : warn!(
1211 : ?reason,
1212 : op = "remove",
1213 0 : "unexpected: two racing processes to enable and disable a gc blocking reason (remove)"
1214 : );
1215 0 : }
1216 :
1217 0 : upload_queue.dirty.gc_blocking =
1218 0 : current.as_ref().and_then(|x| x.without_reason(reason));
1219 0 : assert!(wanted(upload_queue.dirty.gc_blocking.as_ref()));
1220 0 : self.schedule_index_upload(upload_queue);
1221 0 : Some(self.schedule_barrier0(upload_queue))
1222 : }
1223 : }
1224 : };
1225 :
1226 0 : Ok(async move {
1227 0 : if let Some(barrier) = maybe_barrier {
1228 0 : Self::wait_completion0(barrier).await?;
1229 0 : }
1230 0 : Ok(())
1231 0 : })
1232 0 : }
1233 :
1234 : /// Launch an upload operation in the background; the file is added to be included in next
1235 : /// `index_part.json` upload.
1236 8412 : pub(crate) fn schedule_layer_file_upload(
1237 8412 : self: &Arc<Self>,
1238 8412 : layer: ResidentLayer,
1239 8412 : ) -> Result<(), NotInitialized> {
1240 8412 : let mut guard = self.upload_queue.lock().unwrap();
1241 8412 : let upload_queue = guard.initialized_mut()?;
1242 :
1243 8412 : self.schedule_layer_file_upload0(upload_queue, layer);
1244 8412 : self.launch_queued_tasks(upload_queue);
1245 8412 : Ok(())
1246 8412 : }
1247 :
1248 10584 : fn schedule_layer_file_upload0(
1249 10584 : self: &Arc<Self>,
1250 10584 : upload_queue: &mut UploadQueueInitialized,
1251 10584 : layer: ResidentLayer,
1252 10584 : ) {
1253 10584 : let metadata = layer.metadata();
1254 10584 :
1255 10584 : upload_queue
1256 10584 : .dirty
1257 10584 : .layer_metadata
1258 10584 : .insert(layer.layer_desc().layer_name(), metadata.clone());
1259 10584 : upload_queue.latest_files_changes_since_metadata_upload_scheduled += 1;
1260 10584 :
1261 10584 : info!(
1262 : gen=?metadata.generation,
1263 : shard=?metadata.shard,
1264 0 : "scheduled layer file upload {layer}",
1265 : );
1266 :
1267 10584 : let op = UploadOp::UploadLayer(layer, metadata, None);
1268 10584 : self.metric_begin(&op);
1269 10584 : upload_queue.queued_operations.push_back(op);
1270 10584 : }
1271 :
1272 : /// Launch a delete operation in the background.
1273 : ///
1274 : /// The operation does not modify local filesystem state.
1275 : ///
1276 : /// Note: This schedules an index file upload before the deletions. The
1277 : /// deletion won't actually be performed, until all previously scheduled
1278 : /// upload operations, and the index file upload, have completed
1279 : /// successfully.
1280 48 : pub fn schedule_layer_file_deletion(
1281 48 : self: &Arc<Self>,
1282 48 : names: &[LayerName],
1283 48 : ) -> anyhow::Result<()> {
1284 48 : let mut guard = self.upload_queue.lock().unwrap();
1285 48 : let upload_queue = guard.initialized_mut()?;
1286 :
1287 48 : let with_metadata =
1288 48 : self.schedule_unlinking_of_layers_from_index_part0(upload_queue, names.iter().cloned());
1289 48 :
1290 48 : self.schedule_deletion_of_unlinked0(upload_queue, with_metadata);
1291 48 :
1292 48 : // Launch the tasks immediately, if possible
1293 48 : self.launch_queued_tasks(upload_queue);
1294 48 : Ok(())
1295 48 : }
1296 :
1297 : /// Unlinks the layer files from `index_part.json` but does not yet schedule deletion for the
1298 : /// layer files, leaving them dangling.
1299 : ///
1300 : /// The files will be leaked in remote storage unless [`Self::schedule_deletion_of_unlinked`]
1301 : /// is invoked on them.
1302 24 : pub(crate) fn schedule_gc_update(
1303 24 : self: &Arc<Self>,
1304 24 : gc_layers: &[Layer],
1305 24 : ) -> Result<(), NotInitialized> {
1306 24 : let mut guard = self.upload_queue.lock().unwrap();
1307 24 : let upload_queue = guard.initialized_mut()?;
1308 :
1309 : // just forget the return value; after uploading the next index_part.json, we can consider
1310 : // the layer files as "dangling". this is fine, at worst case we create work for the
1311 : // scrubber.
1312 :
1313 24 : let names = gc_layers.iter().map(|x| x.layer_desc().layer_name());
1314 24 :
1315 24 : self.schedule_unlinking_of_layers_from_index_part0(upload_queue, names);
1316 24 :
1317 24 : self.launch_queued_tasks(upload_queue);
1318 24 :
1319 24 : Ok(())
1320 24 : }
1321 :
1322 : /// Update the remote index file, removing the to-be-deleted files from the index,
1323 : /// allowing scheduling of actual deletions later.
1324 528 : fn schedule_unlinking_of_layers_from_index_part0<I>(
1325 528 : self: &Arc<Self>,
1326 528 : upload_queue: &mut UploadQueueInitialized,
1327 528 : names: I,
1328 528 : ) -> Vec<(LayerName, LayerFileMetadata)>
1329 528 : where
1330 528 : I: IntoIterator<Item = LayerName>,
1331 528 : {
1332 528 : // Decorate our list of names with each name's metadata, dropping
1333 528 : // names that are unexpectedly missing from our metadata. This metadata
1334 528 : // is later used when physically deleting layers, to construct key paths.
1335 528 : let with_metadata: Vec<_> = names
1336 528 : .into_iter()
1337 3072 : .filter_map(|name| {
1338 3072 : let meta = upload_queue.dirty.layer_metadata.remove(&name);
1339 :
1340 3072 : if let Some(meta) = meta {
1341 3072 : upload_queue.latest_files_changes_since_metadata_upload_scheduled += 1;
1342 3072 : Some((name, meta))
1343 : } else {
1344 : // This can only happen if we forgot to to schedule the file upload
1345 : // before scheduling the delete. Log it because it is a rare/strange
1346 : // situation, and in case something is misbehaving, we'd like to know which
1347 : // layers experienced this.
1348 0 : info!("Deleting layer {name} not found in latest_files list, never uploaded?");
1349 0 : None
1350 : }
1351 3072 : })
1352 528 : .collect();
1353 :
1354 : #[cfg(feature = "testing")]
1355 3600 : for (name, metadata) in &with_metadata {
1356 3072 : let gen_ = metadata.generation;
1357 3072 : if let Some(unexpected) = upload_queue.dangling_files.insert(name.to_owned(), gen_) {
1358 0 : if unexpected == gen_ {
1359 0 : tracing::error!("{name} was unlinked twice with same generation");
1360 : } else {
1361 0 : tracing::error!(
1362 0 : "{name} was unlinked twice with different generations {gen_:?} and {unexpected:?}"
1363 : );
1364 : }
1365 3072 : }
1366 : }
1367 :
1368 : // after unlinking files from the upload_queue.latest_files we must always schedule an
1369 : // index_part update, because that needs to be uploaded before we can actually delete the
1370 : // files.
1371 528 : if upload_queue.latest_files_changes_since_metadata_upload_scheduled > 0 {
1372 432 : self.schedule_index_upload(upload_queue);
1373 432 : }
1374 :
1375 528 : with_metadata
1376 528 : }
1377 :
1378 : /// Schedules deletion for layer files which have previously been unlinked from the
1379 : /// `index_part.json` with [`Self::schedule_gc_update`] or [`Self::schedule_compaction_update`].
1380 3076 : pub(crate) fn schedule_deletion_of_unlinked(
1381 3076 : self: &Arc<Self>,
1382 3076 : layers: Vec<(LayerName, LayerFileMetadata)>,
1383 3076 : ) -> anyhow::Result<()> {
1384 3076 : let mut guard = self.upload_queue.lock().unwrap();
1385 3076 : let upload_queue = guard.initialized_mut()?;
1386 :
1387 3076 : self.schedule_deletion_of_unlinked0(upload_queue, layers);
1388 3076 : self.launch_queued_tasks(upload_queue);
1389 3076 : Ok(())
1390 3076 : }
1391 :
1392 3112 : fn schedule_deletion_of_unlinked0(
1393 3112 : self: &Arc<Self>,
1394 3112 : upload_queue: &mut UploadQueueInitialized,
1395 3112 : mut with_metadata: Vec<(LayerName, LayerFileMetadata)>,
1396 3112 : ) {
1397 3112 : // Filter out any layers which were not created by this tenant shard. These are
1398 3112 : // layers that originate from some ancestor shard after a split, and may still
1399 3112 : // be referenced by other shards. We are free to delete them locally and remove
1400 3112 : // them from our index (and would have already done so when we reach this point
1401 3112 : // in the code), but we may not delete them remotely.
1402 3112 : with_metadata.retain(|(name, meta)| {
1403 3076 : let retain = meta.shard.shard_number == self.tenant_shard_id.shard_number
1404 3076 : && meta.shard.shard_count == self.tenant_shard_id.shard_count;
1405 3076 : if !retain {
1406 0 : tracing::debug!(
1407 0 : "Skipping deletion of ancestor-shard layer {name}, from shard {}",
1408 : meta.shard
1409 : );
1410 3076 : }
1411 3076 : retain
1412 3112 : });
1413 :
1414 6188 : for (name, meta) in &with_metadata {
1415 3076 : info!(
1416 0 : "scheduling deletion of layer {}{} (shard {})",
1417 0 : name,
1418 0 : meta.generation.get_suffix(),
1419 : meta.shard
1420 : );
1421 : }
1422 :
1423 : #[cfg(feature = "testing")]
1424 6188 : for (name, meta) in &with_metadata {
1425 3076 : let gen_ = meta.generation;
1426 3076 : match upload_queue.dangling_files.remove(name) {
1427 3052 : Some(same) if same == gen_ => { /* expected */ }
1428 0 : Some(other) => {
1429 0 : tracing::error!("{name} was unlinked with {other:?} but deleted with {gen_:?}");
1430 : }
1431 : None => {
1432 24 : tracing::error!("{name} was unlinked but was not dangling");
1433 : }
1434 : }
1435 : }
1436 :
1437 : // schedule the actual deletions
1438 3112 : if with_metadata.is_empty() {
1439 : // avoid scheduling the op & bumping the metric
1440 36 : return;
1441 3076 : }
1442 3076 : let op = UploadOp::Delete(Delete {
1443 3076 : layers: with_metadata,
1444 3076 : });
1445 3076 : self.metric_begin(&op);
1446 3076 : upload_queue.queued_operations.push_back(op);
1447 3112 : }
1448 :
1449 : /// Schedules a compaction update to the remote `index_part.json`.
1450 : ///
1451 : /// `compacted_from` represent the L0 names which have been `compacted_to` L1 layers.
1452 456 : pub(crate) fn schedule_compaction_update(
1453 456 : self: &Arc<Self>,
1454 456 : compacted_from: &[Layer],
1455 456 : compacted_to: &[ResidentLayer],
1456 456 : ) -> Result<(), NotInitialized> {
1457 456 : let mut guard = self.upload_queue.lock().unwrap();
1458 456 : let upload_queue = guard.initialized_mut()?;
1459 :
1460 2628 : for layer in compacted_to {
1461 2172 : self.schedule_layer_file_upload0(upload_queue, layer.clone());
1462 2172 : }
1463 :
1464 3036 : let names = compacted_from.iter().map(|x| x.layer_desc().layer_name());
1465 456 :
1466 456 : self.schedule_unlinking_of_layers_from_index_part0(upload_queue, names);
1467 456 : self.launch_queued_tasks(upload_queue);
1468 456 :
1469 456 : Ok(())
1470 456 : }
1471 :
1472 : /// Wait for all previously scheduled uploads/deletions to complete
1473 1368 : pub(crate) async fn wait_completion(self: &Arc<Self>) -> Result<(), WaitCompletionError> {
1474 1368 : let receiver = {
1475 1368 : let mut guard = self.upload_queue.lock().unwrap();
1476 1368 : let upload_queue = guard
1477 1368 : .initialized_mut()
1478 1368 : .map_err(WaitCompletionError::NotInitialized)?;
1479 1368 : self.schedule_barrier0(upload_queue)
1480 1368 : };
1481 1368 :
1482 1368 : Self::wait_completion0(receiver).await
1483 1368 : }
1484 :
1485 1368 : async fn wait_completion0(
1486 1368 : mut receiver: tokio::sync::watch::Receiver<()>,
1487 1368 : ) -> Result<(), WaitCompletionError> {
1488 1368 : if receiver.changed().await.is_err() {
1489 0 : return Err(WaitCompletionError::UploadQueueShutDownOrStopped);
1490 1368 : }
1491 1368 :
1492 1368 : Ok(())
1493 1368 : }
1494 :
1495 36 : pub(crate) fn schedule_barrier(self: &Arc<Self>) -> anyhow::Result<()> {
1496 36 : let mut guard = self.upload_queue.lock().unwrap();
1497 36 : let upload_queue = guard.initialized_mut()?;
1498 36 : self.schedule_barrier0(upload_queue);
1499 36 : Ok(())
1500 36 : }
1501 :
1502 1404 : fn schedule_barrier0(
1503 1404 : self: &Arc<Self>,
1504 1404 : upload_queue: &mut UploadQueueInitialized,
1505 1404 : ) -> tokio::sync::watch::Receiver<()> {
1506 1404 : let (sender, receiver) = tokio::sync::watch::channel(());
1507 1404 : let barrier_op = UploadOp::Barrier(sender);
1508 1404 :
1509 1404 : upload_queue.queued_operations.push_back(barrier_op);
1510 1404 : // Don't count this kind of operation!
1511 1404 :
1512 1404 : // Launch the task immediately, if possible
1513 1404 : self.launch_queued_tasks(upload_queue);
1514 1404 :
1515 1404 : receiver
1516 1404 : }
1517 :
1518 : /// Wait for all previously scheduled operations to complete, and then stop.
1519 : ///
1520 : /// Not cancellation safe
1521 60 : pub(crate) async fn shutdown(self: &Arc<Self>) {
1522 60 : // On cancellation the queue is left in ackward state of refusing new operations but
1523 60 : // proper stop is yet to be called. On cancel the original or some later task must call
1524 60 : // `stop` or `shutdown`.
1525 60 : let sg = scopeguard::guard((), |_| {
1526 0 : tracing::error!(
1527 0 : "RemoteTimelineClient::shutdown was cancelled; this should not happen, do not make this into an allowed_error"
1528 : )
1529 60 : });
1530 :
1531 48 : let fut = {
1532 60 : let mut guard = self.upload_queue.lock().unwrap();
1533 60 : let upload_queue = match &mut *guard {
1534 : UploadQueue::Stopped(_) => {
1535 12 : scopeguard::ScopeGuard::into_inner(sg);
1536 12 : return;
1537 : }
1538 : UploadQueue::Uninitialized => {
1539 : // transition into Stopped state
1540 0 : self.stop_impl(&mut guard);
1541 0 : scopeguard::ScopeGuard::into_inner(sg);
1542 0 : return;
1543 : }
1544 48 : UploadQueue::Initialized(init) => init,
1545 48 : };
1546 48 :
1547 48 : // if the queue is already stuck due to a shutdown operation which was cancelled, then
1548 48 : // just don't add more of these as they would never complete.
1549 48 : //
1550 48 : // TODO: if launch_queued_tasks were to be refactored to accept a &mut UploadQueue
1551 48 : // in every place we would not have to jump through this hoop, and this method could be
1552 48 : // made cancellable.
1553 48 : if !upload_queue.shutting_down {
1554 36 : upload_queue.shutting_down = true;
1555 36 : upload_queue.queued_operations.push_back(UploadOp::Shutdown);
1556 36 : // this operation is not counted similar to Barrier
1557 36 :
1558 36 : self.launch_queued_tasks(upload_queue);
1559 36 : }
1560 :
1561 48 : upload_queue.shutdown_ready.clone().acquire_owned()
1562 : };
1563 :
1564 48 : let res = fut.await;
1565 :
1566 48 : scopeguard::ScopeGuard::into_inner(sg);
1567 48 :
1568 48 : match res {
1569 0 : Ok(_permit) => unreachable!("shutdown_ready should not have been added permits"),
1570 48 : Err(_closed) => {
1571 48 : // expected
1572 48 : }
1573 48 : }
1574 48 :
1575 48 : self.stop();
1576 60 : }
1577 :
1578 : /// Set the deleted_at field in the remote index file.
1579 : ///
1580 : /// This fails if the upload queue has not been `stop()`ed.
1581 : ///
1582 : /// The caller is responsible for calling `stop()` AND for waiting
1583 : /// for any ongoing upload tasks to finish after `stop()` has succeeded.
1584 : /// Check method [`RemoteTimelineClient::stop`] for details.
1585 : #[instrument(skip_all)]
1586 : pub(crate) async fn persist_index_part_with_deleted_flag(
1587 : self: &Arc<Self>,
1588 : ) -> Result<(), PersistIndexPartWithDeletedFlagError> {
1589 : let index_part_with_deleted_at = {
1590 : let mut locked = self.upload_queue.lock().unwrap();
1591 :
1592 : // We must be in stopped state because otherwise
1593 : // we can have inprogress index part upload that can overwrite the file
1594 : // with missing is_deleted flag that we going to set below
1595 : let stopped = locked.stopped_mut()?;
1596 :
1597 : match stopped.deleted_at {
1598 : SetDeletedFlagProgress::NotRunning => (), // proceed
1599 : SetDeletedFlagProgress::InProgress(at) => {
1600 : return Err(PersistIndexPartWithDeletedFlagError::AlreadyInProgress(at));
1601 : }
1602 : SetDeletedFlagProgress::Successful(at) => {
1603 : return Err(PersistIndexPartWithDeletedFlagError::AlreadyDeleted(at));
1604 : }
1605 : };
1606 : let deleted_at = Utc::now().naive_utc();
1607 : stopped.deleted_at = SetDeletedFlagProgress::InProgress(deleted_at);
1608 :
1609 : let mut index_part = stopped.upload_queue_for_deletion.dirty.clone();
1610 : index_part.deleted_at = Some(deleted_at);
1611 : index_part
1612 : };
1613 :
1614 0 : let undo_deleted_at = scopeguard::guard(Arc::clone(self), |self_clone| {
1615 0 : let mut locked = self_clone.upload_queue.lock().unwrap();
1616 0 : let stopped = locked
1617 0 : .stopped_mut()
1618 0 : .expect("there's no way out of Stopping, and we checked it's Stopping above");
1619 0 : stopped.deleted_at = SetDeletedFlagProgress::NotRunning;
1620 0 : });
1621 :
1622 : pausable_failpoint!("persist_deleted_index_part");
1623 :
1624 : backoff::retry(
1625 0 : || {
1626 0 : upload::upload_index_part(
1627 0 : &self.storage_impl,
1628 0 : &self.tenant_shard_id,
1629 0 : &self.timeline_id,
1630 0 : self.generation,
1631 0 : &index_part_with_deleted_at,
1632 0 : &self.cancel,
1633 0 : )
1634 0 : },
1635 0 : |_e| false,
1636 : 1,
1637 : // have just a couple of attempts
1638 : // when executed as part of timeline deletion this happens in context of api call
1639 : // when executed as part of tenant deletion this happens in the background
1640 : 2,
1641 : "persist_index_part_with_deleted_flag",
1642 : &self.cancel,
1643 : )
1644 : .await
1645 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
1646 0 : .and_then(|x| x)?;
1647 :
1648 : // all good, disarm the guard and mark as success
1649 : ScopeGuard::into_inner(undo_deleted_at);
1650 : {
1651 : let mut locked = self.upload_queue.lock().unwrap();
1652 :
1653 : let stopped = locked
1654 : .stopped_mut()
1655 : .expect("there's no way out of Stopping, and we checked it's Stopping above");
1656 : stopped.deleted_at = SetDeletedFlagProgress::Successful(
1657 : index_part_with_deleted_at
1658 : .deleted_at
1659 : .expect("we set it above"),
1660 : );
1661 : }
1662 :
1663 : Ok(())
1664 : }
1665 :
1666 0 : pub(crate) fn is_deleting(&self) -> bool {
1667 0 : let mut locked = self.upload_queue.lock().unwrap();
1668 0 : locked.stopped_mut().is_ok()
1669 0 : }
1670 :
1671 0 : pub(crate) async fn preserve_initdb_archive(
1672 0 : self: &Arc<Self>,
1673 0 : tenant_id: &TenantId,
1674 0 : timeline_id: &TimelineId,
1675 0 : cancel: &CancellationToken,
1676 0 : ) -> anyhow::Result<()> {
1677 0 : backoff::retry(
1678 0 : || async {
1679 0 : upload::preserve_initdb_archive(&self.storage_impl, tenant_id, timeline_id, cancel)
1680 0 : .await
1681 0 : },
1682 0 : TimeoutOrCancel::caused_by_cancel,
1683 0 : FAILED_DOWNLOAD_WARN_THRESHOLD,
1684 0 : FAILED_REMOTE_OP_RETRIES,
1685 0 : "preserve_initdb_tar_zst",
1686 0 : &cancel.clone(),
1687 0 : )
1688 0 : .await
1689 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
1690 0 : .and_then(|x| x)
1691 0 : .context("backing up initdb archive")?;
1692 0 : Ok(())
1693 0 : }
1694 :
1695 : /// Uploads the given layer **without** adding it to be part of a future `index_part.json` upload.
1696 : ///
1697 : /// This is not normally needed.
1698 0 : pub(crate) async fn upload_layer_file(
1699 0 : self: &Arc<Self>,
1700 0 : uploaded: &ResidentLayer,
1701 0 : cancel: &CancellationToken,
1702 0 : ) -> anyhow::Result<()> {
1703 0 : let remote_path = remote_layer_path(
1704 0 : &self.tenant_shard_id.tenant_id,
1705 0 : &self.timeline_id,
1706 0 : uploaded.metadata().shard,
1707 0 : &uploaded.layer_desc().layer_name(),
1708 0 : uploaded.metadata().generation,
1709 0 : );
1710 0 :
1711 0 : backoff::retry(
1712 0 : || async {
1713 0 : upload::upload_timeline_layer(
1714 0 : &self.storage_impl,
1715 0 : uploaded.local_path(),
1716 0 : &remote_path,
1717 0 : uploaded.metadata().file_size,
1718 0 : cancel,
1719 0 : )
1720 0 : .await
1721 0 : },
1722 0 : TimeoutOrCancel::caused_by_cancel,
1723 0 : FAILED_UPLOAD_WARN_THRESHOLD,
1724 0 : FAILED_REMOTE_OP_RETRIES,
1725 0 : "upload a layer without adding it to latest files",
1726 0 : cancel,
1727 0 : )
1728 0 : .await
1729 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
1730 0 : .and_then(|x| x)
1731 0 : .context("upload a layer without adding it to latest files")
1732 0 : }
1733 :
1734 : /// Copies the `adopted` remote existing layer to the remote path of `adopted_as`. The layer is
1735 : /// not added to be part of a future `index_part.json` upload.
1736 0 : pub(crate) async fn copy_timeline_layer(
1737 0 : self: &Arc<Self>,
1738 0 : adopted: &Layer,
1739 0 : adopted_as: &Layer,
1740 0 : cancel: &CancellationToken,
1741 0 : ) -> anyhow::Result<()> {
1742 0 : let source_remote_path = remote_layer_path(
1743 0 : &self.tenant_shard_id.tenant_id,
1744 0 : &adopted
1745 0 : .get_timeline_id()
1746 0 : .expect("Source timeline should be alive"),
1747 0 : adopted.metadata().shard,
1748 0 : &adopted.layer_desc().layer_name(),
1749 0 : adopted.metadata().generation,
1750 0 : );
1751 0 :
1752 0 : let target_remote_path = remote_layer_path(
1753 0 : &self.tenant_shard_id.tenant_id,
1754 0 : &self.timeline_id,
1755 0 : adopted_as.metadata().shard,
1756 0 : &adopted_as.layer_desc().layer_name(),
1757 0 : adopted_as.metadata().generation,
1758 0 : );
1759 0 :
1760 0 : backoff::retry(
1761 0 : || async {
1762 0 : upload::copy_timeline_layer(
1763 0 : &self.storage_impl,
1764 0 : &source_remote_path,
1765 0 : &target_remote_path,
1766 0 : cancel,
1767 0 : )
1768 0 : .await
1769 0 : },
1770 0 : TimeoutOrCancel::caused_by_cancel,
1771 0 : FAILED_UPLOAD_WARN_THRESHOLD,
1772 0 : FAILED_REMOTE_OP_RETRIES,
1773 0 : "copy timeline layer",
1774 0 : cancel,
1775 0 : )
1776 0 : .await
1777 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
1778 0 : .and_then(|x| x)
1779 0 : .context("remote copy timeline layer")
1780 0 : }
1781 :
1782 0 : async fn flush_deletion_queue(&self) -> Result<(), DeletionQueueError> {
1783 0 : match tokio::time::timeout(
1784 0 : DELETION_QUEUE_FLUSH_TIMEOUT,
1785 0 : self.deletion_queue_client.flush_immediate(),
1786 0 : )
1787 0 : .await
1788 : {
1789 0 : Ok(result) => result,
1790 0 : Err(_timeout) => {
1791 0 : // Flushing remote deletions is not mandatory: we flush here to make the system easier to test, and
1792 0 : // to ensure that _usually_ objects are really gone after a DELETE is acked. However, in case of deletion
1793 0 : // queue issues (https://github.com/neondatabase/neon/issues/6440), we don't want to wait indefinitely here.
1794 0 : tracing::warn!(
1795 0 : "Timed out waiting for deletion queue flush, acking deletion anyway"
1796 : );
1797 0 : Ok(())
1798 : }
1799 : }
1800 0 : }
1801 :
1802 : /// Prerequisites: UploadQueue should be in stopped state and deleted_at should be successfuly set.
1803 : /// The function deletes layer files one by one, then lists the prefix to see if we leaked something
1804 : /// deletes leaked files if any and proceeds with deletion of index file at the end.
1805 0 : pub(crate) async fn delete_all(self: &Arc<Self>) -> Result<(), DeleteTimelineError> {
1806 0 : debug_assert_current_span_has_tenant_and_timeline_id();
1807 :
1808 0 : let layers: Vec<RemotePath> = {
1809 0 : let mut locked = self.upload_queue.lock().unwrap();
1810 0 : let stopped = locked.stopped_mut().map_err(DeleteTimelineError::Other)?;
1811 :
1812 0 : if !matches!(stopped.deleted_at, SetDeletedFlagProgress::Successful(_)) {
1813 0 : return Err(DeleteTimelineError::Other(anyhow::anyhow!(
1814 0 : "deleted_at is not set"
1815 0 : )));
1816 0 : }
1817 0 :
1818 0 : debug_assert!(stopped.upload_queue_for_deletion.no_pending_work());
1819 :
1820 0 : stopped
1821 0 : .upload_queue_for_deletion
1822 0 : .dirty
1823 0 : .layer_metadata
1824 0 : .drain()
1825 0 : .filter(|(_file_name, meta)| {
1826 0 : // Filter out layers that belonged to an ancestor shard. Since we are deleting the whole timeline from
1827 0 : // all shards anyway, we _could_ delete these, but
1828 0 : // - it creates a potential race if other shards are still
1829 0 : // using the layers while this shard deletes them.
1830 0 : // - it means that if we rolled back the shard split, the ancestor shards would be in a state where
1831 0 : // these timelines are present but corrupt (their index exists but some layers don't)
1832 0 : //
1833 0 : // These layers will eventually be cleaned up by the scrubber when it does physical GC.
1834 0 : meta.shard.shard_number == self.tenant_shard_id.shard_number
1835 0 : && meta.shard.shard_count == self.tenant_shard_id.shard_count
1836 0 : })
1837 0 : .map(|(file_name, meta)| {
1838 0 : remote_layer_path(
1839 0 : &self.tenant_shard_id.tenant_id,
1840 0 : &self.timeline_id,
1841 0 : meta.shard,
1842 0 : &file_name,
1843 0 : meta.generation,
1844 0 : )
1845 0 : })
1846 0 : .collect()
1847 0 : };
1848 0 :
1849 0 : let layer_deletion_count = layers.len();
1850 0 : self.deletion_queue_client
1851 0 : .push_immediate(layers)
1852 0 : .await
1853 0 : .map_err(|_| DeleteTimelineError::Cancelled)?;
1854 :
1855 : // Delete the initdb.tar.zst, which is not always present, but deletion attempts of
1856 : // inexistant objects are not considered errors.
1857 0 : let initdb_path =
1858 0 : remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &self.timeline_id);
1859 0 : self.deletion_queue_client
1860 0 : .push_immediate(vec![initdb_path])
1861 0 : .await
1862 0 : .map_err(|_| DeleteTimelineError::Cancelled)?;
1863 :
1864 : // Do not delete index part yet, it is needed for possible retry. If we remove it first
1865 : // and retry will arrive to different pageserver there wont be any traces of it on remote storage
1866 0 : let timeline_storage_path = remote_timeline_path(&self.tenant_shard_id, &self.timeline_id);
1867 0 :
1868 0 : // Execute all pending deletions, so that when we proceed to do a listing below, we aren't
1869 0 : // taking the burden of listing all the layers that we already know we should delete.
1870 0 : self.flush_deletion_queue()
1871 0 : .await
1872 0 : .map_err(|_| DeleteTimelineError::Cancelled)?;
1873 :
1874 0 : let cancel = shutdown_token();
1875 :
1876 0 : let remaining = download_retry(
1877 0 : || async {
1878 0 : self.storage_impl
1879 0 : .list(
1880 0 : Some(&timeline_storage_path),
1881 0 : ListingMode::NoDelimiter,
1882 0 : None,
1883 0 : &cancel,
1884 0 : )
1885 0 : .await
1886 0 : },
1887 0 : "list remaining files",
1888 0 : &cancel,
1889 0 : )
1890 0 : .await
1891 0 : .context("list files remaining files")?
1892 : .keys;
1893 :
1894 : // We will delete the current index_part object last, since it acts as a deletion
1895 : // marker via its deleted_at attribute
1896 0 : let latest_index = remaining
1897 0 : .iter()
1898 0 : .filter(|o| {
1899 0 : o.key
1900 0 : .object_name()
1901 0 : .map(|n| n.starts_with(IndexPart::FILE_NAME))
1902 0 : .unwrap_or(false)
1903 0 : })
1904 0 : .filter_map(|o| {
1905 0 : parse_remote_index_path(o.key.clone()).map(|gen_| (o.key.clone(), gen_))
1906 0 : })
1907 0 : .max_by_key(|i| i.1)
1908 0 : .map(|i| i.0.clone())
1909 0 : .unwrap_or(
1910 0 : // No generation-suffixed indices, assume we are dealing with
1911 0 : // a legacy index.
1912 0 : remote_index_path(&self.tenant_shard_id, &self.timeline_id, Generation::none()),
1913 0 : );
1914 0 :
1915 0 : let remaining_layers: Vec<RemotePath> = remaining
1916 0 : .into_iter()
1917 0 : .filter_map(|o| {
1918 0 : if o.key == latest_index || o.key.object_name() == Some(INITDB_PRESERVED_PATH) {
1919 0 : None
1920 : } else {
1921 0 : Some(o.key)
1922 : }
1923 0 : })
1924 0 : .inspect(|path| {
1925 0 : if let Some(name) = path.object_name() {
1926 0 : info!(%name, "deleting a file not referenced from index_part.json");
1927 : } else {
1928 0 : warn!(%path, "deleting a nameless or non-utf8 object not referenced from index_part.json");
1929 : }
1930 0 : })
1931 0 : .collect();
1932 0 :
1933 0 : let not_referenced_count = remaining_layers.len();
1934 0 : if !remaining_layers.is_empty() {
1935 0 : self.deletion_queue_client
1936 0 : .push_immediate(remaining_layers)
1937 0 : .await
1938 0 : .map_err(|_| DeleteTimelineError::Cancelled)?;
1939 0 : }
1940 :
1941 0 : fail::fail_point!("timeline-delete-before-index-delete", |_| {
1942 0 : Err(DeleteTimelineError::Other(anyhow::anyhow!(
1943 0 : "failpoint: timeline-delete-before-index-delete"
1944 0 : )))?
1945 0 : });
1946 :
1947 0 : debug!("enqueuing index part deletion");
1948 0 : self.deletion_queue_client
1949 0 : .push_immediate([latest_index].to_vec())
1950 0 : .await
1951 0 : .map_err(|_| DeleteTimelineError::Cancelled)?;
1952 :
1953 : // Timeline deletion is rare and we have probably emitted a reasonably number of objects: wait
1954 : // for a flush to a persistent deletion list so that we may be sure deletion will occur.
1955 0 : self.flush_deletion_queue()
1956 0 : .await
1957 0 : .map_err(|_| DeleteTimelineError::Cancelled)?;
1958 :
1959 0 : fail::fail_point!("timeline-delete-after-index-delete", |_| {
1960 0 : Err(DeleteTimelineError::Other(anyhow::anyhow!(
1961 0 : "failpoint: timeline-delete-after-index-delete"
1962 0 : )))?
1963 0 : });
1964 :
1965 0 : info!(prefix=%timeline_storage_path, referenced=layer_deletion_count, not_referenced=%not_referenced_count, "done deleting in timeline prefix, including index_part.json");
1966 :
1967 0 : Ok(())
1968 0 : }
1969 :
1970 : /// Pick next tasks from the queue, and start as many of them as possible without violating
1971 : /// the ordering constraints.
1972 : ///
1973 : /// The number of inprogress tasks is limited by `Self::inprogress_tasks`, see `next_ready`.
1974 42962 : fn launch_queued_tasks(self: &Arc<Self>, upload_queue: &mut UploadQueueInitialized) {
1975 65878 : while let Some((mut next_op, coalesced_ops)) = upload_queue.next_ready() {
1976 22916 : debug!("starting op: {next_op}");
1977 :
1978 : // Prepare upload.
1979 22916 : match &mut next_op {
1980 10584 : UploadOp::UploadLayer(layer, meta, mode) => {
1981 10584 : if upload_queue
1982 10584 : .recently_deleted
1983 10584 : .remove(&(layer.layer_desc().layer_name().clone(), meta.generation))
1984 0 : {
1985 0 : *mode = Some(OpType::FlushDeletion);
1986 0 : } else {
1987 10584 : *mode = Some(OpType::MayReorder)
1988 : }
1989 : }
1990 9037 : UploadOp::UploadMetadata { .. } => {}
1991 1891 : UploadOp::Delete(Delete { layers }) => {
1992 3782 : for (name, meta) in layers {
1993 1891 : upload_queue
1994 1891 : .recently_deleted
1995 1891 : .insert((name.clone(), meta.generation));
1996 1891 : }
1997 : }
1998 1404 : UploadOp::Barrier(sender) => {
1999 1404 : sender.send_replace(());
2000 1404 : continue;
2001 : }
2002 0 : UploadOp::Shutdown => unreachable!("shutdown is intentionally never popped off"),
2003 : };
2004 :
2005 : // Assign unique ID to this task
2006 21512 : upload_queue.task_counter += 1;
2007 21512 : let upload_task_id = upload_queue.task_counter;
2008 21512 :
2009 21512 : // Add it to the in-progress map
2010 21512 : let task = Arc::new(UploadTask {
2011 21512 : task_id: upload_task_id,
2012 21512 : op: next_op,
2013 21512 : coalesced_ops,
2014 21512 : retries: AtomicU32::new(0),
2015 21512 : });
2016 21512 : upload_queue
2017 21512 : .inprogress_tasks
2018 21512 : .insert(task.task_id, Arc::clone(&task));
2019 21512 :
2020 21512 : // Spawn task to perform the task
2021 21512 : let self_rc = Arc::clone(self);
2022 21512 : let tenant_shard_id = self.tenant_shard_id;
2023 21512 : let timeline_id = self.timeline_id;
2024 21512 : task_mgr::spawn(
2025 21512 : &self.runtime,
2026 21512 : TaskKind::RemoteUploadTask,
2027 21512 : self.tenant_shard_id,
2028 21512 : Some(self.timeline_id),
2029 21512 : "remote upload",
2030 21093 : async move {
2031 21093 : self_rc.perform_upload_task(task).await;
2032 20170 : Ok(())
2033 20170 : }
2034 21512 : .instrument(info_span!(parent: None, "remote_upload", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), %timeline_id, %upload_task_id)),
2035 : );
2036 :
2037 : // Loop back to process next task
2038 : }
2039 42962 : }
2040 :
2041 : ///
2042 : /// Perform an upload task.
2043 : ///
2044 : /// The task is in the `inprogress_tasks` list. This function will try to
2045 : /// execute it, retrying forever. On successful completion, the task is
2046 : /// removed it from the `inprogress_tasks` list, and any next task(s) in the
2047 : /// queue that were waiting by the completion are launched.
2048 : ///
2049 : /// The task can be shut down, however. That leads to stopping the whole
2050 : /// queue.
2051 : ///
2052 21093 : async fn perform_upload_task(self: &Arc<Self>, task: Arc<UploadTask>) {
2053 21093 : let cancel = shutdown_token();
2054 : // Loop to retry until it completes.
2055 : loop {
2056 : // If we're requested to shut down, close up shop and exit.
2057 : //
2058 : // Note: We only check for the shutdown requests between retries, so
2059 : // if a shutdown request arrives while we're busy uploading, in the
2060 : // upload::upload:*() call below, we will wait not exit until it has
2061 : // finished. We probably could cancel the upload by simply dropping
2062 : // the Future, but we're not 100% sure if the remote storage library
2063 : // is cancellation safe, so we don't dare to do that. Hopefully, the
2064 : // upload finishes or times out soon enough.
2065 21093 : if cancel.is_cancelled() {
2066 0 : info!("upload task cancelled by shutdown request");
2067 0 : self.stop();
2068 0 : return;
2069 21093 : }
2070 21093 :
2071 21093 : // Assert that we don't modify a layer that's referenced by the current index.
2072 21093 : if cfg!(debug_assertions) {
2073 21093 : let modified = match &task.op {
2074 10228 : UploadOp::UploadLayer(layer, layer_metadata, _) => {
2075 10228 : vec![(layer.layer_desc().layer_name(), layer_metadata)]
2076 : }
2077 1891 : UploadOp::Delete(delete) => {
2078 1891 : delete.layers.iter().map(|(n, m)| (n.clone(), m)).collect()
2079 : }
2080 : // These don't modify layers.
2081 8974 : UploadOp::UploadMetadata { .. } => Vec::new(),
2082 0 : UploadOp::Barrier(_) => Vec::new(),
2083 0 : UploadOp::Shutdown => Vec::new(),
2084 : };
2085 21093 : if let Ok(queue) = self.upload_queue.lock().unwrap().initialized_mut() {
2086 33164 : for (ref name, metadata) in modified {
2087 12119 : debug_assert!(
2088 12119 : !queue.clean.0.references(name, metadata),
2089 24 : "layer {name} modified while referenced by index",
2090 : );
2091 : }
2092 24 : }
2093 0 : }
2094 :
2095 21069 : let upload_result: anyhow::Result<()> = match &task.op {
2096 10228 : UploadOp::UploadLayer(layer, layer_metadata, mode) => {
2097 : // TODO: check if this mechanism can be removed now that can_bypass() performs
2098 : // conflict checks during scheduling.
2099 10228 : if let Some(OpType::FlushDeletion) = mode {
2100 0 : if self.config.read().unwrap().block_deletions {
2101 : // Of course, this is not efficient... but usually the queue should be empty.
2102 0 : let mut queue_locked = self.upload_queue.lock().unwrap();
2103 0 : let mut detected = false;
2104 0 : if let Ok(queue) = queue_locked.initialized_mut() {
2105 0 : for list in queue.blocked_deletions.iter_mut() {
2106 0 : list.layers.retain(|(name, meta)| {
2107 0 : if name == &layer.layer_desc().layer_name()
2108 0 : && meta.generation == layer_metadata.generation
2109 : {
2110 0 : detected = true;
2111 0 : // remove the layer from deletion queue
2112 0 : false
2113 : } else {
2114 : // keep the layer
2115 0 : true
2116 : }
2117 0 : });
2118 0 : }
2119 0 : }
2120 0 : if detected {
2121 0 : info!(
2122 0 : "cancelled blocked deletion of layer {} at gen {:?}",
2123 0 : layer.layer_desc().layer_name(),
2124 : layer_metadata.generation
2125 : );
2126 0 : }
2127 : } else {
2128 : // TODO: we did not guarantee that upload task starts after deletion task, so there could be possibly race conditions
2129 : // that we still get the layer deleted. But this only happens if someone creates a layer immediately after it's deleted,
2130 : // which is not possible in the current system.
2131 0 : info!(
2132 0 : "waiting for deletion queue flush to complete before uploading layer {} at gen {:?}",
2133 0 : layer.layer_desc().layer_name(),
2134 : layer_metadata.generation
2135 : );
2136 : {
2137 : // We are going to flush, we can clean up the recently deleted list.
2138 0 : let mut queue_locked = self.upload_queue.lock().unwrap();
2139 0 : if let Ok(queue) = queue_locked.initialized_mut() {
2140 0 : queue.recently_deleted.clear();
2141 0 : }
2142 : }
2143 0 : if let Err(e) = self.deletion_queue_client.flush_execute().await {
2144 0 : warn!(
2145 0 : "failed to flush the deletion queue before uploading layer {} at gen {:?}, still proceeding to upload: {e:#} ",
2146 0 : layer.layer_desc().layer_name(),
2147 : layer_metadata.generation
2148 : );
2149 : } else {
2150 0 : info!(
2151 0 : "done flushing deletion queue before uploading layer {} at gen {:?}",
2152 0 : layer.layer_desc().layer_name(),
2153 : layer_metadata.generation
2154 : );
2155 : }
2156 : }
2157 10228 : }
2158 10228 : let local_path = layer.local_path();
2159 10228 :
2160 10228 : // We should only be uploading layers created by this `Tenant`'s lifetime, so
2161 10228 : // the metadata in the upload should always match our current generation.
2162 10228 : assert_eq!(layer_metadata.generation, self.generation);
2163 :
2164 10228 : let remote_path = remote_layer_path(
2165 10228 : &self.tenant_shard_id.tenant_id,
2166 10228 : &self.timeline_id,
2167 10228 : layer_metadata.shard,
2168 10228 : &layer.layer_desc().layer_name(),
2169 10228 : layer_metadata.generation,
2170 10228 : );
2171 10228 :
2172 10228 : upload::upload_timeline_layer(
2173 10228 : &self.storage_impl,
2174 10228 : local_path,
2175 10228 : &remote_path,
2176 10228 : layer_metadata.file_size,
2177 10228 : &self.cancel,
2178 10228 : )
2179 10228 : .measure_remote_op(
2180 10228 : Some(TaskKind::RemoteUploadTask),
2181 10228 : RemoteOpFileKind::Layer,
2182 10228 : RemoteOpKind::Upload,
2183 10228 : Arc::clone(&self.metrics),
2184 10228 : )
2185 10228 : .await
2186 : }
2187 8974 : UploadOp::UploadMetadata { uploaded } => {
2188 8974 : let res = upload::upload_index_part(
2189 8974 : &self.storage_impl,
2190 8974 : &self.tenant_shard_id,
2191 8974 : &self.timeline_id,
2192 8974 : self.generation,
2193 8974 : uploaded,
2194 8974 : &self.cancel,
2195 8974 : )
2196 8974 : .measure_remote_op(
2197 8974 : Some(TaskKind::RemoteUploadTask),
2198 8974 : RemoteOpFileKind::Index,
2199 8974 : RemoteOpKind::Upload,
2200 8974 : Arc::clone(&self.metrics),
2201 8974 : )
2202 8974 : .await;
2203 8905 : if res.is_ok() {
2204 8905 : self.update_remote_physical_size_gauge(Some(uploaded));
2205 8905 : let mention_having_future_layers = if cfg!(feature = "testing") {
2206 8905 : uploaded
2207 8905 : .layer_metadata
2208 8905 : .keys()
2209 104498 : .any(|x| x.is_in_future(uploaded.metadata.disk_consistent_lsn()))
2210 : } else {
2211 0 : false
2212 : };
2213 8905 : if mention_having_future_layers {
2214 : // find rationale near crate::tenant::timeline::init::cleanup_future_layer
2215 372 : tracing::info!(
2216 0 : disk_consistent_lsn = %uploaded.metadata.disk_consistent_lsn(),
2217 0 : "uploaded an index_part.json with future layers -- this is ok! if shutdown now, expect future layer cleanup"
2218 : );
2219 8533 : }
2220 0 : }
2221 8905 : res
2222 : }
2223 : // TODO: this should wait for the deletion to be executed by the deletion queue.
2224 : // Otherwise, the deletion may race with an upload and wrongfully delete a newer
2225 : // file. Some of the above logic attempts to work around this, it should be replaced
2226 : // by the upload queue ordering guarantees (see `can_bypass`). See:
2227 : // <https://github.com/neondatabase/neon/issues/10283>.
2228 1867 : UploadOp::Delete(delete) => {
2229 1867 : if self.config.read().unwrap().block_deletions {
2230 0 : let mut queue_locked = self.upload_queue.lock().unwrap();
2231 0 : if let Ok(queue) = queue_locked.initialized_mut() {
2232 0 : queue.blocked_deletions.push(delete.clone());
2233 0 : }
2234 0 : Ok(())
2235 : } else {
2236 1867 : pausable_failpoint!("before-delete-layer-pausable");
2237 1867 : self.deletion_queue_client
2238 1867 : .push_layers(
2239 1867 : self.tenant_shard_id,
2240 1867 : self.timeline_id,
2241 1867 : self.generation,
2242 1867 : delete.layers.clone(),
2243 1867 : )
2244 1867 : .map_err(|e| anyhow::anyhow!(e))
2245 : }
2246 : }
2247 0 : unexpected @ UploadOp::Barrier(_) | unexpected @ UploadOp::Shutdown => {
2248 : // unreachable. Barrier operations are handled synchronously in
2249 : // launch_queued_tasks
2250 0 : warn!("unexpected {unexpected:?} operation in perform_upload_task");
2251 0 : break;
2252 : }
2253 : };
2254 :
2255 0 : match upload_result {
2256 : Ok(()) => {
2257 20146 : break;
2258 : }
2259 0 : Err(e) if TimeoutOrCancel::caused_by_cancel(&e) => {
2260 0 : // loop around to do the proper stopping
2261 0 : continue;
2262 : }
2263 0 : Err(e) => {
2264 0 : let retries = task.retries.fetch_add(1, Ordering::SeqCst);
2265 0 :
2266 0 : // Uploads can fail due to rate limits (IAM, S3), spurious network problems,
2267 0 : // or other external reasons. Such issues are relatively regular, so log them
2268 0 : // at info level at first, and only WARN if the operation fails repeatedly.
2269 0 : //
2270 0 : // (See similar logic for downloads in `download::download_retry`)
2271 0 : if retries < FAILED_UPLOAD_WARN_THRESHOLD {
2272 0 : info!(
2273 0 : "failed to perform remote task {}, will retry (attempt {}): {:#}",
2274 0 : task.op, retries, e
2275 : );
2276 : } else {
2277 0 : warn!(
2278 0 : "failed to perform remote task {}, will retry (attempt {}): {:?}",
2279 0 : task.op, retries, e
2280 : );
2281 : }
2282 :
2283 : // sleep until it's time to retry, or we're cancelled
2284 0 : exponential_backoff(
2285 0 : retries,
2286 0 : DEFAULT_BASE_BACKOFF_SECONDS,
2287 0 : DEFAULT_MAX_BACKOFF_SECONDS,
2288 0 : &cancel,
2289 0 : )
2290 0 : .await;
2291 : }
2292 : }
2293 : }
2294 :
2295 20146 : let retries = task.retries.load(Ordering::SeqCst);
2296 20146 : if retries > 0 {
2297 0 : info!(
2298 0 : "remote task {} completed successfully after {} retries",
2299 0 : task.op, retries
2300 : );
2301 : } else {
2302 20146 : debug!("remote task {} completed successfully", task.op);
2303 : }
2304 :
2305 : // The task has completed successfully. Remove it from the in-progress list.
2306 20146 : let lsn_update = {
2307 20146 : let mut upload_queue_guard = self.upload_queue.lock().unwrap();
2308 20146 : let upload_queue = match upload_queue_guard.deref_mut() {
2309 0 : UploadQueue::Uninitialized => panic!(
2310 0 : "callers are responsible for ensuring this is only called on an initialized queue"
2311 0 : ),
2312 0 : UploadQueue::Stopped(_stopped) => None,
2313 20146 : UploadQueue::Initialized(qi) => Some(qi),
2314 : };
2315 :
2316 20146 : let upload_queue = match upload_queue {
2317 20146 : Some(upload_queue) => upload_queue,
2318 : None => {
2319 0 : info!("another concurrent task already stopped the queue");
2320 0 : return;
2321 : }
2322 : };
2323 :
2324 20146 : upload_queue.inprogress_tasks.remove(&task.task_id);
2325 :
2326 20146 : let lsn_update = match task.op {
2327 9374 : UploadOp::UploadLayer(_, _, _) => None,
2328 8905 : UploadOp::UploadMetadata { ref uploaded } => {
2329 8905 : // the task id is reused as a monotonicity check for storing the "clean"
2330 8905 : // IndexPart.
2331 8905 : let last_updater = upload_queue.clean.1;
2332 8905 : let is_later = last_updater.is_some_and(|task_id| task_id < task.task_id);
2333 8905 : let monotone = is_later || last_updater.is_none();
2334 :
2335 8905 : assert!(
2336 8905 : monotone,
2337 0 : "no two index uploads should be completing at the same time, prev={last_updater:?}, task.task_id={}",
2338 0 : task.task_id
2339 : );
2340 :
2341 : // not taking ownership is wasteful
2342 8905 : upload_queue.clean.0.clone_from(uploaded);
2343 8905 : upload_queue.clean.1 = Some(task.task_id);
2344 8905 :
2345 8905 : let lsn = upload_queue.clean.0.metadata.disk_consistent_lsn();
2346 8905 : self.metrics
2347 8905 : .projected_remote_consistent_lsn_gauge
2348 8905 : .set(lsn.0);
2349 8905 :
2350 8905 : if self.generation.is_none() {
2351 : // Legacy mode: skip validating generation
2352 0 : upload_queue.visible_remote_consistent_lsn.store(lsn);
2353 0 : None
2354 8905 : } else if self
2355 8905 : .config
2356 8905 : .read()
2357 8905 : .unwrap()
2358 8905 : .process_remote_consistent_lsn_updates
2359 : {
2360 8905 : Some((lsn, upload_queue.visible_remote_consistent_lsn.clone()))
2361 : } else {
2362 : // Our config disables remote_consistent_lsn updates: drop it.
2363 0 : None
2364 : }
2365 : }
2366 1867 : UploadOp::Delete(_) => None,
2367 0 : UploadOp::Barrier(..) | UploadOp::Shutdown => unreachable!(),
2368 : };
2369 :
2370 : // Launch any queued tasks that were unblocked by this one.
2371 20146 : self.launch_queued_tasks(upload_queue);
2372 20146 : lsn_update
2373 : };
2374 :
2375 20146 : if let Some((lsn, slot)) = lsn_update {
2376 : // Updates to the remote_consistent_lsn we advertise to pageservers
2377 : // are all routed through the DeletionQueue, to enforce important
2378 : // data safety guarantees (see docs/rfcs/025-generation-numbers.md)
2379 8905 : self.deletion_queue_client
2380 8905 : .update_remote_consistent_lsn(
2381 8905 : self.tenant_shard_id,
2382 8905 : self.timeline_id,
2383 8905 : self.generation,
2384 8905 : lsn,
2385 8905 : slot,
2386 8905 : )
2387 8905 : .await;
2388 11241 : }
2389 :
2390 20146 : self.metric_end(&task.op);
2391 20146 : for coalesced_op in &task.coalesced_ops {
2392 28 : self.metric_end(coalesced_op);
2393 28 : }
2394 20146 : }
2395 :
2396 43242 : fn metric_impl(
2397 43242 : &self,
2398 43242 : op: &UploadOp,
2399 43242 : ) -> Option<(
2400 43242 : RemoteOpFileKind,
2401 43242 : RemoteOpKind,
2402 43242 : RemoteTimelineClientMetricsCallTrackSize,
2403 43242 : )> {
2404 : use RemoteTimelineClientMetricsCallTrackSize::DontTrackSize;
2405 43242 : let res = match op {
2406 19958 : UploadOp::UploadLayer(_, m, _) => (
2407 19958 : RemoteOpFileKind::Layer,
2408 19958 : RemoteOpKind::Upload,
2409 19958 : RemoteTimelineClientMetricsCallTrackSize::Bytes(m.file_size),
2410 19958 : ),
2411 18293 : UploadOp::UploadMetadata { .. } => (
2412 18293 : RemoteOpFileKind::Index,
2413 18293 : RemoteOpKind::Upload,
2414 18293 : DontTrackSize {
2415 18293 : reason: "metadata uploads are tiny",
2416 18293 : },
2417 18293 : ),
2418 4943 : UploadOp::Delete(_delete) => (
2419 4943 : RemoteOpFileKind::Layer,
2420 4943 : RemoteOpKind::Delete,
2421 4943 : DontTrackSize {
2422 4943 : reason: "should we track deletes? positive or negative sign?",
2423 4943 : },
2424 4943 : ),
2425 : UploadOp::Barrier(..) | UploadOp::Shutdown => {
2426 : // we do not account these
2427 48 : return None;
2428 : }
2429 : };
2430 43194 : Some(res)
2431 43242 : }
2432 :
2433 23020 : fn metric_begin(&self, op: &UploadOp) {
2434 23020 : let (file_kind, op_kind, track_bytes) = match self.metric_impl(op) {
2435 23020 : Some(x) => x,
2436 0 : None => return,
2437 : };
2438 23020 : let guard = self.metrics.call_begin(&file_kind, &op_kind, track_bytes);
2439 23020 : guard.will_decrement_manually(); // in metric_end(), see right below
2440 23020 : }
2441 :
2442 20222 : fn metric_end(&self, op: &UploadOp) {
2443 20222 : let (file_kind, op_kind, track_bytes) = match self.metric_impl(op) {
2444 20174 : Some(x) => x,
2445 48 : None => return,
2446 : };
2447 20174 : self.metrics.call_end(&file_kind, &op_kind, track_bytes);
2448 20222 : }
2449 :
2450 : /// Close the upload queue for new operations and cancel queued operations.
2451 : ///
2452 : /// Use [`RemoteTimelineClient::shutdown`] for graceful stop.
2453 : ///
2454 : /// In-progress operations will still be running after this function returns.
2455 : /// Use `task_mgr::shutdown_tasks(Some(TaskKind::RemoteUploadTask), Some(self.tenant_shard_id), Some(timeline_id))`
2456 : /// to wait for them to complete, after calling this function.
2457 108 : pub(crate) fn stop(&self) {
2458 108 : // Whichever *task* for this RemoteTimelineClient grabs the mutex first will transition the queue
2459 108 : // into stopped state, thereby dropping all off the queued *ops* which haven't become *tasks* yet.
2460 108 : // The other *tasks* will come here and observe an already shut down queue and hence simply wrap up their business.
2461 108 : let mut guard = self.upload_queue.lock().unwrap();
2462 108 : self.stop_impl(&mut guard);
2463 108 : }
2464 :
2465 108 : fn stop_impl(&self, guard: &mut std::sync::MutexGuard<UploadQueue>) {
2466 108 : match &mut **guard {
2467 : UploadQueue::Uninitialized => {
2468 0 : info!("UploadQueue is in state Uninitialized, nothing to do");
2469 0 : **guard = UploadQueue::Stopped(UploadQueueStopped::Uninitialized);
2470 : }
2471 : UploadQueue::Stopped(_) => {
2472 : // nothing to do
2473 48 : info!("another concurrent task already shut down the queue");
2474 : }
2475 60 : UploadQueue::Initialized(initialized) => {
2476 60 : info!("shutting down upload queue");
2477 :
2478 : // Replace the queue with the Stopped state, taking ownership of the old
2479 : // Initialized queue. We will do some checks on it, and then drop it.
2480 60 : let qi = {
2481 : // Here we preserve working version of the upload queue for possible use during deletions.
2482 : // In-place replace of Initialized to Stopped can be done with the help of https://github.com/Sgeo/take_mut
2483 : // but for this use case it doesnt really makes sense to bring unsafe code only for this usage point.
2484 : // Deletion is not really perf sensitive so there shouldnt be any problems with cloning a fraction of it.
2485 60 : let upload_queue_for_deletion = UploadQueueInitialized {
2486 60 : inprogress_limit: initialized.inprogress_limit,
2487 60 : task_counter: 0,
2488 60 : dirty: initialized.dirty.clone(),
2489 60 : clean: initialized.clean.clone(),
2490 60 : latest_files_changes_since_metadata_upload_scheduled: 0,
2491 60 : visible_remote_consistent_lsn: initialized
2492 60 : .visible_remote_consistent_lsn
2493 60 : .clone(),
2494 60 : inprogress_tasks: HashMap::default(),
2495 60 : queued_operations: VecDeque::default(),
2496 60 : #[cfg(feature = "testing")]
2497 60 : dangling_files: HashMap::default(),
2498 60 : blocked_deletions: Vec::new(),
2499 60 : shutting_down: false,
2500 60 : shutdown_ready: Arc::new(tokio::sync::Semaphore::new(0)),
2501 60 : recently_deleted: HashSet::new(),
2502 60 : };
2503 60 :
2504 60 : let upload_queue = std::mem::replace(
2505 60 : &mut **guard,
2506 60 : UploadQueue::Stopped(UploadQueueStopped::Deletable(
2507 60 : UploadQueueStoppedDeletable {
2508 60 : upload_queue_for_deletion,
2509 60 : deleted_at: SetDeletedFlagProgress::NotRunning,
2510 60 : },
2511 60 : )),
2512 60 : );
2513 60 : if let UploadQueue::Initialized(qi) = upload_queue {
2514 60 : qi
2515 : } else {
2516 0 : unreachable!("we checked in the match above that it is Initialized");
2517 : }
2518 : };
2519 :
2520 : // We don't need to do anything here for in-progress tasks. They will finish
2521 : // on their own, decrement the unfinished-task counter themselves, and observe
2522 : // that the queue is Stopped.
2523 60 : drop(qi.inprogress_tasks);
2524 :
2525 : // Tear down queued ops
2526 60 : for op in qi.queued_operations.into_iter() {
2527 48 : self.metric_end(&op);
2528 48 : // Dropping UploadOp::Barrier() here will make wait_completion() return with an Err()
2529 48 : // which is exactly what we want to happen.
2530 48 : drop(op);
2531 48 : }
2532 : }
2533 : }
2534 108 : }
2535 :
2536 : /// Returns an accessor which will hold the UploadQueue mutex for accessing the upload queue
2537 : /// externally to RemoteTimelineClient.
2538 0 : pub(crate) fn initialized_upload_queue(
2539 0 : &self,
2540 0 : ) -> Result<UploadQueueAccessor<'_>, NotInitialized> {
2541 0 : let mut inner = self.upload_queue.lock().unwrap();
2542 0 : inner.initialized_mut()?;
2543 0 : Ok(UploadQueueAccessor { inner })
2544 0 : }
2545 :
2546 48 : pub(crate) fn no_pending_work(&self) -> bool {
2547 48 : let inner = self.upload_queue.lock().unwrap();
2548 48 : match &*inner {
2549 : UploadQueue::Uninitialized
2550 0 : | UploadQueue::Stopped(UploadQueueStopped::Uninitialized) => true,
2551 48 : UploadQueue::Stopped(UploadQueueStopped::Deletable(x)) => {
2552 48 : x.upload_queue_for_deletion.no_pending_work()
2553 : }
2554 0 : UploadQueue::Initialized(x) => x.no_pending_work(),
2555 : }
2556 48 : }
2557 :
2558 : /// 'foreign' in the sense that it does not belong to this tenant shard. This method
2559 : /// is used during GC for other shards to get the index of shard zero.
2560 0 : pub(crate) async fn download_foreign_index(
2561 0 : &self,
2562 0 : shard_number: ShardNumber,
2563 0 : cancel: &CancellationToken,
2564 0 : ) -> Result<(IndexPart, Generation, std::time::SystemTime), DownloadError> {
2565 0 : let foreign_shard_id = TenantShardId {
2566 0 : shard_number,
2567 0 : shard_count: self.tenant_shard_id.shard_count,
2568 0 : tenant_id: self.tenant_shard_id.tenant_id,
2569 0 : };
2570 0 : download_index_part(
2571 0 : &self.storage_impl,
2572 0 : &foreign_shard_id,
2573 0 : &self.timeline_id,
2574 0 : Generation::MAX,
2575 0 : cancel,
2576 0 : )
2577 0 : .await
2578 0 : }
2579 : }
2580 :
2581 : pub(crate) struct UploadQueueAccessor<'a> {
2582 : inner: std::sync::MutexGuard<'a, UploadQueue>,
2583 : }
2584 :
2585 : impl UploadQueueAccessor<'_> {
2586 0 : pub(crate) fn latest_uploaded_index_part(&self) -> &IndexPart {
2587 0 : match &*self.inner {
2588 0 : UploadQueue::Initialized(x) => &x.clean.0,
2589 : UploadQueue::Uninitialized | UploadQueue::Stopped(_) => {
2590 0 : unreachable!("checked before constructing")
2591 : }
2592 : }
2593 0 : }
2594 : }
2595 :
2596 0 : pub fn remote_tenant_path(tenant_shard_id: &TenantShardId) -> RemotePath {
2597 0 : let path = format!("tenants/{tenant_shard_id}");
2598 0 : RemotePath::from_string(&path).expect("Failed to construct path")
2599 0 : }
2600 :
2601 5472 : pub fn remote_tenant_manifest_path(
2602 5472 : tenant_shard_id: &TenantShardId,
2603 5472 : generation: Generation,
2604 5472 : ) -> RemotePath {
2605 5472 : let path = format!(
2606 5472 : "tenants/{tenant_shard_id}/tenant-manifest{}.json",
2607 5472 : generation.get_suffix()
2608 5472 : );
2609 5472 : RemotePath::from_string(&path).expect("Failed to construct path")
2610 5472 : }
2611 :
2612 : /// Prefix to all generations' manifest objects in a tenant shard
2613 1392 : pub fn remote_tenant_manifest_prefix(tenant_shard_id: &TenantShardId) -> RemotePath {
2614 1392 : let path = format!("tenants/{tenant_shard_id}/tenant-manifest",);
2615 1392 : RemotePath::from_string(&path).expect("Failed to construct path")
2616 1392 : }
2617 :
2618 1572 : pub fn remote_timelines_path(tenant_shard_id: &TenantShardId) -> RemotePath {
2619 1572 : let path = format!("tenants/{tenant_shard_id}/{TIMELINES_SEGMENT_NAME}");
2620 1572 : RemotePath::from_string(&path).expect("Failed to construct path")
2621 1572 : }
2622 :
2623 0 : fn remote_timelines_path_unsharded(tenant_id: &TenantId) -> RemotePath {
2624 0 : let path = format!("tenants/{tenant_id}/{TIMELINES_SEGMENT_NAME}");
2625 0 : RemotePath::from_string(&path).expect("Failed to construct path")
2626 0 : }
2627 :
2628 180 : pub fn remote_timeline_path(
2629 180 : tenant_shard_id: &TenantShardId,
2630 180 : timeline_id: &TimelineId,
2631 180 : ) -> RemotePath {
2632 180 : remote_timelines_path(tenant_shard_id).join(Utf8Path::new(&timeline_id.to_string()))
2633 180 : }
2634 :
2635 : /// Obtains the path of the given Layer in the remote
2636 : ///
2637 : /// Note that the shard component of a remote layer path is _not_ always the same
2638 : /// as in the TenantShardId of the caller: tenants may reference layers from a different
2639 : /// ShardIndex. Use the ShardIndex from the layer's metadata.
2640 12108 : pub fn remote_layer_path(
2641 12108 : tenant_id: &TenantId,
2642 12108 : timeline_id: &TimelineId,
2643 12108 : shard: ShardIndex,
2644 12108 : layer_file_name: &LayerName,
2645 12108 : generation: Generation,
2646 12108 : ) -> RemotePath {
2647 12108 : // Generation-aware key format
2648 12108 : let path = format!(
2649 12108 : "tenants/{tenant_id}{0}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{1}{2}",
2650 12108 : shard.get_suffix(),
2651 12108 : layer_file_name,
2652 12108 : generation.get_suffix()
2653 12108 : );
2654 12108 :
2655 12108 : RemotePath::from_string(&path).expect("Failed to construct path")
2656 12108 : }
2657 :
2658 : /// Returns true if a and b have the same layer path within a tenant/timeline. This is essentially
2659 : /// remote_layer_path(a) == remote_layer_path(b) without the string allocations.
2660 : ///
2661 : /// TODO: there should be a variant of LayerName for the physical path that contains information
2662 : /// about the shard and generation, such that this could be replaced by a simple comparison.
2663 7050665 : pub fn is_same_remote_layer_path(
2664 7050665 : aname: &LayerName,
2665 7050665 : ameta: &LayerFileMetadata,
2666 7050665 : bname: &LayerName,
2667 7050665 : bmeta: &LayerFileMetadata,
2668 7050665 : ) -> bool {
2669 7050665 : // NB: don't assert remote_layer_path(a) == remote_layer_path(b); too expensive even for debug.
2670 7050665 : aname == bname && ameta.shard == bmeta.shard && ameta.generation == bmeta.generation
2671 7050665 : }
2672 :
2673 24 : pub fn remote_initdb_archive_path(tenant_id: &TenantId, timeline_id: &TimelineId) -> RemotePath {
2674 24 : RemotePath::from_string(&format!(
2675 24 : "tenants/{tenant_id}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{INITDB_PATH}"
2676 24 : ))
2677 24 : .expect("Failed to construct path")
2678 24 : }
2679 :
2680 12 : pub fn remote_initdb_preserved_archive_path(
2681 12 : tenant_id: &TenantId,
2682 12 : timeline_id: &TimelineId,
2683 12 : ) -> RemotePath {
2684 12 : RemotePath::from_string(&format!(
2685 12 : "tenants/{tenant_id}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{INITDB_PRESERVED_PATH}"
2686 12 : ))
2687 12 : .expect("Failed to construct path")
2688 12 : }
2689 :
2690 9358 : pub fn remote_index_path(
2691 9358 : tenant_shard_id: &TenantShardId,
2692 9358 : timeline_id: &TimelineId,
2693 9358 : generation: Generation,
2694 9358 : ) -> RemotePath {
2695 9358 : RemotePath::from_string(&format!(
2696 9358 : "tenants/{tenant_shard_id}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{0}{1}",
2697 9358 : IndexPart::FILE_NAME,
2698 9358 : generation.get_suffix()
2699 9358 : ))
2700 9358 : .expect("Failed to construct path")
2701 9358 : }
2702 :
2703 0 : pub(crate) fn remote_heatmap_path(tenant_shard_id: &TenantShardId) -> RemotePath {
2704 0 : RemotePath::from_string(&format!(
2705 0 : "tenants/{tenant_shard_id}/{TENANT_HEATMAP_BASENAME}"
2706 0 : ))
2707 0 : .expect("Failed to construct path")
2708 0 : }
2709 :
2710 : /// Given the key of an index, parse out the generation part of the name
2711 108 : pub fn parse_remote_index_path(path: RemotePath) -> Option<Generation> {
2712 108 : let file_name = match path.get_path().file_name() {
2713 108 : Some(f) => f,
2714 : None => {
2715 : // Unexpected: we should be seeing index_part.json paths only
2716 0 : tracing::warn!("Malformed index key {}", path);
2717 0 : return None;
2718 : }
2719 : };
2720 :
2721 108 : match file_name.split_once('-') {
2722 72 : Some((_, gen_suffix)) => Generation::parse_suffix(gen_suffix),
2723 36 : None => None,
2724 : }
2725 108 : }
2726 :
2727 : /// Given the key of a tenant manifest, parse out the generation number
2728 0 : pub fn parse_remote_tenant_manifest_path(path: RemotePath) -> Option<Generation> {
2729 : static RE: OnceLock<Regex> = OnceLock::new();
2730 0 : let re = RE.get_or_init(|| Regex::new(r".*tenant-manifest-([0-9a-f]{8}).json").unwrap());
2731 0 : re.captures(path.get_path().as_str())
2732 0 : .and_then(|c| c.get(1))
2733 0 : .and_then(|m| Generation::parse_suffix(m.as_str()))
2734 0 : }
2735 :
2736 : #[cfg(test)]
2737 : mod tests {
2738 : use std::collections::HashSet;
2739 :
2740 : use super::*;
2741 : use crate::DEFAULT_PG_VERSION;
2742 : use crate::context::RequestContext;
2743 : use crate::tenant::config::AttachmentMode;
2744 : use crate::tenant::harness::{TIMELINE_ID, TenantHarness};
2745 : use crate::tenant::storage_layer::layer::local_layer_path;
2746 : use crate::tenant::{TenantShard, Timeline};
2747 :
2748 48 : pub(super) fn dummy_contents(name: &str) -> Vec<u8> {
2749 48 : format!("contents for {name}").into()
2750 48 : }
2751 :
2752 12 : pub(super) fn dummy_metadata(disk_consistent_lsn: Lsn) -> TimelineMetadata {
2753 12 : let metadata = TimelineMetadata::new(
2754 12 : disk_consistent_lsn,
2755 12 : None,
2756 12 : None,
2757 12 : Lsn(0),
2758 12 : Lsn(0),
2759 12 : Lsn(0),
2760 12 : // Any version will do
2761 12 : // but it should be consistent with the one in the tests
2762 12 : crate::DEFAULT_PG_VERSION,
2763 12 : );
2764 12 :
2765 12 : // go through serialize + deserialize to fix the header, including checksum
2766 12 : TimelineMetadata::from_bytes(&metadata.to_bytes().unwrap()).unwrap()
2767 12 : }
2768 :
2769 12 : fn assert_file_list(a: &HashSet<LayerName>, b: &[&str]) {
2770 36 : let mut avec: Vec<String> = a.iter().map(|x| x.to_string()).collect();
2771 12 : avec.sort();
2772 12 :
2773 12 : let mut bvec = b.to_vec();
2774 12 : bvec.sort_unstable();
2775 12 :
2776 12 : assert_eq!(avec, bvec);
2777 12 : }
2778 :
2779 24 : fn assert_remote_files(expected: &[&str], remote_path: &Utf8Path, generation: Generation) {
2780 24 : let mut expected: Vec<String> = expected
2781 24 : .iter()
2782 96 : .map(|x| format!("{}{}", x, generation.get_suffix()))
2783 24 : .collect();
2784 24 : expected.sort();
2785 24 :
2786 24 : let mut found: Vec<String> = Vec::new();
2787 96 : for entry in std::fs::read_dir(remote_path).unwrap().flatten() {
2788 96 : let entry_name = entry.file_name();
2789 96 : let fname = entry_name.to_str().unwrap();
2790 96 : found.push(String::from(fname));
2791 96 : }
2792 24 : found.sort();
2793 24 :
2794 24 : assert_eq!(found, expected);
2795 24 : }
2796 :
2797 : struct TestSetup {
2798 : harness: TenantHarness,
2799 : tenant: Arc<TenantShard>,
2800 : timeline: Arc<Timeline>,
2801 : tenant_ctx: RequestContext,
2802 : }
2803 :
2804 : impl TestSetup {
2805 48 : async fn new(test_name: &str) -> anyhow::Result<Self> {
2806 48 : let test_name = Box::leak(Box::new(format!("remote_timeline_client__{test_name}")));
2807 48 : let harness = TenantHarness::create(test_name).await?;
2808 48 : let (tenant, ctx) = harness.load().await;
2809 :
2810 48 : let timeline = tenant
2811 48 : .create_test_timeline(TIMELINE_ID, Lsn(8), DEFAULT_PG_VERSION, &ctx)
2812 48 : .await?;
2813 :
2814 48 : Ok(Self {
2815 48 : harness,
2816 48 : tenant,
2817 48 : timeline,
2818 48 : tenant_ctx: ctx,
2819 48 : })
2820 48 : }
2821 :
2822 : /// Construct a RemoteTimelineClient in an arbitrary generation
2823 60 : fn build_client(&self, generation: Generation) -> Arc<RemoteTimelineClient> {
2824 60 : let location_conf = AttachedLocationConfig {
2825 60 : generation,
2826 60 : attach_mode: AttachmentMode::Single,
2827 60 : };
2828 60 : Arc::new(RemoteTimelineClient {
2829 60 : conf: self.harness.conf,
2830 60 : runtime: tokio::runtime::Handle::current(),
2831 60 : tenant_shard_id: self.harness.tenant_shard_id,
2832 60 : timeline_id: TIMELINE_ID,
2833 60 : generation,
2834 60 : storage_impl: self.harness.remote_storage.clone(),
2835 60 : deletion_queue_client: self.harness.deletion_queue.new_client(),
2836 60 : upload_queue: Mutex::new(UploadQueue::Uninitialized),
2837 60 : metrics: Arc::new(RemoteTimelineClientMetrics::new(
2838 60 : &self.harness.tenant_shard_id,
2839 60 : &TIMELINE_ID,
2840 60 : )),
2841 60 : config: std::sync::RwLock::new(RemoteTimelineClientConfig::from(&location_conf)),
2842 60 : cancel: CancellationToken::new(),
2843 60 : })
2844 60 : }
2845 :
2846 : /// A tracing::Span that satisfies remote_timeline_client methods that assert tenant_id
2847 : /// and timeline_id are present.
2848 36 : fn span(&self) -> tracing::Span {
2849 36 : tracing::info_span!(
2850 : "test",
2851 : tenant_id = %self.harness.tenant_shard_id.tenant_id,
2852 0 : shard_id = %self.harness.tenant_shard_id.shard_slug(),
2853 : timeline_id = %TIMELINE_ID
2854 : )
2855 36 : }
2856 : }
2857 :
2858 : // Test scheduling
2859 : #[tokio::test]
2860 12 : async fn upload_scheduling() {
2861 12 : // Test outline:
2862 12 : //
2863 12 : // Schedule upload of a bunch of layers. Check that they are started immediately, not queued
2864 12 : // Schedule upload of index. Check that it is queued
2865 12 : // let the layer file uploads finish. Check that the index-upload is now started
2866 12 : // let the index-upload finish.
2867 12 : //
2868 12 : // Download back the index.json. Check that the list of files is correct
2869 12 : //
2870 12 : // Schedule upload. Schedule deletion. Check that the deletion is queued
2871 12 : // let upload finish. Check that deletion is now started
2872 12 : // Schedule another deletion. Check that it's launched immediately.
2873 12 : // Schedule index upload. Check that it's queued
2874 12 :
2875 12 : let test_setup = TestSetup::new("upload_scheduling").await.unwrap();
2876 12 : let span = test_setup.span();
2877 12 : let _guard = span.enter();
2878 12 :
2879 12 : let TestSetup {
2880 12 : harness,
2881 12 : tenant: _tenant,
2882 12 : timeline,
2883 12 : tenant_ctx: _tenant_ctx,
2884 12 : } = test_setup;
2885 12 :
2886 12 : let client = &timeline.remote_client;
2887 12 :
2888 12 : // Download back the index.json, and check that the list of files is correct
2889 12 : let initial_index_part = match client
2890 12 : .download_index_file(&CancellationToken::new())
2891 12 : .await
2892 12 : .unwrap()
2893 12 : {
2894 12 : MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
2895 12 : MaybeDeletedIndexPart::Deleted(_) => panic!("unexpectedly got deleted index part"),
2896 12 : };
2897 12 : let initial_layers = initial_index_part
2898 12 : .layer_metadata
2899 12 : .keys()
2900 12 : .map(|f| f.to_owned())
2901 12 : .collect::<HashSet<LayerName>>();
2902 12 : let initial_layer = {
2903 12 : assert!(initial_layers.len() == 1);
2904 12 : initial_layers.into_iter().next().unwrap()
2905 12 : };
2906 12 :
2907 12 : let timeline_path = harness.timeline_path(&TIMELINE_ID);
2908 12 :
2909 12 : println!("workdir: {}", harness.conf.workdir);
2910 12 :
2911 12 : let remote_timeline_dir = harness
2912 12 : .remote_fs_dir
2913 12 : .join(timeline_path.strip_prefix(&harness.conf.workdir).unwrap());
2914 12 : println!("remote_timeline_dir: {remote_timeline_dir}");
2915 12 :
2916 12 : let generation = harness.generation;
2917 12 : let shard = harness.shard;
2918 12 :
2919 12 : // Create a couple of dummy files, schedule upload for them
2920 12 :
2921 12 : let layers = [
2922 12 : ("000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D8-00000000016B5A51".parse().unwrap(), dummy_contents("foo")),
2923 12 : ("000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D9-00000000016B5A52".parse().unwrap(), dummy_contents("bar")),
2924 12 : ("000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59DA-00000000016B5A53".parse().unwrap(), dummy_contents("baz"))
2925 12 : ]
2926 12 : .into_iter()
2927 36 : .map(|(name, contents): (LayerName, Vec<u8>)| {
2928 36 :
2929 36 : let local_path = local_layer_path(
2930 36 : harness.conf,
2931 36 : &timeline.tenant_shard_id,
2932 36 : &timeline.timeline_id,
2933 36 : &name,
2934 36 : &generation,
2935 36 : );
2936 36 : std::fs::write(&local_path, &contents).unwrap();
2937 36 :
2938 36 : Layer::for_resident(
2939 36 : harness.conf,
2940 36 : &timeline,
2941 36 : local_path,
2942 36 : name,
2943 36 : LayerFileMetadata::new(contents.len() as u64, generation, shard),
2944 36 : )
2945 36 : }).collect::<Vec<_>>();
2946 12 :
2947 12 : client
2948 12 : .schedule_layer_file_upload(layers[0].clone())
2949 12 : .unwrap();
2950 12 : client
2951 12 : .schedule_layer_file_upload(layers[1].clone())
2952 12 : .unwrap();
2953 12 :
2954 12 : // Check that they are started immediately, not queued
2955 12 : //
2956 12 : // this works because we running within block_on, so any futures are now queued up until
2957 12 : // our next await point.
2958 12 : {
2959 12 : let mut guard = client.upload_queue.lock().unwrap();
2960 12 : let upload_queue = guard.initialized_mut().unwrap();
2961 12 : assert!(upload_queue.queued_operations.is_empty());
2962 12 : assert_eq!(upload_queue.inprogress_tasks.len(), 2);
2963 12 : assert_eq!(upload_queue.num_inprogress_layer_uploads(), 2);
2964 12 :
2965 12 : // also check that `latest_file_changes` was updated
2966 12 : assert!(upload_queue.latest_files_changes_since_metadata_upload_scheduled == 2);
2967 12 : }
2968 12 :
2969 12 : // Schedule upload of index. Check that it is queued
2970 12 : let metadata = dummy_metadata(Lsn(0x20));
2971 12 : client
2972 12 : .schedule_index_upload_for_full_metadata_update(&metadata)
2973 12 : .unwrap();
2974 12 : {
2975 12 : let mut guard = client.upload_queue.lock().unwrap();
2976 12 : let upload_queue = guard.initialized_mut().unwrap();
2977 12 : assert!(upload_queue.queued_operations.len() == 1);
2978 12 : assert!(upload_queue.latest_files_changes_since_metadata_upload_scheduled == 0);
2979 12 : }
2980 12 :
2981 12 : // Wait for the uploads to finish
2982 12 : client.wait_completion().await.unwrap();
2983 12 : {
2984 12 : let mut guard = client.upload_queue.lock().unwrap();
2985 12 : let upload_queue = guard.initialized_mut().unwrap();
2986 12 :
2987 12 : assert!(upload_queue.queued_operations.is_empty());
2988 12 : assert!(upload_queue.inprogress_tasks.is_empty());
2989 12 : }
2990 12 :
2991 12 : // Download back the index.json, and check that the list of files is correct
2992 12 : let index_part = match client
2993 12 : .download_index_file(&CancellationToken::new())
2994 12 : .await
2995 12 : .unwrap()
2996 12 : {
2997 12 : MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
2998 12 : MaybeDeletedIndexPart::Deleted(_) => panic!("unexpectedly got deleted index part"),
2999 12 : };
3000 12 :
3001 12 : assert_file_list(
3002 12 : &index_part
3003 12 : .layer_metadata
3004 12 : .keys()
3005 36 : .map(|f| f.to_owned())
3006 12 : .collect(),
3007 12 : &[
3008 12 : &initial_layer.to_string(),
3009 12 : &layers[0].layer_desc().layer_name().to_string(),
3010 12 : &layers[1].layer_desc().layer_name().to_string(),
3011 12 : ],
3012 12 : );
3013 12 : assert_eq!(index_part.metadata, metadata);
3014 12 :
3015 12 : // Schedule upload and then a deletion. Check that the deletion is queued
3016 12 : client
3017 12 : .schedule_layer_file_upload(layers[2].clone())
3018 12 : .unwrap();
3019 12 :
3020 12 : // this is no longer consistent with how deletion works with Layer::drop, but in this test
3021 12 : // keep using schedule_layer_file_deletion because we don't have a way to wait for the
3022 12 : // spawn_blocking started by the drop.
3023 12 : client
3024 12 : .schedule_layer_file_deletion(&[layers[0].layer_desc().layer_name()])
3025 12 : .unwrap();
3026 12 : {
3027 12 : let mut guard = client.upload_queue.lock().unwrap();
3028 12 : let upload_queue = guard.initialized_mut().unwrap();
3029 12 :
3030 12 : // Deletion schedules upload of the index file, and the file deletion itself
3031 12 : assert_eq!(upload_queue.queued_operations.len(), 2);
3032 12 : assert_eq!(upload_queue.inprogress_tasks.len(), 1);
3033 12 : assert_eq!(upload_queue.num_inprogress_layer_uploads(), 1);
3034 12 : assert_eq!(upload_queue.num_inprogress_deletions(), 0);
3035 12 : assert_eq!(
3036 12 : upload_queue.latest_files_changes_since_metadata_upload_scheduled,
3037 12 : 0
3038 12 : );
3039 12 : }
3040 12 : assert_remote_files(
3041 12 : &[
3042 12 : &initial_layer.to_string(),
3043 12 : &layers[0].layer_desc().layer_name().to_string(),
3044 12 : &layers[1].layer_desc().layer_name().to_string(),
3045 12 : "index_part.json",
3046 12 : ],
3047 12 : &remote_timeline_dir,
3048 12 : generation,
3049 12 : );
3050 12 :
3051 12 : // Finish them
3052 12 : client.wait_completion().await.unwrap();
3053 12 : harness.deletion_queue.pump().await;
3054 12 :
3055 12 : assert_remote_files(
3056 12 : &[
3057 12 : &initial_layer.to_string(),
3058 12 : &layers[1].layer_desc().layer_name().to_string(),
3059 12 : &layers[2].layer_desc().layer_name().to_string(),
3060 12 : "index_part.json",
3061 12 : ],
3062 12 : &remote_timeline_dir,
3063 12 : generation,
3064 12 : );
3065 12 : }
3066 :
3067 : #[tokio::test]
3068 12 : async fn bytes_unfinished_gauge_for_layer_file_uploads() {
3069 12 : // Setup
3070 12 :
3071 12 : let TestSetup {
3072 12 : harness,
3073 12 : tenant: _tenant,
3074 12 : timeline,
3075 12 : ..
3076 12 : } = TestSetup::new("metrics").await.unwrap();
3077 12 : let client = &timeline.remote_client;
3078 12 :
3079 12 : let layer_file_name_1: LayerName = "000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D8-00000000016B5A51".parse().unwrap();
3080 12 : let local_path = local_layer_path(
3081 12 : harness.conf,
3082 12 : &timeline.tenant_shard_id,
3083 12 : &timeline.timeline_id,
3084 12 : &layer_file_name_1,
3085 12 : &harness.generation,
3086 12 : );
3087 12 : let content_1 = dummy_contents("foo");
3088 12 : std::fs::write(&local_path, &content_1).unwrap();
3089 12 :
3090 12 : let layer_file_1 = Layer::for_resident(
3091 12 : harness.conf,
3092 12 : &timeline,
3093 12 : local_path,
3094 12 : layer_file_name_1.clone(),
3095 12 : LayerFileMetadata::new(content_1.len() as u64, harness.generation, harness.shard),
3096 12 : );
3097 12 :
3098 12 : #[derive(Debug, PartialEq, Clone, Copy)]
3099 12 : struct BytesStartedFinished {
3100 12 : started: Option<usize>,
3101 12 : finished: Option<usize>,
3102 12 : }
3103 12 : impl std::ops::Add for BytesStartedFinished {
3104 12 : type Output = Self;
3105 24 : fn add(self, rhs: Self) -> Self::Output {
3106 24 : Self {
3107 24 : started: self.started.map(|v| v + rhs.started.unwrap_or(0)),
3108 24 : finished: self.finished.map(|v| v + rhs.finished.unwrap_or(0)),
3109 24 : }
3110 24 : }
3111 12 : }
3112 36 : let get_bytes_started_stopped = || {
3113 36 : let started = client
3114 36 : .metrics
3115 36 : .get_bytes_started_counter_value(&RemoteOpFileKind::Layer, &RemoteOpKind::Upload)
3116 36 : .map(|v| v.try_into().unwrap());
3117 36 : let stopped = client
3118 36 : .metrics
3119 36 : .get_bytes_finished_counter_value(&RemoteOpFileKind::Layer, &RemoteOpKind::Upload)
3120 36 : .map(|v| v.try_into().unwrap());
3121 36 : BytesStartedFinished {
3122 36 : started,
3123 36 : finished: stopped,
3124 36 : }
3125 36 : };
3126 12 :
3127 12 : // Test
3128 12 : tracing::info!("now doing actual test");
3129 12 :
3130 12 : let actual_a = get_bytes_started_stopped();
3131 12 :
3132 12 : client
3133 12 : .schedule_layer_file_upload(layer_file_1.clone())
3134 12 : .unwrap();
3135 12 :
3136 12 : let actual_b = get_bytes_started_stopped();
3137 12 :
3138 12 : client.wait_completion().await.unwrap();
3139 12 :
3140 12 : let actual_c = get_bytes_started_stopped();
3141 12 :
3142 12 : // Validate
3143 12 :
3144 12 : let expected_b = actual_a
3145 12 : + BytesStartedFinished {
3146 12 : started: Some(content_1.len()),
3147 12 : // assert that the _finished metric is created eagerly so that subtractions work on first sample
3148 12 : finished: Some(0),
3149 12 : };
3150 12 : assert_eq!(actual_b, expected_b);
3151 12 :
3152 12 : let expected_c = actual_a
3153 12 : + BytesStartedFinished {
3154 12 : started: Some(content_1.len()),
3155 12 : finished: Some(content_1.len()),
3156 12 : };
3157 12 : assert_eq!(actual_c, expected_c);
3158 12 : }
3159 :
3160 72 : async fn inject_index_part(test_state: &TestSetup, generation: Generation) -> IndexPart {
3161 72 : // An empty IndexPart, just sufficient to ensure deserialization will succeed
3162 72 : let example_index_part = IndexPart::example();
3163 72 :
3164 72 : let index_part_bytes = serde_json::to_vec(&example_index_part).unwrap();
3165 72 :
3166 72 : let index_path = test_state.harness.remote_fs_dir.join(
3167 72 : remote_index_path(
3168 72 : &test_state.harness.tenant_shard_id,
3169 72 : &TIMELINE_ID,
3170 72 : generation,
3171 72 : )
3172 72 : .get_path(),
3173 72 : );
3174 72 :
3175 72 : std::fs::create_dir_all(index_path.parent().unwrap())
3176 72 : .expect("creating test dir should work");
3177 72 :
3178 72 : eprintln!("Writing {index_path}");
3179 72 : std::fs::write(&index_path, index_part_bytes).unwrap();
3180 72 : example_index_part
3181 72 : }
3182 :
3183 : /// Assert that when a RemoteTimelineclient in generation `get_generation` fetches its
3184 : /// index, the IndexPart returned is equal to `expected`
3185 60 : async fn assert_got_index_part(
3186 60 : test_state: &TestSetup,
3187 60 : get_generation: Generation,
3188 60 : expected: &IndexPart,
3189 60 : ) {
3190 60 : let client = test_state.build_client(get_generation);
3191 :
3192 60 : let download_r = client
3193 60 : .download_index_file(&CancellationToken::new())
3194 60 : .await
3195 60 : .expect("download should always succeed");
3196 60 : assert!(matches!(download_r, MaybeDeletedIndexPart::IndexPart(_)));
3197 60 : match download_r {
3198 60 : MaybeDeletedIndexPart::IndexPart(index_part) => {
3199 60 : assert_eq!(&index_part, expected);
3200 : }
3201 0 : MaybeDeletedIndexPart::Deleted(_index_part) => panic!("Test doesn't set deleted_at"),
3202 : }
3203 60 : }
3204 :
3205 : #[tokio::test]
3206 12 : async fn index_part_download_simple() -> anyhow::Result<()> {
3207 12 : let test_state = TestSetup::new("index_part_download_simple").await.unwrap();
3208 12 : let span = test_state.span();
3209 12 : let _guard = span.enter();
3210 12 :
3211 12 : // Simple case: we are in generation N, load the index from generation N - 1
3212 12 : let generation_n = 5;
3213 12 : let injected = inject_index_part(&test_state, Generation::new(generation_n - 1)).await;
3214 12 :
3215 12 : assert_got_index_part(&test_state, Generation::new(generation_n), &injected).await;
3216 12 :
3217 12 : Ok(())
3218 12 : }
3219 :
3220 : #[tokio::test]
3221 12 : async fn index_part_download_ordering() -> anyhow::Result<()> {
3222 12 : let test_state = TestSetup::new("index_part_download_ordering")
3223 12 : .await
3224 12 : .unwrap();
3225 12 :
3226 12 : let span = test_state.span();
3227 12 : let _guard = span.enter();
3228 12 :
3229 12 : // A generation-less IndexPart exists in the bucket, we should find it
3230 12 : let generation_n = 5;
3231 12 : let injected_none = inject_index_part(&test_state, Generation::none()).await;
3232 12 : assert_got_index_part(&test_state, Generation::new(generation_n), &injected_none).await;
3233 12 :
3234 12 : // If a more recent-than-none generation exists, we should prefer to load that
3235 12 : let injected_1 = inject_index_part(&test_state, Generation::new(1)).await;
3236 12 : assert_got_index_part(&test_state, Generation::new(generation_n), &injected_1).await;
3237 12 :
3238 12 : // If a more-recent-than-me generation exists, we should ignore it.
3239 12 : let _injected_10 = inject_index_part(&test_state, Generation::new(10)).await;
3240 12 : assert_got_index_part(&test_state, Generation::new(generation_n), &injected_1).await;
3241 12 :
3242 12 : // If a directly previous generation exists, _and_ an index exists in my own
3243 12 : // generation, I should prefer my own generation.
3244 12 : let _injected_prev =
3245 12 : inject_index_part(&test_state, Generation::new(generation_n - 1)).await;
3246 12 : let injected_current = inject_index_part(&test_state, Generation::new(generation_n)).await;
3247 12 : assert_got_index_part(
3248 12 : &test_state,
3249 12 : Generation::new(generation_n),
3250 12 : &injected_current,
3251 12 : )
3252 12 : .await;
3253 12 :
3254 12 : Ok(())
3255 12 : }
3256 : }
|