-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.rs
423 lines (373 loc) · 12.6 KB
/
main.rs
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*
* jail_exporter
* -------------
*
* An exporter for Prometheus, exporting jail metrics as reported by rctl(8).
*
*/
extern crate env_logger;
extern crate hyper;
extern crate libc;
#[macro_use] extern crate clap;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate log;
#[macro_use] extern crate prometheus;
extern crate jail;
mod rctl;
use hyper::{
Body,
Method,
Request,
Response,
Server,
StatusCode,
};
use hyper::header::CONTENT_TYPE;
use hyper::rt::Future;
use hyper::service::service_fn_ok;
use jail::RunningJail;
use prometheus::{
Encoder,
IntCounterVec,
IntGauge,
IntGaugeVec,
TextEncoder,
};
use std::net::SocketAddr;
use std::process::exit;
use std::str::FromStr;
// Descriptions of these metrics are taken from rctl(8) where possible.
lazy_static!{
// build info metric
static ref JAIL_EXPORTER_BUILD_INFO: IntGaugeVec = register_int_gauge_vec!(
"jail_exporter_build_info",
"A metric with a constant '1' value labelled by version \
from which jail_exporter was built",
&["version"]
).unwrap();
// Bytes metrics
static ref JAIL_COREDUMPSIZE_BYTES: IntGaugeVec = register_int_gauge_vec!(
"jail_coredumpsize_bytes",
"core dump size, in bytes",
&["name"]
).unwrap();
static ref JAIL_DATASIZE_BYTES: IntGaugeVec = register_int_gauge_vec!(
"jail_datasize_bytes",
"data size, in bytes",
&["name"]
).unwrap();
static ref JAIL_MEMORYLOCKED_BYTES: IntGaugeVec = register_int_gauge_vec!(
"jail_memorylocked_bytes",
"locked memory, in bytes",
&["name"]
).unwrap();
static ref JAIL_MEMORYUSE_BYTES: IntGaugeVec = register_int_gauge_vec!(
"jail_memoryuse_bytes",
"resident set size, in bytes",
&["name"]
).unwrap();
static ref JAIL_MSGQSIZE_BYTES: IntGaugeVec = register_int_gauge_vec!(
"jail_msgqsize_bytes",
"SysV message queue size, in bytes",
&["name"]
).unwrap();
static ref JAIL_SHMSIZE_BYTES: IntGaugeVec = register_int_gauge_vec!(
"jail_shmsize_bytes",
"SysV shared memory size, in bytes",
&["name"]
).unwrap();
static ref JAIL_STACKSIZE_BYTES: IntGaugeVec = register_int_gauge_vec!(
"jail_stacksize_bytes",
"stack size, in bytes",
&["name"]
).unwrap();
static ref JAIL_SWAPUSE_BYTES: IntGaugeVec = register_int_gauge_vec!(
"jail_swapuse_bytes",
"swap space that may be reserved or used, in bytes",
&["name"]
).unwrap();
static ref JAIL_VMEMORYUSE_BYTES: IntGaugeVec = register_int_gauge_vec!(
"jail_vmemoryuse_bytes",
"address space limit, in bytes",
&["name"]
).unwrap();
// Percent metrics
static ref JAIL_PCPU_USED: IntCounterVec = register_int_counter_vec!(
"jail_pcpu_used",
"%CPU, in percents of a single CPU core",
&["name"]
).unwrap();
// Random numberical values without a specific unit.
static ref JAIL_MAXPROC: IntGaugeVec = register_int_gauge_vec!(
"jail_maxproc",
"number of processes",
&["name"]
).unwrap();
static ref JAIL_MSGQQUEUED: IntGaugeVec = register_int_gauge_vec!(
"jail_msgqqueued",
"number of queued SysV messages",
&["name"]
).unwrap();
static ref JAIL_NMSGQ: IntGaugeVec = register_int_gauge_vec!(
"jail_nmsgq",
"number of SysV message queues",
&["name"]
).unwrap();
static ref JAIL_NSEM: IntGaugeVec = register_int_gauge_vec!(
"jail_nsem",
"number of SysV semaphores",
&["name"]
).unwrap();
static ref JAIL_NSEMOP: IntGaugeVec = register_int_gauge_vec!(
"jail_nsemop",
"number of SysV semaphores modified in a single semop(2) call",
&["name"]
).unwrap();
static ref JAIL_NSHM: IntGaugeVec = register_int_gauge_vec!(
"jail_nshm",
"number of SysV shared memory segments",
&["name"]
).unwrap();
static ref JAIL_NTHR: IntGaugeVec = register_int_gauge_vec!(
"jail_nthr",
"number of threads",
&["name"]
).unwrap();
static ref JAIL_OPENFILES: IntGaugeVec = register_int_gauge_vec!(
"jail_openfiles",
"file descriptor table size",
&["name"]
).unwrap();
static ref JAIL_PSEUDOTERMINALS: IntGaugeVec = register_int_gauge_vec!(
"jail_pseudoterminals",
"number of PTYs",
&["name"]
).unwrap();
// Seconds metrics
static ref JAIL_CPUTIME_SECONDS: IntCounterVec = register_int_counter_vec!(
"jail_cputime_seconds_total",
"CPU time, in seconds",
&["name"]
).unwrap();
static ref JAIL_WALLCLOCK_SECONDS: IntCounterVec = register_int_counter_vec!(
"jail_wallclock_seconds_total",
"wallclock time, in seconds",
&["name"]
).unwrap();
// Metrics created by the exporter
static ref JAIL_ID: IntGaugeVec = register_int_gauge_vec!(
"jail_id",
"ID of the named jail.",
&["name"]
).unwrap();
static ref JAIL_TOTAL: IntGauge = register_int_gauge!(
"jail_num",
"Current number of running jails."
).unwrap();
}
// Processes the MetricsHash setting the appripriate time series.
fn process_metrics_hash(name: &str, metrics: &rctl::MetricsHash) {
debug!("process_metrics_hash");
for (key, value) in metrics {
match key.as_ref() {
"coredumpsize" => {
JAIL_COREDUMPSIZE_BYTES.with_label_values(&[&name]).set(*value);
},
"cputime" => {
let series = JAIL_CPUTIME_SECONDS.with_label_values(&[&name]);
let inc = *value - series.get();
series.inc_by(inc);
},
"datasize" => {
JAIL_DATASIZE_BYTES.with_label_values(&[&name]).set(*value);
},
"maxproc" => {
JAIL_MAXPROC.with_label_values(&[&name]).set(*value);
},
"memorylocked" => {
JAIL_MEMORYLOCKED_BYTES.with_label_values(&[&name]).set(*value);
},
"memoryuse" => {
JAIL_MEMORYUSE_BYTES.with_label_values(&[&name]).set(*value);
},
"msgqqueued" => {
JAIL_MSGQQUEUED.with_label_values(&[&name]).set(*value);
},
"msgqsize" => {
JAIL_MSGQSIZE_BYTES.with_label_values(&[&name]).set(*value);
},
"nmsgq" => {
JAIL_NMSGQ.with_label_values(&[&name]).set(*value);
},
"nsem" => {
JAIL_NSEM.with_label_values(&[&name]).set(*value);
},
"nsemop" => {
JAIL_NSEMOP.with_label_values(&[&name]).set(*value);
},
"nshm" => {
JAIL_NSHM.with_label_values(&[&name]).set(*value);
},
"nthr" => {
JAIL_NTHR.with_label_values(&[&name]).set(*value);
},
"openfiles" => {
JAIL_OPENFILES.with_label_values(&[&name]).set(*value);
},
"pcpu" => {
JAIL_PCPU_USED.with_label_values(&[&name]).inc_by(*value);
},
"pseudoterminals" => {
JAIL_PSEUDOTERMINALS.with_label_values(&[&name]).set(*value);
},
"shmsize" => {
JAIL_SHMSIZE_BYTES.with_label_values(&[&name]).set(*value);
},
"stacksize" => {
JAIL_STACKSIZE_BYTES.with_label_values(&[&name]).set(*value);
},
"swapuse" => {
JAIL_SWAPUSE_BYTES.with_label_values(&[&name]).set(*value);
},
"vmemoryuse" => {
JAIL_VMEMORYUSE_BYTES.with_label_values(&[&name]).set(*value);
},
"wallclock" => {
let series = JAIL_WALLCLOCK_SECONDS.with_label_values(&[&name]);
let inc = *value - series.get();
series.inc_by(inc);
},
// jid isn't actually reported by rctl, but we add it into this
// hash to keep things simpler.
"jid" => {
JAIL_ID.with_label_values(&[&name]).set(*value);
},
// Intentionally unhandled metrics.
// These are documented being difficult to observe via rctl(8).
"readbps" | "writebps" | "readiops" | "writeiops" => {},
_ => println!("Unrecognised metric: {}", key),
}
}
}
fn get_jail_metrics() {
debug!("get_jail_metrics");
// Set JAIL_TOTAL to zero before gathering.
JAIL_TOTAL.set(0);
// Loop over jails.
for jail in RunningJail::all() {
let name = jail.name()
.expect("Could not get jail name");
debug!("JID: {}, Name: {:?}", jail.jid, name);
let rusage = match rctl::get_resource_usage(jail.jid, &name) {
Ok(res) => res,
Err(err) => {
err.to_string();
break;
},
};
// Get a hash of resources based on rusage string.
process_metrics_hash(&name, &rusage);
JAIL_TOTAL.set(JAIL_TOTAL.get() + 1);
}
}
fn metrics(_req: Request<Body>) -> Response<Body> {
debug!("Processing metrics request");
get_jail_metrics();
let encoder = TextEncoder::new();
let metric_families = prometheus::gather();
let mut buffer = vec![];
encoder.encode(&metric_families, &mut buffer).unwrap();
Response::builder()
.status(StatusCode::OK)
.header(CONTENT_TYPE, "text/plain")
.body(Body::from(buffer))
.unwrap()
}
// HTTP request router
fn http_router(req: Request<Body>) -> Response<Body> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/metrics") => {
metrics(req)
},
_ => {
debug!("No handler for request found");
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap()
},
}
}
// Used as a validator for the argument parsing.
fn is_ipaddress(s: String) -> Result<(), String> {
let res = SocketAddr::from_str(&s);
match res {
Ok(_) => Ok(()),
Err(_) => Err(format!("'{}' is not a valid ADDR:PORT string", s)),
}
}
fn main() {
env_logger::init();
// First, check if RACCT/RCTL is available.
debug!("Checking RACCT/RCTL status");
let racct_rctl_available = match rctl::is_enabled() {
rctl::State::Disabled => {
eprintln!("RACCT/RCTL present, but disabled; enable using \
kern.racct.enable=1 tunable");
false
},
rctl::State::Enabled => {
true
},
rctl::State::NotPresent => {
eprintln!("RACCT/RCTL support not present in kernel; see rctl(8) \
for details");
false
},
rctl::State::UnknownError(s) => {
eprintln!("Unknown error while checking RACCT/RCTL state: {}", s);
false
},
};
// If it's not available, exit.
if !racct_rctl_available {
exit(1);
}
debug!("Parsing command line arguments");
let matches = clap::App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.arg(clap::Arg::with_name("WEB_LISTEN_ADDRESS")
.long("web.listen-address")
.value_name("[ADDR:PORT]")
.help("Address on which to expose metrics and web interface.")
.takes_value(true)
.default_value("127.0.0.1:9452")
.validator(is_ipaddress))
.arg(clap::Arg::with_name("WEB_TELEMETRY_PATH")
.long("web.telemetry-path")
.value_name("PATH")
.help("Path under which to expose metrics.")
.takes_value(true)
.default_value("/metrics"))
.get_matches();
// This should always be fine, we've already validated it during arg
// parsing.
// However, we keep the expect as a last resort.
let addr: SocketAddr = matches.value_of("WEB_LISTEN_ADDRESS").unwrap()
.parse().expect("unable to parse socket address");
let router = || {
service_fn_ok(http_router)
};
// Set build_info metric.
let build_info_labels = [
crate_version!(),
];
JAIL_EXPORTER_BUILD_INFO.with_label_values(&build_info_labels).set(1);
info!("Starting HTTP server on {}", addr);
let server = Server::bind(&addr)
.serve(router)
.map_err(|e| eprintln!("server error: {}", e));
hyper::rt::run(server);
}