python-compute/node_agent/config.py

39 lines
1.2 KiB
Python
Raw Normal View History

2023-06-17 20:07:50 +03:00
import os
import tomllib
2023-07-22 23:59:49 +03:00
from collections import UserDict
2023-08-24 22:36:12 +03:00
from pathlib import Path
2023-06-17 20:07:50 +03:00
2023-07-22 23:59:49 +03:00
NODEAGENT_CONFIG_FILE = os.getenv('NODEAGENT_CONFIG_FILE')
NODEAGENT_DEFAULT_CONFIG_FILE = '/etc/node-agent/config.toml'
2023-06-17 20:07:50 +03:00
2023-08-27 23:42:56 +03:00
class ConfigLoaderError(Exception):
2023-08-24 22:36:12 +03:00
"""Bad config file syntax, unreachable file or bad config schema."""
2023-07-29 15:35:36 +03:00
2023-07-22 23:59:49 +03:00
class ConfigLoader(UserDict):
2023-08-24 22:36:12 +03:00
2023-07-22 23:59:49 +03:00
def __init__(self, file: Path | None = None):
if file is None:
file = NODEAGENT_CONFIG_FILE or NODEAGENT_DEFAULT_CONFIG_FILE
self.file = Path(file)
2023-08-24 22:36:12 +03:00
super().__init__(self._load())
2023-07-28 01:01:32 +03:00
# todo: load deafult configuration
2023-06-17 20:07:50 +03:00
2023-08-31 20:37:41 +03:00
def _load(self) -> dict:
2023-07-22 23:59:49 +03:00
try:
with open(self.file, 'rb') as config:
return tomllib.load(config)
2023-07-28 01:01:32 +03:00
# todo: config schema validation
2023-07-22 23:59:49 +03:00
except tomllib.TOMLDecodeError as tomlerr:
2023-08-27 23:42:56 +03:00
raise ConfigLoaderError(
2023-08-24 22:36:12 +03:00
f'Bad TOML syntax in config file: {self.file}: {tomlerr}'
) from tomlerr
2023-07-29 14:29:37 +03:00
except (OSError, ValueError) as readerr:
2023-08-27 23:42:56 +03:00
raise ConfigLoaderError(
2023-08-24 22:36:12 +03:00
f'Cannot read config file: {self.file}: {readerr}') from readerr
2023-08-31 20:37:41 +03:00
def reload(self) -> None:
2023-08-24 22:36:12 +03:00
self.data = self._load()