import os import requests import urllib3 from requests.auth import HTTPBasicAuth from flask import Flask, request, Response # Suppress warnings about self-signed certificates urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) app = Flask(__name__) api_key = os.getenv("API_KEY") api_secret = os.getenv("API_SECRET") API_URL = os.getenv("API_URL") HEALTHY_STATUS = os.getenv("HEALTHY_STATUS") JSONROWS = os.getenv("JSONROWS") @app.route("/check") def check(): name = request.args.get("name") if not name: return Response( "Missing name parameter\n", status=400, mimetype="text/plain" ) try: session = requests.Session() session.auth = HTTPBasicAuth(api_key, api_secret) session.headers.update({"Accept": "application/json"}) response = session.get( API_URL, timeout=10, verify=False, ) response.raise_for_status() data = response.json() gateway = next( ( row for row in data.get(JSONROWS, []) if row.get("name", "").lower() == name.lower() ), None ) if gateway is None: return Response( f"{name} not found\n", status=400, mimetype="text/plain" ) status = gateway.get("status", "").lower() if status == HEALTHY_STATUS: return Response( "OK\n", status=200, mimetype="text/plain" ) return Response( f"Status is {status}\n", status=503, mimetype="text/plain" ) except requests.exceptions.RequestException as ex: return Response( f"API communication error: {ex}\n", status=500, mimetype="text/plain" ) except ValueError: return Response( "Invalid JSON received from API\n", status=500, mimetype="text/plain" ) except Exception as ex: return Response( f"Unexpected error: {ex}\n", status=500, mimetype="text/plain" ) @app.route("/health") def health(): return Response( "healthy\n", status=200, mimetype="text/plain" ) if __name__ == "__main__": app.run( host="0.0.0.0", port=8080 )