auberge 0.14.11

CLI tool for managing self-hosted infrastructure with Ansible
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
use crate::output;
use crate::playbook_meta::BackupRecipe;
use crate::services::backup::executor::RecipeExecutor;
use crate::services::backup::restic::{self, ResticMessage, parse_restic_message};
use crate::services::progress::{Progress, TerminalProgress};
use crate::services::ssh::SshSession;
use eyre::{Context, Result};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone)]
pub struct SessionOpts {
    pub host_name: String,
    pub dest: PathBuf,
    pub timestamp: String,
    pub parameters: HashMap<String, bool>,
}

#[derive(Debug, Clone)]
pub struct RecipeOutcome {
    pub app: String,
    pub size_bytes: Option<u64>,
    pub error: Option<String>,
}

impl RecipeOutcome {
    pub fn is_success(&self) -> bool {
        self.error.is_none()
    }
}

#[derive(Debug, Clone)]
pub struct CreateOutcome {
    pub results: Vec<RecipeOutcome>,
    pub timestamp: String,
}

impl CreateOutcome {
    pub fn successful_apps(&self) -> Vec<String> {
        self.results
            .iter()
            .filter(|r| r.is_success())
            .map(|r| r.app.clone())
            .collect()
    }

    pub fn failed_apps(&self) -> Vec<(String, String)> {
        self.results
            .iter()
            .filter(|r| !r.is_success())
            .map(|r| (r.app.clone(), r.error.clone().unwrap_or_default()))
            .collect()
    }

    pub fn total_size(&self) -> u64 {
        self.results.iter().filter_map(|r| r.size_bytes).sum()
    }
}

pub struct BackupSession<'a, S: SshSession + ?Sized> {
    ssh: &'a S,
    recipes: Vec<(String, BackupRecipe)>,
    opts: SessionOpts,
}

impl<'a, S: SshSession + ?Sized> BackupSession<'a, S> {
    pub fn new(ssh: &'a S, recipes: Vec<(String, BackupRecipe)>, opts: SessionOpts) -> Self {
        Self { ssh, recipes, opts }
    }

    pub fn create(&self) -> Result<CreateOutcome> {
        let executor = RecipeExecutor::new(self.ssh);
        let mut results = Vec::with_capacity(self.recipes.len());

        for (app_name, recipe) in &self.recipes {
            let app_dir = self
                .opts
                .dest
                .join(&self.opts.host_name)
                .join(&self.opts.timestamp)
                .join(app_name);

            if let Err(e) = fs::create_dir_all(&app_dir) {
                eprintln!("✗ {} backup failed: {}", app_name, e);
                results.push(RecipeOutcome {
                    app: app_name.clone(),
                    size_bytes: None,
                    error: Some(e.to_string()),
                });
                continue;
            }

            let mut progress = make_recipe_progress(app_name);
            let exec_result =
                executor.backup(recipe, &app_dir, &self.opts.parameters, &mut *progress);

            match exec_result {
                Ok(()) => {
                    let size = calculate_dir_size(&app_dir).unwrap_or(0);
                    if !output::is_verbose() {
                        output::success(&format!("{} ({})", app_name, output::format_size(size)));
                    }
                    results.push(RecipeOutcome {
                        app: app_name.clone(),
                        size_bytes: Some(size),
                        error: None,
                    });
                }
                Err(e) => {
                    let _ = fs::remove_dir_all(&app_dir);
                    eprintln!("✗ {} backup failed: {}", app_name, e);
                    results.push(RecipeOutcome {
                        app: app_name.clone(),
                        size_bytes: None,
                        error: Some(e.to_string()),
                    });
                }
            }
        }

        Ok(CreateOutcome {
            results,
            timestamp: self.opts.timestamp.clone(),
        })
    }
}

#[cfg(not(test))]
fn make_recipe_progress(app: &str) -> Box<dyn Progress> {
    Box::new(TerminalProgress::new(&format!("Backing up {}", app)))
}

#[cfg(test)]
fn make_recipe_progress(app: &str) -> Box<dyn Progress> {
    Box::new(TerminalProgress::hidden(&format!("Backing up {}", app)))
}

fn backup_args(backup_dir: &Path, host: &str) -> Vec<std::ffi::OsString> {
    vec![
        "backup".into(),
        "--json".into(),
        "--tag".into(),
        host.into(),
        backup_dir.into(),
    ]
}

