2020-04-09 21:45:07 +00:00
|
|
|
use std::path::PathBuf;
|
2020-04-10 20:01:48 +00:00
|
|
|
use std::sync::Arc;
|
2020-04-09 21:45:07 +00:00
|
|
|
|
|
|
|
use tokio::fs;
|
|
|
|
use tokio::prelude::*;
|
|
|
|
|
2020-04-10 20:01:48 +00:00
|
|
|
use crate::data::*;
|
2020-04-09 21:45:07 +00:00
|
|
|
use crate::error::Error;
|
|
|
|
use crate::proto::*;
|
2020-04-10 20:01:48 +00:00
|
|
|
use crate::server::Garage;
|
2020-04-09 21:45:07 +00:00
|
|
|
|
|
|
|
fn block_dir(garage: &Garage, hash: &Hash) -> PathBuf {
|
|
|
|
let mut path = garage.system.config.data_dir.clone();
|
|
|
|
path.push(hex::encode(&hash.as_slice()[0..1]));
|
|
|
|
path.push(hex::encode(&hash.as_slice()[1..2]));
|
|
|
|
path
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn write_block(garage: Arc<Garage>, hash: &Hash, data: &[u8]) -> Result<Message, Error> {
|
|
|
|
garage.fs_lock.lock().await;
|
|
|
|
|
|
|
|
let mut path = block_dir(&garage, hash);
|
|
|
|
fs::create_dir_all(&path).await?;
|
|
|
|
|
|
|
|
path.push(hex::encode(hash));
|
|
|
|
if fs::metadata(&path).await.is_ok() {
|
2020-04-10 20:01:48 +00:00
|
|
|
return Ok(Message::Ok);
|
2020-04-09 21:45:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let mut f = fs::File::create(path).await?;
|
|
|
|
f.write_all(data).await?;
|
|
|
|
drop(f);
|
|
|
|
|
|
|
|
Ok(Message::Ok)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn read_block(garage: Arc<Garage>, hash: &Hash) -> Result<Message, Error> {
|
|
|
|
let mut path = block_dir(&garage, hash);
|
|
|
|
path.push(hex::encode(hash));
|
|
|
|
|
|
|
|
let mut f = fs::File::open(path).await?;
|
|
|
|
let mut data = vec![];
|
|
|
|
f.read_to_end(&mut data).await?;
|
|
|
|
|
2020-04-10 20:01:48 +00:00
|
|
|
Ok(Message::PutBlock(PutBlockMessage {
|
2020-04-09 21:45:07 +00:00
|
|
|
hash: hash.clone(),
|
|
|
|
data,
|
|
|
|
}))
|
|
|
|
}
|