Files
vpn-dns-gateway/ci/jenkins-capacity/run_test.py
billandClaude Opus 5.5 1149e9fbc3
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
Document Assignment 6 Jenkins CI in the manual (refs #14)
Add the Continuous Integration with Jenkins chapter in the eight rubric
sections: deployment and persistence (capacity test, memory-limit fix,
restart test), HTTPS/access/firewall with IPv4 and IPv6 exposure checks,
webhook traceability with an actual deployment diagram, pipeline stages,
the required pr-main merge gate, PR #15's failure/repair/review/merge
sequence, credentials and controller build boundary, and controls.

Update the Hosts and Passwords tables (1 GiB resize, Jenkins and
ci.yebilly.me, jenkins-bot account and token hints), the title page,
abstract, Document History, glossary, and AI prompt log (including
Vincent's prepared Oct 19-21 record). Note that Assignment 5's PR #13
merged.

Also version pipeline-graph-view and its dependencies in the Jenkins
plugin lockfile, and add Vincent's source-only ci/jenkins-capacity test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 21:20:31 -04:00

403 lines
21 KiB
Python

"""Bounded, disposable Jenkins plugin/pipeline experiment for The-Ocean.
No SSH, real account credentials, production mounts or host package changes are used.
Run --help for opt-in The-Ocean execution or Windows Docker Desktop validation.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import shutil
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
import inventory
IMAGE = ("jenkins/jenkins:2.580.1-jdk21@sha256:"
"a660310e39ade10631f774bacd5219de767dfd08947ea5c32a739b5e5bb382c1")
LABEL = "ssw590.capacity-owner"
SITE = "https://git.yebilly.me"
PORT = 18080
BOUNDS = ["--memory", "256m", "--memory-swap", "512m", "--cpus", "0.5", "--pids-limit", "256"]
INSTALL_SECONDS = 1200
STARTUP_SECONDS = 900
PIPELINE_SECONDS = 600
TOTAL_SECONDS = 2700
IDLE_SECONDS = 60
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
class Abort(Exception):
pass
def utc():
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def command(*args, timeout=15, check=True):
result = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
if check and result.returncode:
# All invoked commands have non-secret arguments and output by construction.
raise Abort(f"Command failed: {args[0]} {args[1:3]}: {result.stderr.strip()[:500]}")
return result
def http_code(url):
try:
with OPENER.open(url, timeout=6) as response:
return response.status
except urllib.error.HTTPError as error:
return error.code
except (urllib.error.URLError, TimeoutError, OSError):
return 0
def host_memory():
fields = {}
for line in Path("/proc/meminfo").read_text().splitlines():
key, value = line.split(":", 1)
fields[key] = int(value.strip().split()[0])
return fields["MemAvailable"], fields["SwapFree"]
def resource_guard(available, swap_free, initial=False):
memory_floor, swap_floor = (131072, 524288) if initial else (49152, 131072)
if available < memory_floor:
raise Abort(f"Host available RAM below {memory_floor // 1024} MiB")
if swap_free < swap_floor:
raise Abort(f"Host free swap below {swap_floor // 1024} MiB")
def advance_idle(previous, completed_at, healthy):
"""The clock starts AFTER a successful HTTP probe, and resets on failure."""
if not healthy:
return None, False
started = completed_at if previous is None else previous
return started, completed_at - started >= IDLE_SECONDS
def parse_cgroup(raw):
result = {}
section = None
for line in raw.splitlines():
if line in ("memory.current", "memory.swap.current", "memory.events", "cpu.stat"):
section = line
result[section] = {} if section in ("memory.events", "cpu.stat") else None
elif section in ("memory.events", "cpu.stat"):
key, value = line.split()
result[section][key] = int(value)
elif section:
result[section] = int(line)
if any(result.get(key) is None for key in ("memory.current", "memory.swap.current", "memory.events", "cpu.stat")):
raise Abort("Incomplete cgroup accounting")
return result
def owned_container(container, owner):
result = command("docker", "inspect", "--format", '{{index .Config.Labels "' + LABEL + '"}}',
container, check=False)
return result.returncode == 0 and result.stdout.strip() == owner
def remove_owned(container, owner):
if not owned_container(container, owner):
return False
command("docker", "stop", "--time", "10", container, timeout=20, check=False)
result = command("docker", "rm", "--force", "--volumes", container, timeout=20, check=False)
return result.returncode == 0
def watchdog(container, owner, evidence):
# Detached from SSH. This child can delete ONLY this exact, owner-labelled test.
time.sleep(TOTAL_SECONDS + 60)
if owned_container(container, owner):
removed = remove_owned(container, owner)
(evidence / "watchdog.txt").write_text(f"{utc()} deadline expired; removed={removed}\n")
class Experiment:
def __init__(self, bundle, evidence, local=False, plugin_bundle=None):
self.bundle = bundle.resolve()
self.evidence = evidence
self.local = local
self.plugin_bundle = (plugin_bundle or self.bundle / "prepared-plugins").resolve()
self.owner = evidence.name
self.name = "ssw590-jenkins-plugins-" + self.owner.lower()
self.container = None
self.guard = None
self.result = {"status": "INCOMPLETE", "started": utc(), "scope": "disposable plugin/pipeline capacity",
"environment": "local Docker Desktop; NOT droplet capacity" if local else "The-Ocean"}
def save(self, filename, value):
(self.evidence / filename).write_text(json.dumps(value, indent=2) + "\n")
def preflight(self):
manifest = json.loads((self.plugin_bundle / "manifest.json").read_text())
if manifest.get("base_image") != IMAGE:
raise Abort("Plugin bundle was prepared for a different base image")
if manifest.get("plugins") != inventory.inventory(self.plugin_bundle, self.bundle / "plugins.txt"):
raise Abort("Plugin bundle version/hash verification failed")
self.save("prepared-plugin-manifest.json", manifest)
if self.local:
if sys.platform != "win32":
raise Abort("The local smoke-test option is for Windows Docker Desktop only")
else:
if sys.platform != "linux" or os.geteuid() != 0:
raise Abort("Run as root inside the authorized The-Ocean Linux SSH session")
if socket.gethostname().lower() != "the-ocean":
raise Abort("Unexpected host; this experiment is restricted to The-Ocean")
for tool in (("docker",) if self.local else ("docker", "free", "df", "swapon")):
if not shutil.which(tool):
raise Abort("Missing host command: " + tool)
if command("docker", "info", "--format", "{{.CgroupVersion}}").stdout.strip() != "2":
raise Abort("This recorder requires cgroup version 2")
if not self.local:
resource_guard(*host_memory(), initial=True)
if http_code(SITE) != 200:
raise Abort("Baseline Gitea HTTP check failed")
with socket.socket() as probe:
probe.bind(("127.0.0.1", PORT))
# One plugin experiment at a time, even before its HTTP port is published.
existing = command("docker", "ps", "-aq", "--filter", "label=ssw590.purpose=jenkins-plugin-capacity").stdout.strip()
if existing:
raise Abort("Another plugin-test container exists; inspect it before continuing")
if ":18080->" in command("docker", "ps", "--format", "{{.Ports}}").stdout:
raise Abort("A Docker container already publishes the test port")
present = command("docker", "image", "inspect", IMAGE, check=False).returncode == 0
docker_root = command("docker", "info", "--format", "{{.DockerRootDir}}").stdout.strip()
disk_floor = (2 if present else 3) * 1024 ** 3
if not self.local and shutil.disk_usage(docker_root).free < disk_floor:
raise Abort(f"Less than {disk_floor // 1024 ** 3} GiB free in Docker storage")
self.save("baseline.json", {"utc": utc(), "hostname": socket.gethostname(),
"environment": self.result["environment"],
"memory_available_kib": None if self.local else host_memory()[0],
"swap_free_kib": None if self.local else host_memory()[1],
"docker_free_bytes": None if self.local else shutil.disk_usage(docker_root).free,
"docker_engine": command("docker", "info", "--format", "OS={{.OSType}} CPUs={{.NCPU}} MemoryBytes={{.MemTotal}}").stdout,
"containers": command("docker", "ps", "--format", "{{.Names}} {{.Image}} {{.Status}} {{.Ports}}").stdout,
"memory": None if self.local else command("free", "-m").stdout,
"swap": None if self.local else command("swapon", "--show").stdout,
"disk": None if self.local else command("df", "-h", docker_root).stdout,
"reboot_required": None if self.local else Path("/var/run/reboot-required").exists()})
if not present:
# Explicitly separate the pull from constrained plugin/runtime measurements.
with (self.evidence / "image-pull.txt").open("w") as output:
subprocess.run(["docker", "pull", IMAGE], stdout=output, stderr=subprocess.STDOUT,
timeout=300, check=True)
if not self.local:
resource_guard(*host_memory(), initial=True)
self.save("image.json", json.loads(command("docker", "image", "inspect", "--format",
'{"id":{{json .Id}},"digests":{{json .RepoDigests}},"bytes":{{.Size}}}', IMAGE).stdout))
def create(self):
# Nothing under ~/gitea, no real Jenkins home, socket, tokens or runner state.
# Preserve a cleanup handle even if Docker creates it but the CLI times out.
self.container = self.name
self.container = command("docker", "create", "--name", self.name,
"--label", "ssw590.purpose=jenkins-plugin-capacity", "--label", f"{LABEL}={self.owner}",
"--restart", "no", *BOUNDS, "--publish", f"127.0.0.1:{PORT}:8080",
"--log-driver", "json-file", "--log-opt", "max-size=1m", "--log-opt", "max-file=1",
"--mount", f"type=bind,src={self.bundle},dst=/opt/ssw590-input,readonly",
"--mount", f"type=bind,src={self.plugin_bundle},dst=/opt/ssw590-plugins,readonly",
"--env", "SSW590_DISPOSABLE_TEST=1",
"--env", "JAVA_OPTS=-Xms32m -Xmx128m -XX:+UseSerialGC -Djenkins.install.runSetupWizard=false",
"--user", "root", "--entrypoint", "/bin/bash", IMAGE,
"/opt/ssw590-input/container.sh").stdout.strip()
if not self.container:
raise Abort("Docker did not return a container ID")
self.save("test-config.json", {"base_image": IMAGE, "container_id": self.container,
"container_name": self.name, "owner": self.owner,
"ram_mib": 256, "ram_plus_swap_mib": 512, "cpu": 0.5, "pids": 256,
"heap_max_mib": 128, "idle_seconds": IDLE_SECONDS, "total_timeout_seconds": TOTAL_SECONDS,
"requested_plugins": (self.bundle / "plugins.txt").read_text().splitlines(),
"scope_excludes": ["SCM checkout", "webhook", "status reporting", "merge gate", "production deployment"]})
# Start the independent cleanup deadline before launching the container.
self.guard = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "--watchdog",
self.container, self.owner, str(self.evidence)], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=os.name != "nt",
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)
command("docker", "start", self.container)
def read_file(self, name):
result = command("docker", "exec", self.container, "cat", "/tmp/ssw590/" + name,
timeout=8, check=False)
return result.stdout.strip() if result.returncode == 0 else ""
def sample(self):
available, swap_free = (None, None) if self.local else host_memory()
if not self.local:
resource_guard(available, swap_free)
if http_code(SITE) != 200:
raise Abort("Gitea sampled HTTP check failed; cause not established")
running = command("docker", "inspect", "--format", "{{.State.Running}}", self.container).stdout.strip()
if running != "true":
raise Abort("Test container exited; inspect final state/install diagnostics")
phase = self.read_file("phase") or "initializing"
raw_status = self.read_file("status.json")
status = json.loads(raw_status) if raw_status else {}
code = http_code(f"http://127.0.0.1:{PORT}/login") if phase == "startup" else 0
# Timestamp AFTER the HTTP response, avoiding the prior 54-second false pass.
completed_at = time.monotonic()
http_utc = utc()
stats = command("docker", "stats", "--no-stream", "--format", "{{json .}}", self.container,
timeout=10).stdout.strip()
counters = command("docker", "exec", self.container, "sh", "-c",
'for f in memory.current memory.swap.current memory.events cpu.stat; do '
'echo "$f"; cat "/sys/fs/cgroup/$f"; done', timeout=8, check=False)
if counters.returncode:
raise Abort("Cannot read cgroup v2 memory/swap/CPU counters")
accounting = parse_cgroup(counters.stdout)
record = {"utc": http_utc, "http_completed_monotonic_seconds": completed_at,
"phase": phase, "jenkins_phase": status.get("phase"),
"host_available_kib": available, "host_swap_free_kib": swap_free,
"gitea_http": None if self.local else 200, "jenkins_login_http": code,
"docker_stats": json.loads(stats), "cgroup": accounting}
with (self.evidence / "samples.jsonl").open("a") as output:
output.write(json.dumps(record) + "\n")
if accounting["memory.events"].get("oom", 0) or accounting["memory.events"].get("oom_kill", 0):
raise Abort("Container recorded an out-of-memory event")
host_summary = "host guards/Gitea check: droplet-only" if self.local else f"available={available // 1024}MiB swap-free={swap_free // 1024}MiB GiteaHTTP=200"
print(f"{record['utc']} {phase}/{status.get('phase', '-')} JenkinsHTTP={code} {host_summary}", flush=True)
return phase, status, code, completed_at
def monitor(self):
begin = time.monotonic()
startup = pipelines = idle = None
with (self.evidence / "checkpoints.jsonl").open("a") as checkpoints:
while True:
phase, status, code, now = self.sample()
if now - begin > TOTAL_SECONDS:
raise Abort("Overall experiment deadline exceeded")
if status.get("phase") == "failed":
self.save("jenkins-status.json", status)
raise Abort("Jenkins harness failed: " + status.get("errorType", "unknown"))
if phase != "startup":
if now - begin > INSTALL_SECONDS:
raise Abort("Tool/plugin installation deadline exceeded")
else:
if startup is None:
startup = now
if pipelines is None:
healthy = status.get("phase") == "ready" and code == 200
idle, passed = advance_idle(idle, now, healthy)
if passed:
checkpoints.write(json.dumps({"checkpoint": "plugins-and-idle", "utc": utc(),
"observed_seconds": now - idle}) + "\n")
checkpoints.flush()
self.save("jenkins-status-at-idle.json", status)
command("docker", "exec", self.container, "touch", "/tmp/ssw590/start-jobs")
pipelines = now
elif now - startup > STARTUP_SECONDS:
raise Abort("Plugin startup/healthy-idle deadline exceeded")
else:
if code != 200:
raise Abort("Jenkins HTTP check failed during pipeline exercise")
if now - pipelines > PIPELINE_SECONDS:
raise Abort("Pipeline exercise deadline exceeded")
if status.get("phase") == "complete":
builds = status.get("builds", [])
if [b.get("actual") for b in builds] != ["SUCCESS", "FAILURE", "SUCCESS"]:
raise Abort("Missing expected pass/fail/repair results")
self.save("jenkins-status.json", status)
self.result.update(status="PASS", details="Plugins active; >=60-second observed healthy idle; pass/fail/repair fixture pipeline")
return
time.sleep(5)
def cleanup(self):
cleanup_ok = True
if self.container:
try:
if not owned_container(self.container, self.owner):
raise Abort("Cleanup ownership check failed; refusing container deletion")
final = command("docker", "inspect", "--format", "{{json .State}}", self.container, check=False)
if final.returncode == 0:
self.save("final-container-state.json", json.loads(final.stdout))
# Explicit allowlist; no raw controller logs or Jenkins home/credentials.
for name in ("install.txt", "plugins-resolved.json", "plugins-resolved.lock", "status.json",
"pass-console.txt", "intentional-failure-console.txt", "repair-console.txt"):
command("docker", "cp", self.container + ":/tmp/ssw590/" + name,
str(self.evidence / name), timeout=15, check=False)
# Even if a diagnostic copy failed, finally below removes owned resources.
except Exception as error:
self.result["capture_error"] = str(error)
finally:
try:
cleanup_ok = remove_owned(self.container, self.owner)
except Exception as error:
cleanup_ok = False
self.result["cleanup_error"] = str(error)
if self.guard and cleanup_ok:
self.guard.terminate()
try:
self.guard.wait(timeout=3)
except subprocess.TimeoutExpired:
self.guard.kill()
self.guard.wait()
self.result.update(finished=utc(), cleanup_ok=cleanup_ok, gitea_http_after=None if self.local else http_code(SITE))
if self.result["status"] == "PASS":
required = ("install.txt", "plugins-resolved.json", "plugins-resolved.lock", "status.json",
"pass-console.txt", "intentional-failure-console.txt", "repair-console.txt")
missing = [name for name in required if not (self.evidence / name).is_file()]
if missing or self.result.get("capture_error"):
self.result.update(status="NEEDS_ATTENTION", missing_evidence=missing)
if not cleanup_ok or (not self.local and self.result["gitea_http_after"] != 200):
self.result["status"] = "NEEDS_ATTENTION"
self.save("result.json", self.result)
print(json.dumps(self.result, indent=2), flush=True)
print("Evidence: " + str(self.evidence), flush=True)
def main():
# This internal branch is intentionally unavailable from the public parser.
if len(sys.argv) == 5 and sys.argv[1] == "--watchdog":
watchdog(sys.argv[2], sys.argv[3], Path(sys.argv[4]))
return 0
parser = argparse.ArgumentParser(description=__doc__)
modes = parser.add_mutually_exclusive_group()
modes.add_argument("--run-on-the-ocean", action="store_true", help="Execute the bounded experiment on the authorized droplet")
modes.add_argument("--local-smoke-test", action="store_true", help="Windows Docker Desktop runtime check; NOT droplet capacity")
parser.add_argument("--plugin-bundle", type=Path, help="Prepared archives directory; default: prepared-plugins beside this script")
args = parser.parse_args()
if not (args.run_on_the_ocean or args.local_smoke_test):
parser.print_help()
return 0
if args.run_on_the_ocean and (sys.platform != "linux" or os.geteuid() != 0 or socket.gethostname().lower() != "the-ocean"):
parser.error("Execution requires the root session on The-Ocean")
os.umask(0o077)
bundle = Path(__file__).resolve().parent
evidence_root = bundle.parents[1] / "build/evidence/jenkins-plugin-local" if args.local_smoke_test else Path("/root/ssw590-capacity-evidence")
evidence = evidence_root / ("plugins-" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + str(os.getpid()))
evidence.mkdir(parents=True, exist_ok=False)
experiment = Experiment(bundle, evidence, local=args.local_smoke_test, plugin_bundle=args.plugin_bundle)
# Keep source versions with measurements, but never copy unrelated repository data.
experiment.save("input-hashes.json", {str(p.relative_to(bundle)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in bundle.rglob("*") if p.is_file() and "__pycache__" not in p.parts})
def interrupted(signum, frame):
raise Abort("Interrupted by signal " + str(signum))
watched_signals = [signal.SIGINT, signal.SIGTERM] + ([signal.SIGHUP] if hasattr(signal, "SIGHUP") else [])
for sig in watched_signals:
signal.signal(sig, interrupted)
try:
experiment.preflight()
experiment.create()
experiment.monitor()
except Exception as error:
experiment.result.update(status="FAILED_OR_ABORTED", reason=str(error))
finally:
# Prevent a second disconnect signal interrupting resource cleanup.
for sig in watched_signals:
signal.signal(sig, signal.SIG_IGN)
experiment.cleanup()
return 0 if experiment.result["status"] == "PASS" else 1
if __name__ == "__main__":
sys.exit(main())