2024-06-27 23:56:19 +02:00

112 lines
3.9 KiB
Python

import json
from pathlib import Path
import logging
from iottb import definitions
logger = logging.getLogger(__name__)
DB_NAME = 'iottb.db'
class IottbConfig:
""" Class to handle operations on the testbed configuration.
TODO: Add instead of overwrite Database locations when initializing if a location with valid db
exists.
"""
@staticmethod
def warn():
logger.warning(f'DatabaseLocations are DatabaseLocationMap in the class {__name__}')
def __init__(self, cfg_file=definitions.CFG_FILE_PATH):
logger.info('Initializing Config object')
IottbConfig.warn()
self.cfg_file = Path(cfg_file)
self.default_database = None
self.default_path = None
self.DatabaseLocationMap = {}
self.load_config()
def create_default_config(self):
"""Create default iottb config file."""
logger.info(f'Creating default config file at {self.cfg_file}')
self.default_database = DB_NAME
self.default_path = str(Path.home() / DB_NAME)
self.DatabaseLocationMap = {
DB_NAME: self.default_path
}
defaults = {
'DefaultDatabase': self.default_database,
'DefaultDatabasePath': self.default_path,
'DatabaseLocations': self.DatabaseLocationMap
}
try:
self.cfg_file.parent.mkdir(parents=True, exist_ok=True)
with self.cfg_file.open('w') as config_file:
json.dump(defaults, config_file, indent=4)
except IOError as e:
logger.error(f"Failed to create default configuration file at {self.cfg_file}: {e}")
raise RuntimeError(f"Failed to create configuration file: {e}") from e
def load_config(self):
"""Loads or creates default configuration from given file path."""
logger.info('Loading configuration file')
if not self.cfg_file.is_file():
logger.info('Config file does not exist.')
self.create_default_config()
else:
logger.info('Config file exists, opening.')
with self.cfg_file.open('r') as config_file:
data = json.load(config_file)
self.default_database = data.get('DefaultDatabase')
self.default_path = data.get('DefaultDatabasePath')
self.DatabaseLocationMap = data.get('DatabaseLocations', {})
def save_config(self):
"""Save the current configuration to the config file."""
data = {
'DefaultDatabase': self.default_database,
'DefaultDatabasePath': self.default_path,
'DatabaseLocations': self.DatabaseLocationMap
}
try:
with self.cfg_file.open('w') as config_file:
json.dump(data, config_file, indent=4)
except IOError as e:
logger.error(f"Failed to save configuration file at {self.cfg_file}: {e}")
raise RuntimeError(f"Failed to save configuration file: {e}") from e
def set_default_database(self, name, path):
"""Set the default database and its path."""
self.default_database = name
self.default_path = path
self.DatabaseLocationMap[name] = path
def get_database_location(self, name):
"""Get the location of a specific database."""
return self.DatabaseLocationMap.get(name)
def set_database_location(self, name, path):
"""Set the location for a database."""
self.DatabaseLocationMap[name] = path
def get_known_databases(self):
"""Get the set of known databases"""
logger.info(f'Getting known databases.')
return self.DatabaseLocationMap.keys()
def get_know_database_paths(self):
"""Get the paths of all known databases"""
logger.info(f'Getting known database paths.')
return self.DatabaseLocationMap.values()
# TODO: Know issue:
class Database:
pass