bsdt 0.2.2

Repeatable FreeBSD development VMs from a TOML file, booted with QEMU from the official images
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! The `bsdt.toml` environment file.

use std::fmt;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::Deserialize;

pub const DEFAULT_FILE: &str = "bsdt.toml";

/// The unprivileged user bsdt creates in the guest and syncs files as.
pub const GUEST_USER: &str = "bsdt";

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    pub vm: Vm,
    #[serde(default)]
    pub packages: Packages,
    #[serde(default)]
    pub sync: Sync,
    #[serde(default)]
    pub provision: Provision,
    #[serde(default)]
    pub gui: Gui,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Vm {
    pub os: Os,
    pub version: String,
    #[serde(default)]
    pub arch: Arch,
    #[serde(default = "default_cpus")]
    pub cpus: u32,
    #[serde(default = "default_memory")]
    pub memory: String,
    #[serde(default = "default_disk")]
    pub disk: String,
    #[serde(default)]
    pub filesystem: Filesystem,
    pub hostname: Option<String>,
    #[serde(default)]
    pub ports: Vec<Port>,
    /// Let the image install OS security updates on first boot, which
    /// takes a while and reboots. Off by default so every VM starts from
    /// exactly the release image.
    #[serde(default)]
    pub update: bool,
    /// Run a desktop in the guest and open a window on it; see [`Gui`].
    #[serde(default)]
    pub gui: bool,
    /// Attach a USB keyboard and tablet, for `bsdt key` and anything that
    /// reads /dev/input. Defaults to on when `gui` is.
    pub input: Option<bool>,
}

impl Vm {
    pub fn input(&self) -> bool {
        self.input.unwrap_or(self.gui)
    }
}

fn default_cpus() -> u32 {
    2
}

fn default_memory() -> String {
    "2G".into()
}

fn default_disk() -> String {
    "20G".into()
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Packages {
    #[serde(default)]
    pub install: Vec<String>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Sync {
    /// Guest directory the project is synced to; defaults to
    /// `/home/bsdt/<project directory name>`.
    pub dest: Option<String>,
    #[serde(default)]
    pub exclude: Vec<String>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Provision {
    /// Commands run as root, after packages are installed.
    #[serde(default)]
    pub root: Vec<String>,
    /// Commands run as the guest user in the synced directory.
    #[serde(default)]
    pub run: Vec<String>,
}

/// Settings for `vm.gui`. Every field has a default, so `gui = true` on
/// its own gives a sway desktop in a window.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Gui {
    #[serde(default)]
    pub desktop: Desktop,
    /// Command run as the guest user once the desktop is up, on every boot.
    /// Defaults to a terminal on the sway desktop; `""` runs nothing.
    pub start: Option<String>,
    /// Port the guest's VNC server listens on.
    #[serde(default = "default_vnc")]
    pub vnc: u16,
    /// Host port forwarded to `vnc`; a free one is picked when unset.
    pub port: Option<u16>,
    /// Open a viewer window when `bsdt up` finishes.
    #[serde(default = "default_true")]
    pub open: bool,
    #[serde(default = "default_resolution")]
    pub resolution: String,
    /// Open the viewer full screen, where TigerVNC passes system keys such
    /// as Super and Alt+Tab to the VM.
    #[serde(default)]
    pub fullscreen: bool,
    /// The sway modifier key in the config bsdt generates.
    #[serde(default)]
    pub modifier: Modifier,
}

impl Default for Gui {
    fn default() -> Self {
        Gui {
            desktop: Desktop::default(),
            start: None,
            vnc: default_vnc(),
            port: None,
            open: true,
            resolution: default_resolution(),
            fullscreen: false,
            modifier: Modifier::default(),
        }
    }
}

impl Gui {
    /// `resolution` as width and height.
    pub fn size(&self) -> Result<(u32, u32)> {
        let parsed = self.resolution.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?)));
        match parsed {
            Some((w, h)) if w > 0 && h > 0 => Ok((w, h)),
            _ => bail!("invalid gui.resolution {:?}, expected WIDTHxHEIGHT such as \"1280x800\"", self.resolution),
        }
    }

    pub fn start(&self) -> Option<&str> {
        match (&self.start, self.desktop) {
            (Some(cmd), _) => Some(cmd.as_str()).filter(|c| !c.trim().is_empty()),
            (None, Desktop::Sway) => Some("foot"),
            (None, Desktop::None) => None,
        }
    }
}

fn default_vnc() -> u16 {
    5900
}

fn default_true() -> bool {
    true
}

