LCOV - code coverage report
Current view: top level - pageserver/src/tenant/remote_timeline_client - download.rs (source / functions) Coverage Total Hit
Test: b4ae4c4857f9ef3e144e982a35ee23bc84c71983.info Lines: 85.8 % 372 319
Test Date: 2024-10-22 22:13:45 Functions: 54.4 % 79 43

            Line data    Source code
       1              : //! Helper functions to download files from remote storage with a RemoteStorage
       2              : //!
       3              : //! The functions in this module retry failed operations automatically, according
       4              : //! to the FAILED_DOWNLOAD_RETRIES constant.
       5              : 
       6              : use std::collections::HashSet;
       7              : use std::future::Future;
       8              : use std::str::FromStr;
       9              : use std::time::SystemTime;
      10              : 
      11              : use anyhow::{anyhow, Context};
      12              : use camino::{Utf8Path, Utf8PathBuf};
      13              : use pageserver_api::shard::TenantShardId;
      14              : use tokio::fs::{self, File, OpenOptions};
      15              : use tokio::io::{AsyncSeekExt, AsyncWriteExt};
      16              : use tokio_util::io::StreamReader;
      17              : use tokio_util::sync::CancellationToken;
      18              : use tracing::warn;
      19              : use utils::backoff;
      20              : 
      21              : use crate::config::PageServerConf;
      22              : use crate::context::RequestContext;
      23              : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
      24              : use crate::tenant::remote_timeline_client::{remote_layer_path, remote_timelines_path};
      25              : use crate::tenant::storage_layer::LayerName;
      26              : use crate::tenant::Generation;
      27              : #[cfg_attr(target_os = "macos", allow(unused_imports))]
      28              : use crate::virtual_file::owned_buffers_io::io_buf_ext::IoBufExt;
      29              : use crate::virtual_file::{on_fatal_io_error, MaybeFatalIo, VirtualFile};
      30              : use crate::TEMP_FILE_SUFFIX;
      31              : use remote_storage::{DownloadError, DownloadOpts, GenericRemoteStorage, ListingMode, RemotePath};
      32              : use utils::crashsafe::path_with_suffix_extension;
      33              : use utils::id::{TenantId, TimelineId};
      34              : use utils::pausable_failpoint;
      35              : 
      36              : use super::index::{IndexPart, LayerFileMetadata};
      37              : use super::{
      38              :     parse_remote_index_path, remote_index_path, remote_initdb_archive_path,
      39              :     remote_initdb_preserved_archive_path, remote_tenant_path, FAILED_DOWNLOAD_WARN_THRESHOLD,
      40              :     FAILED_REMOTE_OP_RETRIES, INITDB_PATH,
      41              : };
      42              : 
      43              : ///
      44              : /// If 'metadata' is given, we will validate that the downloaded file's size matches that
      45              : /// in the metadata. (In the future, we might do more cross-checks, like CRC validation)
      46              : ///
      47              : /// Returns the size of the downloaded file.
      48              : #[allow(clippy::too_many_arguments)]
      49            6 : pub async fn download_layer_file<'a>(
      50            6 :     conf: &'static PageServerConf,
      51            6 :     storage: &'a GenericRemoteStorage,
      52            6 :     tenant_shard_id: TenantShardId,
      53            6 :     timeline_id: TimelineId,
      54            6 :     layer_file_name: &'a LayerName,
      55            6 :     layer_metadata: &'a LayerFileMetadata,
      56            6 :     local_path: &Utf8Path,
      57            6 :     cancel: &CancellationToken,
      58            6 :     ctx: &RequestContext,
      59            6 : ) -> Result<u64, DownloadError> {
      60            6 :     debug_assert_current_span_has_tenant_and_timeline_id();
      61            6 : 
      62            6 :     let timeline_path = conf.timeline_path(&tenant_shard_id, &timeline_id);
      63            6 : 
      64            6 :     let remote_path = remote_layer_path(
      65            6 :         &tenant_shard_id.tenant_id,
      66            6 :         &timeline_id,
      67            6 :         layer_metadata.shard,
      68            6 :         layer_file_name,
      69            6 :         layer_metadata.generation,
      70            6 :     );
      71            6 : 
      72            6 :     // Perform a rename inspired by durable_rename from file_utils.c.
      73            6 :     // The sequence:
      74            6 :     //     write(tmp)
      75            6 :     //     fsync(tmp)
      76            6 :     //     rename(tmp, new)
      77            6 :     //     fsync(new)
      78            6 :     //     fsync(parent)
      79            6 :     // For more context about durable_rename check this email from postgres mailing list:
      80            6 :     // https://www.postgresql.org/message-id/56583BDD.9060302@2ndquadrant.com
      81            6 :     // If pageserver crashes the temp file will be deleted on startup and re-downloaded.
      82            6 :     let temp_file_path = path_with_suffix_extension(local_path, TEMP_DOWNLOAD_EXTENSION);
      83              : 
      84            6 :     let bytes_amount = download_retry(
      85           59 :         || async { download_object(storage, &remote_path, &temp_file_path, cancel, ctx).await },
      86            6 :         &format!("download {remote_path:?}"),
      87            6 :         cancel,
      88            6 :     )
      89           59 :     .await?;
      90              : 
      91            6 :     let expected = layer_metadata.file_size;
      92            6 :     if expected != bytes_amount {
      93            0 :         return Err(DownloadError::Other(anyhow!(
      94            0 :             "According to layer file metadata should have downloaded {expected} bytes but downloaded {bytes_amount} bytes into file {temp_file_path:?}",
      95            0 :         )));
      96            6 :     }
      97            6 : 
      98            6 :     fail::fail_point!("remote-storage-download-pre-rename", |_| {
      99            0 :         Err(DownloadError::Other(anyhow!(
     100            0 :             "remote-storage-download-pre-rename failpoint triggered"
     101            0 :         )))
     102            6 :     });
     103              : 
     104            6 :     fs::rename(&temp_file_path, &local_path)
     105            4 :         .await
     106            6 :         .with_context(|| format!("rename download layer file to {local_path}"))
     107            6 :         .map_err(DownloadError::Other)?;
     108              : 
     109              :     // We use fatal_err() below because the after the rename above,
     110              :     // the in-memory state of the filesystem already has the layer file in its final place,
     111              :     // and subsequent pageserver code could think it's durable while it really isn't.
     112            6 :     let work = {
     113            6 :         let ctx = ctx.detached_child(ctx.task_kind(), ctx.download_behavior());
     114            6 :         async move {
     115            6 :             let timeline_dir = VirtualFile::open(&timeline_path, &ctx)
     116            3 :                 .await
     117            6 :                 .fatal_err("VirtualFile::open for timeline dir fsync");
     118            6 :             timeline_dir
     119            6 :                 .sync_all()
     120            3 :                 .await
     121            6 :                 .fatal_err("VirtualFile::sync_all timeline dir");
     122            6 :         }
     123              :     };
     124            6 :     crate::virtual_file::io_engine::get()
     125            6 :         .spawn_blocking_and_block_on_if_std(work)
     126            9 :         .await;
     127              : 
     128            6 :     tracing::debug!("download complete: {local_path}");
     129              : 
     130            6 :     Ok(bytes_amount)
     131            6 : }
     132              : 
     133              : /// Download the object `src_path` in the remote `storage` to local path `dst_path`.
     134              : ///
     135              : /// If Ok() is returned, the download succeeded and the inode & data have been made durable.
     136              : /// (Note that the directory entry for the inode is not made durable.)
     137              : /// The file size in bytes is returned.
     138              : ///
     139              : /// If Err() is returned, there was some error. The file at `dst_path` has been unlinked.
     140              : /// The unlinking has _not_ been made durable.
     141            6 : async fn download_object<'a>(
     142            6 :     storage: &'a GenericRemoteStorage,
     143            6 :     src_path: &RemotePath,
     144            6 :     dst_path: &Utf8PathBuf,
     145            6 :     cancel: &CancellationToken,
     146            6 :     #[cfg_attr(target_os = "macos", allow(unused_variables))] ctx: &RequestContext,
     147            6 : ) -> Result<u64, DownloadError> {
     148            6 :     let res = match crate::virtual_file::io_engine::get() {
     149            0 :         crate::virtual_file::io_engine::IoEngine::NotSet => panic!("unset"),
     150              :         crate::virtual_file::io_engine::IoEngine::StdFs => {
     151            3 :             async {
     152            3 :                 let destination_file = tokio::fs::File::create(dst_path)
     153            2 :                     .await
     154            3 :                     .with_context(|| format!("create a destination file for layer '{dst_path}'"))
     155            3 :                     .map_err(DownloadError::Other)?;
     156              : 
     157            3 :                 let download = storage
     158            3 :                     .download(src_path, &DownloadOpts::default(), cancel)
     159            4 :                     .await?;
     160              : 
     161            3 :                 pausable_failpoint!("before-downloading-layer-stream-pausable");
     162              : 
     163            3 :                 let mut buf_writer =
     164            3 :                     tokio::io::BufWriter::with_capacity(super::BUFFER_SIZE, destination_file);
     165            3 : 
     166            3 :                 let mut reader = tokio_util::io::StreamReader::new(download.download_stream);
     167              : 
     168           14 :                 let bytes_amount = tokio::io::copy_buf(&mut reader, &mut buf_writer).await?;
     169            3 :                 buf_writer.flush().await?;
     170              : 
     171            3 :                 let mut destination_file = buf_writer.into_inner();
     172            3 : 
     173            3 :                 // Tokio doc here: https://docs.rs/tokio/1.17.0/tokio/fs/struct.File.html states that:
     174            3 :                 // A file will not be closed immediately when it goes out of scope if there are any IO operations
     175            3 :                 // that have not yet completed. To ensure that a file is closed immediately when it is dropped,
     176            3 :                 // you should call flush before dropping it.
     177            3 :                 //
     178            3 :                 // From the tokio code I see that it waits for pending operations to complete. There shouldt be any because
     179            3 :                 // we assume that `destination_file` file is fully written. I e there is no pending .write(...).await operations.
     180            3 :                 // But for additional safety lets check/wait for any pending operations.
     181            3 :                 destination_file
     182            3 :                     .flush()
     183            0 :                     .await
     184            3 :                     .maybe_fatal_err("download_object sync_all")
     185            3 :                     .with_context(|| format!("flush source file at {dst_path}"))
     186            3 :                     .map_err(DownloadError::Other)?;
     187              : 
     188              :                 // not using sync_data because it can lose file size update
     189            3 :                 destination_file
     190            3 :                     .sync_all()
     191            3 :                     .await
     192            3 :                     .maybe_fatal_err("download_object sync_all")
     193            3 :                     .with_context(|| format!("failed to fsync source file at {dst_path}"))
     194            3 :                     .map_err(DownloadError::Other)?;
     195              : 
     196            3 :                 Ok(bytes_amount)
     197            3 :             }
     198           25 :             .await
     199              :         }
     200              :         #[cfg(target_os = "linux")]
     201              :         crate::virtual_file::io_engine::IoEngine::TokioEpollUring => {
     202              :             use crate::virtual_file::owned_buffers_io::{self, util::size_tracking_writer};
     203              :             use bytes::BytesMut;
     204            3 :             async {
     205            3 :                 let destination_file = VirtualFile::create(dst_path, ctx)
     206            3 :                     .await
     207            3 :                     .with_context(|| format!("create a destination file for layer '{dst_path}'"))
     208            3 :                     .map_err(DownloadError::Other)?;
     209              : 
     210            3 :                 let mut download = storage
     211            3 :                     .download(src_path, &DownloadOpts::default(), cancel)
     212            5 :                     .await?;
     213              : 
     214            3 :                 pausable_failpoint!("before-downloading-layer-stream-pausable");
     215              : 
     216              :                 // TODO: use vectored write (writev) once supported by tokio-epoll-uring.
     217              :                 // There's chunks_vectored() on the stream.
     218            3 :                 let (bytes_amount, destination_file) = async {
     219            3 :                     let size_tracking = size_tracking_writer::Writer::new(destination_file);
     220            3 :                     let mut buffered = owned_buffers_io::write::BufferedWriter::<BytesMut, _>::new(
     221            3 :                         size_tracking,
     222            3 :                         BytesMut::with_capacity(super::BUFFER_SIZE),
     223            3 :                     );
     224           18 :                     while let Some(res) =
     225           21 :                         futures::StreamExt::next(&mut download.download_stream).await
     226              :                     {
     227           18 :                         let chunk = match res {
     228           18 :                             Ok(chunk) => chunk,
     229            0 :                             Err(e) => return Err(e),
     230              :                         };
     231           18 :                         buffered.write_buffered(chunk.slice_len(), ctx).await?;
     232              :                     }
     233            3 :                     let size_tracking = buffered.flush_and_into_inner(ctx).await?;
     234            3 :                     Ok(size_tracking.into_inner())
     235            3 :                 }
     236           20 :                 .await?;
     237              : 
     238              :                 // not using sync_data because it can lose file size update
     239            3 :                 destination_file
     240            3 :                     .sync_all()
     241            3 :                     .await
     242            3 :                     .maybe_fatal_err("download_object sync_all")
     243            3 :                     .with_context(|| format!("failed to fsync source file at {dst_path}"))
     244            3 :                     .map_err(DownloadError::Other)?;
     245              : 
     246            3 :                 Ok(bytes_amount)
     247            3 :             }
     248           34 :             .await
     249              :         }
     250              :     };
     251              : 
     252              :     // in case the download failed, clean up
     253            6 :     match res {
     254            6 :         Ok(bytes_amount) => Ok(bytes_amount),
     255            0 :         Err(e) => {
     256            0 :             if let Err(e) = tokio::fs::remove_file(dst_path).await {
     257            0 :                 if e.kind() != std::io::ErrorKind::NotFound {
     258            0 :                     on_fatal_io_error(&e, &format!("Removing temporary file {dst_path}"));
     259            0 :                 }
     260            0 :             }
     261            0 :             Err(e)
     262              :         }
     263              :     }
     264            6 : }
     265              : 
     266              : const TEMP_DOWNLOAD_EXTENSION: &str = "temp_download";
     267              : 
     268            0 : pub(crate) fn is_temp_download_file(path: &Utf8Path) -> bool {
     269            0 :     let extension = path.extension();
     270            0 :     match extension {
     271            0 :         Some(TEMP_DOWNLOAD_EXTENSION) => true,
     272            0 :         Some(_) => false,
     273            0 :         None => false,
     274              :     }
     275            0 : }
     276              : 
     277          186 : async fn list_identifiers<T>(
     278          186 :     storage: &GenericRemoteStorage,
     279          186 :     prefix: RemotePath,
     280          186 :     cancel: CancellationToken,
     281          186 : ) -> anyhow::Result<(HashSet<T>, HashSet<String>)>
     282          186 : where
     283          186 :     T: FromStr + Eq + std::hash::Hash,
     284          186 : {
     285          186 :     let listing = download_retry_forever(
     286          186 :         || storage.list(Some(&prefix), ListingMode::WithDelimiter, None, &cancel),
     287          186 :         &format!("list identifiers in prefix {prefix}"),
     288          186 :         &cancel,
     289          186 :     )
     290          716 :     .await?;
     291              : 
     292          186 :     let mut parsed_ids = HashSet::new();
     293          186 :     let mut other_prefixes = HashSet::new();
     294              : 
     295          192 :     for id_remote_storage_key in listing.prefixes {
     296            6 :         let object_name = id_remote_storage_key.object_name().ok_or_else(|| {
     297            0 :             anyhow::anyhow!("failed to get object name for key {id_remote_storage_key}")
     298            6 :         })?;
     299              : 
     300            6 :         match object_name.parse::<T>() {
     301            6 :             Ok(t) => parsed_ids.insert(t),
     302            0 :             Err(_) => other_prefixes.insert(object_name.to_string()),
     303              :         };
     304              :     }
     305              : 
     306          186 :     for object in listing.keys {
     307            0 :         let object_name = object
     308            0 :             .key
     309            0 :             .object_name()
     310            0 :             .ok_or_else(|| anyhow::anyhow!("object name for key {}", object.key))?;
     311            0 :         other_prefixes.insert(object_name.to_string());
     312              :     }
     313              : 
     314          186 :     Ok((parsed_ids, other_prefixes))
     315          186 : }
     316              : 
     317              : /// List shards of given tenant in remote storage
     318            0 : pub(crate) async fn list_remote_tenant_shards(
     319            0 :     storage: &GenericRemoteStorage,
     320            0 :     tenant_id: TenantId,
     321            0 :     cancel: CancellationToken,
     322            0 : ) -> anyhow::Result<(HashSet<TenantShardId>, HashSet<String>)> {
     323            0 :     let remote_path = remote_tenant_path(&TenantShardId::unsharded(tenant_id));
     324            0 :     list_identifiers::<TenantShardId>(storage, remote_path, cancel).await
     325            0 : }
     326              : 
     327              : /// List timelines of given tenant shard in remote storage
     328          186 : pub async fn list_remote_timelines(
     329          186 :     storage: &GenericRemoteStorage,
     330          186 :     tenant_shard_id: TenantShardId,
     331          186 :     cancel: CancellationToken,
     332          186 : ) -> anyhow::Result<(HashSet<TimelineId>, HashSet<String>)> {
     333          186 :     fail::fail_point!("storage-sync-list-remote-timelines", |_| {
     334            0 :         anyhow::bail!("storage-sync-list-remote-timelines");
     335          186 :     });
     336              : 
     337          186 :     let remote_path = remote_timelines_path(&tenant_shard_id).add_trailing_slash();
     338          716 :     list_identifiers::<TimelineId>(storage, remote_path, cancel).await
     339          186 : }
     340              : 
     341           34 : async fn do_download_index_part(
     342           34 :     storage: &GenericRemoteStorage,
     343           34 :     tenant_shard_id: &TenantShardId,
     344           34 :     timeline_id: &TimelineId,
     345           34 :     index_generation: Generation,
     346           34 :     cancel: &CancellationToken,
     347           34 : ) -> Result<(IndexPart, Generation, SystemTime), DownloadError> {
     348           34 :     let remote_path = remote_index_path(tenant_shard_id, timeline_id, index_generation);
     349              : 
     350           34 :     let (index_part_bytes, index_part_mtime) = download_retry_forever(
     351           34 :         || async {
     352           34 :             let download = storage
     353           34 :                 .download(&remote_path, &DownloadOpts::default(), cancel)
     354           50 :                 .await?;
     355              : 
     356           20 :             let mut bytes = Vec::new();
     357           20 : 
     358           20 :             let stream = download.download_stream;
     359           20 :             let mut stream = StreamReader::new(stream);
     360           20 : 
     361           20 :             tokio::io::copy_buf(&mut stream, &mut bytes).await?;
     362              : 
     363           20 :             Ok((bytes, download.last_modified))
     364           68 :         },
     365           34 :         &format!("download {remote_path:?}"),
     366           34 :         cancel,
     367           34 :     )
     368           67 :     .await?;
     369              : 
     370           20 :     let index_part: IndexPart = serde_json::from_slice(&index_part_bytes)
     371           20 :         .with_context(|| format!("deserialize index part file at {remote_path:?}"))
     372           20 :         .map_err(DownloadError::Other)?;
     373              : 
     374           20 :     Ok((index_part, index_generation, index_part_mtime))
     375           34 : }
     376              : 
     377              : /// index_part.json objects are suffixed with a generation number, so we cannot
     378              : /// directly GET the latest index part without doing some probing.
     379              : ///
     380              : /// In this function we probe for the most recent index in a generation <= our current generation.
     381              : /// See "Finding the remote indices for timelines" in docs/rfcs/025-generation-numbers.md
     382           20 : #[tracing::instrument(skip_all, fields(generation=?my_generation))]
     383              : pub(crate) async fn download_index_part(
     384              :     storage: &GenericRemoteStorage,
     385              :     tenant_shard_id: &TenantShardId,
     386              :     timeline_id: &TimelineId,
     387              :     my_generation: Generation,
     388              :     cancel: &CancellationToken,
     389              : ) -> Result<(IndexPart, Generation, SystemTime), DownloadError> {
     390              :     debug_assert_current_span_has_tenant_and_timeline_id();
     391              : 
     392              :     if my_generation.is_none() {
     393              :         // Operating without generations: just fetch the generation-less path
     394              :         return do_download_index_part(
     395              :             storage,
     396              :             tenant_shard_id,
     397              :             timeline_id,
     398              :             my_generation,
     399              :             cancel,
     400              :         )
     401              :         .await;
     402              :     }
     403              : 
     404              :     // Stale case: If we were intentionally attached in a stale generation, there may already be a remote
     405              :     // index in our generation.
     406              :     //
     407              :     // This is an optimization to avoid doing the listing for the general case below.
     408              :     let res =
     409              :         do_download_index_part(storage, tenant_shard_id, timeline_id, my_generation, cancel).await;
     410              :     match res {
     411              :         Ok(index_part) => {
     412              :             tracing::debug!(
     413              :                 "Found index_part from current generation (this is a stale attachment)"
     414              :             );
     415              :             return Ok(index_part);
     416              :         }
     417              :         Err(DownloadError::NotFound) => {}
     418              :         Err(e) => return Err(e),
     419              :     };
     420              : 
     421              :     // Typical case: the previous generation of this tenant was running healthily, and had uploaded
     422              :     // and index part.  We may safely start from this index without doing a listing, because:
     423              :     //  - We checked for current generation case above
     424              :     //  - generations > my_generation are to be ignored
     425              :     //  - any other indices that exist would have an older generation than `previous_gen`, and
     426              :     //    we want to find the most recent index from a previous generation.
     427              :     //
     428              :     // This is an optimization to avoid doing the listing for the general case below.
     429              :     let res = do_download_index_part(
     430              :         storage,
     431              :         tenant_shard_id,
     432              :         timeline_id,
     433              :         my_generation.previous(),
     434              :         cancel,
     435              :     )
     436              :     .await;
     437              :     match res {
     438              :         Ok(index_part) => {
     439              :             tracing::debug!("Found index_part from previous generation");
     440              :             return Ok(index_part);
     441              :         }
     442              :         Err(DownloadError::NotFound) => {
     443              :             tracing::debug!(
     444              :                 "No index_part found from previous generation, falling back to listing"
     445              :             );
     446              :         }
     447              :         Err(e) => {
     448              :             return Err(e);
     449              :         }
     450              :     }
     451              : 
     452              :     // General case/fallback: if there is no index at my_generation or prev_generation, then list all index_part.json
     453              :     // objects, and select the highest one with a generation <= my_generation.  Constructing the prefix is equivalent
     454              :     // to constructing a full index path with no generation, because the generation is a suffix.
     455              :     let index_prefix = remote_index_path(tenant_shard_id, timeline_id, Generation::none());
     456              : 
     457              :     let indices = download_retry(
     458            6 :         || async {
     459            6 :             storage
     460            6 :                 .list(Some(&index_prefix), ListingMode::NoDelimiter, None, cancel)
     461            6 :                 .await
     462           12 :         },
     463              :         "list index_part files",
     464              :         cancel,
     465              :     )
     466              :     .await?
     467              :     .keys;
     468              : 
     469              :     // General case logic for which index to use: the latest index whose generation
     470              :     // is <= our own.  See "Finding the remote indices for timelines" in docs/rfcs/025-generation-numbers.md
     471              :     let max_previous_generation = indices
     472              :         .into_iter()
     473           18 :         .filter_map(|o| parse_remote_index_path(o.key))
     474           12 :         .filter(|g| g <= &my_generation)
     475              :         .max();
     476              : 
     477              :     match max_previous_generation {
     478              :         Some(g) => {
     479              :             tracing::debug!("Found index_part in generation {g:?}");
     480              :             do_download_index_part(storage, tenant_shard_id, timeline_id, g, cancel).await
     481              :         }
     482              :         None => {
     483              :             // Migration from legacy pre-generation state: we have a generation but no prior
     484              :             // attached pageservers did.  Try to load from a no-generation path.
     485              :             tracing::debug!("No index_part.json* found");
     486              :             do_download_index_part(
     487              :                 storage,
     488              :                 tenant_shard_id,
     489              :                 timeline_id,
     490              :                 Generation::none(),
     491              :                 cancel,
     492              :             )
     493              :             .await
     494              :         }
     495              :     }
     496              : }
     497              : 
     498            2 : pub(crate) async fn download_initdb_tar_zst(
     499            2 :     conf: &'static PageServerConf,
     500            2 :     storage: &GenericRemoteStorage,
     501            2 :     tenant_shard_id: &TenantShardId,
     502            2 :     timeline_id: &TimelineId,
     503            2 :     cancel: &CancellationToken,
     504            2 : ) -> Result<(Utf8PathBuf, File), DownloadError> {
     505            2 :     debug_assert_current_span_has_tenant_and_timeline_id();
     506            2 : 
     507            2 :     let remote_path = remote_initdb_archive_path(&tenant_shard_id.tenant_id, timeline_id);
     508            2 : 
     509            2 :     let remote_preserved_path =
     510            2 :         remote_initdb_preserved_archive_path(&tenant_shard_id.tenant_id, timeline_id);
     511            2 : 
     512            2 :     let timeline_path = conf.timelines_path(tenant_shard_id);
     513            2 : 
     514            2 :     if !timeline_path.exists() {
     515            0 :         tokio::fs::create_dir_all(&timeline_path)
     516            0 :             .await
     517            0 :             .with_context(|| format!("timeline dir creation {timeline_path}"))
     518            0 :             .map_err(DownloadError::Other)?;
     519            2 :     }
     520            2 :     let temp_path = timeline_path.join(format!(
     521            2 :         "{INITDB_PATH}.download-{timeline_id}.{TEMP_FILE_SUFFIX}"
     522            2 :     ));
     523              : 
     524            2 :     let file = download_retry(
     525            2 :         || async {
     526            2 :             let file = OpenOptions::new()
     527            2 :                 .create(true)
     528            2 :                 .truncate(true)
     529            2 :                 .read(true)
     530            2 :                 .write(true)
     531            2 :                 .open(&temp_path)
     532            2 :                 .await
     533            2 :                 .with_context(|| format!("tempfile creation {temp_path}"))
     534            2 :                 .map_err(DownloadError::Other)?;
     535              : 
     536            2 :             let download = match storage
     537            2 :                 .download(&remote_path, &DownloadOpts::default(), cancel)
     538            4 :                 .await
     539              :             {
     540            2 :                 Ok(dl) => dl,
     541              :                 Err(DownloadError::NotFound) => {
     542            0 :                     storage
     543            0 :                         .download(&remote_preserved_path, &DownloadOpts::default(), cancel)
     544            0 :                         .await?
     545              :                 }
     546            0 :                 Err(other) => Err(other)?,
     547              :             };
     548            2 :             let mut download = tokio_util::io::StreamReader::new(download.download_stream);
     549            2 :             let mut writer = tokio::io::BufWriter::with_capacity(super::BUFFER_SIZE, file);
     550            2 : 
     551          357 :             tokio::io::copy_buf(&mut download, &mut writer).await?;
     552              : 
     553            2 :             let mut file = writer.into_inner();
     554            2 : 
     555            2 :             file.seek(std::io::SeekFrom::Start(0))
     556            0 :                 .await
     557            2 :                 .with_context(|| format!("rewinding initdb.tar.zst at: {remote_path:?}"))
     558            2 :                 .map_err(DownloadError::Other)?;
     559              : 
     560            2 :             Ok(file)
     561            4 :         },
     562            2 :         &format!("download {remote_path}"),
     563            2 :         cancel,
     564            2 :     )
     565          363 :     .await
     566            2 :     .inspect_err(|_e| {
     567              :         // Do a best-effort attempt at deleting the temporary file upon encountering an error.
     568              :         // We don't have async here nor do we want to pile on any extra errors.
     569            0 :         if let Err(e) = std::fs::remove_file(&temp_path) {
     570            0 :             if e.kind() != std::io::ErrorKind::NotFound {
     571            0 :                 warn!("error deleting temporary file {temp_path}: {e}");
     572            0 :             }
     573            0 :         }
     574            2 :     })?;
     575              : 
     576            2 :     Ok((temp_path, file))
     577            2 : }
     578              : 
     579              : /// Helper function to handle retries for a download operation.
     580              : ///
     581              : /// Remote operations can fail due to rate limits (S3), spurious network
     582              : /// problems, or other external reasons. Retry FAILED_DOWNLOAD_RETRIES times,
     583              : /// with backoff.
     584              : ///
     585              : /// (See similar logic for uploads in `perform_upload_task`)
     586           14 : pub(super) async fn download_retry<T, O, F>(
     587           14 :     op: O,
     588           14 :     description: &str,
     589           14 :     cancel: &CancellationToken,
     590           14 : ) -> Result<T, DownloadError>
     591           14 : where
     592           14 :     O: FnMut() -> F,
     593           14 :     F: Future<Output = Result<T, DownloadError>>,
     594           14 : {
     595           14 :     backoff::retry(
     596           14 :         op,
     597           14 :         DownloadError::is_permanent,
     598           14 :         FAILED_DOWNLOAD_WARN_THRESHOLD,
     599           14 :         FAILED_REMOTE_OP_RETRIES,
     600           14 :         description,
     601           14 :         cancel,
     602           14 :     )
     603          428 :     .await
     604           14 :     .ok_or_else(|| DownloadError::Cancelled)
     605           14 :     .and_then(|x| x)
     606           14 : }
     607              : 
     608          220 : async fn download_retry_forever<T, O, F>(
     609          220 :     op: O,
     610          220 :     description: &str,
     611          220 :     cancel: &CancellationToken,
     612          220 : ) -> Result<T, DownloadError>
     613          220 : where
     614          220 :     O: FnMut() -> F,
     615          220 :     F: Future<Output = Result<T, DownloadError>>,
     616          220 : {
     617          220 :     backoff::retry(
     618          220 :         op,
     619          220 :         DownloadError::is_permanent,
     620          220 :         FAILED_DOWNLOAD_WARN_THRESHOLD,
     621          220 :         u32::MAX,
     622          220 :         description,
     623          220 :         cancel,
     624          220 :     )
     625          783 :     .await
     626          220 :     .ok_or_else(|| DownloadError::Cancelled)
     627          220 :     .and_then(|x| x)
     628          220 : }
        

Generated by: LCOV version 2.1-beta