Skip to content

Commit

Permalink
chore(network): remove unwraps inside metrics server
Browse files Browse the repository at this point in the history
  • Loading branch information
RolandSherwin committed Sep 5, 2023
1 parent 3d17aba commit d772972
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 14 deletions.
4 changes: 4 additions & 0 deletions sn_networking/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ pub enum Error {

#[error("Failed to pop from front of CircularVec")]
CircularVecPopFrontError,

#[cfg(feature = "metrics")]
#[error("Network Metric error")]
NetworkMetricError,
}

#[cfg(test)]
Expand Down
41 changes: 27 additions & 14 deletions sn_networking/src/metrics_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use crate::{Error, Result};
use futures::Future;
use hyper::{service::Service, Request, Response, Server, StatusCode};
use hyper::{Body, Method};
use prometheus_client::encoding::text::encode;
use prometheus_client::registry::Registry;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use std::task::{Context, Poll};
use hyper::{service::Service, Body, Method, Request, Response, Server, StatusCode};
use prometheus_client::{encoding::text::encode, registry::Registry};
use std::{
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};

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

Expand Down Expand Up @@ -42,27 +42,37 @@ impl MetricService {
fn get_reg(&mut self) -> SharedRegistry {
Arc::clone(&self.reg)
}
fn respond_with_metrics(&mut self) -> Response<String> {
fn respond_with_metrics(&mut self) -> Result<Response<String>> {
let mut response: Response<String> = Response::default();

response.headers_mut().insert(
hyper::header::CONTENT_TYPE,
METRICS_CONTENT_TYPE.try_into().unwrap(),
METRICS_CONTENT_TYPE
.try_into()
.map_err(|_| Error::NetworkMetricError)?,
);

let reg = self.get_reg();
encode(&mut response.body_mut(), &reg.lock().unwrap()).unwrap();
let reg = reg.lock().map_err(|_| Error::NetworkMetricError)?;
encode(&mut response.body_mut(), &reg).map_err(|_| Error::NetworkMetricError)?;

*response.status_mut() = StatusCode::OK;

response
Ok(response)
}

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())

Check notice

Code scanning / devskim

Accessing localhost could indicate debug code, or could hinder scaling. Note

Do not leave debug code in production
.unwrap()
.expect("Failed to build 404 Response")
}

fn respond_with_500_server_error(&mut self) -> Response<String> {
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body("Something went wrong".to_string())
.expect("Failed to build 500 Response")
}
}

Expand All @@ -80,7 +90,10 @@ impl Service<Request<Body>> for MetricService {
let req_method = req.method();
let resp = if (req_method == Method::GET) && (req_path == "/metrics") {
// Encode and serve metrics from registry.
self.respond_with_metrics()
match self.respond_with_metrics() {
Ok(resp) => resp,
Err(_) => self.respond_with_500_server_error(),
}
} else {
self.respond_with_404_not_found()
};
Expand Down

0 comments on commit d772972

Please sign in to comment.