Repository navigation
feat: add prometheus metrics and integration tests to rpc-extractor - #339
Conversation
|
Changes:
|
| // Start the metric server with our custom registry. | ||
| shared::metricserver::start(&args.prometheus_address, Some(metrics.registry.clone())) | ||
| .expect("Could not start metric server"); |
There was a problem hiding this comment.
This should return a RuntimeError. You are going to need to implement it similar to the io:Error in
peer-observer/tools/metrics/src/error.rs
Line 12 in a3e6d14
| // Start the metric server with our custom registry. | |
| shared::metricserver::start(&args.prometheus_address, Some(metrics.registry.clone())) | |
| .expect("Could not start metric server"); | |
| // Start the metric server with our custom registry. | |
| shared::metricserver::start(&args.prometheus_address, Some(metrics.registry.clone()))?; |
| let _timer = metrics | ||
| .rpc_fetch_duration | ||
| .with_label_values(&[method_name]) | ||
| .start_timer(); |
There was a problem hiding this comment.
doesn't this also need timer.stop_and_record()?
There was a problem hiding this comment.
I it might work without it, as the duration is recorded when the timer is dropped. However, would be good to be explicit about only recording the duration for successful fetches?
| .with_label_values(&[method_name]) | ||
| .start_timer(); | ||
| let res = f(); | ||
| if res.is_err() { |
There was a problem hiding this comment.
Probably good to use timer.stop_and_discard() on error?
| [dev-dependencies] | ||
| ureq = "2.9" | ||
|
|
There was a problem hiding this comment.
An alternative would be to reuse this:
There was a problem hiding this comment.
There are no longer any dev-dependencies, so this can be removed?
0xB10C
left a comment
There was a problem hiding this comment.
Left a few comments above. General direction looks good!
Any reason this is a draft?
|
Thanks for the review! I had some initial doubts about the tests, that's why I left it as a draft. I'll review your latest observations today. |
bd5d90c to
474819d
Compare
|
I'll have another look at this soon. I want to finish #344 first. |
|
Ok, this is next! Can you rebase? Also, can you squash the commits into a few logically separate ones? No need to have seperate fixups for formatting in a PR :) Thanks! |
f96fef0 to
1f5cc1f
Compare
|
Sorry for the commit spam and multiple rebases, I was testing things out. Done & squashed the commits too. |
| [dev-dependencies] | ||
| ureq = "2.9" | ||
|
|
There was a problem hiding this comment.
There are no longer any dev-dependencies, so this can be removed?
There was a problem hiding this comment.
Any reason this is not instrumented?
There was a problem hiding this comment.
And here also not instrumented?
| })?; | ||
| Ok(()) | ||
| } | ||
|
|
There was a problem hiding this comment.
Below 2 methods as per other comments (that is, not instrumented).
| fetch_metrics(port, "/") | ||
| } | ||
|
|
||
| /// Extracts the count value from a histogram metric. |
There was a problem hiding this comment.
Is there much difference between these 2 methods?
one uses starts_with, the other uses contains
Seems like we could consolidate into a single method?
| /// # Panics | ||
| /// Panics if the metric is not found or the value cannot be parsed. | ||
| pub fn get_histogram_count(metrics_raw: &str, metric_name: &str, label_value: &str) -> u64 { | ||
| let search_pattern = format!("{}{{rpc_method=\"{}\"}}", metric_name, label_value); |
There was a problem hiding this comment.
These are only usable for RPC-extractor specific code with rpc_method
| /// # Panics | ||
| /// Panics if the metric is not found or the value cannot be parsed. | ||
| pub fn get_counter_value(metrics_raw: &str, metric_name: &str, label_value: &str) -> u64 { | ||
| let search_pattern = format!("{}{{rpc_method=\"{}\"}}", metric_name, label_value); |
There was a problem hiding this comment.
These are only usable for RPC-extractor specific code with rpc_method
| fn setup_node(conf: corepc_node::Conf) -> corepc_node::Node { | ||
| info!("env BITCOIND_EXE={:?}", std::env::var("BITCOIND_EXE")); | ||
| info!("exe_path={:?}", corepc_node::exe_path()); | ||
|
|
||
| if let Ok(exe_path) = corepc_node::exe_path() { | ||
| info!("Using bitcoind at '{}'", exe_path); | ||
| return corepc_node::Node::with_conf(exe_path, &conf).unwrap(); | ||
| } | ||
|
|
||
| info!("Trying to download a bitcoind.."); | ||
| corepc_node::Node::from_downloaded_with_conf(&conf).unwrap() | ||
| } | ||
|
|
||
| fn setup_two_connected_nodes() -> (corepc_node::Node, corepc_node::Node) { | ||
| // node1 listens for p2p connections | ||
| let mut node1_conf = corepc_node::Conf::default(); | ||
| node1_conf.p2p = corepc_node::P2P::Yes; | ||
| let node1 = setup_node(node1_conf); | ||
|
|
||
| // node2 connects to node1 | ||
| let mut node2_conf = corepc_node::Conf::default(); | ||
| node2_conf.p2p = node1.p2p_connect(true).unwrap(); | ||
| let node2 = setup_node(node2_conf); | ||
|
|
||
| (node1, node2) | ||
| } |
There was a problem hiding this comment.
This seems to be duplicate with the code in integration.rs? How about having a lib.rs for this?
| #[allow(clippy::too_many_arguments)] | ||
| fn make_test_args( | ||
| nats_port: u16, | ||
| rpc_url: String, | ||
| cookie_file: String, | ||
| prometheus_address: String, | ||
| disable_getpeerinfo: bool, | ||
| disable_getmempoolinfo: bool, | ||
| disable_uptime: bool, | ||
| disable_getnettotals: bool, | ||
| disable_getmemoryinfo: bool, | ||
| disable_getaddrmaninfo: bool, | ||
| disable_getchaintxstats: bool, | ||
| disable_getnetworkinfo: bool, | ||
| disable_getblockchaininfo: bool, | ||
| disable_getorphantxs: bool, | ||
| disable_getrawaddrman: bool, | ||
| ) -> Args { | ||
| Args::new( |
There was a problem hiding this comment.
Please use the function from integration.rs and use EnabledRPCsInTest in the tests.
peer-observer/extractors/rpc/tests/integration.rs
Lines 213 to 216 in 89c30e7
| pub query_interval_less_frequent: u64, | ||
|
|
||
| /// Address to serve Prometheus metrics on. | ||
| #[arg(long, default_value = "0.0.0.0:8284")] |
There was a problem hiding this comment.
Don't bind to all interfaces by default: 127.0.0.1:8284
| #[test] | ||
| fn test_metric_registration() { | ||
| // Creating a new Metrics instance should not panic. | ||
| // This verifies that the metrics are registered correctly with the custom registry. | ||
| let metrics = Metrics::new(); | ||
| let _ = metrics | ||
| .rpc_fetch_duration | ||
| .with_label_values(&["test_method"]); | ||
| let _ = metrics.rpc_fetch_errors.with_label_values(&["test_method"]); | ||
| let _ = metrics | ||
| .nats_publish_errors | ||
| .with_label_values(&["test_method"]); | ||
| } |
There was a problem hiding this comment.
I think this test mainly tests functionallity of the prometheus crate and not our code. Not sure if needed.
| #[test] | ||
| fn test_valid_label_values() { | ||
| // Verify that all RPC method names are valid labels. | ||
| // Invalid labels would cause a panic when accessing with_label_values(). | ||
| let metrics = Metrics::new(); | ||
| for method in RPC_METHODS { | ||
| let _ = metrics.rpc_fetch_duration.with_label_values(&[method]); | ||
| let _ = metrics.rpc_fetch_errors.with_label_values(&[method]); | ||
| let _ = metrics.nats_publish_errors.with_label_values(&[method]); | ||
| } | ||
| } |
There was a problem hiding this comment.
RPC_METHODSis missing methods. And we'll forget adding new ones to the list.- I don't think this test is worthwhile having. Again, we are testing functionallity provided by an upstream create here.
Feel free to drop
| #[test] | ||
| fn test_histogram_timer() { | ||
| // Verify that the histogram timer records observations. | ||
| let metrics = Metrics::new(); | ||
| let method = "test_histogram_timer"; | ||
| let histogram = metrics.rpc_fetch_duration.with_label_values(&[method]); | ||
| let count_before = histogram.get_sample_count(); | ||
|
|
||
| { | ||
| let _timer = histogram.start_timer(); | ||
| // Timer is dropped here, recording the observation | ||
| } | ||
|
|
||
| let count_after = histogram.get_sample_count(); | ||
| assert_eq!( | ||
| count_after, | ||
| count_before + 1, | ||
| "Histogram should have recorded one observation" | ||
| ); | ||
| } |
There was a problem hiding this comment.
again, this is not testing our code
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
There was a problem hiding this comment.
I think you can drop all of these as they aren't testing our code but the upstream code.
Since we have intregration test coverage for our metrics, I think there is no need to test the functionallity of the prometheus crate here. We'll notice if something changes in a way we don't like through the integration tests
1f5cc1f to
1ca6190
Compare
|
Thanks for the review, I think that all has been addressed:
|
deadmanoz
left a comment
There was a problem hiding this comment.
Almost there, just a few more things to consider/address!
| }; | ||
|
|
||
| #[tokio::test] | ||
| async fn test_integration_metrics_server_basic() { |
There was a problem hiding this comment.
Can you please provide a brief comment for each test describing what it does/what it's purpose is?
There was a problem hiding this comment.
e.g. the sequence that happens within
| } | ||
|
|
||
| #[derive(Default)] | ||
| pub struct EnabledRPCsInTest { |
There was a problem hiding this comment.
I did not know...
#[derive(Default)] on a struct with bool fields gives each field false by default!
| node1.rpc_url().replace("http://", ""), | ||
| node1.params.cookie_file.display().to_string(), | ||
| format!("127.0.0.1:{}", metrics_port), | ||
| EnabledRPCsInTest { |
There was a problem hiding this comment.
If you do the impl block with all() and enabled_methods(), we simply just use EnabledRPCsInTest::all() here!!!
| pub getorphantxs: bool, | ||
| pub getrawaddrman: bool, | ||
| } | ||
|
|
There was a problem hiding this comment.
I think you should add the following here:
impl EnabledRPCsInTest {
pub fn all() -> Self {
Self {
getpeerinfo: true,
getmempoolinfo: true,
uptime: true,
getnettotals: true,
getmemoryinfo: true,
getaddrmaninfo: true,
getchaintxstats: true,
getnetworkinfo: true,
getblockchaininfo: true,
getorphantxs: true,
getrawaddrman: true,
}
}
pub fn enabled_methods(&self) -> Vec<&'static str> {
let mut methods = Vec::new();
if self.getpeerinfo { methods.push("getpeerinfo"); }
if self.getmempoolinfo { methods.push("getmempoolinfo"); }
if self.uptime { methods.push("uptime"); }
if self.getnettotals { methods.push("getnettotals"); }
if self.getmemoryinfo { methods.push("getmemoryinfo"); }
if self.getaddrmaninfo { methods.push("getaddrmaninfo"); }
if self.getchaintxstats { methods.push("getchaintxstats"); }
if self.getnetworkinfo { methods.push("getnetworkinfo"); }
if self.getblockchaininfo { methods.push("getblockchaininfo"); }
if self.getorphantxs { methods.push("getorphantxs"); }
if self.getrawaddrman { methods.push("getrawaddrman"); }
methods
}
}
This would mean that one place needs updating as new RPCs are added. We don't need to update the tests too, they get it by virtue of using EnabledRPCsInTest::all() and EnabledRPCsInTest::enabled_methods()`!!
There was a problem hiding this comment.
I'll definitely try this!
| let metrics = fetch_metrics(metrics_port, "/metrics").expect("Should fetch metrics"); | ||
|
|
||
| // Verify that each enabled RPC method has recorded at least one call | ||
| let methods_to_check = [ |
There was a problem hiding this comment.
And this whole section, simply becomes...
let rpcs = EnabledRPCsInTest::all();
for method in rpcs.enabled_methods() {
let count = get_metric_value(/* ... */);
assert!(count >= 1, /* ... */);
}
| } | ||
|
|
||
| /// Convenience wrapper that fetches from the root path "/". | ||
| pub fn fetch_metrics_root(port: u16) -> Result<String, std::io::Error> { |
There was a problem hiding this comment.
So in shared/src/metricserver.rs handle_request actually discards the path!
Server reads raw bytes into buffer, but no inspection of method/path/headers:
fn handle_request(
mut stream: TcpStream,
registry: Option<Registry>,
) -> Result<(), RequestHandlingError> {
let mut buffer = [0; 1024];
let _ = stream.read(&mut buffer)?;
...
Server always executes the same response path:
- Gathers metrics (reg.gather() / prometheus::gather())
- Encodes to text
- Writes fixed HTTP/1.1 200 OK with the metrics body
- No branch on request path exists anywhere in
handle_request.
I don't think this was intentional with the original implementation (to confirm with @0xB10C?), but it means that fetch_metrics_root is redundant..
There was a problem hiding this comment.
I did that on purpose. It just serves metrics on all paths. On /, /metrics, /abc, all should return the same thing. I don't want to parse the path in there.
That said, probably a comment about this would have helped to explain it :)
There was a problem hiding this comment.
Thanks for clarification @0xB10C.
So yeah I think fetch_metrics_root is redundant, can just use fetch_metrics(port, "/") (or similar) everywhere.
1ca6190 to
abb08fb
Compare
|
Thanks again @deadmanoz ! Added impl EnabledRPCsInTest with all(), added #[allow(dead_code)] too, because it's referenced only in integration tests. |
|
I will review again |
|
Nice, thanks @GuiSchet. I think the only thing that remains is the redundant |
| @@ -403,11 +403,12 @@ checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" | |||
|
|
|||
| [[package]] | |||
| name = "colored" | |||
| version = "3.1.1" | |||
| version = "2.1.0" | |||
| source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" | |||
| checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8" | |||
| dependencies = [ | |||
| "windows-sys 0.61.2", | |||
| "lazy_static", | |||
| "windows-sys 0.48.0", | |||
| ] | |||
|
|
|||
| [[package]] | |||
| @@ -1175,9 +1176,9 @@ dependencies = [ | |||
|
|
|||
| [[package]] | |||
| name = "log" | |||
| version = "0.4.29" | |||
| version = "0.4.27" | |||
| source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" | |||
| checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" | |||
|
|
|||
| [[package]] | |||
| name = "log-extractor" | |||
| @@ -1289,9 +1290,9 @@ dependencies = [ | |||
|
|
|||
| [[package]] | |||
| name = "once_cell" | |||
| version = "1.18.0" | |||
| version = "1.21.3" | |||
| source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" | |||
| checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" | |||
There was a problem hiding this comment.
These look like unrelated updates to me?
|
Thank you @GuiSchet! I tested this a bit locally and it looks good. For the new prometheus metrics endpoint, a next step would be to support it in the infrastructure. I opened peer-observer/infra-library#107 for it. Feel free to focus on the |
PR Description:
Summary
This PR implements Prometheus metrics for the
rpc-extractorand adds a robust suite of integration tests.Key Changes
Metrics Instrumentation: Added Prometheus metrics to track RPC fetch durations and error rates (both for RPC calls and NATS publishing).
Configuration: Introduced a new
--prometheus-addressCLI argument (defaulting to0.0.0.0:8284) to serve the metrics.Enhanced Testing:
- Added unit tests for the metrics registration and logic.
- Implemented 14 integration tests.
- Verified that all enabled RPC methods (e.g.,
getpeerinfo,getmempoolinfo,uptime, etc.) correctly publish events.- Verified that Prometheus correctly records durations and increments error counters on failures (unreachable host, invalid auth).
Related Issues
#201