-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathprune.rs
1496 lines (1377 loc) · 54.2 KB
/
prune.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! `prune` subcommand
/// App-local prelude includes `app_reader()`/`app_writer()`/`app_config()`
/// accessors along with logging macros. Customize as you see fit.
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
str::FromStr,
sync::{Arc, Mutex},
};
use bytesize::ByteSize;
use chrono::{DateTime, Duration, Local};
use derive_more::Add;
use derive_setters::Setters;
use enumset::{EnumSet, EnumSetType};
use itertools::Itertools;
use log::{info, warn};
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
use serde::{Deserialize, Serialize};
use crate::{
backend::{
decrypt::{DecryptReadBackend, DecryptWriteBackend},
node::NodeType,
FileType, ReadBackend,
},
blob::{
packer::{PackSizer, Repacker},
tree::TreeStreamerOnce,
BlobType, BlobTypeMap, Initialize,
},
error::{CommandErrorKind, RusticErrorKind, RusticResult},
id::Id,
index::{
binarysorted::{IndexCollector, IndexType},
indexer::Indexer,
GlobalIndex, ReadGlobalIndex, ReadIndex,
},
progress::{Progress, ProgressBars},
repofile::{HeaderEntry, IndexBlob, IndexFile, IndexPack, SnapshotFile},
repository::{Open, Repository},
};
pub(super) mod constants {
/// Minimum size of an index file to be considered for pruning
pub(super) const MIN_INDEX_LEN: usize = 10_000;
}
#[allow(clippy::struct_excessive_bools)]
#[cfg_attr(feature = "clap", derive(clap::Parser))]
#[derive(Debug, Clone, Setters)]
#[setters(into)]
/// Options for the `prune` command
pub struct PruneOptions {
/// Define maximum data to repack in % of reposize or as size (e.g. '5b', '2 kB', '3M', '4TiB') or 'unlimited'
#[cfg_attr(
feature = "clap",
clap(long, value_name = "LIMIT", default_value = "10%")
)]
pub max_repack: LimitOption,
/// Tolerate limit of unused data in % of reposize after pruning or as size (e.g. '5b', '2 kB', '3M', '4TiB') or 'unlimited'
#[cfg_attr(
feature = "clap",
clap(long, value_name = "LIMIT", default_value = "5%")
)]
pub max_unused: LimitOption,
/// Minimum duration (e.g. 90d) to keep packs before repacking or removing. More recently created
/// packs won't be repacked or marked for deletion within this prune run.
#[cfg_attr(
feature = "clap",
clap(long, value_name = "DURATION", default_value = "0d")
)]
pub keep_pack: humantime::Duration,
/// Minimum duration (e.g. 10m) to keep packs marked for deletion. More recently marked packs won't be
/// deleted within this prune run.
#[cfg_attr(
feature = "clap",
clap(long, value_name = "DURATION", default_value = "23h")
)]
pub keep_delete: humantime::Duration,
/// Delete files immediately instead of marking them. This also removes all files already marked for deletion.
///
/// # Warning
///
/// Only use if you are sure the repository is not accessed by parallel processes!
#[cfg_attr(feature = "clap", clap(long))]
pub instant_delete: bool,
/// Delete index files early. This allows to run prune if there is few or no space left.
///
/// # Warning
///
/// If prune aborts, this can lead to a (partly) missing index which must be repaired!
#[cfg_attr(feature = "clap", clap(long))]
pub early_delete_index: bool,
/// Simply copy blobs when repacking instead of decrypting; possibly compressing; encrypting
#[cfg_attr(feature = "clap", clap(long))]
pub fast_repack: bool,
/// Repack packs containing uncompressed blobs. This cannot be used with --fast-repack.
/// Implies --max-unused=0.
#[cfg_attr(feature = "clap", clap(long, conflicts_with = "fast_repack"))]
pub repack_uncompressed: bool,
/// Repack all packs. Implies --max-unused=0.
#[cfg_attr(feature = "clap", clap(long))]
pub repack_all: bool,
/// Only repack packs which are cacheable [default: true for a hot/cold repository, else false]
#[cfg_attr(feature = "clap", clap(long, value_name = "TRUE/FALSE"))]
pub repack_cacheable_only: Option<bool>,
/// Do not repack packs which only needs to be resized
#[cfg_attr(feature = "clap", clap(long))]
pub no_resize: bool,
#[cfg_attr(feature = "clap", clap(skip))]
/// Ignore these snapshots when looking for data-still-in-use.
///
/// # Warning
///
/// Use this option with care!
///
/// If you specify snapshots which are not deleted, running the resulting `PrunePlan`
/// will remove data which is used within those snapshots!
pub ignore_snaps: Vec<Id>,
}
impl Default for PruneOptions {
fn default() -> Self {
Self {
max_repack: LimitOption::Percentage(10),
max_unused: LimitOption::Percentage(5),
keep_pack: std::time::Duration::from_secs(0).into(),
keep_delete: std::time::Duration::from_secs(82800).into(), // = 23h
instant_delete: false,
early_delete_index: false,
fast_repack: false,
repack_uncompressed: false,
repack_all: false,
repack_cacheable_only: None,
no_resize: false,
ignore_snaps: Vec::new(),
}
}
}
impl PruneOptions {
/// Get a `PrunePlan` from the given `PruneOptions`.
///
/// # Type Parameters
///
/// * `P` - The progress bar type.
/// * `S` - The state the repository is in.
///
/// # Arguments
///
/// * `repo` - The repository to get the `PrunePlan` for.
///
/// # Errors
///
/// * [`CommandErrorKind::RepackUncompressedRepoV1`] - If `repack_uncompressed` is set and the repository is a version 1 repository
/// * [`CommandErrorKind::FromOutOfRangeError`] - If `keep_pack` or `keep_delete` is out of range
///
/// [`CommandErrorKind::RepackUncompressedRepoV1`]: crate::error::CommandErrorKind::RepackUncompressedRepoV1
/// [`CommandErrorKind::FromOutOfRangeError`]: crate::error::CommandErrorKind::FromOutOfRangeError
pub fn get_plan<P: ProgressBars, S: Open>(
&self,
repo: &Repository<P, S>,
) -> RusticResult<PrunePlan> {
let pb = &repo.pb;
let be = repo.dbe();
if repo.config().version < 2 && self.repack_uncompressed {
return Err(CommandErrorKind::RepackUncompressedRepoV1.into());
}
let mut index_files = Vec::new();
let p = pb.progress_counter("reading index...");
let mut index_collector = IndexCollector::new(IndexType::OnlyTrees);
for index in be.stream_all::<IndexFile>(&p)? {
let (id, index) = index?;
index_collector.extend(index.packs.clone());
// we add the trees from packs_to_delete to the index such that searching for
// used blobs doesn't abort if they are already marked for deletion
index_collector.extend(index.packs_to_delete.clone());
index_files.push((id, index));
}
p.finish();
let (used_ids, total_size) = {
let index = GlobalIndex::new_from_index(index_collector.into_index());
let total_size = BlobTypeMap::init(|blob_type| index.total_size(blob_type));
let used_ids = find_used_blobs(be, &index, &self.ignore_snaps, pb)?;
(used_ids, total_size)
};
// list existing pack files
let p = pb.progress_spinner("getting packs from repository...");
let existing_packs: BTreeMap<_, _> = be
.list_with_size(FileType::Pack)
.map_err(RusticErrorKind::Backend)?
.into_iter()
.collect();
p.finish();
let mut pruner = PrunePlan::new(used_ids, existing_packs, index_files);
pruner.count_used_blobs();
pruner.check()?;
let repack_cacheable_only = self
.repack_cacheable_only
.unwrap_or_else(|| repo.config().is_hot == Some(true));
let pack_sizer =
total_size.map(|tpe, size| PackSizer::from_config(repo.config(), tpe, size));
pruner.decide_packs(
Duration::from_std(*self.keep_pack).map_err(CommandErrorKind::FromOutOfRangeError)?,
Duration::from_std(*self.keep_delete).map_err(CommandErrorKind::FromOutOfRangeError)?,
repack_cacheable_only,
self.repack_uncompressed,
self.repack_all,
&pack_sizer,
)?;
pruner.decide_repack(
&self.max_repack,
&self.max_unused,
self.repack_uncompressed || self.repack_all,
self.no_resize,
&pack_sizer,
);
pruner.check_existing_packs()?;
pruner.filter_index_files(self.instant_delete);
Ok(pruner)
}
}
/// Enum to specify a size limit
#[derive(Clone, Copy, Debug)]
pub enum LimitOption {
/// Size in bytes
Size(ByteSize),
/// Size in percentage of repository size
Percentage(u64),
/// No limit
Unlimited,
}
impl FromStr for LimitOption {
type Err = CommandErrorKind;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s.chars().last().unwrap_or('0') {
'%' => Self::Percentage({
let mut copy = s.to_string();
_ = copy.pop();
copy.parse()?
}),
'd' if s == "unlimited" => Self::Unlimited,
_ => Self::Size(ByteSize::from_str(s).map_err(CommandErrorKind::FromByteSizeParser)?),
})
}
}
#[derive(EnumSetType, Debug, PartialOrd, Ord, Serialize, Deserialize)]
#[enumset(serialize_repr = "list")]
pub enum PackStatus {
NotCompressed,
TooYoung,
TimeNotSet,
TooLarge,
TooSmall,
HasUnusedBlobs,
HasUsedBlobs,
Marked,
}
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DebugDetailedStats {
pub packs: u64,
pub unused_blobs: u64,
pub unused_size: u64,
pub used_blobs: u64,
pub used_size: u64,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct DebugStatsKey {
pub todo: PackToDo,
pub blob_type: BlobType,
pub status: EnumSet<PackStatus>,
}
#[derive(Debug, Default, Serialize)]
pub struct DebugStats(pub BTreeMap<DebugStatsKey, DebugDetailedStats>);
impl DebugStats {
fn add(&mut self, pi: &PackInfo, todo: PackToDo, status: EnumSet<PackStatus>) {
let blob_type = pi.blob_type;
let details = self
.0
.entry(DebugStatsKey {
todo,
blob_type,
status,
})
.or_insert(DebugDetailedStats {
packs: 0,
unused_blobs: 0,
unused_size: 0,
used_blobs: 0,
used_size: 0,
});
details.packs += 1;
details.unused_blobs += u64::from(pi.unused_blobs);
details.unused_size += u64::from(pi.unused_size);
details.used_blobs += u64::from(pi.used_blobs);
details.used_size += u64::from(pi.used_size);
}
}
/// Statistics about what is deleted or kept within `prune`
#[derive(Default, Debug, Clone, Copy)]
pub struct DeleteStats {
/// Number of blobs to remove
pub remove: u64,
/// Number of blobs to recover
pub recover: u64,
/// Number of blobs to keep
pub keep: u64,
}
impl DeleteStats {
/// Returns the total number of blobs
pub const fn total(&self) -> u64 {
self.remove + self.recover + self.keep
}
}
#[derive(Debug, Default, Clone, Copy)]
/// Statistics about packs within `prune`
pub struct PackStats {
/// Number of used packs
pub used: u64,
/// Number of partly used packs
pub partly_used: u64,
/// Number of unused packs
pub unused: u64, // this equals to packs-to-remove
/// Number of packs-to-repack
pub repack: u64,
/// Number of packs-to-keep
pub keep: u64,
}
#[derive(Debug, Default, Clone, Copy, Add)]
/// Statistics about sizes within `prune`
pub struct SizeStats {
/// Number of used blobs
pub used: u64,
/// Number of unused blobs
pub unused: u64,
/// Number of blobs to remove
pub remove: u64,
/// Number of blobs to repack
pub repack: u64,
/// Number of blobs to remove after repacking
pub repackrm: u64,
}
impl SizeStats {
/// Returns the total number of blobs
pub const fn total(&self) -> u64 {
self.used + self.unused
}
/// Returns the total number of blobs after pruning
pub const fn total_after_prune(&self) -> u64 {
self.used + self.unused_after_prune()
}
/// Returns the total number of unused blobs after pruning
pub const fn unused_after_prune(&self) -> u64 {
self.unused - self.remove - self.repackrm
}
}
/// Statistics about a [`PrunePlan`]
#[derive(Default, Debug)]
pub struct PruneStats {
/// Statistics about pack count
pub packs_to_delete: DeleteStats,
/// Statistics about pack sizes
pub size_to_delete: DeleteStats,
/// Statistics about current pack situation
pub packs: PackStats,
/// Statistics about blobs in the repository
pub blobs: BlobTypeMap<SizeStats>,
/// Statistics about total sizes of blobs in the repository
pub size: BlobTypeMap<SizeStats>,
/// Number of unreferenced pack files
pub packs_unref: u64,
/// total size of unreferenced pack files
pub size_unref: u64,
/// Number of index files
pub index_files: u64,
/// Number of index files which will be rebuilt during the prune
pub index_files_rebuild: u64,
/// Detailed debug statistics
pub debug: DebugStats,
}
impl PruneStats {
/// Compute statistics about blobs of all types
#[must_use]
pub fn blobs_sum(&self) -> SizeStats {
self.blobs
.values()
.fold(SizeStats::default(), |acc, x| acc + *x)
}
/// Compute total size statistics for blobs of all types
#[must_use]
pub fn size_sum(&self) -> SizeStats {
self.size
.values()
.fold(SizeStats::default(), |acc, x| acc + *x)
}
}
// TODO: add documentation!
#[derive(Debug)]
struct PruneIndex {
/// The id of the index file
id: Id,
/// Whether the index file was modified
modified: bool,
/// The packs in the index file
packs: Vec<PrunePack>,
}
impl PruneIndex {
// TODO: add documentation!
fn len(&self) -> usize {
self.packs.iter().map(|p| p.blobs.len()).sum()
}
}
/// Task to be executed by a `PrunePlan` on Packs
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub enum PackToDo {
// TODO: Add documentation
Undecided,
/// The pack should be kept
Keep,
/// The pack should be repacked
Repack,
/// The pack should be marked for deletion
MarkDelete,
// TODO: Add documentation
KeepMarked,
// TODO: Add documentation
KeepMarkedAndCorrect,
/// The pack should be recovered
Recover,
/// The pack should be deleted
Delete,
}
impl Default for PackToDo {
fn default() -> Self {
Self::Undecided
}
}
/// A pack which is to be pruned
#[derive(Debug)]
struct PrunePack {
/// The id of the pack
id: Id,
/// The type of the pack
blob_type: BlobType,
/// The size of the pack
size: u32,
/// Whether the pack is marked for deletion
delete_mark: bool,
/// The task to be executed on the pack
to_do: PackToDo,
/// The time the pack was created
time: Option<DateTime<Local>>,
/// The blobs in the pack
blobs: Vec<IndexBlob>,
}
impl PrunePack {
/// Create a new `PrunePack` from an `IndexPack`
///
/// # Arguments
///
/// * `p` - The `IndexPack` to create the `PrunePack` from
/// * `delete_mark` - Whether the pack is marked for deletion
fn from_index_pack(p: IndexPack, delete_mark: bool) -> Self {
Self {
id: p.id,
blob_type: p.blob_type(),
size: p.pack_size(),
delete_mark,
to_do: PackToDo::Undecided,
time: p.time,
blobs: p.blobs,
}
}
/// Create a new `PrunePack` from an `IndexPack` which is not marked for deletion
///
/// # Arguments
///
/// * `p` - The `IndexPack` to create the `PrunePack` from
fn from_index_pack_unmarked(p: IndexPack) -> Self {
Self::from_index_pack(p, false)
}
/// Create a new `PrunePack` from an `IndexPack` which is marked for deletion
///
/// # Arguments
///
/// * `p` - The `IndexPack` to create the `PrunePack` from
fn from_index_pack_marked(p: IndexPack) -> Self {
Self::from_index_pack(p, true)
}
/// Convert the `PrunePack` into an `IndexPack`
fn into_index_pack(self) -> IndexPack {
IndexPack {
id: self.id,
time: self.time,
size: None,
blobs: self.blobs,
}
}
/// Convert the `PrunePack` into an `IndexPack` with the given time
///
/// # Arguments
///
/// * `time` - The time to set
fn into_index_pack_with_time(self, time: DateTime<Local>) -> IndexPack {
IndexPack {
id: self.id,
time: Some(time),
size: None,
blobs: self.blobs,
}
}
/// Set the task to be executed on the pack
///
/// # Arguments
///
/// * `todo` - The task to be executed on the pack
/// * `pi` - The `PackInfo` of the pack
/// * `stats` - The `PruneStats` of the `PrunePlan`
#[allow(clippy::similar_names)]
fn set_todo(
&mut self,
todo: PackToDo,
pi: &PackInfo,
status: EnumSet<PackStatus>,
stats: &mut PruneStats,
) {
let tpe = self.blob_type;
stats.debug.add(pi, todo, status);
match todo {
PackToDo::Undecided => panic!("not possible"),
PackToDo::Keep => {
stats.packs.keep += 1;
}
PackToDo::Repack => {
stats.packs.repack += 1;
stats.blobs[tpe].repack += u64::from(pi.unused_blobs + pi.used_blobs);
stats.blobs[tpe].repackrm += u64::from(pi.unused_blobs);
stats.size[tpe].repack += u64::from(pi.unused_size + pi.used_size);
stats.size[tpe].repackrm += u64::from(pi.unused_size);
}
PackToDo::MarkDelete => {
stats.blobs[tpe].remove += u64::from(pi.unused_blobs);
stats.size[tpe].remove += u64::from(pi.unused_size);
}
PackToDo::Recover => {
stats.packs_to_delete.recover += 1;
stats.size_to_delete.recover += u64::from(self.size);
}
PackToDo::Delete => {
stats.packs_to_delete.remove += 1;
stats.size_to_delete.remove += u64::from(self.size);
}
PackToDo::KeepMarked | PackToDo::KeepMarkedAndCorrect => {
stats.packs_to_delete.keep += 1;
stats.size_to_delete.keep += u64::from(self.size);
}
}
self.to_do = todo;
}
/// Returns whether the pack is compressed
fn is_compressed(&self) -> bool {
self.blobs
.iter()
.all(|blob| blob.uncompressed_length.is_some())
}
}
/// Reasons why a pack should be repacked
#[derive(PartialEq, Eq, Debug)]
enum RepackReason {
/// The pack is partly used
PartlyUsed,
/// The pack is to be compressed
ToCompress,
/// The pack has a size mismatch
SizeMismatch,
}
/// A plan what should be repacked or removed by a `prune` run
#[derive(Debug)]
pub struct PrunePlan {
/// The time the plan was created
time: DateTime<Local>,
/// The ids of the blobs which are used
used_ids: BTreeMap<Id, u8>,
/// The ids of the existing packs
existing_packs: BTreeMap<Id, u32>,
/// The packs which should be repacked
repack_candidates: Vec<(PackInfo, EnumSet<PackStatus>, RepackReason, usize, usize)>,
/// The index files
index_files: Vec<PruneIndex>,
/// `prune` statistics
pub stats: PruneStats,
}
impl PrunePlan {
/// Create a new `PrunePlan`
///
/// # Arguments
///
/// * `used_ids` - The ids of the blobs which are used
/// * `existing_packs` - The ids of the existing packs
/// * `index_files` - The index files
fn new(
used_ids: BTreeMap<Id, u8>,
existing_packs: BTreeMap<Id, u32>,
index_files: Vec<(Id, IndexFile)>,
) -> Self {
let mut processed_packs = BTreeSet::new();
let mut processed_packs_delete = BTreeSet::new();
let mut index_files: Vec<_> = index_files
.into_iter()
.map(|(id, index)| {
let mut modified = false;
let mut packs: Vec<_> = index
.packs
.into_iter()
// filter out duplicate packs
.filter(|p| {
let no_duplicate = processed_packs.insert(p.id);
modified |= !no_duplicate;
no_duplicate
})
.map(PrunePack::from_index_pack_unmarked)
.collect();
packs.extend(
index
.packs_to_delete
.into_iter()
// filter out duplicate packs
.filter(|p| {
let no_duplicate = processed_packs_delete.insert(p.id);
modified |= !no_duplicate;
no_duplicate
})
.map(PrunePack::from_index_pack_marked),
);
PruneIndex {
id,
modified,
packs,
}
})
.collect();
// filter out "normally" indexed packs from packs_to_delete
for index in &mut index_files {
let mut modified = false;
index.packs.retain(|p| {
!p.delete_mark || {
let duplicate = processed_packs.contains(&p.id);
modified |= duplicate;
!duplicate
}
});
index.modified |= modified;
}
Self {
time: Local::now(),
used_ids,
existing_packs,
repack_candidates: Vec::new(),
index_files,
stats: PruneStats::default(),
}
}
/// This function counts the number of times a blob is used in the index files.
fn count_used_blobs(&mut self) {
for blob in self
.index_files
.iter()
.flat_map(|index| &index.packs)
.flat_map(|pack| &pack.blobs)
{
if let Some(count) = self.used_ids.get_mut(&blob.id) {
// note that duplicates are only counted up to 255. If there are more
// duplicates, the number is set to 255. This may imply that later on
// not the "best" pack is chosen to have that blob marked as used.
*count = count.saturating_add(1);
}
}
}
/// This function checks whether all used blobs are present in the index files.
///
/// # Errors
///
/// * [`CommandErrorKind::BlobsMissing`] - If a blob is missing
///
/// [`CommandErrorKind::BlobsMissing`]: crate::error::CommandErrorKind::BlobsMissing
fn check(&self) -> RusticResult<()> {
for (id, count) in &self.used_ids {
if *count == 0 {
return Err(CommandErrorKind::BlobsMissing(*id).into());
}
}
Ok(())
}
/// Decides what to do with the packs
///
/// # Arguments
///
/// * `keep_pack` - The minimum duration to keep packs before repacking or removing
/// * `keep_delete` - The minimum duration to keep packs marked for deletion
/// * `repack_cacheable_only` - Whether to only repack cacheable packs
/// * `repack_uncompressed` - Whether to repack packs containing uncompressed blobs
/// * `repack_all` - Whether to repack all packs
/// * `pack_sizer` - The `PackSizer` for the packs
///
/// # Errors
///
// TODO: add errors!
#[allow(clippy::too_many_lines)]
#[allow(clippy::unnecessary_wraps)]
fn decide_packs(
&mut self,
keep_pack: Duration,
keep_delete: Duration,
repack_cacheable_only: bool,
repack_uncompressed: bool,
repack_all: bool,
pack_sizer: &BlobTypeMap<PackSizer>,
) -> RusticResult<()> {
// first process all marked packs then the unmarked ones:
// - first processed packs are more likely to have all blobs seen as unused
// - if marked packs have used blob but these blobs are all present in
// unmarked packs, we want to perform the deletion!
for mark_case in [true, false] {
for (index_num, index) in self.index_files.iter_mut().enumerate() {
for (pack_num, pack) in index
.packs
.iter_mut()
.enumerate()
.filter(|(_, p)| p.delete_mark == mark_case)
{
let pi = PackInfo::from_pack(pack, &mut self.used_ids);
//update used/unused stats
self.stats.blobs[pi.blob_type].used += u64::from(pi.used_blobs);
self.stats.blobs[pi.blob_type].unused += u64::from(pi.unused_blobs);
self.stats.size[pi.blob_type].used += u64::from(pi.used_size);
self.stats.size[pi.blob_type].unused += u64::from(pi.unused_size);
let mut status = EnumSet::empty();
// Various checks to determine if packs need to be kept
let too_young = pack.time > Some(self.time - keep_pack);
if too_young && !pack.delete_mark {
_ = status.insert(PackStatus::TooYoung);
}
let keep_uncacheable = repack_cacheable_only && !pack.blob_type.is_cacheable();
let to_compress = repack_uncompressed && !pack.is_compressed();
if to_compress {
_ = status.insert(PackStatus::NotCompressed);
}
let size_mismatch = !pack_sizer[pack.blob_type].size_ok(pack.size);
if pack_sizer[pack.blob_type].is_too_small(pack.size) {
_ = status.insert(PackStatus::TooSmall);
}
if pack_sizer[pack.blob_type].is_too_large(pack.size) {
_ = status.insert(PackStatus::TooLarge);
}
match (pack.delete_mark, pi.used_blobs, pi.unused_blobs) {
(false, 0, _) => {
// unused pack
self.stats.packs.unused += 1;
_ = status.insert(PackStatus::HasUnusedBlobs);
if too_young {
// keep packs which are too young
pack.set_todo(PackToDo::Keep, &pi, status, &mut self.stats);
} else {
pack.set_todo(PackToDo::MarkDelete, &pi, status, &mut self.stats);
}
}
(false, 1.., 0) => {
// used pack
self.stats.packs.used += 1;
_ = status.insert(PackStatus::HasUsedBlobs);
if too_young || keep_uncacheable {
pack.set_todo(PackToDo::Keep, &pi, status, &mut self.stats);
} else if to_compress || repack_all {
self.repack_candidates.push((
pi,
status,
RepackReason::ToCompress,
index_num,
pack_num,
));
} else if size_mismatch {
self.repack_candidates.push((
pi,
status,
RepackReason::SizeMismatch,
index_num,
pack_num,
));
} else {
pack.set_todo(PackToDo::Keep, &pi, status, &mut self.stats);
}
}
(false, 1.., 1..) => {
// partly used pack
self.stats.packs.partly_used += 1;
status
.insert_all(PackStatus::HasUsedBlobs | PackStatus::HasUnusedBlobs);
if too_young || keep_uncacheable {
// keep packs which are too young and non-cacheable packs if requested
pack.set_todo(PackToDo::Keep, &pi, status, &mut self.stats);
} else {
// other partly used pack => candidate for repacking
self.repack_candidates.push((
pi,
status,
RepackReason::PartlyUsed,
index_num,
pack_num,
));
}
}
(true, 0, _) => {
_ = status.insert(PackStatus::Marked);
match pack.time {
// unneeded and marked pack => check if we can remove it.
Some(local_date_time)
if self.time - local_date_time >= keep_delete =>
{
_ = status.insert(PackStatus::TooYoung);
pack.set_todo(PackToDo::Delete, &pi, status, &mut self.stats);
}
None => {
warn!("pack to delete {}: no time set, this should not happen! Keeping this pack.", pack.id);
_ = status.insert(PackStatus::TimeNotSet);
pack.set_todo(
PackToDo::KeepMarkedAndCorrect,
&pi,
status,
&mut self.stats,
);
}
Some(_) => pack.set_todo(
PackToDo::KeepMarked,
&pi,
status,
&mut self.stats,
),
}
}
(true, 1.., _) => {
status.insert_all(PackStatus::Marked | PackStatus::HasUsedBlobs);
// needed blobs; mark this pack for recovery
pack.set_todo(PackToDo::Recover, &pi, status, &mut self.stats);
}
}
}
}
}
Ok(())
}
/// Decides if packs should be repacked
///
/// # Arguments
///
/// * `max_repack` - The maximum size of packs to repack
/// * `max_unused` - The maximum size of unused blobs
/// * `repack_uncompressed` - Whether to repack packs containing uncompressed blobs
/// * `no_resize` - Whether to resize packs
/// * `pack_sizer` - The `PackSizer` for the packs
///
/// # Errors
///
// TODO: add errors!
fn decide_repack(
&mut self,
max_repack: &LimitOption,
max_unused: &LimitOption,
repack_uncompressed: bool,
no_resize: bool,
pack_sizer: &BlobTypeMap<PackSizer>,
) {
let max_unused = match (repack_uncompressed, max_unused) {
(true, _) => 0,
(false, LimitOption::Unlimited) => u64::MAX,
(false, LimitOption::Size(size)) => size.as_u64(),
// if percentag is given, we want to have
// unused <= p/100 * size_after = p/100 * (size_used + unused)
// which equals (1 - p/100) * unused <= p/100 * size_used
(false, LimitOption::Percentage(p)) => (p * self.stats.size_sum().used) / (100 - p),
};
let max_repack = match max_repack {
LimitOption::Unlimited => u64::MAX,
LimitOption::Size(size) => size.as_u64(),
LimitOption::Percentage(p) => (p * self.stats.size_sum().total()) / 100,
};
self.repack_candidates.sort_unstable_by_key(|rc| rc.0);
let mut resize_packs = BlobTypeMap::<Vec<_>>::default();
let mut do_repack = BlobTypeMap::default();
let mut repack_size = BlobTypeMap::<u64>::default();
for (pi, status, repack_reason, index_num, pack_num) in
std::mem::take(&mut self.repack_candidates)
{
let pack = &mut self.index_files[index_num].packs[pack_num];
let blob_type = pi.blob_type;
let total_repack_size: u64 = repack_size.into_values().sum();
if total_repack_size + u64::from(pi.used_size) >= max_repack
|| (self.stats.size_sum().unused_after_prune() < max_unused
&& repack_reason == RepackReason::PartlyUsed
&& blob_type == BlobType::Data)
|| (repack_reason == RepackReason::SizeMismatch && no_resize)
{
pack.set_todo(PackToDo::Keep, &pi, status, &mut self.stats);
} else if repack_reason == RepackReason::SizeMismatch {
resize_packs[blob_type].push((pi, status, index_num, pack_num));
repack_size[blob_type] += u64::from(pi.used_size);
} else {
pack.set_todo(PackToDo::Repack, &pi, status, &mut self.stats);
repack_size[blob_type] += u64::from(pi.used_size);
do_repack[blob_type] = true;
}
}
for (blob_type, resize_packs) in resize_packs {
// packs in resize_packs are only repacked if we anyway repack this blob type or
// if the target pack size is reached for the blob type.
let todo = if do_repack[blob_type]
|| repack_size[blob_type] > u64::from(pack_sizer[blob_type].pack_size())
{
PackToDo::Repack
} else {
PackToDo::Keep
};
for (pi, status, index_num, pack_num) in resize_packs {
let pack = &mut self.index_files[index_num].packs[pack_num];
pack.set_todo(todo, &pi, status, &mut self.stats);
}
}
}
/// Checks if the existing packs are ok
///