1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
extern crate failure;
extern crate fmt_extra;
#[macro_use] extern crate failure_derive;

extern crate enumflags2;
#[macro_use]
extern crate enumflags2_derive;

extern crate shell_words;

use enumflags2::BitFlags;
use std::ops::{Deref,DerefMut};
use std::env;
use std::ffi::OsStr;
use std::process;
use std::{io,fmt};

mod zpool;

#[derive(Debug,PartialEq,Eq,Clone)]
pub struct Zfs {
    // FIXME: we require utf-8 here
    zfs_cmd: Vec<String>,
}

#[derive(Debug,PartialEq,Eq,Clone)]
pub enum ListTypes {
    Filesystem,
    Snapshot,
    Volume,
    Bookmark,
}

#[derive(Debug)]
pub struct CmdInfo {
    status: process::ExitStatus,
    stderr: String,
    cmd: String,
}


#[derive(Debug,Fail)]
pub enum ZfsError {
    #[fail(display = "execution of zfs command failed: {}", io)]
    Exec {
        io: io::Error
    },

    #[fail(display = "zfs command returned an error: {:?}", cmd_info)]
    Process {
        cmd_info: CmdInfo,
    },

    // A specific CannotOpen kind
    #[fail(display = "no such dataset '{}' ({:?})", dataset, cmd_info)]
    NoDataset {
        dataset: String,
        cmd_info: CmdInfo,
    },

    #[fail(display = "cannot open: {:?}", cmd_info)]
    CannotOpen {
        cmd_info: CmdInfo,
    },
}

#[derive(Debug,PartialEq,Eq,Clone)]
pub struct ZfsList {
    out: Vec<u8>,
}

impl fmt::Display for ZfsList {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result
    {
        write!(fmt, "[")?;
        for i in self.iter() {
            write!(fmt, "{},", fmt_extra::AsciiStr(i))?;
        }
        write!(fmt, "]")
    }
}

impl Default for ZfsList {
    fn default() -> Self {
        ZfsList { out: Vec::new() }
    }
}

impl ZfsList {
    pub fn iter(&self) -> impl Iterator<Item=&[u8]>
    {
        self.out.split(|&x| x ==  b'\n').filter(|x| x.len() != 0)
    }
}

impl<'a> From<&'a ZfsList> for Vec<Vec<String>> {
    fn from(x: &'a ZfsList) -> Self {
        let mut h = Vec::default();

        for i in x.iter() {
            // collect `i` into a Vec<Vec<u8>>
            let mut vs = Vec::default();
            let mut v = Vec::default();

            for b in i {
                if *b == b'\t'  {
                    vs.push(String::from_utf8(v).unwrap());
                    v = Vec::default();
                } else {
                    v.push(*b);
                }
            }

            vs.push(String::from_utf8(v).unwrap());
            h.push(vs);
        }

        h
    }
}

#[derive(Debug,Default,PartialEq,Eq,Clone)]
struct TypeSpec {
    include_fs: bool,
    include_snap: bool,
    include_vol: bool,
    include_bookmark: bool,
}

impl<'a> From<&'a TypeSpec> for String {
    fn from(t: &'a TypeSpec) -> Self {
        let mut v = vec![];
        if t.include_fs {
            v.push("filesystem")
        }
        if t.include_snap {
            v.push("snapshot")
        }
        if t.include_vol {
            v.push("volume")
        }
        if t.include_bookmark {
            v.push("bookmark")
        }

        v.join(",")
    }
}

#[derive(Debug,PartialEq,Eq,Clone)]
enum ListRecurse {
    No,
    Depth(usize),
    Yes,
}

impl Default for ListRecurse {
    fn default() -> Self {
        ListRecurse::No
    }
}

/// Note: no support for sorting, folks can do that in rust if they really want it.
#[derive(Debug,PartialEq,Eq,Clone,Default)]
pub struct ListBuilder {
    recursive: ListRecurse,
    dataset_types: Option<TypeSpec>,
    elements: Vec<&'static str>,
    base_dataset: Option<String>
}

