servers/metrics_handler.rs
1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(target_os = "linux")]
16use common_stat::CgroupsMetricsCollector;
17use prometheus::{Encoder, TextEncoder};
18
19/// a server that serves metrics
20/// only start when datanode starts in distributed mode
21#[derive(Copy, Clone)]
22pub struct MetricsHandler;
23
24impl MetricsHandler {
25 pub fn render(&self) -> String {
26 let mut buffer = Vec::new();
27 let encoder = TextEncoder::new();
28
29 #[cfg(target_os = "linux")]
30 {
31 static ONCE: std::sync::Once = std::sync::Once::new();
32 ONCE.call_once(|| {
33 // It's unlikely to fail to register the collector.
34 prometheus::register(Box::new(CgroupsMetricsCollector::default())).unwrap();
35 });
36 }
37
38 // Gather the metrics.
39 let metric_families = prometheus::gather();
40 // Encode them to send.
41 match encoder.encode(&metric_families, &mut buffer) {
42 Ok(_) => match String::from_utf8(buffer) {
43 Ok(s) => s,
44 Err(e) => e.to_string(),
45 },
46 Err(e) => e.to_string(),
47 }
48 }
49}