fn forget_args(dry_run: bool) -> Vec<&'static str> {
    let mut args = vec![
        "forget",
        "--group-by",
        "tags",
        "--keep-daily",
        "7",
        "--keep-weekly",
        "4",
        "--keep-monthly",
        "12",
        "--prune",
    ];
    if dry_run {
        args.push("--dry-run");
    }
    args
}

pub fn restic_push(
    restic_repo: &str,
    restic_password: &str,
    backup_dir: &Path,
    host: &str,
) -> Result<()> {
    output::info(&format!("Pushing {} to restic", backup_dir.display()));

    let mut progress = TerminalProgress::new("Checking restic repository");
    let snapshots_check = restic::command(restic_repo, restic_password)
        .arg("snapshots")
        .arg("--json")
        .output();

    let needs_init = match snapshots_check {
        Ok(out) => {
            let stderr_text = String::from_utf8_lossy(&out.stderr);
            let lines = output::subprocess_output("restic", &stderr_text);
            if out.status.success() {
                output::clear_subprocess_lines(lines);
                false
            } else if stderr_text.contains("Is there a repository at the following location")
                || stderr_text.contains("unable to open config file")
            {
                output::clear_subprocess_lines(lines);
                true
            } else {
                eyre::bail!("restic snapshots failed: {}", stderr_text.trim());
            }
        }
        Err(_) => eyre::bail!("restic not found. Install restic: https://restic.net"),
    };

    if needs_init {
        progress.task_started("Initializing restic repository");
        let init_output = restic::command(restic_repo, restic_password)
            .arg("init")
            .output()
            .wrap_err("Failed to initialize restic repository")?;
        let stderr_text = String::from_utf8_lossy(&init_output.stderr);
        let lines = output::subprocess_output("restic", &stderr_text);
        if init_output.status.success() {
            output::clear_subprocess_lines(lines);
        }

        if !init_output.status.success() {
            eyre::bail!(
                "Failed to initialize restic repository: {}",
                stderr_text.trim()
            );
        }
    }

    progress.task_started(&format!("Pushing {}", backup_dir.display()));
    let mut snapshot_id: Option<String> = None;

    let result = output::stream_command_stdout(
        "restic",
        restic::command(restic_repo, restic_password).args(backup_args(backup_dir, host)),
        |line| match parse_restic_message(line) {
            Some(ResticMessage::Status(s)) => {
                if let (Some(total), Some(done)) = (s.total_bytes, s.bytes_done) {
                    progress.set_total(Some(total));
                    progress.bytes_transferred(done);
                } else {
                    progress.set_total(Some(100));
                    progress.bytes_transferred((s.percent_done * 100.0) as u64);
                }
            }
            Some(ResticMessage::Summary(s)) => {
                snapshot_id = Some(s.snapshot_id);
            }
            // restic reports failures on stderr, surfaced via `result.status` below.
            Some(ResticMessage::ExitError(_)) | None => {}
        },
    )
    .wrap_err("Failed to run restic backup")?;

    progress.task_done();

    if !result.status.success() {
        if result.last_stderr.is_empty() {
            eyre::bail!("restic backup failed");
        } else {
            eyre::bail!("restic backup failed: {}", result.last_stderr.trim());
        }
    }

    match snapshot_id {
        Some(id) => output::success(&format!("Push complete: snapshot {}", id)),
        None => output::success("Push complete"),
    };

    Ok(())
}

pub fn restic_prune(restic_repo: &str, restic_password: &str, dry_run: bool) -> Result<()> {
    let mut progress = TerminalProgress::new("Pruning restic snapshots");

    let mut cmd = restic::command(restic_repo, restic_password);
    cmd.args(forget_args(dry_run));

    let prune_output = cmd.output().wrap_err("Failed to run restic forget")?;

    progress.task_done();

    let stderr_text = String::from_utf8_lossy(&prune_output.stderr);
    let lines = output::subprocess_output("restic", &stderr_text);
    if prune_output.status.success() {
        output::clear_subprocess_lines(lines);
    }

    if !prune_output.status.success() {
        eyre::bail!("restic prune failed: {}", stderr_text.trim());
    }

    let stdout = String::from_utf8_lossy(&prune_output.stdout);
    if !stdout.is_empty() {
        eprintln!("{}", stdout.trim());
    }

    if dry_run {
        output::info("Dry run completed (no changes made)");
    } else {
        output::success("Prune complete");
    }

    Ok(())
}

