summaryrefslogtreecommitdiff
path: root/src/spec.rs
blob: 4bd0bb927d403fa3635d32fd553bfd1ba02a5ec1 (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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
//! Virtual machine specification.

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)
    }
}

/// Effective virtual machine specification.
///
/// This is the specification as read from the input file, with the
/// defaults from the configuration file already applied.
#[derive(Debug)]
pub struct Specification {
    /// Name of new virtual machine to create.
    pub name: String,

    /// SSH public keys to install in the default user's `authorized_keys` file.
    pub ssh_keys: Vec<String>,

    /// RSA host key to install in new VM.
    pub rsa_host_key: Option<String>,

    /// RSA host certificate.
    pub rsa_host_cert: Option<String>,

    /// DSA host key to install in new VM.
    pub dsa_host_key: Option<String>,

    /// DSA host certificate.
    pub dsa_host_cert: Option<String>,

    /// ECDSA host key to install in new VM.
    pub ecdsa_host_key: Option<String>,

    /// ECDSA host certificate.
    pub ecdsa_host_cert: Option<String>,

    /// Ed25519 host key to install in new VM.
    pub ed25519_host_key: Option<String>,

    /// Ed25519 host certificate.
    pub ed25519_host_cert: Option<String>,

    /// Path to base image.
    pub base: PathBuf,

    /// Path to new VM image, to be created.
    pub image: PathBuf,

    /// Size of new image, in GiB.
    pub image_size_gib: u64,

    /// Size of memory for new VM, in MiB.
    pub memory_mib: u64,

    /// CPUs new VM should have.
    pub cpus: u64,

    /// Should a new host key and certificate be created for new VM?
    pub generate_host_certificate: bool,

    /// Path to CA key for creating host certificate.
    pub ca_key: Option<PathBuf>,
}

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

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

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

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

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

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

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

    /// I/O error.
    #[error(transparent)]
    IoError(#[from] std::io::Error),

    /// Error parsing string as UTF8.
    #[error(transparent)]
    FromUtf8Error(#[from] std::string::FromUtf8Error),

    /// Error parsing YAML.
    #[error(transparent)]
    YamlError(#[from] serde_yaml::Error),
}

impl Specification {
    /// Read all specifications from a file.
    ///
    /// Apply values from the provided configuration so that the
    /// returned specifications are *effective* and the caller doesn't
    /// need to worry about the configuration anymore.
    ///
    /// Also, SSH public keys are read from the files named in the
    /// input 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,
            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,
        };

        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)
}