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