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
use std::path::PathBuf;
use std::fs::File;
use std::time::SystemTime;
use std::thread::JoinHandle;
use crate::buf::DoubleBuf;
use std::io::Write;
use std::sync::{Arc, Mutex, atomic::AtomicBool, atomic::Ordering};
use super::{Writer, Error, ErrorRepr, ErrorKind};


/// Writer to a file.
pub struct FileWriter {
    f:  File,
}


impl FileWriter {

    /// Creates a `FileWriter` which will write to a file located in `log_dir` directory.
    /// The file name has form `log_<unix_timestamp_seconds>.txt`.
    pub fn new(log_dir: &str) -> Result<FileWriter, Error> {

        let epoch_secs = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|e| { Error::new(ErrorKind::TimeError, ErrorRepr::TimeError(e)) })?
            .as_secs();

        let file_name = format!("log_{}.txt", epoch_secs);

        let mut file_path = PathBuf::new();

        file_path.push(log_dir);
        file_path.push(file_name);

        let file_path = file_path
            .to_str()
            .ok_or(Error::new(ErrorKind::PathToStrConversionError, ErrorRepr::Simple))?;

        let f = std::fs::OpenOptions::new()
            .append(true)
            .create_new(true)
            .open(file_path)
            .map_err(|e| { Error::new(ErrorKind::IoError, ErrorRepr::IoError(e)) })?;

        Ok(FileWriter {
            f,
        })
    }
}


impl Writer for FileWriter {

    fn process_slice(&mut self, slice: &[u8]) {

        let _ret = self.f.write_all(&slice);
    }

    fn flush(&mut self) {

        let _ret = self.f.flush();
    }
}



/// Writer thread.
pub struct ThreadedWriter {
    writer_thread:  JoinHandle<()>,
    terminate:      Arc<AtomicBool>,
}


impl<'a> ThreadedWriter {

    /// Create a new instance: spawn a thread, pass a `writer` there, and do writes of log messages
    /// using the `writer`.
    pub fn new(writer: Arc<Mutex<Box<dyn Writer>>>, db: &DoubleBuf) -> ThreadedWriter {

        let terminate = Arc::new(AtomicBool::new(false));

        let terminate2 = terminate.clone();

        let db2 = db.clone();

        let writer_thread = std::thread::spawn(move || {

            Self::write_log_loop(writer, db2, terminate2);
        });

        ThreadedWriter {
            writer_thread,
            terminate,
        }
    }


    pub fn request_stop(&self) {

        self.terminate.store(true, Ordering::Relaxed);
    }
        
    pub fn wait_termination(self) {
        
        self.writer_thread.join().unwrap();
    }


    /// enters the loop of reading from buffer and writing to a file
    fn write_log_loop(writer: Arc<Mutex<Box<dyn Writer>>>, buf: DoubleBuf, terminate: Arc<AtomicBool>) {

        let mut terminated_cnt = 0;

        let mut buf_id = 0;

        loop {

            let slice = buf.reserve_for_reaed(buf_id);

            let mut guard = writer.lock().unwrap();

            guard.process_slice(slice);

            if terminate.load(Ordering::Relaxed) {

                buf.set_buf_terminated(buf_id);

                terminated_cnt += 1;

                if terminated_cnt == buf.get_buf_cnt() {

                    guard.flush();
                    break;
                }
                
            } else {

                buf.set_buf_appendable(buf_id);
            }

            buf_id = 1 - buf_id;
        }
    }
}