aboutsummaryrefslogtreecommitdiffstats
path: root/zone_nspawn/src/nspawn.rs
blob: 1e22ec102ebc850c8a853fada66663206bc37ef7 (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
use crate::{Config, Container, Error, Result};
use figment::{Figment, Provider};
use std::process::Command;
#[derive(Default, Debug)]
pub struct NSpawn {
    pub config: Config,
}

impl NSpawn {
    pub fn new() -> Result<Self> {
        Self::custom(Config::figment())
    }

    pub fn custom<T: Provider>(provider: T) -> Result<Self> {
        Config::from(Figment::from(provider))
            .map_err(Error::from)
            .map(|config| Self { config })
    }

    /// Uses Command to call to machinectl list -o json
    pub fn get_containers() -> Result<Vec<Container>> {
        Command::new("machinectl")
            .arg("list")
            .args(["-o", "json"])
            .output()
            .map(|o| serde_json::from_slice(o.stdout.as_slice()))?
            .map_err(Error::from)
    }

    pub fn shutdown_container(&self, container: &Container) -> Result<()> {
        Command::new("machinectl")
            .arg("poweroff")
            .arg(&container.machine)
            .status()?
            .success()
            .then(|| ())
            .ok_or_else(|| Error::NSpawn(format!("Failed to shutdown container: {:?}", self)))
    }
}