zrb 0.1.1

Incremental ZFS snapshot replication over SSH with resumable transfers and retention-based pruning
Documentation
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
use std::path::PathBuf;
use std::process;

use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use sd_notify::NotifyState;

use zrb::{config, ops};

#[derive(ValueEnum, Clone)]
enum ShellChoice {
    Bash,
    Zsh,
    Fish,
    Nushell,
    Elvish,
}

#[derive(Parser)]
#[command(name = "zrb", about = "ZFS remote backup tool")]
struct Cli {
    /// Enable debug logging.
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Override the default config file path.
    #[arg(long, global = true, value_name = "PATH")]
    config: Option<PathBuf>,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a zrb-managed snapshot of one or more datasets.
    Snapshot {
        /// Datasets to snapshot (e.g. tank/home).
        #[arg(required = true)]
        datasets: Vec<String>,
    },

    /// List zrb-managed snapshots. Omit DATASET to list all datasets.
    List {
        /// Dataset to inspect (omit to list all).
        dataset: Option<String>,

        /// Also list child datasets. Without DATASET, lists all datasets.
        #[arg(long, short = 'r')]
        recursive: bool,
    },

    /// Send snapshots to one or more configured Remotes.
    Send {
        /// Datasets to send (e.g. tank/home tank/documents).
        #[arg(required = true)]
        datasets: Vec<String>,

        /// Restrict send to a named Remote (repeatable).
        #[arg(long = "remote")]
        remotes: Vec<String>,

        /// Resume an interrupted transfer without creating a new snapshot.
        /// Errors if the newest local snapshot is already present on the Remote.
        #[arg(long)]
        resume: bool,
    },

    /// Prune zrb-managed snapshots according to the Retention Policy.
    Prune {
        /// Dataset to prune (mutually exclusive with --all).
        #[arg(conflicts_with = "all", required_unless_present = "all")]
        dataset: Option<String>,

        /// Prune all datasets that have zrb-managed snapshots.
        #[arg(long, conflicts_with = "dataset", conflicts_with = "recursive")]
        all: bool,

        /// Also prune child datasets. Requires DATASET.
        #[arg(long, short = 'r', conflicts_with = "all", requires = "dataset")]
        recursive: bool,
    },

    /// Run in server mode (invoked via SSH `ForceCommand`).
    Server {
        /// Permitted client name(s) for this SSH key (repeatable).
        #[arg(long = "client", required = true)]
        clients: Vec<String>,
    },

    #[command(hide = true)]
    Completions {
        shell: ShellChoice,
    },

    #[command(hide = true)]
    Man,
}

fn validate_dataset(ds: &str) -> anyhow::Result<()> {
    if ds.starts_with('/') {
        anyhow::bail!("invalid dataset \"{ds}\": ZFS dataset paths must not start with \"/\"");
    }
    Ok(())
}

fn xdg_config_home() -> PathBuf {
    std::env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
        .unwrap_or_else(|| PathBuf::from(".config"))
}

fn default_source_config() -> PathBuf {
    xdg_config_home().join("zrb/config.toml")
}

fn default_server_config() -> PathBuf {
    xdg_config_home().join("zrb/server.toml")
}

fn print_grouped(groups: &[(String, Vec<String>)]) {
    for (i, (dataset, snaps)) in groups.iter().enumerate() {
        if i > 0 {
            println!();
        }
        println!("{dataset}");
        for s in snaps {
            println!("  {s}");
        }
    }
}

