Files
client160_IHMKOS/app.py
T
2025-09-17 17:26:10 +02:00

207 lines
7.3 KiB
Python

import os, subprocess, shlex, uuid, time, hashlib, pathlib, json
from datetime import datetime
from flask import Flask, render_template, request, redirect, url_for, flash, Response, jsonify
from werkzeug.utils import secure_filename
import yaml
import config
app = Flask(__name__)
app.secret_key = config.SECRET_KEY
# Expose DRY_RUN in config and templates
app.config["DRY_RUN"] = config.DRY_RUN
@app.context_processor
def inject_flags():
# Available in templates: {{ DRY_RUN }}
return {"DRY_RUN": app.config["DRY_RUN"]}
JOBS = {}
def _human(n):
for u in ['B','KB','MB','GB','TB']:
if n < 1024:
return f"{n:.0f} {u}"
n /= 1024
return f"{n:.0f} PB"
def _sha256(fp, chunk=8192):
h = hashlib.sha256()
with open(fp, 'rb') as f:
while True:
b = f.read(chunk)
if not b:
break
h.update(b)
return h.hexdigest()
def _scan_playbooks(root, q=None, sort='mtime'):
p = pathlib.Path(root)
if not p.exists():
p.mkdir(parents=True, exist_ok=True)
rows = []
for file in p.rglob("*"):
if file.is_file() and file.suffix.lower() in config.ALLOWED_EXT:
rel = file.relative_to(p)
parts = rel.parts
if len(parts) < 2: # expect domain/filename
continue
domain = parts[0]
name = parts[-1]
if q and q.lower() not in name.lower():
continue
stat = file.stat()
rows.append({
"domain": domain,
"name": name,
"path": str(file),
"rel_path": str(rel),
"size": stat.st_size,
"size_h": _human(stat.st_size),
"mtime": stat.st_mtime,
"mtime_h": datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M"),
"sha256": _sha256(str(file))[:64],
})
key = {
"mtime": lambda x: -x["mtime"],
"name": lambda x: x["name"].lower(),
"size": lambda x: -x["size"]
}.get(sort, lambda x: -x["mtime"])
grouped = {}
for row in sorted(rows, key=key):
grouped.setdefault(row["domain"], []).append(row)
return grouped
@app.route("/")
def user_home():
q = request.args.get("q", "").strip() or None
sort = request.args.get("sort", "mtime")
grouped = _scan_playbooks(config.PLAYBOOK_ROOT, q=q, sort=sort)
return render_template("user.html", grouped=grouped, q=q, sort=sort, title="Playbooks")
@app.route("/admin", methods=["GET", "POST"])
def admin_home():
if request.method == "POST":
token = request.form.get("token", "")
if config.REQUIRE_ADMIN_TOKEN and token != config.ADMIN_TOKEN:
flash("Token d'administration invalide.", "error")
return redirect(url_for("admin_home"))
domain = (request.form.get("domain") or "").strip().lower().replace(" ", "-")
f = request.files.get("file")
if not domain or not f:
flash("Domaine et fichier requis.", "error")
return redirect(url_for("admin_home"))
ext = os.path.splitext(f.filename)[1].lower()
if ext not in config.ALLOWED_EXT:
flash("Extension non autorisée. Utilise .yml ou .yaml.", "error")
return redirect(url_for("admin_home"))
try:
yaml.safe_load(f.read().decode("utf-8"))
f.seek(0)
except Exception as e:
flash(f"YAML invalide: {e}", "error")
return redirect(url_for("admin_home"))
dest_dir = os.path.join(config.PLAYBOOK_ROOT, domain)
os.makedirs(dest_dir, exist_ok=True)
fname = secure_filename(f.filename)
path = os.path.join(dest_dir, fname)
f.save(path)
flash(f"Playbook chargé: {domain}/{fname}", "ok")
return redirect(url_for("admin_home"))
grouped = _scan_playbooks(config.PLAYBOOK_ROOT)
return render_template("admin.html", grouped=grouped, title="Admin", require_token=config.REQUIRE_ADMIN_TOKEN)
@app.route("/run/<domain>/<name>")
def user_run(domain, name):
rel = f"{domain}/{name}"
full = os.path.join(config.PLAYBOOK_ROOT, rel)
if not os.path.isfile(full):
flash("Playbook introuvable.", "error")
return redirect(url_for("user_home"))
return render_template("run.html", domain=domain, name=name, rel_path=rel, title="Lancer")
@app.post("/api/run/<domain>/<name>")
def api_run_start(domain, name):
rel = f"{domain}/{name}"
full = os.path.join(config.PLAYBOOK_ROOT, rel)
if not os.path.isfile(full):
return jsonify({"error": "not found"}), 404
# Params from UI
extra_vars = (request.form.get("extra_vars") or "").strip()
vvv = request.form.get("vvv") or "-vvv"
check_from_form = request.form.get("check") == "yes"
# Global DRY-RUN forces --check and adds --diff
is_check = config.DRY_RUN or check_from_form
diff_flag = " --diff" if is_check else ""
# Auto-start ansible service (canary) if stopped
try:
subprocess.run(
["docker", "compose", "-f", config.DOCKER_COMPOSE_FILE, "up", "-d", config.ANSIBLE_SERVICE],
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
except Exception:
pass
if config.RUN_MODE == "docker":
playbook_in_container = f"/runner/project/{rel}"
shell = (
f'ANSIBLE_CONFIG={shlex.quote(config.ANSIBLE_CONFIG_IN_CONTAINER)} '
f'ansible-playbook {shlex.quote(playbook_in_container)} {vvv}'
)
if is_check:
shell += " --check" + diff_flag
if extra_vars:
shell += f" --extra-vars {shlex.quote(extra_vars)}"
cmd = [
"docker", "compose", "-f", config.DOCKER_COMPOSE_FILE, "exec", "-T",
config.ANSIBLE_SERVICE, "bash", "-lc", shell
]
else:
shell = f'ansible-playbook {shlex.quote(full)} {vvv}'
if is_check:
shell += " --check" + diff_flag
if extra_vars:
shell += f" --extra-vars {shlex.quote(extra_vars)}"
cmd = ["bash", "-lc", shell]
job_id = uuid.uuid4().hex[:12]
log_path = os.path.join(config.JOB_LOG_DIR, f"{job_id}.log")
with open(log_path, "w") as lf:
prefix = "[DRY-RUN] " if config.DRY_RUN else ""
lf.write(f"$ {prefix}{' '.join(cmd)}\n\n")
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1, universal_newlines=True
)
JOBS[job_id] = {"proc": proc, "log_path": log_path, "started": time.time()}
return jsonify({"job_id": job_id})
@app.get("/api/stream/<job_id>")
def api_stream(job_id):
job = JOBS.get(job_id)
if not job:
return Response("not found", status=404)
def generate():
proc = job["proc"]
with open(job["log_path"], "a+") as lf:
while True:
line = proc.stdout.readline()
if not line:
if proc.poll() is not None:
yield f"data: [Exit code {proc.returncode}]\n\n"
break
time.sleep(0.05)
continue
lf.write(line)
lf.flush()
yield f"data: {line.rstrip()}\n\n"
return Response(generate(), mimetype="text/event-stream")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5080, debug=True)