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