1 use anyhow
::{bail, format_err, Error}
;
3 use std
::path
::{Path, PathBuf}
;
5 use std
::sync
::{Arc, Mutex}
;
6 use std
::os
::unix
::io
::AsRawFd
;
8 use proxmox
::tools
::fs
::{CreateOptions, create_path, create_dir}
;
11 use crate::api2
::types
::GarbageCollectionStatus
;
14 use crate::server
::WorkerTask
;
16 /// File system based chunk store
17 pub struct ChunkStore
{
18 name
: String
, // used for error reporting
19 pub (crate) base
: PathBuf
,
22 locker
: Arc
<Mutex
<tools
::ProcessLocker
>>,
25 // TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
27 pub fn verify_chunk_size(size
: usize) -> Result
<(), Error
> {
29 static SIZES
: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
31 if !SIZES
.contains(&size
) {
32 bail
!("Got unsupported chunk size '{}'", size
);
37 fn digest_to_prefix(digest
: &[u8]) -> PathBuf
{
39 let mut buf
= Vec
::<u8>::with_capacity(2+1+2+1);
41 const HEX_CHARS
: &[u8; 16] = b
"0123456789abcdef";
43 buf
.push(HEX_CHARS
[(digest
[0] as usize) >> 4]);
44 buf
.push(HEX_CHARS
[(digest
[0] as usize) &0xf]);
45 buf
.push(HEX_CHARS
[(digest
[1] as usize) >> 4]);
46 buf
.push(HEX_CHARS
[(digest
[1] as usize) & 0xf]);
49 let path
= unsafe { String::from_utf8_unchecked(buf)}
;
56 fn chunk_dir
<P
: AsRef
<Path
>>(path
: P
) -> PathBuf
{
58 let mut chunk_dir
: PathBuf
= PathBuf
::from(path
.as_ref());
59 chunk_dir
.push(".chunks");
64 pub fn create
<P
>(name
: &str, path
: P
, uid
: nix
::unistd
::Uid
, gid
: nix
::unistd
::Gid
) -> Result
<Self, Error
>
69 let base
: PathBuf
= path
.into();
71 if !base
.is_absolute() {
72 bail
!("expected absolute path - got {:?}", base
);
75 let chunk_dir
= Self::chunk_dir(&base
);
77 let options
= CreateOptions
::new()
81 let default_options
= CreateOptions
::new();
83 match create_path(&base
, Some(default_options
.clone()), Some(options
.clone())) {
84 Err(err
) => bail
!("unable to create chunk store '{}' at {:?} - {}", name
, base
, err
),
85 Ok(res
) => if ! res { nix::unistd::chown(&base, Some(uid), Some(gid))? }
,
88 if let Err(err
) = create_dir(&chunk_dir
, options
.clone()) {
89 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, chunk_dir
, err
);
92 // create lock file with correct owner/group
93 let lockfile_path
= Self::lockfile_path(&base
);
94 proxmox
::tools
::fs
::replace_file(lockfile_path
, b
"", options
.clone())?
;
96 // create 64*1024 subdirs
97 let mut last_percentage
= 0;
100 let mut l1path
= chunk_dir
.clone();
101 l1path
.push(format
!("{:04x}", i
));
102 if let Err(err
) = create_dir(&l1path
, options
.clone()) {
103 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, l1path
, err
);
105 let percentage
= (i
*100)/(64*1024);
106 if percentage
!= last_percentage
{
107 eprintln
!("Percentage done: {}", percentage
);
108 last_percentage
= percentage
;
113 Self::open(name
, base
)
116 fn lockfile_path
<P
: Into
<PathBuf
>>(base
: P
) -> PathBuf
{
117 let base
: PathBuf
= base
.into();
119 let mut lockfile_path
= base
.clone();
120 lockfile_path
.push(".lock");
125 pub fn open
<P
: Into
<PathBuf
>>(name
: &str, base
: P
) -> Result
<Self, Error
> {
127 let base
: PathBuf
= base
.into();
129 if !base
.is_absolute() {
130 bail
!("expected absolute path - got {:?}", base
);
133 let chunk_dir
= Self::chunk_dir(&base
);
135 if let Err(err
) = std
::fs
::metadata(&chunk_dir
) {
136 bail
!("unable to open chunk store '{}' at {:?} - {}", name
, chunk_dir
, err
);
139 let lockfile_path
= Self::lockfile_path(&base
);
141 let locker
= tools
::ProcessLocker
::new(&lockfile_path
)?
;
144 name
: name
.to_owned(),
148 mutex
: Mutex
::new(false)
152 pub fn touch_chunk(&self, digest
: &[u8; 32]) -> Result
<(), Error
> {
153 self.cond_touch_chunk(digest
, true)?
;
157 pub fn cond_touch_chunk(&self, digest
: &[u8; 32], fail_if_not_exist
: bool
) -> Result
<bool
, Error
> {
159 let (chunk_path
, _digest_str
) = self.chunk_path(digest
);
161 const UTIME_NOW
: i64 = (1 << 30) - 1;
162 const UTIME_OMIT
: i64 = (1 << 30) - 2;
164 let times
: [libc
::timespec
; 2] = [
165 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_NOW }
,
166 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT }
171 let res
= chunk_path
.with_nix_path(|cstr
| unsafe {
172 let tmp
= libc
::utimensat(-1, cstr
.as_ptr(), ×
[0], libc
::AT_SYMLINK_NOFOLLOW
);
173 nix
::errno
::Errno
::result(tmp
)
176 if let Err(err
) = res
{
177 if !fail_if_not_exist
&& err
.as_errno() == Some(nix
::errno
::Errno
::ENOENT
) {
181 bail
!("update atime failed for chunk {:?} - {}", chunk_path
, err
);
187 pub fn get_chunk_iterator(
190 impl Iterator
<Item
= (Result
<tools
::fs
::ReadDirEntry
, Error
>, usize)> + std
::iter
::FusedIterator
,
194 use nix
::fcntl
::OFlag
;
195 use nix
::sys
::stat
::Mode
;
197 let base_handle
= Dir
::open(&self.chunk_dir
, OFlag
::O_RDONLY
, Mode
::empty())
200 "unable to open store '{}' chunk dir {:?} - {}",
207 let mut done
= false;
208 let mut inner
: Option
<tools
::fs
::ReadDir
> = None
;
210 let mut percentage
= 0;
211 Ok(std
::iter
::from_fn(move || {
217 if let Some(ref mut inner
) = inner
{
220 // skip files if they're not a hash
221 let bytes
= entry
.file_name().to_bytes();
222 if bytes
.len() != 64 {
225 if !bytes
.iter().all(u8::is_ascii_hexdigit
) {
228 return Some((Ok(entry
), percentage
));
231 // stop after first error
233 // and pass the error through:
234 return Some((Err(err
), percentage
));
236 None
=> (), // open next directory
247 let subdir
: &str = &format
!("{:04x}", at
);
248 percentage
= (at
* 100) / 0x10000;
250 match tools
::fs
::read_subdir(base_handle
.as_raw_fd(), subdir
) {
256 Err(ref err
) if err
.as_errno() == Some(nix
::errno
::Errno
::ENOENT
) => {
257 // non-existing directories are okay, just keep going:
261 // other errors are fatal, so end our iteration
263 // and pass the error through:
264 return Some((Err(format_err
!("unable to read subdir '{}' - {}", subdir
, err
)), percentage
));
271 pub fn oldest_writer(&self) -> Option
<i64> {
272 tools
::ProcessLocker
::oldest_shared_lock(self.locker
.clone())
275 pub fn sweep_unused_chunks(
278 status
: &mut GarbageCollectionStatus
,
280 ) -> Result
<(), Error
> {
281 use nix
::sys
::stat
::fstatat
;
283 let now
= unsafe { libc::time(std::ptr::null_mut()) }
;
285 let mut min_atime
= now
- 3600*24; // at least 24h (see mount option relatime)
287 if oldest_writer
< min_atime
{
288 min_atime
= oldest_writer
;
291 min_atime
-= 300; // add 5 mins gap for safety
293 let mut last_percentage
= 0;
294 let mut chunk_count
= 0;
296 for (entry
, percentage
) in self.get_chunk_iterator()?
{
297 if last_percentage
!= percentage
{
298 last_percentage
= percentage
;
299 worker
.log(format
!("percentage done: {}, chunk count: {}", percentage
, chunk_count
));
302 worker
.fail_on_abort()?
;
303 tools
::fail_on_shutdown()?
;
305 let (dirfd
, entry
) = match entry
{
306 Ok(entry
) => (entry
.parent_fd(), entry
),
307 Err(err
) => bail
!("chunk iterator on chunk store '{}' failed - {}", self.name
, err
),
310 let file_type
= match entry
.file_type() {
311 Some(file_type
) => file_type
,
312 None
=> bail
!("unsupported file system type on chunk store '{}'", self.name
),
314 if file_type
!= nix
::dir
::Type
::File
{
320 let filename
= entry
.file_name();
322 let lock
= self.mutex
.lock();
324 if let Ok(stat
) = fstatat(dirfd
, filename
, nix
::fcntl
::AtFlags
::AT_SYMLINK_NOFOLLOW
) {
325 if stat
.st_atime
< min_atime
{
326 //let age = now - stat.st_atime;
327 //println!("UNLINK {} {:?}", age/(3600*24), filename);
328 let res
= unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) }
;
330 let err
= nix
::Error
::last();
332 "unlink chunk {:?} failed on store '{}' - {}",
338 status
.removed_chunks
+= 1;
339 status
.removed_bytes
+= stat
.st_size
as u64;
341 if stat
.st_atime
< oldest_writer
{
342 status
.pending_chunks
+= 1;
343 status
.pending_bytes
+= stat
.st_size
as u64;
345 status
.disk_chunks
+= 1;
346 status
.disk_bytes
+= stat
.st_size
as u64;
360 ) -> Result
<(bool
, u64), Error
> {
362 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
364 let (chunk_path
, digest_str
) = self.chunk_path(digest
);
366 let lock
= self.mutex
.lock();
368 if let Ok(metadata
) = std
::fs
::metadata(&chunk_path
) {
369 if metadata
.is_file() {
370 return Ok((true, metadata
.len()));
372 bail
!("Got unexpected file type on store '{}' for chunk {}", self.name
, digest_str
);
376 let mut tmp_path
= chunk_path
.clone();
377 tmp_path
.set_extension("tmp");
379 let mut file
= std
::fs
::File
::create(&tmp_path
)?
;
381 let raw_data
= chunk
.raw_data();
382 let encoded_size
= raw_data
.len() as u64;
384 file
.write_all(raw_data
)?
;
386 if let Err(err
) = std
::fs
::rename(&tmp_path
, &chunk_path
) {
387 if let Err(_
) = std
::fs
::remove_file(&tmp_path
) { /* ignore */ }
389 "Atomic rename on store '{}' failed for chunk {} - {}",
398 Ok((false, encoded_size
))
401 pub fn chunk_path(&self, digest
:&[u8; 32]) -> (PathBuf
, String
) {
402 let mut chunk_path
= self.chunk_dir
.clone();
403 let prefix
= digest_to_prefix(digest
);
404 chunk_path
.push(&prefix
);
405 let digest_str
= proxmox
::tools
::digest_to_hex(digest
);
406 chunk_path
.push(&digest_str
);
407 (chunk_path
, digest_str
)
410 pub fn relative_path(&self, path
: &Path
) -> PathBuf
{
412 let mut full_path
= self.base
.clone();
413 full_path
.push(path
);
417 pub fn name(&self) -> &str {
421 pub fn base_path(&self) -> PathBuf
{
425 pub fn try_shared_lock(&self) -> Result
<tools
::ProcessLockSharedGuard
, Error
> {
426 tools
::ProcessLocker
::try_shared_lock(self.locker
.clone())
429 pub fn try_exclusive_lock(&self) -> Result
<tools
::ProcessLockExclusiveGuard
, Error
> {
430 tools
::ProcessLocker
::try_exclusive_lock(self.locker
.clone())
436 fn test_chunk_store1() {
438 let mut path
= std
::fs
::canonicalize(".").unwrap(); // we need absulute path
439 path
.push(".testdir");
441 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }
443 let chunk_store
= ChunkStore
::open("test", &path
);
444 assert
!(chunk_store
.is_err());
446 let user
= nix
::unistd
::User
::from_uid(nix
::unistd
::Uid
::current()).unwrap().unwrap();
447 let chunk_store
= ChunkStore
::create("test", &path
, user
.uid
, user
.gid
).unwrap();
449 let (chunk
, digest
) = super::DataChunkBuilder
::new(&[0u8, 1u8]).build().unwrap();
451 let (exists
, _
) = chunk_store
.insert_chunk(&chunk
, &digest
).unwrap();
454 let (exists
, _
) = chunk_store
.insert_chunk(&chunk
, &digest
).unwrap();
458 let chunk_store
= ChunkStore
::create("test", &path
, user
.uid
, user
.gid
);
459 assert
!(chunk_store
.is_err());
461 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }