aboutsummaryrefslogtreecommitdiffstats
path: root/zone_zfs/src/snapshot.rs
blob: 14fafb4a441912dde82104c50da597f936fb1d99 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use chrono::{DateTime, Utc};
use std::{ffi::OsString, path::PathBuf, process::Command};
use tracing::warn;

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

#[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,
        name: String,
        mountpoint: Option<PathBuf>,
    ) -> Result<FileSystem> {
        let new_fs = FileSystem {
            value: PathBuf::from(&self.file_system.value).join(name).into(),
            mountpoint,
        };

        let mut command = Command::new("zfs");

        command.arg("clone");

        if let Some(mp) = &new_fs.mountpoint {
            command
                .arg("-o")
                .arg(format!("mountpoint={}", mp.to_string_lossy()));
        };

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