impl ListBuilder {
    pub fn depth(&mut self, levels: usize) -> &mut Self {
        self.recursive = ListRecurse::Depth(levels);
        self
    }

    pub fn recursive(&mut self) -> &mut Self {
        self.recursive = ListRecurse::Yes;
        self
    }

    pub fn include_filesystems(&mut self) -> &mut Self {
        self.dataset_types.get_or_insert(TypeSpec::default()).include_fs = true;
        self
    }

    pub fn include_snapshots(&mut self) -> &mut Self {
        self.dataset_types.get_or_insert(TypeSpec::default()).include_snap = true;
        self
    }

    pub fn include_bookmarks(&mut self) -> &mut Self {
        self.dataset_types.get_or_insert(TypeSpec::default()).include_bookmark = true;
        self
    }

    pub fn include_volumes(&mut self) -> &mut Self {
        self.dataset_types.get_or_insert(TypeSpec::default()).include_vol = true;
        self
    }

    pub fn with_elements(&mut self, mut elements: Vec<&'static str>) -> &mut Self {
        self.elements.append(&mut elements);
        self
    }

    pub fn with_dataset<T: Into<String>>(&mut self, dataset: T) -> &mut Self {
        self.base_dataset = Some(dataset.into());
        self
    }
}

pub struct ListExecutor<'a> {
    parent: &'a Zfs,
    builder: ListBuilder,
}

impl<'a> ListExecutor<'a> {
    fn from_parent(zfs: &'a Zfs) -> Self {
        ListExecutor {
            parent: zfs,
            builder: Default::default()
        }
    }

    pub fn query(&self) -> Result<ZfsList, ZfsError> {
        self.parent.list_from_builder(self)
    }
}

impl<'a> Deref for ListExecutor<'a> {
    type Target = ListBuilder;
    fn deref(&self) -> &ListBuilder {
        &self.builder
    }
}

impl<'a> DerefMut for ListExecutor<'a> {
    fn deref_mut(&mut self) -> &mut ListBuilder {
        &mut self.builder
    }
}

impl Zfs {

    fn cmd(&self) -> process::Command
    {
        let mut cmd = process::Command::new(&self.zfs_cmd[0]);
        cmd.args(&self.zfs_cmd[1..]);
        cmd
    }

    fn cmdinfo_to_error(cmd_info: CmdInfo) -> ZfsError
    {

        // status: ExitStatus(ExitStatus(256)), stderr: "cannot open \'innerpool/TMP/zoop-test-28239/dst/sub_ds\': dataset does not exist\n"
        let prefix_ca = "cannot open '";
        if cmd_info.stderr.starts_with(prefix_ca) {
            let ds_rest = &cmd_info.stderr[prefix_ca.len()..].to_owned();
            let mut s = ds_rest.split("': ");
            let ds = s.next().unwrap();
            let error = s.next().unwrap();
            return match error {
                "dataset does not exist\n" => {
                    ZfsError::NoDataset {
                        dataset: ds.to_owned(),
                        cmd_info: cmd_info,
                    }
                },
                _ => {
                    ZfsError::CannotOpen {
                        cmd_info: cmd_info,
                    }
                }
            };
        }

        // generic error
        ZfsError::Process {
            cmd_info: cmd_info,
        }
    }

