summaryrefslogtreecommitdiff
path: root/src/bin/vmadm.rs
blob: 0da9af9978fa5c6b60b44c9a3cfc27672c4f145b (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
use bytesize::GIB;
use log::{debug, info};
use std::fs;
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::Duration;
use structopt::StructOpt;
use virt::connect::Connect;
use vmadm::cloudinit::CloudInitConfig;
use vmadm::image::VirtualMachineImage;
use vmadm::install::{virt_install, VirtInstallArgs};
use vmadm::spec::Specification;

const SSH_PORT: i32 = 22;

#[derive(StructOpt, Debug)]
enum Cli {
    New {
        #[structopt(help = "create a new virtual machine", parse(from_os_str))]
        spec: PathBuf,
    },
    List,
    Delete {
        #[structopt(help = "create a new virtual machine", parse(from_os_str))]
        spec: PathBuf,
    },
}

fn main() -> anyhow::Result<()> {
    pretty_env_logger::init();
    match Cli::from_args() {
        Cli::New { spec } => new(&spec)?,
        Cli::List => list()?,
        Cli::Delete { spec } => delete(&spec)?,
    }
    Ok(())
}

fn new(spec: &Path) -> anyhow::Result<()> {
    info!("creating new VM");

    debug!("reading specification from {}", spec.display());
    let spec = fs::read(spec)?;
    let spec: Specification = serde_yaml::from_slice(&spec)?;

    debug!("reading specified SSH public keys");
    let ssh_keys = spec.ssh_keys()?;

    info!("creating cloud-init config");
    let mut init = CloudInitConfig::default();
    init.set_hostname(&spec.name);
    init.set_authorized_keys(&ssh_keys);

    info!(
        "creating VM image {} from {}",
        spec.image.display(),
        spec.base.display()
    );
    let image = VirtualMachineImage::new_from_base(&spec.base, &spec.image)?;

    info!("resizing image to {} GiB", spec.image_size_gib);
    image.resize(spec.image_size_gib * GIB)?;

    info!("creating VM");
    let mut args = VirtInstallArgs::new(&spec.name, &image, &init);
    args.set_memory(spec.memory_mib);
    args.set_vcpus(spec.cpus);
    virt_install(&args)?;

    info!("waiting for {} to open its SSH port", spec.name);
    wait_for_port(&spec.name, SSH_PORT)?;

    Ok(())
}

fn wait_for_port(name: &str, port: i32) -> anyhow::Result<()> {
    let addr = format!("{}:{}", name, port);
    loop {
        match TcpStream::connect(&addr) {
            Ok(_) => return Ok(()),
            Err(_) => (),
        }
    }
}

fn list() -> anyhow::Result<()> {
    let conn = Connect::open("qemu:///system")?;
    let domains = conn.list_all_domains(0)?;
    for domain in domains {
        let name = domain.get_name()?;
        let (state, _) = domain.get_state()?;
        let state = state_name(state);
        println!("{} {}", name, state);
    }

    Ok(())
}

fn state_name(state: virt::domain::DomainState) -> String {
    let name = match state {
        virt::domain::VIR_DOMAIN_NOSTATE => "none",
        virt::domain::VIR_DOMAIN_RUNNING => "running",
        virt::domain::VIR_DOMAIN_BLOCKED => "blocked",
        virt::domain::VIR_DOMAIN_PAUSED => "paused",
        virt::domain::VIR_DOMAIN_SHUTDOWN => "shutdown",
        virt::domain::VIR_DOMAIN_SHUTOFF => "shutoff",
        virt::domain::VIR_DOMAIN_CRASHED => "crashed",
        virt::domain::VIR_DOMAIN_PMSUSPENDED => "power management suspended",
        _ => "unknown",
    };
    name.to_string()
}

fn delete(spec: &Path) -> anyhow::Result<()> {
    info!("deleting virtual machine specified in {}", spec.display());

    debug!("reading specification from {}", spec.display());
    let spec = fs::read(spec)?;
    let spec: Specification = serde_yaml::from_slice(&spec)?;

    debug!("connecting to libvirtd");
    let conn = Connect::open("qemu:///system")?;

    debug!("listing all domains");
    let domains = conn.list_all_domains(0)?;

    for domain in domains {
        debug!("considering {}", domain.get_name()?);
        if domain.get_name()? == spec.name {
            debug!("shutdown {}", spec.name);
            domain.shutdown().ok();

            let briefly = Duration::from_millis(1000);
            loop {
                thread::sleep(briefly);
                match domain.is_active() {
                    Ok(true) => (),
                    Ok(false) => break,
                    Err(err) => {
                        debug!("is_active: {}", err);
                        ()
                    }
                }
                debug!("{} is still running", spec.name);
            }

            debug!("undefine {}", spec.name);
            domain.undefine()?;

            debug!("removing image file {}", spec.image.display());
            std::fs::remove_file(&spec.image)?;
        }
    }
    Ok(())
}