3 use std
::path
::{Path, PathBuf}
;
5 use std
::sync
::{Arc, Mutex}
;
6 use std
::os
::unix
::io
::AsRawFd
;
9 use proxmox
::tools
::fs
::{CreateOptions, create_path, create_dir}
;
13 use crate::server
::WorkerTask
;
15 #[derive(Clone, Serialize)]
16 pub struct GarbageCollectionStatus
{
17 pub upid
: Option
<String
>,
18 pub index_file_count
: usize,
19 pub index_data_bytes
: u64,
21 pub disk_chunks
: usize,
22 pub removed_bytes
: u64,
23 pub removed_chunks
: usize,
26 impl Default
for GarbageCollectionStatus
{
27 fn default() -> Self {
28 GarbageCollectionStatus
{
40 /// File system based chunk store
41 pub struct ChunkStore
{
42 name
: String
, // used for error reporting
43 pub (crate) base
: PathBuf
,
46 locker
: Arc
<Mutex
<tools
::ProcessLocker
>>,
49 // TODO: what about sysctl setting vm.vfs_cache_pressure (0 - 100) ?
51 pub fn verify_chunk_size(size
: usize) -> Result
<(), Error
> {
53 static SIZES
: [usize; 7] = [64*1024, 128*1024, 256*1024, 512*1024, 1024*1024, 2048*1024, 4096*1024];
55 if !SIZES
.contains(&size
) {
56 bail
!("Got unsupported chunk size '{}'", size
);
61 fn digest_to_prefix(digest
: &[u8]) -> PathBuf
{
63 let mut buf
= Vec
::<u8>::with_capacity(2+1+2+1);
65 const HEX_CHARS
: &[u8; 16] = b
"0123456789abcdef";
67 buf
.push(HEX_CHARS
[(digest
[0] as usize) >> 4]);
68 buf
.push(HEX_CHARS
[(digest
[0] as usize) &0xf]);
69 buf
.push(HEX_CHARS
[(digest
[1] as usize) >> 4]);
70 buf
.push(HEX_CHARS
[(digest
[1] as usize) & 0xf]);
73 let path
= unsafe { String::from_utf8_unchecked(buf)}
;
80 fn chunk_dir
<P
: AsRef
<Path
>>(path
: P
) -> PathBuf
{
82 let mut chunk_dir
: PathBuf
= PathBuf
::from(path
.as_ref());
83 chunk_dir
.push(".chunks");
88 pub fn create
<P
>(name
: &str, path
: P
, uid
: nix
::unistd
::Uid
, gid
: nix
::unistd
::Gid
) -> Result
<Self, Error
>
93 let base
: PathBuf
= path
.into();
95 if !base
.is_absolute() {
96 bail
!("expected absolute path - got {:?}", base
);
99 let chunk_dir
= Self::chunk_dir(&base
);
101 let options
= CreateOptions
::new()
105 let default_options
= CreateOptions
::new();
107 if let Err(err
) = create_path(&base
, Some(default_options
.clone()), Some(options
.clone())) {
108 bail
!("unable to create chunk store '{}' at {:?} - {}", name
, base
, err
);
111 if let Err(err
) = create_dir(&chunk_dir
, options
.clone()) {
112 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, chunk_dir
, err
);
115 // create lock file with correct owner/group
116 let lockfile_path
= Self::lockfile_path(&base
);
117 proxmox
::tools
::fs
::replace_file(lockfile_path
, b
"", options
.clone())?
;
119 // create 64*1024 subdirs
120 let mut last_percentage
= 0;
122 for i
in 0..64*1024 {
123 let mut l1path
= chunk_dir
.clone();
124 l1path
.push(format
!("{:04x}", i
));
125 if let Err(err
) = create_dir(&l1path
, options
.clone()) {
126 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, l1path
, err
);
128 let percentage
= (i
*100)/(64*1024);
129 if percentage
!= last_percentage
{
130 eprintln
!("Percentage done: {}", percentage
);
131 last_percentage
= percentage
;
136 Self::open(name
, base
)
139 fn lockfile_path
<P
: Into
<PathBuf
>>(base
: P
) -> PathBuf
{
140 let base
: PathBuf
= base
.into();
142 let mut lockfile_path
= base
.clone();
143 lockfile_path
.push(".lock");
148 pub fn open
<P
: Into
<PathBuf
>>(name
: &str, base
: P
) -> Result
<Self, Error
> {
150 let base
: PathBuf
= base
.into();
152 if !base
.is_absolute() {
153 bail
!("expected absolute path - got {:?}", base
);
156 let chunk_dir
= Self::chunk_dir(&base
);
158 if let Err(err
) = std
::fs
::metadata(&chunk_dir
) {
159 bail
!("unable to open chunk store '{}' at {:?} - {}", name
, chunk_dir
, err
);
162 let lockfile_path
= Self::lockfile_path(&base
);
164 let locker
= tools
::ProcessLocker
::new(&lockfile_path
)?
;
167 name
: name
.to_owned(),
171 mutex
: Mutex
::new(false)
175 pub fn touch_chunk(&self, digest
: &[u8; 32]) -> Result
<(), Error
> {
176 self.cond_touch_chunk(digest
, true)?
;
180 pub fn cond_touch_chunk(&self, digest
: &[u8; 32], fail_if_not_exist
: bool
) -> Result
<bool
, Error
> {
182 let (chunk_path
, _digest_str
) = self.chunk_path(digest
);
184 const UTIME_NOW
: i64 = ((1 << 30) - 1);
185 const UTIME_OMIT
: i64 = ((1 << 30) - 2);
187 let times
: [libc
::timespec
; 2] = [
188 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_NOW }
,
189 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT }
194 let res
= chunk_path
.with_nix_path(|cstr
| unsafe {
195 let tmp
= libc
::utimensat(-1, cstr
.as_ptr(), ×
[0], libc
::AT_SYMLINK_NOFOLLOW
);
196 nix
::errno
::Errno
::result(tmp
)
199 if let Err(err
) = res
{
200 if !fail_if_not_exist
&& err
.as_errno() == Some(nix
::errno
::Errno
::ENOENT
) {
204 bail
!("updata atime failed for chunk {:?} - {}", chunk_path
, err
);
210 pub fn read_chunk(&self, digest
: &[u8; 32]) -> Result
<DataBlob
, Error
> {
212 let (chunk_path
, digest_str
) = self.chunk_path(digest
);
213 let mut file
= std
::fs
::File
::open(&chunk_path
)
216 "store '{}', unable to read chunk '{}' - {}",
223 DataBlob
::load(&mut file
)
226 pub fn get_chunk_iterator(
229 impl Iterator
<Item
= (Result
<tools
::fs
::ReadDirEntry
, Error
>, usize)> + std
::iter
::FusedIterator
,
233 use nix
::fcntl
::OFlag
;
234 use nix
::sys
::stat
::Mode
;
236 let base_handle
= Dir
::open(&self.chunk_dir
, OFlag
::O_RDONLY
, Mode
::empty())
239 "unable to open store '{}' chunk dir {:?} - {}",
246 let mut done
= false;
247 let mut inner
: Option
<tools
::fs
::ReadDir
> = None
;
249 let mut percentage
= 0;
250 Ok(std
::iter
::from_fn(move || {
256 if let Some(ref mut inner
) = inner
{
259 // skip files if they're not a hash
260 let bytes
= entry
.file_name().to_bytes();
261 if bytes
.len() != 64 {
264 if !bytes
.iter().all(u8::is_ascii_hexdigit
) {
267 return Some((Ok(entry
), percentage
));
270 // stop after first error
272 // and pass the error through:
273 return Some((Err(err
), percentage
));
275 None
=> (), // open next directory
286 let subdir
: &str = &format
!("{:04x}", at
);
287 percentage
= (at
* 100) / 0x10000;
289 match tools
::fs
::read_subdir(base_handle
.as_raw_fd(), subdir
) {
295 Err(ref err
) if err
.as_errno() == Some(nix
::errno
::Errno
::ENOENT
) => {
296 // non-existing directories are okay, just keep going:
300 // other errors are fatal, so end our iteration
302 // and pass the error through:
303 return Some((Err(format_err
!("unable to read subdir '{}' - {}", subdir
, err
)), percentage
));
310 pub fn oldest_writer(&self) -> Option
<i64> {
311 tools
::ProcessLocker
::oldest_shared_lock(self.locker
.clone())
314 pub fn sweep_unused_chunks(
316 oldest_writer
: Option
<i64>,
317 status
: &mut GarbageCollectionStatus
,
318 worker
: Arc
<WorkerTask
>,
319 ) -> Result
<(), Error
> {
320 use nix
::sys
::stat
::fstatat
;
322 let now
= unsafe { libc::time(std::ptr::null_mut()) }
;
324 let mut min_atime
= now
- 3600*24; // at least 24h (see mount option relatime)
326 if let Some(stamp
) = oldest_writer
{
327 if stamp
< min_atime
{
332 min_atime
-= 300; // add 5 mins gap for safety
334 let mut last_percentage
= 0;
335 let mut chunk_count
= 0;
337 for (entry
, percentage
) in self.get_chunk_iterator()?
{
338 if last_percentage
!= percentage
{
339 last_percentage
= percentage
;
340 worker
.log(format
!("percentage done: {}, chunk count: {}", percentage
, chunk_count
));
343 tools
::fail_on_shutdown()?
;
345 let (dirfd
, entry
) = match entry
{
346 Ok(entry
) => (entry
.parent_fd(), entry
),
347 Err(err
) => bail
!("chunk iterator on chunk store '{}' failed - {}", self.name
, err
),
350 let file_type
= match entry
.file_type() {
351 Some(file_type
) => file_type
,
352 None
=> bail
!("unsupported file system type on chunk store '{}'", self.name
),
354 if file_type
!= nix
::dir
::Type
::File
{
360 let filename
= entry
.file_name();
362 let lock
= self.mutex
.lock();
364 if let Ok(stat
) = fstatat(dirfd
, filename
, nix
::fcntl
::AtFlags
::AT_SYMLINK_NOFOLLOW
) {
365 let age
= now
- stat
.st_atime
;
366 //println!("FOUND {} {:?}", age/(3600*24), filename);
367 if stat
.st_atime
< min_atime
{
368 println
!("UNLINK {} {:?}", age
/(3600*24), filename
);
369 let res
= unsafe { libc::unlinkat(dirfd, filename.as_ptr(), 0) }
;
371 let err
= nix
::Error
::last();
373 "unlink chunk {:?} failed on store '{}' - {}",
379 status
.removed_chunks
+= 1;
380 status
.removed_bytes
+= stat
.st_size
as u64;
382 status
.disk_chunks
+= 1;
383 status
.disk_bytes
+= stat
.st_size
as u64;
396 ) -> Result
<(bool
, u64), Error
> {
398 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
400 let (chunk_path
, digest_str
) = self.chunk_path(digest
);
402 let lock
= self.mutex
.lock();
404 if let Ok(metadata
) = std
::fs
::metadata(&chunk_path
) {
405 if metadata
.is_file() {
406 return Ok((true, metadata
.len()));
408 bail
!("Got unexpected file type on store '{}' for chunk {}", self.name
, digest_str
);
412 let mut tmp_path
= chunk_path
.clone();
413 tmp_path
.set_extension("tmp");
415 let mut file
= std
::fs
::File
::create(&tmp_path
)?
;
417 let raw_data
= chunk
.raw_data();
418 let encoded_size
= raw_data
.len() as u64;
420 file
.write_all(raw_data
)?
;
422 if let Err(err
) = std
::fs
::rename(&tmp_path
, &chunk_path
) {
423 if let Err(_
) = std
::fs
::remove_file(&tmp_path
) { /* ignore */ }
425 "Atomic rename on store '{}' failed for chunk {} - {}",
434 Ok((false, encoded_size
))
437 pub fn chunk_path(&self, digest
:&[u8; 32]) -> (PathBuf
, String
) {
438 let mut chunk_path
= self.chunk_dir
.clone();
439 let prefix
= digest_to_prefix(digest
);
440 chunk_path
.push(&prefix
);
441 let digest_str
= proxmox
::tools
::digest_to_hex(digest
);
442 chunk_path
.push(&digest_str
);
443 (chunk_path
, digest_str
)
446 pub fn relative_path(&self, path
: &Path
) -> PathBuf
{
448 let mut full_path
= self.base
.clone();
449 full_path
.push(path
);
453 pub fn base_path(&self) -> PathBuf
{
457 pub fn try_shared_lock(&self) -> Result
<tools
::ProcessLockSharedGuard
, Error
> {
458 tools
::ProcessLocker
::try_shared_lock(self.locker
.clone())
461 pub fn try_exclusive_lock(&self) -> Result
<tools
::ProcessLockExclusiveGuard
, Error
> {
462 tools
::ProcessLocker
::try_exclusive_lock(self.locker
.clone())
468 fn test_chunk_store1() {
470 let mut path
= std
::fs
::canonicalize(".").unwrap(); // we need absulute path
471 path
.push(".testdir");
473 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }
475 let chunk_store
= ChunkStore
::open("test", &path
);
476 assert
!(chunk_store
.is_err());
478 let user
= nix
::unistd
::User
::from_uid(nix
::unistd
::Uid
::current()).unwrap().unwrap();
479 let chunk_store
= ChunkStore
::create("test", &path
, user
.uid
, user
.gid
).unwrap();
481 let (chunk
, digest
) = super::DataChunkBuilder
::new(&[0u8, 1u8]).build().unwrap();
483 let (exists
, _
) = chunk_store
.insert_chunk(&chunk
, &digest
).unwrap();
486 let (exists
, _
) = chunk_store
.insert_chunk(&chunk
, &digest
).unwrap();
490 let chunk_store
= ChunkStore
::create("test", &path
, user
.uid
, user
.gid
);
491 assert
!(chunk_store
.is_err());
493 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }