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
// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use std::path::Path;

use crate::error::Error;

#[derive(Debug, PartialEq)]
pub enum SyncMode {
    /// Sync all filesystem caches in system to disk.
    Sync,

    /// Sync the file systems that contain the file.
    Filesystem,

    /// Sync file data and metadata.
    File,

    /// Sync only file data, no unneeded metadata.
    Data,
}

/// Sychronize cached writes to persistent storage.
pub fn sync<P: AsRef<Path>>(file: Option<P>, mode: SyncMode) -> Result<(), Error> {
    if mode == SyncMode::Sync || file.is_none() {
        return nc::sync().map_err(Into::into);
    }
    let file = file.unwrap();
    let file = file.as_ref();
    let mut open_flags = nc::O_RDONLY | nc::O_NONBLOCK;
    let mut fd = nc::open(file, open_flags, 0);
    if fd.is_err() {
        open_flags = nc::O_WRONLY | nc::O_NONBLOCK;
        fd = nc::open(file, open_flags, 0);
    }
    let fd = fd?;
    // We used O_NONBLOCK above to not hang with fifos, so reset that here.
    let fdflags = nc::fcntl(fd, nc::F_GETFL, 0)?;
    let _ = nc::fcntl(fd, nc::F_SETFL, (fdflags & !nc::O_NONBLOCK) as usize)?;

    match mode {
        SyncMode::Filesystem => nc::syncfs(fd)?,
        SyncMode::File => nc::fsync(fd)?,
        SyncMode::Data => nc::fdatasync(fd)?,
        _ => (),
    }

    nc::close(fd)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sync() {
        assert!(sync::<&str>(None, SyncMode::Sync).is_ok());
        assert!(sync(Some("/etc/passwd"), SyncMode::Filesystem).is_ok());
        assert!(sync(Some("/etc/passwd"), SyncMode::File).is_ok());
        assert!(sync(Some("/etc/passwd"), SyncMode::Data).is_ok());
    }
}