57 lines
1.4 KiB
Python
57 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
class Config:
|
|
def __init__(self):
|
|
# global config path
|
|
conf_path = '/etc/ejabberd-metrics.conf'
|
|
self.file = Path(conf_path)
|
|
|
|
self.content = None
|
|
|
|
def _read(self):
|
|
with open(self.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):
|
|
try:
|
|
# if file is present try to read it's contents
|
|
if self.file.exists():
|
|
self._read()
|
|
|
|
# if not create a blank file
|
|
else:
|
|
Path.touch(self.file)
|
|
|
|
# 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) -> (dict, None):
|
|
self._check()
|
|
|
|
# if a special key is request, return just that
|
|
if key is not None:
|
|
|
|
# safety measure
|
|
if key in self.content:
|
|
return self.content[key]
|
|
|
|
# if the key isn't part if self.content return None
|
|
else:
|
|
return None
|
|
|
|
# else return everything
|
|
return self.content
|