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 println!("VMW: creating dir");
20 fs::create_dir_all(path.clone())?;
21 println!("VMW: created dir");
22 // Do a crazy dance with lots of fsync()s to be overly cautious here...
23 // We never want to end up in a state where we've lost the old data, or end up using the
24 // old data on power loss after we've returned.
25 // The way to atomically write a file on Unix platforms is:
26 // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
27 let filename_with_path = get_full_filepath(path, filename);
28 let tmp_filename = format!("{}.tmp", filename_with_path);
31 // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
32 // rust stdlib 1.36 or higher.
33 println!("VMW: about to create file");
34 let mut f = fs::File::create(&tmp_filename)?;
35 println!("VMW: created file");
36 data.write_to_file(&mut f)?;
37 println!("VMW: about to sync all");
39 println!("VMW: sync'd all");
41 println!("VMW: about to rename");
42 fs::rename(&tmp_filename, &filename_with_path)?;
43 println!("VMW: renamed");
44 // Fsync the parent directory on Unix.
45 #[cfg(not(target_os = "windows"))]
47 let path = Path::new(&filename_with_path).parent().unwrap();
48 let dir_file = fs::OpenOptions::new().read(true).open(path)?;
49 unsafe { libc::fsync(dir_file.as_raw_fd()); }
56 use super::{DiskWriteable, get_full_filepath, write_to_file};
61 struct TestWriteable{}
62 impl DiskWriteable for TestWriteable {
63 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), io::Error> {
64 writer.write_all(&[42; 1])
68 // Test that if the persister's path to channel data is read-only, writing
69 // data to it fails. Windows ignores the read-only flag for folders, so this
71 #[cfg(not(target_os = "windows"))]
73 fn test_readonly_dir() {
74 let test_writeable = TestWriteable{};
75 let filename = "test_readonly_dir_persister_filename".to_string();
76 let path = "test_readonly_dir_persister_dir";
77 fs::create_dir_all(path.to_string()).unwrap();
78 let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
79 perms.set_readonly(true);
80 fs::set_permissions(path.to_string(), perms).unwrap();
81 match write_to_file(path.to_string(), filename, &test_writeable) {
82 Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
83 _ => panic!("Unexpected error message")
87 // Test failure to rename in the process of atomically creating a channel
88 // monitor's file. We induce this failure by making the `tmp` file a
90 // Explanation: given "from" = the file being renamed, "to" = the
91 // renamee that already exists: Windows should fail because it'll fail
92 // whenever "to" is a directory, and Unix should fail because if "from" is a
93 // file, then "to" is also required to be a file.
95 fn test_rename_failure() {
96 let test_writeable = TestWriteable{};
97 let filename = "test_rename_failure_filename";
98 let path = "test_rename_failure_dir";
99 // Create the channel data file and make it a directory.
100 fs::create_dir_all(get_full_filepath(path.to_string(), filename.to_string())).unwrap();
101 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
103 #[cfg(not(target_os = "windows"))]
104 assert_eq!(e.kind(), io::ErrorKind::Other);
105 #[cfg(target_os = "windows")]
106 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
108 _ => panic!("Unexpected error message")
110 fs::remove_dir_all(path).unwrap();
114 fn test_diskwriteable_failure() {
115 struct FailingWriteable {}
116 impl DiskWriteable for FailingWriteable {
117 fn write_to_file(&self, _writer: &mut fs::File) -> Result<(), std::io::Error> {
118 Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
122 let filename = "test_diskwriteable_failure";
123 let path = "test_diskwriteable_failure_dir";
124 let test_writeable = FailingWriteable{};
125 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
127 assert_eq!(e.kind(), std::io::ErrorKind::Other);
128 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
130 _ => panic!("unexpected result")
132 fs::remove_dir_all(path).unwrap();
135 // Test failure to create the temporary file in the persistence process.
136 // We induce this failure by having the temp file already exist and be a
139 fn test_tmp_file_creation_failure() {
140 let test_writeable = TestWriteable{};
141 let filename = "test_tmp_file_creation_failure_filename".to_string();
142 let path = "test_tmp_file_creation_failure_dir".to_string();
144 // Create the tmp file and make it a directory.
145 let tmp_path = get_full_filepath(path.clone(), format!("{}.tmp", filename.clone()));
146 fs::create_dir_all(tmp_path).unwrap();
147 match write_to_file(path, filename, &test_writeable) {
149 #[cfg(not(target_os = "windows"))]
150 assert_eq!(e.kind(), io::ErrorKind::Other);
151 #[cfg(target_os = "windows")]
152 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
154 _ => panic!("Unexpected error message")