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