mirror of
https://github.com/FAUSheppy/icinga-webhook-gateway
synced 2025-12-06 15:31:38 +01:00
small code fixes
This commit is contained in:
@@ -3,6 +3,7 @@
|
|||||||
import sys
|
import sys
|
||||||
import argparse
|
import argparse
|
||||||
import requests
|
import requests
|
||||||
|
import datetime
|
||||||
|
|
||||||
STATUS_OK = 0
|
STATUS_OK = 0
|
||||||
STATUS_WARNING = 1
|
STATUS_WARNING = 1
|
||||||
@@ -20,8 +21,9 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
urlBase = "{proto}://{host}:{port}/?service={service}".
|
urlBase = "{proto}://{host}:{port}/?service={service}"
|
||||||
url = urlBase.format(proto=args.protocol, host=args.host, port=args.port)
|
url = urlBase.format(proto=args.protocol, host=args.host,
|
||||||
|
port=args.port, service=args.service)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
@@ -33,22 +35,23 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
# validate response content #
|
# validate response content #
|
||||||
jsonDict = response.json()
|
jsonDict = response.json()
|
||||||
if not all([s in jsonDict for s in ["service", "status", "timestamp", "info"]):
|
if not all([s in jsonDict for s in ["service", "status", "timestamp", "info"]]):
|
||||||
print("Gateway return a bad response: {}".format(jsonDict))
|
print("Gateway return a bad response: {}".format(jsonDict))
|
||||||
sys.exit(STATUS_UNKOWN)
|
sys.exit(STATUS_UNKOWN)
|
||||||
|
|
||||||
if not service == jsonDict["service"]:
|
if not args.service == jsonDict["service"]:
|
||||||
print("Gateway returned wrong bad name ({} for {})".format(jsonDict["service"], service)
|
retService = jsonDict["service"]
|
||||||
|
print("Gateway returned wrong bad name ({} for {})".format(retService, args.service))
|
||||||
|
|
||||||
# handle content #
|
# handle content #
|
||||||
parsedTime = datetime.datetime.from_timestamp(int(jsonDict["timestamp"]))
|
parsedTime = datetime.datetime.fromtimestamp(int(jsonDict["timestamp"]))
|
||||||
timeString = parsedTime.isoformat()
|
timeString = parsedTime.isoformat()
|
||||||
|
|
||||||
baseInfo = "{service}: {status} - {info} ({time})"
|
baseInfo = "{service}: {status} - {info} ({time})"
|
||||||
status = jsonDict["status"]
|
status = jsonDict["status"]
|
||||||
info = jsonDict["info"]
|
info = jsonDict["info"]
|
||||||
|
|
||||||
print(baseInfo.format(service=service, status=status, info=info, timestamp=timeString)
|
print(baseInfo.format(service=args.service, status=status, info=info, time=timeString))
|
||||||
if status == "OK":
|
if status == "OK":
|
||||||
sys.exit(STATUS_OK)
|
sys.exit(STATUS_OK)
|
||||||
elif status == "WARNING":
|
elif status == "WARNING":
|
||||||
@@ -59,6 +62,6 @@ if __name__ == "__main__":
|
|||||||
sys.exit(STATUS_UNKOWN)
|
sys.exit(STATUS_UNKOWN)
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print("Gateway unavailable")
|
print("Gateway unavailable: {}".format(e))
|
||||||
|
|
||||||
sys.exit(STATUS_UNKOWN)
|
sys.exit(STATUS_UNKOWN)
|
||||||
|
|||||||
40
server.py
40
server.py
@@ -14,20 +14,18 @@ from sqlalchemy.sql import func
|
|||||||
import sqlalchemy
|
import sqlalchemy
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
|
||||||
import pytimeparse.timeparse as timeparse
|
|
||||||
|
|
||||||
app = flask.Flask("Icinga Report In Gateway")
|
app = flask.Flask("Icinga Report In Gateway")
|
||||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.sqlite'
|
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.sqlite'
|
||||||
app.config['JSON_CONFIG_FILE'] = 'services.json'
|
app.config['JSON_CONFIG_FILE'] = 'services.json'
|
||||||
db = SQLAlchemy(app)
|
db = SQLAlchemy(app)
|
||||||
|
|
||||||
class Service(db.base):
|
class Service(db.Model):
|
||||||
__tablename__ = "services"
|
__tablename__ = "services"
|
||||||
service = Column(String, primary_key=True)
|
service = Column(String, primary_key=True)
|
||||||
token = Column(String)
|
token = Column(String)
|
||||||
timeout = Column(Integer)
|
timeout = Column(Integer)
|
||||||
|
|
||||||
class Status(db.base):
|
class Status(db.Model):
|
||||||
__tablename__ = "states"
|
__tablename__ = "states"
|
||||||
service = Column(String, primary_key=True)
|
service = Column(String, primary_key=True)
|
||||||
timestamp = Column(Integer)
|
timestamp = Column(Integer)
|
||||||
@@ -47,12 +45,12 @@ def buildReponseDict(status, service=None):
|
|||||||
"info" : status.info_text }
|
"info" : status.info_text }
|
||||||
|
|
||||||
@app.route('/alive')
|
@app.route('/alive')
|
||||||
def additionalDates():
|
def alive():
|
||||||
# simple location for icinga alive checks via HTTP #
|
# simple location for icinga alive checks via HTTP #
|
||||||
return ("", 204)
|
return ("", 204)
|
||||||
|
|
||||||
@app.route('/', methods=["GET", "POST"])
|
@app.route('/', methods=["GET", "POST"])
|
||||||
def additionalDates():
|
def default():
|
||||||
if flask.request.method == "GET":
|
if flask.request.method == "GET":
|
||||||
|
|
||||||
# check for arguments #
|
# check for arguments #
|
||||||
@@ -69,25 +67,23 @@ def additionalDates():
|
|||||||
response = None
|
response = None
|
||||||
status = db.session.query(Status).filter(Status.service == serviceObj.service).first()
|
status = db.session.query(Status).filter(Status.service == serviceObj.service).first()
|
||||||
if not status:
|
if not status:
|
||||||
response = flask.Response("", 200, json=buildReponseDict(status, service=service))
|
return flask.jsonify(buildReponseDict(status))
|
||||||
else:
|
else:
|
||||||
|
|
||||||
|
# if status is ok check for timeout constrainsts, otherwise return last state #
|
||||||
if status.status == "OK":
|
if status.status == "OK":
|
||||||
timeParsed = datetime.datetime.from_timestamp(status.timestamp)
|
timeParsed = datetime.datetime.fromtimestamp(status.timestamp)
|
||||||
delta = datetime.datetime.now() - timeParsed
|
totalSeconds = (datetime.datetime.now() - timeParsed).total_seconds()
|
||||||
timeout = timeparse.timeparse(serviceObj.timeout)
|
delta = datetime.timedelta(seconds=int(totalSeconds))
|
||||||
|
timeout = datetime.timedelta(seconds=serviceObj.timeout)
|
||||||
if not status.timestamp == 0 and timeout < delta:
|
if not status.timestamp == 0 and timeout < delta:
|
||||||
status.info_text = "Service {} overdue since {}".format(service, delta.hours)
|
status.info_text = "Service {} overdue since {}".format(service, str(delta))
|
||||||
if timeout/delta > 0.9 or (delta-timeout).hours < 12:
|
if timeout/delta > 0.9 or (delta - timeout) < datetime.timedelta(hours=12):
|
||||||
status.status = "WARNING"
|
status.status = "WARNING"
|
||||||
else:
|
else:
|
||||||
status.status = "CRITICAL"
|
status.status = "CRITICAL"
|
||||||
|
|
||||||
|
return flask.jsonify(buildReponseDict(status))
|
||||||
response = flask.Response("", 200, json=buildReponseDict(status))
|
|
||||||
|
|
||||||
# finalize and return response #
|
|
||||||
response.add_header("Content-Type: application/json")
|
|
||||||
return response
|
|
||||||
|
|
||||||
elif flask.request.method == "POST":
|
elif flask.request.method == "POST":
|
||||||
|
|
||||||
@@ -100,7 +96,7 @@ def additionalDates():
|
|||||||
|
|
||||||
# verify token & service in config #
|
# verify token & service in config #
|
||||||
verifiedServiceObj = db.session.query(Service).filter(
|
verifiedServiceObj = db.session.query(Service).filter(
|
||||||
Service.service == service and_ Service.token == token).first()
|
and_(Service.service == service, Service.token == token)).first()
|
||||||
|
|
||||||
if not verifiedServiceObj:
|
if not verifiedServiceObj:
|
||||||
return ("Bad service name or token", 401)
|
return ("Bad service name or token", 401)
|
||||||
@@ -117,10 +113,10 @@ def additionalDates():
|
|||||||
def init():
|
def init():
|
||||||
db.create_all()
|
db.create_all()
|
||||||
with open(app.config["JSON_CONFIG_FILE"]) as f:
|
with open(app.config["JSON_CONFIG_FILE"]) as f:
|
||||||
config = json.read(f)
|
config = json.load(f)
|
||||||
for key in config:
|
for key in config:
|
||||||
timeout = timeparse.timeparse(config["timeout"])
|
timeout = timeparse.timeparse(config[key]["timeout"])
|
||||||
db.session.merge(Service(service=key, token=config["token"], timeout=timeout))
|
db.session.merge(Service(service=key, token=config[key]["token"], timeout=timeout))
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user