]>
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> { |
3d5c11e5 | 176 | |
a660978c | 177 | let (chunk_path, _digest_str) = self.chunk_path(digest); |
3d5c11e5 | 178 | |
7ee2aa1b DM |
179 | const UTIME_NOW: i64 = ((1 << 30) - 1); |
180 | const UTIME_OMIT: i64 = ((1 << 30) - 2); | |
181 | ||
a198d74f | 182 | let times: [libc::timespec; 2] = [ |
7ee2aa1b DM |
183 | libc::timespec { tv_sec: 0, tv_nsec: UTIME_NOW }, |
184 | libc::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT } | |
185 | ]; | |
186 | ||
187 | use nix::NixPath; | |
188 | ||
189 | let res = chunk_path.with_nix_path(|cstr| unsafe { | |
190 | libc::utimensat(-1, cstr.as_ptr(), ×[0], libc::AT_SYMLINK_NOFOLLOW) | |
191 | })?; | |
192 | ||
193 | if let Err(err) = nix::errno::Errno::result(res) { | |
194 | bail!("updata atime failed for chunk {:?} - {}", chunk_path, err); | |
195 | } | |
196 | ||
3d5c11e5 DM |
197 | Ok(()) |
198 | } | |
199 | ||
4ee8f53d | 200 | pub fn read_chunk(&self, digest: &[u8; 32]) -> Result<DataBlob, Error> { |
96df2fb4 | 201 | |
81a6ce6f | 202 | let (chunk_path, digest_str) = self.chunk_path(digest); |
f98ac774 | 203 | let mut file = std::fs::File::open(&chunk_path) |
a24e3993 DM |
204 | .map_err(|err| { |
205 | format_err!( | |
206 | "store '{}', unable to read chunk '{}' - {}", | |
207 | self.name, | |
208 | digest_str, | |
209 | err, | |
210 | ) | |
211 | })?; | |
96df2fb4 | 212 | |
4ee8f53d | 213 | DataBlob::load(&mut file) |
96df2fb4 DM |
214 | } |
215 | ||
9739aca4 WB |
216 | pub fn get_chunk_iterator( |
217 | &self, | |
218 | ) -> Result< | |
a5736098 | 219 | impl Iterator<Item = (Result<tools::fs::ReadDirEntry, Error>, usize)> + std::iter::FusedIterator, |
9739aca4 WB |
220 | Error |
221 | > { | |
222 | use nix::dir::Dir; | |
223 | use nix::fcntl::OFlag; | |
224 | use nix::sys::stat::Mode; | |
225 | ||
a24e3993 DM |
226 | let base_handle = Dir::open(&self.chunk_dir, OFlag::O_RDONLY, Mode::empty()) |
227 | .map_err(|err| { | |
228 | format_err!( | |
229 | "unable to open store '{}' chunk dir {:?} - {}", | |
230 | self.name, | |
231 | self.chunk_dir, | |
232 | err, | |
233 | ) | |
234 | })?; | |
9739aca4 | 235 | |
a3f3e91d WB |
236 | let mut done = false; |
237 | let mut inner: Option<tools::fs::ReadDir> = None; | |
238 | let mut at = 0; | |
239 | let mut percentage = 0; | |
240 | Ok(std::iter::from_fn(move || { | |
241 | if done { | |
242 | return None; | |
243 | } | |
244 | ||
245 | loop { | |
246 | if let Some(ref mut inner) = inner { | |
247 | match inner.next() { | |
248 | Some(Ok(entry)) => { | |
249 | // skip files if they're not a hash | |
250 | let bytes = entry.file_name().to_bytes(); | |
251 | if bytes.len() != 64 { | |
252 | continue; | |
253 | } | |
254 | if !bytes.iter().all(u8::is_ascii_hexdigit) { | |
255 | continue; | |
256 | } | |
257 | return Some((Ok(entry), percentage)); | |
258 | } | |
259 | Some(Err(err)) => { | |
260 | // stop after first error | |
261 | done = true; | |
262 | // and pass the error through: | |
263 | return Some((Err(err), percentage)); | |
264 | } | |
265 | None => (), // open next directory | |
c7f481b6 | 266 | } |
c7f481b6 | 267 | } |
a3f3e91d WB |
268 | |
269 | inner = None; | |
270 | ||
271 | if at == 0x10000 { | |
272 | done = true; | |
273 | return None; | |
274 | } | |
275 | ||
276 | let subdir: &str = &format!("{:04x}", at); | |
277 | percentage = (at * 100) / 0x10000; | |
278 | at += 1; | |
279 | match tools::fs::read_subdir(base_handle.as_raw_fd(), subdir) { | |
280 | Ok(dir) => { | |
281 | inner = Some(dir); | |
282 | // start reading: | |
283 | continue; | |
284 | } | |
285 | Err(ref err) if err.as_errno() == Some(nix::errno::Errno::ENOENT) => { | |
286 | // non-existing directories are okay, just keep going: | |
287 | continue; | |
288 | } | |
289 | Err(err) => { | |
290 | // other errors are fatal, so end our iteration | |
291 | done = true; | |
292 | // and pass the error through: | |
9850bcdf | 293 | return Some((Err(format_err!("unable to read subdir '{}' - {}", subdir, err)), percentage)); |
a3f3e91d | 294 | } |
62f2422f WB |
295 | } |
296 | } | |
a3f3e91d | 297 | }).fuse()) |
c7f481b6 WB |
298 | } |
299 | ||
11861a48 DM |
300 | pub fn oldest_writer(&self) -> Option<i64> { |
301 | tools::ProcessLocker::oldest_shared_lock(self.locker.clone()) | |
302 | } | |
303 | ||
304 | pub fn sweep_unused_chunks( | |
305 | &self, | |
306 | oldest_writer: Option<i64>, | |
a5736098 DM |
307 | status: &mut GarbageCollectionStatus, |
308 | worker: Arc<WorkerTask>, | |
11861a48 | 309 | ) -> Result<(), Error> { |
9349d2a1 | 310 | use nix::sys::stat::fstatat; |
08481a0b | 311 | |
fdd71f52 | 312 | let now = unsafe { libc::time(std::ptr::null_mut()) }; |
c7f481b6 | 313 | |
11861a48 DM |
314 | let mut min_atime = now - 3600*24; // at least 24h (see mount option relatime) |
315 | ||
316 | if let Some(stamp) = oldest_writer { | |
317 | if stamp < min_atime { | |
318 | min_atime = stamp; | |
319 | } | |
320 | } | |
321 | ||
322 | min_atime -= 300; // add 5 mins gap for safety | |
323 | ||
a5736098 | 324 | let mut last_percentage = 0; |
e4c2fbf1 DM |
325 | let mut chunk_count = 0; |
326 | ||
a5736098 DM |
327 | for (entry, percentage) in self.get_chunk_iterator()? { |
328 | if last_percentage != percentage { | |
329 | last_percentage = percentage; | |
e4c2fbf1 | 330 | worker.log(format!("percentage done: {}, chunk count: {}", percentage, chunk_count)); |
a5736098 | 331 | } |
92da93b2 DM |
332 | |
333 | tools::fail_on_shutdown()?; | |
334 | ||
fdd71f52 | 335 | let (dirfd, entry) = match entry { |
c7f481b6 | 336 | Ok(entry) => (entry.parent_fd(), entry), |
9850bcdf | 337 | Err(err) => bail!("chunk iterator on chunk store '{}' failed - {}", self.name, err), |
eae8aa3a | 338 | }; |
fdd71f52 | 339 | |
eae8aa3a DM |
340 | let file_type = match entry.file_type() { |
341 | Some(file_type) => file_type, | |
277fc5a3 | 342 | None => bail!("unsupported file system type on chunk store '{}'", self.name), |
eae8aa3a | 343 | }; |
82bc0ad4 WB |
344 | if file_type != nix::dir::Type::File { |
345 | continue; | |
346 | } | |
eae8aa3a | 347 | |
e4c2fbf1 DM |
348 | chunk_count += 1; |
349 | ||
d85987ae DM |
350 | let filename = entry.file_name(); |
351 | ||
15a77c4c DM |
352 | let lock = self.mutex.lock(); |
353 | ||
9349d2a1 | 354 | if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) { |
eae8aa3a | 355 | let age = now - stat.st_atime; |
e95950e4 | 356 | //println!("FOUND {} {:?}", age/(3600*24), filename); |
11861a48 | 357 | if stat.st_atime < min_atime { |
eae8aa3a | 358 | println!("UNLINK {} {:?}", age/(3600*24), filename); |
fdd71f52 | 359 | let res = unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) }; |
277fc5a3 DM |
360 | if res != 0 { |
361 | let err = nix::Error::last(); | |
9349d2a1 WB |
362 | bail!( |
363 | "unlink chunk {:?} failed on store '{}' - {}", | |
364 | filename, | |
365 | self.name, | |
366 | err, | |
367 | ); | |
277fc5a3 | 368 | } |
a660978c DM |
369 | status.removed_chunks += 1; |
370 | status.removed_bytes += stat.st_size as u64; | |
371 | } else { | |
64e53b28 | 372 | status.disk_chunks += 1; |
a660978c | 373 | status.disk_bytes += stat.st_size as u64; |
08481a0b | 374 | } |
eae8aa3a | 375 | } |
15a77c4c | 376 | drop(lock); |
eae8aa3a | 377 | } |
a5736098 | 378 | |
277fc5a3 | 379 | Ok(()) |
08481a0b DM |
380 | } |
381 | ||
f98ac774 | 382 | pub fn insert_chunk( |
9ac6ec86 | 383 | &self, |
4ee8f53d DM |
384 | chunk: &DataBlob, |
385 | digest: &[u8; 32], | |
9ac6ec86 | 386 | ) -> Result<(bool, u64), Error> { |
7b2b40a8 | 387 | |
bffd40d6 | 388 | //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest)); |
128b37fe | 389 | |
81a6ce6f | 390 | let (chunk_path, digest_str) = self.chunk_path(digest); |
c5d82e5f DM |
391 | |
392 | let lock = self.mutex.lock(); | |
393 | ||
394 | if let Ok(metadata) = std::fs::metadata(&chunk_path) { | |
395 | if metadata.is_file() { | |
9ac6ec86 | 396 | return Ok((true, metadata.len())); |
c5d82e5f | 397 | } else { |
f7dd683b | 398 | bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str); |
c5d82e5f DM |
399 | } |
400 | } | |
128b37fe | 401 | |
c5d82e5f DM |
402 | let mut tmp_path = chunk_path.clone(); |
403 | tmp_path.set_extension("tmp"); | |
78216a5a | 404 | |
f98ac774 | 405 | let mut file = std::fs::File::create(&tmp_path)?; |
78216a5a | 406 | |
f98ac774 DM |
407 | let raw_data = chunk.raw_data(); |
408 | let encoded_size = raw_data.len() as u64; | |
78216a5a | 409 | |
f98ac774 | 410 | file.write_all(raw_data)?; |
128b37fe | 411 | |
c5d82e5f DM |
412 | if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) { |
413 | if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ } | |
9349d2a1 WB |
414 | bail!( |
415 | "Atomic rename on store '{}' failed for chunk {} - {}", | |
416 | self.name, | |
417 | digest_str, | |
418 | err, | |
419 | ); | |
c5d82e5f DM |
420 | } |
421 | ||
c5d82e5f DM |
422 | drop(lock); |
423 | ||
f98ac774 | 424 | Ok((false, encoded_size)) |
128b37fe DM |
425 | } |
426 | ||
81a6ce6f DM |
427 | pub fn chunk_path(&self, digest:&[u8; 32]) -> (PathBuf, String) { |
428 | let mut chunk_path = self.chunk_dir.clone(); | |
429 | let prefix = digest_to_prefix(digest); | |
430 | chunk_path.push(&prefix); | |
431 | let digest_str = proxmox::tools::digest_to_hex(digest); | |
432 | chunk_path.push(&digest_str); | |
433 | (chunk_path, digest_str) | |
434 | } | |
435 | ||
606ce64b DM |
436 | pub fn relative_path(&self, path: &Path) -> PathBuf { |
437 | ||
438 | let mut full_path = self.base.clone(); | |
439 | full_path.push(path); | |
440 | full_path | |
441 | } | |
442 | ||
3d5c11e5 DM |
443 | pub fn base_path(&self) -> PathBuf { |
444 | self.base.clone() | |
445 | } | |
43b13033 DM |
446 | |
447 | pub fn try_shared_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> { | |
448 | tools::ProcessLocker::try_shared_lock(self.locker.clone()) | |
449 | } | |
450 | ||
451 | pub fn try_exclusive_lock(&self) -> Result<tools::ProcessLockExclusiveGuard, Error> { | |
452 | tools::ProcessLocker::try_exclusive_lock(self.locker.clone()) | |
453 | } | |
35cf5daa DM |
454 | } |
455 | ||
456 | ||
457 | #[test] | |
458 | fn test_chunk_store1() { | |
459 | ||
332dcc22 DM |
460 | let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path |
461 | path.push(".testdir"); | |
462 | ||
35cf5daa DM |
463 | if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ } |
464 | ||
332dcc22 | 465 | let chunk_store = ChunkStore::open("test", &path); |
35cf5daa DM |
466 | assert!(chunk_store.is_err()); |
467 | ||
64599563 DM |
468 | let user = nix::unistd::User::from_uid(nix::unistd::Uid::current()).unwrap().unwrap(); |
469 | let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid).unwrap(); | |
f98ac774 | 470 | |
4ee8f53d | 471 | let (chunk, digest) = super::DataChunkBuilder::new(&[0u8, 1u8]).build().unwrap(); |
f98ac774 | 472 | |
4ee8f53d | 473 | let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap(); |
391a2e43 DM |
474 | assert!(!exists); |
475 | ||
4ee8f53d | 476 | let (exists, _) = chunk_store.insert_chunk(&chunk, &digest).unwrap(); |
391a2e43 | 477 | assert!(exists); |
128b37fe | 478 | |
35cf5daa | 479 | |
64599563 | 480 | let chunk_store = ChunkStore::create("test", &path, user.uid, user.gid); |
35cf5daa DM |
481 | assert!(chunk_store.is_err()); |
482 | ||
e0a5d1ca | 483 | if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ } |
35cf5daa | 484 | } |