aboutsummaryrefslogtreecommitdiff
path: root/src/house.rs
blob: 735413ec1564ddb9d5cbfdf011be572e43431b50 (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
/*!
  * `House`s are where [crate::waifu::Waifu]s live (the physical hypervisors that
  * libvirtd connects to
  */
use crate::waifu::*;
use crate::errors::Error;
use serde::{Serialize, Deserialize};
use std::convert::TryFrom;
use virt::connect::Connect;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

#[derive(Serialize, Deserialize, Debug)]
pub enum Address {
    IP(String),
    Domain(String)
}

impl ToString for Address {
    fn to_string(&self) -> String {
        match self {
            Address::IP(s) => s.clone(),
            Address::Domain(s) => s.clone(),
        }
    }
}

/// Defines a "house" where waifus live
#[derive(Debug, Serialize, Deserialize)]
pub struct House {
    /// Hostname
    pub name: String,
    /// FQDN or IP address, a way to talk to the house
    pub address: String,

    /// Connection to the House, if available
    #[serde(skip)]
    con: Option<Connect>,
}

impl House { 
    pub fn new(url: String) -> Result<Self, Error> {
        let mut c = Connect::open(&url.clone())?;

        // If the connection succeeds, we've got one!
        Ok(Self {
            name: c.get_hostname()?,
            address: c.get_uri()?,
            con: Some(c),
        })
    }

    pub fn inhabitants(&mut self) -> Result<Vec<Waifu>, Error> {
        match &self.con {
            Some(c) => {
                let domains = c.list_all_domains(0)?;

                let mut waifus: Vec<Waifu> = Vec::new();

                for d in domains.iter() {
                    waifus.push(d.clone().try_into()?);
                }
                Ok(waifus)
            },
            None => {
                return Err(Error::Connection("Domain connection was None".to_string()));
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    /// Kind of a stupid test, but just a sanity check to make sure that [ToString] impl up above
    /// is still working
    #[test]
    fn addr_to_string() {
        let a: Address = Address::IP("127.0.0.1".to_string());
        let d: Address = Address::Domain("example.com".to_string());

        assert_eq!(String::from("127.0.0.1"), a.to_string());
        assert_eq!("example.com".to_string(), d.to_string());
    }

    #[test]
    fn connect_to_house() {
        let h: House = House::new("test:///default".to_string()).unwrap();
    }

    #[test]
    fn list_inhabitants() {
        let mut h: House = House::new("test:///default".to_string()).unwrap();

        let empty_vec: Vec<Waifu> = vec![];

        h.inhabitants().unwrap();
    }

}