160 lines
6.3 KiB
Python
160 lines
6.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, send_from_directory
|
|
from werkzeug.utils import secure_filename
|
|
import yaml
|
|
import config
|
|
|
|
app = Flask(__name__)
|
|
app.secret_key = config.SECRET_KEY
|
|
|
|
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
|
|
extra_vars = (request.form.get("extra_vars") or "").strip()
|
|
check = request.form.get("check") == "yes"
|
|
vvv = request.form.get("vvv") or "-vvv"
|
|
if config.RUN_MODE == "docker":
|
|
playbook_in_container = f"/runner/project/{rel}"
|
|
shell = f'ANSIBLE_CONFIG={shlex.quote(config.ANSIBLE_CONFIG_IN_CONTAINER)} ansible-playbook {shlex.quote(playbook_in_container)} {vvv}'
|
|
if check: shell += " --check"
|
|
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 check: shell += " --check"
|
|
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:
|
|
lf.write(f"$ {' '.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)
|