summaryrefslogtreecommitdiff
path: root/src/libvirt.rs
blob: f0ad2d04d7aca22ef170a3d11228272946a5b132 (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
//! An abstraction on top of the libvirt bindings.

use crate::util::wait_for_ssh;
use log::debug;
use std::path::Path;
use std::thread;
use std::time::Duration;
use virt::connect::Connect;
use virt::domain::{
    Domain, VIR_DOMAIN_AFFECT_CONFIG, VIR_DOMAIN_AFFECT_CURRENT, VIR_DOMAIN_AFFECT_LIVE,
};

/// Errors from this module.
#[derive(Debug, thiserror::Error)]
pub enum VirtError {
    /// Error creating virtual machine.
    #[error(transparent)]
    VirtError(#[from] virt::error::Error),

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

/// Access libvirt for all the things this program needs.
pub struct Libvirt {
    conn: Connect,
}

impl Libvirt {
    pub fn connect(url: &str) -> Result<Self, VirtError> {
        debug!("connecting to libvirtd {}", url);
        let conn = Connect::open(url)?;
        Ok(Self { conn })
    }

    fn get_domains(&self) -> Result<Vec<Domain>, VirtError> {
        debug!("listing all domains");
        Ok(self.conn.list_all_domains(0)?)
    }

    fn get_domain(&self, name: &str) -> Result<Option<Domain>, VirtError> {
        for domain in self.get_domains()? {
            if domain.get_name()? == name {
                return Ok(Some(domain));
            }
        }
        Ok(None)
    }

    pub fn names(&self) -> Result<Vec<String>, VirtError> {
        let mut ret = vec![];
        for domain in self.get_domains()? {
            ret.push(domain.get_name()?);
        }
        Ok(ret)
    }

    pub fn is_active(&self, name: &str) -> Result<bool, VirtError> {
        if let Some(domain) = self.get_domain(name)? {
            Ok(domain.is_active()?)
        } else {
            Ok(false)
        }
    }

    pub fn wait_for_inactive(&self, name: &str) -> Result<(), VirtError> {
        loop {
            if !self.is_active(name)? {
                break;
            }
        }
        Ok(())
    }

    pub fn detach_cloud_init_iso(&self, name: &str) -> Result<(), VirtError> {
        if let Some(domain) = self.get_domain(name)? {
            debug!("detaching cloud-init ISO from {}", name);
            let xml = domain.get_xml_desc(0)?;
            let disk = find_iso_xml(&xml);
            let flags =
                VIR_DOMAIN_AFFECT_CONFIG | VIR_DOMAIN_AFFECT_CURRENT | VIR_DOMAIN_AFFECT_LIVE;
            if disk.len() > 0 {
                domain.detach_device_flags(&disk, flags)?;
            }
        }
        Ok(())
    }

    pub fn start(&self, name: &str) -> Result<(), VirtError> {
        if let Some(domain) = self.get_domain(name)? {
            domain.create()?;
            wait_for_ssh(name);
        }
        Ok(())
    }

    pub fn shutdown(&self, name: &str) -> Result<(), VirtError> {
        if let Some(domain) = self.get_domain(name)? {
            domain.shutdown()?;
            wait_until_inactive(&domain, name);
        }
        Ok(())
    }

    pub fn delete(&self, name: &str, image: &Path) -> Result<(), VirtError> {
        if let Some(domain) = self.get_domain(name)? {
            debug!("shutting down {}", name);
            domain.shutdown().ok();

            wait_until_inactive(&domain, name);

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

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

        Ok(())
    }
}

fn wait_until_inactive(domain: &Domain, name: &str) {
    debug!("waiting for domain {} to become inactive", name);
    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!("domain {} is still running", name);
    }
}

// This is a HACK. The XML description of a domain contains
// descriptions of attached virtual disks. We find one that contains
// ".iso", and return that.
//
//  <disk type='file' device='disk'>
//   <driver name='qemu' type='raw'/>
//   <source file='/tmp/.tmp2rAiVW/cloudinit.iso'/>
//   <backingStore/>
//   <target dev='vdb' bus='virtio'/>
//   <readonly/>
//   <alias name='virtio-disk1'/>
//   <address type='pci' domain='0x0000' bus='0x05' slot='0x00' function='0x0'/>
// </disk>

fn find_iso_xml(xml: &str) -> String {
    let mut xml = xml;
    loop {
        let start = xml.find("<disk ");
        if start.is_none() {
            break;
        }
        let start = start.unwrap();
        xml = &xml[start..];

        let end = xml.find("</disk>");
        if end.is_none() {
            break;
        }
        let end = end.unwrap();
        let disk = &xml[..end + 7];
        if let Some(_) = disk.find(".iso") {
            return disk.to_string();
        }
        xml = &xml[end..];
    }
    "".to_string()
}