-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathglobal_cache_tracker.rs
1815 lines (1724 loc) · 71 KB
/
global_cache_tracker.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
//! Support for tracking the last time files were used to assist with cleaning
//! up those files if they haven't been used in a while.
//!
//! Tracking of cache files is stored in a sqlite database which contains a
//! timestamp of the last time the file was used, as well as the size of the
//! file.
//!
//! While cargo is running, when it detects a use of a cache file, it adds a
//! timestamp to [`DeferredGlobalLastUse`]. This batches up a set of changes
//! that are then flushed to the database all at once (via
//! [`DeferredGlobalLastUse::save`]). Ideally saving would only be done once
//! for performance reasons, but that is not really possible due to the way
//! cargo works, since there are different ways cargo can be used (like `cargo
//! generate-lockfile`, `cargo fetch`, and `cargo build` are all very
//! different ways the code is used).
//!
//! All of the database interaction is done through the [`GlobalCacheTracker`]
//! type.
//!
//! There is a single global [`GlobalCacheTracker`] and
//! [`DeferredGlobalLastUse`] stored in [`GlobalContext`].
//!
//! The high-level interface for performing garbage collection is defined in
//! the [`crate::core::gc`] module. The functions there are responsible for
//! interacting with the [`GlobalCacheTracker`] to handle cleaning of global
//! cache data.
//!
//! ## Automatic gc
//!
//! Some commands (primarily the build commands) will trigger an automatic
//! deletion of files that haven't been used in a while. The high-level
//! interface for this is the [`crate::core::gc::auto_gc`] function.
//!
//! The [`GlobalCacheTracker`] database tracks the last time an automatic gc
//! was performed so that it is only done once per day for performance
//! reasons.
//!
//! ## Manual gc
//!
//! The user can perform a manual garbage collection with the `cargo clean`
//! command. That command has a variety of options to specify what to delete.
//! Manual gc supports deleting based on age or size or both. From a
//! high-level, this is done by the [`crate::core::gc::Gc::gc`] method, which
//! calls into [`GlobalCacheTracker`] to handle all the cleaning.
//!
//! ## Locking
//!
//! Usage of the database requires that the package cache is locked to prevent
//! concurrent access. Although sqlite has built-in locking support, we want
//! to use cargo's locking so that the "Blocking" message gets displayed, and
//! so that locks can block indefinitely for long-running build commands.
//! [`rusqlite`] has a default timeout of 5 seconds, though that is
//! configurable.
//!
//! When garbage collection is being performed, the package cache lock must be
//! in [`CacheLockMode::MutateExclusive`] to ensure no other cargo process is
//! running. See [`crate::util::cache_lock`] for more detail on locking.
//!
//! When performing automatic gc, [`crate::core::gc::auto_gc`] will skip the
//! GC if the package cache lock is already held by anything else. Automatic
//! GC is intended to be opportunistic, and should impose as little disruption
//! to the user as possible.
//!
//! ## Compatibility
//!
//! The database must retain both forwards and backwards compatibility between
//! different versions of cargo. For the most part, this shouldn't be too
//! difficult to maintain. Generally sqlite doesn't change on-disk formats
//! between versions (the introduction of WAL is one of the few examples where
//! version 3 had a format change, but we wouldn't use it anyway since it has
//! shared-memory requirements cargo can't depend on due to things like
//! network mounts).
//!
//! Schema changes must be managed through [`migrations`] by adding new
//! entries that make a change to the database. Changes must not break older
//! versions of cargo. Generally, adding columns should be fine (either with a
//! default value, or NULL). Adding tables should also be fine. Just don't do
//! destructive things like removing a column, or changing the semantics of an
//! existing column.
//!
//! Since users may run older versions of cargo that do not do cache tracking,
//! the [`GlobalCacheTracker::sync_db_with_files`] method helps dealing with
//! keeping the database in sync in the presence of older versions of cargo
//! touching the cache directories.
//!
//! ## Performance
//!
//! A lot of focus on the design of this system is to minimize the performance
//! impact. Every build command needs to save updates which we try to avoid
//! having a noticeable impact on build times. Systems like Windows,
//! particularly with a magnetic hard disk, can experience a fairly large
//! impact of cargo's overhead. Cargo's benchsuite has some benchmarks to help
//! compare different environments, or changes to the code here. Please try to
//! keep performance in mind if making any major changes.
//!
//! Performance of `cargo clean` is not quite as important since it is not
//! expected to be run often. However, it is still courteous to the user to
//! try to not impact it too much. One part that has a performance concern is
//! that the clean command will synchronize the database with whatever is on
//! disk if needed (in case files were added by older versions of cargo that
//! don't do cache tracking, or if the user manually deleted some files). This
//! can potentially be very slow, especially if the two are very out of sync.
//!
//! ## Filesystems
//!
//! Everything here is sensitive to the kind of filesystem it is running on.
//! People tend to run cargo in all sorts of strange environments that have
//! limited capabilities, or on things like read-only mounts. The code here
//! needs to gracefully handle as many situations as possible.
//!
//! See also the information in the [Performance](#performance) and
//! [Locking](#locking) sections when considering different filesystems and
//! their impact on performance and locking.
//!
//! There are checks for read-only filesystems, which is generally ignored.
use crate::core::gc::GcOpts;
use crate::core::Verbosity;
use crate::ops::CleanContext;
use crate::util::cache_lock::CacheLockMode;
use crate::util::interning::InternedString;
use crate::util::sqlite::{self, basic_migration, Migration};
use crate::util::{Filesystem, Progress, ProgressStyle};
use crate::{CargoResult, GlobalContext};
use anyhow::{bail, Context as _};
use cargo_util::paths;
use rusqlite::{params, Connection, ErrorCode};
use std::collections::{hash_map, HashMap};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use tracing::{debug, trace};
/// The filename of the database.
const GLOBAL_CACHE_FILENAME: &str = ".global-cache";
const REGISTRY_INDEX_TABLE: &str = "registry_index";
const REGISTRY_CRATE_TABLE: &str = "registry_crate";
const REGISTRY_SRC_TABLE: &str = "registry_src";
const GIT_DB_TABLE: &str = "git_db";
const GIT_CO_TABLE: &str = "git_checkout";
/// How often timestamps will be updated.
///
/// As an optimization timestamps are not updated unless they are older than
/// the given number of seconds. This helps reduce the amount of disk I/O when
/// running cargo multiple times within a short window.
const UPDATE_RESOLUTION: u64 = 60 * 5;
/// Type for timestamps as stored in the database.
///
/// These are seconds since the Unix epoch.
type Timestamp = u64;
/// The key for a registry index entry stored in the database.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct RegistryIndex {
/// A unique name of the registry source.
pub encoded_registry_name: InternedString,
}
/// The key for a registry `.crate` entry stored in the database.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct RegistryCrate {
/// A unique name of the registry source.
pub encoded_registry_name: InternedString,
/// The filename of the compressed crate, like `foo-1.2.3.crate`.
pub crate_filename: InternedString,
/// The size of the `.crate` file.
pub size: u64,
}
/// The key for a registry src directory entry stored in the database.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct RegistrySrc {
/// A unique name of the registry source.
pub encoded_registry_name: InternedString,
/// The directory name of the extracted source, like `foo-1.2.3`.
pub package_dir: InternedString,
/// Total size of the src directory in bytes.
///
/// This can be None when the size is unknown. For example, when the src
/// directory already exists on disk, and we just want to update the
/// last-use timestamp. We don't want to take the expense of computing disk
/// usage unless necessary. [`GlobalCacheTracker::populate_untracked`]
/// will handle any actual NULL values in the database, which can happen
/// when the src directory is created by an older version of cargo that
/// did not track sizes.
pub size: Option<u64>,
}
/// The key for a git db entry stored in the database.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct GitDb {
/// A unique name of the git database.
pub encoded_git_name: InternedString,
}
/// The key for a git checkout entry stored in the database.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct GitCheckout {
/// A unique name of the git database.
pub encoded_git_name: InternedString,
/// A unique name of the checkout without the database.
pub short_name: InternedString,
/// Total size of the checkout directory.
///
/// This can be None when the size is unknown. See [`RegistrySrc::size`]
/// for an explanation.
pub size: Option<u64>,
}
/// Filesystem paths in the global cache.
///
/// Accessing these assumes a lock has already been acquired.
struct BasePaths {
/// Root path to the index caches.
index: PathBuf,
/// Root path to the git DBs.
git_db: PathBuf,
/// Root path to the git checkouts.
git_co: PathBuf,
/// Root path to the `.crate` files.
crate_dir: PathBuf,
/// Root path to the `src` directories.
src: PathBuf,
}
/// Migrations which initialize the database, and can be used to evolve it over time.
///
/// See [`Migration`] for more detail.
///
/// **Be sure to not change the order or entries here!**
fn migrations() -> Vec<Migration> {
vec![
// registry_index tracks the overall usage of an index cache, and tracks a
// numeric ID to refer to that index that is used in other tables.
basic_migration(
"CREATE TABLE registry_index (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
timestamp INTEGER NOT NULL
)",
),
// .crate files
basic_migration(
"CREATE TABLE registry_crate (
registry_id INTEGER NOT NULL,
name TEXT NOT NULL,
size INTEGER NOT NULL,
timestamp INTEGER NOT NULL,
PRIMARY KEY (registry_id, name),
FOREIGN KEY (registry_id) REFERENCES registry_index (id) ON DELETE CASCADE
)",
),
// Extracted src directories
//
// Note that `size` can be NULL. This will happen when marking a src
// directory as used that was created by an older version of cargo
// that didn't do size tracking.
basic_migration(
"CREATE TABLE registry_src (
registry_id INTEGER NOT NULL,
name TEXT NOT NULL,
size INTEGER,
timestamp INTEGER NOT NULL,
PRIMARY KEY (registry_id, name),
FOREIGN KEY (registry_id) REFERENCES registry_index (id) ON DELETE CASCADE
)",
),
// Git db directories
basic_migration(
"CREATE TABLE git_db (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
timestamp INTEGER NOT NULL
)",
),
// Git checkout directories
basic_migration(
"CREATE TABLE git_checkout (
git_id INTEGER NOT NULL,
name TEXT UNIQUE NOT NULL,
size INTEGER,
timestamp INTEGER NOT NULL,
PRIMARY KEY (git_id, name),
FOREIGN KEY (git_id) REFERENCES git_db (id) ON DELETE CASCADE
)",
),
// This is a general-purpose single-row table that can store arbitrary
// data. Feel free to add columns (with ALTER TABLE) if necessary.
basic_migration(
"CREATE TABLE global_data (
last_auto_gc INTEGER NOT NULL
)",
),
// last_auto_gc tracks the last time auto-gc was run (so that it only
// runs roughly once a day for performance reasons). Prime it with the
// current time to establish a baseline.
Box::new(|conn| {
conn.execute(
"INSERT INTO global_data (last_auto_gc) VALUES (?1)",
[now()],
)?;
Ok(())
}),
]
}
/// Type for SQL columns that refer to the primary key of their parent table.
///
/// For example, `registry_crate.registry_id` refers to its parent `registry_index.id`.
#[derive(Copy, Clone, Debug, PartialEq)]
struct ParentId(i64);
impl rusqlite::types::FromSql for ParentId {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
let i = i64::column_result(value)?;
Ok(ParentId(i))
}
}
impl rusqlite::types::ToSql for ParentId {
fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
Ok(rusqlite::types::ToSqlOutput::from(self.0))
}
}
/// Tracking for the global shared cache (registry files, etc.).
///
/// This is the interface to the global cache database, used for tracking and
/// cleaning. See the [`crate::core::global_cache_tracker`] module docs for
/// details.
#[derive(Debug)]
pub struct GlobalCacheTracker {
/// Connection to the SQLite database.
conn: Connection,
/// This is an optimization used to make sure cargo only checks if gc
/// needs to run once per session. This starts as `false`, and then the
/// first time it checks if automatic gc needs to run, it will be set to
/// `true`.
auto_gc_checked_this_session: bool,
}
impl GlobalCacheTracker {
/// Creates a new [`GlobalCacheTracker`].
///
/// The caller is responsible for locking the package cache with
/// [`CacheLockMode::DownloadExclusive`] before calling this.
pub fn new(gctx: &GlobalContext) -> CargoResult<GlobalCacheTracker> {
let db_path = Self::db_path(gctx);
// A package cache lock is required to ensure only one cargo is
// accessing at the same time. If there is concurrent access, we
// want to rely on cargo's own "Blocking" system (which can
// provide user feedback) rather than blocking inside sqlite
// (which by default has a short timeout).
let db_path = gctx.assert_package_cache_locked(CacheLockMode::DownloadExclusive, &db_path);
let mut conn = Connection::open(db_path)?;
conn.pragma_update(None, "foreign_keys", true)?;
sqlite::migrate(&mut conn, &migrations())?;
Ok(GlobalCacheTracker {
conn,
auto_gc_checked_this_session: false,
})
}
/// The path to the database.
pub fn db_path(gctx: &GlobalContext) -> Filesystem {
gctx.home().join(GLOBAL_CACHE_FILENAME)
}
/// Given an encoded registry name, returns its ID.
///
/// Returns None if the given name isn't in the database.
fn id_from_name(
conn: &Connection,
table_name: &str,
encoded_name: &str,
) -> CargoResult<Option<ParentId>> {
let mut stmt =
conn.prepare_cached(&format!("SELECT id FROM {table_name} WHERE name = ?"))?;
match stmt.query_row([encoded_name], |row| row.get(0)) {
Ok(id) => Ok(Some(id)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(e.into()),
}
}
/// Returns a map of ID to path for the given ids in the given table.
///
/// For example, given `registry_index` IDs, it returns filenames of the
/// form "index.crates.io-6f17d22bba15001f".
fn get_id_map(
conn: &Connection,
table_name: &str,
ids: &[i64],
) -> CargoResult<HashMap<i64, PathBuf>> {
let mut stmt =
conn.prepare_cached(&format!("SELECT name FROM {table_name} WHERE id = ?1"))?;
ids.iter()
.map(|id| {
let name = stmt.query_row(params![id], |row| {
Ok(PathBuf::from(row.get::<_, String>(0)?))
})?;
Ok((*id, name))
})
.collect()
}
/// Returns all index cache timestamps.
pub fn registry_index_all(&self) -> CargoResult<Vec<(RegistryIndex, Timestamp)>> {
let mut stmt = self
.conn
.prepare_cached("SELECT name, timestamp FROM registry_index")?;
let rows = stmt
.query_map([], |row| {
let encoded_registry_name = row.get_unwrap(0);
let timestamp = row.get_unwrap(1);
let kind = RegistryIndex {
encoded_registry_name,
};
Ok((kind, timestamp))
})?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
}
/// Returns all registry crate cache timestamps.
pub fn registry_crate_all(&self) -> CargoResult<Vec<(RegistryCrate, Timestamp)>> {
let mut stmt = self.conn.prepare_cached(
"SELECT registry_index.name, registry_crate.name, registry_crate.size, registry_crate.timestamp
FROM registry_index, registry_crate
WHERE registry_crate.registry_id = registry_index.id",
)?;
let rows = stmt
.query_map([], |row| {
let encoded_registry_name = row.get_unwrap(0);
let crate_filename = row.get_unwrap(1);
let size = row.get_unwrap(2);
let timestamp = row.get_unwrap(3);
let kind = RegistryCrate {
encoded_registry_name,
crate_filename,
size,
};
Ok((kind, timestamp))
})?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
}
/// Returns all registry source cache timestamps.
pub fn registry_src_all(&self) -> CargoResult<Vec<(RegistrySrc, Timestamp)>> {
let mut stmt = self.conn.prepare_cached(
"SELECT registry_index.name, registry_src.name, registry_src.size, registry_src.timestamp
FROM registry_index, registry_src
WHERE registry_src.registry_id = registry_index.id",
)?;
let rows = stmt
.query_map([], |row| {
let encoded_registry_name = row.get_unwrap(0);
let package_dir = row.get_unwrap(1);
let size = row.get_unwrap(2);
let timestamp = row.get_unwrap(3);
let kind = RegistrySrc {
encoded_registry_name,
package_dir,
size,
};
Ok((kind, timestamp))
})?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
}
/// Returns all git db timestamps.
pub fn git_db_all(&self) -> CargoResult<Vec<(GitDb, Timestamp)>> {
let mut stmt = self
.conn
.prepare_cached("SELECT name, timestamp FROM git_db")?;
let rows = stmt
.query_map([], |row| {
let encoded_git_name = row.get_unwrap(0);
let timestamp = row.get_unwrap(1);
let kind = GitDb { encoded_git_name };
Ok((kind, timestamp))
})?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
}
/// Returns all git checkout timestamps.
pub fn git_checkout_all(&self) -> CargoResult<Vec<(GitCheckout, Timestamp)>> {
let mut stmt = self.conn.prepare_cached(
"SELECT git_db.name, git_checkout.name, git_checkout.size, git_checkout.timestamp
FROM git_db, git_checkout
WHERE git_checkout.git_id = git_db.id",
)?;
let rows = stmt
.query_map([], |row| {
let encoded_git_name = row.get_unwrap(0);
let short_name = row.get_unwrap(1);
let size = row.get_unwrap(2);
let timestamp = row.get_unwrap(3);
let kind = GitCheckout {
encoded_git_name,
short_name,
size,
};
Ok((kind, timestamp))
})?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
}
/// Returns whether or not an auto GC should be performed, compared to the
/// last time it was recorded in the database.
pub fn should_run_auto_gc(&mut self, frequency: Duration) -> CargoResult<bool> {
trace!(target: "gc", "should_run_auto_gc");
if self.auto_gc_checked_this_session {
return Ok(false);
}
let last_auto_gc: Timestamp =
self.conn
.query_row("SELECT last_auto_gc FROM global_data", [], |row| row.get(0))?;
let should_run = last_auto_gc + frequency.as_secs() < now();
trace!(target: "gc",
"last auto gc was {}, {}",
last_auto_gc,
if should_run { "running" } else { "skipping" }
);
self.auto_gc_checked_this_session = true;
Ok(should_run)
}
/// Writes to the database to indicate that an automatic GC has just been
/// completed.
pub fn set_last_auto_gc(&self) -> CargoResult<()> {
self.conn
.execute("UPDATE global_data SET last_auto_gc = ?1", [now()])?;
Ok(())
}
/// Deletes files from the global cache based on the given options.
pub fn clean(&mut self, clean_ctx: &mut CleanContext<'_>, gc_opts: &GcOpts) -> CargoResult<()> {
self.clean_inner(clean_ctx, gc_opts)
.with_context(|| "failed to clean entries from the global cache")
}
#[tracing::instrument(skip_all)]
fn clean_inner(
&mut self,
clean_ctx: &mut CleanContext<'_>,
gc_opts: &GcOpts,
) -> CargoResult<()> {
let gctx = clean_ctx.gctx;
let base = BasePaths {
index: gctx.registry_index_path().into_path_unlocked(),
git_db: gctx.git_db_path().into_path_unlocked(),
git_co: gctx.git_checkouts_path().into_path_unlocked(),
crate_dir: gctx.registry_cache_path().into_path_unlocked(),
src: gctx.registry_source_path().into_path_unlocked(),
};
let now = now();
trace!(target: "gc", "cleaning {gc_opts:?}");
let tx = self.conn.transaction()?;
let mut delete_paths = Vec::new();
// This can be an expensive operation, so only perform it if necessary.
if gc_opts.is_download_cache_opt_set() {
// TODO: Investigate how slow this might be.
Self::sync_db_with_files(
&tx,
now,
gctx,
&base,
gc_opts.is_download_cache_size_set(),
&mut delete_paths,
)
.with_context(|| "failed to sync tracking database")?
}
if let Some(max_age) = gc_opts.max_index_age {
let max_age = now - max_age.as_secs();
Self::get_registry_index_to_clean(&tx, max_age, &base, &mut delete_paths)?;
}
if let Some(max_age) = gc_opts.max_src_age {
let max_age = now - max_age.as_secs();
Self::get_registry_items_to_clean_age(
&tx,
max_age,
REGISTRY_SRC_TABLE,
&base.src,
&mut delete_paths,
)?;
}
if let Some(max_age) = gc_opts.max_crate_age {
let max_age = now - max_age.as_secs();
Self::get_registry_items_to_clean_age(
&tx,
max_age,
REGISTRY_CRATE_TABLE,
&base.crate_dir,
&mut delete_paths,
)?;
}
if let Some(max_age) = gc_opts.max_git_db_age {
let max_age = now - max_age.as_secs();
Self::get_git_db_items_to_clean(&tx, max_age, &base, &mut delete_paths)?;
}
if let Some(max_age) = gc_opts.max_git_co_age {
let max_age = now - max_age.as_secs();
Self::get_git_co_items_to_clean(&tx, max_age, &base.git_co, &mut delete_paths)?;
}
// Size collection must happen after date collection so that dates
// have precedence, since size constraints are a more blunt
// instrument.
//
// These are also complicated by the `--max-download-size` option
// overlapping with `--max-crate-size` and `--max-src-size`, which
// requires some coordination between those options which isn't
// necessary with the age-based options. An item's age is either older
// or it isn't, but contrast that with size which is based on the sum
// of all tracked items. Also, `--max-download-size` is summed against
// both the crate and src tracking, which requires combining them to
// compute the size, and then separating them to calculate the correct
// paths.
if let Some(max_size) = gc_opts.max_crate_size {
Self::get_registry_items_to_clean_size(
&tx,
max_size,
REGISTRY_CRATE_TABLE,
&base.crate_dir,
&mut delete_paths,
)?;
}
if let Some(max_size) = gc_opts.max_src_size {
Self::get_registry_items_to_clean_size(
&tx,
max_size,
REGISTRY_SRC_TABLE,
&base.src,
&mut delete_paths,
)?;
}
if let Some(max_size) = gc_opts.max_git_size {
Self::get_git_items_to_clean_size(&tx, max_size, &base, &mut delete_paths)?;
}
if let Some(max_size) = gc_opts.max_download_size {
Self::get_registry_items_to_clean_size_both(&tx, max_size, &base, &mut delete_paths)?;
}
clean_ctx.remove_paths(&delete_paths)?;
if clean_ctx.dry_run {
tx.rollback()?;
} else {
tx.commit()?;
}
Ok(())
}
/// Returns a list of directory entries in the given path.
fn names_from(path: &Path) -> CargoResult<Vec<String>> {
let entries = match path.read_dir() {
Ok(e) => e,
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
return Ok(Vec::new());
} else {
return Err(
anyhow::Error::new(e).context(format!("failed to read path `{path:?}`"))
);
}
}
};
let names = entries
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
.collect();
Ok(names)
}
/// Synchronizes the database to match the files on disk.
///
/// This performs the following cleanups:
///
/// 1. Remove entries from the database that are missing on disk.
/// 2. Adds missing entries to the database that are on disk (such as when
/// files are added by older versions of cargo).
/// 3. Fills in the `size` column where it is NULL (such as when something
/// is added to disk by an older version of cargo, and one of the mark
/// functions marked it without knowing the size).
///
/// Size computations are only done if `sync_size` is set since it can
/// be a very expensive operation. This should only be set if the user
/// requested to clean based on the cache size.
/// 4. Checks for orphaned files. For example, if there are `.crate` files
/// associated with an index that does not exist.
///
/// These orphaned files will be added to `delete_paths` so that the
/// caller can delete them.
#[tracing::instrument(skip(conn, gctx, base, delete_paths))]
fn sync_db_with_files(
conn: &Connection,
now: Timestamp,
gctx: &GlobalContext,
base: &BasePaths,
sync_size: bool,
delete_paths: &mut Vec<PathBuf>,
) -> CargoResult<()> {
debug!(target: "gc", "starting db sync");
// For registry_index and git_db, add anything that is missing in the db.
Self::update_parent_for_missing_from_db(conn, now, REGISTRY_INDEX_TABLE, &base.index)?;
Self::update_parent_for_missing_from_db(conn, now, GIT_DB_TABLE, &base.git_db)?;
// For registry_crate, registry_src, and git_checkout, remove anything
// from the db that isn't on disk.
Self::update_db_for_removed(
conn,
REGISTRY_INDEX_TABLE,
"registry_id",
REGISTRY_CRATE_TABLE,
&base.crate_dir,
)?;
Self::update_db_for_removed(
conn,
REGISTRY_INDEX_TABLE,
"registry_id",
REGISTRY_SRC_TABLE,
&base.src,
)?;
Self::update_db_for_removed(conn, GIT_DB_TABLE, "git_id", GIT_CO_TABLE, &base.git_co)?;
// For registry_index and git_db, remove anything from the db that
// isn't on disk.
//
// This also collects paths for any child files that don't have their
// respective parent on disk.
Self::update_db_parent_for_removed_from_disk(
conn,
REGISTRY_INDEX_TABLE,
&base.index,
&[&base.crate_dir, &base.src],
delete_paths,
)?;
Self::update_db_parent_for_removed_from_disk(
conn,
GIT_DB_TABLE,
&base.git_db,
&[&base.git_co],
delete_paths,
)?;
// For registry_crate, registry_src, and git_checkout, add anything
// that is missing in the db.
Self::populate_untracked_crate(conn, now, &base.crate_dir)?;
Self::populate_untracked(
conn,
now,
gctx,
REGISTRY_INDEX_TABLE,
"registry_id",
REGISTRY_SRC_TABLE,
&base.src,
sync_size,
)?;
Self::populate_untracked(
conn,
now,
gctx,
GIT_DB_TABLE,
"git_id",
GIT_CO_TABLE,
&base.git_co,
sync_size,
)?;
// Update any NULL sizes if needed.
if sync_size {
Self::update_null_sizes(
conn,
gctx,
REGISTRY_INDEX_TABLE,
"registry_id",
REGISTRY_SRC_TABLE,
&base.src,
)?;
Self::update_null_sizes(
conn,
gctx,
GIT_DB_TABLE,
"git_id",
GIT_CO_TABLE,
&base.git_co,
)?;
}
Ok(())
}
/// For parent tables, add any entries that are on disk but aren't tracked in the db.
#[tracing::instrument(skip(conn, now, base_path))]
fn update_parent_for_missing_from_db(
conn: &Connection,
now: Timestamp,
parent_table_name: &str,
base_path: &Path,
) -> CargoResult<()> {
trace!(target: "gc", "checking for untracked parent to add to {parent_table_name}");
let names = Self::names_from(base_path)?;
let mut stmt = conn.prepare_cached(&format!(
"INSERT INTO {parent_table_name} (name, timestamp)
VALUES (?1, ?2)
ON CONFLICT DO NOTHING",
))?;
for name in names {
stmt.execute(params![name, now])?;
}
Ok(())
}
/// Removes database entries for any files that are not on disk for the child tables.
///
/// This could happen for example if the user manually deleted the file or
/// any such scenario where the filesystem and db are out of sync.
#[tracing::instrument(skip(conn, base_path))]
fn update_db_for_removed(
conn: &Connection,
parent_table_name: &str,
id_column_name: &str,
table_name: &str,
base_path: &Path,
) -> CargoResult<()> {
trace!(target: "gc", "checking for db entries to remove from {table_name}");
let mut select_stmt = conn.prepare_cached(&format!(
"SELECT {table_name}.rowid, {parent_table_name}.name, {table_name}.name
FROM {parent_table_name}, {table_name}
WHERE {table_name}.{id_column_name} = {parent_table_name}.id",
))?;
let mut delete_stmt =
conn.prepare_cached(&format!("DELETE FROM {table_name} WHERE rowid = ?1"))?;
let mut rows = select_stmt.query([])?;
while let Some(row) = rows.next()? {
let rowid: i64 = row.get_unwrap(0);
let id_name: String = row.get_unwrap(1);
let name: String = row.get_unwrap(2);
if !base_path.join(id_name).join(name).exists() {
delete_stmt.execute([rowid])?;
}
}
Ok(())
}
/// Removes database entries for any files that are not on disk for the parent tables.
#[tracing::instrument(skip(conn, base_path, child_base_paths, delete_paths))]
fn update_db_parent_for_removed_from_disk(
conn: &Connection,
parent_table_name: &str,
base_path: &Path,
child_base_paths: &[&Path],
delete_paths: &mut Vec<PathBuf>,
) -> CargoResult<()> {
trace!(target: "gc", "checking for db entries to remove from {parent_table_name}");
let mut select_stmt =
conn.prepare_cached(&format!("SELECT rowid, name FROM {parent_table_name}"))?;
let mut delete_stmt =
conn.prepare_cached(&format!("DELETE FROM {parent_table_name} WHERE rowid = ?1"))?;
let mut rows = select_stmt.query([])?;
while let Some(row) = rows.next()? {
let rowid: i64 = row.get_unwrap(0);
let id_name: String = row.get_unwrap(1);
if !base_path.join(&id_name).exists() {
delete_stmt.execute([rowid])?;
// Make sure any child data is also cleaned up.
for child_base in child_base_paths {
let child_path = child_base.join(&id_name);
if child_path.exists() {
debug!(target: "gc", "removing orphaned path {child_path:?}");
delete_paths.push(child_path);
}
}
}
}
Ok(())
}
/// Updates the database to add any `.crate` files that are currently
/// not tracked (such as when they are downloaded by an older version of
/// cargo).
#[tracing::instrument(skip(conn, now, base_path))]
fn populate_untracked_crate(
conn: &Connection,
now: Timestamp,
base_path: &Path,
) -> CargoResult<()> {
trace!(target: "gc", "populating untracked crate files");
let mut insert_stmt = conn.prepare_cached(
"INSERT INTO registry_crate (registry_id, name, size, timestamp)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT DO NOTHING",
)?;
let index_names = Self::names_from(&base_path)?;
for index_name in index_names {
let Some(id) = Self::id_from_name(conn, REGISTRY_INDEX_TABLE, &index_name)? else {
// The id is missing from the database. This should be resolved
// via update_db_parent_for_removed_from_disk.
continue;
};
let index_path = base_path.join(index_name);
for crate_name in Self::names_from(&index_path)? {
if crate_name.ends_with(".crate") {
// Missing files should have already been taken care of by
// update_db_for_removed.
let size = paths::metadata(index_path.join(&crate_name))?.len();
insert_stmt.execute(params![id, crate_name, size, now])?;
}
}
}
Ok(())
}
/// Updates the database to add any files that are currently not tracked
/// (such as when they are downloaded by an older version of cargo).
#[tracing::instrument(skip(conn, now, gctx, base_path, populate_size))]
fn populate_untracked(
conn: &Connection,
now: Timestamp,
gctx: &GlobalContext,
id_table_name: &str,
id_column_name: &str,
table_name: &str,
base_path: &Path,
populate_size: bool,
) -> CargoResult<()> {
trace!(target: "gc", "populating untracked files for {table_name}");
// Gather names (and make sure they are in the database).
let id_names = Self::names_from(&base_path)?;
// This SELECT is used to determine if the directory is already
// tracked. We don't want to do the expensive size computation unless
// necessary.
let mut select_stmt = conn.prepare_cached(&format!(
"SELECT 1 FROM {table_name}
WHERE {id_column_name} = ?1 AND name = ?2",
))?;
let mut insert_stmt = conn.prepare_cached(&format!(
"INSERT INTO {table_name} ({id_column_name}, name, size, timestamp)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT DO NOTHING",
))?;
let mut progress = Progress::with_style("Scanning", ProgressStyle::Ratio, gctx);
// Compute the size of any directory not in the database.
for id_name in id_names {
let Some(id) = Self::id_from_name(conn, id_table_name, &id_name)? else {
// The id is missing from the database. This should be resolved
// via update_db_parent_for_removed_from_disk.
continue;
};
let index_path = base_path.join(id_name);
let names = Self::names_from(&index_path)?;
let max = names.len();
for (i, name) in names.iter().enumerate() {
if select_stmt.exists(params![id, name])? {
continue;
}
let dir_path = index_path.join(name);
if !dir_path.is_dir() {
continue;
}
progress.tick(i, max, "")?;
let size = if populate_size {
Some(du(&dir_path, table_name)?)
} else {
None
};
insert_stmt.execute(params![id, name, size, now])?;
}
}
Ok(())
}
/// Fills in the `size` column where it is NULL.
///
/// This can happen when something is added to disk by an older version of
/// cargo, and one of the mark functions marked it without knowing the
/// size.
///
/// `update_db_for_removed` should be called before this is called.
#[tracing::instrument(skip(conn, gctx, base_path))]
fn update_null_sizes(
conn: &Connection,
gctx: &GlobalContext,
parent_table_name: &str,
id_column_name: &str,
table_name: &str,
base_path: &Path,
) -> CargoResult<()> {
trace!(target: "gc", "updating NULL size information in {table_name}");
let mut null_stmt = conn.prepare_cached(&format!(
"SELECT {table_name}.rowid, {table_name}.name, {parent_table_name}.name
FROM {table_name}, {parent_table_name}
WHERE {table_name}.size IS NULL AND {table_name}.{id_column_name} = {parent_table_name}.id",
))?;