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
#[cfg(feature = "with-binn-ir")]
extern crate binn_ir;
extern crate libc;
#[cfg(feature = "default")]
extern crate rusqlite;
#[macro_use]
#[allow(unused_macros)]
mod __;
#[cfg(feature = "with-binn-ir")]
use std::{
fs::OpenOptions,
io::BufWriter,
collections::BTreeMap,
};
use std::{
fs,
io::{self, Error, ErrorKind},
path::{Path, PathBuf},
ptr,
sync::mpsc::{self, SyncSender},
thread,
time::{Duration, Instant, SystemTime},
};
#[cfg(feature = "with-binn-ir")]
use binn_ir::{
value::Value,
};
#[cfg(feature = "default")]
use rusqlite::{
Connection,
types::ToSql,
};
macro_rules! code_name { () => { "ice-age" }}
macro_rules! version { () => { "0.2.1" }}
pub const NAME: &'static str = "Ice Age";
pub const CODE_NAME: &'static str = code_name!();
pub const VERSION: &'static str = version!();
pub const RELEASE_DATE: (u16, u8, u8) = (2018, 9, 15);
pub const UUID: &'static str = "a9ab5574-e977-427d-a17b-ea421a1a6b5b";
pub const TAG: &'static str = concat!(code_name!(), "::a9ab5574::", version!());
#[test]
fn test_crate_version() {
assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
}
#[cfg(feature = "default")]
const SQL_CREATOR: &'static str = include_str!("../res/db_creator.sql");
#[cfg(feature = "default")]
const LOG_FILE_EXT: &'static str = ".sqlite";
#[cfg(feature = "with-binn-ir")]
const LOG_FILE_EXT: &'static str = ".ice-age";
pub struct Config {
pub work_dir: PathBuf,
pub max_file_len: u64,
pub log_files_reserved: Duration,
pub buf_len: usize,
pub disk_flush_interval: Duration,
}
#[derive(Debug)]
pub struct Log {
pub time: u64,
pub remote_ip: String,
pub url: String,
pub response_size: Option<u64>,
pub code: u16,
pub runtime: Duration,
pub notes: Option<String>,
}
#[cfg(feature = "with-binn-ir")]
impl Log {
const KEY_TIME: i32 = 0;
const KEY_REMOTE_IP: i32 = 1;
const KEY_URL: i32 = 2;
const KEY_RESPONSE_SIZE: i32 = 3;
const KEY_CODE: i32 = 4;
const KEY_RUNTIME: i32 = 5;
const KEY_NOTES: i32 = 6;
pub fn to_value(self) -> Value {
Value::Map({
let mut map = BTreeMap::new();
map.insert(Self::KEY_TIME, self.time.into());
map.insert(Self::KEY_REMOTE_IP, self.remote_ip.into());
map.insert(Self::KEY_URL, self.url.into());
if let Some(response_size) = self.response_size {
map.insert(Self::KEY_RESPONSE_SIZE, response_size.into());
}
map.insert(Self::KEY_CODE, self.code.into());
map.insert(Self::KEY_RUNTIME, self.runtime.as_secs().into());
if let Some(notes) = self.notes {
map.insert(Self::KEY_NOTES, notes.into());
}
map
})
}
pub fn from_value(value: Value) -> io::Result<Self> {
match value {
Value::Map(mut map) => Ok(Self {
time: match map.remove(&Self::KEY_TIME).ok_or(Error::new(ErrorKind::InvalidInput, __!("Missing time")))? {
Value::U64(time) => time,
other => return Err(Error::new(ErrorKind::InvalidInput, __!("Expected U64 for time, got: {:?}", other))),
},
remote_ip: match map.remove(&Self::KEY_REMOTE_IP).ok_or(Error::new(ErrorKind::InvalidInput, __!("Missing remote IP")))? {
Value::Text(remote_ip) => remote_ip,
other => return Err(Error::new(ErrorKind::InvalidInput, __!("Expected Text for remote IP, got: {:?}", other))),
},
url: match map.remove(&Self::KEY_URL).ok_or(Error::new(ErrorKind::InvalidInput, __!("Missing URL")))? {
Value::Text(url) => url,
other => return Err(Error::new(ErrorKind::InvalidInput, __!("Expected Text for URL, got: {:?}", other))),
},
response_size: match map.remove(&Self::KEY_RESPONSE_SIZE) {
Some(Value::U64(response_size)) => Some(response_size),
None => None,
other => return Err(Error::new(ErrorKind::InvalidInput, __!("Expected U64 for response size, got: {:?}", other))),
},
code: match map.remove(&Self::KEY_CODE).ok_or(Error::new(ErrorKind::InvalidInput, __!("Missing code")))? {
Value::U16(code) => code,
other => return Err(Error::new(ErrorKind::InvalidInput, __!("Expected U16 for code, got: {:?}", other))),
},
runtime: match map.remove(&Self::KEY_RUNTIME).ok_or(Error::new(ErrorKind::InvalidInput, __!("Missing runtime")))? {
Value::U64(runtime) => Duration::from_secs(runtime),
other => return Err(Error::new(ErrorKind::InvalidInput, __!("Expected U64 for runtime, got: {:?}", other))),
},
notes: match map.remove(&Self::KEY_NOTES) {
Some(Value::Text(notes)) => Some(notes),
None => None,
other => return Err(Error::new(ErrorKind::InvalidInput, __!("Expected Text for notes, got: {:?}", other))),
},
}),
other => Err(Error::new(ErrorKind::InvalidInput, __!("Expected a map, got: {:?}", other))),
}
}
}
#[derive(Debug)]
pub enum Cmd {
StoreLog(Log),
FlushToDisk,
Ping,
}
pub type CmdSender = SyncSender<Cmd>;
pub struct Logger {
logs: Vec<Log>,
config: Config,
output: Option<PathBuf>,
}
impl Logger {
pub fn make(config: Config) -> io::Result<CmdSender> {
if config.disk_flush_interval.as_secs() == 0 {
return Err(Error::new(ErrorKind::InvalidInput, "Disk flush interval must be larger than zero"));
}
let disk_flush_interval = config.disk_flush_interval.clone();
let (sender, receiver) = mpsc::sync_channel(config.buf_len);
thread::spawn(move || {
let mut logger = Self {
logs: Vec::with_capacity(config.buf_len),
config,
output: None,
};
loop {
match receiver.recv() {
Ok(Cmd::StoreLog(log)) => logger.push(log),
Ok(Cmd::FlushToDisk) => if let Err(err) = logger.flush_to_disk() {
__e!("{}", err);
},
Ok(Cmd::Ping) => (),
Err(err) => {
__e!("Failed to receive command: {} -> stopping server", err);
break;
},
};
}
});
{
let sender = sender.clone();
thread::spawn(move || {
let sleep_time = Duration::from_secs(disk_flush_interval.as_secs().min(10));
let mut last_saved = Instant::now();
loop {
let now = Instant::now();
match now - last_saved >= disk_flush_interval {
true => match sender.send(Cmd::FlushToDisk) {
Ok(()) => last_saved = Instant::now(),
Err(err) => {
__e!("Failed sending {:?} to server -> {}", Cmd::FlushToDisk, err);
break;
},
},
false => if let Err(err) = sender.send(Cmd::Ping) {
__e!("Failed sending {:?} to server -> {}", Cmd::Ping, err);
break;
},
};
thread::sleep(sleep_time);
}
});
}
Ok(sender)
}
pub fn push(&mut self, log: Log) {
self.logs.push(log);
if self.logs.len() >= self.logs.capacity() {
__p!("Buffer full; flushing to disk...");
if let Err(err) = self.flush_to_disk() {
__e!("Failed flushing logs to disk: {}", err);
}
self.logs.clear();
self.clean_up_old_log_files();
}
}
fn flush_to_disk(&mut self) -> io::Result<()> {
let need_new_file = match self.output.as_ref() {
Some(output) => output.metadata()?.len() >= self.config.max_file_len,
None => true,
};
if need_new_file {
let (year, month, day, hour, min, sec) = unsafe {
let localtime = libc::localtime(&libc::time(ptr::null_mut()));
match localtime.is_null() {
true => return Err(Error::new(ErrorKind::Other, __!("Failed to get local time"))),
false => (
(*localtime).tm_year.saturating_add(1900), (*localtime).tm_mon.saturating_add(1), (*localtime).tm_mday,
(*localtime).tm_hour, (*localtime).tm_min, (*localtime).tm_sec,
),
}
};
let path = self.config.work_dir.join(
format!("{:04}-{:02}-{:02}__{:02}-{:02}-{:02}{}", year, month, day, hour, min, sec, LOG_FILE_EXT)
);
match path.exists() {
true => return Err(Error::new(ErrorKind::Other, __!("Failed to create output file (it existed already): {:?}", path))),
false => self.output = Some(path),
}
}
if let Some(output) = self.output.clone() {
self.flush_to_file(output)?;
}
Ok(())
}
#[cfg(feature = "default")]
fn flush_to_file(&self, file: impl AsRef<Path>) -> io::Result<()> {
let file = file.as_ref();
let start_time = Instant::now();
let file_existed = file.exists();
let mut conn = Connection::open(file).map_err(|err|
Error::new(ErrorKind::Other, __!("Failed to open database connection: {}", err))
)?;
if file_existed == false {
conn.execute_batch(SQL_CREATOR).map_err(|err| Error::new(ErrorKind::Other, __!("Failed making new database: {}", err)))?;
}
let transaction = conn.transaction().map_err(|err|
Error::new(ErrorKind::Other, __!("Failed to make new database transaction: {}", err))
)?;
{
let mut statement = transaction.prepare_cached(
"insert into logs (time, remote_ip, url, response_size, code, runtime, runtime_millis, notes) values (?,?,?,?,?,?,?,?);"
).map_err(|err| {
Error::new(ErrorKind::Other, __!("Internal error: {}", err))
})?;
for log in self.logs.iter() {
let params: &[&ToSql] = &[
&(log.time as i64), &log.remote_ip, &log.url, &log.response_size.map(|s| s as i64), &log.code,
&(log.runtime.as_secs() as i64), &log.runtime.subsec_millis(), &(log.notes),
];
statement.execute(params).map_err(|err| Error::new(ErrorKind::Other, __!("Failed running SQL statement: {}", err)))?;
}
}
transaction.commit().map_err(|err| Error::new(ErrorKind::Other, __!("Failed to commit: {}", err)))?;
__p!(
"Flushed {} record{} to disk successfully, in {:?}",
self.logs.len(), match self.logs.len() { 1 => "", _ => "s" }, Instant::now().duration_since(start_time),
);
Ok(())
}
#[cfg(feature = "with-binn-ir")]
fn flush_to_file(&mut self, file: impl AsRef<Path>) -> io::Result<()> {
let file = file.as_ref();
let start_time = Instant::now();
let count = self.logs.len();
{
let mut writer = BufWriter::new(OpenOptions::new().append(true).create(true).open(file)?);
for i in (0..count).rev() {
self.logs.remove(i).to_value().encode(&mut writer)?;
}
}
__p!(
"Flushed {} record{} to disk successfully, in {:?}",
count, match count { 1 => "", _ => "s" }, Instant::now().duration_since(start_time),
);
Ok(())
}
fn clean_up_old_log_files(&self) {
let work_dir = self.config.work_dir.clone();
let log_files_reserved = self.config.log_files_reserved.clone();
thread::spawn(move || {
let read_dir = match fs::read_dir(&work_dir) {
Ok(read_dir) => read_dir,
Err(err) => {
__e!("Cleaning up old log files: failed to read work directory {:?} -> {}", work_dir, err);
return;
},
};
for dir_entry in read_dir {
if let Ok(dir_entry) = dir_entry {
match dir_entry.file_name().to_str() {
Some(file_name) if file_name.ends_with(LOG_FILE_EXT) => (),
_ => continue,
};
match dir_entry.metadata().map(|m| m.modified().map(|m| SystemTime::now().duration_since(m))) {
Ok(Ok(Ok(duration))) if duration > log_files_reserved => {
let path = dir_entry.path();
if path.is_file() == false {
continue;
}
match fs::remove_file(&path) {
Ok(()) => __p!("Removed old log file: {:?}", path),
Err(err) => __e!("Failed to remove old log file {:?} -> {}", path, err),
}
},
_ => continue,
};
}
}
});
}
}