import os import subprocess from flask import Flask, request, jsonify, abort from functools import wraps ASN_FILE_PATH = os.getenv("ASN_FILE_PATH", "/opt/irr-update/asns.txt") LOG_FILE_PATH = os.getenv("LOG_FILE_PATH", "/opt/irr-update/irr_updater.log") SCRIPT_PATH = os.getenv("SCRIPT_PATH", "/opt/irr-update/gen.sh") EXPECTED_API_KEY = "your-secret-key-123" app = Flask(__name__) def require_api_key(f): @wraps(f) def decorated_function(*args, **kwargs): if request.headers.get('X-API-Key') != EXPECTED_API_KEY: abort(401, description="Invalid API Key") return f(*args, **kwargs) return decorated_function @app.route("/ping") def ping(): return "pong" @app.route('/asns', methods=['GET']) @require_api_key def get_asns(): try: with open(ASN_FILE_PATH, 'r') as f: content = f.read() return jsonify({"content": content}) except FileNotFoundError: return jsonify({"error": "asns.txt not found."}), 404 except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/asns', methods=['POST']) @require_api_key def update_asns(): content = request.json.get('content') if content is None: return jsonify({"error": "Missing 'content' in request body."}), 400 try: with open(ASN_FILE_PATH, 'w') as f: f.write(content) return jsonify({"success": True, "message": "asns.txt updated successfully."}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/run-update', methods=['POST']) @require_api_key def run_update(): try: subprocess.Popen([SCRIPT_PATH]) return jsonify({ "success": True, "message": "IRR update script started in background." }) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/log', methods=['GET']) @require_api_key def get_log(): START_MARKER = "Starting IRR filter update process." NUM_RUNS_TO_SHOW = 3 try: with open(LOG_FILE_PATH, 'r') as f: lines = f.readlines() except FileNotFoundError: return jsonify({"log": "Log file not found."}) except Exception as e: return jsonify({"error": str(e)}), 500 if not lines: return jsonify({"log": "Log file is empty."}) start_indices = [i for i, line in enumerate(lines) if START_MARKER in line] if not start_indices: return jsonify({"log": "".join(lines)}) num_runs_found = len(start_indices) if num_runs_found <= NUM_RUNS_TO_SHOW: run_start_index = start_indices[0] else: run_start_index = start_indices[num_runs_found - NUM_RUNS_TO_SHOW] final_start_index = max(0, run_start_index - 1) last_runs_lines = lines[final_start_index:] log_content = "".join(last_runs_lines) return jsonify({"log": log_content}) if __name__ == '__main__': app.run(host='0.0.0.0', port=5001)