LCOV - code coverage report
Current view: top level - storage_scrubber/src - garbage.rs (source / functions) Coverage Total Hit
Test: 42f947419473a288706e86ecdf7c2863d760d5d7.info Lines: 0.0 % 401 0
Test Date: 2024-08-02 21:34:27 Functions: 0.0 % 84 0

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

Generated by: LCOV version 2.1-beta