Skip to main content

saluki_common/logging/
rolling.rs

1use std::{
2    ffi::OsString,
3    fs::{self, File, OpenOptions},
4    io::{self, BufWriter, Write},
5    path::{Path, PathBuf},
6};
7
8/// A log file writer that rolls over to a new file once the current one reaches a maximum size.
9///
10/// Rolled files use Debian-style names: the active file is `path`, the most recently rolled file is `path.1`, and the
11/// oldest is `path.N`, where `N` is the maximum number of rolled files to keep. Rolling over deletes `path.N`, renames
12/// each remaining file to the next number up, and starts a new, empty `path`.
13///
14/// The size check happens before each write, and a write is never split across files: once the file reaches the
15/// maximum size, the next write rolls it over first. A file can therefore exceed the maximum size by up to one write.
16///
17/// An existing file at `path` is appended to, and its size counts towards the maximum once the file is open (see
18/// [`new`][Self::new] for when that is).
19///
20/// If rolling over fails, a warning is printed to standard error and writing continues at `path`. When `path` itself
21/// couldn't be renamed, writing continues in the same file. Otherwise, the renames that succeeded stay in place and a new
22/// file is started, so a rolled file whose own rename failed can be replaced by the one below it.
23pub struct RollingFileWriter {
24    path: PathBuf,
25    max_size: u64,
26    max_rolls: usize,
27    file: Option<BufWriter<File>>,
28    current_size: u64,
29}
30
31impl RollingFileWriter {
32    /// Creates a new `RollingFileWriter` for the given path.
33    ///
34    /// The file, and any missing parent directories, are created on the first write. `max_size` is in bytes.
35    /// `max_rolls` is the number of rolled files to keep, where `0` is treated as `1`.
36    ///
37    /// Because the file isn't open yet, the first write is appended to an existing file without checking its size, and
38    /// the size counts from the second write on. Use [`open`][Self::open] to count it before the first write.
39    pub fn new(path: impl Into<PathBuf>, max_size: u64, max_rolls: usize) -> Self {
40        Self {
41            path: path.into(),
42            max_size,
43            max_rolls: max_rolls.max(1),
44            file: None,
45            current_size: 0,
46        }
47    }
48
49    /// Creates a new `RollingFileWriter` for the given path, and opens the file immediately.
50    ///
51    /// See [`new`][Self::new] for the meaning of the parameters.
52    ///
53    /// # Errors
54    ///
55    /// If the file, or any missing parent directories, can't be created, an error is returned.
56    pub fn open(path: impl Into<PathBuf>, max_size: u64, max_rolls: usize) -> io::Result<Self> {
57        let mut writer = Self::new(path, max_size, max_rolls);
58        writer.open_if_needed()?;
59        Ok(writer)
60    }
61
62    fn open_if_needed(&mut self) -> io::Result<()> {
63        if self.file.is_some() {
64            return Ok(());
65        }
66
67        let mut options = OpenOptions::new();
68        options.append(true).create(true);
69        let file = match options.open(&self.path) {
70            Ok(file) => file,
71            Err(e) => {
72                let Some(parent) = self.path.parent() else {
73                    return Err(e);
74                };
75                fs::create_dir_all(parent)?;
76                options.open(&self.path)?
77            }
78        };
79
80        self.current_size = file.metadata().map_or(0, |metadata| metadata.len());
81        self.file = Some(BufWriter::new(file));
82        Ok(())
83    }
84
85    fn roll_over(&mut self) -> io::Result<()> {
86        // A failed flush leaves the current file open, so the buffered data isn't lost and the next write tries again.
87        self.flush()?;
88        self.file = None;
89        self.current_size = 0;
90
91        // The oldest rolled file doesn't exist until enough roll-overs have happened.
92        let _ = fs::remove_file(rolled_path(&self.path, self.max_rolls));
93
94        // Keep renaming after a failure, so that one stuck file doesn't stop the others from moving.
95        let mut result = Ok(());
96        for n in (0..self.max_rolls).rev() {
97            match fs::rename(rolled_path(&self.path, n), rolled_path(&self.path, n + 1)) {
98                Err(e) if e.kind() != io::ErrorKind::NotFound => result = Err(e),
99                _ => {}
100            }
101        }
102        result?;
103
104        self.open_if_needed()
105    }
106}
107
108impl Write for RollingFileWriter {
109    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
110        if self.current_size >= self.max_size {
111            if let Err(e) = self.roll_over() {
112                // This usually sits underneath the logging subsystem, so it can't report through it.
113                eprintln!("WARNING: Failed to roll over log file '{}': {}", self.path.display(), e);
114            }
115        }
116
117        self.open_if_needed()?;
118        let Some(file) = self.file.as_mut() else {
119            return Err(io::Error::other("log file should be open after opening it"));
120        };
121        file.write_all(buf)?;
122        self.current_size = self
123            .current_size
124            .saturating_add(u64::try_from(buf.len()).unwrap_or(u64::MAX));
125        Ok(buf.len())
126    }
127
128    fn flush(&mut self) -> io::Result<()> {
129        match self.file.as_mut() {
130            Some(file) => file.flush(),
131            None => Ok(()),
132        }
133    }
134}
135
136/// Returns the path of the `n`th rolled file, where `0` is the active file.
137fn rolled_path(path: &Path, n: usize) -> PathBuf {
138    if n == 0 {
139        return path.to_path_buf();
140    }
141
142    let mut rolled = OsString::from(path.as_os_str());
143    rolled.push(format!(".{}", n));
144    PathBuf::from(rolled)
145}
146
147#[cfg(test)]
148mod tests {
149    use proptest::prelude::*;
150    use tempfile::TempDir;
151
152    use super::*;
153
154    fn temp_log_path() -> (TempDir, PathBuf) {
155        let dir = tempfile::tempdir().expect("temporary directory should be created");
156        let path = dir.path().join("test.log");
157        (dir, path)
158    }
159
160    fn contents(path: &Path, n: usize) -> Option<String> {
161        fs::read_to_string(rolled_path(path, n)).ok()
162    }
163
164    fn write_all(writer: &mut RollingFileWriter, writes: &[&str]) {
165        for data in writes {
166            writer.write_all(data.as_bytes()).expect("write should succeed");
167        }
168    }
169
170    #[test]
171    fn rolls_over_on_the_first_write_after_reaching_max_size() {
172        let (_dir, path) = temp_log_path();
173        let mut writer = RollingFileWriter::open(&path, 10, 9).expect("writer should open");
174
175        // "0" brings the file to exactly the maximum, and the oversized write still lands whole in one file.
176        write_all(&mut writer, &["12345", "6789", "0", "abcdefghijkl", "ZZZ"]);
177        drop(writer);
178
179        assert_eq!(contents(&path, 2).as_deref(), Some("1234567890"));
180        assert_eq!(contents(&path, 1).as_deref(), Some("abcdefghijkl"));
181        assert_eq!(contents(&path, 0).as_deref(), Some("ZZZ"));
182        assert_eq!(contents(&path, 3), None);
183    }
184
185    #[test]
186    fn reopening_counts_existing_contents_from_the_next_write() {
187        let (_dir, path) = temp_log_path();
188        let mut writer = RollingFileWriter::open(&path, 10, 9).expect("writer should open");
189        write_all(&mut writer, &["12345"]);
190        drop(writer);
191
192        let mut writer = RollingFileWriter::new(&path, 10, 9);
193        write_all(&mut writer, &["6789", "0", "abcdefghijkl", "ZZZ"]);
194        drop(writer);
195
196        assert_eq!(contents(&path, 2).as_deref(), Some("1234567890"));
197        assert_eq!(contents(&path, 1).as_deref(), Some("abcdefghijkl"));
198        assert_eq!(contents(&path, 0).as_deref(), Some("ZZZ"));
199    }
200
201    #[test]
202    fn open_counts_existing_contents_before_the_first_write() {
203        let (_dir, path) = temp_log_path();
204        fs::write(&path, "0123456789").expect("existing log file should be written");
205
206        let mut writer = RollingFileWriter::open(&path, 10, 1).expect("writer should open");
207        write_all(&mut writer, &["new"]);
208        drop(writer);
209
210        assert_eq!(contents(&path, 1).as_deref(), Some("0123456789"));
211        assert_eq!(contents(&path, 0).as_deref(), Some("new"));
212    }
213
214    #[test]
215    fn new_appends_the_first_write_to_an_existing_file() {
216        let (_dir, path) = temp_log_path();
217        fs::write(&path, "0123456789").expect("existing log file should be written");
218
219        let mut writer = RollingFileWriter::new(&path, 10, 1);
220        write_all(&mut writer, &["a"]);
221        writer.flush().expect("flush should succeed");
222        assert_eq!(contents(&path, 0).as_deref(), Some("0123456789a"));
223        assert_eq!(contents(&path, 1), None);
224
225        write_all(&mut writer, &["b"]);
226        drop(writer);
227        assert_eq!(contents(&path, 1).as_deref(), Some("0123456789a"));
228        assert_eq!(contents(&path, 0).as_deref(), Some("b"));
229    }
230
231    #[test]
232    fn max_rolls_of_zero_keeps_one_rolled_file() {
233        let (_dir, path) = temp_log_path();
234        let mut writer = RollingFileWriter::new(&path, 1, 0);
235        write_all(&mut writer, &["a", "b", "c"]);
236        drop(writer);
237
238        assert_eq!(contents(&path, 0).as_deref(), Some("c"));
239        assert_eq!(contents(&path, 1).as_deref(), Some("b"));
240        assert_eq!(contents(&path, 2), None);
241    }
242
243    #[test]
244    fn max_size_of_zero_rolls_over_before_every_write() {
245        let (_dir, path) = temp_log_path();
246        let mut writer = RollingFileWriter::new(&path, 0, 2);
247        write_all(&mut writer, &["a", "b", "c", "d"]);
248        drop(writer);
249
250        assert_eq!(contents(&path, 0).as_deref(), Some("d"));
251        assert_eq!(contents(&path, 1).as_deref(), Some("c"));
252        assert_eq!(contents(&path, 2).as_deref(), Some("b"));
253        assert_eq!(contents(&path, 3), None);
254    }
255
256    #[test]
257    fn creates_missing_parent_directories() {
258        let dir = tempfile::tempdir().expect("temporary directory should be created");
259
260        let lazy_path = dir.path().join("lazy").join("nested").join("test.log");
261        let mut writer = RollingFileWriter::new(&lazy_path, 10, 1);
262        assert!(!lazy_path.exists());
263        write_all(&mut writer, &["x"]);
264        drop(writer);
265        assert_eq!(fs::read_to_string(&lazy_path).ok().as_deref(), Some("x"));
266
267        let eager_path = dir.path().join("eager").join("nested").join("test.log");
268        let _writer = RollingFileWriter::open(&eager_path, 10, 1).expect("writer should open");
269        assert!(eager_path.exists());
270    }
271
272    #[test]
273    fn open_fails_when_the_parent_is_not_a_directory() {
274        let dir = tempfile::tempdir().expect("temporary directory should be created");
275        let blocker = dir.path().join("not-a-directory");
276        fs::write(&blocker, "").expect("blocking file should be written");
277
278        assert!(RollingFileWriter::open(blocker.join("test.log"), 10, 1).is_err());
279    }
280
281    #[test]
282    fn failed_open_is_retried_on_the_next_write() {
283        let dir = tempfile::tempdir().expect("temporary directory should be created");
284        let blocker = dir.path().join("logs");
285        fs::write(&blocker, "").expect("blocking file should be written");
286        let path = blocker.join("test.log");
287
288        let mut writer = RollingFileWriter::new(&path, 10, 1);
289        assert!(writer.write_all(b"first").is_err());
290
291        fs::remove_file(&blocker).expect("blocking file should be removed");
292        write_all(&mut writer, &["second"]);
293        drop(writer);
294        assert_eq!(fs::read_to_string(&path).ok().as_deref(), Some("second"));
295    }
296
297    #[test]
298    fn failed_roll_over_keeps_writing_to_the_current_file() {
299        let (_dir, path) = temp_log_path();
300
301        // A non-empty directory where the first rolled file belongs can be neither removed nor replaced.
302        let blocker = rolled_path(&path, 1);
303        fs::create_dir(&blocker).expect("blocking directory should be created");
304        fs::write(blocker.join("keep"), "keep").expect("file in blocking directory should be written");
305
306        let mut writer = RollingFileWriter::new(&path, 1, 1);
307        write_all(&mut writer, &["a", "b", "c"]);
308        drop(writer);
309
310        assert_eq!(contents(&path, 0).as_deref(), Some("abc"));
311        assert_eq!(fs::read_to_string(blocker.join("keep")).ok().as_deref(), Some("keep"));
312    }
313
314    #[test]
315    fn partially_failed_roll_over_starts_a_new_file() {
316        let (_dir, path) = temp_log_path();
317
318        // As above, but for the second rolled file, so that only the rename into it fails.
319        let blocker = rolled_path(&path, 2);
320        fs::create_dir(&blocker).expect("blocking directory should be created");
321        fs::write(blocker.join("keep"), "keep").expect("file in blocking directory should be written");
322
323        let mut writer = RollingFileWriter::new(&path, 1, 2);
324        write_all(&mut writer, &["a", "b", "c"]);
325        drop(writer);
326
327        // Renaming `.1` into place fails on the second roll-over, but the active file still moves to `.1`, replacing it.
328        assert_eq!(contents(&path, 0).as_deref(), Some("c"));
329        assert_eq!(contents(&path, 1).as_deref(), Some("b"));
330        assert_eq!(fs::read_to_string(blocker.join("keep")).ok().as_deref(), Some("keep"));
331    }
332
333    #[cfg(target_os = "linux")]
334    #[test]
335    fn failed_flush_aborts_the_roll_over() {
336        let (_dir, path) = temp_log_path();
337
338        // Every write to `/dev/full` fails, so flushing the buffered data before rolling over fails.
339        std::os::unix::fs::symlink("/dev/full", &path).expect("symlink should be created");
340
341        let mut writer = RollingFileWriter::new(&path, 1, 1);
342        write_all(&mut writer, &["a", "b"]);
343        drop(writer);
344
345        // `exists()` would follow the link, so look at the paths themselves.
346        let metadata = fs::symlink_metadata(&path).expect("log path should still exist");
347        assert!(metadata.file_type().is_symlink());
348        assert!(fs::symlink_metadata(rolled_path(&path, 1)).is_err());
349    }
350
351    #[test]
352    fn rolls_over_while_another_handle_has_the_file_open() {
353        let (_dir, path) = temp_log_path();
354        let mut writer = RollingFileWriter::new(&path, 1, 1);
355        write_all(&mut writer, &["a"]);
356        writer.flush().expect("flush should succeed");
357
358        let _reader = File::open(&path).expect("log file should be readable");
359        write_all(&mut writer, &["b"]);
360        drop(writer);
361
362        assert_eq!(contents(&path, 1).as_deref(), Some("a"));
363        assert_eq!(contents(&path, 0).as_deref(), Some("b"));
364    }
365
366    #[cfg(target_os = "linux")]
367    #[test]
368    fn rolls_over_files_with_non_utf8_names() {
369        use std::os::unix::ffi::OsStrExt as _;
370
371        let dir = tempfile::tempdir().expect("temporary directory should be created");
372        let path = dir.path().join(std::ffi::OsStr::from_bytes(b"test-\xff.log"));
373        let mut writer = RollingFileWriter::new(&path, 1, 1);
374        write_all(&mut writer, &["a", "b"]);
375        drop(writer);
376
377        let mut rolled = path.clone().into_os_string();
378        rolled.push(".1");
379        assert_eq!(fs::read(&rolled).ok().as_deref(), Some(&b"a"[..]));
380        assert_eq!(fs::read(&path).ok().as_deref(), Some(&b"b"[..]));
381    }
382
383    /// Applies the same writes to an in-memory model of the rolling behavior, returning the expected contents of each
384    /// file, where index `0` is the active file.
385    fn model_files(writes: &[Vec<u8>], max_size: u64, max_rolls: usize) -> Vec<Option<Vec<u8>>> {
386        let max_rolls = max_rolls.max(1);
387        let mut files: Vec<Option<Vec<u8>>> = vec![None; max_rolls + 2];
388        let mut current_size = 0;
389
390        for data in writes {
391            if current_size >= max_size {
392                files[max_rolls] = None;
393                for n in (0..max_rolls).rev() {
394                    if let Some(file) = files[n].take() {
395                        files[n + 1] = Some(file);
396                    }
397                }
398                files[0] = Some(Vec::new());
399            }
400
401            let active = files[0].get_or_insert_with(Vec::new);
402            active.extend_from_slice(data);
403            current_size = active.len() as u64;
404        }
405
406        files
407    }
408
409    proptest! {
410        #![proptest_config(ProptestConfig::with_cases(64))]
411
412        #[test]
413        fn property_test_matches_a_model_of_size_based_rolling(
414            writes in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..16), 0..48),
415            max_size in 0u64..32,
416            max_rolls in 0usize..4,
417        ) {
418            let (_dir, path) = temp_log_path();
419            let mut writer = RollingFileWriter::new(&path, max_size, max_rolls);
420            for data in &writes {
421                prop_assert_eq!(writer.write(data).expect("write should succeed"), data.len());
422            }
423            drop(writer);
424
425            let expected = model_files(&writes, max_size, max_rolls);
426            for (n, expected) in expected.iter().enumerate() {
427                prop_assert_eq!(&fs::read(rolled_path(&path, n)).ok(), expected, "file {}", n);
428            }
429        }
430    }
431}