Line data Source code
1 : use std::collections::{BTreeMap, BTreeSet, HashMap};
2 : use std::sync::Arc;
3 : use std::time::Duration;
4 :
5 : use crate::checks::{
6 : list_tenant_manifests, list_timeline_blobs, BlobDataParseResult, ListTenantManifestResult,
7 : RemoteTenantManifestInfo,
8 : };
9 : use crate::metadata_stream::{stream_tenant_timelines, stream_tenants};
10 : use crate::{init_remote, BucketConfig, NodeKind, RootTarget, TenantShardTimelineId, MAX_RETRIES};
11 : use async_stream::try_stream;
12 : use futures::future::Either;
13 : use futures_util::{StreamExt, TryStreamExt};
14 : use pageserver::tenant::remote_timeline_client::index::LayerFileMetadata;
15 : use pageserver::tenant::remote_timeline_client::manifest::OffloadedTimelineManifest;
16 : use pageserver::tenant::remote_timeline_client::{
17 : parse_remote_index_path, parse_remote_tenant_manifest_path, remote_layer_path,
18 : };
19 : use pageserver::tenant::storage_layer::LayerName;
20 : use pageserver::tenant::IndexPart;
21 : use pageserver_api::controller_api::TenantDescribeResponse;
22 : use pageserver_api::shard::{ShardIndex, TenantShardId};
23 : use remote_storage::{GenericRemoteStorage, ListingObject, RemotePath};
24 : use reqwest::Method;
25 : use serde::Serialize;
26 : use storage_controller_client::control_api;
27 : use tokio_util::sync::CancellationToken;
28 : use tracing::{info_span, Instrument};
29 : use utils::backoff;
30 : use utils::generation::Generation;
31 : use utils::id::{TenantId, TenantTimelineId};
32 :
33 : #[derive(Serialize, Default)]
34 : pub struct GcSummary {
35 : indices_deleted: usize,
36 : tenant_manifests_deleted: usize,
37 : remote_storage_errors: usize,
38 : controller_api_errors: usize,
39 : ancestor_layers_deleted: usize,
40 : }
41 :
42 : impl GcSummary {
43 0 : fn merge(&mut self, other: Self) {
44 0 : let Self {
45 0 : indices_deleted,
46 0 : tenant_manifests_deleted,
47 0 : remote_storage_errors,
48 0 : ancestor_layers_deleted,
49 0 : controller_api_errors,
50 0 : } = other;
51 0 :
52 0 : self.indices_deleted += indices_deleted;
53 0 : self.tenant_manifests_deleted += tenant_manifests_deleted;
54 0 : self.remote_storage_errors += remote_storage_errors;
55 0 : self.ancestor_layers_deleted += ancestor_layers_deleted;
56 0 : self.controller_api_errors += controller_api_errors;
57 0 : }
58 : }
59 :
60 : #[derive(clap::ValueEnum, Debug, Clone, Copy)]
61 : pub enum GcMode {
62 : // Delete nothing
63 : DryRun,
64 :
65 : // Enable only removing old-generation indices
66 : IndicesOnly,
67 :
68 : // Enable all forms of GC
69 : Full,
70 : }
71 :
72 : impl std::fmt::Display for GcMode {
73 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 0 : match self {
75 0 : GcMode::DryRun => write!(f, "dry-run"),
76 0 : GcMode::IndicesOnly => write!(f, "indices-only"),
77 0 : GcMode::Full => write!(f, "full"),
78 : }
79 0 : }
80 : }
81 :
82 : mod refs {
83 : use super::*;
84 : // Map of cross-shard layer references, giving a refcount for each layer in each shard that is referenced by some other
85 : // shard in the same tenant. This is sparse! The vast majority of timelines will have no cross-shard refs, and those that
86 : // do have cross shard refs should eventually drop most of them via compaction.
87 : //
88 : // In our inner map type, the TTID in the key is shard-agnostic, and the ShardIndex in the value refers to the _ancestor
89 : // which is is referenced_.
90 : #[derive(Default)]
91 : pub(super) struct AncestorRefs(
92 : BTreeMap<TenantTimelineId, HashMap<(ShardIndex, LayerName), usize>>,
93 : );
94 :
95 : impl AncestorRefs {
96 : /// Insert references for layers discovered in a particular shard-timeline that refer to an ancestral shard-timeline.
97 0 : pub(super) fn update(
98 0 : &mut self,
99 0 : ttid: TenantShardTimelineId,
100 0 : layers: Vec<(LayerName, LayerFileMetadata)>,
101 0 : ) {
102 0 : let ttid_refs = self.0.entry(ttid.as_tenant_timeline_id()).or_default();
103 0 : for (layer_name, layer_metadata) in layers {
104 0 : // Increment refcount of this layer in the ancestor shard
105 0 : *(ttid_refs
106 0 : .entry((layer_metadata.shard, layer_name))
107 0 : .or_default()) += 1;
108 0 : }
109 0 : }
110 :
111 : /// For a particular TTID, return the map of all ancestor layers referenced by a descendent to their refcount
112 : ///
113 : /// The `ShardIndex` in the result's key is the index of the _ancestor_, not the descendent.
114 0 : pub(super) fn get_ttid_refcounts(
115 0 : &self,
116 0 : ttid: &TenantTimelineId,
117 0 : ) -> Option<&HashMap<(ShardIndex, LayerName), usize>> {
118 0 : self.0.get(ttid)
119 0 : }
120 : }
121 : }
122 :
123 : use refs::AncestorRefs;
124 :
125 : // As we see shards for a tenant, acccumulate knowledge needed for cross-shard GC:
126 : // - Are there any ancestor shards?
127 : // - Are there any refs to ancestor shards' layers?
128 : #[derive(Default)]
129 : struct TenantRefAccumulator {
130 : shards_seen: HashMap<TenantId, BTreeSet<ShardIndex>>,
131 :
132 : // For each shard that has refs to an ancestor's layers, the set of ancestor layers referred to
133 : ancestor_ref_shards: AncestorRefs,
134 : }
135 :
136 : impl TenantRefAccumulator {
137 0 : fn update(&mut self, ttid: TenantShardTimelineId, index_part: &IndexPart) {
138 0 : let this_shard_idx = ttid.tenant_shard_id.to_index();
139 0 : (*self
140 0 : .shards_seen
141 0 : .entry(ttid.tenant_shard_id.tenant_id)
142 0 : .or_default())
143 0 : .insert(this_shard_idx);
144 0 :
145 0 : let mut ancestor_refs = Vec::new();
146 0 : for (layer_name, layer_metadata) in &index_part.layer_metadata {
147 0 : if layer_metadata.shard != this_shard_idx {
148 0 : // This is a reference from this shard to a layer in an ancestor shard: we must track this
149 0 : // as a marker to not GC this layer from the parent.
150 0 : ancestor_refs.push((layer_name.clone(), layer_metadata.clone()));
151 0 : }
152 : }
153 :
154 0 : if !ancestor_refs.is_empty() {
155 0 : tracing::info!(%ttid, "Found {} ancestor refs", ancestor_refs.len());
156 0 : self.ancestor_ref_shards.update(ttid, ancestor_refs);
157 0 : }
158 0 : }
159 :
160 : /// Consume Self and return a vector of ancestor tenant shards that should be GC'd, and map of referenced ancestor layers to preserve
161 0 : async fn into_gc_ancestors(
162 0 : self,
163 0 : controller_client: &control_api::Client,
164 0 : summary: &mut GcSummary,
165 0 : ) -> (Vec<TenantShardId>, AncestorRefs) {
166 0 : let mut ancestors_to_gc = Vec::new();
167 0 : for (tenant_id, shard_indices) in self.shards_seen {
168 : // Find the highest shard count
169 0 : let latest_count = shard_indices
170 0 : .iter()
171 0 : .map(|i| i.shard_count)
172 0 : .max()
173 0 : .expect("Always at least one shard");
174 0 :
175 0 : let mut shard_indices = shard_indices.iter().collect::<Vec<_>>();
176 0 : let (mut latest_shards, ancestor_shards) = {
177 0 : let at =
178 0 : itertools::partition(&mut shard_indices, |i| i.shard_count == latest_count);
179 0 : (shard_indices[0..at].to_owned(), &shard_indices[at..])
180 0 : };
181 0 : // Sort shards, as we will later compare them with a sorted list from the controller
182 0 : latest_shards.sort();
183 0 :
184 0 : // Check that we have a complete view of the latest shard count: this should always be the case unless we happened
185 0 : // to scan the S3 bucket halfway through a shard split.
186 0 : if latest_shards.len() != latest_count.count() as usize {
187 : // This should be extremely rare, so we warn on it.
188 0 : tracing::warn!(%tenant_id, "Missed some shards at count {:?}: {latest_shards:?}", latest_count);
189 0 : continue;
190 0 : }
191 0 :
192 0 : // Check if we have any non-latest-count shards
193 0 : if ancestor_shards.is_empty() {
194 0 : tracing::debug!(%tenant_id, "No ancestor shards to clean up");
195 0 : continue;
196 0 : }
197 0 :
198 0 : // Based on S3 view, this tenant looks like it might have some ancestor shard work to do. We
199 0 : // must only do this work if the tenant is not currently being split: otherwise, it is not safe
200 0 : // to GC ancestors, because if the split fails then the controller will try to attach ancestor
201 0 : // shards again.
202 0 : match controller_client
203 0 : .dispatch::<(), TenantDescribeResponse>(
204 0 : Method::GET,
205 0 : format!("control/v1/tenant/{tenant_id}"),
206 0 : None,
207 0 : )
208 0 : .await
209 : {
210 0 : Err(e) => {
211 0 : // We were not able to learn the latest shard split state from the controller, so we will not
212 0 : // do ancestor GC on this tenant.
213 0 : tracing::warn!(%tenant_id, "Failed to query storage controller, will not do ancestor GC: {e}");
214 0 : summary.controller_api_errors += 1;
215 0 : continue;
216 : }
217 0 : Ok(desc) => {
218 0 : // We expect to see that the latest shard count matches the one we saw in S3, and that none
219 0 : // of the shards indicate splitting in progress.
220 0 :
221 0 : let controller_indices: Vec<ShardIndex> = desc
222 0 : .shards
223 0 : .iter()
224 0 : .map(|s| s.tenant_shard_id.to_index())
225 0 : .collect();
226 0 : if !controller_indices.iter().eq(latest_shards.iter().copied()) {
227 0 : tracing::info!(%tenant_id, "Latest shards seen in S3 ({latest_shards:?}) don't match controller state ({controller_indices:?})");
228 0 : continue;
229 0 : }
230 0 :
231 0 : if desc.shards.iter().any(|s| s.is_splitting) {
232 0 : tracing::info!(%tenant_id, "One or more shards is currently splitting");
233 0 : continue;
234 0 : }
235 0 :
236 0 : // This shouldn't be too noisy, because we only log this for tenants that have some ancestral refs.
237 0 : tracing::info!(%tenant_id, "Validated state with controller: {desc:?}");
238 : }
239 : }
240 :
241 : // GC ancestor shards
242 0 : for ancestor_shard in ancestor_shards.iter().map(|idx| TenantShardId {
243 0 : tenant_id,
244 0 : shard_count: idx.shard_count,
245 0 : shard_number: idx.shard_number,
246 0 : }) {
247 0 : ancestors_to_gc.push(ancestor_shard);
248 0 : }
249 : }
250 :
251 0 : (ancestors_to_gc, self.ancestor_ref_shards)
252 0 : }
253 : }
254 :
255 0 : fn is_old_enough(min_age: &Duration, key: &ListingObject, summary: &mut GcSummary) -> bool {
256 : // Validation: we will only GC indices & layers after a time threshold (e.g. one week) so that during an incident
257 : // it is easier to read old data for analysis, and easier to roll back shard splits without having to un-delete any objects.
258 0 : let age = match key.last_modified.elapsed() {
259 0 : Ok(e) => e,
260 : Err(_) => {
261 0 : tracing::warn!("Bad last_modified time: {:?}", key.last_modified);
262 0 : summary.remote_storage_errors += 1;
263 0 : return false;
264 : }
265 : };
266 0 : let old_enough = &age > min_age;
267 0 :
268 0 : if !old_enough {
269 0 : tracing::info!(
270 0 : "Skipping young object {} < {}",
271 0 : humantime::format_duration(age),
272 0 : humantime::format_duration(*min_age)
273 : );
274 0 : }
275 :
276 0 : old_enough
277 0 : }
278 :
279 : /// Same as [`is_old_enough`], but doesn't require a [`ListingObject`] passed to it.
280 0 : async fn check_is_old_enough(
281 0 : remote_client: &GenericRemoteStorage,
282 0 : key: &RemotePath,
283 0 : min_age: &Duration,
284 0 : summary: &mut GcSummary,
285 0 : ) -> Option<bool> {
286 0 : let listing_object = remote_client
287 0 : .head_object(key, &CancellationToken::new())
288 0 : .await
289 0 : .ok()?;
290 0 : Some(is_old_enough(min_age, &listing_object, summary))
291 0 : }
292 :
293 0 : async fn maybe_delete_index(
294 0 : remote_client: &GenericRemoteStorage,
295 0 : min_age: &Duration,
296 0 : latest_gen: Generation,
297 0 : obj: &ListingObject,
298 0 : mode: GcMode,
299 0 : summary: &mut GcSummary,
300 0 : ) {
301 0 : // Validation: we will only delete things that parse cleanly
302 0 : let basename = obj.key.get_path().file_name().unwrap();
303 0 : let candidate_generation =
304 0 : match parse_remote_index_path(RemotePath::from_string(basename).unwrap()) {
305 0 : Some(g) => g,
306 : None => {
307 0 : if basename == IndexPart::FILE_NAME {
308 : // A legacy pre-generation index
309 0 : Generation::none()
310 : } else {
311 : // A strange key: we will not delete this because we don't understand it.
312 0 : tracing::warn!("Bad index key");
313 0 : return;
314 : }
315 : }
316 : };
317 :
318 : // Validation: we will only delete indices more than one generation old, to avoid interfering
319 : // in typical migrations, even if they are very long running.
320 0 : if candidate_generation >= latest_gen {
321 : // This shouldn't happen: when we loaded metadata, it should have selected the latest
322 : // generation already, and only populated [`S3TimelineBlobData::unused_index_keys`]
323 : // with older generations.
324 0 : tracing::warn!("Deletion candidate is >= latest generation, this is a bug!");
325 0 : return;
326 0 : } else if candidate_generation.next() == latest_gen {
327 : // Skip deleting the latest-1th generation's index.
328 0 : return;
329 0 : }
330 0 :
331 0 : if !is_old_enough(min_age, obj, summary) {
332 0 : return;
333 0 : }
334 :
335 0 : if matches!(mode, GcMode::DryRun) {
336 0 : tracing::info!("Dry run: would delete this key");
337 0 : return;
338 0 : }
339 0 :
340 0 : // All validations passed: erase the object
341 0 : let cancel = CancellationToken::new();
342 0 : match backoff::retry(
343 0 : || remote_client.delete(&obj.key, &cancel),
344 0 : |_| false,
345 0 : 3,
346 0 : MAX_RETRIES as u32,
347 0 : "maybe_delete_index",
348 0 : &cancel,
349 0 : )
350 0 : .await
351 : {
352 : None => {
353 0 : unreachable!("Using a dummy cancellation token");
354 : }
355 : Some(Ok(_)) => {
356 0 : tracing::info!("Successfully deleted index");
357 0 : summary.indices_deleted += 1;
358 : }
359 0 : Some(Err(e)) => {
360 0 : tracing::warn!("Failed to delete index: {e}");
361 0 : summary.remote_storage_errors += 1;
362 : }
363 : }
364 0 : }
365 :
366 0 : async fn maybe_delete_tenant_manifest(
367 0 : remote_client: &GenericRemoteStorage,
368 0 : min_age: &Duration,
369 0 : latest_gen: Generation,
370 0 : obj: &ListingObject,
371 0 : mode: GcMode,
372 0 : summary: &mut GcSummary,
373 0 : ) {
374 0 : // Validation: we will only delete things that parse cleanly
375 0 : let basename = obj.key.get_path().file_name().unwrap();
376 0 : let Some(candidate_generation) =
377 0 : parse_remote_tenant_manifest_path(RemotePath::from_string(basename).unwrap())
378 : else {
379 : // A strange key: we will not delete this because we don't understand it.
380 0 : tracing::warn!("Bad index key");
381 0 : return;
382 : };
383 :
384 : // Validation: we will only delete manifests more than one generation old, and in fact we
385 : // should never be called with such recent generations.
386 0 : if candidate_generation >= latest_gen {
387 0 : tracing::warn!("Deletion candidate is >= latest generation, this is a bug!");
388 0 : return;
389 0 : } else if candidate_generation.next() == latest_gen {
390 0 : tracing::warn!("Deletion candidate is >= latest generation - 1, this is a bug!");
391 0 : return;
392 0 : }
393 0 :
394 0 : if !is_old_enough(min_age, obj, summary) {
395 0 : return;
396 0 : }
397 :
398 0 : if matches!(mode, GcMode::DryRun) {
399 0 : tracing::info!("Dry run: would delete this key");
400 0 : return;
401 0 : }
402 0 :
403 0 : // All validations passed: erase the object
404 0 : let cancel = CancellationToken::new();
405 0 : match backoff::retry(
406 0 : || remote_client.delete(&obj.key, &cancel),
407 0 : |_| false,
408 0 : 3,
409 0 : MAX_RETRIES as u32,
410 0 : "maybe_delete_tenant_manifest",
411 0 : &cancel,
412 0 : )
413 0 : .await
414 : {
415 : None => {
416 0 : unreachable!("Using a dummy cancellation token");
417 : }
418 : Some(Ok(_)) => {
419 0 : tracing::info!("Successfully deleted tenant manifest");
420 0 : summary.tenant_manifests_deleted += 1;
421 : }
422 0 : Some(Err(e)) => {
423 0 : tracing::warn!("Failed to delete tenant manifest: {e}");
424 0 : summary.remote_storage_errors += 1;
425 : }
426 : }
427 0 : }
428 :
429 : #[allow(clippy::too_many_arguments)]
430 0 : async fn gc_ancestor(
431 0 : remote_client: &GenericRemoteStorage,
432 0 : root_target: &RootTarget,
433 0 : min_age: &Duration,
434 0 : ancestor: TenantShardId,
435 0 : refs: &AncestorRefs,
436 0 : mode: GcMode,
437 0 : summary: &mut GcSummary,
438 0 : ) -> anyhow::Result<()> {
439 : // Scan timelines in the ancestor
440 0 : let timelines = stream_tenant_timelines(remote_client, root_target, ancestor).await?;
441 0 : let mut timelines = std::pin::pin!(timelines);
442 :
443 : // Build a list of keys to retain
444 :
445 0 : while let Some(ttid) = timelines.next().await {
446 0 : let ttid = ttid?;
447 :
448 0 : let data = list_timeline_blobs(remote_client, ttid, root_target).await?;
449 :
450 0 : let s3_layers = match data.blob_data {
451 : BlobDataParseResult::Parsed {
452 : index_part: _,
453 : index_part_generation: _,
454 0 : s3_layers,
455 0 : index_part_last_modified_time: _,
456 0 : index_part_snapshot_time: _,
457 0 : } => s3_layers,
458 : BlobDataParseResult::Relic => {
459 : // Post-deletion tenant location: don't try and GC it.
460 0 : continue;
461 : }
462 : BlobDataParseResult::Incorrect {
463 0 : errors,
464 0 : s3_layers: _, // TODO(yuchen): could still check references to these s3 layers?
465 0 : } => {
466 0 : // Our primary purpose isn't to report on bad data, but log this rather than skipping silently
467 0 : tracing::warn!(
468 0 : "Skipping ancestor GC for timeline {ttid}, bad metadata: {errors:?}"
469 : );
470 0 : continue;
471 : }
472 : };
473 :
474 0 : let ttid_refs = refs.get_ttid_refcounts(&ttid.as_tenant_timeline_id());
475 0 : let ancestor_shard_index = ttid.tenant_shard_id.to_index();
476 :
477 0 : for (layer_name, layer_gen) in s3_layers {
478 0 : let ref_count = ttid_refs
479 0 : .and_then(|m| m.get(&(ancestor_shard_index, layer_name.clone())))
480 0 : .copied()
481 0 : .unwrap_or(0);
482 0 :
483 0 : if ref_count > 0 {
484 0 : tracing::debug!(%ttid, "Ancestor layer {layer_name} has {ref_count} refs");
485 0 : continue;
486 0 : }
487 0 :
488 0 : tracing::info!(%ttid, "Ancestor layer {layer_name} is not referenced");
489 :
490 : // Build the key for the layer we are considering deleting
491 0 : let key = root_target.absolute_key(&remote_layer_path(
492 0 : &ttid.tenant_shard_id.tenant_id,
493 0 : &ttid.timeline_id,
494 0 : ancestor_shard_index,
495 0 : &layer_name,
496 0 : layer_gen,
497 0 : ));
498 0 :
499 0 : // We apply a time threshold to GCing objects that are un-referenced: this preserves our ability
500 0 : // to roll back a shard split if we have to, by avoiding deleting ancestor layers right away
501 0 : let path = RemotePath::from_string(key.strip_prefix("/").unwrap_or(&key)).unwrap();
502 0 : if check_is_old_enough(remote_client, &path, min_age, summary).await != Some(true) {
503 0 : continue;
504 0 : }
505 :
506 0 : if !matches!(mode, GcMode::Full) {
507 0 : tracing::info!("Dry run: would delete key {key}");
508 0 : continue;
509 0 : }
510 0 :
511 0 : // All validations passed: erase the object
512 0 : match remote_client.delete(&path, &CancellationToken::new()).await {
513 : Ok(_) => {
514 0 : tracing::info!("Successfully deleted unreferenced ancestor layer {key}");
515 0 : summary.ancestor_layers_deleted += 1;
516 : }
517 0 : Err(e) => {
518 0 : tracing::warn!("Failed to delete layer {key}: {e}");
519 0 : summary.remote_storage_errors += 1;
520 : }
521 : }
522 : }
523 :
524 : // TODO: if all the layers are gone, clean up the whole timeline dir (remove index)
525 : }
526 :
527 0 : Ok(())
528 0 : }
529 :
530 0 : async fn gc_tenant_manifests(
531 0 : remote_client: &GenericRemoteStorage,
532 0 : min_age: Duration,
533 0 : target: &RootTarget,
534 0 : mode: GcMode,
535 0 : tenant_shard_id: TenantShardId,
536 0 : ) -> anyhow::Result<(GcSummary, Option<RemoteTenantManifestInfo>)> {
537 0 : let mut gc_summary = GcSummary::default();
538 0 : match list_tenant_manifests(remote_client, tenant_shard_id, target).await? {
539 : ListTenantManifestResult::WithErrors {
540 0 : errors,
541 : unknown_keys: _,
542 : } => {
543 0 : for (_key, error) in errors {
544 0 : tracing::warn!(%tenant_shard_id, "list_tenant_manifests: {error}");
545 : }
546 0 : Ok((gc_summary, None))
547 : }
548 : ListTenantManifestResult::NoErrors {
549 0 : latest_generation,
550 0 : mut manifests,
551 : } => {
552 0 : let Some(latest_generation) = latest_generation else {
553 0 : return Ok((gc_summary, None));
554 : };
555 0 : manifests.sort_by_key(|(generation, _obj)| *generation);
556 0 : // skip the two latest generations (they don't neccessarily have to be 1 apart from each other)
557 0 : let candidates = manifests.iter().rev().skip(2);
558 0 : for (_generation, key) in candidates {
559 0 : maybe_delete_tenant_manifest(
560 0 : remote_client,
561 0 : &min_age,
562 0 : latest_generation.generation,
563 0 : key,
564 0 : mode,
565 0 : &mut gc_summary,
566 0 : )
567 0 : .instrument(
568 0 : info_span!("maybe_delete_tenant_manifest", %tenant_shard_id, ?latest_generation.generation, %key.key),
569 : )
570 0 : .await;
571 : }
572 0 : Ok((gc_summary, Some(latest_generation)))
573 : }
574 : }
575 0 : }
576 :
577 0 : async fn gc_timeline(
578 0 : remote_client: &GenericRemoteStorage,
579 0 : min_age: &Duration,
580 0 : target: &RootTarget,
581 0 : mode: GcMode,
582 0 : ttid: TenantShardTimelineId,
583 0 : accumulator: &std::sync::Mutex<TenantRefAccumulator>,
584 0 : tenant_manifest_info: Arc<Option<RemoteTenantManifestInfo>>,
585 0 : ) -> anyhow::Result<GcSummary> {
586 0 : let mut summary = GcSummary::default();
587 0 : let data = list_timeline_blobs(remote_client, ttid, target).await?;
588 :
589 0 : let (index_part, latest_gen, candidates) = match &data.blob_data {
590 : BlobDataParseResult::Parsed {
591 0 : index_part,
592 0 : index_part_generation,
593 0 : s3_layers: _,
594 0 : index_part_last_modified_time: _,
595 0 : index_part_snapshot_time: _,
596 0 : } => (index_part, *index_part_generation, data.unused_index_keys),
597 : BlobDataParseResult::Relic => {
598 : // Post-deletion tenant location: don't try and GC it.
599 0 : return Ok(summary);
600 : }
601 : BlobDataParseResult::Incorrect {
602 0 : errors,
603 0 : s3_layers: _,
604 0 : } => {
605 0 : // Our primary purpose isn't to report on bad data, but log this rather than skipping silently
606 0 : tracing::warn!("Skipping timeline {ttid}, bad metadata: {errors:?}");
607 0 : return Ok(summary);
608 : }
609 : };
610 :
611 0 : if let Some(tenant_manifest_info) = &*tenant_manifest_info {
612 : // TODO: this is O(n^2) in the number of offloaded timelines. Do a hashmap lookup instead.
613 0 : let maybe_offloaded = tenant_manifest_info
614 0 : .manifest
615 0 : .offloaded_timelines
616 0 : .iter()
617 0 : .find(|offloaded_timeline| offloaded_timeline.timeline_id == ttid.timeline_id);
618 0 : if let Some(offloaded) = maybe_offloaded {
619 0 : let warnings = validate_index_part_with_offloaded(index_part, offloaded);
620 0 : let warn = if warnings.is_empty() {
621 0 : false
622 : } else {
623 : // Verify that the manifest hasn't changed. If it has, a potential racing change could have been cause for our troubles.
624 0 : match list_tenant_manifests(remote_client, ttid.tenant_shard_id, target).await? {
625 : ListTenantManifestResult::WithErrors {
626 0 : errors,
627 : unknown_keys: _,
628 : } => {
629 0 : for (_key, error) in errors {
630 0 : tracing::warn!(%ttid, "list_tenant_manifests in gc_timeline: {error}");
631 : }
632 0 : true
633 : }
634 : ListTenantManifestResult::NoErrors {
635 0 : latest_generation,
636 : manifests: _,
637 : } => {
638 0 : if let Some(new_latest_gen) = latest_generation {
639 0 : let manifest_changed = (
640 0 : new_latest_gen.generation,
641 0 : new_latest_gen.listing_object.last_modified,
642 0 : ) == (
643 0 : tenant_manifest_info.generation,
644 0 : tenant_manifest_info.listing_object.last_modified,
645 0 : );
646 0 : if manifest_changed {
647 0 : tracing::debug!(%ttid, "tenant manifest changed since it was loaded, suppressing {} warnings", warnings.len());
648 0 : }
649 0 : manifest_changed
650 : } else {
651 : // The latest generation is gone. This timeline is in the progress of being deleted?
652 0 : false
653 : }
654 : }
655 : }
656 : };
657 0 : if warn {
658 0 : for warning in warnings {
659 0 : tracing::warn!(%ttid, "{}", warning);
660 : }
661 0 : }
662 0 : }
663 0 : }
664 :
665 0 : accumulator.lock().unwrap().update(ttid, index_part);
666 :
667 0 : for key in candidates {
668 0 : maybe_delete_index(remote_client, min_age, latest_gen, &key, mode, &mut summary)
669 0 : .instrument(info_span!("maybe_delete_index", %ttid, ?latest_gen, %key.key))
670 0 : .await;
671 : }
672 :
673 0 : Ok(summary)
674 0 : }
675 :
676 0 : fn validate_index_part_with_offloaded(
677 0 : index_part: &IndexPart,
678 0 : offloaded: &OffloadedTimelineManifest,
679 0 : ) -> Vec<String> {
680 0 : let mut warnings = Vec::new();
681 0 : if let Some(archived_at_index_part) = index_part.archived_at {
682 0 : if archived_at_index_part
683 0 : .signed_duration_since(offloaded.archived_at)
684 0 : .num_seconds()
685 0 : != 0
686 0 : {
687 0 : warnings.push(format!(
688 0 : "index-part archived_at={} differs from manifest archived_at={}",
689 0 : archived_at_index_part, offloaded.archived_at
690 0 : ));
691 0 : }
692 0 : } else {
693 0 : warnings.push("Timeline offloaded in manifest but not archived in index-part".to_string());
694 0 : }
695 0 : if index_part.metadata.ancestor_timeline() != offloaded.ancestor_timeline_id {
696 0 : warnings.push(format!(
697 0 : "index-part anestor={:?} differs from manifest ancestor={:?}",
698 0 : index_part.metadata.ancestor_timeline(),
699 0 : offloaded.ancestor_timeline_id
700 0 : ));
701 0 : }
702 0 : warnings
703 0 : }
704 :
705 : /// Physical garbage collection: removing unused S3 objects.
706 : ///
707 : /// This is distinct from the garbage collection done inside the pageserver, which operates at a higher level
708 : /// (keys, layers). This type of garbage collection is about removing:
709 : /// - Objects that were uploaded but never referenced in the remote index (e.g. because of a shutdown between
710 : /// uploading a layer and uploading an index)
711 : /// - Index objects and tenant manifests from historic generations
712 : ///
713 : /// This type of GC is not necessary for correctness: rather it serves to reduce wasted storage capacity, and
714 : /// make sure that object listings don't get slowed down by large numbers of garbage objects.
715 0 : pub async fn pageserver_physical_gc(
716 0 : bucket_config: &BucketConfig,
717 0 : controller_client: Option<&control_api::Client>,
718 0 : tenant_shard_ids: Vec<TenantShardId>,
719 0 : min_age: Duration,
720 0 : mode: GcMode,
721 0 : ) -> anyhow::Result<GcSummary> {
722 0 : let (remote_client, target) = init_remote(bucket_config.clone(), NodeKind::Pageserver).await?;
723 :
724 0 : let remote_client = Arc::new(remote_client);
725 0 : let tenants = if tenant_shard_ids.is_empty() {
726 0 : Either::Left(stream_tenants(&remote_client, &target))
727 : } else {
728 0 : Either::Right(futures::stream::iter(tenant_shard_ids.into_iter().map(Ok)))
729 : };
730 :
731 : // How many tenants to process in parallel. We need to be mindful of pageservers
732 : // accessing the same per tenant prefixes, so use a lower setting than pageservers.
733 : const CONCURRENCY: usize = 32;
734 :
735 : // Accumulate information about each tenant for cross-shard GC step we'll do at the end
736 0 : let accumulator = std::sync::Mutex::new(TenantRefAccumulator::default());
737 0 :
738 0 : // Accumulate information about how many manifests we have GCd
739 0 : let manifest_gc_summary = std::sync::Mutex::new(GcSummary::default());
740 0 :
741 0 : // Generate a stream of TenantTimelineId
742 0 : let timelines = tenants.map_ok(|tenant_shard_id| {
743 0 : let target_ref = ⌖
744 0 : let remote_client_ref = &remote_client;
745 0 : let manifest_gc_summary_ref = &manifest_gc_summary;
746 0 : async move {
747 0 : let gc_manifest_result = gc_tenant_manifests(
748 0 : remote_client_ref,
749 0 : min_age,
750 0 : target_ref,
751 0 : mode,
752 0 : tenant_shard_id,
753 0 : )
754 0 : .await;
755 0 : let (summary_from_manifest, tenant_manifest_opt) = match gc_manifest_result {
756 0 : Ok((gc_summary, tenant_manifest)) => (gc_summary, tenant_manifest),
757 0 : Err(e) => {
758 0 : tracing::warn!(%tenant_shard_id, "Error in gc_tenant_manifests: {e}");
759 0 : (GcSummary::default(), None)
760 : }
761 : };
762 0 : manifest_gc_summary_ref
763 0 : .lock()
764 0 : .unwrap()
765 0 : .merge(summary_from_manifest);
766 0 : let tenant_manifest_arc = Arc::new(tenant_manifest_opt);
767 0 : let mut timelines = Box::pin(
768 0 : stream_tenant_timelines(remote_client_ref, target_ref, tenant_shard_id).await?,
769 : );
770 0 : Ok(try_stream! {
771 0 : while let Some(ttid_res) = timelines.next().await {
772 0 : let ttid = ttid_res?;
773 0 : yield (ttid, tenant_manifest_arc.clone());
774 0 : }
775 0 : })
776 0 : }
777 0 : });
778 0 :
779 0 : let mut summary = GcSummary::default();
780 0 : {
781 0 : let timelines = std::pin::pin!(timelines.try_buffered(CONCURRENCY));
782 0 : let timelines = timelines.try_flatten();
783 0 :
784 0 : let timelines = timelines.map_ok(|(ttid, tenant_manifest_arc)| {
785 0 : gc_timeline(
786 0 : &remote_client,
787 0 : &min_age,
788 0 : &target,
789 0 : mode,
790 0 : ttid,
791 0 : &accumulator,
792 0 : tenant_manifest_arc,
793 0 : )
794 0 : });
795 0 : let mut timelines = std::pin::pin!(timelines.try_buffered(CONCURRENCY));
796 :
797 : // Drain futures for per-shard GC, populating accumulator as a side effect
798 0 : while let Some(i) = timelines.next().await {
799 0 : summary.merge(i?);
800 : }
801 : }
802 : // Streams are lazily evaluated, so only now do we have access to the inner object
803 0 : summary.merge(manifest_gc_summary.into_inner().unwrap());
804 :
805 : // Execute cross-shard GC, using the accumulator's full view of all the shards built in the per-shard GC
806 0 : let Some(client) = controller_client else {
807 0 : tracing::info!("Skipping ancestor layer GC, because no `--controller-api` was specified");
808 0 : return Ok(summary);
809 : };
810 :
811 0 : let (ancestor_shards, ancestor_refs) = accumulator
812 0 : .into_inner()
813 0 : .unwrap()
814 0 : .into_gc_ancestors(client, &mut summary)
815 0 : .await;
816 :
817 0 : for ancestor_shard in ancestor_shards {
818 0 : gc_ancestor(
819 0 : &remote_client,
820 0 : &target,
821 0 : &min_age,
822 0 : ancestor_shard,
823 0 : &ancestor_refs,
824 0 : mode,
825 0 : &mut summary,
826 0 : )
827 0 : .instrument(info_span!("gc_ancestor", %ancestor_shard))
828 0 : .await?;
829 : }
830 :
831 0 : Ok(summary)
832 0 : }
|