utilize /etc/ directory

+ add config.py to read / touch create the etc config file
This commit is contained in:
nico 2020-02-16 20:19:03 +01:00
parent 7c656961ce
commit f02b7e87ed
4 changed files with 91 additions and 32 deletions

1
.gitignore vendored
View File

@ -110,6 +110,7 @@ dmypy.json
# Pycharm # Pycharm
.idea/ .idea/
.venv/ .venv/
venv
# config # config
config.json config.json

66
config.py Normal file
View File

@ -0,0 +1,66 @@
#!/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
# 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.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 try to read it's contents
if self.file.exists():
return
# 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, 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

View File

@ -1,12 +1,10 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import json
import os
import time import time
from influxdb import InfluxDBClient from influxdb import InfluxDBClient
from config import Config
from ejabberdrpc import EjabberdMetrics from ejabberdrpc import EjabberdMetrics
@ -79,19 +77,17 @@ class Influx:
if __name__ == '__main__': if __name__ == '__main__':
# load config # load config
path = os.path.dirname(__file__) config = Config()
with open('/'.join([path, 'config.json']), 'r', encoding='utf-8') as f:
config = json.load(f)
# creds and params # credentials and parameters
url = config['url'] if 'url' in config else 'http://localhost:5280/api' url = config.get('url', default='http://localhost:5280/api')
login = config['login'] if 'login' in config else None login = config.get('login', default=None)
api = config['api'] if 'api' in config else 'rest' api = config.get('api', default='rest')
# config influxdb # config influxdb
influx_host = config['influxdb_host'] if 'influxdb_host' in config else 'localhost' influx_host = config.get('influxdb_host', default='localhost')
influx_port = config['influxdb_port'] if 'influxdb_port' in config else 8086 influx_port = config.get('influxdb_port', default=8086)
influx_dbname = config['influxdb_db'] if 'influxdb_db' in config else 'ejabberd' influx_dbname = config.get('influxdb_db', default='ejabberd')
# init handler # init handler
metrics = EjabberdMetrics(url, login, api) metrics = EjabberdMetrics(url, login, api)

View File

@ -1,14 +1,16 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ejabberdrpc import EjabberdMetrics
import time
import threading
import socket import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn from socketserver import ThreadingMixIn
from config import Config
from ejabberdrpc import EjabberdMetrics
class _ThreadingSimpleServer(ThreadingMixIn, HTTPServer): class _ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
"""Thread per request HTTP server.""" """Thread per request HTTP server."""
# Make worker threads "fire and forget". Beginning with Python 3.7 this # Make worker threads "fire and forget". Beginning with Python 3.7 this
@ -65,10 +67,8 @@ class Prometheus():
for k, v in data.items(): for k, v in data.items():
output += self._parse_metric("ejabberd_online_client_ipversion", v, {"vhost": host, "node": node, "ipversion": str(k), "client": client}) output += self._parse_metric("ejabberd_online_client_ipversion", v, {"vhost": host, "node": node, "ipversion": str(k), "client": client})
return output return output
def listen(self, port, addr='::'): def listen(self, port, addr='::'):
"""Starts an HTTP server for prometheus metrics as a daemon thread""" """Starts an HTTP server for prometheus metrics as a daemon thread"""
class myHandler(BaseHTTPRequestHandler): class myHandler(BaseHTTPRequestHandler):
@ -79,28 +79,24 @@ class Prometheus():
result = self._get_metrics() result = self._get_metrics()
r.wfile.write(result.encode('utf-8')) r.wfile.write(result.encode('utf-8'))
httpd = _ThreadingSimpleServer((addr, port), myHandler) httpd = _ThreadingSimpleServer((addr, port), myHandler)
t = threading.Thread(target=httpd.serve_forever) t = threading.Thread(target=httpd.serve_forever)
t.daemon = True t.daemon = True
t.start() t.start()
if __name__ == "__main__": if __name__ == "__main__":
import os
import json
# load config # load config
path = os.path.dirname(__file__) config = Config()
with open("/".join([path, "config.json"]), "r", encoding="utf-8") as f:
config = json.load(f)
# credentials and parameters
url = config.get('url', default='http://[::1]:5280/api')
login = config.get('login', default=None)
api = config.get('api', default='rest')
url = config['url'] if "url" in config else "http://[::1]:5280/api" # config prometheus
login = config['login'] if "login" in config else None prom_port = config.get('prometheus_port', default=8080)
api = config['api'] if "api" in config else "rest" prom_refresh = config.get('prometheus_refresh', default=10)
prom_port = config['prometheus_port'] if "prometheus_port" in config else 8080
prom_refresh = config['prometheus_refresh'] if "prometheus_refresh" in config else 10
metrics = EjabberdMetrics(url, login, api) metrics = EjabberdMetrics(url, login, api)
prom = Prometheus(metrics) prom = Prometheus(metrics)