5 use super::chunk_stat
::*;
6 use super::chunk_store
::*;
9 use std
::io
::{Read, Write}
;
11 use std
::path
::{Path, PathBuf}
;
12 use std
::os
::unix
::io
::AsRawFd
;
14 use chrono
::{Local, TimeZone}
;
17 /// Header format definition for fixed index files (`.fidx`)
19 pub struct FixedIndexHeader
{
23 /// Sha256 over the index ``SHA256(digest1||digest2||...)``
24 pub index_csum
: [u8; 32],
27 reserved
: [u8; 4016], // overall size is one page (4096 bytes)
30 // split image into fixed size chunks
32 pub struct FixedIndexReader
{
33 store
: Arc
<ChunkStore
>,
36 pub chunk_size
: usize,
42 pub index_csum
: [u8; 32],
45 // `index` is mmap()ed which cannot be thread-local so should be sendable
46 unsafe impl Send
for FixedIndexReader {}
48 impl Drop
for FixedIndexReader
{
51 if let Err(err
) = self.unmap() {
52 eprintln
!("Unable to unmap file {:?} - {}", self.filename
, err
);
57 impl FixedIndexReader
{
59 pub fn open(store
: Arc
<ChunkStore
>, path
: &Path
) -> Result
<Self, Error
> {
61 let full_path
= store
.relative_path(path
);
63 let mut file
= File
::open(&full_path
)
64 .map_err(|err
| format_err
!("Unable to open fixed index {:?} - {}", full_path
, err
))?
;
66 if let Err(err
) = nix
::fcntl
::flock(file
.as_raw_fd(), nix
::fcntl
::FlockArg
::LockSharedNonblock
) {
67 bail
!("unable to get shared lock on {:?} - {}", full_path
, err
);
70 let header_size
= std
::mem
::size_of
::<FixedIndexHeader
>();
72 // todo: use static assertion when available in rust
73 if header_size
!= 4096 { bail!("got unexpected header size for {:?}
", path); }
75 let mut buffer = vec![0u8; header_size];
76 file.read_exact(&mut buffer)?;
78 let header = unsafe { &mut * (buffer.as_ptr() as *mut FixedIndexHeader) };
80 if header.magic != super::FIXED_SIZED_CHUNK_INDEX_1_0 {
81 bail!("got unknown magic number
for {:?}
", path);
84 let size = u64::from_le(header.size) as usize;
85 let ctime = u64::from_le(header.ctime);
86 let chunk_size = u64::from_le(header.chunk_size) as usize;
88 let index_length = (size + chunk_size - 1)/chunk_size;
89 let index_size = index_length*32;
91 let rawfd = file.as_raw_fd();
93 let stat = match nix::sys::stat::fstat(rawfd) {
95 Err(err) => bail!("fstat {:?} failed
- {}
", path, err),
98 let expected_index_size = (stat.st_size as usize) - header_size;
99 if index_size != expected_index_size {
100 bail!("got unexpected file size
for {:?}
({}
!= {}
)",
101 path, index_size, expected_index_size);
104 let data = unsafe { nix::sys::mman::mmap(
105 std::ptr::null_mut(),
107 nix::sys::mman::ProtFlags::PROT_READ,
108 nix::sys::mman::MapFlags::MAP_PRIVATE,
110 header_size as i64) }? as *mut u8;
122 index_csum: header.index_csum,
126 fn unmap(&mut self) -> Result<(), Error> {
128 if self.index == std::ptr::null_mut() { return Ok(()); }
130 let index_size = self.index_length*32;
132 if let Err(err) = unsafe { nix::sys::mman::munmap(self.index as *mut std::ffi::c_void, index_size) } {
133 bail!("unmap file {:?} failed
- {}
", self.filename, err);
136 self.index = std::ptr::null_mut();
141 pub fn print_info(&self) {
142 println!("Filename
: {:?}
", self.filename);
143 println!("Size
: {}
", self.size);
144 println!("ChunkSize
: {}
", self.chunk_size);
145 println!("CTime
: {}
", Local.timestamp(self.ctime as i64, 0).format("%c
"));
146 println!("UUID
: {:?}
", self.uuid);
150 impl IndexFile for FixedIndexReader {
151 fn index_count(&self) -> usize {
155 fn index_digest(&self, pos: usize) -> Option<&[u8; 32]> {
156 if pos >= self.index_length {
159 Some(unsafe { std::mem::transmute(self.index.add(pos*32)) })
163 fn index_bytes(&self) -> u64 {
164 (self.index_length * self.chunk_size) as u64
168 pub struct FixedIndexWriter {
169 store: Arc<ChunkStore>,
171 _lock: tools::ProcessLockSharedGuard,
173 tmp_filename: PathBuf,
182 // `index` is mmap()ed which cannot be thread-local so should be sendable
183 unsafe impl Send for FixedIndexWriter {}
185 impl Drop for FixedIndexWriter {
188 let _ = std::fs::remove_file(&self.tmp_filename); // ignore errors
189 if let Err(err) = self.unmap() {
190 eprintln!("Unable to unmap file {:?}
- {}
", self.tmp_filename, err);
195 impl FixedIndexWriter {
197 pub fn create(store: Arc<ChunkStore>, path: &Path, size: usize, chunk_size: usize) -> Result<Self, Error> {
199 let shared_lock = store.try_shared_lock()?;
201 let full_path = store.relative_path(path);
202 let mut tmp_path = full_path.clone();
203 tmp_path.set_extension("tmp_fidx
");
205 let mut file = std::fs::OpenOptions::new()
206 .create(true).truncate(true)
211 let header_size = std::mem::size_of::<FixedIndexHeader>();
213 // todo: use static assertion when available in rust
214 if header_size != 4096 { panic!("got unexpected header size"); }
216 let ctime = std::time::SystemTime::now().duration_since(
217 std::time::SystemTime::UNIX_EPOCH)?.as_secs();
219 let uuid = Uuid::new_v4();
221 let buffer = vec![0u8; header_size];
222 let header = unsafe { &mut * (buffer.as_ptr() as *mut FixedIndexHeader) };
224 header.magic = super::FIXED_SIZED_CHUNK_INDEX_1_0;
225 header.ctime = u64::to_le(ctime);
226 header.size = u64::to_le(size as u64);
227 header.chunk_size = u64::to_le(chunk_size as u64);
228 header.uuid = *uuid.as_bytes();
230 header.index_csum = [0u8; 32];
232 file.write_all(&buffer)?;
234 let index_length = (size + chunk_size - 1)/chunk_size;
235 let index_size = index_length*32;
236 nix::unistd::ftruncate(file.as_raw_fd(), (header_size + index_size) as i64)?;
238 let data = unsafe { nix::sys::mman::mmap(
239 std::ptr::null_mut(),
241 nix::sys::mman::ProtFlags::PROT_READ | nix::sys::mman::ProtFlags::PROT_WRITE,
242 nix::sys::mman::MapFlags::MAP_SHARED,
244 header_size as i64) }? as *mut u8;
251 tmp_filename: tmp_path,
257 uuid: *uuid.as_bytes(),
261 pub fn index_length(&self) -> usize {
265 fn unmap(&mut self) -> Result<(), Error> {
267 if self.index == std::ptr::null_mut() { return Ok(()); }
269 let index_size = self.index_length*32;
271 if let Err(err) = unsafe { nix::sys::mman::munmap(self.index as *mut std::ffi::c_void, index_size) } {
272 bail!("unmap file {:?} failed
- {}
", self.tmp_filename, err);
275 self.index = std::ptr::null_mut();
280 pub fn close(&mut self) -> Result<[u8; 32], Error> {
282 if self.index == std::ptr::null_mut() { bail!("cannot close already closed index file."); }
284 let index_size = self.index_length*32;
285 let data = unsafe { std::slice::from_raw_parts(self.index, index_size) };
286 let index_csum = openssl::sha::sha256(data);
292 let csum_offset = proxmox::tools::offsetof!(FixedIndexHeader, index_csum);
293 self.file.seek(std::io::SeekFrom::Start(csum_offset as u64))?;
294 self.file.write_all(&index_csum)?;
297 if let Err(err) = std::fs::rename(&self.tmp_filename, &self.filename) {
298 bail!("Atomic rename file {:?} failed
- {}
", self.filename, err);
304 // Note: We want to add data out of order, so do not assume any order here.
305 pub fn add_chunk(&mut self, chunk_info: &ChunkInfo, stat: &mut ChunkStat) -> Result<(), Error> {
307 let chunk_len = chunk_info.chunk_len as usize;
308 let end = chunk_info.offset as usize;
311 bail!("got chunk with small
offset ({}
< {}
", end, chunk_len);
314 let pos = end - chunk_len;
317 bail!("write chunk data exceeds
size ({}
>= {}
)", end, self.size);
320 // last chunk can be smaller
321 if ((end != self.size) && (chunk_len != self.chunk_size)) ||
322 (chunk_len > self.chunk_size) || (chunk_len == 0) {
323 bail!("got chunk with wrong
length ({}
!= {}
", chunk_len, self.chunk_size);
326 if pos & (self.chunk_size-1) != 0 { bail!("add unaligned chunk (pos = {})", pos
); }
328 if (end
as u64) != chunk_info
.offset
{
329 bail
!("got chunk with wrong offset ({} != {}", end
, chunk_info
.offset
);
332 let (is_duplicate
, compressed_size
) = self.store
.insert_chunk(&chunk_info
.chunk
)?
;
334 stat
.chunk_count
+= 1;
335 stat
.compressed_size
+= compressed_size
;
337 let digest
= chunk_info
.chunk
.digest();
339 println
!("ADD CHUNK {} {} {}% {} {}", pos
, chunk_len
,
340 (compressed_size
*100)/(chunk_len
as u64), is_duplicate
, proxmox
::tools
::digest_to_hex(digest
));
343 stat
.duplicate_chunks
+= 1;
345 stat
.disk_size
+= compressed_size
;
348 self.add_digest(pos
/ self.chunk_size
, digest
)
351 pub fn add_digest(&mut self, index
: usize, digest
: &[u8; 32]) -> Result
<(), Error
> {
353 if index
>= self.index_length
{
354 bail
!("add digest failed - index out of range ({} >= {})", index
, self.index_length
);
357 if self.index
== std
::ptr
::null_mut() { bail!("cannot write to closed index file."); }
359 let index_pos
= index
*32;
361 let dst
= self.index
.add(index_pos
);
362 dst
.copy_from_nonoverlapping(digest
.as_ptr(), 32);