Page MenuHomec4science

sausage-api
No OneTemporary

File Metadata

Created
Thu, Apr 25, 14:39

sausage-api

#!/usr/bin/python3
# © All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE,
# Switzerland
# SCITAS - Scientific IT and Application Support, 2021
# See the LICENSE.txt file for more details.
import falcon
import gunicorn.app.base
import multiprocessing
import time
import threading
import requests
import logging
from datetime import date
from sys import exit
from os import getpid
from sausage.middleware import Sausage
from sausage.readconf import ReadConf
class UpdateDb(object):
def __init__(self):
server_opt = ReadConf()
self.server = server_opt.bind_addr + ":" + server_opt.bind_port
self.reponse = {}
# create logger
self.logger = logging.getLogger('UpdateDb')
self.logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
lconf = logging.StreamHandler()
lconf.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
lconf.setFormatter(formatter)
self.logger.addHandler(lconf)
self.exe = threading.Thread(target=self.infinite)
self.exe.daemon = True
self.exe.start()
def infinite(self):
init = 0
purgedb = 1
pid = getpid()
try:
while True:
if int(date.today().day) == 1 and purgedb == 1:
self.response = requests.get(
'http://' + self.server + '/database/purge')
purgedb = 0
if int(date.today().day) > 1:
purgedb = 1
if init == 1:
timeout = 180
else:
timeout = 3
init = 1
# Hack to catch sigint in the self thread
try:
time.sleep(timeout)
except (KeyboardInterrupt, SystemExit):
exit(0)
# End of hack
self.response = requests.get(
'http://' + self.server + '/database/update')
req_state = self.response.json()
if req_state['return'] == 'Database connection error':
self.logger.warning(req_state['return'])
else:
self.logger.info('Update Database with pid ' + str(pid))
except Exception:
self.logger.error('Error updating records in database')
exit(1)
class GunicornApp(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == '__main__':
sausage_api = Sausage()
server_opt = ReadConf()
options = {
'bind': '%s:%s' % (server_opt.bind_addr, server_opt.bind_port),
'workers': multiprocessing.cpu_count(),
}
updtdb = UpdateDb()
GunicornApp(sausage_api, options).run()

Event Timeline