ceph_safe_disk/
from.rs

1use crate::error::CSDError;
2use crate::exec::call_ceph;
3
4use std::fmt::Debug;
5use std::fs::File;
6use std::io::prelude::*;
7
8use serde::de::DeserializeOwned;
9
10// Generic trait to read file to serializable struct
11pub trait FromFile<T> {
12    fn from_file(path: &str) -> Result<T, CSDError>;
13}
14
15impl<T: DeserializeOwned + Debug> FromFile<T> for T {
16    fn from_file(path: &str) -> Result<T, CSDError> {
17        let mut file = File::open(path)?;
18        let mut buffer = String::new();
19        file.read_to_string(&mut buffer)?;
20        Ok(serde_json::from_str(&buffer)?)
21    }
22}
23
24// Generic trait to create structs from ceph JSON output. Since most if not all
25// of of ceph's commands can be formatted to JSON. For example:
26// let pgmap = PGMap::from_ceph("pg dump").unwrap()
27pub trait FromCeph<T> {
28    fn from_ceph(cmd: &str) -> Result<T, CSDError>;
29}
30
31impl<T: DeserializeOwned + Debug> FromCeph<T> for T {
32    fn from_ceph(cmd: &str) -> Result<T, CSDError> {
33        let ceph_output = call_ceph(cmd)?;
34        let serde_res: Result<T, serde_json::Error> = serde_json::from_str(&ceph_output);
35        trace!("deserialize ceph: {:?}", serde_res);
36
37        Ok(serde_res?)
38    }
39}