-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmetrics.rs
99 lines (93 loc) · 2.96 KB
/
metrics.rs
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
use anyhow::Result;
use reqwest::Client;
use resources::{
models::Response,
objects::{
metrics::{FunctionMetric, PodMetric, PodMetrics, PodMetricsInfo, Resource},
Labels,
},
};
use crate::CONFIG;
pub struct MetricsClient {
client: Client,
}
impl MetricsClient {
pub fn new() -> Self {
Self {
client: reqwest::Client::new(),
}
}
/// Get pod metrics in raw value
pub async fn get_resource_metric_value(
&self,
resource: &Resource,
selector: &Labels,
) -> Result<PodMetricsInfo> {
let metrics = self.get_pod_metrics(selector).await?;
if metrics.is_empty() {
Err(anyhow::anyhow!("No metrics found"))
} else {
let mut metric_info = PodMetricsInfo::new();
for pod in metrics {
let mut sum = 0;
if pod.containers.is_empty() {
continue;
}
for container in pod.containers {
let usage = container.usage.get(resource);
match usage {
Some(usage) => sum += *usage,
None => {
tracing::debug!(
"Missing resource metric {} for container {} in pod {}",
resource,
container.name,
pod.name
);
break;
},
}
}
metric_info.insert(
pod.name,
PodMetric {
timestamp: pod.timestamp,
window: pod.window,
value: sum,
},
);
}
Ok(metric_info)
}
}
async fn get_pod_metrics(&self, selector: &Labels) -> Result<Vec<PodMetrics>> {
let response = self
.client
.get(format!("{}/api/v1/metrics/pods", CONFIG.api_server_url,))
.query::<Vec<(&str, String)>>(&vec![("selector", selector.to_string())])
.send()
.await?
.json::<Response<Vec<PodMetrics>>>()
.await?;
match response.data {
Some(data) => Ok(data),
None => Err(anyhow::anyhow!("Failed to get pod metrics")),
}
}
pub async fn get_function_metric(&self, func_name: &str) -> Result<FunctionMetric> {
let response = self
.client
.get(format!(
"{}/api/v1/metrics/functions/{}",
CONFIG.api_server_url, func_name
))
.send()
.await?
.json::<Response<FunctionMetric>>()
.await?;
match response.data {
Some(data) => Ok(data),
None => Err(anyhow::anyhow!("Failed to get function metrics")),
}
}
}