]> git.proxmox.com Git - proxmox-backup.git/blame - src/client/pxar_backup_stream.rs
src/pxar/encoder.rs: allow to pass list of devices
[proxmox-backup.git] / src / client / pxar_backup_stream.rs
CommitLineData
e8edbbd4
DM
1use failure::*;
2
3use std::thread;
4use std::os::unix::io::FromRawFd;
17d6979a 5use std::path::{Path, PathBuf};
2eeaacb9 6use std::collections::HashSet;
e8edbbd4 7
0c516b12 8use futures::Poll;
e8edbbd4
DM
9use futures::stream::Stream;
10
11use nix::fcntl::OFlag;
12use nix::sys::stat::Mode;
23bb8780 13use nix::dir::Dir;
e8edbbd4 14
3dbfe5b1 15use crate::pxar;
0c516b12 16use crate::tools::wrapped_reader_stream::WrappedReaderStream;
e8edbbd4 17
8968258b 18/// Stream implementation to encode and upload .pxar archives.
151c6ce2
DM
19///
20/// The hyper client needs an async Stream for file upload, so we
8968258b 21/// spawn an extra thread to encode the .pxar data and pipe it to the
151c6ce2 22/// consumer.
8968258b 23pub struct PxarBackupStream {
2698e8a5 24 stream: Option<WrappedReaderStream<std::fs::File>>,
e8edbbd4
DM
25 child: Option<thread::JoinHandle<()>>,
26}
27
8968258b 28impl Drop for PxarBackupStream {
e8edbbd4
DM
29
30 fn drop(&mut self) {
2698e8a5 31 self.stream = None;
e8edbbd4
DM
32 self.child.take().unwrap().join().unwrap();
33 }
34}
35
8968258b 36impl PxarBackupStream {
e8edbbd4 37
2eeaacb9 38 pub fn new(mut dir: Dir, path: PathBuf, device_set: Option<HashSet<u64>>, verbose: bool) -> Result<Self, Error> {
e8edbbd4
DM
39
40 let (rx, tx) = nix::unistd::pipe()?;
41
0c516b12 42 let buffer_size = 1024*1024;
c6e28b66
DM
43 nix::fcntl::fcntl(rx, nix::fcntl::FcntlArg::F_SETPIPE_SZ(buffer_size as i32))?;
44
e8edbbd4
DM
45 let child = thread::spawn(move|| {
46 let mut writer = unsafe { std::fs::File::from_raw_fd(tx) };
2eeaacb9 47 if let Err(err) = pxar::Encoder::encode(path, &mut dir, &mut writer, device_set, verbose, pxar::CA_FORMAT_DEFAULT) {
8968258b 48 eprintln!("pxar encode failed - {}", err);
e8edbbd4
DM
49 }
50 });
51
52 let pipe = unsafe { std::fs::File::from_raw_fd(rx) };
0c516b12 53 let stream = crate::tools::wrapped_reader_stream::WrappedReaderStream::new(pipe);
e8edbbd4 54
2698e8a5 55 Ok(Self { stream: Some(stream), child: Some(child) })
e8edbbd4 56 }
23bb8780 57
2eeaacb9 58 pub fn open(dirname: &Path, device_set: Option<HashSet<u64>>, verbose: bool) -> Result<Self, Error> {
23bb8780 59
728797d0 60 let dir = nix::dir::Dir::open(dirname, OFlag::O_DIRECTORY, Mode::empty())?;
23bb8780
DM
61 let path = std::path::PathBuf::from(dirname);
62
2eeaacb9 63 Self::new(dir, path, device_set, verbose)
23bb8780 64 }
e8edbbd4
DM
65}
66
8968258b 67impl Stream for PxarBackupStream {
e8edbbd4
DM
68
69 type Item = Vec<u8>;
70 type Error = Error;
71
e8edbbd4 72 fn poll(&mut self) -> Poll<Option<Vec<u8>>, Error> {
2698e8a5 73 self.stream.as_mut().unwrap().poll().map_err(Error::from)
e8edbbd4
DM
74 }
75}