albs-oval-errata-diff/albs_oval_erratta_diff/start.py
2022-12-28 17:57:00 +01:00

101 lines
2.9 KiB
Python

"""
service compares rhel oval with alma ovals and errata ovals
results available via API Call
"""
from aiohttp import web
import copy
import logging
from logging.handlers import RotatingFileHandler
import threading
from time import sleep
import json
from .config import LOG_FILE, DIFF_FILE, UPDATE_INTERVAL_MINUTES, SERVER_IP, SERVER_PORT
from .comparer import comparer_run
# This dict holds all current differentes
diffs = {}
diffs_lock = threading.Lock()
async def web_handler(request):
data = {}
try:
diffs_lock.acquire()
data = copy.deepcopy(diffs)
diffs_lock.release()
except Exception as e:
logging.critical("Unhandled exeption %s", e, exc_info=True)
return web.json_response(data=data)
def webserver_run():
app = web.Application()
app.add_routes([web.get('/', web_handler)])
web.run_app(app=app, host=SERVER_IP, port=SERVER_PORT)
def diff_checker():
while True:
logging.info("Start comparing")
# generating new diff
try:
result = comparer_run()
except Exception as e:
logging.critical("Unhandled exeption %s", e, exc_info=True)
else:
logging.info("Finished comparing, updating diff dict")
diffs_lock.acquire()
global diffs
diffs = result
diffs_lock.release()
# dumping
logging.info("Saving results to disk")
try:
with open(DIFF_FILE, 'w', encoding='utf-8') as flw:
json.dump(result, flw, indent=4)
except Exception as e:
logging.critical("Unhandled exeption %s", e, exc_info=True)
logging.info("Done")
logging.info("Finished comparing, go to sleep for %d minutes",
UPDATE_INTERVAL_MINUTES)
sleep(UPDATE_INTERVAL_MINUTES * 60)
def start():
# making sure that directory exists
for p in [LOG_FILE, DIFF_FILE]:
if not p.parent.exists():
p.parent.mkdir()
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(funcName)s %(message)s',
handlers=[logging.FileHandler(LOG_FILE, mode='a'),
logging.StreamHandler(),
RotatingFileHandler(LOG_FILE, maxBytes=10000, backupCount=3)])
logging.info("Trying to load diff file from disk")
try:
with open(DIFF_FILE, 'r', encoding='utf-8') as flr:
loaded_data = json.load(flr)
diffs_lock.acquire()
diffs = loaded_data
diffs_lock.release()
except Exception as e:
logging.warning('cant load data from disk %s', e)
else:
logging.info('diff file was loaded')
logging.info("Starting diff_checker in background")
thread = threading.Thread(target=diff_checker)
thread.daemon = True
thread.start()
logging.info("Starting webserver")
webserver_run()
if __name__ == "__main__":
start()