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 compaction = inode_state.as_ref().map(|s| s.compaction.clone()).unwrap_or_default();
430 let latest_cno = Inode::from_raw(&raw_inode, inode_state).get_last_cno();
431 let high_cno = if high == 0 { latest_cno } else { high };
432
433 debug!("view of container low: {}, high: {}, format: {:?}", low, high_cno, fmt);
434 validate_segid_range(low, high_cno)?;
435
436 let high_summary = summary_obj(high_cno, &fmt);
443 let ss = self.load_segment_sum(high_summary).await?;
444 if !ss.hdr.has_magic() || ss.hdr.s_cno != high_cno {
449 return Err(Error::new(
450 ErrorKind::InvalidData,
451 format!(
452 "{} does not read as checkpoint {}'s summary (magic {:#x}, checkpoint {})",
453 high_summary, high_cno, ss.hdr.s_magic, ss.hdr.s_cno,
454 ),
455 ));
456 }
457 let walked_stored = high_cno == latest_cno;
467 let ss_inode = if walked_stored { raw_inode } else { ss.hdr.s_inode };
468 let meta_block_size = 1usize << ss.hdr.s_meta_blk_shift;
473 let data_block_size = 1usize << ss.hdr.s_data_blk_shift;
474
475 let timing = Arc::new(ReadTiming::default());
482 let loader = S3BlockLoader::new(
483 &self.client, &self.bucket, &self.root_path, timing.clone(),
484 );
485 let join = tokio::task::spawn_blocking(move || -> Result<LivePtrs> {
486 let nodes = prefetch_nodes(&loader, meta_block_size, &ss_inode)?;
489 let bmap = BMap::<BlockIndex, BlockPtr, BlockPtr, S3BlockLoader, Prefetched>
490 ::read(&ss_inode.i_bmap, meta_block_size, loader, Prefetched(Arc::new(nodes)))?;
491 let live = Self::walk_live_ptrs(bmap);
492 debug!("map walk: {} node reads", timing.snapshot().meta_gets);
493 live
494 });
495 let live = match join.await {
496 Ok(inner) => inner?,
497 Err(join_err) => {
498 return Err(Error::other(
499 format!("bmap walk task failed to join: {}", join_err),
500 ));
501 }
502 };
503
504 let listing = self.list_segment_objects().await?;
505 if !listing.objects.iter().any(|(segid, _)| *segid == high_summary) {
509 return Err(Error::new(
510 ErrorKind::InvalidData,
511 format!(
512 "the listing has no object named {}, the summary just read; \
513 refusing to judge what is referenced",
514 high_summary,
515 ),
516 ));
517 }
518 Ok(ContainerView {
519 low,
520 high_cno,
521 stored: raw_inode,
522 walked_stored,
523 walked: ss_inode,
524 compaction,
525 fmt,
526 high_summary,
527 data_block_size,
528 meta_block_size,
529 live,
530 listing,
531 })
532 }
533
534 async fn collect_unref_seg(
544 &self,
545 low: Cno,
546 high: Cno,
547 ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
548 self.collect_within(low, high, std::time::Duration::ZERO, 1).await
549 }
550
551 async fn collect_within(
555 &self,
556 low: Cno,
557 high: Cno,
558 grace: std::time::Duration,
559 attempts: usize,
560 ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
561 let attempts = attempts.max(1);
569 for _ in 0..attempts {
570 let (judged, attached_before) = self.collect_within_once(low, high, grace).await?;
571 if grace.is_zero() {
572 return Ok(judged);
573 }
574 let (_, state) = self.load_raw_inode().await?;
575 let attached_now = state.map(|s| s.compaction).unwrap_or_default();
576 if attached_now == attached_before {
577 return Ok(judged);
578 }
579 debug!("prune: a compaction was attached while judging; judging again");
580 }
581 Err(Error::new(ErrorKind::ResourceBusy, format!(
582 "compactions were attached while prune judged, {} times; try again", attempts)))
583 }
584
585 async fn collect_within_once(
588 &self,
589 low: Cno,
590 high: Cno,
591 grace: std::time::Duration,
592 ) -> Result<((Vec<SegmentId>, Vec<SegmentId>), StoredCompaction)> {
593 let view = self.view(low, high).await?;
594 let attached_before = view.compaction.clone();
595 if !grace.is_zero() {
596 let hook = self.pause_after_view.lock().unwrap().clone();
597 if let Some(hook) = hook {
598 hook().await;
599 }
600 }
601 let mut roots = Vec::new();
604 if !view.walked_stored {
605 roots.push(view.stored);
606 }
607 if let Some(root) = view.attached_root()? {
610 roots.push(root);
611 }
612 let mut young = BTreeSet::new();
613 if !grace.is_zero() {
614 let (now, _) = self.staging.load_segment_timestamp(SegmentId::new_from_cno(view.high_cno)).await?;
617 let cutoff = now.saturating_sub(grace.as_secs().min(i64::MAX as u64) as i64);
618 young = view.listing.modified.iter().filter(|(_, t)| **t >= cutoff).map(|(s, _)| *s).collect();
619 let versions = self.versions_since(&view, cutoff).await?;
620 young.extend(versions.iter().map(|(id, _)| *id));
625 roots.extend(versions.into_iter().map(|(_, v)| v));
626 }
627 debug!("prune roots: {:?}", roots.iter().map(|r| (r.i_last_cno, r.fingerprint())).collect::<Vec<_>>());
628 let more = match self.walk_more(&view, roots.clone()).await {
629 Ok(m) => m,
630 Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::InvalidData) => {
631 let attached = view.attached_root().ok().flatten().map(|r| r.i_bmap);
632 for r in &roots {
633 if let Err(e2) = self.walk_more(&view, vec![*r]).await {
634 error!("prune: root of checkpoint {} (fingerprint {:#x}, {}) reaches a deleted object: {}", r.i_last_cno,
635 r.fingerprint(), if Some(r.i_bmap) == attached { "the attached compaction" } else { "a version" }, e2);
636 }
637 }
638 return Err(e);
639 },
640 Err(e) => return Err(e),
641 };
642 let mut referenced = view.referenced_objects();
643 referenced.extend(more.iter().map(|p| view.object_of(p)));
644 let (v_ref, mut unref) = partition_objects(
645 &view.object_ids(),
646 &referenced,
647 view.low,
648 view.high_cno,
649 view.high_summary,
650 );
651 unref.retain(|o| !young.contains(o));
652 Ok(((v_ref, unref), attached_before))
653 }
654
655 async fn versions_since(&self, view: &ContainerView, cutoff: i64) -> Result<Vec<(SegmentId, InodeRaw)>> {
663 let stream = view.fmt.is_stream();
664 let modified = |id: &SegmentId| view.listing.modified.get(id).copied();
665 let summaries: Vec<(SegmentId, i64)> = view.listing.objects.iter()
666 .map(|(id, _)| *id)
667 .filter(|id| *id == summary_obj(id.as_cno(), &view.fmt))
668 .filter_map(|id| modified(&id).map(|t| (id, t)))
669 .collect();
670 let from = summaries.iter().rposition(|(_, t)| *t < cutoff).unwrap_or(0);
673 let mut versions: Vec<(i64, SegmentId, InodeRaw)> = Vec::new();
674 for (id, t) in &summaries[from..] {
675 match self.staging.load_segment_header(*id, stream).await {
676 Ok(hdr) => versions.push((*t, *id, hdr.s_inode)),
677 Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::InvalidData) => {
679 debug!("prune: {} has no readable summary ({}); not a version to keep", id, e);
680 },
681 Err(e) => return Err(e),
682 }
683 }
684 debug!("prune window from {}: versions {:?}", cutoff, versions.iter().map(|(t, _, v)| (v.i_last_cno, *t)).collect::<Vec<_>>());
685 let opened = versions.iter().filter(|(t, _, _)| *t < cutoff).map(|(t, _, _)| *t).max();
687 Ok(versions.into_iter()
688 .filter(|(t, _, _)| opened.is_none_or(|o| *t >= o))
689 .map(|(_, id, v)| (id, v))
690 .collect())
691 }
692
693 pub async fn prune_with(&self, low: Cno, high: Cno, opts: &PruneOptions) -> Result<Vec<SegmentId>> {
696 let (_, unref) = self.collect_within(low, high, opts.grace, opts.judge_attempts).await?;
697 if opts.dry_run {
698 return Ok(unref);
699 }
700 let delete_keys = unref.iter()
701 .map(|segid| format!("{}/{}", self.root_path, Segment::segid_to_staging_file_id(*segid)))
702 .collect::<Vec<String>>();
703 debug!("unreferenced segments to delete: {:?}", delete_keys);
704 Self::do_delete_objects(&self.client, &self.bucket, delete_keys).await?;
705 Ok(unref)
706 }
707
708 pub(crate) async fn reachable_objects(&self, view: &ContainerView, root: InodeRaw) -> Result<BTreeSet<SegmentId>> {
710 let loader = S3BlockLoader::new(
711 &self.client, &self.bucket, &self.root_path,
712 Arc::new(ReadTiming::default()),
713 );
714 let meta_block_size = view.meta_block_size;
715 let join = tokio::task::spawn_blocking(move || -> Result<BTreeSet<BlockPtr>> {
716 walk_roots(&loader, meta_block_size, &[root], BTreeSet::new())
717 });
718 let ptrs = match join.await {
719 Ok(inner) => inner?,
720 Err(join_err) => return Err(Error::other(format!("bmap walk task failed to join: {}", join_err))),
721 };
722 Ok(ptrs.iter().map(|p| view.object_of(p)).collect())
723 }
724
725 async fn walk_more(&self, view: &ContainerView, roots: Vec<InodeRaw>) -> Result<BTreeSet<BlockPtr>> {
729 let roots: Vec<InodeRaw> = roots.into_iter()
730 .filter(|r| r.i_bmap != view.walked_root().i_bmap)
731 .collect();
732 if roots.is_empty() {
733 return Ok(BTreeSet::new());
734 }
735 let loader = S3BlockLoader::new(
736 &self.client, &self.bucket, &self.root_path,
737 Arc::new(ReadTiming::default()),
738 );
739 let known = view.live.meta.clone();
740 let meta_block_size = view.meta_block_size;
741 let join = tokio::task::spawn_blocking(move || -> Result<BTreeSet<BlockPtr>> {
742 walk_roots(&loader, meta_block_size, &roots, known)
743 });
744 match join.await {
745 Ok(inner) => inner,
746 Err(join_err) => Err(Error::other(format!("bmap walk task failed to join: {}", join_err))),
747 }
748 }
749}
750
751fn prefetch_nodes(loader: &S3BlockLoader, meta_block_size: usize, root: &InodeRaw)
754 -> Result<std::collections::HashMap<BlockPtr, Vec<u8>>>
755{
756 use btree_ondisk::node::{BtreeNode, BTREE_NODE_LEVEL_MIN};
757 let handle = tokio::runtime::Handle::current();
758 let mut nodes = std::collections::HashMap::new();
759 let top = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&root.i_bmap)?;
760 if !top.is_large() || top.get_level() == BTREE_NODE_LEVEL_MIN {
761 return Ok(nodes);
762 }
763 let ud = top.get_userdata();
764 let mut frontier: Vec<BlockPtr> = (0..top.get_nchild()).map(|i| *top.get_val::<BlockPtr>(i))
765 .filter(BlockPtrFormat::is_on_staging).collect();
766 while !frontier.is_empty() {
767 let level: Vec<BlockPtr> = std::mem::take(&mut frontier);
768 let mut ask: Vec<BlockPtr> = level.iter().copied().filter(|p| !nodes.contains_key(p)).collect();
769 ask.sort_unstable();
770 ask.dedup();
771 let mut bufs: Vec<Vec<u8>> = vec![vec![0u8; meta_block_size]; ask.len()];
772 let extra = handle.block_on(loader.read_batch(&ask, &mut bufs, ud))?;
773 for (p, b) in ask.into_iter().zip(bufs).chain(extra) {
778 nodes.entry(p).or_insert(b);
779 }
780 for p in level {
781 let node = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&nodes[&p])?;
782 if node.get_level() > BTREE_NODE_LEVEL_MIN {
783 frontier.extend((0..node.get_nchild()).map(|i| *node.get_val::<BlockPtr>(i))
784 .filter(BlockPtrFormat::is_on_staging));
785 }
786 }
787 }
788 Ok(nodes)
789}
790
791#[derive(Clone)]
793pub(crate) struct Prefetched(Arc<std::collections::HashMap<BlockPtr, Vec<u8>>>);
794
795impl btree_ondisk::NodeCache<BlockPtr> for Prefetched {
796 fn push(&self, _: &BlockPtr, _: &[u8]) {}
797 async fn load(&self, p: BlockPtr, data: &mut [u8]) -> Result<bool> {
798 match self.0.get(&p) {
799 Some(b) => { data.copy_from_slice(b); Ok(true) },
800 None => Ok(false),
801 }
802 }
803 fn invalid(&self, _: &BlockPtr) {}
804 fn evict(&self) {}
805 fn get_stats(&self) -> btree_ondisk::NodeTieredCacheStats { btree_ondisk::NodeTieredCacheStats::default() }
806 fn shutdown(&self) {}
807 async fn reset(&self) -> Result<()> { Ok(()) }
808}
809
810fn walk_roots(loader: &S3BlockLoader, meta_block_size: usize, roots: &[InodeRaw], mut known: BTreeSet<BlockPtr>)
814 -> Result<BTreeSet<BlockPtr>>
815{
816 use btree_ondisk::node::{BtreeNode, DirectNode, BTREE_NODE_LEVEL_MIN};
817 let handle = tokio::runtime::Handle::current();
818 let mut found = BTreeSet::new();
819 for root in roots {
820 let node = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&root.i_bmap)?;
821 let ud = node.get_userdata();
822 let mut frontier: Vec<BlockPtr> = Vec::new();
824 if !node.is_large() {
825 let direct = DirectNode::<BlockPtr>::from_slice_ref(&root.i_bmap)?;
826 for i in 0..direct.get_capacity() {
827 found.insert(*direct.get_val(i));
828 }
829 } else {
830 let leaf = node.get_level() == BTREE_NODE_LEVEL_MIN;
831 for i in 0..node.get_nchild() {
832 let v = *node.get_val::<BlockPtr>(i);
833 if leaf {
834 found.insert(v);
835 } else if known.insert(v) {
836 found.insert(v);
837 frontier.push(v);
838 }
839 }
840 }
841 let mut side: std::collections::HashMap<BlockPtr, Vec<u8>> = std::collections::HashMap::new();
842 while !frontier.is_empty() {
843 let mut bufs: Vec<Vec<u8>> = Vec::with_capacity(frontier.len());
844 let mut ask: Vec<BlockPtr> = Vec::new();
845 let mut have: Vec<(BlockPtr, Vec<u8>)> = Vec::new();
846 for p in frontier.drain(..) {
847 match side.remove(&p) {
848 Some(b) => have.push((p, b)),
849 None => { ask.push(p); bufs.push(vec![0u8; meta_block_size]); },
850 }
851 }
852 if !ask.is_empty() {
853 for (p, b) in handle.block_on(loader.read_batch(&ask, &mut bufs, ud))? {
854 side.insert(p, b);
855 }
856 have.extend(ask.into_iter().zip(bufs));
857 }
858 for (_, bytes) in have {
859 let node = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&bytes)?;
860 let leaf = node.get_level() == BTREE_NODE_LEVEL_MIN;
861 for i in 0..node.get_nchild() {
862 let v = *node.get_val::<BlockPtr>(i);
863 if leaf {
864 found.insert(v);
865 } else if known.insert(v) {
866 found.insert(v);
867 frontier.push(v);
868 }
869 }
870 }
871 }
872 }
873 found.retain(BlockPtrFormat::is_on_staging);
874 Ok(found)
875}
876
877#[derive(Clone, Debug)]
897pub struct PruneOptions {
898 pub grace: std::time::Duration,
901 pub dry_run: bool,
903 pub judge_attempts: usize,
907}
908
909impl Default for PruneOptions {
910 fn default() -> Self {
911 Self { grace: std::time::Duration::ZERO, dry_run: false, judge_attempts: 3 }
912 }
913}
914
915pub(crate) struct LivePtrs {
917 pub(crate) all: BTreeSet<BlockPtr>,
918 pub(crate) meta: BTreeSet<BlockPtr>,
919 pub(crate) windows: Vec<(BlockIndex, usize)>,
923 pub(crate) node_keys: BTreeMap<BlockPtr, (BlockIndex, BlockPtr)>,
926}
927
928pub(crate) const DATA_WINDOW_BLOCKS: usize = 64 * 1024;
931
932#[derive(Default)]
934pub(crate) struct ObjectListing {
935 pub(crate) objects: Vec<(SegmentId, u64)>,
937 pub(crate) modified: std::collections::BTreeMap<SegmentId, i64>,
939 pub(crate) foreign: usize,
942 pub(crate) foreign_sample: Option<String>,
943}
944
945pub(crate) struct ContainerView {
947 pub(crate) low: Cno,
948 pub(crate) high_cno: Cno,
949 pub(crate) stored: InodeRaw,
951 pub(crate) walked_stored: bool,
954 pub(crate) walked: InodeRaw,
956 pub(crate) compaction: StoredCompaction,
958 pub(crate) fmt: BlockPtrFormat,
959 pub(crate) high_summary: SegmentId,
960 pub(crate) data_block_size: usize,
961 pub(crate) meta_block_size: usize,
962 pub(crate) live: LivePtrs,
963 pub(crate) listing: ObjectListing,
964}
965
966impl ContainerView {
967 pub(crate) fn attached_root(&self) -> Result<Option<InodeRaw>> {
974 let root = |p: &PendingCompaction| {
975 let mut r = self.stored;
976 r.i_bmap = p.root;
977 r
978 };
979 match &self.compaction {
980 StoredCompaction::Pending(p) => Ok(Some(root(p))),
981 StoredCompaction::Unreadable(why) => Err(Error::new(ErrorKind::InvalidData, format!(
982 "the inode object's compaction metadata does not read ({}); refusing to judge what \
983 an attached compaction reads through", why))),
984 StoredCompaction::None if self.stored.is_compaction_pending() => Err(Error::new(ErrorKind::InvalidData,
985 "the inode says a compaction is attached and its object has no compaction metadata; \
986 refusing to judge what that compaction reads through")),
987 StoredCompaction::None => Ok(None),
988 }
989 }
990
991 pub(crate) fn walked_root(&self) -> &InodeRaw {
992 if self.walked_stored { &self.stored } else { &self.walked }
993 }
994
995 pub(crate) fn object_ids(&self) -> Vec<SegmentId> {
996 self.listing.objects.iter().map(|(segid, _)| *segid).collect()
997 }
998
999 pub(crate) fn referenced_objects(&self) -> BTreeSet<SegmentId> {
1001 self.live.all.iter()
1002 .map(|p| BlockPtrFormat::decode(p, &self.fmt).0)
1003 .collect()
1004 }
1005
1006 pub(crate) fn object_of(&self, blkptr: &BlockPtr) -> SegmentId {
1008 BlockPtrFormat::decode(blkptr, &self.fmt).0
1009 }
1010}
1011
1012fn trim_root_uri(root_uri: &str) -> &str {
1018 match root_uri.strip_suffix('/') {
1019 Some(r) if !r.ends_with(":/") => r,
1020 _ => root_uri,
1021 }
1022}
1023
1024const S_IFMT: u32 = 0o170000;
1027const S_IFCHR: u32 = 0o020000;
1028const S_IFBLK: u32 = 0o060000;
1029
1030fn refuse_unsegmented(raw: &InodeRaw) -> Result<()> {
1039 let fmt = raw.i_mode & S_IFMT;
1040 let what = if raw.is_inline() {
1041 Some("an inline file, whose data lives in the inode")
1042 } else if fmt == S_IFCHR || fmt == S_IFBLK {
1043 Some("a device node, which stores rdev where a checkpoint number would be")
1044 } else {
1045 None
1046 };
1047 match what {
1048 Some(what) => Err(Error::new(
1049 ErrorKind::InvalidInput,
1050 format!("this container is {}: it has no segments to collect, prune or compact", what),
1051 )),
1052 None => Ok(()),
1053 }
1054}
1055
1056fn container_ptr_format(raw_inode: &InodeRaw) -> Result<BlockPtrFormat> {
1070 if raw_inode.i_meta_config == 0 {
1071 return Ok(BlockPtrFormat::MicroGroup);
1072 }
1073 HyperFileMetaConfig::try_from_u32(raw_inode.i_meta_config)
1074 .map(|cfg| cfg.block_ptr_format)
1075 .map_err(|e| Error::new(
1076 ErrorKind::Unsupported,
1077 format!(
1078 "the container's inode records a format this build cannot read \
1079 (meta config {:#x}: {}); a cleaner built against an older hyperfile \
1080 must not walk it, since it would misread every pointer",
1081 raw_inode.i_meta_config, e,
1082 ),
1083 ))
1084}
1085
1086fn summary_obj(cno: Cno, fmt: &BlockPtrFormat) -> SegmentId {
1088 let segid = SegmentId::new_from_cno(cno);
1089 if fmt.is_parted() {
1090 segid.at_part(Segment::SUMMARY_PART)
1091 } else {
1092 segid
1093 }
1094}
1095
1096fn parse_segment_object_name(name: &str) -> Option<SegmentId> {
1102 if name.contains('/') {
1105 return None;
1106 }
1107 let (seq_str, part_str) = match name.split_once('.') {
1108 Some((seq, part)) => (seq, Some(part)),
1109 None => (name, None),
1110 };
1111 if seq_str.len() != 10 || !seq_str.bytes().all(|b| b.is_ascii_digit()) {
1112 return None;
1113 }
1114 let seq_id = seq_str.parse::<u32>().ok()?;
1117 match part_str {
1118 None => Some(SegmentId::new(seq_id)),
1119 Some(p) => {
1120 if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
1121 return None;
1122 }
1123 Some(SegmentId::with_part(seq_id, p.parse::<u16>().ok()?))
1124 },
1125 }
1126}
1127
1128fn partition_objects(
1153 existing: &[SegmentId],
1154 referenced: &BTreeSet<SegmentId>,
1155 low: Cno,
1156 high: Cno,
1157 high_summary: SegmentId,
1158) -> (Vec<SegmentId>, Vec<SegmentId>) {
1159 let mut unref = Vec::new();
1160 for obj in existing {
1161 let cno = obj.as_cno();
1162 if cno < low || cno > high {
1163 continue;
1164 }
1165 if referenced.contains(obj) {
1166 continue;
1167 }
1168 if *obj == high_summary {
1169 continue;
1170 }
1171 unref.push(*obj);
1172 }
1173 let v_ref = referenced.iter().copied().collect::<Vec<SegmentId>>();
1174 (v_ref, unref)
1175}
1176
1177fn validate_segid_range(low: Cno, high_cno: Cno) -> Result<()> {
1196 if low > high_cno {
1197 return Err(Error::new(
1198 ErrorKind::InvalidInput,
1199 format!("invalid segment range [{}, {}]", low, high_cno),
1200 ));
1201 }
1202 if high_cno > u32::MAX as Cno {
1203 return Err(Error::new(
1204 ErrorKind::InvalidInput,
1205 format!("checkpoint {} is past what a block pointer can name ({})",
1206 high_cno, u32::MAX),
1207 ));
1208 }
1209 Ok(())
1210}
1211
1212impl Cleaner for S3Cleaner {
1213 async fn collect(
1214 &self,
1215 low: Cno,
1216 high: Cno,
1217 ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
1218 self.collect_unref_seg(low, high).await
1219 }
1220
1221 async fn prune(&self, low: Cno, high: Cno) -> Result<()> {
1225 let (_, non_ref) = self.collect_unref_seg(low, high).await?;
1226 let delete_keys = non_ref.iter()
1227 .map(|segid| format!(
1228 "{}/{}",
1229 self.root_path,
1230 Segment::segid_to_staging_file_id(*segid),
1231 ))
1232 .collect::<Vec<String>>();
1233 debug!("unreferenced segments to delete: {:?}", delete_keys);
1234 Self::do_delete_objects(&self.client, &self.bucket, delete_keys).await
1235 }
1236}
1237
1238#[cfg(test)]
1239mod tests {
1240 use super::*;
1241
1242 #[tokio::test]
1246 async fn delete_empty_keys_is_noop() {
1247 let cfg = aws_config::load_from_env().await;
1248 let client = Client::new(&cfg);
1249 let r = S3Cleaner::do_delete_objects(&client, "any-bucket", Vec::new()).await;
1251 assert!(r.is_ok(), "empty key list should not call S3");
1252 }
1253
1254 #[test]
1259 fn segid_range_accepts_a_single_checkpoint() {
1260 assert!(validate_segid_range(1, 1).is_ok());
1261 }
1262
1263 #[test]
1264 fn segid_range_accepts_a_normal_span() {
1265 assert!(validate_segid_range(1, 5).is_ok());
1266 }
1267
1268 #[test]
1271 fn segid_range_rejects_an_empty_span() {
1272 for (low, high) in [(5u64, 3u64), (2, 1), (1, 0)] {
1273 let e = validate_segid_range(low, high)
1274 .expect_err("low > high must be rejected");
1275 assert_eq!(e.kind(), ErrorKind::InvalidInput);
1276 assert!(
1277 e.to_string().contains(&format!("[{}, {}]", low, high)),
1278 "error should name the range, got {:?}", e.to_string(),
1279 );
1280 }
1281 }
1282
1283 #[test]
1284 fn a_trailing_slash_is_trimmed_but_not_the_schemes() {
1285 assert_eq!(trim_root_uri("s3://b/k/"), "s3://b/k");
1286 assert_eq!(trim_root_uri("s3://b/k"), "s3://b/k");
1287 assert_eq!(trim_root_uri("s3://"), "s3://");
1288 assert_eq!(trim_root_uri("S3://"), "S3://");
1289 assert_eq!(trim_root_uri(""), "");
1290 }
1291
1292 #[test]
1296 fn an_unknown_format_is_refused_not_guessed() {
1297 let legacy = InodeRaw { i_meta_config: 0, ..Default::default() };
1298 assert_eq!(container_ptr_format(&legacy).unwrap(), BlockPtrFormat::MicroGroup);
1299
1300 for fmt in [BlockPtrFormat::MicroGroup, BlockPtrFormat::PartedSegment,
1301 BlockPtrFormat::StreamSegment] {
1302 let cfg = HyperFileMetaConfig::new(56, 4096, 4096, fmt);
1303 let raw = InodeRaw { i_meta_config: cfg.as_u32(), ..Default::default() };
1304 assert_eq!(container_ptr_format(&raw).unwrap(), fmt);
1305 }
1306
1307 let future = HyperFileMetaConfig::new(56, 4096, 4096, BlockPtrFormat::PartedSegment)
1308 .as_u32() & !0xFF | 0x7F;
1309 let raw = InodeRaw { i_meta_config: future, ..Default::default() };
1310 let e = container_ptr_format(&raw).expect_err("an unknown format byte must be refused");
1311 assert_eq!(e.kind(), ErrorKind::Unsupported);
1312 }
1313
1314 #[test]
1318 fn an_inode_without_segments_is_refused() {
1319 let mut inline = InodeRaw { i_mode: 0o100644, ..Default::default() };
1320 inline.set_inline(b"hello");
1321 let e = refuse_unsegmented(&inline).expect_err("inline must be refused");
1322 assert_eq!(e.kind(), ErrorKind::InvalidInput);
1323 assert!(e.to_string().contains("inline"), "{}", e);
1324
1325 for mode in [0o020644u32, 0o060644] {
1326 let dev = InodeRaw { i_mode: mode, ..Default::default() };
1327 let e = refuse_unsegmented(&dev).expect_err("a device node must be refused");
1328 assert!(e.to_string().contains("device"), "{}", e);
1329 }
1330
1331 for mode in [0o100644u32, 0o040755, 0o120777] {
1332 let ok = InodeRaw { i_mode: mode, ..Default::default() };
1333 assert!(refuse_unsegmented(&ok).is_ok(), "mode {:o} has segments", mode);
1334 }
1335 }
1336
1337 #[test]
1340 fn segid_range_rejects_a_checkpoint_past_a_pointer() {
1341 let e = validate_segid_range(1, u32::MAX as Cno + 1)
1342 .expect_err("a cno past u32::MAX must be rejected");
1343 assert_eq!(e.kind(), ErrorKind::InvalidInput);
1344 assert!(validate_segid_range(1, u32::MAX as Cno).is_ok());
1345 }
1346
1347 #[test]
1350 fn object_names_round_trip_through_the_parser() {
1351 for segid in [
1352 SegmentId::new(1),
1353 SegmentId::new(4294967295),
1354 SegmentId::with_part(7, 0),
1355 SegmentId::with_part(7, 16383),
1356 ] {
1357 let name = Segment::segid_to_staging_file_id(segid);
1358 assert_eq!(parse_segment_object_name(&name), Some(segid),
1359 "name {:?} did not parse back", name);
1360 }
1361 }
1362
1363 #[test]
1367 fn a_bare_name_is_not_part_zero() {
1368 assert_eq!(parse_segment_object_name("0000000007"), Some(SegmentId::new(7)));
1369 assert_eq!(parse_segment_object_name("0000000007.0"),
1370 Some(SegmentId::with_part(7, 0)));
1371 }
1372
1373 #[test]
1374 fn keys_that_are_not_segment_objects_are_skipped() {
1375 for name in [
1376 "inode", "wal/0000000001", "0000000001/0_0_4096",
1379 "000000001", "00000000012", "9999999999", "0000000001.", "0000000001.x",
1384 "0000000001.65536", "0000000001.0.1",
1386 "",
1387 ] {
1388 assert_eq!(parse_segment_object_name(name), None,
1389 "{:?} should not be read as a segment object", name);
1390 }
1391 }
1392
1393 fn partition(
1396 existing: &[SegmentId],
1397 referenced: &[SegmentId],
1398 low: Cno,
1399 high: Cno,
1400 high_summary: SegmentId,
1401 ) -> Vec<SegmentId> {
1402 let set: BTreeSet<SegmentId> = referenced.iter().copied().collect();
1403 let (_, unref) = partition_objects(existing, &set, low, high, high_summary);
1404 unref
1405 }
1406
1407 #[test]
1410 fn an_unreferenced_checkpoint_is_reclaimable() {
1411 let existing = [SegmentId::new(1), SegmentId::new(2), SegmentId::new(3)];
1412 let unref = partition(&existing, &[SegmentId::new(3)], 1, 3, SegmentId::new(3));
1413 assert_eq!(unref, vec![SegmentId::new(1), SegmentId::new(2)]);
1414 }
1415
1416 #[test]
1419 fn objects_outside_the_range_are_left_alone() {
1420 let existing = [
1421 SegmentId::new(1), SegmentId::new(2), SegmentId::new(3), SegmentId::new(4),
1422 ];
1423 let unref = partition(&existing, &[], 2, 3, SegmentId::new(9));
1424 assert_eq!(unref, vec![SegmentId::new(2), SegmentId::new(3)]);
1425 }
1426
1427 #[test]
1430 fn the_summary_of_high_is_kept_even_when_nothing_points_into_it() {
1431 let existing = [SegmentId::new(1), SegmentId::new(2)];
1432 let unref = partition(&existing, &[], 1, 2, SegmentId::new(2));
1433 assert_eq!(unref, vec![SegmentId::new(1)]);
1434
1435 let existing = [SegmentId::with_part(2, 0), SegmentId::with_part(2, 1)];
1437 let unref = partition(&existing, &[], 1, 2, SegmentId::with_part(2, 0));
1438 assert_eq!(unref, vec![SegmentId::with_part(2, 1)]);
1439 }
1440
1441 #[test]
1445 fn an_abandoned_partial_is_reclaimable_while_its_checkpoint_lives() {
1446 let existing = [
1447 SegmentId::with_part(5, 0), SegmentId::with_part(5, 1), SegmentId::with_part(5, 2), ];
1451 let referenced = [SegmentId::with_part(5, 0), SegmentId::with_part(5, 1)];
1452 let unref = partition(&existing, &referenced, 1, 9, SegmentId::with_part(9, 0));
1453 assert_eq!(unref, vec![SegmentId::with_part(5, 2)]);
1454 }
1455
1456 #[test]
1459 fn the_summary_part_nothing_points_into_goes_while_its_checkpoint_lives() {
1460 let existing = [SegmentId::with_part(4, 0), SegmentId::with_part(4, 3)];
1461 let unref = partition(&existing, &[SegmentId::with_part(4, 3)], 1, 9,
1462 SegmentId::with_part(9, 0));
1463 assert_eq!(unref, vec![SegmentId::with_part(4, 0)]);
1464 }
1465
1466 #[test]
1469 fn a_wholly_dead_parted_checkpoint_goes_including_its_summary() {
1470 let existing = [
1471 SegmentId::with_part(4, 0), SegmentId::with_part(4, 1),
1472 SegmentId::with_part(6, 0),
1473 ];
1474 let unref = partition(&existing, &[SegmentId::with_part(6, 0)], 1, 9,
1475 SegmentId::with_part(6, 0));
1476 assert_eq!(unref, vec![SegmentId::with_part(4, 0), SegmentId::with_part(4, 1)]);
1477 }
1478}