QVolution2019.2/AoM_Service/aom_service.py

82 lines
2.4 KiB
Python
Executable File

#!/usr/bin/python3
""" Alert On Metrics Project"""
import logging
import multiprocessing
import json
import base64
import os
import subprocess
from time import time, sleep
import requests
import yaml
from sanic import Sanic, response
from library.args import get_service_args
from library.config import glob_the_configs
from library.logger import AlertLogging
from library.service import Service
LOG = AlertLogging('aom')
LOG.start()
LOG.start_log_file("logs/aom_service.log")
APP = Sanic()
SERVICE_JOB = multiprocessing.Value('i', 0)
NUM_JOBS = multiprocessing.Value('i', 0)
LEADERSHIP = multiprocessing.Value('i', 0)
LEADER_STATUS = None
LEADER_TIME = None
CONSUL_URL = None
LEADER_OVERRIDE = None
HOSTNAME = None
SERVICE_CONFIG = None
@APP.route("/")
async def index(_):
"""
Return total number of jobs
"""
global NUM_JOBS
return response.json({"job_count": NUM_JOBS.value})
@APP.route('/healthcheck')
async def health(request):
"""
Flask healthcheck so that consul and friends work, see this as a service
Returns:
json object of status: ok
"""
LOG.debug("healthcheck")
service_process = multiprocessing.Process(target=start_service, \
args=(LOG, SERVICE_CONFIG['alert_reload_interval']), \
name="service", daemon=False)
# TRY TO START SERVICE, IF LEADER AND NOT RUNNING
if SERVICE_JOB.value == 0:
LOG.info("Starting alerts background job")
SERVICE_JOB.value += 1
service_process.start()#start_service(log)
return response.json({"status": "ok"}, 200)
def start_service(log, reload_interval):
s = Service(log, reload_interval, HOSTNAME, SERVICE_CONFIG)
s.start()
if __name__ == "__main__":
# GET ARGS AND START LOGGING
ARGS = get_service_args()
logging.setLoggerClass(AlertLogging)
LOG.info("Starting Service")
# GET SERVICE CONFIG
LEADER_OVERRIDE = ARGS['override']
HOSTNAME = ARGS['hostname']
SERVICE_CONFIG = yaml.safe_load(open('service.yaml', 'r').read())
if ARGS['alert_configs'] is not None:
SERVICE_CONFIG['alert_folder'] = ARGS['alert_configs']
if ARGS['alert_routing_lookup'] is not None:
SERVICE_CONFIG['alert_routing_lookup'] = ARGS['alert_routing_lookup']
# SET CONSUL URL FOR LEADER CHECK
CONSUL_URL = SERVICE_CONFIG['consul_url']
# START THE MAIN SERVICE
APP.run(host="0.0.0.0", port=ARGS['port'])