]> git.proxmox.com Git - proxmox-backup.git/blame - src/config/datastore.rs
use const api definitions
[proxmox-backup.git] / src / config / datastore.rs
CommitLineData
496a6784 1use std::collections::HashMap;
928650c4 2use std::io::Read;
678d72df 3
928650c4
WB
4use failure::*;
5use lazy_static::lazy_static;
678d72df 6
928650c4 7use proxmox::tools::{fs::file_set_contents, try_block};
678d72df 8
255f378a 9use crate::api_schema::{Schema, ObjectSchema, StringSchema};
928650c4 10use crate::section_config::{SectionConfig, SectionConfigData, SectionConfigPlugin};
678d72df 11
91640ab5 12lazy_static! {
678d72df
DM
13 static ref CONFIG: SectionConfig = init();
14}
15
255f378a
DM
16const DIR_NAME_SCHEMA: Schema = StringSchema::new("Directory name").schema();
17const DATASTORE_ID_SCHEMA: Schema = StringSchema::new("DataStore ID schema.")
18 .min_length(3)
19 .schema();
20const DATASTORE_PROPERTIES: ObjectSchema = ObjectSchema::new(
21 "DataStore properties",
22 &[
23 ("path", false, &DIR_NAME_SCHEMA)
24 ]
25);
678d72df 26
255f378a
DM
27fn init() -> SectionConfig {
28 let plugin = SectionConfigPlugin::new("datastore".to_string(), &DATASTORE_PROPERTIES);
29 let mut config = SectionConfig::new(&DATASTORE_ID_SCHEMA);
678d72df
DM
30 config.register_plugin(plugin);
31
32 config
33}
34
6ce50400 35const DATASTORE_CFG_FILENAME: &str = "/etc/proxmox-backup/datastore.cfg";
678d72df 36
567713b4 37pub fn config() -> Result<SectionConfigData, Error> {
678d72df 38 let mut contents = String::new();
9b50c161
DM
39
40 try_block!({
d11594db
DM
41 match std::fs::File::open(DATASTORE_CFG_FILENAME) {
42 Ok(mut file) => file.read_to_string(&mut contents),
43 Err(err) => {
44 if err.kind() == std::io::ErrorKind::NotFound {
45 contents = String::from("");
46 Ok(0)
47 } else {
48 Err(err)
49 }
50 }
51 }
91640ab5
WB
52 })
53 .map_err(|e| format_err!("unable to read '{}' - {}", DATASTORE_CFG_FILENAME, e))?;
678d72df 54
6ce50400 55 CONFIG.parse(DATASTORE_CFG_FILENAME, &contents)
678d72df
DM
56}
57
652c1190 58pub fn save_config(config: &SectionConfigData) -> Result<(), Error> {
652c1190
DM
59 let raw = CONFIG.write(DATASTORE_CFG_FILENAME, &config)?;
60
e18a6c9e 61 file_set_contents(DATASTORE_CFG_FILENAME, raw.as_bytes(), None)?;
652c1190
DM
62
63 Ok(())
64}
30d2e99c
DM
65
66// shell completion helper
496a6784 67pub fn complete_datastore_name(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
e3d40bb8 68 match config() {
91640ab5 69 Ok(data) => data.sections.iter().map(|(id, _)| id.to_string()).collect(),
30d2e99c 70 Err(_) => return vec![],
30d2e99c 71 }
30d2e99c 72}