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