summaryrefslogtreecommitdiff
path: root/src/spec.rs
blob: 2c13af7d7c259fe5c35ab197956f8e972703e479 (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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
use crate::config::Configuration;

use log::debug;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct OneVmInputSpecification {
    #[serde(default)]
    pub ssh_key_files: Option<Vec<PathBuf>>,

    pub rsa_host_key: Option<String>,
    pub rsa_host_cert: Option<String>,
    pub dsa_host_key: Option<String>,
    pub dsa_host_cert: Option<String>,
    pub ecdsa_host_key: Option<String>,
    pub ecdsa_host_cert: Option<String>,
    pub ed25519_host_key: Option<String>,
    pub ed25519_host_cert: Option<String>,

    pub base: Option<PathBuf>,
    pub image: Option<PathBuf>,
    pub image_size_gib: Option<u64>,
    pub memory_mib: Option<u64>,
    pub cpus: Option<u64>,
    pub generate_host_certificate: Option<bool>,
    pub ca_key: Option<PathBuf>,
}

impl OneVmInputSpecification {
    fn ssh_key_files(
        &self,
        config: &Configuration,
        name: &str,
    ) -> Result<Vec<PathBuf>, SpecificationError> {
        get(
            &self.ssh_key_files,
            &config.authorized_keys,
            SpecificationError::NoAuthorizedKeys(name.to_string()),
        )
    }

    fn base_image(
        &self,
        config: &Configuration,
        name: &str,
    ) -> Result<PathBuf, SpecificationError> {
        get(
            &self.base,
            &config.default_base_image,
            SpecificationError::NoBaseImage(name.to_string()),
        )
    }

    fn image(&self, config: &Configuration, name: &str) -> Result<PathBuf, SpecificationError> {
        let default_image = if let Some(dirname) = &config.image_directory {
            Some(dirname.join(format!("{}.qcow2", name)))
        } else {
            None
        };

        get(
            &self.image,
            &default_image,
            SpecificationError::NoBaseImage(name.to_string()),
        )
    }

    fn image_size_gib(
        &self,
        config: &Configuration,
        name: &str,
    ) -> Result<u64, SpecificationError> {
        get(
            &self.image_size_gib,
            &config.default_image_gib,
            SpecificationError::NoBaseImage(name.to_string()),
        )
    }

    fn memory_mib(&self, config: &Configuration, name: &str) -> Result<u64, SpecificationError> {
        get(
            &self.memory_mib,
            &config.default_memory_mib,
            SpecificationError::NoBaseImage(name.to_string()),
        )
    }

    fn cpus(&self, config: &Configuration, name: &str) -> Result<u64, SpecificationError> {
        get(
            &self.cpus,
            &config.default_cpus,
            SpecificationError::NoBaseImage(name.to_string()),
        )
    }
}

fn get<'a, T>(
    input: &'a Option<T>,
    default: &'a Option<T>,
    error: SpecificationError,
) -> Result<T, SpecificationError>
where
    T: Clone,
{
    if let Some(input) = input {
        Ok((*input).clone())
    } else if let Some(default) = default {
        Ok((*default).clone())
    } else {
        Err(error)
    }
}

#[derive(Debug)]
pub struct Specification {
    pub name: String,
    pub ssh_keys: Vec<String>,
    pub rsa_host_key: Option<String>,
    pub rsa_host_cert: Option<String>,
    pub dsa_host_key: Option<String>,
    pub dsa_host_cert: Option<String>,
    pub ecdsa_host_key: Option<String>,
    pub ecdsa_host_cert: Option<String>,
    pub ed25519_host_key: Option<String>,
    pub ed25519_host_cert: Option<String>,

    pub base: PathBuf,
    pub image: PathBuf,
    pub image_size_gib: u64,
    pub memory_mib: u64,
    pub cpus: u64,
    pub generate_host_certificate: bool,
    pub ca_key: Option<PathBuf>,
}

#[derive(Debug, thiserror::Error)]
pub enum SpecificationError {
    #[error("No base image or default base image specified for {0}")]
    NoBaseImage(String),

    #[error("No image filename specified for {0} and no image_directory in configuration")]
    NoImage(String),

    #[error("No image size specified for {0} and no default configured")]
    NoImageSize(String),

    #[error("No memory size specified for {0} and no default configured")]
    NoMemorySize(String),

    #[error("No CPU count specified for {0} and no default configured")]
    NoCpuCount(String),

    #[error("No SSH authorized keys specified for {0} and no default configured")]
    NoAuthorizedKeys(String),

    #[error("Failed to read SSH public key file {0}")]
    SshKeyRead(PathBuf, #[source] std::io::Error),

    #[error(transparent)]
    IoError(#[from] std::io::Error),

    #[error(transparent)]
    FromUtf8Error(#[from] std::string::FromUtf8Error),

    #[error(transparent)]
    YamlError(#[from] serde_yaml::Error),
}

impl Specification {
    pub fn from_file(
        config: &Configuration,
        filename: &Path,
    ) -> Result<Vec<Specification>, SpecificationError> {
        debug!("reading specification from {}", filename.display());
        let spec = fs::read(filename)?;
        let input: HashMap<String, OneVmInputSpecification> = serde_yaml::from_slice(&spec)?;
        debug!("specification as read from file: {:#?}", input);

        let mut machines = vec![];
        for (name, machine) in input.iter() {
            let spec = Specification::one_machine(config, &name, &machine)?;
            debug!("machine with defaults applied: {:#?}", spec);
            machines.push(spec);
        }

        Ok(machines)
    }

    fn one_machine(
        config: &Configuration,
        name: &str,
        input: &OneVmInputSpecification,
    ) -> Result<Specification, SpecificationError> {
        let key_filenames = input.ssh_key_files(config, name)?;
        let ssh_keys = ssh_keys(&key_filenames)?;
        let ca_key = if let Some(filename) = &input.ca_key {
            Some(filename.clone())
        } else {
            config.ca_key.clone()
        };
        let gen_cert = if let Some(v) = &input.generate_host_certificate {
            *v
        } else if let Some(v) = &config.default_generate_host_certificate {
            *v
        } else {
            false
        };

        let spec = Specification {
            name: name.to_string(),
            ssh_keys: ssh_keys,
            rsa_host_key: input.rsa_host_key.clone(),
            rsa_host_cert: input.rsa_host_cert.clone(),
            dsa_host_key: input.dsa_host_key.clone(),
            dsa_host_cert: input.dsa_host_cert.clone(),
            ecdsa_host_key: input.ecdsa_host_key.clone(),
            ecdsa_host_cert: input.ecdsa_host_cert.clone(),
            ed25519_host_key: input.ed25519_host_key.clone(),
            ed25519_host_cert: input.ed25519_host_cert.clone(),
            base: input.base_image(config, name)?,
            image: input.image(config, name)?,
            image_size_gib: input.image_size_gib(config, name)?,
            memory_mib: input.memory_mib(config, name)?,
            cpus: input.cpus(config, name)?,
            generate_host_certificate: gen_cert,
            ca_key: ca_key,
        };

        debug!("specification as with defaults applied: {:#?}", spec);
        Ok(spec)
    }
}

fn ssh_keys(filenames: &[PathBuf]) -> Result<Vec<String>, SpecificationError> {
    let mut keys = vec![];
    for filename in filenames {
        let key = std::fs::read(filename)
            .map_err(|e| SpecificationError::SshKeyRead(filename.to_path_buf(), e))?;
        let key = String::from_utf8(key)?;
        let key = key.strip_suffix("\n").or(Some(&key)).unwrap();
        keys.push(key.to_string());
    }
    Ok(keys)
}