]> git.proxmox.com Git - proxmox-backup.git/blame - src/backup/chunk_store.rs
drop our zstd-sys replacement
[proxmox-backup.git] / src / backup / chunk_store.rs
CommitLineData
35cf5daa 1use failure::*;
43b13033 2
35cf5daa 3use std::path::{Path, PathBuf};
f98ac774 4use std::io::Write;
43b13033
DM
5use std::sync::{Arc, Mutex};
6use std::os::unix::io::AsRawFd;
11515438 7use serde::Serialize;
128b37fe 8
365bb90f 9use crate::tools;
4ee8f53d 10use super::DataBlob;
a5736098 11use crate::server::WorkerTask;
365bb90f 12
f2b99c34 13#[derive(Clone, Serialize)]
64e53b28 14pub struct GarbageCollectionStatus {
f2b99c34 15 pub upid: Option<String>,
a660978c
DM
16 pub index_file_count: usize,
17 pub index_data_bytes: u64,
18 pub disk_bytes: u64,
64e53b28 19 pub disk_chunks: usize,
a660978c
DM
20 pub removed_bytes: u64,
21 pub removed_chunks: usize,
64e53b28
DM
22}
23
24impl Default for GarbageCollectionStatus {
25 fn default() -> Self {
26 GarbageCollectionStatus {
f2b99c34 27 upid: None,
a660978c
DM
28 index_file_count: 0,
29 index_data_bytes: 0,
64e53b28
DM
30 disk_bytes: 0,
31 disk_chunks: 0,
a660978c
DM
32 removed_bytes: 0,
33 removed_chunks: 0,
64e53b28
DM
34 }
35 }
36}
37
e5064ba6 38/// File system based chunk store
35cf5daa 39pub struct ChunkStore {
277fc5a3 40 name: String, // used for error reporting
2c32fdde 41 pub (crate) base: PathBuf,
35cf5daa 42 chunk_dir: PathBuf,
c5d82e5f 43 mutex: Mutex<bool>,
43b13033 44 locker: Arc<Mutex<tools::ProcessLocker>>,
128b37fe
DM
45}
46
176e4af9
DM
47// TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
48
36898ffc 49pub fn verify_chunk_size(size: usize) -> Result<(), Error> {
247cdbce 50
36898ffc 51 static SIZES: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
247cdbce
DM
52
53 if !SIZES.contains(&size) {
54 bail!("Got unsupported chunk size '{}'", size);
55 }
56 Ok(())
57}
58
08481a0b 59fn digest_to_prefix(digest: &[u8]) -> PathBuf {
128b37fe 60
e95950e4 61 let mut buf = Vec::<u8>::with_capacity(2+1+2+1);
128b37fe 62
62ee2eb4 63 const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
22968600 64
128b37fe
DM
65 buf.push(HEX_CHARS[(digest[0] as usize) >> 4]);
66 buf.push(HEX_CHARS[(digest[0] as usize) &0xf]);
e95950e4 67 buf.push(HEX_CHARS[(digest[1] as usize) >> 4]);
128b37fe 68 buf.push(HEX_CHARS[(digest[1] as usize) & 0xf]);
128b37fe
DM
69 buf.push('/' as u8);
70
71 let path = unsafe { String::from_utf8_unchecked(buf)};
72
73 path.into()
35cf5daa
DM
74}
75
76impl ChunkStore {
77
45773720
DM
78 fn chunk_dir<P: AsRef<Path>>(path: P) -> PathBuf {
79
80 let mut chunk_dir: PathBuf = PathBuf::from(path.as_ref());
81 chunk_dir.push(".chunks");
82
83 chunk_dir
84 }
85
277fc5a3 86 pub fn create<P: Into<PathBuf>>(name: &str, path: P) -> Result<Self, Error> {
35cf5daa 87
45773720 88 let base: PathBuf = path.into();
68469eeb
DM
89
90 if !base.is_absolute() {
91 bail!("expected absolute path - got {:?}", base);
92 }
93
45773720 94 let chunk_dir = Self::chunk_dir(&base);
35cf5daa 95
14f1e630 96 if let Err(err) = std::fs::create_dir_all(&base) {
277fc5a3 97 bail!("unable to create chunk store '{}' at {:?} - {}", name, base, err);
2989f6bf
DM
98 }
99
14f1e630 100 if let Err(err) = std::fs::create_dir_all(&chunk_dir) {
277fc5a3 101 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, chunk_dir, err);
2989f6bf 102 }
35cf5daa 103
bc616633 104 // create 64*1024 subdirs
e95950e4
DM
105 let mut last_percentage = 0;
106
bc616633 107 for i in 0..64*1024 {
af3e7d75 108 let mut l1path = chunk_dir.clone();
bc616633 109 l1path.push(format!("{:04x}", i));
2989f6bf 110 if let Err(err) = std::fs::create_dir(&l1path) {
277fc5a3 111 bail!("unable to create chunk store '{}' subdir {:?} - {}", name, l1path, err);
2989f6bf 112 }
bc616633
DM
113 let percentage = (i*100)/(64*1024);
114 if percentage != last_percentage {
115 eprintln!("Percentage done: {}", percentage);
116 last_percentage = percentage;
e95950e4 117 }
35cf5daa
DM
118 }
119
277fc5a3 120 Self::open(name, base)
35cf5daa
DM
121 }
122
277fc5a3 123 pub fn open<P: Into<PathBuf>>(name: &str, path: P) -> Result<Self, Error> {
35cf5daa 124
45773720 125 let base: PathBuf = path.into();
68469eeb
DM
126
127 if !base.is_absolute() {
128 bail!("expected absolute path - got {:?}", base);
129 }
130
45773720
DM
131 let chunk_dir = Self::chunk_dir(&base);
132
ce55dbbc 133 if let Err(err) = std::fs::metadata(&chunk_dir) {
277fc5a3 134 bail!("unable to open chunk store '{}' at {:?} - {}", name, chunk_dir, err);
ce55dbbc 135 }
45773720
DM
136
137 let mut lockfile_path = base.clone();
138 lockfile_path.push(".lock");
139
43b13033 140 let locker = tools::ProcessLocker::new(&lockfile_path)?;
35cf5daa 141
b8d4766a 142 Ok(ChunkStore {
277fc5a3 143 name: name.to_owned(),
b8d4766a
DM
144 base,
145 chunk_dir,
43b13033 146 locker,
b8d4766a
DM
147 mutex: Mutex::new(false)
148 })
35cf5daa
DM
149 }
150
a660978c 151 pub fn touch_chunk(&self, digest: &[u8; 32]) -> Result<(), Error> {
3d5c11e5 152
a660978c 153 let (chunk_path, _digest_str) = self.chunk_path(digest);
3d5c11e5 154
7ee2aa1b
DM
155 const UTIME_NOW: i64 = ((1 << 30) - 1);
156 const UTIME_OMIT: i64 = ((1 << 30) - 2);
157
a198d74f 158 let times: [libc::timespec; 2] = [
7ee2aa1b
DM
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
3d5c11e5
DM
173 Ok(())
174 }
175
4ee8f53d 176 pub fn read_chunk(&self, digest: &[u8; 32]) -> Result<DataBlob, Error> {
96df2fb4 177
81a6ce6f 178 let (chunk_path, digest_str) = self.chunk_path(digest);
f98ac774 179 let mut file = std::fs::File::open(&chunk_path)
a24e3993
DM
180 .map_err(|err| {
181 format_err!(
182 "store '{}', unable to read chunk '{}' - {}",
183 self.name,
184 digest_str,
185 err,
186 )
187 })?;
96df2fb4 188
4ee8f53d 189 DataBlob::load(&mut file)
96df2fb4
DM
190 }
191
9739aca4
WB
192 pub fn get_chunk_iterator(
193 &self,
194 ) -> Result<
a5736098 195 impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize)> + std::iter::FusedIterator,
9739aca4
WB
196 Error
197 > {
198 use nix::dir::Dir;
199 use nix::fcntl::OFlag;
200 use nix::sys::stat::Mode;
201
a24e3993
DM
202 let base_handle = Dir::open(&self.chunk_dir, OFlag::O_RDONLY, Mode::empty())
203 .map_err(|err| {
204 format_err!(
205 "unable to open store '{}' chunk dir {:?} - {}",
206 self.name,
207 self.chunk_dir,
208 err,
209 )
210 })?;
9739aca4 211
a3f3e91d
WB
212 let mut done = false;
213 let mut inner: Option<tools::fs::ReadDir> = None;
214 let mut at = 0;
215 let mut percentage = 0;
216 Ok(std::iter::from_fn(move || {
217 if done {
218 return None;
219 }
220
221 loop {
222 if let Some(ref mut inner) = inner {
223 match inner.next() {
224 Some(Ok(entry)) => {
225 // skip files if they're not a hash
226 let bytes = entry.file_name().to_bytes();
227 if bytes.len() != 64 {
228 continue;
229 }
230 if !bytes.iter().all(u8::is_ascii_hexdigit) {
231 continue;
232 }
233 return Some((Ok(entry), percentage));
234 }
235 Some(Err(err)) => {
236 // stop after first error
237 done = true;
238 // and pass the error through:
239 return Some((Err(err), percentage));
240 }
241 None => (), // open next directory
c7f481b6 242 }
c7f481b6 243 }
a3f3e91d
WB
244
245 inner = None;
246
247 if at == 0x10000 {
248 done = true;
249 return None;
250 }
251
252 let subdir: &str = &format!("{:04x}", at);
253 percentage = (at * 100) / 0x10000;
254 at += 1;
255 match tools::fs::read_subdir(base_handle.as_raw_fd(), subdir) {
256 Ok(dir) => {
257 inner = Some(dir);
258 // start reading:
259 continue;
260 }
261 Err(ref err) if err.as_errno() == Some(nix::errno::Errno::ENOENT) => {
262 // non-existing directories are okay, just keep going:
263 continue;
264 }
265 Err(err) => {
266 // other errors are fatal, so end our iteration
267 done = true;
268 // and pass the error through:
9850bcdf 269 return Some((Err(format_err!("unable to read subdir '{}' - {}", subdir, err)), percentage));
a3f3e91d 270 }
62f2422f
WB
271 }
272 }
a3f3e91d 273 }).fuse())
c7f481b6
WB
274 }
275
11861a48
DM
276 pub fn oldest_writer(&self) -> Option<i64> {
277 tools::ProcessLocker::oldest_shared_lock(self.locker.clone())
278 }
279
280 pub fn sweep_unused_chunks(
281 &self,
282 oldest_writer: Option<i64>,
a5736098
DM
283 status: &mut GarbageCollectionStatus,
284 worker: Arc<WorkerTask>,
11861a48 285 ) -> Result<(), Error> {
9349d2a1 286 use nix::sys::stat::fstatat;
08481a0b 287
fdd71f52 288 let now = unsafe { libc::time(std::ptr::null_mut()) };
c7f481b6 289
11861a48
DM
290 let mut min_atime = now - 3600*24; // at least 24h (see mount option relatime)
291
292 if let Some(stamp) = oldest_writer {
293 if stamp < min_atime {
294 min_atime = stamp;
295 }
296 }
297
298 min_atime -= 300; // add 5 mins gap for safety
299
a5736098 300 let mut last_percentage = 0;
e4c2fbf1
DM
301 let mut chunk_count = 0;
302
a5736098
DM
303 for (entry, percentage) in self.get_chunk_iterator()? {
304 if last_percentage != percentage {
305 last_percentage = percentage;
e4c2fbf1 306 worker.log(format!("percentage done: {}, chunk count: {}", percentage, chunk_count));
a5736098 307 }
92da93b2
DM
308
309 tools::fail_on_shutdown()?;
310
fdd71f52 311 let (dirfd, entry) = match entry {
c7f481b6 312 Ok(entry) => (entry.parent_fd(), entry),
9850bcdf 313 Err(err) => bail!("chunk iterator on chunk store '{}' failed - {}", self.name, err),
eae8aa3a 314 };
fdd71f52 315
eae8aa3a
DM
316 let file_type = match entry.file_type() {
317 Some(file_type) => file_type,
277fc5a3 318 None => bail!("unsupported file system type on chunk store '{}'", self.name),
eae8aa3a 319 };
82bc0ad4
WB
320 if file_type != nix::dir::Type::File {
321 continue;
322 }
eae8aa3a 323
e4c2fbf1
DM
324 chunk_count += 1;
325
d85987ae
DM
326 let filename = entry.file_name();
327
15a77c4c
DM
328 let lock = self.mutex.lock();
329
9349d2a1 330 if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
eae8aa3a 331 let age = now - stat.st_atime;
e95950e4 332 //println!("FOUND {} {:?}", age/(3600*24), filename);
11861a48 333 if stat.st_atime < min_atime {
eae8aa3a 334 println!("UNLINK {} {:?}", age/(3600*24), filename);
fdd71f52 335 let res = unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) };
277fc5a3
DM
336 if res != 0 {
337 let err = nix::Error::last();
9349d2a1
WB
338 bail!(
339 "unlink chunk {:?} failed on store '{}' - {}",
340 filename,
341 self.name,
342 err,
343 );
277fc5a3 344 }
a660978c
DM
345 status.removed_chunks += 1;
346 status.removed_bytes += stat.st_size as u64;
347 } else {
64e53b28 348 status.disk_chunks += 1;
a660978c 349 status.disk_bytes += stat.st_size as u64;
08481a0b 350 }
eae8aa3a 351 }
15a77c4c 352 drop(lock);
eae8aa3a 353 }
a5736098 354
277fc5a3 355 Ok(())
08481a0b
DM
356 }
357
f98ac774 358 pub fn insert_chunk(
9ac6ec86 359 &self,
4ee8f53d
DM
360 chunk: &DataBlob,
361 digest: &[u8; 32],
9ac6ec86 362 ) -> Result<(bool, u64), Error> {
7b2b40a8 363
bffd40d6 364 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
128b37fe 365
81a6ce6f 366 let (chunk_path, digest_str) = self.chunk_path(digest);
c5d82e5f
DM
367
368 let lock = self.mutex.lock();
369
370 if let Ok(metadata) = std::fs::metadata(&chunk_path) {
371 if metadata.is_file() {
9ac6ec86 372 return Ok((true, metadata.len()));
c5d82e5f 373 } else {
f7dd683b 374 bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str);
c5d82e5f
DM
375 }
376 }
128b37fe 377
c5d82e5f
DM
378 let mut tmp_path = chunk_path.clone();
379 tmp_path.set_extension("tmp");
78216a5a 380
f98ac774 381 let mut file = std::fs::File::create(&tmp_path)?;
78216a5a 382
f98ac774
DM
383 let raw_data = chunk.raw_data();
384 let encoded_size = raw_data.len() as u64;
78216a5a 385
f98ac774 386 file.write_all(raw_data)?;
128b37fe 387
c5d82e5f
DM
388 if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) {
389 if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ }
9349d2a1
WB
390 bail!(
391 "Atomic rename on store '{}' failed for chunk {} - {}",
392 self.name,
393 digest_str,
394 err,
395 );
c5d82e5f
DM
396 }
397
c5d82e5f
DM
398 drop(lock);
399
f98ac774 400 Ok((false, encoded_size))
128b37fe
DM
401 }
402
81a6ce6f
DM
403 pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) {
404 let mut chunk_path = self.chunk_dir.clone();
405 let prefix = digest_to_prefix(digest);
406 chunk_path.push(&prefix);
407 let digest_str = proxmox::tools::digest_to_hex(digest);
408 chunk_path.push(&digest_str);
409 (chunk_path, digest_str)
410 }
411
606ce64b
DM
412 pub fn relative_path(&self, path: &Path) -> PathBuf {
413
414 let mut full_path = self.base.clone();
415 full_path.push(path);
416 full_path
417 }
418
3d5c11e5
DM
419 pub fn base_path(&self) -> PathBuf {
420 self.base.clone()
421 }
43b13033
DM
422
423 pub fn try_shared_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> {
424 tools::ProcessLocker::try_shared_lock(self.locker.clone())
425 }
426
427 pub fn try_exclusive_lock(&self) -> Result<tools::ProcessLockExclusiveGuard, Error> {
428 tools::ProcessLocker::try_exclusive_lock(self.locker.clone())
429 }
35cf5daa
DM
430}
431
432
433#[test]
434fn test_chunk_store1() {
435
332dcc22
DM
436 let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path
437 path.push(".testdir");
438
35cf5daa
DM
439 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
440
332dcc22 441 let chunk_store = ChunkStore::open("test", &path);
35cf5daa
DM
442 assert!(chunk_store.is_err());
443
332dcc22 444 let chunk_store = ChunkStore::create("test", &path).unwrap();
f98ac774 445
4ee8f53d 446 let (chunk, digest) = super::DataChunkBuilder::new(&[0u8, 1u8]).build().unwrap();
f98ac774 447
4ee8f53d 448 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
391a2e43
DM
449 assert!(!exists);
450
4ee8f53d 451 let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap();
391a2e43 452 assert!(exists);
128b37fe 453
35cf5daa 454
332dcc22 455 let chunk_store = ChunkStore::create("test", &path);
35cf5daa
DM
456 assert!(chunk_store.is_err());
457
e0a5d1ca 458 if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ }
35cf5daa 459}