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
use crossbeam_channel::{Receiver, Sender};
use lazy_static::*;
use log::*;
use mio::*;
use std::collections::BTreeMap;
use std::fmt;
use std::io::prelude::*;
use std::net::{Ipv4Addr, SocketAddr};
use std::time::Duration;
lazy_static! {
static ref CHAN: (Sender<(Metric, Action)>, Receiver<(Metric, Action)>) = {
std::thread::spawn(|| if let Err(e) = run_http_server() {
warn!("HTTP thread failed to start: {}", e);
});
crossbeam_channel::unbounded()
};
}
pub struct Metric {
pub name: &'static str,
pub labels: Labels,
}
type Labels = Vec<(&'static str, Box<dyn fmt::Display + Send>)>;
enum Action {
Inc(f64),
Set(f64),
}
impl Metric {
#[inline]
pub fn set(self, x: f64) {
let _ = CHAN.0.send((self, Action::Set(x)));
}
#[inline]
pub fn add(self, x: f64) {
let _ = CHAN.0.send((self, Action::Inc(x)));
}
}
#[macro_export]
macro_rules! metric{
($name:ident) => {
epimetheus::Metric {
name: stringify!($name),
labels: Vec::new(),
}
};
($name:ident{$($key:ident = $val:expr),*}) => {
epimetheus::Metric {
name: stringify!($name),
labels: vec![$((stringify!($key), Box::new($val))),*],
}
};
}
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct LabelsDisplay(BTreeMap<&'static str, String>);
impl LabelsDisplay {
fn new(labels: Labels) -> LabelsDisplay {
let labels = labels
.into_iter()
.map(|(k, v)| (k, v.to_string()))
.collect::<BTreeMap<_, _>>();
LabelsDisplay(labels)
}
}
impl fmt::Display for LabelsDisplay {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut labels = self.0.iter();
if let Some(head) = labels.next() {
f.write_str("{")?;
f.write_str(head.0)?;
f.write_str("=")?;
fmt::Debug::fmt(head.1, f)?;
for (k, v) in labels {
f.write_str(",")?;
f.write_str(k)?;
f.write_str("=")?;
fmt::Debug::fmt(v, f)?;
}
f.write_str("}")?;
}
Ok(())
}
}
fn run_http_server() -> Result<(), std::io::Error> {
let mut metrics = BTreeMap::<(&'static str, LabelsDisplay), f64>::default();
let port = std::env::var("RUST_METRICS_PORT")
.ok()
.and_then(|x| x.parse::<u16>().ok())
.unwrap_or(9898);
let sock = net::TcpListener::bind(&SocketAddr::from((Ipv4Addr::LOCALHOST, port)))?;
let poll = Poll::new()?;
poll.register(&sock, Token(0), Ready::readable(), PollOpt::edge())?;
info!("Started HTTP thread");
let mut events = Events::with_capacity(64);
let mut buf = [0; 1024];
loop {
poll.poll(&mut events, Some(Duration::from_secs(20)))?;
events.clear();
for (metric, action) in CHAN.1.try_iter() {
let labels = LabelsDisplay::new(metric.labels);
match action {
Action::Inc(x) => *metrics.entry((metric.name, labels)).or_insert(0.0) += x,
Action::Set(x) => *metrics.entry((metric.name, labels)).or_insert(0.0) = x,
}
}
while let Ok((mut conn, _)) = sock.accept_std() {
let _ = conn.read(&mut buf).unwrap();
writeln!(conn, "HTTP/1.1 200 OK\r\n").unwrap();
for ((name, labels), val) in &metrics {
writeln!(conn, "{}{} {}", name, labels, val).unwrap();
}
}
}
}