fn default_resolution() -> String {
    "1280x800".into()
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Modifier {
    /// Alt, which desktops on the host rarely take for themselves.
    #[default]
    Alt,
    Super,
}

impl Modifier {
    /// The name sway uses for it.
    pub fn sway(self) -> &'static str {
        match self {
            Modifier::Alt => "Mod1",
            Modifier::Super => "Mod4",
        }
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Desktop {
    /// sway on a headless output, shared over VNC by wayvnc, all installed
    /// and started by bsdt.
    #[default]
    Sway,
    /// Nothing; `start` brings up whatever serves VNC on `vnc`.
    None,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Os {
    FreeBSD,
    NetBSD,
    OpenBSD,
}

impl fmt::Display for Os {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Os::FreeBSD => "freebsd",
            Os::NetBSD => "netbsd",
            Os::OpenBSD => "openbsd",
        })
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Arch {
    /// Whatever the host is, so the guest gets hardware acceleration.
    #[default]
    Auto,
    #[serde(alias = "x86_64")]
    Amd64,
    #[serde(alias = "arm64")]
    Aarch64,
}

impl Arch {
    pub fn host() -> Arch {
        match std::env::consts::ARCH {
            "aarch64" => Arch::Aarch64,
            _ => Arch::Amd64,
        }
    }

    /// `Auto` replaced by the host architecture.
    pub fn resolve(self) -> Arch {
        match self {
            Arch::Auto => Arch::host(),
            arch => arch,
        }
    }
}

impl fmt::Display for Arch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Arch::Auto => "auto",
            Arch::Amd64 => "amd64",
            Arch::Aarch64 => "aarch64",
        })
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Filesystem {
    #[default]
    Ufs,
    Zfs,
}

impl fmt::Display for Filesystem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Filesystem::Ufs => "ufs",
            Filesystem::Zfs => "zfs",
        })
    }
}

/// A TCP port forwarded from `127.0.0.1:host` to the guest, written as
/// `"HOST:GUEST"`, or just `"PORT"` when both are the same.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub struct Port {
    pub host: u16,
    pub guest: u16,
}

impl TryFrom<String> for Port {
    type Error = String;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        let parse = |p: &str| p.trim().parse::<u16>().ok().filter(|&n| n != 0);
        let port = match s.split_once(':') {
            Some((host, guest)) => parse(host).zip(parse(guest)),
            None => parse(&s).map(|p| (p, p)),
        };
        match port {
            Some((host, guest)) => Ok(Port { host, guest }),
            None => Err(format!("invalid port {s:?}, expected \"HOST:GUEST\" or \"PORT\"")),
        }
    }
}

impl fmt::Display for Port {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "127.0.0.1:{} -> {}", self.host, self.guest)
    }
}

/// A loaded environment file and where it lives.
pub struct Project {
    /// Directory holding the environment file; this is what gets synced.
    pub dir: PathBuf,
    pub file: PathBuf,
    pub config: Config,
}

impl Project {
    /// Load `file`, or find `bsdt.toml` in the current directory or one of
    /// its parents.
    pub fn load(file: Option<&Path>) -> Result<Project> {
        let file = match file {
            Some(file) => file.to_path_buf(),
            None => find(&std::env::current_dir()?)?,
        };
        let file = std::path::absolute(&file)?;
        let text = std::fs::read_to_string(&file).with_context(|| format!("reading {}", file.display()))?;
        let config: Config = toml::from_str(&text).with_context(|| format!("parsing {}", file.display()))?;
        let dir = file.parent().context("environment file has no parent directory")?.to_path_buf();
        Ok(Project { dir, file, config })
    }

    /// The project directory's name, cleaned up for use as a hostname.
    pub fn name(&self) -> String {
        let raw = self.dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
        sanitize_hostname(&raw)
    }

    pub fn hostname(&self) -> String {
        match &self.config.vm.hostname {
            Some(h) => h.clone(),
            None => self.name(),
        }
    }

    /// Where VM state lives: `.bsdt/<file stem>/` beside the environment
    /// file, so `bsdt.toml` and `-f other.toml` get separate VMs.
    pub fn state_dir(&self) -> PathBuf {
        let stem = self.file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "bsdt".into());
        self.dir.join(".bsdt").join(stem)
    }

    pub fn dest(&self) -> String {
        match &self.config.sync.dest {
            Some(dest) => dest.trim_end_matches('/').to_string(),
            None => format!("/home/{GUEST_USER}/{}", self.name()),
        }
    }

    /// The guest directory matching the host's current directory, falling
    /// back to the sync destination when outside the project.
    pub fn guest_cwd(&self) -> String {
        let dest = self.dest();
        let rel = std::env::current_dir().ok().and_then(|cwd| cwd.strip_prefix(&self.dir).ok().map(Path::to_path_buf));
        match rel {
            Some(rel) if !rel.as_os_str().is_empty() => format!("{dest}/{}", rel.to_string_lossy()),
            _ => dest,
        }
    }
}

