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 pub struct ChunkStore
{
33 name
: String
, // used for error reporting
34 pub (crate) base
: PathBuf
,
40 const HEX_CHARS
: &'
static [u8; 16] = b
"0123456789abcdef";
42 // TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
44 pub fn digest_to_hex(digest
: &[u8]) -> String
{
46 let mut buf
= Vec
::<u8>::with_capacity(digest
.len()*2);
48 for i
in 0..digest
.len() {
49 buf
.push(HEX_CHARS
[(digest
[i
] >> 4) as usize]);
50 buf
.push(HEX_CHARS
[(digest
[i
] & 0xf) as usize]);
53 unsafe { String::from_utf8_unchecked(buf) }
56 fn digest_to_prefix(digest
: &[u8]) -> PathBuf
{
58 let mut buf
= Vec
::<u8>::with_capacity(2+1+2+1);
60 buf
.push(HEX_CHARS
[(digest
[0] as usize) >> 4]);
61 buf
.push(HEX_CHARS
[(digest
[0] as usize) &0xf]);
62 buf
.push(HEX_CHARS
[(digest
[1] as usize) >> 4]);
63 buf
.push(HEX_CHARS
[(digest
[1] as usize) & 0xf]);
66 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 // make sure only one process/thread/task can use it
137 let lockfile
= tools
::open_file_locked(
138 lockfile_path
, Duration
::from_secs(10))?
;
141 name
: name
.to_owned(),
145 mutex
: Mutex
::new(false)
149 pub fn touch_chunk(&self, digest
:&[u8]) -> Result
<(), Error
> {
151 let mut chunk_path
= self.chunk_dir
.clone();
152 let prefix
= digest_to_prefix(&digest
);
153 chunk_path
.push(&prefix
);
154 let digest_str
= digest_to_hex(&digest
);
155 chunk_path
.push(&digest_str
);
157 const UTIME_NOW
: i64 = ((1 << 30) - 1);
158 const UTIME_OMIT
: i64 = ((1 << 30) - 2);
160 let times
: [libc
::timespec
; 2] = [
161 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_NOW }
,
162 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT }
167 let res
= chunk_path
.with_nix_path(|cstr
| unsafe {
168 libc
::utimensat(-1, cstr
.as_ptr(), ×
[0], libc
::AT_SYMLINK_NOFOLLOW
)
171 if let Err(err
) = nix
::errno
::Errno
::result(res
) {
172 bail
!("updata atime failed for chunk {:?} - {}", chunk_path
, err
);
178 pub fn read_chunk(&self, digest
:&[u8], buffer
: &mut Vec
<u8>) -> Result
<(), Error
> {
180 let mut chunk_path
= self.chunk_dir
.clone();
181 let prefix
= digest_to_prefix(&digest
);
182 chunk_path
.push(&prefix
);
183 let digest_str
= digest_to_hex(&digest
);
184 chunk_path
.push(&digest_str
);
186 let mut f
= std
::fs
::File
::open(&chunk_path
)?
;
188 let stat
= nix
::sys
::stat
::fstat(f
.as_raw_fd())?
;
189 let size
= stat
.st_size
as usize;
191 if buffer
.capacity() < size
{
192 let mut newsize
= buffer
.capacity();
193 while newsize
< size { newsize = newsize << 1; }
194 let additional
= newsize
- buffer
.len();
195 buffer
.reserve_exact(additional
);
197 unsafe { buffer.set_len(size); }
201 f
.read_exact(buffer
.as_mut_slice())?
;
206 fn sweep_old_files(&self, handle
: &mut nix
::dir
::Dir
, status
: &mut GarbageCollectionStatus
) -> Result
<(), Error
> {
208 let rawfd
= handle
.as_raw_fd();
210 let now
= unsafe { libc::time(std::ptr::null_mut()) }
;
212 for entry
in handle
.iter() {
213 let entry
= match entry
{
215 Err(_
) => continue /* ignore */,
217 let file_type
= match entry
.file_type() {
218 Some(file_type
) => file_type
,
219 None
=> bail
!("unsupported file system type on chunk store '{}'", self.name
),
221 if file_type
!= nix
::dir
::Type
::File { continue; }
223 let filename
= entry
.file_name();
224 if let Ok(stat
) = nix
::sys
::stat
::fstatat(rawfd
, filename
, nix
::fcntl
::AtFlags
::AT_SYMLINK_NOFOLLOW
) {
225 let age
= now
- stat
.st_atime
;
226 //println!("FOUND {} {:?}", age/(3600*24), filename);
227 if age
/(3600*24) >= 2 {
228 println
!("UNLINK {} {:?}", age
/(3600*24), filename
);
229 let res
= unsafe { libc::unlinkat(rawfd, filename.as_ptr(), 0) }
;
231 let err
= nix
::Error
::last();
232 bail
!("unlink chunk {:?} failed on store '{}' - {}", filename
, self.name
, err
);
235 status
.disk_chunks
+= 1;
236 status
.disk_bytes
+= stat
.st_size
as usize;
244 pub fn sweep_unused_chunks(&self, status
: &mut GarbageCollectionStatus
) -> Result
<(), Error
> {
246 use nix
::fcntl
::OFlag
;
247 use nix
::sys
::stat
::Mode
;
250 let base_handle
= match Dir
::open(
251 &self.chunk_dir
, OFlag
::O_RDONLY
, Mode
::empty()) {
253 Err(err
) => bail
!("unable to open store '{}' chunk dir {:?} - {}",
254 self.name
, self.chunk_dir
, err
),
257 let base_fd
= base_handle
.as_raw_fd();
259 let mut last_percentage
= 0;
261 for i
in 0..64*1024 {
263 let percentage
= (i
*100)/(64*1024);
264 if percentage
!= last_percentage
{
265 eprintln
!("Percentage done: {}", percentage
);
266 last_percentage
= percentage
;
269 let l1name
= PathBuf
::from(format
!("{:04x}", i
));
270 match nix
::dir
::Dir
::openat(base_fd
, &l1name
, OFlag
::O_RDONLY
, Mode
::empty()) {
272 //println!("SCAN {:?} {:?}", l1name);
273 self.sweep_old_files(&mut h
, status
)?
;
275 Err(err
) => bail
!("unable to open store '{}' dir {:?}/{:?} - {}",
276 self.name
, self.chunk_dir
, l1name
, err
),
282 pub fn insert_chunk(&self, chunk
: &[u8]) -> Result
<(bool
, [u8; 32]), Error
> {
284 // fixme: use Sha512/256 when available
285 let mut hasher
= sha
::Sha256
::new();
286 hasher
.update(chunk
);
288 let digest
= hasher
.finish();
290 //println!("DIGEST {}", digest_to_hex(&digest));
292 let mut chunk_path
= self.chunk_dir
.clone();
293 let prefix
= digest_to_prefix(&digest
);
294 chunk_path
.push(&prefix
);
295 let digest_str
= digest_to_hex(&digest
);
296 chunk_path
.push(&digest_str
);
298 let lock
= self.mutex
.lock();
300 if let Ok(metadata
) = std
::fs
::metadata(&chunk_path
) {
301 if metadata
.is_file() {
302 return Ok((true, digest
));
304 bail
!("Got unexpected file type on store '{}' for chunk {}", self.name
, digest_str
);
308 let mut tmp_path
= chunk_path
.clone();
309 tmp_path
.set_extension("tmp");
310 let mut f
= std
::fs
::File
::create(&tmp_path
)?
;
313 if let Err(err
) = std
::fs
::rename(&tmp_path
, &chunk_path
) {
314 if let Err(_
) = std
::fs
::remove_file(&tmp_path
) { /* ignore */ }
315 bail
!("Atomic rename on store '{}' failed for chunk {} - {}", self.name
, digest_str
, err
);
318 //println!("PATH {:?}", chunk_path);
325 pub fn relative_path(&self, path
: &Path
) -> PathBuf
{
327 let mut full_path
= self.base
.clone();
328 full_path
.push(path
);
332 pub fn base_path(&self) -> PathBuf
{
339 fn test_chunk_store1() {
341 let mut path
= std
::fs
::canonicalize(".").unwrap(); // we need absulute path
342 path
.push(".testdir");
344 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }
346 let chunk_store
= ChunkStore
::open("test", &path
);
347 assert
!(chunk_store
.is_err());
349 let chunk_store
= ChunkStore
::create("test", &path
).unwrap();
350 let (exists
, _
) = chunk_store
.insert_chunk(&[0u8, 1u8]).unwrap();
353 let (exists
, _
) = chunk_store
.insert_chunk(&[0u8, 1u8]).unwrap();
357 let chunk_store
= ChunkStore
::create("test", &path
);
358 assert
!(chunk_store
.is_err());