aboutsummaryrefslogtreecommitdiffstats
path: root/zone_core/src/container.rs
blob: 9296fb69e72d0748849ebfbf22fb286df8861139 (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::path::PathBuf;
use tabled::Tabled;

use crate::FilterContainer;

pub use status::ContainerStatus;

mod status;

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

    #[header("Template")]
    pub template: String,

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

    #[header("Status")]
    pub status: ContainerStatus,
}

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

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

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

impl From<WebSocketOptions> for String {
    fn from(val: WebSocketOptions) -> Self {
        format!("{}-{}-{}", val.user, val.template, val.id)
    }
}

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.template.as_ref().map_or(false, |p| p == &c.template)
                    && 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(file_system: zone_zfs::FileSystem) -> zone_zfs::Result<Self> {
        let path_buf = PathBuf::from(file_system.dataset())
            .file_name()
            .ok_or_else(|| {
                zone_zfs::Error::FileSystem(format!("Invalid FileSystem path: {:?}", file_system))
            })?
            .to_string_lossy()
            .into_owned();

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

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

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

        Ok(Container {
            id,
            template,
            user: user.to_string(),
            status: ContainerStatus::default(),
        })
    }
}

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

    fn try_from(value: zone_nspawn::Container) -> zone_nspawn::Result<Self> {
        // user, template, id
        let machine = value.machine.to_string_lossy();
        let v: Vec<&str> = machine.split('-').collect();

        Ok(Container {
            id: v[2].parse().map_err(|err| {
                zone_nspawn::Error::Parsing(format!("Failed to parse container id: {:?}", err))
            })?,
            template: v[1].to_owned(),
            user: v[0].to_owned(),
            status: ContainerStatus::Running,
        })
    }
}