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