refactor: extract iroh-metrics into its own repo (#2989)

## Description

Lives now in https://github.com/n0-computer/iroh-metrics

## Breaking Changes

<!-- Optional, if there are any breaking changes document them,
including how to migrate older code. -->

## Notes & open questions

<!-- Any notes, remarks or open questions you have to make about the PR.
-->

## Change checklist

- [x] Self-review.
- [x] Documentation updates following the [style
guide](https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html#appendix-a-full-conventions-text),
if relevant.
- [x] Tests if relevant.
- [x] All breaking changes documented.
This commit is contained in:
Friedel Ziegelmayer
2024-12-02 17:21:39 +00:00
committed by GitHub
parent 8c00f7b68e
commit df591bcea3
16 changed files with 12 additions and 610 deletions
+1 -1
View File
@@ -189,7 +189,7 @@ jobs:
# uses: obi1kenobi/cargo-semver-checks-action@v2
uses: n0-computer/cargo-semver-checks-action@feat-baseline
with:
package: iroh, iroh-base, iroh-dns-server, iroh-metrics, iroh-net-bench, iroh-node-util, netwatch, portmapper, iroh-relay, iroh-net-report
package: iroh, iroh-base, iroh-dns-server, iroh-net-bench, iroh-node-util, netwatch, portmapper, iroh-relay, iroh-net-report
baseline-rev: ${{ env.HEAD_COMMIT_SHA }}
use-cache: false
+1 -1
View File
@@ -23,7 +23,7 @@ env:
RUSTFLAGS: -Dwarnings
RUSTDOCFLAGS: -Dwarnings
SCCACHE_CACHE_SIZE: "10G"
CRATES_LIST: "iroh,iroh-node-util,iroh-metrics,iroh-net-bench,iroh-test,iroh-dns-server,netwatch,portmapper,iroh-relay,iroh-net-report"
CRATES_LIST: "iroh,iroh-node-util,iroh-net-bench,iroh-test,iroh-dns-server,netwatch,portmapper,iroh-relay,iroh-net-report"
IROH_FORCE_STAGING_RELAYS: "1"
jobs:
Generated
+4 -2
View File
@@ -1279,9 +1279,9 @@ dependencies = [
[[package]]
name = "erased_set"
version = "0.8.0"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a02a5d186d7bf1cb21f1f95e1a9cfa5c1f2dcd803a47aad454423ceec13525c5"
checksum = "76a5aa24577083f8190ad401e376b55887c7cd9083ae95d83ceec5d28ea78125"
[[package]]
name = "errno"
@@ -2568,6 +2568,8 @@ dependencies = [
[[package]]
name = "iroh-metrics"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0d40f2ee3997489d47403d204a06514ed65373d224b5b43a8ea133f543e5db1"
dependencies = [
"anyhow",
"erased_set",
-1
View File
@@ -2,7 +2,6 @@
members = [
"iroh-base",
"iroh-dns-server",
"iroh-metrics",
"iroh",
"iroh-test",
"iroh/bench",
+1 -1
View File
@@ -29,7 +29,7 @@ governor = "0.6.3" #needs new release of tower_governor for 0.7.0
hickory-proto = "=0.25.0-alpha.2"
hickory-server = { version = "=0.25.0-alpha.2", features = ["dns-over-rustls"] }
http = "1.0.0"
iroh-metrics = { version = "0.28.0", path = "../iroh-metrics" }
iroh-metrics = "0.28"
lru = "0.12.3"
parking_lot = "0.12.1"
pkarr = { version = "2.2.0", features = [ "async", "relay", "dht"], default-features = false }
-40
View File
@@ -1,40 +0,0 @@
[package]
name = "iroh-metrics"
version = "0.28.0"
edition = "2021"
readme = "README.md"
description = "metrics for iroh"
license = "MIT OR Apache-2.0"
authors = ["arqu <asmir@n0.computer>", "n0 team"]
repository = "https://github.com/n0-computer/iroh"
# Sadly this also needs to be updated in .github/workflows/ci.yml
rust-version = "1.76"
[lints]
workspace = true
[dependencies]
anyhow = { version = "1" }
erased_set = "0.8"
http-body-util = "0.1.0"
hyper = { version = "1", features = ["server", "http1"] }
hyper-util = { version = "0.1.1", features = ["tokio"] }
once_cell = "1.17.0"
prometheus-client = { version = "0.22", optional = true }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1", features = ["derive"] }
struct_iterable = "0.1"
time = { version = "0.3.21", features = ["serde-well-known"] }
tokio = { version = "1", features = ["rt", "net", "fs"]}
tracing = "0.1"
[dev-dependencies]
tokio = { version = "1", features = ["io-util", "sync", "rt", "net", "fs", "macros", "time", "test-util"] }
[features]
default = ["metrics"]
metrics = ["prometheus-client"]
[package.metadata.docs.rs]
all-features = true
-22
View File
@@ -1,22 +0,0 @@
# iroh-metrics
Metrics collection for iroh. It keeps the "glue" necessary to expose metrics defined metrics for collection: an HTTP server that exposes tracked metrics that a service like prometheus can poll for recording.
Nearly all metrics in iroh are recorded as simple counters.
# License
This project is licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this project by you, as defined in the Apache-2.0 license,
shall be dual licensed as above, without any additional terms or conditions.
-196
View File
@@ -1,196 +0,0 @@
use erased_set::ErasedSyncSet;
use once_cell::sync::OnceCell;
#[cfg(feature = "metrics")]
use prometheus_client::{encoding::text::encode, registry::Registry};
#[cfg(not(feature = "metrics"))]
type Registry = ();
static CORE: OnceCell<Core> = OnceCell::new();
/// Core is the base metrics struct.
///
/// It manages the mapping between the metrics name and the actual metrics.
/// It also carries a single prometheus registry to be used by all metrics.
#[derive(Debug, Default)]
pub struct Core {
#[cfg(feature = "metrics")]
registry: Registry,
metrics_map: ErasedSyncSet,
}
/// Open Metrics [`Counter`] to measure discrete events.
///
/// Single monotonically increasing value metric.
#[derive(Debug, Clone)]
pub struct Counter {
/// The actual prometheus counter.
#[cfg(feature = "metrics")]
pub counter: prometheus_client::metrics::counter::Counter,
/// What this counter measures.
pub description: &'static str,
}
impl Counter {
/// Constructs a new counter, based on the given `description`.
pub fn new(description: &'static str) -> Self {
Counter {
#[cfg(feature = "metrics")]
counter: Default::default(),
description,
}
}
/// Increase the [`Counter`] by 1, returning the previous value.
pub fn inc(&self) -> u64 {
#[cfg(feature = "metrics")]
{
self.counter.inc()
}
#[cfg(not(feature = "metrics"))]
0
}
/// Increase the [`Counter`] by `u64`, returning the previous value.
#[cfg(feature = "metrics")]
pub fn inc_by(&self, v: u64) -> u64 {
self.counter.inc_by(v)
}
/// Set the [`Counter`] value.
/// Warning: this is not default behavior for a counter that should always be monotonically increasing.
#[cfg(feature = "metrics")]
pub fn set(&self, v: u64) -> u64 {
self.counter
.inner()
.store(v, std::sync::atomic::Ordering::Relaxed);
v
}
/// Set the [`Counter`] value.
/// Warning: this is not default behavior for a counter that should always be monotonically increasing.
#[cfg(not(feature = "metrics"))]
pub fn set(&self, _v: u64) -> u64 {
0
}
/// Increase the [`Counter`] by `u64`, returning the previous value.
#[cfg(not(feature = "metrics"))]
pub fn inc_by(&self, _v: u64) -> u64 {
0
}
/// Get the current value of the [`Counter`].
pub fn get(&self) -> u64 {
#[cfg(feature = "metrics")]
{
self.counter.get()
}
#[cfg(not(feature = "metrics"))]
0
}
}
/// Description of a group of metrics.
pub trait Metric:
Default + struct_iterable::Iterable + Sized + std::fmt::Debug + 'static + Send + Sync
{
/// Initializes this metric group.
#[cfg(feature = "metrics")]
fn new(registry: &mut prometheus_client::registry::Registry) -> Self {
let sub_registry = registry.sub_registry_with_prefix(Self::name());
let this = Self::default();
for (metric, counter) in this.iter() {
if let Some(counter) = counter.downcast_ref::<Counter>() {
sub_registry.register(metric, counter.description, counter.counter.clone());
}
}
this
}
/// Initializes this metric group.
#[cfg(not(feature = "metrics"))]
fn new(_: &mut ()) -> Self {
Self::default()
}
/// The name of this metric group.
fn name() -> &'static str;
/// Access to this metrics group to record a metric.
/// Only records if this metric is registered in the global registry.
#[cfg(feature = "metrics")]
fn with_metric<T, F: FnOnce(&Self) -> T>(f: F) {
Self::try_get().map(f);
}
/// Access to this metrics group to record a metric.
#[cfg(not(feature = "metrics"))]
fn with_metric<T, F: FnOnce(&Self) -> T>(_f: F) {
// nothing to do
}
/// Attempts to get the current metric from the global registry.
fn try_get() -> Option<&'static Self> {
Core::get().and_then(|c| c.get_collector::<Self>())
}
}
impl Core {
/// Must only be called once to init metrics.
///
/// Panics if called a second time.
pub fn init<F: FnOnce(&mut Registry, &mut ErasedSyncSet)>(f: F) {
Self::try_init(f).expect("must only be called once");
}
/// Trieds to init the metrics.
pub fn try_init<F: FnOnce(&mut Registry, &mut ErasedSyncSet)>(f: F) -> std::io::Result<()> {
let mut registry = Registry::default();
let mut metrics_map = ErasedSyncSet::new();
f(&mut registry, &mut metrics_map);
CORE.set(Core {
metrics_map,
#[cfg(feature = "metrics")]
registry,
})
.map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "already set"))
}
/// Returns a reference to the core metrics.
pub fn get() -> Option<&'static Self> {
CORE.get()
}
/// Returns a reference to the prometheus registry.
#[cfg(feature = "metrics")]
pub fn registry(&self) -> &Registry {
&self.registry
}
/// Returns a reference to the mapped metrics instance.
pub fn get_collector<T: Metric>(&self) -> Option<&T> {
self.metrics_map.get::<T>()
}
/// Encodes the current metrics registry to a string in
/// the prometheus text exposition format.
#[cfg(feature = "metrics")]
pub fn encode(&self) -> Result<String, std::fmt::Error> {
let mut buf = String::new();
encode(&mut buf, &self.registry)?;
Ok(buf)
}
}
/// Interface for all single value based metrics.
pub trait MetricType {
/// Returns the name of the metric
fn name(&self) -> &'static str;
}
/// Interface for all distribution based metrics.
pub trait HistogramType {
/// Returns the name of the metric
fn name(&self) -> &'static str;
}
-91
View File
@@ -1,91 +0,0 @@
//! Metrics library for iroh
#![deny(missing_docs, rustdoc::broken_intra_doc_links)]
pub mod metrics;
/// Expose core types and traits
pub mod core;
/// Expose iroh metrics
#[cfg(feature = "metrics")]
mod service;
use std::collections::HashMap;
/// Reexport to make matching versions easier.
pub use struct_iterable;
/// Increment the given counter by 1.
#[macro_export]
macro_rules! inc {
($m:ty, $f:ident) => {
<$m as $crate::core::Metric>::with_metric(|m| m.$f.inc());
};
}
/// Increment the given counter `n`.
#[macro_export]
macro_rules! inc_by {
($m:ty, $f:ident, $n:expr) => {
<$m as $crate::core::Metric>::with_metric(|m| m.$f.inc_by($n));
};
}
/// Set the given counter to `n`.
#[macro_export]
macro_rules! set {
($m:ty, $f:ident, $n:expr) => {
<$m as $crate::core::Metric>::with_metric(|m| m.$f.set($n));
};
}
/// Parse Prometheus metrics from a string.
pub fn parse_prometheus_metrics(data: &str) -> anyhow::Result<HashMap<String, f64>> {
let mut metrics = HashMap::new();
for line in data.lines() {
if line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 2 {
continue;
}
let metric = parts[0];
let value = parts[1].parse::<f64>();
if value.is_err() {
continue;
}
metrics.insert(metric.to_string(), value.unwrap());
}
Ok(metrics)
}
/// Configuration for pushing metrics to a remote endpoint.
#[derive(PartialEq, Eq, Debug, Default, serde::Deserialize, Clone)]
pub struct PushMetricsConfig {
/// The push interval in seconds.
pub interval: u64,
/// The endpoint url for the push metrics collector.
pub endpoint: String,
/// The name of the service you're exporting metrics for.
///
/// Generally, `metrics_exporter` is good enough for use
/// outside of production deployments.
pub service_name: String,
/// The name of the instance you're exporting metrics for.
///
/// This should be device-unique. If not, this will sum up
/// metrics from different devices.
///
/// E.g. `username-laptop`, `username-phone`, etc.
///
/// Another potential scheme with good privacy would be a
/// keyed blake3 hash of the secret key. (This gives you
/// an identifier that is as unique as a `NodeID`, but
/// can't be correlated to `NodeID`s.)
pub instance_name: String,
/// The username for basic auth for the push metrics collector.
pub username: Option<String>,
/// The password for basic auth for the push metrics collector.
pub password: String,
}
-82
View File
@@ -1,82 +0,0 @@
//! Metrics collection
//!
//! Enables and manages a global registry of metrics.
//! Divided up into modules, each module has its own metrics.
//! Starting the metrics service will expose the metrics on a OpenMetrics http endpoint.
//!
//! To enable metrics collection, call `init_metrics()` before starting the service.
//!
//! - To increment a **counter**, use the [`crate::inc`] macro with a value.
//! - To increment a **counter** by 1, use the [`crate::inc_by`] macro.
//!
//! To expose the metrics, start the metrics service with `start_metrics_server()`.
//!
//! # Example:
//! ```rust
//! use iroh_metrics::{
//! core::{Core, Counter, Metric},
//! inc, inc_by,
//! };
//! use struct_iterable::Iterable;
//!
//! #[derive(Debug, Clone, Iterable)]
//! pub struct Metrics {
//! pub things_added: Counter,
//! }
//!
//! impl Default for Metrics {
//! fn default() -> Self {
//! Self {
//! things_added: Counter::new(
//! "things_added tracks the number of things we have added",
//! ),
//! }
//! }
//! }
//!
//! impl Metric for Metrics {
//! fn name() -> &'static str {
//! "my_metrics"
//! }
//! }
//!
//! Core::init(|reg, metrics| {
//! metrics.insert(Metrics::new(reg));
//! });
//!
//! inc_by!(Metrics, things_added, 2);
//! inc!(Metrics, things_added);
//! ```
// TODO: move cfg to lib.rs
#[cfg(feature = "metrics")]
use std::net::SocketAddr;
/// Start a server to serve the OpenMetrics endpoint.
#[cfg(feature = "metrics")]
pub async fn start_metrics_server(addr: SocketAddr) -> anyhow::Result<()> {
crate::service::run(addr).await
}
/// Start a metrics dumper service.
#[cfg(feature = "metrics")]
pub async fn start_metrics_dumper(
path: std::path::PathBuf,
interval: std::time::Duration,
) -> anyhow::Result<()> {
crate::service::dumper(&path, interval).await
}
/// Start a metrics exporter service.
#[cfg(feature = "metrics")]
pub async fn start_metrics_exporter(cfg: crate::PushMetricsConfig) {
crate::service::exporter(
cfg.endpoint,
cfg.service_name,
cfg.instance_name,
cfg.username,
cfg.password,
std::time::Duration::from_secs(cfg.interval),
)
.await;
}
-168
View File
@@ -1,168 +0,0 @@
use std::{
net::SocketAddr,
path::PathBuf,
time::{Duration, Instant},
};
use anyhow::{anyhow, Context, Result};
use hyper::{service::service_fn, Request, Response};
use tokio::{io::AsyncWriteExt as _, net::TcpListener};
use tracing::{debug, error, info, warn};
use crate::{core::Core, parse_prometheus_metrics};
type BytesBody = http_body_util::Full<hyper::body::Bytes>;
/// Start a HTTP server to report metrics.
pub async fn run(metrics_addr: SocketAddr) -> Result<()> {
info!("Starting metrics server on {metrics_addr}");
let listener = TcpListener::bind(metrics_addr)
.await
.with_context(|| format!("failed to bind metrics on {metrics_addr}"))?;
loop {
let (stream, _addr) = listener.accept().await?;
let io = hyper_util::rt::TokioIo::new(stream);
tokio::spawn(async move {
if let Err(err) = hyper::server::conn::http1::Builder::new()
.serve_connection(io, service_fn(handler))
.await
{
error!("Error serving metrics connection: {err:#}");
}
});
}
}
/// HTTP handler that will respond with the OpenMetrics encoding of our metrics.
async fn handler(_req: Request<hyper::body::Incoming>) -> Result<Response<BytesBody>> {
let core = Core::get().ok_or_else(|| anyhow!("metrics disabled"))?;
core.encode().map_err(anyhow::Error::new).map(|r| {
Response::builder()
.header(hyper::header::CONTENT_TYPE, "text/plain; charset=utf-8")
.body(body_full(r))
.expect("Failed to build response")
})
}
/// Creates a new [`BytesBody`] with given content.
fn body_full(content: impl Into<hyper::body::Bytes>) -> BytesBody {
http_body_util::Full::new(content.into())
}
/// Start a metrics dumper loop to write metrics to an output file.
pub async fn dumper(path: &PathBuf, interval_ms: Duration) -> Result<()> {
info!(file = %path.display(), ?interval_ms, "running metrics dumper");
let _ = Core::get().ok_or_else(|| anyhow!("metrics disabled"))?;
let start = Instant::now();
let file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&path)
.await?;
let mut file = tokio::io::BufWriter::new(file);
// Dump metrics once with a header
dump_metrics(&mut file, &start, true).await?;
loop {
dump_metrics(&mut file, &start, false).await?;
tokio::time::sleep(interval_ms).await;
}
}
/// Dump metrics to a file.
async fn dump_metrics(
file: &mut tokio::io::BufWriter<tokio::fs::File>,
start: &Instant,
write_header: bool,
) -> Result<()> {
let core = Core::get().ok_or_else(|| anyhow!("metrics disabled"))?;
let m = core.encode();
match m {
Err(e) => error!("Failed to encode metrics: {e:#}"),
Ok(m) => {
let m = parse_prometheus_metrics(&m)?;
let time_since_start = start.elapsed().as_millis() as f64;
// take the keys from m and sort them
let mut keys: Vec<&String> = m.keys().collect();
keys.sort();
let mut metrics = String::new();
if write_header {
metrics.push_str("time");
for key in keys.iter() {
metrics.push(',');
metrics.push_str(key);
}
metrics.push('\n');
}
metrics.push_str(&format!("{}", time_since_start));
for key in keys.iter() {
let value = m[*key];
let formatted_value = format!("{:.3}", value);
metrics.push(',');
metrics.push_str(&formatted_value);
}
metrics.push('\n');
file.write_all(metrics.as_bytes()).await?;
file.flush().await?;
}
}
Ok(())
}
/// Export metrics to a push gateway.
pub async fn exporter(
gateway_endpoint: String,
service_name: String,
instance_name: String,
username: Option<String>,
password: String,
interval: Duration,
) {
let Some(core) = Core::get() else {
error!("metrics disabled");
return;
};
let push_client = reqwest::Client::new();
let prom_gateway_uri = format!(
"{}/metrics/job/{}/instance/{}",
gateway_endpoint, service_name, instance_name
);
loop {
tokio::time::sleep(interval).await;
let buff = core.encode();
match buff {
Err(e) => error!("Failed to encode metrics: {e:#}"),
Ok(buff) => {
let mut req = push_client.post(&prom_gateway_uri);
if let Some(username) = username.clone() {
req = req.basic_auth(username, Some(password.clone()));
}
let res = match req.body(buff).send().await {
Ok(res) => res,
Err(e) => {
warn!("failed to push metrics: {}", e);
continue;
}
};
match res.status() {
reqwest::StatusCode::OK => {
debug!("pushed metrics to gateway");
}
_ => {
warn!("failed to push metrics to gateway: {:?}", res);
let body = res.text().await.unwrap();
warn!("error body: {}", body);
}
}
}
}
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ futures-buffered = "0.2.8"
futures-lite = "2.3"
hickory-resolver = "=0.25.0-alpha.2"
iroh-base = { version = "0.28.0", path = "../iroh-base", default-features = false, features = ["relay"] }
iroh-metrics = { version = "0.28.0", path = "../iroh-metrics", default-features = false, optional = true }
iroh-metrics = { version = "0.28.0", default-features = false, optional = true }
iroh-relay = { version = "0.28", path = "../iroh-relay" }
netwatch = { version = "0.1.0", path = "../net-tools/netwatch" }
portmapper = { version = "0.1.0", path = "../net-tools/portmapper" }
+1 -1
View File
@@ -39,7 +39,7 @@ http-body-util = "0.1.0"
hyper = { version = "1", features = ["server", "client", "http1"] }
hyper-util = "0.1.1"
iroh-base = { version = "0.28.0", path = "../iroh-base", features = ["key"] }
iroh-metrics = { version = "0.28.0", path = "../iroh-metrics", default-features = false }
iroh-metrics = { version = "0.28.0", default-features = false }
libc = "0.2.139"
num_enum = "0.7"
once_cell = "1.18.0"
+1 -1
View File
@@ -110,7 +110,7 @@ z32 = "1.0.3"
net-report = { package = "iroh-net-report", path = "../iroh-net-report", version = "0.28" }
# metrics
iroh-metrics = { version = "0.28.0", path = "../iroh-metrics", default-features = false }
iroh-metrics = { version = "0.28.0", default-features = false }
strum = { version = "0.26", features = ["derive"] }
# local-swarm-discovery
+1 -1
View File
@@ -10,7 +10,7 @@ anyhow = "1.0.22"
bytes = "1.7"
hdrhistogram = { version = "7.2", default-features = false }
iroh = { path = ".." }
iroh-metrics = { path = "../../iroh-metrics" }
iroh-metrics = "0.28"
quinn = { package = "iroh-quinn", version = "0.12" }
rcgen = "0.13"
rustls = { version = "0.23", default-features = false, features = ["ring"] }
+1 -1
View File
@@ -20,7 +20,7 @@ derive_more = { version = "1.0.0", features = ["debug", "display", "from", "try_
futures-lite = "2.5"
futures-util = "0.3.25"
igd-next = { version = "0.15.1", features = ["aio_tokio"] }
iroh-metrics = { version = "0.28.0", path = "../../iroh-metrics", default-features = false }
iroh-metrics = { version = "0.28.0", default-features = false }
libc = "0.2.139"
netwatch = { version = "0.1.0", path = "../netwatch" }
num_enum = "0.7"