#[allow(clippy::too_many_lines)]
fn run() -> anyhow::Result<()> {
    let cli = Cli::parse();

    let log_level = if cli.verbose { "debug" } else { "info" };
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(log_level)).init();

    match cli.command {
        Commands::Snapshot { datasets } => {
            for ds in &datasets {
                validate_dataset(ds)?;
            }
            let cfg_path = cli.config.unwrap_or_else(default_source_config);
            let cfg = config::load_source(&cfg_path)?;
            for ds in &datasets {
                let name = ops::snapshot::snapshot(ds, &cfg)?;
                log::info!("created {name}");
            }
        }

        Commands::List { dataset, recursive } => {
            if let Some(ds) = &dataset {
                validate_dataset(ds)?;
            }
            let groups: Vec<(String, Vec<String>)> = match dataset.as_deref() {
                None => ops::list::list_all()?,
                Some(ds) if recursive => ops::list::list_recursive(ds)?,
                Some(ds) => vec![(ds.to_owned(), ops::list::list(ds)?)],
            };
            print_grouped(&groups);
        }

        Commands::Send { datasets, remotes, resume } => {
            for ds in &datasets {
                validate_dataset(ds)?;
            }
            let cfg_path = cli.config.unwrap_or_else(default_source_config);
            let cfg = config::load_source(&cfg_path)?;
            let _ = sd_notify::notify(&[NotifyState::Ready]);
            let ds_refs: Vec<&str> = datasets.iter().map(String::as_str).collect();
            let filter: Option<Vec<&str>> = if remotes.is_empty() {
                None
            } else {
                Some(remotes.iter().map(String::as_str).collect())
            };
            if resume {
                ops::send::send_resume(&ds_refs, filter.as_deref(), &cfg)?;
            } else {
                ops::send::send(&ds_refs, filter.as_deref(), &cfg)?;
            }
            let _ = sd_notify::notify(&[NotifyState::Stopping]);
        }

        Commands::Prune { dataset, all, recursive } => {
            if let Some(ds) = &dataset {
                validate_dataset(ds)?;
            }
            let cfg_path = cli.config.unwrap_or_else(default_source_config);
            // Server config takes priority: the remote runs `zrb prune` with
            // `--config server.toml`, which has `resume_hold_days`.
            let (retention, hold_days) = config::load_server(&cfg_path)
                .map(|c| {
                    let days = c.resume_hold_days();
                    (c.retention, Some(days))
                })
                .or_else(|_| config::load_source(&cfg_path).map(|c| (c.retention, None)))?;
            if all {
                let results = ops::prune::prune_all(&retention, hold_days)?;
                for (ds, result) in &results {
                    log::info!(
                        "pruned {}: kept {}, deleted {}",
                        ds,
                        result.kept.len(),
                        result.deleted.len()
                    );
                    for s in &result.deleted {
                        log::debug!("deleted {s}");
                    }
                }
            } else {
                let dataset = dataset.expect("required_unless_present = all");
                let results = if recursive {
                    ops::prune::prune_recursive(&dataset, &retention, hold_days)?
                } else {
                    let result = ops::prune::prune(&dataset, &retention, hold_days)?;
                    vec![(dataset, result)]
                };
                for (ds, result) in &results {
                    log::info!(
                        "pruned {}: kept {}, deleted {}",
                        ds,
                        result.kept.len(),
                        result.deleted.len()
                    );
                    for s in &result.deleted {
                        log::debug!("deleted {s}");
                    }
                }
            }
        }

        Commands::Server { clients } => {
            let cfg_path = cli.config.unwrap_or_else(default_server_config);
            let cfg = config::load_server(&cfg_path)?;
            ops::server::server(&cfg, &clients)?;
        }

        Commands::Completions { shell } => {
            let mut cmd = Cli::command();
            let name = cmd.get_name().to_owned();
            let stdout = &mut std::io::stdout();
            match shell {
                ShellChoice::Bash => clap_complete::generate(clap_complete::Shell::Bash, &mut cmd, name, stdout),
                ShellChoice::Zsh => clap_complete::generate(clap_complete::Shell::Zsh, &mut cmd, name, stdout),
                ShellChoice::Fish => clap_complete::generate(clap_complete::Shell::Fish, &mut cmd, name, stdout),
                ShellChoice::Elvish => clap_complete::generate(clap_complete::Shell::Elvish, &mut cmd, name, stdout),
                ShellChoice::Nushell => clap_complete::generate(clap_complete_nushell::Nushell, &mut cmd, name, stdout),
            }
        }

        Commands::Man => {
            let cmd = Cli::command();
            let man = clap_mangen::Man::new(cmd);
            let mut buf = Vec::new();
            man.render(&mut buf)?;
            std::io::Write::write_all(&mut std::io::stdout(), &buf)?;
        }
    }

    Ok(())
}

