Compare commits
No commits in common. "ab1ed5a57c271132a75e0e63bfad6649e9b01b98" and "3ff97a5222008c8fc5fe546bca927ce563d9e873" have entirely different histories.
ab1ed5a57c
...
3ff97a5222
|
|
@ -1,8 +1,3 @@
|
|||
# port binding for prometheus-exporter
|
||||
# default value = 9100
|
||||
PROMETHEUS_EXPORTER_PORT = 9100
|
||||
|
||||
# setting up max level of logging
|
||||
# default - INFO
|
||||
# values : WARN, ERROR, INFO, DEBUG, TRACE
|
||||
PROMETHEUS_EXPORTER_LOG_LEVEL = "TRACE"
|
||||
|
|
@ -4,27 +4,12 @@ use axum::{
|
|||
http
|
||||
};
|
||||
use crate::structs::v3::PrometheusMetrics;
|
||||
use prometheus::{ core::Collector, Encoder, Gauge, Registry, TextEncoder};
|
||||
use std::{cell::RefCell, rc::Rc, sync::{ Arc, MutexGuard }};
|
||||
use prometheus::{ Encoder, Gauge, Registry, TextEncoder};
|
||||
use std::sync::{ Arc, MutexGuard };
|
||||
use crate::AppState;
|
||||
use tracing::{ debug, error, info, warn, trace };
|
||||
use tracing::{ debug, error, info, warn };
|
||||
use crate::metrics::{MetricsProcesser, MetricsValueType};
|
||||
|
||||
struct BoxCollectorProducer {
|
||||
inner : *mut dyn Collector,
|
||||
}
|
||||
|
||||
impl BoxCollectorProducer {
|
||||
pub fn new(target: Box<dyn Collector>) -> Self {
|
||||
Self {
|
||||
inner : Box::into_raw(target)
|
||||
}
|
||||
}
|
||||
pub fn new_box(&self) -> Box<dyn Collector> {
|
||||
unsafe { Box::from_raw(self.inner) }
|
||||
}
|
||||
}
|
||||
|
||||
/// An `Update` endpoint
|
||||
///
|
||||
/// Used to registrate new metrics and to update already
|
||||
|
|
@ -33,14 +18,14 @@ impl BoxCollectorProducer {
|
|||
/// # Usage
|
||||
///
|
||||
/// ``` bash
|
||||
/// curl -X POST -d '...' 'http::/localhost:9100/update'
|
||||
/// curl -X POST -d '"id" : ...' 'http::/localhost:9100/update'
|
||||
/// ```
|
||||
///
|
||||
pub async fn update_metrics(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(request) : Json<PrometheusMetrics<'_>>
|
||||
) -> impl IntoResponse {
|
||||
trace!("post on /update");
|
||||
info!("post on /update");
|
||||
let service = &request.service_name;
|
||||
let endpoint = &request.endpoint_name;
|
||||
|
||||
|
|
@ -50,11 +35,9 @@ pub async fn update_metrics(
|
|||
match MetricsProcesser::get_type_of_value(&i) {
|
||||
MetricsValueType::Array |
|
||||
MetricsValueType::TaggedArray => {
|
||||
trace!("processing an array of metrics");
|
||||
// ...
|
||||
|
||||
},
|
||||
MetricsValueType::Number => {
|
||||
trace!("processing a number type of metric");
|
||||
let gauge = MetricsProcesser::gauge_from_number(
|
||||
&i,
|
||||
&metric_name,
|
||||
|
|
@ -77,11 +60,9 @@ pub async fn update_metrics(
|
|||
}
|
||||
},
|
||||
MetricsValueType::ArrayOfStrings => {
|
||||
trace!("processing an array of strings");
|
||||
warn!("String arrays are unsupported, ignoring ...");
|
||||
},
|
||||
_ => {
|
||||
trace!("processing unrecognized type of metric");
|
||||
warn!("Unrecognized metric type was supplied, ignoring ...");
|
||||
}
|
||||
}
|
||||
|
|
@ -102,18 +83,13 @@ pub async fn update_metrics(
|
|||
/// ```
|
||||
///
|
||||
pub async fn metrics_handler(State(state): State<Arc<AppState>>) -> String {
|
||||
trace!("get on /metrics");
|
||||
let registry = state.registry.lock();
|
||||
|
||||
debug!("registry mutex lock is {}", registry.is_ok());
|
||||
return match registry {
|
||||
Ok(registry) => {
|
||||
let encoder = TextEncoder::new();
|
||||
let mut buffer = Vec::new();
|
||||
let metric_families = registry.gather();
|
||||
|
||||
debug!("vec of metric families - {:?}", &metric_families);
|
||||
|
||||
encoder.encode(&metric_families, &mut buffer).unwrap();
|
||||
String::from_utf8(buffer).unwrap()
|
||||
},
|
||||
|
|
@ -129,17 +105,13 @@ pub async fn metrics_handler(State(state): State<Arc<AppState>>) -> String {
|
|||
/// `Registry`
|
||||
///
|
||||
pub fn update_or_insert_metric<'a>(
|
||||
metric: Box<dyn Collector>,
|
||||
metric: Gauge,
|
||||
registry: MutexGuard<'a, Registry>,
|
||||
metric_name: &str
|
||||
) -> anyhow::Result<()> {
|
||||
trace!("fn update_or_insert_metric is running");
|
||||
use prometheus::Error;
|
||||
// let mut counter = 0;
|
||||
// let ptr = Box::into_raw(metric);
|
||||
let prod = BoxCollectorProducer::new(metric);
|
||||
|
||||
match registry.register(prod.new_box()) {
|
||||
match registry.register(Box::new(metric.clone())) {
|
||||
Ok(_) => {
|
||||
info!("Metric `{}` was registered!", metric_name);
|
||||
},
|
||||
|
|
@ -147,10 +119,10 @@ pub fn update_or_insert_metric<'a>(
|
|||
// update or throw away
|
||||
match er {
|
||||
Error::AlreadyReg => {
|
||||
trace!("processing already regged metric");
|
||||
match registry.unregister(prod.new_box()) {
|
||||
|
||||
match registry.unregister(Box::new(metric.clone())) {
|
||||
Ok(_) => {
|
||||
if let Err(er) = registry.register(prod.new_box()) {
|
||||
if let Err(er) = registry.register(Box::new(metric)) {
|
||||
warn!("Cannot update metric `{}`", metric_name);
|
||||
return Err(anyhow::Error::msg(
|
||||
format!("Cannot update metric `{}` due to {}", metric_name, er)
|
||||
|
|
|
|||
24
src/main.rs
24
src/main.rs
|
|
@ -11,7 +11,7 @@ use axum::{
|
|||
routing::{get, post},
|
||||
Router};
|
||||
use prometheus::Registry;
|
||||
use std::{str::FromStr, sync::{Arc, Mutex}};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use endpoints::*;
|
||||
use tokio::net::TcpListener;
|
||||
use tracing::info;
|
||||
|
|
@ -27,22 +27,12 @@ struct AppState {
|
|||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
dotenv().ok();
|
||||
|
||||
let log_level = std::env::var("PROMETHEUS_EXPORTER_LOG_LEVEL")
|
||||
.unwrap_or_else(|_| "INFO".to_owned());
|
||||
|
||||
tracing_subscriber::fmt()
|
||||
.with_max_level(tracing::Level::from_str(&log_level).unwrap_or_else(|_| tracing::Level::INFO))
|
||||
.with_writer(std::io::stdout)
|
||||
.with_span_events(tracing_subscriber::fmt::format::FmtSpan::NEW)
|
||||
.with_line_number(false)
|
||||
.with_target(false)
|
||||
.with_file(false)
|
||||
.compact()
|
||||
.with_max_level(tracing::Level::DEBUG)
|
||||
.init();
|
||||
|
||||
info!("Loading env vars from .env if exists ...");
|
||||
dotenv().ok();
|
||||
|
||||
info!("Initializing local Prometehus metrics registry ...");
|
||||
let registry = Registry::new();
|
||||
|
|
@ -59,12 +49,10 @@ async fn main() -> anyhow::Result<()> {
|
|||
.route("/update", post(update_metrics))
|
||||
.with_state(state.clone());
|
||||
|
||||
let port = std::env::var("PROMETHEUS_EXPORTER_PORT")
|
||||
.unwrap_or_else(|_| "9100".to_owned());
|
||||
let bind_address = format!("0.0.0.0:{}", &port);
|
||||
let listener = TcpListener::bind(bind_address).await?;
|
||||
let bind_address = format!("0.0.0.0:{}", std::env::var("PROMETHEUS_EXPORTER_PORT").unwrap_or_else(|_| "9100".to_owned()));
|
||||
let listener = TcpListener::bind(bind_address).await.unwrap();
|
||||
|
||||
info!("Serving on ...:{}", &port);
|
||||
info!("Serving on ...:9100");
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,12 +1,9 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use crate::structs::v3::MetricOutput;
|
||||
use serde_json::{Map, Value};
|
||||
use prometheus::Gauge;
|
||||
use tracing::error;
|
||||
use prometheus::Opts;
|
||||
use prometheus::{opts, GaugeVec, core::Collector};
|
||||
use tracing::{debug, trace};
|
||||
use prometheus::GaugeVec;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MetricsValueType {
|
||||
|
|
@ -21,25 +18,20 @@ pub struct MetricsProcesser;
|
|||
|
||||
|
||||
impl MetricsProcesser {
|
||||
|
||||
pub fn get_type_of_value(metrics: &MetricOutput) -> MetricsValueType {
|
||||
trace!("defining metric type");
|
||||
if Self::is_number(metrics) {
|
||||
debug!("processing Number");
|
||||
return MetricsValueType::Number;
|
||||
}
|
||||
else if Self::is_array(metrics) {
|
||||
if Self::is_tagged_array(metrics) {
|
||||
debug!("processing TaggedArray");
|
||||
return MetricsValueType::TaggedArray;
|
||||
}
|
||||
if Self::is_array_of_string_values(metrics) {
|
||||
debug!("processing ArrayOfStrings");
|
||||
return MetricsValueType::ArrayOfStrings;
|
||||
}
|
||||
debug!("processing Array");
|
||||
return MetricsValueType::Array;
|
||||
}
|
||||
debug!("processing undefined type");
|
||||
MetricsValueType::None
|
||||
}
|
||||
|
||||
|
|
@ -48,14 +40,7 @@ impl MetricsProcesser {
|
|||
metric: &MetricOutput,
|
||||
metric_name: &str,
|
||||
metric_desc: &str
|
||||
) -> Option<Box<dyn Collector>> {
|
||||
trace!("fn gauge_from_number is running");
|
||||
if let Some(status) = metric.status {
|
||||
let vec = GaugeVec::new(opts!(metric_name, metric_desc), &["status"]).unwrap();
|
||||
vec.with_label_values(&[&status.to_string()]).set(metric.value.as_f64().unwrap_or_else(|| 0.0));
|
||||
return Some(Box::new(vec));
|
||||
}
|
||||
|
||||
) -> Option<Gauge> {
|
||||
let gauge = Gauge::new(
|
||||
metric_name,
|
||||
metric_desc
|
||||
|
|
@ -63,6 +48,10 @@ impl MetricsProcesser {
|
|||
|
||||
match gauge {
|
||||
Ok(gauge) => {
|
||||
// let value = metric.value.as_number().unwrap_or({
|
||||
// error!("Cannot convert {} metric value to f64 type. Value was set to 0.0", &metric_name);
|
||||
// });
|
||||
// let value = value.as_f64()
|
||||
let val = match metric.value.as_number() {
|
||||
Some(val) => {
|
||||
val.as_f64().unwrap_or_else(||
|
||||
|
|
@ -75,8 +64,7 @@ impl MetricsProcesser {
|
|||
},
|
||||
};
|
||||
gauge.set(val);
|
||||
debug!("processed metric: {:?}", &gauge);
|
||||
return Some(Box::new(gauge));
|
||||
return Some(gauge);
|
||||
},
|
||||
Err(er) => error!("Cannot create Gauge metric {} due to {}", &metric_name, er),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,6 @@ pub mod v3 {
|
|||
pub value : Value,
|
||||
#[serde(rename = "description")]
|
||||
pub desc : Option<Cow<'a, String>>,
|
||||
pub status: Option<isize>
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
|
|
|
|||
Loading…
Reference in New Issue