2 use std
::path
::{Path, PathBuf}
;
3 use std
::io
::{Read, Write}
;
4 use std
::time
::Duration
;
10 use std
::os
::unix
::io
::AsRawFd
;
14 pub struct GarbageCollectionStatus
{
15 pub used_bytes
: usize,
16 pub used_chunks
: usize,
17 pub disk_bytes
: usize,
18 pub disk_chunks
: usize,
21 impl Default
for GarbageCollectionStatus
{
22 fn default() -> Self {
23 GarbageCollectionStatus
{
32 /// File system based chunk store
33 pub struct ChunkStore
{
34 name
: String
, // used for error reporting
35 pub (crate) base
: PathBuf
,
41 // TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
43 pub fn verify_chunk_size(size
: u64) -> Result
<(), Error
> {
45 static SIZES
: [u64; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
47 if !SIZES
.contains(&size
) {
48 bail
!("Got unsupported chunk size '{}'", size
);
53 fn digest_to_prefix(digest
: &[u8]) -> PathBuf
{
55 let mut buf
= Vec
::<u8>::with_capacity(2+1+2+1);
57 const HEX_CHARS
: &'
static [u8; 16] = b
"0123456789abcdef";
59 buf
.push(HEX_CHARS
[(digest
[0] as usize) >> 4]);
60 buf
.push(HEX_CHARS
[(digest
[0] as usize) &0xf]);
61 buf
.push(HEX_CHARS
[(digest
[1] as usize) >> 4]);
62 buf
.push(HEX_CHARS
[(digest
[1] as usize) & 0xf]);
65 let path
= unsafe { String::from_utf8_unchecked(buf)}
;
72 fn chunk_dir
<P
: AsRef
<Path
>>(path
: P
) -> PathBuf
{
74 let mut chunk_dir
: PathBuf
= PathBuf
::from(path
.as_ref());
75 chunk_dir
.push(".chunks");
80 pub fn create
<P
: Into
<PathBuf
>>(name
: &str, path
: P
) -> Result
<Self, Error
> {
82 let base
: PathBuf
= path
.into();
84 if !base
.is_absolute() {
85 bail
!("expected absolute path - got {:?}", base
);
88 let chunk_dir
= Self::chunk_dir(&base
);
90 if let Err(err
) = std
::fs
::create_dir(&base
) {
91 bail
!("unable to create chunk store '{}' at {:?} - {}", name
, base
, err
);
94 if let Err(err
) = std
::fs
::create_dir(&chunk_dir
) {
95 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, chunk_dir
, err
);
98 // create 64*1024 subdirs
99 let mut last_percentage
= 0;
101 for i
in 0..64*1024 {
102 let mut l1path
= chunk_dir
.clone();
103 l1path
.push(format
!("{:04x}", i
));
104 if let Err(err
) = std
::fs
::create_dir(&l1path
) {
105 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, l1path
, err
);
107 let percentage
= (i
*100)/(64*1024);
108 if percentage
!= last_percentage
{
109 eprintln
!("Percentage done: {}", percentage
);
110 last_percentage
= percentage
;
114 Self::open(name
, base
)
117 pub fn open
<P
: Into
<PathBuf
>>(name
: &str, path
: P
) -> Result
<Self, Error
> {
119 let base
: PathBuf
= path
.into();
121 if !base
.is_absolute() {
122 bail
!("expected absolute path - got {:?}", base
);
125 let chunk_dir
= Self::chunk_dir(&base
);
127 if let Err(err
) = std
::fs
::metadata(&chunk_dir
) {
128 bail
!("unable to open chunk store '{}' at {:?} - {}", name
, chunk_dir
, err
);
131 let mut lockfile_path
= base
.clone();
132 lockfile_path
.push(".lock");
134 // make sure only one process/thread/task can use it
135 let lockfile
= tools
::open_file_locked(
136 lockfile_path
, Duration
::from_secs(10))?
;
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
);
184 let f
= std
::fs
::File
::open(&chunk_path
)?
;
185 let mut decoder
= lz4
::Decoder
::new(f
)?
;
187 decoder
.read_to_end(buffer
)?
;
192 pub fn get_chunk_iterator(
194 print_percentage
: bool
,
196 impl Iterator
<Item
= Result
<tools
::fs
::ReadDirEntry
, Error
>> + std
::iter
::FusedIterator
,
200 use nix
::fcntl
::OFlag
;
201 use nix
::sys
::stat
::Mode
;
203 let base_handle
= match Dir
::open(
204 &self.chunk_dir
, OFlag
::O_RDONLY
, Mode
::empty()) {
206 Err(err
) => bail
!("unable to open store '{}' chunk dir {:?} - {}",
207 self.name
, self.chunk_dir
, err
),
210 let mut verbose
= true;
211 let mut last_percentage
= 0;
213 Ok((0..0x10000).filter_map(move |index
| {
214 if print_percentage
{
215 let percentage
= (index
* 100) / 0x10000;
216 if last_percentage
!= percentage
{
217 last_percentage
= percentage
;
218 eprintln
!("percentage done: {}", percentage
);
221 let subdir
: &str = &format
!("{:04x}", index
);
222 match tools
::fs
::read_subdir(base_handle
.as_raw_fd(), subdir
) {
225 eprintln
!("Error iterating through chunks: {}", e
);
230 Ok(iter
) => Some(iter
),
235 // Check that the file name is actually a hash! (64 hex digits)
236 let entry
= match entry
{
237 Err(_
) => return true, // pass errors onwards
238 Ok(ref entry
) => entry
,
240 let bytes
= entry
.file_name().to_bytes();
241 if bytes
.len() != 64 {
245 if !b
.is_ascii_hexdigit() {
253 pub fn sweep_unused_chunks(&self, status
: &mut GarbageCollectionStatus
) -> Result
<(), Error
> {
254 use nix
::sys
::stat
::fstatat
;
256 let now
= unsafe { libc::time(std::ptr::null_mut()) }
;
258 for entry
in self.get_chunk_iterator(true)?
{
259 let (dirfd
, entry
) = match entry
{
260 Ok(entry
) => (entry
.parent_fd(), entry
),
261 Err(_
) => continue, // ignore errors
264 let file_type
= match entry
.file_type() {
265 Some(file_type
) => file_type
,
266 None
=> bail
!("unsupported file system type on chunk store '{}'", self.name
),
268 if file_type
!= nix
::dir
::Type
::File
{
272 let filename
= entry
.file_name();
273 if let Ok(stat
) = fstatat(dirfd
, filename
, nix
::fcntl
::AtFlags
::AT_SYMLINK_NOFOLLOW
) {
274 let age
= now
- stat
.st_atime
;
275 //println!("FOUND {} {:?}", age/(3600*24), filename);
276 if age
/(3600*24) >= 2 {
277 println
!("UNLINK {} {:?}", age
/(3600*24), filename
);
278 let res
= unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) }
;
280 let err
= nix
::Error
::last();
282 "unlink chunk {:?} failed on store '{}' - {}",
289 status
.disk_chunks
+= 1;
290 status
.disk_bytes
+= stat
.st_size
as usize;
298 pub fn insert_chunk(&self, chunk
: &[u8]) -> Result
<(bool
, [u8; 32], u64), Error
> {
300 // fixme: use Sha512/256 when available
301 let digest
= sha
::sha256(chunk
);
302 let (new
, csize
) = self.insert_chunk_noverify(&digest
, chunk
)?
;
303 Ok((new
, digest
, csize
))
306 pub fn insert_chunk_noverify(
310 ) -> Result
<(bool
, u64), Error
> {
312 //println!("DIGEST {}", tools::digest_to_hex(&digest));
314 let mut chunk_path
= self.chunk_dir
.clone();
315 let prefix
= digest_to_prefix(digest
);
316 chunk_path
.push(&prefix
);
317 let digest_str
= tools
::digest_to_hex(digest
);
318 chunk_path
.push(&digest_str
);
320 let lock
= self.mutex
.lock();
322 if let Ok(metadata
) = std
::fs
::metadata(&chunk_path
) {
323 if metadata
.is_file() {
324 return Ok((true, metadata
.len()));
326 bail
!("Got unexpected file type on store '{}' for chunk {}", self.name
, digest_str
);
330 let mut tmp_path
= chunk_path
.clone();
331 tmp_path
.set_extension("tmp");
333 let f
= std
::fs
::File
::create(&tmp_path
)?
;
335 // fixme: what is the fasted lz4 encoder available (see lzbench)?
336 let mut encoder
= lz4
::EncoderBuilder
::new().level(1).build(f
)?
;
338 encoder
.write_all(chunk
)?
;
339 let (f
, encode_result
) = encoder
.finish();
342 if let Err(err
) = std
::fs
::rename(&tmp_path
, &chunk_path
) {
343 if let Err(_
) = std
::fs
::remove_file(&tmp_path
) { /* ignore */ }
345 "Atomic rename on store '{}' failed for chunk {} - {}",
352 // fixme: is there a better way to get the compressed size?
353 let stat
= nix
::sys
::stat
::fstat(f
.as_raw_fd())?
;
354 let compressed_size
= stat
.st_size
as u64;
356 //println!("PATH {:?}", chunk_path);
360 Ok((false, compressed_size
))
363 pub fn relative_path(&self, path
: &Path
) -> PathBuf
{
365 let mut full_path
= self.base
.clone();
366 full_path
.push(path
);
370 pub fn base_path(&self) -> PathBuf
{
377 fn test_chunk_store1() {
379 let mut path
= std
::fs
::canonicalize(".").unwrap(); // we need absulute path
380 path
.push(".testdir");
382 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }
384 let chunk_store
= ChunkStore
::open("test", &path
);
385 assert
!(chunk_store
.is_err());
387 let chunk_store
= ChunkStore
::create("test", &path
).unwrap();
388 let (exists
, _
, _
) = chunk_store
.insert_chunk(&[0u8, 1u8]).unwrap();
391 let (exists
, _
, _
) = chunk_store
.insert_chunk(&[0u8, 1u8]).unwrap();
395 let chunk_store
= ChunkStore
::create("test", &path
);
396 assert
!(chunk_store
.is_err());
398 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }