2023-06-17 20:07:50 +03:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import tomllib
|
2023-07-22 23:59:49 +03:00
|
|
|
from pathlib import Path
|
|
|
|
from collections import UserDict
|
2023-06-17 20:07:50 +03:00
|
|
|
|
2023-07-22 23:59:49 +03:00
|
|
|
from .exceptions import ConfigLoadError
|
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-07-22 23:59:49 +03:00
|
|
|
class ConfigLoader(UserDict):
|
|
|
|
def __init__(self, file: Path | None = None):
|
|
|
|
if file is None:
|
|
|
|
file = NODEAGENT_CONFIG_FILE or NODEAGENT_DEFAULT_CONFIG_FILE
|
|
|
|
self.file = Path(file)
|
|
|
|
self.data = self._load()
|
2023-06-17 20:07:50 +03:00
|
|
|
|
2023-07-22 23:59:49 +03:00
|
|
|
def _load(self):
|
|
|
|
try:
|
|
|
|
with open(self.file, 'rb') as config:
|
|
|
|
return tomllib.load(config)
|
|
|
|
# todo: schema validation
|
|
|
|
except (OSError, ValueError) as readerr:
|
|
|
|
raise ConfigLoadError('Cannot read config file: %s: %s', (self.file, readerr)) from readerr
|
|
|
|
except tomllib.TOMLDecodeError as tomlerr:
|
|
|
|
raise ConfigLoadError('Bad TOML syntax in config file: %s: %s', (self.file, tomlerr)) from tomlerr
|