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