diff --git a/app.py b/app.py new file mode 100644 index 0000000..b53fe66 --- /dev/null +++ b/app.py @@ -0,0 +1,131 @@ +import json +import os +import subprocess + +import requests +from flask import Flask, redirect, render_template_string + +app = Flask(__name__) + +CF_API_TOKEN = os.environ["CF_API_TOKEN"] +CF_ZONE_ID = os.environ["CF_ZONE_ID"] +SELF_NAME = os.environ.get("SELF_CONTAINER_NAME", "") + + +def extract_hostname(labels, name): + key = f"traefik.http.routers.{name}.rule" + rule = labels.get(key, "") + if "`" in rule: + return rule.split("`")[1] + return None + + +def list_projects(): + out = subprocess.run( + ["docker", "ps", "-a", "--filter", "label=traefik.enable=true", "--format", "{{.ID}}"], + capture_output=True, text=True, check=True, + ).stdout.split() + + projects = [] + for cid in out: + info = json.loads(subprocess.run( + ["docker", "inspect", cid], capture_output=True, text=True, check=True + ).stdout)[0] + name = info["Name"].lstrip("/") + if name == SELF_NAME: + continue + labels = info["Config"]["Labels"] or {} + hostname = extract_hostname(labels, name) + projects.append({ + "name": name, + "hostname": hostname, + "status": info["State"]["Status"], + "image": info["Config"]["Image"], + }) + projects.sort(key=lambda p: p["name"]) + return projects + + +def delete_dns_record(hostname): + if not hostname: + return + r = requests.get( + f"https://api.cloudflare.com/client/v4/zones/{CF_ZONE_ID}/dns_records", + params={"name": hostname}, + headers={"Authorization": f"Bearer {CF_API_TOKEN}"}, + timeout=10, + ).json() + for rec in r.get("result", []): + requests.delete( + f"https://api.cloudflare.com/client/v4/zones/{CF_ZONE_ID}/dns_records/{rec['id']}", + headers={"Authorization": f"Bearer {CF_API_TOKEN}"}, + timeout=10, + ) + + +TEMPLATE = """ + + + +Deploy Panel + + + + +

Deploy Panel

+ {% if projects %} + + + {% for p in projects %} + + + + + + + + {% endfor %} +
ProjeAdresDurumİmaj
{{ p.name }}{% if p.hostname %}{{ p.hostname }}{% else %}—{% endif %}{{ p.status }}{{ p.image }} +
+ +
+
+ {% else %} +

Henüz deploy edilmiş bir proje yok.

+ {% endif %} + + +""" + + +@app.route("/") +def index(): + return render_template_string(TEMPLATE, projects=list_projects()) + + +@app.route("/delete/", methods=["POST"]) +def delete(name): + projects = {p["name"]: p for p in list_projects()} + target = projects.get(name) + if target: + subprocess.run(["docker", "rm", "-f", name]) + delete_dns_record(target["hostname"]) + return redirect("/") + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=5000)