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