refactor(lab): drive docker from python so the cli works on windows and posix without bash

This commit is contained in:
ZSecurity
2026-10-24 14:07:06 +07:00
parent 8366583c43
commit 476b3d2078
8 changed files with 305 additions and 54 deletions
+116
View File
@@ -0,0 +1,116 @@
import os
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request
INIT = ("cp /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini\n"
"chown -R www-data:www-data /out 2>/dev/null || true\n"
"exec apache2-foreground")
class LabError(Exception):
pass
def docker():
exe = shutil.which("docker")
if not exe:
raise LabError("docker not found in PATH")
return exe
def host_path(path, nt=None):
if nt is None:
nt = os.name == "nt"
return path.replace("\\", "/") if nt else path
def build_run_args(root, image, name, port, net="", nt=None):
lab_dir = os.path.join(root, "lab")
out_dir = os.path.join(root, "out")
args = ["run", "-d", "--name", name]
if net:
args += ["--network", net]
args += [
"-p", "127.0.0.1:%d:80" % port,
"-v", host_path(os.path.join(lab_dir, "index.php"), nt) + ":/var/www/html/index.php:ro",
"-v", host_path(os.path.join(lab_dir, "apache-single-worker.conf"), nt) + ":/etc/apache2/conf-enabled/zz-p2s.conf:ro",
"-v", host_path(out_dir, nt) + ":/out",
image,
"/bin/sh", "-c", INIT,
]
return args
def run(args, timeout=300, check=True):
exe = docker()
try:
proc = subprocess.run([exe] + args, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise LabError("docker %s timed out" % args[0]) from exc
if check and proc.returncode != 0:
msg = (proc.stderr or proc.stdout or "").strip().splitlines()
raise LabError("docker %s failed: %s" % (args[0], msg[-1] if msg else "exit %d" % proc.returncode))
return proc
def executable(root, name):
exe = docker()
cmd = [exe, "exec", name] + root
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
return proc.stdout
def wait_ready(port, host="127.0.0.1", attempts=60, delay=0.5):
url = "http://%s:%d/index.php" % (host, port)
for _ in range(attempts):
try:
with urllib.request.urlopen(url, timeout=2) as resp:
body = resp.read().decode("latin1").strip()
return body
except (urllib.error.URLError, OSError):
time.sleep(delay)
return None
def up(root, image, name, port, net="", host="127.0.0.1"):
run(["rm", "-f", name], check=False)
os.makedirs(os.path.join(root, "out"), exist_ok=True)
if net:
run(["network", "create", net], check=False)
run(build_run_args(root, image, name, port, net))
body = wait_ready(port, host)
if body is None:
logs = run(["logs", "--tail", "20", name], check=False)
raise LabError("target did not become ready on port %d\n%s" % (port, logs.stdout + logs.stderr))
return body
def down(name):
run(["rm", "-f", name], check=False)
return True
def status(root, name, lib_path):
rows = []
ver = executable(["php", "-v"], name).splitlines()
rows.append(("php", ver[0] if ver else "?"))
info = executable(["php", "-i"], name)
keep = {"display_errors", "memory_limit", "post_max_size", "output_buffering",
"max_file_uploads", "max_input_vars", "session.upload_progress.enabled",
"session.save_handler", "session.serialize_handler"}
for line in info.splitlines():
key, _, val = line.partition("=>")
key = key.strip()
if key in keep:
rows.append((key, val.split("=>")[0].strip()))
sha = executable(["sha256sum", lib_path], name).split()
rows.append(("libphp_sha256", sha[0] if sha else "?"))
apache = executable(["apache2", "-v"], name).splitlines()
rows.append(("apache", apache[0] if apache else "?"))
workers = executable(["sh", "-c", "pgrep -c apache2"], name).strip()
rows.append(("workers", workers))
return rows