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