]> git.proxmox.com Git - proxmox-backup.git/blob - src/backup/datastore.rs
gc: use human readable units for summary
[proxmox-backup.git] / src / backup / datastore.rs
1 use std::collections::{HashSet, HashMap};
2 use std::io::{self, Write};
3 use std::path::{Path, PathBuf};
4 use std::sync::{Arc, Mutex};
5 use std::convert::TryFrom;
6
7 use anyhow::{bail, format_err, Error};
8 use lazy_static::lazy_static;
9 use chrono::{DateTime, Utc};
10 use serde_json::Value;
11
12 use proxmox::tools::fs::{replace_file, CreateOptions};
13
14 use super::backup_info::{BackupGroup, BackupDir};
15 use super::chunk_store::ChunkStore;
16 use super::dynamic_index::{DynamicIndexReader, DynamicIndexWriter};
17 use super::fixed_index::{FixedIndexReader, FixedIndexWriter};
18 use super::manifest::{MANIFEST_BLOB_NAME, CLIENT_LOG_BLOB_NAME, BackupManifest};
19 use super::index::*;
20 use super::{DataBlob, ArchiveType, archive_type};
21 use crate::config::datastore;
22 use crate::server::WorkerTask;
23 use crate::tools;
24 use crate::tools::format::HumanByte;
25 use crate::tools::fs::{lock_dir_noblock, DirLockGuard};
26 use crate::api2::types::{GarbageCollectionStatus, Userid};
27
28 lazy_static! {
29 static ref DATASTORE_MAP: Mutex<HashMap<String, Arc<DataStore>>> = Mutex::new(HashMap::new());
30 }
31
32 /// Datastore Management
33 ///
34 /// A Datastore can store severals backups, and provides the
35 /// management interface for backup.
36 pub struct DataStore {
37 chunk_store: Arc<ChunkStore>,
38 gc_mutex: Mutex<bool>,
39 last_gc_status: Mutex<GarbageCollectionStatus>,
40 }
41
42 impl DataStore {
43
44 pub fn lookup_datastore(name: &str) -> Result<Arc<DataStore>, Error> {
45
46 let (config, _digest) = datastore::config()?;
47 let config: datastore::DataStoreConfig = config.lookup("datastore", name)?;
48
49 let mut map = DATASTORE_MAP.lock().unwrap();
50
51 if let Some(datastore) = map.get(name) {
52 // Compare Config - if changed, create new Datastore object!
53 if datastore.chunk_store.base == PathBuf::from(&config.path) {
54 return Ok(datastore.clone());
55 }
56 }
57
58 let datastore = DataStore::open(name)?;
59
60 let datastore = Arc::new(datastore);
61 map.insert(name.to_string(), datastore.clone());
62
63 Ok(datastore)
64 }
65
66 pub fn open(store_name: &str) -> Result<Self, Error> {
67
68 let (config, _digest) = datastore::config()?;
69 let (_, store_config) = config.sections.get(store_name)
70 .ok_or(format_err!("no such datastore '{}'", store_name))?;
71
72 let path = store_config["path"].as_str().unwrap();
73
74 let chunk_store = ChunkStore::open(store_name, path)?;
75
76 let gc_status = GarbageCollectionStatus::default();
77
78 Ok(Self {
79 chunk_store: Arc::new(chunk_store),
80 gc_mutex: Mutex::new(false),
81 last_gc_status: Mutex::new(gc_status),
82 })
83 }
84
85 pub fn get_chunk_iterator(
86 &self,
87 ) -> Result<
88 impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize)>,
89 Error
90 > {
91 self.chunk_store.get_chunk_iterator()
92 }
93
94 pub fn create_fixed_writer<P: AsRef<Path>>(&self, filename: P, size: usize, chunk_size: usize) -> Result<FixedIndexWriter, Error> {
95
96 let index = FixedIndexWriter::create(self.chunk_store.clone(), filename.as_ref(), size, chunk_size)?;
97
98 Ok(index)
99 }
100
101 pub fn open_fixed_reader<P: AsRef<Path>>(&self, filename: P) -> Result<FixedIndexReader, Error> {
102
103 let full_path = self.chunk_store.relative_path(filename.as_ref());
104
105 let index = FixedIndexReader::open(&full_path)?;
106
107 Ok(index)
108 }
109
110 pub fn create_dynamic_writer<P: AsRef<Path>>(
111 &self, filename: P,
112 ) -> Result<DynamicIndexWriter, Error> {
113
114 let index = DynamicIndexWriter::create(
115 self.chunk_store.clone(), filename.as_ref())?;
116
117 Ok(index)
118 }
119
120 pub fn open_dynamic_reader<P: AsRef<Path>>(&self, filename: P) -> Result<DynamicIndexReader, Error> {
121
122 let full_path = self.chunk_store.relative_path(filename.as_ref());
123
124 let index = DynamicIndexReader::open(&full_path)?;
125
126 Ok(index)
127 }
128
129 pub fn open_index<P>(&self, filename: P) -> Result<Box<dyn IndexFile + Send>, Error>
130 where
131 P: AsRef<Path>,
132 {
133 let filename = filename.as_ref();
134 let out: Box<dyn IndexFile + Send> =
135 match archive_type(filename)? {
136 ArchiveType::DynamicIndex => Box::new(self.open_dynamic_reader(filename)?),
137 ArchiveType::FixedIndex => Box::new(self.open_fixed_reader(filename)?),
138 _ => bail!("cannot open index file of unknown type: {:?}", filename),
139 };
140 Ok(out)
141 }
142
143 pub fn name(&self) -> &str {
144 self.chunk_store.name()
145 }
146
147 pub fn base_path(&self) -> PathBuf {
148 self.chunk_store.base_path()
149 }
150
151 /// Cleanup a backup directory
152 ///
153 /// Removes all files not mentioned in the manifest.
154 pub fn cleanup_backup_dir(&self, backup_dir: &BackupDir, manifest: &BackupManifest
155 ) -> Result<(), Error> {
156
157 let mut full_path = self.base_path();
158 full_path.push(backup_dir.relative_path());
159
160 let mut wanted_files = HashSet::new();
161 wanted_files.insert(MANIFEST_BLOB_NAME.to_string());
162 wanted_files.insert(CLIENT_LOG_BLOB_NAME.to_string());
163 manifest.files().iter().for_each(|item| { wanted_files.insert(item.filename.clone()); });
164
165 for item in tools::fs::read_subdir(libc::AT_FDCWD, &full_path)? {
166 if let Ok(item) = item {
167 if let Some(file_type) = item.file_type() {
168 if file_type != nix::dir::Type::File { continue; }
169 }
170 let file_name = item.file_name().to_bytes();
171 if file_name == b"." || file_name == b".." { continue; };
172
173 if let Ok(name) = std::str::from_utf8(file_name) {
174 if wanted_files.contains(name) { continue; }
175 }
176 println!("remove unused file {:?}", item.file_name());
177 let dirfd = item.parent_fd();
178 let _res = unsafe { libc::unlinkat(dirfd, item.file_name().as_ptr(), 0) };
179 }
180 }
181
182 Ok(())
183 }
184
185 /// Returns the absolute path for a backup_group
186 pub fn group_path(&self, backup_group: &BackupGroup) -> PathBuf {
187 let mut full_path = self.base_path();
188 full_path.push(backup_group.group_path());
189 full_path
190 }
191
192 /// Returns the absolute path for backup_dir
193 pub fn snapshot_path(&self, backup_dir: &BackupDir) -> PathBuf {
194 let mut full_path = self.base_path();
195 full_path.push(backup_dir.relative_path());
196 full_path
197 }
198
199 /// Remove a complete backup group including all snapshots
200 pub fn remove_backup_group(&self, backup_group: &BackupGroup) -> Result<(), Error> {
201
202 let full_path = self.group_path(backup_group);
203
204 let _guard = tools::fs::lock_dir_noblock(&full_path, "backup group", "possible running backup")?;
205
206 log::info!("removing backup group {:?}", full_path);
207 std::fs::remove_dir_all(&full_path)
208 .map_err(|err| {
209 format_err!(
210 "removing backup group {:?} failed - {}",
211 full_path,
212 err,
213 )
214 })?;
215
216 Ok(())
217 }
218
219 /// Remove a backup directory including all content
220 pub fn remove_backup_dir(&self, backup_dir: &BackupDir, force: bool) -> Result<(), Error> {
221
222 let full_path = self.snapshot_path(backup_dir);
223
224 let _guard;
225 if !force {
226 _guard = lock_dir_noblock(&full_path, "snapshot", "possibly running or used as base")?;
227 }
228
229 log::info!("removing backup snapshot {:?}", full_path);
230 std::fs::remove_dir_all(&full_path)
231 .map_err(|err| {
232 format_err!(
233 "removing backup snapshot {:?} failed - {}",
234 full_path,
235 err,
236 )
237 })?;
238
239 Ok(())
240 }
241
242 /// Returns the time of the last successful backup
243 ///
244 /// Or None if there is no backup in the group (or the group dir does not exist).
245 pub fn last_successful_backup(&self, backup_group: &BackupGroup) -> Result<Option<DateTime<Utc>>, Error> {
246 let base_path = self.base_path();
247 let mut group_path = base_path.clone();
248 group_path.push(backup_group.group_path());
249
250 if group_path.exists() {
251 backup_group.last_successful_backup(&base_path)
252 } else {
253 Ok(None)
254 }
255 }
256
257 /// Returns the backup owner.
258 ///
259 /// The backup owner is the user who first created the backup group.
260 pub fn get_owner(&self, backup_group: &BackupGroup) -> Result<Userid, Error> {
261 let mut full_path = self.base_path();
262 full_path.push(backup_group.group_path());
263 full_path.push("owner");
264 let owner = proxmox::tools::fs::file_read_firstline(full_path)?;
265 Ok(owner.trim_end().parse()?) // remove trailing newline
266 }
267
268 /// Set the backup owner.
269 pub fn set_owner(
270 &self,
271 backup_group: &BackupGroup,
272 userid: &Userid,
273 force: bool,
274 ) -> Result<(), Error> {
275 let mut path = self.base_path();
276 path.push(backup_group.group_path());
277 path.push("owner");
278
279 let mut open_options = std::fs::OpenOptions::new();
280 open_options.write(true);
281 open_options.truncate(true);
282
283 if force {
284 open_options.create(true);
285 } else {
286 open_options.create_new(true);
287 }
288
289 let mut file = open_options.open(&path)
290 .map_err(|err| format_err!("unable to create owner file {:?} - {}", path, err))?;
291
292 write!(file, "{}\n", userid)
293 .map_err(|err| format_err!("unable to write owner file {:?} - {}", path, err))?;
294
295 Ok(())
296 }
297
298 /// Create (if it does not already exists) and lock a backup group
299 ///
300 /// And set the owner to 'userid'. If the group already exists, it returns the
301 /// current owner (instead of setting the owner).
302 ///
303 /// This also acquires an exclusive lock on the directory and returns the lock guard.
304 pub fn create_locked_backup_group(
305 &self,
306 backup_group: &BackupGroup,
307 userid: &Userid,
308 ) -> Result<(Userid, DirLockGuard), Error> {
309 // create intermediate path first:
310 let base_path = self.base_path();
311
312 let mut full_path = base_path.clone();
313 full_path.push(backup_group.backup_type());
314 std::fs::create_dir_all(&full_path)?;
315
316 full_path.push(backup_group.backup_id());
317
318 // create the last component now
319 match std::fs::create_dir(&full_path) {
320 Ok(_) => {
321 let guard = lock_dir_noblock(&full_path, "backup group", "another backup is already running")?;
322 self.set_owner(backup_group, userid, false)?;
323 let owner = self.get_owner(backup_group)?; // just to be sure
324 Ok((owner, guard))
325 }
326 Err(ref err) if err.kind() == io::ErrorKind::AlreadyExists => {
327 let guard = lock_dir_noblock(&full_path, "backup group", "another backup is already running")?;
328 let owner = self.get_owner(backup_group)?; // just to be sure
329 Ok((owner, guard))
330 }
331 Err(err) => bail!("unable to create backup group {:?} - {}", full_path, err),
332 }
333 }
334
335 /// Creates a new backup snapshot inside a BackupGroup
336 ///
337 /// The BackupGroup directory needs to exist.
338 pub fn create_locked_backup_dir(&self, backup_dir: &BackupDir)
339 -> Result<(PathBuf, bool, DirLockGuard), Error>
340 {
341 let relative_path = backup_dir.relative_path();
342 let mut full_path = self.base_path();
343 full_path.push(&relative_path);
344
345 let lock = ||
346 lock_dir_noblock(&full_path, "snapshot", "internal error - tried creating snapshot that's already in use");
347
348 match std::fs::create_dir(&full_path) {
349 Ok(_) => Ok((relative_path, true, lock()?)),
350 Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok((relative_path, false, lock()?)),
351 Err(e) => Err(e.into())
352 }
353 }
354
355 pub fn list_images(&self) -> Result<Vec<PathBuf>, Error> {
356 let base = self.base_path();
357
358 let mut list = vec![];
359
360 use walkdir::WalkDir;
361
362 let walker = WalkDir::new(&base).same_file_system(true).into_iter();
363
364 // make sure we skip .chunks (and other hidden files to keep it simple)
365 fn is_hidden(entry: &walkdir::DirEntry) -> bool {
366 entry.file_name()
367 .to_str()
368 .map(|s| s.starts_with("."))
369 .unwrap_or(false)
370 }
371 let handle_entry_err = |err: walkdir::Error| {
372 if let Some(inner) = err.io_error() {
373 let path = err.path().unwrap_or(Path::new(""));
374 match inner.kind() {
375 io::ErrorKind::PermissionDenied => {
376 // only allow to skip ext4 fsck directory, avoid GC if, for example,
377 // a user got file permissions wrong on datastore rsync to new server
378 if err.depth() > 1 || !path.ends_with("lost+found") {
379 bail!("cannot continue garbage-collection safely, permission denied on: {}", path.display())
380 }
381 },
382 _ => bail!("unexpected error on datastore traversal: {} - {}", inner, path.display()),
383 }
384 }
385 Ok(())
386 };
387 for entry in walker.filter_entry(|e| !is_hidden(e)) {
388 let path = match entry {
389 Ok(entry) => entry.into_path(),
390 Err(err) => {
391 handle_entry_err(err)?;
392 continue
393 },
394 };
395 if let Ok(archive_type) = archive_type(&path) {
396 if archive_type == ArchiveType::FixedIndex || archive_type == ArchiveType::DynamicIndex {
397 list.push(path);
398 }
399 }
400 }
401
402 Ok(list)
403 }
404
405 // mark chunks used by ``index`` as used
406 fn index_mark_used_chunks<I: IndexFile>(
407 &self,
408 index: I,
409 file_name: &Path, // only used for error reporting
410 status: &mut GarbageCollectionStatus,
411 worker: &WorkerTask,
412 ) -> Result<(), Error> {
413
414 status.index_file_count += 1;
415 status.index_data_bytes += index.index_bytes();
416
417 for pos in 0..index.index_count() {
418 worker.fail_on_abort()?;
419 tools::fail_on_shutdown()?;
420 let digest = index.index_digest(pos).unwrap();
421 if let Err(err) = self.chunk_store.touch_chunk(digest) {
422 worker.warn(&format!("warning: unable to access chunk {}, required by {:?} - {}",
423 proxmox::tools::digest_to_hex(digest), file_name, err));
424 }
425 }
426 Ok(())
427 }
428
429 fn mark_used_chunks(&self, status: &mut GarbageCollectionStatus, worker: &WorkerTask) -> Result<(), Error> {
430
431 let image_list = self.list_images()?;
432
433 for path in image_list {
434
435 worker.fail_on_abort()?;
436 tools::fail_on_shutdown()?;
437
438 if let Ok(archive_type) = archive_type(&path) {
439 if archive_type == ArchiveType::FixedIndex {
440 let index = self.open_fixed_reader(&path)?;
441 self.index_mark_used_chunks(index, &path, status, worker)?;
442 } else if archive_type == ArchiveType::DynamicIndex {
443 let index = self.open_dynamic_reader(&path)?;
444 self.index_mark_used_chunks(index, &path, status, worker)?;
445 }
446 }
447 }
448
449 Ok(())
450 }
451
452 pub fn last_gc_status(&self) -> GarbageCollectionStatus {
453 self.last_gc_status.lock().unwrap().clone()
454 }
455
456 pub fn garbage_collection_running(&self) -> bool {
457 if let Ok(_) = self.gc_mutex.try_lock() { false } else { true }
458 }
459
460 pub fn garbage_collection(&self, worker: &WorkerTask) -> Result<(), Error> {
461
462 if let Ok(ref mut _mutex) = self.gc_mutex.try_lock() {
463
464 let _exclusive_lock = self.chunk_store.try_exclusive_lock()?;
465
466 let phase1_start_time = unsafe { libc::time(std::ptr::null_mut()) };
467 let oldest_writer = self.chunk_store.oldest_writer().unwrap_or(phase1_start_time);
468
469 let mut gc_status = GarbageCollectionStatus::default();
470 gc_status.upid = Some(worker.to_string());
471
472 worker.log("Start GC phase1 (mark used chunks)");
473
474 self.mark_used_chunks(&mut gc_status, &worker)?;
475
476 worker.log("Start GC phase2 (sweep unused chunks)");
477 self.chunk_store.sweep_unused_chunks(oldest_writer, phase1_start_time, &mut gc_status, &worker)?;
478
479 worker.log(&format!("Removed garbage: {}", HumanByte::from(gc_status.removed_bytes)));
480 worker.log(&format!("Removed chunks: {}", gc_status.removed_chunks));
481 if gc_status.pending_bytes > 0 {
482 worker.log(&format!("Pending removals: {} (in {} chunks)", HumanByte::from(gc_status.pending_bytes), gc_status.pending_chunks));
483 }
484
485 worker.log(&format!("Original data usage: {}", HumanByte::from(gc_status.index_data_bytes)));
486
487 if gc_status.index_data_bytes > 0 {
488 let comp_per = (gc_status.disk_bytes as f64 * 100.)/gc_status.index_data_bytes as f64;
489 worker.log(&format!("On-Disk usage: {} ({:.2}%)", HumanByte::from(gc_status.disk_bytes), comp_per));
490 }
491
492 worker.log(&format!("On-Disk chunks: {}", gc_status.disk_chunks));
493
494 if gc_status.disk_chunks > 0 {
495 let avg_chunk = gc_status.disk_bytes/(gc_status.disk_chunks as u64);
496 worker.log(&format!("Average chunk size: {}", HumanByte::from(avg_chunk)));
497 }
498
499 *self.last_gc_status.lock().unwrap() = gc_status;
500
501 } else {
502 bail!("Start GC failed - (already running/locked)");
503 }
504
505 Ok(())
506 }
507
508 pub fn try_shared_chunk_store_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> {
509 self.chunk_store.try_shared_lock()
510 }
511
512 pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) {
513 self.chunk_store.chunk_path(digest)
514 }
515
516 pub fn cond_touch_chunk(&self, digest: &[u8; 32], fail_if_not_exist: bool) -> Result<bool, Error> {
517 self.chunk_store.cond_touch_chunk(digest, fail_if_not_exist)
518 }
519
520 pub fn insert_chunk(
521 &self,
522 chunk: &DataBlob,
523 digest: &[u8; 32],
524 ) -> Result<(bool, u64), Error> {
525 self.chunk_store.insert_chunk(chunk, digest)
526 }
527
528 pub fn load_blob(&self, backup_dir: &BackupDir, filename: &str) -> Result<DataBlob, Error> {
529 let mut path = self.base_path();
530 path.push(backup_dir.relative_path());
531 path.push(filename);
532
533 proxmox::try_block!({
534 let mut file = std::fs::File::open(&path)?;
535 DataBlob::load_from_reader(&mut file)
536 }).map_err(|err| format_err!("unable to load blob '{:?}' - {}", path, err))
537 }
538
539
540 pub fn load_chunk(&self, digest: &[u8; 32]) -> Result<DataBlob, Error> {
541
542 let (chunk_path, digest_str) = self.chunk_store.chunk_path(digest);
543
544 proxmox::try_block!({
545 let mut file = std::fs::File::open(&chunk_path)?;
546 DataBlob::load_from_reader(&mut file)
547 }).map_err(|err| format_err!(
548 "store '{}', unable to load chunk '{}' - {}",
549 self.name(),
550 digest_str,
551 err,
552 ))
553 }
554
555 pub fn load_manifest(
556 &self,
557 backup_dir: &BackupDir,
558 ) -> Result<(BackupManifest, u64), Error> {
559 let blob = self.load_blob(backup_dir, MANIFEST_BLOB_NAME)?;
560 let raw_size = blob.raw_size();
561 let manifest = BackupManifest::try_from(blob)?;
562 Ok((manifest, raw_size))
563 }
564
565 pub fn load_manifest_json(
566 &self,
567 backup_dir: &BackupDir,
568 ) -> Result<Value, Error> {
569 let blob = self.load_blob(backup_dir, MANIFEST_BLOB_NAME)?;
570 // no expected digest available
571 let manifest_data = blob.decode(None, None)?;
572 let manifest: Value = serde_json::from_slice(&manifest_data[..])?;
573 Ok(manifest)
574 }
575
576 pub fn store_manifest(
577 &self,
578 backup_dir: &BackupDir,
579 manifest: Value,
580 ) -> Result<(), Error> {
581 let manifest = serde_json::to_string_pretty(&manifest)?;
582 let blob = DataBlob::encode(manifest.as_bytes(), None, true)?;
583 let raw_data = blob.raw_data();
584
585 let mut path = self.base_path();
586 path.push(backup_dir.relative_path());
587 path.push(MANIFEST_BLOB_NAME);
588
589 replace_file(&path, raw_data, CreateOptions::new())?;
590
591 Ok(())
592 }
593 }