2 use std
::io
::{self, BufWriter, Seek, SeekFrom, Write}
;
4 use std
::os
::unix
::io
::AsRawFd
;
5 use std
::path
::{Path, PathBuf}
;
6 use std
::sync
::{Arc, Mutex}
;
7 use std
::task
::Context
;
10 use anyhow
::{bail, format_err, Error}
;
12 use proxmox
::tools
::io
::ReadExt
;
13 use proxmox
::tools
::uuid
::Uuid
;
14 use proxmox
::tools
::mmap
::Mmap
;
15 use pxar
::accessor
::{MaybeReady, ReadAt, ReadAtOperation}
;
17 use super::chunk_stat
::ChunkStat
;
18 use super::chunk_store
::ChunkStore
;
19 use super::index
::ChunkReadInfo
;
20 use super::read_chunk
::ReadChunk
;
23 use super::{DataBlob, DataChunkBuilder}
;
26 /// Header format definition for dynamic index files (`.dixd`)
28 pub struct DynamicIndexHeader
{
32 /// Sha256 over the index ``SHA256(offset1||digest1||offset2||digest2||...)``
33 pub index_csum
: [u8; 32],
34 reserved
: [u8; 4032], // overall size is one page (4096 bytes)
36 proxmox
::static_assert_size
!(DynamicIndexHeader
, 4096);
37 // TODO: Once non-Copy unions are stabilized, use:
38 // union DynamicIndexHeader {
39 // reserved: [u8; 4096],
40 // pub data: DynamicIndexHeaderData,
43 impl DynamicIndexHeader
{
44 /// Convenience method to allocate a zero-initialized header struct.
45 pub fn zeroed() -> Box
<Self> {
47 Box
::from_raw(std
::alloc
::alloc_zeroed(std
::alloc
::Layout
::new
::<Self>()) as *mut Self)
51 pub fn as_bytes(&self) -> &[u8] {
53 std
::slice
::from_raw_parts(
54 self as *const Self as *const u8,
55 std
::mem
::size_of
::<Self>(),
61 #[derive(Clone, Debug)]
63 pub struct DynamicEntry
{
70 pub fn end(&self) -> u64 {
71 u64::from_le(self.end_le
)
75 pub struct DynamicIndexReader
{
78 index
: Mmap
<DynamicEntry
>,
81 pub index_csum
: [u8; 32],
84 impl DynamicIndexReader
{
85 pub fn open(path
: &Path
) -> Result
<Self, Error
> {
89 .map_err(|err
| format_err
!("Unable to open dynamic index {:?} - {}", path
, err
))
92 pub fn new(mut file
: std
::fs
::File
) -> Result
<Self, Error
> {
93 // FIXME: This is NOT OUR job! Check the callers of this method and remove this!
94 file
.seek(SeekFrom
::Start(0))?
;
96 let header_size
= std
::mem
::size_of
::<DynamicIndexHeader
>();
98 let header
: Box
<DynamicIndexHeader
> = unsafe { file.read_host_value_boxed()? }
;
100 if header
.magic
!= super::DYNAMIC_SIZED_CHUNK_INDEX_1_0
{
101 bail
!("got unknown magic number");
104 let ctime
= proxmox
::tools
::time
::epoch_i64();
106 let rawfd
= file
.as_raw_fd();
108 let stat
= nix
::sys
::stat
::fstat(rawfd
)?
;
110 let size
= stat
.st_size
as usize;
112 let index_size
= size
- header_size
;
113 let index_count
= index_size
/ 40;
114 if index_count
* 40 != index_size
{
115 bail
!("got unexpected file size");
123 nix
::sys
::mman
::ProtFlags
::PROT_READ
,
124 nix
::sys
::mman
::MapFlags
::MAP_PRIVATE
,
134 index_csum
: header
.index_csum
,
139 #[allow(clippy::cast_ptr_alignment)]
140 fn chunk_end(&self, pos
: usize) -> u64 {
141 if pos
>= self.index
.len() {
142 panic
!("chunk index out of range");
144 self.index
[pos
].end()
148 fn chunk_digest(&self, pos
: usize) -> &[u8; 32] {
149 if pos
>= self.index
.len() {
150 panic
!("chunk index out of range");
152 &self.index
[pos
].digest
155 // TODO: can we use std::slice::binary_search with Mmap now?
163 ) -> Result
<usize, Error
> {
164 if (offset
>= end
) || (offset
< start
) {
165 bail
!("offset out of range");
168 if end_idx
== start_idx
{
169 return Ok(start_idx
); // found
171 let middle_idx
= (start_idx
+ end_idx
) / 2;
172 let middle_end
= self.chunk_end(middle_idx
);
174 if offset
< middle_end
{
175 self.binary_search(start_idx
, start
, middle_idx
, middle_end
, offset
)
177 self.binary_search(middle_idx
+ 1, middle_end
, end_idx
, end
, offset
)
182 impl IndexFile
for DynamicIndexReader
{
183 fn index_count(&self) -> usize {
187 fn index_digest(&self, pos
: usize) -> Option
<&[u8; 32]> {
188 if pos
>= self.index
.len() {
191 Some(unsafe { std::mem::transmute(self.chunk_digest(pos).as_ptr()) }
)
195 fn index_bytes(&self) -> u64 {
196 if self.index
.is_empty() {
199 self.chunk_end(self.index
.len() - 1)
203 fn compute_csum(&self) -> ([u8; 32], u64) {
204 let mut csum
= openssl
::sha
::Sha256
::new();
205 let mut chunk_end
= 0;
206 for pos
in 0..self.index_count() {
207 let info
= self.chunk_info(pos
).unwrap();
208 chunk_end
= info
.range
.end
;
209 csum
.update(&chunk_end
.to_le_bytes());
210 csum
.update(&info
.digest
);
212 let csum
= csum
.finish();
216 #[allow(clippy::cast_ptr_alignment)]
217 fn chunk_info(&self, pos
: usize) -> Option
<ChunkReadInfo
> {
218 if pos
>= self.index
.len() {
221 let start
= if pos
== 0 { 0 }
else { self.index[pos - 1].end() }
;
223 let end
= self.index
[pos
].end();
227 digest
: self.index
[pos
].digest
.clone(),
231 fn chunk_from_offset(&self, offset
: u64) -> Option
<(usize, u64)> {
232 let end_idx
= self.index
.len() - 1;
233 let end
= self.chunk_end(end_idx
);
234 let found_idx
= self.binary_search(0, 0, end_idx
, end
, offset
);
235 let found_idx
= match found_idx
{
237 Err(_
) => return None
240 let found_start
= if found_idx
== 0 {
243 self.chunk_end(found_idx
- 1)
246 Some((found_idx
, offset
- found_start
))
256 /// Perform sanity checks on the range and data size:
257 pub fn new(range
: Range
<u64>, data
: Vec
<u8>) -> Result
<Self, Error
> {
258 if data
.len() as u64 != range
.end
- range
.start
{
260 "read chunk with wrong size ({} != {})",
262 range
.end
- range
.start
,
265 Ok(Self { range, data }
)
269 pub struct BufferedDynamicReader
<S
> {
271 index
: DynamicIndexReader
,
273 read_buffer
: Vec
<u8>,
274 buffered_chunk_idx
: usize,
275 buffered_chunk_start
: u64,
277 lru_cache
: crate::tools
::lru_cache
::LruCache
<usize, CachedChunk
>,
280 struct ChunkCacher
<'a
, S
> {
282 index
: &'a DynamicIndexReader
,
285 impl<'a
, S
: ReadChunk
> crate::tools
::lru_cache
::Cacher
<usize, CachedChunk
> for ChunkCacher
<'a
, S
> {
286 fn fetch(&mut self, index
: usize) -> Result
<Option
<CachedChunk
>, Error
> {
287 let info
= match self.index
.chunk_info(index
) {
289 None
=> bail
!("chunk index out of range"),
291 let range
= info
.range
;
292 let data
= self.store
.read_chunk(&info
.digest
)?
;
293 CachedChunk
::new(range
, data
).map(Some
)
297 impl<S
: ReadChunk
> BufferedDynamicReader
<S
> {
298 pub fn new(index
: DynamicIndexReader
, store
: S
) -> Self {
299 let archive_size
= index
.index_bytes();
304 read_buffer
: Vec
::with_capacity(1024 * 1024),
305 buffered_chunk_idx
: 0,
306 buffered_chunk_start
: 0,
308 lru_cache
: crate::tools
::lru_cache
::LruCache
::new(32),
312 pub fn archive_size(&self) -> u64 {
316 fn buffer_chunk(&mut self, idx
: usize) -> Result
<(), Error
> {
317 //let (start, end, data) = self.lru_cache.access(
318 let cached_chunk
= self.lru_cache
.access(
321 store
: &mut self.store
,
324 )?
.ok_or_else(|| format_err
!("chunk not found by cacher"))?
;
327 self.read_buffer
.clear();
328 self.read_buffer
.extend_from_slice(&cached_chunk
.data
);
330 self.buffered_chunk_idx
= idx
;
332 self.buffered_chunk_start
= cached_chunk
.range
.start
;
333 //println!("BUFFER {} {}", self.buffered_chunk_start, end);
338 impl<S
: ReadChunk
> crate::tools
::BufferedRead
for BufferedDynamicReader
<S
> {
339 fn buffered_read(&mut self, offset
: u64) -> Result
<&[u8], Error
> {
340 if offset
== self.archive_size
{
341 return Ok(&self.read_buffer
[0..0]);
344 let buffer_len
= self.read_buffer
.len();
345 let index
= &self.index
;
347 // optimization for sequential read
349 && ((self.buffered_chunk_idx
+ 1) < index
.index
.len())
350 && (offset
>= (self.buffered_chunk_start
+ (self.read_buffer
.len() as u64)))
352 let next_idx
= self.buffered_chunk_idx
+ 1;
353 let next_end
= index
.chunk_end(next_idx
);
354 if offset
< next_end
{
355 self.buffer_chunk(next_idx
)?
;
356 let buffer_offset
= (offset
- self.buffered_chunk_start
) as usize;
357 return Ok(&self.read_buffer
[buffer_offset
..]);
362 || (offset
< self.buffered_chunk_start
)
363 || (offset
>= (self.buffered_chunk_start
+ (self.read_buffer
.len() as u64)))
365 let end_idx
= index
.index
.len() - 1;
366 let end
= index
.chunk_end(end_idx
);
367 let idx
= index
.binary_search(0, 0, end_idx
, end
, offset
)?
;
368 self.buffer_chunk(idx
)?
;
371 let buffer_offset
= (offset
- self.buffered_chunk_start
) as usize;
372 Ok(&self.read_buffer
[buffer_offset
..])
376 impl<S
: ReadChunk
> std
::io
::Read
for BufferedDynamicReader
<S
> {
377 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize, std
::io
::Error
> {
378 use crate::tools
::BufferedRead
;
379 use std
::io
::{Error, ErrorKind}
;
381 let data
= match self.buffered_read(self.read_offset
) {
383 Err(err
) => return Err(Error
::new(ErrorKind
::Other
, err
.to_string())),
386 let n
= if data
.len() > buf
.len() {
392 buf
[0..n
].copy_from_slice(&data
[0..n
]);
394 self.read_offset
+= n
as u64;
400 impl<S
: ReadChunk
> std
::io
::Seek
for BufferedDynamicReader
<S
> {
401 fn seek(&mut self, pos
: SeekFrom
) -> Result
<u64, std
::io
::Error
> {
402 let new_offset
= match pos
{
403 SeekFrom
::Start(start_offset
) => start_offset
as i64,
404 SeekFrom
::End(end_offset
) => (self.archive_size
as i64) + end_offset
,
405 SeekFrom
::Current(offset
) => (self.read_offset
as i64) + offset
,
408 use std
::io
::{Error, ErrorKind}
;
409 if (new_offset
< 0) || (new_offset
> (self.archive_size
as i64)) {
410 return Err(Error
::new(
413 "seek is out of range {} ([0..{}])",
414 new_offset
, self.archive_size
418 self.read_offset
= new_offset
as u64;
424 /// This is a workaround until we have cleaned up the chunk/reader/... infrastructure for better
427 /// Ideally BufferedDynamicReader gets replaced so the LruCache maps to `BroadcastFuture<Chunk>`,
428 /// so that we can properly access it from multiple threads simultaneously while not issuing
429 /// duplicate simultaneous reads over http.
431 pub struct LocalDynamicReadAt
<R
: ReadChunk
> {
432 inner
: Arc
<Mutex
<BufferedDynamicReader
<R
>>>,
435 impl<R
: ReadChunk
> LocalDynamicReadAt
<R
> {
436 pub fn new(inner
: BufferedDynamicReader
<R
>) -> Self {
438 inner
: Arc
::new(Mutex
::new(inner
)),
443 impl<R
: ReadChunk
> ReadAt
for LocalDynamicReadAt
<R
> {
444 fn start_read_at
<'a
>(
449 ) -> MaybeReady
<io
::Result
<usize>, ReadAtOperation
<'a
>> {
451 MaybeReady
::Ready(tokio
::task
::block_in_place(move || {
452 let mut reader
= self.inner
.lock().unwrap();
453 reader
.seek(SeekFrom
::Start(offset
))?
;
454 Ok(reader
.read(buf
)?
)
458 fn poll_complete
<'a
>(
460 _op
: ReadAtOperation
<'a
>,
461 ) -> MaybeReady
<io
::Result
<usize>, ReadAtOperation
<'a
>> {
462 panic
!("LocalDynamicReadAt::start_read_at returned Pending");
467 /// Create dynamic index files (`.dixd`)
468 pub struct DynamicIndexWriter
{
469 store
: Arc
<ChunkStore
>,
470 _lock
: tools
::ProcessLockSharedGuard
,
471 writer
: BufWriter
<File
>,
474 tmp_filename
: PathBuf
,
475 csum
: Option
<openssl
::sha
::Sha256
>,
480 impl Drop
for DynamicIndexWriter
{
482 let _
= std
::fs
::remove_file(&self.tmp_filename
); // ignore errors
486 impl DynamicIndexWriter
{
487 pub fn create(store
: Arc
<ChunkStore
>, path
: &Path
) -> Result
<Self, Error
> {
488 let shared_lock
= store
.try_shared_lock()?
;
490 let full_path
= store
.relative_path(path
);
491 let mut tmp_path
= full_path
.clone();
492 tmp_path
.set_extension("tmp_didx");
494 let file
= std
::fs
::OpenOptions
::new()
501 let mut writer
= BufWriter
::with_capacity(1024 * 1024, file
);
503 let ctime
= proxmox
::tools
::time
::epoch_i64();
505 let uuid
= Uuid
::generate();
507 let mut header
= DynamicIndexHeader
::zeroed();
508 header
.magic
= super::DYNAMIC_SIZED_CHUNK_INDEX_1_0
;
509 header
.ctime
= i64::to_le(ctime
);
510 header
.uuid
= *uuid
.as_bytes();
511 // header.index_csum = [0u8; 32];
512 writer
.write_all(header
.as_bytes())?
;
514 let csum
= Some(openssl
::sha
::Sha256
::new());
522 tmp_filename
: tmp_path
,
524 uuid
: *uuid
.as_bytes(),
529 // fixme: use add_chunk instead?
530 pub fn insert_chunk(&self, chunk
: &DataBlob
, digest
: &[u8; 32]) -> Result
<(bool
, u64), Error
> {
531 self.store
.insert_chunk(chunk
, digest
)
534 pub fn close(&mut self) -> Result
<[u8; 32], Error
> {
537 "cannot close already closed archive index file {:?}",
544 self.writer
.flush()?
;
546 let csum_offset
= proxmox
::offsetof!(DynamicIndexHeader
, index_csum
);
547 self.writer
.seek(SeekFrom
::Start(csum_offset
as u64))?
;
549 let csum
= self.csum
.take().unwrap();
550 let index_csum
= csum
.finish();
552 self.writer
.write_all(&index_csum
)?
;
553 self.writer
.flush()?
;
555 if let Err(err
) = std
::fs
::rename(&self.tmp_filename
, &self.filename
) {
556 bail
!("Atomic rename file {:?} failed - {}", self.filename
, err
);
562 // fixme: rename to add_digest
563 pub fn add_chunk(&mut self, offset
: u64, digest
: &[u8; 32]) -> Result
<(), Error
> {
566 "cannot write to closed dynamic index file {:?}",
571 let offset_le
: &[u8; 8] = unsafe { &std::mem::transmute::<u64, [u8; 8]>(offset.to_le()) }
;
573 if let Some(ref mut csum
) = self.csum
{
574 csum
.update(offset_le
);
578 self.writer
.write_all(offset_le
)?
;
579 self.writer
.write_all(digest
)?
;
584 /// Writer which splits a binary stream into dynamic sized chunks
586 /// And store the resulting chunk list into the index file.
587 pub struct DynamicChunkWriter
{
588 index
: DynamicIndexWriter
,
594 chunk_buffer
: Vec
<u8>,
597 impl DynamicChunkWriter
{
598 pub fn new(index
: DynamicIndexWriter
, chunk_size
: usize) -> Self {
602 chunker
: Chunker
::new(chunk_size
),
603 stat
: ChunkStat
::new(0),
606 chunk_buffer
: Vec
::with_capacity(chunk_size
* 4),
610 pub fn stat(&self) -> &ChunkStat
{
614 pub fn close(&mut self) -> Result
<(), Error
> {
621 self.write_chunk_buffer()?
;
625 self.stat
.size
= self.chunk_offset
as u64;
627 // add size of index file
629 (self.stat
.chunk_count
* 40 + std
::mem
::size_of
::<DynamicIndexHeader
>()) as u64;
634 fn write_chunk_buffer(&mut self) -> Result
<(), Error
> {
635 let chunk_size
= self.chunk_buffer
.len();
641 let expected_chunk_size
= self.chunk_offset
- self.last_chunk
;
642 if expected_chunk_size
!= self.chunk_buffer
.len() {
643 bail
!("wrong chunk size {} != {}", expected_chunk_size
, chunk_size
);
646 self.stat
.chunk_count
+= 1;
648 self.last_chunk
= self.chunk_offset
;
650 let (chunk
, digest
) = DataChunkBuilder
::new(&self.chunk_buffer
)
654 match self.index
.insert_chunk(&chunk
, &digest
) {
655 Ok((is_duplicate
, compressed_size
)) => {
656 self.stat
.compressed_size
+= compressed_size
;
658 self.stat
.duplicate_chunks
+= 1;
660 self.stat
.disk_size
+= compressed_size
;
664 "ADD CHUNK {:016x} {} {}% {} {}",
667 (compressed_size
* 100) / (chunk_size
as u64),
669 proxmox
::tools
::digest_to_hex(&digest
)
671 self.index
.add_chunk(self.chunk_offset
as u64, &digest
)?
;
672 self.chunk_buffer
.truncate(0);
676 self.chunk_buffer
.truncate(0);
683 impl Write
for DynamicChunkWriter
{
684 fn write(&mut self, data
: &[u8]) -> std
::result
::Result
<usize, std
::io
::Error
> {
685 let chunker
= &mut self.chunker
;
687 let pos
= chunker
.scan(data
);
690 self.chunk_buffer
.extend_from_slice(&data
[0..pos
]);
691 self.chunk_offset
+= pos
;
693 if let Err(err
) = self.write_chunk_buffer() {
694 return Err(std
::io
::Error
::new(
695 std
::io
::ErrorKind
::Other
,
701 self.chunk_offset
+= data
.len();
702 self.chunk_buffer
.extend_from_slice(data
);
707 fn flush(&mut self) -> std
::result
::Result
<(), std
::io
::Error
> {
708 Err(std
::io
::Error
::new(
709 std
::io
::ErrorKind
::Other
,
710 "please use close() instead of flush()",