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