1use std::io::{Result, Error, ErrorKind};
10use std::collections::{BTreeMap, BTreeSet};
11use std::sync::Arc;
12use aws_sdk_s3::Client;
13use log::{debug, error};
14use btree_ondisk::bmap::BMap;
15use btree_ondisk::BlockLoader;
16use hyperfile::{BlockIndex, BlockPtr, Cno, SegmentId, s3_code_kind, s3_error_kind};
17use hyperfile::file::ReadTiming;
18use hyperfile::meta_loader::s3::S3BlockLoader;
19use hyperfile::ondisk::InodeRaw;
20use hyperfile::compaction::{PendingCompaction, StoredCompaction};
21use hyperfile::inode::{Inode, OnDiskState};
22use hyperfile::segment::{Segment, SegmentSum, SegmentReadWrite};
23use hyperfile::staging::{Staging, config::StagingConfig, s3::S3Staging};
24use hyperfile::config::{HyperFileMetaConfig, HyperFileRuntimeConfig};
25use hyperfile::s3uri::S3Uri;
26use hyperfile::meta_format::BlockPtrFormat;
27use crate::Cleaner;
28
29pub struct S3Cleaner {
44 client: Client,
45 bucket: String,
46 root_path: String,
47 staging: S3Staging,
48 pause_after_view: std::sync::Mutex<Option<PauseHook>>,
49}
50
51#[doc(hidden)]
53pub type PauseHook = std::sync::Arc<dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> + Send + Sync>;
54
55impl S3Cleaner {
56 pub async fn new(root_uri: &str) -> Result<Self> {
62 let cfg = aws_config::load_from_env().await;
63 let client = Client::new(&cfg);
64 Self::with_client(&client, root_uri).await
65 }
66
67 pub async fn with_client(client: &Client, root_uri: &str) -> Result<Self> {
74 let trimmed = trim_root_uri(root_uri);
75 let s3uri = S3Uri::parse(trimmed).map_err(|e| {
76 Error::new(
77 ErrorKind::InvalidInput,
78 format!("invalid S3 URI {:?}: {}", root_uri, e),
79 )
80 })?;
81 let runtime_config = HyperFileRuntimeConfig::default();
82 let staging_config = StagingConfig::new_s3_staging(s3uri.bucket, "", s3uri.key, None);
83 let staging = S3Staging::from(client, staging_config, runtime_config).await?;
84 Ok(Self {
85 client: client.clone(),
86 bucket: s3uri.bucket.to_owned(),
87 root_path: s3uri.key.to_owned(),
88 staging,
89 pause_after_view: std::sync::Mutex::new(None),
90 })
91 }
92
93 #[doc(hidden)]
96 pub fn set_pause_after_view(&self, hook: Option<PauseHook>) {
97 *self.pause_after_view.lock().unwrap() = hook;
98 }
99
100 async fn load_segment_sum(&self, segid: SegmentId) -> Result<SegmentSum> {
101 self.staging.open(segid).await
102 }
103
104 pub(crate) fn root_uri(&self) -> String {
106 format!("s3://{}/{}", self.bucket, self.root_path)
107 }
108
109 pub(crate) fn client(&self) -> &Client {
111 &self.client
112 }
113
114 async fn load_raw_inode(&self) -> Result<(InodeRaw, Option<OnDiskState>)> {
115 let mut raw_inode = InodeRaw::default();
116 let inode_state = self.staging.load_inode(raw_inode.as_mut_u8_slice()).await?;
117 Ok((raw_inode, inode_state))
118 }
119
120 fn walk_live_ptrs<L>(
136 bmap: BMap<'_, BlockIndex, BlockPtr, BlockPtr, L, Prefetched>,
137 ) -> Result<LivePtrs>
138 where
139 L: BlockLoader<BlockPtr> + Clone,
140 {
141 let handle = tokio::runtime::Handle::current();
148 let on_staging = |v: Vec<BlockPtr>| -> BTreeSet<BlockPtr> {
149 v.into_iter().filter(BlockPtrFormat::is_on_staging).collect()
150 };
151 let all = on_staging(handle.block_on(bmap.collect_ptrs())?);
152 let meta = on_staging(handle.block_on(bmap.collect_meta_ptrs())?);
153
154 let mut windows: Vec<(BlockIndex, usize)> = Vec::new();
166 let mut pos: BlockIndex = 0;
167 loop {
168 let key = match handle.block_on(bmap.seek_key(&pos)) {
169 Ok(key) => key,
170 Err(e) if e.kind() == ErrorKind::NotFound => break,
171 Err(e) => return Err(e),
172 };
173 match windows.last_mut() {
174 Some((start, n)) if *start + *n as BlockIndex == key
175 && *n + DATA_WINDOW_BLOCKS <= 4 * DATA_WINDOW_BLOCKS =>
176 {
177 *n += DATA_WINDOW_BLOCKS;
178 },
179 _ => windows.push((key, DATA_WINDOW_BLOCKS)),
180 }
181 match key.checked_add(DATA_WINDOW_BLOCKS as BlockIndex) {
182 Some(next) => pos = next,
183 None => break,
184 }
185 }
186 let node_keys = Self::walk_node_keys(&bmap, &handle)?;
187 Ok(LivePtrs { all, meta, windows, node_keys })
188 }
189
190 fn walk_node_keys<L>(
201 bmap: &BMap<'_, BlockIndex, BlockPtr, BlockPtr, L, Prefetched>,
202 handle: &tokio::runtime::Handle,
203 ) -> Result<BTreeMap<BlockPtr, (BlockIndex, BlockPtr)>>
204 where
205 L: BlockLoader<BlockPtr> + Clone,
206 {
207 let mut keys = BTreeMap::new();
208 if bmap.is_direct() {
209 return Ok(keys);
210 }
211 let first = match handle.block_on(bmap.seek_key(&0)) {
212 Ok(k) => k,
213 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(keys),
214 Err(e) => return Err(e),
215 };
216 let mut stack = vec![(bmap.height() - 1, first)];
218 while let Some((level, key)) = stack.pop() {
219 let children = handle.block_on(bmap.node_children(level, &key))?;
220 for (k, p, _) in children.iter() {
221 if BlockPtrFormat::is_on_staging(p) {
222 if let Some(found) = Self::block_on_storage_under(bmap, handle, level - 1, *k)? {
223 keys.insert(*p, found);
224 }
225 }
226 if level - 1 >= 2 {
227 stack.push((level - 1, *k));
228 }
229 }
230 }
231 Ok(keys)
232 }
233
234 fn block_on_storage_under<L>(
239 bmap: &BMap<'_, BlockIndex, BlockPtr, BlockPtr, L, Prefetched>,
240 handle: &tokio::runtime::Handle,
241 level: usize,
242 key: BlockIndex,
243 ) -> Result<Option<(BlockIndex, BlockPtr)>>
244 where
245 L: BlockLoader<BlockPtr> + Clone,
246 {
247 if level <= 1 {
248 let entries = handle.block_on(bmap.leaf_entries(&key))?;
249 return Ok(entries.into_iter().find(|(_, v)| BlockPtrFormat::is_on_staging(v)));
250 }
251 for (k, _, _) in handle.block_on(bmap.node_children(level, &key))? {
252 if let Some(found) = Self::block_on_storage_under(bmap, handle, level - 1, k)? {
253 return Ok(Some(found));
254 }
255 }
256 Ok(None)
257 }
258
259 async fn list_segment_objects(&self) -> Result<ObjectListing> {
277 let prefix = format!("{}/", self.root_path);
278 let mut listing = ObjectListing::default();
279 let mut pages = self.client.list_objects_v2()
280 .bucket(&self.bucket)
281 .prefix(&prefix)
282 .into_paginator()
283 .send();
284 while let Some(page) = pages.next().await {
285 let page = page.map_err(|e| Error::new(
286 s3_error_kind(&e),
287 format!("listing segment objects under s3://{}/{} failed: {}",
288 self.bucket, prefix, e),
289 ))?;
290 for obj in page.contents() {
291 let Some(key) = obj.key() else { continue };
292 if key == self.staging.inode_file {
293 continue;
294 }
295 let Some(name) = key.strip_prefix(&prefix) else { continue };
296 match parse_segment_object_name(name) {
297 Some(segid) => {
298 listing.objects.push((segid, obj.size().unwrap_or(0).max(0) as u64));
299 if let Some(t) = obj.last_modified() {
300 listing.modified.insert(segid, t.secs());
301 }
302 },
303 None => {
304 listing.foreign += 1;
305 if listing.foreign_sample.is_none() {
306 listing.foreign_sample = Some(key.to_string());
307 }
308 },
309 }
310 }
311 }
312 listing.objects.sort();
313 Ok(listing)
314 }
315
316 async fn do_delete_objects(
340 client: &Client,
341 bucket: &str,
342 delete_keys: Vec<String>,
343 ) -> Result<()> {
344 use aws_sdk_s3::types::ObjectIdentifier;
345 if delete_keys.is_empty() {
346 return Ok(());
347 }
348 let mut failed_keys: Vec<String> = Vec::new();
349 let mut first_kind: Option<ErrorKind> = None;
350 for keys in delete_keys.chunks(1000) {
351 let obj_ids = keys.iter()
352 .map(|k| {
353 ObjectIdentifier::builder()
354 .key(k)
355 .build()
356 .expect("ObjectIdentifier requires non-empty key")
357 })
358 .collect::<Vec<ObjectIdentifier>>();
359 let delete = aws_sdk_s3::types::Delete::builder()
363 .set_objects(Some(obj_ids))
364 .quiet(true)
365 .build()
366 .expect("Delete::builder requires non-empty object list");
367 match client.delete_objects()
368 .bucket(bucket)
369 .delete(delete)
370 .send()
371 .await
372 {
373 Ok(output) => {
374 if let Some(errors) = output.errors {
379 for e in errors {
380 let key = e.key.unwrap_or_default();
381 let code = e.code.as_deref().unwrap_or("?");
382 let msg = e.message.as_deref().unwrap_or("");
383 error!("DeleteObjects per-key failure: key={} code={} message={}",
384 key, code, msg);
385 first_kind.get_or_insert(s3_code_kind(e.code.as_deref()));
386 if !key.is_empty() {
387 failed_keys.push(key);
388 }
389 }
390 }
391 },
392 Err(sdk_err) => {
393 error!("DeleteObjects batch failed (bucket={}, count={}): {}",
396 bucket, keys.len(), sdk_err);
397 first_kind.get_or_insert(s3_error_kind(&sdk_err));
398 failed_keys.extend(keys.iter().cloned());
399 }
400 }
401 }
402 if failed_keys.is_empty() {
403 Ok(())
404 } else {
405 Err(Error::new(
406 first_kind.unwrap_or(ErrorKind::Other),
407 format!(
408 "DeleteObjects failed for {} object(s); first failed key: {:?}",
409 failed_keys.len(),
410 failed_keys.first(),
411 ),
412 ))
413 }
414 }
415
416 pub(crate) async fn view(&self, low: Cno, high: Cno) -> Result<ContainerView> {
423 let (raw_inode, inode_state) = self.load_raw_inode().await?;
427 refuse_unsegmented(&raw_inode)?;
428 let fmt = container_ptr_format(&raw_inode)?;
429 let latest_compacted = raw_inode.is_compacted();
430 let compaction = inode_state.as_ref().map(|s| s.compaction.clone()).unwrap_or_default();
431 let latest_cno = Inode::from_raw(&raw_inode, inode_state).get_last_cno();
432 let high_cno = if high == 0 { latest_cno } else { high };
433
434 debug!("view of container low: {}, high: {}, format: {:?}", low, high_cno, fmt);
435 validate_segid_range(low, high_cno)?;
436
437 let high_summary = summary_obj(high_cno, &fmt);
444 let ss = self.load_segment_sum(high_summary).await?;
445 if !ss.hdr.has_magic() || ss.hdr.s_cno != high_cno {
450 return Err(Error::new(
451 ErrorKind::InvalidData,
452 format!(
453 "{} does not read as checkpoint {}'s summary (magic {:#x}, checkpoint {})",
454 high_summary, high_cno, ss.hdr.s_magic, ss.hdr.s_cno,
455 ),
456 ));
457 }
458 let walked_stored = high_cno == latest_cno;
468 let ss_inode = if walked_stored { raw_inode } else { ss.hdr.s_inode };
469 let meta_block_size = 1usize << ss.hdr.s_meta_blk_shift;
474 let data_block_size = 1usize << ss.hdr.s_data_blk_shift;
475
476 let timing = Arc::new(ReadTiming::default());
483 let loader = S3BlockLoader::new(
484 &self.client, &self.bucket, &self.root_path, timing.clone(),
485 );
486 let join = tokio::task::spawn_blocking(move || -> Result<LivePtrs> {
487 let nodes = prefetch_nodes(&loader, meta_block_size, &ss_inode)?;
490 let bmap = BMap::<BlockIndex, BlockPtr, BlockPtr, S3BlockLoader, Prefetched>
491 ::read(&ss_inode.i_bmap, meta_block_size, loader, Prefetched(Arc::new(nodes)))?;
492 let live = Self::walk_live_ptrs(bmap);
493 debug!("map walk: {} node reads", timing.snapshot().meta_gets);
494 live
495 });
496 let live = match join.await {
497 Ok(inner) => inner?,
498 Err(join_err) => {
499 return Err(Error::other(
500 format!("bmap walk task failed to join: {}", join_err),
501 ));
502 }
503 };
504
505 let listing = self.list_segment_objects().await?;
506 if !listing.objects.iter().any(|(segid, _)| *segid == high_summary) {
510 return Err(Error::new(
511 ErrorKind::InvalidData,
512 format!(
513 "the listing has no object named {}, the summary just read; \
514 refusing to judge what is referenced",
515 high_summary,
516 ),
517 ));
518 }
519 Ok(ContainerView {
520 low,
521 high_cno,
522 stored: raw_inode,
523 walked_stored,
524 walked: ss_inode,
525 compaction,
526 latest_compacted,
527 fmt,
528 high_summary,
529 data_block_size,
530 meta_block_size,
531 live,
532 listing,
533 })
534 }
535
536 async fn collect_unref_seg(
546 &self,
547 low: Cno,
548 high: Cno,
549 ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
550 self.collect_within(low, high, std::time::Duration::ZERO, 1).await
551 }
552
553 async fn collect_within(
557 &self,
558 low: Cno,
559 high: Cno,
560 grace: std::time::Duration,
561 attempts: usize,
562 ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
563 let attempts = attempts.max(1);
571 for _ in 0..attempts {
572 let (judged, attached_before) = self.collect_within_once(low, high, grace).await?;
573 if grace.is_zero() {
574 return Ok(judged);
575 }
576 let (_, state) = self.load_raw_inode().await?;
577 let attached_now = state.map(|s| s.compaction).unwrap_or_default();
578 if attached_now == attached_before {
579 return Ok(judged);
580 }
581 debug!("prune: a compaction was attached while judging; judging again");
582 }
583 Err(Error::new(ErrorKind::ResourceBusy, format!(
584 "compactions were attached while prune judged, {} times; try again", attempts)))
585 }
586
587 async fn collect_within_once(
590 &self,
591 low: Cno,
592 high: Cno,
593 grace: std::time::Duration,
594 ) -> Result<((Vec<SegmentId>, Vec<SegmentId>), StoredCompaction)> {
595 let view = self.view(low, high).await?;
596 let attached_before = view.compaction.clone();
597 if !grace.is_zero() {
598 let hook = self.pause_after_view.lock().unwrap().clone();
599 if let Some(hook) = hook {
600 hook().await;
601 }
602 }
603 let mut roots = Vec::new();
606 if !view.walked_stored {
607 roots.push(view.stored);
608 }
609 if let Some(root) = view.attached_root()? {
612 roots.push(root);
613 }
614 let mut young = BTreeSet::new();
615 if !grace.is_zero() {
616 let (now, _) = self.staging.load_segment_timestamp(SegmentId::new_from_cno(view.high_cno)).await?;
619 let cutoff = now.saturating_sub(grace.as_secs().min(i64::MAX as u64) as i64);
620 young = view.listing.modified.iter().filter(|(_, t)| **t >= cutoff).map(|(s, _)| *s).collect();
621 let versions = self.versions_since(&view, cutoff).await?;
622 young.extend(versions.iter().map(|(id, _)| *id));
627 roots.extend(versions.into_iter().map(|(_, v)| v));
628 }
629 debug!("prune roots: {:?}", roots.iter().map(|r| (r.i_last_cno, r.fingerprint())).collect::<Vec<_>>());
630 let more = match self.walk_more(&view, roots.clone()).await {
631 Ok(m) => m,
632 Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::InvalidData) => {
633 let attached = view.attached_root().ok().flatten().map(|r| r.i_bmap);
634 for r in &roots {
635 if let Err(e2) = self.walk_more(&view, vec![*r]).await {
636 error!("prune: root of checkpoint {} (fingerprint {:#x}, {}) reaches a deleted object: {}", r.i_last_cno,
637 r.fingerprint(), if Some(r.i_bmap) == attached { "the attached compaction" } else { "a version" }, e2);
638 }
639 }
640 return Err(e);
641 },
642 Err(e) => return Err(e),
643 };
644 let mut referenced = view.referenced_objects();
645 referenced.extend(more.iter().map(|p| view.object_of(p)));
646 let (v_ref, mut unref) = partition_objects(
647 &view.object_ids(),
648 &referenced,
649 view.low,
650 view.high_cno,
651 view.high_summary,
652 );
653 unref.retain(|o| !young.contains(o));
654 Ok(((v_ref, unref), attached_before))
655 }
656
657 async fn versions_since(&self, view: &ContainerView, cutoff: i64) -> Result<Vec<(SegmentId, InodeRaw)>> {
665 let stream = view.fmt.is_stream();
666 let modified = |id: &SegmentId| view.listing.modified.get(id).copied();
667 let summaries: Vec<(SegmentId, i64)> = view.listing.objects.iter()
668 .map(|(id, _)| *id)
669 .filter(|id| *id == summary_obj(id.as_cno(), &view.fmt))
670 .filter_map(|id| modified(&id).map(|t| (id, t)))
671 .collect();
672 let from = summaries.iter().rposition(|(_, t)| *t < cutoff).unwrap_or(0);
675 let mut versions: Vec<(i64, SegmentId, InodeRaw)> = Vec::new();
676 for (id, t) in &summaries[from..] {
677 match self.staging.load_segment_header(*id, stream).await {
678 Ok(hdr) => versions.push((*t, *id, hdr.s_inode)),
679 Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::InvalidData) => {
681 debug!("prune: {} has no readable summary ({}); not a version to keep", id, e);
682 },
683 Err(e) => return Err(e),
684 }
685 }
686 debug!("prune window from {}: versions {:?}", cutoff, versions.iter().map(|(t, _, v)| (v.i_last_cno, *t)).collect::<Vec<_>>());
687 let opened = versions.iter().filter(|(t, _, _)| *t < cutoff).map(|(t, _, _)| *t).max();
689 Ok(versions.into_iter()
690 .filter(|(t, _, _)| opened.is_none_or(|o| *t >= o))
691 .map(|(_, id, v)| (id, v))
692 .collect())
693 }
694
695 pub async fn prune_with(&self, low: Cno, high: Cno, opts: &PruneOptions) -> Result<Vec<SegmentId>> {
698 let (_, unref) = self.collect_within(low, high, opts.grace, opts.judge_attempts).await?;
699 if opts.dry_run {
700 return Ok(unref);
701 }
702 let delete_keys = unref.iter()
703 .map(|segid| format!("{}/{}", self.root_path, Segment::segid_to_staging_file_id(*segid)))
704 .collect::<Vec<String>>();
705 debug!("unreferenced segments to delete: {:?}", delete_keys);
706 Self::do_delete_objects(&self.client, &self.bucket, delete_keys).await?;
707 Ok(unref)
708 }
709
710 pub(crate) async fn reachable_objects(&self, view: &ContainerView, root: InodeRaw) -> Result<BTreeSet<SegmentId>> {
712 let loader = S3BlockLoader::new(
713 &self.client, &self.bucket, &self.root_path,
714 Arc::new(ReadTiming::default()),
715 );
716 let meta_block_size = view.meta_block_size;
717 let join = tokio::task::spawn_blocking(move || -> Result<BTreeSet<BlockPtr>> {
718 walk_roots(&loader, meta_block_size, &[root], BTreeSet::new())
719 });
720 let ptrs = match join.await {
721 Ok(inner) => inner?,
722 Err(join_err) => return Err(Error::other(format!("bmap walk task failed to join: {}", join_err))),
723 };
724 Ok(ptrs.iter().map(|p| view.object_of(p)).collect())
725 }
726
727 async fn walk_more(&self, view: &ContainerView, roots: Vec<InodeRaw>) -> Result<BTreeSet<BlockPtr>> {
731 let roots: Vec<InodeRaw> = roots.into_iter()
732 .filter(|r| r.i_bmap != view.walked_root().i_bmap)
733 .collect();
734 if roots.is_empty() {
735 return Ok(BTreeSet::new());
736 }
737 let loader = S3BlockLoader::new(
738 &self.client, &self.bucket, &self.root_path,
739 Arc::new(ReadTiming::default()),
740 );
741 let known = view.live.meta.clone();
742 let meta_block_size = view.meta_block_size;
743 let join = tokio::task::spawn_blocking(move || -> Result<BTreeSet<BlockPtr>> {
744 walk_roots(&loader, meta_block_size, &roots, known)
745 });
746 match join.await {
747 Ok(inner) => inner,
748 Err(join_err) => Err(Error::other(format!("bmap walk task failed to join: {}", join_err))),
749 }
750 }
751}
752
753fn prefetch_nodes(loader: &S3BlockLoader, meta_block_size: usize, root: &InodeRaw)
756 -> Result<std::collections::HashMap<BlockPtr, Vec<u8>>>
757{
758 use btree_ondisk::node::{BtreeNode, BTREE_NODE_LEVEL_MIN};
759 let handle = tokio::runtime::Handle::current();
760 let mut nodes = std::collections::HashMap::new();
761 let top = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&root.i_bmap)?;
762 if !top.is_large() || top.get_level() == BTREE_NODE_LEVEL_MIN {
763 return Ok(nodes);
764 }
765 let ud = top.get_userdata();
766 let mut frontier: Vec<BlockPtr> = (0..top.get_nchild()).map(|i| *top.get_val::<BlockPtr>(i))
767 .filter(BlockPtrFormat::is_on_staging).collect();
768 while !frontier.is_empty() {
769 let ask: Vec<BlockPtr> = frontier.drain(..).filter(|p| !nodes.contains_key(p)).collect();
770 let mut bufs: Vec<Vec<u8>> = vec![vec![0u8; meta_block_size]; ask.len()];
771 let extra = handle.block_on(loader.read_batch(&ask, &mut bufs, ud))?;
772 for (p, b) in ask.into_iter().zip(bufs).chain(extra) {
773 let node = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&b)?;
774 if node.get_level() > BTREE_NODE_LEVEL_MIN {
775 frontier.extend((0..node.get_nchild()).map(|i| *node.get_val::<BlockPtr>(i))
776 .filter(BlockPtrFormat::is_on_staging));
777 }
778 nodes.insert(p, b);
779 }
780 }
781 Ok(nodes)
782}
783
784#[derive(Clone)]
786pub(crate) struct Prefetched(Arc<std::collections::HashMap<BlockPtr, Vec<u8>>>);
787
788impl btree_ondisk::NodeCache<BlockPtr> for Prefetched {
789 fn push(&self, _: &BlockPtr, _: &[u8]) {}
790 async fn load(&self, p: BlockPtr, data: &mut [u8]) -> Result<bool> {
791 match self.0.get(&p) {
792 Some(b) => { data.copy_from_slice(b); Ok(true) },
793 None => Ok(false),
794 }
795 }
796 fn invalid(&self, _: &BlockPtr) {}
797 fn evict(&self) {}
798 fn get_stats(&self) -> btree_ondisk::NodeTieredCacheStats { btree_ondisk::NodeTieredCacheStats::default() }
799 fn shutdown(&self) {}
800 async fn reset(&self) -> Result<()> { Ok(()) }
801}
802
803fn walk_roots(loader: &S3BlockLoader, meta_block_size: usize, roots: &[InodeRaw], mut known: BTreeSet<BlockPtr>)
807 -> Result<BTreeSet<BlockPtr>>
808{
809 use btree_ondisk::node::{BtreeNode, DirectNode, BTREE_NODE_LEVEL_MIN};
810 let handle = tokio::runtime::Handle::current();
811 let mut found = BTreeSet::new();
812 for root in roots {
813 let node = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&root.i_bmap)?;
814 let ud = node.get_userdata();
815 let mut frontier: Vec<BlockPtr> = Vec::new();
817 if !node.is_large() {
818 let direct = DirectNode::<BlockPtr>::from_slice_ref(&root.i_bmap)?;
819 for i in 0..direct.get_capacity() {
820 found.insert(*direct.get_val(i));
821 }
822 } else {
823 let leaf = node.get_level() == BTREE_NODE_LEVEL_MIN;
824 for i in 0..node.get_nchild() {
825 let v = *node.get_val::<BlockPtr>(i);
826 if leaf {
827 found.insert(v);
828 } else if known.insert(v) {
829 found.insert(v);
830 frontier.push(v);
831 }
832 }
833 }
834 let mut side: std::collections::HashMap<BlockPtr, Vec<u8>> = std::collections::HashMap::new();
835 while !frontier.is_empty() {
836 let mut bufs: Vec<Vec<u8>> = Vec::with_capacity(frontier.len());
837 let mut ask: Vec<BlockPtr> = Vec::new();
838 let mut have: Vec<(BlockPtr, Vec<u8>)> = Vec::new();
839 for p in frontier.drain(..) {
840 match side.remove(&p) {
841 Some(b) => have.push((p, b)),
842 None => { ask.push(p); bufs.push(vec![0u8; meta_block_size]); },
843 }
844 }
845 if !ask.is_empty() {
846 for (p, b) in handle.block_on(loader.read_batch(&ask, &mut bufs, ud))? {
847 side.insert(p, b);
848 }
849 have.extend(ask.into_iter().zip(bufs));
850 }
851 for (_, bytes) in have {
852 let node = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&bytes)?;
853 let leaf = node.get_level() == BTREE_NODE_LEVEL_MIN;
854 for i in 0..node.get_nchild() {
855 let v = *node.get_val::<BlockPtr>(i);
856 if leaf {
857 found.insert(v);
858 } else if known.insert(v) {
859 found.insert(v);
860 frontier.push(v);
861 }
862 }
863 }
864 }
865 }
866 found.retain(BlockPtrFormat::is_on_staging);
867 Ok(found)
868}
869
870#[derive(Clone, Debug)]
890pub struct PruneOptions {
891 pub grace: std::time::Duration,
894 pub dry_run: bool,
896 pub judge_attempts: usize,
900}
901
902impl Default for PruneOptions {
903 fn default() -> Self {
904 Self { grace: std::time::Duration::ZERO, dry_run: false, judge_attempts: 3 }
905 }
906}
907
908pub(crate) struct LivePtrs {
910 pub(crate) all: BTreeSet<BlockPtr>,
911 pub(crate) meta: BTreeSet<BlockPtr>,
912 pub(crate) windows: Vec<(BlockIndex, usize)>,
916 pub(crate) node_keys: BTreeMap<BlockPtr, (BlockIndex, BlockPtr)>,
919}
920
921pub(crate) const DATA_WINDOW_BLOCKS: usize = 64 * 1024;
924
925#[derive(Default)]
927pub(crate) struct ObjectListing {
928 pub(crate) objects: Vec<(SegmentId, u64)>,
930 pub(crate) modified: std::collections::BTreeMap<SegmentId, i64>,
932 pub(crate) foreign: usize,
935 pub(crate) foreign_sample: Option<String>,
936}
937
938pub(crate) struct ContainerView {
940 pub(crate) low: Cno,
941 pub(crate) high_cno: Cno,
942 pub(crate) stored: InodeRaw,
944 pub(crate) walked_stored: bool,
947 pub(crate) walked: InodeRaw,
949 pub(crate) compaction: StoredCompaction,
951 pub(crate) latest_compacted: bool,
954 pub(crate) fmt: BlockPtrFormat,
955 pub(crate) high_summary: SegmentId,
956 pub(crate) data_block_size: usize,
957 pub(crate) meta_block_size: usize,
958 pub(crate) live: LivePtrs,
959 pub(crate) listing: ObjectListing,
960}
961
962impl ContainerView {
963 pub(crate) fn attached_root(&self) -> Result<Option<InodeRaw>> {
970 let root = |p: &PendingCompaction| {
971 let mut r = self.stored;
972 r.i_bmap = p.root;
973 r
974 };
975 match &self.compaction {
976 StoredCompaction::Pending(p) => Ok(Some(root(p))),
977 StoredCompaction::Unreadable(why) => Err(Error::new(ErrorKind::InvalidData, format!(
978 "the inode object's compaction metadata does not read ({}); refusing to judge what \
979 an attached compaction reads through", why))),
980 StoredCompaction::None if self.stored.is_compaction_pending() => Err(Error::new(ErrorKind::InvalidData,
981 "the inode says a compaction is attached and its object has no compaction metadata; \
982 refusing to judge what that compaction reads through")),
983 StoredCompaction::None => Ok(None),
984 }
985 }
986
987 pub(crate) fn walked_root(&self) -> &InodeRaw {
988 if self.walked_stored { &self.stored } else { &self.walked }
989 }
990
991 pub(crate) fn object_ids(&self) -> Vec<SegmentId> {
992 self.listing.objects.iter().map(|(segid, _)| *segid).collect()
993 }
994
995 pub(crate) fn referenced_objects(&self) -> BTreeSet<SegmentId> {
997 self.live.all.iter()
998 .map(|p| BlockPtrFormat::decode(p, &self.fmt).0)
999 .collect()
1000 }
1001
1002 pub(crate) fn object_of(&self, blkptr: &BlockPtr) -> SegmentId {
1004 BlockPtrFormat::decode(blkptr, &self.fmt).0
1005 }
1006}
1007
1008fn trim_root_uri(root_uri: &str) -> &str {
1014 match root_uri.strip_suffix('/') {
1015 Some(r) if !r.ends_with(":/") => r,
1016 _ => root_uri,
1017 }
1018}
1019
1020const S_IFMT: u32 = 0o170000;
1023const S_IFCHR: u32 = 0o020000;
1024const S_IFBLK: u32 = 0o060000;
1025
1026fn refuse_unsegmented(raw: &InodeRaw) -> Result<()> {
1035 let fmt = raw.i_mode & S_IFMT;
1036 let what = if raw.is_inline() {
1037 Some("an inline file, whose data lives in the inode")
1038 } else if fmt == S_IFCHR || fmt == S_IFBLK {
1039 Some("a device node, which stores rdev where a checkpoint number would be")
1040 } else {
1041 None
1042 };
1043 match what {
1044 Some(what) => Err(Error::new(
1045 ErrorKind::InvalidInput,
1046 format!("this container is {}: it has no segments to collect, prune or compact", what),
1047 )),
1048 None => Ok(()),
1049 }
1050}
1051
1052fn container_ptr_format(raw_inode: &InodeRaw) -> Result<BlockPtrFormat> {
1066 if raw_inode.i_meta_config == 0 {
1067 return Ok(BlockPtrFormat::MicroGroup);
1068 }
1069 HyperFileMetaConfig::try_from_u32(raw_inode.i_meta_config)
1070 .map(|cfg| cfg.block_ptr_format)
1071 .map_err(|e| Error::new(
1072 ErrorKind::Unsupported,
1073 format!(
1074 "the container's inode records a format this build cannot read \
1075 (meta config {:#x}: {}); a cleaner built against an older hyperfile \
1076 must not walk it, since it would misread every pointer",
1077 raw_inode.i_meta_config, e,
1078 ),
1079 ))
1080}
1081
1082fn summary_obj(cno: Cno, fmt: &BlockPtrFormat) -> SegmentId {
1084 let segid = SegmentId::new_from_cno(cno);
1085 if fmt.is_parted() {
1086 segid.at_part(Segment::SUMMARY_PART)
1087 } else {
1088 segid
1089 }
1090}
1091
1092fn parse_segment_object_name(name: &str) -> Option<SegmentId> {
1098 if name.contains('/') {
1101 return None;
1102 }
1103 let (seq_str, part_str) = match name.split_once('.') {
1104 Some((seq, part)) => (seq, Some(part)),
1105 None => (name, None),
1106 };
1107 if seq_str.len() != 10 || !seq_str.bytes().all(|b| b.is_ascii_digit()) {
1108 return None;
1109 }
1110 let seq_id = seq_str.parse::<u32>().ok()?;
1113 match part_str {
1114 None => Some(SegmentId::new(seq_id)),
1115 Some(p) => {
1116 if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
1117 return None;
1118 }
1119 Some(SegmentId::with_part(seq_id, p.parse::<u16>().ok()?))
1120 },
1121 }
1122}
1123
1124fn partition_objects(
1149 existing: &[SegmentId],
1150 referenced: &BTreeSet<SegmentId>,
1151 low: Cno,
1152 high: Cno,
1153 high_summary: SegmentId,
1154) -> (Vec<SegmentId>, Vec<SegmentId>) {
1155 let mut unref = Vec::new();
1156 for obj in existing {
1157 let cno = obj.as_cno();
1158 if cno < low || cno > high {
1159 continue;
1160 }
1161 if referenced.contains(obj) {
1162 continue;
1163 }
1164 if *obj == high_summary {
1165 continue;
1166 }
1167 unref.push(*obj);
1168 }
1169 let v_ref = referenced.iter().copied().collect::<Vec<SegmentId>>();
1170 (v_ref, unref)
1171}
1172
1173fn validate_segid_range(low: Cno, high_cno: Cno) -> Result<()> {
1192 if low > high_cno {
1193 return Err(Error::new(
1194 ErrorKind::InvalidInput,
1195 format!("invalid segment range [{}, {}]", low, high_cno),
1196 ));
1197 }
1198 if high_cno > u32::MAX as Cno {
1199 return Err(Error::new(
1200 ErrorKind::InvalidInput,
1201 format!("checkpoint {} is past what a block pointer can name ({})",
1202 high_cno, u32::MAX),
1203 ));
1204 }
1205 Ok(())
1206}
1207
1208impl Cleaner for S3Cleaner {
1209 async fn collect(
1210 &self,
1211 low: Cno,
1212 high: Cno,
1213 ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
1214 self.collect_unref_seg(low, high).await
1215 }
1216
1217 async fn prune(&self, low: Cno, high: Cno) -> Result<()> {
1221 let (_, non_ref) = self.collect_unref_seg(low, high).await?;
1222 let delete_keys = non_ref.iter()
1223 .map(|segid| format!(
1224 "{}/{}",
1225 self.root_path,
1226 Segment::segid_to_staging_file_id(*segid),
1227 ))
1228 .collect::<Vec<String>>();
1229 debug!("unreferenced segments to delete: {:?}", delete_keys);
1230 Self::do_delete_objects(&self.client, &self.bucket, delete_keys).await
1231 }
1232}
1233
1234#[cfg(test)]
1235mod tests {
1236 use super::*;
1237
1238 #[tokio::test]
1242 async fn delete_empty_keys_is_noop() {
1243 let cfg = aws_config::load_from_env().await;
1244 let client = Client::new(&cfg);
1245 let r = S3Cleaner::do_delete_objects(&client, "any-bucket", Vec::new()).await;
1247 assert!(r.is_ok(), "empty key list should not call S3");
1248 }
1249
1250 #[test]
1255 fn segid_range_accepts_a_single_checkpoint() {
1256 assert!(validate_segid_range(1, 1).is_ok());
1257 }
1258
1259 #[test]
1260 fn segid_range_accepts_a_normal_span() {
1261 assert!(validate_segid_range(1, 5).is_ok());
1262 }
1263
1264 #[test]
1267 fn segid_range_rejects_an_empty_span() {
1268 for (low, high) in [(5u64, 3u64), (2, 1), (1, 0)] {
1269 let e = validate_segid_range(low, high)
1270 .expect_err("low > high must be rejected");
1271 assert_eq!(e.kind(), ErrorKind::InvalidInput);
1272 assert!(
1273 e.to_string().contains(&format!("[{}, {}]", low, high)),
1274 "error should name the range, got {:?}", e.to_string(),
1275 );
1276 }
1277 }
1278
1279 #[test]
1280 fn a_trailing_slash_is_trimmed_but_not_the_schemes() {
1281 assert_eq!(trim_root_uri("s3://b/k/"), "s3://b/k");
1282 assert_eq!(trim_root_uri("s3://b/k"), "s3://b/k");
1283 assert_eq!(trim_root_uri("s3://"), "s3://");
1284 assert_eq!(trim_root_uri("S3://"), "S3://");
1285 assert_eq!(trim_root_uri(""), "");
1286 }
1287
1288 #[test]
1292 fn an_unknown_format_is_refused_not_guessed() {
1293 let legacy = InodeRaw { i_meta_config: 0, ..Default::default() };
1294 assert_eq!(container_ptr_format(&legacy).unwrap(), BlockPtrFormat::MicroGroup);
1295
1296 for fmt in [BlockPtrFormat::MicroGroup, BlockPtrFormat::PartedSegment,
1297 BlockPtrFormat::StreamSegment] {
1298 let cfg = HyperFileMetaConfig::new(56, 4096, 4096, fmt);
1299 let raw = InodeRaw { i_meta_config: cfg.as_u32(), ..Default::default() };
1300 assert_eq!(container_ptr_format(&raw).unwrap(), fmt);
1301 }
1302
1303 let future = HyperFileMetaConfig::new(56, 4096, 4096, BlockPtrFormat::PartedSegment)
1304 .as_u32() & !0xFF | 0x7F;
1305 let raw = InodeRaw { i_meta_config: future, ..Default::default() };
1306 let e = container_ptr_format(&raw).expect_err("an unknown format byte must be refused");
1307 assert_eq!(e.kind(), ErrorKind::Unsupported);
1308 }
1309
1310 #[test]
1314 fn an_inode_without_segments_is_refused() {
1315 let mut inline = InodeRaw { i_mode: 0o100644, ..Default::default() };
1316 inline.set_inline(b"hello");
1317 let e = refuse_unsegmented(&inline).expect_err("inline must be refused");
1318 assert_eq!(e.kind(), ErrorKind::InvalidInput);
1319 assert!(e.to_string().contains("inline"), "{}", e);
1320
1321 for mode in [0o020644u32, 0o060644] {
1322 let dev = InodeRaw { i_mode: mode, ..Default::default() };
1323 let e = refuse_unsegmented(&dev).expect_err("a device node must be refused");
1324 assert!(e.to_string().contains("device"), "{}", e);
1325 }
1326
1327 for mode in [0o100644u32, 0o040755, 0o120777] {
1328 let ok = InodeRaw { i_mode: mode, ..Default::default() };
1329 assert!(refuse_unsegmented(&ok).is_ok(), "mode {:o} has segments", mode);
1330 }
1331 }
1332
1333 #[test]
1336 fn segid_range_rejects_a_checkpoint_past_a_pointer() {
1337 let e = validate_segid_range(1, u32::MAX as Cno + 1)
1338 .expect_err("a cno past u32::MAX must be rejected");
1339 assert_eq!(e.kind(), ErrorKind::InvalidInput);
1340 assert!(validate_segid_range(1, u32::MAX as Cno).is_ok());
1341 }
1342
1343 #[test]
1346 fn object_names_round_trip_through_the_parser() {
1347 for segid in [
1348 SegmentId::new(1),
1349 SegmentId::new(4294967295),
1350 SegmentId::with_part(7, 0),
1351 SegmentId::with_part(7, 16383),
1352 ] {
1353 let name = Segment::segid_to_staging_file_id(segid);
1354 assert_eq!(parse_segment_object_name(&name), Some(segid),
1355 "name {:?} did not parse back", name);
1356 }
1357 }
1358
1359 #[test]
1363 fn a_bare_name_is_not_part_zero() {
1364 assert_eq!(parse_segment_object_name("0000000007"), Some(SegmentId::new(7)));
1365 assert_eq!(parse_segment_object_name("0000000007.0"),
1366 Some(SegmentId::with_part(7, 0)));
1367 }
1368
1369 #[test]
1370 fn keys_that_are_not_segment_objects_are_skipped() {
1371 for name in [
1372 "inode", "wal/0000000001", "0000000001/0_0_4096",
1375 "000000001", "00000000012", "9999999999", "0000000001.", "0000000001.x",
1380 "0000000001.65536", "0000000001.0.1",
1382 "",
1383 ] {
1384 assert_eq!(parse_segment_object_name(name), None,
1385 "{:?} should not be read as a segment object", name);
1386 }
1387 }
1388
1389 fn partition(
1392 existing: &[SegmentId],
1393 referenced: &[SegmentId],
1394 low: Cno,
1395 high: Cno,
1396 high_summary: SegmentId,
1397 ) -> Vec<SegmentId> {
1398 let set: BTreeSet<SegmentId> = referenced.iter().copied().collect();
1399 let (_, unref) = partition_objects(existing, &set, low, high, high_summary);
1400 unref
1401 }
1402
1403 #[test]
1406 fn an_unreferenced_checkpoint_is_reclaimable() {
1407 let existing = [SegmentId::new(1), SegmentId::new(2), SegmentId::new(3)];
1408 let unref = partition(&existing, &[SegmentId::new(3)], 1, 3, SegmentId::new(3));
1409 assert_eq!(unref, vec![SegmentId::new(1), SegmentId::new(2)]);
1410 }
1411
1412 #[test]
1415 fn objects_outside_the_range_are_left_alone() {
1416 let existing = [
1417 SegmentId::new(1), SegmentId::new(2), SegmentId::new(3), SegmentId::new(4),
1418 ];
1419 let unref = partition(&existing, &[], 2, 3, SegmentId::new(9));
1420 assert_eq!(unref, vec![SegmentId::new(2), SegmentId::new(3)]);
1421 }
1422
1423 #[test]
1426 fn the_summary_of_high_is_kept_even_when_nothing_points_into_it() {
1427 let existing = [SegmentId::new(1), SegmentId::new(2)];
1428 let unref = partition(&existing, &[], 1, 2, SegmentId::new(2));
1429 assert_eq!(unref, vec![SegmentId::new(1)]);
1430
1431 let existing = [SegmentId::with_part(2, 0), SegmentId::with_part(2, 1)];
1433 let unref = partition(&existing, &[], 1, 2, SegmentId::with_part(2, 0));
1434 assert_eq!(unref, vec![SegmentId::with_part(2, 1)]);
1435 }
1436
1437 #[test]
1441 fn an_abandoned_partial_is_reclaimable_while_its_checkpoint_lives() {
1442 let existing = [
1443 SegmentId::with_part(5, 0), SegmentId::with_part(5, 1), SegmentId::with_part(5, 2), ];
1447 let referenced = [SegmentId::with_part(5, 0), SegmentId::with_part(5, 1)];
1448 let unref = partition(&existing, &referenced, 1, 9, SegmentId::with_part(9, 0));
1449 assert_eq!(unref, vec![SegmentId::with_part(5, 2)]);
1450 }
1451
1452 #[test]
1455 fn the_summary_part_nothing_points_into_goes_while_its_checkpoint_lives() {
1456 let existing = [SegmentId::with_part(4, 0), SegmentId::with_part(4, 3)];
1457 let unref = partition(&existing, &[SegmentId::with_part(4, 3)], 1, 9,
1458 SegmentId::with_part(9, 0));
1459 assert_eq!(unref, vec![SegmentId::with_part(4, 0)]);
1460 }
1461
1462 #[test]
1465 fn a_wholly_dead_parted_checkpoint_goes_including_its_summary() {
1466 let existing = [
1467 SegmentId::with_part(4, 0), SegmentId::with_part(4, 1),
1468 SegmentId::with_part(6, 0),
1469 ];
1470 let unref = partition(&existing, &[SegmentId::with_part(6, 0)], 1, 9,
1471 SegmentId::with_part(6, 0));
1472 assert_eq!(unref, vec![SegmentId::with_part(4, 0), SegmentId::with_part(4, 1)]);
1473 }
1474}