LCOV - code coverage report
Current view: top level - pageserver/src/tenant/remote_timeline_client - upload.rs (source / functions) Coverage Total Hit
Test: 17080b14f46954d6812ea0a7dad4b2247e0840a8.info Lines: 42.2 % 180 76
Test Date: 2025-07-08 18:30:10 Functions: 19.4 % 31 6

            Line data    Source code
       1              : //! Helper functions to upload files to remote storage with a RemoteStorage
       2              : 
       3              : use std::io::{ErrorKind, SeekFrom};
       4              : use std::num::NonZeroU32;
       5              : use std::time::SystemTime;
       6              : 
       7              : use anyhow::{Context, bail};
       8              : use bytes::Bytes;
       9              : use camino::Utf8Path;
      10              : use fail::fail_point;
      11              : use pageserver_api::shard::TenantShardId;
      12              : use remote_storage::{GenericRemoteStorage, RemotePath, TimeTravelError};
      13              : use tokio::fs::{self, File};
      14              : use tokio::io::AsyncSeekExt;
      15              : use tokio_util::sync::CancellationToken;
      16              : use tracing::info;
      17              : use utils::id::{TenantId, TimelineId};
      18              : use utils::{backoff, pausable_failpoint};
      19              : 
      20              : use super::Generation;
      21              : use super::index::IndexPart;
      22              : use super::manifest::TenantManifest;
      23              : use crate::tenant::remote_timeline_client::{
      24              :     remote_index_path, remote_initdb_archive_path, remote_initdb_preserved_archive_path,
      25              :     remote_tenant_manifest_path,
      26              : };
      27              : 
      28              : /// Serializes and uploads the given index part data to the remote storage.
      29          769 : pub(crate) async fn upload_index_part(
      30          769 :     storage: &GenericRemoteStorage,
      31          769 :     tenant_shard_id: &TenantShardId,
      32          769 :     timeline_id: &TimelineId,
      33          769 :     generation: Generation,
      34          769 :     index_part: &IndexPart,
      35          769 :     cancel: &CancellationToken,
      36          769 : ) -> anyhow::Result<()> {
      37          769 :     tracing::trace!("uploading new index part");
      38              : 
      39          769 :     fail_point!("before-upload-index", |_| {
      40            0 :         bail!("failpoint before-upload-index")
      41            0 :     });
      42          769 :     pausable_failpoint!("before-upload-index-pausable");
      43              : 
      44              :     // Safety: refuse to persist invalid index metadata, to mitigate the impact of any bug that produces this
      45              :     // (this should never happen)
      46          768 :     index_part.validate().map_err(|e| anyhow::anyhow!(e))?;
      47              : 
      48              :     // FIXME: this error comes too late
      49          768 :     let serialized = index_part.to_json_bytes()?;
      50          768 :     let serialized = Bytes::from(serialized);
      51              : 
      52          768 :     let index_part_size = serialized.len();
      53              : 
      54          768 :     let remote_path = remote_index_path(tenant_shard_id, timeline_id, generation);
      55          768 :     storage
      56          768 :         .upload_storage_object(
      57          768 :             futures::stream::once(futures::future::ready(Ok(serialized))),
      58          768 :             index_part_size,
      59          768 :             &remote_path,
      60          768 :             cancel,
      61          768 :         )
      62          768 :         .await
      63          766 :         .with_context(|| format!("upload index part for '{tenant_shard_id} / {timeline_id}'"))
      64          766 : }
      65              : 
      66              : /// Serializes and uploads the given tenant manifest data to the remote storage.
      67          116 : pub(crate) async fn upload_tenant_manifest(
      68          116 :     storage: &GenericRemoteStorage,
      69          116 :     tenant_shard_id: &TenantShardId,
      70          116 :     generation: Generation,
      71          116 :     tenant_manifest: &TenantManifest,
      72          116 :     cancel: &CancellationToken,
      73          116 : ) -> anyhow::Result<()> {
      74          116 :     tracing::trace!("uploading new tenant manifest");
      75              : 
      76          116 :     fail_point!("before-upload-manifest", |_| {
      77            0 :         bail!("failpoint before-upload-manifest")
      78            0 :     });
      79          116 :     pausable_failpoint!("before-upload-manifest-pausable");
      80              : 
      81          116 :     let serialized = Bytes::from(tenant_manifest.to_json_bytes()?);
      82          116 :     let tenant_manifest_size = serialized.len();
      83          116 :     let remote_path = remote_tenant_manifest_path(tenant_shard_id, generation);
      84              : 
      85          116 :     storage
      86          116 :         .upload_storage_object(
      87          116 :             futures::stream::once(futures::future::ready(Ok(serialized))),
      88          116 :             tenant_manifest_size,
      89          116 :             &remote_path,
      90          116 :             cancel,
      91          116 :         )
      92          116 :         .await
      93          116 :         .with_context(|| format!("upload tenant manifest for '{tenant_shard_id}'"))
      94          116 : }
      95              : 
      96              : /// Attempts to upload given layer files.
      97              : /// No extra checks for overlapping files is made and any files that are already present remotely will be overwritten, if submitted during the upload.
      98              : ///
      99              : /// On an error, bumps the retries count and reschedules the entire task.
     100          890 : pub(super) async fn upload_timeline_layer<'a>(
     101          890 :     storage: &'a GenericRemoteStorage,
     102          890 :     local_path: &'a Utf8Path,
     103          890 :     remote_path: &'a RemotePath,
     104          890 :     metadata_size: u64,
     105          890 :     cancel: &CancellationToken,
     106          890 : ) -> anyhow::Result<()> {
     107          890 :     fail_point!("before-upload-layer", |_| {
     108            0 :         bail!("failpoint before-upload-layer")
     109            0 :     });
     110              : 
     111          890 :     pausable_failpoint!("before-upload-layer-pausable");
     112              : 
     113          888 :     let source_file_res = fs::File::open(&local_path).await;
     114          887 :     let source_file = match source_file_res {
     115          887 :         Ok(source_file) => source_file,
     116            0 :         Err(e) if e.kind() == ErrorKind::NotFound => {
     117              :             // If we encounter this arm, it wasn't intended, but it's also not
     118              :             // a big problem, if it's because the file was deleted before an
     119              :             // upload. However, a nonexistent file can also be indicative of
     120              :             // something worse, like when a file is scheduled for upload before
     121              :             // it has been written to disk yet.
     122              :             //
     123              :             // This is tested against `test_compaction_delete_before_upload`
     124            0 :             info!(path = %local_path, "File to upload doesn't exist. Likely the file has been deleted and an upload is not required any more.");
     125            0 :             return Ok(());
     126              :         }
     127            0 :         Err(e) => Err(e).with_context(|| format!("open a source file for layer {local_path:?}"))?,
     128              :     };
     129              : 
     130          887 :     let fs_size = source_file
     131          887 :         .metadata()
     132          887 :         .await
     133          886 :         .with_context(|| format!("get the source file metadata for layer {local_path:?}"))?
     134          886 :         .len();
     135              : 
     136          886 :     if metadata_size != fs_size {
     137            0 :         bail!(
     138            0 :             "File {local_path:?} has its current FS size {fs_size} diferent from initially determined {metadata_size}"
     139              :         );
     140          886 :     }
     141              : 
     142          886 :     let fs_size = usize::try_from(fs_size)
     143          886 :         .with_context(|| format!("convert {local_path:?} size {fs_size} usize"))?;
     144              : 
     145          886 :     let reader = tokio_util::io::ReaderStream::with_capacity(source_file, super::BUFFER_SIZE);
     146              : 
     147          886 :     storage
     148          886 :         .upload(reader, fs_size, remote_path, None, cancel)
     149          886 :         .await
     150          833 :         .with_context(|| format!("upload layer from local path '{local_path}'"))
     151          833 : }
     152              : 
     153            0 : pub(super) async fn copy_timeline_layer(
     154            0 :     storage: &GenericRemoteStorage,
     155            0 :     source_path: &RemotePath,
     156            0 :     target_path: &RemotePath,
     157            0 :     cancel: &CancellationToken,
     158            0 : ) -> anyhow::Result<()> {
     159            0 :     fail_point!("before-copy-layer", |_| {
     160            0 :         bail!("failpoint before-copy-layer")
     161            0 :     });
     162              : 
     163            0 :     pausable_failpoint!("before-copy-layer-pausable");
     164              : 
     165            0 :     storage
     166            0 :         .copy_object(source_path, target_path, cancel)
     167            0 :         .await
     168            0 :         .with_context(|| format!("copy layer {source_path} to {target_path}"))
     169            0 : }
     170              : 
     171              : /// Uploads the given `initdb` data to the remote storage.
     172            0 : pub(crate) async fn upload_initdb_dir(
     173            0 :     storage: &GenericRemoteStorage,
     174            0 :     tenant_id: &TenantId,
     175            0 :     timeline_id: &TimelineId,
     176            0 :     mut initdb_tar_zst: File,
     177            0 :     size: u64,
     178            0 :     cancel: &CancellationToken,
     179            0 : ) -> anyhow::Result<()> {
     180            0 :     tracing::trace!("uploading initdb dir");
     181              : 
     182              :     // We might have read somewhat into the file already in the prior retry attempt
     183            0 :     initdb_tar_zst.seek(SeekFrom::Start(0)).await?;
     184              : 
     185            0 :     let file = tokio_util::io::ReaderStream::with_capacity(initdb_tar_zst, super::BUFFER_SIZE);
     186              : 
     187            0 :     let remote_path = remote_initdb_archive_path(tenant_id, timeline_id);
     188            0 :     storage
     189            0 :         .upload_storage_object(file, size as usize, &remote_path, cancel)
     190            0 :         .await
     191            0 :         .with_context(|| format!("upload initdb dir for '{tenant_id} / {timeline_id}'"))
     192            0 : }
     193              : 
     194            0 : pub(crate) async fn preserve_initdb_archive(
     195            0 :     storage: &GenericRemoteStorage,
     196            0 :     tenant_id: &TenantId,
     197            0 :     timeline_id: &TimelineId,
     198            0 :     cancel: &CancellationToken,
     199            0 : ) -> anyhow::Result<()> {
     200            0 :     let source_path = remote_initdb_archive_path(tenant_id, timeline_id);
     201            0 :     let dest_path = remote_initdb_preserved_archive_path(tenant_id, timeline_id);
     202            0 :     storage
     203            0 :         .copy_object(&source_path, &dest_path, cancel)
     204            0 :         .await
     205            0 :         .with_context(|| format!("backing up initdb archive for '{tenant_id} / {timeline_id}'"))
     206            0 : }
     207              : 
     208            0 : pub(crate) async fn time_travel_recover_tenant(
     209            0 :     storage: &GenericRemoteStorage,
     210            0 :     tenant_shard_id: &TenantShardId,
     211            0 :     timestamp: SystemTime,
     212            0 :     done_if_after: SystemTime,
     213            0 :     cancel: &CancellationToken,
     214            0 : ) -> Result<(), TimeTravelError> {
     215            0 :     let warn_after = 3;
     216            0 :     let max_attempts = 10;
     217            0 :     let mut prefixes = Vec::with_capacity(2);
     218            0 :     if tenant_shard_id.is_shard_zero() {
     219            0 :         // Also recover the unsharded prefix for a shard of zero:
     220            0 :         // - if the tenant is totally unsharded, the unsharded prefix contains all the data
     221            0 :         // - if the tenant is sharded, we still want to recover the initdb data, but we only
     222            0 :         //   want to do it once, so let's do it on the 0 shard
     223            0 :         let timelines_path_unsharded =
     224            0 :             super::remote_timelines_path_unsharded(&tenant_shard_id.tenant_id);
     225            0 :         prefixes.push(timelines_path_unsharded);
     226            0 :     }
     227            0 :     if !tenant_shard_id.is_unsharded() {
     228            0 :         // If the tenant is sharded, we need to recover the sharded prefix
     229            0 :         let timelines_path = super::remote_timelines_path(tenant_shard_id);
     230            0 :         prefixes.push(timelines_path);
     231            0 :     }
     232              : 
     233              :     // Limit the number of versions deletions, mostly so that we don't
     234              :     // keep requesting forever if the list is too long, as we'd put the
     235              :     // list in RAM.
     236              :     // Building a list of 100k entries that reaches the limit roughly takes
     237              :     // 40 seconds, and roughly corresponds to tenants of 2 TiB physical size.
     238              :     const COMPLEXITY_LIMIT: Option<NonZeroU32> = NonZeroU32::new(100_000);
     239              : 
     240            0 :     for prefix in &prefixes {
     241            0 :         backoff::retry(
     242            0 :             || async {
     243            0 :                 storage
     244            0 :                     .time_travel_recover(
     245            0 :                         Some(prefix),
     246            0 :                         timestamp,
     247            0 :                         done_if_after,
     248            0 :                         cancel,
     249            0 :                         COMPLEXITY_LIMIT,
     250            0 :                     )
     251            0 :                     .await
     252            0 :             },
     253            0 :             |e| !matches!(e, TimeTravelError::Other(_)),
     254            0 :             warn_after,
     255            0 :             max_attempts,
     256            0 :             "time travel recovery of tenant prefix",
     257            0 :             cancel,
     258              :         )
     259            0 :         .await
     260            0 :         .ok_or_else(|| TimeTravelError::Cancelled)
     261            0 :         .and_then(|x| x)?;
     262              :     }
     263            0 :     Ok(())
     264            0 : }
        

Generated by: LCOV version 2.1-beta