    pub fn list_from_builder(&self, builder: &ListBuilder) -> Result<ZfsList, ZfsError>
    {
        // zfs list -H
        // '-s <prop>' sort by property (multiple allowed)
        // '-d <depth>' recurse to depth
        // '-r' 
        let mut cmd = self.cmd();

        cmd
            .arg("list")
            // +parsable, +scripting mode
            .arg("-pH")
            // sorting by name is faster.
            // TODO: find out why
            .arg("-s").arg("name")
            ;

        if builder.elements.len() == 0 {
            cmd
                // only name
                .arg("-o").arg("name")
                ;
        } else {
            let mut elem_arg = String::new();
            for e in builder.elements.iter() {
                elem_arg.push_str(e);
                elem_arg.push(',');
            }

            cmd.arg("-o").arg(elem_arg);
        }

        match builder.recursive {
            ListRecurse::No => {},
            ListRecurse::Depth(sz) => {
                cmd.arg("-d").arg(format!("{}",sz));
            },
            ListRecurse::Yes => {
                cmd.arg("-r");
            }
        }

        match &builder.dataset_types {
            &None => {
                // TODO: should we require this?
            },
            &Some(ref v) => {
                cmd.arg("-t").arg(String::from(v));
            }
        }

        match builder.base_dataset {
            None => {},
            Some(ref v) => {
                cmd.arg(v);
            }
        }

        eprintln!("run: {:?}", cmd);

        let output = cmd.output().map_err(|e| ZfsError::Exec{ io: e})?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr[..]).into_owned();

            let cmd_info = CmdInfo {
                status: output.status,
                stderr: stderr,
                cmd: format!("{:?}", cmd),
            };

