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