-
Notifications
You must be signed in to change notification settings - Fork 25
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
Metrics exporter to Prometheus with OTLP #1438
Merged
Merged
Changes from 8 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
b57aa09
Add /metrics route for metric backend scraper
92329b5
/metrics endpoint returns prometheus sample metrics with otel
397c390
Merge branch 'private-attribution:main' into main
shinta-liem 68a42b6
Added metrics exporter for prometheus
a8235de
Add conversion from ipa-metric counter to OTLP
3d986b4
Merge branch 'private-attribution:main' into main
shinta-liem dcbbf51
Simplified test case
35fbb2e
Move prometheus exporter to its own crate
ec5e5e4
Merge branch 'private-attribution:main' into main
shinta-liem 92c3a28
Wiring in logging_handle to the handler
d49a6da
Merge branch 'private-attribution:main' into main
shinta-liem 8076f04
Merge branch 'main' into main
shinta-liem 5d7c689
Move metrics out of query module, add test cases
76c6652
cargo fmt
7e1cb2b
Add logging_handle to TestApp
dd2a174
imports
822c659
cargo fmt
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
use axum::{routing::get, Router}; | ||
use hyper::StatusCode; | ||
use opentelemetry::KeyValue; | ||
|
||
use crate::net::{ | ||
http_serde::{self}, | ||
Error, | ||
}; | ||
|
||
use opentelemetry::metrics::MeterProvider; | ||
use opentelemetry_sdk::metrics::SdkMeterProvider; | ||
use prometheus::{self, Encoder, TextEncoder}; | ||
|
||
/// Takes details from the HTTP request and creates a `[TransportCommand]::CreateQuery` that is sent | ||
/// to the [`HttpTransport`]. | ||
async fn handler(// transport: Extension<MpcHttpTransport>, | ||
// QueryConfigQueryParams(query_config): QueryConfigQueryParams, | ||
) -> Result<Vec<u8>, Error> { | ||
// match transport.dispatch(query_config, BodyStream::empty()).await { | ||
// Ok(resp) => Ok(Json(resp.try_into()?)), | ||
// Err(err @ ApiError::NewQuery(NewQueryError::State { .. })) => { | ||
// Err(Error::application(StatusCode::CONFLICT, err)) | ||
// } | ||
// Err(err) => Err(Error::application(StatusCode::INTERNAL_SERVER_ERROR, err)), | ||
// } | ||
|
||
// TODO: Remove this dummy metrics and get metrics for scraper from ipa-metrics::PrometheusMetricsExporter (see ipa-metrics/exporter.rs) | ||
|
||
// create a new prometheus registry | ||
let registry = prometheus::Registry::new(); | ||
|
||
// configure OpenTelemetry to use this registry | ||
let exporter = opentelemetry_prometheus::exporter() | ||
.with_registry(registry.clone()) | ||
.build() | ||
.unwrap(); | ||
|
||
// set up a meter to create instruments | ||
let provider = SdkMeterProvider::builder().with_reader(exporter).build(); | ||
let meter = provider.meter("ipa-helper"); | ||
|
||
// Use two instruments | ||
let counter = meter | ||
.u64_counter("a.counter") | ||
.with_description("Counts things") | ||
.init(); | ||
let histogram = meter | ||
.u64_histogram("a.histogram") | ||
.with_description("Records values") | ||
.init(); | ||
|
||
counter.add(100, &[KeyValue::new("key", "value")]); | ||
histogram.record(100, &[KeyValue::new("key", "value")]); | ||
|
||
// Encode data as text or protobuf | ||
let encoder = TextEncoder::new(); | ||
let metric_families = registry.gather(); | ||
let mut result = Vec::new(); | ||
match encoder.encode(&metric_families, &mut result) { | ||
Ok(()) => Ok(result), | ||
Err(err) => Err(Error::application(StatusCode::INTERNAL_SERVER_ERROR, err)), | ||
} | ||
} | ||
|
||
pub fn router() -> Router { | ||
Router::new().route(http_serde::metrics::AXUM_PATH, get(handler)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
[package] | ||
name = "ipa-metrics-prometheus" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[features] | ||
default = [] | ||
|
||
[dependencies] | ||
ipa-metrics = { path = "../ipa-metrics" } | ||
|
||
# Open telemetry crates: opentelemetry-prometheus crate implementation is based on Opentelemetry API and SDK 0.23. (TBC) | ||
opentelemetry = "0.24" | ||
opentelemetry_sdk = { version = "0.24", features = ["metrics", "rt-tokio"] } | ||
opentelemetry-prometheus = { version = "0.17" } | ||
prometheus = "0.13.3" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
use std::io; | ||
|
||
use opentelemetry::metrics::{Meter, MeterProvider}; | ||
use opentelemetry::KeyValue; | ||
use opentelemetry_sdk::metrics::SdkMeterProvider; | ||
use prometheus::{self, Encoder, TextEncoder}; | ||
|
||
use ipa_metrics::MetricsStore; | ||
|
||
pub trait PrometheusMetricsExporter { | ||
fn export<W: io::Write>(&mut self, w: &mut W); | ||
} | ||
|
||
impl PrometheusMetricsExporter for MetricsStore { | ||
fn export<W: io::Write>(&mut self, w: &mut W) { | ||
// Setup prometheus registry and open-telemetry exporter | ||
let registry = prometheus::Registry::new(); | ||
|
||
let exporter = opentelemetry_prometheus::exporter() | ||
.with_registry(registry.clone()) | ||
.build() | ||
.unwrap(); | ||
|
||
let meter_provider = SdkMeterProvider::builder().with_reader(exporter).build(); | ||
|
||
// Convert the snapshot to otel struct | ||
// TODO : We need to define a proper scope for the metrics | ||
let meter = meter_provider.meter("ipa-helper"); | ||
|
||
let counters = self.counters(); | ||
counters.for_each(|(counter_name, counter_value)| { | ||
let otlp_counter = meter.u64_counter(counter_name.key).init(); | ||
|
||
let attributes: Vec<KeyValue> = counter_name | ||
.labels() | ||
.map(|l| KeyValue::new(l.name, l.val.to_string())) | ||
.collect(); | ||
|
||
otlp_counter.add(counter_value, &attributes[..]); | ||
}); | ||
|
||
let encoder = TextEncoder::new(); | ||
let metric_families = registry.gather(); | ||
// TODO: Handle error? | ||
encoder.encode(&metric_families, w).unwrap(); | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
|
||
use std::thread; | ||
|
||
use ipa_metrics::{counter, install_new_thread, MetricChannelType}; | ||
|
||
use super::PrometheusMetricsExporter; | ||
|
||
#[test] | ||
fn export_to_prometheus() { | ||
let (producer, controller, _) = install_new_thread(MetricChannelType::Rendezvous).unwrap(); | ||
|
||
thread::spawn(move || { | ||
producer.install(); | ||
counter!("baz", 4); | ||
counter!("bar", 1); | ||
let _ = producer.drop_handle(); | ||
}) | ||
.join() | ||
.unwrap(); | ||
|
||
let mut store = controller.snapshot().unwrap(); | ||
|
||
let mut buff = Vec::new(); | ||
store.export(&mut buff); | ||
|
||
let result = String::from_utf8(buff).unwrap(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be good to validate the results somehow. Also consider removing the println. |
||
println!("Export to Prometheus: {result}"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
mod exporter; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,4 +17,3 @@ hashbrown = "0.15" | |
rustc-hash = "2.0.0" | ||
# logging | ||
tracing = "0.1" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,6 +20,7 @@ use hashbrown::hash_map::Entry; | |
use rustc_hash::FxBuildHasher; | ||
|
||
use crate::{ | ||
key::OwnedMetricName, | ||
kind::CounterValue, | ||
store::{CounterHandle, Store}, | ||
MetricName, | ||
|
@@ -120,6 +121,10 @@ impl PartitionedStore { | |
self.get_mut(CurrentThreadContext::get()).counter(key) | ||
} | ||
|
||
pub fn counters(&mut self) -> impl Iterator<Item = (&OwnedMetricName, CounterValue)> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is |
||
self.get_mut(CurrentThreadContext::get()).counters() | ||
} | ||
|
||
#[must_use] | ||
pub fn len(&self) -> usize { | ||
self.inner.len() + self.default_store.len() | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@akoshelev I'm still not clear how we can pull the metrics from the logging_handle. IpaHttpClient doesn't seem to have a reference to it?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
that's right, it is not referenced from anywhere.
helper.rs
does have logging_handle that has a reference to this controller. So we need to plumb it through to deliverController
to the handlers