libp2prs_exporter/lib.rs
1// Copyright 2020 Netwarps Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21pub(crate) mod exporter;
22
23use prometheus::{register, Encoder, TextEncoder};
24use tide::{Body, Request, Response, Server};
25
26use crate::exporter::Exporter;
27use libp2prs_runtime::task;
28use libp2prs_swarm::Control;
29
30/// Exporter server
31pub struct ExporterServer {
32 s: Server<()>,
33}
34
35impl ExporterServer {
36 pub fn new(control: Control) -> Self {
37 let mut s = tide::new();
38
39 // Register exporter to global registry, and then we can use default gather method.
40 let exporter = Exporter::new(control);
41 let _ = register(Box::new(exporter));
42 s.at("/metrics").get(get_metric);
43 ExporterServer { s }
44 }
45
46 pub fn start(self, addr: String) {
47 task::spawn(async move {
48 let r = self.s.listen(addr).await;
49 log::info!("Exporter server started result={:?}", r);
50 });
51 }
52}
53
54/// Return metrics to prometheus
55async fn get_metric(_: Request<()>) -> tide::Result {
56 let encoder = TextEncoder::new();
57 let metric_families = prometheus::gather();
58 let mut buffer = vec![];
59
60 encoder.encode(&metric_families, &mut buffer).unwrap();
61
62 let response = Response::builder(200)
63 .content_type("text/plain; version=0.0.4")
64 .body(Body::from(buffer))
65 .build();
66
67 Ok(response)
68}