aboutsummaryrefslogtreecommitdiff
path: root/src/planet.rs
blob: c29fb69064066bd8393b4c34b8a4ecec4583501b (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
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
use std::convert::TryFrom;
use virt::{domain::{Domain, DomainState}};
use serde::{Serialize, Deserialize};

use crate::errors::Error;

/**
 * Defines the amount of memory a planet has
 */
#[derive(Debug, Serialize, Deserialize)]
pub struct Memory(pub u64);

impl From<u64> for Memory {
    fn from(u: u64) -> Self {
        Self(u)
    }
}

/**
 * Defines the number of vCPUs a planet has
 */
#[derive(Debug, Serialize, Deserialize)]
pub struct CpuCount(pub u64);

impl From<u64> for CpuCount {
    fn from(u: u64) -> Self {
        Self(u)
    }
}

/**
 * Represents a virtual machine, that's active on some server
 *
 * In keeping with the theme, it's named [Planet] :)
 *
 * There is a private `domain` field that contains a reference to the actual domain. This will not
 * be (de)serialized, and, if needed across a network, should be recreated from the `host` and
 * `uuid` attributes using [virt::domain::lookup_from_uuid_string]
 */
#[derive(Debug, Serialize, Deserialize)]
pub struct Planet {
    /// The reference name of the machine
    pub name: String,

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

    /// The UUID
    pub uuid: String,

    /// 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: Memory,

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

    #[serde(skip)]
    domain: Option<Domain>,
}

impl PartialEq for Planet {
    fn eq(&self, other: &Self) -> bool {
        self.uuid == other.uuid
    }
}

impl TryFrom<Domain> for Planet {
    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
        //
        // Based on code by Cadey in waifud
        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,
            uuid: d.get_uuid_string()?,
            mem: d.get_max_memory()?.into(),
            cpu_count: d.get_max_vcpus()?.into(),
            domain: Some(d),
        })
    }
}


impl TryFrom<&Domain> for Planet {
    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
        //
        // Based on code by Cadey in waifud
        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,
            uuid: d.get_uuid_string()?,
            mem: d.get_max_memory()?.into(),
            cpu_count: d.get_max_vcpus()?.into(),
            domain: Some(*d),
        })
    }
}

#[repr(u32)]
#[derive(Serialize, Deserialize)]
pub enum Health {
    Unknown = 0,
    Running = 1,
    Blocked = 2,
    Paused  = 3,
    ShuttingDown = 4,
    ShutDown = 5,
    Crashed = 6,
    GuestSuspended = 7
}

impl Planet {
    fn get_status(&self) -> Result<Health, Error> {
        let d = match self.domain {
            Some(d) => d,
            None => {
                return Err(Error::Other(String::from("No domain connection found")));
            }
        };

        let state = d.get_state()?;

        Ok(state.0 as Health)
    }
}