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