fn calculate_dir_size(path: &Path) -> Result<u64> {
    let mut total = 0u64;

    if path.is_file() {
        return Ok(path.metadata()?.len());
    }

    if path.is_dir() {
        for entry in fs::read_dir(path)? {
            let entry = entry?;
            let metadata = entry.metadata()?;

            if metadata.is_file() {
                total += metadata.len();
            } else if metadata.is_dir() {
                total += calculate_dir_size(&entry.path())?;
            }
        }
    }

    Ok(total)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::playbook_meta::DbRecipe;
    use crate::services::ssh::{MockSshSession, SshOp};

    fn baikal_recipe() -> BackupRecipe {
        BackupRecipe {
            systemd_services: vec![],
            paths: vec!["/opt/baikal/Specific".to_string()],
            owner: Some(("baikal".to_string(), "baikal".to_string())),
            db: None,
            post_restore_command: None,
            parameters: HashMap::new(),
        }
    }

    fn bichon_recipe() -> BackupRecipe {
        BackupRecipe {
            systemd_services: vec!["bichon".to_string()],
            paths: vec!["/opt/bichon/data".to_string()],
            owner: None,
            db: None,
            post_restore_command: None,
            parameters: HashMap::new(),
        }
    }

    fn paperless_recipe() -> BackupRecipe {
        BackupRecipe {
            systemd_services: vec!["paperless-webserver".to_string()],
            paths: vec!["/opt/paperless/data".to_string()],
            owner: Some(("paperless".to_string(), "paperless".to_string())),
            db: Some(DbRecipe {
                name: "paperless".to_string(),
                dump_path: "/tmp/paperless_db.dump".to_string(),
            }),
            post_restore_command: None,
            parameters: HashMap::new(),
        }
    }

    fn opts(dest: &Path) -> SessionOpts {
        SessionOpts {
            host_name: "myserver".to_string(),
            dest: dest.to_path_buf(),
            timestamp: "2026-04-28_03-00-00".to_string(),
            parameters: HashMap::new(),
        }
    }

    #[test]
    fn backup_args_tags_snapshot_with_host() {
        let args = backup_args(
            Path::new("/backups/myserver/2026-04-28_03-00-00"),
            "myserver",
        );

        let tag_pos = args.iter().position(|a| a == "--tag").unwrap();
        assert_eq!(args[tag_pos + 1], "myserver");
        assert_eq!(
            args.last().unwrap(),
            &std::ffi::OsString::from("/backups/myserver/2026-04-28_03-00-00")
        );
    }

    #[test]
    fn forget_args_group_by_tags_so_retention_spans_snapshots() {
        let args = forget_args(false);

        assert!(args.windows(2).any(|w| w == ["--group-by", "tags"]));
        assert!(args.windows(2).any(|w| w == ["--keep-daily", "7"]));
        assert!(args.contains(&"--prune"));
        assert!(!args.contains(&"--dry-run"));
    }

    #[test]
    fn forget_args_dry_run_appends_flag() {
        assert!(forget_args(true).contains(&"--dry-run"));
    }

    #[test]
    fn create_runs_recipes_in_order() {
        let tmp = tempfile::tempdir().unwrap();
        let mock = MockSshSession::new();
        let recipes = vec![
            ("baikal".to_string(), baikal_recipe()),
            ("bichon".to_string(), bichon_recipe()),
        ];
        let session = BackupSession::new(&mock, recipes, opts(tmp.path()));

        let outcome = session.create().unwrap();

        assert_eq!(outcome.results.len(), 2);
        assert_eq!(outcome.results[0].app, "baikal");
        assert_eq!(outcome.results[1].app, "bichon");
        assert!(outcome.results.iter().all(RecipeOutcome::is_success));

        let calls = mock.calls();
        let baikal_rsync = calls.iter().position(
            |c| matches!(c, SshOp::RsyncFrom { remote, .. } if remote == "/opt/baikal/Specific"),
        );
        let bichon_stop = calls.iter().position(|c| {
            matches!(
                c,
                SshOp::Systemctl { action, service }
                if action == "stop" && service == "bichon"
            )
        });
        assert!(baikal_rsync.is_some());
        assert!(bichon_stop.is_some());
        assert!(baikal_rsync.unwrap() < bichon_stop.unwrap());
    }

    #[test]
    fn create_creates_per_app_dest_directories() {
        let tmp = tempfile::tempdir().unwrap();
        let mock = MockSshSession::new();
        let recipes = vec![
            ("baikal".to_string(), baikal_recipe()),
            ("bichon".to_string(), bichon_recipe()),
        ];
        let session = BackupSession::new(&mock, recipes, opts(tmp.path()));

        session.create().unwrap();

        let baikal_dir = tmp
            .path()
            .join("myserver")
            .join("2026-04-28_03-00-00")
            .join("baikal");
        let bichon_dir = tmp
            .path()
            .join("myserver")
            .join("2026-04-28_03-00-00")
            .join("bichon");
        assert!(baikal_dir.is_dir());
        assert!(bichon_dir.is_dir());
    }

    #[test]
    fn create_does_not_abort_on_recipe_failure() {
        let tmp = tempfile::tempdir().unwrap();
        let mock = MockSshSession::new();
        // Stage a failure for paperless's pg_dump (the first run() call).
        mock.stage_run_result(crate::services::ssh::CommandResult {
            success: false,
            exit_code: Some(1),
            stdout: Vec::new(),
            stderr: b"connection refused".to_vec(),
        });

        let recipes = vec![
            ("paperless".to_string(), paperless_recipe()),
            ("baikal".to_string(), baikal_recipe()),
        ];
        let session = BackupSession::new(&mock, recipes, opts(tmp.path()));

        let outcome = session.create().unwrap();

        assert_eq!(outcome.results.len(), 2);
        let paperless = outcome
            .results
            .iter()
            .find(|r| r.app == "paperless")
            .unwrap();
        let baikal = outcome.results.iter().find(|r| r.app == "baikal").unwrap();
        assert!(!paperless.is_success());
        assert!(baikal.is_success());

        // Ensure the failed recipe's dest dir was cleaned up.
        let paperless_dir = tmp
            .path()
            .join("myserver")
            .join("2026-04-28_03-00-00")
            .join("paperless");
        assert!(!paperless_dir.exists());
    }

    #[test]
    fn create_outcome_helpers_partition_results() {
        let outcome = CreateOutcome {
            timestamp: "2026-04-28_03-00-00".to_string(),
            results: vec![
                RecipeOutcome {
                    app: "baikal".to_string(),
                    size_bytes: Some(1024),
                    error: None,
                },
                RecipeOutcome {
                    app: "bichon".to_string(),
                    size_bytes: None,
                    error: Some("oops".to_string()),
                },
                RecipeOutcome {
                    app: "freshrss".to_string(),
                    size_bytes: Some(2048),
                    error: None,
                },
            ],
        };

        assert_eq!(
            outcome.successful_apps(),
            vec!["baikal".to_string(), "freshrss".to_string()]
        );
        assert_eq!(
            outcome.failed_apps(),
            vec![("bichon".to_string(), "oops".to_string())]
        );
        assert_eq!(outcome.total_size(), 3072);
    }

    #[test]
    fn create_handles_empty_recipe_list() {
        let tmp = tempfile::tempdir().unwrap();
        let mock = MockSshSession::new();
        let session = BackupSession::new(&mock, vec![], opts(tmp.path()));

        let outcome = session.create().unwrap();

        assert!(outcome.results.is_empty());
        assert_eq!(outcome.timestamp, "2026-04-28_03-00-00");
        assert!(mock.calls().is_empty());
    }

    #[test]
    fn create_passes_parameters_to_executor() {
        let tmp = tempfile::tempdir().unwrap();
        let mock = MockSshSession::new();

        let mut params = HashMap::new();
        params.insert(
            "include_music".to_string(),
            crate::playbook_meta::BackupParameter {
                default: false,
                adds_paths: vec!["/srv/music".to_string()],
            },
        );
        let navidrome = BackupRecipe {
            systemd_services: vec!["navidrome".to_string()],
            paths: vec!["/var/lib/navidrome".to_string()],
            owner: None,
            db: None,
            post_restore_command: None,
            parameters: params,
        };

        let mut session_params = HashMap::new();
        session_params.insert("include_music".to_string(), true);

        let opts_with_param = SessionOpts {
            host_name: "myserver".to_string(),
            dest: tmp.path().to_path_buf(),
            timestamp: "2026-04-28_03-00-00".to_string(),
            parameters: session_params,
        };

        let session = BackupSession::new(
            &mock,
            vec![("navidrome".to_string(), navidrome)],
            opts_with_param,
        );
        session.create().unwrap();

        let rsync_remotes: Vec<String> = mock
            .calls()
            .iter()
            .filter_map(|c| match c {
                SshOp::RsyncFrom { remote, .. } => Some(remote.clone()),
                _ => None,
            })
            .collect();
        assert!(rsync_remotes.contains(&"/srv/music".to_string()));
    }
}