Skip to main content

reth_cli_commands/download/
prune.rs

1//! Removes snapshot-managed data that the selected download plan does not list.
2
3use super::{
4    extract::ensure_no_symlinks, managed_datadir_path, planning::PlannedArchive,
5    verify::OutputVerifier, MANAGED_DATADIR_PATHS,
6};
7use eyre::{Result, WrapErr};
8use reth_db::lockfile::StorageLock;
9use reth_fs_util as fs;
10use std::{
11    collections::HashSet,
12    path::{Path, PathBuf},
13};
14use tracing::info;
15
16/// Removes every file under the paths that `--force` clears (`db`, `rocksdb`, `static_files`,
17/// and `reth.toml`) that no planned archive lists as an output.
18///
19/// Listed files are kept so the startup integrity check can reuse the ones that still verify.
20/// Once the download completes, those paths hold exactly the snapshot's files, with no leftovers
21/// such as blocks or history indices from a chain the node extended past the snapshot block.
22///
23/// This relies on each archive's `output_files` listing every file the archive extracts. A file
24/// an archive extracts without listing it is removed here and not restored, because the archive
25/// is reused once its listed outputs verify.
26///
27/// Pruning rejects symlinks at managed paths under the data dir, just as extraction does.
28/// An explicitly configured static files directory is treated as a root, like the data dir itself.
29/// Symlinks below managed directories are removed rather than followed. Nested directories left
30/// empty are removed, but the managed directories themselves are kept.
31///
32/// Fails if a running node holds the database lock, since pruning would otherwise delete its
33/// lock and files from under it.
34pub(crate) fn prune_unlisted_outputs(
35    planned: &[PlannedArchive],
36    target_dir: &Path,
37    static_files_dir: Option<&Path>,
38) -> Result<()> {
39    // Validate every managed path before pruning any of them.
40    for &entry in MANAGED_DATADIR_PATHS {
41        if entry != "static_files" || static_files_dir.is_none() {
42            ensure_no_symlinks(target_dir, Path::new(entry))?;
43        }
44    }
45
46    let db_dir = target_dir.join("db");
47    if db_dir.is_dir() {
48        drop(StorageLock::try_acquire(&db_dir).wrap_err("refusing to prune a data dir in use")?);
49    }
50
51    let verifier = OutputVerifier::new(target_dir, static_files_dir);
52    let listed = planned
53        .iter()
54        .flat_map(|planned| &planned.archive.output_files)
55        .map(|output| verifier.output_path(output))
56        .collect::<Result<HashSet<_>>>()?;
57
58    let mut removed = 0;
59    for entry in MANAGED_DATADIR_PATHS {
60        let root = managed_datadir_path(entry, target_dir, static_files_dir);
61        if !root.try_exists()? {
62            continue
63        }
64
65        if fs::metadata(&root)?.is_dir() {
66            removed += prune_dir(&root, &listed)?;
67        } else if !listed.contains(&root) {
68            fs::remove_file(&root)?;
69            removed += 1;
70        }
71    }
72
73    info!(target: "reth::cli", removed, "Removed existing files not listed in the snapshot plan");
74    Ok(())
75}
76
77/// Removes unlisted entries below `dir` without following symlinks, and returns how many files
78/// or links it removed. Removing a symlink leaves its target intact.
79fn prune_dir(dir: &Path, listed: &HashSet<PathBuf>) -> Result<usize> {
80    let mut removed = 0;
81    for entry in fs::read_dir(dir)? {
82        let entry = entry?;
83        let path = entry.path();
84        // Unlike `fs::metadata`, this does not follow symlinks.
85        let file_type = entry
86            .file_type()
87            .wrap_err_with(|| format!("failed to read file type of {}", path.display()))?;
88        if file_type.is_dir() {
89            removed += prune_dir(&path, listed)?;
90            remove_dir_if_empty(&path)?;
91            continue
92        }
93        if listed.contains(&path) {
94            continue
95        }
96
97        // Windows removes a symlink to a directory with `remove_dir`, not `remove_file`.
98        #[cfg(windows)]
99        if std::os::windows::fs::FileTypeExt::is_symlink_dir(&file_type) {
100            std::fs::remove_dir(&path)
101                .wrap_err_with(|| format!("failed to remove {}", path.display()))?;
102            removed += 1;
103            continue
104        }
105        fs::remove_file(&path)?;
106        removed += 1;
107    }
108    Ok(removed)
109}
110
111/// Removes `dir` if pruning left it empty.
112fn remove_dir_if_empty(dir: &Path) -> Result<()> {
113    if fs::read_dir(dir)?.next().is_none() {
114        std::fs::remove_dir(dir)
115            .wrap_err_with(|| format!("failed to remove empty directory {}", dir.display()))?;
116    }
117    Ok(())
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use crate::download::manifest::{OutputFileChecksum, SnapshotArchive, SnapshotComponentType};
124    use tempfile::tempdir;
125
126    fn planned_with_outputs(paths: &[&str]) -> Vec<PlannedArchive> {
127        vec![PlannedArchive {
128            ty: SnapshotComponentType::State,
129            component: "State".to_string(),
130            archive: SnapshotArchive {
131                url: "https://example.com/state.tar.zst".to_string(),
132                file_name: "state.tar.zst".to_string(),
133                size: Some(1),
134                blake3: None,
135                output_files: paths
136                    .iter()
137                    .map(|path| OutputFileChecksum {
138                        path: (*path).to_string(),
139                        size: 1,
140                        blake3: String::new(),
141                    })
142                    .collect(),
143            },
144        }]
145    }
146
147    fn write_file(path: &Path) {
148        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
149        std::fs::write(path, b"data").unwrap();
150    }
151
152    #[test]
153    fn prune_removes_unlisted_files_and_keeps_listed_ones() {
154        let dir = tempdir().unwrap();
155        let target = dir.path();
156        let listed = ["db/mdbx.dat", "static_files/static_file_headers_0_499999"];
157        let leftovers = [
158            "db/stale.dat",
159            "rocksdb/000042.sst",
160            "static_files/static_file_headers_500000_999999",
161            "reth.toml",
162        ];
163        for path in listed.iter().chain(&leftovers).chain(&["known-peers.json"]) {
164            write_file(&target.join(path));
165        }
166
167        prune_unlisted_outputs(&planned_with_outputs(&listed), target, None).unwrap();
168
169        assert!(listed.iter().all(|path| target.join(path).exists()));
170        assert!(leftovers.iter().all(|path| !target.join(path).exists()));
171        assert!(target.join("known-peers.json").exists());
172    }
173
174    #[test]
175    fn prune_removes_nested_directories_it_empties_and_keeps_managed_ones() {
176        let dir = tempdir().unwrap();
177        write_file(&dir.path().join("rocksdb/nested/000042.sst"));
178
179        prune_unlisted_outputs(&planned_with_outputs(&["db/mdbx.dat"]), dir.path(), None).unwrap();
180
181        assert!(!dir.path().join("rocksdb/nested").exists());
182        assert!(dir.path().join("rocksdb").is_dir());
183    }
184
185    #[test]
186    fn prune_resolves_static_files_in_a_custom_directory() {
187        let dir = tempdir().unwrap();
188        let target = dir.path().join("datadir");
189        let static_files = dir.path().join("custom-static-files");
190        write_file(&static_files.join("static_file_headers_0_499999"));
191        write_file(&static_files.join("static_file_headers_500000_999999"));
192
193        prune_unlisted_outputs(
194            &planned_with_outputs(&["static_files/static_file_headers_0_499999"]),
195            &target,
196            Some(&static_files),
197        )
198        .unwrap();
199
200        assert!(static_files.join("static_file_headers_0_499999").exists());
201        assert!(!static_files.join("static_file_headers_500000_999999").exists());
202    }
203
204    #[test]
205    fn prune_skips_missing_managed_paths() {
206        let dir = tempdir().unwrap();
207
208        prune_unlisted_outputs(&planned_with_outputs(&["db/mdbx.dat"]), dir.path(), None).unwrap();
209
210        assert!(!dir.path().join("db").exists());
211    }
212
213    #[cfg(unix)]
214    #[test]
215    fn prune_removes_nested_symlinks_without_following_them() {
216        let dir = tempdir().unwrap();
217        let target = dir.path().join("datadir");
218        let outside = dir.path().join("outside");
219        write_file(&outside.join("unrelated.dat"));
220        write_file(&target.join("static_files/static_file_headers_0_499999"));
221        std::os::unix::fs::symlink(&outside, target.join("static_files/linked")).unwrap();
222
223        prune_unlisted_outputs(
224            &planned_with_outputs(&["static_files/static_file_headers_0_499999"]),
225            &target,
226            None,
227        )
228        .unwrap();
229
230        assert!(std::fs::symlink_metadata(target.join("static_files/linked")).is_err());
231        assert!(outside.join("unrelated.dat").exists());
232    }
233
234    #[cfg(unix)]
235    #[test]
236    fn prune_refuses_a_symlinked_managed_directory() {
237        let dir = tempdir().unwrap();
238        let target = dir.path().join("datadir");
239        let other_disk = dir.path().join("other-disk");
240        write_file(&other_disk.join("static_file_headers_0_499999"));
241        write_file(&other_disk.join("static_file_headers_500000_999999"));
242        std::fs::create_dir_all(&target).unwrap();
243        std::os::unix::fs::symlink(&other_disk, target.join("static_files")).unwrap();
244
245        let err = prune_unlisted_outputs(
246            &planned_with_outputs(&["static_files/static_file_headers_0_499999"]),
247            &target,
248            None,
249        )
250        .unwrap_err();
251
252        assert_eq!(
253            err.to_string(),
254            format!("Archive path `{}` contains a symlink", target.join("static_files").display())
255        );
256        assert!(std::fs::symlink_metadata(target.join("static_files")).unwrap().is_symlink());
257        assert!(other_disk.join("static_file_headers_0_499999").exists());
258        assert!(other_disk.join("static_file_headers_500000_999999").exists());
259    }
260}