1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340

use whoami;
use whoami::Platform::{Linux, Windows};
use serde::{Serialize, Deserialize};
use serde_yaml;
use std::fs::{
	copy,
	create_dir_all, 
	rename, 
	metadata,
	read_to_string, 
	OpenOptions,
	remove_file,
	remove_dir_all,
	canonicalize,
};
use std::collections::HashMap;
use std::env;
use std::io::Write;
use std::process;
use std::thread;
use std::time;
use std::mem::drop;
use std::vec::Vec;
use rand::random;
use sysinfo::{System, SystemExt};
use generic_error::{Result, GenErr, GenericError};
use fs_util::copy_dir;


#[cfg(test)]
mod tests;


#[derive(Serialize, Deserialize, Debug)]
pub struct State {
	name: String,
	path: String,
	identifier: String,
	lockfile_path: String,
	manifest_path: String,
	tmp_manifest_path: String,
	items: HashMap<String, String>,
	preserved: HashMap<String, String>,
}


enum WhoOwns {
	Me,
	Other,
	Nobody,
}


fn build_var_path(var: &str, sub_dir: &str) -> Result<String> {
	let s = env::var(var)?;
	Ok(format!("{}/{}", s, sub_dir))
}


fn get_storage_dir() -> Result<String> {
	match whoami::platform() {
		Linux => {
			build_var_path("HOME", ".local/rust_nonvolatile")
		},
		Windows => {
			build_var_path("appdata", "rust_nonvolatile")
		},
		_ => GenErr!("nonvolatile: {} not supported", whoami::platform()),
	}
}


fn get_state_id() -> String {
	format!("{}-{}", process::id(), random::<u32>())
}


fn match_state_id(my_id: &str, read_id: &str) -> WhoOwns {
	if my_id == read_id {
		return WhoOwns::Me;
	}
	let parts: Vec<&str> = read_id.split("-").collect();
	let parts = match parts.len() {
		2 => (parts[0], parts[1]),
		_ => return WhoOwns::Nobody,
	};
	let read_pid: u32 = match parts.0.parse() {
		Ok(pid) => pid,
		Err(_) => return WhoOwns::Nobody,
	};
	
	let mut system = System::new();
	system.refresh_processes();
	
	for (other_pid, _proc) in system.get_process_list() {
		if *other_pid as u32 == read_pid {
			return WhoOwns::Other;
		}
	}
	WhoOwns::Nobody
}


fn get_lock_acquired(lockfile_path: &str, state_id: &str) -> Result<bool> {
	let mdata = match metadata(lockfile_path) {
		Ok(mdata) => mdata,
		Err(_) => return Ok(false),
	};
	if !mdata.is_file() {
		return Ok(false);
	}
	let read_id = read_to_string(lockfile_path)?;
	match match_state_id(state_id, &read_id) {
		WhoOwns::Me => return Ok(true),
		WhoOwns::Other => return GenErr!("lockfile {} already owned by state {}", lockfile_path, read_id),
		WhoOwns::Nobody => return Ok(false),
	}
}


fn acquire_dir(lockfile_path: &str, state_id: &str) -> Result<()> {
	match get_lock_acquired(lockfile_path, state_id) {
		Ok(true) => return Ok(()),
		Ok(false) => (),
		Err(e) => {
			return Err(e)
		},
	};
	
	let _ = remove_file(lockfile_path);
	let mut file = OpenOptions::new().write(true).create(true).open(lockfile_path)?;
	write!(file, "{}", state_id)?;
	drop(file);
	
	thread::sleep(time::Duration::new(0, 1000));
	match get_lock_acquired(lockfile_path, state_id) {
		Ok(true) => Ok(()),
		Ok(false) => GenErr!("Nobody owns the lock, but I still managed to fail to acquire it!"),
		Err(e) => Err(e),
	}
}


impl State {

