Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement metrics expiry #196

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ http-body-util = "0.1.1"
[build-dependencies]
prost-build = { version = "0.12.0", optional = true }

[[example]]
name = "prune"

[[bench]]
name = "baseline"
harness = false
Expand Down
84 changes: 84 additions & 0 deletions examples/prune.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
use prometheus_client::encoding::{text::encode, EncodeMetric, MetricEncoder};
use prometheus_client::metrics::counter::Atomic;
use prometheus_client::metrics::family::Family;
use prometheus_client::metrics::{MetricType, TypedMetric};
use prometheus_client::registry::Registry;
use prometheus_client_derive_encode::EncodeLabelSet;
use std::fmt::Error;
use std::sync::atomic::AtomicU64;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use tokio::time::Instant;

#[derive(Default, Debug)]
struct MyCounter {
value: Arc<AtomicU64>,
last_access: Arc<Mutex<Option<Instant>>>,
}

impl TypedMetric for MyCounter {}

impl MyCounter {
pub fn get(&self) -> u64 {
self.value.get()
}
pub fn inc(&self) -> u64 {
let mut last = self.last_access.lock().unwrap();
*last = Some(Instant::now());
self.value.inc()
}
}

impl EncodeMetric for MyCounter {
fn encode(&self, mut encoder: MetricEncoder) -> Result<(), Error> {
encoder.encode_counter::<(), _, u64>(&self.get(), None)

Check failure on line 35 in examples/prune.rs

View workflow job for this annotation

GitHub Actions / Clippy

the trait bound `(): prometheus_client::encoding::EncodeLabelSet` is not satisfied

Check failure on line 35 in examples/prune.rs

View workflow job for this annotation

GitHub Actions / Test Suite

the trait bound `(): EncodeLabelSet` is not satisfied
}

fn metric_type(&self) -> MetricType {
todo!()
}
}

#[derive(Clone, Hash, Default, Debug, PartialEq, Eq, EncodeLabelSet)]
struct Labels {
name: String,
}

fn main() {
let mut registry = Registry::default();

let metric: Family<Labels, MyCounter> = Family::default();
registry.register("my_custom_metric", "test", metric.clone());
metric
.get_or_create(&Labels {
name: "apple".to_string(),
})
.inc();
metric
.get_or_create(&Labels {
name: "banana".to_string(),
})
.inc();

let mut encoded = String::new();
encode(&mut encoded, &registry).unwrap();

println!("Scrape output:\n{}", encoded);
thread::sleep(Duration::from_secs(1));
metric
.get_or_create(&Labels {
name: "banana".to_string(),
})
.inc();
let now = Instant::now();
metric.retain(|a, b| {

Check failure on line 75 in examples/prune.rs

View workflow job for this annotation

GitHub Actions / Clippy

unused variable: `a`

Check warning on line 75 in examples/prune.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused variable: `a`
let last = b.last_access.lock().unwrap().unwrap();
now.saturating_duration_since(last) > Duration::from_secs(1)
});

let mut encoded = String::new();
encode(&mut encoded, &registry).unwrap();

println!("Scrape output:\n{}", encoded);
}
8 changes: 8 additions & 0 deletions src/metrics/family.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,14 @@ impl<S: Clone + std::hash::Hash + Eq, M, C: MetricConstructor<M>> Family<S, M, C
self.metrics.write().clear()
}

/// retain
pub fn retain<F>(&self, f: F)
where
F: FnMut(&S, &mut M) -> bool,
{
self.metrics.write().retain(f)
}

pub(crate) fn read(&self) -> RwLockReadGuard<HashMap<S, M>> {
self.metrics.read()
}
Expand Down
Loading