]> git.proxmox.com Git - proxmox-backup.git/blob - src/backup/chunk_store.rs
src/api2/admin/datastore.rs: impl list_snapshots
[proxmox-backup.git] / src / backup / chunk_store.rs
1 use failure::*;
2 use std::path::{Path, PathBuf};
3 use std::io::{Read, 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 f = std::fs::File::open(&chunk_path)?;
185 let mut decoder = lz4::Decoder::new(f)?;
186
187 decoder.read_to_end(buffer)?;
188
189 Ok(())
190 }
191
192 pub fn get_chunk_iterator(
193 &self,
194 print_percentage: bool,
195 ) -> Result<
196 impl Iterator<Item = Result<tools::fs::ReadDirEntry, Error>> + std::iter::FusedIterator,
197 Error
198 > {
199 use nix::dir::Dir;
200 use nix::fcntl::OFlag;
201 use nix::sys::stat::Mode;
202
203 let base_handle = match Dir::open(
204 &self.chunk_dir, OFlag::O_RDONLY, Mode::empty()) {
205 Ok(h) => h,
206 Err(err) => bail!("unable to open store '{}' chunk dir {:?} - {}",
207 self.name, self.chunk_dir, err),
208 };
209
210 let mut verbose = true;
211 let mut last_percentage = 0;
212
213 Ok((0..0x10000).filter_map(move |index| {
214 if print_percentage {
215 let percentage = (index * 100) / 0x10000;
216 if last_percentage != percentage {
217 last_percentage = percentage;
218 eprintln!("percentage done: {}", percentage);
219 }
220 }
221 let subdir: &str = &format!("{:04x}", index);
222 match tools::fs::read_subdir(base_handle.as_raw_fd(), subdir) {
223 Err(e) => {
224 if verbose {
225 eprintln!("Error iterating through chunks: {}", e);
226 verbose = false;
227 }
228 None
229 }
230 Ok(iter) => Some(iter),
231 }
232 })
233 .flatten()
234 .filter(|entry| {
235 // Check that the file name is actually a hash! (64 hex digits)
236 let entry = match entry {
237 Err(_) => return true, // pass errors onwards
238 Ok(ref entry) => entry,
239 };
240 let bytes = entry.file_name().to_bytes();
241 if bytes.len() != 64 {
242 return false;
243 }
244 for b in bytes {
245 if !b.is_ascii_hexdigit() {
246 return false;
247 }
248 }
249 true
250 }))
251 }
252
253 pub fn sweep_unused_chunks(&self, status: &mut GarbageCollectionStatus) -> Result<(), Error> {
254 use nix::sys::stat::fstatat;
255
256 let now = unsafe { libc::time(std::ptr::null_mut()) };
257
258 for entry in self.get_chunk_iterator(true)? {
259 let (dirfd, entry) = match entry {
260 Ok(entry) => (entry.parent_fd(), entry),
261 Err(_) => continue, // ignore errors
262 };
263
264 let file_type = match entry.file_type() {
265 Some(file_type) => file_type,
266 None => bail!("unsupported file system type on chunk store '{}'", self.name),
267 };
268 if file_type != nix::dir::Type::File {
269 continue;
270 }
271
272 let filename = entry.file_name();
273 if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
274 let age = now - stat.st_atime;
275 //println!("FOUND {} {:?}", age/(3600*24), filename);
276 if age/(3600*24) >= 2 {
277 println!("UNLINK {} {:?}", age/(3600*24), filename);
278 let res = unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) };
279 if res != 0 {
280 let err = nix::Error::last();
281 bail!(
282 "unlink chunk {:?} failed on store '{}' - {}",
283 filename,
284 self.name,
285 err,
286 );
287 }
288 } else {
289 status.disk_chunks += 1;
290 status.disk_bytes += stat.st_size as usize;
291
292 }
293 }
294 }
295 Ok(())
296 }
297
298 pub fn insert_chunk(&self, chunk: &[u8]) -> Result<(bool, [u8; 32], u64), Error> {
299
300 // fixme: use Sha512/256 when available
301 let digest = sha::sha256(chunk);
302 let (new, csize) = self.insert_chunk_noverify(&digest, chunk)?;
303 Ok((new, digest, csize))
304 }
305
306 pub fn insert_chunk_noverify(
307 &self,
308 digest: &[u8; 32],
309 chunk: &[u8],
310 ) -> Result<(bool, u64), Error> {
311
312 //println!("DIGEST {}", tools::digest_to_hex(&digest));
313
314 let mut chunk_path = self.chunk_dir.clone();
315 let prefix = digest_to_prefix(digest);
316 chunk_path.push(&prefix);
317 let digest_str = tools::digest_to_hex(digest);
318 chunk_path.push(&digest_str);
319
320 let lock = self.mutex.lock();
321
322 if let Ok(metadata) = std::fs::metadata(&chunk_path) {
323 if metadata.is_file() {
324 return Ok((true, metadata.len()));
325 } else {
326 bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str);
327 }
328 }
329
330 let mut tmp_path = chunk_path.clone();
331 tmp_path.set_extension("tmp");
332
333 let f = std::fs::File::create(&tmp_path)?;
334
335 // fixme: what is the fasted lz4 encoder available (see lzbench)?
336 let mut encoder = lz4::EncoderBuilder::new().level(1).build(f)?;
337
338 encoder.write_all(chunk)?;
339 let (f, encode_result) = encoder.finish();
340 encode_result?;
341
342 if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) {
343 if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ }
344 bail!(
345 "Atomic rename on store '{}' failed for chunk {} - {}",
346 self.name,
347 digest_str,
348 err,
349 );
350 }
351
352 // fixme: is there a better way to get the compressed size?
353 let stat = nix::sys::stat::fstat(f.as_raw_fd())?;
354 let compressed_size = stat.st_size as u64;
355
356 //println!("PATH {:?}", chunk_path);
357
358 drop(lock);
359
360 Ok((false, compressed_size))
361 }
362
363 pub fn relative_path(&self, path: &Path) -> PathBuf {
364
365 let mut full_path = self.base.clone();
366 full_path.push(path);
367 full_path
368 }
369
370 pub fn base_path(&self) -> PathBuf {
371 self.base.clone()
372 }
373 }
374
375
376 #[test]
377 fn test_chunk_store1() {
378
379 let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path
380 path.push(".testdir");
381
382 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
383
384 let chunk_store = ChunkStore::open("test", &path);
385 assert!(chunk_store.is_err());
386
387 let chunk_store = ChunkStore::create("test", &path).unwrap();
388 let (exists, _, _) = chunk_store.insert_chunk(&[0u8, 1u8]).unwrap();
389 assert!(!exists);
390
391 let (exists, _, _) = chunk_store.insert_chunk(&[0u8, 1u8]).unwrap();
392 assert!(exists);
393
394
395 let chunk_store = ChunkStore::create("test", &path);
396 assert!(chunk_store.is_err());
397
398 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
399 }