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
#![deny(missing_docs)]
extern crate chrono;
extern crate hyper;
extern crate hyper_native_tls;
#[macro_use]
extern crate log;
extern crate rustc_serialize;
extern crate toml;
use chrono::Timelike;
use hyper::{Client, Url};
use hyper::header::{Headers, Authorization, Basic, ContentType};
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use rustc_serialize::Decodable;
use rustc_serialize::json;
use rustc_serialize::json::EncoderError;
use std::collections::HashMap;
use std::convert::From;
use std::fs::File;
use std::io::Read;
use std::path::Path;
pub type EmitterResult = Result<(), EmitterError>;
#[derive(Debug)]
pub enum EmitterError {
JsonParseError(EncoderError),
EmitError(String),
ReceiveError(String),
}
impl From<std::io::Error> for EmitterError {
fn from(err: std::io::Error) -> EmitterError {
EmitterError::EmitError(format!("{}", err))
}
}
impl From<EncoderError> for EmitterError {
fn from(err: EncoderError) -> EmitterError {
EmitterError::JsonParseError(err)
}
}
#[derive(Debug)]
pub struct BosunClient {
pub host: String,
}
impl BosunClient {
pub fn new(host: &str) -> BosunClient {
BosunClient { host: host.to_string() }
}
pub fn emit_metadata(&self, metadata: &Metadata) -> EmitterResult {
let encoded = try!(metadata.to_json());
let res = BosunClient::send_to_bosun_api(&self.host, "/api/metadata/put", &encoded);
info!("Sent medata '{:?}' to '{:?}' with result: '{:?}'.",
encoded,
self.host,
res);
res
}
pub fn emit_datum(&self, datum: &Datum) -> EmitterResult {
let encoded = try!(datum.to_json());
let res = BosunClient::send_to_bosun_api(&self.host, "/api/put", &encoded);
info!("Sent datum '{:?}' to '{:?}' with result: '{:?}'.",
encoded,
&self.host,
res);
res
}
fn send_to_bosun_api(host: &str, path: &str, json: &str) -> EmitterResult {
let uri = if host.starts_with("http") {
format!("{}{}", host, path)
} else {
format!("http://{}{}", host, path)
};
let url = Url::parse(&uri).unwrap();
let client = if url.scheme() == "https" {
let ssl = NativeTlsClient::new().unwrap();
let connector = HttpsConnector::new(ssl);
Client::with_connector(connector)
} else {
Client::new()
};
let mut headers = Headers::new();
headers.set(
ContentType(
Mime(
TopLevel::Application,
SubLevel::Json,
vec![(Attr::Charset, Value::Utf8)]
)
)
);
if url.has_authority() && url.password().is_some() {
let password = match url.password() {
Some(p) => Some(p.to_owned()),
None => None
};
headers.set(
Authorization(
Basic {
username: url.username().to_owned(),
password: password
}
)
);
}
let res = client.post(&uri)
.headers(headers)
.body(json)
.send();
match res {
Ok(ref response) if response.status == hyper::status::StatusCode::NoContent => Ok(()),
Ok(response) => Err(EmitterError::ReceiveError(format!("{}", response.status))),
Err(err) => Err(EmitterError::EmitError(format!("{}", err))),
}
}
}
#[derive(RustcEncodable, Debug)]
pub struct Metadata<'a> {
pub metric: &'a str,
pub rate: &'a str,
pub unit: &'a str,
pub description: &'a str,
}
impl<'a> Metadata<'a> {
pub fn new(metric: &'a str,
rate: &'a str,
unit: &'a str,
description: &'a str)
-> Metadata<'a> {
Metadata {
metric: metric,
rate: rate,
unit: unit,
description: description,
}
}
pub fn to_json(&self) -> Result<String, EmitterError> {
let mut metadata = [HashMap::new(), HashMap::new(), HashMap::new()];
metadata[0].insert("metric", self.metric);
metadata[0].insert("name", "unit");
metadata[0].insert("value", self.unit);
metadata[1].insert("metric", self.metric);
metadata[1].insert("name", "rate");
metadata[1].insert("value", self.rate);
metadata[2].insert("metric", self.metric);
metadata[2].insert("name", "desc");
metadata[2].insert("value", self.description);
let json = try!(json::encode(&metadata));
debug!("Metadata::to_json '{:?}', '{:?}'", &self, json);
Ok(json)
}
}
pub type Tags = HashMap<String, String>;
#[derive(RustcEncodable, Debug)]
pub struct Datum<'a> {
pub metric: &'a str,
pub timestamp: i64,
pub value: &'a str,
pub tags: &'a Tags,
}
impl<'a> Datum<'a> {
pub fn new(metric: &'a str,
timestamp: i64,
value: &'a str,
tags: &'a Tags)
-> Datum<'a> {
Datum {
metric: metric,
timestamp: timestamp,
value: value,
tags: tags,
}
}
pub fn now(metric: &'a str,
value: &'a str,
tags: &'a Tags)
-> Datum<'a> {
Datum {
metric: metric,
timestamp: now_in_ms(),
value: value,
tags: tags,
}
}
pub fn to_json(&self) -> Result<String, EmitterError> {
let json = try!(json::encode(self));
debug!("Datum::to_json '{:?}', '{:?}'", &self, json);
Ok(json)
}
}
pub fn now_in_ms() -> i64 {
let now = chrono::Local::now();
now.timestamp() * 1000 + (now.nanosecond() / 1_000_000) as i64
}
#[derive(Debug)]
#[derive(RustcDecodable)]
#[allow(non_snake_case)]
pub struct BosunConfig {
pub Host: String,
pub Hostname: String,
pub Tags: Tags,
}
impl BosunConfig {
pub fn default() -> BosunConfig {
BosunConfig {
Host: "localhost:8070".to_string(),
Hostname: "localhost".to_string(),
Tags: Tags::new(),
}
}
pub fn load_from_scollector_config(file_path: &Path) -> Result<BosunConfig, Box<std::error::Error>> {
match BosunConfig::load_toml(file_path) {
Ok(toml) => {
let mut decoder = toml::Decoder::new(toml);
let config = try!(BosunConfig::decode(&mut decoder));
Ok(config)
}
Err(err) => Err(err),
}
}
fn load_toml(file_path: &Path) -> Result<toml::Value, Box<std::error::Error>> {
let mut config_file = try!(File::open(file_path));
let mut config_content = String::new();
try!(config_file.read_to_string(&mut config_content));
let mut parser = toml::Parser::new(&config_content);
match parser.parse() {
Some(toml) => Ok(toml::Value::Table(toml)),
None => Err(From::from(parser.errors.pop().unwrap())),
}
}
}