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

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

#[derive(Debug, Default, Clone, Builder)]
#[builder(
    build_fn(private, name = "build_file_system"),
    derive(Debug),
    setter(into),
    default
)]
pub struct FileSystem {
    dataset: PathBuf,
    mountpoint: PathBuf,
    quota: ByteSize,
}

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

impl FileSystemBuilder {
    pub fn build(&self) -> Result<FileSystem> {
        self.build_file_system()?.create()
    }

    pub fn build_from(&self, snapshot: &Snapshot) -> Result<FileSystem> {
        self.build_file_system()?.create_from(snapshot)
    }

    pub(crate) fn to_file_system(&self) -> Result<FileSystem> {
        self.build_file_system().map_err(Error::from)
    }
}

impl FileSystem {
    pub fn builder() -> FileSystemBuilder {
        FileSystemBuilder::default()
    }

    /// Get a reference to the file system's dataset.
    pub fn dataset(&self) -> &PathBuf {
        &self.dataset
    }

    /// Get a reference to the file system's mountpoint.
    pub fn mountpoint(&self) -> &PathBuf {
        &self.mountpoint
    }

    /// Get the file system's quota.
    pub fn quota(&self) -> ByteSize {
        self.quota
    }

    /// Get the value of the file system's `option` from ZFS
    pub fn get_opt<T>(&self, option: T) -> Result<OsString>
    where
        T: AsRef<OsStr>,
    {
        Command::new("zfs")
            .arg("get")
            .arg("-H")
            .arg("-o")
            .arg("value,source")
            .arg(&option)
            .arg(&self.dataset)
            .output()
            .map(|o| String::from_utf8(o.stdout))?
            .map(OsString::from)
            .map_err(Error::from)
    }

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

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

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

    pub fn get_mountpoint(&self) -> PathBuf {
        self.mountpoint.to_owned()
    }

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

    #[cfg(feature = "chrono")]
    pub fn get_latest_snapshot(&self) -> Result<Option<Snapshot>> {
        self.get_snapshots()
            .map(|v| v.into_iter().max_by_key(Snapshot::timestamp))
    }

    pub(crate) fn create(&self) -> Result<Self> {
        Command::new("zfs")
            .arg("create")
            .arg("-o")
            .arg(concat_opt!("mountpoint=", &self.mountpoint))
            .arg(concat_opt!("quota=", self.quota.to_string()))
            .status()?
            .success()
            .then(|| self.to_owned())
            .ok_or_else(|| Error::FileSystem(format!("Failed to create file system: {:?}", self)))
    }

    pub(crate) fn create_from(&self, snapshot: &Snapshot) -> Result<Self> {
        Command::new("zfs")
            .arg("clone")
            .arg(&snapshot.name())
            .arg(&self.dataset)
            .status()?
            .success()
            .then(|| self.to_owned())
            .ok_or_else(|| Error::Snapshot(format!("Failed to clone snapshot: {:?}", self)))
    }

    pub fn destroy(&self, force: bool) -> Result<()> {
        let args = if force {
            vec!["destroy", "-f"]
        } else {
            vec!["destroy"]
        };

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

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