pybackive/backive/config/config.py

96 lines
2.7 KiB
Python
Raw Normal View History

2019-01-06 17:34:02 +01:00
import os
import pwd
from ruamel.yaml import YAML
import logging
2019-02-22 21:26:01 +01:00
import jsonschema
2019-01-06 17:34:02 +01:00
2019-01-06 21:29:21 +01:00
from backive.core.backup import Backup
from backive.core.device import Device
2019-01-06 17:34:02 +01:00
class Config:
__shared_state = dict
2019-01-06 17:34:02 +01:00
def __init__(self):
self.__dict__ = self.__shared_state
2019-01-06 21:29:21 +01:00
self._config = dict()
2019-02-22 21:26:01 +01:00
self._schema = dict()
self._backups = list()
self._devices = list()
2019-02-22 21:26:01 +01:00
file_path = os.path.realpath(__file__)
schema_path = os.path.join(
os.path.dirname(
file_path
),
"schema.yml"
)
2019-02-22 21:26:01 +01:00
with open(schema_path, "r") as stream:
self._schema = YAML().load(stream)
2019-01-06 17:34:02 +01:00
def find_config(self):
# who are we?
uid = os.getuid()
# name?
user = pwd.getpwuid(uid).pw_name
try:
if uid == 0:
2019-01-06 21:29:21 +01:00
config_file = "/etc/backive.yml"
2019-01-06 17:34:02 +01:00
else:
2019-05-03 21:36:44 +02:00
config_file = os.path.join(
os.path.expanduser("~"),
".config",
"backive",
"backive.yml"
)
2019-01-06 17:34:02 +01:00
with open(config_file, "r") as cfg:
self._config = YAML().load(cfg)
2019-02-22 21:26:01 +01:00
jsonschema.validate(self._config, self._schema)
2019-01-06 17:34:02 +01:00
except Exception as e:
logging.error(e)
2019-01-06 21:29:21 +01:00
def get_devices(self):
if self._config.get("devices", None) and not self._devices:
2019-01-06 21:29:21 +01:00
data = self._config.get("devices")
for device in data:
self._devices.append(
2019-01-06 21:29:21 +01:00
Device.instance(
device,
data.get(device)
)
)
return self._devices
2019-01-06 21:29:21 +01:00
def get_backups(self):
if self._config.get("backups", None) and not self._backups:
2019-01-06 21:29:21 +01:00
data = self._config.get("backups")
for name in data:
self._backups.append(
2019-01-06 21:29:21 +01:00
Backup.instance(
name,
data.get(name)
)
)
return self._backups
def get_backups_by_device(self, uuid):
name = None
for k, v in self._config.get("devices").items():
if v.get("uuid") == uuid:
name = k
if name:
return self.get_device_backups(name)
return None
2019-01-06 21:29:21 +01:00
def get_device_backups(self, name):
backups = list()
2019-02-22 21:26:01 +01:00
for backup in self.get_backups():
if backup.target == name:
2019-02-22 21:26:01 +01:00
backups.append(backup)
return backups
def get_preferences(self):
if self._config.get("preferences", None):
return self._config.get("preferences")
2019-01-06 21:29:21 +01:00
return {}