aboutsummaryrefslogtreecommitdiffstats
path: root/zone_core/src/container.rs
blob: 71dfb7319dc7a08bc2c71b0c2c7546d4994c43f8 (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
use clap::Args;
use derive_builder::Builder;
use serde::{Deserialize, Serialize};
use std::{fmt::Display, path::PathBuf};
use tabled::Tabled;

use crate::FilterContainer;

pub use status::ContainerStatus;

mod status;

#[derive(Debug, PartialEq, Default, Serialize, Deserialize, Builder, Tabled, Clone, Args)]
#[builder(
    name = "ContainerOptions",
    derive(Debug, Serialize, Deserialize),
    field(public)
)]
#[serde(rename_all = "camelCase")]
pub struct Container {
    #[tabled("ID")]
    pub id: u64,

    #[tabled("Template")]
    pub parent: String,

    #[tabled("User")]
    pub user: String,
}

impl Container {
    pub fn builder() -> ContainerOptions {
        ContainerOptions::default()
    }
}

impl Display for Container {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}-{}-{}", self.user, self.parent, self.id)
    }
}

impl From<Container> for String {
    fn from(c: Container) -> Self {
        format!("{}-{}-{}", c.user, c.parent, c.id)
    }
}

impl From<Container> for ContainerOptions {
    fn from(c: Container) -> Self {
        Self {
            id: Some(c.id),
            parent: Some(c.parent),
            user: Some(c.user),
        }
    }
}

impl From<&Container> for &ContainerOptions {
    fn from(c: &Container) -> Self {
        ContainerOptions {
            id: Some(c.id.to_owned()),
            parent: Some(c.parent.to_owned()),
            user: Some(c.user.to_owned()),
        }
        .into()
    }
}

impl From<ContainerOptions> for &ContainerOptions {
    fn from(o: ContainerOptions) -> Self {
        o.into()
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Args)]
pub struct CloneOptions {
    pub template: String,
    pub user: String,
}

impl<T> FilterContainer for T
where
    T: Iterator,
    T::Item: TryInto<Container>,
{
    fn filter_container(&mut self, pred: &ContainerOptions) -> Vec<Container> {
        self.filter_map(|c| -> Option<Container> { c.try_into().ok() })
            .filter(|c| {
                pred.id.map_or(false, |p| p == c.id)
                    && pred.parent.as_ref().map_or(false, |p| p == &c.parent)
                    && pred.user.as_ref().map_or(false, |p| p == &c.user)
            })
            .collect()
    }
}

impl TryFrom<zone_zfs::FileSystem> for Container {
    type Error = zone_zfs::Error;

    fn try_from(fs: zone_zfs::FileSystem) -> zone_zfs::Result<Self> {
        let path_buf = PathBuf::from(fs.dataset())
            .file_name()
            .ok_or_else(|| {
                zone_zfs::Error::FileSystem(format!("Invalid FileSystem path: {:?}", fs))
            })?
            .to_string_lossy()
            .into_owned();

        let (user, id) = path_buf.rsplit_once('-').ok_or_else(|| {
            zone_zfs::Error::FileSystem(format!("Invalid FileSystem name: {:?}", fs))
        })?;

        let id = id.parse::<u64>().map_err(|err| {
            zone_zfs::Error::FileSystem(format!("Failed to parse container ID: {:?}", err))
        })?;

        let template = PathBuf::from(fs.dataset())
            .parent()
            .ok_or_else(|| {
                zone_zfs::Error::FileSystem(format!("Invalid path for filesystem: {:?}", &fs))
            })?
            .to_string_lossy()
            .into_owned();

        Ok(Container {
            id,
            parent: template,
            user: user.to_string(),
        })
    }
}