ejabberd-tools/config.py

71 lines
2.0 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import sys
from os import environ
from pathlib import Path
class Config:
def __init__(self):
# class variables
self.content = None
self.conf_file = Path('/etc/ejabberd-metrics.conf')
# dev config overwrite
if environ.get('ejabberd_metrics_dev'):
self.conf_file = Path('config.json')
# read config file
self._read()
def _read(self):
"""init the config object with this method"""
self._check()
# open and load json content from config
with open(self.conf_file, 'r', encoding='utf-8') as f:
try:
self.content = json.load(f)
# catch json decoding errors
except json.JSONDecodeError as err:
print(err, file=sys.stderr)
exit(1)
def _check(self):
"""internal method to check if the config file exists"""
try:
# if file is present continue
if self.conf_file.exists():
return
# if not create a blank file
else:
self.conf_file.touch(mode=0o640)
# 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