aboutsummaryrefslogtreecommitdiffstats
path: root/zone_zfs/src/file_system.rs
blob: 7c9c6ab9e3e5ec7092a3a783ebc8278f9a44dfa8 (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
use anyhow::{anyhow, Context, Result};
use zone_core::{Container, ContainerStatus};

use std::{
    ffi::{OsStr, OsString},
    fmt::Display,
    path::PathBuf,
    process::{Command, Output},
};

use super::snapshot::Snapshot;

#[derive(Debug)]
pub struct FileSystem {
    pub(crate) value: OsString,
    pub(crate) mountpoint: Option<PathBuf>,
}

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

// pool/000.0/nkollack-1
impl TryFrom<OsString> for FileSystem {
    type Error = anyhow::Error;

    fn try_from(value: OsString) -> Result<Self, Self::Error> {
        Ok(FileSystem {
            value,
            mountpoint: None,
        })
    }
}

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

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        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 From<FileSystem> for Container {
    fn from(file_system: FileSystem) -> Self {
        let path_buf = PathBuf::from(&file_system)
            .file_name()
            .expect("Invalid FileSystem path")
            .to_string_lossy()
            .into_owned();

        let (user, id) = path_buf.rsplit_once("-").expect("Invalid FileSystem name!");

        Container {
            id: id
                .parse()
                .expect("Failed to parse ID from FileSystem name!"),
            template: PathBuf::from(file_system)
                .parent()
                .expect("Base path has no parent!")
                .to_string_lossy()
                .into_owned(),
            user: user.to_string(),
            status: ContainerStatus::default(),
        }
    }
}

impl TryFrom<Output> for FileSystem {
    type Error = anyhow::Error;

    fn try_from(value: Output) -> Result<Self, Self::Error> {
        std::str::from_utf8(&value.stdout)?.try_into()
    }
}

impl FileSystem {
    pub(super) fn get_name(&self) -> Result<String> {
        Ok(PathBuf::from(self.value.clone())
            .file_name()
            .context("Invalid path for filesystem")?
            .to_string_lossy()
            .into_owned())
    }

    pub fn set_quota(&self, quota: &str) -> Result<()> {
        match Command::new("zfs")
            .arg("set")
            .arg(format!("quota={}", quota))
            .arg(&self.value)
            .status()?
            .success()
        {
            true => Ok(()),
            false => Err(anyhow!("Failed to set a quota: {:?}", self)),
        }
    }

    pub(super) fn get_snapshots(&self) -> Result<Vec<Snapshot>> {
        let stdout = Command::new("zfs")
            .arg("list")
            .arg("-H")
            .arg("-o")
            .arg("name")
            .arg("-t")
            .arg("snapshot")
            .arg(self)
            .output()?
            .stdout;

        String::from_utf8(stdout)?
            .split_whitespace()
            .map(|s| s.try_into())
            .collect()
    }

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

    pub(super) fn get_file_systems() -> Result<Vec<FileSystem>> {
        let output = Command::new("zfs")
            .arg("list")
            .arg("-H")
            .arg("-o")
            .arg("name")
            .output()?
            .stdout;

        std::str::from_utf8(&output)?
            .split_whitespace()
            .map(|fs| fs.try_into())
            .collect()
    }
}