aboutsummaryrefslogtreecommitdiff
path: root/src/waifu.rs
blob: a7dfba86b3d268925d4ea491ff185a1465fe92a5 (plain) (blame)
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
use std::convert::TryFrom;
use virt::{connect::Connect, domain::Domain};
use serde::{Serialize, Deserialize};

use crate::errors::Error;

type Fqdn = String;

/**
 * Represents a virtual machine, that's active on some server
 *
 * In keeping with the theme, it's named [Waifu] :)
 */
#[derive(Debug, Serialize, Deserialize)]
pub struct Waifu {
    /// The reference name of the machine
    pub name: String,

    /// The physical machine where this one lives
    pub host: Fqdn,

    /// The network address where this machine can be reached
    pub addr: Option<String>,

    /// The amount of RAM (in MB) assigned to this machine
    pub mem: u64,

    /// The amount of vCPUs assigned to this machine
    pub cpu_count: u64,
}

impl TryFrom<Domain> for Waifu {
    type Error = Error;

    fn try_from(d: Domain) -> Result<Self, Self::Error> {
        let c = d.get_connect()?;

        // This... feels wrong
        //
        // I know it probably works
        let addr: Option<String> = if d.is_active()? {
            let mut addr: Vec<String> = d
                .interface_addresses(virt::domain::VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE, 0)?
                .into_iter()
                .map(|iface| iface.addrs.clone())
                .filter(|addrs| addrs.get(0).is_some())
                .map(|addrs| addrs.get(0).unwrap().clone().addr)
                .collect();

            if addr.get(0).is_none() {
                Some(String::from("localhost"))
            } else {
                Some(addr.swap_remove(0))
            }
        } else {
            None
        };

        Ok(Self {
            name: d.get_name()?,
            host: c.get_hostname()?,
            addr,
            mem: d.get_max_memory()?,
            cpu_count: d.get_max_vcpus()?,
        })
    }
}