Skip to main content

isothrum_machine/place/proxmox/
api.rs

1//! What a Proxmox VE server's API answers, read once, here, into the fields placement reads:
2//! every answer is `{"data": …}`, and each path's `data` has its own shape. Unknown fields are
3//! skipped; a missing field is `None`, so a server that leaves one out reads as it did.
4
5use serde::Deserialize;
6use serde::de::DeserializeOwned;
7
8/// The API's envelope: its `data`, none when it is null or missing.
9#[derive(Debug, Deserialize)]
10struct Answer<T> {
11    data: Option<T>,
12}
13
14/// The `data` of `body`, an answer of the API (empty when it has none).
15///
16/// # Errors
17///
18/// `body` isn't JSON, or not the shape the path answers.
19pub fn data<T: DeserializeOwned + Default>(body: &str) -> Result<T, serde_json::Error> {
20    serde_json::from_str::<Answer<T>>(body).map(|a| a.data.unwrap_or_default())
21}
22
23/// `access/ticket`'s answer to a user's password.
24#[derive(Debug, Default, Deserialize)]
25pub struct Ticket {
26    /// The ticket that signs the next calls in (the `PVEAuthCookie`).
27    pub ticket: Option<String>,
28}
29
30/// A node of `/nodes`.
31#[derive(Debug, Deserialize)]
32pub struct Node {
33    /// Its name.
34    pub node: Option<String>,
35    /// `online` or `offline`.
36    pub status: Option<String>,
37}
38
39/// A storage of `/nodes/<node>/storage`.
40#[derive(Debug, Deserialize)]
41pub struct Storage {
42    /// Its id (`local`, `local-lvm`).
43    #[serde(rename = "storage")]
44    pub id: Option<String>,
45    /// What it accepts, comma-separated (`images,iso,snippets`).
46    pub content: Option<String>,
47    /// 0 when it is disabled.
48    pub enabled: Option<u64>,
49    /// 0 when it isn't active.
50    pub active: Option<u64>,
51}
52
53impl Storage {
54    /// What it accepts (`images`, `iso`, `snippets`), each trimmed.
55    #[must_use]
56    pub fn contents(&self) -> Vec<String> {
57        self.content.as_deref().unwrap_or_default().split(',').map(|c| c.trim().to_owned()).collect()
58    }
59
60    /// Whether it can be used: not disabled, not inactive (when the API says).
61    #[must_use]
62    pub fn usable(&self) -> bool {
63        self.enabled != Some(0) && self.active != Some(0)
64    }
65}
66
67/// A network interface of `/nodes/<node>/network`.
68#[derive(Debug, Deserialize)]
69pub struct Iface {
70    /// Its name (`vmbr0`).
71    #[serde(rename = "iface")]
72    pub name: Option<String>,
73    /// Its address with its prefix (`10.0.0.50/24`).
74    pub cidr: Option<String>,
75    /// Its address, when the API gives it apart from its netmask.
76    pub address: Option<String>,
77    /// Its netmask (`255.255.255.0`).
78    pub netmask: Option<String>,
79    /// A bridge's physical ports, space-separated; empty or missing for a host-internal one.
80    pub bridge_ports: Option<String>,
81}
82
83impl Iface {
84    /// A bridge without physical ports (`bridge_ports` empty or missing): host-internal.
85    #[must_use]
86    pub fn has_no_ports(&self) -> bool {
87        self.bridge_ports.as_deref().map(str::trim).unwrap_or_default().is_empty()
88    }
89}
90
91/// `/nodes/<node>/status`: its cores and memory.
92#[derive(Debug, Default, Deserialize)]
93pub struct NodeStatus {
94    /// Its CPUs.
95    pub cpuinfo: Option<CpuInfo>,
96    /// Its memory, in bytes.
97    pub memory: Option<Memory>,
98}
99
100/// A node's CPUs.
101#[derive(Debug, Deserialize)]
102pub struct CpuInfo {
103    /// How many logical CPUs it has.
104    pub cpus: Option<u64>,
105}
106
107/// A node's memory, in bytes.
108#[derive(Debug, Deserialize)]
109pub struct Memory {
110    /// All of it.
111    pub total: Option<u64>,
112    /// What is free.
113    pub free: Option<u64>,
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    // Answers as Proxmox VE 8 gives them (secrets shortened, fields trimmed to a few).
121    const TICKET: &str =
122        r#"{"data":{"username":"root@pam","ticket":"PVE:root@pam:6553F0A4::c2lnbmVk","CSRFPreventionToken":"6553F0A4:Y3NyZg","cap":{"vms":{"VM.Console":1}}}}"#;
123    const NODES: &str = r#"{"data":[{"node":"pve","status":"online","type":"node","id":"node/pve","cpu":0.0123,"maxcpu":8,"mem":2147483648,"maxmem":34359738368,"uptime":86400,"level":"","ssl_fingerprint":"AA:BB"}]}"#;
124    const STORAGE: &str = r#"{"data":[{"storage":"local","type":"dir","content":"iso,vztmpl,backup","enabled":1,"active":1,"shared":0,"total":100,"used":10,"avail":90,"used_fraction":0.1},{"storage":"local-lvm","type":"lvmthin","content":"rootdir,images","enabled":1,"active":1,"shared":0}]}"#;
125    const NETWORK: &str = r#"{"data":[{"iface":"vmbr0","type":"bridge","method":"static","families":["inet"],"active":1,"autostart":1,"bridge_ports":"eno1","bridge_stp":"off","bridge_fd":"0","cidr":"192.168.1.5/24","address":"192.168.1.5","netmask":"24","gateway":"192.168.1.1","priority":3},{"iface":"eno1","type":"eth","method":"manual","active":1,"exists":1,"priority":2}]}"#;
126    const STATUS: &str = r#"{"data":{"cpuinfo":{"cpus":8,"cores":4,"sockets":1,"model":"Intel(R) Core(TM) i7"},"memory":{"total":34359738368,"free":30000000000,"used":4359738368},"uptime":86400,"pveversion":"pve-manager/8.2.4"}}"#;
127
128    #[test]
129    fn each_answer_reads_as_its_fields() {
130        let t: Ticket = data(TICKET).unwrap();
131        assert_eq!(t.ticket.as_deref(), Some("PVE:root@pam:6553F0A4::c2lnbmVk"));
132        let nodes: Vec<Node> = data(NODES).unwrap();
133        assert_eq!((nodes[0].node.as_deref(), nodes[0].status.as_deref()), (Some("pve"), Some("online")));
134        let storages: Vec<Storage> = data(STORAGE).unwrap();
135        assert_eq!(storages[0].contents(), ["iso", "vztmpl", "backup"]);
136        assert!(storages.iter().all(Storage::usable));
137        let ifaces: Vec<Iface> = data(NETWORK).unwrap();
138        assert_eq!(
139            (ifaces[0].bridge_ports.as_deref(), ifaces[0].cidr.as_deref()),
140            (Some("eno1"), Some("192.168.1.5/24"))
141        );
142        assert_eq!(ifaces[1].bridge_ports, None);
143        let status: NodeStatus = data(STATUS).unwrap();
144        assert_eq!(status.cpuinfo.and_then(|c| c.cpus), Some(8));
145        assert_eq!(status.memory.and_then(|m| m.total), Some(34_359_738_368));
146    }
147
148    #[test]
149    fn no_data_is_empty_and_another_shape_an_error() {
150        assert!(data::<Vec<Node>>(r#"{"data":null}"#).unwrap().is_empty());
151        assert!(data::<Vec<Node>>("{}").unwrap().is_empty());
152        assert!(data::<Vec<Node>>(r#"{"data":{"node":"pve"}}"#).is_err(), "not a list");
153        assert!(data::<Ticket>("<html>").is_err());
154        let off: Vec<Storage> = data(r#"{"data":[{"storage":"nfs","enabled":1,"active":0}]}"#).unwrap();
155        assert!(!off[0].usable());
156    }
157}