subbeat
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.3 KiB

3 years ago
use async_trait::async_trait;
use serde_json::Value;
3 years ago
use crate::{
metric::{Metric, MetricResult},
types,
};
use serde_derive::{Deserialize, Serialize};
use serde_qs as qs;
3 years ago
use super::GrafanaService;
pub struct Prometheus<'a> {
3 years ago
url: String,
3 years ago
query: String,
step: u32,
grafana_service: &'a GrafanaService,
}
#[derive(Deserialize, Serialize)]
struct Query {
query: String,
step: u32,
start: u64,
end: u64,
}
impl<'a> Prometheus<'a> {
3 years ago
pub fn new(
grafana_service: &'a GrafanaService,
url: &str,
query: &str,
step: u32,
) -> Prometheus<'a> {
3 years ago
Prometheus {
3 years ago
url: url.to_owned(),
3 years ago
grafana_service,
query: query.to_string(),
step,
}
}
}
fn parse_result(value: Value) -> types::Result<MetricResult> {
let metric = &value["data"]["result"][0]["metric"];
let metric_name = metric
.as_object()
.unwrap()
.iter()
.map(|(k, v)| format!("{}=\"{}\"", k, v.as_str().unwrap()))
.collect::<Vec<String>>()
.join(",");
let metric_name = format!("{{{}}}", metric_name);
let values = &value["data"]["result"][0]["values"]
.as_array()
.unwrap()
.iter()
.map(|e| {
let r = e.as_array().unwrap();
return (
r[0].as_u64().unwrap(),
r[1].as_str().unwrap().to_string().parse::<f64>().unwrap(),
);
})
.collect::<Vec<(u64, f64)>>();
let mut result = MetricResult::new();
result.insert(metric_name, values.to_owned());
3 years ago
// println!("{:?}", result);
return Ok(result);
}
3 years ago
#[async_trait]
impl Metric for Prometheus<'_> {
async fn query(&self, from: u64, to: u64) -> types::Result<MetricResult> {
let q = Query {
query: self.query.to_owned(),
step: self.step,
start: from,
end: to,
};
3 years ago
3 years ago
// TODO: use serialisatoin from serde
let rq = qs::to_string(&q)?;
3 years ago
let (status_code, value) = self.grafana_service.post_form(&self.url, &rq).await?;
3 years ago
// TODO: return error
// if status_code != StatusCode::OK {
// return std::error::("Bad status code");
// }
// println!("{:?}", value);
3 years ago
return parse_result(value);
3 years ago
}
}