xonecas.ioDon't click! Sean Caetano Martin Sign in
cast / src / vm / mod.rs 79 lines1.9 kB Raw
1pub mod bake;
2mod download;
3pub mod env;
4pub mod files;
5mod git;
6mod qemu;
7mod seed;
8pub mod ssh;
9
10use crate::app::bus::{Bus, Event};
11use std::path::Path;
12use std::process::{Child, Stdio};
13use std::time::{Duration, Instant};
14
15pub enum Vm {
16    Off,
17    Booting,
18    Ready(u16),
19    Failed(String),
20}
21
22impl Vm {
23    pub fn port(&self) -> Option<u16> {
24        match self {
25            Vm::Ready(p) => Some(*p),
26            _ => None,
27        }
28    }
29}
30
31pub struct Machine(Child);
32
33impl Drop for Machine {
34    fn drop(&mut self) {
35        let _ = self.0.kill();
36        let _ = self.0.wait();
37    }
38}
39
40pub fn boot(bus: &Bus, dir: &Path, state: &Path) -> std::io::Result<Machine> {
41    std::fs::create_dir_all(state)?;
42    let port = std::net::TcpListener::bind("127.0.0.1:0")?
43        .local_addr()?
44        .port();
45    let child = qemu::command(
46        &files::disk(),
47        &[("work", dir, false), ("cast", state, false)],
48    )
49    .arg("-snapshot")
50    .arg("-nic")
51    .arg(format!(
52        "user,model=virtio-net-pci,hostfwd=tcp:127.0.0.1:{port}-:22"
53    ))
54    .arg("-serial")
55    .arg(format!("file:{}", files::console_log().display()))
56    .stdin(Stdio::null())
57    .stdout(Stdio::null())
58    .stderr(Stdio::null())
59    .spawn()?;
60    let bus = bus.clone();
61    let identity = git::identity();
62    std::thread::spawn(move || {
63        let start = Instant::now();
64        while start.elapsed() < Duration::from_secs(180) {
65            if ssh::run(
66                port,
67                "mountpoint -q /work && mountpoint -q /cast && DISPLAY=:0 xset q",
68            ) {
69                ssh::run(port, &identity);
70                return bus.send(Event::Vm(Ok(port)));
71            }
72            std::thread::sleep(Duration::from_secs(2));
73        }
74        bus.send(Event::Vm(Err(
75            "the VM did not come up with its mounts and desktop within 3 minutes".into(),
76        )));
77    });
78    Ok(Machine(child))
79}