2 use std
::path
::{Path, PathBuf}
;
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 mut f
= std
::fs
::File
::open(&chunk_path
)?
;
186 let stat
= nix
::sys
::stat
::fstat(f
.as_raw_fd())?
;
187 let size
= stat
.st_size
as usize;
189 if buffer
.capacity() < size
{
190 let mut newsize
= buffer
.capacity();
191 while newsize
< size { newsize = newsize << 1; }
192 let additional
= newsize
- buffer
.len();
193 buffer
.reserve_exact(additional
);
195 unsafe { buffer.set_len(size); }
199 f
.read_exact(buffer
.as_mut_slice())?
;
204 pub fn get_chunk_iterator(
207 impl Iterator
<Item
= Result
<tools
::fs
::ReadDirEntry
, Error
>>,
211 use nix
::fcntl
::OFlag
;
212 use nix
::sys
::stat
::Mode
;
214 let base_handle
= match Dir
::open(
215 &self.chunk_dir
, OFlag
::O_RDONLY
, Mode
::empty()) {
217 Err(err
) => bail
!("unable to open store '{}' chunk dir {:?} - {}",
218 self.name
, self.chunk_dir
, err
),
221 let mut verbose
= true;
222 let mut last_percentage
= 0;
224 Ok((0..0x10000).filter_map(move |index
| {
225 let percentage
= (index
* 100) / 0x10000;
226 if last_percentage
!= percentage
{
227 last_percentage
= percentage
;
228 eprintln
!("percentage done: {}", percentage
);
230 let subdir
: &str = &format
!("{:04x}", index
);
231 match tools
::fs
::read_subdir(base_handle
.as_raw_fd(), subdir
) {
234 eprintln
!("Error iterating through chunks: {}", e
);
239 Ok(iter
) => Some(iter
),
244 // Check that the file name is actually a hash! (64 hex digits)
245 let entry
= match entry
{
246 Err(_
) => return true, // pass errors onwards
247 Ok(ref entry
) => entry
,
249 let bytes
= entry
.file_name().to_bytes();
250 if bytes
.len() != 64 {
254 if !b
.is_ascii_hexdigit() {
262 pub fn sweep_unused_chunks(&self, status
: &mut GarbageCollectionStatus
) -> Result
<(), Error
> {
263 use nix
::sys
::stat
::fstatat
;
265 let now
= unsafe { libc::time(std::ptr::null_mut()) }
;
267 for entry
in self.get_chunk_iterator()?
{
268 let (dirfd
, entry
) = match entry
{
269 Ok(entry
) => (entry
.parent_fd(), entry
),
270 Err(_
) => continue, // ignore errors
273 let file_type
= match entry
.file_type() {
274 Some(file_type
) => file_type
,
275 None
=> bail
!("unsupported file system type on chunk store '{}'", self.name
),
277 if file_type
!= nix
::dir
::Type
::File
{
281 let filename
= entry
.file_name();
282 if let Ok(stat
) = fstatat(dirfd
, filename
, nix
::fcntl
::AtFlags
::AT_SYMLINK_NOFOLLOW
) {
283 let age
= now
- stat
.st_atime
;
284 //println!("FOUND {} {:?}", age/(3600*24), filename);
285 if age
/(3600*24) >= 2 {
286 println
!("UNLINK {} {:?}", age
/(3600*24), filename
);
287 let res
= unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) }
;
289 let err
= nix
::Error
::last();
291 "unlink chunk {:?} failed on store '{}' - {}",
298 status
.disk_chunks
+= 1;
299 status
.disk_bytes
+= stat
.st_size
as usize;
307 pub fn insert_chunk(&self, chunk
: &[u8]) -> Result
<(bool
, [u8; 32]), Error
> {
309 // fixme: use Sha512/256 when available
310 let mut hasher
= sha
::Sha256
::new();
311 hasher
.update(chunk
);
313 let digest
= hasher
.finish();
315 //println!("DIGEST {}", tools::digest_to_hex(&digest));
317 let mut chunk_path
= self.chunk_dir
.clone();
318 let prefix
= digest_to_prefix(&digest
);
319 chunk_path
.push(&prefix
);
320 let digest_str
= tools
::digest_to_hex(&digest
);
321 chunk_path
.push(&digest_str
);
323 let lock
= self.mutex
.lock();
325 if let Ok(metadata
) = std
::fs
::metadata(&chunk_path
) {
326 if metadata
.is_file() {
327 return Ok((true, digest
));
329 bail
!("Got unexpected file type on store '{}' for chunk {}", self.name
, digest_str
);
333 let mut tmp_path
= chunk_path
.clone();
334 tmp_path
.set_extension("tmp");
335 let mut f
= std
::fs
::File
::create(&tmp_path
)?
;
338 if let Err(err
) = std
::fs
::rename(&tmp_path
, &chunk_path
) {
339 if let Err(_
) = std
::fs
::remove_file(&tmp_path
) { /* ignore */ }
341 "Atomic rename on store '{}' failed for chunk {} - {}",
348 //println!("PATH {:?}", chunk_path);
355 pub fn relative_path(&self, path
: &Path
) -> PathBuf
{
357 let mut full_path
= self.base
.clone();
358 full_path
.push(path
);
362 pub fn base_path(&self) -> PathBuf
{
369 fn test_chunk_store1() {
371 let mut path
= std
::fs
::canonicalize(".").unwrap(); // we need absulute path
372 path
.push(".testdir");
374 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }
376 let chunk_store
= ChunkStore
::open("test", &path
);
377 assert
!(chunk_store
.is_err());
379 let chunk_store
= ChunkStore
::create("test", &path
).unwrap();
380 let (exists
, _
) = chunk_store
.insert_chunk(&[0u8, 1u8]).unwrap();
383 let (exists
, _
) = chunk_store
.insert_chunk(&[0u8, 1u8]).unwrap();
387 let chunk_store
= ChunkStore
::create("test", &path
);
388 assert
!(chunk_store
.is_err());
390 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }