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
// License: see LICENSE file at root directory of `master` branch

//! # Root

use std::{
    fs,
    io::{self, Error, ErrorKind},
    path::{Path, PathBuf},
    ptr,
    sync::{
        Arc,
        atomic::{self, AtomicBool},
        mpsc::{self, SyncSender},
    },
    thread,
    time::{Duration, Instant, SystemTime},
};

use rusqlite::{Connection, ToSql};

const SQL_CREATOR: &'static str = include_str!("../res/db_creator.sql");
const LOG_FILE_EXT_WITH_DOT: &'static str = ".sqlite";
const JOURNAL_LOG_FILE_EXT_WITH_DOT: &'static str = ".sqlite-journal";

/// # Config
#[derive(Debug)]
pub struct Config {

    /// # Work directory
    pub work_dir: PathBuf,

    /// # Max file length
    pub max_file_len: u64,

    /// # Duration to reserve log files
    pub log_files_reserved: Duration,

    /// # Buffer length
    ///
    /// It's the length of total log items, _not_ bytes.
    pub buf_len: usize,

    /// # Disk flush interval
    pub disk_flush_interval: Duration,

}

/// # Log
#[derive(Debug)]
pub struct Log {

    /// # Time in seconds
    pub time: u64,

    /// # Remote IP
    pub remote_ip: String,

    /// # URL
    pub url: String,

    /// # Response size
    pub response_size: Option<u64>,

    /// # Status code
    pub code: u16,

    /// # Runtime
    pub runtime: Duration,

    /// # Notes
    pub notes: Option<String>,

}

/// # Commands
#[derive(Debug)]
pub enum Cmd {

    /// # Store a log
    StoreLog(Log),

    /// # Flushes to disk
    FlushToDisk,

    /// # Ping
    Ping,

}

/// # Command sender
pub type CmdSender = SyncSender<Cmd>;

/// # Logger
pub struct Logger {

    /// # Logs
    logs: Vec<Log>,

    /// # Config
    config: Config,

    /// # Output log file
    output: Option<PathBuf>,

    /// # Log file cleaner flag
    log_file_cleaner_is_running: Arc<AtomicBool>,

}

impl Logger {

    /// # Makes new instance
    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;
        let (sender, receiver) = mpsc::sync_channel(config.buf_len);

        // This thread waits for commands and run them
        thread::spawn(move || {
            let mut logger = Self {
                logs: Vec::with_capacity(config.buf_len),
                config,
                output: None,
                log_file_cleaner_is_running: Arc::new(AtomicBool::new(false)),
            };
            loop {
                match receiver.recv() {
                    Ok(Cmd::StoreLog(log)) => logger.push(log),
                    Ok(Cmd::FlushToDisk) => if let Err(err) = logger.flush_to_disk_and_clear_logs() {
                        __e!("{}", err);
                    },
                    Ok(Cmd::Ping) => {},
                    Err(err) => {
                        __e!("Failed to receive command: {} -> stopping server", err);
                        break;
                    },
                };
            }
        });

        // This thread sends Cmd::FlushToDisk command to above thread, periodically
        {
            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 && 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)
    }

    /// # Pushes new log into cache
    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_and_clear_logs() {
                __e!("Failed flushing logs to disk: {}", err);
            }
        }
    }

    /// # Flushes to disk and clears logs
    fn flush_to_disk_and_clear_logs(&mut self) -> io::Result<()> {
        // Check file size
        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_WITH_DOT)
            );
            match path.exists() {
                true => return Err(Error::new(ErrorKind::Other, __!("Failed to create output file (it already exists): {:?}", path))),
                false => self.output = Some(path),
            }
        }

        if let Some(output) = self.output.clone() {
            self.flush_to_file(output)?;
        }

        self.logs.clear();
        self.clean_up_old_log_files();

        Ok(())
    }

    /// # Flushes to file
    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(())
    }

    /// # Cleans up old log files
    fn clean_up_old_log_files(&self) {
        const ATOMIC_ORDERING: atomic::Ordering = atomic::Ordering::Relaxed;

        if self.log_file_cleaner_is_running.compare_and_swap(false, true, ATOMIC_ORDERING) {
            __p!("Log file cleaner was scheduled but another instance is still running...");
            return;
        }

        let work_dir = self.config.work_dir.clone();
        let log_files_reserved = self.config.log_files_reserved.clone();
        let log_file_cleaner_is_running = self.log_file_cleaner_is_running.clone();
        thread::spawn(move || {
            match fs::read_dir(&work_dir) {
                Ok(read_dir) => 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_WITH_DOT) || file_name.ends_with(JOURNAL_LOG_FILE_EXT_WITH_DOT)
                            => {},
                            _ => 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,
                        };
                    }
                },
                Err(err) => __e!("Cleaning up old log files: failed to read work directory {:?} -> {}", work_dir, err),
            };
            log_file_cleaner_is_running.store(false, ATOMIC_ORDERING);
        });
    }

}