LCOV - code coverage report
Current view: top level - storage_scrubber/src - garbage.rs (source / functions) Coverage Total Hit
Test: 09e7485004805bd42b53a0c369170b3228136512.info Lines: 0.0 % 425 0
Test Date: 2024-11-21 18:36:18 Functions: 0.0 % 88 0

            Line data    Source code
       1              : //! Functionality for finding and purging garbage, as in "garbage collection".
       2              : //!
       3              : //! Garbage means S3 objects which are either not referenced by any metadata,
       4              : //! or are referenced by a control plane tenant/timeline in a deleted state.
       5              : 
       6              : use std::{
       7              :     collections::{HashMap, HashSet},
       8              :     sync::Arc,
       9              :     time::Duration,
      10              : };
      11              : 
      12              : use anyhow::Context;
      13              : use futures_util::TryStreamExt;
      14              : use pageserver_api::shard::TenantShardId;
      15              : use remote_storage::{GenericRemoteStorage, ListingMode, ListingObject, RemotePath};
      16              : use serde::{Deserialize, Serialize};
      17              : use tokio_stream::StreamExt;
      18              : use tokio_util::sync::CancellationToken;
      19              : use utils::{backoff, id::TenantId};
      20              : 
      21              : use crate::{
      22              :     cloud_admin_api::{CloudAdminApiClient, MaybeDeleted, ProjectData},
      23              :     init_remote, list_objects_with_retries,
      24              :     metadata_stream::{stream_tenant_timelines, stream_tenants_maybe_prefix},
      25              :     BucketConfig, ConsoleConfig, NodeKind, TenantShardTimelineId, TraversingDepth, MAX_RETRIES,
      26              : };
      27              : 
      28            0 : #[derive(Serialize, Deserialize, Debug)]
      29              : enum GarbageReason {
      30              :     DeletedInConsole,
      31              :     MissingInConsole,
      32              : 
      33              :     // The remaining data relates to a known deletion issue, and we're sure that purging this
      34              :     // will not delete any real data, for example https://github.com/neondatabase/neon/pull/7928 where
      35              :     // there is nothing in a tenant path apart from a heatmap file.
      36              :     KnownBug,
      37              : }
      38              : 
      39            0 : #[derive(Serialize, Deserialize, Debug)]
      40              : enum GarbageEntity {
      41              :     Tenant(TenantShardId),
      42              :     Timeline(TenantShardTimelineId),
      43              : }
      44              : 
      45            0 : #[derive(Serialize, Deserialize, Debug)]
      46              : struct GarbageItem {
      47              :     entity: GarbageEntity,
      48              :     reason: GarbageReason,
      49              : }
      50              : 
      51            0 : #[derive(Serialize, Deserialize, Debug)]
      52              : pub struct GarbageList {
      53              :     /// Remember what NodeKind we were finding garbage for, so that we can
      54              :     /// purge the list without re-stating it.
      55              :     node_kind: NodeKind,
      56              : 
      57              :     /// Embed the identity of the bucket, so that we do not risk executing
      58              :     /// the wrong list against the wrong bucket, and so that the user does not have
      59              :     /// to re-state the bucket details when purging.
      60              :     bucket_config: BucketConfig,
      61              : 
      62              :     items: Vec<GarbageItem>,
      63              : 
      64              :     /// Advisory information to enable consumers to do a validation that if we
      65              :     /// see garbage, we saw some active tenants too.  This protects against classes of bugs
      66              :     /// in the scrubber that might otherwise generate a "deleted all" result.
      67              :     active_tenant_count: usize,
      68              :     active_timeline_count: usize,
      69              : }
      70              : 
      71              : impl GarbageList {
      72            0 :     fn new(node_kind: NodeKind, bucket_config: BucketConfig) -> Self {
      73            0 :         Self {
      74            0 :             items: Vec::new(),
      75            0 :             active_tenant_count: 0,
      76            0 :             active_timeline_count: 0,
      77            0 :             node_kind,
      78            0 :             bucket_config,
      79            0 :         }
      80            0 :     }
      81              : 
      82              :     /// If an entity has been identified as requiring purge due to a known bug, e.g.
      83              :     /// a particular type of object left behind after an incomplete deletion.
      84            0 :     fn append_buggy(&mut self, entity: GarbageEntity) {
      85            0 :         self.items.push(GarbageItem {
      86            0 :             entity,
      87            0 :             reason: GarbageReason::KnownBug,
      88            0 :         });
      89            0 :     }
      90              : 
      91              :     /// Return true if appended, false if not.  False means the result was not garbage.
      92            0 :     fn maybe_append<T>(&mut self, entity: GarbageEntity, result: Option<T>) -> bool
      93            0 :     where
      94            0 :         T: MaybeDeleted,
      95            0 :     {
      96            0 :         match result {
      97            0 :             Some(result_item) if result_item.is_deleted() => {
      98            0 :                 self.items.push(GarbageItem {
      99            0 :                     entity,
     100            0 :                     reason: GarbageReason::DeletedInConsole,
     101            0 :                 });
     102            0 :                 true
     103              :             }
     104            0 :             Some(_) => false,
     105              :             None => {
     106            0 :                 self.items.push(GarbageItem {
     107            0 :                     entity,
     108            0 :                     reason: GarbageReason::MissingInConsole,
     109            0 :                 });
     110            0 :                 true
     111              :             }
     112              :         }
     113            0 :     }
     114              : }
     115              : 
     116            0 : pub async fn find_garbage(
     117            0 :     bucket_config: BucketConfig,
     118            0 :     console_config: ConsoleConfig,
     119            0 :     depth: TraversingDepth,
     120            0 :     node_kind: NodeKind,
     121            0 :     tenant_id_prefix: Option<String>,
     122            0 :     output_path: String,
     123            0 : ) -> anyhow::Result<()> {
     124            0 :     let garbage = find_garbage_inner(
     125            0 :         bucket_config,
     126            0 :         console_config,
     127            0 :         depth,
     128            0 :         node_kind,
     129            0 :         tenant_id_prefix,
     130            0 :     )
     131            0 :     .await?;
     132            0 :     let serialized = serde_json::to_vec_pretty(&garbage)?;
     133              : 
     134            0 :     tokio::fs::write(&output_path, &serialized).await?;
     135              : 
     136            0 :     tracing::info!("Wrote garbage report to {output_path}");
     137              : 
     138            0 :     Ok(())
     139            0 : }
     140              : 
     141              : // How many concurrent S3 operations to issue (approximately): this is the concurrency
     142              : // for things like listing the timelines within tenant prefixes.
     143              : const S3_CONCURRENCY: usize = 32;
     144              : 
     145              : // How many concurrent API requests to make to the console API.
     146              : //
     147              : // Be careful increasing this; roughly we shouldn't have more than ~100 rps. It
     148              : // would be better to implement real rsp limiter.
     149              : const CONSOLE_CONCURRENCY: usize = 16;
     150              : 
     151              : struct ConsoleCache {
     152              :     /// Set of tenants found in the control plane API
     153              :     projects: HashMap<TenantId, ProjectData>,
     154              :     /// Set of tenants for which the control plane API returned 404
     155              :     not_found: HashSet<TenantId>,
     156              : }
     157              : 
     158            0 : async fn find_garbage_inner(
     159            0 :     bucket_config: BucketConfig,
     160            0 :     console_config: ConsoleConfig,
     161            0 :     depth: TraversingDepth,
     162            0 :     node_kind: NodeKind,
     163            0 :     tenant_id_prefix: Option<String>,
     164            0 : ) -> anyhow::Result<GarbageList> {
     165              :     // Construct clients for S3 and for Console API
     166            0 :     let (remote_client, target) = init_remote(bucket_config.clone(), node_kind).await?;
     167            0 :     let cloud_admin_api_client = Arc::new(CloudAdminApiClient::new(console_config));
     168              : 
     169              :     // Build a set of console-known tenants, for quickly eliminating known-active tenants without having
     170              :     // to issue O(N) console API requests.
     171            0 :     let console_projects: HashMap<TenantId, ProjectData> = cloud_admin_api_client
     172            0 :         .list_projects()
     173            0 :         .await?
     174            0 :         .into_iter()
     175            0 :         .map(|t| (t.tenant, t))
     176            0 :         .collect();
     177            0 :     tracing::info!(
     178            0 :         "Loaded {} console projects tenant IDs",
     179            0 :         console_projects.len()
     180              :     );
     181              : 
     182              :     // Because many tenant shards may look up the same TenantId, we maintain a cache.
     183            0 :     let console_cache = Arc::new(std::sync::Mutex::new(ConsoleCache {
     184            0 :         projects: console_projects,
     185            0 :         not_found: HashSet::new(),
     186            0 :     }));
     187            0 : 
     188            0 :     // Enumerate Tenants in S3, and check if each one exists in Console
     189            0 :     tracing::info!("Finding all tenants in {}...", bucket_config.desc_str());
     190            0 :     let tenants = stream_tenants_maybe_prefix(&remote_client, &target, tenant_id_prefix);
     191            0 :     let tenants_checked = tenants.map_ok(|t| {
     192            0 :         let api_client = cloud_admin_api_client.clone();
     193            0 :         let console_cache = console_cache.clone();
     194            0 :         async move {
     195              :             // Check cache before issuing API call
     196            0 :             let project_data = {
     197            0 :                 let cache = console_cache.lock().unwrap();
     198            0 :                 let result = cache.projects.get(&t.tenant_id).cloned();
     199            0 :                 if result.is_none() && cache.not_found.contains(&t.tenant_id) {
     200            0 :                     return Ok((t, None));
     201            0 :                 }
     202            0 :                 result
     203            0 :             };
     204            0 : 
     205            0 :             match project_data {
     206            0 :                 Some(project_data) => Ok((t, Some(project_data.clone()))),
     207              :                 None => {
     208            0 :                     let project_data = api_client
     209            0 :                         .find_tenant_project(t.tenant_id)
     210            0 :                         .await
     211            0 :                         .map_err(|e| anyhow::anyhow!(e));
     212            0 : 
     213            0 :                     // Populate cache with result of API call
     214            0 :                     {
     215            0 :                         let mut cache = console_cache.lock().unwrap();
     216            0 :                         if let Ok(Some(project_data)) = &project_data {
     217            0 :                             cache.projects.insert(t.tenant_id, project_data.clone());
     218            0 :                         } else if let Ok(None) = &project_data {
     219            0 :                             cache.not_found.insert(t.tenant_id);
     220            0 :                         }
     221              :                     }
     222              : 
     223            0 :                     project_data.map(|r| (t, r))
     224              :                 }
     225              :             }
     226            0 :         }
     227            0 :     });
     228            0 :     let mut tenants_checked =
     229            0 :         std::pin::pin!(tenants_checked.try_buffer_unordered(CONSOLE_CONCURRENCY));
     230            0 : 
     231            0 :     // Process the results of Tenant checks.  If a Tenant is garbage, it goes into
     232            0 :     // the `GarbageList`.  Else it goes into `active_tenants` for more detailed timeline
     233            0 :     // checks if they are enabled by the `depth` parameter.
     234            0 :     let mut garbage = GarbageList::new(node_kind, bucket_config);
     235            0 :     let mut active_tenants: Vec<TenantShardId> = vec![];
     236            0 :     let mut counter = 0;
     237            0 :     while let Some(result) = tenants_checked.next().await {
     238            0 :         let (tenant_shard_id, console_result) = result?;
     239              : 
     240              :         // Paranoia check
     241            0 :         if let Some(project) = &console_result {
     242            0 :             assert!(project.tenant == tenant_shard_id.tenant_id);
     243            0 :         }
     244              : 
     245              :         // Special case: If it's missing in console, check for known bugs that would enable us to conclusively
     246              :         // identify it as purge-able anyway
     247            0 :         if console_result.is_none() {
     248            0 :             let timelines = stream_tenant_timelines(&remote_client, &target, tenant_shard_id)
     249            0 :                 .await?
     250            0 :                 .collect::<Vec<_>>()
     251            0 :                 .await;
     252            0 :             if timelines.is_empty() {
     253              :                 // No timelines, but a heatmap: the deletion bug where we deleted everything but heatmaps
     254            0 :                 let tenant_objects = list_objects_with_retries(
     255            0 :                     &remote_client,
     256            0 :                     ListingMode::WithDelimiter,
     257            0 :                     &target.tenant_root(&tenant_shard_id),
     258            0 :                 )
     259            0 :                 .await?;
     260            0 :                 if let Some(object) = tenant_objects.keys.first() {
     261            0 :                     if object.key.get_path().as_str().ends_with("heatmap-v1.json") {
     262            0 :                         tracing::info!("Tenant {tenant_shard_id}: is missing in console and is only a heatmap (known historic deletion bug)");
     263            0 :                         garbage.append_buggy(GarbageEntity::Tenant(tenant_shard_id));
     264            0 :                         continue;
     265              :                     } else {
     266            0 :                         tracing::info!("Tenant {tenant_shard_id} is missing in console and contains one object: {}", object.key);
     267              :                     }
     268              :                 } else {
     269            0 :                     tracing::info!("Tenant {tenant_shard_id} is missing in console appears to have been deleted while we ran");
     270              :                 }
     271              :             } else {
     272              :                 // A console-unknown tenant with timelines: check if these timelines only contain initdb.tar.zst, from the initial
     273              :                 // rollout of WAL DR in which we never deleted these.
     274            0 :                 let mut any_non_initdb = false;
     275              : 
     276            0 :                 for timeline_r in timelines {
     277            0 :                     let timeline = timeline_r?;
     278            0 :                     let timeline_objects = list_objects_with_retries(
     279            0 :                         &remote_client,
     280            0 :                         ListingMode::WithDelimiter,
     281            0 :                         &target.timeline_root(&timeline),
     282            0 :                     )
     283            0 :                     .await?;
     284            0 :                     if !timeline_objects.prefixes.is_empty() {
     285            0 :                         // Sub-paths?  Unexpected
     286            0 :                         any_non_initdb = true;
     287            0 :                     } else {
     288            0 :                         let object = timeline_objects.keys.first().unwrap();
     289            0 :                         if object.key.get_path().as_str().ends_with("initdb.tar.zst") {
     290            0 :                             tracing::info!("Timeline {timeline} contains only initdb.tar.zst");
     291            0 :                         } else {
     292            0 :                             any_non_initdb = true;
     293            0 :                         }
     294              :                     }
     295              :                 }
     296              : 
     297            0 :                 if any_non_initdb {
     298            0 :                     tracing::info!("Tenant {tenant_shard_id}: is missing in console and contains timelines, one or more of which are more than just initdb");
     299              :                 } else {
     300            0 :                     tracing::info!("Tenant {tenant_shard_id}: is missing in console and contains only timelines that only contain initdb");
     301            0 :                     garbage.append_buggy(GarbageEntity::Tenant(tenant_shard_id));
     302            0 :                     continue;
     303              :                 }
     304              :             }
     305            0 :         }
     306              : 
     307            0 :         if garbage.maybe_append(GarbageEntity::Tenant(tenant_shard_id), console_result) {
     308            0 :             tracing::debug!("Tenant {tenant_shard_id} is garbage");
     309              :         } else {
     310            0 :             tracing::debug!("Tenant {tenant_shard_id} is active");
     311            0 :             active_tenants.push(tenant_shard_id);
     312            0 :             garbage.active_tenant_count = active_tenants.len();
     313              :         }
     314              : 
     315            0 :         counter += 1;
     316            0 :         if counter % 1000 == 0 {
     317            0 :             tracing::info!(
     318            0 :                 "Progress: {counter} tenants checked, {} active, {} garbage",
     319            0 :                 active_tenants.len(),
     320            0 :                 garbage.items.len()
     321              :             );
     322            0 :         }
     323              :     }
     324              : 
     325            0 :     tracing::info!(
     326            0 :         "Found {}/{} garbage tenants",
     327            0 :         garbage.items.len(),
     328            0 :         garbage.items.len() + active_tenants.len()
     329              :     );
     330              : 
     331              :     // If we are only checking tenant-deep, we are done.  Otherwise we must
     332              :     // proceed to check the individual timelines of the active tenants.
     333            0 :     if depth == TraversingDepth::Tenant {
     334            0 :         return Ok(garbage);
     335            0 :     }
     336            0 : 
     337            0 :     tracing::info!(
     338            0 :         "Checking timelines for {} active tenants",
     339            0 :         active_tenants.len(),
     340              :     );
     341              : 
     342              :     // Construct a stream of all timelines within active tenants
     343            0 :     let active_tenants = tokio_stream::iter(active_tenants.iter().map(Ok));
     344            0 :     let timelines = active_tenants.map_ok(|t| stream_tenant_timelines(&remote_client, &target, *t));
     345            0 :     let timelines = timelines.try_buffer_unordered(S3_CONCURRENCY);
     346            0 :     let timelines = timelines.try_flatten();
     347            0 : 
     348            0 :     // For all timelines within active tenants, call into console API to check their existence
     349            0 :     let timelines_checked = timelines.map_ok(|ttid| {
     350            0 :         let api_client = cloud_admin_api_client.clone();
     351            0 :         async move {
     352            0 :             api_client
     353            0 :                 .find_timeline_branch(ttid.tenant_shard_id.tenant_id, ttid.timeline_id)
     354            0 :                 .await
     355            0 :                 .map_err(|e| anyhow::anyhow!(e))
     356            0 :                 .map(|r| (ttid, r))
     357            0 :         }
     358            0 :     });
     359            0 :     let mut timelines_checked =
     360            0 :         std::pin::pin!(timelines_checked.try_buffer_unordered(CONSOLE_CONCURRENCY));
     361            0 : 
     362            0 :     // Update the GarbageList with any timelines which appear not to exist.
     363            0 :     let mut active_timelines: Vec<TenantShardTimelineId> = vec![];
     364            0 :     while let Some(result) = timelines_checked.next().await {
     365            0 :         let (ttid, console_result) = result?;
     366            0 :         if garbage.maybe_append(GarbageEntity::Timeline(ttid), console_result) {
     367            0 :             tracing::debug!("Timeline {ttid} is garbage");
     368              :         } else {
     369            0 :             tracing::debug!("Timeline {ttid} is active");
     370            0 :             active_timelines.push(ttid);
     371            0 :             garbage.active_timeline_count = active_timelines.len();
     372              :         }
     373              :     }
     374              : 
     375            0 :     let num_garbage_timelines = garbage
     376            0 :         .items
     377            0 :         .iter()
     378            0 :         .filter(|g| matches!(g.entity, GarbageEntity::Timeline(_)))
     379            0 :         .count();
     380            0 :     tracing::info!(
     381            0 :         "Found {}/{} garbage timelines in active tenants",
     382            0 :         num_garbage_timelines,
     383            0 :         active_timelines.len(),
     384              :     );
     385              : 
     386            0 :     Ok(garbage)
     387            0 : }
     388              : 
     389            0 : #[derive(clap::ValueEnum, Debug, Clone)]
     390              : pub enum PurgeMode {
     391              :     /// The safest mode: only delete tenants that were explicitly reported as deleted
     392              :     /// by Console API.
     393              :     DeletedOnly,
     394              : 
     395              :     /// Delete all garbage tenants, including those which are only presumed to be deleted,
     396              :     /// because the Console API could not find them.
     397              :     DeletedAndMissing,
     398              : }
     399              : 
     400              : impl std::fmt::Display for PurgeMode {
     401            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     402            0 :         match self {
     403            0 :             PurgeMode::DeletedOnly => write!(f, "deleted-only"),
     404            0 :             PurgeMode::DeletedAndMissing => write!(f, "deleted-and-missing"),
     405              :         }
     406            0 :     }
     407              : }
     408              : 
     409            0 : pub async fn get_tenant_objects(
     410            0 :     s3_client: &GenericRemoteStorage,
     411            0 :     tenant_shard_id: TenantShardId,
     412            0 : ) -> anyhow::Result<Vec<ListingObject>> {
     413            0 :     tracing::debug!("Listing objects in tenant {tenant_shard_id}");
     414            0 :     let tenant_root = super::remote_tenant_path(&tenant_shard_id);
     415            0 : 
     416            0 :     // TODO: apply extra validation based on object modification time.  Don't purge
     417            0 :     // tenants where any timeline's index_part.json has been touched recently.
     418            0 : 
     419            0 :     let cancel = CancellationToken::new();
     420            0 :     let list = backoff::retry(
     421            0 :         || s3_client.list(Some(&tenant_root), ListingMode::NoDelimiter, None, &cancel),
     422            0 :         |_| false,
     423            0 :         3,
     424            0 :         MAX_RETRIES as u32,
     425            0 :         "get_tenant_objects",
     426            0 :         &cancel,
     427            0 :     )
     428            0 :     .await
     429            0 :     .expect("dummy cancellation token")?;
     430            0 :     Ok(list.keys)
     431            0 : }
     432              : 
     433            0 : pub async fn get_timeline_objects(
     434            0 :     s3_client: &GenericRemoteStorage,
     435            0 :     ttid: TenantShardTimelineId,
     436            0 : ) -> anyhow::Result<Vec<ListingObject>> {
     437            0 :     tracing::debug!("Listing objects in timeline {ttid}");
     438            0 :     let timeline_root = super::remote_timeline_path_id(&ttid);
     439            0 : 
     440            0 :     let cancel = CancellationToken::new();
     441            0 :     let list = backoff::retry(
     442            0 :         || {
     443            0 :             s3_client.list(
     444            0 :                 Some(&timeline_root),
     445            0 :                 ListingMode::NoDelimiter,
     446            0 :                 None,
     447            0 :                 &cancel,
     448            0 :             )
     449            0 :         },
     450            0 :         |_| false,
     451            0 :         3,
     452            0 :         MAX_RETRIES as u32,
     453            0 :         "get_timeline_objects",
     454            0 :         &cancel,
     455            0 :     )
     456            0 :     .await
     457            0 :     .expect("dummy cancellation token")?;
     458              : 
     459            0 :     Ok(list.keys)
     460            0 : }
     461              : 
     462              : const MAX_KEYS_PER_DELETE: usize = 1000;
     463              : 
     464              : /// Drain a buffer of keys into DeleteObjects requests
     465              : ///
     466              : /// If `drain` is true, drains keys completely; otherwise stops when <
     467              : /// MAX_KEYS_PER_DELETE keys are left.
     468              : /// `num_deleted` returns number of deleted keys.
     469            0 : async fn do_delete(
     470            0 :     remote_client: &GenericRemoteStorage,
     471            0 :     keys: &mut Vec<ListingObject>,
     472            0 :     dry_run: bool,
     473            0 :     drain: bool,
     474            0 :     progress_tracker: &mut DeletionProgressTracker,
     475            0 : ) -> anyhow::Result<()> {
     476            0 :     let cancel = CancellationToken::new();
     477            0 :     while (!keys.is_empty() && drain) || (keys.len() >= MAX_KEYS_PER_DELETE) {
     478            0 :         let request_keys =
     479            0 :             keys.split_off(keys.len() - (std::cmp::min(MAX_KEYS_PER_DELETE, keys.len())));
     480            0 : 
     481            0 :         let request_keys: Vec<RemotePath> = request_keys.into_iter().map(|o| o.key).collect();
     482            0 : 
     483            0 :         let num_deleted = request_keys.len();
     484            0 :         if dry_run {
     485            0 :             tracing::info!("Dry-run deletion of objects: ");
     486            0 :             for k in request_keys {
     487            0 :                 tracing::info!("  {k:?}");
     488              :             }
     489              :         } else {
     490            0 :             remote_client
     491            0 :                 .delete_objects(&request_keys, &cancel)
     492            0 :                 .await
     493            0 :                 .context("deletetion request")?;
     494            0 :             progress_tracker.register(num_deleted);
     495              :         }
     496              :     }
     497              : 
     498            0 :     Ok(())
     499            0 : }
     500              : 
     501              : /// Simple tracker reporting each 10k deleted keys.
     502              : #[derive(Default)]
     503              : struct DeletionProgressTracker {
     504              :     num_deleted: usize,
     505              :     last_reported_num_deleted: usize,
     506              : }
     507              : 
     508              : impl DeletionProgressTracker {
     509            0 :     fn register(&mut self, n: usize) {
     510            0 :         self.num_deleted += n;
     511            0 :         if self.num_deleted - self.last_reported_num_deleted > 10000 {
     512            0 :             tracing::info!("progress: deleted {} keys", self.num_deleted);
     513            0 :             self.last_reported_num_deleted = self.num_deleted;
     514            0 :         }
     515            0 :     }
     516              : }
     517              : 
     518            0 : pub async fn purge_garbage(
     519            0 :     input_path: String,
     520            0 :     mode: PurgeMode,
     521            0 :     min_age: Duration,
     522            0 :     dry_run: bool,
     523            0 : ) -> anyhow::Result<()> {
     524            0 :     let list_bytes = tokio::fs::read(&input_path).await?;
     525            0 :     let garbage_list = serde_json::from_slice::<GarbageList>(&list_bytes)?;
     526            0 :     tracing::info!(
     527            0 :         "Loaded {} items in garbage list from {}",
     528            0 :         garbage_list.items.len(),
     529              :         input_path
     530              :     );
     531              : 
     532            0 :     let (remote_client, _target) =
     533            0 :         init_remote(garbage_list.bucket_config.clone(), garbage_list.node_kind).await?;
     534              : 
     535            0 :     assert_eq!(
     536            0 :         garbage_list.bucket_config.bucket_name().unwrap(),
     537            0 :         remote_client.bucket_name().unwrap()
     538            0 :     );
     539              : 
     540              :     // Sanity checks on the incoming list
     541            0 :     if garbage_list.active_tenant_count == 0 {
     542            0 :         anyhow::bail!("Refusing to purge a garbage list that reports 0 active tenants");
     543            0 :     }
     544            0 :     if garbage_list
     545            0 :         .items
     546            0 :         .iter()
     547            0 :         .any(|g| matches!(g.entity, GarbageEntity::Timeline(_)))
     548            0 :         && garbage_list.active_timeline_count == 0
     549              :     {
     550            0 :         anyhow::bail!("Refusing to purge a garbage list containing garbage timelines that reports 0 active timelines");
     551            0 :     }
     552            0 : 
     553            0 :     let filtered_items = garbage_list
     554            0 :         .items
     555            0 :         .iter()
     556            0 :         .filter(|i| match (&mode, &i.reason) {
     557            0 :             (PurgeMode::DeletedAndMissing, _) => true,
     558            0 :             (PurgeMode::DeletedOnly, GarbageReason::DeletedInConsole) => true,
     559            0 :             (PurgeMode::DeletedOnly, GarbageReason::KnownBug) => true,
     560            0 :             (PurgeMode::DeletedOnly, GarbageReason::MissingInConsole) => false,
     561            0 :         });
     562            0 : 
     563            0 :     tracing::info!(
     564            0 :         "Filtered down to {} garbage items based on mode {}",
     565            0 :         garbage_list.items.len(),
     566              :         mode
     567              :     );
     568              : 
     569            0 :     let items = tokio_stream::iter(filtered_items.map(Ok));
     570            0 :     let get_objects_results = items.map_ok(|i| {
     571            0 :         let remote_client = remote_client.clone();
     572            0 :         async move {
     573            0 :             match i.entity {
     574            0 :                 GarbageEntity::Tenant(tenant_id) => {
     575            0 :                     get_tenant_objects(&remote_client, tenant_id).await
     576              :                 }
     577            0 :                 GarbageEntity::Timeline(ttid) => get_timeline_objects(&remote_client, ttid).await,
     578              :             }
     579            0 :         }
     580            0 :     });
     581            0 :     let mut get_objects_results =
     582            0 :         std::pin::pin!(get_objects_results.try_buffer_unordered(S3_CONCURRENCY));
     583            0 : 
     584            0 :     let mut objects_to_delete = Vec::new();
     585            0 :     let mut progress_tracker = DeletionProgressTracker::default();
     586            0 :     while let Some(result) = get_objects_results.next().await {
     587            0 :         let mut object_list = result?;
     588              : 
     589              :         // Extra safety check: even if a collection of objects is garbage, check max() of modification
     590              :         // times before purging, so that if we incorrectly marked a live tenant as garbage then we would
     591              :         // notice that its index has been written recently and would omit deleting it.
     592            0 :         if object_list.is_empty() {
     593              :             // Simplify subsequent code by ensuring list always has at least one item
     594              :             // Usually, this only occurs if there is parallel deletions racing us, as there is no empty prefixes
     595            0 :             continue;
     596            0 :         }
     597            0 :         let max_mtime = object_list.iter().map(|o| o.last_modified).max().unwrap();
     598            0 :         let age = max_mtime.elapsed();
     599            0 :         match age {
     600              :             Err(_) => {
     601            0 :                 tracing::warn!("Bad last_modified time");
     602            0 :                 continue;
     603              :             }
     604            0 :             Ok(a) if a < min_age => {
     605            0 :                 // Failed age check.  This doesn't mean we did something wrong: a tenant might really be garbage and recently
     606            0 :                 // written, but out of an abundance of caution we still don't purge it.
     607            0 :                 tracing::info!(
     608            0 :                     "Skipping tenant with young objects {}..{}",
     609            0 :                     object_list.first().as_ref().unwrap().key,
     610            0 :                     object_list.last().as_ref().unwrap().key
     611              :                 );
     612            0 :                 continue;
     613              :             }
     614            0 :             Ok(_) => {
     615            0 :                 // Passed age check
     616            0 :             }
     617            0 :         }
     618            0 : 
     619            0 :         objects_to_delete.append(&mut object_list);
     620            0 :         if objects_to_delete.len() >= MAX_KEYS_PER_DELETE {
     621            0 :             do_delete(
     622            0 :                 &remote_client,
     623            0 :                 &mut objects_to_delete,
     624            0 :                 dry_run,
     625            0 :                 false,
     626            0 :                 &mut progress_tracker,
     627            0 :             )
     628            0 :             .await?;
     629            0 :         }
     630              :     }
     631              : 
     632            0 :     do_delete(
     633            0 :         &remote_client,
     634            0 :         &mut objects_to_delete,
     635            0 :         dry_run,
     636            0 :         true,
     637            0 :         &mut progress_tracker,
     638            0 :     )
     639            0 :     .await?;
     640              : 
     641            0 :     tracing::info!("{} keys deleted in total", progress_tracker.num_deleted);
     642              : 
     643            0 :     Ok(())
     644            0 : }
        

Generated by: LCOV version 2.1-beta