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 : //! [`Tenant::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 : //! [`Tenant::timeline_init_and_sync`]: super::Tenant::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 944 : fn from(lc: &AttachedLocationConfig) -> Self {
323 944 : Self {
324 944 : block_deletions: !lc.may_delete_layers_hint(),
325 944 : process_remote_consistent_lsn_updates: lc.may_upload_layers_hint(),
326 944 : }
327 944 : }
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 40 : fn drop(&mut self) {
374 40 : debug!("dropping RemoteTimelineClient");
375 40 : }
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 924 : pub(crate) fn new(
386 924 : remote_storage: GenericRemoteStorage,
387 924 : deletion_queue_client: DeletionQueueClient,
388 924 : conf: &'static PageServerConf,
389 924 : tenant_shard_id: TenantShardId,
390 924 : timeline_id: TimelineId,
391 924 : generation: Generation,
392 924 : location_conf: &AttachedLocationConfig,
393 924 : ) -> RemoteTimelineClient {
394 924 : RemoteTimelineClient {
395 924 : conf,
396 924 : runtime: if cfg!(test) {
397 : // remote_timeline_client.rs tests rely on current-thread runtime
398 924 : tokio::runtime::Handle::current()
399 : } else {
400 0 : BACKGROUND_RUNTIME.handle().clone()
401 : },
402 924 : tenant_shard_id,
403 924 : timeline_id,
404 924 : generation,
405 924 : storage_impl: remote_storage,
406 924 : deletion_queue_client,
407 924 : upload_queue: Mutex::new(UploadQueue::Uninitialized),
408 924 : metrics: Arc::new(RemoteTimelineClientMetrics::new(
409 924 : &tenant_shard_id,
410 924 : &timeline_id,
411 924 : )),
412 924 : config: std::sync::RwLock::new(RemoteTimelineClientConfig::from(location_conf)),
413 924 : cancel: CancellationToken::new(),
414 924 : }
415 924 : }
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 12 : pub fn init_upload_queue(&self, index_part: &IndexPart) -> anyhow::Result<()> {
421 12 : // Set the maximum number of inprogress tasks to the remote storage concurrency. There's
422 12 : // certainly no point in starting more upload tasks than this.
423 12 : let inprogress_limit = self
424 12 : .conf
425 12 : .remote_storage_config
426 12 : .as_ref()
427 12 : .map_or(0, |r| r.concurrency_limit());
428 12 : let mut upload_queue = self.upload_queue.lock().unwrap();
429 12 : upload_queue.initialize_with_current_remote_index_part(index_part, inprogress_limit)?;
430 12 : self.update_remote_physical_size_gauge(Some(index_part));
431 12 : info!(
432 0 : "initialized upload queue from remote index with {} layer files",
433 0 : index_part.layer_metadata.len()
434 : );
435 12 : Ok(())
436 12 : }
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 912 : pub fn init_upload_queue_for_empty_remote(
444 912 : &self,
445 912 : local_metadata: &TimelineMetadata,
446 912 : rel_size_v2_status: Option<RelSizeMigration>,
447 912 : ) -> anyhow::Result<()> {
448 912 : // Set the maximum number of inprogress tasks to the remote storage concurrency. There's
449 912 : // certainly no point in starting more upload tasks than this.
450 912 : let inprogress_limit = self
451 912 : .conf
452 912 : .remote_storage_config
453 912 : .as_ref()
454 912 : .map_or(0, |r| r.concurrency_limit());
455 912 : let mut upload_queue = self.upload_queue.lock().unwrap();
456 912 : let initialized_queue =
457 912 : upload_queue.initialize_empty_remote(local_metadata, inprogress_limit)?;
458 912 : initialized_queue.dirty.rel_size_migration = rel_size_v2_status;
459 912 : self.update_remote_physical_size_gauge(None);
460 912 : info!("initialized upload queue as empty");
461 912 : Ok(())
462 912 : }
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 32 : pub(crate) fn is_archived(&self) -> Option<bool> {
568 32 : self.upload_queue
569 32 : .lock()
570 32 : .unwrap()
571 32 : .initialized_mut()
572 32 : .map(|q| q.clean.0.archived_at.is_some())
573 32 : .ok()
574 32 : }
575 :
576 : /// Returns true if the timeline is invisible in synthetic size calculations.
577 32 : pub(crate) fn is_invisible(&self) -> Option<bool> {
578 32 : self.upload_queue
579 32 : .lock()
580 32 : .unwrap()
581 32 : .initialized_mut()
582 32 : .map(|q| q.clean.0.marked_invisible_at.is_some())
583 32 : .ok()
584 32 : }
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 4 : pub(crate) fn archived_at_stopped_queue(
590 4 : &self,
591 4 : ) -> Result<Option<NaiveDateTime>, UploadQueueNotReadyError> {
592 4 : self.upload_queue
593 4 : .lock()
594 4 : .unwrap()
595 4 : .stopped_mut()
596 4 : .map(|q| q.upload_queue_for_deletion.clean.0.archived_at)
597 4 : .map_err(|_| UploadQueueNotReadyError)
598 4 : }
599 :
600 3854 : fn update_remote_physical_size_gauge(&self, current_remote_index_part: Option<&IndexPart>) {
601 3854 : let size: u64 = if let Some(current_remote_index_part) = current_remote_index_part {
602 2942 : current_remote_index_part
603 2942 : .layer_metadata
604 2942 : .values()
605 35206 : .map(|ilmd| ilmd.file_size)
606 2942 : .sum()
607 : } else {
608 912 : 0
609 : };
610 3854 : self.metrics.remote_physical_size_gauge.set(size);
611 3854 : }
612 :
613 4 : pub fn get_remote_physical_size(&self) -> u64 {
614 4 : self.metrics.remote_physical_size_gauge.get()
615 4 : }
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 40 : pub async fn download_index_file(
626 40 : &self,
627 40 : cancel: &CancellationToken,
628 40 : ) -> Result<MaybeDeletedIndexPart, DownloadError> {
629 40 : let _unfinished_gauge_guard = self.metrics.call_begin(
630 40 : &RemoteOpFileKind::Index,
631 40 : &RemoteOpKind::Download,
632 40 : crate::metrics::RemoteTimelineClientMetricsCallTrackSize::DontTrackSize {
633 40 : reason: "no need for a downloads gauge",
634 40 : },
635 40 : );
636 :
637 40 : let (index_part, index_generation, index_last_modified) = download::download_index_part(
638 40 : &self.storage_impl,
639 40 : &self.tenant_shard_id,
640 40 : &self.timeline_id,
641 40 : self.generation,
642 40 : cancel,
643 40 : )
644 40 : .measure_remote_op(
645 40 : Option::<TaskKind>::None,
646 40 : RemoteOpFileKind::Index,
647 40 : RemoteOpKind::Download,
648 40 : Arc::clone(&self.metrics),
649 40 : )
650 40 : .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 40 : 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 40 : });
666 40 : 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 40 : }
700 :
701 40 : if index_part.deleted_at.is_some() {
702 0 : Ok(MaybeDeletedIndexPart::Deleted(index_part))
703 : } else {
704 40 : Ok(MaybeDeletedIndexPart::IndexPart(index_part))
705 : }
706 40 : }
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 28 : pub async fn download_layer_file(
714 28 : &self,
715 28 : layer_file_name: &LayerName,
716 28 : layer_metadata: &LayerFileMetadata,
717 28 : local_path: &Utf8Path,
718 28 : gate: &utils::sync::gate::Gate,
719 28 : cancel: &CancellationToken,
720 28 : ctx: &RequestContext,
721 28 : ) -> Result<u64, DownloadError> {
722 28 : let downloaded_size = {
723 28 : let _unfinished_gauge_guard = self.metrics.call_begin(
724 28 : &RemoteOpFileKind::Layer,
725 28 : &RemoteOpKind::Download,
726 28 : crate::metrics::RemoteTimelineClientMetricsCallTrackSize::DontTrackSize {
727 28 : reason: "no need for a downloads gauge",
728 28 : },
729 28 : );
730 28 : download::download_layer_file(
731 28 : self.conf,
732 28 : &self.storage_impl,
733 28 : self.tenant_shard_id,
734 28 : self.timeline_id,
735 28 : layer_file_name,
736 28 : layer_metadata,
737 28 : local_path,
738 28 : gate,
739 28 : cancel,
740 28 : ctx,
741 28 : )
742 28 : .measure_remote_op(
743 28 : Some(ctx.task_kind()),
744 28 : RemoteOpFileKind::Layer,
745 28 : RemoteOpKind::Download,
746 28 : Arc::clone(&self.metrics),
747 28 : )
748 28 : .await?
749 : };
750 :
751 28 : REMOTE_ONDEMAND_DOWNLOADED_LAYERS.inc();
752 28 : REMOTE_ONDEMAND_DOWNLOADED_BYTES.inc_by(downloaded_size);
753 28 :
754 28 : Ok(downloaded_size)
755 28 : }
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 472 : pub fn schedule_index_upload_for_full_metadata_update(
777 472 : self: &Arc<Self>,
778 472 : metadata: &TimelineMetadata,
779 472 : ) -> anyhow::Result<()> {
780 472 : let mut guard = self.upload_queue.lock().unwrap();
781 472 : 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 472 : upload_queue.dirty.metadata = metadata.clone();
786 472 :
787 472 : self.schedule_index_upload(upload_queue);
788 472 :
789 472 : Ok(())
790 472 : }
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 2464 : pub(crate) fn schedule_index_upload_for_metadata_update(
800 2464 : self: &Arc<Self>,
801 2464 : update: &MetadataUpdate,
802 2464 : ) -> anyhow::Result<()> {
803 2464 : let mut guard = self.upload_queue.lock().unwrap();
804 2464 : let upload_queue = guard.initialized_mut()?;
805 :
806 2464 : upload_queue.dirty.metadata.apply(update);
807 2464 :
808 2464 : // Defense in depth: if we somehow generated invalid metadata, do not persist it.
809 2464 : upload_queue
810 2464 : .dirty
811 2464 : .validate()
812 2464 : .map_err(|e| anyhow::anyhow!(e))?;
813 :
814 2464 : self.schedule_index_upload(upload_queue);
815 2464 :
816 2464 : Ok(())
817 2464 : }
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 4 : pub(crate) fn schedule_index_upload_for_timeline_archival_state(
825 4 : self: &Arc<Self>,
826 4 : state: TimelineArchivalState,
827 4 : ) -> anyhow::Result<bool> {
828 4 : let mut guard = self.upload_queue.lock().unwrap();
829 4 : 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 8 : fn need_change(
834 8 : archived_at: &Option<NaiveDateTime>,
835 8 : state: TimelineArchivalState,
836 8 : ) -> Option<bool> {
837 8 : 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 8 : (None, TimelineArchivalState::Archived) => Some(true),
845 0 : (Some(_), TimelineArchivalState::Unarchived) => Some(false),
846 : }
847 8 : }
848 4 : let need_upload_scheduled = need_change(&upload_queue.dirty.archived_at, state);
849 :
850 4 : if let Some(archived_at_set) = need_upload_scheduled {
851 4 : let intended_archived_at = archived_at_set.then(|| Utc::now().naive_utc());
852 4 : upload_queue.dirty.archived_at = intended_archived_at;
853 4 : self.schedule_index_upload(upload_queue);
854 4 : }
855 :
856 4 : let need_wait = need_change(&upload_queue.clean.0.archived_at, state).is_some();
857 4 : Ok(need_wait)
858 4 : }
859 :
860 4 : pub(crate) fn schedule_index_upload_for_timeline_invisible_state(
861 4 : self: &Arc<Self>,
862 4 : state: TimelineVisibilityState,
863 4 : ) -> anyhow::Result<()> {
864 4 : let mut guard = self.upload_queue.lock().unwrap();
865 4 : let upload_queue = guard.initialized_mut()?;
866 :
867 4 : fn need_change(
868 4 : marked_invisible_at: &Option<NaiveDateTime>,
869 4 : state: TimelineVisibilityState,
870 4 : ) -> Option<bool> {
871 4 : match (marked_invisible_at, state) {
872 0 : (Some(_), TimelineVisibilityState::Invisible) => Some(false),
873 4 : (None, TimelineVisibilityState::Invisible) => Some(true),
874 0 : (Some(_), TimelineVisibilityState::Visible) => Some(false),
875 0 : (None, TimelineVisibilityState::Visible) => Some(true),
876 : }
877 4 : }
878 :
879 4 : let need_upload_scheduled = need_change(&upload_queue.dirty.marked_invisible_at, state);
880 :
881 4 : if let Some(marked_invisible_at_set) = need_upload_scheduled {
882 4 : let intended_marked_invisible_at =
883 4 : marked_invisible_at_set.then(|| Utc::now().naive_utc());
884 4 : upload_queue.dirty.marked_invisible_at = intended_marked_invisible_at;
885 4 : self.schedule_index_upload(upload_queue);
886 4 : }
887 :
888 4 : Ok(())
889 4 : }
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 4 : pub(crate) async fn shutdown_if_archived(
899 4 : self: &Arc<Self>,
900 4 : ) -> Result<(), ShutdownIfArchivedError> {
901 4 : {
902 4 : let mut guard = self.upload_queue.lock().unwrap();
903 4 : let upload_queue = guard
904 4 : .initialized_mut()
905 4 : .map_err(ShutdownIfArchivedError::NotInitialized)?;
906 :
907 4 : match (
908 4 : upload_queue.dirty.archived_at.is_none(),
909 4 : upload_queue.clean.0.archived_at.is_none(),
910 4 : ) {
911 : // The expected case: the timeline is archived and we don't want to unarchive
912 4 : (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 4 : if !upload_queue.shutting_down {
928 4 : upload_queue.shutting_down = true;
929 4 : upload_queue.queued_operations.push_back(UploadOp::Shutdown);
930 4 : // this operation is not counted similar to Barrier
931 4 : self.launch_queued_tasks(upload_queue);
932 4 : }
933 : }
934 :
935 4 : self.shutdown().await;
936 :
937 4 : Ok(())
938 4 : }
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 740 : pub fn schedule_index_upload_for_file_changes(self: &Arc<Self>) -> Result<(), NotInitialized> {
990 740 : let mut guard = self.upload_queue.lock().unwrap();
991 740 : let upload_queue = guard.initialized_mut()?;
992 :
993 740 : if upload_queue.latest_files_changes_since_metadata_upload_scheduled > 0 {
994 28 : self.schedule_index_upload(upload_queue);
995 712 : }
996 :
997 740 : Ok(())
998 740 : }
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 3116 : fn schedule_index_upload(self: &Arc<Self>, upload_queue: &mut UploadQueueInitialized) {
1010 3116 : let disk_consistent_lsn = upload_queue.dirty.metadata.disk_consistent_lsn();
1011 3116 : // fix up the duplicated field
1012 3116 : upload_queue.dirty.disk_consistent_lsn = disk_consistent_lsn;
1013 3116 :
1014 3116 : // make sure it serializes before doing it in perform_upload_task so that it doesn't
1015 3116 : // look like a retryable error
1016 3116 : let void = std::io::sink();
1017 3116 : serde_json::to_writer(void, &upload_queue.dirty).expect("serialize index_part.json");
1018 3116 :
1019 3116 : let index_part = &upload_queue.dirty;
1020 3116 :
1021 3116 : 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 3116 : let op = UploadOp::UploadMetadata {
1028 3116 : uploaded: Box::new(index_part.clone()),
1029 3116 : };
1030 3116 : self.metric_begin(&op);
1031 3116 : upload_queue.queued_operations.push_back(op);
1032 3116 : upload_queue.latest_files_changes_since_metadata_upload_scheduled = 0;
1033 3116 :
1034 3116 : // Launch the task immediately, if possible
1035 3116 : self.launch_queued_tasks(upload_queue);
1036 3116 : }
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 2776 : pub(crate) fn schedule_layer_file_upload(
1237 2776 : self: &Arc<Self>,
1238 2776 : layer: ResidentLayer,
1239 2776 : ) -> Result<(), NotInitialized> {
1240 2776 : let mut guard = self.upload_queue.lock().unwrap();
1241 2776 : let upload_queue = guard.initialized_mut()?;
1242 :
1243 2776 : self.schedule_layer_file_upload0(upload_queue, layer);
1244 2776 : self.launch_queued_tasks(upload_queue);
1245 2776 : Ok(())
1246 2776 : }
1247 :
1248 3500 : fn schedule_layer_file_upload0(
1249 3500 : self: &Arc<Self>,
1250 3500 : upload_queue: &mut UploadQueueInitialized,
1251 3500 : layer: ResidentLayer,
1252 3500 : ) {
1253 3500 : let metadata = layer.metadata();
1254 3500 :
1255 3500 : upload_queue
1256 3500 : .dirty
1257 3500 : .layer_metadata
1258 3500 : .insert(layer.layer_desc().layer_name(), metadata.clone());
1259 3500 : upload_queue.latest_files_changes_since_metadata_upload_scheduled += 1;
1260 3500 :
1261 3500 : info!(
1262 : gen=?metadata.generation,
1263 : shard=?metadata.shard,
1264 0 : "scheduled layer file upload {layer}",
1265 : );
1266 :
1267 3500 : let op = UploadOp::UploadLayer(layer, metadata, None);
1268 3500 : self.metric_begin(&op);
1269 3500 : upload_queue.queued_operations.push_back(op);
1270 3500 : }
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 16 : pub fn schedule_layer_file_deletion(
1281 16 : self: &Arc<Self>,
1282 16 : names: &[LayerName],
1283 16 : ) -> anyhow::Result<()> {
1284 16 : let mut guard = self.upload_queue.lock().unwrap();
1285 16 : let upload_queue = guard.initialized_mut()?;
1286 :
1287 16 : let with_metadata =
1288 16 : self.schedule_unlinking_of_layers_from_index_part0(upload_queue, names.iter().cloned());
1289 16 :
1290 16 : self.schedule_deletion_of_unlinked0(upload_queue, with_metadata);
1291 16 :
1292 16 : // Launch the tasks immediately, if possible
1293 16 : self.launch_queued_tasks(upload_queue);
1294 16 : Ok(())
1295 16 : }
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 8 : pub(crate) fn schedule_gc_update(
1303 8 : self: &Arc<Self>,
1304 8 : gc_layers: &[Layer],
1305 8 : ) -> Result<(), NotInitialized> {
1306 8 : let mut guard = self.upload_queue.lock().unwrap();
1307 8 : 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 8 : let names = gc_layers.iter().map(|x| x.layer_desc().layer_name());
1314 8 :
1315 8 : self.schedule_unlinking_of_layers_from_index_part0(upload_queue, names);
1316 8 :
1317 8 : self.launch_queued_tasks(upload_queue);
1318 8 :
1319 8 : Ok(())
1320 8 : }
1321 :
1322 : /// Update the remote index file, removing the to-be-deleted files from the index,
1323 : /// allowing scheduling of actual deletions later.
1324 176 : fn schedule_unlinking_of_layers_from_index_part0<I>(
1325 176 : self: &Arc<Self>,
1326 176 : upload_queue: &mut UploadQueueInitialized,
1327 176 : names: I,
1328 176 : ) -> Vec<(LayerName, LayerFileMetadata)>
1329 176 : where
1330 176 : I: IntoIterator<Item = LayerName>,
1331 176 : {
1332 176 : // Decorate our list of names with each name's metadata, dropping
1333 176 : // names that are unexpectedly missing from our metadata. This metadata
1334 176 : // is later used when physically deleting layers, to construct key paths.
1335 176 : let with_metadata: Vec<_> = names
1336 176 : .into_iter()
1337 1024 : .filter_map(|name| {
1338 1024 : let meta = upload_queue.dirty.layer_metadata.remove(&name);
1339 :
1340 1024 : if let Some(meta) = meta {
1341 1024 : upload_queue.latest_files_changes_since_metadata_upload_scheduled += 1;
1342 1024 : 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 1024 : })
1352 176 : .collect();
1353 :
1354 : #[cfg(feature = "testing")]
1355 1200 : for (name, metadata) in &with_metadata {
1356 1024 : let gen_ = metadata.generation;
1357 1024 : 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 1024 : }
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 176 : if upload_queue.latest_files_changes_since_metadata_upload_scheduled > 0 {
1372 144 : self.schedule_index_upload(upload_queue);
1373 144 : }
1374 :
1375 176 : with_metadata
1376 176 : }
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 1021 : pub(crate) fn schedule_deletion_of_unlinked(
1381 1021 : self: &Arc<Self>,
1382 1021 : layers: Vec<(LayerName, LayerFileMetadata)>,
1383 1021 : ) -> anyhow::Result<()> {
1384 1021 : let mut guard = self.upload_queue.lock().unwrap();
1385 1021 : let upload_queue = guard.initialized_mut()?;
1386 :
1387 1021 : self.schedule_deletion_of_unlinked0(upload_queue, layers);
1388 1021 : self.launch_queued_tasks(upload_queue);
1389 1021 : Ok(())
1390 1021 : }
1391 :
1392 1033 : fn schedule_deletion_of_unlinked0(
1393 1033 : self: &Arc<Self>,
1394 1033 : upload_queue: &mut UploadQueueInitialized,
1395 1033 : mut with_metadata: Vec<(LayerName, LayerFileMetadata)>,
1396 1033 : ) {
1397 1033 : // Filter out any layers which were not created by this tenant shard. These are
1398 1033 : // layers that originate from some ancestor shard after a split, and may still
1399 1033 : // be referenced by other shards. We are free to delete them locally and remove
1400 1033 : // them from our index (and would have already done so when we reach this point
1401 1033 : // in the code), but we may not delete them remotely.
1402 1033 : with_metadata.retain(|(name, meta)| {
1403 1021 : let retain = meta.shard.shard_number == self.tenant_shard_id.shard_number
1404 1021 : && meta.shard.shard_count == self.tenant_shard_id.shard_count;
1405 1021 : if !retain {
1406 0 : tracing::debug!(
1407 0 : "Skipping deletion of ancestor-shard layer {name}, from shard {}",
1408 : meta.shard
1409 : );
1410 1021 : }
1411 1021 : retain
1412 1033 : });
1413 :
1414 2054 : for (name, meta) in &with_metadata {
1415 1021 : 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 2054 : for (name, meta) in &with_metadata {
1425 1021 : let gen_ = meta.generation;
1426 1021 : match upload_queue.dangling_files.remove(name) {
1427 1013 : 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 8 : tracing::error!("{name} was unlinked but was not dangling");
1433 : }
1434 : }
1435 : }
1436 :
1437 : // schedule the actual deletions
1438 1033 : if with_metadata.is_empty() {
1439 : // avoid scheduling the op & bumping the metric
1440 12 : return;
1441 1021 : }
1442 1021 : let op = UploadOp::Delete(Delete {
1443 1021 : layers: with_metadata,
1444 1021 : });
1445 1021 : self.metric_begin(&op);
1446 1021 : upload_queue.queued_operations.push_back(op);
1447 1033 : }
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 152 : pub(crate) fn schedule_compaction_update(
1453 152 : self: &Arc<Self>,
1454 152 : compacted_from: &[Layer],
1455 152 : compacted_to: &[ResidentLayer],
1456 152 : ) -> Result<(), NotInitialized> {
1457 152 : let mut guard = self.upload_queue.lock().unwrap();
1458 152 : let upload_queue = guard.initialized_mut()?;
1459 :
1460 876 : for layer in compacted_to {
1461 724 : self.schedule_layer_file_upload0(upload_queue, layer.clone());
1462 724 : }
1463 :
1464 1012 : let names = compacted_from.iter().map(|x| x.layer_desc().layer_name());
1465 152 :
1466 152 : self.schedule_unlinking_of_layers_from_index_part0(upload_queue, names);
1467 152 : self.launch_queued_tasks(upload_queue);
1468 152 :
1469 152 : Ok(())
1470 152 : }
1471 :
1472 : /// Wait for all previously scheduled uploads/deletions to complete
1473 452 : pub(crate) async fn wait_completion(self: &Arc<Self>) -> Result<(), WaitCompletionError> {
1474 452 : let receiver = {
1475 452 : let mut guard = self.upload_queue.lock().unwrap();
1476 452 : let upload_queue = guard
1477 452 : .initialized_mut()
1478 452 : .map_err(WaitCompletionError::NotInitialized)?;
1479 452 : self.schedule_barrier0(upload_queue)
1480 452 : };
1481 452 :
1482 452 : Self::wait_completion0(receiver).await
1483 452 : }
1484 :
1485 452 : async fn wait_completion0(
1486 452 : mut receiver: tokio::sync::watch::Receiver<()>,
1487 452 : ) -> Result<(), WaitCompletionError> {
1488 452 : if receiver.changed().await.is_err() {
1489 0 : return Err(WaitCompletionError::UploadQueueShutDownOrStopped);
1490 452 : }
1491 452 :
1492 452 : Ok(())
1493 452 : }
1494 :
1495 12 : pub(crate) fn schedule_barrier(self: &Arc<Self>) -> anyhow::Result<()> {
1496 12 : let mut guard = self.upload_queue.lock().unwrap();
1497 12 : let upload_queue = guard.initialized_mut()?;
1498 12 : self.schedule_barrier0(upload_queue);
1499 12 : Ok(())
1500 12 : }
1501 :
1502 464 : fn schedule_barrier0(
1503 464 : self: &Arc<Self>,
1504 464 : upload_queue: &mut UploadQueueInitialized,
1505 464 : ) -> tokio::sync::watch::Receiver<()> {
1506 464 : let (sender, receiver) = tokio::sync::watch::channel(());
1507 464 : let barrier_op = UploadOp::Barrier(sender);
1508 464 :
1509 464 : upload_queue.queued_operations.push_back(barrier_op);
1510 464 : // Don't count this kind of operation!
1511 464 :
1512 464 : // Launch the task immediately, if possible
1513 464 : self.launch_queued_tasks(upload_queue);
1514 464 :
1515 464 : receiver
1516 464 : }
1517 :
1518 : /// Wait for all previously scheduled operations to complete, and then stop.
1519 : ///
1520 : /// Not cancellation safe
1521 20 : pub(crate) async fn shutdown(self: &Arc<Self>) {
1522 20 : // On cancellation the queue is left in ackward state of refusing new operations but
1523 20 : // proper stop is yet to be called. On cancel the original or some later task must call
1524 20 : // `stop` or `shutdown`.
1525 20 : 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 20 : });
1530 :
1531 16 : let fut = {
1532 20 : let mut guard = self.upload_queue.lock().unwrap();
1533 20 : let upload_queue = match &mut *guard {
1534 : UploadQueue::Stopped(_) => {
1535 4 : scopeguard::ScopeGuard::into_inner(sg);
1536 4 : 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 16 : UploadQueue::Initialized(init) => init,
1545 16 : };
1546 16 :
1547 16 : // if the queue is already stuck due to a shutdown operation which was cancelled, then
1548 16 : // just don't add more of these as they would never complete.
1549 16 : //
1550 16 : // TODO: if launch_queued_tasks were to be refactored to accept a &mut UploadQueue
1551 16 : // in every place we would not have to jump through this hoop, and this method could be
1552 16 : // made cancellable.
1553 16 : if !upload_queue.shutting_down {
1554 12 : upload_queue.shutting_down = true;
1555 12 : upload_queue.queued_operations.push_back(UploadOp::Shutdown);
1556 12 : // this operation is not counted similar to Barrier
1557 12 :
1558 12 : self.launch_queued_tasks(upload_queue);
1559 12 : }
1560 :
1561 16 : upload_queue.shutdown_ready.clone().acquire_owned()
1562 : };
1563 :
1564 16 : let res = fut.await;
1565 :
1566 16 : scopeguard::ScopeGuard::into_inner(sg);
1567 16 :
1568 16 : match res {
1569 0 : Ok(_permit) => unreachable!("shutdown_ready should not have been added permits"),
1570 16 : Err(_closed) => {
1571 16 : // expected
1572 16 : }
1573 16 : }
1574 16 :
1575 16 : self.stop();
1576 20 : }
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 14216 : fn launch_queued_tasks(self: &Arc<Self>, upload_queue: &mut UploadQueueInitialized) {
1975 21815 : while let Some((mut next_op, coalesced_ops)) = upload_queue.next_ready() {
1976 7599 : debug!("starting op: {next_op}");
1977 :
1978 : // Prepare upload.
1979 7599 : match &mut next_op {
1980 3500 : UploadOp::UploadLayer(layer, meta, mode) => {
1981 3500 : if upload_queue
1982 3500 : .recently_deleted
1983 3500 : .remove(&(layer.layer_desc().layer_name().clone(), meta.generation))
1984 0 : {
1985 0 : *mode = Some(OpType::FlushDeletion);
1986 0 : } else {
1987 3500 : *mode = Some(OpType::MayReorder)
1988 : }
1989 : }
1990 2983 : UploadOp::UploadMetadata { .. } => {}
1991 652 : UploadOp::Delete(Delete { layers }) => {
1992 1304 : for (name, meta) in layers {
1993 652 : upload_queue
1994 652 : .recently_deleted
1995 652 : .insert((name.clone(), meta.generation));
1996 652 : }
1997 : }
1998 464 : UploadOp::Barrier(sender) => {
1999 464 : sender.send_replace(());
2000 464 : continue;
2001 : }
2002 0 : UploadOp::Shutdown => unreachable!("shutdown is intentionally never popped off"),
2003 : };
2004 :
2005 : // Assign unique ID to this task
2006 7135 : upload_queue.task_counter += 1;
2007 7135 : let upload_task_id = upload_queue.task_counter;
2008 7135 :
2009 7135 : // Add it to the in-progress map
2010 7135 : let task = Arc::new(UploadTask {
2011 7135 : task_id: upload_task_id,
2012 7135 : op: next_op,
2013 7135 : coalesced_ops,
2014 7135 : retries: AtomicU32::new(0),
2015 7135 : });
2016 7135 : upload_queue
2017 7135 : .inprogress_tasks
2018 7135 : .insert(task.task_id, Arc::clone(&task));
2019 7135 :
2020 7135 : // Spawn task to perform the task
2021 7135 : let self_rc = Arc::clone(self);
2022 7135 : let tenant_shard_id = self.tenant_shard_id;
2023 7135 : let timeline_id = self.timeline_id;
2024 7135 : task_mgr::spawn(
2025 7135 : &self.runtime,
2026 7135 : TaskKind::RemoteUploadTask,
2027 7135 : self.tenant_shard_id,
2028 7135 : Some(self.timeline_id),
2029 7135 : "remote upload",
2030 6989 : async move {
2031 6989 : self_rc.perform_upload_task(task).await;
2032 6659 : Ok(())
2033 6659 : }
2034 7135 : .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 14216 : }
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 6989 : async fn perform_upload_task(self: &Arc<Self>, task: Arc<UploadTask>) {
2053 6989 : 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 6989 : if cancel.is_cancelled() {
2066 0 : info!("upload task cancelled by shutdown request");
2067 0 : self.stop();
2068 0 : return;
2069 6989 : }
2070 6989 :
2071 6989 : // Assert that we don't modify a layer that's referenced by the current index.
2072 6989 : if cfg!(debug_assertions) {
2073 6989 : let modified = match &task.op {
2074 3376 : UploadOp::UploadLayer(layer, layer_metadata, _) => {
2075 3376 : vec![(layer.layer_desc().layer_name(), layer_metadata)]
2076 : }
2077 652 : UploadOp::Delete(delete) => {
2078 652 : delete.layers.iter().map(|(n, m)| (n.clone(), m)).collect()
2079 : }
2080 : // These don't modify layers.
2081 2961 : UploadOp::UploadMetadata { .. } => Vec::new(),
2082 0 : UploadOp::Barrier(_) => Vec::new(),
2083 0 : UploadOp::Shutdown => Vec::new(),
2084 : };
2085 6989 : if let Ok(queue) = self.upload_queue.lock().unwrap().initialized_mut() {
2086 11002 : for (ref name, metadata) in modified {
2087 4027 : debug_assert!(
2088 4027 : !queue.clean.0.references(name, metadata),
2089 8 : "layer {name} modified while referenced by index",
2090 : );
2091 : }
2092 6 : }
2093 0 : }
2094 :
2095 6981 : let upload_result: anyhow::Result<()> = match &task.op {
2096 3376 : 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 3376 : 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 3376 : }
2158 3376 : let local_path = layer.local_path();
2159 3376 :
2160 3376 : // We should only be uploading layers created by this `Tenant`'s lifetime, so
2161 3376 : // the metadata in the upload should always match our current generation.
2162 3376 : assert_eq!(layer_metadata.generation, self.generation);
2163 :
2164 3376 : let remote_path = remote_layer_path(
2165 3376 : &self.tenant_shard_id.tenant_id,
2166 3376 : &self.timeline_id,
2167 3376 : layer_metadata.shard,
2168 3376 : &layer.layer_desc().layer_name(),
2169 3376 : layer_metadata.generation,
2170 3376 : );
2171 3376 :
2172 3376 : upload::upload_timeline_layer(
2173 3376 : &self.storage_impl,
2174 3376 : local_path,
2175 3376 : &remote_path,
2176 3376 : layer_metadata.file_size,
2177 3376 : &self.cancel,
2178 3376 : )
2179 3376 : .measure_remote_op(
2180 3376 : Some(TaskKind::RemoteUploadTask),
2181 3376 : RemoteOpFileKind::Layer,
2182 3376 : RemoteOpKind::Upload,
2183 3376 : Arc::clone(&self.metrics),
2184 3376 : )
2185 3376 : .await
2186 : }
2187 2961 : UploadOp::UploadMetadata { uploaded } => {
2188 2961 : let res = upload::upload_index_part(
2189 2961 : &self.storage_impl,
2190 2961 : &self.tenant_shard_id,
2191 2961 : &self.timeline_id,
2192 2961 : self.generation,
2193 2961 : uploaded,
2194 2961 : &self.cancel,
2195 2961 : )
2196 2961 : .measure_remote_op(
2197 2961 : Some(TaskKind::RemoteUploadTask),
2198 2961 : RemoteOpFileKind::Index,
2199 2961 : RemoteOpKind::Upload,
2200 2961 : Arc::clone(&self.metrics),
2201 2961 : )
2202 2961 : .await;
2203 2930 : if res.is_ok() {
2204 2930 : self.update_remote_physical_size_gauge(Some(uploaded));
2205 2930 : let mention_having_future_layers = if cfg!(feature = "testing") {
2206 2930 : uploaded
2207 2930 : .layer_metadata
2208 2930 : .keys()
2209 34862 : .any(|x| x.is_in_future(uploaded.metadata.disk_consistent_lsn()))
2210 : } else {
2211 0 : false
2212 : };
2213 2930 : if mention_having_future_layers {
2214 : // find rationale near crate::tenant::timeline::init::cleanup_future_layer
2215 105 : 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 2825 : }
2220 0 : }
2221 2930 : 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 644 : UploadOp::Delete(delete) => {
2229 644 : 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 644 : pausable_failpoint!("before-delete-layer-pausable");
2237 644 : self.deletion_queue_client
2238 644 : .push_layers(
2239 644 : self.tenant_shard_id,
2240 644 : self.timeline_id,
2241 644 : self.generation,
2242 644 : delete.layers.clone(),
2243 644 : )
2244 644 : .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 6651 : 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 6651 : let retries = task.retries.load(Ordering::SeqCst);
2296 6651 : if retries > 0 {
2297 0 : info!(
2298 0 : "remote task {} completed successfully after {} retries",
2299 0 : task.op, retries
2300 : );
2301 : } else {
2302 6651 : debug!("remote task {} completed successfully", task.op);
2303 : }
2304 :
2305 : // The task has completed successfully. Remove it from the in-progress list.
2306 6651 : let lsn_update = {
2307 6651 : let mut upload_queue_guard = self.upload_queue.lock().unwrap();
2308 6651 : 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 6651 : UploadQueue::Initialized(qi) => Some(qi),
2314 : };
2315 :
2316 6651 : let upload_queue = match upload_queue {
2317 6651 : Some(upload_queue) => upload_queue,
2318 : None => {
2319 0 : info!("another concurrent task already stopped the queue");
2320 0 : return;
2321 : }
2322 : };
2323 :
2324 6651 : upload_queue.inprogress_tasks.remove(&task.task_id);
2325 :
2326 6651 : let lsn_update = match task.op {
2327 3077 : UploadOp::UploadLayer(_, _, _) => None,
2328 2930 : UploadOp::UploadMetadata { ref uploaded } => {
2329 2930 : // the task id is reused as a monotonicity check for storing the "clean"
2330 2930 : // IndexPart.
2331 2930 : let last_updater = upload_queue.clean.1;
2332 2930 : let is_later = last_updater.is_some_and(|task_id| task_id < task.task_id);
2333 2930 : let monotone = is_later || last_updater.is_none();
2334 :
2335 2930 : assert!(
2336 2930 : 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 2930 : upload_queue.clean.0.clone_from(uploaded);
2343 2930 : upload_queue.clean.1 = Some(task.task_id);
2344 2930 :
2345 2930 : let lsn = upload_queue.clean.0.metadata.disk_consistent_lsn();
2346 2930 : self.metrics
2347 2930 : .projected_remote_consistent_lsn_gauge
2348 2930 : .set(lsn.0);
2349 2930 :
2350 2930 : 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 2930 : } else if self
2355 2930 : .config
2356 2930 : .read()
2357 2930 : .unwrap()
2358 2930 : .process_remote_consistent_lsn_updates
2359 : {
2360 2930 : 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 644 : UploadOp::Delete(_) => None,
2367 0 : UploadOp::Barrier(..) | UploadOp::Shutdown => unreachable!(),
2368 : };
2369 :
2370 : // Launch any queued tasks that were unblocked by this one.
2371 6651 : self.launch_queued_tasks(upload_queue);
2372 6651 : lsn_update
2373 : };
2374 :
2375 6651 : 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 2930 : self.deletion_queue_client
2380 2930 : .update_remote_consistent_lsn(
2381 2930 : self.tenant_shard_id,
2382 2930 : self.timeline_id,
2383 2930 : self.generation,
2384 2930 : lsn,
2385 2930 : slot,
2386 2930 : )
2387 2930 : .await;
2388 3721 : }
2389 :
2390 6651 : self.metric_end(&task.op);
2391 6651 : for coalesced_op in &task.coalesced_ops {
2392 18 : self.metric_end(coalesced_op);
2393 18 : }
2394 6651 : }
2395 :
2396 14322 : fn metric_impl(
2397 14322 : &self,
2398 14322 : op: &UploadOp,
2399 14322 : ) -> Option<(
2400 14322 : RemoteOpFileKind,
2401 14322 : RemoteOpKind,
2402 14322 : RemoteTimelineClientMetricsCallTrackSize,
2403 14322 : )> {
2404 : use RemoteTimelineClientMetricsCallTrackSize::DontTrackSize;
2405 14322 : let res = match op {
2406 6577 : UploadOp::UploadLayer(_, m, _) => (
2407 6577 : RemoteOpFileKind::Layer,
2408 6577 : RemoteOpKind::Upload,
2409 6577 : RemoteTimelineClientMetricsCallTrackSize::Bytes(m.file_size),
2410 6577 : ),
2411 6064 : UploadOp::UploadMetadata { .. } => (
2412 6064 : RemoteOpFileKind::Index,
2413 6064 : RemoteOpKind::Upload,
2414 6064 : DontTrackSize {
2415 6064 : reason: "metadata uploads are tiny",
2416 6064 : },
2417 6064 : ),
2418 1665 : UploadOp::Delete(_delete) => (
2419 1665 : RemoteOpFileKind::Layer,
2420 1665 : RemoteOpKind::Delete,
2421 1665 : DontTrackSize {
2422 1665 : reason: "should we track deletes? positive or negative sign?",
2423 1665 : },
2424 1665 : ),
2425 : UploadOp::Barrier(..) | UploadOp::Shutdown => {
2426 : // we do not account these
2427 16 : return None;
2428 : }
2429 : };
2430 14306 : Some(res)
2431 14322 : }
2432 :
2433 7637 : fn metric_begin(&self, op: &UploadOp) {
2434 7637 : let (file_kind, op_kind, track_bytes) = match self.metric_impl(op) {
2435 7637 : Some(x) => x,
2436 0 : None => return,
2437 : };
2438 7637 : let guard = self.metrics.call_begin(&file_kind, &op_kind, track_bytes);
2439 7637 : guard.will_decrement_manually(); // in metric_end(), see right below
2440 7637 : }
2441 :
2442 6685 : fn metric_end(&self, op: &UploadOp) {
2443 6685 : let (file_kind, op_kind, track_bytes) = match self.metric_impl(op) {
2444 6669 : Some(x) => x,
2445 16 : None => return,
2446 : };
2447 6669 : self.metrics.call_end(&file_kind, &op_kind, track_bytes);
2448 6685 : }
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 36 : pub(crate) fn stop(&self) {
2458 36 : // Whichever *task* for this RemoteTimelineClient grabs the mutex first will transition the queue
2459 36 : // into stopped state, thereby dropping all off the queued *ops* which haven't become *tasks* yet.
2460 36 : // The other *tasks* will come here and observe an already shut down queue and hence simply wrap up their business.
2461 36 : let mut guard = self.upload_queue.lock().unwrap();
2462 36 : self.stop_impl(&mut guard);
2463 36 : }
2464 :
2465 36 : fn stop_impl(&self, guard: &mut std::sync::MutexGuard<UploadQueue>) {
2466 36 : 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 16 : info!("another concurrent task already shut down the queue");
2474 : }
2475 20 : UploadQueue::Initialized(initialized) => {
2476 20 : 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 20 : 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 20 : let upload_queue_for_deletion = UploadQueueInitialized {
2486 20 : inprogress_limit: initialized.inprogress_limit,
2487 20 : task_counter: 0,
2488 20 : dirty: initialized.dirty.clone(),
2489 20 : clean: initialized.clean.clone(),
2490 20 : latest_files_changes_since_metadata_upload_scheduled: 0,
2491 20 : visible_remote_consistent_lsn: initialized
2492 20 : .visible_remote_consistent_lsn
2493 20 : .clone(),
2494 20 : inprogress_tasks: HashMap::default(),
2495 20 : queued_operations: VecDeque::default(),
2496 20 : #[cfg(feature = "testing")]
2497 20 : dangling_files: HashMap::default(),
2498 20 : blocked_deletions: Vec::new(),
2499 20 : shutting_down: false,
2500 20 : shutdown_ready: Arc::new(tokio::sync::Semaphore::new(0)),
2501 20 : recently_deleted: HashSet::new(),
2502 20 : };
2503 20 :
2504 20 : let upload_queue = std::mem::replace(
2505 20 : &mut **guard,
2506 20 : UploadQueue::Stopped(UploadQueueStopped::Deletable(
2507 20 : UploadQueueStoppedDeletable {
2508 20 : upload_queue_for_deletion,
2509 20 : deleted_at: SetDeletedFlagProgress::NotRunning,
2510 20 : },
2511 20 : )),
2512 20 : );
2513 20 : if let UploadQueue::Initialized(qi) = upload_queue {
2514 20 : 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 20 : drop(qi.inprogress_tasks);
2524 :
2525 : // Tear down queued ops
2526 20 : for op in qi.queued_operations.into_iter() {
2527 16 : self.metric_end(&op);
2528 16 : // Dropping UploadOp::Barrier() here will make wait_completion() return with an Err()
2529 16 : // which is exactly what we want to happen.
2530 16 : drop(op);
2531 16 : }
2532 : }
2533 : }
2534 36 : }
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 16 : pub(crate) fn no_pending_work(&self) -> bool {
2547 16 : let inner = self.upload_queue.lock().unwrap();
2548 16 : match &*inner {
2549 : UploadQueue::Uninitialized
2550 0 : | UploadQueue::Stopped(UploadQueueStopped::Uninitialized) => true,
2551 16 : UploadQueue::Stopped(UploadQueueStopped::Deletable(x)) => {
2552 16 : x.upload_queue_for_deletion.no_pending_work()
2553 : }
2554 0 : UploadQueue::Initialized(x) => x.no_pending_work(),
2555 : }
2556 16 : }
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 1808 : pub fn remote_tenant_manifest_path(
2602 1808 : tenant_shard_id: &TenantShardId,
2603 1808 : generation: Generation,
2604 1808 : ) -> RemotePath {
2605 1808 : let path = format!(
2606 1808 : "tenants/{tenant_shard_id}/tenant-manifest{}.json",
2607 1808 : generation.get_suffix()
2608 1808 : );
2609 1808 : RemotePath::from_string(&path).expect("Failed to construct path")
2610 1808 : }
2611 :
2612 : /// Prefix to all generations' manifest objects in a tenant shard
2613 460 : pub fn remote_tenant_manifest_prefix(tenant_shard_id: &TenantShardId) -> RemotePath {
2614 460 : let path = format!("tenants/{tenant_shard_id}/tenant-manifest",);
2615 460 : RemotePath::from_string(&path).expect("Failed to construct path")
2616 460 : }
2617 :
2618 520 : pub fn remote_timelines_path(tenant_shard_id: &TenantShardId) -> RemotePath {
2619 520 : let path = format!("tenants/{tenant_shard_id}/{TIMELINES_SEGMENT_NAME}");
2620 520 : RemotePath::from_string(&path).expect("Failed to construct path")
2621 520 : }
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 60 : pub fn remote_timeline_path(
2629 60 : tenant_shard_id: &TenantShardId,
2630 60 : timeline_id: &TimelineId,
2631 60 : ) -> RemotePath {
2632 60 : remote_timelines_path(tenant_shard_id).join(Utf8Path::new(&timeline_id.to_string()))
2633 60 : }
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 4042 : pub fn remote_layer_path(
2641 4042 : tenant_id: &TenantId,
2642 4042 : timeline_id: &TimelineId,
2643 4042 : shard: ShardIndex,
2644 4042 : layer_file_name: &LayerName,
2645 4042 : generation: Generation,
2646 4042 : ) -> RemotePath {
2647 4042 : // Generation-aware key format
2648 4042 : let path = format!(
2649 4042 : "tenants/{tenant_id}{0}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{1}{2}",
2650 4042 : shard.get_suffix(),
2651 4042 : layer_file_name,
2652 4042 : generation.get_suffix()
2653 4042 : );
2654 4042 :
2655 4042 : RemotePath::from_string(&path).expect("Failed to construct path")
2656 4042 : }
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 2350630 : pub fn is_same_remote_layer_path(
2664 2350630 : aname: &LayerName,
2665 2350630 : ameta: &LayerFileMetadata,
2666 2350630 : bname: &LayerName,
2667 2350630 : bmeta: &LayerFileMetadata,
2668 2350630 : ) -> bool {
2669 2350630 : // NB: don't assert remote_layer_path(a) == remote_layer_path(b); too expensive even for debug.
2670 2350630 : aname == bname && ameta.shard == bmeta.shard && ameta.generation == bmeta.generation
2671 2350630 : }
2672 :
2673 8 : pub fn remote_initdb_archive_path(tenant_id: &TenantId, timeline_id: &TimelineId) -> RemotePath {
2674 8 : RemotePath::from_string(&format!(
2675 8 : "tenants/{tenant_id}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{INITDB_PATH}"
2676 8 : ))
2677 8 : .expect("Failed to construct path")
2678 8 : }
2679 :
2680 4 : pub fn remote_initdb_preserved_archive_path(
2681 4 : tenant_id: &TenantId,
2682 4 : timeline_id: &TimelineId,
2683 4 : ) -> RemotePath {
2684 4 : RemotePath::from_string(&format!(
2685 4 : "tenants/{tenant_id}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{INITDB_PRESERVED_PATH}"
2686 4 : ))
2687 4 : .expect("Failed to construct path")
2688 4 : }
2689 :
2690 3089 : pub fn remote_index_path(
2691 3089 : tenant_shard_id: &TenantShardId,
2692 3089 : timeline_id: &TimelineId,
2693 3089 : generation: Generation,
2694 3089 : ) -> RemotePath {
2695 3089 : RemotePath::from_string(&format!(
2696 3089 : "tenants/{tenant_shard_id}/{TIMELINES_SEGMENT_NAME}/{timeline_id}/{0}{1}",
2697 3089 : IndexPart::FILE_NAME,
2698 3089 : generation.get_suffix()
2699 3089 : ))
2700 3089 : .expect("Failed to construct path")
2701 3089 : }
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 36 : pub fn parse_remote_index_path(path: RemotePath) -> Option<Generation> {
2712 36 : let file_name = match path.get_path().file_name() {
2713 36 : 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 36 : match file_name.split_once('-') {
2722 24 : Some((_, gen_suffix)) => Generation::parse_suffix(gen_suffix),
2723 12 : None => None,
2724 : }
2725 36 : }
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::{Tenant, Timeline};
2747 :
2748 16 : pub(super) fn dummy_contents(name: &str) -> Vec<u8> {
2749 16 : format!("contents for {name}").into()
2750 16 : }
2751 :
2752 4 : pub(super) fn dummy_metadata(disk_consistent_lsn: Lsn) -> TimelineMetadata {
2753 4 : let metadata = TimelineMetadata::new(
2754 4 : disk_consistent_lsn,
2755 4 : None,
2756 4 : None,
2757 4 : Lsn(0),
2758 4 : Lsn(0),
2759 4 : Lsn(0),
2760 4 : // Any version will do
2761 4 : // but it should be consistent with the one in the tests
2762 4 : crate::DEFAULT_PG_VERSION,
2763 4 : );
2764 4 :
2765 4 : // go through serialize + deserialize to fix the header, including checksum
2766 4 : TimelineMetadata::from_bytes(&metadata.to_bytes().unwrap()).unwrap()
2767 4 : }
2768 :
2769 4 : fn assert_file_list(a: &HashSet<LayerName>, b: &[&str]) {
2770 12 : let mut avec: Vec<String> = a.iter().map(|x| x.to_string()).collect();
2771 4 : avec.sort();
2772 4 :
2773 4 : let mut bvec = b.to_vec();
2774 4 : bvec.sort_unstable();
2775 4 :
2776 4 : assert_eq!(avec, bvec);
2777 4 : }
2778 :
2779 8 : fn assert_remote_files(expected: &[&str], remote_path: &Utf8Path, generation: Generation) {
2780 8 : let mut expected: Vec<String> = expected
2781 8 : .iter()
2782 32 : .map(|x| format!("{}{}", x, generation.get_suffix()))
2783 8 : .collect();
2784 8 : expected.sort();
2785 8 :
2786 8 : let mut found: Vec<String> = Vec::new();
2787 32 : for entry in std::fs::read_dir(remote_path).unwrap().flatten() {
2788 32 : let entry_name = entry.file_name();
2789 32 : let fname = entry_name.to_str().unwrap();
2790 32 : found.push(String::from(fname));
2791 32 : }
2792 8 : found.sort();
2793 8 :
2794 8 : assert_eq!(found, expected);
2795 8 : }
2796 :
2797 : struct TestSetup {
2798 : harness: TenantHarness,
2799 : tenant: Arc<Tenant>,
2800 : timeline: Arc<Timeline>,
2801 : tenant_ctx: RequestContext,
2802 : }
2803 :
2804 : impl TestSetup {
2805 16 : async fn new(test_name: &str) -> anyhow::Result<Self> {
2806 16 : let test_name = Box::leak(Box::new(format!("remote_timeline_client__{test_name}")));
2807 16 : let harness = TenantHarness::create(test_name).await?;
2808 16 : let (tenant, ctx) = harness.load().await;
2809 :
2810 16 : let timeline = tenant
2811 16 : .create_test_timeline(TIMELINE_ID, Lsn(8), DEFAULT_PG_VERSION, &ctx)
2812 16 : .await?;
2813 :
2814 16 : Ok(Self {
2815 16 : harness,
2816 16 : tenant,
2817 16 : timeline,
2818 16 : tenant_ctx: ctx,
2819 16 : })
2820 16 : }
2821 :
2822 : /// Construct a RemoteTimelineClient in an arbitrary generation
2823 20 : fn build_client(&self, generation: Generation) -> Arc<RemoteTimelineClient> {
2824 20 : let location_conf = AttachedLocationConfig {
2825 20 : generation,
2826 20 : attach_mode: AttachmentMode::Single,
2827 20 : };
2828 20 : Arc::new(RemoteTimelineClient {
2829 20 : conf: self.harness.conf,
2830 20 : runtime: tokio::runtime::Handle::current(),
2831 20 : tenant_shard_id: self.harness.tenant_shard_id,
2832 20 : timeline_id: TIMELINE_ID,
2833 20 : generation,
2834 20 : storage_impl: self.harness.remote_storage.clone(),
2835 20 : deletion_queue_client: self.harness.deletion_queue.new_client(),
2836 20 : upload_queue: Mutex::new(UploadQueue::Uninitialized),
2837 20 : metrics: Arc::new(RemoteTimelineClientMetrics::new(
2838 20 : &self.harness.tenant_shard_id,
2839 20 : &TIMELINE_ID,
2840 20 : )),
2841 20 : config: std::sync::RwLock::new(RemoteTimelineClientConfig::from(&location_conf)),
2842 20 : cancel: CancellationToken::new(),
2843 20 : })
2844 20 : }
2845 :
2846 : /// A tracing::Span that satisfies remote_timeline_client methods that assert tenant_id
2847 : /// and timeline_id are present.
2848 12 : fn span(&self) -> tracing::Span {
2849 12 : 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 12 : }
2856 : }
2857 :
2858 : // Test scheduling
2859 : #[tokio::test]
2860 4 : async fn upload_scheduling() {
2861 4 : // Test outline:
2862 4 : //
2863 4 : // Schedule upload of a bunch of layers. Check that they are started immediately, not queued
2864 4 : // Schedule upload of index. Check that it is queued
2865 4 : // let the layer file uploads finish. Check that the index-upload is now started
2866 4 : // let the index-upload finish.
2867 4 : //
2868 4 : // Download back the index.json. Check that the list of files is correct
2869 4 : //
2870 4 : // Schedule upload. Schedule deletion. Check that the deletion is queued
2871 4 : // let upload finish. Check that deletion is now started
2872 4 : // Schedule another deletion. Check that it's launched immediately.
2873 4 : // Schedule index upload. Check that it's queued
2874 4 :
2875 4 : let test_setup = TestSetup::new("upload_scheduling").await.unwrap();
2876 4 : let span = test_setup.span();
2877 4 : let _guard = span.enter();
2878 4 :
2879 4 : let TestSetup {
2880 4 : harness,
2881 4 : tenant: _tenant,
2882 4 : timeline,
2883 4 : tenant_ctx: _tenant_ctx,
2884 4 : } = test_setup;
2885 4 :
2886 4 : let client = &timeline.remote_client;
2887 4 :
2888 4 : // Download back the index.json, and check that the list of files is correct
2889 4 : let initial_index_part = match client
2890 4 : .download_index_file(&CancellationToken::new())
2891 4 : .await
2892 4 : .unwrap()
2893 4 : {
2894 4 : MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
2895 4 : MaybeDeletedIndexPart::Deleted(_) => panic!("unexpectedly got deleted index part"),
2896 4 : };
2897 4 : let initial_layers = initial_index_part
2898 4 : .layer_metadata
2899 4 : .keys()
2900 4 : .map(|f| f.to_owned())
2901 4 : .collect::<HashSet<LayerName>>();
2902 4 : let initial_layer = {
2903 4 : assert!(initial_layers.len() == 1);
2904 4 : initial_layers.into_iter().next().unwrap()
2905 4 : };
2906 4 :
2907 4 : let timeline_path = harness.timeline_path(&TIMELINE_ID);
2908 4 :
2909 4 : println!("workdir: {}", harness.conf.workdir);
2910 4 :
2911 4 : let remote_timeline_dir = harness
2912 4 : .remote_fs_dir
2913 4 : .join(timeline_path.strip_prefix(&harness.conf.workdir).unwrap());
2914 4 : println!("remote_timeline_dir: {remote_timeline_dir}");
2915 4 :
2916 4 : let generation = harness.generation;
2917 4 : let shard = harness.shard;
2918 4 :
2919 4 : // Create a couple of dummy files, schedule upload for them
2920 4 :
2921 4 : let layers = [
2922 4 : ("000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D8-00000000016B5A51".parse().unwrap(), dummy_contents("foo")),
2923 4 : ("000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D9-00000000016B5A52".parse().unwrap(), dummy_contents("bar")),
2924 4 : ("000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59DA-00000000016B5A53".parse().unwrap(), dummy_contents("baz"))
2925 4 : ]
2926 4 : .into_iter()
2927 12 : .map(|(name, contents): (LayerName, Vec<u8>)| {
2928 12 :
2929 12 : let local_path = local_layer_path(
2930 12 : harness.conf,
2931 12 : &timeline.tenant_shard_id,
2932 12 : &timeline.timeline_id,
2933 12 : &name,
2934 12 : &generation,
2935 12 : );
2936 12 : std::fs::write(&local_path, &contents).unwrap();
2937 12 :
2938 12 : Layer::for_resident(
2939 12 : harness.conf,
2940 12 : &timeline,
2941 12 : local_path,
2942 12 : name,
2943 12 : LayerFileMetadata::new(contents.len() as u64, generation, shard),
2944 12 : )
2945 12 : }).collect::<Vec<_>>();
2946 4 :
2947 4 : client
2948 4 : .schedule_layer_file_upload(layers[0].clone())
2949 4 : .unwrap();
2950 4 : client
2951 4 : .schedule_layer_file_upload(layers[1].clone())
2952 4 : .unwrap();
2953 4 :
2954 4 : // Check that they are started immediately, not queued
2955 4 : //
2956 4 : // this works because we running within block_on, so any futures are now queued up until
2957 4 : // our next await point.
2958 4 : {
2959 4 : let mut guard = client.upload_queue.lock().unwrap();
2960 4 : let upload_queue = guard.initialized_mut().unwrap();
2961 4 : assert!(upload_queue.queued_operations.is_empty());
2962 4 : assert_eq!(upload_queue.inprogress_tasks.len(), 2);
2963 4 : assert_eq!(upload_queue.num_inprogress_layer_uploads(), 2);
2964 4 :
2965 4 : // also check that `latest_file_changes` was updated
2966 4 : assert!(upload_queue.latest_files_changes_since_metadata_upload_scheduled == 2);
2967 4 : }
2968 4 :
2969 4 : // Schedule upload of index. Check that it is queued
2970 4 : let metadata = dummy_metadata(Lsn(0x20));
2971 4 : client
2972 4 : .schedule_index_upload_for_full_metadata_update(&metadata)
2973 4 : .unwrap();
2974 4 : {
2975 4 : let mut guard = client.upload_queue.lock().unwrap();
2976 4 : let upload_queue = guard.initialized_mut().unwrap();
2977 4 : assert!(upload_queue.queued_operations.len() == 1);
2978 4 : assert!(upload_queue.latest_files_changes_since_metadata_upload_scheduled == 0);
2979 4 : }
2980 4 :
2981 4 : // Wait for the uploads to finish
2982 4 : client.wait_completion().await.unwrap();
2983 4 : {
2984 4 : let mut guard = client.upload_queue.lock().unwrap();
2985 4 : let upload_queue = guard.initialized_mut().unwrap();
2986 4 :
2987 4 : assert!(upload_queue.queued_operations.is_empty());
2988 4 : assert!(upload_queue.inprogress_tasks.is_empty());
2989 4 : }
2990 4 :
2991 4 : // Download back the index.json, and check that the list of files is correct
2992 4 : let index_part = match client
2993 4 : .download_index_file(&CancellationToken::new())
2994 4 : .await
2995 4 : .unwrap()
2996 4 : {
2997 4 : MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
2998 4 : MaybeDeletedIndexPart::Deleted(_) => panic!("unexpectedly got deleted index part"),
2999 4 : };
3000 4 :
3001 4 : assert_file_list(
3002 4 : &index_part
3003 4 : .layer_metadata
3004 4 : .keys()
3005 12 : .map(|f| f.to_owned())
3006 4 : .collect(),
3007 4 : &[
3008 4 : &initial_layer.to_string(),
3009 4 : &layers[0].layer_desc().layer_name().to_string(),
3010 4 : &layers[1].layer_desc().layer_name().to_string(),
3011 4 : ],
3012 4 : );
3013 4 : assert_eq!(index_part.metadata, metadata);
3014 4 :
3015 4 : // Schedule upload and then a deletion. Check that the deletion is queued
3016 4 : client
3017 4 : .schedule_layer_file_upload(layers[2].clone())
3018 4 : .unwrap();
3019 4 :
3020 4 : // this is no longer consistent with how deletion works with Layer::drop, but in this test
3021 4 : // keep using schedule_layer_file_deletion because we don't have a way to wait for the
3022 4 : // spawn_blocking started by the drop.
3023 4 : client
3024 4 : .schedule_layer_file_deletion(&[layers[0].layer_desc().layer_name()])
3025 4 : .unwrap();
3026 4 : {
3027 4 : let mut guard = client.upload_queue.lock().unwrap();
3028 4 : let upload_queue = guard.initialized_mut().unwrap();
3029 4 :
3030 4 : // Deletion schedules upload of the index file, and the file deletion itself
3031 4 : assert_eq!(upload_queue.queued_operations.len(), 2);
3032 4 : assert_eq!(upload_queue.inprogress_tasks.len(), 1);
3033 4 : assert_eq!(upload_queue.num_inprogress_layer_uploads(), 1);
3034 4 : assert_eq!(upload_queue.num_inprogress_deletions(), 0);
3035 4 : assert_eq!(
3036 4 : upload_queue.latest_files_changes_since_metadata_upload_scheduled,
3037 4 : 0
3038 4 : );
3039 4 : }
3040 4 : assert_remote_files(
3041 4 : &[
3042 4 : &initial_layer.to_string(),
3043 4 : &layers[0].layer_desc().layer_name().to_string(),
3044 4 : &layers[1].layer_desc().layer_name().to_string(),
3045 4 : "index_part.json",
3046 4 : ],
3047 4 : &remote_timeline_dir,
3048 4 : generation,
3049 4 : );
3050 4 :
3051 4 : // Finish them
3052 4 : client.wait_completion().await.unwrap();
3053 4 : harness.deletion_queue.pump().await;
3054 4 :
3055 4 : assert_remote_files(
3056 4 : &[
3057 4 : &initial_layer.to_string(),
3058 4 : &layers[1].layer_desc().layer_name().to_string(),
3059 4 : &layers[2].layer_desc().layer_name().to_string(),
3060 4 : "index_part.json",
3061 4 : ],
3062 4 : &remote_timeline_dir,
3063 4 : generation,
3064 4 : );
3065 4 : }
3066 :
3067 : #[tokio::test]
3068 4 : async fn bytes_unfinished_gauge_for_layer_file_uploads() {
3069 4 : // Setup
3070 4 :
3071 4 : let TestSetup {
3072 4 : harness,
3073 4 : tenant: _tenant,
3074 4 : timeline,
3075 4 : ..
3076 4 : } = TestSetup::new("metrics").await.unwrap();
3077 4 : let client = &timeline.remote_client;
3078 4 :
3079 4 : let layer_file_name_1: LayerName = "000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D8-00000000016B5A51".parse().unwrap();
3080 4 : let local_path = local_layer_path(
3081 4 : harness.conf,
3082 4 : &timeline.tenant_shard_id,
3083 4 : &timeline.timeline_id,
3084 4 : &layer_file_name_1,
3085 4 : &harness.generation,
3086 4 : );
3087 4 : let content_1 = dummy_contents("foo");
3088 4 : std::fs::write(&local_path, &content_1).unwrap();
3089 4 :
3090 4 : let layer_file_1 = Layer::for_resident(
3091 4 : harness.conf,
3092 4 : &timeline,
3093 4 : local_path,
3094 4 : layer_file_name_1.clone(),
3095 4 : LayerFileMetadata::new(content_1.len() as u64, harness.generation, harness.shard),
3096 4 : );
3097 4 :
3098 4 : #[derive(Debug, PartialEq, Clone, Copy)]
3099 4 : struct BytesStartedFinished {
3100 4 : started: Option<usize>,
3101 4 : finished: Option<usize>,
3102 4 : }
3103 4 : impl std::ops::Add for BytesStartedFinished {
3104 4 : type Output = Self;
3105 8 : fn add(self, rhs: Self) -> Self::Output {
3106 8 : Self {
3107 8 : started: self.started.map(|v| v + rhs.started.unwrap_or(0)),
3108 8 : finished: self.finished.map(|v| v + rhs.finished.unwrap_or(0)),
3109 8 : }
3110 8 : }
3111 4 : }
3112 12 : let get_bytes_started_stopped = || {
3113 12 : let started = client
3114 12 : .metrics
3115 12 : .get_bytes_started_counter_value(&RemoteOpFileKind::Layer, &RemoteOpKind::Upload)
3116 12 : .map(|v| v.try_into().unwrap());
3117 12 : let stopped = client
3118 12 : .metrics
3119 12 : .get_bytes_finished_counter_value(&RemoteOpFileKind::Layer, &RemoteOpKind::Upload)
3120 12 : .map(|v| v.try_into().unwrap());
3121 12 : BytesStartedFinished {
3122 12 : started,
3123 12 : finished: stopped,
3124 12 : }
3125 12 : };
3126 4 :
3127 4 : // Test
3128 4 : tracing::info!("now doing actual test");
3129 4 :
3130 4 : let actual_a = get_bytes_started_stopped();
3131 4 :
3132 4 : client
3133 4 : .schedule_layer_file_upload(layer_file_1.clone())
3134 4 : .unwrap();
3135 4 :
3136 4 : let actual_b = get_bytes_started_stopped();
3137 4 :
3138 4 : client.wait_completion().await.unwrap();
3139 4 :
3140 4 : let actual_c = get_bytes_started_stopped();
3141 4 :
3142 4 : // Validate
3143 4 :
3144 4 : let expected_b = actual_a
3145 4 : + BytesStartedFinished {
3146 4 : started: Some(content_1.len()),
3147 4 : // assert that the _finished metric is created eagerly so that subtractions work on first sample
3148 4 : finished: Some(0),
3149 4 : };
3150 4 : assert_eq!(actual_b, expected_b);
3151 4 :
3152 4 : let expected_c = actual_a
3153 4 : + BytesStartedFinished {
3154 4 : started: Some(content_1.len()),
3155 4 : finished: Some(content_1.len()),
3156 4 : };
3157 4 : assert_eq!(actual_c, expected_c);
3158 4 : }
3159 :
3160 24 : async fn inject_index_part(test_state: &TestSetup, generation: Generation) -> IndexPart {
3161 24 : // An empty IndexPart, just sufficient to ensure deserialization will succeed
3162 24 : let example_index_part = IndexPart::example();
3163 24 :
3164 24 : let index_part_bytes = serde_json::to_vec(&example_index_part).unwrap();
3165 24 :
3166 24 : let index_path = test_state.harness.remote_fs_dir.join(
3167 24 : remote_index_path(
3168 24 : &test_state.harness.tenant_shard_id,
3169 24 : &TIMELINE_ID,
3170 24 : generation,
3171 24 : )
3172 24 : .get_path(),
3173 24 : );
3174 24 :
3175 24 : std::fs::create_dir_all(index_path.parent().unwrap())
3176 24 : .expect("creating test dir should work");
3177 24 :
3178 24 : eprintln!("Writing {index_path}");
3179 24 : std::fs::write(&index_path, index_part_bytes).unwrap();
3180 24 : example_index_part
3181 24 : }
3182 :
3183 : /// Assert that when a RemoteTimelineclient in generation `get_generation` fetches its
3184 : /// index, the IndexPart returned is equal to `expected`
3185 20 : async fn assert_got_index_part(
3186 20 : test_state: &TestSetup,
3187 20 : get_generation: Generation,
3188 20 : expected: &IndexPart,
3189 20 : ) {
3190 20 : let client = test_state.build_client(get_generation);
3191 :
3192 20 : let download_r = client
3193 20 : .download_index_file(&CancellationToken::new())
3194 20 : .await
3195 20 : .expect("download should always succeed");
3196 20 : assert!(matches!(download_r, MaybeDeletedIndexPart::IndexPart(_)));
3197 20 : match download_r {
3198 20 : MaybeDeletedIndexPart::IndexPart(index_part) => {
3199 20 : assert_eq!(&index_part, expected);
3200 : }
3201 0 : MaybeDeletedIndexPart::Deleted(_index_part) => panic!("Test doesn't set deleted_at"),
3202 : }
3203 20 : }
3204 :
3205 : #[tokio::test]
3206 4 : async fn index_part_download_simple() -> anyhow::Result<()> {
3207 4 : let test_state = TestSetup::new("index_part_download_simple").await.unwrap();
3208 4 : let span = test_state.span();
3209 4 : let _guard = span.enter();
3210 4 :
3211 4 : // Simple case: we are in generation N, load the index from generation N - 1
3212 4 : let generation_n = 5;
3213 4 : let injected = inject_index_part(&test_state, Generation::new(generation_n - 1)).await;
3214 4 :
3215 4 : assert_got_index_part(&test_state, Generation::new(generation_n), &injected).await;
3216 4 :
3217 4 : Ok(())
3218 4 : }
3219 :
3220 : #[tokio::test]
3221 4 : async fn index_part_download_ordering() -> anyhow::Result<()> {
3222 4 : let test_state = TestSetup::new("index_part_download_ordering")
3223 4 : .await
3224 4 : .unwrap();
3225 4 :
3226 4 : let span = test_state.span();
3227 4 : let _guard = span.enter();
3228 4 :
3229 4 : // A generation-less IndexPart exists in the bucket, we should find it
3230 4 : let generation_n = 5;
3231 4 : let injected_none = inject_index_part(&test_state, Generation::none()).await;
3232 4 : assert_got_index_part(&test_state, Generation::new(generation_n), &injected_none).await;
3233 4 :
3234 4 : // If a more recent-than-none generation exists, we should prefer to load that
3235 4 : let injected_1 = inject_index_part(&test_state, Generation::new(1)).await;
3236 4 : assert_got_index_part(&test_state, Generation::new(generation_n), &injected_1).await;
3237 4 :
3238 4 : // If a more-recent-than-me generation exists, we should ignore it.
3239 4 : let _injected_10 = inject_index_part(&test_state, Generation::new(10)).await;
3240 4 : assert_got_index_part(&test_state, Generation::new(generation_n), &injected_1).await;
3241 4 :
3242 4 : // If a directly previous generation exists, _and_ an index exists in my own
3243 4 : // generation, I should prefer my own generation.
3244 4 : let _injected_prev =
3245 4 : inject_index_part(&test_state, Generation::new(generation_n - 1)).await;
3246 4 : let injected_current = inject_index_part(&test_state, Generation::new(generation_n)).await;
3247 4 : assert_got_index_part(
3248 4 : &test_state,
3249 4 : Generation::new(generation_n),
3250 4 : &injected_current,
3251 4 : )
3252 4 : .await;
3253 4 :
3254 4 : Ok(())
3255 4 : }
3256 : }
|