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