fn main() {
    if let Err(e) = run() {
        eprintln!("error: {e:#}");
        process::exit(1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn generate(shell: clap_complete::Shell) -> Vec<u8> {
        let mut cmd = Cli::command();
        let name = cmd.get_name().to_owned();
        let mut buf = Vec::new();
        clap_complete::generate(shell, &mut cmd, name, &mut buf);
        buf
    }

    fn generate_nushell() -> Vec<u8> {
        let mut cmd = Cli::command();
        let name = cmd.get_name().to_owned();
        let mut buf = Vec::new();
        clap_complete::generate(clap_complete_nushell::Nushell, &mut cmd, name, &mut buf);
        buf
    }

    #[test]
    fn completions_bash_non_empty() {
        assert!(!generate(clap_complete::Shell::Bash).is_empty());
    }

    #[test]
    fn completions_zsh_non_empty() {
        assert!(!generate(clap_complete::Shell::Zsh).is_empty());
    }

    #[test]
    fn completions_fish_non_empty() {
        assert!(!generate(clap_complete::Shell::Fish).is_empty());
    }

    #[test]
    fn completions_nushell_non_empty() {
        assert!(!generate_nushell().is_empty());
    }

    #[test]
    fn completions_elvish_non_empty() {
        assert!(!generate(clap_complete::Shell::Elvish).is_empty());
    }

    #[test]
    fn send_resume_flag_parses() {
        let cli = Cli::try_parse_from(["zrb", "send", "--resume", "tank/home"]);
        assert!(cli.is_ok(), "zrb send --resume <dataset> should parse");
        if let Ok(Cli { command: Commands::Send { resume, .. }, .. }) = cli {
            assert!(resume, "--resume should be true");
        }
    }

    #[test]
    fn send_resume_flag_absent_defaults_false() {
        let cli = Cli::try_parse_from(["zrb", "send", "tank/home"]).unwrap();
        if let Commands::Send { resume, .. } = cli.command {
            assert!(!resume, "--resume should default to false");
        }
    }

    #[test]
    fn prune_all_flag_parses() {
        let cli = Cli::try_parse_from(["zrb", "prune", "--all"]);
        assert!(cli.is_ok(), "zrb prune --all should parse successfully");
    }

    #[test]
    fn prune_dataset_alone_parses() {
        let cli = Cli::try_parse_from(["zrb", "prune", "tank/home"]);
        assert!(cli.is_ok(), "zrb prune <dataset> should still parse successfully");
    }

    #[test]
    fn prune_no_args_errors() {
        let cli = Cli::try_parse_from(["zrb", "prune"]);
        assert!(cli.is_err(), "zrb prune with no args should be a CLI error");
    }

    #[test]
    fn prune_dataset_and_all_conflict() {
        let cli = Cli::try_parse_from(["zrb", "prune", "tank/home", "--all"]);
        assert!(cli.is_err(), "zrb prune <dataset> --all should be a CLI error");
    }

    #[test]
    fn list_no_args_parses() {
        let cli = Cli::try_parse_from(["zrb", "list"]);
        assert!(cli.is_ok(), "zrb list with no args should parse");
        if let Ok(Cli { command: Commands::List { dataset, recursive }, .. }) = cli {
            assert!(dataset.is_none());
            assert!(!recursive);
        }
    }

    #[test]
    fn list_with_dataset_parses() {
        let cli = Cli::try_parse_from(["zrb", "list", "tank/home"]).unwrap();
        if let Commands::List { dataset, recursive } = cli.command {
            assert_eq!(dataset.as_deref(), Some("tank/home"));
            assert!(!recursive);
        }
    }

    #[test]
    fn list_recursive_with_dataset_parses() {
        let cli = Cli::try_parse_from(["zrb", "list", "tank", "--recursive"]).unwrap();
        if let Commands::List { dataset, recursive } = cli.command {
            assert_eq!(dataset.as_deref(), Some("tank"));
            assert!(recursive);
        }
    }

    #[test]
    fn list_recursive_short_flag_parses() {
        let cli = Cli::try_parse_from(["zrb", "list", "tank", "-r"]).unwrap();
        if let Commands::List { recursive, .. } = cli.command {
            assert!(recursive);
        }
    }

    #[test]
    fn list_recursive_without_dataset_parses() {
        let cli = Cli::try_parse_from(["zrb", "list", "--recursive"]);
        assert!(cli.is_ok(), "zrb list --recursive with no dataset should parse");
    }

    #[test]
    fn prune_recursive_with_dataset_parses() {
        let cli = Cli::try_parse_from(["zrb", "prune", "tank", "--recursive"]).unwrap();
        if let Commands::Prune { dataset, recursive, all } = cli.command {
            assert_eq!(dataset.as_deref(), Some("tank"));
            assert!(recursive);
            assert!(!all);
        }
    }

    #[test]
    fn prune_recursive_short_flag_parses() {
        let cli = Cli::try_parse_from(["zrb", "prune", "tank", "-r"]).unwrap();
        if let Commands::Prune { recursive, .. } = cli.command {
            assert!(recursive);
        }
    }

    #[test]
    fn prune_recursive_without_dataset_errors() {
        let cli = Cli::try_parse_from(["zrb", "prune", "--recursive"]);
        assert!(cli.is_err(), "zrb prune --recursive without a dataset should be a CLI error");
    }

    #[test]
    fn prune_recursive_and_all_conflict() {
        let cli = Cli::try_parse_from(["zrb", "prune", "--all", "--recursive"]);
        assert!(cli.is_err(), "zrb prune --all --recursive should be a CLI error");
    }

    #[test]
    fn validate_dataset_rejects_absolute_path() {
        let err = validate_dataset("/something").unwrap_err();
        assert!(err.to_string().contains("/something"));
    }

    #[test]
    fn validate_dataset_accepts_pool_slash_dataset() {
        assert!(validate_dataset("tank/home").is_ok());
    }

    #[test]
    fn validate_dataset_accepts_bare_pool() {
        assert!(validate_dataset("tank").is_ok());
    }

    #[test]
    fn man_page_contains_th_header() {
        let cmd = Cli::command();
        let man = clap_mangen::Man::new(cmd);
        let mut buf = Vec::new();
        man.render(&mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();
        assert!(s.contains(".TH"), "man page should contain .TH roff header");
    }
}