2 use std::path::{Path, PathBuf};
4 #[cfg(not(target_os = "windows"))]
5 use std::os::unix::io::AsRawFd;
7 pub(crate) trait DiskWriteable {
8 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error>;
11 pub(crate) fn get_full_filepath(filepath: String, filename: String) -> String {
12 let mut path = PathBuf::from(filepath);
14 path.to_str().unwrap().to_string()
17 #[allow(bare_trait_objects)]
18 pub(crate) fn write_to_file<D: DiskWriteable>(path: String, filename: String, data: &D) -> std::io::Result<()> {
19 fs::create_dir_all(path.clone())?;
20 // Do a crazy dance with lots of fsync()s to be overly cautious here...
21 // We never want to end up in a state where we've lost the old data, or end up using the
22 // old data on power loss after we've returned.
23 // The way to atomically write a file on Unix platforms is:
24 // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
25 let filename_with_path = get_full_filepath(path, filename);
26 let tmp_filename = format!("{}.tmp", filename_with_path);
29 // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
30 // rust stdlib 1.36 or higher.
31 let mut f = fs::File::create(&tmp_filename)?;
32 data.write_to_file(&mut f)?;
35 fs::rename(&tmp_filename, &filename_with_path)?;
36 // Fsync the parent directory on Unix.
37 #[cfg(not(target_os = "windows"))]
39 let path = Path::new(&filename_with_path).parent().unwrap();
40 let dir_file = fs::OpenOptions::new().read(true).open(path)?;
41 unsafe { libc::fsync(dir_file.as_raw_fd()); }
48 use super::{DiskWriteable, get_full_filepath, write_to_file};
53 struct TestWriteable{}
54 impl DiskWriteable for TestWriteable {
55 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), io::Error> {
56 writer.write_all(&[42; 1])
60 // Test that if the persister's path to channel data is read-only, writing
61 // data to it fails. Windows ignores the read-only flag for folders, so this
63 #[cfg(not(target_os = "windows"))]
65 fn test_readonly_dir() {
66 let test_writeable = TestWriteable{};
67 let filename = "test_readonly_dir_persister_filename".to_string();
68 let path = "test_readonly_dir_persister_dir";
69 fs::create_dir_all(path.to_string()).unwrap();
70 let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
71 perms.set_readonly(true);
72 fs::set_permissions(path.to_string(), perms).unwrap();
73 match write_to_file(path.to_string(), filename, &test_writeable) {
74 Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
75 _ => panic!("Unexpected error message")
79 // Test failure to rename in the process of atomically creating a channel
80 // monitor's file. We induce this failure by making the `tmp` file a
82 // Explanation: given "from" = the file being renamed, "to" = the
83 // renamee that already exists: Windows should fail because it'll fail
84 // whenever "to" is a directory, and Unix should fail because if "from" is a
85 // file, then "to" is also required to be a file.
87 fn test_rename_failure() {
88 let test_writeable = TestWriteable{};
89 let filename = "test_rename_failure_filename";
90 let path = "test_rename_failure_dir";
91 // Create the channel data file and make it a directory.
92 fs::create_dir_all(get_full_filepath(path.to_string(), filename.to_string())).unwrap();
93 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
95 #[cfg(not(target_os = "windows"))]
96 assert_eq!(e.kind(), io::ErrorKind::Other);
97 #[cfg(target_os = "windows")]
98 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
100 _ => panic!("Unexpected error message")
102 fs::remove_dir_all(path).unwrap();
106 fn test_diskwriteable_failure() {
107 struct FailingWriteable {}
108 impl DiskWriteable for FailingWriteable {
109 fn write_to_file(&self, _writer: &mut fs::File) -> Result<(), std::io::Error> {
110 Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
114 let filename = "test_diskwriteable_failure";
115 let path = "test_diskwriteable_failure_dir";
116 let test_writeable = FailingWriteable{};
117 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
119 assert_eq!(e.kind(), std::io::ErrorKind::Other);
120 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
122 _ => panic!("unexpected result")
124 fs::remove_dir_all(path).unwrap();
127 // Test failure to create the temporary file in the persistence process.
128 // We induce this failure by having the temp file already exist and be a
131 fn test_tmp_file_creation_failure() {
132 let test_writeable = TestWriteable{};
133 let filename = "test_tmp_file_creation_failure_filename".to_string();
134 let path = "test_tmp_file_creation_failure_dir".to_string();
136 // Create the tmp file and make it a directory.
137 let tmp_path = get_full_filepath(path.clone(), format!("{}.tmp", filename.clone()));
138 fs::create_dir_all(tmp_path).unwrap();
139 match write_to_file(path, filename, &test_writeable) {
141 #[cfg(not(target_os = "windows"))]
142 assert_eq!(e.kind(), io::ErrorKind::Other);
143 #[cfg(target_os = "windows")]
144 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
146 _ => panic!("Unexpected error message")