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