Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions metrics-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
109 changes: 109 additions & 0 deletions metrics-plugin/src/cache.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -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<ChainSnapshot>,
pub funds: FundsSnapshot,
pub channels: Vec<ChannelSnapshot>,
pub peers: Vec<PeerSnapshot>,
Expand All @@ -57,6 +74,19 @@ pub async fn fetch(socket: &Path) -> anyhow::Result<CachedData> {
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,
Expand Down Expand Up @@ -136,6 +166,7 @@ pub async fn fetch(socket: &Path) -> anyhow::Result<CachedData> {

Ok(CachedData {
node,
chain,
funds: FundsSnapshot {
output_msat,
channel_msat,
Expand All @@ -144,3 +175,81 @@ pub async fn fetch(socket: &Path) -> anyhow::Result<CachedData> {
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<ChainSnapshot> {
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<ChainSnapshot> {
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}");
}
}
}
69 changes: 68 additions & 1 deletion metrics-plugin/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -359,12 +381,17 @@ impl Collector for DerivedCollector {

fn collect(&self) -> Vec<MetricFamily> {
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,
Expand Down Expand Up @@ -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(&registry.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"#));
}
}
Loading