2 #[cfg(target_os = "windows")]
6 use std::path::{Path, PathBuf};
7 #[cfg(target_os = "windows")]
10 std::os::windows::ffi::OsStrExt
12 #[cfg(not(target_os = "windows"))]
13 use std::os::unix::io::AsRawFd;
15 pub(crate) trait DiskWriteable {
16 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error>;
19 pub(crate) fn get_full_filepath(filepath: String, filename: String) -> String {
20 let mut path = PathBuf::from(filepath);
22 path.to_str().unwrap().to_string()
24 #[cfg(target_os = "windows")]
30 return Err(std::io::Error::last_os_error())
35 #[cfg(target_os = "windows")]
36 fn path_to_windows_str<T: AsRef<OsStr>>(x: T) -> Vec<winapi::shared::ntdef::WCHAR> {
37 x.as_ref().encode_wide().chain(Some(0)).collect()
40 #[allow(bare_trait_objects)]
41 pub(crate) fn write_to_file<D: DiskWriteable>(path: String, filename: String, data: &D) -> std::io::Result<()> {
42 println!("VMW: creating dir");
43 fs::create_dir_all(path.clone())?;
44 println!("VMW: created dir");
46 println!("VMW: entries in dir:");
47 let dir = PathBuf::from(path.clone());
48 for entry in fs::read_dir(dir).unwrap() {
49 let entry = entry.unwrap();
50 println!("VMW: entry in dir: {:?}", entry.path());
52 // Do a crazy dance with lots of fsync()s to be overly cautious here...
53 // We never want to end up in a state where we've lost the old data, or end up using the
54 // old data on power loss after we've returned.
55 // The way to atomically write a file on Unix platforms is:
56 // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
57 let filename_with_path = get_full_filepath(path, filename);
58 let tmp_filename = format!("{}.tmp", filename_with_path);
61 // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
62 // rust stdlib 1.36 or higher.
63 println!("VMW: about to create file");
64 let mut f = fs::File::create(&tmp_filename)?;
65 println!("VMW: created file");
66 data.write_to_file(&mut f)?;
67 println!("VMW: about to sync all");
69 println!("VMW: sync'd all");
71 // Fsync the parent directory on Unix.
72 #[cfg(not(target_os = "windows"))]
74 fs::rename(&tmp_filename, &filename_with_path)?;
75 let path = Path::new(&filename_with_path).parent().unwrap();
76 let dir_file = fs::OpenOptions::new().read(true).open(path)?;
77 unsafe { libc::fsync(dir_file.as_raw_fd()); }
79 #[cfg(target_os = "windows")]
81 println!("VMW: about to rename");
82 let src = PathBuf::from(tmp_filename);
83 let dst = PathBuf::from(filename_with_path);
84 call!(unsafe {winapi::um::winbase::MoveFileExW(
85 path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(),
86 winapi::um::winbase::MOVEFILE_WRITE_THROUGH | winapi::um::winbase::MOVEFILE_REPLACE_EXISTING
88 println!("VMW: renamed");
95 use super::{DiskWriteable, get_full_filepath, write_to_file};
100 struct TestWriteable{}
101 impl DiskWriteable for TestWriteable {
102 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), io::Error> {
103 writer.write_all(&[42; 1])
107 // Test that if the persister's path to channel data is read-only, writing
108 // data to it fails. Windows ignores the read-only flag for folders, so this
109 // test is Unix-only.
110 #[cfg(not(target_os = "windows"))]
112 fn test_readonly_dir() {
113 let test_writeable = TestWriteable{};
114 let filename = "test_readonly_dir_persister_filename".to_string();
115 let path = "test_readonly_dir_persister_dir";
116 fs::create_dir_all(path.to_string()).unwrap();
117 let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
118 perms.set_readonly(true);
119 fs::set_permissions(path.to_string(), perms).unwrap();
120 match write_to_file(path.to_string(), filename, &test_writeable) {
121 Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
122 _ => panic!("Unexpected error message")
126 // Test failure to rename in the process of atomically creating a channel
127 // monitor's file. We induce this failure by making the `tmp` file a
129 // Explanation: given "from" = the file being renamed, "to" = the
130 // renamee that already exists: Windows should fail because it'll fail
131 // whenever "to" is a directory, and Unix should fail because if "from" is a
132 // file, then "to" is also required to be a file.
134 fn test_rename_failure() {
135 let test_writeable = TestWriteable{};
136 let filename = "test_rename_failure_filename";
137 let path = "test_rename_failure_dir";
138 // Create the channel data file and make it a directory.
139 fs::create_dir_all(get_full_filepath(path.to_string(), filename.to_string())).unwrap();
140 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
142 #[cfg(not(target_os = "windows"))]
143 assert_eq!(e.kind(), io::ErrorKind::Other);
144 #[cfg(target_os = "windows")]
145 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
147 _ => panic!("Unexpected error message")
149 fs::remove_dir_all(path).unwrap();
153 fn test_diskwriteable_failure() {
154 struct FailingWriteable {}
155 impl DiskWriteable for FailingWriteable {
156 fn write_to_file(&self, _writer: &mut fs::File) -> Result<(), std::io::Error> {
157 Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
161 let filename = "test_diskwriteable_failure";
162 let path = "test_diskwriteable_failure_dir";
163 let test_writeable = FailingWriteable{};
164 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
166 assert_eq!(e.kind(), std::io::ErrorKind::Other);
167 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
169 _ => panic!("unexpected result")
171 fs::remove_dir_all(path).unwrap();
174 // Test failure to create the temporary file in the persistence process.
175 // We induce this failure by having the temp file already exist and be a
178 fn test_tmp_file_creation_failure() {
179 let test_writeable = TestWriteable{};
180 let filename = "test_tmp_file_creation_failure_filename".to_string();
181 let path = "test_tmp_file_creation_failure_dir".to_string();
183 // Create the tmp file and make it a directory.
184 let tmp_path = get_full_filepath(path.clone(), format!("{}.tmp", filename.clone()));
185 fs::create_dir_all(tmp_path).unwrap();
186 match write_to_file(path, filename, &test_writeable) {
188 #[cfg(not(target_os = "windows"))]
189 assert_eq!(e.kind(), io::ErrorKind::Other);
190 #[cfg(target_os = "windows")]
191 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
193 _ => panic!("Unexpected error message")