3 use std
::path
::{Path, PathBuf}
;
4 use std
::io
::{Read, Write}
;
5 use std
::sync
::{Arc, Mutex}
;
6 use std
::os
::unix
::io
::AsRawFd
;
7 use serde_derive
::Serialize
;
13 #[derive(Clone, Serialize)]
14 pub struct GarbageCollectionStatus
{
15 pub upid
: Option
<String
>,
16 pub used_bytes
: usize,
17 pub used_chunks
: usize,
18 pub disk_bytes
: usize,
19 pub disk_chunks
: usize,
22 impl Default
for GarbageCollectionStatus
{
23 fn default() -> Self {
24 GarbageCollectionStatus
{
34 /// File system based chunk store
35 pub struct ChunkStore
{
36 name
: String
, // used for error reporting
37 pub (crate) base
: PathBuf
,
40 locker
: Arc
<Mutex
<tools
::ProcessLocker
>>,
43 // TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
45 pub fn verify_chunk_size(size
: usize) -> Result
<(), Error
> {
47 static SIZES
: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
49 if !SIZES
.contains(&size
) {
50 bail
!("Got unsupported chunk size '{}'", size
);
55 fn digest_to_prefix(digest
: &[u8]) -> PathBuf
{
57 let mut buf
= Vec
::<u8>::with_capacity(2+1+2+1);
59 const HEX_CHARS
: &'
static [u8; 16] = b
"0123456789abcdef";
61 buf
.push(HEX_CHARS
[(digest
[0] as usize) >> 4]);
62 buf
.push(HEX_CHARS
[(digest
[0] as usize) &0xf]);
63 buf
.push(HEX_CHARS
[(digest
[1] as usize) >> 4]);
64 buf
.push(HEX_CHARS
[(digest
[1] as usize) & 0xf]);
67 let path
= unsafe { String::from_utf8_unchecked(buf)}
;
74 fn chunk_dir
<P
: AsRef
<Path
>>(path
: P
) -> PathBuf
{
76 let mut chunk_dir
: PathBuf
= PathBuf
::from(path
.as_ref());
77 chunk_dir
.push(".chunks");
82 pub fn create
<P
: Into
<PathBuf
>>(name
: &str, path
: P
) -> Result
<Self, Error
> {
84 let base
: PathBuf
= path
.into();
86 if !base
.is_absolute() {
87 bail
!("expected absolute path - got {:?}", base
);
90 let chunk_dir
= Self::chunk_dir(&base
);
92 if let Err(err
) = std
::fs
::create_dir(&base
) {
93 bail
!("unable to create chunk store '{}' at {:?} - {}", name
, base
, err
);
96 if let Err(err
) = std
::fs
::create_dir(&chunk_dir
) {
97 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, chunk_dir
, err
);
100 // create 64*1024 subdirs
101 let mut last_percentage
= 0;
103 for i
in 0..64*1024 {
104 let mut l1path
= chunk_dir
.clone();
105 l1path
.push(format
!("{:04x}", i
));
106 if let Err(err
) = std
::fs
::create_dir(&l1path
) {
107 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, l1path
, err
);
109 let percentage
= (i
*100)/(64*1024);
110 if percentage
!= last_percentage
{
111 eprintln
!("Percentage done: {}", percentage
);
112 last_percentage
= percentage
;
116 Self::open(name
, base
)
119 pub fn open
<P
: Into
<PathBuf
>>(name
: &str, path
: P
) -> Result
<Self, Error
> {
121 let base
: PathBuf
= path
.into();
123 if !base
.is_absolute() {
124 bail
!("expected absolute path - got {:?}", base
);
127 let chunk_dir
= Self::chunk_dir(&base
);
129 if let Err(err
) = std
::fs
::metadata(&chunk_dir
) {
130 bail
!("unable to open chunk store '{}' at {:?} - {}", name
, chunk_dir
, err
);
133 let mut lockfile_path
= base
.clone();
134 lockfile_path
.push(".lock");
136 let locker
= tools
::ProcessLocker
::new(&lockfile_path
)?
;
139 name
: name
.to_owned(),
143 mutex
: Mutex
::new(false)
147 pub fn touch_chunk(&self, digest
:&[u8]) -> Result
<(), Error
> {
149 let mut chunk_path
= self.chunk_dir
.clone();
150 let prefix
= digest_to_prefix(&digest
);
151 chunk_path
.push(&prefix
);
152 let digest_str
= tools
::digest_to_hex(&digest
);
153 chunk_path
.push(&digest_str
);
155 const UTIME_NOW
: i64 = ((1 << 30) - 1);
156 const UTIME_OMIT
: i64 = ((1 << 30) - 2);
158 let times
: [libc
::timespec
; 2] = [
159 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_NOW }
,
160 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT }
165 let res
= chunk_path
.with_nix_path(|cstr
| unsafe {
166 libc
::utimensat(-1, cstr
.as_ptr(), ×
[0], libc
::AT_SYMLINK_NOFOLLOW
)
169 if let Err(err
) = nix
::errno
::Errno
::result(res
) {
170 bail
!("updata atime failed for chunk {:?} - {}", chunk_path
, err
);
176 pub fn read_chunk(&self, digest
:&[u8], buffer
: &mut Vec
<u8>) -> Result
<(), Error
> {
178 let mut chunk_path
= self.chunk_dir
.clone();
179 let prefix
= digest_to_prefix(&digest
);
180 chunk_path
.push(&prefix
);
181 let digest_str
= tools
::digest_to_hex(&digest
);
182 chunk_path
.push(&digest_str
);
185 let f
= std
::fs
::File
::open(&chunk_path
)?
;
186 let mut decoder
= zstd
::stream
::Decoder
::new(f
)?
;
188 decoder
.read_to_end(buffer
)?
;
193 pub fn get_chunk_iterator(
195 print_percentage
: bool
,
197 impl Iterator
<Item
= Result
<tools
::fs
::ReadDirEntry
, Error
>> + std
::iter
::FusedIterator
,
201 use nix
::fcntl
::OFlag
;
202 use nix
::sys
::stat
::Mode
;
204 let base_handle
= match Dir
::open(
205 &self.chunk_dir
, OFlag
::O_RDONLY
, Mode
::empty()) {
207 Err(err
) => bail
!("unable to open store '{}' chunk dir {:?} - {}",
208 self.name
, self.chunk_dir
, err
),
211 let mut verbose
= true;
212 let mut last_percentage
= 0;
214 Ok((0..0x10000).filter_map(move |index
| {
215 if print_percentage
{
216 let percentage
= (index
* 100) / 0x10000;
217 if last_percentage
!= percentage
{
218 last_percentage
= percentage
;
219 eprintln
!("percentage done: {}", percentage
);
222 let subdir
: &str = &format
!("{:04x}", index
);
223 match tools
::fs
::read_subdir(base_handle
.as_raw_fd(), subdir
) {
226 eprintln
!("Error iterating through chunks: {}", e
);
231 Ok(iter
) => Some(iter
),
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
,
241 let bytes
= entry
.file_name().to_bytes();
242 if bytes
.len() != 64 {
246 if !b
.is_ascii_hexdigit() {
254 pub fn oldest_writer(&self) -> Option
<i64> {
255 tools
::ProcessLocker
::oldest_shared_lock(self.locker
.clone())
258 pub fn sweep_unused_chunks(
260 oldest_writer
: Option
<i64>,
261 status
: &mut GarbageCollectionStatus
262 ) -> Result
<(), Error
> {
263 use nix
::sys
::stat
::fstatat
;
265 let now
= unsafe { libc::time(std::ptr::null_mut()) }
;
267 let mut min_atime
= now
- 3600*24; // at least 24h (see mount option relatime)
269 if let Some(stamp
) = oldest_writer
{
270 if stamp
< min_atime
{
275 min_atime
-= 300; // add 5 mins gap for safety
277 for entry
in self.get_chunk_iterator(true)?
{
279 tools
::fail_on_shutdown()?
;
281 let (dirfd
, entry
) = match entry
{
282 Ok(entry
) => (entry
.parent_fd(), entry
),
283 Err(_
) => continue, // ignore errors
286 let file_type
= match entry
.file_type() {
287 Some(file_type
) => file_type
,
288 None
=> bail
!("unsupported file system type on chunk store '{}'", self.name
),
290 if file_type
!= nix
::dir
::Type
::File
{
294 let filename
= entry
.file_name();
296 let lock
= self.mutex
.lock();
298 if let Ok(stat
) = fstatat(dirfd
, filename
, nix
::fcntl
::AtFlags
::AT_SYMLINK_NOFOLLOW
) {
299 let age
= now
- stat
.st_atime
;
300 //println!("FOUND {} {:?}", age/(3600*24), filename);
301 if stat
.st_atime
< min_atime
{
302 println
!("UNLINK {} {:?}", age
/(3600*24), filename
);
303 let res
= unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) }
;
305 let err
= nix
::Error
::last();
307 "unlink chunk {:?} failed on store '{}' - {}",
314 status
.disk_chunks
+= 1;
315 status
.disk_bytes
+= stat
.st_size
as usize;
323 pub fn insert_chunk(&self, chunk
: &[u8]) -> Result
<(bool
, [u8; 32], u64), Error
> {
325 // fixme: use Sha512/256 when available
326 let digest
= sha
::sha256(chunk
);
327 let (new
, csize
) = self.insert_chunk_noverify(&digest
, chunk
)?
;
328 Ok((new
, digest
, csize
))
331 pub fn insert_chunk_noverify(
335 ) -> Result
<(bool
, u64), Error
> {
337 //println!("DIGEST {}", tools::digest_to_hex(&digest));
339 let mut chunk_path
= self.chunk_dir
.clone();
340 let prefix
= digest_to_prefix(digest
);
341 chunk_path
.push(&prefix
);
342 let digest_str
= tools
::digest_to_hex(digest
);
343 chunk_path
.push(&digest_str
);
345 let lock
= self.mutex
.lock();
347 if let Ok(metadata
) = std
::fs
::metadata(&chunk_path
) {
348 if metadata
.is_file() {
349 return Ok((true, metadata
.len()));
351 bail
!("Got unexpected file type on store '{}' for chunk {}", self.name
, digest_str
);
355 let mut tmp_path
= chunk_path
.clone();
356 tmp_path
.set_extension("tmp");
358 let f
= std
::fs
::File
::create(&tmp_path
)?
;
360 let mut encoder
= zstd
::stream
::Encoder
::new(f
, 1)?
;
362 encoder
.write_all(chunk
)?
;
363 let f
= encoder
.finish()?
;
365 if let Err(err
) = std
::fs
::rename(&tmp_path
, &chunk_path
) {
366 if let Err(_
) = std
::fs
::remove_file(&tmp_path
) { /* ignore */ }
368 "Atomic rename on store '{}' failed for chunk {} - {}",
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;
379 //println!("PATH {:?}", chunk_path);
383 Ok((false, compressed_size
))
386 pub fn relative_path(&self, path
: &Path
) -> PathBuf
{
388 let mut full_path
= self.base
.clone();
389 full_path
.push(path
);
393 pub fn base_path(&self) -> PathBuf
{
397 pub fn try_shared_lock(&self) -> Result
<tools
::ProcessLockSharedGuard
, Error
> {
398 tools
::ProcessLocker
::try_shared_lock(self.locker
.clone())
401 pub fn try_exclusive_lock(&self) -> Result
<tools
::ProcessLockExclusiveGuard
, Error
> {
402 tools
::ProcessLocker
::try_exclusive_lock(self.locker
.clone())
408 fn test_chunk_store1() {
410 let mut path
= std
::fs
::canonicalize(".").unwrap(); // we need absulute path
411 path
.push(".testdir");
413 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }
415 let chunk_store
= ChunkStore
::open("test", &path
);
416 assert
!(chunk_store
.is_err());
418 let chunk_store
= ChunkStore
::create("test", &path
).unwrap();
419 let (exists
, _
, _
) = chunk_store
.insert_chunk(&[0u8, 1u8]).unwrap();
422 let (exists
, _
, _
) = chunk_store
.insert_chunk(&[0u8, 1u8]).unwrap();
426 let chunk_store
= ChunkStore
::create("test", &path
);
427 assert
!(chunk_store
.is_err());
429 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }