imag/src/storage/backend.rs

312 lines
9.8 KiB
Rust
Raw Normal View History

2015-11-10 18:27:54 +00:00
use std::error::Error;
use std::fmt::Display;
2015-11-10 18:51:43 +00:00
use std::fmt::Formatter;
use std::fmt::Result as FMTResult;
use std::path::Path;
2015-11-23 17:22:02 +00:00
use std::path::PathBuf;
use std::vec::Vec;
use std::fs::File as FSFile;
use std::fs::create_dir_all;
2015-12-02 10:49:11 +00:00
use std::fs::remove_file;
use std::io::Read;
2015-11-24 09:48:30 +00:00
use std::io::Write;
2015-12-02 10:41:49 +00:00
use std::vec::IntoIter;
use glob::glob;
2015-11-23 17:22:02 +00:00
use glob::Paths;
2015-11-10 18:27:54 +00:00
2015-11-23 17:42:55 +00:00
use storage::file::File;
use storage::file_id::*;
2015-11-24 09:27:42 +00:00
use storage::parser::{FileHeaderParser, Parser, ParserError};
2015-11-10 18:27:54 +00:00
2015-11-23 18:54:08 +00:00
use module::Module;
use runtime::Runtime;
pub type BackendOperationResult<T = ()> = Result<T, StorageBackendError>;
2015-11-10 18:27:54 +00:00
2015-11-23 17:45:31 +00:00
pub struct StorageBackend {
2015-11-10 18:27:54 +00:00
basepath: String,
storepath: String,
2015-11-10 18:27:54 +00:00
}
2015-11-23 17:45:31 +00:00
impl StorageBackend {
2015-11-10 18:27:54 +00:00
pub fn new(rt: &Runtime) -> BackendOperationResult<StorageBackend> {
let storepath = rt.get_rtp() + "/store/";
debug!("Trying to create {}", storepath);
create_dir_all(&storepath).and_then(|_| {
debug!("Creating succeeded, constructing backend instance");
Ok(StorageBackend {
basepath: rt.get_rtp(),
storepath: storepath.clone(),
})
}).or_else(|e| {
debug!("Creating failed, constructing error instance");
let mut serr = StorageBackendError::build(
"create_dir_all()",
"Could not create store directories",
Some(storepath)
);
serr.caused_by = Some(Box::new(e));
Err(serr)
})
2015-11-10 18:27:54 +00:00
}
2015-11-23 18:54:08 +00:00
fn build<M: Module>(rt: &Runtime, m: &M) -> StorageBackend {
let path = rt.get_rtp() + m.name() + "/store";
// TODO: Don't use "/store" but value from configuration
debug!("Building StorageBackend for {}", path);
2015-11-23 18:54:08 +00:00
StorageBackend::new(path)
}
fn get_file_ids(&self, m: &Module) -> Option<Vec<FileID>> {
let list = glob(&self.prefix_of_files_for_module(m)[..]);
2015-11-23 17:22:02 +00:00
if let Ok(globlist) = list {
let mut v = vec![];
for entry in globlist {
if let Ok(path) = entry {
debug!(" - File: {:?}", path);
2015-11-23 17:42:55 +00:00
v.push(from_pathbuf(&path));
2015-11-23 17:22:02 +00:00
} else {
// Entry is not a path
}
}
Some(v)
} else {
None
}
2015-11-10 18:27:54 +00:00
}
2015-12-02 10:41:49 +00:00
pub fn iter_ids(&self, m: &Module) -> Option<IntoIter<FileID>>
{
glob(&self.prefix_of_files_for_module(m)[..]).and_then(|globlist| {
let v = globlist.filter_map(Result::ok)
.map(|pbuf| from_pathbuf(&pbuf))
.collect::<Vec<FileID>>()
.into_iter();
Ok(v)
}).ok()
}
2015-12-02 10:42:06 +00:00
pub fn iter_files<'a, HP>(&self, m: &'a Module, p: &Parser<HP>)
-> Option<IntoIter<File<'a>>>
where HP: FileHeaderParser
{
self.iter_ids(m).and_then(|ids| {
Some(ids.filter_map(|id| self.get_file_by_id(m, &id, p))
.collect::<Vec<File>>()
.into_iter())
})
}
2015-11-23 18:25:27 +00:00
/*
* Write a file to disk.
*
* The file is moved to this function as the file won't be edited afterwards
*/
2015-12-02 10:43:11 +00:00
pub fn put_file<HP>(&self, f: File, p: &Parser<HP>) -> BackendOperationResult
where HP: FileHeaderParser
2015-11-24 09:27:42 +00:00
{
2015-12-02 10:43:11 +00:00
let written = write_with_parser(&f, p);
if written.is_err() { return Err(written.err().unwrap()); }
let string = written.unwrap();
let path = self.build_filepath(&f);
debug!("Writing file: {}", path);
debug!(" string: {}", string);
FSFile::create(&path).map(|mut file| {
debug!("Created file at '{}'", path);
file.write_all(&string.clone().into_bytes())
.map_err(|ioerr| {
debug!("Could not write file");
let mut err = StorageBackendError::build(
"File::write_all()",
"Could not write out File contents",
None
);
err.caused_by = Some(Box::new(ioerr));
err
})
}).map_err(|writeerr| {
debug!("Could not create file at '{}'", path);
let mut err = StorageBackendError::build(
"File::create()",
"Creating file on disk failed",
None
);
err.caused_by = Some(Box::new(writeerr));
err
}).and(Ok(()))
2015-11-10 18:27:54 +00:00
}
2015-11-23 18:25:27 +00:00
/*
* Update a file. We have the UUID and can find the file on FS with it and
* then replace its contents with the contents of the passed file object
*/
pub fn update_file<HP>(&self, f: File, p: &Parser<HP>) -> BackendOperationResult
where HP: FileHeaderParser
2015-11-24 09:48:30 +00:00
{
let contents = write_with_parser(&f, p);
if contents.is_err() { return Err(contents.err().unwrap()); }
let string = contents.unwrap();
2015-11-24 09:48:30 +00:00
let path = self.build_filepath(&f);
debug!("Writing file: {}", path);
debug!(" string: {}", string);
2015-11-24 09:48:30 +00:00
FSFile::open(&path).map(|mut file| {
debug!("Open file at '{}'", path);
file.write_all(&string.clone().into_bytes())
.map_err(|ioerr| {
debug!("Could not write file");
let mut err = StorageBackendError::build(
"File::write()",
"Tried to write contents of this file, though operation did not succeed",
Some(string)
);
err.caused_by = Some(Box::new(ioerr));
err
})
}).map_err(|writeerr| {
debug!("Could not write file at '{}'", path);
let mut err = StorageBackendError::build(
"File::open()",
"Tried to update contents of this file, though file doesn't exist",
None
);
err.caused_by = Some(Box::new(writeerr));
err
}).and(Ok(()))
2015-11-10 18:27:54 +00:00
}
2015-11-23 18:25:27 +00:00
/*
* Find a file by its ID and return it if found. Return nothing if not
* found, of course.
*
* TODO: Needs refactoring, as there might be an error when reading from
* disk OR the id just does not exist.
*/
pub fn get_file_by_id<'a, HP>(&self, m: &'a Module, id: FileID, p: &Parser<HP>) -> Option<File<'a>>
where HP: FileHeaderParser
2015-11-24 09:59:30 +00:00
{
debug!("Searching for file with id '{}'", id);
if let Ok(mut fs) = FSFile::open(self.build_filepath_with_id(m, id.clone())) {
2015-11-24 09:59:30 +00:00
let mut s = String::new();
fs.read_to_string(&mut s);
debug!("Success reading file with id '{}'", id);
debug!("Parsing to internal structure now");
p.read(s).and_then(|(h, d)| Ok(File::from_parser_result(m, id.clone(), h, d))).ok()
2015-11-24 09:59:30 +00:00
} else {
debug!("No file with id '{}'", id);
2015-11-24 09:59:30 +00:00
None
}
}
pub fn remove_file(&self, m: &Module, file: File, checked: bool) -> BackendOperationResult {
if checked {
error!("Checked remove not implemented yet. I will crash now");
unimplemented!()
}
debug!("Doing unchecked remove");
info!("Going to remove file: {}", file);
let fp = self.build_filepath(&file);
remove_file(fp).map_err(|e| {
let mut serr = StorageBackendError::build(
"remove_file()",
"File removal failed",
Some(format!("{}", file))
);
serr.caused_by = Some(Box::new(e));
serr
})
}
2015-11-24 09:30:52 +00:00
fn build_filepath(&self, f: &File) -> String {
self.build_filepath_with_id(f.owner(), f.id())
}
fn build_filepath_with_id(&self, owner: &Module, id: FileID) -> String {
debug!("Building filepath with id");
debug!(" basepath: '{}'", self.basepath);
2015-11-28 12:03:54 +00:00
debug!(" storepath: '{}'", self.storepath);
debug!(" id : '{}'", id);
2015-11-28 12:03:54 +00:00
self.storepath.clone() + owner.name() + "-" + &id[..] + ".imag"
2015-11-24 09:30:52 +00:00
}
2015-11-10 18:27:54 +00:00
}
#[derive(Debug)]
2015-11-10 18:51:43 +00:00
pub struct StorageBackendError {
pub action: String, // The file system action in words
pub desc: String, // A short description
pub data_dump: Option<String>, // Data dump, if any
pub caused_by: Option<Box<Error>>, // caused from this error
2015-11-10 18:51:43 +00:00
}
2015-11-10 18:27:54 +00:00
impl StorageBackendError {
fn new(action: String,
desc : String,
2015-11-10 18:51:43 +00:00
data : Option<String>) -> StorageBackendError
{
StorageBackendError {
action: action,
desc: desc,
data_dump: data,
caused_by: None,
2015-11-10 18:51:43 +00:00
}
}
fn build(action: &'static str,
desc: &'static str,
data : Option<String>) -> StorageBackendError
{
StorageBackendError {
action: String::from(action),
desc: String::from(desc),
dataDump: data,
caused_by: None,
}
}
2015-11-10 18:27:54 +00:00
}
impl Error for StorageBackendError {
2015-11-10 18:51:43 +00:00
fn description(&self) -> &str {
&self.desc[..]
}
fn cause(&self) -> Option<&Error> {
self.caused_by.as_ref().map(|e| &**e)
2015-11-10 18:51:43 +00:00
}
2015-11-10 18:27:54 +00:00
}
impl Display for StorageBackendError {
2015-11-10 18:51:43 +00:00
fn fmt(&self, f: &mut Formatter) -> FMTResult {
write!(f, "StorageBackendError[{}]: {}",
self.action, self.desc)
2015-11-10 18:51:43 +00:00
}
2015-11-10 18:27:54 +00:00
}
2015-12-02 10:44:31 +00:00
fn write_with_parser<'a, HP>(f: &File, p: &Parser<HP>) -> Result<String, StorageBackendError>
where HP: FileHeaderParser
{
p.write(f.contents())
.or_else(|err| {
let mut serr = StorageBackendError::build(
"Parser::write()",
"Cannot translate internal representation of file contents into on-disk representation",
None
);
serr.caused_by = Some(Box::new(err));
Err(serr)
})
}