refactor
test-org/prometheus-exporter/pipeline/pr-rc This commit looks good Details

pull/16/head
prplV 2025-05-15 12:07:00 -04:00
parent 1c9a38c978
commit 2ccf1840c0
2 changed files with 3 additions and 214 deletions

View File

@ -8,7 +8,7 @@ use prometheus::{ core::Collector, Encoder, GaugeVec, Registry, TextEncoder, pro
use std::{collections::HashMap, fmt::Display, sync::{ Arc, MutexGuard }}; use std::{collections::HashMap, fmt::Display, sync::{ Arc, MutexGuard }};
use crate::AppState; use crate::AppState;
use tracing::{ debug, error, info, warn, trace }; use tracing::{ debug, error, info, warn, trace };
use crate::metrics::{MetricsProcesser, MetricsValueType, IsTaggedWithParams}; use crate::metrics::{MetricsProcesser, MetricsValueType};
use prometheus::opts; use prometheus::opts;
#[derive(Clone)] #[derive(Clone)]
@ -322,7 +322,7 @@ impl CompareGaugeVec for GaugeVec {
break 'outer; break 'outer;
} else { } else {
match (lables.get("status"), new_lables.get("status")) { match (lables.get("status"), new_lables.get("status")) {
(Some(&status), Some(&new_status)) => { (Some(&status), Some(_)) => {
match ( match (
(lables.get("device"), lables.get("module")), (lables.get("device"), lables.get("module")),
(new_lables.get("device"), new_lables.get("module")), (new_lables.get("device"), new_lables.get("module")),
@ -366,100 +366,3 @@ fn get_hashmap_lables_from_metric(metric: &Metric) -> HashMap<&str, &str> {
.map(|pair| (pair.get_name(), pair.get_value())) .map(|pair| (pair.get_name(), pair.get_value()))
.collect::<HashMap<&str, &str>>() .collect::<HashMap<&str, &str>>()
} }
fn get_vectored_lables_from_metric(metric: &Metric) -> Vec<&str> {
metric.get_label()
.iter()
.map(|pair| pair.get_value())
.collect::<Vec<&str>>()
}
struct MeasureLables<'a> {
status : Option<&'a str>,
device : Option<&'a str>,
module : Option<&'a str>,
}
impl<'a> MeasureLables<'a> {
fn new_from_hashed(entry: HashMap<&'a str, &'a str>) -> MeasureLables<'a> {
MeasureLables {
status : entry.get("status").map(|v| &**v),
device : entry.get("device").map(|v| &**v),
module : entry.get("module").map(|v| &**v),
}
}
fn self_type(&'a self) -> LablesList<'a> {
return match self.status {
None => LablesList::Empty,
Some(status) => {
match self.status {
None => LablesList::OnlyStatus(status),
Some(device) => {
match self.module {
None => LablesList::WithDevice(status, device),
Some(module) => LablesList::Full(status, device, module)
}
},
}
},
}
}
}
enum LablesList<'a> {
Full(&'a str, &'a str, &'a str),
WithDevice(&'a str, &'a str),
OnlyStatus(&'a str),
Empty,
}
enum LablesType {
Full,
WithDevice,
OnlyStatus,
Empty,
}
enum CompareLables {
NeedToSave,
Ignore
}
impl<'a> LablesList<'a> {
fn type_of(&'a self) -> LablesType {
return match self {
LablesList::Full(_, _, _) => LablesType::Full,
LablesList::WithDevice(_, _) => LablesType::WithDevice,
LablesList::OnlyStatus(_) => LablesType::OnlyStatus,
LablesList::Empty => LablesType::Empty,
}
}
fn is_changed(&self, other: &'a LablesList) -> CompareLables {
return match (self, other) {
(LablesList::Full(s, d, m),
LablesList::Full(s1, d1, m1)) => {
if s != s1 && d == d1 && m == m1 {
return CompareLables::NeedToSave
}
CompareLables::Ignore
},
(LablesList::WithDevice(s, d),
LablesList::WithDevice(s1, d1)) => {
if s != s1 && d == d1 {
return CompareLables::NeedToSave
}
CompareLables::Ignore
},
(LablesList::OnlyStatus(s),
LablesList::OnlyStatus(s1)) => {
if s != s1 {
return CompareLables::NeedToSave
}
CompareLables::Ignore
},
_ => CompareLables::Ignore,
}
}
}

View File

@ -1,10 +1,7 @@
use std::sync::Arc; use crate::structs::v3::MetricOutput;
use crate::structs::v3::{MetricOutput, PrometheusMetrics};
use serde_json::{Map, Value}; use serde_json::{Map, Value};
use prometheus::Gauge; use prometheus::Gauge;
use tracing::error; use tracing::error;
use prometheus::Opts;
use prometheus::{opts, GaugeVec, core::Collector}; use prometheus::{opts, GaugeVec, core::Collector};
use tracing::{debug, trace}; use tracing::{debug, trace};
@ -100,89 +97,6 @@ impl MetricsProcesser {
} }
None None
} }
pub fn gauge_from_map_metrics(
map: &Map<String, Value>,
service: &str,
endpoint: &str,
) -> Option<Gauge> {
let map = map.clone();
let help: String = map.keys()
.enumerate()
.map(|(idx, key)| {
if idx == 1 {
return key.to_owned();
}
"".to_owned()
})
.collect();
let name = format!("{}_{}_{}", service, endpoint, &help);
if map.len() > 1 {
// tagged
if map.len() > 2 {
error!("Cannot create Gauge {}. It can be only 1 tag", &name);
} else {
let mut label_name = String::new();
let mut label_value = String::new();
let mut metric_value = 0.0;
map.iter()
.enumerate()
.for_each(|(idx, (key, value))|{
if idx == 0 {
label_name = key.to_owned();
label_value = value.as_str()
.unwrap_or("")
.to_owned();
} else {
metric_value = value.as_f64().unwrap_or(0.0)
}
});
let opts = Opts::new(&name, &help);
let gauge_vec = GaugeVec::new(opts, &[&label_name]);
match gauge_vec {
Ok(vec) => {
match vec.get_metric_with_label_values(&[&label_value]) {
Ok(metric) => {
metric.set(metric_value);
return Some(metric.clone());
},
Err(er) => {
error!("Cannot create Gauge {} due to {}", &name, er);
},
}
},
Err(er) => error!("Cannot create Gauge {} due to {}", &name, er),
}
}
} else {
// not-tagged
let metric = Gauge::new(&name, &help);
match metric {
Ok(gauge) => {
let mut value = 0.0;
map.values()
.map(|val| val.clone().as_f64())
.for_each(|val| {
value = val.unwrap_or(0.0)
});
gauge.set(value);
return Some(gauge);
},
Err(er) => {
error!("Cannot create Gauge {} due to {}", &name, er);
}
}
}
None
}
pub fn get_value_as_vec_map(metrics: &MetricOutput) -> Vec<Map<String, Value>>{
let mut vec: Vec<Map<String, Value>> = Vec::new();
let arr = metrics.value.as_array().unwrap();
arr.iter()
.for_each(|a| {
vec.push(serde_json::from_value(a.clone()).unwrap());
});
vec
}
pub fn is_array_of_string_values(metrics: &MetricOutput) -> bool { pub fn is_array_of_string_values(metrics: &MetricOutput) -> bool {
let arr = metrics.value.clone(); let arr = metrics.value.clone();
let arr = arr.as_array().unwrap(); let arr = arr.as_array().unwrap();
@ -192,9 +106,6 @@ impl MetricsProcesser {
map.values() map.values()
.all(|val| val.is_string()) .all(|val| val.is_string())
} }
// fn is_valid(metrics: &PrometheusMetrics) -> bool {
// false
// }
fn is_array(metrics: &MetricOutput) -> bool { fn is_array(metrics: &MetricOutput) -> bool {
metrics.value.is_array() metrics.value.is_array()
} }
@ -208,28 +119,3 @@ impl MetricsProcesser {
.value.is_number() .value.is_number()
} }
} }
trait IsTaggedArray {
fn is_tagged_array(&self) -> bool;
}
impl IsTaggedArray for Value {
fn is_tagged_array(&self) -> bool {
if let Some(arr) = self.as_array() {
return arr[0].get("tag_name").is_some();
}
false
}
}
pub trait IsTaggedWithParams<'a> {
fn with_device_status_and_module(&self) -> bool;
}
impl<'a> IsTaggedWithParams<'a> for PrometheusMetrics<'a> {
fn with_device_status_and_module(&self) -> bool {
self.metrics.iter().any(|metric| metric.module.is_some() && metric.device.is_some())
}
}