2 #[cfg(target_os = "windows")]
4 #[cfg(target_os = "windows")]
5 use std::os::windows::io::IntoRawHandle;
8 use std::path::{Path, PathBuf};
9 #[cfg(target_os = "windows")]
12 std::os::windows::ffi::OsStrExt
14 #[cfg(not(target_os = "windows"))]
15 use std::os::unix::io::AsRawFd;
17 pub(crate) trait DiskWriteable {
18 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error>;
21 pub(crate) fn get_full_filepath(filepath: String, filename: String) -> String {
22 let mut path = PathBuf::from(filepath);
24 path.to_str().unwrap().to_string()
26 #[cfg(target_os = "windows")]
32 return Err(std::io::Error::last_os_error())
37 #[cfg(target_os = "windows")]
38 fn path_to_windows_str<T: AsRef<OsStr>>(x: T) -> Vec<winapi::shared::ntdef::WCHAR> {
39 x.as_ref().encode_wide().chain(Some(0)).collect()
42 #[allow(bare_trait_objects)]
43 pub(crate) fn write_to_file<D: DiskWriteable>(path: String, filename: String, data: &D) -> std::io::Result<()> {
44 println!("VMW: in write_to_file, filename: {}", filename);
45 fs::create_dir(path.clone())?;
46 /*call!(unsafe {winapi::um::winbase::MoveFileExW(
47 path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(),
48 winapi::um::winbase::MOVEFILE_WRITE_THROUGH | winapi::um::winbase::MOVEFILE_REPLACE_EXISTING
51 // Do a crazy dance with lots of fsync()s to be overly cautious here...
52 // We never want to end up in a state where we've lost the old data, or end up using the
53 // old data on power loss after we've returned.
54 // The way to atomically write a file on Unix platforms is:
55 // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
56 let filename_with_path = get_full_filepath(path.clone(), filename);
57 let tmp_filename = format!("{}.tmp", filename_with_path);
60 // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
61 // rust stdlib 1.36 or higher.
62 println!("VMW: about to create file");
63 let mut f = fs::File::create(&tmp_filename)?;
64 println!("VMW: created file");
65 data.write_to_file(&mut f)?;
66 println!("VMW: about to sync all");
68 println!("VMW: sync'd all");
70 // Fsync the parent directory on Unix.
71 #[cfg(not(target_os = "windows"))]
73 fs::rename(&tmp_filename, &filename_with_path)?;
74 let path = Path::new(&filename_with_path).parent().unwrap();
75 let dir_file = fs::OpenOptions::new().read(true).open(path)?;
76 unsafe { libc::fsync(dir_file.as_raw_fd()); }
78 // std::thread::sleep(std::time::Duration::new(60, 0));
79 #[cfg(target_os = "windows")]
81 println!("VMW: entries in dir:");
82 let dir_perms = fs::metadata(path.clone()).unwrap().permissions();
83 println!("VMW: dir perms: {:?}, readonly: {}", dir_perms, dir_perms.readonly());
84 let dir = PathBuf::from(path.clone());
85 for entry in fs::read_dir(dir).unwrap() {
86 let entry = entry.unwrap();
87 let metadata = entry.metadata().unwrap();
88 println!("VMW: entry in dir: {:?}, perms in entry: {:?}, readonly: {}", entry.path(), metadata.permissions(), metadata.permissions().readonly());
91 // let mut dir_perms = fs::metadata(path.clone()).unwrap().permissions();
92 // dir_perms.set_readonly(false);
93 // if let Ok(metadata) = fs::metadata(filename_with_path.clone()) {
94 // let mut perms = metadata.permissions();
95 // perms.set_readonly(false);
97 // // let mut perms = fs::metadata(filename_with_path.clone())?.permissions();
98 // let mut tmp_perms = fs::metadata(tmp_filename.clone())?.permissions();
99 // tmp_perms.set_readonly(false);
100 // println!("VMW: about to rename");
101 let src = PathBuf::from(tmp_filename.clone());
102 let dst = PathBuf::from(filename_with_path.clone());
103 // fs::rename(&tmp_filename.clone(), &filename_with_path.clone())?;
104 // call!(unsafe {winapi::um::winbase::MoveFileExW(
105 // path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(),
106 // winapi::um::winbase::MOVEFILE_WRITE_THROUGH | winapi::um::winbase::MOVEFILE_REPLACE_EXISTING
108 // let backup_filepath = PathBuf::from(format!("{}.backup", filename_with_path.clone()));
110 /*if Path::new(&filename_with_path.clone()).exists() {
111 unsafe {winapi::um::winbase::ReplaceFileW(
112 path_to_windows_str(dst).as_ptr(), path_to_windows_str(src).as_ptr(), std::ptr::null(),
113 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
116 call!(unsafe {winapi::um::winbase::MoveFileExW(
117 path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(),
118 winapi::um::winbase::MOVEFILE_WRITE_THROUGH | winapi::um::winbase::MOVEFILE_REPLACE_EXISTING
121 let mut final_file = fs::File::open(filename_with_path.clone())?;
122 let file_handle = final_file.into_raw_handle();
123 unsafe{winapi::um::fileapi::FlushFileBuffers(file_handle);}
124 // final_file.sync_all()?;
125 println!("VMW: renamed");
132 use super::{DiskWriteable, get_full_filepath, write_to_file};
137 struct TestWriteable{}
138 impl DiskWriteable for TestWriteable {
139 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), io::Error> {
140 writer.write_all(&[42; 1])
144 // Test that if the persister's path to channel data is read-only, writing
145 // data to it fails. Windows ignores the read-only flag for folders, so this
146 // test is Unix-only.
147 #[cfg(not(target_os = "windows"))]
149 fn test_readonly_dir() {
150 let test_writeable = TestWriteable{};
151 let filename = "test_readonly_dir_persister_filename".to_string();
152 let path = "test_readonly_dir_persister_dir";
153 fs::create_dir_all(path.to_string()).unwrap();
154 let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
155 perms.set_readonly(true);
156 fs::set_permissions(path.to_string(), perms).unwrap();
157 match write_to_file(path.to_string(), filename, &test_writeable) {
158 Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
159 _ => panic!("Unexpected error message")
163 // Test failure to rename in the process of atomically creating a channel
164 // monitor's file. We induce this failure by making the `tmp` file a
166 // Explanation: given "from" = the file being renamed, "to" = the
167 // renamee that already exists: Unix should fail because if "from" is a
168 // file, then "to" is also required to be a file.
170 #[cfg(not(target_os = "windows"))]
171 fn test_rename_failure() {
172 let test_writeable = TestWriteable{};
173 let filename = "test_rename_failure_filename";
174 let path = "test_rename_failure_dir";
175 // Create the channel data file and make it a directory.
176 fs::create_dir_all(get_full_filepath(path.to_string(), filename.to_string())).unwrap();
177 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
179 assert_eq!(e.kind(), io::ErrorKind::Other);
181 _ => panic!("Unexpected Ok(())")
183 fs::remove_dir_all(path).unwrap();
187 fn test_diskwriteable_failure() {
188 struct FailingWriteable {}
189 impl DiskWriteable for FailingWriteable {
190 fn write_to_file(&self, _writer: &mut fs::File) -> Result<(), std::io::Error> {
191 Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
195 let filename = "test_diskwriteable_failure";
196 let path = "test_diskwriteable_failure_dir";
197 let test_writeable = FailingWriteable{};
198 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
200 assert_eq!(e.kind(), std::io::ErrorKind::Other);
201 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
203 _ => panic!("unexpected result")
205 fs::remove_dir_all(path).unwrap();
208 // Test failure to create the temporary file in the persistence process.
209 // We induce this failure by having the temp file already exist and be a
212 fn test_tmp_file_creation_failure() {
213 let test_writeable = TestWriteable{};
214 let filename = "test_tmp_file_creation_failure_filename".to_string();
215 let path = "test_tmp_file_creation_failure_dir".to_string();
217 // Create the tmp file and make it a directory.
218 let tmp_path = get_full_filepath(path.clone(), format!("{}.tmp", filename.clone()));
219 fs::create_dir_all(tmp_path).unwrap();
220 match write_to_file(path, filename, &test_writeable) {
222 #[cfg(not(target_os = "windows"))]
223 assert_eq!(e.kind(), io::ErrorKind::Other);
224 #[cfg(target_os = "windows")]
225 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
227 _ => panic!("Unexpected error message")