from flask import Flask, request, jsonify import os import subprocess import base64 import requests app = Flask(__name__) # Configuration MinIO depuis les variables d'environnement MINIO_BUCKET = os.getenv("MINIO_BUCKET", "nextcloud") MINIO_HOST = os.getenv("MINIO_HOST", "minio.minio.svc.cluster.local:9000") MINIO_REGION = os.getenv("MINIO_REGION", "us-east-1") S3_ACCESS_KEY = os.getenv("S3_ACCESS_KEY") S3_SECRET_KEY = os.getenv("S3_SECRET_KEY") MINIO_MOUNT_PATH = "/mnt" N8N_WEBHOOK_URL = os.getenv("N8N_WEBHOOK_URL", "https://n8n.n8n.svc.kube.ia86.cc/webhook/7950310f-e526-475a-82d1-63818da79339") DEBUG = bool(os.getenv("DEBUG")) def log_debug(message): if DEBUG: print(f"🔍 DEBUG: {message}") def mount_s3(): if not os.path.ismount(MINIO_MOUNT_PATH): os.makedirs(MINIO_MOUNT_PATH, exist_ok=True) credentials_file = "/etc/passwd-s3fs" with open(credentials_file, "w") as f: f.write(f"{S3_ACCESS_KEY}:{S3_SECRET_KEY}\n") os.chmod(credentials_file, 0o600) cmd = f"s3fs {MINIO_BUCKET} {MINIO_MOUNT_PATH} -o passwd_file={credentials_file} -o url=https://{MINIO_HOST} -o use_path_request_style -o allow_other" subprocess.run(cmd, shell=True, capture_output=True, text=True) @app.route("/build", methods=["POST"]) def build_mkdocs(): data = request.json website = data.get("WEBSITE") error_callback = data.get("ERROR_CALLBACK", N8N_WEBHOOK_URL) if not website: log_debug("❌ ParamĂštre WEBSITE manquant.") return jsonify({"error": "ParamĂštre WEBSITE manquant"}), 400 lock_file = f"/tmp/build_{website}.lock" if os.path.exists(lock_file): log_debug(f"⚠ Un build est dĂ©jĂ  en cours pour {website}.") return jsonify({ "status": "busy", "message": f"Un build est dĂ©jĂ  en cours pour {website}." }), 429 # CrĂ©ation du verrou open(lock_file, 'w').close() log_debug(f"🔐 Verrou activĂ© pour {website}.") try: mount_s3() src = f"/mnt/files/sites/@{website}/mkdocs.yml" tmp = f"/srv/{website}" if not os.path.exists(src): log_debug(f"❌ Le fichier de configuration {src} n'existe pas.") return jsonify({"error": f"{src} introuvable"}), 404 cmd = f"mkdocs build --quiet --no-strict --config-file {src} --site-dir {tmp}" log_debug(f"🚀 ExĂ©cution: {cmd}") result = subprocess.run(cmd, shell=True, capture_output=True, text=True) if result.returncode != 0: build_error = base64.b64encode(result.stderr.encode()).decode() json_payload = {"site": tmp, "erreur": build_error} requests.post(error_callback, json=json_payload, headers={"Content-Type": "application/json"}) log_debug(f"❌ Échec du build {website}: {result.stderr}") return jsonify({"status": "error", "message": "Build Ă©chouĂ©", "error": result.stderr}), 500 log_debug(f"✅ Build rĂ©ussi pour {website}.") return jsonify({"status": "success", "message": "Build rĂ©ussi"}), 200 finally: if os.path.exists(lock_file): os.remove(lock_file) log_debug(f"🔓 Verrou supprimĂ© pour {website}.") if __name__ == "__main__": log_debug("🚀 Serveur Flask dĂ©marrĂ©.") app.run(host="0.0.0.0", port=80)