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