diff --git a/metrics-plugin/README.md b/metrics-plugin/README.md index 48dfe84..c46cc71 100644 --- a/metrics-plugin/README.md +++ b/metrics-plugin/README.md @@ -68,6 +68,20 @@ scrape_configs: | `lightning_node_blockheight` | Gauge | Current Bitcoin blockheight | | `lightning_fees_collected_msat` | Gauge | Total routing fees collected | +### Chain + +From `getchaininfo`, which CLN's Bitcoin backend plugin (`bcli` by default) +answers from bitcoind. `lightning_chain_headers - lightning_node_blockheight` +is how many blocks the node is behind its bitcoind. If `getchaininfo` fails +or takes over 10 s, these series are absent until the next successful +refresh; the other metrics still refresh. + +| Metric | Type | Description | +|---------------------------|-------|-------------------------------------------------| +| `lightning_chain_headers` | Gauge | Block headers bitcoind knows (`headercount`) | +| `lightning_chain_blocks` | Gauge | Blocks bitcoind has validated (`blockcount`) | +| `lightning_chain_ibd` | Gauge | `1` while bitcoind is in initial block download | + ### Funds | Metric | Type | Description | diff --git a/metrics-plugin/src/cache.rs b/metrics-plugin/src/cache.rs index 5a4b0c0..8742e62 100644 --- a/metrics-plugin/src/cache.rs +++ b/metrics-plugin/src/cache.rs @@ -1,8 +1,11 @@ use std::collections::HashMap; use std::path::Path; +use std::time::Duration; use cln_rpc::ClnRpc; use cln_rpc::model::requests::{GetinfoRequest, ListfundsRequest, ListpeerchannelsRequest}; +use serde_json::{Value, json}; +use tracing::warn; #[derive(Clone, Default)] pub struct ChannelSnapshot { @@ -30,6 +33,17 @@ pub struct NodeSnapshot { pub fees_collected_msat: i64, } +/// The chain as the Bitcoin backend (bcli) sees it, from `getchaininfo`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ChainSnapshot { + /// Headers bitcoind knows: the chain tip the node should reach. + pub headers: i64, + /// Blocks bitcoind has validated. + pub blocks: i64, + /// Whether bitcoind is in initial block download. + pub ibd: bool, +} + #[derive(Clone, Default)] pub struct FundsSnapshot { pub output_msat: i64, @@ -48,6 +62,9 @@ pub struct PeerSnapshot { #[derive(Clone, Default)] pub struct CachedData { pub node: NodeSnapshot, + /// `None` when `getchaininfo` failed: its series go missing for this + /// refresh, and every other metric still refreshes. + pub chain: Option, pub funds: FundsSnapshot, pub channels: Vec, pub peers: Vec, @@ -57,6 +74,19 @@ pub async fn fetch(socket: &Path) -> anyhow::Result { let mut rpc = ClnRpc::new(socket).await?; let info = rpc.call_typed(&GetinfoRequest {}).await?; + let chain = match tokio::time::timeout(CHAININFO_TIMEOUT, fetch_chain(socket, info.blockheight)) + .await + { + Ok(Ok(chain)) => Some(chain), + Ok(Err(e)) => { + warn!("getchaininfo failed, chain metrics missing: {:#}", e); + None + } + Err(_) => { + warn!("getchaininfo timed out, chain metrics missing"); + None + } + }; let channels_resp = rpc .call_typed(&ListpeerchannelsRequest { id: None, @@ -136,6 +166,7 @@ pub async fn fetch(socket: &Path) -> anyhow::Result { Ok(CachedData { node, + chain, funds: FundsSnapshot { output_msat, channel_msat, @@ -144,3 +175,81 @@ pub async fn fetch(socket: &Path) -> anyhow::Result { peers, }) } + +/// How long `getchaininfo` may take before its series are dropped for this +/// refresh. bcli asks bitcoind, which may be the thing that is stuck. +const CHAININFO_TIMEOUT: Duration = Duration::from_secs(10); + +/// `getchaininfo` is registered by CLN's Bitcoin backend plugin (bcli), and +/// cln-rpc 0.6 has no typed request for it. `last_height` is the node's own +/// height from `getinfo`. It runs on its own connection, so a call cut off +/// by the timeout leaves no reply pending on the one the refresh uses. +async fn fetch_chain(socket: &Path, last_height: u32) -> anyhow::Result { + let mut rpc = ClnRpc::new(socket).await?; + let resp: Value = rpc + .call_raw("getchaininfo", &json!({ "last_height": last_height })) + .await?; + parse_chaininfo(&resp) +} + +fn parse_chaininfo(resp: &Value) -> anyhow::Result { + let count = |field: &str| { + resp.get(field) + .and_then(Value::as_u64) + .and_then(|n| i64::try_from(n).ok()) + .ok_or_else(|| anyhow::anyhow!("getchaininfo: {field} missing or not a count")) + }; + Ok(ChainSnapshot { + headers: count("headercount")?, + blocks: count("blockcount")?, + ibd: resp + .get("ibd") + .and_then(Value::as_bool) + .ok_or_else(|| anyhow::anyhow!("getchaininfo: ibd missing or not a bool"))?, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_getchaininfo() { + let resp = json!({ + "chain": "main", + "headercount": 925_010, + "blockcount": 925_008, + "ibd": false, + }); + assert_eq!( + parse_chaininfo(&resp).unwrap(), + ChainSnapshot { + headers: 925_010, + blocks: 925_008, + ibd: false, + } + ); + } + + #[test] + fn parses_initial_block_download() { + let resp = json!({ "chain": "regtest", "headercount": 0, "blockcount": 0, "ibd": true }); + assert!(parse_chaininfo(&resp).unwrap().ibd); + } + + #[test] + fn refuses_a_malformed_getchaininfo() { + for resp in [ + json!({}), + json!({ "blockcount": 1, "ibd": false }), + json!({ "headercount": 1, "ibd": false }), + json!({ "headercount": 1, "blockcount": 1 }), + json!({ "headercount": -1, "blockcount": 1, "ibd": false }), + json!({ "headercount": "1", "blockcount": 1, "ibd": false }), + json!({ "headercount": 1.5, "blockcount": 1, "ibd": false }), + json!({ "headercount": 1, "blockcount": 1, "ibd": 0 }), + ] { + assert!(parse_chaininfo(&resp).is_err(), "{resp}"); + } + } +} diff --git a/metrics-plugin/src/metrics.rs b/metrics-plugin/src/metrics.rs index fd8d744..4e6c247 100644 --- a/metrics-plugin/src/metrics.rs +++ b/metrics-plugin/src/metrics.rs @@ -143,6 +143,10 @@ pub struct DerivedCollector { // Scalar gauges node_blockheight: Opts, + // Absent while getchaininfo fails, so alerts see a gap, not a stale value. + chain_headers: Opts, + chain_blocks: Opts, + chain_ibd: Opts, fees_collected_msat: Opts, funds_output_msat: Opts, funds_channel_msat: Opts, @@ -181,6 +185,18 @@ impl DerivedCollector { "lightning_node_blockheight", "Current Bitcoin blockheight on this node.", ); + let chain_headers = o( + "lightning_chain_headers", + "Block headers known to the node's bitcoind (getchaininfo headercount): the chain tip the node should reach.", + ); + let chain_blocks = o( + "lightning_chain_blocks", + "Blocks validated by the node's bitcoind (getchaininfo blockcount).", + ); + let chain_ibd = o( + "lightning_chain_ibd", + "Is the node's bitcoind in initial block download? (1=yes, 0=no)", + ); let fees_collected_msat = o( "lightning_fees_collected_msat", "Total routing fees collected by this node in millisatoshis.", @@ -280,6 +296,9 @@ impl DerivedCollector { let mut descs = Vec::new(); for opts in [ &node_blockheight, + &chain_headers, + &chain_blocks, + &chain_ibd, &fees_collected_msat, &funds_output_msat, &funds_channel_msat, @@ -324,6 +343,9 @@ impl DerivedCollector { cache, descs, node_blockheight, + chain_headers, + chain_blocks, + chain_ibd, fees_collected_msat, funds_output_msat, funds_channel_msat, @@ -359,12 +381,17 @@ impl Collector for DerivedCollector { fn collect(&self) -> Vec { let cache = self.cache.read().expect("cache lock poisoned"); - let mut out = Vec::with_capacity(26); + let mut out = Vec::with_capacity(29); out.extend(scalar( &self.node_blockheight, cache.node.blockheight as f64, )); + if let Some(chain) = &cache.chain { + out.extend(scalar(&self.chain_headers, chain.headers as f64)); + out.extend(scalar(&self.chain_blocks, chain.blocks as f64)); + out.extend(scalar(&self.chain_ibd, if chain.ibd { 1.0 } else { 0.0 })); + } out.extend(scalar( &self.fees_collected_msat, @@ -639,4 +666,44 @@ mod tests { let app = Router::new().route("/metrics", get(metrics_handler)); assert_eq!(get_metrics(app, None).await, StatusCode::OK); } + + fn exposition(cache: CachedData) -> String { + let registry = prometheus::Registry::new(); + let collector = DerivedCollector::new("02aa", Arc::new(RwLock::new(cache))).unwrap(); + registry.register(Box::new(collector)).unwrap(); + let mut body = Vec::new(); + TextEncoder::new() + .encode(®istry.gather(), &mut body) + .unwrap(); + String::from_utf8(body).unwrap() + } + + #[test] + fn chain_series_follow_getchaininfo() { + let mut cache = CachedData::default(); + cache.node.blockheight = 100; + cache.chain = Some(crate::cache::ChainSnapshot { + headers: 105, + blocks: 104, + ibd: true, + }); + let body = exposition(cache); + for line in [ + r#"lightning_node_blockheight{node_id="02aa"} 100"#, + r#"lightning_chain_headers{node_id="02aa"} 105"#, + r#"lightning_chain_blocks{node_id="02aa"} 104"#, + r#"lightning_chain_ibd{node_id="02aa"} 1"#, + ] { + assert!(body.lines().any(|l| l == line), "{line} not in:\n{body}"); + } + } + + #[test] + fn chain_series_are_absent_when_getchaininfo_failed() { + let mut cache = CachedData::default(); + cache.node.blockheight = 100; + let body = exposition(cache); + assert!(!body.contains("lightning_chain_"), "{body}"); + assert!(body.contains(r#"lightning_node_blockheight{node_id="02aa"} 100"#)); + } }