aboutsummaryrefslogtreecommitdiffstats
path: root/zone_zfs/src/lib.rs
blob: c430cbac7934911a185965d268bc3f30e12eb92e (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
use self::file_system::FileSystem;
use figment::{
    providers::{Env, Format, Serialized, Toml},
    Figment, Metadata, Profile, Provider,
};
use serde::{Deserialize, Serialize};
use std::{io, path::PathBuf, result};

pub mod file_system;

pub mod snapshot;

type Result<T> = result::Result<T, Error>;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("ZFS error")]
    ZFS(String),

    #[error("Snapshot Error: {0:?}")]
    Snapshot(String),

    #[error("File System Error: {0:?}")]
    FileSystem(String),

    #[error("IO Error: Failed to run command")]
    IO(#[from] io::Error),
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Config {
    pub quota: String,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            quota: "16G".to_string(),
        }
    }
}

impl Config {
    pub fn from<T: Provider>(provider: T) -> result::Result<Config, figment::Error> {
        Figment::from(provider).extract()
    }

    pub fn figment() -> Figment {
        Figment::from(Config::default())
            .merge(Toml::file(Env::var_or("ZFS_CONFIG", "ZFS.toml")).nested())
            .merge(Env::prefixed("ZFS_").global())
    }
}

impl Provider for Config {
    fn metadata(&self) -> Metadata {
        Metadata::named("ZFS Config")
    }

    fn data(
        &self,
    ) -> result::Result<figment::value::Map<Profile, figment::value::Dict>, figment::Error> {
        Serialized::defaults(Config::default()).data()
    }
}

pub fn create_file_system(
    base_fs_name: String,
    name: String,
    config: &Config,
) -> Result<FileSystem> {
    let fs = FileSystem::get_file_systems()?
        .into_iter()
        .find_map(|fs| match fs.get_name() {
            Ok(n) if n == base_fs_name => Some(fs),
            _ => None,
        })
        .ok_or_else(|| Error::FileSystem("No ".to_string()))?;

    let snapshot = fs
        .get_latest_snapshot()?
        .ok_or_else(|| Error::Snapshot("No snapshot found".to_string()))?;

    let mut mountpoint = fs.value;
    mountpoint.push(name);

    let cloned_fs = snapshot.clone_into_file_system(
        snapshot.file_system.get_name()?,
        Some(PathBuf::from(mountpoint)),
    )?;

    cloned_fs.set_quota(&config.quota)?;

    Ok(cloned_fs)
}

#[cfg(test)]
mod tests {
    #[test]
    fn zfs_list() {
        use super::*;
        assert!(FileSystem::get_file_systems().is_ok());
    }
}