use serde::Deserialize;
use serde::de::DeserializeOwned;
#[derive(Debug, Deserialize)]
struct Answer<T> {
data: Option<T>,
}
pub fn data<T: DeserializeOwned + Default>(body: &str) -> Result<T, serde_json::Error> {
serde_json::from_str::<Answer<T>>(body).map(|a| a.data.unwrap_or_default())
}
#[derive(Debug, Default, Deserialize)]
pub struct Ticket {
pub ticket: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct Node {
pub node: Option<String>,
pub status: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct Storage {
#[serde(rename = "storage")]
pub id: Option<String>,
pub content: Option<String>,
pub enabled: Option<u64>,
pub active: Option<u64>,
}
impl Storage {
#[must_use]
pub fn contents(&self) -> Vec<String> {
self.content.as_deref().unwrap_or_default().split(',').map(|c| c.trim().to_owned()).collect()
}
#[must_use]
pub fn usable(&self) -> bool {
self.enabled != Some(0) && self.active != Some(0)
}
}
#[derive(Debug, Deserialize)]
pub struct Iface {
#[serde(rename = "iface")]
pub name: Option<String>,
pub cidr: Option<String>,
pub address: Option<String>,
pub netmask: Option<String>,
pub bridge_ports: Option<String>,
}
impl Iface {
#[must_use]
pub fn has_no_ports(&self) -> bool {
self.bridge_ports.as_deref().map(str::trim).unwrap_or_default().is_empty()
}
}
#[derive(Debug, Default, Deserialize)]
pub struct NodeStatus {
pub cpuinfo: Option<CpuInfo>,
pub memory: Option<Memory>,
}
#[derive(Debug, Deserialize)]
pub struct CpuInfo {
pub cpus: Option<u64>,
}
#[derive(Debug, Deserialize)]
pub struct Memory {
pub total: Option<u64>,
pub free: Option<u64>,
}
#[cfg(test)]
mod tests {
use super::*;
const TICKET: &str =
r#"{"data":{"username":"root@pam","ticket":"PVE:root@pam:6553F0A4::c2lnbmVk","CSRFPreventionToken":"6553F0A4:Y3NyZg","cap":{"vms":{"VM.Console":1}}}}"#;
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"}]}"#;
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}]}"#;
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}]}"#;
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"}}"#;
#[test]
fn each_answer_reads_as_its_fields() {
let t: Ticket = data(TICKET).unwrap();
assert_eq!(t.ticket.as_deref(), Some("PVE:root@pam:6553F0A4::c2lnbmVk"));
let nodes: Vec<Node> = data(NODES).unwrap();
assert_eq!((nodes[0].node.as_deref(), nodes[0].status.as_deref()), (Some("pve"), Some("online")));
let storages: Vec<Storage> = data(STORAGE).unwrap();
assert_eq!(storages[0].contents(), ["iso", "vztmpl", "backup"]);
assert!(storages.iter().all(Storage::usable));
let ifaces: Vec<Iface> = data(NETWORK).unwrap();
assert_eq!(
(ifaces[0].bridge_ports.as_deref(), ifaces[0].cidr.as_deref()),
(Some("eno1"), Some("192.168.1.5/24"))
);
assert_eq!(ifaces[1].bridge_ports, None);
let status: NodeStatus = data(STATUS).unwrap();
assert_eq!(status.cpuinfo.and_then(|c| c.cpus), Some(8));
assert_eq!(status.memory.and_then(|m| m.total), Some(34_359_738_368));
}
#[test]
fn no_data_is_empty_and_another_shape_an_error() {
assert!(data::<Vec<Node>>(r#"{"data":null}"#).unwrap().is_empty());
assert!(data::<Vec<Node>>("{}").unwrap().is_empty());
assert!(data::<Vec<Node>>(r#"{"data":{"node":"pve"}}"#).is_err(), "not a list");
assert!(data::<Ticket>("<html>").is_err());
let off: Vec<Storage> = data(r#"{"data":[{"storage":"nfs","enabled":1,"active":0}]}"#).unwrap();
assert!(!off[0].usable());
}
}