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
use crate::{launcher, storage::SystemdStorage};
use anyhow::{anyhow, Result};
use serde::Serialize;
use tinytemplate::TinyTemplate;

const EMU_DEFAULT_PATH: &str = "/bin/emu";

const SYSTEMD_UNIT: &str = "
[Unit]
Description=Virtual Machine: {vm_name}

[Service]
Type=simple
ExecStart={command} {{for value in args}}{value} {{ endfor }}
TimeoutStopSec=30
ExecStop={emu_path} shutdown {vm_name}
KillSignal=SIGCONT
FinalKillSignal=SIGKILL

[Install]
WantedBy=default.target
";

#[derive(Serialize)]
pub struct Data {
    vm_name: String,
    command: String,
    args: Vec<String>,
    emu_path: String,
}

impl Data {
    pub fn new(vm_name: String, command: String, args: Vec<String>) -> Self {
        Self {
            vm_name,
            command,
            args,
            emu_path: match std::env::current_exe() {
                Ok(path) => path.to_str().unwrap().to_string(),
                Err(_) => EMU_DEFAULT_PATH.to_string(),
            },
        }
    }
}

pub struct Systemd {
    emu: Box<dyn launcher::Emulator>,
    systemd_storage: SystemdStorage,
}

impl Systemd {
    pub fn new(emu: Box<dyn launcher::Emulator>, systemd_storage: SystemdStorage) -> Self {
        Self {
            emu,
            systemd_storage,
        }
    }

    fn template(&self, vm_name: &str, rc: &launcher::RuntimeConfig) -> Result<String> {
        let mut t = TinyTemplate::new();
        t.add_template("systemd", SYSTEMD_UNIT)?;
        let args = self.emu.args(vm_name, rc)?;

        let data = Data::new(vm_name.to_string(), self.emu.bin()?, args);
        match t.render("systemd", &data) {
            Ok(x) => Ok(x),
            Err(e) => Err(anyhow!(e)),
        }
    }

    pub fn write(&self, vm_name: &str, rc: &launcher::RuntimeConfig) -> Result<()> {
        let path = self.systemd_storage.service_filename(vm_name)?;
        let template = self.template(vm_name, rc)?;

        match std::fs::write(path, template) {
            Ok(_) => Ok(()),
            Err(e) => Err(anyhow!(e)),
        }
    }
}