From 85f81d8e0ad22c12cdac1bf919da64b13e234de2 Mon Sep 17 00:00:00 2001 From: Vincent Date: Wed, 25 Nov 2026 22:28:57 -0500 Subject: [PATCH] Patch Jenkins and delivery agent Java runtimes --- delivery/README.md | 5 + delivery/agent/Dockerfile | 4 + delivery/agent/compose.droplet.yaml | 2 +- delivery/agent/compose.yaml | 2 +- delivery/bootstrap/start-agent.ps1 | 2 +- delivery/bootstrap/start-droplet-agent.sh | 4 +- deploy/README.md | 4 + deploy/docker-compose.yml | 2 +- deploy/jenkins/Dockerfile | 4 + manual/latex/devopsAIPromptLog.tex | 47 +++++++ manual/latex/devopsDocumentHistory.tex | 1 + manual/latex/devopsHostsPasswords.tex | 5 +- security/java/Dockerfile | 12 ++ security/java/README.md | 99 +++++++++++++ security/java/patch-existing.py | 160 ++++++++++++++++++++++ 15 files changed, 346 insertions(+), 7 deletions(-) create mode 100644 security/java/Dockerfile create mode 100644 security/java/README.md create mode 100644 security/java/patch-existing.py diff --git a/delivery/README.md b/delivery/README.md index f149097..276ca8b 100644 --- a/delivery/README.md +++ b/delivery/README.md @@ -38,6 +38,11 @@ and both recovery exercises require dated execution evidence. ## Attribution and preparation record +The 23 November [Java security update](../security/java/README.md) replaces the +trusted agent's Java runtime with pinned Temurin 21.0.13.1+2. Its current image +is `ssw590-delivery-agent:20261114-java21.0.13.1-2`; historical execution evidence +below retains the original versions actually used. + On 14 November 2026 Vincent asked Codex to review the assignment and begin preparation while he started Docker Desktop. Codex checked the repository's AI requirements and usage guide, read Chapter 6 and the example sources, diff --git a/delivery/agent/Dockerfile b/delivery/agent/Dockerfile index 9ee1c17..2b8cc71 100644 --- a/delivery/agent/Dockerfile +++ b/delivery/agent/Dockerfile @@ -1,8 +1,12 @@ +FROM eclipse-temurin:21.0.13.1_2-jdk-jammy@sha256:4b3d0998ee65462bd86ff060c87119b3575294cb3d0927372afa6f3708b0c8db AS patched_java FROM docker:29-cli@sha256:5a7af0dcb0e46c803efe9b45371dd21cb500e5b4453250394ac6f06d49b6e6f1 AS dockercli FROM aquasec/trivy:0.76.2@sha256:8f6bb947dbc528902e11f2f5be52f7b519f6a39d5d148f41166f2040499768fb AS scanner FROM jenkins/inbound-agent:jdk21@sha256:25a3704f7de4d3d0becc441f5683a227556658df1473865ee94c5232355678ab USER root +RUN rm -rf /opt/java/openjdk +COPY --from=patched_java /opt/java/openjdk /opt/java/openjdk +ENV JAVA_VERSION=jdk-21.0.13.1+2 RUN apt-get update \ && apt-get install -y --no-install-recommends python3 python3-venv git openssh-client ca-certificates curl \ && rm -rf /var/lib/apt/lists/* diff --git a/delivery/agent/compose.droplet.yaml b/delivery/agent/compose.droplet.yaml index 494a960..37fe863 100644 --- a/delivery/agent/compose.droplet.yaml +++ b/delivery/agent/compose.droplet.yaml @@ -1,7 +1,7 @@ name: ssw590-delivery services: agent: - image: ssw590-delivery-agent:20261114 + image: ssw590-delivery-agent:20261114-java21.0.13.1-2 restart: unless-stopped entrypoint: ["java", "-jar", "/usr/share/jenkins/agent.jar"] command: diff --git a/delivery/agent/compose.yaml b/delivery/agent/compose.yaml index c580e80..6becdfb 100644 --- a/delivery/agent/compose.yaml +++ b/delivery/agent/compose.yaml @@ -1,7 +1,7 @@ name: ssw590-delivery services: agent: - image: ssw590-delivery-agent:20261114 + image: ssw590-delivery-agent:20261114-java21.0.13.1-2 restart: "no" entrypoint: ["java", "-jar", "/usr/share/jenkins/agent.jar"] command: diff --git a/delivery/bootstrap/start-agent.ps1 b/delivery/bootstrap/start-agent.ps1 index 5bd6844..53e817a 100644 --- a/delivery/bootstrap/start-agent.ps1 +++ b/delivery/bootstrap/start-agent.ps1 @@ -18,7 +18,7 @@ $sshArguments = @('-i', $IdentityFile, '-o', 'IdentitiesOnly=yes', '-o', 'BatchM & ssh @sshArguments 'docker exec -u jenkins gitea-jenkins-1 cat /var/jenkins_home/delivery-bootstrap/agent-secret' | & docker run --rm -i --network none --user 0:0 --entrypoint sh ` --mount 'type=volume,source=ssw590-delivery-identity,target=/identity' ` - ssw590-delivery-agent:20261114 -c 'set -eu; umask 077; cat > /identity/agent-secret; test -s /identity/agent-secret; chown 1000:1000 /identity /identity/agent-secret; chmod 700 /identity; chmod 400 /identity/agent-secret' + ssw590-delivery-agent:20261114-java21.0.13.1-2 -c 'set -eu; umask 077; cat > /identity/agent-secret; test -s /identity/agent-secret; chown 1000:1000 /identity /identity/agent-secret; chmod 700 /identity; chmod 400 /identity/agent-secret' Push-Location $repoPath try { & docker compose -f delivery/agent/compose.yaml up -d diff --git a/delivery/bootstrap/start-droplet-agent.sh b/delivery/bootstrap/start-droplet-agent.sh index eae1fe1..6424fa2 100644 --- a/delivery/bootstrap/start-droplet-agent.sh +++ b/delivery/bootstrap/start-droplet-agent.sh @@ -10,14 +10,14 @@ DOCKER_GID=$(stat -c '%g' /var/run/docker.sock) # Numeric group only, not a credential. Keep it available for later Compose use. printf 'DOCKER_GID=%s\n' "$DOCKER_GID" > .env chmod 644 .env -docker image inspect ssw590-delivery-agent:20261114 >/dev/null +docker image inspect ssw590-delivery-agent:20261114-java21.0.13.1-2 >/dev/null docker compose -f compose.droplet.yaml config --quiet docker exec -u jenkins gitea-jenkins-1 test -s /var/jenkins_home/delivery-bootstrap/agent-secret docker volume create ssw590-delivery-identity >/dev/null docker exec -u jenkins gitea-jenkins-1 cat /var/jenkins_home/delivery-bootstrap/agent-secret | docker run --rm -i --network none --user 0:0 --entrypoint sh \ --mount type=volume,source=ssw590-delivery-identity,target=/identity \ - ssw590-delivery-agent:20261114 -c \ + ssw590-delivery-agent:20261114-java21.0.13.1-2 -c \ 'set -eu; umask 077; cat > /identity/agent-secret; test -s /identity/agent-secret; chown 1000:1000 /identity /identity/agent-secret; chmod 700 /identity; chmod 400 /identity/agent-secret' docker compose -f compose.droplet.yaml up -d --pull never agent=ssw590-delivery-agent-1 diff --git a/deploy/README.md b/deploy/README.md index 40a28c7..6eae137 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -152,6 +152,10 @@ Remove it with `docker rm -f color-buttons-app`, delete the block, and reload. ## Jenkins CI (Assignment 6 / Instructor Manual Chapter 4) +The 23 November runtime-only [Java security update](../security/java/README.md) +retains Jenkins 2.580.1 and pins patched Temurin 21.0.13.1+2 in the Dockerfile. +Compose now selects `ssw590-jenkins:2.580.1-java21.0.13.1-2`. + `jenkins/Dockerfile` extends the official `jenkins/jenkins:2.580.1-lts-jdk21` image (digest pinned) with `python3` and the plugins in `jenkins/plugins.txt`. Builds run on the controller's single executor. Jenkins publishes no port: diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 17a4b73..d6c03cf 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -44,7 +44,7 @@ services: # Bounded so Gitea keeps memory on the 512 MB droplet. jenkins: build: ./jenkins - image: ssw590-jenkins:2.580.1 + image: ssw590-jenkins:2.580.1-java21.0.13.1-2 restart: unless-stopped environment: # The capacity test's 128 MiB heap ran builds, but the web UI hit "OutOfMemoryError: diff --git a/deploy/jenkins/Dockerfile b/deploy/jenkins/Dockerfile index fd4ea52..f14bfca 100644 --- a/deploy/jenkins/Dockerfile +++ b/deploy/jenkins/Dockerfile @@ -1,8 +1,12 @@ # Official Jenkins LTS image plus what the controller executor needs to run the # pipeline: python3 for the tests and the pinned plugin lockfile. +FROM eclipse-temurin:21.0.13.1_2-jdk-jammy@sha256:4b3d0998ee65462bd86ff060c87119b3575294cb3d0927372afa6f3708b0c8db AS patched_java FROM jenkins/jenkins:2.580.1-lts-jdk21@sha256:a660310e39ade10631f774bacd5219de767dfd08947ea5c32a739b5e5bb382c1 USER root +RUN rm -rf /opt/java/openjdk +COPY --from=patched_java /opt/java/openjdk /opt/java/openjdk +ENV JAVA_VERSION=jdk-21.0.13.1+2 RUN apt-get update \ && apt-get install -y --no-install-recommends python3 \ && rm -rf /var/lib/apt/lists/* diff --git a/manual/latex/devopsAIPromptLog.tex b/manual/latex/devopsAIPromptLog.tex index fcb3e6c..64aa987 100644 --- a/manual/latex/devopsAIPromptLog.tex +++ b/manual/latex/devopsAIPromptLog.tex @@ -1106,3 +1106,50 @@ staging v2, Document History and this log; and prepared the complete TinyTeX build and visual review. Passwords hints, credentials, permissions, earlier coursework, Billy/Claude records and shared services were preserved. Vincent handles final commits/pushes and submission; Billy reviews the final PR. + +\section{Java Runtime Security Maintenance} +Date: November 23, 2026; Tool: OpenAI Codex; Human: Vincent Sun. +Vincent asked Codex to assess DigitalOcean's PHP and OpenJDK email alerts, +then explicitly authorized patching after loading his SSH key privately. +Codex read the alerts and verified the Java fix against Adoptium's advisory. +The earlier PHP inventory found no PHP. The local Docker VM and the Droplet +both lacked the AVX-512 VBMI feature required for the documented Java exploit; +this hardware qualification was distinguished from having a patched runtime. + +The controller used Temurin 21.0.12.1+1 before this update. +The delivery agent used Temurin 21.0.13+9. +Codex selected the official fixed Temurin 21.0.13.1+2 image, +verified its registry digest, retained original image and Compose checkpoints, +and built runtime-only replacement images under bounded resources. An initial +Adoptium assets endpoint returned 404; official GitHub release metadata and +Docker Hub provided the release and pinned image instead. Isolated version +checks passed before service replacement. Codex checked for unfinished or +queued Jenkins work, stopped the idle agent and recreated only the controller +and agent. The controller returned HTTP 200, the agent logged Connected, both +running containers reported the fixed Java build and their persistent mounts +matched the checkpoint. Existing private Gitea and Grafana checks passed. +A post-check initially assumed Java was process 1; Jenkins uses the normal +\texttt{tini} wrapper. Codex corrected the check to inspect the Java processes' +actual executables rather than treating the wrapper as a service failure. + +Codex updated source Dockerfiles, current image selectors, bootstrap references, +the current host inventory, maintenance runbook and this log. The live controller +build recipe was also patched with its original retained. Jobs, plugins, +permissions, credentials, release records, existing application containers and +other services were preserved. No release pipeline, human approval, commit or +push was performed. Root-only recovery checkpoints remain on the existing paid +Droplet; selected non-secret evidence remains in the ignored local build folder. +Local Zammad and its data remain stopped and unchanged; its future image review +is separate from this completed cloud runtime update. The full manual is rebuilt +with TinyTeX and affected pages are visually reviewed for this record. + +On November 25 Vincent requested separate branches after confirming the +Assignment 8 merge. Codex fetched and verified merge \texttt{6064cce}, +then prepared a separate worktree from that main on: +\begin{quote}\small +\path{codex/security-java-runtime} +\end{quote} +Only the Java source/runbook changes and their manual records +were placed here; Zammad and demo work remain in separate worktrees. +Original mixed changes were preserved and verified before separation. +No additional runtime operation, commit or push was performed. diff --git a/manual/latex/devopsDocumentHistory.tex b/manual/latex/devopsDocumentHistory.tex index a19a923..57c6c94 100644 --- a/manual/latex/devopsDocumentHistory.tex +++ b/manual/latex/devopsDocumentHistory.tex @@ -12,6 +12,7 @@ link each entry to the changed chapter, table, figure, or controlled artifact. \multicolumn{4}{l}{\small\itshape Document Update History (continued)}\\ \toprule \textbf{Date / Version} & \textbf{Author Initials} & \textbf{Change} & \textbf{Changed At}\\ \midrule \endhead \bottomrule \endlastfoot +November 23, 2026 / 7.0 maintenance & VS, CDX & At Vincent's request, patched the live Jenkins controller and trusted delivery agent to Temurin 21.0.13.1+2 for CVE-2026-114938. Retained application versions, plugins, persistent mounts and recovery images; verified controller HTTP and agent reconnection. Updated future build recipes, image selectors and current host inventory. Local Zammad remains stopped; Assignment 9 remains incomplete. & \hyperref[Chapter:HostsPasswords]{Hosts}, \hyperref[Chapter:AIPromptLog]{AI log}\\ November 15, 2026 / 6.4 & VS, BY, CDX & Verified Billy's PR~\#27 review and Vincent's merge; completed human-approved production rollback (build 8), blocked staging fault (9), and original-configuration recovery with changed=0 (10). Preserved build 7's pre-deployment runner error, measured HTTPS interruptions and monitoring sampling limits. Added original CSVs, hashes, runtime state, timelines, source/access links and final evidence; created issue~\#28 with Vincent's approval during finalization. Updated the Hosts table and architecture to production v1/staging v2; Passwords hints and permissions are unchanged. Prepared the complete manual for submission review. & \ChapterRef{SecureDelivery}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\ November 15, 2026 / 6.3 & BY, VS, CDX & Recorded PR~\#26's review/merge and successful Jenkins v1/v2 releases 5/6, zero-change reruns, actual vsun1 approvals and identical per-release staging/production digests. Saved the four real selectors for review. Applied the reviewed production probe/panel after healthy v1, verified live targets/Grafana and preserved one HTTP 502 sample during v2 replacement. Updated both-app inventory and architecture; prepared a staging-only fault patch and reviewed-history/revert procedure for the still-pending recovery exercises. Passwords hints and access scopes are unchanged. & \ChapterRef{SecureDelivery}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\ November 15, 2026 / 6.2 & VS, CDX & Verified PR~\#25's review/merge and ran pricing build 4: scans/publication and initial staging checks passed; the unchanged rerun blocked at the three-second Docker health deadline. Tested ten seconds under identical limits in an isolated temporary container: eight checks passed, then the container was removed. Prepared the health correction and separate v2 source/test change for one review preserving both commits. Updated staging inventory, diagram and actual evidence; Passwords hints are unchanged. No production approval or completed release is claimed. & \ChapterRef{SecureDelivery}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\ diff --git a/manual/latex/devopsHostsPasswords.tex b/manual/latex/devopsHostsPasswords.tex index 5168ca1..5eeabc6 100644 --- a/manual/latex/devopsHostsPasswords.tex +++ b/manual/latex/devopsHostsPasswords.tex @@ -47,12 +47,15 @@ healthy production. No credential or permission changed during these runs. \bottomrule \endlastfoot Role & Gitea work hub (Gitea 1.27.3 behind Caddy 2.11.4 TLS proxy); since 22 Oct 2026 also the Jenkins 2.580.1 LTS controller, which runs the CI builds; +its Java runtime was patched to Temurin 21.0.13.1+2 on 23 Nov 2026; since 28 Oct 2026 also the monitoring stack (Prometheus 3.15.1, Grafana OSS 13.2.5, Node Exporter 1.12.1, Blackbox Exporter 0.29.1). The Assignment 3 Color Buttons app (29 Sep 2026) is retired: container stopped with restart policy \texttt{no}; its Caddy route remains\\ Delivery agent & Legacy node \texttt{ssw590-vince-delivery}, label \texttt{delivery-trusted}, one exclusive executor; image -\texttt{ssw590-delivery-agent:20261114}. RAM / RAM+swap: 512 / 768 MiB, +\texttt{ssw590-delivery-agent:}\allowbreak +\texttt{20261114-java21.0.13.1-2}, with patched Temurin 21.0.13.1+2 +(23 Nov 2026). RAM / RAM+swap: 512 / 768 MiB, 0.5 CPU; separate pinned BuildKit: 256 / 384 MiB, 0.5 CPU. Private WebSocket to Jenkins and SSH through Docker host gateway with pinned public-IP host-key alias. Docker socket control grants host administration. diff --git a/security/java/Dockerfile b/security/java/Dockerfile new file mode 100644 index 0000000..6288cf9 --- /dev/null +++ b/security/java/Dockerfile @@ -0,0 +1,12 @@ +# Runtime-only update for an existing Jenkins controller or trusted agent image. +# BASE_IMAGE must be a local rollback tag verified against the running image ID. +# The final image retains the application's version, tools, plugins and user. +ARG BASE_IMAGE +FROM eclipse-temurin:21.0.13.1_2-jdk-jammy@sha256:4b3d0998ee65462bd86ff060c87119b3575294cb3d0927372afa6f3708b0c8db AS patched_java +FROM ${BASE_IMAGE} +USER root +RUN rm -rf /opt/java/openjdk +COPY --from=patched_java /opt/java/openjdk /opt/java/openjdk +ENV JAVA_VERSION=jdk-21.0.13.1+2 +USER jenkins +RUN java -version diff --git a/security/java/README.md b/security/java/README.md new file mode 100644 index 0000000..6138a28 --- /dev/null +++ b/security/java/README.md @@ -0,0 +1,99 @@ +# Java runtime security maintenance - 23 November 2026 + +Vincent authorized patching CVE-2026-114938 after reviewing DigitalOcean's +OpenJDK alert. This is operational maintenance, separate from the pending +Assignment 9 Zammad setup. No commits or pushes were requested. + +The running Jenkins controller used Temurin 21.0.12.1+1 and its trusted delivery +agent used 21.0.13+9. Both were replaced with **Temurin 21.0.13.1+2**, which +[Adoptium identifies as fixed](https://adoptium.net/news/2026/11/temurin-november-2026-cspu-java4shell). +The Droplet's exposed CPU flags did not include AVX-512 VBMI; that is a required +hardware condition for the documented exploit. Updating the runtimes avoids +depending on that hardware limitation. + +| Service | Updated image | Actual local image ID | +| --- | --- | --- | +| Jenkins controller | `ssw590-jenkins:2.580.1-java21.0.13.1-2` | `05067cf69fd76a98de8d434e7af9782cb9f979e0db3301760038da557cd5927b` | +| Trusted delivery agent | `ssw590-delivery-agent:20261114-java21.0.13.1-2` | `8d6302db4598887010c11ee7de0f87b0f62ab92e53bf7ec1e81fbab98d9778a7` | + +The official `eclipse-temurin:21.0.13.1_2-jdk-jammy` runtime stage is pinned to +index digest `sha256:4b3d0998ee65462bd86ff060c87119b3575294cb3d0927372afa6f3708b0c8db`. +Its Linux/amd64 manifest was +`sha256:4e38bcd64a552586921cdd011831cabc0d56c4f7c950aa460c0b9e03237871ed`. +Only `/opt/java/openjdk` and its descriptive `JAVA_VERSION` environment value +were replaced in the existing application images. Jenkins remains 2.580.1; +plugins, tools, identity and workspace were retained. No production release, +approval, dependency upgrade or database migration was performed. + +## Procedure and verification + +`patch-existing.py` is deliberately specific to The-Ocean's two existing Compose +projects. Review its paths before reuse. Its `prepare` action captures selected +non-secret metadata, saves Compose copies, refuses unfinished/queued Jenkins +work, pulls the pinned runtime and builds both images sequentially. Builds used +512 MiB and 0.5 CPU limits. Isolated smoke containers have no network or data +mounts and a read-only filesystem. The legacy builder warning was retained; +this choice permits explicit build-container limits on this small host. + +The `apply` action checks the checkpoint again, changes only the two image +selectors, stops the idle agent, recreates the controller, waits for its login +page, and recreates the agent. It verifies the fixed runtime, running state, +absence of OOM kills, and identical persistent mounts. It does not automatically +roll back after an error; inspect the checkpoint and service state first. + +Executed verification confirmed Jenkins login HTTP 200 and the agent's +`Connected` message. Gitea and Grafana private HTTP checks passed. The live +controller Dockerfile was also updated to retain the fix on future builds; +its original was preserved. The pricing containers, proxy, monitoring and +manual runner were not recreated. No full release pipeline was triggered. + +Selected-field evidence is retained in ignored +`build/evidence/java-patch-20261123/`. On the Droplet, checkpoints and logs remain +in root-only `/root/ssw590-java-patch-20261123/`. Credentials and full Docker +inspect output are excluded. No additional cloud resource or plan was created; +this used the existing paid Droplet, with transient CPU, storage and network use. + +## Recovery + +The original images retain the local tags +`ssw590-java-rollback:jenkins-20261123` and +`ssw590-java-rollback:agent-20261123` as recovery checkpoints. They contain the +old runtime; do not select them during normal operation. + +If the new runtime causes a verified operational regression, first stop or drain +Jenkins work. On the authorized host, restore the corresponding saved Compose +file from the root-only checkpoint directory to its original path: + +- `jenkins-compose.before` -> `/root/gitea/docker-compose.yml` +- `agent-compose.before` -> `/opt/ssw590-delivery-agent/compose.droplet.yaml` + +Validate with `docker compose -f config --quiet`, then recreate +only that service using `up -d --no-deps --pull never ` from its project +directory. Original image tags remain present. Preserve volumes and identities; +never use `down -v`. Restoring the old controller Dockerfile is needed only if +its future build recipe must also be reverted. If running the old Java build on +affected hardware, the vendor's interim mitigation is +`-XX:-UseBASE64Intrinsics` followed by a service restart. + +Retain the checkpoint images and files until the group has reviewed the update. +Do not prune shared Docker images, build caches or volumes to clean up this task. + +## Scope limits + +Local Zammad remains stopped and unchanged. Its Elasticsearch Java build also +predates the fix, but the laptop's Docker VM was verified to lack AVX-512 VBMI. +Review its official patched image before the next local setup session. +The earlier PHP inventory found no PHP; this Java patch does not install PHP. +The NGINX alert and its separately recorded HTTP/2 assessment remain separate. + +For a future full source rebuild, the controller and agent Dockerfiles also +copy the same pinned fixed Java stage. Build the agent from `delivery/`: + +```sh +docker build -f agent/Dockerfile -t ssw590-delivery-agent:20261114-java21.0.13.1-2 . +``` + +Build the controller using its Compose project. Full source rebuild image IDs +will differ from the runtime-only maintenance images above; verify Java again. +The stopped laptop fallback requires the patched agent image to be built or +loaded before it can be used. Never start it alongside the active cloud agent. diff --git a/security/java/patch-existing.py b/security/java/patch-existing.py new file mode 100644 index 0000000..a1ee91e --- /dev/null +++ b/security/java/patch-existing.py @@ -0,0 +1,160 @@ +"""Targeted The-Ocean Java update; run as root after reviewing this file. + +prepare builds and smoke-tests images without restarting services. apply +requires those prepared images and refuses active/queued Jenkins work. +Rollback copies and selected-field evidence remain outside the repository. +""" +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +import xml.etree.ElementTree as ET + +ROOT = Path('/root/ssw590-java-patch-20261123') +JAVA_IMAGE = ('eclipse-temurin:21.0.13.1_2-jdk-jammy@' + 'sha256:4b3d0998ee65462bd86ff060c87119b3575294cb3d0927372afa6f3708b0c8db') +SERVICES = [ + dict(name='gitea-jenkins-1', service='jenkins', + directory='/root/gitea', compose='docker-compose.yml', + image='ssw590-jenkins:2.580.1-java21.0.13.1-2'), + dict(name='ssw590-delivery-agent-1', service='agent', + directory='/opt/ssw590-delivery-agent', compose='compose.droplet.yaml', + image='ssw590-delivery-agent:20261114-java21.0.13.1-2'), +] + + +def run(*args, capture=True, **kwargs): + result = subprocess.run(args, check=True, text=True, + stdout=subprocess.PIPE if capture else None, + stderr=subprocess.STDOUT, **kwargs) + return result.stdout.strip() if capture else '' + + +def inspect(name): + # Never serialize full inspect output: it can contain secret environment values. + obj = json.loads(run('docker', 'inspect', name))[0] + return dict(name=name, image=obj['Image'], reference=obj['Config']['Image'], + running=obj['State']['Running'], oom=obj['State']['OOMKilled'], + restarts=obj['RestartCount'], + mounts=[dict(type=m['Type'], source=m['Source'], + destination=m['Destination'], rw=m['RW']) + for m in obj['Mounts']]) + + +def assert_idle(): + home = Path(run('docker', 'volume', 'inspect', '-f', '{{.Mountpoint}}', + 'gitea_jenkins-home')) + active = [] + for path in (home / 'jobs').rglob('build.xml'): + tree = ET.parse(path).getroot() + if tree.find('result') is None: + active.append(str(path.relative_to(home))) + assert not active, 'Refusing restart: unfinished Jenkins builds: ' + repr(active) + queue = home / 'queue.xml' + if queue.exists(): + tree = ET.parse(queue).getroot() + assert not list(tree.iter('item')), 'Refusing restart: Jenkins queue is nonempty' + for items in tree.iter('items'): + assert not list(items), 'Refusing restart: Jenkins queue contains work' + + +def smoke(image): + result = run('docker', 'run', '--rm', '--pull', 'never', '--network', 'none', + '--read-only', '--cap-drop', 'ALL', '--security-opt', + 'no-new-privileges', '--entrypoint', 'java', image, '-version') + assert '21.0.13.1' in result and '+2' in result, result + return result + + +def compose(spec, *args): + return run('docker', 'compose', '-f', spec['compose'], *args, + cwd=spec['directory']) + + +def prepare(): + ROOT.mkdir(mode=0o700, exist_ok=True) + os.chmod(ROOT, 0o700) + before_path = ROOT / 'before.json' + if before_path.exists(): + before = json.loads(before_path.read_text()) + assert [inspect(s['name'])['image'] for s in SERVICES] == [ + s['image'] for s in before], 'Current images differ from original checkpoint' + else: + before = [inspect(s['name']) for s in SERVICES] + before_path.write_text(json.dumps(before, indent=2) + '\n') + for spec in SERVICES: + shutil.copy2(Path(spec['directory']) / spec['compose'], + ROOT / (spec['service'] + '-compose.before')) + assert_idle() + run('docker', 'pull', JAVA_IMAGE, capture=False) + smoke(JAVA_IMAGE) + env = dict(os.environ, DOCKER_BUILDKIT='0') + # No application state, Compose backup or evidence enters the build context. + context = ROOT / 'empty-context' + context.mkdir(exist_ok=True) + built = [] + for spec, old in zip(SERVICES, before): + rollback = 'ssw590-java-rollback:' + spec['service'] + '-20261123' + run('docker', 'tag', old['image'], rollback) + run('docker', 'build', '--pull=false', '--memory', '512m', + '--cpu-quota', '50000', '--build-arg', 'BASE_IMAGE=' + rollback, + '-t', spec['image'], '-f', str(ROOT / 'Dockerfile'), str(context), + env=env, capture=False) + built.append(dict(name=spec['name'], reference=spec['image'], + image=run('docker', 'image', 'inspect', '-f', '{{.Id}}', spec['image']), + java=smoke(spec['image']), rollback=rollback)) + (ROOT / 'prepared.json').write_text(json.dumps(built, indent=2) + '\n') + print(json.dumps(built, indent=2)) + + +def apply(): + before = json.loads((ROOT / 'before.json').read_text()) + prepared = json.loads((ROOT / 'prepared.json').read_text()) + assert_idle() + for spec, old, built in zip(SERVICES, before, prepared): + assert inspect(spec['name'])['image'] == old['image'], 'Unexpected current image' + assert run('docker', 'image', 'inspect', '-f', '{{.Id}}', spec['image']) == built['image'] + path = Path(spec['directory']) / spec['compose'] + assert path.read_bytes() == (ROOT / (spec['service'] + '-compose.before')).read_bytes(), 'Compose changed after preparation' + source = path.read_text() + needle = 'image: ' + old['reference'] + assert source.count(needle) == 1, 'Expected exactly one original image selector' + path.write_text(source.replace(needle, 'image: ' + spec['image'])) + compose(spec, 'config', '--quiet') + # Stop the idle agent first so no delivery job can start during maintenance. + compose(SERVICES[1], 'stop', '-t', '30', 'agent') + compose(SERVICES[0], 'up', '-d', '--no-deps', '--pull', 'never', 'jenkins') + for _ in range(60): + try: + code = run('docker', 'exec', SERVICES[0]['name'], 'curl', '-sS', + '--max-time', '5', '-o', '/dev/null', '-w', '%{http_code}', + 'http://localhost:8080/login') if inspect(SERVICES[0]['name'])['running'] else '000' + except subprocess.CalledProcessError: + code = '000' + if code == '200': + break + time.sleep(3) + else: + raise RuntimeError('Controller did not return HTTP 200; retain checkpoint and investigate') + compose(SERVICES[1], 'up', '-d', '--no-deps', '--pull', 'never', 'agent') + after = [] + for spec, old in zip(SERVICES, before): + now = inspect(spec['name']) + assert now['running'] and not now['oom'] + assert now['mounts'] == old['mounts'], 'Persistent mounts changed' + now['java'] = run('docker', 'exec', spec['name'], 'java', '-version') + assert '21.0.13.1' in now['java'] and '+2' in now['java'] + after.append(now) + (ROOT / 'after.json').write_text(json.dumps(after, indent=2) + '\n') + print(json.dumps(after, indent=2)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=['prepare', 'apply']) + args = parser.parse_args() + assert os.geteuid() == 0, 'Run as root on the authorized host' + {'prepare': prepare, 'apply': apply}[args.action]()