Skip to content

Commit

Permalink
fix(misc/server): adhere to --metrics-path and listen on 0.0.0.0:8888
Browse files Browse the repository at this point in the history
This commit reverts the previous metrics behavior. Namely:

- adhering to --metrics-path flag
- listening on 0.0.0.0:8888 instead of 127.0.0.1:8080

Note that 8888 is the default IPFS debug (aka. metrics) port.

See https://github.com/mxinden/rust-libp2p-server/blob/master/src/metric_server.rs for previous behavior.

Pull-Request: #4392.
  • Loading branch information
mxinden authored Aug 30, 2023
1 parent e36e8ce commit 96213b3
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 20 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ libp2p-quic = { version = "0.9.2", path = "transports/quic" }
libp2p-relay = { version = "0.16.1", path = "protocols/relay" }
libp2p-rendezvous = { version = "0.13.0", path = "protocols/rendezvous" }
libp2p-request-response = { version = "0.25.1", path = "protocols/request-response" }
libp2p-server = { version = "0.12.1", path = "misc/server" }
libp2p-server = { version = "0.12.2", path = "misc/server" }
libp2p-swarm = { version = "0.43.3", path = "swarm" }
libp2p-swarm-derive = { version = "0.33.0", path = "swarm-derive" }
libp2p-swarm-test = { version = "0.2.0", path = "swarm-test" }
Expand Down
8 changes: 7 additions & 1 deletion misc/server/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.12.1]
## [0.12.2]
### Fixed
- Adhere to `--metrics-path` flag and listen on `0.0.0.0:8888` (default IPFS metrics port).
[PR 4392]

[PR 4392]: https://github.com/libp2p/rust-libp2p/pull/4392

## [0.12.1]
### Changed
- Move to tokio and hyper.
See [PR 4311].
Expand Down
2 changes: 1 addition & 1 deletion misc/server/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "libp2p-server"
version = "0.12.1"
version = "0.12.2"
authors = ["Max Inden <mail@max-inden.de>"]
edition = "2021"
repository = "https://github.com/libp2p/rust-libp2p"
Expand Down
31 changes: 23 additions & 8 deletions misc/server/src/http_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,23 @@ use std::task::{Context, Poll};

const METRICS_CONTENT_TYPE: &str = "application/openmetrics-text;charset=utf-8;version=1.0.0";

pub(crate) async fn metrics_server(registry: Registry) -> Result<(), std::io::Error> {
pub(crate) async fn metrics_server(
registry: Registry,
metrics_path: String,
) -> Result<(), std::io::Error> {
// Serve on localhost.
let addr = ([127, 0, 0, 1], 8080).into();
let addr = ([0, 0, 0, 0], 8888).into();

// Use the tokio runtime to run the hyper server.
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(async {
let server = Server::bind(&addr).serve(MakeMetricService::new(registry));
info!("Metrics server on http://{}/metrics", server.local_addr());
let server =
Server::bind(&addr).serve(MakeMetricService::new(registry, metrics_path.clone()));
info!(
"Metrics server on http://{}{}",
server.local_addr(),
metrics_path
);
if let Err(e) = server.await {
error!("server error: {}", e);
}
Expand All @@ -49,6 +57,7 @@ pub(crate) async fn metrics_server(registry: Registry) -> Result<(), std::io::Er

pub(crate) struct MetricService {
reg: Arc<Mutex<Registry>>,
metrics_path: String,
}

type SharedRegistry = Arc<Mutex<Registry>>;
Expand All @@ -75,7 +84,10 @@ impl MetricService {
fn respond_with_404_not_found(&mut self) -> Response<String> {
Response::builder()
.status(StatusCode::NOT_FOUND)
.body("Not found try localhost:[port]/metrics".to_string())
.body(format!(
"Not found try localhost:[port]/{}",
self.metrics_path
))
.unwrap()
}
}
Expand All @@ -92,7 +104,7 @@ impl Service<Request<Body>> for MetricService {
fn call(&mut self, req: Request<Body>) -> Self::Future {
let req_path = req.uri().path();
let req_method = req.method();
let resp = if (req_method == Method::GET) && (req_path == "/metrics") {
let resp = if (req_method == Method::GET) && (req_path == self.metrics_path) {
// Encode and serve metrics from registry.
self.respond_with_metrics()
} else {
Expand All @@ -104,12 +116,14 @@ impl Service<Request<Body>> for MetricService {

pub(crate) struct MakeMetricService {
reg: SharedRegistry,
metrics_path: String,
}

impl MakeMetricService {
pub(crate) fn new(registry: Registry) -> MakeMetricService {
pub(crate) fn new(registry: Registry, metrics_path: String) -> MakeMetricService {
MakeMetricService {
reg: Arc::new(Mutex::new(registry)),
metrics_path,
}
}
}
Expand All @@ -125,7 +139,8 @@ impl<T> Service<T> for MakeMetricService {

fn call(&mut self, _: T) -> Self::Future {
let reg = self.reg.clone();
let fut = async move { Ok(MetricService { reg }) };
let metrics_path = self.metrics_path.clone();
let fut = async move { Ok(MetricService { reg, metrics_path }) };
Box::pin(fut)
}
}
21 changes: 13 additions & 8 deletions misc/server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use libp2p::swarm::{SwarmBuilder, SwarmEvent};
use libp2p::tcp;
use libp2p::yamux;
use libp2p::Transport;
use log::{debug, info};
use log::{debug, info, warn};
use prometheus_client::metrics::info::Info;
use prometheus_client::registry::Registry;
use std::error::Error;
Expand Down Expand Up @@ -79,7 +79,7 @@ async fn main() -> Result<(), Box<dyn Error>> {

(peer_id, keypair)
};
println!("Local peer id: {local_peer_id}");
info!("Local peer id: {local_peer_id}");

let transport = {
let tcp_transport =
Expand Down Expand Up @@ -115,24 +115,24 @@ async fn main() -> Result<(), Box<dyn Error>> {
let mut swarm = SwarmBuilder::with_tokio_executor(transport, behaviour, local_peer_id).build();

if config.addresses.swarm.is_empty() {
log::warn!("No listen addresses configured.");
warn!("No listen addresses configured.");
}
for address in &config.addresses.swarm {
match swarm.listen_on(address.clone()) {
Ok(_) => {}
Err(e @ libp2p::TransportError::MultiaddrNotSupported(_)) => {
log::warn!("Failed to listen on {address}, continuing anyways, {e}")
warn!("Failed to listen on {address}, continuing anyways, {e}")
}
Err(e) => return Err(e.into()),
}
}
if config.addresses.append_announce.is_empty() {
log::warn!("No external addresses configured.");
warn!("No external addresses configured.");
}
for address in &config.addresses.append_announce {
swarm.add_external_address(address.clone())
}
log::info!(
info!(
"External addresses: {:?}",
swarm.external_addresses().collect::<Vec<_>>()
);
Expand All @@ -145,7 +145,12 @@ async fn main() -> Result<(), Box<dyn Error>> {
"A metric with a constant '1' value labeled by version",
build_info,
);
thread::spawn(move || block_on(http_service::metrics_server(metric_registry)));
thread::spawn(move || {
block_on(http_service::metrics_server(
metric_registry,
opt.metrics_path,
))
});

let mut bootstrap_timer = Delay::new(BOOTSTRAP_INTERVAL);

Expand Down Expand Up @@ -205,7 +210,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// metrics.record(&e)
}
SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening on {address:?}");
info!("Listening on {address:?}");
}
_ => {}
}
Expand Down

0 comments on commit 96213b3

Please sign in to comment.