summaryrefslogtreecommitdiffstats
path: root/config.py
diff options
context:
space:
mode:
authornico <nico@magicbroccoli.de>2020-08-27 18:10:23 +0200
committernico <nico@magicbroccoli.de>2020-08-27 18:10:23 +0200
commit893b93379fffd91c18a21315dc0b5c5d7285494c (patch)
treef17f35d763fa069ea6cec46ed199eb8e4a2fe6aa /config.py
Initial working releaseHEADmaster
TeamSpeak InfluxDB exporter base of ejabberd-tools framework + implement TeamSpeak REST api call to gather statistics + implement metrics logic to omit unnecessary data points + add systemd service file + implement pre-commit framework
Diffstat (limited to 'config.py')
-rw-r--r--config.py76
1 files changed, 76 insertions, 0 deletions
diff --git a/config.py b/config.py
new file mode 100644
index 0000000..c3db1b4
--- /dev/null
+++ b/config.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import sys
+from pathlib import Path
+
+from ruamel.yaml import YAML
+from ruamel.yaml.parser import ParserError
+from ruamel.yaml.scanner import ScannerError
+
+
+class Config:
+ def __init__(self):
+ # class variables
+ self.content = None
+
+ # select config file
+ if Path.exists(Path("teamspeak-influx.yml")):
+ self.conf_file = Path("teamspeak-influx.yml")
+ else:
+ self.conf_file = Path("/etc/teamspeak-influx.yml")
+
+ # read config file
+ self._read()
+
+ def _read(self):
+ """init the config object with this method"""
+ self._check()
+
+ # open file as an iostream
+ with open(self.conf_file, "r", encoding="utf-8") as f:
+ try:
+ self.content = YAML(typ="safe").load(f)
+
+ # catch json decoding errors
+ except (ParserError, ScannerError) 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 all config values, 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