xdbm/src/storages.rs

245 lines
7.3 KiB
Rust
Raw Normal View History

//! Manipulates storages.
use crate::storages::directory::Directory;
use crate::storages::online_storage::OnlineStorage;
use crate::storages::physical_drive_partition::PhysicalDrivePartition;
2024-03-10 13:00:28 +09:00
use crate::{devices, storages};
use anyhow::{anyhow, Context, Result};
use clap::ValueEnum;
2024-03-10 13:00:28 +09:00
use core::panic;
use serde::{Deserialize, Serialize};
2024-03-10 13:00:28 +09:00
use std::ffi::OsString;
use std::{
collections::HashMap,
ffi,
fmt::{self, format},
fs, io, path, u64,
};
/// YAML file to store known storages..
pub const STORAGESFILE: &str = "storages.yml";
#[derive(ValueEnum, Clone, Copy, Debug)]
pub enum StorageType {
2024-03-10 13:00:28 +09:00
/// Physical storage
P,
/// Sub directory
S,
/// Online storage
O,
}
/// All storage types.
#[derive(Serialize, Deserialize, Debug)]
pub enum Storage {
PhysicalStorage(PhysicalDrivePartition),
2023-09-01 10:37:30 +09:00
SubDirectory(Directory),
Online(OnlineStorage),
}
2024-02-24 18:31:56 +09:00
impl Storage {
/// Full type name like "PhysicalStorage".
pub fn typename(&self) -> &str {
match self {
Self::PhysicalStorage(_) => "PhysicalStorage",
Self::SubDirectory(_) => "SubDirectory",
Self::Online(_) => "OnlineStorage",
}
}
/// Short type name with one letter like "P".
pub fn shorttypename(&self) -> &str {
match self {
Self::PhysicalStorage(_) => "P",
Self::SubDirectory(_) => "S",
Self::Online(_) => "O",
}
}
}
2023-08-29 21:33:46 +09:00
impl StorageExt for Storage {
fn name(&self) -> &String {
match self {
Self::PhysicalStorage(s) => s.name(),
2023-09-01 10:37:30 +09:00
Self::SubDirectory(s) => s.name(),
Self::Online(s) => s.name(),
}
}
2023-12-04 21:34:24 +09:00
2023-12-08 03:18:31 +09:00
fn local_info(&self, device: &devices::Device) -> Option<&local_info::LocalInfo> {
2023-12-05 03:24:49 +09:00
match self {
2023-12-08 03:18:31 +09:00
Self::PhysicalStorage(s) => s.local_info(device),
Self::SubDirectory(s) => s.local_info(device),
Self::Online(s) => s.local_info(device),
2023-12-05 03:24:49 +09:00
}
}
fn mount_path(
&self,
device: &devices::Device,
2024-03-10 13:00:28 +09:00
storages: &Storages,
2023-12-05 03:24:49 +09:00
) -> Result<path::PathBuf> {
match self {
Self::PhysicalStorage(s) => s.mount_path(&device, &storages),
Self::SubDirectory(s) => s.mount_path(&device, &storages),
Self::Online(s) => s.mount_path(&device, &storages),
2023-12-05 03:24:49 +09:00
}
}
2023-12-08 03:18:31 +09:00
fn bound_on_device(
&mut self,
alias: String,
mount_point: path::PathBuf,
device: &devices::Device,
) -> Result<()> {
match self {
Storage::PhysicalStorage(s) => s.bound_on_device(alias, mount_point, device),
Storage::SubDirectory(s) => s.bound_on_device(alias, mount_point, device),
Storage::Online(s) => s.bound_on_device(alias, mount_point, device),
}
}
2024-03-03 06:11:25 +09:00
fn capacity(&self) -> Option<u64> {
match self {
Storage::PhysicalStorage(s) => s.capacity(),
Storage::SubDirectory(s) => s.capacity(),
Storage::Online(s) => s.capacity(),
}
}
2024-03-10 13:00:28 +09:00
fn parent<'a>(&'a self, storages: &'a Storages) -> Result<Option<&Storage>> {
match self {
Storage::PhysicalStorage(s) => s.parent(storages),
Storage::SubDirectory(s) => s.parent(storages),
Storage::Online(s) => s.parent(storages),
}
}
}
2023-08-29 04:22:04 +09:00
impl fmt::Display for Storage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::PhysicalStorage(s) => s.fmt(f),
2023-09-01 10:37:30 +09:00
Self::SubDirectory(s) => s.fmt(f),
Self::Online(s) => s.fmt(f),
2023-08-29 04:22:04 +09:00
}
}
}
/// Trait to manipulate all `Storage`s (Enums).
pub trait StorageExt {
fn name(&self) -> &String;
2023-12-08 03:18:31 +09:00
2024-03-03 06:11:25 +09:00
/// Capacity in bytes.
/// Since [Directory] has no capacity information, it has `None`.
fn capacity(&self) -> Option<u64>;
2023-12-08 03:18:31 +09:00
/// Return `true` if `self` has local info on the `device`.
/// Used to check if the storage is bound on the `device`.
fn has_alias(&self, device: &devices::Device) -> bool {
self.local_info(device).is_some()
}
/// Get local info of `device`.
fn local_info(&self, device: &devices::Device) -> Option<&local_info::LocalInfo>;
/// Get mount path of `self` on `device`.
2024-03-03 06:11:25 +09:00
/// `storages` is a `HashMap` with key of storage name and value of the storage.
2023-12-05 03:24:49 +09:00
fn mount_path(
&self,
device: &devices::Device,
2024-03-10 13:00:28 +09:00
storages: &Storages,
2023-12-05 03:24:49 +09:00
) -> Result<path::PathBuf>;
2023-12-08 03:18:31 +09:00
/// Add local info of `device` to `self`.
fn bound_on_device(
&mut self,
alias: String,
mount_point: path::PathBuf,
device: &devices::Device,
) -> Result<()>;
2024-03-10 13:00:28 +09:00
/// Get parent
fn parent<'a>(&'a self, storages: &'a Storages) -> Result<Option<&Storage>>;
}
2023-09-01 10:37:30 +09:00
pub mod directory;
2023-12-04 21:34:24 +09:00
pub mod local_info;
pub mod online_storage;
pub mod physical_drive_partition;
2024-03-10 13:00:28 +09:00
#[derive(Debug, Serialize, Deserialize)]
pub struct Storages {
pub list: HashMap<String, Storage>,
}
impl Storages {
/// Construct empty [`Storages`]
pub fn new() -> Storages {
Storages {
list: HashMap::new(),
}
}
/// Get [`Storage`] with `name`.
pub fn get(&self, name: &String) -> Option<&Storage> {
self.list.get(name)
}
/// Add new [`Storage`] to [`Storages`]
/// New `storage` must has new unique name.
pub fn add(&mut self, storage: Storage) -> Result<()> {
if self.list.keys().any(|name| name == storage.name()) {
return Err(anyhow!(format!(
"Storage name {} already used",
storage.name()
)));
}
match self.list.insert(storage.name().to_string(), storage) {
Some(v) => {
error!("Inserted storage with existing name: {}", v);
panic!("unexpected behavior")
}
None => Ok(()),
}
}
/// Remove `storage` from [`Storages`].
/// Returns `Result` of removed [`Storage`].
pub fn remove(mut self, storage: Storage) -> Result<Option<Storage>> {
// dependency check
if self.list.iter().any(|(_k, v)| {
v.parent(&self)
.unwrap()
.is_some_and(|parent| parent.name() == storage.name())
}) {
return Err(anyhow!(
"Dependency error: storage {} has some children",
storage.name()
));
}
Ok(self.list.remove(storage.name()))
}
/// Load [`Storages`] from data in `config_dir`.
pub fn read(config_dir: &path::Path) -> Result<Self> {
let storages_file = config_dir.join(STORAGESFILE);
if !storages_file.exists() {
warn!("No storages file found.");
return Err(anyhow!("Couln't find {}", STORAGESFILE))
2024-03-10 13:00:28 +09:00
}
trace!("Reading {:?}", storages_file);
let f = fs::File::open(storages_file)?;
let reader = io::BufReader::new(f);
2024-03-10 13:00:28 +09:00
let yaml: Storages =
serde_yaml::from_reader(reader).context("Failed to parse storages.yml")?;
Ok(yaml)
}
2024-03-10 13:00:28 +09:00
pub fn write(self, config_dir: &path::Path) -> Result<()> {
let f = fs::File::create(config_dir.join(STORAGESFILE)).context("Failed to open storages file")?;
let writer = io::BufWriter::new(f);
serde_yaml::to_writer(writer, &self).context(format!("Failed to writing to {:?}", STORAGESFILE))
}
2023-09-01 10:37:30 +09:00
}