reth_cli_commands/download/
prune.rs1use 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
16pub(crate) fn prune_unlisted_outputs(
35 planned: &[PlannedArchive],
36 target_dir: &Path,
37 static_files_dir: Option<&Path>,
38) -> Result<()> {
39 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
77fn 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 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 #[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
111fn 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}