Line data Source code
1 : use std::collections::HashMap;
2 :
3 : use anyhow::Context;
4 : use async_stream::stream;
5 : use camino::Utf8PathBuf;
6 : use futures::{StreamExt, TryStreamExt};
7 : use pageserver::tenant::IndexPart;
8 : use pageserver::tenant::remote_timeline_client::index::LayerFileMetadata;
9 : use pageserver::tenant::remote_timeline_client::remote_layer_path;
10 : use pageserver::tenant::storage_layer::LayerName;
11 : use pageserver_api::shard::TenantShardId;
12 : use remote_storage::GenericRemoteStorage;
13 : use tokio_util::sync::CancellationToken;
14 : use utils::generation::Generation;
15 : use utils::id::TenantId;
16 :
17 : use crate::checks::{BlobDataParseResult, RemoteTimelineBlobData, list_timeline_blobs};
18 : use crate::metadata_stream::{stream_tenant_shards, stream_tenant_timelines};
19 : use crate::{
20 : BucketConfig, NodeKind, RootTarget, TenantShardTimelineId, download_object_to_file, init_remote,
21 : };
22 :
23 : pub struct SnapshotDownloader {
24 : remote_client: GenericRemoteStorage,
25 : #[allow(dead_code)]
26 : target: RootTarget,
27 : bucket_config: BucketConfig,
28 : tenant_id: TenantId,
29 : output_path: Utf8PathBuf,
30 : concurrency: usize,
31 : }
32 :
33 : impl SnapshotDownloader {
34 0 : pub async fn new(
35 0 : bucket_config: BucketConfig,
36 0 : tenant_id: TenantId,
37 0 : output_path: Utf8PathBuf,
38 0 : concurrency: usize,
39 0 : ) -> anyhow::Result<Self> {
40 0 : let (remote_client, target) =
41 0 : init_remote(bucket_config.clone(), NodeKind::Pageserver).await?;
42 :
43 0 : Ok(Self {
44 0 : remote_client,
45 0 : target,
46 0 : bucket_config,
47 0 : tenant_id,
48 0 : output_path,
49 0 : concurrency,
50 0 : })
51 0 : }
52 :
53 0 : async fn download_layer(
54 0 : &self,
55 0 : ttid: TenantShardTimelineId,
56 0 : layer_name: LayerName,
57 0 : layer_metadata: LayerFileMetadata,
58 0 : ) -> anyhow::Result<(LayerName, LayerFileMetadata)> {
59 0 : let cancel = CancellationToken::new();
60 0 : // Note this is local as in a local copy of S3 data, not local as in the pageserver's local format. They use
61 0 : // different layer names (remote-style has the generation suffix)
62 0 : let local_path = self.output_path.join(format!(
63 0 : "{}/timelines/{}/{}{}",
64 0 : ttid.tenant_shard_id,
65 0 : ttid.timeline_id,
66 0 : layer_name,
67 0 : layer_metadata.generation.get_suffix()
68 0 : ));
69 0 :
70 0 : // We should only be called for layers that are owned by the input TTID
71 0 : assert_eq!(layer_metadata.shard, ttid.tenant_shard_id.to_index());
72 :
73 : // Assumption: we always write layer files atomically, and layer files are immutable. Therefore if the file
74 : // already exists on local disk, we assume it is fully correct and skip it.
75 0 : if tokio::fs::try_exists(&local_path).await? {
76 0 : tracing::debug!("{} already exists", local_path);
77 0 : return Ok((layer_name, layer_metadata));
78 : } else {
79 0 : tracing::debug!("{} requires download...", local_path);
80 :
81 0 : let remote_path = remote_layer_path(
82 0 : &ttid.tenant_shard_id.tenant_id,
83 0 : &ttid.timeline_id,
84 0 : layer_metadata.shard,
85 0 : &layer_name,
86 0 : layer_metadata.generation,
87 0 : );
88 0 : let mode = remote_storage::ListingMode::NoDelimiter;
89 :
90 : // List versions: the object might be deleted.
91 0 : let versions = self
92 0 : .remote_client
93 0 : .list_versions(Some(&remote_path), mode, None, &cancel)
94 0 : .await?;
95 0 : let Some(version) = versions.versions.first() else {
96 0 : return Err(anyhow::anyhow!("No versions found for {remote_path}"));
97 : };
98 0 : download_object_to_file(
99 0 : &self.remote_client,
100 0 : &remote_path,
101 0 : version.version_id().cloned(),
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 : index_part_last_modified_time: _,
266 0 : index_part_snapshot_time: _,
267 0 : } => {
268 0 : self.download_timeline(
269 0 : ttid,
270 0 : index_part,
271 0 : index_part_generation,
272 0 : &mut ancestor_layers,
273 0 : )
274 0 : .await
275 0 : .context("Downloading timeline")?;
276 : }
277 0 : BlobDataParseResult::Relic => {}
278 : BlobDataParseResult::Incorrect { .. } => {
279 0 : tracing::error!("Bad metadata in timeline {ttid}");
280 : }
281 : };
282 : }
283 : }
284 :
285 0 : for (ttid, layers) in ancestor_layers.into_iter() {
286 0 : tracing::info!(
287 0 : "Downloading {} layers from ancestor timeline {ttid}...",
288 0 : layers.len()
289 : );
290 :
291 0 : self.download_layers(ttid, layers.into_iter().collect())
292 0 : .await?;
293 : }
294 :
295 0 : Ok(())
296 0 : }
297 : }
|