canic-cli 0.30.4

Operator CLI for Canic fleet backup and restore workflows
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
use canic_backup::{
    journal::JournalResumeReport,
    persistence::{BackupIntegrityReport, BackupLayout, PersistenceError},
};
use std::{
    ffi::OsString,
    fs,
    io::{self, Write},
    path::PathBuf,
};
use thiserror::Error as ThisError;

///
/// BackupCommandError
///

#[derive(Debug, ThisError)]
pub enum BackupCommandError {
    #[error("{0}")]
    Usage(&'static str),

    #[error("missing required option {0}")]
    MissingOption(&'static str),

    #[error("unknown option {0}")]
    UnknownOption(String),

    #[error("option {0} requires a value")]
    MissingValue(&'static str),

    #[error(transparent)]
    Io(#[from] std::io::Error),

    #[error(transparent)]
    Json(#[from] serde_json::Error),

    #[error(transparent)]
    Persistence(#[from] PersistenceError),
}

///
/// BackupVerifyOptions
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BackupVerifyOptions {
    pub dir: PathBuf,
    pub out: Option<PathBuf>,
}

impl BackupVerifyOptions {
    /// Parse backup verification options from CLI arguments.
    pub fn parse<I>(args: I) -> Result<Self, BackupCommandError>
    where
        I: IntoIterator<Item = OsString>,
    {
        let mut dir = None;
        let mut out = None;

        let mut args = args.into_iter();
        while let Some(arg) = args.next() {
            let arg = arg
                .into_string()
                .map_err(|_| BackupCommandError::Usage(usage()))?;
            match arg.as_str() {
                "--dir" => dir = Some(PathBuf::from(next_value(&mut args, "--dir")?)),
                "--out" => out = Some(PathBuf::from(next_value(&mut args, "--out")?)),
                "--help" | "-h" => return Err(BackupCommandError::Usage(usage())),
                _ => return Err(BackupCommandError::UnknownOption(arg)),
            }
        }

        Ok(Self {
            dir: dir.ok_or(BackupCommandError::MissingOption("--dir"))?,
            out,
        })
    }
}

///
/// BackupStatusOptions
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BackupStatusOptions {
    pub dir: PathBuf,
    pub out: Option<PathBuf>,
}

impl BackupStatusOptions {
    /// Parse backup status options from CLI arguments.
    pub fn parse<I>(args: I) -> Result<Self, BackupCommandError>
    where
        I: IntoIterator<Item = OsString>,
    {
        let mut dir = None;
        let mut out = None;

        let mut args = args.into_iter();
        while let Some(arg) = args.next() {
            let arg = arg
                .into_string()
                .map_err(|_| BackupCommandError::Usage(usage()))?;
            match arg.as_str() {
                "--dir" => dir = Some(PathBuf::from(next_value(&mut args, "--dir")?)),
                "--out" => out = Some(PathBuf::from(next_value(&mut args, "--out")?)),
                "--help" | "-h" => return Err(BackupCommandError::Usage(usage())),
                _ => return Err(BackupCommandError::UnknownOption(arg)),
            }
        }

        Ok(Self {
            dir: dir.ok_or(BackupCommandError::MissingOption("--dir"))?,
            out,
        })
    }
}

/// Run a backup subcommand.
pub fn run<I>(args: I) -> Result<(), BackupCommandError>
where
    I: IntoIterator<Item = OsString>,
{
    let mut args = args.into_iter();
    let Some(command) = args.next().and_then(|arg| arg.into_string().ok()) else {
        return Err(BackupCommandError::Usage(usage()));
    };

    match command.as_str() {
        "status" => {
            let options = BackupStatusOptions::parse(args)?;
            let report = backup_status(&options)?;
            write_status_report(&options, &report)?;
            Ok(())
        }
        "verify" => {
            let options = BackupVerifyOptions::parse(args)?;
            let report = verify_backup(&options)?;
            write_report(&options, &report)?;
            Ok(())
        }
        "help" | "--help" | "-h" => Err(BackupCommandError::Usage(usage())),
        _ => Err(BackupCommandError::UnknownOption(command)),
    }
}

/// Summarize a backup journal's resumable state.
pub fn backup_status(
    options: &BackupStatusOptions,
) -> Result<JournalResumeReport, BackupCommandError> {
    let layout = BackupLayout::new(options.dir.clone());
    let journal = layout.read_journal()?;
    Ok(journal.resume_report())
}

/// Verify a backup directory's manifest, journal, and durable artifacts.
pub fn verify_backup(
    options: &BackupVerifyOptions,
) -> Result<BackupIntegrityReport, BackupCommandError> {
    let layout = BackupLayout::new(options.dir.clone());
    layout.verify_integrity().map_err(BackupCommandError::from)
}

// Write the journal status report to stdout or a requested output file.
fn write_status_report(
    options: &BackupStatusOptions,
    report: &JournalResumeReport,
) -> Result<(), BackupCommandError> {
    if let Some(path) = &options.out {
        let data = serde_json::to_vec_pretty(report)?;
        fs::write(path, data)?;
        return Ok(());
    }

    let stdout = io::stdout();
    let mut handle = stdout.lock();
    serde_json::to_writer_pretty(&mut handle, report)?;
    writeln!(handle)?;
    Ok(())
}

// Write the integrity report to stdout or a requested output file.
fn write_report(
    options: &BackupVerifyOptions,
    report: &BackupIntegrityReport,
) -> Result<(), BackupCommandError> {
    if let Some(path) = &options.out {
        let data = serde_json::to_vec_pretty(report)?;
        fs::write(path, data)?;
        return Ok(());
    }

    let stdout = io::stdout();
    let mut handle = stdout.lock();
    serde_json::to_writer_pretty(&mut handle, report)?;
    writeln!(handle)?;
    Ok(())
}

// Read the next required option value.
fn next_value<I>(args: &mut I, option: &'static str) -> Result<String, BackupCommandError>
where
    I: Iterator<Item = OsString>,
{
    args.next()
        .and_then(|value| value.into_string().ok())
        .ok_or(BackupCommandError::MissingValue(option))
}

// Return backup command usage text.
const fn usage() -> &'static str {
    "usage: canic backup status --dir <backup-dir> [--out <file>]\n       canic backup verify --dir <backup-dir> [--out <file>]"
}

#[cfg(test)]
mod tests {
    use super::*;
    use canic_backup::{
        artifacts::ArtifactChecksum,
        journal::{ArtifactJournalEntry, ArtifactState, DownloadJournal},
        manifest::{
            BackupUnit, BackupUnitKind, ConsistencyMode, ConsistencySection, FleetBackupManifest,
            FleetMember, FleetSection, IdentityMode, SourceMetadata, SourceSnapshot, ToolMetadata,
            VerificationCheck, VerificationPlan,
        },
    };
    use std::{
        fs,
        path::Path,
        time::{SystemTime, UNIX_EPOCH},
    };

    const ROOT: &str = "aaaaa-aa";
    const HASH: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    // Ensure backup verification options parse the intended command shape.
    #[test]
    fn parses_backup_verify_options() {
        let options = BackupVerifyOptions::parse([
            OsString::from("--dir"),
            OsString::from("backups/run"),
            OsString::from("--out"),
            OsString::from("report.json"),
        ])
        .expect("parse options");

        assert_eq!(options.dir, PathBuf::from("backups/run"));
        assert_eq!(options.out, Some(PathBuf::from("report.json")));
    }

    // Ensure backup status options parse the intended command shape.
    #[test]
    fn parses_backup_status_options() {
        let options = BackupStatusOptions::parse([
            OsString::from("--dir"),
            OsString::from("backups/run"),
            OsString::from("--out"),
            OsString::from("status.json"),
        ])
        .expect("parse options");

        assert_eq!(options.dir, PathBuf::from("backups/run"));
        assert_eq!(options.out, Some(PathBuf::from("status.json")));
    }

    // Ensure backup status reads the journal and reports resume actions.
    #[test]
    fn backup_status_reads_journal_resume_report() {
        let root = temp_dir("canic-cli-backup-status");
        let layout = BackupLayout::new(root.clone());
        layout
            .write_journal(&journal_with_checksum(HASH.to_string()))
            .expect("write journal");

        let options = BackupStatusOptions {
            dir: root.clone(),
            out: None,
        };
        let report = backup_status(&options).expect("read backup status");

        fs::remove_dir_all(root).expect("remove temp root");
        assert_eq!(report.backup_id, "backup-test");
        assert_eq!(report.total_artifacts, 1);
        assert!(report.is_complete);
        assert_eq!(report.pending_artifacts, 0);
        assert_eq!(report.counts.skip, 1);
    }

    // Ensure the CLI verification path reads a layout and returns an integrity report.
    #[test]
    fn verify_backup_reads_layout_and_artifacts() {
        let root = temp_dir("canic-cli-backup-verify");
        let layout = BackupLayout::new(root.clone());
        let checksum = write_artifact(&root, b"root artifact");

        layout
            .write_manifest(&valid_manifest())
            .expect("write manifest");
        layout
            .write_journal(&journal_with_checksum(checksum.hash.clone()))
            .expect("write journal");

        let options = BackupVerifyOptions {
            dir: root.clone(),
            out: None,
        };
        let report = verify_backup(&options).expect("verify backup");

        fs::remove_dir_all(root).expect("remove temp root");
        assert_eq!(report.backup_id, "backup-test");
        assert!(report.verified);
        assert_eq!(report.durable_artifacts, 1);
        assert_eq!(report.artifacts[0].checksum, checksum.hash);
    }

    // Build one valid manifest for CLI verification tests.
    fn valid_manifest() -> FleetBackupManifest {
        FleetBackupManifest {
            manifest_version: 1,
            backup_id: "backup-test".to_string(),
            created_at: "2026-05-03T00:00:00Z".to_string(),
            tool: ToolMetadata {
                name: "canic".to_string(),
                version: "0.30.3".to_string(),
            },
            source: SourceMetadata {
                environment: "local".to_string(),
                root_canister: ROOT.to_string(),
            },
            consistency: ConsistencySection {
                mode: ConsistencyMode::CrashConsistent,
                backup_units: vec![BackupUnit {
                    unit_id: "fleet".to_string(),
                    kind: BackupUnitKind::SubtreeRooted,
                    roles: vec!["root".to_string()],
                    consistency_reason: None,
                    dependency_closure: Vec::new(),
                    topology_validation: "subtree-closed".to_string(),
                    quiescence_strategy: None,
                }],
            },
            fleet: FleetSection {
                topology_hash_algorithm: "sha256".to_string(),
                topology_hash_input: "sorted(pid,parent_pid,role,module_hash)".to_string(),
                discovery_topology_hash: HASH.to_string(),
                pre_snapshot_topology_hash: HASH.to_string(),
                topology_hash: HASH.to_string(),
                members: vec![fleet_member()],
            },
            verification: VerificationPlan::default(),
        }
    }

    // Build one valid manifest member.
    fn fleet_member() -> FleetMember {
        FleetMember {
            role: "root".to_string(),
            canister_id: ROOT.to_string(),
            parent_canister_id: None,
            subnet_canister_id: Some(ROOT.to_string()),
            controller_hint: None,
            identity_mode: IdentityMode::Fixed,
            restore_group: 1,
            verification_class: "basic".to_string(),
            verification_checks: vec![VerificationCheck {
                kind: "status".to_string(),
                method: None,
                roles: vec!["root".to_string()],
            }],
            source_snapshot: SourceSnapshot {
                snapshot_id: "root-snapshot".to_string(),
                module_hash: None,
                wasm_hash: None,
                code_version: Some("v0.30.3".to_string()),
                artifact_path: "artifacts/root".to_string(),
                checksum_algorithm: "sha256".to_string(),
            },
        }
    }

    // Build one durable journal with a caller-provided checksum.
    fn journal_with_checksum(checksum: String) -> DownloadJournal {
        DownloadJournal {
            journal_version: 1,
            backup_id: "backup-test".to_string(),
            artifacts: vec![ArtifactJournalEntry {
                canister_id: ROOT.to_string(),
                snapshot_id: "root-snapshot".to_string(),
                state: ArtifactState::Durable,
                temp_path: None,
                artifact_path: "artifacts/root".to_string(),
                checksum_algorithm: "sha256".to_string(),
                checksum: Some(checksum),
                updated_at: "2026-05-03T00:00:00Z".to_string(),
            }],
        }
    }

    // Write one artifact at the layout-relative path used by test journals.
    fn write_artifact(root: &Path, bytes: &[u8]) -> ArtifactChecksum {
        let path = root.join("artifacts/root");
        fs::create_dir_all(path.parent().expect("artifact has parent")).expect("create artifacts");
        fs::write(&path, bytes).expect("write artifact");
        ArtifactChecksum::from_bytes(bytes)
    }

    // Build a unique temporary directory.
    fn temp_dir(prefix: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time after epoch")
            .as_nanos();
        std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()))
    }
}