From 09e974623183e8a9bafdfc25fa255ed9fd5c808f Mon Sep 17 00:00:00 2001 From: Asmir Avdicevic Date: Mon, 22 Jul 2024 20:07:09 +0200 Subject: [PATCH] refactor!: metrics (#2464) ## Description - Cleans up stale counters - Introduces unique daily node counts on relays - Introduces a metrics dumper so we can create dumps of metrics and also view them in doctor plot - Introduces new trace level counters ## Breaking Changes - Introduces `metrics_dump_path` on the top level CLI parameters, which if set will make sure metrics are collected at regular intervals and written to the provided path in CSV format. ## Notes & open questions ## Change checklist - [ ] Self-review. - [ ] 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. - [ ] Tests if relevant. - [ ] All breaking changes documented. --- Cargo.lock | 6 +- iroh-blobs/Cargo.toml | 4 +- iroh-blobs/src/downloader.rs | 9 ++ iroh-blobs/src/lib.rs | 1 - iroh-blobs/src/metrics.rs | 30 +++++++ iroh-cli/src/commands.rs | 4 + iroh-cli/src/commands/doctor.rs | 141 +++++++++++++++++++++++------- iroh-cli/src/commands/start.rs | 20 +++++ iroh-cli/src/config.rs | 3 + iroh-dns-server/src/metrics.rs | 2 - iroh-docs/Cargo.toml | 4 +- iroh-docs/src/actor.rs | 3 + iroh-docs/src/engine/gossip.rs | 6 ++ iroh-docs/src/engine/live.rs | 8 ++ iroh-docs/src/lib.rs | 1 - iroh-docs/src/metrics.rs | 44 ++++++++++ iroh-gossip/src/metrics.rs | 28 +++++- iroh-gossip/src/net.rs | 14 ++- iroh-metrics/Cargo.toml | 4 +- iroh-metrics/src/core.rs | 17 ++++ iroh-metrics/src/lib.rs | 30 +++++++ iroh-metrics/src/metrics.rs | 9 ++ iroh-metrics/src/service.rs | 72 +++++++++++++++ iroh-net/src/magicsock.rs | 8 ++ iroh-net/src/magicsock/metrics.rs | 38 ++++---- iroh-net/src/netcheck/metrics.rs | 2 - iroh-net/src/relay/metrics.rs | 30 ++----- iroh-net/src/relay/server.rs | 93 ++++++++++++++------ iroh/src/metrics.rs | 44 ++++++++-- 29 files changed, 545 insertions(+), 130 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 711d74759e..1b5b6a01d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4798,7 +4798,7 @@ dependencies = [ "once_cell", "ring 0.17.8", "rustls-pki-types", - "rustls-webpki 0.102.5", + "rustls-webpki 0.102.6", "subtle", "zeroize", ] @@ -4852,9 +4852,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.102.5" +version = "0.102.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a6fccd794a42c2c105b513a2f62bc3fd8f3ba57a4593677ceb0bd035164d78" +checksum = "8e6b52d4fda176fd835fdc55a835d4a89b8499cad995885a21149d5ad62f852e" dependencies = [ "ring 0.17.8", "rustls-pki-types", diff --git a/iroh-blobs/Cargo.toml b/iroh-blobs/Cargo.toml index a422d47351..44df64134d 100644 --- a/iroh-blobs/Cargo.toml +++ b/iroh-blobs/Cargo.toml @@ -29,7 +29,7 @@ hashlink = { version = "0.9.0", optional = true } hex = "0.4.3" iroh-base = { version = "0.20.0", features = ["redb"], path = "../iroh-base" } iroh-io = { version = "0.6.0", features = ["stats"] } -iroh-metrics = { version = "0.20.0", path = "../iroh-metrics", optional = true } +iroh-metrics = { version = "0.20.0", path = "../iroh-metrics", default-features = false } iroh-net = { version = "0.20.0", path = "../iroh-net" } num_cpus = "1.15.0" parking_lot = { version = "0.12.1", optional = true } @@ -77,7 +77,7 @@ version = "0.10" default = ["fs-store"] downloader = ["dep:parking_lot", "tokio-util/time", "dep:hashlink"] fs-store = ["dep:reflink-copy", "redb", "dep:redb_v1", "dep:tempfile"] -metrics = ["dep:iroh-metrics"] +metrics = ["iroh-metrics/metrics"] redb = ["dep:redb"] [package.metadata.docs.rs] diff --git a/iroh-blobs/src/downloader.rs b/iroh-blobs/src/downloader.rs index ca3d7a9b87..dd26a8bc6d 100644 --- a/iroh-blobs/src/downloader.rs +++ b/iroh-blobs/src/downloader.rs @@ -40,6 +40,7 @@ use std::{ use futures_lite::{future::BoxedLocal, Stream, StreamExt}; use hashlink::LinkedHashSet; use iroh_base::hash::{BlobFormat, Hash, HashAndFormat}; +use iroh_metrics::inc; use iroh_net::{endpoint, Endpoint, NodeAddr, NodeId}; use tokio::{ sync::{mpsc, oneshot}, @@ -50,6 +51,7 @@ use tracing::{debug, error_span, trace, warn, Instrument}; use crate::{ get::{db::DownloadProgress, Stats}, + metrics::Metrics, store::Store, util::{local_pool::LocalPoolHandle, progress::ProgressSender}, }; @@ -566,13 +568,16 @@ impl, D: Dialer> Service { async fn run(mut self) { loop { trace!("wait for tick"); + inc!(Metrics, downloader_tick_main); tokio::select! { Some((node, conn_result)) = self.dialer.next() => { trace!(node=%node.fmt_short(), "tick: connection ready"); + inc!(Metrics, downloader_tick_connection_ready); self.on_connection_ready(node, conn_result); } maybe_msg = self.msg_rx.recv() => { trace!(msg=?maybe_msg, "tick: message received"); + inc!(Metrics, downloader_tick_message_received); match maybe_msg { Some(msg) => self.handle_message(msg).await, None => return self.shutdown().await, @@ -582,21 +587,25 @@ impl, D: Dialer> Service { match res { Ok((kind, result)) => { trace!(%kind, "tick: transfer completed"); + inc!(Metrics, downloader_tick_transfer_completed); self.on_download_completed(kind, result); } Err(err) => { warn!(?err, "transfer task panicked"); + inc!(Metrics, downloader_tick_transfer_failed); } } } Some(expired) = self.retry_nodes_queue.next() => { let node = expired.into_inner(); trace!(node=%node.fmt_short(), "tick: retry node"); + inc!(Metrics, downloader_tick_retry_node); self.on_retry_wait_elapsed(node); } Some(expired) = self.goodbye_nodes_queue.next() => { let node = expired.into_inner(); trace!(node=%node.fmt_short(), "tick: goodbye node"); + inc!(Metrics, downloader_tick_goodbye_node); self.disconnect_idle_node(node, "idle expired"); } } diff --git a/iroh-blobs/src/lib.rs b/iroh-blobs/src/lib.rs index d482faf215..ce2788d5a9 100644 --- a/iroh-blobs/src/lib.rs +++ b/iroh-blobs/src/lib.rs @@ -9,7 +9,6 @@ pub mod export; pub mod format; pub mod get; pub mod hashseq; -#[cfg(feature = "metrics")] pub mod metrics; pub mod protocol; pub mod provider; diff --git a/iroh-blobs/src/metrics.rs b/iroh-blobs/src/metrics.rs index cdb6d66033..d44f70cba6 100644 --- a/iroh-blobs/src/metrics.rs +++ b/iroh-blobs/src/metrics.rs @@ -14,6 +14,14 @@ pub struct Metrics { pub downloads_success: Counter, pub downloads_error: Counter, pub downloads_notfound: Counter, + + pub downloader_tick_main: Counter, + pub downloader_tick_connection_ready: Counter, + pub downloader_tick_message_received: Counter, + pub downloader_tick_transfer_completed: Counter, + pub downloader_tick_transfer_failed: Counter, + pub downloader_tick_retry_node: Counter, + pub downloader_tick_goodbye_node: Counter, } impl Default for Metrics { @@ -24,6 +32,28 @@ impl Default for Metrics { downloads_success: Counter::new("Total number of successful downloads"), downloads_error: Counter::new("Total number of downloads failed with error"), downloads_notfound: Counter::new("Total number of downloads failed with not found"), + + downloader_tick_main: Counter::new( + "Number of times the main downloader actor loop ticked", + ), + downloader_tick_connection_ready: Counter::new( + "Number of times the downloader actor ticked for a connection ready", + ), + downloader_tick_message_received: Counter::new( + "Number of times the downloader actor ticked for a message received", + ), + downloader_tick_transfer_completed: Counter::new( + "Number of times the downloader actor ticked for a transfer completed", + ), + downloader_tick_transfer_failed: Counter::new( + "Number of times the downloader actor ticked for a transfer failed", + ), + downloader_tick_retry_node: Counter::new( + "Number of times the downloader actor ticked for a retry node", + ), + downloader_tick_goodbye_node: Counter::new( + "Number of times the downloader actor ticked for a goodbye node", + ), } } } diff --git a/iroh-cli/src/commands.rs b/iroh-cli/src/commands.rs index 5c35727153..cf97d62fe8 100644 --- a/iroh-cli/src/commands.rs +++ b/iroh-cli/src/commands.rs @@ -46,6 +46,10 @@ pub(crate) struct Cli { /// Address to serve RPC on. #[clap(long)] pub(crate) rpc_addr: Option, + + /// If set, metrics will be dumped in CSV format to the specified path at regular intervals (100ms). + #[clap(long)] + pub(crate) metrics_dump_path: Option, } #[derive(Debug, Clone)] diff --git a/iroh-cli/src/commands/doctor.rs b/iroh-cli/src/commands/doctor.rs index 6f229e84ca..a9886c827b 100644 --- a/iroh-cli/src/commands/doctor.rs +++ b/iroh-cli/src/commands/doctor.rs @@ -55,6 +55,7 @@ use crossterm::{ }; use rand::Rng; use ratatui::{prelude::*, widgets::*}; +use tracing::warn; #[derive(Debug, Clone, derive_more::Display)] pub enum SecretKeyOption { @@ -232,6 +233,9 @@ pub enum Commands { /// Endpoint to scrape for prometheus metrics #[clap(long, default_value = "http://localhost:9090")] scrape_url: String, + /// File to read the metrics from. Takes precedence over scrape_url. + #[clap(long)] + file: Option, }, } @@ -1172,6 +1176,7 @@ pub async fn run(command: Commands, config: &NodeConfig) -> anyhow::Result<()> { metrics, timeframe, scrape_url, + file, } => { let metrics: Vec = metrics.split(',').map(|s| s.to_string()).collect(); let interval = Duration::from_millis(interval); @@ -1182,7 +1187,7 @@ pub async fn run(command: Commands, config: &NodeConfig) -> anyhow::Result<()> { let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; - let app = PlotterApp::new(metrics, timeframe, scrape_url); + let app = PlotterApp::new(metrics, timeframe, scrape_url, file); let res = run_plotter(&mut terminal, app, interval).await; disable_raw_mode()?; execute!( @@ -1214,7 +1219,7 @@ async fn run_plotter( loop { terminal.draw(|f| plotter_draw(f, &mut app))?; - if crossterm::event::poll(Duration::from_millis(100))? { + if crossterm::event::poll(Duration::from_millis(10))? { if let Event::Key(key) = event::read()? { if key.kind == KeyEventKind::Press { if let KeyCode::Char(c) = key.code { @@ -1283,8 +1288,16 @@ fn plot_chart(frame: &mut Frame, area: Rect, app: &PlotterApp, metric: &str) { let y_start = data_y_range.0; let y_end = data_y_range.1; + let last_val = data.last(); + let name = match last_val { + Some(val) => { + let val_y = val.1; + format!("{metric}: {val_y:.0}") + } + None => metric.to_string(), + }; let datasets = vec![Dataset::default() - .name(metric) + .name(name) .marker(symbols::Marker::Dot) .graph_type(GraphType::Line) .style(Style::default().fg(Color::Cyan)) @@ -1304,19 +1317,19 @@ fn plot_chart(frame: &mut Frame, area: Rect, app: &PlotterApp, metric: &str) { ]; let mut y_labels = vec![Span::styled( - format!("{:.1}", y_start), + format!("{:.0}", y_start), Style::default().add_modifier(Modifier::BOLD), )]; for i in 1..=10 { y_labels.push(Span::raw(format!( - "{:.1}", + "{:.0}", y_start + (y_end - y_start) / 10.0 * i as f64 ))); } y_labels.push(Span::styled( - format!("{:.1}", y_end), + format!("{:.0}", y_end), Style::default().add_modifier(Modifier::BOLD), )); @@ -1355,23 +1368,64 @@ struct PlotterApp { freeze: bool, internal_ts: Duration, scrape_url: String, + file_data: Vec, + file_header: Vec, } impl PlotterApp { - fn new(metrics: Vec, timeframe: usize, scrape_url: String) -> Self { + fn new( + metrics: Vec, + timeframe: usize, + scrape_url: String, + file: Option, + ) -> Self { let data = metrics.iter().map(|m| (m.clone(), vec![])).collect(); let data_y_range = metrics.iter().map(|m| (m.clone(), (0.0, 0.0))).collect(); + let mut file_data: Vec = file + .map(|f| std::fs::read_to_string(f).unwrap()) + .unwrap_or_default() + .split('\n') + .map(|s| s.to_string()) + .collect(); + let mut file_header = vec![]; + let mut timeframe = timeframe; + if !file_data.is_empty() { + file_header = file_data[0].split(',').map(|s| s.to_string()).collect(); + file_data.remove(0); + + while file_data.last().unwrap().is_empty() { + file_data.pop(); + } + + let first_line: Vec = file_data[0].split(',').map(|s| s.to_string()).collect(); + let last_line: Vec = file_data + .last() + .unwrap() + .split(',') + .map(|s| s.to_string()) + .collect(); + + let start_time: usize = first_line.first().unwrap().parse().unwrap(); + let end_time: usize = last_line.first().unwrap().parse().unwrap(); + + timeframe = (end_time - start_time) / 1000; + } + timeframe = timeframe.clamp(30, 90); + + file_data.reverse(); Self { should_quit: false, metrics, start_ts: Instant::now(), data, data_y_range, - timeframe: timeframe - 25, + timeframe, rng: rand::thread_rng(), freeze: false, internal_ts: Duration::default(), scrape_url, + file_data, + file_header, } } @@ -1392,16 +1446,34 @@ impl PlotterApp { return; } - let req = reqwest::Client::new().get(&self.scrape_url).send().await; - if req.is_err() { - return; - } - let data = req.unwrap().text().await.unwrap(); - let metrics_response = parse_prometheus_metrics(&data); - if metrics_response.is_err() { - return; - } - let metrics_response = metrics_response.unwrap(); + let metrics_response = match self.file_data.is_empty() { + true => { + let req = reqwest::Client::new().get(&self.scrape_url).send().await; + if req.is_err() { + return; + } + let data = req.unwrap().text().await.unwrap(); + let metrics_response = iroh_metrics::parse_prometheus_metrics(&data); + if metrics_response.is_err() { + return; + } + metrics_response.unwrap() + } + false => { + if self.file_data.len() == 1 { + self.freeze = true; + return; + } + let data = self.file_data.pop().unwrap(); + let r = parse_csv_metrics(&self.file_header, &data); + if let Ok(mr) = r { + mr + } else { + warn!("Failed to parse csv metrics: {:?}", r.err()); + HashMap::new() + } + } + }; self.internal_ts = self.start_ts.elapsed(); for metric in &self.metrics { let val = if metric.eq("random") { @@ -1412,7 +1484,12 @@ impl PlotterApp { 0.0 }; let e = self.data.entry(metric.clone()).or_default(); - e.push((self.internal_ts.as_secs_f64(), val)); + let mut ts = self.internal_ts.as_secs_f64(); + if metrics_response.contains_key("time") { + ts = *metrics_response.get("time").unwrap() / 1000.0; + } + self.internal_ts = Duration::from_secs_f64(ts); + e.push((ts, val)); let yr = self.data_y_range.get_mut(metric).unwrap(); if val * 1.1 < yr.0 { yr.0 = val * 1.2; @@ -1424,22 +1501,18 @@ impl PlotterApp { } } -fn parse_prometheus_metrics(data: &str) -> anyhow::Result> { +fn parse_csv_metrics(header: &[String], data: &str) -> anyhow::Result> { 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::(); - if value.is_err() { - continue; - } - metrics.insert(metric.to_string(), value.unwrap()); + let data = data.split(',').collect::>(); + for (i, h) in header.iter().enumerate() { + let val = match h.as_str() { + "time" => { + let ts = data[i].parse::()?; + ts as f64 + } + _ => data[i].parse::()?, + }; + metrics.insert(h.clone(), val); } Ok(metrics) } diff --git a/iroh-cli/src/commands/start.rs b/iroh-cli/src/commands/start.rs index c6c91c49f8..39449fd15c 100644 --- a/iroh-cli/src/commands/start.rs +++ b/iroh-cli/src/commands/start.rs @@ -1,3 +1,4 @@ +use std::path::PathBuf; use std::{future::Future, net::SocketAddr, path::Path, time::Duration}; use crate::config::NodeConfig; @@ -39,12 +40,17 @@ where { let _guard = crate::logging::init_terminal_and_file_logging(&config.file_logs, iroh_data_root)?; let metrics_fut = start_metrics_server(config.metrics_addr); + let metrics_dumper_fut = + start_metrics_dumper(config.metrics_dump_path.clone(), Duration::from_millis(100)); let res = run_with_command_inner(config, iroh_data_root, rpc_addr, run_type, command).await; if let Some(metrics_fut) = metrics_fut { metrics_fut.abort(); } + if let Some(metrics_dumper_fut) = metrics_dumper_fut { + metrics_dumper_fut.abort(); + } let (clear_rpc, res) = match res { Ok(()) => (true, res), @@ -186,6 +192,20 @@ pub fn start_metrics_server( None } +pub fn start_metrics_dumper( + path: Option, + interval: Duration, +) -> Option> { + // doesn't start the dumper if the address is None + Some(tokio::task::spawn(async move { + if let Some(path) = path { + if let Err(e) = iroh_metrics::metrics::start_metrics_dumper(path, interval).await { + eprintln!("Failed to start metrics dumper: {e}"); + } + } + })) +} + #[cfg(test)] mod tests { use super::*; diff --git a/iroh-cli/src/config.rs b/iroh-cli/src/config.rs index 3183d588b8..d47250d862 100644 --- a/iroh-cli/src/config.rs +++ b/iroh-cli/src/config.rs @@ -58,6 +58,8 @@ pub(crate) struct NodeConfig { /// Bind address on which to serve Prometheus metrics pub(crate) metrics_addr: Option, pub(crate) file_logs: super::logging::FileLogging, + /// Path to dump metrics to in CSV format. + pub(crate) metrics_dump_path: Option, } impl Default for NodeConfig { @@ -83,6 +85,7 @@ impl Default for NodeConfig { gc_policy: GcPolicy::Disabled, metrics_addr: Some(([127, 0, 0, 1], 9090).into()), file_logs: Default::default(), + metrics_dump_path: None, } } } diff --git a/iroh-dns-server/src/metrics.rs b/iroh-dns-server/src/metrics.rs index 7b07ac07a0..82d715dd5a 100644 --- a/iroh-dns-server/src/metrics.rs +++ b/iroh-dns-server/src/metrics.rs @@ -9,7 +9,6 @@ use struct_iterable::Iterable; pub struct Metrics { pub pkarr_publish_update: Counter, pub pkarr_publish_noop: Counter, - pub pkarr_publish_error: Counter, pub dns_requests: Counter, pub dns_requests_udp: Counter, pub dns_requests_https: Counter, @@ -32,7 +31,6 @@ impl Default for Metrics { pkarr_publish_noop: Counter::new( "Number of pkarr relay puts that did not update the state", ), - pkarr_publish_error: Counter::new("Number of pkarr relay puts that failed"), dns_requests: Counter::new("DNS requests (total)"), dns_requests_udp: Counter::new("DNS requests via UDP"), dns_requests_https: Counter::new("DNS requests via HTTPS (DoH)"), diff --git a/iroh-docs/Cargo.toml b/iroh-docs/Cargo.toml index bcaa820eeb..4bc74c6c44 100644 --- a/iroh-docs/Cargo.toml +++ b/iroh-docs/Cargo.toml @@ -28,7 +28,7 @@ hex = "0.4" iroh-base = { version = "0.20.0", path = "../iroh-base" } iroh-blobs = { version = "0.20.0", path = "../iroh-blobs", optional = true, features = ["downloader"] } iroh-gossip = { version = "0.20.0", path = "../iroh-gossip", optional = true } -iroh-metrics = { version = "0.20.0", path = "../iroh-metrics", optional = true } +iroh-metrics = { version = "0.20.0", path = "../iroh-metrics", default-features = false } iroh-net = { version = "0.20.0", optional = true, path = "../iroh-net" } lru = "0.12" num_enum = "0.7" @@ -58,7 +58,7 @@ test-strategy = "0.3.1" [features] default = ["net", "metrics", "engine"] net = ["dep:iroh-net", "tokio/io-util", "dep:tokio-stream", "dep:tokio-util"] -metrics = ["dep:iroh-metrics"] +metrics = ["iroh-metrics/metrics"] engine = ["net", "dep:iroh-gossip", "dep:iroh-blobs"] [package.metadata.docs.rs] diff --git a/iroh-docs/src/actor.rs b/iroh-docs/src/actor.rs index 8789161947..769f14a482 100644 --- a/iroh-docs/src/actor.rs +++ b/iroh-docs/src/actor.rs @@ -12,11 +12,13 @@ use anyhow::{anyhow, Context, Result}; use bytes::Bytes; use futures_util::FutureExt; use iroh_base::hash::Hash; +use iroh_metrics::inc; use serde::{Deserialize, Serialize}; use tokio::{sync::oneshot, task::JoinSet}; use tracing::{debug, error, error_span, trace, warn}; use crate::{ + metrics::Metrics, ranger::Message, store::{ fs::{ContentHashesIterator, StoreInstance}, @@ -629,6 +631,7 @@ impl Actor { } }; trace!(%action, "tick"); + inc!(Metrics, actor_tick_main); match action { Action::Shutdown { reply } => { break reply; diff --git a/iroh-docs/src/engine/gossip.rs b/iroh-docs/src/engine/gossip.rs index 17077ac802..210356c969 100644 --- a/iroh-docs/src/engine/gossip.rs +++ b/iroh-docs/src/engine/gossip.rs @@ -4,6 +4,7 @@ use anyhow::{Context, Result}; use futures_lite::StreamExt; use futures_util::FutureExt; use iroh_gossip::net::{Event, Gossip}; +use iroh_metrics::inc; use iroh_net::key::PublicKey; use tokio::{ sync::{broadcast, mpsc}, @@ -15,6 +16,7 @@ use tokio_stream::{ }; use tracing::{debug, error, trace, warn}; +use crate::metrics::Metrics; use crate::{actor::SyncHandle, ContentStatus, NamespaceId}; use super::live::{Op, ToLiveActor}; @@ -67,9 +69,11 @@ impl GossipActor { loop { i += 1; trace!(?i, "tick wait"); + inc!(Metrics, doc_gossip_tick_main); tokio::select! { next = self.gossip_events.next(), if !self.gossip_events.is_empty() => { trace!(?i, "tick: gossip_event"); + inc!(Metrics, doc_gossip_tick_event); if let Err(err) = self.on_gossip_event(next).await { error!("gossip actor died: {err:?}"); return Err(err); @@ -78,12 +82,14 @@ impl GossipActor { msg = self.inbox.recv() => { let msg = msg.context("to_actor closed")?; trace!(%msg, ?i, "tick: to_actor"); + inc!(Metrics, doc_gossip_tick_actor); if !self.on_actor_message(msg).await.context("on_actor_message")? { break; } } Some(res) = self.pending_joins.join_next(), if !self.pending_joins.is_empty() => { trace!(?i, "tick: pending_joins"); + inc!(Metrics, doc_gossip_tick_pending_join); let (namespace, res) = res.context("pending_joins closed")?; match res { Ok(stream) => { diff --git a/iroh-docs/src/engine/live.rs b/iroh-docs/src/engine/live.rs index 8c6864c831..f41744ac73 100644 --- a/iroh-docs/src/engine/live.rs +++ b/iroh-docs/src/engine/live.rs @@ -10,6 +10,7 @@ use iroh_blobs::get::Stats; use iroh_blobs::HashAndFormat; use iroh_blobs::{store::EntryStatus, Hash}; use iroh_gossip::{net::Gossip, proto::TopicId}; +use iroh_metrics::inc; use iroh_net::NodeId; use iroh_net::{key::PublicKey, Endpoint, NodeAddr}; use serde::{Deserialize, Serialize}; @@ -19,6 +20,7 @@ use tokio::{ }; use tracing::{debug, error, error_span, info, instrument, trace, warn, Instrument, Span}; +use crate::metrics::Metrics; use crate::{ actor::{OpenOpts, SyncHandle}, net::{ @@ -244,11 +246,13 @@ impl LiveActor { loop { i += 1; trace!(?i, "tick wait"); + inc!(Metrics, doc_live_tick_main); tokio::select! { biased; msg = self.inbox.recv() => { let msg = msg.context("to_actor closed")?; trace!(?i, %msg, "tick: to_actor"); + inc!(Metrics, doc_live_tick_actor); match msg { ToLiveActor::Shutdown { reply } => { break Ok(reply); @@ -260,6 +264,7 @@ impl LiveActor { } event = self.replica_events_rx.recv_async() => { trace!(?i, "tick: replica_event"); + inc!(Metrics, doc_live_tick_replica_event); let event = event.context("replica_events closed")?; if let Err(err) = self.on_replica_event(event).await { error!(?err, "Failed to process replica event"); @@ -267,17 +272,20 @@ impl LiveActor { } Some(res) = self.running_sync_connect.join_next(), if !self.running_sync_connect.is_empty() => { trace!(?i, "tick: running_sync_connect"); + inc!(Metrics, doc_live_tick_running_sync_connect); let (namespace, peer, reason, res) = res.context("running_sync_connect closed")?; self.on_sync_via_connect_finished(namespace, peer, reason, res).await; } Some(res) = self.running_sync_accept.join_next(), if !self.running_sync_accept.is_empty() => { trace!(?i, "tick: running_sync_accept"); + inc!(Metrics, doc_live_tick_running_sync_accept); let res = res.context("running_sync_accept closed")?; self.on_sync_via_accept_finished(res).await; } Some(res) = self.download_tasks.join_next(), if !self.download_tasks.is_empty() => { trace!(?i, "tick: pending_downloads"); + inc!(Metrics, doc_live_tick_pending_downloads); let (namespace, hash, res) = res.context("pending_downloads closed")?; self.on_download_ready(namespace, hash, res).await; diff --git a/iroh-docs/src/lib.rs b/iroh-docs/src/lib.rs index b1347fe7be..0e84ea61f6 100644 --- a/iroh-docs/src/lib.rs +++ b/iroh-docs/src/lib.rs @@ -33,7 +33,6 @@ //! [paper]: https://arxiv.org/abs/2212.13567 #![deny(missing_docs, rustdoc::broken_intra_doc_links)] -#[cfg(feature = "metrics")] pub mod metrics; #[cfg(feature = "net")] pub mod net; diff --git a/iroh-docs/src/metrics.rs b/iroh-docs/src/metrics.rs index 90d562495c..69d7ab6733 100644 --- a/iroh-docs/src/metrics.rs +++ b/iroh-docs/src/metrics.rs @@ -17,6 +17,20 @@ pub struct Metrics { pub sync_via_connect_failure: Counter, pub sync_via_accept_success: Counter, pub sync_via_accept_failure: Counter, + + pub actor_tick_main: Counter, + + pub doc_gossip_tick_main: Counter, + pub doc_gossip_tick_event: Counter, + pub doc_gossip_tick_actor: Counter, + pub doc_gossip_tick_pending_join: Counter, + + pub doc_live_tick_main: Counter, + pub doc_live_tick_actor: Counter, + pub doc_live_tick_replica_event: Counter, + pub doc_live_tick_running_sync_connect: Counter, + pub doc_live_tick_running_sync_accept: Counter, + pub doc_live_tick_pending_downloads: Counter, } impl Default for Metrics { @@ -30,6 +44,36 @@ impl Default for Metrics { sync_via_accept_failure: Counter::new("Number of failed syncs (via accept)"), sync_via_connect_success: Counter::new("Number of successful syncs (via connect)"), sync_via_connect_failure: Counter::new("Number of failed syncs (via connect)"), + + actor_tick_main: Counter::new("Number of times the main actor loop ticked"), + + doc_gossip_tick_main: Counter::new("Number of times the gossip actor loop ticked"), + doc_gossip_tick_event: Counter::new( + "Number of times the gossip actor processed an event", + ), + doc_gossip_tick_actor: Counter::new( + "Number of times the gossip actor processed an actor event", + ), + doc_gossip_tick_pending_join: Counter::new( + "Number of times the gossip actor processed a pending join", + ), + + doc_live_tick_main: Counter::new("Number of times the live actor loop ticked"), + doc_live_tick_actor: Counter::new( + "Number of times the live actor processed an actor event", + ), + doc_live_tick_replica_event: Counter::new( + "Number of times the live actor processed a replica event", + ), + doc_live_tick_running_sync_connect: Counter::new( + "Number of times the live actor processed a running sync connect", + ), + doc_live_tick_running_sync_accept: Counter::new( + "Number of times the live actor processed a running sync accept", + ), + doc_live_tick_pending_downloads: Counter::new( + "Number of times the live actor processed a pending download", + ), } } } diff --git a/iroh-gossip/src/metrics.rs b/iroh-gossip/src/metrics.rs index ff89e1aa12..0de9680eb2 100644 --- a/iroh-gossip/src/metrics.rs +++ b/iroh-gossip/src/metrics.rs @@ -19,8 +19,14 @@ pub struct Metrics { pub msgs_ctrl_recv_size: Counter, pub neighbor_up: Counter, pub neighbor_down: Counter, - // pub topics_joined: Counter, - // pub topics_left: Counter, + pub actor_tick_main: Counter, + pub actor_tick_rx: Counter, + pub actor_tick_endpoint: Counter, + pub actor_tick_dialer: Counter, + pub actor_tick_dialer_success: Counter, + pub actor_tick_dialer_failure: Counter, + pub actor_tick_in_event_rx: Counter, + pub actor_tick_timers: Counter, } impl Default for Metrics { @@ -36,8 +42,22 @@ impl Default for Metrics { msgs_ctrl_recv_size: Counter::new("Total size of all control messages received"), neighbor_up: Counter::new("Number of times we connected to a peer"), neighbor_down: Counter::new("Number of times we disconnected from a peer"), - // topics_joined: Counter::new("Number of times we joined a topic"), - // topics_left: Counter::new("Number of times we left a topic"), + actor_tick_main: Counter::new("Number of times the main actor loop ticked"), + actor_tick_rx: Counter::new("Number of times the actor ticked for a message received"), + actor_tick_endpoint: Counter::new( + "Number of times the actor ticked for an endpoint event", + ), + actor_tick_dialer: Counter::new("Number of times the actor ticked for a dialer event"), + actor_tick_dialer_success: Counter::new( + "Number of times the actor ticked for a successful dialer event", + ), + actor_tick_dialer_failure: Counter::new( + "Number of times the actor ticked for a failed dialer event", + ), + actor_tick_in_event_rx: Counter::new( + "Number of times the actor ticked for an incoming event", + ), + actor_tick_timers: Counter::new("Number of times the actor ticked for a timer event"), } } } diff --git a/iroh-gossip/src/net.rs b/iroh-gossip/src/net.rs index 290866fef3..7844117509 100644 --- a/iroh-gossip/src/net.rs +++ b/iroh-gossip/src/net.rs @@ -4,6 +4,7 @@ use anyhow::{anyhow, Context}; use bytes::{Bytes, BytesMut}; use futures_lite::stream::Stream; use genawaiter::sync::{Co, Gen}; +use iroh_metrics::inc; use iroh_net::{ dialer::Dialer, endpoint::{get_remote_node_id, Connection}, @@ -20,7 +21,10 @@ use tokio::{ use tracing::{debug, error_span, trace, warn, Instrument}; use self::util::{read_message, write_message, Timers}; -use crate::proto::{self, PeerData, Scope, TopicId}; +use crate::{ + metrics::Metrics, + proto::{self, PeerData, Scope, TopicId}, +}; pub mod util; @@ -368,10 +372,12 @@ impl Actor { loop { i += 1; trace!(?i, "tick"); + inc!(Metrics, actor_tick_main); tokio::select! { biased; msg = self.to_actor_rx.recv() => { trace!(?i, "tick: to_actor_rx"); + inc!(Metrics, actor_tick_rx); match msg { Some(msg) => self.handle_to_actor_msg(msg, Instant::now()).await?, None => { @@ -383,6 +389,7 @@ impl Actor { new_endpoints = self.on_direct_addr_rx.recv() => { match new_endpoints { Some(endpoints) => { + inc!(Metrics, actor_tick_endpoint); let addr = NodeAddr::from_parts( self.endpoint.node_id(), self.endpoint.home_relay(), @@ -399,18 +406,22 @@ impl Actor { } (peer_id, res) = self.dialer.next_conn() => { trace!(?i, "tick: dialer"); + inc!(Metrics, actor_tick_dialer); match res { Ok(conn) => { debug!(peer = ?peer_id, "dial successful"); + inc!(Metrics, actor_tick_dialer_success); self.handle_to_actor_msg(ToActor::ConnIncoming(peer_id, ConnOrigin::Dial, conn), Instant::now()).await.context("dialer.next -> conn -> handle_to_actor_msg")?; } Err(err) => { warn!(peer = ?peer_id, "dial failed: {err}"); + inc!(Metrics, actor_tick_dialer_failure); } } } event = self.in_event_rx.recv() => { trace!(?i, "tick: in_event_rx"); + inc!(Metrics, actor_tick_in_event_rx); match event { Some(event) => { self.handle_in_event(event, Instant::now()).await.context("in_event_rx.recv -> handle_in_event")?; @@ -420,6 +431,7 @@ impl Actor { } drain = self.timers.wait_and_drain() => { trace!(?i, "tick: timers"); + inc!(Metrics, actor_tick_timers); let now = Instant::now(); for (_instant, timer) in drain { self.handle_in_event(InEvent::TimerExpired(timer), now).await.context("timers.drain_expired -> handle_in_event")?; diff --git a/iroh-metrics/Cargo.toml b/iroh-metrics/Cargo.toml index 19e6bbb9bb..b1568765ef 100644 --- a/iroh-metrics/Cargo.toml +++ b/iroh-metrics/Cargo.toml @@ -21,12 +21,12 @@ 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.0", optional = true } +prometheus-client = { version = "0.22", optional = true } reqwest = { version = "0.12.4", default-features = false, features = ["json", "rustls-tls"] } serde = { version = "1.0", features = ["derive"] } struct_iterable = "0.1" time = { version = "0.3.21", features = ["serde-well-known"] } -tokio = { version = "1", features = ["rt", "net"]} +tokio = { version = "1", features = ["rt", "net", "fs"]} tracing = "0.1" [dev-dependencies] diff --git a/iroh-metrics/src/core.rs b/iroh-metrics/src/core.rs index b5d3bab370..c1218a7af1 100644 --- a/iroh-metrics/src/core.rs +++ b/iroh-metrics/src/core.rs @@ -60,6 +60,23 @@ impl Counter { 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 { diff --git a/iroh-metrics/src/lib.rs b/iroh-metrics/src/lib.rs index 5a0f684b3d..d7fa5beaf3 100644 --- a/iroh-metrics/src/lib.rs +++ b/iroh-metrics/src/lib.rs @@ -11,6 +11,7 @@ pub mod core; mod service; use core::UsageStatsReport; +use std::collections::HashMap; /// Reexport to make matching versions easier. pub use struct_iterable; @@ -31,6 +32,14 @@ macro_rules! inc_by { }; } +/// 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)); + }; +} + /// Report usage statistics to the configured endpoint. #[allow(unused_variables)] pub async fn report_usage_stats(report: &UsageStatsReport) { @@ -46,3 +55,24 @@ pub async fn report_usage_stats(report: &UsageStatsReport) { } } } + +/// Parse Prometheus metrics from a string. +pub fn parse_prometheus_metrics(data: &str) -> anyhow::Result> { + 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::(); + if value.is_err() { + continue; + } + metrics.insert(metric.to_string(), value.unwrap()); + } + Ok(metrics) +} diff --git a/iroh-metrics/src/metrics.rs b/iroh-metrics/src/metrics.rs index b8d57e5d23..49f413454b 100644 --- a/iroh-metrics/src/metrics.rs +++ b/iroh-metrics/src/metrics.rs @@ -53,3 +53,12 @@ use std::net::SocketAddr; 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 +} diff --git a/iroh-metrics/src/service.rs b/iroh-metrics/src/service.rs index c114a60ff4..6b873d5b98 100644 --- a/iroh-metrics/src/service.rs +++ b/iroh-metrics/src/service.rs @@ -1,12 +1,16 @@ use std::net::SocketAddr; +use std::path::PathBuf; +use std::time::{Duration, Instant}; use anyhow::{anyhow, Context, Result}; use hyper::service::service_fn; use hyper::{Request, Response}; +use tokio::io::AsyncWriteExt as _; use tokio::net::TcpListener; use tracing::{error, info}; use crate::core::Core; +use crate::parse_prometheus_metrics; type BytesBody = http_body_util::Full; @@ -45,3 +49,71 @@ async fn handler(_req: Request) -> Result) -> 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, + 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(()) +} diff --git a/iroh-net/src/magicsock.rs b/iroh-net/src/magicsock.rs index d2e571cf58..724732c8ea 100644 --- a/iroh-net/src/magicsock.rs +++ b/iroh-net/src/magicsock.rs @@ -1750,19 +1750,23 @@ impl Actor { let mut portmap_watcher = self.port_mapper.watch_external_address(); loop { + inc!(Metrics, actor_tick_main); tokio::select! { Some(msg) = self.msg_receiver.recv() => { trace!(?msg, "tick: msg"); + inc!(Metrics, actor_tick_msg); if self.handle_actor_message(msg).await { return Ok(()); } } tick = self.periodic_re_stun_timer.tick() => { trace!("tick: re_stun {:?}", tick); + inc!(Metrics, actor_tick_re_stun); self.msock.re_stun("periodic"); } Ok(()) = portmap_watcher.changed() => { trace!("tick: portmap changed"); + inc!(Metrics, actor_tick_portmap_changed); let new_external_address = *portmap_watcher.borrow(); debug!("external address updated: {new_external_address:?}"); self.msock.re_stun("portmap_updated"); @@ -1772,6 +1776,7 @@ impl Actor { "tick: direct addr heartbeat {} direct addrs", self.msock.node_map.node_count(), ); + inc!(Metrics, actor_tick_direct_addr_heartbeat); // TODO: this might trigger too many packets at once, pace this self.msock.node_map.prune_inactive(); @@ -1781,16 +1786,19 @@ impl Actor { _ = direct_addr_update_receiver.changed() => { let reason = *direct_addr_update_receiver.borrow(); trace!("tick: direct addr update receiver {:?}", reason); + inc!(Metrics, actor_tick_direct_addr_update_receiver); if let Some(reason) = reason { self.update_direct_addrs(reason).await; } } Some(is_major) = link_change_r.recv() => { trace!("tick: link change {}", is_major); + inc!(Metrics, actor_link_change); self.handle_network_change(is_major).await; } else => { trace!("tick: other"); + inc!(Metrics, actor_tick_other); } } } diff --git a/iroh-net/src/magicsock/metrics.rs b/iroh-net/src/magicsock/metrics.rs index 4140842c4d..0f3b8b40f1 100644 --- a/iroh-net/src/magicsock/metrics.rs +++ b/iroh-net/src/magicsock/metrics.rs @@ -7,19 +7,12 @@ use iroh_metrics::{ #[allow(missing_docs)] #[derive(Debug, Clone, Iterable)] pub struct Metrics { - pub rebind_calls: Counter, pub re_stun_calls: Counter, pub update_direct_addrs: Counter, // Sends (data or disco) - pub send_relay_queued: Counter, - pub send_relay_error_chan: Counter, - pub send_relay_error_closed: Counter, - pub send_relay_error_queue: Counter, pub send_ipv4: Counter, - pub send_ipv4_error: Counter, pub send_ipv6: Counter, - pub send_ipv6_error: Counter, pub send_relay: Counter, pub send_relay_error: Counter, @@ -40,7 +33,6 @@ pub struct Metrics { pub sent_disco_ping: Counter, pub sent_disco_pong: Counter, pub sent_disco_call_me_maybe: Counter, - pub recv_disco_bad_peer: Counter, pub recv_disco_bad_key: Counter, pub recv_disco_bad_parse: Counter, @@ -49,7 +41,6 @@ pub struct Metrics { pub recv_disco_ping: Counter, pub recv_disco_pong: Counter, pub recv_disco_call_me_maybe: Counter, - pub recv_disco_call_me_maybe_bad_node: Counter, pub recv_disco_call_me_maybe_bad_disco: Counter, // How many times our relay home node DI has changed from non-zero to a different non-zero. @@ -66,6 +57,15 @@ pub struct Metrics { pub num_relay_conns_added: Counter, /// The number of connections to peers we have removed over relay. pub num_relay_conns_removed: Counter, + + pub actor_tick_main: Counter, + pub actor_tick_msg: Counter, + pub actor_tick_re_stun: Counter, + pub actor_tick_portmap_changed: Counter, + pub actor_tick_direct_addr_heartbeat: Counter, + pub actor_tick_direct_addr_update_receiver: Counter, + pub actor_link_change: Counter, + pub actor_tick_other: Counter, } impl Default for Metrics { @@ -74,19 +74,12 @@ impl Default for Metrics { num_relay_conns_added: Counter::new("num_relay_conns added"), num_relay_conns_removed: Counter::new("num_relay_conns removed"), - rebind_calls: Counter::new("rebind_calls"), re_stun_calls: Counter::new("restun_calls"), update_direct_addrs: Counter::new("update_endpoints"), // Sends (data or disco) - send_relay_queued: Counter::new("send_relay_queued"), - send_relay_error_chan: Counter::new("send_relay_error_chan"), - send_relay_error_closed: Counter::new("send_relay_error_closed"), - send_relay_error_queue: Counter::new("send_relay_error_queue"), send_ipv4: Counter::new("send_ipv4"), - send_ipv4_error: Counter::new("send_ipv4_error"), send_ipv6: Counter::new("send_ipv6"), - send_ipv6_error: Counter::new("send_ipv6_error"), send_relay: Counter::new("send_relay"), send_relay_error: Counter::new("send_relay_error"), @@ -106,7 +99,6 @@ impl Default for Metrics { sent_disco_ping: Counter::new("disco_sent_ping"), sent_disco_pong: Counter::new("disco_sent_pong"), sent_disco_call_me_maybe: Counter::new("disco_sent_callmemaybe"), - recv_disco_bad_peer: Counter::new("disco_recv_bad_peer"), recv_disco_bad_key: Counter::new("disco_recv_bad_key"), recv_disco_bad_parse: Counter::new("disco_recv_bad_parse"), @@ -115,7 +107,6 @@ impl Default for Metrics { recv_disco_ping: Counter::new("disco_recv_ping"), recv_disco_pong: Counter::new("disco_recv_pong"), recv_disco_call_me_maybe: Counter::new("disco_recv_callmemaybe"), - recv_disco_call_me_maybe_bad_node: Counter::new("disco_recv_callmemaybe_bad_node"), recv_disco_call_me_maybe_bad_disco: Counter::new("disco_recv_callmemaybe_bad_disco"), // How many times our relay home node DI has changed from non-zero to a different non-zero. @@ -127,6 +118,17 @@ impl Default for Metrics { num_direct_conns_removed: Counter::new( "number of direct connections to a peer we have removed", ), + + actor_tick_main: Counter::new("actor_tick_main"), + actor_tick_msg: Counter::new("actor_tick_msg"), + actor_tick_re_stun: Counter::new("actor_tick_re_stun"), + actor_tick_portmap_changed: Counter::new("actor_tick_portmap_changed"), + actor_tick_direct_addr_heartbeat: Counter::new("actor_tick_direct_addr_heartbeat"), + actor_tick_direct_addr_update_receiver: Counter::new( + "actor_tick_direct_addr_update_receiver", + ), + actor_link_change: Counter::new("actor_link_change"), + actor_tick_other: Counter::new("actor_tick_other"), } } } diff --git a/iroh-net/src/netcheck/metrics.rs b/iroh-net/src/netcheck/metrics.rs index 49539f0035..f3891d4792 100644 --- a/iroh-net/src/netcheck/metrics.rs +++ b/iroh-net/src/netcheck/metrics.rs @@ -14,7 +14,6 @@ pub struct Metrics { pub stun_packets_recv_ipv6: Counter, pub reports: Counter, pub reports_full: Counter, - pub reports_error: Counter, } impl Default for Metrics { @@ -29,7 +28,6 @@ impl Default for Metrics { stun_packets_recv_ipv6: Counter::new("Number of IPv6 STUN packets received"), reports: Counter::new("Number of reports executed by netcheck, including full reports"), reports_full: Counter::new("Number of full reports executed by netcheck"), - reports_error: Counter::new("Number of executed reports resulting in an error"), } } } diff --git a/iroh-net/src/relay/metrics.rs b/iroh-net/src/relay/metrics.rs index 923d375b4a..486922516a 100644 --- a/iroh-net/src/relay/metrics.rs +++ b/iroh-net/src/relay/metrics.rs @@ -36,11 +36,6 @@ pub struct Metrics { /// Packets of other `FrameType`s dropped pub other_packets_dropped: Counter, - /// Number of packets we have forwarded out to another packet forwarder - pub packets_forwarded_out: Counter, - /// Number of packets we have been asked to forward - pub packets_forwarded_in: Counter, - /// Number of `FrameType::Ping`s received pub got_ping: Counter, /// Number of `FrameType::Pong`s sent @@ -51,16 +46,14 @@ pub struct Metrics { /* * Metrics about peers */ - /// Number of packet forwarders added - pub added_pkt_fwder: Counter, - /// Number of packet forwarders removed - pub removed_pkt_fwder: Counter, - /// Number of connections we have accepted pub accepts: Counter, /// Number of connections we have removed because of an error pub disconnects: Counter, + /// Number of unique client keys per day + pub unique_client_keys: Counter, + /// Number of accepted websocket connections pub websocket_accepts: Counter, /// Number of accepted 'iroh derp http' connection upgrades @@ -96,14 +89,6 @@ impl Default for Metrics { other_packets_dropped: Counter::new( "Number of times a non-disco, non-'send; packet was dropped.", ), - - packets_forwarded_out: Counter::new( - "Number of times the server has sent a forwarded packet", - ), - packets_forwarded_in: Counter::new( - "Number of times the server has received a forwarded packet.", - ), - got_ping: Counter::new("Number of times the server has received a Ping from a client."), sent_pong: Counter::new("Number of times the server has sent a Pong to a client."), unknown_frames: Counter::new("Number of unknown frames sent to this server."), @@ -111,16 +96,11 @@ impl Default for Metrics { /* * Metrics about peers */ - added_pkt_fwder: Counter::new( - "Number of times a packeted forwarded was added to this server.", - ), - removed_pkt_fwder: Counter::new( - "Number of times a packet forwarded was removed to this server.", - ), - accepts: Counter::new("Number of times this server has accepted a connection."), disconnects: Counter::new("Number of clients that have then disconnected."), + unique_client_keys: Counter::new("Number of unique client keys per day."), + websocket_accepts: Counter::new("Number of accepted websocket connections"), derp_accepts: Counter::new("Number of accepted 'iroh derp http' connection upgrades"), // TODO: enable when we can have multiple connections for one node id diff --git a/iroh-net/src/relay/server.rs b/iroh-net/src/relay/server.rs index 8240b0fb2c..4ce80a3e6f 100644 --- a/iroh-net/src/relay/server.rs +++ b/iroh-net/src/relay/server.rs @@ -1,4 +1,5 @@ //! based on tailscale/derp/derp_server.go +use std::collections::HashMap; use std::pin::Pin; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; @@ -10,7 +11,8 @@ use futures_lite::Stream; use futures_sink::Sink; use hyper::HeaderMap; use iroh_metrics::core::UsageStatsReport; -use iroh_metrics::{inc, report_usage_stats}; +use iroh_metrics::{inc, inc_by, report_usage_stats}; +use time::{Date, OffsetDateTime}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::sync::mpsc; use tokio::task::JoinHandle; @@ -231,6 +233,7 @@ pub(crate) struct ServerActor { receiver: mpsc::Receiver, /// All clients connected to this server clients: Clients, + client_counter: ClientCounter, } impl ServerActor { @@ -239,6 +242,7 @@ impl ServerActor { key, receiver, clients: Clients::new(), + client_counter: ClientCounter::default(), } } @@ -290,43 +294,45 @@ impl ServerActor { tracing::warn!("send disco packet: no way to reach client {key:?}, dropped packet"); inc!(Metrics, disco_packets_dropped); } - } - ServerMessage::CreateClient(client_builder) => { - inc!(Metrics, accepts); + } + ServerMessage::CreateClient(client_builder) => { + inc!(Metrics, accepts); - tracing::trace!("create client: {:?}", client_builder.key); - let key = client_builder.key; + tracing::trace!("create client: {:?}", client_builder.key); + let key = client_builder.key; - report_usage_stats(&UsageStatsReport::new( + report_usage_stats(&UsageStatsReport::new( "relay_accepts".to_string(), self.key.to_string(), 1, None, // TODO(arqu): attribute to user id; possibly with the re-introduction of request tokens or other auth Some(key.to_string()), )).await; + let nc = self.client_counter.update(key); + inc_by!(Metrics, unique_client_keys, nc); - // build and register client, starting up read & write loops for the - // client connection - self.clients.register(client_builder); + // build and register client, starting up read & write loops for the + // client connection + self.clients.register(client_builder); - } - ServerMessage::RemoveClient((key, conn_num)) => { - inc!(Metrics, disconnects); - tracing::trace!("remove client: {:?}", key); - // ensure we still have the client in question - if self.clients.has_client(&key, conn_num) { - // remove the client from the map of clients, & notify any peers that it - // has sent messages that it has left the network - self.clients.unregister(&key); + } + ServerMessage::RemoveClient((key, conn_num)) => { + inc!(Metrics, disconnects); + tracing::trace!("remove client: {:?}", key); + // ensure we still have the client in question + if self.clients.has_client(&key, conn_num) { + // remove the client from the map of clients, & notify any peers that it + // has sent messages that it has left the network + self.clients.unregister(&key); } - } - ServerMessage::Shutdown => { - tracing::info!("server gracefully shutting down..."); - // close all client connections and client read/write loops - self.clients.shutdown().await; - return Ok(()); - } - } + } + ServerMessage::Shutdown => { + tracing::info!("server gracefully shutting down..."); + // close all client connections and client read/write loops + self.clients.shutdown().await; + return Ok(()); + } + } } } } @@ -510,6 +516,39 @@ impl AsyncWrite for MaybeTlsStream { } } +struct ClientCounter { + clients: HashMap, + last_clear_date: Date, +} + +impl Default for ClientCounter { + fn default() -> Self { + Self { + clients: HashMap::new(), + last_clear_date: OffsetDateTime::now_utc().date(), + } + } +} + +impl ClientCounter { + fn check_and_clear(&mut self) { + let today = OffsetDateTime::now_utc().date(); + if today != self.last_clear_date { + self.clients.clear(); + self.last_clear_date = today; + } + } + + /// Updates the client counter. + pub fn update(&mut self, client: PublicKey) -> u64 { + self.check_and_clear(); + let new_conn = !self.clients.contains_key(&client); + let counter = self.clients.entry(client).or_insert(0); + *counter += 1; + new_conn as u64 + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/iroh/src/metrics.rs b/iroh/src/metrics.rs index 8a4601745e..fb8e1cc93d 100644 --- a/iroh/src/metrics.rs +++ b/iroh/src/metrics.rs @@ -11,17 +11,49 @@ use crate::rpc_protocol::node::CounterStats; #[allow(missing_docs)] #[derive(Debug, Clone, Iterable)] pub struct Metrics { - pub requests_total: Counter, - pub bytes_sent: Counter, - pub bytes_received: Counter, + pub doc_gossip_tick_main: Counter, + pub doc_gossip_tick_event: Counter, + pub doc_gossip_tick_actor: Counter, + pub doc_gossip_tick_pending_join: Counter, + + pub doc_live_tick_main: Counter, + pub doc_live_tick_actor: Counter, + pub doc_live_tick_replica_event: Counter, + pub doc_live_tick_running_sync_connect: Counter, + pub doc_live_tick_running_sync_accept: Counter, + pub doc_live_tick_pending_downloads: Counter, } impl Default for Metrics { fn default() -> Self { Self { - requests_total: Counter::new("Total number of requests received"), - bytes_sent: Counter::new("Number of bytes streamed"), - bytes_received: Counter::new("Number of bytes received"), + doc_gossip_tick_main: Counter::new("Number of times the main gossip actor loop ticked"), + doc_gossip_tick_event: Counter::new( + "Number of times the gossip actor ticked for an event", + ), + doc_gossip_tick_actor: Counter::new( + "Number of times the gossip actor ticked for an actor message", + ), + doc_gossip_tick_pending_join: Counter::new( + "Number of times the gossip actor ticked pending join", + ), + + doc_live_tick_main: Counter::new("Number of times the main live actor loop ticked"), + doc_live_tick_actor: Counter::new( + "Number of times the live actor ticked for an actor message", + ), + doc_live_tick_replica_event: Counter::new( + "Number of times the live actor ticked for a replica event", + ), + doc_live_tick_running_sync_connect: Counter::new( + "Number of times the live actor ticked for a running sync connect", + ), + doc_live_tick_running_sync_accept: Counter::new( + "Number of times the live actor ticked for a running sync accept", + ), + doc_live_tick_pending_downloads: Counter::new( + "Number of times the live actor ticked for a pending download", + ), } } }