Document Assignment 6 Jenkins CI in the manual (refs #14)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good

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>
This commit is contained in:
2026-10-22 21:20:31 -04:00
co-authored by Claude Opus 5.5
parent 420ba4c56b
commit 1149e9fbc3
32 changed files with 1889 additions and 27 deletions
+202
View File
@@ -0,0 +1,202 @@
# Jenkins plugin and pipeline capacity experiment
Prepared for Vincent Sun and Billy Ye on October 21, 2026. This disposable test
passed locally in Docker Desktop; it has NOT run on The-Ocean and is not the
Assignment 6 deployment. See `VALIDATION.md` for the evidence and limitations.
## The question we are answering
Can The-Ocean's existing 512 MB plan run the Jenkins features we need, together
with Gitea, under the limits used in the earlier core-only experiment?
Jenkins core is the base server. Plugins add features to it. Pipeline supplies
the job execution engine and steps; the Gitea connector supplies integration
with Gitea. A plugin can download successfully but fail to load because of
incompatible dependencies or insufficient memory. Loading successfully also
does not prove that a build can run. We check these separately.
The previous core-only experiment started Jenkins, but its final accounting
included about 212 MiB swap as well as 80 MiB RAM. Its raw 60-second PASS was
qualified because the successful HTTP samples spanned only 54 seconds.
## What, why and how
| Check | Why it matters | How we test / pass criterion |
|---|---|---|
| Fresh baseline | Yesterday's resources may differ today | Correct hostname/root session, available RAM >=128 MiB, swap free >=512 MiB, enough Docker disk, unused test port, Gitea HTTP 200 |
| Prepare plugins on the laptop | Catalog processing exceeded the old 128 MiB installer heap locally | Official installer resolves the selected plugins in a separate laptop container with 768 MiB RAM / 512 MiB heap; exact roots, all resolved versions and archive hashes recorded |
| Tools and plugin installation on the target | The useful system needs more than Jenkins core | In a fresh capped container, install Python/Git and copy the verified prepared archives; inspect the installed versions before Jenkins starts |
| Plugin loading | Files on disk are not evidence that Jenkins loaded them | After initialization, verify requested plugins at expected versions, every installed plugin active and no failed-plugin entries |
| Healthy idle | A momentary login response is too weak | HTTP `/login` returns 200 over >=60 seconds of sampled observations AFTER initialization and plugin verification; any failed probe resets the clock |
| Passing pipeline | Exercise actual execution and unit tests | One executor runs dependency checks, a fresh local fixture, Python syntax checking and two unit tests; Jenkins reports SUCCESS |
| Controlled failure | Prove the tests actually detect a defect | Change multiplication to addition only in the disposable workspace; Jenkins reports FAILURE and console proves the intended `13 != 30` assertion, not an unrelated infrastructure error |
| Repair | Prove recovery works without restarting the service | Recreate the original fixture in a fresh workspace on the same job; the two tests run and Jenkins reports SUCCESS |
| Shared-host protection | Jenkins must not consume all the host's resources | Repeatedly check host available RAM/free swap, Gitea HTTP 200, container RAM/swap, CPU throttling and OOM counters; abort on guard failure |
| Cleanup | Leave existing coursework services intact | Remove only this owner-labelled test container and its anonymous home volume; preserve evidence and the base image; check Gitea afterward |
This is a small selected plugin set, not the smallest theoretically possible
dependency graph. `workflow-aggregator` is a suite, so two requested IDs will
produce more than two installed plugins. The current root requests are:
```text
workflow-aggregator:608.v67378e9d3db_1
gitea:286.v0740a_413c1eb_
```
The prepared local bundle contains 59 plugin archives (45,336,313 bytes). Two
requested features therefore do not mean two loaded files. The official plugin
pages checked October 21 list minimum Jenkins versions
2.479.3 and 2.528.3 respectively, below the recorded 2.580.1 core. That baseline
comparison is only a preliminary check; dependency resolution and actual loading
are still tested. Laptop preparation uses the official bundled `jenkins-plugin-cli`.
Current dependencies are resolved (`--latest true`) rather than deliberately
installing the old aggregator's minimum dependency versions. Requested roots
are checked for an exact match; every resolved archive version and SHA-256 goes
into the prepared `manifest.json`, with a full `plugins.lock` beside it. The
target verifies the hashes before starting Docker, then inventories the copied
archives again as `plugins-resolved.json` / `plugins-resolved.lock`.
Keep installer security warnings visible in prepared `installer.txt` and review them before
any real deployment. No flag hides warnings or skips failed plugins.
New dependency preparation and Debian package versions can change between runs.
Reusing the SAME prepared bundle fixes the plugin archives and hashes for the
target comparison; Python/Git apt versions remain recorded, not fully locked.
Retain the lock file/hashes and package-version output. Do not silently
substitute a different image/plugin set and compare it as the same experiment.
## Isolation and resource limits
- Same official core image tag as before, now also pinned to its recorded digest:
`jenkins/jenkins:2.580.1-jdk21@sha256:a660310e39ade10631f774bacd5219de767dfd08947ea5c32a739b5e5bb382c1`.
- 256 MiB container RAM; 512 MiB combined RAM plus swap, allowing up to 256 MiB
container swap. Half one CPU, 256 processes, Java heap 32-128 MiB and Serial GC.
- These target limits cover Python/Git installation, copying the prepared
plugins, AND Jenkins/Python pipeline runtime. Plugin catalog resolution and
downloads are a SEPARATE laptop-only preparation: 768 MiB RAM, 1 GiB combined
RAM+swap, 512 MiB Java heap, one CPU, no service port, fifteen-minute timeout.
Those preparation limits are not proposed for the 512 MB droplet. The base-image
pull is also separate, reused if cached, and bounded to five minutes.
- Existing host swap, packages, proxy, firewall, Gitea data and containers are
not changed. The installer runs as root inside the temporary container only;
the Jenkins process and its builds then run as the container's `jenkins` user.
- Only this source directory and the prepared plugin directory are mounted,
both read-only. No Docker socket, real
credential, runner registration, production checkout or existing Jenkins home.
- Only `127.0.0.1:18080` is published. Nothing is attached to Caddy or a public
Jenkins hostname. The disposable instance has authentication enabled and
anonymous read disabled. Its random test-account password is generated inside
Jenkins, never printed/read/exported, and discarded with the temporary home.
Setup-wizard automation is specific to this disposable instance.
- One built-in executor runs only this reviewed local fixture. This is an explicit
capacity-test choice, not approval to run arbitrary PR code on a production
controller. No separate agent is tested here.
- A sampled host floor of 48 MiB available RAM or 128 MiB free swap aborts the
run; any sampled Gitea non-200, container OOM event or unexpected exit also
aborts. These are sampled best-effort guards, not a guarantee that Gitea can
never be affected between probes. A failed health request alone does not
establish that Jenkins caused the failure.
- Installation timeout: 20 minutes. Startup/idle timeout: 15 minutes. Pipeline
phase: 10 minutes; each build has a three-minute outer wait. Overall: 45 minutes.
A detached watchdog attempts targeted cleanup after 46 minutes if SSH drops.
Normal interruption also runs cleanup. Check `cleanup_ok` and inspect leftovers
after machine/Docker failure; no script can guarantee cleanup of a stopped host.
- Requires Linux cgroup v2, Docker, Python 3.8+ on the HOST and root on The-Ocean.
Ubuntu 24.04 normally provides Python, but the preflight must confirm it.
The explicit Windows `--local-smoke-test` mode applies the same CONTAINER runtime
limits but does not run the droplet host RAM/swap/disk guards or Gitea checks.
Those fields are recorded as null, not invented measurements. Docker Desktop's
VM has different resources and does not host the real Gitea service, so local
success does not answer whether Jenkins and Gitea can share the droplet.
The experiment adds no cloud instance, subscription or resize. It uses the team's
existing droplet, disk and ordinary package/plugin/image download traffic; provider
transfer billing, if applicable, remains subject to the existing account plan.
Vincent/Billy own execution and cleanup. No maintenance/reboot is performed.
## Run when SSH access is restored
For the local regression checks only, run `python ci/jenkins-capacity/test_harness.py`
from the repository on Windows, or use `python3` on Linux. These standard-library
tests need no Docker or cloud access and do not launch Jenkins. They cannot
replace the real experiment below.
First collect/review the baseline as discussed. This script intentionally refuses
the `--run-on-the-ocean` option on Vincent's laptop or a differently named host.
Do not change that guard to obtain a false droplet PASS. Docker Desktop is not
needed to upload/run the PREPARED package; Docker on the droplet is needed.
Use the prepared ZIP, which includes a `jenkins-capacity` directory with its
`prepared-plugins` subdirectory. Extract it to a new task-local folder. From
**PowerShell in the extracted ZIP's parent folder**:
```powershell
scp -i "$env:USERPROFILE\.ssh\digitalocean" -r .\jenkins-capacity root@147.182.178.136:/root/ssw590-plugin-test
ssh -i "$env:USERPROFILE\.ssh\digitalocean" root@147.182.178.136
```
The SCP command assumes `/root/ssw590-plugin-test` does not already exist. If it
does, inspect its contents before copying; SCP may nest the source directory.
Upload the whole directory, not only `run_test.py`. Billy uses his own trusted
SSH key, not Vincent's key path.
Then **inside the droplet's Linux terminal**:
```sh
cd /root/ssw590-plugin-test
python3 --version
python3 run_test.py --help
python3 run_test.py --run-on-the-ocean
```
Expect progress lines naming `tools`, `plugins`, `startup/ready`, and
`startup/pipelines`, followed by `result.json` and the evidence path. During
installation, Jenkins HTTP is reported as 0 because Jenkins has not started;
Gitea should remain 200. You can stop with Ctrl+C; let cleanup finish.
Evidence goes under `/root/ssw590-capacity-evidence/plugins-<UTC>-<PID>/`.
Download that exact printed directory with SCP for review. It contains baseline,
input hashes, base-image identity, resource samples, checkpoint duration, resolved
plugins, controlled build logs, final state and result. It deliberately excludes
raw Jenkins controller logs, the credential-bearing home and private keys.
For a NEW bundle from source on Windows (not needed to use the packaged one):
```powershell
python ci/jenkins-capacity/prepare_plugins.py --output build/jenkins-plugin-bundle
python ci/jenkins-capacity/run_test.py --local-smoke-test --plugin-bundle build/jenkins-plugin-bundle
```
The preparation command refuses to overwrite an existing bundle. Preserve or
review the old bundle first. In the repository the archives live under ignored
`build/`; they are packaged into `prepared-plugins` for upload, not committed.
Interpret the result by phase. Preparation failure can be a download, dependency,
disk or memory problem; it does not automatically mean Jenkins cannot run.
Target installation failure may come from apt/tools or copying/unpacking plugins.
Startup failure can be plugin compatibility or resource pressure. An intentional
fixture FAILURE is expected only if the correct unit-test assertion is present.
Check OOM/CPU/swap and installer output before attributing a cause. A PASS with
heavy swap or throttling demonstrates feasibility under this small test, not
comfortable capacity, long-term reliability, concurrency or production readiness.
## What a PASS does not prove
The Gitea plugin must load here, but this experiment does not configure or exercise
Gitea discovery, SCM checkout, PR head selection, webhooks, credentials, status
reporting or branch protection. Git is installed and its version checked; no
repository is cloned. The pipeline is the bundled local fixture, not yet the
assignment's root repository Jenkinsfile. The fixture's repair is not a real
issue-linked reviewed PR. No HTTPS deployment, restart persistence, real admin
accounts, concurrent runner test, final report chapter or assignment completion
is claimed. Those are subsequent implementation/evidence steps.
## Primary references
- [Official Jenkins Docker image and plugin customization](https://github.com/jenkinsci/docker)
- [Plugin installation manager options and dependency behavior](https://github.com/jenkinsci/plugin-installation-manager-tool)
- [Pipeline suite](https://plugins.jenkins.io/workflow-aggregator/)
- [Gitea connector](https://plugins.jenkins.io/gitea/)
- [Groovy initialization hooks](https://www.jenkins.io/doc/book/managing/groovy-hook-scripts/)
- [Controller isolation and built-in executor risks](https://www.jenkins.io/doc/book/security/controller-isolation/)
- [Docker RAM, swap and CPU constraints](https://docs.docker.com/engine/containers/resource_constraints/)
+73
View File
@@ -0,0 +1,73 @@
# Verification, October 21, 2026
**Prepared and passed in Windows Docker Desktop. NOT run on The-Ocean.**
## Actual Docker results
1. Initial all-in-one local attempt, `plugins-20261021T232534Z-28212`: Python/Git
installation succeeded, but `jenkins-plugin-cli` failed with Java heap space
exhaustion while fetching the plugin-version catalog at the original 128 MiB
heap. Container exit code was 1; Docker `OOMKilled` was false. This was a JVM
heap failure, not a kernel container kill and not a Jenkins runtime test.
Cleanup succeeded. Original installer output/result were preserved.
2. Separate local plugin preparation: official installer, 768 MiB container RAM,
1 GiB combined RAM+swap, 512 MiB Java heap, one CPU. Successfully resolved 59
archives totaling 45,336,313 bytes, with exact requested root versions and a
SHA-256/version manifest. The preparation container was removed. This proves
that these preparation bounds worked, not the minimum memory the installer
needs. It did not start Jenkins.
3. Revised runtime test, `plugins-20261021T233125Z-27744`: SAME original runtime
limits (256 MiB RAM, 512 MiB combined RAM+swap, half a CPU, 128 MiB Java heap).
All 59 plugins were active, no failed plugins were reported, and healthy HTTP
samples spanned **65.39 seconds** before jobs started. Build 1 was SUCCESS;
build 2 was FAILURE with the intended `13 != 30` assertion and two unit tests
executed; build 3 repaired the calculation and was SUCCESS. Final result PASS,
cleanup true. A subsequent owner-label query found no experiment containers.
Twenty runtime samples recorded peak cgroup RAM 255.99 MiB, peak swap 137.63 MiB,
and peak SIMULTANEOUS RAM+swap 389.51 MiB. The maxima of RAM and swap need not occur
at the same time. Container OOM/OOM-kill events were zero; the RAM cap was reached
repeatedly and CPU throttling occurred. These results demonstrate this small
runtime exercise on the laptop, not spare capacity or concurrent Gitea safety.
Docker Desktop reported 16 CPUs and about 13.5 GiB VM memory. Local mode deliberately
did not measure the droplet's host memory, swap, disk or Gitea health: those fields
are null. The real droplet has about 458 MiB RAM and runs Gitea/Caddy. Its guarded
run remains necessary. No new cloud resource, firewall change or reboot occurred.
Raw local evidence remains under ignored `build/evidence/jenkins-plugin-local/`;
prepared binaries/manifest are under ignored `build/jenkins-plugin-bundle/`.
The shareable ZIP includes the prepared archives and selected non-secret local
evidence. No controller logs, Jenkins home, token, SSH key or generated test
password is included. The official base image is cached for reuse; the temporary
containers and anonymous homes were removed.
## Local regression and static checks
- Nine Python regression/fault checks passed: the previous 54-second false PASS,
failed-probe timer reset, monitor's complete idle gate, low memory/swap aborts,
refusal to delete another owner's container, cleanup despite diagnostic errors,
separate cgroup accounting, folded plugin manifests/exact root versions, and
actual Python fixture pass/failure/repair.
- Bash bootstrap syntax was checked and actual Docker execution succeeded.
- Opted-in droplet execution on Windows was rejected before Docker activity;
the container bootstrap also refused execution outside its test container.
- Python sources parsed and Linux inputs used LF endings.
- Plugin root versions/minimum core baselines were checked against official
Jenkins pages. Actual installation and activation supplied stronger evidence.
## Still unverified
- Droplet capacity with Gitea/Caddy, host pressure guards, site checks, target apt
availability and cleanup/watchdog behavior after a real SSH disconnect.
- Gitea discovery/SCM checkout/PR revision selection/webhooks/status reporting,
merge protection, a production build boundary, HTTPS deployment and persistence.
- The real reviewed failure/repair PR and Assignment 6 report chapter/submission.
SSH and the web console time out from school. The attached Cloud Firewall visibly
allowed the measured school IPv4; Gitea HTTPS returned 200 while direct TCP 22
timed out. This does not establish where filtering occurs. Docker was initially
off, then Vincent enabled it and authorized using it for local verification.
This directory supplements the earlier October 21 Billy/Claude handoff, which
predates this new test and manual record. No commit or push was performed.
+39
View File
@@ -0,0 +1,39 @@
#!/bin/bash
# Runs INSIDE the newly created disposable container, never on the host.
set -euo pipefail
[ "${SSW590_DISPOSABLE_TEST:-}" = 1 ] && [ -f /.dockerenv ] && [ -d /opt/ssw590-input ] || {
echo 'Refusing: this bootstrap runs only inside the disposable test container.' >&2
exit 1
}
umask 022
mkdir -p /tmp/ssw590
chmod 755 /tmp/ssw590
echo tools > /tmp/ssw590/phase
{
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install --no-install-recommends -y python3 git util-linux
apt-get clean
rm -rf /var/lib/apt/lists/*
python3 --version
git --version
echo plugins > /tmp/ssw590/phase
mkdir -p /usr/share/jenkins/ref/plugins /usr/share/jenkins/ref/init.groovy.d
chown jenkins:jenkins /usr/share/jenkins/ref/plugins
# Catalog resolution is prepared on the laptop, outside the runtime limits.
# The host verifies this bundle's hashes before mounting it read-only.
cp /opt/ssw590-plugins/*.jpi /usr/share/jenkins/ref/plugins/
chown -R jenkins:jenkins /usr/share/jenkins/ref/plugins
python3 /opt/ssw590-input/inventory.py /usr/share/jenkins/ref/plugins \
/opt/ssw590-input/plugins.txt > /tmp/ssw590/plugins-resolved.json
python3 - <<'PY' > /tmp/ssw590/plugins-resolved.lock
import json
for p in json.load(open('/tmp/ssw590/plugins-resolved.json')):
print(p['id'] + ':' + p['version'])
PY
cp /opt/ssw590-input/init.groovy /usr/share/jenkins/ref/init.groovy.d/90-capacity.groovy
chown -R jenkins:jenkins /tmp/ssw590
} > /tmp/ssw590/install.txt 2>&1
echo startup > /tmp/ssw590/phase
# Replace the preparer with the normal official Jenkins launcher, as non-root.
exec runuser -u jenkins -- /usr/bin/tini -- /usr/local/bin/jenkins.sh
+27
View File
@@ -0,0 +1,27 @@
// Disposable, locally supplied fixture; no SCM credentials or production checkout.
node {
stage('Dependencies') {
sh 'python3 --version && git --version'
}
stage('Fresh fixture') {
// Delete only this disposable job workspace, inside the test container.
deleteDir()
sh 'cp -R /opt/ssw590-input/fixtures/. .'
if (params.BREAK_CALCULATION) {
sh '''python3 - <<'PY'
from pathlib import Path
p = Path('pricing.py')
s = p.read_text()
assert s.count('return unit_price * quantity') == 1
p.write_text(s.replace('return unit_price * quantity', 'return unit_price + quantity'))
PY'''
}
sh 'sha256sum pricing.py'
}
stage('Syntax') {
sh 'python3 -m py_compile pricing.py'
}
stage('Unit tests') {
sh 'python3 -m unittest discover -s tests -v'
}
}
+4
View File
@@ -0,0 +1,4 @@
def total_price(unit_price, quantity):
if quantity < 1:
raise ValueError("Quantity must be positive")
return unit_price * quantity
@@ -0,0 +1,12 @@
import unittest
from pricing import total_price
class PricingTests(unittest.TestCase):
def test_total(self):
self.assertEqual(total_price(10, 3), 30)
def test_invalid_quantity(self):
with self.assertRaises(ValueError):
total_price(10, 0)
+106
View File
@@ -0,0 +1,106 @@
import groovy.json.JsonOutput
import hudson.init.InitMilestone
import hudson.model.BooleanParameterDefinition
import hudson.model.BooleanParameterValue
import hudson.model.ParametersAction
import hudson.model.ParametersDefinitionProperty
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy
import hudson.security.HudsonPrivateSecurityRealm
import hudson.security.ACL
import jenkins.model.Jenkins
import java.util.concurrent.TimeUnit
// Trusted administrator bootstrap, only in a new temporary home. Never log secrets.
def j = Jenkins.get()
def realm = new HudsonPrivateSecurityRealm(false)
realm.createAccount('capacity-test', UUID.randomUUID().toString() + UUID.randomUUID().toString())
j.setSecurityRealm(realm)
def authorization = new FullControlOnceLoggedInAuthorizationStrategy()
authorization.setAllowAnonymousRead(false)
j.setAuthorizationStrategy(authorization)
j.setNumExecutors(1)
j.setQuietPeriod(0)
j.save()
def root = new File('/tmp/ssw590')
def state = [phase: 'initializing', builds: []]
def writeState = {
def temporary = new File(root, 'status.next')
temporary.text = JsonOutput.toJson(state)
java.nio.file.Files.move(temporary.toPath(), new File(root, 'status.json').toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.ATOMIC_MOVE)
}
writeState()
Thread.startDaemon('ssw590-disposable-test') {
// The trusted bootstrap worker needs the same system identity as the init hook.
def securityContext = ACL.as2(ACL.SYSTEM2)
try {
while (j.getInitLevel() != InitMilestone.COMPLETED) { Thread.sleep(1000) }
state.plugins = j.pluginManager.plugins.collect {
[id: it.shortName, version: it.version, active: it.isActive()]
}
state.failedPlugins = j.pluginManager.failedPlugins.collect { it.name }
def requested = new File('/opt/ssw590-input/plugins.txt').readLines().findAll { it.trim() }
requested.each { entry ->
def (id, version) = entry.trim().split(':', 2)
def p = j.pluginManager.getPlugin(id)
if (p == null || !p.isActive() || p.version != version) {
throw new IllegalStateException('Requested plugin not active at expected version: ' + id)
}
}
if (state.failedPlugins || state.plugins.any { !it.active }) {
throw new IllegalStateException('Plugin load failure; inspect recorded inventory')
}
// Access plugin classes only after checking that they loaded.
def jobClass = j.pluginManager.uberClassLoader.loadClass('org.jenkinsci.plugins.workflow.job.WorkflowJob')
def definitionClass = j.pluginManager.uberClassLoader.loadClass('org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition')
def job = j.createProject(jobClass, 'capacity-pricing')
job.addProperty(new ParametersDefinitionProperty(
new BooleanParameterDefinition('BREAK_CALCULATION', false, 'Disposable failure exercise')))
job.setDefinition(definitionClass.getConstructor(String.class, Boolean.TYPE).newInstance(
new File('/opt/ssw590-input/fixtures/Jenkinsfile').text, true))
job.save()
state.phase = 'ready'
writeState()
// Host must observe >=60 seconds of healthy HTTP AFTER plugin checks first.
while (!new File(root, 'start-jobs').exists()) { Thread.sleep(1000) }
state.phase = 'pipelines'
writeState()
def cases = [[name: 'pass', broken: false, expected: 'SUCCESS'],
[name: 'intentional-failure', broken: true, expected: 'FAILURE'],
[name: 'repair', broken: false, expected: 'SUCCESS']]
for (testCase in cases) {
def future = job.scheduleBuild2(0, new ParametersAction(
new BooleanParameterValue('BREAK_CALCULATION', testCase.broken)))
if (future == null) { throw new IllegalStateException('Build could not be scheduled') }
def build = future.get(180, TimeUnit.SECONDS)
// Only these known fixture-job logs are copied, never controller logs.
def console = build.getLog(500).join('\n') + '\n'
new File(root, testCase.name + '-console.txt').text = console
def observed = build.result.toString()
state.builds << [name: testCase.name, number: build.number,
expected: testCase.expected, actual: observed]
writeState()
if (observed != testCase.expected) {
throw new IllegalStateException('Unexpected fixture build result: ' + testCase.name)
}
if (!console.contains('Ran 2 tests')) {
throw new IllegalStateException('Unit tests did not actually execute')
}
if (testCase.broken && (!console.contains('13 != 30') || !console.contains('FAILED (failures=1)'))) {
throw new IllegalStateException('Failure was not the intended calculation assertion')
}
}
state.phase = 'complete'
writeState()
} catch (Throwable failure) {
state.phase = 'failed'
// Fixed harness error text/type; do not dump arbitrary stack traces or secrets.
state.errorType = failure.class.name
writeState()
} finally {
securityContext.close()
}
}
+39
View File
@@ -0,0 +1,39 @@
"""Inspect downloaded plugin archives without loading Jenkins or reading secrets."""
import email.parser
import hashlib
import json
from pathlib import Path
import sys
import zipfile
def inventory(directory, requested):
entries = []
for path in sorted(Path(directory).glob("*.jpi")):
with zipfile.ZipFile(path) as archive:
raw = archive.read("META-INF/MANIFEST.MF").decode("utf-8")
# JAR manifests fold lines by prefixing continuation lines with one space.
unfolded = raw.replace("\r\n ", "").replace("\n ", "")
manifest = email.parser.Parser().parsestr(unfolded)
with path.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest() if hasattr(hashlib, "file_digest") else None
if digest is None:
h = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
h.update(block)
digest = h.hexdigest()
entries.append({"id": manifest["Short-Name"], "version": manifest["Plugin-Version"],
"requires_jenkins": manifest["Jenkins-Version"], "sha256": digest})
versions = {p["id"]: p["version"] for p in entries}
roots = [line.strip().split(":") for line in Path(requested).read_text().splitlines() if line.strip()]
for name, version in roots:
if versions.get(name) != version:
raise ValueError(f"Requested root version was not installed exactly: {name}:{version}")
if not entries:
raise ValueError("No plugin archives found")
return entries
if __name__ == "__main__":
print(json.dumps(inventory(sys.argv[1], sys.argv[2]), indent=2))
+2
View File
@@ -0,0 +1,2 @@
workflow-aggregator:608.v67378e9d3db_1
gitea:286.v0740a_413c1eb_
+74
View File
@@ -0,0 +1,74 @@
"""Resolve plugins on Windows Docker Desktop, never on the small droplet.
This launches only the official plugin installer, not Jenkins. The output is
non-secret plugin archives plus a hash/version manifest for the runtime test.
"""
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import subprocess
import sys
import inventory
from run_test import IMAGE, LABEL, command, remove_owned
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, required=True, help="NEW local plugin-bundle directory")
args = parser.parse_args()
if sys.platform != "win32":
parser.error("Prepare on Windows Docker Desktop; do not run this on the 512 MB droplet")
output = args.output.resolve()
if output.exists():
parser.error("Output already exists; preserve or review it before preparing another bundle")
bundle = Path(__file__).resolve().parent
owner = "prepare-" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ").lower()
container = None
output.mkdir(parents=True)
metadata = {"status": "INCOMPLETE", "environment": "Windows Docker Desktop plugin preparation only",
"base_image": IMAGE, "ram_mib": 768, "ram_plus_swap_mib": 1024,
"heap_max_mib": 512, "cpu": 1, "jenkins_started": False}
try:
if command("docker", "info", "--format", "{{.OSType}}").stdout.strip() != "linux":
raise RuntimeError("Use Docker Desktop's Linux engine")
if command("docker", "image", "inspect", IMAGE, check=False).returncode:
command("docker", "pull", IMAGE, timeout=300)
container = "ssw590-jenkins-" + owner
container = command("docker", "create", "--name", container,
"--label", f"{LABEL}={owner}", "--restart", "no",
"--memory", "768m", "--memory-swap", "1024m", "--cpus", "1", "--pids-limit", "256",
"--mount", f"type=bind,src={bundle},dst=/opt/ssw590-input,readonly",
"--env", "JAVA_OPTS=-Xms32m -Xmx512m -XX:+UseSerialGC",
"--entrypoint", "/bin/bash", IMAGE, "-c",
"mkdir -p /tmp/ssw590-prepared/plugins; "
"jenkins-plugin-cli --war /usr/share/jenkins/jenkins.war "
"--plugin-file /opt/ssw590-input/plugins.txt "
"--plugin-download-directory /tmp/ssw590-prepared/plugins --latest true --list "
"> /tmp/ssw590-prepared/installer.txt 2>&1").stdout.strip()
with (output / "preparer-process.txt").open("w") as log:
subprocess.run(["docker", "start", "--attach", container], stdout=log,
stderr=subprocess.STDOUT, timeout=900, check=True)
command("docker", "cp", container + ":/tmp/ssw590-prepared/plugins/.", str(output), timeout=60)
command("docker", "cp", container + ":/tmp/ssw590-prepared/installer.txt", str(output / "installer.txt"))
plugins = inventory.inventory(output, bundle / "plugins.txt")
(output / "manifest.json").write_text(json.dumps({"base_image": IMAGE, "plugins": plugins}, indent=2) + "\n")
(output / "plugins.lock").write_text("".join(p["id"] + ":" + p["version"] + "\n" for p in plugins))
metadata.update(status="PASS", plugin_count=len(plugins))
except Exception as error:
metadata.update(status="FAILED", reason=str(error))
if container:
command("docker", "cp", container + ":/tmp/ssw590-prepared/installer.txt",
str(output / "installer.txt"), check=False)
finally:
metadata["cleanup_ok"] = remove_owned(container, owner) if container else True
if not metadata["cleanup_ok"]:
metadata["status"] = "NEEDS_ATTENTION"
(output / "preparation.json").write_text(json.dumps(metadata, indent=2) + "\n")
print(json.dumps(metadata, indent=2))
return 0 if metadata["status"] == "PASS" else 1
if __name__ == "__main__":
sys.exit(main())
+402
View File
@@ -0,0 +1,402 @@
"""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())
+122
View File
@@ -0,0 +1,122 @@
"""Local fault/regression checks; these do not emulate a Jenkins runtime."""
import contextlib
import io
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import zipfile
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
import run_test as harness
import inventory
class TimingAndProtectionTests(unittest.TestCase):
def test_previous_54_second_false_pass_is_rejected(self):
started, passed = harness.advance_idle(None, 100, True)
self.assertFalse(passed)
self.assertFalse(harness.advance_idle(started, 154, True)[1])
self.assertTrue(harness.advance_idle(started, 160, True)[1])
def test_failed_probe_restarts_the_idle_window(self):
started, _ = harness.advance_idle(None, 100, True)
started, passed = harness.advance_idle(started, 159, False)
self.assertIsNone(started)
started, passed = harness.advance_idle(started, 170, True)
self.assertFalse(passed)
self.assertFalse(harness.advance_idle(started, 229, True)[1])
self.assertTrue(harness.advance_idle(started, 230, True)[1])
def test_low_memory_or_swap_stops_the_experiment(self):
for available, swap in [(49151, 999999), (999999, 131071)]:
with self.assertRaises(harness.Abort):
harness.resource_guard(available, swap)
with self.assertRaises(harness.Abort):
harness.resource_guard(131071, 524288, initial=True)
harness.resource_guard(131072, 524288, initial=True)
def test_cleanup_refuses_other_owners(self):
wrong_owner = subprocess.CompletedProcess([], 0, stdout="someone-else\n", stderr="")
with patch.object(harness, "command", return_value=wrong_owner) as commands:
self.assertFalse(harness.remove_owned("unrelated-container", "our-run"))
self.assertEqual(commands.call_count, 1)
self.assertEqual(commands.call_args.args[:2], ("docker", "inspect"))
def test_cgroup_ram_swap_and_cpu_are_separate(self):
raw = "memory.current\n83513344\nmemory.swap.current\n221806592\nmemory.events\noom 0\noom_kill 0\ncpu.stat\nnr_periods 2090\nnr_throttled 1052\n"
result = harness.parse_cgroup(raw)
self.assertEqual(result["memory.current"] + result["memory.swap.current"], 305319936)
self.assertEqual(result["cpu.stat"]["nr_throttled"], 1052)
with self.assertRaises(harness.Abort):
harness.parse_cgroup("memory.current\n10\n")
class EvidenceAndFixtureTests(unittest.TestCase):
def test_monitor_waits_full_window_before_starting_jobs(self):
with tempfile.TemporaryDirectory() as temporary:
run = harness.Experiment(ROOT, Path(temporary))
run.container = 'our-test-id'
completed = {"phase": "complete", "builds": [{"actual": r} for r in ["SUCCESS", "FAILURE", "SUCCESS"]]}
samples = [("startup", {"phase": "ready"}, 200, t) for t in (100, 154, 160)]
samples.append(("startup", completed, 200, 170))
with patch.object(run, "sample", side_effect=samples), patch.object(harness.time, "monotonic", return_value=0), \
patch.object(harness.time, "sleep"), patch.object(harness, "command") as commands:
run.monitor()
commands.assert_called_once_with("docker", "exec", 'our-test-id', "touch", "/tmp/ssw590/start-jobs")
checkpoint = json.loads((Path(temporary) / "checkpoints.jsonl").read_text())
self.assertEqual(checkpoint["observed_seconds"], 60)
self.assertEqual(run.result["status"], "PASS")
def test_diagnostic_error_does_not_skip_targeted_cleanup(self):
with tempfile.TemporaryDirectory() as temporary:
run = harness.Experiment(ROOT, Path(temporary))
run.container = 'our-test-id'
with patch.object(harness, "owned_container", return_value=True), \
patch.object(harness, "command", side_effect=TimeoutError("diagnostic timed out")), \
patch.object(harness, "remove_owned", return_value=True) as remove, \
patch.object(harness, "http_code", return_value=200), contextlib.redirect_stdout(io.StringIO()):
run.cleanup()
remove.assert_called_once_with('our-test-id', run.owner)
self.assertTrue(run.result["cleanup_ok"])
def test_folded_plugin_manifest_and_root_mismatch(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
requested = root / "plugins.txt"
requested.write_text("gitea:286.v0740a_413c1eb_\n")
with zipfile.ZipFile(root / "gitea.jpi", "w") as archive:
archive.writestr("META-INF/MANIFEST.MF", "Manifest-Version: 1.0\r\nShort-Name: gitea\r\nPlugin-Version: 286.v0740a_\r\n 413c1eb_\r\nJenkins-Version: 2.528.3\r\n\r\n")
result = inventory.inventory(root, requested)
self.assertEqual(result[0]["version"], "286.v0740a_413c1eb_")
self.assertEqual(len(result[0]["sha256"]), 64)
requested.write_text("gitea:wrong\n")
with self.assertRaises(ValueError):
inventory.inventory(root, requested)
def test_real_python_fixture_pass_failure_and_repair(self):
with tempfile.TemporaryDirectory() as temporary:
working = Path(temporary)
shutil.copytree(ROOT / "fixtures", working, dirs_exist_ok=True)
pricing = working / "pricing.py"
original = pricing.read_text()
for broken, expected in ((False, 0), (True, 1), (False, 0)):
pricing.write_text(original.replace("return unit_price * quantity", "return unit_price + quantity") if broken else original)
# Fresh process and no stale bytecode even if file timestamps collide.
shutil.rmtree(working / "__pycache__", ignore_errors=True)
run = subprocess.run([sys.executable, "-B", "-m", "unittest", "discover", "-s", "tests", "-v"],
cwd=working, capture_output=True, text=True)
self.assertEqual(run.returncode, expected, run.stderr)
self.assertIn("Ran 2 tests", run.stderr)
if broken:
self.assertIn("13 != 30", run.stderr)
self.assertIn("FAILED (failures=1)", run.stderr)
if __name__ == "__main__":
unittest.main(verbosity=2)