aboutsummaryrefslogtreecommitdiffstats
path: root/zone_zfs/src/snapshot.rs
blob: b0fabb9da9c19d4272e73a0fc2d18371c53db308 (plain)
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
use chrono::{DateTime, Utc};
use std::{ffi::OsString, path::PathBuf, process::Command};
use tracing::warn;

use crate::{error::Error, error::Result, file_system::FileSystem, Config};

#[derive(Debug)]
pub struct Snapshot {
    // pool/000.0@00000000000
    pub value: OsString,
    pub file_system: FileSystem,
    pub timestamp: DateTime<Utc>,
}

impl TryFrom<&str> for Snapshot {
    // <file_system>@<timestamp>
    type Error = Error;

    fn try_from(value: &str) -> Result<Self> {
        match value.split('@').collect::<Vec<&str>>()[..] {
            [file_system, name] => Ok(Snapshot {
                file_system: FileSystem::try_from(file_system)?,
                value: file_system.into(),
                timestamp: name.parse().unwrap_or_else(|_err| {
                    warn!(
                        "Failed to parse timestamp from `{}`, using default value.",
                        value
                    );
                    chrono::MIN_DATETIME
                }),
            }),
            _ => Err(Error::Snapshot(format!(
                "Failed to parse snapshot: {:?}",
                value
            ))),
        }
    }
}

impl Snapshot {
    pub fn clone_into_file_system(&self, new_fs: PathBuf) -> Result<FileSystem> {
        let mut file_system = self.file_system.clone();
        file_system.value.push(&new_fs);

        Command::new("zfs")
            .arg("clone")
            .arg(&self.value)
            .arg(&new_fs)
            .status()?
            .success()
            .then(|| file_system)
            .ok_or_else(|| Error::Snapshot(format!("Failed to clone snapshot: {:?}", self)))
    }
}