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