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