            return Err(Self::cmdinfo_to_error(cmd_info))
        }

        if output.stderr.len() > 0 {
            eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        }

        Ok(ZfsList { out: output.stdout })
    }

    pub fn list_basic(&self) -> Result<ZfsList, ZfsError>
    {
        self.list().query()
    }

    pub fn list(&self) -> ListExecutor {
        ListExecutor::from_parent(self)
    }

    // delete
    //
    // hold
    // release
    //
    // create
    //
    // send
    // recv
    //
    // get (for resume)

    pub fn from_env_prefix(prefix: &'static str) -> Self {
        // TODO: consider failing if {}_ZFS_CMD is not a valid OsStr
        // TODO: parse this into a series of values

        let env_name = format!("{}_ZFS_CMD", prefix);
        let env_specific = env::var_os(env_name);
        let env = match env_specific {
            Some(x) => x,
            None => env::var_os("ZFS_CMD").unwrap_or(OsStr::new("zfs").to_owned()),
        };

        let env = env.to_str().expect("env is not utf-8");

        let zfs_cmd = shell_words::split(env).expect("failed to split words");

        Zfs {
            zfs_cmd: zfs_cmd,
        }
    }

    /// Resume sending a stream using `receive_resume_token` from the destination filesystem
    ///
    /// flags here is constrained to `[Penv]`
    pub fn send_resume(&self, receive_resume_token: &str, flags: BitFlags<SendFlags>) -> io::Result<ZfsSend>
    {
        let mut cmd = self.cmd();

        cmd.arg("send");

        let mut opts = "-".to_owned();

        // forbidden flags:
        //  - `replicate`: `-R`
        //  - `props`: `-p`
        //  - `backup`: `-b`
        //  - `dedup`: `-D`
        //  - `holds`: `-h`
        //  - `redactbook`: `-d` `arg`

        for flag in flags.iter() {
            match flag {
                SendFlags::LargeBlock => { opts.push('L') },
                SendFlags::EmbedData => { opts.push('e') },
                SendFlags::Compressed => { opts.push('c') },
                SendFlags::Raw => { opts.push('w') },

                SendFlags::Verbose => { opts.push('v') },
                SendFlags::DryRun => { opts.push('n') },
                SendFlags::Parsable => { opts.push('P') },
                _ => { panic!("unsupported flag: {:?}", flag); }
            }
        }

        cmd.arg("-t").arg(receive_resume_token);

        eprintln!("run: {:?}", cmd);

        Ok(ZfsSend {
            child: cmd
                .stdout(std::process::Stdio::piped())
                .spawn()?
        })
    }

    //pub fn recv_abort_incomplete(&self)

    pub fn send(&self, snapname: &str, from: Option<&str>, flags: BitFlags<SendFlags>) -> io::Result<ZfsSend>
    {
        let mut cmd = self.cmd();

        cmd.arg("send");

        let mut opts = "-".to_owned();

        let mut include_intermediary = false;
        // realistically, a series of `if flags.contains(*) {*}` statements more susinctly
        // represents the work needed to be done here. Unfortunately, it isn't clear how to form
        // that in a way that ensures we have handling for all `SendFlags`.
        for flag in flags.iter() {
            match flag {
                SendFlags::EmbedData => { opts.push('e') },
                SendFlags::LargeBlock => { opts.push('L') },
                SendFlags::Compressed => { opts.push('c') },
                SendFlags::Raw => { opts.push('w') },

                SendFlags::Dedup => { opts.push('D') },

                SendFlags::IncludeIntermediary => {
                    include_intermediary = true
                },
                SendFlags::IncludeHolds => { opts.push('h') },
                SendFlags::IncludeProps => { opts.push('p') },
                SendFlags::Verbose => { opts.push('v') },
                SendFlags::DryRun => { opts.push('n') },
                SendFlags::Parsable => { opts.push('P') },
                SendFlags::Replicate => { opts.push('R') },
            }
        }

        cmd.arg(opts);

        match from {
            Some(f) => {
                if include_intermediary {
                    cmd.arg("-I")
                } else {
                    cmd.arg("-i")
                }.arg(f);
            }
            None => {
                if include_intermediary {
                    panic!("include_intermediary set to no effect because no `from` was specified");
                }
            }
        }

        cmd.arg(snapname);

        eprintln!("run: {:?}", cmd);

        Ok(ZfsSend {
            child: cmd
                .stdout(std::process::Stdio::piped())
                .spawn()?
        })
    }

    // XXX: `set_props` would ideally take an iterator over things that are &str like
    // 
    // note: `lzc_receive()` uses bools for `force` and `raw`, and has no other flags. It then has
    // a seperate `lzc_receive_resumable()` function for resumable (which internally passes another
    // boolean), `lzc_receive_with_reader()` then exposes an additional `resumable` boolean (but
    // also provides a mechanism to pass in a `dmu_replay_record_t` which was read from the `fd`
    // prior to function invocation).
    pub fn recv(&self, snapname: &str, set_props: Vec<(String,String)>, origin: Option<&str>,
        
        exclude_props: Vec<String>, flags: BitFlags<RecvFlags>) ->
        io::Result<ZfsRecv>
    {
        let mut cmd = self.cmd();

        cmd.arg("recv");

        let mut opts = "-".to_owned();

        for flag in flags.iter() {
            match flag {
                RecvFlags::Force => opts.push('F'),
                RecvFlags::Resumeable => opts.push('s'),

                RecvFlags::DiscardFirstName => opts.push('d'),
                RecvFlags::DiscardAllButLastName => opts.push('e'),
                RecvFlags::IgnoreHolds => opts.push('h'),
                RecvFlags::DryRun => opts.push('n'),
                RecvFlags::NoMount => opts.push('u'),
                RecvFlags::Verbose => opts.push('v'),
            }
        }

        cmd
            .arg(opts);

        for set_prop in set_props.into_iter() {
            let mut s = set_prop.0;
            s.push('=');
            s.push_str(&set_prop.1[..]);
            cmd.arg("-o").arg(s);
        }

        for exclude_prop in exclude_props.into_iter() {
            cmd.arg("-x").arg(exclude_prop);
        }

        match origin {
            Some(o) => { cmd.arg("-o").arg(o); },
            None => {},
        }

        cmd.arg(snapname);
        eprintln!("run: {:?}", cmd);

        Ok(ZfsRecv {
            child: cmd
                .stdin(std::process::Stdio::piped())
                .spawn()?,
        })
    }
}

pub struct ZfsSend {
    // note: in the lzc case, this is just a `fd`
    child: std::process::Child,
}

