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