3 use std
::path
::{Path, PathBuf}
;
5 use std
::sync
::{Arc, Mutex}
;
6 use std
::os
::unix
::io
::AsRawFd
;
12 #[derive(Clone, Serialize)]
13 pub struct GarbageCollectionStatus
{
14 pub upid
: Option
<String
>,
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
{
33 /// File system based chunk store
34 pub struct ChunkStore
{
35 name
: String
, // used for error reporting
36 pub (crate) base
: PathBuf
,
39 locker
: Arc
<Mutex
<tools
::ProcessLocker
>>,
42 // TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
44 pub fn verify_chunk_size(size
: usize) -> Result
<(), Error
> {
46 static SIZES
: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
48 if !SIZES
.contains(&size
) {
49 bail
!("Got unsupported chunk size '{}'", size
);
54 fn digest_to_prefix(digest
: &[u8]) -> PathBuf
{
56 let mut buf
= Vec
::<u8>::with_capacity(2+1+2+1);
58 const HEX_CHARS
: &'
static [u8; 16] = b
"0123456789abcdef";
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)}
;
73 fn chunk_dir
<P
: AsRef
<Path
>>(path
: P
) -> PathBuf
{
75 let mut chunk_dir
: PathBuf
= PathBuf
::from(path
.as_ref());
76 chunk_dir
.push(".chunks");
81 pub fn create
<P
: Into
<PathBuf
>>(name
: &str, path
: P
) -> Result
<Self, Error
> {
83 let base
: PathBuf
= path
.into();
85 if !base
.is_absolute() {
86 bail
!("expected absolute path - got {:?}", base
);
89 let chunk_dir
= Self::chunk_dir(&base
);
91 if let Err(err
) = std
::fs
::create_dir(&base
) {
92 bail
!("unable to create chunk store '{}' at {:?} - {}", name
, base
, err
);
95 if let Err(err
) = std
::fs
::create_dir(&chunk_dir
) {
96 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, chunk_dir
, err
);
99 // create 64*1024 subdirs
100 let mut last_percentage
= 0;
102 for i
in 0..64*1024 {
103 let mut l1path
= chunk_dir
.clone();
104 l1path
.push(format
!("{:04x}", i
));
105 if let Err(err
) = std
::fs
::create_dir(&l1path
) {
106 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, l1path
, err
);
108 let percentage
= (i
*100)/(64*1024);
109 if percentage
!= last_percentage
{
110 eprintln
!("Percentage done: {}", percentage
);
111 last_percentage
= percentage
;
115 Self::open(name
, base
)
118 pub fn open
<P
: Into
<PathBuf
>>(name
: &str, path
: P
) -> Result
<Self, Error
> {
120 let base
: PathBuf
= path
.into();
122 if !base
.is_absolute() {
123 bail
!("expected absolute path - got {:?}", base
);
126 let chunk_dir
= Self::chunk_dir(&base
);
128 if let Err(err
) = std
::fs
::metadata(&chunk_dir
) {
129 bail
!("unable to open chunk store '{}' at {:?} - {}", name
, chunk_dir
, err
);
132 let mut lockfile_path
= base
.clone();
133 lockfile_path
.push(".lock");
135 let locker
= tools
::ProcessLocker
::new(&lockfile_path
)?
;
138 name
: name
.to_owned(),
142 mutex
: Mutex
::new(false)
146 pub fn touch_chunk(&self, digest
:&[u8]) -> Result
<(), Error
> {
148 let mut chunk_path
= self.chunk_dir
.clone();
149 let prefix
= digest_to_prefix(&digest
);
150 chunk_path
.push(&prefix
);
151 let digest_str
= proxmox
::tools
::digest_to_hex(&digest
);
152 chunk_path
.push(&digest_str
);
154 const UTIME_NOW
: i64 = ((1 << 30) - 1);
155 const UTIME_OMIT
: i64 = ((1 << 30) - 2);
157 let times
: [libc
::timespec
; 2] = [
158 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_NOW }
,
159 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT }
164 let res
= chunk_path
.with_nix_path(|cstr
| unsafe {
165 libc
::utimensat(-1, cstr
.as_ptr(), ×
[0], libc
::AT_SYMLINK_NOFOLLOW
)
168 if let Err(err
) = nix
::errno
::Errno
::result(res
) {
169 bail
!("updata atime failed for chunk {:?} - {}", chunk_path
, err
);
175 pub fn read_chunk(&self, digest
:&[u8; 32]) -> Result
<DataChunk
, Error
> {
177 let (chunk_path
, digest_str
) = self.chunk_path(digest
);
178 let mut file
= std
::fs
::File
::open(&chunk_path
)
179 .map_err(|err
| format_err
!(
180 "store '{}', unable to read chunk '{}' - {}", self.name
, digest_str
, err
))?
;
182 DataChunk
::load(&mut file
, *digest
)
185 pub fn get_chunk_iterator(
187 print_percentage
: bool
,
189 impl Iterator
<Item
= Result
<tools
::fs
::ReadDirEntry
, Error
>> + std
::iter
::FusedIterator
,
193 use nix
::fcntl
::OFlag
;
194 use nix
::sys
::stat
::Mode
;
196 let base_handle
= match Dir
::open(
197 &self.chunk_dir
, OFlag
::O_RDONLY
, Mode
::empty()) {
199 Err(err
) => bail
!("unable to open store '{}' chunk dir {:?} - {}",
200 self.name
, self.chunk_dir
, err
),
203 let mut verbose
= true;
204 let mut last_percentage
= 0;
206 Ok((0..0x10000).filter_map(move |index
| {
207 if print_percentage
{
208 let percentage
= (index
* 100) / 0x10000;
209 if last_percentage
!= percentage
{
210 last_percentage
= percentage
;
211 eprintln
!("percentage done: {}", percentage
);
214 let subdir
: &str = &format
!("{:04x}", index
);
215 match tools
::fs
::read_subdir(base_handle
.as_raw_fd(), subdir
) {
218 eprintln
!("Error iterating through chunks: {}", e
);
223 Ok(iter
) => Some(iter
),
228 // Check that the file name is actually a hash! (64 hex digits)
229 let entry
= match entry
{
230 Err(_
) => return true, // pass errors onwards
231 Ok(ref entry
) => entry
,
233 let bytes
= entry
.file_name().to_bytes();
234 if bytes
.len() != 64 {
238 if !b
.is_ascii_hexdigit() {
246 pub fn oldest_writer(&self) -> Option
<i64> {
247 tools
::ProcessLocker
::oldest_shared_lock(self.locker
.clone())
250 pub fn sweep_unused_chunks(
252 oldest_writer
: Option
<i64>,
253 status
: &mut GarbageCollectionStatus
254 ) -> Result
<(), Error
> {
255 use nix
::sys
::stat
::fstatat
;
257 let now
= unsafe { libc::time(std::ptr::null_mut()) }
;
259 let mut min_atime
= now
- 3600*24; // at least 24h (see mount option relatime)
261 if let Some(stamp
) = oldest_writer
{
262 if stamp
< min_atime
{
267 min_atime
-= 300; // add 5 mins gap for safety
269 for entry
in self.get_chunk_iterator(true)?
{
271 tools
::fail_on_shutdown()?
;
273 let (dirfd
, entry
) = match entry
{
274 Ok(entry
) => (entry
.parent_fd(), entry
),
275 Err(_
) => continue, // ignore errors
278 let file_type
= match entry
.file_type() {
279 Some(file_type
) => file_type
,
280 None
=> bail
!("unsupported file system type on chunk store '{}'", self.name
),
282 if file_type
!= nix
::dir
::Type
::File
{
286 let filename
= entry
.file_name();
288 let lock
= self.mutex
.lock();
290 if let Ok(stat
) = fstatat(dirfd
, filename
, nix
::fcntl
::AtFlags
::AT_SYMLINK_NOFOLLOW
) {
291 let age
= now
- stat
.st_atime
;
292 //println!("FOUND {} {:?}", age/(3600*24), filename);
293 if stat
.st_atime
< min_atime
{
294 println
!("UNLINK {} {:?}", age
/(3600*24), filename
);
295 let res
= unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) }
;
297 let err
= nix
::Error
::last();
299 "unlink chunk {:?} failed on store '{}' - {}",
306 status
.disk_chunks
+= 1;
307 status
.disk_bytes
+= stat
.st_size
as usize;
318 ) -> Result
<(bool
, u64), Error
> {
320 let digest
= chunk
.digest();
322 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
324 let (chunk_path
, digest_str
) = self.chunk_path(digest
);
326 let lock
= self.mutex
.lock();
328 if let Ok(metadata
) = std
::fs
::metadata(&chunk_path
) {
329 if metadata
.is_file() {
330 return Ok((true, metadata
.len()));
332 bail
!("Got unexpected file type on store '{}' for chunk {}", self.name
, digest_str
);
336 let mut tmp_path
= chunk_path
.clone();
337 tmp_path
.set_extension("tmp");
339 let mut file
= std
::fs
::File
::create(&tmp_path
)?
;
341 let raw_data
= chunk
.raw_data();
342 let encoded_size
= raw_data
.len() as u64;
344 file
.write_all(raw_data
)?
;
346 if let Err(err
) = std
::fs
::rename(&tmp_path
, &chunk_path
) {
347 if let Err(_
) = std
::fs
::remove_file(&tmp_path
) { /* ignore */ }
349 "Atomic rename on store '{}' failed for chunk {} - {}",
358 Ok((false, encoded_size
))
361 pub fn chunk_path(&self, digest
:&[u8; 32]) -> (PathBuf
, String
) {
362 let mut chunk_path
= self.chunk_dir
.clone();
363 let prefix
= digest_to_prefix(digest
);
364 chunk_path
.push(&prefix
);
365 let digest_str
= proxmox
::tools
::digest_to_hex(digest
);
366 chunk_path
.push(&digest_str
);
367 (chunk_path
, digest_str
)
370 pub fn relative_path(&self, path
: &Path
) -> PathBuf
{
372 let mut full_path
= self.base
.clone();
373 full_path
.push(path
);
377 pub fn base_path(&self) -> PathBuf
{
381 pub fn try_shared_lock(&self) -> Result
<tools
::ProcessLockSharedGuard
, Error
> {
382 tools
::ProcessLocker
::try_shared_lock(self.locker
.clone())
385 pub fn try_exclusive_lock(&self) -> Result
<tools
::ProcessLockExclusiveGuard
, Error
> {
386 tools
::ProcessLocker
::try_exclusive_lock(self.locker
.clone())
392 fn test_chunk_store1() {
394 let mut path
= std
::fs
::canonicalize(".").unwrap(); // we need absulute path
395 path
.push(".testdir");
397 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }
399 let chunk_store
= ChunkStore
::open("test", &path
);
400 assert
!(chunk_store
.is_err());
402 let chunk_store
= ChunkStore
::create("test", &path
).unwrap();
404 let chunk
= super::DataChunkBuilder
::new(&[0u8, 1u8]).build().unwrap();
406 let (exists
, _
) = chunk_store
.insert_chunk(&chunk
).unwrap();
409 let (exists
, _
) = chunk_store
.insert_chunk(&chunk
).unwrap();
413 let chunk_store
= ChunkStore
::create("test", &path
);
414 assert
!(chunk_store
.is_err());
416 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }