feat: port utils actions (extract-traefik-certs, generate-happ-subscriptions, lint-docker-compose)

This commit is contained in:
deytenit committed 2026-07-04 21:29:17 +03:00
1 parent b9c80b0212
commit ec54ab592f
4 files changed
+157

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
# actions/utils/extract-traefik-certs.py
"""Port of utils/extract-traefik-certs — dump traefik v3 acme.json to pem via docker."""
import os
from engine.descriptor import Meta, Arg
METADATA = Meta(summary="Extract Traefik v3 acme.json certs into fullchain.pem/privkey.pem (via docker).",
args=[Arg("source_acme", "path to acme.json"),
Arg("dest_dir", "destination directory"),
Arg("telegram_bot_url", "(optional) Telegram Bot URL", required=False)])
TITLE = "Traefik Cert Extraction"
def run(ctx, args):
log, node, url = ctx.log, ctx.node.name, args.telegram_bot_url
if not os.path.isfile(args.source_acme):
log.error(f"Source file not found: {args.source_acme}"); raise SystemExit(1)
abs_src = os.path.realpath(args.source_acme)
src_dir, src_file = os.path.dirname(abs_src), os.path.basename(abs_src)
ctx.sys.sudo(["mkdir", "-p", args.dest_dir])
abs_dest = os.path.realpath(args.dest_dir)
log.info(f"Extracting certs: {abs_src} -> {abs_dest}")
try:
ctx.sys.run(["docker", "run", "--rm", "-v", f"{src_dir}:/data", "-v", f"{abs_dest}:/output",
"ldez/traefik-certs-dumper:v2.9.3", "file", "--version", "v3",
"--source", f"/data/{src_file}", "--dest", "/output", "--domain-subdir=true",
"--crt-name=fullchain", "--crt-ext=.pem", "--key-name=privkey", "--key-ext=.pem"],
check=True)
log.info("Setting secure permissions (600) on extracted keys...")
ctx.sys.sudo(["find", abs_dest, "-type", "f", "-name", "*.pem", "-exec", "chmod", "600", "{}", "+"])
ctx.sys.sudo(["chown", "-R", f"{os.getuid()}:{os.getgid()}", abs_dest])
log.success("Certificates extracted.")
ctx.notify.success(TITLE, url, f"Certificates extracted for {node}", node)
except Exception as e:
log.error(str(e)); ctx.notify.error(TITLE, url, f"cert extraction failed: {e}", node)
raise SystemExit(1)
@@ -0,0 +1,19 @@
# actions/utils/generate-happ-subscriptions.py
"""Port of utils/generate-happ-subscriptions — build + run the happ generator image."""
import os
from engine.descriptor import Meta, Arg
METADATA = Meta(summary="Generate .psub files from a JSON config via the happ generator (docker).",
args=[Arg("input_json", "input JSON config"), Arg("output_dir", "output directory")])
IMAGE = "happ-subscription-generator"
def run(ctx, args):
log = ctx.log
src_dir = os.path.join(ctx.paths.commons, "source", "happ-subscription-generator")
inp, out = os.path.realpath(args.input_json), os.path.realpath(args.output_dir)
log.info(f"Building {IMAGE}...")
ctx.sys.run(["docker", "build", "-t", IMAGE, src_dir], check=True)
log.info(f"Running generator: {inp} -> {out}")
ctx.sys.run(["docker", "run", "--rm", "-v", f"{inp}:/app/input.json:ro",
"-v", f"{out}:/app/output:rw", IMAGE, "/app/input.json", "/app/output"], check=True)
log.success("Subscription generation completed.")
+62
View File
@@ -0,0 +1,62 @@
# actions/utils/lint-docker-compose.py
"""Port of utils/lint-docker-compose (dclint via docker) + stdlib anchor-IP validation:
every ipv4_address in compositions/*/docker-compose.yml must be unique and inside the
node's /24 (SP3 §6.2). No new deps — ipaddress + re are stdlib."""
import ipaddress, os, re, shutil
from engine.descriptor import Meta, Flag
METADATA = Meta(summary="Lint docker-compose files (dclint via docker); validate anchor IPs in the node /24.",
args=[Flag("--hook", "Only process staged compose files (pre-commit).")])
def run(ctx, args):
log, s = ctx.log, ctx.sys
repo = ctx.paths.repo_root
rc_ip = _validate_anchor_ips(ctx)
if not shutil.which("docker"):
log.error("docker is not installed or not in PATH."); return rc_ip or 1
files_string, targets = "", ["."]
if args.hook:
cp = s.run(["git", "-C", repo, "diff", "--cached", "--name-only", "--diff-filter=ACM",
"--", "*docker-compose.yml", "*docker-compose.yaml",
"docker-compose*.yml", "docker-compose*.yaml"], check=False, capture=True)
files_string = (cp.stdout or "").strip()
if not files_string:
log.info("No staged docker-compose files to lint."); return rc_ip
targets = [f"/workdir/{f}" for f in files_string.splitlines()]
log.info("Running dclint --fix (via docker)...")
r = s.run(["docker", "run", "--rm", "-v", f"{repo}:/workdir", "-w", "/workdir", "node:lts-alpine",
"npx", "--yes", "dclint", "-e", "@tier1", "-e", "@tier2", "-e", "@tier3", "-e", ".env",
"-r", "--fix", *targets], check=False)
if r.returncode != 0:
log.error(f"dclint issues (exit {r.returncode})."); return r.returncode or rc_ip
if args.hook and files_string:
for f in files_string.splitlines():
s.run(["git", "-C", repo, "add", f], check=False)
log.success("Lint completed.")
return rc_ip
def _validate_anchor_ips(ctx) -> int:
comp = ctx.paths.compositions
if not os.path.isdir(comp):
return 0
try:
subnet = ipaddress.ip_network(ctx.node.subnet) if ctx.node else None
except Exception:
subnet = None
seen, rc = {}, 0
for proj in sorted(os.listdir(comp)):
f = os.path.join(comp, proj, "docker-compose.yml")
if not os.path.isfile(f):
continue
for m in re.finditer(r"ipv4_address:\s*([0-9.]+)", open(f).read()):
ip = m.group(1)
if ip in seen:
ctx.log.error(f"Duplicate anchor IP {ip} in {proj} and {seen[ip]}"); rc = 1
seen[ip] = proj
if subnet is not None and ipaddress.ip_address(ip) not in subnet:
ctx.log.error(f"Anchor IP {ip} ({proj}) not in node subnet {subnet}"); rc = 1
if rc == 0:
ctx.log.info("Anchor IP validation passed.")
return rc