pub struct ZfsRecv {
    // note: in the lzc case, this is just a `fd`
    child: std::process::Child,
}

pub fn send_recv(mut send: ZfsSend, mut recv: ZfsRecv) -> io::Result<u64>
{
    // XXX: It woudl be _really_ nice to be able to consume stderr from both send & recv into our
    // own data to examine. right now we have to guess about the error cause.
    let bytes = std::io::copy(send.child.stdout.as_mut().unwrap(), recv.child.stdin.as_mut().unwrap())?;

    // discard the stdin/stdout we left open
    // (and hope this causes the subprocesses to exit)
    send.child.stdout.take();
    recv.child.stdin.take();

    let ss = send.child.wait()?;
    let rs = recv.child.wait()?;

    if !ss.success() || !rs.success() {
        return Err(io::Error::new(io::ErrorKind::Other,
                           format!("send or recv failed: {:?}, {:?}", ss.code(), rs.code())));
    }

    Ok(bytes)
}

#[derive(EnumFlags,Copy,Clone,Debug,PartialEq,Eq)]
pub enum RecvFlags {
    // correspond to `lzc` booleans/functions
    /// -F
    Force = 1<<0,
    /// -s
    Resumeable = 1<<1,

    // lzc includes a `raw` boolean with no equivelent in the `zfs recv` cmd. It isn't immediately
    // clear how this gets set by `zfs recv`, but it might be by examining the
    // `dmu_replay_record_t`.
    //
    // Raw,

    // No equive in `lzc`
    // These appear to essentially be implimented by
    // examining the `dmu_replay_record_t` and modifying args to `lzc_recieve_with_header()`.
    /// -d
    DiscardFirstName = 1<<2,
    /// -e
    DiscardAllButLastName = 1<<3,

    // `zfs receive` options with no equive in `lzc`.
    //
    // unclear how holds are handled. `zfs send` has a similar mismatch (no flag in `lzc_send()`)
    /// -h
    IgnoreHolds = 1<<4,
    // I really don't know.
    /// -u
    NoMount = 1<<5,


    /// -v
    Verbose = 1<<6,
    /// -n
    DryRun = 1<<7,
}


#[derive(EnumFlags,Copy,Clone,Debug,PartialEq,Eq)]
pub enum SendFlags {
    // correspond to lzc SendFlags
    /// -e
    EmbedData = 1<<0,
    /// -L
    LargeBlock = 1<<1,
    /// -c
    Compressed = 1<<2,
    /// -w
    Raw = 1<<3,

    // these are additional items corresponding to `zfs send` cmd flags
    /// -D
    Dedup = 1<<4,
    /// -I
    IncludeIntermediary = 1<<5,
    /// -h
    IncludeHolds = 1<<6,
    /// -p
    IncludeProps = 1<<7,
    /// -v
    Verbose = 1<<8,
    /// -n
    DryRun = 1<<9,
    /// -P
    Parsable = 1<<10,
    /// -R
    Replicate = 1<<11,
}


// 
// send -t <token>
//  resume send
// send -D
//  dedup. depricated
// send -I <snapshot>
//  send all intermediary snapshots from <snapshot>
// send -L
//  large block
// send -P
//  print machine parsable info
// send -R
//  replicate (send filesystem and all decendent filesystems up to the named snapshot)
// send -e
//  embed (generate a more compact stream)
// send -c
//  compress
// send -w
//  raw
// send -h
//  holds included
// send -n
//  dry run
// send -p
//  props -- include dataset props in stream
// send -v
//  verbose
// send -i <snapshot>
//  generate stream from the first <snapshot> [src] to the second <snapshot> [target]
// 

impl Default for Zfs {
    fn default() -> Self {
        Zfs {
            zfs_cmd: vec![env::var_os("ZFS_CMD").unwrap_or(OsStr::new("zfs").to_owned()).to_str().unwrap().to_owned()],
        }
    }
}