]>
Commit | Line | Data |
---|---|---|
35cf5daa | 1 | use failure::*; |
43b13033 | 2 | |
35cf5daa | 3 | use std::path::{Path, PathBuf}; |
78216a5a | 4 | use std::io::{Read, Write}; |
43b13033 DM |
5 | use std::sync::{Arc, Mutex}; |
6 | use std::os::unix::io::AsRawFd; | |
f2b99c34 | 7 | use serde_derive::Serialize; |
128b37fe | 8 | |
7b2b40a8 | 9 | use openssl::sha; |
35cf5daa | 10 | |
365bb90f DM |
11 | use crate::tools; |
12 | ||
f2b99c34 | 13 | #[derive(Clone, Serialize)] |
64e53b28 | 14 | pub struct GarbageCollectionStatus { |
f2b99c34 | 15 | pub upid: Option<String>, |
64e53b28 DM |
16 | pub used_bytes: usize, |
17 | pub used_chunks: usize, | |
18 | pub disk_bytes: usize, | |
19 | pub disk_chunks: usize, | |
20 | } | |
21 | ||
22 | impl Default for GarbageCollectionStatus { | |
23 | fn default() -> Self { | |
24 | GarbageCollectionStatus { | |
f2b99c34 | 25 | upid: None, |
64e53b28 DM |
26 | used_bytes: 0, |
27 | used_chunks: 0, | |
28 | disk_bytes: 0, | |
29 | disk_chunks: 0, | |
30 | } | |
31 | } | |
32 | } | |
33 | ||
e5064ba6 | 34 | /// File system based chunk store |
35cf5daa | 35 | pub struct ChunkStore { |
277fc5a3 | 36 | name: String, // used for error reporting |
2c32fdde | 37 | pub (crate) base: PathBuf, |
35cf5daa | 38 | chunk_dir: PathBuf, |
c5d82e5f | 39 | mutex: Mutex<bool>, |
43b13033 | 40 | locker: Arc<Mutex<tools::ProcessLocker>>, |
128b37fe DM |
41 | } |
42 | ||
176e4af9 DM |
43 | // TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ? |
44 | ||
36898ffc | 45 | pub fn verify_chunk_size(size: usize) -> Result<(), Error> { |
247cdbce | 46 | |
36898ffc | 47 | static SIZES: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024]; |
247cdbce DM |
48 | |
49 | if !SIZES.contains(&size) { | |
50 | bail!("Got unsupported chunk size '{}'", size); | |
51 | } | |
52 | Ok(()) | |
53 | } | |
54 | ||
08481a0b | 55 | fn digest_to_prefix(digest: &[u8]) -> PathBuf { |
128b37fe | 56 | |
e95950e4 | 57 | let mut buf = Vec::<u8>::with_capacity(2+1+2+1); |
128b37fe | 58 | |
22968600 DM |
59 | const HEX_CHARS: &'static [u8; 16] = b"0123456789abcdef"; |
60 | ||
128b37fe DM |
61 | buf.push(HEX_CHARS[(digest[0] as usize) >> 4]); |
62 | buf.push(HEX_CHARS[(digest[0] as usize) &0xf]); | |
e95950e4 | 63 | buf.push(HEX_CHARS[(digest[1] as usize) >> 4]); |
128b37fe | 64 | buf.push(HEX_CHARS[(digest[1] as usize) & 0xf]); |
128b37fe DM |
65 | buf.push('/' as u8); |
66 | ||
67 | let path = unsafe { String::from_utf8_unchecked(buf)}; | |
68 | ||
69 | path.into() | |
35cf5daa DM |
70 | } |
71 | ||
72 | impl ChunkStore { | |
73 | ||
45773720 DM |
74 | fn chunk_dir<P: AsRef<Path>>(path: P) -> PathBuf { |
75 | ||
76 | let mut chunk_dir: PathBuf = PathBuf::from(path.as_ref()); | |
77 | chunk_dir.push(".chunks"); | |
78 | ||
79 | chunk_dir | |
80 | } | |
81 | ||
277fc5a3 | 82 | pub fn create<P: Into<PathBuf>>(name: &str, path: P) -> Result<Self, Error> { |
35cf5daa | 83 | |
45773720 | 84 | let base: PathBuf = path.into(); |
68469eeb DM |
85 | |
86 | if !base.is_absolute() { | |
87 | bail!("expected absolute path - got {:?}", base); | |
88 | } | |
89 | ||
45773720 | 90 | let chunk_dir = Self::chunk_dir(&base); |
35cf5daa | 91 | |
2989f6bf | 92 | if let Err(err) = std::fs::create_dir(&base) { |
277fc5a3 | 93 | bail!("unable to create chunk store '{}' at {:?} - {}", name, base, err); |
2989f6bf DM |
94 | } |
95 | ||
96 | if let Err(err) = std::fs::create_dir(&chunk_dir) { | |
277fc5a3 | 97 | bail!("unable to create chunk store '{}' subdir {:?} - {}", name, chunk_dir, err); |
2989f6bf | 98 | } |
35cf5daa | 99 | |
bc616633 | 100 | // create 64*1024 subdirs |
e95950e4 DM |
101 | let mut last_percentage = 0; |
102 | ||
bc616633 | 103 | for i in 0..64*1024 { |
af3e7d75 | 104 | let mut l1path = chunk_dir.clone(); |
bc616633 | 105 | l1path.push(format!("{:04x}", i)); |
2989f6bf | 106 | if let Err(err) = std::fs::create_dir(&l1path) { |
277fc5a3 | 107 | bail!("unable to create chunk store '{}' subdir {:?} - {}", name, l1path, err); |
2989f6bf | 108 | } |
bc616633 DM |
109 | let percentage = (i*100)/(64*1024); |
110 | if percentage != last_percentage { | |
111 | eprintln!("Percentage done: {}", percentage); | |
112 | last_percentage = percentage; | |
e95950e4 | 113 | } |
35cf5daa DM |
114 | } |
115 | ||
277fc5a3 | 116 | Self::open(name, base) |
35cf5daa DM |
117 | } |
118 | ||
277fc5a3 | 119 | pub fn open<P: Into<PathBuf>>(name: &str, path: P) -> Result<Self, Error> { |
35cf5daa | 120 | |
45773720 | 121 | let base: PathBuf = path.into(); |
68469eeb DM |
122 | |
123 | if !base.is_absolute() { | |
124 | bail!("expected absolute path - got {:?}", base); | |
125 | } | |
126 | ||
45773720 DM |
127 | let chunk_dir = Self::chunk_dir(&base); |
128 | ||
ce55dbbc | 129 | if let Err(err) = std::fs::metadata(&chunk_dir) { |
277fc5a3 | 130 | bail!("unable to open chunk store '{}' at {:?} - {}", name, chunk_dir, err); |
ce55dbbc | 131 | } |
45773720 DM |
132 | |
133 | let mut lockfile_path = base.clone(); | |
134 | lockfile_path.push(".lock"); | |
135 | ||
43b13033 | 136 | let locker = tools::ProcessLocker::new(&lockfile_path)?; |
35cf5daa | 137 | |
b8d4766a | 138 | Ok(ChunkStore { |
277fc5a3 | 139 | name: name.to_owned(), |
b8d4766a DM |
140 | base, |
141 | chunk_dir, | |
43b13033 | 142 | locker, |
b8d4766a DM |
143 | mutex: Mutex::new(false) |
144 | }) | |
35cf5daa DM |
145 | } |
146 | ||
7394ca3e | 147 | pub fn touch_chunk(&self, digest:&[u8]) -> Result<(), Error> { |
3d5c11e5 | 148 | |
a198d74f | 149 | let mut chunk_path = self.chunk_dir.clone(); |
08481a0b | 150 | let prefix = digest_to_prefix(&digest); |
3d5c11e5 | 151 | chunk_path.push(&prefix); |
22968600 | 152 | let digest_str = tools::digest_to_hex(&digest); |
3d5c11e5 DM |
153 | chunk_path.push(&digest_str); |
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 | ||
df9973e8 | 176 | pub fn read_chunk(&self, digest:&[u8], buffer: &mut Vec<u8>) -> Result<(), Error> { |
96df2fb4 DM |
177 | |
178 | let mut chunk_path = self.chunk_dir.clone(); | |
179 | let prefix = digest_to_prefix(&digest); | |
180 | chunk_path.push(&prefix); | |
22968600 | 181 | let digest_str = tools::digest_to_hex(&digest); |
96df2fb4 DM |
182 | chunk_path.push(&digest_str); |
183 | ||
d2690f74 | 184 | buffer.clear(); |
78216a5a | 185 | let f = std::fs::File::open(&chunk_path)?; |
141f062e | 186 | let mut decoder = zstd::stream::Decoder::new(f)?; |
df9973e8 | 187 | |
78216a5a | 188 | decoder.read_to_end(buffer)?; |
96df2fb4 | 189 | |
df9973e8 | 190 | Ok(()) |
96df2fb4 DM |
191 | } |
192 | ||
9739aca4 WB |
193 | pub fn get_chunk_iterator( |
194 | &self, | |
eff25eca | 195 | print_percentage: bool, |
9739aca4 | 196 | ) -> Result< |
3a50ddd0 | 197 | impl Iterator<Item = Result<tools::fs::ReadDirEntry, Error>> + std::iter::FusedIterator, |
9739aca4 WB |
198 | Error |
199 | > { | |
200 | use nix::dir::Dir; | |
201 | use nix::fcntl::OFlag; | |
202 | use nix::sys::stat::Mode; | |
203 | ||
204 | let base_handle = match Dir::open( | |
205 | &self.chunk_dir, OFlag::O_RDONLY, Mode::empty()) { | |
206 | Ok(h) => h, | |
207 | Err(err) => bail!("unable to open store '{}' chunk dir {:?} - {}", | |
208 | self.name, self.chunk_dir, err), | |
209 | }; | |
210 | ||
c7f481b6 WB |
211 | let mut verbose = true; |
212 | let mut last_percentage = 0; | |
213 | ||
9739aca4 | 214 | Ok((0..0x10000).filter_map(move |index| { |
eff25eca WB |
215 | if print_percentage { |
216 | let percentage = (index * 100) / 0x10000; | |
217 | if last_percentage != percentage { | |
218 | last_percentage = percentage; | |
219 | eprintln!("percentage done: {}", percentage); | |
220 | } | |
c7f481b6 WB |
221 | } |
222 | let subdir: &str = &format!("{:04x}", index); | |
223 | match tools::fs::read_subdir(base_handle.as_raw_fd(), subdir) { | |
224 | Err(e) => { | |
225 | if verbose { | |
226 | eprintln!("Error iterating through chunks: {}", e); | |
227 | verbose = false; | |
228 | } | |
229 | None | |
230 | } | |
231 | Ok(iter) => Some(iter), | |
232 | } | |
233 | }) | |
62f2422f WB |
234 | .flatten() |
235 | .filter(|entry| { | |
236 | // Check that the file name is actually a hash! (64 hex digits) | |
237 | let entry = match entry { | |
238 | Err(_) => return true, // pass errors onwards | |
239 | Ok(ref entry) => entry, | |
240 | }; | |
241 | let bytes = entry.file_name().to_bytes(); | |
242 | if bytes.len() != 64 { | |
243 | return false; | |
244 | } | |
245 | for b in bytes { | |
246 | if !b.is_ascii_hexdigit() { | |
247 | return false; | |
248 | } | |
249 | } | |
250 | true | |
251 | })) | |
c7f481b6 WB |
252 | } |
253 | ||
11861a48 DM |
254 | pub fn oldest_writer(&self) -> Option<i64> { |
255 | tools::ProcessLocker::oldest_shared_lock(self.locker.clone()) | |
256 | } | |
257 | ||
258 | pub fn sweep_unused_chunks( | |
259 | &self, | |
260 | oldest_writer: Option<i64>, | |
261 | status: &mut GarbageCollectionStatus | |
262 | ) -> Result<(), Error> { | |
9349d2a1 | 263 | use nix::sys::stat::fstatat; |
08481a0b | 264 | |
fdd71f52 | 265 | let now = unsafe { libc::time(std::ptr::null_mut()) }; |
c7f481b6 | 266 | |
11861a48 DM |
267 | let mut min_atime = now - 3600*24; // at least 24h (see mount option relatime) |
268 | ||
269 | if let Some(stamp) = oldest_writer { | |
270 | if stamp < min_atime { | |
271 | min_atime = stamp; | |
272 | } | |
273 | } | |
274 | ||
275 | min_atime -= 300; // add 5 mins gap for safety | |
276 | ||
eff25eca | 277 | for entry in self.get_chunk_iterator(true)? { |
92da93b2 DM |
278 | |
279 | tools::fail_on_shutdown()?; | |
280 | ||
fdd71f52 | 281 | let (dirfd, entry) = match entry { |
c7f481b6 WB |
282 | Ok(entry) => (entry.parent_fd(), entry), |
283 | Err(_) => continue, // ignore errors | |
eae8aa3a | 284 | }; |
fdd71f52 | 285 | |
eae8aa3a DM |
286 | let file_type = match entry.file_type() { |
287 | Some(file_type) => file_type, | |
277fc5a3 | 288 | None => bail!("unsupported file system type on chunk store '{}'", self.name), |
eae8aa3a | 289 | }; |
82bc0ad4 WB |
290 | if file_type != nix::dir::Type::File { |
291 | continue; | |
292 | } | |
eae8aa3a | 293 | |
d85987ae DM |
294 | let filename = entry.file_name(); |
295 | ||
15a77c4c DM |
296 | let lock = self.mutex.lock(); |
297 | ||
9349d2a1 | 298 | if let Ok(stat) = fstatat(dirfd, filename, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) { |
eae8aa3a | 299 | let age = now - stat.st_atime; |
e95950e4 | 300 | //println!("FOUND {} {:?}", age/(3600*24), filename); |
11861a48 | 301 | if stat.st_atime < min_atime { |
eae8aa3a | 302 | println!("UNLINK {} {:?}", age/(3600*24), filename); |
fdd71f52 | 303 | let res = unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) }; |
277fc5a3 DM |
304 | if res != 0 { |
305 | let err = nix::Error::last(); | |
9349d2a1 WB |
306 | bail!( |
307 | "unlink chunk {:?} failed on store '{}' - {}", | |
308 | filename, | |
309 | self.name, | |
310 | err, | |
311 | ); | |
277fc5a3 | 312 | } |
64e53b28 DM |
313 | } else { |
314 | status.disk_chunks += 1; | |
315 | status.disk_bytes += stat.st_size as usize; | |
08481a0b | 316 | } |
eae8aa3a | 317 | } |
15a77c4c | 318 | drop(lock); |
eae8aa3a | 319 | } |
277fc5a3 | 320 | Ok(()) |
08481a0b DM |
321 | } |
322 | ||
798f7fa0 | 323 | pub fn insert_chunk(&self, chunk: &[u8]) -> Result<(bool, [u8; 32], u64), Error> { |
128b37fe | 324 | |
7b2b40a8 | 325 | // fixme: use Sha512/256 when available |
9ac6ec86 WB |
326 | let digest = sha::sha256(chunk); |
327 | let (new, csize) = self.insert_chunk_noverify(&digest, chunk)?; | |
328 | Ok((new, digest, csize)) | |
329 | } | |
7b2b40a8 | 330 | |
9ac6ec86 WB |
331 | pub fn insert_chunk_noverify( |
332 | &self, | |
333 | digest: &[u8; 32], | |
334 | chunk: &[u8], | |
335 | ) -> Result<(bool, u64), Error> { | |
7b2b40a8 | 336 | |
22968600 | 337 | //println!("DIGEST {}", tools::digest_to_hex(&digest)); |
128b37fe | 338 | |
af3e7d75 | 339 | let mut chunk_path = self.chunk_dir.clone(); |
9ac6ec86 | 340 | let prefix = digest_to_prefix(digest); |
c5d82e5f | 341 | chunk_path.push(&prefix); |
9ac6ec86 | 342 | let digest_str = tools::digest_to_hex(digest); |
c5d82e5f DM |
343 | chunk_path.push(&digest_str); |
344 | ||
345 | let lock = self.mutex.lock(); | |
346 | ||
347 | if let Ok(metadata) = std::fs::metadata(&chunk_path) { | |
348 | if metadata.is_file() { | |
9ac6ec86 | 349 | return Ok((true, metadata.len())); |
c5d82e5f | 350 | } else { |
f7dd683b | 351 | bail!("Got unexpected file type on store '{}' for chunk {}", self.name, digest_str); |
c5d82e5f DM |
352 | } |
353 | } | |
128b37fe | 354 | |
c5d82e5f DM |
355 | let mut tmp_path = chunk_path.clone(); |
356 | tmp_path.set_extension("tmp"); | |
78216a5a DM |
357 | |
358 | let f = std::fs::File::create(&tmp_path)?; | |
359 | ||
141f062e | 360 | let mut encoder = zstd::stream::Encoder::new(f, 1)?; |
78216a5a DM |
361 | |
362 | encoder.write_all(chunk)?; | |
141f062e | 363 | let f = encoder.finish()?; |
128b37fe | 364 | |
c5d82e5f DM |
365 | if let Err(err) = std::fs::rename(&tmp_path, &chunk_path) { |
366 | if let Err(_) = std::fs::remove_file(&tmp_path) { /* ignore */ } | |
9349d2a1 WB |
367 | bail!( |
368 | "Atomic rename on store '{}' failed for chunk {} - {}", | |
369 | self.name, | |
370 | digest_str, | |
371 | err, | |
372 | ); | |
c5d82e5f DM |
373 | } |
374 | ||
798f7fa0 DM |
375 | // fixme: is there a better way to get the compressed size? |
376 | let stat = nix::sys::stat::fstat(f.as_raw_fd())?; | |
377 | let compressed_size = stat.st_size as u64; | |
378 | ||
77703d95 | 379 | //println!("PATH {:?}", chunk_path); |
128b37fe | 380 | |
c5d82e5f DM |
381 | drop(lock); |
382 | ||
9ac6ec86 | 383 | Ok((false, compressed_size)) |
128b37fe DM |
384 | } |
385 | ||
606ce64b DM |
386 | pub fn relative_path(&self, path: &Path) -> PathBuf { |
387 | ||
388 | let mut full_path = self.base.clone(); | |
389 | full_path.push(path); | |
390 | full_path | |
391 | } | |
392 | ||
3d5c11e5 DM |
393 | pub fn base_path(&self) -> PathBuf { |
394 | self.base.clone() | |
395 | } | |
43b13033 DM |
396 | |
397 | pub fn try_shared_lock(&self) -> Result<tools::ProcessLockSharedGuard, Error> { | |
398 | tools::ProcessLocker::try_shared_lock(self.locker.clone()) | |
399 | } | |
400 | ||
401 | pub fn try_exclusive_lock(&self) -> Result<tools::ProcessLockExclusiveGuard, Error> { | |
402 | tools::ProcessLocker::try_exclusive_lock(self.locker.clone()) | |
403 | } | |
35cf5daa DM |
404 | } |
405 | ||
406 | ||
407 | #[test] | |
408 | fn test_chunk_store1() { | |
409 | ||
332dcc22 DM |
410 | let mut path = std::fs::canonicalize(".").unwrap(); // we need absulute path |
411 | path.push(".testdir"); | |
412 | ||
35cf5daa DM |
413 | if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ } |
414 | ||
332dcc22 | 415 | let chunk_store = ChunkStore::open("test", &path); |
35cf5daa DM |
416 | assert!(chunk_store.is_err()); |
417 | ||
332dcc22 | 418 | let chunk_store = ChunkStore::create("test", &path).unwrap(); |
798f7fa0 | 419 | let (exists, _, _) = chunk_store.insert_chunk(&[0u8, 1u8]).unwrap(); |
391a2e43 DM |
420 | assert!(!exists); |
421 | ||
798f7fa0 | 422 | let (exists, _, _) = chunk_store.insert_chunk(&[0u8, 1u8]).unwrap(); |
391a2e43 | 423 | assert!(exists); |
128b37fe | 424 | |
35cf5daa | 425 | |
332dcc22 | 426 | let chunk_store = ChunkStore::create("test", &path); |
35cf5daa DM |
427 | assert!(chunk_store.is_err()); |
428 | ||
e0a5d1ca | 429 | if let Err(_e) = std::fs::remove_dir_all(".testdir") { /* ignore */ } |
35cf5daa | 430 | } |