]> git.proxmox.com Git - proxmox-backup.git/blame - src/backup/chunk_store.rs
src/bin/proxmox-backup-manager.rs: add task management cli
[proxmox-backup.git] / src / backup / chunk_store.rs
CommitLineData
35cf5daa 1use failure::*;
43b13033 2
35cf5daa 3use std::path::{Path, PathBuf};
f98ac774 4use std::io::Write;
43b13033
DM
5use std::sync::{Arc, Mutex};
6use std::os::unix::io::AsRawFd;
11515438 7use serde::Serialize;
128b37fe 8
0b97bc61
DM
9use proxmox::tools::fs::{CreateOptions, create_path, create_dir};
10
365bb90f 11use crate::tools;
4ee8f53d 12use super::DataBlob;
a5736098 13use crate::server::WorkerTask;
365bb90f 14
f2b99c34 15#[derive(Clone, Serialize)]
64e53b28 16pub struct GarbageCollectionStatus {
f2b99c34 17 pub upid: Option<String>,
a660978c
DM
18 pub index_file_count: usize,
19 pub index_data_bytes: u64,
20 pub disk_bytes: u64,
64e53b28 21 pub disk_chunks: usize,
a660978c
DM
22 pub removed_bytes: u64,
23 pub removed_chunks: usize,
64e53b28
DM
24}
25
26impl Default for GarbageCollectionStatus {
27 fn default() -> Self {
28 GarbageCollectionStatus {
f2b99c34 29 upid: None,
a660978c
DM
30 index_file_count: 0,
31 index_data_bytes: 0,
64e53b28
DM
32 disk_bytes: 0,
33 disk_chunks: 0,
a660978c
DM
34 removed_bytes: 0,
35 removed_chunks: 0,
64e53b28
DM
36 }
37 }
38}
39
e5064ba6 40/// File system based chunk store
35cf5daa 41pub struct ChunkStore {
277fc5a3 42 name: String, // used for error reporting
2c32fdde 43 pub (crate) base: PathBuf,
35cf5daa 44 chunk_dir: PathBuf,
c5d82e5f 45 mutex: Mutex<bool>,
43b13033 46 locker: Arc<Mutex<tools::ProcessLocker>>,
128b37fe
DM
47}
48
176e4af9
DM
49// TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
50
36898ffc 51pub fn verify_chunk_size(size: usize) -> Result<(), Error> {
247cdbce 52
36898ffc 53 static SIZES: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
247cdbce
DM
54
55 if !SIZES.contains(&size) {
56 bail!("Got unsupported chunk size '{}'", size);
57 }
58 Ok(())
59}
60
08481a0b 61fn digest_to_prefix(digest: &[u8]) -> PathBuf {
128b37fe 62
e95950e4 63 let mut buf = Vec::<u8>::with_capacity(2+1+2+1);
128b37fe 64
62ee2eb4 65 const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
22968600 66
128b37fe
DM
67 buf.push(HEX_CHARS[(digest[0] as usize) >> 4]);
68 buf.push(HEX_CHARS[(digest[0] as usize) &0xf]);
e95950e4 69 buf.push(HEX_CHARS[(digest[1] as usize) >> 4]);
128b37fe 70 buf.push(HEX_CHARS[(digest[1] as usize) & 0xf]);
128b37fe
DM
71 buf.push('/' as u8);
72
73 let path = unsafe { String::from_utf8_unchecked(buf)};
74
75 path.into()
35cf5daa
DM
76}
77
78impl ChunkStore {
79
45773720
DM
80 fn chunk_dir<P: AsRef<Path>>(path: P) -> PathBuf {
81
82 let mut chunk_dir: PathBuf = PathBuf::from(path.as_ref());
83 chunk_dir.push(".chunks");
84
85 chunk_dir
86 }
87
277fc5a3 88 pub fn create<P: Into<PathBuf>>(name: &str, path: P) -> Result<Self, Error> {
35cf5daa 89
45773720 90 let base: PathBuf = path.into();
68469eeb
DM
91
92 if !base.is_absolute() {
93 bail!("expected absolute path - got {:?}", base);
94 }
95
45773720 96 let chunk_dir = Self::chunk_dir(&base);
35cf5daa 97
f74a03da 98 let backup_user = crate::backup::backup_user()?;
0b97bc61
DM
99
100 let options = CreateOptions::new()
f74a03da
DM
101 .owner(backup_user.uid)
102 .group(backup_user.gid);
0b97bc61
DM
103
104 let default_options = CreateOptions::new();
105
106 if let Err(err) = create_path(&base, Some(default_options.clone()), Some(options.clone())) {
277fc5a3 107 bail!("unable to create chunk store '{}' at {:?} - {}", name, base, err);
2989f6bf
DM
108 }
109
0b97bc61 110 if let Err(err) = create_dir(&chunk_dir, options.clone()) {
277fc5a3 111 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, chunk_dir, err);
2989f6bf 112 }
35cf5daa 113
7e210bd0
DM
114 // create lock file with correct owner/group
115 let lockfile_path = Self::lockfile_path(&base);
116 proxmox::tools::fs::replace_file(lockfile_path, b"", options.clone())?;
117
bc616633 118 // create 64*1024 subdirs
e95950e4
DM
119 let mut last_percentage = 0;
120
bc616633 121 for i in 0..64*1024 {
af3e7d75 122 let mut l1path = chunk_dir.clone();
bc616633 123 l1path.push(format!("{:04x}", i));
0b97bc61 124 if let Err(err) = create_dir(&l1path, options.clone()) {
277fc5a3 125 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, l1path, err);
2989f6bf 126 }
bc616633
DM
127 let percentage = (i*100)/(64*1024);
128 if percentage != last_percentage {
129 eprintln!("Percentage done: {}", percentage);
130 last_percentage = percentage;
e95950e4 131 }
35cf5daa
DM
132 }
133
7e210bd0 134
277fc5a3 135 Self::open(name, base)
35cf5daa
DM
136 }
137
7e210bd0
DM
138 fn lockfile_path<P: Into<PathBuf>>(base: P) -> PathBuf {
139 let base: PathBuf = base.into();
35cf5daa 140
7e210bd0
DM
141 let mut lockfile_path = base.clone();
142 lockfile_path.push(".lock");
143
144 lockfile_path
145 }
146
147 pub fn open<P: Into<PathBuf>>(name: &str, base: P) -> Result<Self, Error> {
148
149 let base: PathBuf = base.into();
68469eeb
DM
150
151 if !base.is_absolute() {
152 bail!("expected absolute path - got {:?}", base);
153 }
154
45773720
DM
155 let chunk_dir = Self::chunk_dir(&base);
156
ce55dbbc 157 if let Err(err) = std::fs::metadata(&chunk_dir) {
277fc5a3 158 bail!("unable to open chunk store '{}' at {:?} - {}", name, chunk_dir, err);
ce55dbbc 159 }
45773720 160
7e210bd0 161 let lockfile_path = Self::lockfile_path(&base);
45773720 162
43b13033 163 let locker = tools::ProcessLocker::new(&lockfile_path)?;
35cf5daa 164
b8d4766a 165 Ok(ChunkStore {
277fc5a3 166 name: name.to_owned(),
b8d4766a
DM
167 base,
168 chunk_dir,
43b13033 169 locker,
b8d4766a
DM
170 mutex: Mutex::new(false)
171 })
35cf5daa
DM
172 }
173
a660978c 174 pub fn touch_chunk(&self, digest: &[u8; 32]) -> Result<(), Error> {
3d5c11e5 175
a660978c 176 let (chunk_path, _digest_str) = self.chunk_path(digest);
3d5c11e5 177
7ee2aa1b
DM
178 const UTIME_NOW: i64 = ((1 << 30) - 1);
179 const UTIME_OMIT: i64 = ((1 << 30) - 2);
180
a198d74f 181 let times: [libc::timespec; 2] = [
7ee2aa1b
DM
182 libc::timespec { tv_sec: 0, tv_nsec: UTIME_NOW },
183 libc::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT }
184 ];
185
186 use nix::NixPath;
187
188 let res = chunk_path.with_nix_path(|cstr| unsafe {
189 libc::utimensat(-1, cstr.as_ptr(), &times[0], libc::AT_SYMLINK_NOFOLLOW)
190 })?;
191
192 if let Err(err) = nix::errno::Errno::result(res) {
193 bail!("updata atime failed for chunk {:?} - {}", chunk_path, err);
194 }
195
3d5c11e5
DM
196 Ok(())
197 }
198
4ee8f53d 199 pub fn read_chunk(&self, digest: &[u8; 32]) -> Result<DataBlob, Error> {
96df2fb4 200
81a6ce6f 201 let (chunk_path, digest_str) = self.chunk_path(digest);
f98ac774 202 let mut file = std::fs::File::open(&chunk_path)
a24e3993
DM
203 .map_err(|err| {
204 format_err!(
205 "store '{}', unable to read chunk '{}' - {}",
206 self.name,
207 digest_str,
208 err,
209 )
210 })?;
96df2fb4 211
4ee8f53d 212 DataBlob::load(&mut file)
96df2fb4
DM
213 }
214
9739aca4
WB
215 pub fn get_chunk_iterator(
216 &self,
217 ) -> Result<
a5736098 218 impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize)> + std::iter::FusedIterator,
9739aca4
WB
219 Error
220 > {
221 use nix::dir::Dir;
222 use nix::fcntl::OFlag;
223 use nix::sys::stat::Mode;
224
a24e3993
DM
225 let base_handle = Dir::open(&self.chunk_dir, OFlag::O_RDONLY, Mode::empty())
226 .map_err(|err| {
227 format_err!(
228 "unable to open store '{}' chunk dir {:?} - {}",
229 self.name,
230 self.chunk_dir,
231 err,
232 )
233 })?;
9739aca4 234
a3f3e91d
WB
235 let mut done = false;
236 let mut inner: Option<tools::fs::ReadDir> = None;
237 let mut at = 0;
238 let mut percentage = 0;
239 Ok(std::iter::from_fn(move || {
240 if done {
241 return None;
242 }
243
244 loop {
245 if let Some(ref mut inner) = inner {
246 match inner.next() {
247 Some(Ok(entry)) => {
248 // skip files if they're not a hash
249 let bytes = entry.file_name().to_bytes();
250 if bytes.len() != 64 {
251 continue;
252 }
253 if !bytes.iter().all(u8::is_ascii_hexdigit) {
254 continue;
255 }
256 return Some((Ok(entry), percentage));
257 }
258 Some(Err(err)) => {
259 // stop after first error
260 done = true;
261 // and pass the error through:
262 return Some((Err(err), percentage));
263 }
264 None => (), // open next directory
c7f481b6 265 }
c7f481b6 266 }
a3f3e91d
WB
267
268 inner = None;
269
270 if at == 0x10000 {
271 done = true;
272 return None;
273 }
274
275 let subdir: &str = &format!("{:04x}", at);
276 percentage = (at * 100) / 0x10000;
277 at += 1;
278 match tools::fs::read_subdir(base_handle.as_raw_fd(), subdir) {
279 Ok(dir) => {
280 inner = Some(dir);
281 // start reading:
282 continue;
283 }
284 Err(ref err) if err.as_errno() == Some(nix::errno::Errno::ENOENT) => {
285 // non-existing directories are okay, just keep going:
286 continue;
287 }
288 Err(err) => {
289 // other errors are fatal, so end our iteration
290 done = true;
291 // and pass the error through:
9850bcdf 292 return Some((Err(format_err!("unable to read subdir '{}' - {}", subdir, err)), percentage));
a3f3e91d 293 }
62f2422f
WB
294 }
295 }
a3f3e91d 296 }).fuse())
c7f481b6
WB
297 }
298
11861a48
DM
299 pub fn oldest_writer(&self) -> Option<i64> {
300 tools::ProcessLocker::oldest_shared_lock(self.locker.clone())
301 }
302
303 pub fn sweep_unused_chunks(
304 &self,
305 oldest_writer: Option<i64>,
a5736098
DM
306 status: &mut GarbageCollectionStatus,
307 worker: Arc<WorkerTask>,
11861a48 308 ) -> Result<(), Error> {
9349d2a1 309 use nix::sys::stat::fstatat;
08481a0b 310
fdd71f52 311 let now = unsafe { libc::time(std::ptr::null_mut()) };
c7f481b6 312
11861a48
DM
313 let mut min_atime = now - 3600*24; // at least 24h (see mount option relatime)
314
315 if let Some(stamp) = oldest_writer {
316 if stamp < min_atime {
317 min_atime = stamp;
318 }
319 }
320
321 min_atime -= 300; // add 5 mins gap for safety
322
a5736098 323 let mut last_percentage = 0;
e4c2fbf1
DM
324 let mut chunk_count = 0;
325
a5736098
DM
326 for (entry, percentage) in self.get_chunk_iterator()? {
327 if last_percentage != percentage {
328 last_percentage = percentage;
e4c2fbf1 329 worker.log(format!("percentage done: {}, chunk count: {}", percentage, chunk_count));
a5736098 330 }
92da93b2
DM
331
332 tools::fail_on_shutdown()?;
333
fdd71f52 334 let (dirfd, entry) = match entry {
c7f481b6 335 Ok(entry) => (entry.parent_fd(), entry),
9850bcdf 336 Err(err) => bail!("chunk iterator on chunk store '{}' failed - {}", self.name, err),
eae8aa3a 337 };
fdd71f52 338
eae8aa3a
DM
339 let file_type = match entry.file_type() {
340 Some(file_type) => file_type,
277fc5a3 341 None => bail!("unsupported file system type on chunk store '{}'", self.name),
eae8aa3a 342 };
82bc0ad4
WB
343 if file_type != nix::dir::Type::File {
344 continue;
345 }
eae8aa3a 346
e4c2fbf1
DM
347 chunk_count += 1;
348
d85987ae
DM
349 let filename = entry.file_name();
350
15a77c4c
DM
351 let lock = self.mutex.lock();
352
9349d2a1 353 if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
eae8aa3a 354 let age = now - stat.st_atime;
e95950e4 355 //println!("FOUND {} {:?}", age/(3600*24), filename);
11861a48 356 if stat.st_atime < min_atime {
eae8aa3a 357 println!("UNLINK {} {:?}", age/(3600*24), filename);
fdd71f52 358 let res = unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) };
277fc5a3
DM
359 if res != 0 {
360 let err = nix::Error::last();
9349d2a1
WB
361 bail!(
362 "unlink chunk {:?} failed on store '{}' - {}",
363 filename,
364 self.name,
365 err,
366 );
277fc5a3 367 }
a660978c
DM
368 status.removed_chunks += 1;
369 status.removed_bytes += stat.st_size as u64;
370 } else {
64e53b28 371 status.disk_chunks += 1;
a660978c 372 status.disk_bytes += stat.st_size as u64;
08481a0b 373 }
eae8aa3a 374 }
15a77c4c 375 drop(lock);
eae8aa3a 376 }
a5736098 377
277fc5a3 378 Ok(())
08481a0b
DM
379 }
380
f98ac774 381 pub fn insert_chunk(
9ac6ec86 382 &self,
4ee8f53d
DM
383 chunk: &DataBlob,
384 digest: &[u8; 32],
9ac6ec86 385 ) -> Result<(bool, u64), Error> {
7b2b40a8 386
bffd40d6 387 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
128b37fe 388
81a6ce6f 389 let (chunk_path, digest_str) = self.chunk_path(digest);
c5d82e5f
DM
390
391 let lock = self.mutex.lock();
392
393 if let Ok(metadata) = std::fs::metadata(&chunk_path) {
394 if metadata.is_file() {
9ac6ec86 395 return Ok((true, metadata.len()));
c5d82e5f 396 } else {
f7dd683b 397 bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str);
c5d82e5f
DM
398 }
399 }
128b37fe 400
c5d82e5f
DM
401 let mut tmp_path = chunk_path.clone();
402 tmp_path.set_extension("tmp");
78216a5a 403
f98ac774 404 let mut file = std::fs::File::create(&tmp_path)?;
78216a5a 405
f98ac774
DM
406 let raw_data = chunk.raw_data();
407 let encoded_size = raw_data.len() as u64;
78216a5a 408
f98ac774 409 file.write_all(raw_data)?;
128b37fe 410
c5d82e5f
DM
411 if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) {
412 if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ }
9349d2a1
WB
413 bail!(
414 "Atomic rename on store '{}' failed for chunk {} - {}",
415 self.name,
416 digest_str,
417 err,
418 );
c5d82e5f
DM
419 }
420
c5d82e5f
DM
421 drop(lock);
422
f98ac774 423 Ok((false, encoded_size))
128b37fe
DM
424 }
425
81a6ce6f
DM
426 pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) {
427 let mut chunk_path = self.chunk_dir.clone();
428 let prefix = digest_to_prefix(digest);
429 chunk_path.push(&prefix);
430 let digest_str = proxmox::tools::digest_to_hex(digest);
431 chunk_path.push(&digest_str);
432 (chunk_path, digest_str)
433 }
434
606ce64b
DM
435 pub fn relative_path(&self, path: &Path) -> PathBuf {
436
437 let mut full_path = self.base.clone();
438 full_path.push(path);
439 full_path
440 }
441
3d5c11e5
DM
442 pub fn base_path(&self) -> PathBuf {
443 self.base.clone()
444 }
43b13033
DM
445
446 pub fn try_shared_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> {
447 tools::ProcessLocker::try_shared_lock(self.locker.clone())
448 }
449
450 pub fn try_exclusive_lock(&self) -> Result<tools::ProcessLockExclusiveGuard, Error> {
451 tools::ProcessLocker::try_exclusive_lock(self.locker.clone())
452 }
35cf5daa
DM
453}
454
455
456#[test]
457fn test_chunk_store1() {
458
332dcc22
DM
459 let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path
460 path.push(".testdir");
461
35cf5daa
DM
462 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
463
332dcc22 464 let chunk_store = ChunkStore::open("test", &path);
35cf5daa
DM
465 assert!(chunk_store.is_err());
466
332dcc22 467 let chunk_store = ChunkStore::create("test", &path).unwrap();
f98ac774 468
4ee8f53d 469 let (chunk, digest) = super::DataChunkBuilder::new(&[0u8, 1u8]).build().unwrap();
f98ac774 470
4ee8f53d 471 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
391a2e43
DM
472 assert!(!exists);
473
4ee8f53d 474 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
391a2e43 475 assert!(exists);
128b37fe 476
35cf5daa 477
332dcc22 478 let chunk_store = ChunkStore::create("test", &path);
35cf5daa
DM
479 assert!(chunk_store.is_err());
480
e0a5d1ca 481 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
35cf5daa 482}