2020-02-16 20:19:03 +01:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
import sys
|
2020-02-17 02:05:33 +01:00
|
|
|
from os import environ
|
2020-02-16 20:19:03 +01:00
|
|
|
from pathlib import Path
|
|
|
|
|
2020-03-06 11:58:01 +01:00
|
|
|
from ruamel.yaml import YAML
|
|
|
|
from ruamel.yaml.parser import ParserError
|
|
|
|
from ruamel.yaml.scanner import ScannerError
|
|
|
|
|
2020-02-16 20:19:03 +01:00
|
|
|
|
|
|
|
class Config:
|
|
|
|
def __init__(self):
|
2020-02-17 02:05:33 +01:00
|
|
|
# class variables
|
2020-02-16 20:19:03 +01:00
|
|
|
self.content = None
|
2020-03-06 11:58:01 +01:00
|
|
|
self.conf_file = Path('/etc/ejabberd-metrics.yml')
|
2020-02-17 02:05:33 +01:00
|
|
|
|
|
|
|
# dev config overwrite
|
|
|
|
if environ.get('ejabberd_metrics_dev'):
|
2020-03-06 11:58:01 +01:00
|
|
|
self.conf_file = Path('config.yml')
|
2020-02-16 20:19:03 +01:00
|
|
|
|
|
|
|
# read config file
|
|
|
|
self._read()
|
|
|
|
|
|
|
|
def _read(self):
|
|
|
|
"""init the config object with this method"""
|
|
|
|
self._check()
|
|
|
|
|
2020-03-06 11:58:01 +01:00
|
|
|
# open file as an iostream
|
2020-02-17 02:05:33 +01:00
|
|
|
with open(self.conf_file, 'r', encoding='utf-8') as f:
|
2020-02-16 20:19:03 +01:00
|
|
|
try:
|
2020-03-06 11:58:01 +01:00
|
|
|
self.content = YAML(typ='safe').load(f)
|
2020-02-16 20:19:03 +01:00
|
|
|
|
|
|
|
# catch json decoding errors
|
2020-03-06 11:58:01 +01:00
|
|
|
except (ParserError, ScannerError) as err:
|
2020-02-16 20:19:03 +01:00
|
|
|
print(err, file=sys.stderr)
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
def _check(self):
|
|
|
|
"""internal method to check if the config file exists"""
|
|
|
|
try:
|
2020-02-17 02:05:33 +01:00
|
|
|
# if file is present continue
|
|
|
|
if self.conf_file.exists():
|
2020-02-16 20:19:03 +01:00
|
|
|
return
|
|
|
|
|
|
|
|
# if not create a blank file
|
|
|
|
else:
|
2020-02-17 02:05:33 +01:00
|
|
|
self.conf_file.touch(mode=0o640)
|
2020-02-16 20:19:03 +01:00
|
|
|
|
|
|
|
# catch permission exceptions as this tries to write to /etc/
|
|
|
|
except PermissionError as err:
|
|
|
|
print(err, file=sys.stderr)
|
|
|
|
sys.exit(err.errno)
|
|
|
|
|
|
|
|
def get(self, key: str = None, default: (str, int) = None) -> (dict, str, int, None):
|
|
|
|
"""method to retrieve the whole config data, a single value or the optional default value"""
|
|
|
|
# if a special key is request, return only that value
|
|
|
|
if key is not None:
|
|
|
|
|
|
|
|
# safety measure
|
|
|
|
if key in self.content:
|
|
|
|
return self.content[key]
|
|
|
|
|
|
|
|
# if a default value is given return that
|
|
|
|
if default is not None:
|
|
|
|
return default
|
|
|
|
|
|
|
|
# if the key isn't part if self.content return None
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
# else return everything
|
|
|
|
return self.content
|