fn find(start: &Path) -> Result<PathBuf> {
    for dir in start.ancestors() {
        let candidate = dir.join(DEFAULT_FILE);
        if candidate.is_file() {
            return Ok(candidate);
        }
    }
    bail!("no {DEFAULT_FILE} in {} or its parents (run `bsdt init` to create one)", start.display())
}

fn sanitize_hostname(raw: &str) -> String {
    let mut name: String = raw
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' })
        .collect();
    name.truncate(63);
    let name = name.trim_matches('-');
    if name.is_empty() { "bsdt".into() } else { name.into() }
}

/// The file `bsdt init` writes.
pub const TEMPLATE: &str = r#"# bsdt environment; see bsdt(1).

[vm]
os = "freebsd"
version = "15.1"
# arch = "auto"         # auto (match the host), amd64 or aarch64
# cpus = 2
# memory = "2G"
# disk = "20G"
# filesystem = "ufs"    # ufs or zfs
# ports = ["8080:80"]   # 127.0.0.1:HOST on the host -> GUEST in the VM
# update = false        # install OS security updates on first boot
# gui = false           # a sway desktop in a window; see [gui] in bsdt(1)

[packages]
install = ["git"]

[sync]
# dest = "/home/bsdt/<project directory>"
exclude = ["target"]

[provision]
# root = ["sysrc foo_enable=YES"]
# run = ["cargo fetch"]
"#;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn template_parses() {
        let config: Config = toml::from_str(TEMPLATE).unwrap();
        assert_eq!(config.vm.os, Os::FreeBSD);
        assert_eq!(config.vm.arch, Arch::Auto);
        assert_eq!(config.vm.cpus, 2);
        assert_eq!(config.packages.install, ["git"]);
    }

    #[test]
    fn full_config_parses() {
        let config: Config = toml::from_str(
            r#"
            [vm]
            os = "freebsd"
            version = "14.5"
            arch = "arm64"
            filesystem = "zfs"
            ports = ["8080:80", "5432"]
            [provision]
            root = ["sysrc sshd_enable=YES"]
            run = ["make"]
            "#,
        )
        .unwrap();
        assert_eq!(config.vm.arch, Arch::Aarch64);
        assert_eq!(config.vm.filesystem, Filesystem::Zfs);
        assert_eq!(config.vm.ports, [Port { host: 8080, guest: 80 }, Port { host: 5432, guest: 5432 }]);
        assert_eq!(config.provision.run, ["make"]);
    }

    #[test]
    fn gui_defaults() {
        let config: Config = toml::from_str("[vm]\nos = \"freebsd\"\nversion = \"15.1\"\ngui = true").unwrap();
        assert!(config.vm.input());
        assert_eq!(config.gui.desktop, Desktop::Sway);
        assert_eq!(config.gui.vnc, 5900);
        assert_eq!(config.gui.port, None);
        assert!(config.gui.open);
        assert_eq!(config.gui.start(), Some("foot"));
        assert_eq!(config.gui.modifier, Modifier::Alt);
        assert!(!config.gui.fullscreen);
        assert_eq!(config.gui.size().unwrap(), (1280, 800));

        let config: Config = toml::from_str(
            "[vm]\nos = \"freebsd\"\nversion = \"15.1\"\ngui = true\ninput = false\n[gui]\ndesktop = \"none\"\nstart = \"x11vnc\"\nport = 5901",
        )
        .unwrap();
        assert!(!config.vm.input());
        assert_eq!(config.gui.start(), Some("x11vnc"));
        assert_eq!(config.gui.port, Some(5901));

        let mut gui = Gui::default();
        for bad in ["1280", "x800", "0x800", "1280x"] {
            gui.resolution = bad.into();
            assert!(gui.size().is_err(), "{bad} should be rejected");
        }

        let config: Config = toml::from_str("[vm]\nos = \"freebsd\"\nversion = \"15.1\"\ninput = true\n[gui]\nstart = \"\"").unwrap();
        assert!(config.vm.input() && !config.vm.gui);
        assert_eq!(config.gui.start(), None);
    }

    #[test]
    fn rejects_unknown_keys_and_bad_ports() {
        assert!(toml::from_str::<Config>("[vm]\nos = \"freebsd\"\nversion = \"15.1\"\nram = \"2G\"").is_err());
        for bad in ["0", "x:80", "80:", "70000:80"] {
            assert!(Port::try_from(bad.to_string()).is_err(), "{bad} should be rejected");
        }
    }

    #[test]
    fn hostnames_are_sanitized() {
        assert_eq!(sanitize_hostname("My_Project.rs"), "my-project-rs");
        assert_eq!(sanitize_hostname("..."), "bsdt");
    }
}