diff --git a/metrics-plugin/README.md b/metrics-plugin/README.md index 48dfe84..e9c5e48 100644 --- a/metrics-plugin/README.md +++ b/metrics-plugin/README.md @@ -70,11 +70,27 @@ scrape_configs: ### Funds -| Metric | Type | Description | -|--------------------------------|-------|-------------------------------------| -| `lightning_funds_output_msat` | Gauge | On-chain balance | -| `lightning_funds_channel_msat` | Gauge | Balance held in channels (our side) | -| `lightning_funds_total_msat` | Gauge | Total balance (on-chain + channels) | +| Metric | Type | Description | +|--------------------------------|-------|-----------------------------------------------------------------------------| +| `lightning_funds_output_msat` | Gauge | On-chain balance, by output `status` and `reserved` (see below) | +| `lightning_funds_channel_msat` | Gauge | Balance held in channels (our side) | +| `lightning_funds_total_msat` | Gauge | Total balance (all on-chain outputs + channels) | + +`lightning_funds_output_msat` has two labels, taken from each `listfunds` output: + +- `status`: `unconfirmed`, `confirmed`, `spent` or `immature` +- `reserved`: `true` when a pending transaction (such as a channel open) has reserved the output, else `false` + +All 8 combinations are always exported, at 0 when empty. `spent` stays at 0, because the +plugin calls `listfunds` without `spent`. + +```promql +# On-chain funds that can be spent now, e.g. to open a channel +lightning_funds_output_msat{status="confirmed", reserved="false"} + +# All on-chain funds (what the series showed before it had labels) +sum without (status, reserved) (lightning_funds_output_msat) +``` ### Liquidity diff --git a/metrics-plugin/dashboards/cln-metrics.json b/metrics-plugin/dashboards/cln-metrics.json new file mode 100644 index 0000000..bc44e4e --- /dev/null +++ b/metrics-plugin/dashboards/cln-metrics.json @@ -0,0 +1,697 @@ +{ + "title": "CLN Node Metrics", + "uid": "cln-metrics", + "schemaVersion": 38, + "version": 5, + "refresh": "15s", + "time": { "from": "now-1h", "to": "now" }, + "timepicker": {}, + "timezone": "browser", + "editable": true, + "graphTooltip": 0, + "links": [], + "annotations": { "list": [] }, + "templating": { + "list": [ + { + "name": "node_id", + "label": "Node", + "type": "query", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "query": { + "query": "label_values(lightning_node_blockheight, node_id)", + "refId": "StandardVariableQuery" + }, + "refresh": 2, + "includeAll": false, + "multi": false, + "sort": 1, + "hide": 0, + "searchable": true, + "current": {} + }, + { + "name": "channel", + "label": "Channel (scid)", + "type": "query", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "query": { + "query": "label_values(lightning_channel_balance_msat{node_id=\"$node_id\"}, scid)", + "refId": "StandardVariableQuery" + }, + "refresh": 2, + "includeAll": true, + "allValue": ".*", + "multi": false, + "sort": 1, + "hide": 0, + "searchable": true, + "current": {} + } + ] + }, + "panels": [ + { + "id": 1, + "title": "Block Height", + "type": "stat", + "gridPos": { "h": 4, "w": 4, "x": 0, "y": 0 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "value", + "graphMode": "none", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "text", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_node_blockheight{node_id=\"$node_id\"}", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 31, + "title": "Peers", + "type": "stat", + "gridPos": { "h": 4, "w": 4, "x": 8, "y": 0 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "value", + "graphMode": "none", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "blue", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_peers{node_id=\"$node_id\"}", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 32, + "title": "Channels", + "type": "stat", + "gridPos": { "h": 4, "w": 4, "x": 12, "y": 0 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "value", + "graphMode": "none", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "purple", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_channels{node_id=\"$node_id\"}", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 33, + "title": "Version", + "type": "stat", + "gridPos": { "h": 4, "w": 8, "x": 16, "y": 0 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "name", "colorMode": "none", + "graphMode": "none", "justifyMode": "center" + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "text", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_build_info{node_id=\"$node_id\"}", + "legendFormat": "{{version}}", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 3, + "title": "Total Funds (BTC)", + "description": "On-chain + channel funds", + "type": "stat", + "gridPos": { "h": 4, "w": 6, "x": 0, "y": 4 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "value", + "graphMode": "none", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "currencyBTC", "decimals": 4, + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "text", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_funds_total_msat{node_id=\"$node_id\"} / 1e11", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 4, + "title": "On-chain Funds (BTC)", + "type": "stat", + "gridPos": { "h": 4, "w": 6, "x": 6, "y": 4 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "value", + "graphMode": "none", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "currencyBTC", "decimals": 4, + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "blue", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "sum(lightning_funds_output_msat{node_id=\"$node_id\"}) / 1e11", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 5, + "title": "Channel Funds (BTC)", + "type": "stat", + "gridPos": { "h": 4, "w": 6, "x": 12, "y": 4 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "value", + "graphMode": "none", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "currencyBTC", "decimals": 4, + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "purple", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_funds_channel_msat{node_id=\"$node_id\"} / 1e11", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 2, + "title": "Fees Collected (sat)", + "type": "stat", + "gridPos": { "h": 4, "w": 6, "x": 18, "y": 4 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "value", + "graphMode": "none", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_fees_collected_msat{node_id=\"$node_id\"} / 1000", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 34, + "title": "Total Outbound (BTC)", + "description": "Sum of spendable across all channels", + "type": "stat", + "gridPos": { "h": 4, "w": 6, "x": 0, "y": 8 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "background", + "graphMode": "none", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "currencyBTC", "decimals": 4, + "color": { "mode": "thresholds" }, + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "red", "value": null }, + { "color": "yellow", "value": 0.00001 }, + { "color": "green", "value": 0.00005 } + ] + } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_total_outbound_msat{node_id=\"$node_id\"} / 1e11", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 35, + "title": "Total Inbound (BTC)", + "description": "Sum of receivable across all channels", + "type": "stat", + "gridPos": { "h": 4, "w": 6, "x": 6, "y": 8 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "background", + "graphMode": "none", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "currencyBTC", "decimals": 4, + "color": { "mode": "thresholds" }, + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "red", "value": null }, + { "color": "yellow", "value": 0.00001 }, + { "color": "green", "value": 0.00005 } + ] + } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_total_inbound_msat{node_id=\"$node_id\"} / 1e11", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 36, + "title": "Liquidity Distribution", + "description": "Outbound vs inbound across all channels", + "type": "piechart", + "gridPos": { "h": 4, "w": 12, "x": 12, "y": 8 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "pieType": "pie", + "legend": { "displayMode": "list", "placement": "right" }, + "tooltip": { "mode": "single" } + }, + "fieldConfig": { + "defaults": { "unit": "short", "decimals": 0 }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_total_outbound_msat{node_id=\"$node_id\"}", + "legendFormat": "Outbound", "instant": true, "refId": "A" + }, + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_total_inbound_msat{node_id=\"$node_id\"}", + "legendFormat": "Inbound", "instant": true, "refId": "B" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 20, + "title": "Events", + "type": "row", + "gridPos": { "h": 1, "w": 24, "x": 0, "y": 12 }, + "collapsed": false + }, + { + "id": 11, + "title": "Forward Events", + "description": "Forwarding events by status", + "type": "timeseries", + "gridPos": { "h": 8, "w": 16, "x": 0, "y": 13 }, + "options": { + "tooltip": { "mode": "multi", "sort": "none" }, + "legend": { "displayMode": "list", "placement": "bottom" } + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "color": { "mode": "palette-classic" }, + "custom": { "lineWidth": 2, "fillOpacity": 10 } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_forward_events_total{node_id=\"$node_id\"}", + "legendFormat": "{{status}}", "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 12, + "title": "HTLCs Accepted", + "type": "stat", + "gridPos": { "h": 4, "w": 4, "x": 16, "y": 13 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "value", + "graphMode": "area", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_htlc_accepted_total{node_id=\"$node_id\"}", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 13, + "title": "Channels Opened", + "type": "stat", + "gridPos": { "h": 4, "w": 4, "x": 20, "y": 13 }, + "options": { + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "orientation": "auto", "textMode": "auto", "colorMode": "value", + "graphMode": "area", "justifyMode": "auto" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "blue", "value": null }] } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_channel_opened_total{node_id=\"$node_id\"}", + "legendFormat": "", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 14, + "title": "Channel State Changes", + "type": "timeseries", + "gridPos": { "h": 4, "w": 8, "x": 16, "y": 17 }, + "options": { + "tooltip": { "mode": "multi", "sort": "none" }, + "legend": { "displayMode": "list", "placement": "bottom" } + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "color": { "mode": "palette-classic" }, + "custom": { "lineWidth": 2, "fillOpacity": 10 } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_channel_state_changes_total{node_id=\"$node_id\"}", + "legendFormat": "{{old_state}} → {{new_state}}", "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 21, + "title": "Channel Detail — $channel", + "type": "row", + "gridPos": { "h": 1, "w": 24, "x": 0, "y": 21 }, + "collapsed": false + }, + { + "id": 6, + "title": "Balance (sat) — our side", + "description": "Our balance per channel", + "type": "bargauge", + "gridPos": { "h": 8, "w": 6, "x": 0, "y": 22 }, + "options": { + "orientation": "horizontal", "displayMode": "basic", + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "showUnfilled": true, "valueMode": "color" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, "min": 0, + "color": { "mode": "thresholds" }, + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "red", "value": null }, + { "color": "yellow", "value": 100000 }, + { "color": "green", "value": 500000 } + ] + } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_channel_balance_msat{node_id=\"$node_id\",scid=~\"$channel\"}", + "legendFormat": "{{scid}}", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 7, + "title": "Spendable (sat) — outbound", + "description": "Currently spendable per channel", + "type": "bargauge", + "gridPos": { "h": 8, "w": 6, "x": 6, "y": 22 }, + "options": { + "orientation": "horizontal", "displayMode": "basic", + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "showUnfilled": true, "valueMode": "color" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, "min": 0, + "color": { "mode": "thresholds" }, + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "red", "value": null }, + { "color": "yellow", "value": 100000 }, + { "color": "green", "value": 500000 } + ] + } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_channel_spendable_msat{node_id=\"$node_id\",scid=~\"$channel\"}", + "legendFormat": "{{scid}}", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 37, + "title": "Receivable (sat) — inbound", + "description": "Currently receivable per channel", + "type": "bargauge", + "gridPos": { "h": 8, "w": 6, "x": 12, "y": 22 }, + "options": { + "orientation": "horizontal", "displayMode": "basic", + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "showUnfilled": true, "valueMode": "color" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, "min": 0, + "color": { "mode": "thresholds" }, + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "red", "value": null }, + { "color": "yellow", "value": 100000 }, + { "color": "green", "value": 500000 } + ] + } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_channel_receivable_msat{node_id=\"$node_id\",scid=~\"$channel\"}", + "legendFormat": "{{scid}}", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 8, + "title": "Capacity (sat)", + "description": "Total capacity per channel", + "type": "bargauge", + "gridPos": { "h": 8, "w": 6, "x": 18, "y": 22 }, + "options": { + "orientation": "horizontal", "displayMode": "basic", + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "showUnfilled": true, "valueMode": "color" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, "min": 0, + "color": { "mode": "thresholds" }, + "thresholds": { + "mode": "absolute", + "steps": [{ "color": "text", "value": null }] + } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_channel_capacity_msat{node_id=\"$node_id\",scid=~\"$channel\"}", + "legendFormat": "{{scid}}", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 15, + "title": "Active HTLCs", + "type": "bargauge", + "gridPos": { "h": 6, "w": 12, "x": 0, "y": 30 }, + "options": { + "orientation": "horizontal", "displayMode": "basic", + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "showUnfilled": true, "valueMode": "color" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, "min": 0, + "color": { "mode": "thresholds" }, + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "green", "value": null }, + { "color": "yellow", "value": 5 }, + { "color": "red", "value": 20 } + ] + } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_channel_htlcs{node_id=\"$node_id\",scid=~\"$channel\"}", + "legendFormat": "{{scid}}", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + }, + { + "id": 9, + "title": "Peer Connectivity", + "description": "1 = connected, 0 = disconnected", + "type": "bargauge", + "gridPos": { "h": 6, "w": 12, "x": 12, "y": 30 }, + "options": { + "orientation": "horizontal", "displayMode": "basic", + "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, + "showUnfilled": true, "valueMode": "color" + }, + "fieldConfig": { + "defaults": { + "unit": "short", "decimals": 0, "min": 0, "max": 1, + "color": { "mode": "thresholds" }, + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "red", "value": null }, + { "color": "green", "value": 1 } + ] + } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "lightning_peer_connected{node_id=\"$node_id\"}", + "legendFormat": "{{id}}", "instant": true, "refId": "A" + } + ], + "datasource": { "type": "prometheus", "uid": "prometheus" } + } + ] +} diff --git a/metrics-plugin/src/cache.rs b/metrics-plugin/src/cache.rs index 5a4b0c0..96171c4 100644 --- a/metrics-plugin/src/cache.rs +++ b/metrics-plugin/src/cache.rs @@ -3,6 +3,7 @@ use std::path::Path; use cln_rpc::ClnRpc; use cln_rpc::model::requests::{GetinfoRequest, ListfundsRequest, ListpeerchannelsRequest}; +use cln_rpc::model::responses::{ListfundsOutputs, ListfundsOutputsStatus}; #[derive(Clone, Default)] pub struct ChannelSnapshot { @@ -30,12 +31,43 @@ pub struct NodeSnapshot { pub fees_collected_msat: i64, } +/// Every `status` `listfunds` can report for an output, in a fixed order so +/// each scrape exports the same series, at 0 when the wallet has none. +pub const OUTPUT_STATUSES: [&str; 4] = ["unconfirmed", "confirmed", "spent", "immature"]; + #[derive(Clone, Default)] pub struct FundsSnapshot { - pub output_msat: i64, + /// On-chain msat per output status (indexed like `OUTPUT_STATUSES`), + /// split by whether the output is reserved: `[unreserved, reserved]`. + pub outputs_msat: [[i64; 2]; OUTPUT_STATUSES.len()], pub channel_msat: i64, } +impl FundsSnapshot { + /// All on-chain outputs, whatever their status or reservation. + pub fn output_msat(&self) -> i64 { + self.outputs_msat.iter().flatten().sum() + } +} + +fn status_index(status: &ListfundsOutputsStatus) -> usize { + match status { + ListfundsOutputsStatus::UNCONFIRMED => 0, + ListfundsOutputsStatus::CONFIRMED => 1, + ListfundsOutputsStatus::SPENT => 2, + ListfundsOutputsStatus::IMMATURE => 3, + } +} + +/// Sums `listfunds` outputs by status and reservation. +fn split_outputs(outputs: &[ListfundsOutputs]) -> [[i64; 2]; OUTPUT_STATUSES.len()] { + let mut split = [[0; 2]; OUTPUT_STATUSES.len()]; + for o in outputs { + split[status_index(&o.status)][usize::from(o.reserved)] += o.amount_msat.msat() as i64; + } + split +} + #[derive(Clone, Default)] pub struct PeerSnapshot { pub id: String, @@ -71,11 +103,7 @@ pub async fn fetch(socket: &Path) -> anyhow::Result { fees_collected_msat: info.fees_collected_msat.msat() as i64, }; - let output_msat: i64 = funds_resp - .outputs - .iter() - .map(|o| o.amount_msat.msat() as i64) - .sum(); + let outputs_msat = split_outputs(&funds_resp.outputs); let channel_msat: i64 = funds_resp .channels @@ -137,10 +165,67 @@ pub async fn fetch(socket: &Path) -> anyhow::Result { Ok(CachedData { node, funds: FundsSnapshot { - output_msat, + outputs_msat, channel_msat, }, channels, peers, }) } + +#[cfg(test)] +mod tests { + use super::*; + use ListfundsOutputsStatus::*; + use cln_rpc::primitives::Amount; + + fn output(status: ListfundsOutputsStatus, reserved: bool, sat: u64) -> ListfundsOutputs { + ListfundsOutputs { + address: None, + blockheight: None, + redeemscript: None, + reserved_to_block: None, + status, + amount_msat: Amount::from_msat(sat * 1000), + output: 0, + reserved, + scriptpubkey: String::new(), + txid: String::new(), + } + } + + #[test] + fn outputs_are_split_by_status_and_reservation() { + let funds = FundsSnapshot { + outputs_msat: split_outputs(&[ + output(CONFIRMED, false, 200_000), + output(CONFIRMED, false, 50_000), + output(CONFIRMED, true, 300_000), + output(UNCONFIRMED, false, 70_000), + output(UNCONFIRMED, true, 1_000), + output(IMMATURE, false, 5_000), + ]), + channel_msat: 0, + }; + + // [unreserved, reserved] per status, indexed like OUTPUT_STATUSES. + assert_eq!(funds.outputs_msat[0], [70_000_000, 1_000_000]); + assert_eq!(funds.outputs_msat[1], [250_000_000, 300_000_000]); + assert_eq!(funds.outputs_msat[2], [0, 0]); + assert_eq!(funds.outputs_msat[3], [5_000_000, 0]); + // The labelled series add up to the old unlabelled total. + assert_eq!(funds.output_msat(), 626_000_000); + } + + #[test] + fn status_index_matches_output_statuses() { + for (status, name) in [UNCONFIRMED, CONFIRMED, SPENT, IMMATURE].iter().zip([ + "unconfirmed", + "confirmed", + "spent", + "immature", + ]) { + assert_eq!(OUTPUT_STATUSES[status_index(status)], name); + } + } +} diff --git a/metrics-plugin/src/metrics.rs b/metrics-plugin/src/metrics.rs index fd8d744..28e3086 100644 --- a/metrics-plugin/src/metrics.rs +++ b/metrics-plugin/src/metrics.rs @@ -1,4 +1,4 @@ -use crate::cache::CachedData; +use crate::cache::{CachedData, OUTPUT_STATUSES}; use axum::{ Router, extract::{Request, State}, @@ -19,6 +19,7 @@ use tracing::error; const CHANNEL_LABELS: &[&str] = &["peer_id", "scid"]; const PEER_LABELS: &[&str] = &["peer_id"]; +const FUNDS_OUTPUT_LABELS: &[&str] = &["status", "reserved"]; /// Registers with the global registry while returning a caller-owned handle. /// Clone happens before boxing because 'register' takes ownership via 'Box'. @@ -187,7 +188,7 @@ impl DerivedCollector { ); let funds_output_msat = o( "lightning_funds_output_msat", - "On-chain millisatoshis available to the node.", + "On-chain millisatoshis in the node's wallet outputs, by status and reservation.", ); let funds_channel_msat = o( "lightning_funds_channel_msat", @@ -281,7 +282,6 @@ impl DerivedCollector { for opts in [ &node_blockheight, &fees_collected_msat, - &funds_output_msat, &funds_channel_msat, &funds_total_msat, &total_outbound_msat, @@ -292,6 +292,8 @@ impl DerivedCollector { let g = Gauge::with_opts(opts.clone())?; descs.extend(g.desc().into_iter().cloned()); } + let gv = GaugeVec::new(funds_output_msat.clone(), FUNDS_OUTPUT_LABELS)?; + descs.extend(gv.desc().into_iter().cloned()); for opts in [ &channel_balance_msat, &channel_spendable_msat, @@ -370,17 +372,23 @@ impl Collector for DerivedCollector { &self.fees_collected_msat, cache.node.fees_collected_msat as f64, )); - out.extend(scalar( - &self.funds_output_msat, - cache.funds.output_msat as f64, - )); + let funds_output = + GaugeVec::new(self.funds_output_msat.clone(), FUNDS_OUTPUT_LABELS).unwrap(); + for (status, by_reserved) in OUTPUT_STATUSES.iter().zip(cache.funds.outputs_msat) { + for (reserved, msat) in ["false", "true"].iter().zip(by_reserved) { + funds_output + .with_label_values(&[*status, *reserved]) + .set(msat as f64); + } + } + out.extend(funds_output.collect()); out.extend(scalar( &self.funds_channel_msat, cache.funds.channel_msat as f64, )); out.extend(scalar( &self.funds_total_msat, - (cache.funds.output_msat + cache.funds.channel_msat) as f64, + (cache.funds.output_msat() + cache.funds.channel_msat) as f64, )); let total_outbound: i64 = cache.channels.iter().map(|c| c.spendable_msat).sum(); @@ -639,4 +647,61 @@ mod tests { let app = Router::new().route("/metrics", get(metrics_handler)); assert_eq!(get_metrics(app, None).await, StatusCode::OK); } + + fn scrape(funds: crate::cache::FundsSnapshot) -> String { + let cache = Arc::new(RwLock::new(CachedData { + funds, + ..Default::default() + })); + let collector = DerivedCollector::new("n1", cache).unwrap(); + // Like prometheus::gather(), skip families with no series (here, the + // per-channel and per-peer ones); the encoder rejects them. + let families: Vec<_> = collector + .collect() + .into_iter() + .filter(|f| !f.get_metric().is_empty()) + .collect(); + let mut buf = Vec::new(); + TextEncoder::new().encode(&families, &mut buf).unwrap(); + String::from_utf8(buf).unwrap() + } + + fn value(text: &str, series: &str) -> f64 { + text.lines() + .find_map(|l| l.strip_prefix(series)?.strip_prefix(' ')?.parse().ok()) + .unwrap_or_else(|| panic!("{series} not in:\n{text}")) + } + + #[test] + fn funds_are_exported_by_status_and_reservation() { + let mut outputs_msat = [[0; 2]; OUTPUT_STATUSES.len()]; + outputs_msat[0] = [7_000, 1_000]; // unconfirmed + outputs_msat[1] = [25_000, 30_000]; // confirmed + let text = scrape(crate::cache::FundsSnapshot { + outputs_msat, + channel_msat: 100_000, + }); + + let output = |status: &str, reserved: &str| { + value( + &text, + &format!( + r#"lightning_funds_output_msat{{node_id="n1",reserved="{reserved}",status="{status}"}}"# + ), + ) + }; + // Spendable on-chain funds: confirmed and not reserved. + assert_eq!(output("confirmed", "false"), 25_000.0); + assert_eq!(output("confirmed", "true"), 30_000.0); + assert_eq!(output("unconfirmed", "false"), 7_000.0); + assert_eq!(output("unconfirmed", "true"), 1_000.0); + // Statuses without outputs are exported at 0, so the series never go absent. + assert_eq!(output("immature", "false"), 0.0); + assert_eq!(output("spent", "true"), 0.0); + + assert_eq!( + value(&text, r#"lightning_funds_total_msat{node_id="n1"}"#), + 163_000.0 + ); + } }