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
mod fsstats;
use std::os::unix::fs::MetadataExt;
use std::io::{Result, Error, Write, BufWriter};
use std::fs;
use std::fmt::Debug;
use std::path::PathBuf;
use log::{info, warn};
use chrono::Local;
#[derive(Debug, Clone, PartialEq)]
pub struct LogWriterConfig {
pub target_dir: PathBuf,
pub prefix: String,
pub suffix: String,
pub max_use_of_total: Option<f64>,
pub min_avail_of_total: Option<f64>,
pub warn_if_avail_reached: bool,
pub min_avail_bytes: Option<usize>,
pub max_file_size: usize,
}
pub struct LogWriter<T: LogWriterCallbacks + Sized + Clone + Debug> {
cfg: LogWriterConfig,
current: BufWriter<fs::File>,
current_name: String,
current_size: usize,
callbacks: T,
}
pub trait LogWriterCallbacks: Sized + Clone + Debug {
fn start_file(&mut self, log_writer: &mut LogWriter<Self>) -> Result<()>;
fn end_file(&mut self, log_writer: &mut LogWriter<Self>) -> Result<()>;
}
#[derive(Clone, Debug)]
struct NoopLogWriterCallbacks;
impl LogWriterCallbacks for NoopLogWriterCallbacks {
fn start_file(&mut self, _log_writer: &mut LogWriter<Self>) -> Result<()> { Ok(()) }
fn end_file(&mut self, _log_writer: &mut LogWriter<Self>) -> Result<()> { Ok(()) }
}
fn create_next_file(cfg: &LogWriterConfig) -> Result<(String, BufWriter<fs::File>)> {
let name = format!("{}{}{}", cfg.prefix, Local::now().format("%Y-%m-%d-%H-%M-%S"), cfg.suffix);
let file = fs::OpenOptions::new()
.write(true)
.create(true)
.open(cfg.target_dir.join(&name))?;
Ok((name, BufWriter::new(file)))
}
impl LogWriter<NoopLogWriterCallbacks> {
pub fn new(cfg: LogWriterConfig) -> Result<Self> {
LogWriter::new_with_callbacks(cfg, NoopLogWriterCallbacks)
}
}
impl<T: LogWriterCallbacks + Sized + Clone + Debug> LogWriter<T> {
pub fn new_with_callbacks(cfg: LogWriterConfig, callbacks: T) -> Result<Self> {
fs::create_dir_all(&cfg.target_dir)?;
let (current_name, current) = create_next_file(&cfg)?;
let mut log_writer = Self {
cfg,
current_name,
current,
current_size: 0,
callbacks,
};
log_writer.callbacks.clone().start_file(&mut log_writer)?;
Ok(log_writer)
}
fn enough_space(&mut self, len: usize) -> Result<bool> {
let fsstat = fsstats::statvfs(&self.cfg.target_dir)?;
if let Some(max_use_of_total) = self.cfg.max_use_of_total {
let mut used = 0;
for entry in fs::read_dir(&self.cfg.target_dir)? {
let entry = match entry {
Err(_) => {
info!("entry get failed during size calculation");
continue;
},
Ok(entry) => entry,
};
let path = entry.path();
let meta = match entry.metadata() {
Err(_) => {
info!("could not get metadata for \"{:?}\", ignoring for size calculation", &path);
continue;
},
Ok(meta) => meta,
};
if !meta.is_file() {
info!("ignoring non-file \"{:?}\" for size calculation", &path);
continue;
}
used += meta.blocks() * 512;
};
let used_of_total = used as f64 / fsstat.total_space as f64;
if used_of_total > max_use_of_total {
return Ok(false);
}
}
if let Some(min_avail_of_total) = self.cfg.min_avail_of_total {
let avail = fsstat.available_space - len as u64;
let avail_of_total = avail as f64 / fsstat.total_space as f64;
if avail_of_total < min_avail_of_total {
if self.cfg.warn_if_avail_reached {
warn!("min_avail_of_total reached, you said this shouldn't happen");
}
return Ok(false);
}
}
Ok(true)
}
fn cleanup(&mut self) -> Result<bool> {
let mut entries: Vec<_> = fs::read_dir(&self.cfg.target_dir)?
.filter_map(|x| x.ok())
.filter(|x| x.file_type().and_then(|t| Ok(t.is_file())).unwrap_or(false))
.collect();
entries.sort_by(|a, b| a.path().cmp(&b.path()));
let oldest_file = entries.get(0)
.ok_or_else(|| Error::from_raw_os_error(libc::ENOSPC))?;
let file_name = oldest_file.file_name().into_string()
.map_err(|_| Error::from_raw_os_error(libc::ENOSPC))?;
if file_name == self.current_name {
return Err(Error::from_raw_os_error(libc::ENOSPC));
}
fs::remove_file(oldest_file.path())?;
Ok(true)
}
fn next_file(&mut self) -> Result<()> {
let (next_name, next) = create_next_file(&self.cfg)?;
self.callbacks.clone().end_file(self)?;
self.current.flush()?;
self.current_name = next_name;
self.current_size = 0;
self.current = next;
self.callbacks.clone().start_file(self)?;
Ok(())
}
}
impl<T: LogWriterCallbacks + Sized + Clone + Debug> Write for LogWriter<T> {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
if self.current_size + buf.len() > self.cfg.max_file_size {
self.next_file()?;
}
while !self.enough_space(buf.len())? {
if !self.cleanup()? {
warn!("could not free enough space, this might cause strange behaviour");
break;
}
}
let written = self.current.write(buf)?;
self.current_size += written;
Ok(written)
}
fn flush(&mut self) -> Result<()> {
self.current.flush()
}
}