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