1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//! # Example coding
//! ```
//! use prometheus::{IntCounter, Opts, Registry};
//! use prometheus_hyper::{RegistryFn, Server};
//! use std::{error::Error, net::SocketAddr, sync::Arc, time::Duration};
//! use tokio::sync::Notify;
//!
//! pub struct CustomMetrics {
//!     pub foo: IntCounter,
//! }
//!
//! impl CustomMetrics {
//!     pub fn new() -> Result<(Self, RegistryFn), Box<dyn Error>> {
//!         let foo = IntCounter::with_opts(Opts::new("foo", "description"))?;
//!         let foo_clone = foo.clone();
//!         let f = |r: &Registry| r.register(Box::new(foo_clone));
//!         Ok((Self { foo }, Box::new(f)))
//!     }
//! }
//!
//! #[tokio::main(flavor = "current_thread")]
//! async fn main() -> std::result::Result<(), std::io::Error> {
//!     let registry = Arc::new(Registry::new());
//!     let shutdown = Arc::new(Notify::new());
//!     let shutdown_clone = Arc::clone(&shutdown);
//!     let (metrics, f) = CustomMetrics::new().expect("failed prometheus");
//!     f(&registry).expect("problem registering");
//!
//!     // Startup Server
//!     let jh = tokio::spawn(async move {
//!         Server::run(
//!             Arc::clone(&registry),
//!             SocketAddr::from(([0; 4], 8080)),
//!             shutdown_clone.notified(),
//!         )
//!         .await
//!     });
//!
//!     // Change Metrics
//!     metrics.foo.inc();
//!
//!     // Shutdown
//!     tokio::time::sleep(Duration::from_secs(5)).await;
//!     shutdown.notify_one();
//!     jh.await.unwrap()
//! }
//! ```
use bytes::Bytes;
use http_body_util::Full;
use hyper::{header, service::Service, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use prometheus::{Encoder, Registry, TextEncoder};
use std::{convert::Infallible, future::Future, net::SocketAddr, ops::Deref, pin::Pin};
use tokio::net::TcpListener;
use tracing::{info, trace};

#[cfg(feature = "internal_metrics")]
use prometheus::{
    register_histogram_with_registry, register_int_counter_with_registry, register_int_gauge_with_registry, Histogram,
    IntCounter, IntGauge,
};

#[cfg(feature = "internal_metrics")]
use std::convert::TryInto;

/// Helper fn to register metrics
pub type RegistryFn = Box<dyn FnOnce(&Registry) -> Result<(), prometheus::Error>>;

/// Metrics Server based on [`tokio`] and [`hyper`]
///
/// [`tokio`]: tokio
/// [`hyper`]: hyper
pub struct Server {}

impl Server {
    /// Create and run the metrics Server
    ///
    /// # Arguments
    /// * `registry` - provide the [`Registry`] you are also registering your
    ///   metric types to.
    /// * `addr` - `host:ip` to tcp listen on.
    /// * `shutdown` - a [`Future`], once this completes the server will start
    ///   to shut down. You can use a [`signal`] or [`Notify`] for clean
    ///   shutdown or [`pending`] to newer shutdown.
    /// # Result
    /// * [`std::io::Error`] is thrown when listening on addr fails. All other
    ///   causes are handled internally, logged and ignored
    ///
    /// # Examples
    /// ```
    /// use prometheus::Registry;
    /// use prometheus_hyper::Server;
    /// use std::{net::SocketAddr, sync::Arc};
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() {
    ///
    /// let registry = Arc::new(Registry::new());
    ///
    /// // Start Server endlessly
    /// tokio::spawn(async move {
    ///     Server::run(
    ///         Arc::clone(&registry),
    ///         SocketAddr::from(([0; 4], 8080)),
    ///         futures_util::future::pending(),
    ///     )
    ///     .await
    /// });
    /// # }
    /// ```
    /// [`Registry`]: prometheus::Registry
    /// [`Future`]: std::future::Future
    /// [`pending`]: https://docs.rs/futures-util/latest/futures_util/future/fn.pending.html
    /// [`hyper::Error`]: hyper::Error
    /// [`signal`]: tokio::signal
    /// [`Notify`]: tokio::sync::Notify
    /// [`tokio`]: tokio
    /// [`hyper`]: hyper
    pub async fn run<S, F, R>(registry: R, addr: S, shutdown: F) -> Result<(), std::io::Error>
    where
        S: Into<SocketAddr>,
        F: Future<Output = ()>,
        R: Deref<Target = Registry> + Clone + Send + 'static,
    {
        let addr = addr.into();

        #[cfg(feature = "internal_metrics")]
        let durations = register_histogram_with_registry!(
            "prometheus_exporter_request_duration_seconds",
            "HTTP request durations in seconds",
            registry
        )
        .unwrap();
        #[cfg(feature = "internal_metrics")]
        let requests = register_int_counter_with_registry!(
            "prometheus_exporter_requests_total",
            "HTTP requests received in metrics endpoint",
            registry
        )
        .unwrap();
        #[cfg(feature = "internal_metrics")]
        let sizes = register_int_gauge_with_registry!(
            "prometheus_exporter_response_size_bytes",
            "HTTP response sizes in bytes",
            registry
        )
        .unwrap();

        info!("starting hyper server to serve metrics");

        let service = MetricsService {
            registry: registry.clone(),
            #[cfg(feature = "internal_metrics")]
            durations: durations.clone(),
            #[cfg(feature = "internal_metrics")]
            requests: requests.clone(),
            #[cfg(feature = "internal_metrics")]
            sizes: sizes.clone(),
        };

        let listener = TcpListener::bind(addr).await?;
        let mut shutdown = core::pin::pin!(shutdown);
        while let Some(conn) = tokio::select! {
            _ = shutdown.as_mut() => None,
            conn = listener.accept() => Some(conn),
        } {
            match conn {
                Ok((tcp, _)) => {
                    let io = TokioIo::new(tcp);
                    let service_clone = service.clone();

                    tokio::task::spawn(async move {
                        use hyper::server::conn::http1;
                        let conn = http1::Builder::new().serve_connection(io, service_clone);

                        if let Err(e) = conn.await {
                            tracing::error!(?e, "error serving connection")
                        }
                    });
                },
                Err(e) => tracing::error!(?e, "error accepting new connection"),
            }
        }

        #[cfg(feature = "internal_metrics")]
        {
            if let Err(e) = registry.unregister(Box::new(durations)) {
                tracing::error!(?e, "could not unregister 'durations'");
            };
            if let Err(e) = registry.unregister(Box::new(requests)) {
                tracing::error!(?e, "could not unregister 'requests'");
            };
            if let Err(e) = registry.unregister(Box::new(sizes)) {
                tracing::error!(?e, "could not unregister 'sizes'");
            };
        }

        Ok(())
    }
}

#[cfg(feature = "internal_metrics")]
#[derive(Debug, Clone)]
struct MetricsService<R> {
    registry:  R,
    durations: Histogram,
    requests:  IntCounter,
    sizes:     IntGauge,
}

#[cfg(not(feature = "internal_metrics"))]
#[derive(Debug, Clone)]
struct MetricsService<R> {
    registry: R,
}

impl<R> Service<Request<hyper::body::Incoming>> for MetricsService<R>
where
    R: Deref<Target = Registry> + Clone + Send + 'static,
{
    type Error = Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
    type Response = Response<Full<Bytes>>;

    fn call(&self, req: Request<hyper::body::Incoming>) -> Self::Future {
        #[cfg(feature = "internal_metrics")]
        let timer = self.durations.start_timer();

        let (code, body) = if req.uri().path() == "/metrics" {
            #[cfg(feature = "internal_metrics")]
            self.requests.inc();

            trace!("request");

            let mf = self.registry.deref().gather();
            let mut buffer = vec![];

            let encoder = TextEncoder::new();
            encoder.encode(&mf, &mut buffer).expect("write to vec cannot fail");

            #[cfg(feature = "internal_metrics")]
            if let Ok(size) = buffer.len().try_into() {
                self.sizes.set(size);
            }

            (StatusCode::OK, Full::new(Bytes::from(buffer)))
        } else {
            trace!("wrong uri, return 404");
            (StatusCode::NOT_FOUND, Full::new(Bytes::from("404 not found")))
        };

        let response = Response::builder()
            .status(code)
            .header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
            .body(body)
            .unwrap();

        #[cfg(feature = "internal_metrics")]
        timer.observe_duration();

        Box::pin(async { Ok::<Response<http_body_util::Full<bytes::Bytes>>, Infallible>(response) })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use http_body_util::Empty;
    use hyper::Request;
    use std::{sync::Arc, time::Duration};
    use tokio::{net::TcpStream, sync::Notify};

    #[tokio::test]
    async fn test_create() {
        let shutdown = Arc::new(Notify::new());
        let registry = Arc::new(Registry::new());

        let shutdown_clone = Arc::clone(&shutdown);

        let r = tokio::spawn(async move {
            Server::run(
                Arc::clone(&registry),
                SocketAddr::from(([0; 4], 6001)),
                shutdown_clone.notified(),
            )
            .await
        });

        shutdown.notify_one();
        r.await.expect("tokio error").expect("prometheus_hyper server error");
    }

    #[tokio::test]
    async fn test_default() {
        let shutdown = Arc::new(Notify::new());
        let registry = prometheus::default_registry();

        let shutdown_clone = Arc::clone(&shutdown);

        let r = tokio::spawn(async move {
            Server::run(registry, SocketAddr::from(([0; 4], 6002)), shutdown_clone.notified()).await
        });

        shutdown.notify_one();
        r.await.expect("tokio error").expect("prometheus_hyper server error");
    }

    #[tokio::test]
    async fn test_sample() {
        let shutdown = Arc::new(Notify::new());
        let registry = Arc::new(Registry::new());

        let shutdown_clone = Arc::clone(&shutdown);

        let r = tokio::spawn(async move {
            Server::run(
                Arc::clone(&registry),
                SocketAddr::from(([0; 4], 6003)),
                shutdown_clone.notified(),
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(500)).await;

        let stream = TcpStream::connect(SocketAddr::from(([0; 4], 6003))).await.unwrap();
        let io = TokioIo::new(stream);
        let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await.unwrap();
        tokio::task::spawn(async move {
            if let Err(err) = conn.await {
                println!("Connection failed: {:?}", err);
            }
        });

        let req = Request::builder()
            .method("GET")
            .uri("http://localhost:6003/metrics")
            .body(Empty::<Bytes>::new())
            .expect("request builder");

        let res = sender.send_request(req).await.expect("couldn't reach server");

        assert_eq!(res.status(), StatusCode::OK);

        shutdown.notify_one();
        r.await.expect("tokio error").expect("prometheus_hyper server error");
    }

    #[tokio::test]
    async fn test_wrong_endpoint_sample() {
        let shutdown = Arc::new(Notify::new());
        let registry = Arc::new(Registry::new());

        let shutdown_clone = Arc::clone(&shutdown);

        let r = tokio::spawn(async move {
            Server::run(
                Arc::clone(&registry),
                SocketAddr::from(([0; 4], 6004)),
                shutdown_clone.notified(),
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(500)).await;

        let stream = TcpStream::connect(SocketAddr::from(([0; 4], 6004))).await.unwrap();
        let io = TokioIo::new(stream);
        let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await.unwrap();
        tokio::task::spawn(async move {
            if let Err(err) = conn.await {
                println!("Connection failed: {:?}", err);
            }
        });

        let req = Request::builder()
            .method("GET")
            .uri("http://localhost:6004/foobar")
            .body(Empty::<Bytes>::new())
            .expect("request builder");

        let res = sender.send_request(req).await.expect("couldn't reach server");
        assert_eq!(res.status(), StatusCode::NOT_FOUND);

        shutdown.notify_one();
        r.await.expect("tokio error").expect("prometheus_hyper server error");
    }
}