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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
extern crate backtrace;
extern crate chrono;
#[macro_use]
extern crate hyper;
extern crate hyper_native_tls;
#[macro_use]
extern crate log;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use chrono::offset::utc::UTC;
use hyper::Client;
use hyper::header::{ Headers, ContentType };
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::collections::BTreeMap;
use std::env;
use std::fmt::Debug;
use std::fs::File;
use std::io::Read;
use std::io::BufReader;
use std::io::BufRead;
use std::sync::mpsc::{ channel, Receiver, Sender, SendError };
use std::sync::{ Arc, Mutex};
use std::sync::atomic::{ AtomicBool, Ordering };
use std::time::Duration;
use std::thread;
struct ThreadState<'a> {
alive: &'a mut Arc<AtomicBool>,
}
impl<'a> ThreadState<'a> {
fn set_alive(&self) {
self.alive.store(true, Ordering::Relaxed);
}
}
impl <'a> Drop for ThreadState<'a> {
fn drop(&mut self) {
self.alive.store(false, Ordering::Relaxed);
}
}
pub trait WorkerClosure<T, P>: Fn(&P, T) -> () + Send + Sync {}
impl <T, F, P> WorkerClosure<T, P> for F where F: Fn(&P, T) -> () + Send + Sync {}
pub struct SingleWorker<T: 'static + Send, P: Clone + Send> {
parameters: P,
f: Arc<Box<WorkerClosure<T, P, Output = ()>>>,
receiver: Arc<Mutex<Receiver<T>>>,
sender: Mutex<Sender<T>>,
alive: Arc<AtomicBool>,
}
impl <T: 'static + Debug + Send, P: 'static + Clone + Send> SingleWorker<T, P> {
pub fn new(parameters: P, f: Box<WorkerClosure<T, P, Output = ()>>) -> SingleWorker<T, P> {
let (sender, reciever) = channel::<T>();
let worker = SingleWorker {
parameters: parameters,
f: Arc::new(f),
receiver: Arc::new(Mutex::new(reciever)),
sender: Mutex::new(sender),
alive: Arc::new(AtomicBool::new(true)),
};
SingleWorker::spawn_thread(&worker);
worker
}
fn is_alive(&self) -> bool {
self.alive.clone().load(Ordering::Relaxed)
}
fn spawn_thread(worker: &SingleWorker<T, P>) {
let mut alive = worker.alive.clone();
let f = worker.f.clone();
let receiver = worker.receiver.clone();
let parameters = worker.parameters.clone();
thread::spawn(move || {
let state = ThreadState {
alive: &mut alive
};
state.set_alive();
let lock = match receiver.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
loop {
match lock.recv() {
Ok(value) => f(¶meters, value),
Err(_) => {
thread::yield_now();
}
};
}
});
while !worker.is_alive() {
thread::yield_now();
}
}
pub fn work_with(&self, msg: T) -> Result<(), SendError<T>> {
let alive = self.is_alive();
if !alive {
SingleWorker::spawn_thread(self);
}
let lock = match self.sender.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
lock.send(msg)
}
}
#[derive(Clone, Debug, Serialize)]
pub struct StackFrame {
pub filename: String,
pub function: String,
pub lineno: u32,
pub pre_context: Vec<String>,
pub post_context: Vec<String>,
pub context_line: String,
}
#[derive(Clone, Debug, Serialize)]
pub struct SDK {
pub name: String,
pub version: String,
}
#[derive(Clone, Debug, Serialize)]
pub struct Device {
pub name: String,
pub version: String,
pub build: String,
}
#[derive(Clone, Debug)]
pub struct Event {
pub event_id: String,
pub message: String,
pub timestamp: String,
pub level: String,
pub logger: String,
pub platform: String,
pub sdk: SDK,
pub device: Device,
pub culprit: Option<String>,
pub server_name: Option<String>,
pub stacktrace: Option<Vec<StackFrame>>,
pub release: Option<String>,
pub tags: BTreeMap<String, String>,
pub environment: Option<String>,
pub modules: BTreeMap<String, String>,
pub extra: BTreeMap<String, String>,
pub fingerprint: Vec<String>,
}
impl Event {
pub fn to_string(&self) -> String {
let mut base_str = String::new();
base_str.push_str("{");
base_str.push_str(&format!("\"event_id\":\"{}\",", self.event_id));
base_str.push_str(&format!("\"message\":\"{}\",", self.message));
base_str.push_str(&format!("\"timestamp\":\"{}\",", self.timestamp));
base_str.push_str(&format!("\"level\": \"{}\",", self.level));
base_str.push_str(&format!("\"logger\": \"{}\",", self.logger));
base_str.push_str(&format!("\"platform\": \"{}\",", self.platform));
base_str.push_str(&format!("\"sdk\": {},",
serde_json::to_string_pretty(&self.sdk).unwrap_or("".to_owned())));
base_str.push_str(&format!("\"device\": {}",
serde_json::to_string_pretty(&self.device).unwrap_or("".to_owned())));
if let Some(ref culprit) = self.culprit {
base_str.push_str(&format!(",\"culprit\": \"{}\"", culprit));
}
if let Some(ref server_name) = self.server_name {
base_str.push_str(&format!(",\"server_name\": \"{}\"", server_name));
}
if let Some(ref release) = self.release {
base_str.push_str(&format!(",\"release\":\"{}\"", release));
}
let tag_length = self.tags.len();
if tag_length > 0 {
let last_index = tag_length - 1;
base_str.push_str(",\"tags\": {");
for (index, item) in self.tags.iter().enumerate() {
base_str.push_str(&format!("\"{}\":\"{}\"", item.0, item.1));
if index != last_index {
base_str.push_str(",");
}
}
base_str.push_str("}");
}
if let Some(ref environment) = self.environment {
base_str.push_str(&format!(",\"environment\": \"{}\"", environment));
}
let modules_len = self.modules.len();
if modules_len > 0 {
base_str.push_str(",\"modules\": {");
let last_iter = modules_len - 1;
for (index, item) in self.modules.iter().enumerate() {
base_str.push_str(&format!("\"{}\": \"{}\"", item.0, item.1));
if index != last_iter {
base_str.push_str(",");
}
}
base_str.push_str("}");
}
let extra_len = self.extra.len();
if extra_len > 0 {
base_str.push_str(", \"extra\": {");
let last_iter = extra_len - 1;
for (index, item) in self.extra.iter().enumerate() {
base_str.push_str(&format!("\"{}\": \"{}\"", item.0, item.1));
if index != last_iter {
base_str.push_str(",");
}
}
base_str.push_str("}");
}
if let Some(ref stacktrace) = self.stacktrace {
base_str.push_str(",\"stacktrace\":{\"frames\": [");
let max_iter = stacktrace.len() - 1;
for (index, item) in stacktrace.iter().enumerate() {
base_str.push_str("{");
if item.filename != "" {
let mut true_filename = item.filename.clone();
let tf_len = true_filename.len();
if true_filename.starts_with("\"") {
true_filename.remove(0);
true_filename.truncate(tf_len - 1);
}
base_str.push_str(&format!("\"filename\": \"{}\",", true_filename.replace("\"", "")));
} else {
base_str.push_str(&format!("\"filename\": \"\","));
}
base_str.push_str(&format!("\"in_app\": true,"));
base_str.push_str(&format!("\"function\": \"{}\",", item.function));
base_str.push_str(&format!("\"lineno\": {},", item.lineno));
base_str.push_str(&format!("\"pre_context\": {:?},", item.pre_context));
base_str.push_str(&format!("\"post_context\": {:?},", item.post_context));
let mut true_context_line = item.context_line.clone();
let tc_len = true_context_line.len();
if true_context_line.starts_with("\"") {
true_context_line.remove(0);
true_context_line.truncate(tc_len - 1);
}
base_str.push_str(&format!("\"context_line\": \"{}\"", true_context_line.replace("\"", "")));
base_str.push_str("}");
if index != max_iter {
base_str.push_str(",");
}
}
base_str.push_str("]}");
}
let fingerprint_len = self.fingerprint.len();
if fingerprint_len > 0 {
base_str.push_str(",\"fingerprint\": [");
let max_iter = fingerprint_len - 1;
for (index, item) in self.fingerprint.iter().enumerate() {
base_str.push_str(&format!("\"{}\"", item));
if index != max_iter {
base_str.push_str(",");
}
}
base_str.push_str("]");
}
base_str.push_str("}");
base_str
}
}
impl Event {
pub fn new(logger: &str, level: &str, message: &str, culprit: Option<&str>,
fingerprint: Option<Vec<String>>, server_name: Option<&str>, stacktrace: Option<Vec<StackFrame>>,
release: Option<&str>, environment: Option<&str>) -> Event {
Event {
event_id: "".to_owned(),
message: message.to_owned(),
timestamp: UTC::now().format("%Y-%m-%dT%H:%M:%S").to_string(),
level: level.to_owned(),
logger: logger.to_owned(),
platform: "other".to_string(),
sdk: SDK {
name: "rust-sentry".to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
},
device: Device {
name: env::var_os("OSTYPE")
.and_then(|cs| cs.into_string().ok())
.unwrap_or("".to_string()),
version: "".to_string(),
build: "".to_string(),
},
culprit: culprit.map(|c| c.to_owned()),
server_name: server_name.map(|c| c.to_owned()),
stacktrace: stacktrace,
release: release.map(|c| c.to_owned()),
tags: BTreeMap::new(),
environment: environment.map(|c| c.to_owned()),
modules: BTreeMap::new(),
extra: BTreeMap::new(),
fingerprint: fingerprint.unwrap_or(vec![]),
}
}
pub fn add_tag(&mut self, key: String, value: String) {
self.tags.insert(key, value);
}
}
#[derive(Clone, Debug)]
pub struct SentryCredentials {
pub key: String,
pub secret: String,
pub host: Option<String>,
pub project_id: String,
}
pub struct Sentry {
pub server_name: String,
pub release: String,
pub environment: String,
pub worker: Arc<SingleWorker<Event, SentryCredentials>>,
}
header! { (XSentryAuth, "X-Sentry-Auth") => [String] }
impl Sentry {
pub fn new(server_name: String, release: String, environment: String,
credentials: SentryCredentials) -> Sentry {
let worker = SingleWorker::new(credentials, Box::new(move |credentials, e| {
Sentry::post(credentials, &e);
}));
Sentry {
server_name: server_name,
release: release,
environment: environment,
worker: Arc::new(worker),
}
}
fn post(credentials: &SentryCredentials, e: &Event) {
info!("Post has been called for Sentry!");
let mut headers = Headers::new();
debug!("Created Headers!");
let timestamp = UTC::now().timestamp().to_string();
debug!("Got Timestamp for Sentry: [ {:?} ]", timestamp.clone());
let sentry_auth = format!("Sentry sentry_version=7,sentry_client=rust-sentry/{},sentry_timestamp={},sentry_key={},sentry_secret={}",
env!("CARGO_PKG_VERSION"), timestamp, credentials.key, credentials.secret);
headers.set(XSentryAuth(sentry_auth));
headers.set(ContentType::json());
debug!("Content Headers Set!");
let body = e.to_string();
let ssl = NativeTlsClient::new().unwrap();
let connector = HttpsConnector::new(ssl);
let mut client = Client::with_connector(connector);
client.set_read_timeout(Some(Duration::new(5, 0)));
client.set_write_timeout(Some(Duration::new(5, 0)));
let url = format!("https://{}:{}@{}/api/{}/store/", credentials.key, credentials.secret,
credentials.host.clone().unwrap_or("sentry.insops.net".to_owned()), credentials.project_id);
debug!("Posting body: {:?}", body.clone());
let res = client.post(&url).headers(headers).body(&body).send();
if res.is_err() {
return;
}
let mut res = res.unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
info!("Sentry Response: {:?}", body);
}
pub fn log_event(&self, e: Event) {
let _ = self.worker.work_with(e);
}
pub fn register_panic_handler(&self) {
info!("Registering Panic Handler for Sentry!");
let server_name = self.server_name.clone();
let release = self.release.clone();
let environment = self.environment.clone();
let worker = self.worker.clone();
std::panic::set_hook(Box::new(move |info: &std::panic::PanicInfo| {
let location = info.location().map(|l| format!("{}: {}", l.file(), l.line())).unwrap_or("Unknown".to_string());
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
None => {
match info.payload().downcast_ref::<String>() {
Some(s) => &s[..],
None => "Box<Any>",
}
}
};
let mut frames = vec![];
backtrace::trace(|frame: &backtrace::Frame| {
backtrace::resolve(frame.ip(), |symbol| {
let name = symbol.name().map_or("unresolved symbol".to_string(), |name| name.to_string());
let filename = symbol.filename().map_or("".to_string(), |sym| format!("{:?}", sym));
let lineno = symbol.lineno().unwrap_or(0);
let f = File::open(&filename.replace("\"", ""));
let mut pre_context = Vec::new();
let mut context_line = String::new();
let mut post_context = Vec::new();
if f.is_ok() {
let file = f.unwrap();
let buffed_reader = BufReader::new(&file);
let items = buffed_reader.lines().skip((lineno - 3) as usize).take(5);
let mut i = 0;
for item in items {
if item.is_ok() {
let true_item = item.unwrap();
match i {
0|1 => {
pre_context.push(true_item);
},
2 => {
context_line = true_item;
},
3|4 => {
post_context.push(true_item);
},
_ => continue
}
}
i += 1;
}
} else {
drop(f);
}
frames.push(StackFrame {
filename: filename,
function: name,
lineno: lineno,
pre_context: pre_context,
post_context: post_context,
context_line: context_line
});
});
true
});
let event = Event::new("panic", "fatal", msg, Some(&location), None, Some(&server_name),
Some(frames), Some(&release), Some(&environment));
let result = worker.work_with(event.clone());
if result.is_ok() {
std::thread::sleep(Duration::from_secs(5));
}
}));
info!("Setup Panic Handler!");
}
pub fn unregister_panic_handler(&self) {
let _ = std::panic::take_hook();
}
pub fn fatal(&self, logger: &str, message: &str, culprit: Option<&str>) {
self.log(logger, "fatal", message, culprit, None);
}
pub fn error(&self, logger: &str, message: &str, culprit: Option<&str>) {
self.log(logger, "error", message, culprit, None);
}
pub fn warning(&self, logger: &str, message: &str, culprit: Option<&str>) {
self.log(logger, "warning", message, culprit, None);
}
pub fn info(&self, logger: &str, message: &str, culprit: Option<&str>) {
self.log(logger, "info", message, culprit, None);
}
pub fn debug(&self, logger: &str, message: &str, culprit: Option<&str>) {
self.log(logger, "debug", message, culprit, None);
}
fn log(&self, logger: &str, level: &str, message: &str, culprit: Option<&str>,
fingerprint: Option<Vec<String>>) {
let fpr = match fingerprint {
Some(f) => f,
None => {
vec![
logger.to_string(),
level.to_string(),
culprit.map(|c| c.to_string()).unwrap_or("".to_string())
]
}
};
let _ = self.worker.work_with(Event::new(logger, level, message, culprit, Some(fpr),
Some(&self.server_name), None, Some(&self.release), Some(&self.environment)));
}
}