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: in write_to_file, filename: {}", filename);
43 fs::create_dir_all(path.clone())?;
45 // Do a crazy dance with lots of fsync()s to be overly cautious here...
46 // We never want to end up in a state where we've lost the old data, or end up using the
47 // old data on power loss after we've returned.
48 // The way to atomically write a file on Unix platforms is:
49 // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
50 let filename_with_path = get_full_filepath(path.clone(), filename);
51 let tmp_filename = format!("{}.tmp", filename_with_path);
54 // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
55 // rust stdlib 1.36 or higher.
56 println!("VMW: about to create file");
57 let mut f = fs::File::create(&tmp_filename)?;
58 println!("VMW: created file");
59 data.write_to_file(&mut f)?;
60 println!("VMW: about to sync all");
62 println!("VMW: sync'd all");
64 // Fsync the parent directory on Unix.
65 #[cfg(not(target_os = "windows"))]
67 fs::rename(&tmp_filename, &filename_with_path)?;
68 let path = Path::new(&filename_with_path).parent().unwrap();
69 let dir_file = fs::OpenOptions::new().read(true).open(path)?;
70 unsafe { libc::fsync(dir_file.as_raw_fd()); }
72 // std::thread::sleep(std::time::Duration::new(60, 0));
73 #[cfg(target_os = "windows")]
75 println!("VMW: entries in dir:");
76 let dir_perms = fs::metadata(path.clone()).unwrap().permissions();
77 println!("VMW: dir perms: {:?}, readonly: {}", dir_perms, dir_perms.readonly());
78 let dir = PathBuf::from(path.clone());
79 for entry in fs::read_dir(dir).unwrap() {
80 let entry = entry.unwrap();
81 let metadata = entry.metadata().unwrap();
82 println!("VMW: entry in dir: {:?}, perms in entry: {:?}, readonly: {}", entry.path(), metadata.permissions(), metadata.permissions().readonly());
85 // let mut dir_perms = fs::metadata(path.clone()).unwrap().permissions();
86 // dir_perms.set_readonly(false);
87 // if let Ok(metadata) = fs::metadata(filename_with_path.clone()) {
88 // let mut perms = metadata.permissions();
89 // perms.set_readonly(false);
91 // // let mut perms = fs::metadata(filename_with_path.clone())?.permissions();
92 // let mut tmp_perms = fs::metadata(tmp_filename.clone())?.permissions();
93 // tmp_perms.set_readonly(false);
94 // println!("VMW: about to rename");
95 let src = PathBuf::from(tmp_filename.clone());
96 let dst = PathBuf::from(filename_with_path.clone());
97 // fs::rename(&tmp_filename.clone(), &filename_with_path.clone())?;
98 // call!(unsafe {winapi::um::winbase::MoveFileExW(
99 // path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(),
100 // winapi::um::winbase::MOVEFILE_WRITE_THROUGH | winapi::um::winbase::MOVEFILE_REPLACE_EXISTING
102 // let backup_filepath = PathBuf::from(format!("{}.backup", filename_with_path.clone()));
104 if Path::new(&filename_with_path.clone()).exists() {
105 unsafe {winapi::um::winbase::ReplaceFileW(
106 path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(), std::ptr::null(),
107 winapi::um::winbase::REPLACEFILE_IGNORE_MERGE_ERRORS, std::ptr::null_mut() as *mut winapi::ctypes::c_void, std::ptr::null_mut() as *mut winapi::ctypes::c_void
110 call!(unsafe {winapi::um::winbase::MoveFileExW(
111 path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(),
112 winapi::um::winbase::MOVEFILE_WRITE_THROUGH | winapi::um::winbase::MOVEFILE_REPLACE_EXISTING
115 let mut final_file = fs::File::open(filename_with_path.clone())?;
116 final_file.sync_all()?;
117 println!("VMW: renamed");
124 use super::{DiskWriteable, get_full_filepath, write_to_file};
129 struct TestWriteable{}
130 impl DiskWriteable for TestWriteable {
131 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), io::Error> {
132 writer.write_all(&[42; 1])
136 // Test that if the persister's path to channel data is read-only, writing
137 // data to it fails. Windows ignores the read-only flag for folders, so this
138 // test is Unix-only.
139 #[cfg(not(target_os = "windows"))]
141 fn test_readonly_dir() {
142 let test_writeable = TestWriteable{};
143 let filename = "test_readonly_dir_persister_filename".to_string();
144 let path = "test_readonly_dir_persister_dir";
145 fs::create_dir_all(path.to_string()).unwrap();
146 let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
147 perms.set_readonly(true);
148 fs::set_permissions(path.to_string(), perms).unwrap();
149 match write_to_file(path.to_string(), filename, &test_writeable) {
150 Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
151 _ => panic!("Unexpected error message")
155 // Test failure to rename in the process of atomically creating a channel
156 // monitor's file. We induce this failure by making the `tmp` file a
158 // Explanation: given "from" = the file being renamed, "to" = the
159 // renamee that already exists: Unix should fail because if "from" is a
160 // file, then "to" is also required to be a file.
162 #[cfg(not(target_os = "windows"))]
163 fn test_rename_failure() {
164 let test_writeable = TestWriteable{};
165 let filename = "test_rename_failure_filename";
166 let path = "test_rename_failure_dir";
167 // Create the channel data file and make it a directory.
168 fs::create_dir_all(get_full_filepath(path.to_string(), filename.to_string())).unwrap();
169 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
171 assert_eq!(e.kind(), io::ErrorKind::Other);
173 _ => panic!("Unexpected Ok(())")
175 fs::remove_dir_all(path).unwrap();
179 fn test_diskwriteable_failure() {
180 struct FailingWriteable {}
181 impl DiskWriteable for FailingWriteable {
182 fn write_to_file(&self, _writer: &mut fs::File) -> Result<(), std::io::Error> {
183 Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
187 let filename = "test_diskwriteable_failure";
188 let path = "test_diskwriteable_failure_dir";
189 let test_writeable = FailingWriteable{};
190 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
192 assert_eq!(e.kind(), std::io::ErrorKind::Other);
193 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
195 _ => panic!("unexpected result")
197 fs::remove_dir_all(path).unwrap();
200 // Test failure to create the temporary file in the persistence process.
201 // We induce this failure by having the temp file already exist and be a
204 fn test_tmp_file_creation_failure() {
205 let test_writeable = TestWriteable{};
206 let filename = "test_tmp_file_creation_failure_filename".to_string();
207 let path = "test_tmp_file_creation_failure_dir".to_string();
209 // Create the tmp file and make it a directory.
210 let tmp_path = get_full_filepath(path.clone(), format!("{}.tmp", filename.clone()));
211 fs::create_dir_all(tmp_path).unwrap();
212 match write_to_file(path, filename, &test_writeable) {
214 #[cfg(not(target_os = "windows"))]
215 assert_eq!(e.kind(), io::ErrorKind::Other);
216 #[cfg(target_os = "windows")]
217 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
219 _ => panic!("Unexpected error message")