]>
Commit | Line | Data |
---|---|---|
7759eef5 | 1 | use std::collections::{HashSet, HashMap}; |
54552dda | 2 | use std::io::{self, Write}; |
367f002e WB |
3 | use std::path::{Path, PathBuf}; |
4 | use std::sync::{Arc, Mutex}; | |
60f9a6ea | 5 | use std::convert::TryFrom; |
cb4b721c | 6 | use std::str::FromStr; |
1a374fcf | 7 | use std::time::Duration; |
367f002e | 8 | |
f7d4e4b5 | 9 | use anyhow::{bail, format_err, Error}; |
2c32fdde | 10 | use lazy_static::lazy_static; |
e4439025 | 11 | |
7526d864 | 12 | use proxmox::tools::fs::{replace_file, file_read_optional_string, CreateOptions}; |
529de6c7 | 13 | |
e7d4be9d | 14 | use pbs_api_types::{UPID, DataStoreConfig, Authid, GarbageCollectionStatus}; |
2f02e431 WB |
15 | use pbs_datastore::DataBlob; |
16 | use pbs_datastore::backup_info::{BackupGroup, BackupDir}; | |
17 | use pbs_datastore::chunk_store::ChunkStore; | |
18 | use pbs_datastore::dynamic_index::{DynamicIndexReader, DynamicIndexWriter}; | |
19 | use pbs_datastore::fixed_index::{FixedIndexReader, FixedIndexWriter}; | |
20 | use pbs_datastore::index::IndexFile; | |
21 | use pbs_datastore::manifest::{ | |
22 | MANIFEST_BLOB_NAME, MANIFEST_LOCK_NAME, CLIENT_LOG_BLOB_NAME, | |
23 | ArchiveType, BackupManifest, | |
24 | archive_type, | |
25 | }; | |
770a36e5 WB |
26 | use pbs_tools::format::HumanByte; |
27 | use pbs_tools::fs::{lock_dir_noblock, DirLockGuard}; | |
ccc3896f | 28 | use pbs_tools::process_locker::ProcessLockSharedGuard; |
c8449217 | 29 | use pbs_tools::{task_log, task_warn, task::WorkerTaskContext}; |
21211748 | 30 | use pbs_config::{open_backup_lockfile, BackupLockGuard}; |
529de6c7 | 31 | |
367f002e WB |
32 | lazy_static! { |
33 | static ref DATASTORE_MAP: Mutex<HashMap<String, Arc<DataStore>>> = Mutex::new(HashMap::new()); | |
b3483782 | 34 | } |
ff3d3100 | 35 | |
9751ef4b DC |
36 | /// checks if auth_id is owner, or, if owner is a token, if |
37 | /// auth_id is the user of the token | |
38 | pub fn check_backup_owner( | |
39 | owner: &Authid, | |
40 | auth_id: &Authid, | |
41 | ) -> Result<(), Error> { | |
42 | let correct_owner = owner == auth_id | |
43 | || (owner.is_token() && &Authid::from(owner.user().clone()) == auth_id); | |
44 | if !correct_owner { | |
45 | bail!("backup owner check failed ({} != {})", auth_id, owner); | |
46 | } | |
47 | Ok(()) | |
48 | } | |
49 | ||
e5064ba6 DM |
50 | /// Datastore Management |
51 | /// | |
52 | /// A Datastore can store severals backups, and provides the | |
53 | /// management interface for backup. | |
529de6c7 | 54 | pub struct DataStore { |
1629d2ad | 55 | chunk_store: Arc<ChunkStore>, |
81b2a872 | 56 | gc_mutex: Mutex<()>, |
f2b99c34 | 57 | last_gc_status: Mutex<GarbageCollectionStatus>, |
0698f78d | 58 | verify_new: bool, |
529de6c7 DM |
59 | } |
60 | ||
61 | impl DataStore { | |
62 | ||
2c32fdde DM |
63 | pub fn lookup_datastore(name: &str) -> Result<Arc<DataStore>, Error> { |
64 | ||
e7d4be9d DM |
65 | let (config, _digest) = pbs_config::datastore::config()?; |
66 | let config: DataStoreConfig = config.lookup("datastore", name)?; | |
df729017 | 67 | let path = PathBuf::from(&config.path); |
2c32fdde | 68 | |
515688d1 | 69 | let mut map = DATASTORE_MAP.lock().unwrap(); |
2c32fdde DM |
70 | |
71 | if let Some(datastore) = map.get(name) { | |
72 | // Compare Config - if changed, create new Datastore object! | |
c23192d3 | 73 | if datastore.chunk_store.base() == path && |
0698f78d SR |
74 | datastore.verify_new == config.verify_new.unwrap_or(false) |
75 | { | |
2c32fdde DM |
76 | return Ok(datastore.clone()); |
77 | } | |
78 | } | |
79 | ||
df729017 | 80 | let datastore = DataStore::open_with_path(name, &path, config)?; |
f0a61124 DM |
81 | |
82 | let datastore = Arc::new(datastore); | |
83 | map.insert(name.to_string(), datastore.clone()); | |
2c32fdde | 84 | |
f0a61124 | 85 | Ok(datastore) |
2c32fdde DM |
86 | } |
87 | ||
062cf75c DC |
88 | /// removes all datastores that are not configured anymore |
89 | pub fn remove_unused_datastores() -> Result<(), Error>{ | |
e7d4be9d | 90 | let (config, _digest) = pbs_config::datastore::config()?; |
062cf75c DC |
91 | |
92 | let mut map = DATASTORE_MAP.lock().unwrap(); | |
93 | // removes all elements that are not in the config | |
94 | map.retain(|key, _| { | |
95 | config.sections.contains_key(key) | |
96 | }); | |
97 | Ok(()) | |
98 | } | |
99 | ||
0698f78d | 100 | fn open_with_path(store_name: &str, path: &Path, config: DataStoreConfig) -> Result<Self, Error> { |
277fc5a3 | 101 | let chunk_store = ChunkStore::open(store_name, path)?; |
529de6c7 | 102 | |
b683fd58 DC |
103 | let mut gc_status_path = chunk_store.base_path(); |
104 | gc_status_path.push(".gc-status"); | |
105 | ||
106 | let gc_status = if let Some(state) = file_read_optional_string(gc_status_path)? { | |
107 | match serde_json::from_str(&state) { | |
108 | Ok(state) => state, | |
109 | Err(err) => { | |
110 | eprintln!("error reading gc-status: {}", err); | |
111 | GarbageCollectionStatus::default() | |
112 | } | |
113 | } | |
114 | } else { | |
115 | GarbageCollectionStatus::default() | |
116 | }; | |
f2b99c34 | 117 | |
529de6c7 | 118 | Ok(Self { |
1629d2ad | 119 | chunk_store: Arc::new(chunk_store), |
81b2a872 | 120 | gc_mutex: Mutex::new(()), |
f2b99c34 | 121 | last_gc_status: Mutex::new(gc_status), |
0698f78d | 122 | verify_new: config.verify_new.unwrap_or(false), |
529de6c7 DM |
123 | }) |
124 | } | |
125 | ||
d59397e6 WB |
126 | pub fn get_chunk_iterator( |
127 | &self, | |
128 | ) -> Result< | |
770a36e5 | 129 | impl Iterator<Item = (Result<pbs_tools::fs::ReadDirEntry, Error>, usize, bool)>, |
d59397e6 WB |
130 | Error |
131 | > { | |
a5736098 | 132 | self.chunk_store.get_chunk_iterator() |
d59397e6 WB |
133 | } |
134 | ||
91a905b6 | 135 | pub fn create_fixed_writer<P: AsRef<Path>>(&self, filename: P, size: usize, chunk_size: usize) -> Result<FixedIndexWriter, Error> { |
529de6c7 | 136 | |
91a905b6 | 137 | let index = FixedIndexWriter::create(self.chunk_store.clone(), filename.as_ref(), size, chunk_size)?; |
529de6c7 DM |
138 | |
139 | Ok(index) | |
140 | } | |
141 | ||
91a905b6 | 142 | pub fn open_fixed_reader<P: AsRef<Path>>(&self, filename: P) -> Result<FixedIndexReader, Error> { |
529de6c7 | 143 | |
a7c72ad9 DM |
144 | let full_path = self.chunk_store.relative_path(filename.as_ref()); |
145 | ||
146 | let index = FixedIndexReader::open(&full_path)?; | |
529de6c7 DM |
147 | |
148 | Ok(index) | |
149 | } | |
3d5c11e5 | 150 | |
93d5d779 | 151 | pub fn create_dynamic_writer<P: AsRef<Path>>( |
0433db19 | 152 | &self, filename: P, |
93d5d779 | 153 | ) -> Result<DynamicIndexWriter, Error> { |
0433db19 | 154 | |
93d5d779 | 155 | let index = DynamicIndexWriter::create( |
976595e1 | 156 | self.chunk_store.clone(), filename.as_ref())?; |
0433db19 DM |
157 | |
158 | Ok(index) | |
159 | } | |
ff3d3100 | 160 | |
93d5d779 | 161 | pub fn open_dynamic_reader<P: AsRef<Path>>(&self, filename: P) -> Result<DynamicIndexReader, Error> { |
77703d95 | 162 | |
d48a9955 DM |
163 | let full_path = self.chunk_store.relative_path(filename.as_ref()); |
164 | ||
165 | let index = DynamicIndexReader::open(&full_path)?; | |
77703d95 DM |
166 | |
167 | Ok(index) | |
168 | } | |
169 | ||
5de2bced WB |
170 | pub fn open_index<P>(&self, filename: P) -> Result<Box<dyn IndexFile + Send>, Error> |
171 | where | |
172 | P: AsRef<Path>, | |
173 | { | |
174 | let filename = filename.as_ref(); | |
175 | let out: Box<dyn IndexFile + Send> = | |
1e8da0a7 DM |
176 | match archive_type(filename)? { |
177 | ArchiveType::DynamicIndex => Box::new(self.open_dynamic_reader(filename)?), | |
178 | ArchiveType::FixedIndex => Box::new(self.open_fixed_reader(filename)?), | |
5de2bced WB |
179 | _ => bail!("cannot open index file of unknown type: {:?}", filename), |
180 | }; | |
181 | Ok(out) | |
182 | } | |
183 | ||
1369bcdb | 184 | /// Fast index verification - only check if chunks exists |
28570d19 DM |
185 | pub fn fast_index_verification( |
186 | &self, | |
187 | index: &dyn IndexFile, | |
188 | checked: &mut HashSet<[u8;32]>, | |
189 | ) -> Result<(), Error> { | |
1369bcdb DM |
190 | |
191 | for pos in 0..index.index_count() { | |
192 | let info = index.chunk_info(pos).unwrap(); | |
28570d19 DM |
193 | if checked.contains(&info.digest) { |
194 | continue; | |
195 | } | |
196 | ||
1369bcdb DM |
197 | self.stat_chunk(&info.digest). |
198 | map_err(|err| { | |
199 | format_err!( | |
200 | "fast_index_verification error, stat_chunk {} failed - {}", | |
201 | proxmox::tools::digest_to_hex(&info.digest), | |
202 | err, | |
203 | ) | |
204 | })?; | |
28570d19 DM |
205 | |
206 | checked.insert(info.digest); | |
1369bcdb DM |
207 | } |
208 | ||
209 | Ok(()) | |
210 | } | |
211 | ||
60f9a6ea DM |
212 | pub fn name(&self) -> &str { |
213 | self.chunk_store.name() | |
214 | } | |
215 | ||
ff3d3100 DM |
216 | pub fn base_path(&self) -> PathBuf { |
217 | self.chunk_store.base_path() | |
218 | } | |
219 | ||
c47e294e | 220 | /// Cleanup a backup directory |
7759eef5 DM |
221 | /// |
222 | /// Removes all files not mentioned in the manifest. | |
223 | pub fn cleanup_backup_dir(&self, backup_dir: &BackupDir, manifest: &BackupManifest | |
224 | ) -> Result<(), Error> { | |
225 | ||
226 | let mut full_path = self.base_path(); | |
227 | full_path.push(backup_dir.relative_path()); | |
228 | ||
229 | let mut wanted_files = HashSet::new(); | |
230 | wanted_files.insert(MANIFEST_BLOB_NAME.to_string()); | |
1610c45a | 231 | wanted_files.insert(CLIENT_LOG_BLOB_NAME.to_string()); |
7759eef5 DM |
232 | manifest.files().iter().for_each(|item| { wanted_files.insert(item.filename.clone()); }); |
233 | ||
770a36e5 | 234 | for item in pbs_tools::fs::read_subdir(libc::AT_FDCWD, &full_path)? { |
7759eef5 DM |
235 | if let Ok(item) = item { |
236 | if let Some(file_type) = item.file_type() { | |
237 | if file_type != nix::dir::Type::File { continue; } | |
238 | } | |
239 | let file_name = item.file_name().to_bytes(); | |
240 | if file_name == b"." || file_name == b".." { continue; }; | |
241 | ||
242 | if let Ok(name) = std::str::from_utf8(file_name) { | |
243 | if wanted_files.contains(name) { continue; } | |
244 | } | |
245 | println!("remove unused file {:?}", item.file_name()); | |
246 | let dirfd = item.parent_fd(); | |
247 | let _res = unsafe { libc::unlinkat(dirfd, item.file_name().as_ptr(), 0) }; | |
248 | } | |
249 | } | |
250 | ||
251 | Ok(()) | |
252 | } | |
4b4eba0b | 253 | |
41b373ec DM |
254 | /// Returns the absolute path for a backup_group |
255 | pub fn group_path(&self, backup_group: &BackupGroup) -> PathBuf { | |
4b4eba0b DM |
256 | let mut full_path = self.base_path(); |
257 | full_path.push(backup_group.group_path()); | |
41b373ec DM |
258 | full_path |
259 | } | |
260 | ||
261 | /// Returns the absolute path for backup_dir | |
262 | pub fn snapshot_path(&self, backup_dir: &BackupDir) -> PathBuf { | |
263 | let mut full_path = self.base_path(); | |
264 | full_path.push(backup_dir.relative_path()); | |
265 | full_path | |
266 | } | |
267 | ||
268 | /// Remove a complete backup group including all snapshots | |
6abce6c2 | 269 | pub fn remove_backup_group(&self, backup_group: &BackupGroup) -> Result<(), Error> { |
41b373ec DM |
270 | |
271 | let full_path = self.group_path(backup_group); | |
4b4eba0b | 272 | |
770a36e5 | 273 | let _guard = pbs_tools::fs::lock_dir_noblock(&full_path, "backup group", "possible running backup")?; |
c9756b40 | 274 | |
4b4eba0b | 275 | log::info!("removing backup group {:?}", full_path); |
4c0ae82e SR |
276 | |
277 | // remove all individual backup dirs first to ensure nothing is using them | |
278 | for snap in backup_group.list_backups(&self.base_path())? { | |
279 | self.remove_backup_dir(&snap.backup_dir, false)?; | |
280 | } | |
281 | ||
282 | // no snapshots left, we can now safely remove the empty folder | |
6abce6c2 | 283 | std::fs::remove_dir_all(&full_path) |
8a1d68c8 DM |
284 | .map_err(|err| { |
285 | format_err!( | |
4c0ae82e | 286 | "removing backup group directory {:?} failed - {}", |
8a1d68c8 DM |
287 | full_path, |
288 | err, | |
289 | ) | |
290 | })?; | |
4b4eba0b DM |
291 | |
292 | Ok(()) | |
293 | } | |
294 | ||
8f579717 | 295 | /// Remove a backup directory including all content |
c9756b40 | 296 | pub fn remove_backup_dir(&self, backup_dir: &BackupDir, force: bool) -> Result<(), Error> { |
8f579717 | 297 | |
41b373ec | 298 | let full_path = self.snapshot_path(backup_dir); |
8f579717 | 299 | |
1a374fcf | 300 | let (_guard, _manifest_guard); |
c9756b40 | 301 | if !force { |
238a872d | 302 | _guard = lock_dir_noblock(&full_path, "snapshot", "possibly running or in use")?; |
6bd0a00c | 303 | _manifest_guard = self.lock_manifest(backup_dir)?; |
c9756b40 SR |
304 | } |
305 | ||
8a1d68c8 | 306 | log::info!("removing backup snapshot {:?}", full_path); |
6abce6c2 | 307 | std::fs::remove_dir_all(&full_path) |
8a1d68c8 DM |
308 | .map_err(|err| { |
309 | format_err!( | |
310 | "removing backup snapshot {:?} failed - {}", | |
311 | full_path, | |
312 | err, | |
313 | ) | |
314 | })?; | |
8f579717 | 315 | |
179145dc DC |
316 | // the manifest does not exists anymore, we do not need to keep the lock |
317 | if let Ok(path) = self.manifest_lock_path(backup_dir) { | |
318 | // ignore errors | |
319 | let _ = std::fs::remove_file(path); | |
320 | } | |
321 | ||
8f579717 DM |
322 | Ok(()) |
323 | } | |
324 | ||
41b373ec DM |
325 | /// Returns the time of the last successful backup |
326 | /// | |
327 | /// Or None if there is no backup in the group (or the group dir does not exist). | |
6a7be83e | 328 | pub fn last_successful_backup(&self, backup_group: &BackupGroup) -> Result<Option<i64>, Error> { |
41b373ec DM |
329 | let base_path = self.base_path(); |
330 | let mut group_path = base_path.clone(); | |
331 | group_path.push(backup_group.group_path()); | |
332 | ||
333 | if group_path.exists() { | |
334 | backup_group.last_successful_backup(&base_path) | |
335 | } else { | |
336 | Ok(None) | |
337 | } | |
338 | } | |
339 | ||
54552dda DM |
340 | /// Returns the backup owner. |
341 | /// | |
e6dc35ac FG |
342 | /// The backup owner is the entity who first created the backup group. |
343 | pub fn get_owner(&self, backup_group: &BackupGroup) -> Result<Authid, Error> { | |
54552dda DM |
344 | let mut full_path = self.base_path(); |
345 | full_path.push(backup_group.group_path()); | |
346 | full_path.push("owner"); | |
347 | let owner = proxmox::tools::fs::file_read_firstline(full_path)?; | |
e7cb4dc5 | 348 | Ok(owner.trim_end().parse()?) // remove trailing newline |
54552dda DM |
349 | } |
350 | ||
9751ef4b DC |
351 | pub fn owns_backup(&self, backup_group: &BackupGroup, auth_id: &Authid) -> Result<bool, Error> { |
352 | let owner = self.get_owner(backup_group)?; | |
353 | ||
8e0b852f | 354 | Ok(check_backup_owner(&owner, auth_id).is_ok()) |
9751ef4b DC |
355 | } |
356 | ||
54552dda | 357 | /// Set the backup owner. |
e7cb4dc5 WB |
358 | pub fn set_owner( |
359 | &self, | |
360 | backup_group: &BackupGroup, | |
e6dc35ac | 361 | auth_id: &Authid, |
e7cb4dc5 WB |
362 | force: bool, |
363 | ) -> Result<(), Error> { | |
54552dda DM |
364 | let mut path = self.base_path(); |
365 | path.push(backup_group.group_path()); | |
366 | path.push("owner"); | |
367 | ||
368 | let mut open_options = std::fs::OpenOptions::new(); | |
369 | open_options.write(true); | |
370 | open_options.truncate(true); | |
371 | ||
372 | if force { | |
373 | open_options.create(true); | |
374 | } else { | |
375 | open_options.create_new(true); | |
376 | } | |
377 | ||
378 | let mut file = open_options.open(&path) | |
379 | .map_err(|err| format_err!("unable to create owner file {:?} - {}", path, err))?; | |
380 | ||
e6dc35ac | 381 | writeln!(file, "{}", auth_id) |
54552dda DM |
382 | .map_err(|err| format_err!("unable to write owner file {:?} - {}", path, err))?; |
383 | ||
384 | Ok(()) | |
385 | } | |
386 | ||
1fc82c41 | 387 | /// Create (if it does not already exists) and lock a backup group |
54552dda DM |
388 | /// |
389 | /// And set the owner to 'userid'. If the group already exists, it returns the | |
390 | /// current owner (instead of setting the owner). | |
1fc82c41 | 391 | /// |
1ffe0301 | 392 | /// This also acquires an exclusive lock on the directory and returns the lock guard. |
e7cb4dc5 WB |
393 | pub fn create_locked_backup_group( |
394 | &self, | |
395 | backup_group: &BackupGroup, | |
e6dc35ac FG |
396 | auth_id: &Authid, |
397 | ) -> Result<(Authid, DirLockGuard), Error> { | |
8731e40a | 398 | // create intermediate path first: |
44288184 | 399 | let mut full_path = self.base_path(); |
54552dda | 400 | full_path.push(backup_group.backup_type()); |
8731e40a WB |
401 | std::fs::create_dir_all(&full_path)?; |
402 | ||
54552dda DM |
403 | full_path.push(backup_group.backup_id()); |
404 | ||
405 | // create the last component now | |
406 | match std::fs::create_dir(&full_path) { | |
407 | Ok(_) => { | |
e4342585 | 408 | let guard = lock_dir_noblock(&full_path, "backup group", "another backup is already running")?; |
e6dc35ac | 409 | self.set_owner(backup_group, auth_id, false)?; |
54552dda | 410 | let owner = self.get_owner(backup_group)?; // just to be sure |
1fc82c41 | 411 | Ok((owner, guard)) |
54552dda DM |
412 | } |
413 | Err(ref err) if err.kind() == io::ErrorKind::AlreadyExists => { | |
e4342585 | 414 | let guard = lock_dir_noblock(&full_path, "backup group", "another backup is already running")?; |
54552dda | 415 | let owner = self.get_owner(backup_group)?; // just to be sure |
1fc82c41 | 416 | Ok((owner, guard)) |
54552dda DM |
417 | } |
418 | Err(err) => bail!("unable to create backup group {:?} - {}", full_path, err), | |
419 | } | |
420 | } | |
421 | ||
422 | /// Creates a new backup snapshot inside a BackupGroup | |
423 | /// | |
424 | /// The BackupGroup directory needs to exist. | |
f23f7543 SR |
425 | pub fn create_locked_backup_dir(&self, backup_dir: &BackupDir) |
426 | -> Result<(PathBuf, bool, DirLockGuard), Error> | |
427 | { | |
b3483782 DM |
428 | let relative_path = backup_dir.relative_path(); |
429 | let mut full_path = self.base_path(); | |
430 | full_path.push(&relative_path); | |
ff3d3100 | 431 | |
f23f7543 SR |
432 | let lock = || |
433 | lock_dir_noblock(&full_path, "snapshot", "internal error - tried creating snapshot that's already in use"); | |
434 | ||
8731e40a | 435 | match std::fs::create_dir(&full_path) { |
f23f7543 SR |
436 | Ok(_) => Ok((relative_path, true, lock()?)), |
437 | Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok((relative_path, false, lock()?)), | |
438 | Err(e) => Err(e.into()) | |
8731e40a | 439 | } |
ff3d3100 DM |
440 | } |
441 | ||
3d5c11e5 | 442 | pub fn list_images(&self) -> Result<Vec<PathBuf>, Error> { |
ff3d3100 | 443 | let base = self.base_path(); |
3d5c11e5 DM |
444 | |
445 | let mut list = vec![]; | |
446 | ||
95cea65b DM |
447 | use walkdir::WalkDir; |
448 | ||
84466003 | 449 | let walker = WalkDir::new(&base).into_iter(); |
95cea65b DM |
450 | |
451 | // make sure we skip .chunks (and other hidden files to keep it simple) | |
452 | fn is_hidden(entry: &walkdir::DirEntry) -> bool { | |
453 | entry.file_name() | |
454 | .to_str() | |
d8d8af98 | 455 | .map(|s| s.starts_with('.')) |
95cea65b DM |
456 | .unwrap_or(false) |
457 | } | |
c3b090ac TL |
458 | let handle_entry_err = |err: walkdir::Error| { |
459 | if let Some(inner) = err.io_error() { | |
d08cff51 FG |
460 | if let Some(path) = err.path() { |
461 | if inner.kind() == io::ErrorKind::PermissionDenied { | |
c3b090ac TL |
462 | // only allow to skip ext4 fsck directory, avoid GC if, for example, |
463 | // a user got file permissions wrong on datastore rsync to new server | |
464 | if err.depth() > 1 || !path.ends_with("lost+found") { | |
d08cff51 | 465 | bail!("cannot continue garbage-collection safely, permission denied on: {:?}", path) |
c3b090ac | 466 | } |
d08cff51 FG |
467 | } else { |
468 | bail!("unexpected error on datastore traversal: {} - {:?}", inner, path) | |
469 | } | |
470 | } else { | |
471 | bail!("unexpected error on datastore traversal: {}", inner) | |
c3b090ac TL |
472 | } |
473 | } | |
474 | Ok(()) | |
475 | }; | |
95cea65b | 476 | for entry in walker.filter_entry(|e| !is_hidden(e)) { |
c3b090ac TL |
477 | let path = match entry { |
478 | Ok(entry) => entry.into_path(), | |
479 | Err(err) => { | |
480 | handle_entry_err(err)?; | |
481 | continue | |
482 | }, | |
483 | }; | |
1e8da0a7 DM |
484 | if let Ok(archive_type) = archive_type(&path) { |
485 | if archive_type == ArchiveType::FixedIndex || archive_type == ArchiveType::DynamicIndex { | |
95cea65b | 486 | list.push(path); |
3d5c11e5 DM |
487 | } |
488 | } | |
489 | } | |
490 | ||
491 | Ok(list) | |
492 | } | |
493 | ||
a660978c DM |
494 | // mark chunks used by ``index`` as used |
495 | fn index_mark_used_chunks<I: IndexFile>( | |
496 | &self, | |
497 | index: I, | |
498 | file_name: &Path, // only used for error reporting | |
499 | status: &mut GarbageCollectionStatus, | |
c8449217 | 500 | worker: &dyn WorkerTaskContext, |
a660978c DM |
501 | ) -> Result<(), Error> { |
502 | ||
503 | status.index_file_count += 1; | |
504 | status.index_data_bytes += index.index_bytes(); | |
505 | ||
506 | for pos in 0..index.index_count() { | |
f6b1d1cc | 507 | worker.check_abort()?; |
0fd55b08 | 508 | worker.fail_on_shutdown()?; |
a660978c | 509 | let digest = index.index_digest(pos).unwrap(); |
1399c592 | 510 | if !self.chunk_store.cond_touch_chunk(digest, false)? { |
c23192d3 | 511 | task_warn!( |
f6b1d1cc | 512 | worker, |
d1d74c43 | 513 | "warning: unable to access non-existent chunk {}, required by {:?}", |
f6b1d1cc WB |
514 | proxmox::tools::digest_to_hex(digest), |
515 | file_name, | |
f6b1d1cc | 516 | ); |
fd192564 SR |
517 | |
518 | // touch any corresponding .bad files to keep them around, meaning if a chunk is | |
519 | // rewritten correctly they will be removed automatically, as well as if no index | |
520 | // file requires the chunk anymore (won't get to this loop then) | |
521 | for i in 0..=9 { | |
522 | let bad_ext = format!("{}.bad", i); | |
523 | let mut bad_path = PathBuf::new(); | |
524 | bad_path.push(self.chunk_path(digest).0); | |
525 | bad_path.set_extension(bad_ext); | |
526 | self.chunk_store.cond_touch_path(&bad_path, false)?; | |
527 | } | |
a660978c DM |
528 | } |
529 | } | |
530 | Ok(()) | |
531 | } | |
532 | ||
f6b1d1cc WB |
533 | fn mark_used_chunks( |
534 | &self, | |
535 | status: &mut GarbageCollectionStatus, | |
c8449217 | 536 | worker: &dyn WorkerTaskContext, |
f6b1d1cc | 537 | ) -> Result<(), Error> { |
3d5c11e5 DM |
538 | |
539 | let image_list = self.list_images()?; | |
8317873c DM |
540 | let image_count = image_list.len(); |
541 | ||
8317873c DM |
542 | let mut last_percentage: usize = 0; |
543 | ||
cb4b721c FG |
544 | let mut strange_paths_count: u64 = 0; |
545 | ||
ea368a06 | 546 | for (i, img) in image_list.into_iter().enumerate() { |
92da93b2 | 547 | |
f6b1d1cc | 548 | worker.check_abort()?; |
0fd55b08 | 549 | worker.fail_on_shutdown()?; |
92da93b2 | 550 | |
cb4b721c FG |
551 | if let Some(backup_dir_path) = img.parent() { |
552 | let backup_dir_path = backup_dir_path.strip_prefix(self.base_path())?; | |
553 | if let Some(backup_dir_str) = backup_dir_path.to_str() { | |
554 | if BackupDir::from_str(backup_dir_str).is_err() { | |
555 | strange_paths_count += 1; | |
556 | } | |
557 | } | |
558 | } | |
559 | ||
efcac39d | 560 | match std::fs::File::open(&img) { |
e0762002 | 561 | Ok(file) => { |
788d82d9 | 562 | if let Ok(archive_type) = archive_type(&img) { |
e0762002 | 563 | if archive_type == ArchiveType::FixedIndex { |
788d82d9 | 564 | let index = FixedIndexReader::new(file).map_err(|e| { |
efcac39d | 565 | format_err!("can't read index '{}' - {}", img.to_string_lossy(), e) |
2f0b9235 | 566 | })?; |
788d82d9 | 567 | self.index_mark_used_chunks(index, &img, status, worker)?; |
e0762002 | 568 | } else if archive_type == ArchiveType::DynamicIndex { |
788d82d9 | 569 | let index = DynamicIndexReader::new(file).map_err(|e| { |
efcac39d | 570 | format_err!("can't read index '{}' - {}", img.to_string_lossy(), e) |
2f0b9235 | 571 | })?; |
788d82d9 | 572 | self.index_mark_used_chunks(index, &img, status, worker)?; |
e0762002 DM |
573 | } |
574 | } | |
575 | } | |
788d82d9 | 576 | Err(err) if err.kind() == io::ErrorKind::NotFound => (), // ignore vanished files |
efcac39d | 577 | Err(err) => bail!("can't open index {} - {}", img.to_string_lossy(), err), |
77703d95 | 578 | } |
8317873c | 579 | |
ea368a06 | 580 | let percentage = (i + 1) * 100 / image_count; |
8317873c | 581 | if percentage > last_percentage { |
c23192d3 | 582 | task_log!( |
f6b1d1cc | 583 | worker, |
7956877f | 584 | "marked {}% ({} of {} index files)", |
f6b1d1cc | 585 | percentage, |
ea368a06 | 586 | i + 1, |
f6b1d1cc WB |
587 | image_count, |
588 | ); | |
8317873c DM |
589 | last_percentage = percentage; |
590 | } | |
3d5c11e5 DM |
591 | } |
592 | ||
cb4b721c | 593 | if strange_paths_count > 0 { |
c23192d3 | 594 | task_log!( |
cb4b721c FG |
595 | worker, |
596 | "found (and marked) {} index files outside of expected directory scheme", | |
597 | strange_paths_count, | |
598 | ); | |
599 | } | |
600 | ||
601 | ||
3d5c11e5 | 602 | Ok(()) |
f2b99c34 DM |
603 | } |
604 | ||
605 | pub fn last_gc_status(&self) -> GarbageCollectionStatus { | |
606 | self.last_gc_status.lock().unwrap().clone() | |
607 | } | |
3d5c11e5 | 608 | |
8545480a | 609 | pub fn garbage_collection_running(&self) -> bool { |
a6bd6698 | 610 | !matches!(self.gc_mutex.try_lock(), Ok(_)) |
8545480a DM |
611 | } |
612 | ||
c8449217 | 613 | pub fn garbage_collection(&self, worker: &dyn WorkerTaskContext, upid: &UPID) -> Result<(), Error> { |
3d5c11e5 | 614 | |
a198d74f | 615 | if let Ok(ref mut _mutex) = self.gc_mutex.try_lock() { |
e95950e4 | 616 | |
c6772c92 TL |
617 | // avoids that we run GC if an old daemon process has still a |
618 | // running backup writer, which is not save as we have no "oldest | |
619 | // writer" information and thus no safe atime cutoff | |
43b13033 DM |
620 | let _exclusive_lock = self.chunk_store.try_exclusive_lock()?; |
621 | ||
823867f5 | 622 | let phase1_start_time = proxmox::tools::time::epoch_i64(); |
49a92084 | 623 | let oldest_writer = self.chunk_store.oldest_writer().unwrap_or(phase1_start_time); |
11861a48 | 624 | |
64e53b28 | 625 | let mut gc_status = GarbageCollectionStatus::default(); |
f6b1d1cc WB |
626 | gc_status.upid = Some(upid.to_string()); |
627 | ||
c23192d3 | 628 | task_log!(worker, "Start GC phase1 (mark used chunks)"); |
f6b1d1cc WB |
629 | |
630 | self.mark_used_chunks(&mut gc_status, worker)?; | |
631 | ||
c23192d3 | 632 | task_log!(worker, "Start GC phase2 (sweep unused chunks)"); |
f6b1d1cc WB |
633 | self.chunk_store.sweep_unused_chunks( |
634 | oldest_writer, | |
635 | phase1_start_time, | |
636 | &mut gc_status, | |
637 | worker, | |
638 | )?; | |
639 | ||
c23192d3 | 640 | task_log!( |
f6b1d1cc WB |
641 | worker, |
642 | "Removed garbage: {}", | |
643 | HumanByte::from(gc_status.removed_bytes), | |
644 | ); | |
c23192d3 | 645 | task_log!(worker, "Removed chunks: {}", gc_status.removed_chunks); |
cf459b19 | 646 | if gc_status.pending_bytes > 0 { |
c23192d3 | 647 | task_log!( |
f6b1d1cc WB |
648 | worker, |
649 | "Pending removals: {} (in {} chunks)", | |
650 | HumanByte::from(gc_status.pending_bytes), | |
651 | gc_status.pending_chunks, | |
652 | ); | |
cf459b19 | 653 | } |
a9767cf7 | 654 | if gc_status.removed_bad > 0 { |
c23192d3 | 655 | task_log!(worker, "Removed bad chunks: {}", gc_status.removed_bad); |
a9767cf7 | 656 | } |
cf459b19 | 657 | |
b4fb2623 | 658 | if gc_status.still_bad > 0 { |
c23192d3 | 659 | task_log!(worker, "Leftover bad chunks: {}", gc_status.still_bad); |
b4fb2623 DM |
660 | } |
661 | ||
c23192d3 | 662 | task_log!( |
f6b1d1cc WB |
663 | worker, |
664 | "Original data usage: {}", | |
665 | HumanByte::from(gc_status.index_data_bytes), | |
666 | ); | |
868c5852 DM |
667 | |
668 | if gc_status.index_data_bytes > 0 { | |
49a92084 | 669 | let comp_per = (gc_status.disk_bytes as f64 * 100.)/gc_status.index_data_bytes as f64; |
c23192d3 | 670 | task_log!( |
f6b1d1cc WB |
671 | worker, |
672 | "On-Disk usage: {} ({:.2}%)", | |
673 | HumanByte::from(gc_status.disk_bytes), | |
674 | comp_per, | |
675 | ); | |
868c5852 DM |
676 | } |
677 | ||
c23192d3 | 678 | task_log!(worker, "On-Disk chunks: {}", gc_status.disk_chunks); |
868c5852 | 679 | |
d6373f35 DM |
680 | let deduplication_factor = if gc_status.disk_bytes > 0 { |
681 | (gc_status.index_data_bytes as f64)/(gc_status.disk_bytes as f64) | |
682 | } else { | |
683 | 1.0 | |
684 | }; | |
685 | ||
c23192d3 | 686 | task_log!(worker, "Deduplication factor: {:.2}", deduplication_factor); |
d6373f35 | 687 | |
868c5852 DM |
688 | if gc_status.disk_chunks > 0 { |
689 | let avg_chunk = gc_status.disk_bytes/(gc_status.disk_chunks as u64); | |
c23192d3 | 690 | task_log!(worker, "Average chunk size: {}", HumanByte::from(avg_chunk)); |
868c5852 | 691 | } |
64e53b28 | 692 | |
b683fd58 DC |
693 | if let Ok(serialized) = serde_json::to_string(&gc_status) { |
694 | let mut path = self.base_path(); | |
695 | path.push(".gc-status"); | |
696 | ||
21211748 | 697 | let backup_user = pbs_config::backup_user()?; |
b683fd58 DC |
698 | let mode = nix::sys::stat::Mode::from_bits_truncate(0o0644); |
699 | // set the correct owner/group/permissions while saving file | |
700 | // owner(rw) = backup, group(r)= backup | |
701 | let options = CreateOptions::new() | |
702 | .perm(mode) | |
703 | .owner(backup_user.uid) | |
704 | .group(backup_user.gid); | |
705 | ||
706 | // ignore errors | |
707 | let _ = replace_file(path, serialized.as_bytes(), options); | |
708 | } | |
709 | ||
f2b99c34 DM |
710 | *self.last_gc_status.lock().unwrap() = gc_status; |
711 | ||
64e53b28 | 712 | } else { |
d4b59ae0 | 713 | bail!("Start GC failed - (already running/locked)"); |
64e53b28 | 714 | } |
3d5c11e5 DM |
715 | |
716 | Ok(()) | |
717 | } | |
3b7ade9e | 718 | |
ccc3896f | 719 | pub fn try_shared_chunk_store_lock(&self) -> Result<ProcessLockSharedGuard, Error> { |
1cf5178a DM |
720 | self.chunk_store.try_shared_lock() |
721 | } | |
722 | ||
d48a9955 DM |
723 | pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) { |
724 | self.chunk_store.chunk_path(digest) | |
725 | } | |
726 | ||
2585a8a4 DM |
727 | pub fn cond_touch_chunk(&self, digest: &[u8; 32], fail_if_not_exist: bool) -> Result<bool, Error> { |
728 | self.chunk_store.cond_touch_chunk(digest, fail_if_not_exist) | |
729 | } | |
730 | ||
f98ac774 | 731 | pub fn insert_chunk( |
3b7ade9e | 732 | &self, |
4ee8f53d DM |
733 | chunk: &DataBlob, |
734 | digest: &[u8; 32], | |
3b7ade9e | 735 | ) -> Result<(bool, u64), Error> { |
4ee8f53d | 736 | self.chunk_store.insert_chunk(chunk, digest) |
3b7ade9e | 737 | } |
60f9a6ea | 738 | |
39f18b30 | 739 | pub fn load_blob(&self, backup_dir: &BackupDir, filename: &str) -> Result<DataBlob, Error> { |
60f9a6ea DM |
740 | let mut path = self.base_path(); |
741 | path.push(backup_dir.relative_path()); | |
742 | path.push(filename); | |
743 | ||
39f18b30 DM |
744 | proxmox::try_block!({ |
745 | let mut file = std::fs::File::open(&path)?; | |
746 | DataBlob::load_from_reader(&mut file) | |
747 | }).map_err(|err| format_err!("unable to load blob '{:?}' - {}", path, err)) | |
748 | } | |
e4439025 DM |
749 | |
750 | ||
7f394c80 DC |
751 | pub fn stat_chunk(&self, digest: &[u8; 32]) -> Result<std::fs::Metadata, Error> { |
752 | let (chunk_path, _digest_str) = self.chunk_store.chunk_path(digest); | |
753 | std::fs::metadata(chunk_path).map_err(Error::from) | |
754 | } | |
755 | ||
39f18b30 DM |
756 | pub fn load_chunk(&self, digest: &[u8; 32]) -> Result<DataBlob, Error> { |
757 | ||
758 | let (chunk_path, digest_str) = self.chunk_store.chunk_path(digest); | |
759 | ||
760 | proxmox::try_block!({ | |
761 | let mut file = std::fs::File::open(&chunk_path)?; | |
762 | DataBlob::load_from_reader(&mut file) | |
763 | }).map_err(|err| format_err!( | |
764 | "store '{}', unable to load chunk '{}' - {}", | |
765 | self.name(), | |
766 | digest_str, | |
767 | err, | |
768 | )) | |
1a374fcf SR |
769 | } |
770 | ||
179145dc DC |
771 | /// Returns the filename to lock a manifest |
772 | /// | |
773 | /// Also creates the basedir. The lockfile is located in | |
774 | /// '/run/proxmox-backup/locks/{datastore}/{type}/{id}/{timestamp}.index.json.lck' | |
775 | fn manifest_lock_path( | |
776 | &self, | |
777 | backup_dir: &BackupDir, | |
778 | ) -> Result<String, Error> { | |
779 | let mut path = format!( | |
780 | "/run/proxmox-backup/locks/{}/{}/{}", | |
781 | self.name(), | |
782 | backup_dir.group().backup_type(), | |
783 | backup_dir.group().backup_id(), | |
784 | ); | |
785 | std::fs::create_dir_all(&path)?; | |
786 | use std::fmt::Write; | |
787 | write!(path, "/{}{}", backup_dir.backup_time_string(), &MANIFEST_LOCK_NAME)?; | |
788 | ||
789 | Ok(path) | |
790 | } | |
791 | ||
1a374fcf SR |
792 | fn lock_manifest( |
793 | &self, | |
794 | backup_dir: &BackupDir, | |
7526d864 | 795 | ) -> Result<BackupLockGuard, Error> { |
179145dc | 796 | let path = self.manifest_lock_path(backup_dir)?; |
1a374fcf SR |
797 | |
798 | // update_manifest should never take a long time, so if someone else has | |
799 | // the lock we can simply block a bit and should get it soon | |
7526d864 | 800 | open_backup_lockfile(&path, Some(Duration::from_secs(5)), true) |
1a374fcf SR |
801 | .map_err(|err| { |
802 | format_err!( | |
803 | "unable to acquire manifest lock {:?} - {}", &path, err | |
804 | ) | |
805 | }) | |
806 | } | |
e4439025 | 807 | |
1a374fcf | 808 | /// Load the manifest without a lock. Must not be written back. |
521a0acb WB |
809 | pub fn load_manifest( |
810 | &self, | |
811 | backup_dir: &BackupDir, | |
ff86ef00 | 812 | ) -> Result<(BackupManifest, u64), Error> { |
39f18b30 DM |
813 | let blob = self.load_blob(backup_dir, MANIFEST_BLOB_NAME)?; |
814 | let raw_size = blob.raw_size(); | |
60f9a6ea | 815 | let manifest = BackupManifest::try_from(blob)?; |
ff86ef00 | 816 | Ok((manifest, raw_size)) |
60f9a6ea | 817 | } |
e4439025 | 818 | |
1a374fcf SR |
819 | /// Update the manifest of the specified snapshot. Never write a manifest directly, |
820 | /// only use this method - anything else may break locking guarantees. | |
821 | pub fn update_manifest( | |
e4439025 DM |
822 | &self, |
823 | backup_dir: &BackupDir, | |
1a374fcf | 824 | update_fn: impl FnOnce(&mut BackupManifest), |
e4439025 | 825 | ) -> Result<(), Error> { |
1a374fcf SR |
826 | |
827 | let _guard = self.lock_manifest(backup_dir)?; | |
828 | let (mut manifest, _) = self.load_manifest(&backup_dir)?; | |
829 | ||
830 | update_fn(&mut manifest); | |
831 | ||
883aa6d5 | 832 | let manifest = serde_json::to_value(manifest)?; |
e4439025 DM |
833 | let manifest = serde_json::to_string_pretty(&manifest)?; |
834 | let blob = DataBlob::encode(manifest.as_bytes(), None, true)?; | |
835 | let raw_data = blob.raw_data(); | |
836 | ||
837 | let mut path = self.base_path(); | |
838 | path.push(backup_dir.relative_path()); | |
839 | path.push(MANIFEST_BLOB_NAME); | |
840 | ||
1a374fcf | 841 | // atomic replace invalidates flock - no other writes past this point! |
e4439025 DM |
842 | replace_file(&path, raw_data, CreateOptions::new())?; |
843 | ||
844 | Ok(()) | |
845 | } | |
0698f78d SR |
846 | |
847 | pub fn verify_new(&self) -> bool { | |
848 | self.verify_new | |
849 | } | |
4921a411 DC |
850 | |
851 | /// returns a list of chunks sorted by their inode number on disk | |
852 | /// chunks that could not be stat'ed are at the end of the list | |
853 | pub fn get_chunks_in_order<F, A>( | |
854 | &self, | |
855 | index: &Box<dyn IndexFile + Send>, | |
856 | skip_chunk: F, | |
857 | check_abort: A, | |
858 | ) -> Result<Vec<(usize, u64)>, Error> | |
859 | where | |
860 | F: Fn(&[u8; 32]) -> bool, | |
861 | A: Fn(usize) -> Result<(), Error>, | |
862 | { | |
863 | let index_count = index.index_count(); | |
864 | let mut chunk_list = Vec::with_capacity(index_count); | |
865 | use std::os::unix::fs::MetadataExt; | |
866 | for pos in 0..index_count { | |
867 | check_abort(pos)?; | |
868 | ||
869 | let info = index.chunk_info(pos).unwrap(); | |
870 | ||
871 | if skip_chunk(&info.digest) { | |
872 | continue; | |
873 | } | |
874 | ||
875 | let ino = match self.stat_chunk(&info.digest) { | |
876 | Err(_) => u64::MAX, // could not stat, move to end of list | |
877 | Ok(metadata) => metadata.ino(), | |
878 | }; | |
879 | ||
880 | chunk_list.push((pos, ino)); | |
881 | } | |
882 | ||
883 | // sorting by inode improves data locality, which makes it lots faster on spinners | |
884 | chunk_list.sort_unstable_by(|(_, ino_a), (_, ino_b)| ino_a.cmp(&ino_b)); | |
885 | ||
886 | Ok(chunk_list) | |
887 | } | |
529de6c7 | 888 | } |