LCOV - code coverage report
Current view: top level - storage_scrubber/src - tenant_snapshot.rs (source / functions) Coverage Total Hit
Test: 90b23405d17e36048d3bb64e314067f397803f1b.info Lines: 0.0 % 200 0
Test Date: 2024-09-20 13:14:58 Functions: 0.0 % 17 0

            Line data    Source code
       1              : use std::collections::HashMap;
       2              : use std::sync::Arc;
       3              : 
       4              : use crate::checks::{list_timeline_blobs, BlobDataParseResult, RemoteTimelineBlobData};
       5              : use crate::metadata_stream::{stream_tenant_shards, stream_tenant_timelines};
       6              : use crate::{
       7              :     download_object_to_file_s3, init_remote, init_remote_s3, BucketConfig, NodeKind, RootTarget,
       8              :     TenantShardTimelineId,
       9              : };
      10              : use anyhow::Context;
      11              : use async_stream::stream;
      12              : use aws_sdk_s3::Client;
      13              : use camino::Utf8PathBuf;
      14              : use futures::{StreamExt, TryStreamExt};
      15              : use pageserver::tenant::remote_timeline_client::index::LayerFileMetadata;
      16              : use pageserver::tenant::storage_layer::LayerName;
      17              : use pageserver::tenant::IndexPart;
      18              : use pageserver_api::shard::TenantShardId;
      19              : use remote_storage::GenericRemoteStorage;
      20              : use utils::generation::Generation;
      21              : use utils::id::TenantId;
      22              : 
      23              : pub struct SnapshotDownloader {
      24              :     s3_client: Arc<Client>,
      25              :     s3_root: RootTarget,
      26              :     bucket_config: BucketConfig,
      27              :     tenant_id: TenantId,
      28              :     output_path: Utf8PathBuf,
      29              :     concurrency: usize,
      30              : }
      31              : 
      32              : impl SnapshotDownloader {
      33            0 :     pub async fn new(
      34            0 :         bucket_config: BucketConfig,
      35            0 :         tenant_id: TenantId,
      36            0 :         output_path: Utf8PathBuf,
      37            0 :         concurrency: usize,
      38            0 :     ) -> anyhow::Result<Self> {
      39            0 :         let (s3_client, s3_root) =
      40            0 :             init_remote_s3(bucket_config.clone(), NodeKind::Pageserver).await?;
      41            0 :         Ok(Self {
      42            0 :             s3_client,
      43            0 :             s3_root,
      44            0 :             bucket_config,
      45            0 :             tenant_id,
      46            0 :             output_path,
      47            0 :             concurrency,
      48            0 :         })
      49            0 :     }
      50              : 
      51            0 :     async fn download_layer(
      52            0 :         &self,
      53            0 :         ttid: TenantShardTimelineId,
      54            0 :         layer_name: LayerName,
      55            0 :         layer_metadata: LayerFileMetadata,
      56            0 :     ) -> anyhow::Result<(LayerName, LayerFileMetadata)> {
      57            0 :         // Note this is local as in a local copy of S3 data, not local as in the pageserver's local format.  They use
      58            0 :         // different layer names (remote-style has the generation suffix)
      59            0 :         let local_path = self.output_path.join(format!(
      60            0 :             "{}/timelines/{}/{}{}",
      61            0 :             ttid.tenant_shard_id,
      62            0 :             ttid.timeline_id,
      63            0 :             layer_name,
      64            0 :             layer_metadata.generation.get_suffix()
      65            0 :         ));
      66            0 : 
      67            0 :         // We should only be called for layers that are owned by the input TTID
      68            0 :         assert_eq!(layer_metadata.shard, ttid.tenant_shard_id.to_index());
      69              : 
      70              :         // Assumption: we always write layer files atomically, and layer files are immutable.  Therefore if the file
      71              :         // already exists on local disk, we assume it is fully correct and skip it.
      72            0 :         if tokio::fs::try_exists(&local_path).await? {
      73            0 :             tracing::debug!("{} already exists", local_path);
      74            0 :             return Ok((layer_name, layer_metadata));
      75              :         } else {
      76            0 :             tracing::debug!("{} requires download...", local_path);
      77              : 
      78            0 :             let timeline_root = self.s3_root.timeline_root(&ttid);
      79            0 :             let remote_layer_path = format!(
      80            0 :                 "{}{}{}",
      81            0 :                 timeline_root.prefix_in_bucket,
      82            0 :                 layer_name,
      83            0 :                 layer_metadata.generation.get_suffix()
      84            0 :             );
      85              : 
      86              :             // List versions: the object might be deleted.
      87            0 :             let versions = self
      88            0 :                 .s3_client
      89            0 :                 .list_object_versions()
      90            0 :                 .bucket(self.bucket_config.bucket.clone())
      91            0 :                 .prefix(&remote_layer_path)
      92            0 :                 .send()
      93            0 :                 .await?;
      94            0 :             let Some(version) = versions.versions.as_ref().and_then(|v| v.first()) else {
      95            0 :                 return Err(anyhow::anyhow!("No versions found for {remote_layer_path}"));
      96              :             };
      97            0 :             download_object_to_file_s3(
      98            0 :                 &self.s3_client,
      99            0 :                 &self.bucket_config.bucket,
     100            0 :                 &remote_layer_path,
     101            0 :                 version.version_id.as_deref(),
     102            0 :                 &local_path,
     103            0 :             )
     104            0 :             .await?;
     105              : 
     106            0 :             tracing::debug!("Downloaded successfully to {local_path}");
     107              :         }
     108              : 
     109            0 :         Ok((layer_name, layer_metadata))
     110            0 :     }
     111              : 
     112              :     /// Download many layers belonging to the same TTID, with some concurrency
     113            0 :     async fn download_layers(
     114            0 :         &self,
     115            0 :         ttid: TenantShardTimelineId,
     116            0 :         layers: Vec<(LayerName, LayerFileMetadata)>,
     117            0 :     ) -> anyhow::Result<()> {
     118            0 :         let layer_count = layers.len();
     119            0 :         tracing::info!("Downloading {} layers for timeline {ttid}...", layer_count);
     120            0 :         let layers_stream = stream! {
     121            0 :             for (layer_name, layer_metadata) in layers {
     122            0 :                 yield self.download_layer(ttid, layer_name, layer_metadata);
     123            0 :             }
     124            0 :         };
     125            0 : 
     126            0 :         tokio::fs::create_dir_all(self.output_path.join(format!(
     127            0 :             "{}/timelines/{}",
     128            0 :             ttid.tenant_shard_id, ttid.timeline_id
     129            0 :         )))
     130            0 :         .await?;
     131              : 
     132            0 :         let layer_results = layers_stream.buffered(self.concurrency);
     133            0 :         let mut layer_results = std::pin::pin!(layer_results);
     134            0 : 
     135            0 :         let mut err = None;
     136            0 :         let mut download_count = 0;
     137            0 :         while let Some(i) = layer_results.next().await {
     138            0 :             download_count += 1;
     139            0 :             match i {
     140            0 :                 Ok((layer_name, layer_metadata)) => {
     141            0 :                     tracing::info!(
     142            0 :                         "[{download_count}/{layer_count}] OK: {} bytes {ttid} {}",
     143              :                         layer_metadata.file_size,
     144              :                         layer_name
     145              :                     );
     146              :                 }
     147            0 :                 Err(e) => {
     148            0 :                     // Warn and continue: we will download what we can
     149            0 :                     tracing::warn!("Download error: {e}");
     150            0 :                     err = Some(e);
     151              :                 }
     152              :             }
     153              :         }
     154            0 :         if let Some(e) = err {
     155            0 :             tracing::warn!("Some errors occurred downloading {ttid} layers, last error: {e}");
     156            0 :             Err(e)
     157              :         } else {
     158            0 :             Ok(())
     159              :         }
     160            0 :     }
     161              : 
     162            0 :     async fn download_timeline(
     163            0 :         &self,
     164            0 :         ttid: TenantShardTimelineId,
     165            0 :         index_part: Box<IndexPart>,
     166            0 :         index_part_generation: Generation,
     167            0 :         ancestor_layers: &mut HashMap<TenantShardTimelineId, HashMap<LayerName, LayerFileMetadata>>,
     168            0 :     ) -> anyhow::Result<()> {
     169            0 :         let index_bytes = serde_json::to_string(&index_part).unwrap();
     170            0 : 
     171            0 :         let layers = index_part
     172            0 :             .layer_metadata
     173            0 :             .into_iter()
     174            0 :             .filter_map(|(layer_name, layer_metadata)| {
     175            0 :                 if layer_metadata.shard.shard_count != ttid.tenant_shard_id.shard_count {
     176              :                     // Accumulate ancestor layers for later download
     177            0 :                     let ancestor_ttid = TenantShardTimelineId::new(
     178            0 :                         TenantShardId {
     179            0 :                             tenant_id: ttid.tenant_shard_id.tenant_id,
     180            0 :                             shard_number: layer_metadata.shard.shard_number,
     181            0 :                             shard_count: layer_metadata.shard.shard_count,
     182            0 :                         },
     183            0 :                         ttid.timeline_id,
     184            0 :                     );
     185            0 :                     let ancestor_ttid_layers = ancestor_layers.entry(ancestor_ttid).or_default();
     186              :                     use std::collections::hash_map::Entry;
     187            0 :                     match ancestor_ttid_layers.entry(layer_name) {
     188            0 :                         Entry::Occupied(entry) => {
     189            0 :                             // Descendent shards that reference a layer from an ancestor should always have matching metadata,
     190            0 :                             // as their siblings, because it is read atomically during a shard split.
     191            0 :                             assert_eq!(entry.get(), &layer_metadata);
     192              :                         }
     193            0 :                         Entry::Vacant(entry) => {
     194            0 :                             entry.insert(layer_metadata);
     195            0 :                         }
     196              :                     }
     197            0 :                     None
     198              :                 } else {
     199            0 :                     Some((layer_name, layer_metadata))
     200              :                 }
     201            0 :             })
     202            0 :             .collect();
     203              : 
     204            0 :         let download_result = self.download_layers(ttid, layers).await;
     205              : 
     206              :         // Write index last, once all the layers it references are downloaded
     207            0 :         let local_index_path = self.output_path.join(format!(
     208            0 :             "{}/timelines/{}/index_part.json{}",
     209            0 :             ttid.tenant_shard_id,
     210            0 :             ttid.timeline_id,
     211            0 :             index_part_generation.get_suffix()
     212            0 :         ));
     213            0 :         tokio::fs::write(&local_index_path, index_bytes)
     214            0 :             .await
     215            0 :             .context("writing index")?;
     216              : 
     217            0 :         download_result
     218            0 :     }
     219              : 
     220            0 :     pub async fn download(&self) -> anyhow::Result<()> {
     221            0 :         let (remote_client, target) =
     222            0 :             init_remote(self.bucket_config.clone(), NodeKind::Pageserver).await?;
     223              : 
     224              :         // Generate a stream of TenantShardId
     225            0 :         let shards = stream_tenant_shards(&remote_client, &target, self.tenant_id).await?;
     226            0 :         let shards: Vec<TenantShardId> = shards.try_collect().await?;
     227              : 
     228              :         // Only read from shards that have the highest count: avoids redundantly downloading
     229              :         // from ancestor shards.
     230            0 :         let Some(shard_count) = shards.iter().map(|s| s.shard_count).max() else {
     231            0 :             anyhow::bail!("No shards found");
     232              :         };
     233              : 
     234              :         // We will build a collection of layers in anccestor shards to download (this will only
     235              :         // happen if this tenant has been split at some point)
     236            0 :         let mut ancestor_layers: HashMap<
     237            0 :             TenantShardTimelineId,
     238            0 :             HashMap<LayerName, LayerFileMetadata>,
     239            0 :         > = Default::default();
     240              : 
     241            0 :         for shard in shards.into_iter().filter(|s| s.shard_count == shard_count) {
     242              :             // Generate a stream of TenantTimelineId
     243            0 :             let timelines = stream_tenant_timelines(&remote_client, &target, shard).await?;
     244              : 
     245              :             // Generate a stream of S3TimelineBlobData
     246            0 :             async fn load_timeline_index(
     247            0 :                 remote_client: &GenericRemoteStorage,
     248            0 :                 target: &RootTarget,
     249            0 :                 ttid: TenantShardTimelineId,
     250            0 :             ) -> anyhow::Result<(TenantShardTimelineId, RemoteTimelineBlobData)> {
     251            0 :                 let data = list_timeline_blobs(remote_client, ttid, target).await?;
     252            0 :                 Ok((ttid, data))
     253            0 :             }
     254            0 :             let timelines =
     255            0 :                 timelines.map_ok(|ttid| load_timeline_index(&remote_client, &target, ttid));
     256            0 :             let mut timelines = std::pin::pin!(timelines.try_buffered(8));
     257              : 
     258            0 :             while let Some(i) = timelines.next().await {
     259            0 :                 let (ttid, data) = i?;
     260            0 :                 match data.blob_data {
     261              :                     BlobDataParseResult::Parsed {
     262            0 :                         index_part,
     263            0 :                         index_part_generation,
     264            0 :                         s3_layers: _,
     265            0 :                     } => {
     266            0 :                         self.download_timeline(
     267            0 :                             ttid,
     268            0 :                             index_part,
     269            0 :                             index_part_generation,
     270            0 :                             &mut ancestor_layers,
     271            0 :                         )
     272            0 :                         .await
     273            0 :                         .context("Downloading timeline")?;
     274              :                     }
     275            0 :                     BlobDataParseResult::Relic => {}
     276              :                     BlobDataParseResult::Incorrect { .. } => {
     277            0 :                         tracing::error!("Bad metadata in timeline {ttid}");
     278              :                     }
     279              :                 };
     280              :             }
     281              :         }
     282              : 
     283            0 :         for (ttid, layers) in ancestor_layers.into_iter() {
     284            0 :             tracing::info!(
     285            0 :                 "Downloading {} layers from ancestor timeline {ttid}...",
     286            0 :                 layers.len()
     287              :             );
     288              : 
     289            0 :             self.download_layers(ttid, layers.into_iter().collect())
     290            0 :                 .await?;
     291              :         }
     292              : 
     293            0 :         Ok(())
     294            0 :     }
     295              : }
        

Generated by: LCOV version 2.1-beta