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