]> git.proxmox.com Git - proxmox-backup.git/blob - src/backup/chunk_store.rs
remove tools::getpwnam_ugid, impl. crate::backup::backup_user()
[proxmox-backup.git] / src / backup / chunk_store.rs
1 use failure::*;
2
3 use std::path::{Path, PathBuf};
4 use std::io::Write;
5 use std::sync::{Arc, Mutex};
6 use std::os::unix::io::AsRawFd;
7 use serde::Serialize;
8
9 use proxmox::tools::fs::{CreateOptions, create_path, create_dir};
10
11 use crate::tools;
12 use super::DataBlob;
13 use crate::server::WorkerTask;
14
15 #[derive(Clone, Serialize)]
16 pub struct GarbageCollectionStatus {
17 pub upid: Option<String>,
18 pub index_file_count: usize,
19 pub index_data_bytes: u64,
20 pub disk_bytes: u64,
21 pub disk_chunks: usize,
22 pub removed_bytes: u64,
23 pub removed_chunks: usize,
24 }
25
26 impl Default for GarbageCollectionStatus {
27 fn default() -> Self {
28 GarbageCollectionStatus {
29 upid: None,
30 index_file_count: 0,
31 index_data_bytes: 0,
32 disk_bytes: 0,
33 disk_chunks: 0,
34 removed_bytes: 0,
35 removed_chunks: 0,
36 }
37 }
38 }
39
40 /// File system based chunk store
41 pub struct ChunkStore {
42 name: String, // used for error reporting
43 pub (crate) base: PathBuf,
44 chunk_dir: PathBuf,
45 mutex: Mutex<bool>,
46 locker: Arc<Mutex<tools::ProcessLocker>>,
47 }
48
49 // TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
50
51 pub fn verify_chunk_size(size: usize) -> Result<(), Error> {
52
53 static SIZES: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
54
55 if !SIZES.contains(&size) {
56 bail!("Got unsupported chunk size '{}'", size);
57 }
58 Ok(())
59 }
60
61 fn digest_to_prefix(digest: &[u8]) -> PathBuf {
62
63 let mut buf = Vec::<u8>::with_capacity(2+1+2+1);
64
65 const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
66
67 buf.push(HEX_CHARS[(digest[0] as usize) >> 4]);
68 buf.push(HEX_CHARS[(digest[0] as usize) &0xf]);
69 buf.push(HEX_CHARS[(digest[1] as usize) >> 4]);
70 buf.push(HEX_CHARS[(digest[1] as usize) & 0xf]);
71 buf.push('/' as u8);
72
73 let path = unsafe { String::from_utf8_unchecked(buf)};
74
75 path.into()
76 }
77
78 impl ChunkStore {
79
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
88 pub fn create<P: Into<PathBuf>>(name: &str, path: P) -> Result<Self, Error> {
89
90 let base: PathBuf = path.into();
91
92 if !base.is_absolute() {
93 bail!("expected absolute path - got {:?}", base);
94 }
95
96 let chunk_dir = Self::chunk_dir(&base);
97
98 let backup_user = crate::backup::backup_user()?;
99
100 let options = CreateOptions::new()
101 .owner(backup_user.uid)
102 .group(backup_user.gid);
103
104 let default_options = CreateOptions::new();
105
106 if let Err(err) = create_path(&base, Some(default_options.clone()), Some(options.clone())) {
107 bail!("unable to create chunk store '{}' at {:?} - {}", name, base, err);
108 }
109
110 if let Err(err) = create_dir(&chunk_dir, options.clone()) {
111 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, chunk_dir, err);
112 }
113
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
118 // create 64*1024 subdirs
119 let mut last_percentage = 0;
120
121 for i in 0..64*1024 {
122 let mut l1path = chunk_dir.clone();
123 l1path.push(format!("{:04x}", i));
124 if let Err(err) = create_dir(&l1path, options.clone()) {
125 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, l1path, err);
126 }
127 let percentage = (i*100)/(64*1024);
128 if percentage != last_percentage {
129 eprintln!("Percentage done: {}", percentage);
130 last_percentage = percentage;
131 }
132 }
133
134
135 Self::open(name, base)
136 }
137
138 fn lockfile_path<P: Into<PathBuf>>(base: P) -> PathBuf {
139 let base: PathBuf = base.into();
140
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();
150
151 if !base.is_absolute() {
152 bail!("expected absolute path - got {:?}", base);
153 }
154
155 let chunk_dir = Self::chunk_dir(&base);
156
157 if let Err(err) = std::fs::metadata(&chunk_dir) {
158 bail!("unable to open chunk store '{}' at {:?} - {}", name, chunk_dir, err);
159 }
160
161 let lockfile_path = Self::lockfile_path(&base);
162
163 let locker = tools::ProcessLocker::new(&lockfile_path)?;
164
165 Ok(ChunkStore {
166 name: name.to_owned(),
167 base,
168 chunk_dir,
169 locker,
170 mutex: Mutex::new(false)
171 })
172 }
173
174 pub fn touch_chunk(&self, digest: &[u8; 32]) -> Result<(), Error> {
175
176 let (chunk_path, _digest_str) = self.chunk_path(digest);
177
178 const UTIME_NOW: i64 = ((1 << 30) - 1);
179 const UTIME_OMIT: i64 = ((1 << 30) - 2);
180
181 let times: [libc::timespec; 2] = [
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
196 Ok(())
197 }
198
199 pub fn read_chunk(&self, digest: &[u8; 32]) -> Result<DataBlob, Error> {
200
201 let (chunk_path, digest_str) = self.chunk_path(digest);
202 let mut file = std::fs::File::open(&chunk_path)
203 .map_err(|err| {
204 format_err!(
205 "store '{}', unable to read chunk '{}' - {}",
206 self.name,
207 digest_str,
208 err,
209 )
210 })?;
211
212 DataBlob::load(&mut file)
213 }
214
215 pub fn get_chunk_iterator(
216 &self,
217 ) -> Result<
218 impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize)> + std::iter::FusedIterator,
219 Error
220 > {
221 use nix::dir::Dir;
222 use nix::fcntl::OFlag;
223 use nix::sys::stat::Mode;
224
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 })?;
234
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
265 }
266 }
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:
292 return Some((Err(format_err!("unable to read subdir '{}' - {}", subdir, err)), percentage));
293 }
294 }
295 }
296 }).fuse())
297 }
298
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>,
306 status: &mut GarbageCollectionStatus,
307 worker: Arc<WorkerTask>,
308 ) -> Result<(), Error> {
309 use nix::sys::stat::fstatat;
310
311 let now = unsafe { libc::time(std::ptr::null_mut()) };
312
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
323 let mut last_percentage = 0;
324 let mut chunk_count = 0;
325
326 for (entry, percentage) in self.get_chunk_iterator()? {
327 if last_percentage != percentage {
328 last_percentage = percentage;
329 worker.log(format!("percentage done: {}, chunk count: {}", percentage, chunk_count));
330 }
331
332 tools::fail_on_shutdown()?;
333
334 let (dirfd, entry) = match entry {
335 Ok(entry) => (entry.parent_fd(), entry),
336 Err(err) => bail!("chunk iterator on chunk store '{}' failed - {}", self.name, err),
337 };
338
339 let file_type = match entry.file_type() {
340 Some(file_type) => file_type,
341 None => bail!("unsupported file system type on chunk store '{}'", self.name),
342 };
343 if file_type != nix::dir::Type::File {
344 continue;
345 }
346
347 chunk_count += 1;
348
349 let filename = entry.file_name();
350
351 let lock = self.mutex.lock();
352
353 if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
354 let age = now - stat.st_atime;
355 //println!("FOUND {} {:?}", age/(3600*24), filename);
356 if stat.st_atime < min_atime {
357 println!("UNLINK {} {:?}", age/(3600*24), filename);
358 let res = unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) };
359 if res != 0 {
360 let err = nix::Error::last();
361 bail!(
362 "unlink chunk {:?} failed on store '{}' - {}",
363 filename,
364 self.name,
365 err,
366 );
367 }
368 status.removed_chunks += 1;
369 status.removed_bytes += stat.st_size as u64;
370 } else {
371 status.disk_chunks += 1;
372 status.disk_bytes += stat.st_size as u64;
373 }
374 }
375 drop(lock);
376 }
377
378 Ok(())
379 }
380
381 pub fn insert_chunk(
382 &self,
383 chunk: &DataBlob,
384 digest: &[u8; 32],
385 ) -> Result<(bool, u64), Error> {
386
387 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
388
389 let (chunk_path, digest_str) = self.chunk_path(digest);
390
391 let lock = self.mutex.lock();
392
393 if let Ok(metadata) = std::fs::metadata(&chunk_path) {
394 if metadata.is_file() {
395 return Ok((true, metadata.len()));
396 } else {
397 bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str);
398 }
399 }
400
401 let mut tmp_path = chunk_path.clone();
402 tmp_path.set_extension("tmp");
403
404 let mut file = std::fs::File::create(&tmp_path)?;
405
406 let raw_data = chunk.raw_data();
407 let encoded_size = raw_data.len() as u64;
408
409 file.write_all(raw_data)?;
410
411 if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) {
412 if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ }
413 bail!(
414 "Atomic rename on store '{}' failed for chunk {} - {}",
415 self.name,
416 digest_str,
417 err,
418 );
419 }
420
421 drop(lock);
422
423 Ok((false, encoded_size))
424 }
425
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
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
442 pub fn base_path(&self) -> PathBuf {
443 self.base.clone()
444 }
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 }
453 }
454
455
456 #[test]
457 fn test_chunk_store1() {
458
459 let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path
460 path.push(".testdir");
461
462 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
463
464 let chunk_store = ChunkStore::open("test", &path);
465 assert!(chunk_store.is_err());
466
467 let chunk_store = ChunkStore::create("test", &path).unwrap();
468
469 let (chunk, digest) = super::DataChunkBuilder::new(&[0u8, 1u8]).build().unwrap();
470
471 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
472 assert!(!exists);
473
474 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
475 assert!(exists);
476
477
478 let chunk_store = ChunkStore::create("test", &path);
479 assert!(chunk_store.is_err());
480
481 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
482 }