2 use std
::os
::unix
::io
::AsRawFd
;
3 use std
::path
::{Path, PathBuf}
;
4 use std
::sync
::{Arc, Mutex}
;
6 use anyhow
::{bail, format_err, Error}
;
8 use proxmox
::tools
::fs
::{CreateOptions, create_path, create_dir}
;
10 use pbs_api_types
::GarbageCollectionStatus
;
11 use pbs_tools
::process_locker
::{self, ProcessLocker}
;
12 use pbs_tools
::{task_log, task::WorkerTaskContext}
;
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
<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 base(&self) -> &Path
{
68 pub fn create
<P
>(name
: &str, path
: P
, uid
: nix
::unistd
::Uid
, gid
: nix
::unistd
::Gid
, worker
: Option
<&dyn WorkerTaskContext
>) -> Result
<Self, Error
>
73 let base
: PathBuf
= path
.into();
75 if !base
.is_absolute() {
76 bail
!("expected absolute path - got {:?}", base
);
79 let chunk_dir
= Self::chunk_dir(&base
);
81 let options
= CreateOptions
::new()
85 let default_options
= CreateOptions
::new();
87 match create_path(&base
, Some(default_options
), Some(options
.clone())) {
88 Err(err
) => bail
!("unable to create chunk store '{}' at {:?} - {}", name
, base
, err
),
89 Ok(res
) => if ! res { nix::unistd::chown(&base, Some(uid), Some(gid))? }
,
92 if let Err(err
) = create_dir(&chunk_dir
, options
.clone()) {
93 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, chunk_dir
, err
);
96 // create lock file with correct owner/group
97 let lockfile_path
= Self::lockfile_path(&base
);
98 proxmox
::tools
::fs
::replace_file(lockfile_path
, b
"", options
.clone())?
;
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
) = create_dir(&l1path
, options
.clone()) {
107 bail
!("unable to create chunk store '{}' subdir {:?} - {}", name
, l1path
, err
);
109 let percentage
= (i
*100)/(64*1024);
110 if percentage
!= last_percentage
{
111 if let Some(worker
) = worker
{
112 task_log
!(worker
, "Chunkstore create: {}%", percentage
)
114 last_percentage
= percentage
;
118 Self::open(name
, base
)
121 fn lockfile_path
<P
: Into
<PathBuf
>>(base
: P
) -> PathBuf
{
122 let mut lockfile_path
: PathBuf
= base
.into();
124 lockfile_path
.push(".lock");
129 pub fn open
<P
: Into
<PathBuf
>>(name
: &str, base
: P
) -> Result
<Self, Error
> {
131 let base
: PathBuf
= base
.into();
133 if !base
.is_absolute() {
134 bail
!("expected absolute path - got {:?}", base
);
137 let chunk_dir
= Self::chunk_dir(&base
);
139 if let Err(err
) = std
::fs
::metadata(&chunk_dir
) {
140 bail
!("unable to open chunk store '{}' at {:?} - {}", name
, chunk_dir
, err
);
143 let lockfile_path
= Self::lockfile_path(&base
);
145 let locker
= ProcessLocker
::new(&lockfile_path
)?
;
148 name
: name
.to_owned(),
152 mutex
: Mutex
::new(())
156 pub fn touch_chunk(&self, digest
: &[u8; 32]) -> Result
<(), Error
> {
157 self.cond_touch_chunk(digest
, true)?
;
161 pub fn cond_touch_chunk(&self, digest
: &[u8; 32], fail_if_not_exist
: bool
) -> Result
<bool
, Error
> {
162 let (chunk_path
, _digest_str
) = self.chunk_path(digest
);
163 self.cond_touch_path(&chunk_path
, fail_if_not_exist
)
166 pub fn cond_touch_path(&self, path
: &Path
, fail_if_not_exist
: bool
) -> Result
<bool
, Error
> {
167 const UTIME_NOW
: i64 = (1 << 30) - 1;
168 const UTIME_OMIT
: i64 = (1 << 30) - 2;
170 let times
: [libc
::timespec
; 2] = [
171 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_NOW }
,
172 libc
::timespec { tv_sec: 0, tv_nsec: UTIME_OMIT }
177 let res
= path
.with_nix_path(|cstr
| unsafe {
178 let tmp
= libc
::utimensat(-1, cstr
.as_ptr(), ×
[0], libc
::AT_SYMLINK_NOFOLLOW
);
179 nix
::errno
::Errno
::result(tmp
)
182 if let Err(err
) = res
{
183 if !fail_if_not_exist
&& err
.as_errno() == Some(nix
::errno
::Errno
::ENOENT
) {
187 bail
!("update atime failed for chunk/file {:?} - {}", path
, err
);
193 pub fn get_chunk_iterator(
196 impl Iterator
<Item
= (Result
<pbs_tools
::fs
::ReadDirEntry
, Error
>, usize, bool
)> + std
::iter
::FusedIterator
,
200 use nix
::fcntl
::OFlag
;
201 use nix
::sys
::stat
::Mode
;
203 let base_handle
= Dir
::open(&self.chunk_dir
, OFlag
::O_RDONLY
, Mode
::empty())
206 "unable to open store '{}' chunk dir {:?} - {}",
213 let mut done
= false;
214 let mut inner
: Option
<pbs_tools
::fs
::ReadDir
> = None
;
216 let mut percentage
= 0;
217 Ok(std
::iter
::from_fn(move || {
223 if let Some(ref mut inner
) = inner
{
226 // skip files if they're not a hash
227 let bytes
= entry
.file_name().to_bytes();
228 if bytes
.len() != 64 && bytes
.len() != 64 + ".0.bad".len() {
231 if !bytes
.iter().take(64).all(u8::is_ascii_hexdigit
) {
235 let bad
= bytes
.ends_with(b
".bad");
236 return Some((Ok(entry
), percentage
, bad
));
239 // stop after first error
241 // and pass the error through:
242 return Some((Err(err
), percentage
, false));
244 None
=> (), // open next directory
255 let subdir
: &str = &format
!("{:04x}", at
);
256 percentage
= (at
* 100) / 0x10000;
258 match pbs_tools
::fs
::read_subdir(base_handle
.as_raw_fd(), subdir
) {
264 Err(ref err
) if err
.as_errno() == Some(nix
::errno
::Errno
::ENOENT
) => {
265 // non-existing directories are okay, just keep going:
269 // other errors are fatal, so end our iteration
271 // and pass the error through:
272 return Some((Err(format_err
!("unable to read subdir '{}' - {}", subdir
, err
)), percentage
, false));
279 pub fn oldest_writer(&self) -> Option
<i64> {
280 ProcessLocker
::oldest_shared_lock(self.locker
.clone())
283 pub fn sweep_unused_chunks(
286 phase1_start_time
: i64,
287 status
: &mut GarbageCollectionStatus
,
288 worker
: &dyn WorkerTaskContext
,
289 ) -> Result
<(), Error
> {
290 use nix
::sys
::stat
::fstatat
;
291 use nix
::unistd
::{unlinkat, UnlinkatFlags}
;
293 let mut min_atime
= phase1_start_time
- 3600*24; // at least 24h (see mount option relatime)
295 if oldest_writer
< min_atime
{
296 min_atime
= oldest_writer
;
299 min_atime
-= 300; // add 5 mins gap for safety
301 let mut last_percentage
= 0;
302 let mut chunk_count
= 0;
304 for (entry
, percentage
, bad
) in self.get_chunk_iterator()?
{
305 if last_percentage
!= percentage
{
306 last_percentage
= percentage
;
309 "processed {}% ({} chunks)",
315 worker
.check_abort()?
;
316 worker
.fail_on_shutdown()?
;
318 let (dirfd
, entry
) = match entry
{
319 Ok(entry
) => (entry
.parent_fd(), entry
),
320 Err(err
) => bail
!("chunk iterator on chunk store '{}' failed - {}", self.name
, err
),
323 let file_type
= match entry
.file_type() {
324 Some(file_type
) => file_type
,
325 None
=> bail
!("unsupported file system type on chunk store '{}'", self.name
),
327 if file_type
!= nix
::dir
::Type
::File
{
333 let filename
= entry
.file_name();
335 let lock
= self.mutex
.lock();
337 if let Ok(stat
) = fstatat(dirfd
, filename
, nix
::fcntl
::AtFlags
::AT_SYMLINK_NOFOLLOW
) {
338 if stat
.st_atime
< min_atime
{
339 //let age = now - stat.st_atime;
340 //println!("UNLINK {} {:?}", age/(3600*24), filename);
341 if let Err(err
) = unlinkat(Some(dirfd
), filename
, UnlinkatFlags
::NoRemoveDir
) {
343 status
.still_bad
+= 1;
346 "unlinking chunk {:?} failed on store '{}' - {}",
353 status
.removed_bad
+= 1;
355 status
.removed_chunks
+= 1;
357 status
.removed_bytes
+= stat
.st_size
as u64;
358 } else if stat
.st_atime
< oldest_writer
{
360 status
.still_bad
+= 1;
362 status
.pending_chunks
+= 1;
364 status
.pending_bytes
+= stat
.st_size
as u64;
367 status
.disk_chunks
+= 1;
369 status
.disk_bytes
+= stat
.st_size
as u64;
382 ) -> Result
<(bool
, u64), Error
> {
384 //println!("DIGEST {}", proxmox::tools::digest_to_hex(digest));
386 let (chunk_path
, digest_str
) = self.chunk_path(digest
);
388 let lock
= self.mutex
.lock();
390 if let Ok(metadata
) = std
::fs
::metadata(&chunk_path
) {
391 if metadata
.is_file() {
392 self.touch_chunk(digest
)?
;
393 return Ok((true, metadata
.len()));
395 bail
!("Got unexpected file type on store '{}' for chunk {}", self.name
, digest_str
);
399 let mut tmp_path
= chunk_path
.clone();
400 tmp_path
.set_extension("tmp");
402 let mut file
= std
::fs
::File
::create(&tmp_path
).map_err(|err
| {
404 "creating temporary chunk on store '{}' failed for {} - {}",
411 let raw_data
= chunk
.raw_data();
412 let encoded_size
= raw_data
.len() as u64;
414 file
.write_all(raw_data
).map_err(|err
| {
416 "writing temporary chunk on store '{}' failed for {} - {}",
423 if let Err(err
) = std
::fs
::rename(&tmp_path
, &chunk_path
) {
424 if std
::fs
::remove_file(&tmp_path
).is_err() { /* ignore */ }
426 "Atomic rename on store '{}' failed for chunk {} - {}",
435 Ok((false, encoded_size
))
438 pub fn chunk_path(&self, digest
:&[u8; 32]) -> (PathBuf
, String
) {
439 let mut chunk_path
= self.chunk_dir
.clone();
440 let prefix
= digest_to_prefix(digest
);
441 chunk_path
.push(&prefix
);
442 let digest_str
= proxmox
::tools
::digest_to_hex(digest
);
443 chunk_path
.push(&digest_str
);
444 (chunk_path
, digest_str
)
447 pub fn relative_path(&self, path
: &Path
) -> PathBuf
{
449 let mut full_path
= self.base
.clone();
450 full_path
.push(path
);
454 pub fn name(&self) -> &str {
458 pub fn base_path(&self) -> PathBuf
{
462 pub fn try_shared_lock(&self) -> Result
<process_locker
::ProcessLockSharedGuard
, Error
> {
463 ProcessLocker
::try_shared_lock(self.locker
.clone())
466 pub fn try_exclusive_lock(&self) -> Result
<process_locker
::ProcessLockExclusiveGuard
, Error
> {
467 ProcessLocker
::try_exclusive_lock(self.locker
.clone())
473 fn test_chunk_store1() {
475 let mut path
= std
::fs
::canonicalize(".").unwrap(); // we need absolute path
476 path
.push(".testdir");
478 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }
480 let chunk_store
= ChunkStore
::open("test", &path
);
481 assert
!(chunk_store
.is_err());
483 let user
= nix
::unistd
::User
::from_uid(nix
::unistd
::Uid
::current()).unwrap().unwrap();
484 let chunk_store
= ChunkStore
::create("test", &path
, user
.uid
, user
.gid
, None
).unwrap();
486 let (chunk
, digest
) = crate::data_blob
::DataChunkBuilder
::new(&[0u8, 1u8]).build().unwrap();
488 let (exists
, _
) = chunk_store
.insert_chunk(&chunk
, &digest
).unwrap();
491 let (exists
, _
) = chunk_store
.insert_chunk(&chunk
, &digest
).unwrap();
495 let chunk_store
= ChunkStore
::create("test", &path
, user
.uid
, user
.gid
, None
);
496 assert
!(chunk_store
.is_err());
498 if let Err(_e
) = std
::fs
::remove_dir_all(".testdir") { /* ignore */ }