	fn write_manifest(&self) -> Result<()> {
		let mut file = OpenOptions::new().write(true).create(true).open(&self.tmp_manifest_path)?;
		let data = serde_yaml::to_vec(self)?;
		file.write(&data)?;
		rename(&self.tmp_manifest_path, &self.manifest_path)?;
		Ok(())
	}
	
	
	pub fn set<T>(&mut self, var: &str, value: T) -> Result<()> where T: Serialize {
		if self.preserved.contains_key(var) {
			return GenErr!("nonvolatile: can't set a variable with the same name as a preserved file/folder");
		}
		let _ = self.items.insert(String::from(var), serde_yaml::to_string(&value)?);
		self.write_manifest()
	}
	
	
	pub fn get<'de, T>(&self, var: &str) -> Option<T> where for<'a> T: Deserialize<'a> {
		let item = self.items.get(var)?;
		match serde_yaml::from_str(item) {
			Ok(obj) => Some(obj),
			Err(_) => None,
		}
	}
	
	
	pub fn delete(&mut self, name: &str) -> Result<()> {
		let _ = self.items.remove(name);
		if let Some(_) = self.preserved.remove(name) {
			let path = format!("{}/{}", &self.path, name);
			remove_file(&path)?;
			remove_dir_all(&path)?;
		}
		self.write_manifest()
	}
	
	
	pub fn new_from(name: &str, path: &str) -> Result<State> {
		let path = format!("{}/{}", path, name);
		create_dir_all(&path)?;
		
		let items: HashMap<String, String> = HashMap::new();
		let preserved: HashMap<String, String> = HashMap::new();
		
		let state_id = get_state_id();
		let lockfile_path = format!("{}/{}", &path, "~rust_nonvolatile.lock");
		
		acquire_dir(&lockfile_path, &state_id)?;
		
		let state = State {
			name: String::from(name),
			path: path.clone(),
			identifier: state_id,
			lockfile_path: lockfile_path.clone(),
			manifest_path: format!("{}/{}", &path, ".manifest"),
			tmp_manifest_path: format!("{}/{}", &path, ".manifest_tmp"),
			items: items,
			preserved: preserved,
		};
		
		match state.write_manifest() {
			Ok(_) => Ok(state),
			Err(e) => {
				let _ = remove_file(&lockfile_path);
				Err(e)
			}
		}
	}
	
	
	pub fn new(name: &str) -> Result<State> {
		let dir = get_storage_dir()?;
		State::new_from(name, &dir)
	}
	
	
	pub fn load_from(name: &str, path: &str) -> Result<State> {
		let path = format!("{}/{}", path, name);
		let manifest_path = format!("{}/{}", &path, ".manifest");
		
		let state_id = get_state_id();
		let lockfile_path = format!("{}/{}", &path, "~rust_nonvolatile.lock");
		
		acquire_dir(&lockfile_path, &state_id)?;
		
		let data = match read_to_string(&manifest_path) {
			Ok(data) => data,
			Err(e) => {
				let _ = remove_file(&lockfile_path);
				return Err(GenericError::from(e));
			}
		};
		
		let mut state: State = match serde_yaml::from_str(&data) {
			Ok(state) => state,
			Err(e) => {
				let _ = remove_file(&lockfile_path);
				return Err(GenericError::from(e));
			}
		};
		
		state.identifier = state_id;
		state.lockfile_path = lockfile_path;
		
		Ok(state)
	}
	
	
	pub fn load(name: &str) -> Result<State> {
		let dir = get_storage_dir()?;		
		State::load_from(name, &dir)
	}
	
	
	pub fn load_else_create(name: &str) -> Result<State> {
		State::load(name).or_else(|_| State::new(name))
	}
	
	
	pub fn load_else_create_from(name: &str, path: &str) -> Result<State> {
		State::load_from(name, path).or_else(|_| State::new_from(name, path))
	}
	
	
	pub fn destroy_state(name: &str) {
		if let Ok(dir) = get_storage_dir() {
			let path = format!("{}/{}", dir, name);
			let _ = remove_dir_all(path);
		} 
	}
	
	
	pub fn has(&self, item: &str) -> bool {
		self.items.contains_key(item) || self.preserved.contains_key(item)
	}
	
	
	fn _preserve(&mut self, path: &str, name: &str) -> Result<()> {
		if self.items.contains_key(name) {
			return GenErr!("nonvolatile: can't preserve a file with the same name as a set variable");
		}
		let path = match canonicalize(path)?.to_str() {
			Some(p) => String::from(p),
			None => return GenErr!("nonvolatile preserve: failed to canonicalize path"),
		};
		let tmp_name = format!("tmp_{}", name);
		let tmp_dest = format!("{}/{}", &self.path, &tmp_name);
		let dest = format!("{}/{}", &self.path, name);
		if metadata(&path)?.is_dir() {
			copy_dir(&path, &tmp_dest)?;
		}
		else {
			copy(&path, &tmp_dest)?;
		}
		
		let _ = self.preserved.insert(String::from(name), String::from(path));
		self.write_manifest()?;
		
		rename(tmp_dest, dest)?;
		Ok(())
	}


	fn _restore(&self, name: &str) -> Result<()> {
		let path = match self.preserved.get(name) {
			Some(p) => p,
			None => return GenErr!("Nothing by the name '{}' has been preserved", name),
		};
		self._restore_to(name, path)
	}
	
	
	fn _restore_to(&self, name: &str, path: &str) -> Result<()> {
		if !self.preserved.contains_key(name) {
			return GenErr!("Nothing by the name '{}' has been preserved", name);
		}
		let preserved_path = format!("{}/{}", &self.path, name);
		if metadata(&preserved_path)?.is_dir() {
			copy_dir(&preserved_path, path)?;
		}
		else {
			copy(&preserved_path, path)?;
		}
		Ok(())
	}
}


impl Drop for State {
	fn drop(&mut self) {
		let _ = remove_file(&self.lockfile_path);
	}
}