aboutsummaryrefslogtreecommitdiffstats
path: root/zone_zfs/src/file_system.rs
blob: c9612775f2c94b9d4ea3fb4393b4c794a96d1662 (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
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
use crate::{Error, Result, Snapshot};
use bytesize::ByteSize;
use std::{
    ffi::{OsStr, OsString},
    fmt::Display,
    path::PathBuf,
    process::Command,
};

macro_rules! opt [
    ($name:expr, $value:expr) => ({
        let mut _temp = OsString::new();
        _temp.push($name);
        _temp.push("=");
        _temp.push($value);
        _temp
    })
];

#[derive(Debug, Default, Clone)]
pub struct FileSystem {
    pub(crate) value: OsString,
    mountpoint: PathBuf,
    quota: ByteSize,
}

impl Display for FileSystem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.value.to_string_lossy())
    }
}

impl TryFrom<OsString> for FileSystem {
    type Error = Error;

    fn try_from(value: OsString) -> Result<Self> {
        Ok(FileSystem {
            value,
            ..FileSystem::default()
        })
    }
}

impl TryFrom<&str> for FileSystem {
    type Error = Error;

    fn try_from(value: &str) -> Result<Self> {
        value.try_into()
    }
}

impl AsRef<OsStr> for FileSystem {
    fn as_ref(&self) -> &OsStr {
        self.value.as_ref()
    }
}

impl From<FileSystem> for PathBuf {
    fn from(val: FileSystem) -> Self {
        PathBuf::from(val.value)
    }
}

impl From<FileSystem> for String {
    fn from(val: FileSystem) -> Self {
        val.value.to_string_lossy().to_string()
    }
}

impl FileSystem {
    pub(super) fn set_opt<T, U>(&self, name: T, value: U) -> Result<&Self>
    where
        T: AsRef<OsStr>,
        U: AsRef<OsStr>,
    {
        Command::new("zfs")
            .arg("set")
            .arg(opt!(&name, value))
            .arg(&self.value)
            .status()?
            .success()
            .then(|| self)
            .ok_or_else(|| {
                Error::FileSystem(format!("Failed to set {:?}: {:?}", name.as_ref(), self))
            })
    }

    pub(super) fn set_quota(&mut self, quota: ByteSize) -> Result<Self> {
        self.set_opt("quota", quota.to_string())?;
        self.quota = quota;
        Ok(self.to_owned())
    }

    pub(super) fn set_mountpoint(&mut self, mountpoint: PathBuf) -> Result<Self> {
        self.set_opt("mountpoint", &mountpoint)?;
        self.mountpoint = mountpoint;
        Ok(self.to_owned())
    }

    pub(super) fn get_snapshots(&self) -> Result<Vec<Snapshot>> {
        Command::new("zfs")
            .arg("list")
            .arg("-H")
            .arg("-o")
            .arg("name")
            .arg("-t")
            .arg("snapshot")
            .arg(self)
            .output()
            .map(|o| String::from_utf8(o.stdout))?
            .map_err(Error::from)?
            .split_whitespace()
            .map(Snapshot::try_from)
            .collect()
    }

    pub(super) fn get_latest_snapshot(&self) -> Result<Option<Snapshot>> {
        Ok(self
            .get_snapshots()?
            .into_iter()
            .max_by_key(|s| s.timestamp))
    }

    pub fn mount(&self) -> Result<()> {
        Command::new("zfs")
            .arg("mount")
            .arg(&self.value)
            .status()?
            .success()
            .then(|| ())
            .ok_or_else(|| Error::FileSystem(format!("Failed to mount: {:?}", self)))
    }

    pub fn unmount(&self) -> Result<()> {
        Command::new("zfs")
            .arg("unmount")
            .arg(&self.value)
            .status()?
            .success()
            .then(|| ())
            .ok_or_else(|| Error::FileSystem(format!("Failed to unmount: {:?}", self)))
    }

    pub fn destroy(&self, force: bool) -> Result<()> {
        let mut args: Vec<&OsStr> = Vec::new();
        let f_arg = &OsString::from("-f");
        if force {
            args.push(f_arg);
        }
        args.push(&self.value);

        Command::new("zfs")
            .arg("destroy")
            .args(args)
            .status()?
            .success()
            .then(|| ())
            .ok_or_else(|| Error::FileSystem(format!("Failed to destroy: {:?}", self)))
    }
}