Author SHA1 Message Date
vsun1 29e580c461 Revert "Exercise staging-only Gunicorn bind mismatch"
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
This reverts commit 1e23001e73.
2026-11-15 23:00:00 -05:00
vsun1 1e23001e73 Exercise staging-only Gunicorn bind mismatch 2026-11-15 23:00:00 -05:00
vsun1 6c5342219a Record verified releases and prepare recovery exercises 2026-11-15 23:00:00 -05:00
vsun1 231d11528a Merge pull request 'Codex/assignment8 v1 v2 evidence' (#26) from codex/assignment8-v1-v2-evidence into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 2m7s
Reviewed-on: #26
Reviewed-by: bill <yebilly4@gmail.com>
2026-11-16 02:57:41 +00:00
vsun1 6bddbfba5a Add pricing v2 at twelve dollars per unit
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
2026-11-15 21:54:21 -05:00
vsun1 34f26e6948 Allow constrained pricing health checks to complete 2026-11-15 21:54:21 -05:00
vsun1 a19fab34e3 Merge pull request 'Fix noninteractive Ansible deployment and record delivery gates' (#25) from codex/assignment8-release-evidence into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 2m7s
Reviewed-on: #25
Reviewed-by: bill <yebilly4@gmail.com>
2026-11-16 01:51:04 +00:00
vsun1 5b703edc79 Fix noninteractive Ansible deployment and record delivery gates
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
2026-11-15 18:07:48 -05:00
vsun1 09731acb03 Merge pull request 'Prepare Assignment 8 secure delivery and rollback' (#24) from codex/assignment8-secure-delivery into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 2m25s
Reviewed-on: #24
Reviewed-by: bill <yebilly4@gmail.com>
2026-11-15 21:59:30 +00:00
vsun1 ed0a862657 Move CI runners to Droplet and enable application HTTPS
vpn-dns-gateway/pipeline/pr-main This commit looks good
2026-11-15 12:49:06 -05:00
vsun1 bf28adc7fb Prepare Assignment 8 secure delivery and rollback
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
Add the locked pricing service, trusted-agent pipeline, Ansible deployments, security gates, recovery runbooks, prerequisite evidence, and preparation manual.

Prepared with Codex assistance. Vincent explicitly authorized this local commit and will handle the push. Assessed releases and recovery exercises remain pending.
2026-11-14 17:09:25 -05:00
vsun1 8beefde2a4 Merge pull request 'Finalize Assignment 7 evidence and documentation (refs #19)' (#23) from codex/assignment7-final-corrections into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 4m32s
Reviewed-on: #23
Reviewed-by: bill <yebilly4@gmail.com>
2026-10-28 20:34:40 +00:00
vsun1 4d1996c0ab Finalize Assignment 7 evidence and local manual builds (refs #19)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
2026-10-28 16:23:42 -04:00
bill 34c4c7488a Merge pull request 'Add Prometheus/Grafana monitoring and SRE manual chapter (Assignment 7)' (#22) from feature/issue-19-monitoring into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 45s
Reviewed-on: #22
Reviewed-by: vsun1 <vsun4046@gmail.com>
2026-10-28 18:18:35 +00:00
billandClaude Opus 5.5 11270cfced Address second chapter audit: accuracy and presentation (refs #19)
vpn-dns-gateway/pipeline/pr-main This commit looks good
A second independent, grader-style review of the built PDF found smaller
gaps; all fixed except template-wide items left unchanged.

- Build comparison: phase labels match the 1-minute rate windows
  (15:17:30 is before the build), 15:19:30 row added, Phase header,
  2-minute vs 1-minute rate difference explained, no-annotation reason,
  and the baseline-build deviation from Step 1 stated.
- Full image digests listed; metric inventory gains a labels column;
  collection-test figure adds the HTTPS resolved capture.
- Corrections: network membership of the exporters, dashboard version
  wording, "two and a half minutes", diagram network name, "A SLO/SLA",
  -- rendering in retention flags, dashboard capture predating the
  I/O-wait line.
- Presentation: login URLs as a list, floats for DNS/dashboard figures,
  split wrapped queries, unbroken restart policy, Grafana OSS casing in
  the bibliography, Windows taskbar cropped from Grafana screenshots.
- Starting commit linked; backup pins alpine:3.22 and documents restore;
  MFA recorded for Billy's Discord and GitHub; EVIDENCE.md records the
  PR #22 approvals, pr-main checks, and the live verification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:13:51 -04:00
billandClaude Opus 5.5 249488d6fc Address chapter audit: collection-health alert, hardening, citations (refs #19)
vpn-dns-gateway/pipeline/pr-main This commit looks good
An independent review of the SRE chapter against the instructor's rubric
found gaps; each was fixed and, where operational, tested on the droplet.

Monitoring:
- New Grafana rule "Monitoring target down" (up < 1 for 1 m, no data ->
  Alerting). Tested by stopping Blackbox Exporter 17:34:44-17:37:52 UTC:
  it fired and resolved, and "HTTPS service down" fired on NoData when
  every probe series disappeared.
- Blackbox Exporter runs as nobody (65534) instead of the image's root.
- README: runbook for the new rule; contact-point test prompts for the
  password; secrets section reflects the replaced admin password.

Manual (v5.0):
- Alert table with all three rules and their summaries; runbooks in the
  PDF; accurate no-data description; collection-test figure.
- Diagram shows networks per container and the existing volumes.
- Targets table, CPU counters vs /proc/stat, probe module excerpt,
  container identities and mounts, backup command, exposure commands,
  replaced Grafana admin credential, PR #22 and review gate.
- Bibliography enabled with SRE Workbook and tool documentation.
- Corrected baseline memory figures, Jenkins start-up length, dashboard
  version wording, and start-up order; links point to main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:52:13 -04:00
billandClaude Opus 5.5 336eaaefa7 Add SRE monitoring chapter and manual v5.0 (refs #19)
vpn-dns-gateway/pipeline/pr-main This commit looks good
New chapter "Introduction to SRE: Monitoring and Reliability" covering the
eight Assignment 7 rubric rows: deployment and capacity trial, metrics and
probes, HTTPS and exposure tests, dashboard and build comparison, SLI/SLO
worked example and measured window, alert rules and tests, the Jenkins
outage exercise with blameless review (#20, #21), and controls.

- Title page and abstract for Assignment 7 "Grafana and Prometheus SRE --
  Group", version 5.0; Document History entry.
- Hosts table: monitoring containers, ports, volumes, metrics DNS, swap,
  disabled host services, monitoring and backup status.
- Passwords table: Grafana billy and vsun1, monitoring secrets file,
  Discord webhook (hints only).
- Glossary: SLI, SLA, SRE, error budget, exporter, scrape, contact point,
  blameless review. AI prompt log record.
- EVIDENCE.md: SLO window, post-recovery build, probe status codes,
  improvement issues, Grafana accounts. Outage dashboard figure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:08:23 -04:00
billandClaude Opus 5.5 b6cf080618 Record alert tests, Jenkins outage drill, and restart persistence (refs #19)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
- Dashboard: CPU panel adds an I/O wait series; the background CPU on
  the 1 GiB droplet is mostly swap-in wait, not computation.
- EVIDENCE.md: normal Jenkins build #1 vs host metrics (no attributable
  change), Discord contact-point test, capacity alert test (threshold
  raised to 70% on the droplet, fired after 5 m, restored to 15%),
  controlled Jenkins outage timeline (firing ~2 m after injection,
  recovery ~1 m after restart), and Prometheus/Grafana restart
  persistence with no collection gap.
- Screenshots: build window, disk alert firing/resolved, Jenkins alert
  firing/resolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:30:30 -04:00
billandClaude Opus 5.5 d3a5e6bc73 Add Prometheus/Grafana monitoring stack (refs #19)
vpn-dns-gateway/pipeline/head This commit looks good
Assignment 7 (instructor manual v1.42, Chapter 5): Prometheus, Grafana OSS,
Node Exporter and Blackbox Exporter beside Gitea/Jenkins on The-Ocean, pinned
by tag and digest, memory-capped for the 1 GiB droplet, no host ports.

- monitoring/: compose, scrape and probe config, Grafana provisioning
  (data source, Group 1 SRE dashboard, two alert rules, Discord contact
  point via env var), README with deploy/backup/rollback and runbooks,
  EVIDENCE.md with the deploy, capacity and exposure test records.
- deploy/: private probe network (172.30.90.0/28) with Caddy aliases;
  ci allowlist admits only the Blackbox address 172.30.90.10; new
  metrics.yebilly.me route behind the same allowlist.
- manual images: DNS record, Discord webhook, contact-point test, dashboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:11:02 -04:00
vsun1 9b0dc4dc52 Merge pull request 'Finalize Assignment 6 documentation corrections' (#18) from codex/assignment6-final-corrections into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 34s
Reviewed-on: #18
Reviewed-by: bill <yebilly4@gmail.com>
2026-10-23 23:15:45 +00:00
vsun1 d54d801020 Finalize Assignment 6 documentation corrections
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
2026-10-23 18:06:07 -04:00
bill ac18f11186 Merge pull request 'Manual 4.1: access path, campus test, audit fixes' (#17) from docs/history-initials into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 34s
Reviewed-on: #17
Reviewed-by: vsun1 <vsun4046@gmail.com>
2026-10-23 20:55:12 +00:00
billandClaude Opus 5.5 6152f4777b Address re-audit findings in the Jenkins chapter (v4.1)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
- Add a table of all 14 Gitea webhook deliveries with commits and
  results, and diagnose the real timed-out delivery #3 (Jenkins still
  queued the build two seconds later).
- Redraw the deployment figure as a UML deployment diagram with
  <<device>>/<<container>>/<<artifact>>/<<executionEnvironment>>
  stereotypes; route checkout and status through Caddy.
- Show the stored Jenkins URL, free disk space, and reconciled plugin
  counts (59 tested, 63 locked, 66 installed).
- Correct wording on push rights (jenkins-bot also has Write), the
  resource-limit change, five corrective actions, startup timings, and
  the AI log's backup statement; quote the run-1 checkout.
- Fix the stray tab that printed "extttStevens-Net", the stale
  "version 4.0" sentence, and the overflowing VPN table row; note that
  grader IPs are removed from .env after grading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:01:00 -04:00
billandClaude Opus 5.5 34bd5e6146 Correct Jenkins instructor access path and record campus test (v4.1)
The manual said the instructor could reach ci.yebilly.me from campus or
the Stevens VPN. A GlobalProtect test (sitvpn.stevens.edu, the only
gateway) showed the VPN is split-tunnel: only 155.246.0.0/16 is routed
through it, so off-campus visitors keep their own ISP address and get
403. The approved path is now the campus network (Stevens-Net), with
off-campus graders' addresses added to CI_TEAM_IPS on request.

Vincent's campus test on Stevens-Net (155.246.151.38) loaded the Jenkins
sign-in page; it is added as a figure and a PASS row in the exposure
table alongside the VPN finding. Password field and personal addresses
are redacted. Bumps the manual to 4.1 with a history row and AI log
entry, and updates the Caddyfile comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:46:41 -04:00
billandClaude Opus 5.5 92bc9545e2 Use short AI initials in Document History (CDX, CD)
Replace the tool names in the Author Initials column with initials:
OpenAI Codex -> CDX (matching the existing DDM, CDX rows) and Anthropic
Claude -> CD. GEM is reserved for Google Gemini; no row uses it yet.
Only the initials column changes; dates, versions, and change text are
untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:23:33 -04:00
bill e4f3ce5dfb Merge pull request 'Document Assignment 6 Jenkins CI in the manual' (#16) from docs/assignment6-jenkins-manual into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 32s
Reviewed-on: #16
Reviewed-by: vsun1 <vsun4046@gmail.com>
2026-10-23 01:24:41 +00:00
billandClaude Opus 5.5 1149e9fbc3 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>
2026-10-22 21:20:31 -04:00
bill 420ba4c56b Merge pull request 'Add Jenkins CI with required merge check' (#15) from feature/issue-14 into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 30s
Reviewed-on: #15
Reviewed-by: vsun1 <vsun4046@gmail.com>
2026-10-23 00:55:20 +00:00
billandClaude Opus 5.5 9381d2aa9a Repair total_price: restore multiplication (refs #14)
vpn-dns-gateway/pipeline/pr-main This commit looks good
Reverts the controlled failure from 52b297c so the Jenkins Test stage
passes again and the required check on PR #15 turns green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:15:06 -04:00
billandClaude Opus 5.5 52b297c2f3 Controlled failure: add instead of multiply in total_price (refs #14)
vpn-dns-gateway/pipeline/pr-main There was a failure building this commit
Deliberately breaks the pricing calculation so the Jenkins Test stage
fails (10 + 3 = 13, expected 30) and the required Gitea check blocks
merging PR #15. The next commit restores multiplication.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:10:28 -04:00
billandClaude Opus 5.5 ad35197ee4 Add Jenkins CI service, pricing app, tests and Jenkinsfile (refs #14)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
Deploy Jenkins LTS 2.580.1 beside Gitea on The-Ocean:
- deploy/jenkins: official image pinned by digest plus python3 and a
  hashed 60-plugin lockfile (Pipeline + Gitea bundle tested by
  ci/jenkins-capacity, plus matrix-auth for named roles)
- compose: jenkins service with persistent jenkins-home, no published
  ports, 512 MiB RAM / 768 MiB RAM+swap / 0.75 CPU, 256 MiB heap
- Gitea webhooks restricted to the private jenkins host; Caddy alias
  keeps Jenkins->Gitea checkout and status traffic on the droplet
- Caddy serves ci.yebilly.me only to Stevens 155.246.0.0/16 and team
  IPs from the untracked .env

Add the instructor's pricing example, unit tests and Declarative
Jenkinsfile (checkout, syntax check, unit tests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:55:59 -04:00
vsun1 1389c53165 Merge pull request 'Automate LaTeX manual builds with Gitea Actions' (#13) from codex/assignment5-manual-build into main
Automated Manual Build / manual (push) Successful in 36s
Reviewed-on: #13
Reviewed-by: bill <yebilly4@gmail.com>
2026-10-08 05:19:02 +00:00
153 changed files with 10240 additions and 70 deletions
+7
View File
@@ -0,0 +1,7 @@
# Docker/Jenkins shell scripts require Unix line endings on Windows checkouts.
delivery/**/*.sh text eol=lf
delivery/agent/ssh_config.droplet text eol=lf
gitea/droplet-runner/*.sh text eol=lf
# Preserve spaces emitted by tools in captured evidence.
delivery/evidence/*.txt -whitespace
+10 -2
View File
@@ -91,5 +91,13 @@ Thumbs.db
*.key
secrets.*
# Source images, the reference template, and the reviewed root submission PDF
# are intentionally not ignored.
# Source images and the reference template remain versioned.
# Local manual builds replace one deliverable; do not commit generated PDFs.
/manual/2026F-SSW-590-DevOps-Group-1.pdf
/manual/latex/devopsAssignment.pdf
# Python test environments and bytecode
.venv/
.ansible-venv/
__pycache__/
*.pyc
Vendored
+27
View File
@@ -0,0 +1,27 @@
pipeline {
agent any
options { skipDefaultCheckout() }
stages {
stage('Checkout') {
steps { checkout scm }
}
stage('Syntax check') {
steps {
sh 'python3 -m py_compile pricing.py'
sh '''python3 -B - <<'PY'
import ast
from pathlib import Path
for source in Path('delivery').rglob('*.py'):
ast.parse(source.read_text(), filename=str(source))
print('Delivery Python syntax: passed')
PY'''
}
}
stage('Test') {
steps {
sh 'python3 -m unittest discover -s tests -v'
sh 'python3 -B -m unittest discover -s delivery/ci -p "test_controls.py" -v'
}
}
}
}
+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)
+11
View File
@@ -1,5 +1,16 @@
# Manual compiler and Gitea workflow
## Current runner placement
On 14 November 2026 Vincent requested moving the active Actions runner onto
The-Ocean. Its historical name/label remain `ssw590-vince-local` / `latex-local`;
the same tested compiler image below was transferred with checksum verification.
The laptop daemon is stopped. Remote jobs are capped at 512 MiB RAM / 768 MiB
RAM+swap and 0.5 CPU. Run them sequentially with Jenkins delivery work.
See [remote runner operations](../../gitea/droplet-runner/README.md).
The Docker Desktop instructions below remain useful for image reproduction
and an explicitly selected fallback, not for starting a second live runner.
## Local runner preparation
Build the job image on the runner's Docker Desktop engine from repository root:
+4
View File
@@ -0,0 +1,4 @@
**/__pycache__
**/.venv
**/*.pyc
agent/.env
+178
View File
@@ -0,0 +1,178 @@
# Billy / Claude handoff: Assignment 8 DNS
**Completed update, 15 November 2026:** Billy added both A records. Google and
Cloudflare resolve them to `147.182.178.136`; Caddy now serves trusted HTTPS and
redirects HTTP for both names. The app backends are still absent (HTTP 502).
Do not repeat DNS setup. The original handoff below is retained as the dated
November 14 preparation record; reviewed application releases remain pending.
Prepared for Billy Ye at Vincent Sun's request on **14 November 2026**.
This file is context and a proposed procedure. Billy must authorize changes
in his own session; it does not grant Claude account access or override its
active instructions. Billy handles login and MFA privately.
## Quick start for Claude
Help Billy add the two A records below to the existing `yebilly.me` DNS zone,
verify public resolution, and return a short evidence summary to Vincent.
Recheck existing records first. Preserve earlier services and stop after DNS
verification. SSH, Docker, Jenkins and application deployment are outside this
DNS task. Do not rerun the deployment bootstrap; it is already complete.
```yaml
task: assignment_8_dns_setup
scope: two_A_records_and_verification
domain: yebilly.me
expected_provider: Namecheap
droplet_name: The-Ocean
droplet_ipv4: 147.182.178.136
repository: https://git.yebilly.me/ssw590-group1/vpn-dns-gateway
prepared_branch: codex/assignment8-secure-delivery
prepared_commit: bf28adc7fb03fe25c5cc939599e34427a61ad2fc
records_to_add:
- type: A
host: staging
fqdn: staging.yebilly.me
value: 147.182.178.136
ttl: Automatic
- type: A
host: app
fqdn: app.yebilly.me
value: 147.182.178.136
ttl: Automatic
success_condition: both_names_resolve_to_the_expected_IPv4_and_existing_records_are_preserved
next_owner: Vincent_and_Codex_for_Caddy_TLS_and_reviewed_release_execution
```
## Why these records are needed
Assignment 8 follows **Chapter 6, Secure Delivery and Rollback**, in instructor
manual `dosManual-V1.43.pdf`. It requires distinct staging and production HTTPS
hostnames. Both applications will run on the same existing droplet, in separate
Docker Compose projects. Caddy selects the private application by hostname:
| Public hostname | Intended destination behind Caddy |
|---|---|
| `staging.yebilly.me` | `pricing-staging:8000` |
| `app.yebilly.me` | `pricing-production:8000` |
An A record maps a name to the droplet's IPv4 address. It does not contain a
port, URL scheme, or application path. Caddy will handle HTTPS certificates.
This task uses the existing domain and droplet; no purchase is part of it.
Preparation already completed: locked v1 pricing service, Ansible, release and
security gates, a trusted Jenkins agent now on The-Ocean (migrated from Vincent's
laptop to avoid campus SSH restrictions), dedicated deployment
access and scoped credentials. The prerequisite Jenkins job passed. The
prepared branch was pushed and its ordinary Jenkins branch check passed.
Peer review/merge, assessed releases and recovery exercises remain outstanding.
The release job is disabled pending reviewed source. The new Caddy routes and
production monitoring additions are prepared in Git but have not been applied.
## Observed baseline: recheck before making changes
Public Cloudflare DNS-over-HTTPS queries were checked on
**14 November 2026, about 20:35 America/New_York**
(15 November, about 01:35 UTC). These are observations, not a guarantee that
the zone will remain unchanged when Billy opens it.
| Query | Observed answer |
|---|---|
| `yebilly.me` NS | `dns1.registrar-servers.com`, `dns2.registrar-servers.com` |
| `staging.yebilly.me` A | NXDOMAIN: name did not exist |
| `app.yebilly.me` A | NXDOMAIN: name did not exist |
| `git.yebilly.me` A | `147.182.178.136` |
| `ci.yebilly.me` A | `147.182.178.136` |
| `metrics.yebilly.me` A | `147.182.178.136` |
The existing services are Gitea (`git`), Jenkins (`ci`) and Grafana (`metrics`).
Other zone records may also exist, including the retired Color Buttons name,
mail and verification records. Preserve them. The droplet has been resized to
2 GiB RAM with its 25 GB plan disk retained; no address change was observed.
## Namecheap procedure
1. Billy signs in to the account managing `yebilly.me`.
2. Open **Domain List > Manage** beside that domain, then **Advanced DNS**.
3. In **Host Records**, add the two rows from the YAML/table. Enter only
`staging` or `app` in the Host field. Use **A Record**, the exact IPv4 value,
and **Automatic** TTL. Save the two additions.
4. Inspect the saved rows and retain a cropped screenshot showing those rows,
with account, billing, login and secret information excluded.
If a requested record already has the correct value, reuse it. If an existing
`staging` or `app` record conflicts (including a CNAME/redirect), explain the
conflict to Billy before changing it; do not delete unrelated records. This
request is for IPv4 A records, not additional AAAA, wildcard or redirect records.
If Host Records is unavailable or nameservers differ from the baseline, identify
the active DNS provider and edit the existing zone there. Keep nameserver
delegation unchanged. Namecheap documents this distinction in its host-record
guide linked below.
## Verify and capture evidence
From PowerShell, record the actual UTC time and check public resolution:
```powershell
[DateTime]::UtcNow.ToString('o')
Resolve-DnsName staging.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
Resolve-DnsName app.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
Resolve-DnsName staging.yebilly.me -Type A -Server 8.8.8.8 -DnsOnly
Resolve-DnsName app.yebilly.me -Type A -Server 8.8.8.8 -DnsOnly
```
Expected A answer for both names: **147.182.178.136**. A resolver may briefly
retain the earlier negative answer; allow caches to expire and repeat. A lookup
that times out on a restricted network is inconclusive. Do not report success
from the saved dashboard rows alone.
Recheck the earlier names as well:
```powershell
Resolve-DnsName git.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
Resolve-DnsName ci.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
Resolve-DnsName metrics.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
```
If direct public-resolver queries are blocked, use an available DNS lookup
method and record which resolver/method was actually used. Authoritative checks
can help distinguish an unsaved record from resolver caching; document the
actual results and any disagreement rather than assuming propagation completed.
**DNS success is not application success.** HTTPS may still be unavailable,
show a certificate problem, or return an upstream error before Vincent applies
Caddy routes and deploys the applications. Do not weaken TLS checks or alter
firewall rules to make a DNS-only check appear successful.
## Return to Vincent
Report:
- The two saved record types, hostnames, values and actual TTL selection.
- Verification UTC time, resolver(s), actual answers and any pending cache result.
- Confirmation that existing records were preserved, with the earlier-name checks.
- A cropped screenshot or text evidence containing no credentials/account details.
- Any blocker, conflicting record, or unverified assumption.
Then Vincent/Codex can finish Caddy HTTPS setup and the reviewed release tests.
Billy's separate code-review task remains: review/approve the preparation PR
if satisfied, and later review v2 and the staging failure configuration. DNS
completion does not approve code or authorize a production promotion.
For repository work, read `AGENTS.md`,
`manual/latex/devopsAIAgentRequirements.tex` and
`manual/latex/devopsAIAgentGuide.tex` first. Useful context is in
`delivery/README.md`, `delivery/RUNBOOKS.md`, `delivery/SECURITY.md`,
`deploy/Caddyfile` and `delivery/evidence/agent-preflight-1.txt`.
## Official references and provenance
- [Namecheap: add an A record](https://www.namecheap.com/support/knowledgebase/article.aspx/319/2237/how-can-i-set-up-an-a-address-record-for-my-domain/).
- [Namecheap: host records, provider selection and TTL](https://www.namecheap.com/support/knowledgebase/article.aspx/434/2237/how-do-i-set-up-host-records-for-a-domain/).
Codex prepared this handoff at Vincent's explicit request, using the repository's
prepared configuration, current public DNS observations and those official
Namecheap guides. No DNS account was opened or modified during its preparation.
The original instructor manual defines the assignment; the names/IP above are
the team's selected deployment values.
+71
View File
@@ -0,0 +1,71 @@
# Assignment 8 evidence
## Reviewed Jenkins execution, 15 November 2026
PRs 24–26 are merged. The actual [test/secret gate demonstrations](evidence/gates-20261115.md)
blocked as intended. [Release attempt 3](evidence/release-attempt-3-20261115.md)
published v1 and stopped at the Ansible PTY request. After that correction
merged, [release attempt 4](evidence/release-attempt-4-20261115.md) passed initial
staging checks but its unchanged rerun stopped at Docker's health timeout.
Eight isolated diagnostic probes passed with ten seconds instead of three.
After review, [builds 5 and 6](evidence/releases-20261115.md) completed v1/v2
promotions, zero-change reruns and actual human approvals. Production monitoring
is live; one HTTP 502 sample during v2 replacement is preserved. The exact
successful records and staging-only fault/revert history await review before
recovery. Both recovery exercises remain unexecuted.
## Preparation evidence — historical baseline
All timestamps below are UTC on 14 November 2026. No assessed application
release, image publication, production approval or rollback has occurred yet.
| Check | Actual result |
|---|---|
| 19:50 user-run original target baseline | 961 MiB RAM, 126 MiB available, 752 MiB swap used; deploy account absent |
| 20:15 post-resize SSH check | 1,967 MiB RAM, 1,008 MiB available, 101 MiB swap used; disk unchanged; seven containers up; zero failed systemd units |
| Post-maintenance external HTTPS | Gitea, Jenkins and Grafana login routes each returned HTTP 200 from laptop |
| 20:04 local runtime smoke | Gunicorn, UID 10001, read-only root/capability drops, 64 MiB cap; health v1, explicit `uncommitted-preflight` identity, total 30, invalid input HTTP 400 |
| 19:55 synthetic secret gate | Blocked; actual scanner detected the generated fixture; exit status 1 |
| 20:27 controlled wrong-price test | Three original tests passed; extra expected=-1 assertion failed; exit status 1 |
| 20:40 restored local app baseline | Three tests passed; exit status 0 |
| 20:32 full runtime image gate | Passed, zero HIGH/CRITICAL findings; full JSON and tool/database metadata retained |
| 21:00–21:01 final source/dependency gate | Passed; source scanner and pip-audit exit status 0 |
| Linux regression/syntax checks | Existing two tests and 12 delivery-control tests passed; Ansible syntax passed |
| Jenkins/Compose validation | Dedicated delivery pipeline validated using installed declarative parser; final agent Compose configuration validated |
| Proxy/monitoring candidates | Installed Caddy validation and Prometheus promtool syntax checks passed; candidates were not reloaded or applied |
| 20:40:49 Jenkins bootstrap | Exclusive node and folder-scoped credentials created; pricing release job disabled; earlier jobs retained |
| 20:42:28 agent connection | WebSocket opened; agent connected; no agent host port published |
| 20:46 agent prerequisite build 1 | SUCCESS; real Jenkins credential binding, pinned SSH host key, deploy login, sudo, Python/Docker/Compose prerequisites |
The final preflight image was local only, tagged
`ssw590-pricing:preflight-v1-runtime`. It is not a reviewed source release or
published registry RepoDigest. Earlier Debian and installer-containing Alpine
image scans were blocked and retained; no security exception was added.
Raw local reports: ignored `build/evidence/assignment8-local/`. Publicly
versioned prerequisite inventory: `evidence/agent-preflight-1.txt`.
Jenkins evidence: [build 1](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/)
and its [tool inventory artifact](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/artifact/build/preflight/tools-and-target.txt).
Jenkins requires existing approved-network access and login as applicable.
Remaining assessed evidence must come from actual reviewed v1/v2 pipeline
runs, not these local checks. See `ISSUE.md` and `RUNBOOKS.md`.
## Later agent migration
The agent subsequently moved to The-Ocean at Vincent's direction to remove
campus SSH dependence. [Migration record](evidence/agent-migration-20261114.md)
distinguishes the actual remote prerequisite build 2 and bounded capacity trial
from the initial laptop checks above. UTC dates cross into November 15 while
the client's Eastern date is still November 14. At that point the PDF runner
was unchanged. It subsequently moved too; see the
[manual runner migration record](../gitea/droplet-runner/EVIDENCE.md).
Assessed releases and recovery are still pending.
## DNS and TLS readiness
On 15 November Billy's two DNS records were verified and Caddy's prepared
routes applied. Both names have trusted TLS and HTTP 308 redirects; HTTPS
returns 502 while pricing backends are absent. See the
[dated HTTPS evidence](evidence/https-20261115.md). Application deployment,
production monitoring and assessed recovery evidence remain pending.
+19
View File
@@ -0,0 +1,19 @@
# Implement Assignment 8 secure delivery and rollback
Use instructor manual 1.43 Chapter 6 and its Startup Pricing Service on the
existing Gitea/Jenkins/Caddy/monitoring foundation.
- [x] Prepare exact dependencies, base digest, trusted agent and Ansible.
- [x] Verify deploy SSH, host-key pinning, sudo and target prerequisites.
- [x] Prepare gates, pipeline, approval and recovery automation.
- [ ] Review/merge v1 source; configure staging/app DNS and TLS routes.
- [ ] Show blocked unit-test and synthetic-secret Jenkins runs, then repair.
- [ ] Publish v1; deploy staging; prove changed=0; approve production.
- [ ] Preserve v1 records; review/merge v2; promote the same v2 digest.
- [ ] Roll production back to matching v1 image/config; measure interruption.
- [ ] Review staging-only bad command; show failed wait and recovery.
- [ ] Add production monitoring and correlate actual samples/timestamps.
- [ ] Finalize traceability, runbooks, history, AI log and one PDF.
Local preparation is not assessed release evidence. Preserve branch protection
and earlier services/data; keep credentials out of Git and reports.
+146
View File
@@ -0,0 +1,146 @@
// A separate trusted delivery job loads this file from protected main.
// The existing multibranch PR job keeps its ordinary test-only Jenkinsfile.
pipeline {
agent { label 'delivery-trusted' }
options {
skipDefaultCheckout()
disableConcurrentBuilds()
timeout(time: 60, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '20'))
}
parameters {
choice(name: 'MODE', choices: ['release', 'blocked-test', 'blocked-secret', 'rollback-production', 'staging-failure', 'recover-staging'], description: 'Reviewed release or recovery operation')
string(name: 'SOURCE_COMMIT', defaultValue: '', description: 'Optional full reviewed source commit already on main')
string(name: 'RELEASE_RECORD', defaultValue: '', description: 'Reviewed delivery/releases/*.json for rollback or recovery')
string(name: 'STAGING_FAILURE_CONFIG', defaultValue: '', description: 'Only for staging-failure. Full reviewed commit of the staging-only bad command template')
}
environment {
PYTHONDONTWRITEBYTECODE = '1'
TRIVY_CACHE_DIR = '/home/jenkins/agent/.cache/trivy'
}
stages {
stage('Reviewed checkout') {
steps {
deleteDir()
checkout scm
script {
if (params.SOURCE_COMMIT) {
if (!(params.SOURCE_COMMIT ==~ /[0-9a-f]{40}/)) {
error('SOURCE_COMMIT must be a full Git commit')
}
withEnv(["RELEASE_SOURCE=${params.SOURCE_COMMIT}"]) {
sh 'git merge-base --is-ancestor "$RELEASE_SOURCE" origin/main && git checkout --detach "$RELEASE_SOURCE"'
}
}
}
sh 'git merge-base --is-ancestor HEAD origin/main'
sh 'mkdir -p build/delivery/reports && git rev-parse HEAD > build/delivery/reports/source-commit.txt'
}
}
stage('Unit tests') {
steps {
sh 'python3 -B -m unittest discover -s delivery/ci -p "test_controls.py" -v'
script {
withEnv(["TEST_FAILURE=${params.MODE == 'blocked-test'}"]) {
sh 'sh delivery/ci/test-app.sh'
}
}
}
}
stage('Source security gates') {
steps {
script {
def fixture = params.MODE == 'blocked-secret' ? ' --fixture' : ''
sh "python3 delivery/ci/security.py source${fixture}"
}
}
}
stage('Build, scan, publish') {
when { expression { params.MODE == 'release' } }
steps {
withCredentials([usernamePassword(credentialsId: 'delivery-registry-write', usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_TOKEN')]) {
sh 'sh delivery/ci/publish.sh'
}
}
}
stage('Select release record') {
steps {
script {
if (params.MODE == 'release') {
env.SELECTED_RECORD = sh(script: "find build/delivery/releases -name '*-staging.json'", returnStdout: true).trim()
} else {
if (!(params.RELEASE_RECORD ==~ /delivery\/releases\/[a-zA-Z0-9._-]+\.json/)) {
error('Choose a committed delivery/releases/*.json record')
}
env.SELECTED_RECORD = params.RELEASE_RECORD
if (params.MODE == 'staging-failure') {
if (!(params.STAGING_FAILURE_CONFIG ==~ /[0-9a-f]{40}/)) {
error('Choose the full reviewed staging failure configuration commit')
}
withEnv(["FAILURE_CONFIG=${params.STAGING_FAILURE_CONFIG}"]) {
sh '''mkdir -p build/delivery/releases
python3 - <<'PY'
import json, os
from pathlib import Path
record = json.loads(Path(os.environ['SELECTED_RECORD']).read_text())
assert record['target_env'] == 'staging', 'Failure exercise requires staging'
record['configuration_commit'] = os.environ['FAILURE_CONFIG']
Path('build/delivery/releases/failure-staging.json').write_text(json.dumps(record, indent=2))
PY'''
}
env.SELECTED_RECORD = 'build/delivery/releases/failure-staging.json'
}
}
}
sh 'python3 delivery/ci/release.py verify "$SELECTED_RECORD"'
}
}
stage('Staging deploy and unchanged rerun') {
when { expression { params.MODE == 'release' || params.MODE == 'recover-staging' || params.MODE == 'staging-failure' } }
steps {
withCredentials([
sshUserPrivateKey(credentialsId: 'delivery-deploy-ssh', keyFileVariable: 'DEPLOY_KEY'),
file(credentialsId: 'delivery-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')
]) {
sh 'sh delivery/ci/deploy.sh "$SELECTED_RECORD" staging'
sh 'sh delivery/ci/deploy.sh "$SELECTED_RECORD" staging rerun'
}
}
}
stage('Production approval') {
when { expression { params.MODE == 'release' || params.MODE == 'rollback-production' } }
steps {
archiveArtifacts(artifacts: 'build/delivery/reports/**,build/delivery/releases/**', allowEmptyArchive: false)
script {
if (params.MODE == 'release') {
env.SELECTED_RECORD = env.SELECTED_RECORD.replace('-staging.json', '-production.json')
}
sh 'python3 delivery/ci/release.py verify "$SELECTED_RECORD" --environment production'
def record = readFile(env.SELECTED_RECORD)
def approver
timeout(time: 20, unit: 'MINUTES') {
approver = input(message: "Approve production? Source, digest and target below. Review archived scan reports and staging console results.\n${record}", ok: 'Approve production', submitter: 'billy,vsun1', submitterParameter: 'APPROVER')
}
def approvedAt = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true).trim()
writeFile(file: 'build/delivery/reports/production-approval.txt', text: "Approver=${approver}\nDecision=approved\nUTC=${approvedAt}\n${record}\n")
}
}
}
stage('Production deploy and verification') {
when { expression { params.MODE == 'release' || params.MODE == 'rollback-production' } }
steps {
withCredentials([
sshUserPrivateKey(credentialsId: 'delivery-deploy-ssh', keyFileVariable: 'DEPLOY_KEY'),
file(credentialsId: 'delivery-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')
]) {
sh 'sh delivery/ci/deploy.sh "$SELECTED_RECORD" production'
}
}
}
}
post {
always {
archiveArtifacts(artifacts: 'build/delivery/reports/**,build/delivery/releases/**', excludes: '**/test-venv/**', allowEmptyArchive: true)
}
}
}
+26
View File
@@ -0,0 +1,26 @@
# Record verified releases and prepare the recovery exercises
Jenkins builds 5 and 6 completed reviewed v1/v2 delivery: tests/scans passed,
unchanged staging reruns had changed=0, Vincent approved each production input,
and each exact digest was promoted without rebuilding. Copy their four actual
release selectors into Git so recovery can use reviewed known-good records.
Preserve failed attempts, approvals, timings and scan hashes as evidence.
The reviewed production probe/panel was applied after healthy v1 and verified
in Prometheus and the Grafana UI. Record the single HTTP 502 sample during v2
replacement; zero downtime and unobserved alert notifications are not claimed.
Include the guarded operator helper and current manual/inventory updates.
The recovery fixture deliberately binds Gunicorn to 8001 only in staging,
while health still probes 8000. Keep three commits in this PR: records/evidence
and the patch; the staging-only template fault; its immediate revert. Review
all three, including the intermediate bad configuration. Merge with a merge
commit, preserving that SHA while the final main template remains correct.
The explicit Jenkins staging-failure mode selects that historical configuration;
merging alone does not deploy it. Both recovery executions remain pending.
Validation: successful Jenkins builds 5/6, real approval records, strict selector
verification for all four records, post-release HTTPS identity/price/400 checks,
all six scrape targets up, successful reload and the live production panel.
The failure patch passes git apply --check and local staging/production isolation
checks. No credential or access scope changed.
+131
View File
@@ -0,0 +1,131 @@
# Secure Delivery and Rollback — Assignment 8
The application is adapted from the instructor's Startup Pricing Service
v1 in `Examples.zip`, `Examples/dosSecureDelivery/v1/`. The deployment
starters come from that bundle's `ansible/` directory. The task follows
Chapter 6 of instructor manual version 1.43.
`app/` contains the Flask/Gunicorn service, nine exact direct/transitive
dependencies, and a pinned Python 3.13 Alpine base digest for Linux/amd64.
The inventory selects The-Ocean's dedicated deploy account. The example
release record remains explicitly an example; real registry digests are
generated by Jenkins from reviewed source.
Current execution status, 15 November Eastern / 16 November UTC: PRs 24–26
are merged, preserving the separate v1/v2 commits. Real Jenkins test/secret
demonstrations blocked as intended. Builds 5 and 6 then completed both releases,
with zero-change staging reruns, passing gates and actual human production
approvals. Both environments are healthy v2; production monitoring is live.
See [release evidence](evidence/releases-20261115.md). The four successful
records and staging-only fault history need review before the two remaining
[recovery exercises](exercises/README.md). Earlier failures/trials remain
historical evidence, not the current release result.
Run the tests from `app/` after installing its requirements into the selected
Linux test environment. The expected v1 result for three units is USD 30.
The reviewed v2 source/test change returns USD 36. PR 26 preserved the separate
v1 and v2 SHAs, selected explicitly by builds 5 and 6 and baked into each image.
Deployment work uses a dedicated trusted Jenkins agent, immutable images
in the existing Gitea registry, and separate Ansible-managed staging and
production Compose projects. The agent requires Docker build capability,
Python, Ansible, the Docker collection, and the selected security scanners.
Registry publication, staging deployment, approval, production promotion,
and both recovery exercises require dated execution evidence.
## Attribution and preparation record
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,
verified remote main `8beefde`, and created branch
`codex/assignment8-secure-delivery`. It copied the v1 and Ansible starters
without changing their contents and checked Python syntax. This preparation
record will be consolidated into the manual's AI assistance log when the
assignment chapter is authored. The instructor retains authorship of the
starter application and playbook.
## Verified preparation, 14 November 2026
The existing two pricing tests, three new Flask tests and twelve release/control
tests passed. The deliberate wrong-price assertion failed as intended; the
synthetic secret fixture blocked its gate. Pip-audit passed for the nine locked
application dependencies. The full Trivy runtime-image gate reported no HIGH
or CRITICAL findings. Earlier failed scans remain in ignored local evidence;
no scanner exception was introduced. A non-root Gunicorn container passed
health, identity, pricing and invalid-input checks with a 64 MiB memory cap.
The droplet now has 2 GiB RAM and its original 25 GB plan disk. Vincent resized
it and installed package updates. The existing seven service containers and
their HTTPS routes were verified after maintenance.
The trusted node `ssw590-vince-delivery` now runs on The-Ocean, with one
exclusive executor and label `delivery-trusted`. Its name is retained from
the initial laptop installation. The laptop copy is stopped. The remote
agent uses private HTTP/WebSocket to `jenkins:8080`; its SSH configuration
routes the existing deployment inventory address through Docker's host gateway,
retaining `HostKeyAlias 147.182.178.136` and the pinned Jenkins known-hosts file.
No campus SSH connection is needed to run a delivery job from the browser.
[Agent prerequisite build 1](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/)
passed using the dedicated deploy key, pinned host key and root sudo. Its
non-secret tool inventory is versioned in `evidence/agent-preflight-1.txt`.
The `secure-delivery/pricing` job loads `delivery/Jenkinsfile` from protected
main and was enabled after PR 24 merged. Release credentials are scoped
to that Jenkins folder; the PR job does not bind them or the Docker socket.
The original inventory above is historical. [Remote prerequisite build 2](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/2/)
passed after migration; `evidence/agent-preflight-2.txt` records the tools and
target. A separate bounded capacity trial passed control/app tests, source and
dependency checks, a limited image build, image scan and temporary HTTP smoke.
It used a preparation snapshot, not a reviewed release, and published nothing.
The deployment account has root-only passwordless sudo: effective host
administration privileges, restricted to reviewed delivery code. Distinct
package-write and package-read tokens under `vsun1` are stored in Jenkins and
root's target Docker configuration respectively. No values are in Git.
Remote agent identity and workspace live in named Docker volumes outside Git.
The agent has administrative access to the same Docker host as Jenkins and
Gitea; a container is not a security boundary against malicious trusted jobs.
Use only reviewed delivery code. `agent/compose.droplet.yaml` caps the agent
at 512 MiB RAM / 768 MiB RAM+swap and 0.5 CPU; a dedicated pinned BuildKit
builder has 256 MiB / 384 MiB and 0.5 CPU. Builds select that builder explicitly.
Agent and builder restart unless stopped. `bootstrap/start-droplet-agent.sh`
is the root-operated installation/reconnect helper in
`/opt/ssw590-delivery-agent`; it detects the Docker socket group (987 on this host).
No public agent, Docker API or app port is added.
`bootstrap/start-agent.ps1` refuses to start the laptop copy by default.
For an intentional fallback, first stop the remote agent and builder, then use
`-AllowLaptopFallback`. Never connect both copies of the same node. Preserve
their volumes. The Gitea Actions manual-build runner subsequently moved to
The-Ocean too; see `../gitea/droplet-runner/README.md`. Neither active runner
now depends on Docker Desktop. Run manual builds and delivery releases sequentially.
See `RUNBOOKS.md`.
Ansible syntax, agent Compose configuration, and the installed Jenkins
controller's declarative parser checks passed. These are preparation checks;
The subsequent actual release evidence is linked above; **the two recovery
exercises remain unexecuted**.
## Remaining checkpoints
Vincent merged PR #24, including runner migration and HTTPS, after Billy's
latest review; PR 25's SSH correction and PR 26's two source commits are also
merged. Review/merge the actual successful records and the preserved staging-only
fault/revert commits before recovery. Create the assignment issue if still absent.
Keep main protection and preserve commit history with a merge commit.
Billy added the A
records; Google and Cloudflare now resolve both names to `147.182.178.136`.
On 15 November Caddy's prepared routes were validated and gracefully reloaded;
both names have trusted HTTPS and HTTP redirects. Both environments now passed
v1/v2 release checks and are healthy v2. The original TLS
readiness snapshot is `evidence/https-20261115.md`.
The release job is enabled; follow `RUNBOOKS.md` after the recovery records/configuration are reviewed on main.
Keep Jenkins and the remote delivery node available. Production approval requires an authorized
human; an agent must not approve unattended.
`SECURITY.md` defines the gate policy. `bootstrap/` makes administrator setup
reviewable; its one-time script refuses to overwrite existing deployment state.
Raw local reports remain under ignored `build/evidence/assignment8-local/`.
The manual records material AI assistance and distinguishes pending work from
actual evidence. This preparation is not ready for assignment submission.
+182
View File
@@ -0,0 +1,182 @@
# Release, recovery and cleanup
These are execution instructions, not completed release evidence.
Current status, 15 November 2026 Eastern / 16 November UTC: Billy's DNS records resolve correctly and the
two Caddy routes are active with trusted certificates and HTTP-to-HTTPS redirects.
The one-time HTTPS helper has already run; use the normal validate/reload
procedure for later changes. PRs 24–26 are merged. Actual builds 5/6 passed
v1/v2 promotions, zero-change reruns and real vsun1 approvals. Both environments
are healthy v2. The production probe/panel is applied and verified; one HTTP 502
sample during replacement is recorded. Review the four actual successful
records and staging-only fault/revert history before recovery; see
`exercises/README.md`. The earlier failed builds remain historical evidence.
## Authority and preparation
Billy reviews code; Vincent commits/pushes. Jenkins users `billy` or `vsun1`
may approve production interactively; administrators retain override authority.
The Droplet delivery agent must be online and source/configuration commits reviewed and
merged into protected main. Do not run untrusted PR/fork code with its Docker
socket or the delivery folder's credentials. Exclusive scheduling alone does
not prevent someone authorized to alter jobs from selecting the node.
Confirm A records `staging` and `app` point to The-Ocean. Validate and reload
the prepared additions to `/root/gitea/Caddyfile`, preserving the earlier file,
allowlist environment and volumes. Publish no application host port. The
applications join the existing `gitea_web` network with different aliases.
Enable `secure-delivery/pricing` after reviewed source reaches main.
The installed-binary validation commands are:
```text
docker exec gitea-caddy-1 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
docker exec gitea-caddy-1 caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile
docker exec monitoring-prometheus-1 promtool check config /etc/prometheus/prometheus.yml
```
Preserve bind-mounted file inodes when copying new contents. Monitoring was
applied only after healthy v1 production, using the guarded one-time
`bootstrap/enable-production-monitoring.py`. It compares prior probes/panels,
validates with promtool, backs up and reloads Prometheus via SIGHUP. Do not
rerun its one-time application over the already changed state. The protected
backup is `/root/ssw590-delivery-bootstrap/monitoring-20261116/`. Actual targets,
reload metric and the provisioned Grafana panel were verified separately.
## v1 and v2
1. Run MODE `blocked-test`: the wrong-price fixture must fail and prevent
publication/deployment. Run MODE `blocked-secret`: the generated synthetic
fixture must block the scanner gate. Fixtures exist only during those runs.
2. Run MODE `release` with the full reviewed v1 SOURCE_COMMIT if needed. Tests,
dependency/secret checks and image gates must pass. The commit-tagged image
is built once, scanned, pushed/pulled, and selected by exact registry digest.
Existing commit tags are reused, not overwritten. Full reports are archived.
3. Staging checks health, version, source SHA and total 30. Its unchanged rerun
must report changed=0; the pipeline blocks otherwise.
4. Review the presented release metadata, archived scans and staging results.
An authorized human approves within 20 minutes. Rejection/timeout stops
production. The actual approval identity/UTC is archived. Production uses
the same digest and verifies all three endpoints; it does not rebuild.
5. Save both generated v1 JSON records from Jenkins into `delivery/releases/`
and review/commit them before recovery. Never invent a digest or commit SHA.
6. Apply the supplied v2 application/test changes in a separate reviewed commit:
VERSION=v2, UNIT_PRICE=12, expected total=36. Repeat the complete release and
real approval. Preserve v1 images/configuration/records; save v2 records.
The v1 health correction and v2 source/test change may be reviewed together
in one PR while remaining separate commits. Do not squash them: the delivery
job requires both selected source commits to remain ancestors of protected
main. Start with the full v1 health-fix SHA, then use the full v2 SHA only after
v1 production verification. Actual successful records still need review before
rollback. Never substitute a failed attempt's generated record for that evidence.
## Healthy production rollback
Record the detection/decision UTC and reason. Before approval, start the HTTPS
observer on an available client or the remote agent, for example:
```text
python delivery/ci/observe.py --url https://app.yebilly.me --seconds 600 --output build/evidence/assignment8/rollback-health.csv
```
Run MODE `rollback-production` with committed
`delivery/releases/v1-production.json`. SOURCE_COMMIT can stay on main: the
record selects the exact historical image and configuration. Review/approve
the input. Ansible restores playbook/template using `git archive` of the
configuration commit, then verifies v1, its original SHA and total 30.
Archive decision, approval, deployment start/completion/elapsed time and the
observer CSV. Report failed samples and gaps; no failed samples does not prove
zero interruption between requests. Correlate the 30-second monitoring samples.
## Failed staging deployment and recovery
After v2 succeeds, add this staging-only override to the app service in
`ansible/templates/compose.yaml.j2` in a separate reviewed configuration commit:
```jinja2
{% if target_env == 'staging' %}
command: ["gunicorn", "--bind", "0.0.0.0:8001", "--workers", "1", "--worker-tmp-dir", "/tmp", "app:app"]
{% endif %}
```
The image's healthcheck still probes 8000. Select MODE `staging-failure`, the
committed good v2 staging record, and full STAGING_FAILURE_CONFIG SHA. Compose
wait must fail within its 90-second bound and stop Jenkins before production.
Do not use MODE `release` to build an image for this configuration exercise.
Restore/review the correct template, then use MODE `recover-staging` with the
original good v2 staging record and matching configuration commit. Verify
health, exact source SHA, total 36 and changed=0. Retain failure, restoration,
recovery reports and observer timing. Do not alter earlier infrastructure to
manufacture a failure.
## Monitoring and limits
After production is healthy, add `https://app.yebilly.me/health` to the existing
Prometheus `https` job and display it in Grafana. Keep Gitea/Jenkins probes and
host metrics. Validate configuration before reload. Record actual samples and
alerts around releases/recovery; a short failure can fall between scrapes or
below the alert duration. HTTP status cannot validate the expected price.
Each stateless app is capped at 64 MiB RAM, 96 MiB RAM+swap, 0.25 CPU and 64
PIDs, with a read-only root filesystem, 16 MiB /tmp tmpfs, UID 10001 and all
capabilities dropped. The remote agent is capped at 512 MiB RAM / 768 MiB
RAM+swap and 0.5 CPU; its pinned BuildKit builder at 256 MiB / 384 MiB and
0.5 CPU. The preparation trial passed but used swap and is not a full release
load test. Keep one exclusive executor and serialized delivery. One droplet
and a shared proxy network provide neither high availability nor strong lateral
isolation. A real database migration or external payment can invalidate image
rollback; use compatible expand/migrate/contract changes and tested backups.
## After grading, only when instructed
Archive required evidence first. Remove only the two pricing Compose projects,
their routes, monitoring additions and test DNS names. Revoke the two named
Assignment 8 package tokens, then remove the deploy key/sudo grant and its
Jenkins folder/node when no longer needed. Preserve required job history before
removing configuration. Stop the remote agent and dedicated builder; remove only their identity/workspace
volumes after approval. Preserve Gitea, Jenkins home, proxy storage, monitoring
volumes and earlier assignments. Never system-prune or use `down -v` here.
## Bootstrap recovery
The protected `/root/ssw590-delivery-bootstrap/` directory contains metadata,
a consistent Jenkins-home archive and a Gitea SQLite backup taken before token
creation. Metadata records token names, not values. Transient private inputs
are erased after Jenkins encrypts them. If setup fails partway, inspect its
marker/logs and existing state rather than rerunning or rotating credentials.
Do not restore entire volumes/databases over later work without a reviewed plan.
## Agent placement and campus demonstration
The node name `ssw590-vince-delivery` is historical; it now runs on The-Ocean.
Deployment SSH goes to `host.docker.internal` through the mounted SSH config,
with the original public-IP host-key alias and strict verification. The Jenkins
connection is private HTTP/WebSocket on `gitea_web`; public browser access
continues through Caddy HTTPS and its existing allowlist. No campus SSH is
needed for this delivery path. Rehearse campus browser access before presenting.
The Gitea Actions PDF runner now also runs on The-Ocean. Its existing label
`latex-local` is historical. Both laptop copies are stopped; run manual builds
and delivery releases sequentially. See `../gitea/droplet-runner/README.md`.
To stop the remote agent from an authorized administrator shell:
```sh
cd /opt/ssw590-delivery-agent
docker compose -f compose.droplet.yaml stop
docker stop buildx_buildkit_ssw590-delivery-limited0
```
To reconnect, run `bash /opt/ssw590-delivery-agent/start-droplet-agent.sh`.
It reuses protected identity and workspace volumes; do not rerun the original
host/account bootstrap. Agent recreation reuses the node identity. The verified
tool image was transferred from Docker Desktop and checked by archive SHA-256
and image ID before loading. It can be rebuilt from `agent/Dockerfile` on a
build-capable machine and transferred again if required.
For a laptop fallback, stop the remote copy first, load the administrator key
into Windows ssh-agent, then run
`./delivery/bootstrap/start-agent.ps1 -AllowLaptopFallback`.
Stop the laptop copy before starting the remote one again.
No new cloud instance or plan change was made; existing Droplet billing applies.
VS maintains this agent and BY retains server administration ownership.
+39
View File
@@ -0,0 +1,39 @@
# Release security policy
Policy selected before the assessed scans on 14 November 2026.
- Block every detected repository secret. Use Trivy's built-in rules together
with the course synthetic-fixture rule in `trivy-secret.yaml`.
- Block HIGH and CRITICAL image vulnerabilities, including issues without a
published fix. Retain the full report, including lower severities, for review.
- Block every Python dependency advisory reported by pip-audit. Review direct
and transitive dependencies and update the exact lock before rebuilding.
- A scanner execution error, unavailable advisory service, unavailable
vulnerability database, malformed report, or missing report fails the gate.
- No exceptions are currently approved. An exception requires instructor
acceptance, an advisory identifier, owner, rationale, compensating controls,
and expiry recorded with the release. Findings must never be silently ignored.
- For a suspected false positive, retain the report and record the evidence
used for triage. Keep the release blocked until the finding is resolved or
an instructor-approved exception is recorded.
Each release archives UTC scan times, tool versions, Trivy database metadata,
commands, exit codes, reports, source commit, and the selected image digest.
Rebuild and rescan after changing a dependency or base image.
The synthetic fixture is generated only for a deliberate blocked-gate run.
Its label identifies course test data and has no credential authority. Remove
the fixture and repeat the gate before a release can proceed.
The deployment agent now has administrative Docker access on The-Ocean,
including the host running the controller, registry and monitoring, as well as
deployment privileges. Co-location reduces isolation: the agent's container
and resource caps do not prevent a malicious Docker-authorized job from
accessing other containers or host files. This is a documented course-lab
trade-off to avoid campus SSH restrictions, not a hardened production design.
Run reviewed delivery code on
this agent. Pull-request jobs must not receive its Docker socket or release
credentials. The remote agent connects over private HTTP/WebSocket on the
existing Docker network; browser access remains HTTPS through Caddy. Strict
SSH verification retains the public-IP host-key alias while transport stays
on Docker's host gateway. No firewall, TLS, approval or credential scope was relaxed.
+25
View File
@@ -0,0 +1,25 @@
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 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/*
COPY --from=dockercli /usr/local/bin/docker /usr/local/bin/docker
COPY --from=dockercli /usr/local/libexec/docker/cli-plugins/ /usr/local/libexec/docker/cli-plugins/
COPY --from=scanner /usr/local/bin/trivy /usr/local/bin/trivy
COPY agent/requirements.txt /tmp/requirements.txt
RUN python3 -m venv /opt/delivery-tools \
&& /opt/delivery-tools/bin/pip install --no-cache-dir -r /tmp/requirements.txt
ENV PATH="/opt/delivery-tools/bin:${PATH}" \
ANSIBLE_COLLECTIONS_PATH=/opt/ansible-collections \
PYTHONDONTWRITEBYTECODE=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
COPY ansible/requirements.yml /tmp/collections.yml
RUN ansible-galaxy collection install -r /tmp/collections.yml -p /opt/ansible-collections \
&& chmod -R a+rX /opt/ansible-collections \
&& mkdir -p /opt/delivery-tools/inventory \
&& dpkg-query -W > /opt/delivery-tools/inventory/debian-packages.txt \
&& pip freeze > /opt/delivery-tools/inventory/python-packages.txt
USER jenkins
+54
View File
@@ -0,0 +1,54 @@
name: ssw590-delivery
services:
agent:
image: ssw590-delivery-agent:20261114
restart: unless-stopped
entrypoint: ["java", "-jar", "/usr/share/jenkins/agent.jar"]
command:
- -url
- http://jenkins:8080/
- -name
- ssw590-vince-delivery
- -secret
- "@/run/delivery-identity/agent-secret"
- -webSocket
- -workDir
- /home/jenkins/agent
environment:
JAVA_TOOL_OPTIONS: "-Xms32m -Xmx96m -XX:+UseSerialGC -XX:MaxMetaspaceSize=96m"
GOMEMLIMIT: 192MiB
TRIVY_PARALLEL: "1"
BUILDX_CONFIG: /home/jenkins/agent/.buildx
DELIVERY_BUILDER: ssw590-delivery-limited
# Docker membership is host administration, including controller access.
# Only reviewed delivery jobs may select this exclusive one-executor node.
group_add: ["${DOCKER_GID:?set to the host Docker socket group}"]
extra_hosts:
- "host.docker.internal:host-gateway"
networks: [web]
volumes:
- workspace:/home/jenkins/agent
- /var/run/docker.sock:/var/run/docker.sock
- identity:/run/delivery-identity:ro
- ./ssh_config.droplet:/etc/ssh/ssh_config.d/90-delivery-target.conf:ro
mem_limit: 512m
memswap_limit: 768m
cpus: 0.5
pids_limit: 128
security_opt: ["no-new-privileges:true"]
cap_drop: ["ALL"]
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
networks:
web:
external: true
name: gitea_web
volumes:
identity:
external: true
name: ssw590-delivery-identity
workspace:
name: ssw590-delivery-workspace
+33
View File
@@ -0,0 +1,33 @@
name: ssw590-delivery
services:
agent:
image: ssw590-delivery-agent:20261114
restart: "no"
entrypoint: ["java", "-jar", "/usr/share/jenkins/agent.jar"]
command:
- -url
- https://ci.yebilly.me/
- -name
- ssw590-vince-delivery
- -secret
- "@/run/delivery-identity/agent-secret"
- -webSocket
- -workDir
- /home/jenkins/agent
# Docker's Linux VM socket is owned by group 0. Membership grants Docker
# administration privileges. Use this node exclusively for trusted jobs.
group_add: ["0"]
volumes:
- workspace:/home/jenkins/agent
- /var/run/docker.sock:/var/run/docker.sock
- identity:/run/delivery-identity:ro
mem_limit: 2g
cpus: 2
security_opt: ["no-new-privileges:true"]
cap_drop: ["ALL"]
volumes:
identity:
external: true
name: ssw590-delivery-identity
workspace:
name: ssw590-delivery-workspace
+2
View File
@@ -0,0 +1,2 @@
ansible-core==2.21.6
pip-audit==2.10.1
+35
View File
@@ -0,0 +1,35 @@
ansible-core==2.21.6
boolean.py==5.0
CacheControl==0.14.4
certifi==2026.10.23
cffi==2.1.1
charset-normalizer==3.5.2
cryptography==50.0.2
cyclonedx-python-lib==11.12.0
defusedxml==0.7.1
filelock==4.2.10
idna==3.20
Jinja2==3.1.6
license-expression==30.4.4
markdown-it-py==4.3.0
MarkupSafe==3.0.4
mdurl==0.1.2
msgpack==1.2.4
packageurl-python==0.17.6
packaging==26.3
pip-requirements-parser==32.0.1
pip_api==0.0.35
pip_audit==2.10.1
platformdirs==4.14.5
py-serializable==2.2.0
pycparser==3.12
Pygments==2.21.0
pyparsing==3.3.3
PyYAML==6.0.3
requests==2.34.2
resolvelib==1.2.1
rich==15.0.0
sortedcontainers==2.4.0
tomli==2.5.0
tomli_w==1.2.0
urllib3==2.8.0
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
set -eu
python -m venv /tmp/tools
/tmp/tools/bin/python -m pip install --disable-pip-version-check -r /workspace/delivery/agent/requirements.in
/tmp/tools/bin/python -m pip freeze > /workspace/delivery/agent/requirements.txt
/tmp/tools/bin/ansible-galaxy collection install -r /workspace/delivery/ansible/requirements.yml -p /tmp/collections
/tmp/tools/bin/ansible-galaxy collection list -p /tmp/collections --format json > /tmp/collections.json
/tmp/tools/bin/python - <<'PY'
import json
from pathlib import Path
data = json.loads(Path('/tmp/collections.json').read_text())
versions = {
name: metadata['version']
for collections in data.values()
for name, metadata in collections.items()
if name.startswith('community.')
}
assert 'community.docker' in versions, versions
Path('/workspace/delivery/ansible/requirements.yml').write_text(
'collections:\n' + ''.join(
f' - name: {name}\n version: "{version}"\n'
for name, version in sorted(versions.items())
)
)
print(f'Pinned collections: {versions}')
PY
+6
View File
@@ -0,0 +1,6 @@
# On The-Ocean only: keep the inventory and pinned public-key identity, but
# send deployment SSH to this Docker host's gateway, never across campus Wi-Fi.
Host 147.182.178.136
HostName host.docker.internal
HostKeyAlias 147.182.178.136
ConnectTimeout 10
+74
View File
@@ -0,0 +1,74 @@
- name: Deploy a selected immutable pricing release
hosts: delivery
become: true
vars:
project_dir: "/opt/startup/pricing-{{ target_env }}"
tasks:
- name: Validate release selection
ansible.builtin.assert:
that:
- target_env in ['staging', 'production']
- "'@sha256:' in release_image"
- expected_version in ['v1', 'v2']
- expected_total | int > 0
- public_url.startswith('https://')
- proxy_network | length > 0
- expected_commit is match('^[0-9a-f]{40}$')
- configuration_commit is match('^[0-9a-f]{40}$')
- release_image is match('^git[.]yebilly[.]me/ssw590-group1/pricing@sha256:[0-9a-f]{64}$')
- proxy_network == 'gitea_web'
- public_url == ('https://staging.yebilly.me' if target_env == 'staging' else 'https://app.yebilly.me')
- expected_total | int == (30 if expected_version == 'v1' else 36)
- name: Create deployment directory
ansible.builtin.file:
path: "{{ project_dir }}"
state: directory
mode: '0750'
- name: Render selected Compose configuration
ansible.builtin.template:
src: compose.yaml.j2
dest: "{{ project_dir }}/compose.yaml"
mode: '0640'
- name: Converge application without rebuilding
community.docker.docker_compose_v2:
project_src: "{{ project_dir }}"
project_name: "pricing-{{ target_env }}"
state: present
build: never
pull: missing
wait: true
wait_timeout: 90
- name: Verify health through public TLS endpoint
ansible.builtin.uri:
url: "{{ public_url }}/health"
return_content: true
validate_certs: true
register: health
until: health.status == 200 and health.json.status == 'ok'
retries: 12
delay: 5
changed_when: false
- name: Read release identity
ansible.builtin.uri:
url: "{{ public_url }}/"
return_content: true
register: identity
changed_when: false
- name: Exercise business behavior
ansible.builtin.uri:
url: "{{ public_url }}/price?quantity=3"
return_content: true
register: price
changed_when: false
- name: Check release identity and calculation
ansible.builtin.assert:
that:
- identity.json.version == expected_version
- health.json.version == expected_version
- identity.json.commit == expected_commit
- price.json.total | int == expected_total | int
- name: Preserve the selected non-secret release metadata
ansible.builtin.copy:
dest: "{{ project_dir }}/release.json"
mode: '0640'
content: "{{ {'release_image': release_image, 'source_commit': expected_commit, 'configuration_commit': configuration_commit, 'version': expected_version, 'expected_total': expected_total, 'public_url': public_url} | to_nice_json }}\n"
+7
View File
@@ -0,0 +1,7 @@
[delivery]
# The SSH host key must be verified and supplied by the trusted delivery job.
startup ansible_host=147.182.178.136 ansible_user=deploy ansible_python_interpreter=/usr/bin/python3
[delivery:vars]
# The dedicated deploy key forbids PTY allocation; sudo is noninteractive.
ansible_ssh_use_tty=false
+9
View File
@@ -0,0 +1,9 @@
# Copy to a release-specific file and replace EVERY placeholder.
target_env: staging
release_image: git.yebilly.me/ssw590-group1/pricing@sha256:REPLACE_DIGEST
expected_version: v1
expected_commit: REPLACE_FULL_GIT_COMMIT
configuration_commit: REPLACE_FULL_REVIEWED_CONFIGURATION_COMMIT
expected_total: 30
public_url: https://staging.yebilly.me
proxy_network: gitea_web
+5
View File
@@ -0,0 +1,5 @@
collections:
- name: community.docker
version: "5.4.0"
- name: community.library_inventory_filtering_v1
version: "1.1.5"
@@ -0,0 +1,23 @@
services:
app:
image: "{{ release_image }}"
restart: unless-stopped
read_only: true
tmpfs:
- /tmp:size=16m,mode=1777
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
mem_limit: 64m
memswap_limit: 96m
cpus: 0.25
pids_limit: 64
networks:
edge:
aliases:
- "pricing-{{ target_env }}"
networks:
edge:
external: true
name: "{{ proxy_network }}"
+4
View File
@@ -0,0 +1,4 @@
__pycache__
.venv
.git
*.pyc
+14
View File
@@ -0,0 +1,14 @@
FROM python:3.13-alpine@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e
ARG APP_COMMIT=development
ENV APP_COMMIT=$APP_COMMIT PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt \
&& python -m pip uninstall -y pip \
&& rm -rf /usr/local/lib/python3.13/ensurepip
COPY app.py .
USER 10001:10001
EXPOSE 8000
# Allow Python startup under the 0.25 CPU cap; the HTTP timeout remains 2s.
HEALTHCHECK --interval=10s --timeout=10s --start-period=10s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2)"
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "1", "--worker-tmp-dir", "/tmp", "app:app"]
+33
View File
@@ -0,0 +1,33 @@
import os
from flask import Flask, jsonify, request
app = Flask(__name__)
VERSION = "v2"
UNIT_PRICE = 12
COMMIT = os.environ.get("APP_COMMIT", "development")
def total_price(quantity):
if quantity < 1 or quantity > 1000:
raise ValueError("quantity must be between 1 and 1000")
return UNIT_PRICE * quantity
@app.get("/")
def index():
return jsonify(service="Startup Pricing", version=VERSION, commit=COMMIT)
@app.get("/health")
def health():
return jsonify(status="ok", version=VERSION)
@app.get("/price")
def price():
try:
quantity = int(request.args.get("quantity", "1"))
total = total_price(quantity)
except ValueError as error:
return jsonify(error=str(error)), 400
return jsonify(quantity=quantity, total=total, currency="USD")
+3
View File
@@ -0,0 +1,3 @@
# Instructor compatibility ranges. requirements.txt locks the assessed versions.
Flask>=3.1,<3.2
gunicorn>=23,<24
+9
View File
@@ -0,0 +1,9 @@
blinker==1.9.0
click==8.5.1
Flask==3.1.3
gunicorn==23.0.0
itsdangerous==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.4
packaging==26.3
Werkzeug==3.1.9
+25
View File
@@ -0,0 +1,25 @@
import unittest
from app import app, total_price
class PricingTests(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
def test_price(self):
self.assertEqual(total_price(3), 36)
response = self.client.get("/price?quantity=3")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json["total"], 36)
def test_invalid_quantity(self):
for value in ["0", "-1", "1001", "abc", "1.5"]:
self.assertEqual(self.client.get("/price?quantity=" + value).status_code, 400)
def test_release_identity(self):
self.assertEqual(self.client.get("/").json["version"], "v2")
self.assertEqual(self.client.get("/health").json["status"], "ok")
if __name__ == "__main__":
unittest.main()
+57
View File
@@ -0,0 +1,57 @@
#!/bin/sh
# Run inside the idle trusted agent from a non-secret preparation snapshot.
# This is a capacity/tool trial, never a reviewed release or registry push.
set -eu
export TRIVY_CACHE_DIR=/home/jenkins/agent/.cache/trivy
mkdir -p build/delivery/reports
date -u
python3 -B -m unittest discover -s delivery/ci -p 'test_controls.py' -v
sh delivery/ci/test-app.sh
python3 delivery/ci/security.py source
: "${DELIVERY_BUILDER:?use the limited remote builder}"
docker buildx build --builder "$DELIVERY_BUILDER" --load --platform linux/amd64 \
--build-arg APP_COMMIT=uncommitted-remote-preflight \
-t ssw590-pricing:remote-preflight-v1 delivery/app
python3 delivery/ci/security.py image --image ssw590-pricing:remote-preflight-v1
name=ssw590-delivery-capacity-smoke
cleanup() { docker rm -f "$name" >/dev/null 2>&1 || true; }
# Refuse to replace any existing container, even one from an interrupted trial.
if docker container inspect "$name" >/dev/null 2>&1; then
echo 'Inspect the existing trial container before retrying' >&2
exit 1
fi
trap cleanup EXIT
docker run -d --name "$name" --network gitea_web --read-only \
--tmpfs /tmp:rw,nosuid,noexec,size=16m --memory 64m --memory-swap 96m \
--cpus .25 --pids-limit 64 --cap-drop ALL --security-opt no-new-privileges \
ssw590-pricing:remote-preflight-v1
python3 - <<'PY'
import json, time, urllib.request, urllib.error
url = 'http://ssw590-delivery-capacity-smoke:8000'
for attempt in range(30):
try:
with urllib.request.urlopen(url + '/health', timeout=2) as response:
health = json.load(response)
break
except (OSError, ValueError):
time.sleep(1)
else:
raise RuntimeError('Application failed to start')
def get(path):
with urllib.request.urlopen(url + path, timeout=5) as response:
return json.load(response)
identity, price = get('/'), get('/price?quantity=3')
assert health['status'] == 'ok' and health['version'] == 'v1', health
assert identity['commit'] == 'uncommitted-remote-preflight', identity
assert price['total'] == 30, price
try:
get('/price?quantity=-1')
raise AssertionError('Invalid quantity accepted')
except urllib.error.HTTPError as error:
assert error.code == 400, error.code
print(json.dumps({'health': health, 'identity': identity, 'price': price,
'invalid_quantity_status': 400}, indent=2))
PY
docker inspect "$name" --format 'smoke OOMKilled={{.State.OOMKilled}} memory={{.HostConfig.Memory}}'
date -u
echo 'PASS: remote capacity preparation; no image published or assessed environment deployed'
@@ -0,0 +1,79 @@
// One-time bootstrap loaded from Jenkins home after an authorized host setup.
// Never print secret values. Scope release credentials to the delivery folder.
import jenkins.model.Jenkins
import hudson.model.Node
import hudson.slaves.DumbSlave
import hudson.slaves.JNLPLauncher
import hudson.slaves.RetentionStrategy
import com.cloudbees.hudson.plugins.folder.Folder
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.CredentialsScope
import com.cloudbees.plugins.credentials.SecretBytes
import com.cloudbees.plugins.credentials.domains.Domain
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
import org.jenkinsci.plugins.workflow.job.WorkflowJob
import org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition
import hudson.plugins.git.GitSCM
import hudson.plugins.git.UserRemoteConfig
import hudson.plugins.git.BranchSpec
import groovy.json.JsonOutput
def j = Jenkins.get()
def inputs = new File(j.rootDir, 'delivery-bootstrap')
def done = new File(inputs, 'configured.json')
if (done.exists()) return
assert j.getItem('secure-delivery') == null : 'Existing folder requires review'
assert j.getNode('ssw590-vince-delivery') == null : 'Existing node requires review'
def folder = j.createProject(Folder, 'secure-delivery')
folder.description = 'Assignment 8: reviewed releases only; folder-scoped deployment credentials.'
folder.save()
def store = CredentialsProvider.lookupStores(folder).find { it.context == folder }
assert store != null : 'Folder credential store unavailable'
def scope = CredentialsScope.GLOBAL
def credential = new UsernamePasswordCredentialsImpl(scope, 'delivery-registry-write',
'Assignment 8 package-write only; vsun1; revoke after grading', 'vsun1',
new File(inputs, 'registry-write').text.trim())
assert store.addCredentials(Domain.global(), credential)
def key = new BasicSSHUserPrivateKey(scope, 'delivery-deploy-ssh', 'deploy',
new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(new File(inputs, 'deploy_ed25519').text),
'', 'Assignment 8 deploy account; root sudo; reviewed releases only')
assert store.addCredentials(Domain.global(), key)
def knownHosts = new FileCredentialsImpl(scope, 'delivery-known-hosts',
'The-Ocean ED25519 host key verified through existing pinned administrator SSH',
'known_hosts', SecretBytes.fromBytes(new File(inputs, 'known_hosts').bytes))
assert store.addCredentials(Domain.global(), knownHosts)
def launcher = new JNLPLauncher()
launcher.setWebSocket(true)
def node = new DumbSlave('ssw590-vince-delivery', 'Trusted The-Ocean Docker/Ansible delivery agent (legacy node name)',
'/home/jenkins/agent', '1', Node.Mode.EXCLUSIVE, 'delivery-trusted', launcher,
new RetentionStrategy.Always(), [])
j.addNode(node)
def secret = new File(inputs, 'agent-secret')
secret.text = node.toComputer().getJnlpMac() + '\n'
secret.setReadable(false, false)
secret.setWritable(false, false)
secret.setReadable(true, true)
secret.setWritable(true, true)
def job = folder.createProject(WorkflowJob, 'pricing')
def scm = new GitSCM(
[new UserRemoteConfig('https://git.yebilly.me/ssw590-group1/vpn-dns-gateway.git', null, null, 'gitea-jenkins-bot')],
[new BranchSpec('*/main')], false, [], null, null, [])
def definition = new CpsScmFlowDefinition(scm, 'delivery/Jenkinsfile')
definition.lightweight = true
job.definition = definition
job.description = 'Reviewed protected-main code only. Enable after the Assignment 8 source is reviewed and merged.'
job.disabled = true
job.save()
done.text = JsonOutput.prettyPrint(JsonOutput.toJson([
configured_at: new Date().format("yyyy-MM-dd'T'HH:mm:ssXXX", TimeZone.getTimeZone('UTC')),
node: node.nodeName, label: 'delivery-trusted', executors: 1, exclusive: true,
job: job.fullName, disabled: true, credential_scope: folder.fullName,
credential_ids: ['delivery-registry-write', 'delivery-deploy-ssh', 'delivery-known-hosts']
])) + '\n'
['registry-write', 'deploy_ed25519', 'known_hosts'].each { name ->
assert new File(inputs, name).delete() : "Could not remove transient bootstrap input ${name}"
}
assert new File(j.rootDir, 'init.groovy.d/ssw590-delivery.groovy').delete()
println('Assignment 8 delivery configuration complete; secret values were not printed; job is disabled.')
+72
View File
@@ -0,0 +1,72 @@
"""Apply only the prepared Assignment 8 proxy additions, preserving the bind inode."""
import argparse
import hashlib
import json
import os
import shutil
import socket
import subprocess
from datetime import datetime, timezone
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument('--candidate', required=True, type=Path)
parser.add_argument('--backup', required=True, type=Path)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
live = Path('/root/gitea/Caddyfile')
marker = '# Assignment 8: apply after both DNS names resolve to The-Ocean.'
candidate = args.candidate.read_text()
before = live.read_bytes()
prefix, additions = candidate.split(marker, 1)
expected = '''# Assignment 8: apply after both DNS names resolve to The-Ocean. Containers
# publish no host ports; the existing proxy reaches their private aliases.
staging.yebilly.me {
\treverse_proxy pricing-staging:8000
}
app.yebilly.me {
\treverse_proxy pricing-production:8000
}'''
assert (marker + additions).strip() == expected, 'Unexpected proxy additions'
assert prefix.strip() == before.decode().replace('\r\n', '\n').strip(), 'Live earlier routes differ; inspect instead of overwriting'
for host in ('staging.yebilly.me', 'app.yebilly.me'):
addresses = {item[4][0] for item in socket.getaddrinfo(host, 443, socket.AF_INET)}
assert addresses == {'147.182.178.136'}, (host, addresses)
temp = '/tmp/ssw590-assignment8-https.Caddyfile'
subprocess.run(['docker', 'cp', str(args.candidate), 'gitea-caddy-1:' + temp], check=True)
try:
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'caddy', 'validate', '--config', temp, '--adapter', 'caddyfile'], check=True)
if not args.apply:
print('Candidate validated; no active configuration changed.')
raise SystemExit(0)
args.backup.mkdir(mode=0o700, parents=True, exist_ok=True)
backup = args.backup / 'Caddyfile.before'
assert not backup.exists(), 'Existing backup: inspect state before retrying'
shutil.copy2(live, backup)
prior_stat = live.stat()
try:
with live.open('wb') as stream:
stream.write(candidate.encode())
stream.flush()
os.fsync(stream.fileno())
assert live.stat().st_ino == prior_stat.st_ino, 'Bind-mounted inode changed'
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'caddy', 'reload', '--config', '/etc/caddy/Caddyfile', '--adapter', 'caddyfile'], check=True)
except Exception:
with live.open('wb') as stream:
stream.write(before)
stream.flush()
os.fsync(stream.fileno())
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'caddy', 'reload', '--config', '/etc/caddy/Caddyfile', '--adapter', 'caddyfile'], check=True)
raise
report = {'applied_at': datetime.now(timezone.utc).isoformat(),
'before_sha256': hashlib.sha256(before).hexdigest(),
'after_sha256': hashlib.sha256(live.read_bytes()).hexdigest(),
'inode_preserved': live.stat().st_ino == prior_stat.st_ino,
'prior_routes_preserved': True, 'applications_deployed': False,
'new_hosts': ['staging.yebilly.me', 'app.yebilly.me'],
'backup': str(backup), 'result': 'reloaded; certificate verification pending'}
(args.backup / 'applied.json').write_text(json.dumps(report, indent=2))
print(json.dumps(report, indent=2))
finally:
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'rm', '-f', temp], check=True)
@@ -0,0 +1,79 @@
"""Apply the reviewed production probe/panel only after production is healthy."""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import urllib.request
parser = argparse.ArgumentParser()
parser.add_argument('--prometheus', required=True, type=Path)
parser.add_argument('--dashboard', required=True, type=Path)
parser.add_argument('--backup', required=True, type=Path)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
live_prom = Path('/root/monitoring/prometheus/prometheus.yml')
live_dashboard = Path('/root/monitoring/grafana/dashboards/sre.json')
before = {live_prom:live_prom.read_bytes(), live_dashboard:live_dashboard.read_bytes()}
candidate_prom = args.prometheus.read_text().replace('\r\n','\n')
candidate_dashboard = args.dashboard.read_bytes()
addition = ' # Apply this addition only after Assignment 8 production is healthy.\n - https://app.yebilly.me/health\n'
assert candidate_prom.count(addition) == 1, 'Unexpected production probe'
assert candidate_prom.replace(addition,'').strip() == before[live_prom].decode().replace('\r\n','\n').strip(), 'Existing probes differ; inspect before changing'
old = json.loads(before[live_dashboard])
new = json.loads(candidate_dashboard)
assert old['uid'] == new['uid'] == 'group1-sre'
assert old['version'] == 1 and new['version'] == 2
panel = new['panels'][-1]
assert panel['id'] == 8 and panel['type'] == 'timeseries'
assert panel['targets'][0]['expr'] == 'probe_success{job="https",instance="https://app.yebilly.me/health"}'
comparison = dict(new, version=old['version'], panels=new['panels'][:-1])
assert comparison == old, 'Existing dashboard differs; inspect before changing'
with urllib.request.urlopen('https://app.yebilly.me/health',timeout=10) as response:
health = json.load(response)
assert response.status == 200 and health['status'] == 'ok' and health['version'] in {'v1','v2'}, 'Production must be healthy first'
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
temporary = '/tmp/ssw590-production-probe-' + stamp + '.yml'
subprocess.run(['docker','cp',str(args.prometheus),'monitoring-prometheus-1:'+temporary],check=True,capture_output=True)
try:
validation = subprocess.check_output(['docker','exec','monitoring-prometheus-1','promtool','check','config',temporary],text=True)
if not args.apply:
print(validation + 'Validated only; no active file changed.')
raise SystemExit(0)
args.backup.mkdir(parents=True,mode=0o700,exist_ok=False)
for path in before:
shutil.copy2(path,args.backup / (path.name + '.before'))
inodes = {p:p.stat().st_ino for p in before}
def write(path,content):
with path.open('wb') as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
assert path.stat().st_ino == inodes[path], 'Bind inode changed'
try:
write(live_prom,candidate_prom.encode())
write(live_dashboard,candidate_dashboard)
subprocess.run(['docker','kill','--signal','HUP','monitoring-prometheus-1'],check=True,capture_output=True)
except Exception:
for path,content in before.items():
write(path,content)
subprocess.run(['docker','kill','--signal','HUP','monitoring-prometheus-1'],check=True,capture_output=True)
raise
report = {'applied_at':datetime.now(timezone.utc).isoformat(),'production_health':health,
'validation':validation,'prior_probes_and_panels_preserved':True,
'files':[{'path':str(p),'before_sha256':hashlib.sha256(before[p]).hexdigest(),
'after_sha256':hashlib.sha256(p.read_bytes()).hexdigest(),
'inode_preserved':p.stat().st_ino == inodes[p]} for p in before],
'backup':str(args.backup),'reload':'Prometheus SIGHUP; Grafana file provisioning',
'result':'applied; runtime probe and panel verification still required'}
(args.backup / 'applied.json').write_text(json.dumps(report,indent=2))
print(json.dumps(report,indent=2))
finally:
# docker cp creates a root-owned file; the Prometheus service runs as nobody.
subprocess.run(['docker','exec','--user','0','monitoring-prometheus-1','rm','-f',temporary],check=True,capture_output=True)
+42
View File
@@ -0,0 +1,42 @@
// Administrator preparation only: no checkout, image publication or deployment.
pipeline {
agent { label 'delivery-trusted' }
options { disableConcurrentBuilds(); timeout(time: 5, unit: 'MINUTES') }
stages {
stage('Tool and target prerequisites') {
steps {
withCredentials([
sshUserPrivateKey(credentialsId: 'delivery-deploy-ssh', keyFileVariable: 'DEPLOY_KEY'),
file(credentialsId: 'delivery-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')
]) {
sh '''set -eu
set +x
mkdir -p build/preflight
{
date -u
id
python3 --version
ansible --version
ansible-galaxy collection list
docker --version
docker compose version
trivy --version
pip-audit --version
ssh -i "$DEPLOY_KEY" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$DEPLOY_KNOWN_HOSTS" deploy@147.182.178.136 'id; sudo -n true; python3 --version; sudo -n docker --version; sudo -n docker compose version; free -m; nproc; df -h /'
# Exercise Ansible's own SSH/become path as well as plain SSH. Its default
# PTY request is incompatible with the intentionally restricted deploy key.
export ANSIBLE_HOST_KEY_CHECKING=True
export ANSIBLE_PRIVATE_KEY_FILE="$DEPLOY_KEY"
export ANSIBLE_SSH_ARGS="-o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$DEPLOY_KNOWN_HOSTS"
ansible all -i '147.182.178.136,' -u deploy --become \
-e '{"ansible_ssh_use_tty":false,"ansible_python_interpreter":"/usr/bin/python3"}' \
-m ansible.builtin.command -a 'id -u'
} > build/preflight/tools-and-target.txt
cat build/preflight/tools-and-target.txt
'''
}
}
}
}
post { always { archiveArtifacts(artifacts: 'build/preflight/**', allowEmptyArchive: true) } }
}
+129
View File
@@ -0,0 +1,129 @@
"""One-time administrator bootstrap; run only on the authorized droplet.
Secrets stay in protected host/Jenkins storage and are never printed. This
does not deploy an application, enable the release job, commit, or push.
"""
import argparse
import json
import os
from pathlib import Path
import shutil
import sqlite3
import subprocess
from datetime import datetime, timezone
HOME = Path('/var/lib/docker/volumes/gitea_jenkins-home/_data')
STATE = Path('/root/ssw590-delivery-bootstrap')
SCRIPTS = Path(__file__).resolve().parent
def run(args, **kwargs):
return subprocess.run(args, check=True, **kwargs)
def private_file(path, content, owner=None):
path.write_text(content)
path.chmod(0o600)
if owner is not None:
os.chown(path, owner, owner)
def registry_token(name, scope):
result = subprocess.run([
'docker', 'exec', '-u', 'git', 'gitea-gitea-1', 'gitea',
'--config', '/data/gitea/conf/app.ini', 'admin', 'user',
'generate-access-token', '--username', 'vsun1', '--token-name', name,
'--scopes', scope, '--raw',
], text=True, capture_output=True)
value = result.stdout.strip()
if result.returncode or len(value) != 40 or not all(c in '0123456789abcdef' for c in value):
raise RuntimeError('Token creation did not return the expected format; no secret output emitted')
return value
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
if not args.apply:
print('Plan: back up Jenkins/Gitea; create deploy SSH/sudo access; create package-only tokens;')
print('configure folder-scoped Jenkins credentials, an exclusive agent and a DISABLED release job; restart Jenkins.')
return
if os.geteuid() != 0 or not HOME.is_dir():
raise RuntimeError('Run as root on the existing The-Ocean droplet')
if STATE.exists() or (HOME / 'delivery-bootstrap').exists():
raise RuntimeError('Bootstrap state already exists: inspect it rather than rotating or overwriting access')
if subprocess.run(['id', 'deploy'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0:
raise RuntimeError('An existing deploy account requires review before modification')
run(['docker', 'exec', 'gitea-jenkins-1', 'test', '-e', '/var/jenkins_home/plugins/cloudbees-folder.jpi'])
STATE.mkdir(mode=0o700)
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
backup = STATE / ('backup-' + stamp)
backup.mkdir(mode=0o700)
database = Path('/var/lib/docker/volumes/gitea_gitea-data/_data/gitea/gitea.db')
with sqlite3.connect(f'file:{database}?mode=ro', uri=True) as source:
with sqlite3.connect(backup / 'gitea.db') as target:
source.backup(target)
(backup / 'gitea.db').chmod(0o600)
run(['docker', 'stop', 'gitea-jenkins-1'], stdout=subprocess.DEVNULL)
try:
run(['tar', '-czf', str(backup / 'jenkins-home.tgz'), '-C', str(HOME), '.'])
finally:
run(['docker', 'start', 'gitea-jenkins-1'], stdout=subprocess.DEVNULL)
(backup / 'jenkins-home.tgz').chmod(0o600)
if Path('/root/.docker/config.json').exists():
shutil.copy2('/root/.docker/config.json', backup / 'docker-config.json')
(backup / 'docker-config.json').chmod(0o600)
key = STATE / 'deploy_ed25519'
run(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-C', 'ssw590-jenkins-delivery', '-f', str(key)])
run(['useradd', '--create-home', '--shell', '/bin/bash', '--comment', 'SSW590 trusted Ansible deployment', 'deploy'])
sshdir = Path('/home/deploy/.ssh')
sshdir.mkdir(mode=0o700)
run(['chown', 'deploy:deploy', str(sshdir)])
public_key = key.with_suffix('.pub').read_text().strip()
private_file(sshdir / 'authorized_keys', 'restrict ' + public_key + '\n')
run(['chown', 'deploy:deploy', str(sshdir / 'authorized_keys')])
sudoers = Path('/etc/sudoers.d/ssw590-delivery')
private_file(sudoers, '# Trusted Ansible release account: effective host administrator.\ndeploy ALL=(root) NOPASSWD: ALL\n')
sudoers.chmod(0o440)
run(['visudo', '-cf', str(sudoers)])
write_token = registry_token('ssw590-delivery-agent-' + stamp, 'write:package')
read_token = registry_token('ssw590-delivery-target-' + stamp, 'read:package')
result = subprocess.run([
'docker', 'login', '--username', 'vsun1', '--password-stdin', 'git.yebilly.me'
], input=read_token + '\n', text=True, capture_output=True)
if result.returncode:
raise RuntimeError('Target registry login failed; no secret output emitted')
inputs = HOME / 'delivery-bootstrap'
inputs.mkdir(mode=0o700)
os.chown(inputs, 1000, 1000)
private_file(inputs / 'deploy_ed25519', key.read_text(), 1000)
private_file(inputs / 'registry-write', write_token, 1000)
public_host_key = Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()
private_file(inputs / 'known_hosts', '147.182.178.136 ' + ' '.join(public_host_key[:2]) + '\n', 1000)
init = HOME / 'init.groovy.d'
init.mkdir(exist_ok=True)
os.chown(init, 1000, 1000)
script = init / 'ssw590-delivery.groovy'
shutil.copyfile(SCRIPTS / 'configure_jenkins.groovy', script)
script.chmod(0o600)
os.chown(script, 1000, 1000)
private_file(STATE / 'metadata.json', json.dumps({
'started': stamp, 'registry_user': 'vsun1',
'agent_token_name': 'ssw590-delivery-agent-' + stamp,
'target_token_name': 'ssw590-delivery-target-' + stamp,
'agent_scope': 'write:package', 'target_scope': 'read:package',
'backup_directory': str(backup),
'deploy_sudo_scope': 'root commands without a password; trusted code only',
}, indent=2))
run(['docker', 'restart', 'gitea-jenkins-1'], stdout=subprocess.DEVNULL)
# The private key is now the Jenkins bootstrap input; remove the duplicate.
key.unlink()
key.with_suffix('.pub').unlink()
print('Host bootstrap applied. Jenkins is restarting; verify its completion marker before starting the agent.')
print('Existing Gitea, proxy and monitoring configuration was preserved. Release job remains disabled.')
if __name__ == '__main__':
main()
+28
View File
@@ -0,0 +1,28 @@
param(
[switch]$AllowLaptopFallback,
[string]$Droplet = '147.182.178.136',
[string]$IdentityFile = (Join-Path $env:USERPROFILE '.ssh/digitalocean')
)
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
if (-not $AllowLaptopFallback) {
throw 'The delivery node now runs on The-Ocean. Start a laptop fallback only after stopping the remote copy, then pass -AllowLaptopFallback. Never connect both copies of the same node.'
}
$repoPath = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
$sshArguments = @('-i', $IdentityFile, '-o', 'IdentitiesOnly=yes', '-o', 'BatchMode=yes',
'-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10', "root@$Droplet")
& ssh @sshArguments 'docker exec -u jenkins gitea-jenkins-1 test -f /var/jenkins_home/delivery-bootstrap/configured.json'
& docker volume create ssw590-delivery-identity | Out-Null
# The generated identity flows directly from pinned administrator SSH into a
# protected Docker volume. No secret enters command arguments, output or Git.
& 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'
Push-Location $repoPath
try {
& docker compose -f delivery/agent/compose.yaml up -d
& docker compose -f delivery/agent/compose.yaml ps
} finally {
Pop-Location
}
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# Run as root from /opt/ssw590-delivery-agent after stopping the laptop copy.
# Copy compose.droplet.yaml and ssh_config.droplet here first; load the verified
# agent image. Never copy any identity file into this directory or into Git.
set -euo pipefail
test "$(id -u)" = 0
cd /opt/ssw590-delivery-agent
export DOCKER_GID
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 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 \
'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
# BuildKit's own container must be limited too: the socket mount does not make
# child build containers inherit the agent's resource caps.
if ! docker exec "$agent" docker buildx inspect ssw590-delivery-limited >/dev/null 2>&1; then
docker exec "$agent" docker buildx create --name ssw590-delivery-limited \
--driver docker-container \
--driver-opt image=moby/buildkit@sha256:c5f8862f52499773af85bc07695b2379ef08e8002352b0df2c4864c91d78dabe,memory=256m,memory-swap=384m,cpu-period=100000,cpu-quota=50000,restart-policy=unless-stopped
fi
docker exec "$agent" docker buildx inspect ssw590-delivery-limited --bootstrap
docker compose -f compose.droplet.yaml ps
@@ -0,0 +1,41 @@
"""Read-only, non-secret runtime checks; run as root on The-Ocean."""
import json
import subprocess
from datetime import datetime, timezone
from pathlib import Path
def run(*args):
return subprocess.check_output(args, text=True).strip()
report = {"observed_at": datetime.now(timezone.utc).isoformat(), "containers": []}
names = ["ssw590-delivery-agent-1", "buildx_buildkit_ssw590-delivery-limited0"]
for name in names:
info = json.loads(run("docker", "inspect", name))[0]
config, state = info["HostConfig"], info["State"]
events = Path("/sys/fs/cgroup/system.slice", "docker-" + info["Id"] + ".scope", "memory.events")
report["containers"].append({
"name": name, "running": state["Running"], "oom_killed": state["OOMKilled"],
"restart_count": info["RestartCount"], "restart_policy": config["RestartPolicy"]["Name"],
"memory_bytes": config["Memory"], "memory_swap_bytes": config["MemorySwap"],
"nano_cpus": config["NanoCpus"], "cpu_quota": config["CpuQuota"],
"cpu_period": config["CpuPeriod"], "port_bindings": config["PortBindings"],
"memory_events": events.read_text().strip() if events.exists() else "unavailable",
})
assert state["Running"] and not state["OOMKilled"], name
report["private_http"] = {}
for url in ["http://jenkins:8080/login", "http://gitea:3000/", "http://monitoring-grafana-1:3000/login"]:
code = run("docker", "exec", names[0], "curl", "--silent", "--show-error", "--max-time", "15",
"-o", "/dev/null", "-w", "%{http_code}", url)
report["private_http"][url] = code
assert code == "200", (url, code)
ssh = run("docker", "exec", names[0], "ssh", "-G", "147.182.178.136")
report["deployment_ssh_route"] = [line for line in ssh.splitlines() if line.startswith(("hostname ", "hostkeyalias "))]
assert "hostname host.docker.internal" in ssh.splitlines()
assert "hostkeyalias 147.182.178.136" in ssh.splitlines()
report["memory"] = run("free", "-m")
report["disk"] = run("df", "-h", "/")
report["running_containers"] = run("docker", "ps", "--format", "{{.Names}} {{.Status}}")
report["result"] = "passed"
print(json.dumps(report, indent=2))
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
set -eu
record=$1
environment=$2
operation=${3:-deploy}
case "$record" in
build/delivery/releases/*.json|delivery/releases/*.json) ;;
*) echo 'Release record must be in the release metadata directory' >&2; exit 1 ;;
esac
python3 delivery/ci/release.py verify "$record" --environment "$environment"
config=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["configuration_commit"])' "$record")
scratch=$(mktemp -d)
trap 'rm -rf "$scratch"' EXIT
# Recover both playbook and template from the configuration recorded with this image.
git archive "$config" delivery/ansible | tar -x -C "$scratch"
: "${DEPLOY_KEY:?bind the deployment SSH key as a Jenkins file credential}"
: "${DEPLOY_KNOWN_HOSTS:?bind the verified known_hosts as a Jenkins file credential}"
export ANSIBLE_HOST_KEY_CHECKING=True
export ANSIBLE_SSH_ARGS="-o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$DEPLOY_KNOWN_HOSTS"
export ANSIBLE_PRIVATE_KEY_FILE="$DEPLOY_KEY"
ansible-playbook -i "$scratch/delivery/ansible/inventory.ini" \
"$scratch/delivery/ansible/deploy.yml" --syntax-check -e "@$record"
python3 delivery/ci/run-ansible.py "$record" "$operation" \
-i "$scratch/delivery/ansible/inventory.ini" \
"$scratch/delivery/ansible/deploy.yml" -e "@$record"
+48
View File
@@ -0,0 +1,48 @@
"""Sample public HTTPS health during release/recovery; failures are evidence."""
import argparse
import csv
from datetime import datetime, timezone
import json
from pathlib import Path
import time
import urllib.error
import urllib.request
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--url', choices=['https://app.yebilly.me', 'https://staging.yebilly.me'], required=True)
parser.add_argument('--seconds', type=int, default=600)
parser.add_argument('--interval', type=float, default=1)
parser.add_argument('--output', required=True)
args = parser.parse_args()
if not 1 <= args.seconds <= 1800 or args.interval < 0.5:
parser.error('Use 1-1800 seconds and at least 0.5 seconds between samples')
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
deadline = time.monotonic() + args.seconds
with output.open('w', newline='') as stream:
writer = csv.writer(stream)
writer.writerow(['started_utc', 'elapsed_seconds', 'http_status', 'status', 'version', 'error'])
while time.monotonic() < deadline:
started = datetime.now(timezone.utc).isoformat()
clock = time.monotonic()
code, status, version, error = '', '', '', ''
try:
with urllib.request.urlopen(args.url + '/health', timeout=2) as response:
code = response.status
body = json.load(response)
status, version = body.get('status', ''), body.get('version', '')
except urllib.error.HTTPError as failure:
code, error = failure.code, type(failure).__name__
except (OSError, ValueError, urllib.error.URLError) as failure:
error = type(failure).__name__
writer.writerow([started, round(time.monotonic() - clock, 3), code, status, version, error])
stream.flush()
time.sleep(max(0, args.interval - (time.monotonic() - clock)))
print(f'Saved samples to {output}; inspect failed samples and gaps, not just the exit status')
if __name__ == '__main__':
main()
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
set -eu
set +x
: "${REGISTRY_USER:?bind registry credentials}"
: "${REGISTRY_TOKEN:?bind registry credentials}"
image=git.yebilly.me/ssw590-group1/pricing
commit=$(git rev-parse HEAD)
reports=build/delivery/reports
mkdir -p "$reports" build/delivery/releases
export DOCKER_CONFIG
DOCKER_CONFIG=$(mktemp -d)
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
printf '%s' "$REGISTRY_TOKEN" | docker login --username "$REGISTRY_USER" --password-stdin git.yebilly.me
# Never overwrite a source-commit tag during a retry.
if docker manifest inspect "$image:$commit" > "$reports/existing-manifest.json" 2> "$reports/manifest-check.log"; then
docker pull "$image:$commit"
else
if ! grep -Eqi 'manifest unknown|no such manifest|not found' "$reports/manifest-check.log"; then
cat "$reports/manifest-check.log" >&2
exit 1
fi
if [ -n "${DELIVERY_BUILDER:-}" ]; then
docker buildx build --builder "$DELIVERY_BUILDER" --load --platform linux/amd64 \
--build-arg "APP_COMMIT=$commit" -t "$image:$commit" delivery/app
else
docker build --platform linux/amd64 --build-arg "APP_COMMIT=$commit" -t "$image:$commit" delivery/app
fi
python3 delivery/ci/security.py image --image "$image:$commit" --reports "$reports/image-gate"
docker push "$image:$commit"
docker pull "$image:$commit"
fi
digest=$(docker image inspect "$image:$commit" --format '{{index .RepoDigests 0}}')
python3 delivery/ci/security.py image --image "$digest" --reports "$reports/published-image-gate"
printf '%s\n' "$digest" > "$reports/published-digest.txt"
python3 delivery/ci/release.py create --image "$digest" --build-url "$BUILD_URL" --output build/delivery/releases
+77
View File
@@ -0,0 +1,77 @@
"""Create and verify non-secret release records used by Ansible."""
import argparse
import ast
import json
import re
import subprocess
from datetime import datetime, timezone
from pathlib import Path
URLS = {"staging": "https://staging.yebilly.me", "production": "https://app.yebilly.me"}
IMAGE = re.compile(r"git\.yebilly\.me/ssw590-group1/pricing@sha256:[0-9a-f]{64}")
COMMIT = re.compile(r"[0-9a-f]{40}")
def verify(record):
required = {"release_image", "expected_commit", "configuration_commit",
"expected_version", "expected_total", "proxy_network", "target_env", "public_url"}
if not required <= record.keys() or record.keys() - required - {"build_url", "created_at"}:
raise ValueError("Missing or unexpected release fields")
if not IMAGE.fullmatch(record["release_image"]):
raise ValueError("Release requires the team registry image and exact digest")
for name in ("expected_commit", "configuration_commit"):
value = record[name]
if not COMMIT.fullmatch(value):
raise ValueError(f"Invalid {name}")
subprocess.run(["git", "merge-base", "--is-ancestor", value, "origin/main"], check=True)
version = record["expected_version"]
if version not in {"v1", "v2"}:
raise ValueError("Unsupported application release")
if record["expected_total"] != {"v1": 30, "v2": 36}[version]:
raise ValueError("Unexpected business result")
environment = record["target_env"]
if record["public_url"] != URLS[environment] or record["proxy_network"] != "gitea_web":
raise ValueError("Unexpected deployment target")
def main():
parser = argparse.ArgumentParser()
commands = parser.add_subparsers(dest="action", required=True)
create = commands.add_parser("create")
create.add_argument("--image", required=True)
create.add_argument("--build-url", required=True)
create.add_argument("--output", required=True)
check = commands.add_parser("verify")
check.add_argument("record")
check.add_argument("--environment", choices=["staging", "production"])
args = parser.parse_args()
if args.action == "verify":
record = json.loads(Path(args.record).read_text())
verify(record)
if args.environment and record["target_env"] != args.environment:
raise ValueError("Release environment does not match the authorized pipeline stage")
return
values = {}
for node in ast.parse(Path("delivery/app/app.py").read_text()).body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in {"VERSION", "UNIT_PRICE"}:
values[target.id] = ast.literal_eval(node.value)
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
record = {
"release_image": args.image, "expected_commit": commit,
"configuration_commit": commit, "expected_version": values["VERSION"],
"expected_total": values["UNIT_PRICE"] * 3, "proxy_network": "gitea_web",
"build_url": args.build_url, "created_at": datetime.now(timezone.utc).isoformat(),
}
output = Path(args.output)
output.mkdir(parents=True, exist_ok=True)
for environment, url in URLS.items():
target = dict(record, target_env=environment, public_url=url)
verify(target)
(output / f"{values['VERSION']}-{environment}.json").write_text(json.dumps(target, indent=2))
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
"""Archive deployment timing/recaps and enforce the unchanged-rerun gate."""
import json
import os
import re
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
def main():
record = json.loads(Path(sys.argv[1]).read_text())
operation = sys.argv[2]
if operation not in {"deploy", "rerun"}:
raise ValueError("Unknown deployment operation")
reports = Path("build/delivery/reports")
reports.mkdir(parents=True, exist_ok=True)
stem = f"ansible-{record['target_env']}-{operation}"
started = datetime.now(timezone.utc).isoformat()
clock = time.monotonic()
process = subprocess.Popen(
["ansible-playbook", *sys.argv[3:]], text=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
env=dict(os.environ, ANSIBLE_NOCOLOR="1"),
)
lines = []
with (reports / f"{stem}.txt").open("w") as log:
for line in process.stdout:
print(line, end="", flush=True)
log.write(line)
lines.append(line)
status = process.wait()
recaps = []
for line in lines:
match = re.match(r"^(\S+)\s+:\s+ok=(\d+)\s+changed=(\d+)\s+unreachable=(\d+)\s+failed=(\d+)", line)
if match:
recaps.append(dict(zip(
["host", "ok", "changed", "unreachable", "failed"],
[match[1], *map(int, match.groups()[1:])],
)))
passed = status == 0 and bool(recaps) and all(
row["failed"] == 0 and row["unreachable"] == 0
and (operation != "rerun" or row["changed"] == 0)
for row in recaps
)
report = {
"started": started, "completed": datetime.now(timezone.utc).isoformat(),
"elapsed_seconds": round(time.monotonic() - clock, 3),
"operation": operation, "release": record,
"ansible_exit_code": status, "recaps": recaps,
"result": "passed" if passed else "blocked",
}
(reports / f"{stem}.json").write_text(json.dumps(report, indent=2))
if not passed:
print("Deployment gate blocked: inspect the archived Ansible recap", file=sys.stderr)
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())
+127
View File
@@ -0,0 +1,127 @@
"""Run release gates and preserve reports, tool versions, and process exit codes."""
import argparse
import json
import subprocess
import tempfile
from datetime import datetime, timezone
from pathlib import Path
def now():
return datetime.now(timezone.utc).isoformat()
def check_report(report, kind):
if kind == "dependencies":
dependencies = report["dependencies"]
if not dependencies:
raise ValueError("Dependency audit returned no packages")
return [v for package in dependencies for v in package["vulns"]]
if report["SchemaVersion"] != 2 or "ArtifactName" not in report:
raise ValueError("Unrecognized Trivy report")
results = report["Results"]
if not isinstance(results, list):
raise ValueError("Trivy Results must be a list")
if kind == "image" and not results:
raise ValueError("Image scan returned no analyzed targets")
if kind == "secrets":
return [secret for result in results for secret in result.get("Secrets", [])]
return [
vulnerability
for result in results
for vulnerability in result.get("Vulnerabilities", [])
if vulnerability["Severity"] in {"HIGH", "CRITICAL"}
]
def redact_secret_matches(report):
for result in report.get("Results", []):
for secret in result.get("Secrets", []):
secret["Match"] = "[REDACTED]"
for line in secret.get("Code", {}).get("Lines", []):
line["Content"] = "[REDACTED]"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("phase", choices=["source", "image"])
parser.add_argument("--image")
parser.add_argument("--fixture", action="store_true")
parser.add_argument("--reports", default="build/delivery/reports")
args = parser.parse_args()
reports = Path(args.reports).resolve()
reports.mkdir(parents=True, exist_ok=True)
execution = {"started": now(), "phase": args.phase, "steps": []}
def run(command, label, accepted=(0,)):
result = subprocess.run(command, text=True, capture_output=True)
(reports / f"{label}.log").write_text(result.stdout + result.stderr)
execution["steps"].append({
"label": label, "command": command, "completed": now(),
"exit_code": result.returncode,
})
if result.returncode not in accepted:
raise RuntimeError(f"{label} failed with exit code {result.returncode}")
return result
def scan_secrets(target, label):
output = reports / f"{label}.json"
run([
"trivy", "fs", "--scanners", "secret", "--secret-config",
"delivery/trivy-secret.yaml", "--format", "json", "--output", str(output),
"--skip-dirs", ".git", "--skip-dirs", "build", "--skip-dirs", "work",
"--skip-dirs", ".venv", str(target),
], label)
report = json.loads(output.read_text())
redact_secret_matches(report)
output.write_text(json.dumps(report, indent=2))
if check_report(report, "secrets"):
raise RuntimeError(f"{label}: detected secrets block delivery")
try:
run(["trivy", "--version"], "trivy-version")
run(["pip-audit", "--version"], "pip-audit-version")
if args.phase == "source":
scan_secrets(".", "source-secrets")
output = reports / "dependencies.json"
result = run([
"pip-audit", "-r", "delivery/app/requirements.txt", "--no-deps",
"--disable-pip", "--format", "json", "--output", str(output),
], "dependencies", accepted=(0, 1))
findings = check_report(json.loads(output.read_text()), "dependencies")
if result.returncode or findings:
raise RuntimeError("Dependency findings or audit errors block delivery")
if args.fixture:
with tempfile.TemporaryDirectory(prefix="ssw590-scan-") as directory:
# Construct the nonfunctional course fixture only in the test run.
value = "SSW590_SYNTHETIC_SECRET_" + "0" * 16
Path(directory, "fixture.txt").write_text(value)
scan_secrets(directory, "synthetic-secret")
raise RuntimeError("Synthetic fixture was not detected")
else:
if not args.image:
raise ValueError("--image is required for the image gate")
output = reports / "image.json"
run([
"trivy", "image", "--scanners", "vuln", "--format", "json",
"--output", str(output), args.image,
], "image")
run(["trivy", "--version"], "trivy-database-version")
if check_report(json.loads(output.read_text()), "image"):
raise RuntimeError("HIGH/CRITICAL image findings block delivery")
execution["result"] = "passed"
print(f"{args.phase} gate passed")
except (OSError, ValueError, KeyError, TypeError, RuntimeError) as error:
execution["result"] = "blocked"
execution["reason"] = str(error)
print(f"{args.phase} gate blocked: {error}")
return 1
finally:
execution["completed"] = now()
(reports / f"{args.phase}-execution.json").write_text(json.dumps(execution, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+43
View File
@@ -0,0 +1,43 @@
#!/bin/sh
set -eu
reports=${REPORTS_DIR:-build/delivery/reports}
mkdir -p "$reports"
reports=$(cd "$reports" && pwd)
test_dir=$(mktemp -d)
trap 'rm -rf "$test_dir"' EXIT
python3 -m venv "$test_dir/venv"
test_python="$test_dir/venv/bin/python"
"$test_python" -m pip install -r delivery/app/requirements.txt
cp delivery/app/app.py delivery/app/test_app.py "$test_dir/"
if [ "${TEST_FAILURE:-false}" = true ]; then
cat > "$test_dir/test_gate_fixture.py" <<'PY'
import unittest
from app import app
class ControlledWrongPrice(unittest.TestCase):
def test_deliberately_wrong_expected_price(self):
response = app.test_client().get('/price?quantity=3')
self.assertEqual(response.json['total'], -1, 'Controlled test must block delivery')
PY
fi
cd "$test_dir"
"$test_python" -B - "$reports" <<'PY'
import json
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
started = datetime.now(timezone.utc).isoformat()
result = subprocess.run([sys.executable, '-B', '-m', 'unittest', '-v'], text=True, capture_output=True)
output = result.stdout + result.stderr
print(output, end='')
reports = Path(sys.argv[1])
(reports / 'unit-tests.txt').write_text(output)
(reports / 'unit-tests.json').write_text(json.dumps({
'started': started, 'completed': datetime.now(timezone.utc).isoformat(),
'exit_code': result.returncode,
'result': 'passed' if result.returncode == 0 else 'blocked',
}, indent=2))
raise SystemExit(result.returncode)
PY
+112
View File
@@ -0,0 +1,112 @@
"""Regression checks for fail-closed release and scan boundaries."""
import importlib.util
import io
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
import release
import security
spec = importlib.util.spec_from_file_location('run_ansible', Path(__file__).with_name('run-ansible.py'))
run_ansible = importlib.util.module_from_spec(spec)
spec.loader.exec_module(run_ansible)
class SecurityGateTests(unittest.TestCase):
def test_empty_dependency_audit_is_not_clean_evidence(self):
with self.assertRaises(ValueError):
security.check_report({"dependencies": []}, "dependencies")
def test_incomplete_or_unrecognized_scan_is_rejected(self):
for report in [{}, {"SchemaVersion": 2, "ArtifactName": "."},
{"SchemaVersion": 3, "ArtifactName": ".", "Results": []}]:
with self.subTest(report=report), self.assertRaises((ValueError, KeyError)):
security.check_report(report, "secrets")
def test_high_findings_and_secrets_block(self):
report = {"SchemaVersion": 2, "ArtifactName": "image", "Results": [{
"Vulnerabilities": [{"Severity": "LOW"}, {"Severity": "HIGH"}, {"Severity": "CRITICAL"}],
"Secrets": [{"Severity": "LOW", "Match": "test-data"}],
}]}
self.assertEqual(len(security.check_report(report, "image")), 2)
self.assertEqual(len(security.check_report(report, "secrets")), 1)
security.redact_secret_matches(report)
self.assertEqual(report["Results"][0]["Secrets"][0]["Match"], "[REDACTED]")
def test_image_without_analyzed_targets_is_rejected(self):
with self.assertRaises(ValueError):
security.check_report({"SchemaVersion": 2, "ArtifactName": "image", "Results": []}, "image")
class ReleaseBoundaryTests(unittest.TestCase):
def setUp(self):
self.record = {
"release_image": "git.yebilly.me/ssw590-group1/pricing@sha256:" + "a" * 64,
"expected_commit": "b" * 40, "configuration_commit": "c" * 40,
"expected_version": "v1", "expected_total": 30,
"proxy_network": "gitea_web", "target_env": "staging",
"public_url": "https://staging.yebilly.me",
}
@patch("release.subprocess.run")
def test_both_commits_must_be_reviewed_main_ancestors(self, run):
release.verify(self.record)
self.assertEqual([call.args[0][-2] for call in run.call_args_list], ["b" * 40, "c" * 40])
self.assertTrue(all(call.kwargs["check"] for call in run.call_args_list))
@patch("release.subprocess.run")
def test_cross_environment_url_is_rejected(self, run):
self.record["public_url"] = "https://app.yebilly.me"
with self.assertRaises(ValueError):
release.verify(self.record)
def test_mutable_tag_or_other_registry_is_rejected(self):
for image in ["git.yebilly.me/ssw590-group1/pricing:latest", "example.com/pricing@sha256:" + "a" * 64]:
self.record["release_image"] = image
with self.assertRaises(ValueError):
release.verify(self.record)
def test_unexpected_ansible_variables_are_rejected(self):
self.record["ansible_host"] = "unapproved-host"
with self.assertRaises(ValueError):
release.verify(self.record)
class UnchangedRerunTests(unittest.TestCase):
def check_recap(self, text, exit_code=0):
original = Path.cwd()
with tempfile.TemporaryDirectory() as directory:
try:
os.chdir(directory)
Path('release.json').write_text(json.dumps({'target_env': 'staging'}))
with patch('sys.argv', ['run-ansible.py', 'release.json', 'rerun', 'playbook.yml']), \
patch.object(run_ansible.subprocess, 'Popen') as launch, \
patch('sys.stdout', new_callable=io.StringIO), \
patch('sys.stderr', new_callable=io.StringIO):
launch.return_value.stdout = io.StringIO(text)
launch.return_value.wait.return_value = exit_code
return run_ansible.main()
finally:
os.chdir(original)
def test_unchanged_success_passes(self):
self.assertEqual(self.check_recap('startup : ok=9 changed=0 unreachable=0 failed=0 skipped=0\n'), 0)
def test_success_with_unnecessary_changes_blocks(self):
self.assertEqual(self.check_recap('startup : ok=9 changed=1 unreachable=0 failed=0 skipped=0\n'), 1)
def test_missing_recap_is_not_a_success(self):
self.assertEqual(self.check_recap('No deployment results\n'), 1)
def test_ansible_error_blocks_even_with_good_looking_recap(self):
self.assertEqual(self.check_recap('startup : ok=9 changed=0 unreachable=0 failed=0\n', 1), 1)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,64 @@
# Delivery agent migration — preparation evidence
Vincent selected The-Ocean instead of the laptop to avoid the previously
observed campus SSH restriction. This work occurred on November 14 Eastern;
the host's UTC timestamps below fall on November 15, 2026.
- Existing host: 1 CPU, 1,967 MiB RAM, original 25 GB plan disk, 2 GiB swap.
At 03:29 UTC, 811 MiB RAM was available and swap used was 129 MiB.
- Transferred the existing agent image, without rebuilding its toolchain:
`sha256:0752666650a3afe7b61854c1df4dca21f4ef381fab1f4fb9b042adaa203c58a8`.
Transfer archive SHA-256 matched on both machines:
`f987fdb285757aabe91fffd21a3a58da00bec975efcce7ee8ef3f127b27d0696`.
- Stopped the laptop container before connecting its replacement. Existing
node name `ssw590-vince-delivery`, label `delivery-trusted`, one exclusive
executor, folder credentials and disabled pricing job were retained.
- Remote agent: 512 MiB RAM / 768 MiB RAM+swap, 0.5 CPU, 96 MiB JVM heap,
no published port, existing `gitea_web` network, private WebSocket connection.
Socket group detected as 987; initial group-0 mismatch was corrected.
- Builder: BuildKit v0.34.2 image pinned by index digest in the start helper;
256 MiB RAM / 384 MiB RAM+swap, CPU quota 50000/100000, no published port.
The pipeline explicitly selects this builder when `DELIVERY_BUILDER` is set.
- Deployment SSH: `ssh -G` reports `hostname host.docker.internal` and
`hostkeyalias 147.182.178.136`. The existing Jenkins known-hosts credential
remains authoritative; host verification was not bypassed.
- [Jenkins prerequisite build 2](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/2/)
passed at 03:47 UTC, including real credential binding, deploy login, pinned
host key and sudo. See [inventory](agent-preflight-2.txt).
- 03:50:16–03:51:43 UTC: the separate capacity preparation trial passed 12
control tests and 3 app tests, source-secret/dependency gates, capped image
build, full image gate (zero HIGH/CRITICAL), and a temporary 64 MiB app smoke.
Health v1, identity `uncommitted-remote-preflight`, total 30 for quantity 3,
and HTTP 400 for invalid quantity were verified. The smoke container was
removed. No image was pushed and no assessed environment was deployed.
- The trial used a non-secret local snapshot of `delivery/app`, `delivery/ci`,
the scanner rule and the trial script, not a reviewed full repository checkout.
Snapshot archive SHA-256:
`2cd5d23062ff9904b48a23dfd5d9f2b9c67929cb86db006e7b2677060da3afa0`.
Gate reports retain actual timestamps and tool/database metadata.
- Observed available RAM exceeded 700 MiB; swap used increased from 263 to
372 MiB during the sampled trial. At 03:54 UTC, 861 MiB was available, swap
used was 370 MiB and root disk was 56% used (11 GiB available, rounded by df).
Agent cgroup memory-limit events were nonzero; agent and builder `oom` and
`oom_kill` counters were zero, and both reported `OOMKilled=false`.
- Gitea, Jenkins login and Grafana login returned HTTP 200 through private
Docker routes after the trial. Seven previous containers remained running.
- Restarted only the agent; logs recorded a fresh WebSocket connection and
`Connected` at 03:57:57 UTC. `unless-stopped` is configured for both agent and
builder; an entire-host reboot was not performed as part of this migration.
Raw reports, partial resource-output capture, runtime JSON and screenshot:
ignored `build/evidence/assignment8-agent-migration/`. Protected server reports:
`/root/ssw590-delivery-bootstrap/agent-migration/`. The short trial used swap
and does not prove full release, recovery or campus presentation performance.
No firewall rule, credential scope, TLS verification, peer-review requirement
or human production approval changed. Co-located Docker authority gives trusted
jobs administrative access to the shared host; this is an explicit course-lab
trade-off. The older Gitea Actions PDF runner remains on the laptop. No new
instance or cloud plan change was made. Migration changes are uncommitted;
DNS, reviewed releases, production approvals and recovery exercises remain pending.
Subsequently Vincent requested moving that Actions runner too. The statement
above describes the end of the delivery-agent migration, not current placement.
See the [later runner record](../../gitea/droplet-runner/EVIDENCE.md).
+32
View File
@@ -0,0 +1,32 @@
Sat Nov 14 20:46:17 UTC 2026
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),0(root)
Python 3.13.5
ansible [core 2.21.6]
config file = None
configured module search path = ['/home/jenkins/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /opt/delivery-tools/lib/python3.13/site-packages/ansible
ansible collection location = /opt/ansible-collections
executable location = /opt/delivery-tools/bin/ansible
python version = 3.13.5 (main, Aug 10 2026, 12:06:59) [GCC 14.2.0] (/opt/delivery-tools/bin/python3)
jinja version = 3.1.6
pyyaml version = 6.0.3 (with libyaml v0.2.5)
# /opt/ansible-collections/ansible_collections
Collection Version
---------------------------------------- -------
community.docker 5.4.0
community.library_inventory_filtering_v1 1.1.5
Docker version 29.9.3, build 5457199
Docker Compose version v5.7.1
Version: 0.76.2
pip-audit 2.10.1
uid=1000(deploy) gid=1000(deploy) groups=1000(deploy)
Python 3.12.3
Docker version 29.9.3, build 5457199
Docker Compose version v5.7.1
total used free shared buff/cache available
Mem: 1967 1089 85 4 955 878
Swap: 2047 102 1945
1
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 24G 9.5G 14G 41% /
+32
View File
@@ -0,0 +1,32 @@
Sun Nov 15 03:47:13 UTC 2026
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),987
Python 3.13.5
ansible [core 2.21.6]
config file = None
configured module search path = ['/home/jenkins/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /opt/delivery-tools/lib/python3.13/site-packages/ansible
ansible collection location = /opt/ansible-collections
executable location = /opt/delivery-tools/bin/ansible
python version = 3.13.5 (main, Aug 10 2026, 12:06:59) [GCC 14.2.0] (/opt/delivery-tools/bin/python3)
jinja version = 3.1.6
pyyaml version = 6.0.3 (with libyaml v0.2.5)
# /opt/ansible-collections/ansible_collections
Collection Version
---------------------------------------- -------
community.docker 5.4.0
community.library_inventory_filtering_v1 1.1.5
Docker version 29.9.3, build 5457199
Docker Compose version v5.7.1
Version: 0.76.2
pip-audit 2.10.1
uid=1000(deploy) gid=1000(deploy) groups=1000(deploy)
Python 3.12.3
Docker version 29.9.3, build 5457199
Docker Compose version v5.7.1
total used free shared buff/cache available
Mem: 1967 1205 106 3 832 762
Swap: 2047 265 1782
1
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 24G 12G 13G 49% /
+35
View File
@@ -0,0 +1,35 @@
Sun Nov 15 22:50:10 UTC 2026
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),987
Python 3.13.5
ansible [core 2.21.6]
config file = None
configured module search path = ['/home/jenkins/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /opt/delivery-tools/lib/python3.13/site-packages/ansible
ansible collection location = /opt/ansible-collections
executable location = /opt/delivery-tools/bin/ansible
python version = 3.13.5 (main, Aug 10 2026, 12:06:59) [GCC 14.2.0] (/opt/delivery-tools/bin/python3)
jinja version = 3.1.6
pyyaml version = 6.0.3 (with libyaml v0.2.5)
# /opt/ansible-collections/ansible_collections
Collection Version
---------------------------------------- -------
community.docker 5.4.0
community.library_inventory_filtering_v1 1.1.5
Docker version 29.9.3, build 5457199
Docker Compose version v5.7.1
Version: 0.76.2
pip-audit 2.10.1
uid=1000(deploy) gid=1000(deploy) groups=1000(deploy)
Python 3.12.3
Docker version 29.9.3, build 5457199
Docker Compose version v5.7.1
total used free shared buff/cache available
Mem: 1967 1239 86 3 817 728
Swap: 2047 413 1634
1
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 24G 15G 9.2G 61% /
147.182.178.136 | CHANGED | rc=0 >>
0
+31
View File
@@ -0,0 +1,31 @@
# Assessed Jenkins gate demonstrations — 15 November 2026
Reviewed source: `09731acb0370566471dd4e401e59bafe55e927dc`, the merge of
[PR 24](https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/pulls/24).
Billy (`bill`) approved the latest preparation head `ed0a862` at 21:06 UTC;
Vincent merged it at 21:59 UTC. The merge-triggered manual workflow
[run 13](https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/actions/runs/13)
passed in 2m25s before the delivery demonstrations began.
| Jenkins pricing run | Mode | Actual result |
|---|---|---|
| [1](https://ci.yebilly.me/job/secure-delivery/job/pricing/1/) | `blocked-test` | FAILURE as intended, 54.202 seconds. Twelve control tests and three normal Flask tests passed; the additional expected-total=-1 assertion failed against the real v1 total 30. All later security, publication, deployment and approval stages were skipped. |
| [2](https://ci.yebilly.me/job/secure-delivery/job/pricing/2/) | `blocked-secret` | FAILURE as intended, 31.375 seconds. Twelve control tests and three Flask tests passed. Clean-source scanning and all nine locked dependency audits passed; the generated synthetic-secret fixture was detected, blocking publication, deployment and approval. |
Run 1 began at 22:11:34.732 UTC. Run 2 began at 22:12:51.073 UTC;
its source gate ran from 22:13:14.233 to 22:13:20.115 UTC. The scanner itself
returned zero after writing a valid report; the gate wrapper returned one
because that report contained a finding. This is expected policy enforcement,
not a scanner execution error. The synthetic fixture is nonfunctional and
generated only in a temporary directory; captured match/code fields are redacted.
Jenkins archives the test and gate reports for each run. Exact local copies,
selected build metadata and console logs are retained in ignored
`build/evidence/assignment8-execution/jenkins-{1,2}/`. These two negative
demonstrations do not establish a successful release or production approval.
The job was enabled only after the merge. A bootstrap MODE choice parameter
allowed the first run to select `blocked-test`; the reviewed Jenkinsfile then
installed its normal four parameter definitions and retained its approval,
timeout, concurrency and ancestry checks. Existing credentials and access
permissions were unchanged.
@@ -0,0 +1,133 @@
{
"started": "2026-11-16T02:06:37.133690+00:00",
"image": "git.yebilly.me/ssw590-group1/pricing@sha256:63e2e3d49a5119b1064868b0b15b39a1719a60a632ff0ecdc3f676fcdc55de3b",
"existing_staging_health": {
"Status": "healthy",
"FailingStreak": 0,
"Log": [
{
"Start": "2026-11-16T02:05:39.379167981Z",
"End": "2026-11-16T02:05:42.481797619Z",
"ExitCode": -1,
"Output": "Health check exceeded timeout (3s)"
},
{
"Start": "2026-11-16T02:05:52.483085766Z",
"End": "2026-11-16T02:05:55.560331159Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:06:05.56119162Z",
"End": "2026-11-16T02:06:08.689713122Z",
"ExitCode": -1,
"Output": "Health check exceeded timeout (3s)"
},
{
"Start": "2026-11-16T02:06:18.690913613Z",
"End": "2026-11-16T02:06:21.782465826Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:06:31.784224739Z",
"End": "2026-11-16T02:06:34.780482181Z",
"ExitCode": 0,
"Output": ""
}
]
},
"existing_staging_memory_events": "low 0\nhigh 0\nmax 29\noom 0\noom_kill 0\noom_group_kill 0",
"candidate_timeout_seconds": 10,
"samples": [
{
"Start": "2026-11-16T02:06:42.778495877Z",
"End": "2026-11-16T02:06:48.438554619Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:06:58.439880386Z",
"End": "2026-11-16T02:07:01.623272338Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:07:11.624979767Z",
"End": "2026-11-16T02:07:14.734453351Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:07:24.735921433Z",
"End": "2026-11-16T02:07:27.640717567Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:07:37.641388311Z",
"End": "2026-11-16T02:07:40.639898244Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:07:50.64115933Z",
"End": "2026-11-16T02:07:53.824315905Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:08:03.825342377Z",
"End": "2026-11-16T02:08:07.523556252Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:08:17.525594582Z",
"End": "2026-11-16T02:08:20.342264608Z",
"ExitCode": 0,
"Output": ""
}
],
"final_health": {
"Status": "healthy",
"FailingStreak": 0,
"Log": [
{
"Start": "2026-11-16T02:07:24.735921433Z",
"End": "2026-11-16T02:07:27.640717567Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:07:37.641388311Z",
"End": "2026-11-16T02:07:40.639898244Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:07:50.64115933Z",
"End": "2026-11-16T02:07:53.824315905Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:08:03.825342377Z",
"End": "2026-11-16T02:08:07.523556252Z",
"ExitCode": 0,
"Output": ""
},
{
"Start": "2026-11-16T02:08:17.525594582Z",
"End": "2026-11-16T02:08:20.342264608Z",
"ExitCode": 0,
"Output": ""
}
]
},
"memory_events": "low 0\nhigh 0\nmax 0\noom 0\noom_kill 0\noom_group_kill 0",
"cpu_stat": "usage_usec 8426586\nuser_usec 6475439\nsystem_usec 1951147\ncore_sched.force_idle_usec 0\nnr_periods 372\nnr_throttled 327\nthrottled_usec 23409965\nnr_bursts 0\nburst_usec 0",
"passed": true,
"completed": "2026-11-16T02:08:24.345181+00:00",
"temporary_container_removed": true
}
@@ -0,0 +1,51 @@
"""Administrator-only diagnostic; never deploys a pricing environment."""
import json
import subprocess
import time
from datetime import datetime, timezone
IMAGE = 'git.yebilly.me/ssw590-group1/pricing@sha256:63e2e3d49a5119b1064868b0b15b39a1719a60a632ff0ecdc3f676fcdc55de3b'
NAME = 'ssw590-pricing-health-trial'
def command(*args):
return subprocess.check_output(args, text=True).strip()
def health(container):
return json.loads(command('docker', 'inspect', '--format', '{{json .State.Health}}', container))
def now():
return datetime.now(timezone.utc).isoformat()
existing = subprocess.run(['docker','container','inspect',NAME],capture_output=True)
assert existing.returncode != 0, 'Existing diagnostic container must be reviewed'
report = {'started':now(), 'image':IMAGE, 'existing_staging_health':health('pricing-staging-app-1'),
'existing_staging_memory_events':command('docker','exec','pricing-staging-app-1','cat','/sys/fs/cgroup/memory.events'),
'candidate_timeout_seconds':10, 'samples':[]}
container = command('docker','run','-d','--pull','never','--name',NAME,
'--network','none','--read-only','--tmpfs','/tmp:size=16m,mode=1777',
'--cap-drop','ALL','--security-opt','no-new-privileges:true','--user','10001:10001',
'--memory','64m','--memory-swap','96m','--cpus','0.25','--pids-limit','64',
'--health-timeout','10s',IMAGE)
assert len(container) == 64 and all(c in '0123456789abcdef' for c in container)
seen = set()
try:
deadline = time.monotonic() + 170
while time.monotonic() < deadline:
state = health(container)
for sample in state.get('Log',[]):
if sample['Start'] not in seen:
seen.add(sample['Start'])
report['samples'].append(sample)
if len(report['samples']) >= 8:
break
time.sleep(5)
report['final_health'] = health(container)
report['memory_events'] = command('docker','exec',container,'cat','/sys/fs/cgroup/memory.events')
report['cpu_stat'] = command('docker','exec',container,'cat','/sys/fs/cgroup/cpu.stat')
report['passed'] = len(report['samples']) >= 8 and all(s['ExitCode'] == 0 for s in report['samples']) and report['final_health']['Status'] == 'healthy'
finally:
subprocess.run(['docker','rm','-f',container],check=True,capture_output=True)
report['completed'] = now()
report['temporary_container_removed'] = True
print(json.dumps(report,indent=2))
assert report['passed'], 'Health trial did not pass'
+36
View File
@@ -0,0 +1,36 @@
# DNS and HTTPS readiness — 15 November 2026
Billy added A records for `staging.yebilly.me` and `app.yebilly.me` pointing to
`147.182.178.136`. At 06:14 UTC, Google and Cloudflare DNS-over-HTTPS both returned
that A record and no AAAA answer for each name. No DNS account was accessed or
changed by Codex.
At 06:09:34 UTC, the prepared `deploy/Caddyfile` additions were validated with
installed Caddy 2.11.4, backed up and gracefully reloaded. The helper checked
that earlier routes matched before changing anything and preserved the existing
bind-mounted inode. The first comparison stopped because of CRLF versus LF;
normalizing only that comparison allowed the matching routes to pass.
- Before SHA-256: `0197f100c5a1f2a21c6a293964fada27f61fe6f4ddf0b0c6d1ed6455f2cfbcc5`.
- After SHA-256: `7adbd9469b1e0ebcb8d6b62c8576eb4fb8b51efc70409607f604f453f8ac8187`.
- Backup: `/root/ssw590-delivery-bootstrap/https-20261115/Caddyfile.before`.
- Existing Gitea/Jenkins/Grafana routes, allowlist placeholders, volumes and
certificate storage were preserved. No firewall or published port changed.
Normal Windows curl and Ubuntu Python TLS checks passed without insecure mode.
Both hostnames negotiated TLS 1.3 with trusted hostname-matching certificates.
HTTP returned 308 with the corresponding HTTPS Location. HTTPS returned 502:
the staging/production pricing containers do not exist yet. This proves DNS,
TLS and redirects, not app health or a completed release.
All ten prior service/agent/builder containers remained running. Gitea, Jenkins
login and Grafana login returned private HTTP 200 after the reload. Production
monitoring was not enabled while the pricing service was absent.
Actual DNS answers, certificate issuer/SAN/validity/fingerprints and HTTP results
are in ignored `build/evidence/assignment8-https/verification.json`; application
and existing-service checks remain separate. No reviewed release, registry
publication, promotion, rollback, password reset or account-permission change
was performed during this work. The source changes remain uncommitted.
Caddy behavior: [Automatic HTTPS](https://caddyserver.com/docs/automatic-https).
@@ -0,0 +1,26 @@
{
"applied_at": "2026-11-16T03:08:11.087796+00:00",
"production_health": {
"status": "ok",
"version": "v1"
},
"validation": "Checking /tmp/ssw590-production-probe-20261116T030810544427Z.yml\n SUCCESS: /tmp/ssw590-production-probe-20261116T030810544427Z.yml is valid prometheus config file syntax\n\n",
"prior_probes_and_panels_preserved": true,
"files": [
{
"path": "/root/monitoring/prometheus/prometheus.yml",
"before_sha256": "fe1d0f479d947e20ea7ebfec164689fe69ea9539ba0289adc2b7d26b8ffe62d6",
"after_sha256": "e35bc7fb3d09f7b3442324a2af147d8f1319ae1f0631ba81ed7577bb63826edd",
"inode_preserved": true
},
{
"path": "/root/monitoring/grafana/dashboards/sre.json",
"before_sha256": "c21fadca47ee624001133a82b788e728d08168664302666ed103113f3bec5f13",
"after_sha256": "08f99b845e5d56b81f54bf1b386aa50a54a88296ce5caf9496c5bfbf62929ed1",
"inode_preserved": true
}
],
"backup": "/root/ssw590-delivery-bootstrap/monitoring-20261116",
"reload": "Prometheus SIGHUP; Grafana file provisioning",
"result": "applied; runtime probe and panel verification still required"
}
@@ -0,0 +1,218 @@
{
"observed_at": "2026-11-16T03:14:11.206493+00:00",
"queries": {
"probe_success{job=\"https\"}": [
{
"metric": {
"__name__": "probe_success",
"instance": "https://ci.yebilly.me/login",
"job": "https"
},
"value": [
1794798851.242,
"1"
]
},
{
"metric": {
"__name__": "probe_success",
"instance": "https://git.yebilly.me/user/login",
"job": "https"
},
"value": [
1794798851.242,
"1"
]
},
{
"metric": {
"__name__": "probe_success",
"instance": "https://app.yebilly.me/health",
"job": "https"
},
"value": [
1794798851.242,
"1"
]
}
],
"prometheus_config_last_reload_successful": [
{
"metric": {
"__name__": "prometheus_config_last_reload_successful",
"instance": "prometheus:9090",
"job": "prometheus"
},
"value": [
1794798851.244,
"1"
]
}
],
"up": [
{
"metric": {
"__name__": "up",
"instance": "blackbox-exporter:9115",
"job": "blackbox"
},
"value": [
1794798851.245,
"1"
]
},
{
"metric": {
"__name__": "up",
"instance": "prometheus:9090",
"job": "prometheus"
},
"value": [
1794798851.245,
"1"
]
},
{
"metric": {
"__name__": "up",
"instance": "https://ci.yebilly.me/login",
"job": "https"
},
"value": [
1794798851.245,
"1"
]
},
{
"metric": {
"__name__": "up",
"instance": "https://git.yebilly.me/user/login",
"job": "https"
},
"value": [
1794798851.245,
"1"
]
},
{
"metric": {
"__name__": "up",
"instance": "node-exporter:9100",
"job": "node"
},
"value": [
1794798851.245,
"1"
]
},
{
"metric": {
"__name__": "up",
"instance": "https://app.yebilly.me/health",
"job": "https"
},
"value": [
1794798851.245,
"1"
]
}
]
},
"targets": [
{
"labels": {
"instance": "blackbox-exporter:9115",
"job": "blackbox"
},
"health": "up",
"lastError": "",
"lastScrape": "2026-11-16T03:13:46.738098436Z"
},
{
"labels": {
"instance": "https://git.yebilly.me/user/login",
"job": "https"
},
"health": "up",
"lastError": "",
"lastScrape": "2026-11-16T03:14:02.878212313Z"
},
{
"labels": {
"instance": "https://ci.yebilly.me/login",
"job": "https"
},
"health": "up",
"lastError": "",
"lastScrape": "2026-11-16T03:13:50.769303819Z"
},
{
"labels": {
"instance": "https://app.yebilly.me/health",
"job": "https"
},
"health": "up",
"lastError": "",
"lastScrape": "2026-11-16T03:13:54.602557327Z"
},
{
"labels": {
"instance": "node-exporter:9100",
"job": "node"
},
"health": "up",
"lastError": "",
"lastScrape": "2026-11-16T03:14:06.522911829Z"
},
{
"labels": {
"instance": "prometheus:9090",
"job": "prometheus"
},
"health": "up",
"lastError": "",
"lastScrape": "2026-11-16T03:13:47.742950331Z"
}
],
"dashboard_provisioning_source": {
"uid": "group1-sre",
"title": "Group 1 SRE",
"panels": [
{
"id": 1,
"title": "Droplet CPU utilization (%)"
},
{
"id": 2,
"title": "Available memory (bytes)"
},
{
"id": 3,
"title": "Root filesystem available (%)"
},
{
"id": 4,
"title": "Gitea HTTPS availability (probe_success)"
},
{
"id": 5,
"title": "Jenkins HTTPS availability (probe_success)"
},
{
"id": 6,
"title": "HTTPS probe duration (s)"
},
{
"id": 7,
"title": "Scrape health (up)"
},
{
"id": 8,
"title": "Pricing production HTTPS availability (probe_success)"
}
]
},
"production_probe_up": true,
"pricing_panel_configured": true,
"runtime_panel_verification": "Separate Grafana UI verification required"
}
@@ -0,0 +1,55 @@
# v1 publication and blocked deployment — 15 November 2026
[Pricing build 3](https://ci.yebilly.me/job/secure-delivery/job/pricing/3/)
ran in `release` mode from reviewed source/configuration commit
`09731acb0370566471dd4e401e59bafe55e927dc`. It began at 22:25:23.584 UTC,
took 77.799 seconds, and finished FAILURE. This was a published image followed
by a connection failure, **not a successful staging or production release**.
Tests, clean-source scanning and all nine locked dependency audits passed.
Both pre-push and registry-digest Trivy image reports analyzed two targets and
contained zero HIGH/CRITICAL findings. The agent built the image once, pushed
the source-SHA tag, pulled it back and verified this registry reference:
```text
git.yebilly.me/ssw590-group1/pricing@sha256:cccd47f112f839f3443c88c4d16fd7a1ed0fec2100a26464156526d53ccc2695
```
The generated staging/production records were timestamped 22:26:29.144 UTC.
Staging deployment began 22:26:33.530 and stopped at 22:26:39.422 UTC
(5.892 seconds), before any application configuration or container was created:
```text
TASK [Gathering Facts]
Failed to connect to the host via ssh: PTY allocation request failed on channel 0
startup : ok=0 changed=0 unreachable=1 failed=0
Ansible exit code: 4
```
Jenkins skipped the unchanged rerun and production approval/deployment.
The generated records and scans are archived in that build and copied to ignored
`build/evidence/assignment8-execution/jenkins-3/`. They are deliberately absent
from `delivery/releases/`: neither environment has been verified healthy.
## Correction and verification
Ansible's SSH connection plugin defaults to forcing a terminal. The deploy
key intentionally forbids PTY allocation. The inventory now selects
`ansible_ssh_use_tty=false` for the delivery group, matching that restriction.
See the official [Ansible 2.21 SSH connection options](https://docs.ansible.com/projects/ansible-core/2.21/collections/ansible/builtin/ssh_connection.html#parameter-use_tty).
Pinned host verification, key restrictions, credentials and sudo policy are unchanged.
The administrator-only preflight was extended to exercise Ansible's actual
SSH/become path using the same bound credentials, rather than plain SSH alone.
[Agent preflight build 3](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/3/)
passed in 17 seconds at 22:50 UTC. Its `ansible.builtin.command` invocation
of `id -u` returned `0`, proving the noninteractive module and sudo path.
The module reports CHANGED by default for a command; this is not a pricing
deployment or an unchanged-rerun result. Exact non-secret output is retained in
[`agent-preflight-3.txt`](agent-preflight-3.txt).
The source correction awaits Vincent's commit/push and Billy's review/merge.
Retry `release` from the corrected full main SHA; let the pipeline generate
fresh records for that reviewed source/configuration. Do not manually change
the failed attempt's record to imply a successful deployment or reuse it for
rollback. Retain its published image and reports as evidence.
@@ -0,0 +1,74 @@
# Staging deployment, blocked rerun and health-timeout trial
Client date: 15 November 2026 (Eastern). Execution timestamps below are
16 November UTC. Billy approved PR 25 at 01:46:19 UTC; Vincent merged it at
01:51:04 as `a19fab34e39420811e73f91fcfbb82ee598bd74a`.
[Pricing build 4](https://ci.yebilly.me/job/secure-delivery/job/pricing/4/)
selected that full source/configuration commit. It began 02:00:09.554 UTC,
took 198.101 seconds and finished FAILURE. Twelve control tests, three app
tests, source/dependency gates and both image gates passed. The published image was:
```text
git.yebilly.me/ssw590-group1/pricing@sha256:63e2e3d49a5119b1064868b0b15b39a1719a60a632ff0ecdc3f676fcdc55de3b
```
The noninteractive SSH correction worked. Initial staging deployment ran
02:01:48.628–02:02:58.341 UTC (69.713 seconds) and passed all HTTPS health,
version, source-SHA and quantity=3 total=30 assertions. Its recap was
`ok=10 changed=4 unreachable=0 failed=0`.
The unchanged rerun ran 02:03:01.314–02:03:25.201 UTC (23.887 seconds).
Directory/template checks were unchanged, but Compose stopped because the
existing container was unhealthy: `ok=4 changed=0 unreachable=0 failed=1`.
This is **not** a passed idempotence gate. Jenkins skipped production approval
and deployment. All reports are archived in build 4 and copied to ignored
`build/evidence/assignment8-execution/jenkins-4/`. These records are not
known-good rollback selections in `delivery/releases/`.
## Diagnosis
Docker reported `Health check exceeded timeout (3s)`. Its recorded probe
durations were near three seconds, including successful probes. The staging
container later recovered without a restart; an HTTPS health request returned
`{"status":"ok","version":"v1"}`. Gunicorn remained running. The observed
container had no OOM kill, about 48.56 MiB usage against 64 MiB, and memory-limit
events without OOM events. CPU quota is 0.25. This supports a probe deadline
problem under these constraints; it does not establish that every later health
failure has that cause.
## Bounded diagnostic of the correction
At 02:06:37–02:08:24 UTC a temporary container ran the **same reviewed image**
with the same UID, read-only filesystem, capability restrictions, 64/96 MiB
RAM/RAM+swap, 0.25 CPU and 64 PID cap. It had no Docker network, published port,
proxy alias, deployment directory or app data volume. Only Docker's overall
health timeout was overridden to ten seconds. The HTTP request timeout remained
two seconds. Existing staging and shared services were unchanged.
Eight consecutive probes passed, taking 5.660, 3.183, 3.109, 2.905, 2.999,
3.183, 3.698 and 2.817 seconds. The final state was healthy; memory events
showed no limit hit or OOM. CPU throttling was observed. The temporary container
was removed by its exact newly created ID in a finally block. The
[exact diagnostic script](health-timeout-trial-20261115.py) and
[raw JSON](health-timeout-trial-20261115.json) preserve the experiment.
The Dockerfile correction changes only the overall health-check timeout from
three to ten seconds. It keeps the endpoint, request timeout, retry count,
cadence, startup period and all resource/security limits. It still needs review
and a successful assessed release; this diagnostic did not deploy production.
## v1 and v2 review sequence
The branch also prepares the required v2 source/test change: VERSION=v2,
UNIT_PRICE=12, quantity 3 total=36. Three local functional tests and twelve
control tests passed. The Windows functional environment used Flask 3.1.3 and
Werkzeug 3.1.8; deployment remains locked to Werkzeug 3.1.9 and must pass the
real Jenkins gates. Docker Desktop was not running; the remote runners remain
independent of it.
Keep two commits: first the health fix with v1 source, then the v2 app/test
change. Review both in one PR and merge with a merge commit, preserving their
SHAs. Run v1 with the first reviewed commit and v2 with the second; each still
requires staging/idempotence and real human production approval. Save and
review the actual successful release records before either recovery exercise.
+202
View File
@@ -0,0 +1,202 @@
{
"releases": [
{
"version": "v1",
"build": 5,
"url": "https://ci.yebilly.me/job/secure-delivery/job/pricing/5/",
"result": "SUCCESS",
"source": "34f26e6948b7001ede8ca19f23b67a02082e6a9a",
"started": "2026-11-16T03:00:10.966000+00:00",
"completed": "2026-11-16T03:05:08.180000+00:00",
"total_seconds": 297.214,
"approval": {
"Approver": "vsun1",
"Decision": "approved",
"UTC": "2026-11-16T03:04:01Z"
},
"deployments": {
"staging-deploy": {
"started": "2026-11-16T03:01:27.245015+00:00",
"completed": "2026-11-16T03:02:26.405414+00:00",
"elapsed_seconds": 59.16,
"operation": "deploy",
"ansible_exit_code": 0,
"recaps": [
{
"host": "startup",
"ok": 10,
"changed": 3,
"unreachable": 0,
"failed": 0
}
],
"result": "passed"
},
"staging-rerun": {
"started": "2026-11-16T03:02:29.440969+00:00",
"completed": "2026-11-16T03:03:10.939985+00:00",
"elapsed_seconds": 41.499,
"operation": "rerun",
"ansible_exit_code": 0,
"recaps": [
{
"host": "startup",
"ok": 10,
"changed": 0,
"unreachable": 0,
"failed": 0
}
],
"result": "passed"
},
"production-deploy": {
"started": "2026-11-16T03:04:05.207821+00:00",
"completed": "2026-11-16T03:05:05.610689+00:00",
"elapsed_seconds": 60.403,
"operation": "deploy",
"ansible_exit_code": 0,
"recaps": [
{
"host": "startup",
"ok": 10,
"changed": 4,
"unreachable": 0,
"failed": 0
}
],
"result": "passed"
}
},
"scans": {
"image-gate": {
"analyzed_targets": 2,
"high_critical": 0,
"report_sha256": "55ca73c4b493fa7a612671e02e6cf097c0b3fc011895712189704c8721b9028e"
},
"published-image-gate": {
"analyzed_targets": 2,
"high_critical": 0,
"report_sha256": "f375643ae8f6888e9f5ab582342c4d11bee8563936c86a9de08e7b7b5cd52ef8"
},
"dependencies": {
"packages": 9,
"advisories": 0
},
"source_secrets": {
"findings": 0
}
},
"unit_tests": {
"started": "2026-11-16T03:00:34.908112+00:00",
"completed": "2026-11-16T03:00:35.815417+00:00",
"exit_code": 0,
"result": "passed"
},
"release_image": "git.yebilly.me/ssw590-group1/pricing@sha256:59c880b2704f91668618d9a2ff0bc8fbab0af4239ceb916de261863890ef88d8",
"configuration_commit": "34f26e6948b7001ede8ca19f23b67a02082e6a9a",
"records": [
"delivery/releases/v1-staging.json",
"delivery/releases/v1-production.json"
]
},
{
"version": "v2",
"build": 6,
"url": "https://ci.yebilly.me/job/secure-delivery/job/pricing/6/",
"result": "SUCCESS",
"source": "6bddbfba5a36e0e397537678ffb197e101fb0670",
"started": "2026-11-16T03:05:33.456000+00:00",
"completed": "2026-11-16T03:12:29.163000+00:00",
"total_seconds": 415.707,
"approval": {
"Approver": "vsun1",
"Decision": "approved",
"UTC": "2026-11-16T03:11:18Z"
},
"deployments": {
"staging-deploy": {
"started": "2026-11-16T03:06:46.416545+00:00",
"completed": "2026-11-16T03:07:46.522813+00:00",
"elapsed_seconds": 60.106,
"operation": "deploy",
"ansible_exit_code": 0,
"recaps": [
{
"host": "startup",
"ok": 10,
"changed": 3,
"unreachable": 0,
"failed": 0
}
],
"result": "passed"
},
"staging-rerun": {
"started": "2026-11-16T03:07:49.044973+00:00",
"completed": "2026-11-16T03:08:34.532184+00:00",
"elapsed_seconds": 45.487,
"operation": "rerun",
"ansible_exit_code": 0,
"recaps": [
{
"host": "startup",
"ok": 10,
"changed": 0,
"unreachable": 0,
"failed": 0
}
],
"result": "passed"
},
"production-deploy": {
"started": "2026-11-16T03:11:21.802336+00:00",
"completed": "2026-11-16T03:12:28.036700+00:00",
"elapsed_seconds": 66.234,
"operation": "deploy",
"ansible_exit_code": 0,
"recaps": [
{
"host": "startup",
"ok": 10,
"changed": 3,
"unreachable": 0,
"failed": 0
}
],
"result": "passed"
}
},
"scans": {
"image-gate": {
"analyzed_targets": 2,
"high_critical": 0,
"report_sha256": "89d8912330a8fdfb0e5e8ccd1e41f971415c611ba80ee2dd6d484401ec2f6a09"
},
"published-image-gate": {
"analyzed_targets": 2,
"high_critical": 0,
"report_sha256": "32562513adffdd78782417083b51e56fd29f758a3e050faeda147dee822bc339"
},
"dependencies": {
"packages": 9,
"advisories": 0
},
"source_secrets": {
"findings": 0
}
},
"unit_tests": {
"started": "2026-11-16T03:05:54.830225+00:00",
"completed": "2026-11-16T03:05:55.609726+00:00",
"exit_code": 0,
"result": "passed"
},
"release_image": "git.yebilly.me/ssw590-group1/pricing@sha256:efe8658a0adf0854038d58199652030cbd0ef70047a1c6ebc7b09906cf1ec88b",
"configuration_commit": "6bddbfba5a36e0e397537678ffb197e101fb0670",
"records": [
"delivery/releases/v2-staging.json",
"delivery/releases/v2-production.json"
]
}
]
}
+85
View File
@@ -0,0 +1,85 @@
# Reviewed v1/v2 releases and production monitoring
Client date: 15 November 2026 Eastern; all times below are 16 November UTC.
Billy approved PR 26 at 02:56:00; Vincent merged it at 02:57:42 as
`231d11528a425114a8d3570afba56943c4d57d96`, preserving both source commits.
The merge-triggered manual workflow 15 passed in 2m7s before delivery began.
| Evidence | v1 | v2 |
|---|---|---|
| Source and configuration | `34f26e6948b7001ede8ca19f23b67a02082e6a9a` | `6bddbfba5a36e0e397537678ffb197e101fb0670` |
| Jenkins | [Build 5 SUCCESS](https://ci.yebilly.me/job/secure-delivery/job/pricing/5/) | [Build 6 SUCCESS](https://ci.yebilly.me/job/secure-delivery/job/pricing/6/) |
| Full run, including human wait | 03:00:10.966–03:05:08.180; 297.214 s | 03:05:33.456–03:12:29.163; 415.707 s |
| Initial staging | 59.160 s; ok=10, changed=3, failed=0 | 60.106 s; ok=10, changed=3, failed=0 |
| Unchanged staging rerun | 41.499 s; ok=10, changed=0, failed=0 | 45.487 s; ok=10, changed=0, failed=0 |
| Actual human approval | `vsun1`, 03:04:01 | `vsun1`, 03:11:18 |
| Production deployment | 03:04:05.208–03:05:05.611; 60.403 s | 03:11:21.802–03:12:28.037; 66.234 s |
| Verified quantity 3 total | USD 30 in both environments | USD 36 in both environments |
Both runs passed twelve control tests and three Flask tests, clean-source
scanning, all nine locked dependency audits (zero advisories), and pre-push and
registry-digest image gates (two analyzed targets, zero HIGH/CRITICAL findings).
No exception was added. Each source-SHA image was built once, pushed, pulled
and promoted by the same exact digest across staging and production.
Repository: `git.yebilly.me/ssw590-group1/pricing`
```text
v1 sha256:59c880b2704f91668618d9a2ff0bc8fbab0af4239ceb916de261863890ef88d8
v2 sha256:efe8658a0adf0854038d58199652030cbd0ef70047a1c6ebc7b09906cf1ec88b
```
The four selectors in `delivery/releases/` are copied unchanged from these
successful Jenkins builds. They include the real source/configuration SHAs,
digest, environment, expected version/total, build URL and creation time.
They pass `release.py verify` and need review/commit before recovery. Earlier
failed-attempt records were not substituted. Full reports and actual approval
records remain archived in Jenkins; exact local copies are retained in ignored
`build/evidence/assignment8-execution/jenkins-{5,6}/`.
[Machine-readable summary](releases-20261115.json) includes recaps, timestamps,
scan counts and full image-report SHA-256 hashes.
## Production monitoring, applied only after healthy v1
At 03:08:11 the previously reviewed production `/health` target and panel 8
were applied. The guarded helper required healthy production, compared earlier
probes/panels, validated the candidate with installed promtool, saved protected
backups and preserved both bind-mounted file inodes. Prometheus reloaded via
SIGHUP; Grafana provisioned the changed file. No container, volume, retention,
allowlist, credential or existing alert rule was replaced. The first dry-run
cleanup needed root inside Prometheus because docker cp created a root-owned
temporary file; that was corrected before active application.
[Applied metadata](monitoring-applied-20261115.json) records hashes and backup
`/root/ssw590-delivery-bootstrap/monitoring-20261116/`.
[Actual samples and targets](monitoring-runtime-20261115.json), observed at
03:14:11, showed production, Gitea and Jenkins probe_success=1, all six scrape
targets up and successful reload=1. The dashboard source retained its previous
seven panels; the actual Grafana UI also displayed the new pricing panel and
its data. A legacy SQL dashboard lookup returned no row, so it was not used
as proof of provisioning.
Prometheus supports [runtime SIGHUP reload](https://prometheus.io/docs/prometheus/latest/configuration/configuration/).
Grafana's [file provisioning](https://grafana.com/docs/grafana/latest/administration/provisioning/)
detects dashboard changes; visible runtime verification was performed separately.
## Observed availability during v2 promotion
The [post-release capture](runtime-20261115.json) at 03:28:08 verified both
environments as healthy v2 with the exact source SHA, HTTP 200 for identity,
health and total 36, and HTTP 400 for quantity 0. Both containers had zero OOM
events and no observed memory-limit events in that capture.
The production probe history contains one failed sample at **03:11:54.602**
during v2's 03:11:21.802–03:12:28.037 deployment window. Adjacent successful
samples were 03:11:24.602 and 03:12:24.602. The capture preserves exact HTTP
status and duration samples. A single failed 30-second-cadence sample does
not establish an exact 30-second outage or zero downtime between other samples.
The interval is shorter than the existing one-minute alert duration; no alert
firing or notification is claimed without separate evidence. The single-host
Compose replacement is not blue/green or highly available deployment.
The Grafana screenshot is retained in the manual's image folder. Production
rollback and deliberate staging failure/recovery remain **unexecuted** pending
review of the successful records and preserved staging-only configuration fault.
See [the recovery exercise instructions](../exercises/README.md).
+604
View File
@@ -0,0 +1,604 @@
{
"observed_at": "2026-11-16T03:28:08.004273+00:00",
"endpoints": {
"staging": [
{
"path": "/",
"http_status": 200,
"body": {
"commit": "6bddbfba5a36e0e397537678ffb197e101fb0670",
"service": "Startup Pricing",
"version": "v2"
}
},
{
"path": "/health",
"http_status": 200,
"body": {
"status": "ok",
"version": "v2"
}
},
{
"path": "/price?quantity=3",
"http_status": 200,
"body": {
"currency": "USD",
"quantity": 3,
"total": 36
}
},
{
"path": "/price?quantity=0",
"http_status": 400,
"body": {
"error": "quantity must be between 1 and 1000"
}
}
],
"production": [
{
"path": "/",
"http_status": 200,
"body": {
"commit": "6bddbfba5a36e0e397537678ffb197e101fb0670",
"service": "Startup Pricing",
"version": "v2"
}
},
{
"path": "/health",
"http_status": 200,
"body": {
"status": "ok",
"version": "v2"
}
},
{
"path": "/price?quantity=3",
"http_status": 200,
"body": {
"currency": "USD",
"quantity": 3,
"total": 36
}
},
{
"path": "/price?quantity=0",
"http_status": 400,
"body": {
"error": "quantity must be between 1 and 1000"
}
}
]
},
"containers": {
"staging": {
"running": true,
"oom_killed": false,
"health": "healthy",
"memory_events": "low 0\nhigh 0\nmax 0\noom 0\noom_kill 0\noom_group_kill 0\n"
},
"production": {
"running": true,
"oom_killed": false,
"health": "healthy",
"memory_events": "low 0\nhigh 0\nmax 0\noom 0\noom_kill 0\noom_group_kill 0\n"
}
},
"monitoring_samples": {
"probe_success": [
{
"metric": {
"__name__": "probe_success",
"instance": "https://app.yebilly.me/health",
"job": "https"
},
"values": [
[
1794798504.602,
"1"
],
[
1794798534.602,
"1"
],
[
1794798564.602,
"1"
],
[
1794798594.602,
"1"
],
[
1794798624.602,
"1"
],
[
1794798654.602,
"1"
],
[
1794798684.602,
"1"
],
[
1794798714.602,
"0"
],
[
1794798744.602,
"1"
],
[
1794798774.602,
"1"
],
[
1794798804.602,
"1"
],
[
1794798834.602,
"1"
],
[
1794798864.602,
"1"
],
[
1794798894.602,
"1"
],
[
1794798924.602,
"1"
],
[
1794798954.602,
"1"
],
[
1794798984.602,
"1"
],
[
1794799014.602,
"1"
],
[
1794799044.602,
"1"
],
[
1794799074.602,
"1"
],
[
1794799104.602,
"1"
],
[
1794799134.602,
"1"
],
[
1794799164.602,
"1"
],
[
1794799194.602,
"1"
],
[
1794799224.602,
"1"
],
[
1794799254.602,
"1"
],
[
1794799284.602,
"1"
],
[
1794799314.602,
"1"
],
[
1794799344.602,
"1"
],
[
1794799374.602,
"1"
],
[
1794799404.602,
"1"
],
[
1794799434.602,
"1"
],
[
1794799464.602,
"1"
],
[
1794799494.602,
"1"
],
[
1794799524.602,
"1"
],
[
1794799554.602,
"1"
],
[
1794799584.602,
"1"
],
[
1794799614.602,
"1"
],
[
1794799644.602,
"1"
],
[
1794799674.602,
"1"
]
]
}
],
"probe_http_status_code": [
{
"metric": {
"__name__": "probe_http_status_code",
"instance": "https://app.yebilly.me/health",
"job": "https"
},
"values": [
[
1794798504.602,
"200"
],
[
1794798534.602,
"200"
],
[
1794798564.602,
"200"
],
[
1794798594.602,
"200"
],
[
1794798624.602,
"200"
],
[
1794798654.602,
"200"
],
[
1794798684.602,
"200"
],
[
1794798714.602,
"502"
],
[
1794798744.602,
"200"
],
[
1794798774.602,
"200"
],
[
1794798804.602,
"200"
],
[
1794798834.602,
"200"
],
[
1794798864.602,
"200"
],
[
1794798894.602,
"200"
],
[
1794798924.602,
"200"
],
[
1794798954.602,
"200"
],
[
1794798984.602,
"200"
],
[
1794799014.602,
"200"
],
[
1794799044.602,
"200"
],
[
1794799074.602,
"200"
],
[
1794799104.602,
"200"
],
[
1794799134.602,
"200"
],
[
1794799164.602,
"200"
],
[
1794799194.602,
"200"
],
[
1794799224.602,
"200"
],
[
1794799254.602,
"200"
],
[
1794799284.602,
"200"
],
[
1794799314.602,
"200"
],
[
1794799344.602,
"200"
],
[
1794799374.602,
"200"
],
[
1794799404.602,
"200"
],
[
1794799434.602,
"200"
],
[
1794799464.602,
"200"
],
[
1794799494.602,
"200"
],
[
1794799524.602,
"200"
],
[
1794799554.602,
"200"
],
[
1794799584.602,
"200"
],
[
1794799614.602,
"200"
],
[
1794799644.602,
"200"
],
[
1794799674.602,
"200"
]
]
}
],
"probe_duration_seconds": [
{
"metric": {
"__name__": "probe_duration_seconds",
"instance": "https://app.yebilly.me/health",
"job": "https"
},
"values": [
[
1794798504.602,
"0.057399797"
],
[
1794798534.602,
"0.028300941"
],
[
1794798564.602,
"0.023132207"
],
[
1794798594.602,
"0.021246711"
],
[
1794798624.602,
"0.023551593"
],
[
1794798654.602,
"0.023607454"
],
[
1794798684.602,
"0.182590187"
],
[
1794798714.602,
"0.080492206"
],
[
1794798744.602,
"0.048286408"
],
[
1794798774.602,
"0.021541103"
],
[
1794798804.602,
"0.082225976"
],
[
1794798834.602,
"0.026266413"
],
[
1794798864.602,
"0.021229488"
],
[
1794798894.602,
"0.026039405"
],
[
1794798924.602,
"0.024995092"
],
[
1794798954.602,
"0.026780972"
],
[
1794798984.602,
"0.022616423"
],
[
1794799014.602,
"0.079699801"
],
[
1794799044.602,
"0.023901787"
],
[
1794799074.602,
"0.029992619"
],
[
1794799104.602,
"0.022638427"
],
[
1794799134.602,
"0.082084913"
],
[
1794799164.602,
"0.03257138"
],
[
1794799194.602,
"0.028129282"
],
[
1794799224.602,
"0.02010407"
],
[
1794799254.602,
"0.081311747"
],
[
1794799284.602,
"0.027378471"
],
[
1794799314.602,
"0.020048075"
],
[
1794799344.602,
"0.018652785"
],
[
1794799374.602,
"0.019703541"
],
[
1794799404.602,
"0.020952708"
],
[
1794799434.602,
"0.020200855"
],
[
1794799464.602,
"0.081365277"
],
[
1794799494.602,
"0.030027777"
],
[
1794799524.602,
"0.020230579"
],
[
1794799554.602,
"0.028499939"
],
[
1794799584.602,
"0.024388546"
],
[
1794799614.602,
"0.02259808"
],
[
1794799644.602,
"0.030377942"
],
[
1794799674.602,
"0.080982268"
]
]
}
]
}
}
+64
View File
@@ -0,0 +1,64 @@
# Reviewed recovery exercises
V1 and v2 have now completed Jenkins releases 5 and 6 with real human approvals.
The four exact successful records in `../releases/` need review/commit before
recovery. Do not use the earlier failed attempts' records.
The patch here is a deliberate **staging-only** configuration fault: Gunicorn
binds to 8001 while the unchanged image healthcheck probes 8000. It changes no
image, host port, credential, shared service, production command or stored data.
The reviewed Jenkins `staging-failure` mode requires a staging record and uses
that record's existing v2 digest; it does not publish/rebuild an image.
## Commit and review sequence
1. Commit the actual release records, evidence, monitoring helper, manual and
this patch while the active template remains correct.
2. Apply this patch and commit the one changed template as
`Exercise staging-only Gunicorn bind mismatch`.
3. Immediately revert that second commit, creating a third commit. The final
branch/main template must be good; the bad configuration survives only as
a reviewed historical commit selected explicitly by SHA for the exercise.
4. Billy reviews all three commits, including the intermediate configuration
fault and its restoration. Use a merge commit, preserving history.
After the first commit, the two configuration commits can be made with:
```powershell
git apply delivery/exercises/staging-bind-mismatch.patch
git add delivery/ansible/templates/compose.yaml.j2
git commit -m "Exercise staging-only Gunicorn bind mismatch"
git revert --no-edit HEAD
```
## Execution after review/merge
First record the planned healthy production rollback decision and start the
HTTPS observer. Use `MODE=rollback-production` and
`RELEASE_RECORD=delivery/releases/v1-production.json`. The approved operation
must restore v1's exact image/configuration, source SHA and total 30. This is
an exercise on healthy v2, not a claimed production incident. A real human
must approve the Jenkins production input.
Then start a separate staging observer and select:
```text
MODE=staging-failure
RELEASE_RECORD=delivery/releases/v2-staging.json
STAGING_FAILURE_CONFIG=<full SHA of the reviewed bind-mismatch commit>
```
The SHA must be the actual preserved intermediate commit, not the final
revert or an invented placeholder. Leave SOURCE_COMMIT blank so the job uses
reviewed current main for its control code. Compose wait must block within
its 90-second bound and stop before production. Preserve that failure.
Recover with `MODE=recover-staging` and the same good v2 staging record, leaving
STAGING_FAILURE_CONFIG blank. It must restore the recorded good configuration,
verify source/version/total 36, and pass the unchanged rerun with changed=0.
Save decision/start/completion times, recaps, observer samples and monitoring
correlation. Samples cannot establish zero interruption between requests.
Both exercises remain unexecuted. No failure configuration is deployed merely
by merging this PR: its net template is unchanged and the bad SHA is selected
only in the explicit staging exercise.
@@ -0,0 +1,13 @@
diff --git a/delivery/ansible/templates/compose.yaml.j2 b/delivery/ansible/templates/compose.yaml.j2
--- a/delivery/ansible/templates/compose.yaml.j2
+++ b/delivery/ansible/templates/compose.yaml.j2
@@ -1,6 +1,9 @@
services:
app:
image: "{{ release_image }}"
+{% if target_env == 'staging' %}
+ command: ["gunicorn", "--bind", "0.0.0.0:8001", "--workers", "1", "--worker-tmp-dir", "/tmp", "app:app"]
+{% endif %}
restart: unless-stopped
read_only: true
tmpfs:
+12
View File
@@ -0,0 +1,12 @@
{
"release_image": "git.yebilly.me/ssw590-group1/pricing@sha256:59c880b2704f91668618d9a2ff0bc8fbab0af4239ceb916de261863890ef88d8",
"expected_commit": "34f26e6948b7001ede8ca19f23b67a02082e6a9a",
"configuration_commit": "34f26e6948b7001ede8ca19f23b67a02082e6a9a",
"expected_version": "v1",
"expected_total": 30,
"proxy_network": "gitea_web",
"build_url": "https://ci.yebilly.me/job/secure-delivery/job/pricing/5/",
"created_at": "2026-11-16T03:01:23.246375+00:00",
"target_env": "production",
"public_url": "https://app.yebilly.me"
}
+12
View File
@@ -0,0 +1,12 @@
{
"release_image": "git.yebilly.me/ssw590-group1/pricing@sha256:59c880b2704f91668618d9a2ff0bc8fbab0af4239ceb916de261863890ef88d8",
"expected_commit": "34f26e6948b7001ede8ca19f23b67a02082e6a9a",
"configuration_commit": "34f26e6948b7001ede8ca19f23b67a02082e6a9a",
"expected_version": "v1",
"expected_total": 30,
"proxy_network": "gitea_web",
"build_url": "https://ci.yebilly.me/job/secure-delivery/job/pricing/5/",
"created_at": "2026-11-16T03:01:23.246375+00:00",
"target_env": "staging",
"public_url": "https://staging.yebilly.me"
}
+12
View File
@@ -0,0 +1,12 @@
{
"release_image": "git.yebilly.me/ssw590-group1/pricing@sha256:efe8658a0adf0854038d58199652030cbd0ef70047a1c6ebc7b09906cf1ec88b",
"expected_commit": "6bddbfba5a36e0e397537678ffb197e101fb0670",
"configuration_commit": "6bddbfba5a36e0e397537678ffb197e101fb0670",
"expected_version": "v2",
"expected_total": 36,
"proxy_network": "gitea_web",
"build_url": "https://ci.yebilly.me/job/secure-delivery/job/pricing/6/",
"created_at": "2026-11-16T03:06:40.913173+00:00",
"target_env": "production",
"public_url": "https://app.yebilly.me"
}
+12
View File
@@ -0,0 +1,12 @@
{
"release_image": "git.yebilly.me/ssw590-group1/pricing@sha256:efe8658a0adf0854038d58199652030cbd0ef70047a1c6ebc7b09906cf1ec88b",
"expected_commit": "6bddbfba5a36e0e397537678ffb197e101fb0670",
"configuration_commit": "6bddbfba5a36e0e397537678ffb197e101fb0670",
"expected_version": "v2",
"expected_total": 36,
"proxy_network": "gitea_web",
"build_url": "https://ci.yebilly.me/job/secure-delivery/job/pricing/6/",
"created_at": "2026-11-16T03:06:40.913173+00:00",
"target_env": "staging",
"public_url": "https://staging.yebilly.me"
}
+6
View File
@@ -0,0 +1,6 @@
rules:
- id: ssw590-synthetic-secret
category: course-test
title: SSW590 synthetic blocked-gate fixture
severity: HIGH
regex: 'SSW590_SYNTHETIC_SECRET_[A-Z0-9]{16}'
+27
View File
@@ -6,3 +6,30 @@ git.yebilly.me {
colors.yebilly.me {
reverse_proxy color-buttons-app:3000
}
# Jenkins: Stevens campus network (155.246.0.0/16) plus team and approved grader
# IPs from CI_TEAM_IPS in the untracked .env. Everyone else gets 403 before login.
# The Stevens VPN is split-tunnel, so it does not give visitors a 155.246.x.x address.
# 172.30.90.10 is Blackbox Exporter on the private probe network (monitoring/compose.yaml).
ci.yebilly.me {
@denied not remote_ip 155.246.0.0/16 172.30.90.10/32 {$CI_TEAM_IPS}
respond @denied 403
reverse_proxy jenkins:8080
}
# Grafana (Assignment 7): same allowlist as Jenkins, then Grafana's own login.
metrics.yebilly.me {
@denied not remote_ip 155.246.0.0/16 {$CI_TEAM_IPS}
respond @denied 403
reverse_proxy grafana:3000
}
# Assignment 8: apply after both DNS names resolve to The-Ocean. Containers
# publish no host ports; the existing proxy reaches their private aliases.
staging.yebilly.me {
reverse_proxy pricing-staging:8000
}
app.yebilly.me {
reverse_proxy pricing-production:8000
}
+36
View File
@@ -149,3 +149,39 @@ port; Caddy reaches it on the private `gitea_web` network.
```
Remove it with `docker rm -f color-buttons-app`, delete the block, and reload.
## Jenkins CI (Assignment 6 / Instructor Manual Chapter 4)
`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:
browsers reach it through Caddy at `https://ci.yebilly.me/login`, and the Gitea
webhook reaches `http://jenkins:8080/gitea-webhook/post` on the private network.
1. DNS: `A` record `ci` -> droplet IPv4.
2. On the droplet, put team source IPs in the untracked `~/gitea/.env`
(space separated CIDRs; Stevens 155.246.0.0/16 is already in the Caddyfile):
```bash
echo 'CI_TEAM_IPS=203.0.113.7/32' > ~/gitea/.env # example address
```
3. Copy `docker-compose.yml`, `Caddyfile` (with `cat >`, see above) and the
`jenkins/` folder, then:
```bash
cd ~/gitea
docker compose build jenkins
docker compose up -d jenkins
docker compose up -d --force-recreate gitea caddy # webhook allowlist + CI_TEAM_IPS + alias
```
4. Unlock Jenkins with `docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword`
(read it yourself; never paste it anywhere), install **no** suggested
plugins, create one named administrator per teammate, and set the Jenkins
URL to `https://ci.yebilly.me/`.
Operate:
```bash
docker compose restart jenkins # settings and jobs live in the jenkins-home volume
docker compose logs --tail 100 jenkins # failed build or webhook: check here, then
# Gitea repo Settings -> Webhooks -> Recent Deliveries
docker stats --no-stream; free -m # memory pressure on the 512 MB droplet
```
+40 -1
View File
@@ -12,6 +12,7 @@ services:
- GITEA__server__ROOT_URL=https://git.yebilly.me/
- GITEA__server__HTTP_PORT=3000
- GITEA__server__DISABLE_SSH=true # Git over HTTPS only
- GITEA__webhook__ALLOWED_HOST_LIST=jenkins # only private webhook target allowed
volumes:
- gitea-data:/data
networks: [web]
@@ -27,13 +28,51 @@ services:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy-data:/data # certificates + ACME account
- caddy-config:/config
networks: [web]
environment:
- CI_TEAM_IPS=${CI_TEAM_IPS:-} # team source IPs for ci.yebilly.me, kept in untracked .env
networks:
web:
# Jenkins resolves git.yebilly.me to Caddy here, so checkout and status
# calls stay on the droplet instead of hairpinning through the public IP.
aliases: [git.yebilly.me]
probe:
# Blackbox Exporter (monitoring/compose.yaml) probes both sites through Caddy here.
aliases: [git.yebilly.me, ci.yebilly.me]
depends_on: [gitea]
# Jenkins LTS controller (Assignment 6). Builds run on its single executor.
# Bounded so Gitea keeps memory on the 512 MB droplet.
jenkins:
build: ./jenkins
image: ssw590-jenkins:2.580.1
restart: unless-stopped
environment:
# The capacity test's 128 MiB heap ran builds, but the web UI hit "OutOfMemoryError:
# Java heap space" once the update-center catalog loaded (2026-10-22), so the
# persistent service gets twice the test bounds on the 1 GiB droplet.
- JAVA_OPTS=-Xms64m -Xmx256m -XX:+UseSerialGC -Djava.awt.headless=true
volumes:
- jenkins-home:/var/jenkins_home
networks: [web]
mem_limit: 512m
memswap_limit: 768m
cpus: 0.75
pids_limit: 256
# ponytail: no ports: on purpose -- Caddy and the Gitea webhook reach jenkins:8080 privately;
# agent port 50000 is never published.
volumes:
gitea-data:
caddy-data:
caddy-config:
jenkins-home:
networks:
web:
# Fixed subnet so Blackbox Exporter can have a fixed address (172.30.90.10), the only
# private address the ci.yebilly.me allowlist admits. The web subnet stays denied:
# Docker's proxy presents IPv6 and hairpin visitors as its gateway, 172.18.0.1.
probe:
ipam:
config:
- subnet: 172.30.90.0/28
+18
View File
@@ -0,0 +1,18 @@
# Official Jenkins LTS image plus what the controller executor needs to run the
# pipeline: python3 for the tests and the pinned plugin lockfile.
FROM jenkins/jenkins:2.580.1-lts-jdk21@sha256:a660310e39ade10631f774bacd5219de767dfd08947ea5c32a739b5e5bb382c1
USER root
RUN apt-get update \
&& apt-get install -y --no-install-recommends python3 \
&& rm -rf /var/lib/apt/lists/*
USER jenkins
# ponytail: curl + sha256sum instead of jenkins-plugin-cli, which needs >128 MiB heap
# just to parse the update-center JSON on a 512 MB droplet.
COPY plugins.txt /tmp/plugins.txt
RUN mkdir -p /usr/share/jenkins/ref/plugins && cd /usr/share/jenkins/ref/plugins \
&& tr -d '\r' < /tmp/plugins.txt | grep -Ev '^(#|$)' | while IFS=: read -r name ver sha; do \
curl -fsSL -o "$name.jpi" "https://updates.jenkins.io/download/plugins/$name/$ver/$name.hpi" \
&& echo "$sha $name.jpi" | sha256sum -c --quiet || exit 1; \
done
+71
View File
@@ -0,0 +1,71 @@
# Lockfile copied from the team's prepared plugin bundle (Vincent Sun, 2026-10-21): roots
# workflow-aggregator:608.v67378e9d3db_1 and gitea:286.v0740a_413c1eb_ plus every resolved
# dependency, the same set exercised by ci/jenkins-capacity. Format name:version:sha256.
# Regenerate the whole file from a new bundle manifest rather than hand-editing one line.
# Added 2026-10-22: matrix-auth:3.3 for named Jenkins roles (its only dependency, ionicons-api,
# was already in the bundle at the required version).
# Added 2026-10-23: pipeline-graph-view (stage view of each run) with its new dependencies
# jackson3-api and snakeyaml-engine-api; other required versions were already satisfied.
apache-httpcomponents-client-4-api:4.5.14-269.vfa_2321039a_83:cea2f61cc72890b962fd4b767c31778c6cb30015b4a8758b4c26b62e51ca9533
asm-api:9.11.1-226.vff833a_e4c58e:ba315fe727be0311cd5115205a09a2abb550b73287cc4ee07af5f7ef6502f1f8
authentication-tokens:1.144.v5ff4a_5ec5c33:8069074af688b102703410045a11394fb8d2f52c2cc2d7abd3067e3adff5fc24
bouncycastle-api:2.30.1.86.2-310.v4655f6742752:57cc5cf1585f9a8f29c5a1e3985f07dace5d5359545d788e72ecaa3636515a58
branch-api:2.1303.v9f3b_95dc329d:6ecfc3d335cec791008a2d06ca933c6ccc97db1c14a4aee5030affebb97482e0
caffeine-api:3.3.1-214.v18eb_56b_34920:768ed05774f12d85bf8ecff5d509f037810d1359de8b4fb1385624f6f547c90b
cloudbees-folder:6.1106.v3a_d9a_6d2465e:4ccfcfe145a1b36aef61f19187e8aa74eb3c90fdb9c9bfce865e09aa13c8a70a
commons-lang3-api:3.21.0-122.v6a_ea_4fd34049:4d6194f8d3b3f2b69264f0403fe5a51846236a41f4e363f6aae45f82f7761657
commons-text-api:1.15.0-218.va_61573470393:ae2abdf957694f4aa39b9ba0b539edabc384f3da277551879e34ffb22fb13764
credentials-binding:728.v902a_273b_8947:bd7d1a187e35c8e2b6619cd50f2f8c5d28aafc4ef8fd9de572fb2cfa464f466d
credentials:1514.vb_01eb_014e7d4:b6e0a05d107fe492bb57baea75fb585fb65dd90c2456a6432b90b87226997457
display-url-api:2.217.va_6b_de84cc74b_:07eeaae738b451bade4756900b48561c6c493a42c7ba07a45b22a2dce71ac0ca
durable-task:686.v80ff80875b_82:1f5bb92ee5784ee01a4e4e0307e806fa1e260db8aceba56fe8d277e939278dfa
git-client:6.6.1:69ab80e3bd51e2e4e676a18722c02c7b163eb11a758b52ecf179d58e1ca1738f
git:5.11.0:bf4639abb65e6ca210bd0d7cb9b6570e93717894bdcd008b2e7e5a916dd818f6
gitea:286.v0740a_413c1eb_:242e091be9cbbd289546c65a85cf948670de2b3020db573e162926a97c3b5837
gson-api:2.14.0-201.v8eefe5515533:6940cd0f795f72371fd5644d885db9ec0a2077985ac55de85d19ab3b1fac2bb7
handy-uri-templates-2-api:2.1.8-38.vcea_5d521d5f3:2e5881410b0bca648fb78c890bfd8b83c46e4ff4c778235cb58e28b45d89b10e
instance-identity:203.v15e81a_1b_7a_38:df2b3205a6177248f12b294650a60405f65ba2cd503ca9599b2dcb72c1de5018
ionicons-api:94.vcc3065403257:95f3504375d628d887425ccdf32d5606a230261ee42dc683f13958d8e973ac3f
jackson-annotations2-api:2.22-19.v10a_a_582ea_26e:f13d0a17af6f8c8939a6edd30952006b77dca4760b1f40e0289c363918b7d17d
jackson2-api:2.22.3-447.v6a_93ce7d2c82:ce2cfb7a5ad6e66aea9a5b6c4a5ea0622bfc5c05db5db8918581ae7f1d10ff33
jackson3-api:3.2.4-103.vf5a_b_3f4ea_cec:4397f73c11ba5085a40280555b519c9427cf8d69d63d5d60f4f623f72f953fe2
jakarta-activation-api:2.1.4-1:e62298341742f14b374045387ba641ad8a19376793c76bdafebb4a05b5099712
jakarta-mail-api:2.1.5-1:244735ea85a51332c079d235a5713e70d3810bea62332894002acc39914ce11b
jakarta-xml-bind-api:4.0.9-19.v2b_a_5b_44d9a_1c:2f59227936687ec00f7ea62b550e7a6e9c86cda3423f3567ffe66bbdf235ffb5
javax-activation-api:1.2.0-8:e96e88c52edf07ba00fb45b26cc411a7a95fa3d4491aaa1a5d36637665880560
jaxb:2.3.9-143.v5979df3304e6:38ddf4cf5db61a591044130c2f7ccb2b7aa9abebc8fcd8a6953f8da550d002ed
joda-time-api:2.15.0-208.v6b_084e7a_d9f0:427513635d122f62fcd8e52af08cc895913b9a70568e7665a3ce8fc1a4871ddf
json-api:20260814-226.v20f9685d642c:c5ac5ecfddd35c07087b3333ae05ec4167a70abae8bf0ebcb7338b6b54540889
mailer:534.v1b_36f5864073:5426a66a3f879d25fcb4baff678a28422afbabff22cd6e4f0f998fc67a3dc3fa
matrix-auth:3.3:b8f7a916f1de0872d4c16264bcf9604fdb5b2da1827764745946c7ac5f613948
mina-sshd-api-common:2.19.0-192.v2b_a_7b_2c1dc71:887ebd645e43919b6113201257821b990fc923f375382a5dada0c089e49b85bc
mina-sshd-api-core:2.19.0-192.v2b_a_7b_2c1dc71:5039ea17ea1aa9e349712ccc1e036c38ea9f20f722affc220c2c751369f32495
pipeline-build-step:601.v6d4c6d1a_9dc7:1b61a1820844f3f72f9dfcd6d7eeab66fa0fbcee5e3923b912cd1ed10fbf63c5
pipeline-graph-view:1053.v9df19e6ceed2:4a92651101fb02e0db24170211ef1b4cc14b7d3c20df51a2fa61807f75bff8ff
pipeline-groovy-lib:822.vc95f70dea_db_7:a633824da17e95fe2a9f03e8d951a771c70a729e987fc51874146723f3b6343b
pipeline-input-step:560.v56198a_642157:7c61bb745ecd1e4e5c7864dc7c8352148d9b2281bcca5a48fd3a7cca7290a135
pipeline-milestone-step:152.v6e22b_8cfc66c:cb3187809e219f01b42068f277058a818033f3cfd14da7ec59c86f028fc38386
pipeline-model-api:2.2293.v6e7193cec599:cdd72a69bf2863a1683b282febd0256d5d266111134c3803a8c4a051b6b4c133
pipeline-model-definition:2.2293.v6e7193cec599:9f4f62e0a13fefc9c5736a20ad5124af2a324357294fd8ea8d8f848b7c497f92
pipeline-model-extensions:2.2293.v6e7193cec599:00fbf0938ef13f6aedaa0900ec4cd03fcc986e34b1820bf13f761c2f29831861
pipeline-stage-step:345.va_96187909426:2eba433b28f2dfc90519e233b14264890f97b93b78e25c664d56607141fcd94b
pipeline-stage-tags-metadata:2.2293.v6e7193cec599:032f011fc50cb273b300d44fb6c2800e3dbdf0d78548b15e0f192ba7cc95d178
plain-credentials:199.v9f8e1f741799:b5e5e35cf93ad3b818a983916cbcdf3f7866699410a4df923e6a2968ecc3a448
scm-api:728.vc30dcf7a_0df5:1336472987daa2fa912210aba00e1e37b739ce03f75c973a6794d1a0f55c0326
script-security:1436.v1082791135e4:c2292e200c5796675c16d19325469aac4a5460c7ad23974952b9823f62066f6a
snakeyaml-api:2.7-152.vc672728cf536:bfa595a283634c8dd63aa8d1b039cf3d3f52e0952048058fc0b9a4826ca06508
snakeyaml-engine-api:3.2-18.v885ed7ff698f:89c14c0ac2816c1efc192dd333b4b26d97ae58d2ab1d492e8b52feca406e220e
ssh-credentials:372.va_250881b_08cd:7b4d035b05b331038f3dfa99ddfef0cabbacede8f0ad2a6ca9611fb0844108a9
structs:362.va_b_695ef4fdf9:a0a5db44f2cb082a9ec6572c088340521f033fff8c351fc7eba9ef7f07dbbf8d
variant:70.va_d9f17f859e0:12e214ea694469a4461b55881ecb4074ae5dfb04797dbc0dad390f6f4bc75aaf
woodstox-core-api:7.3.0-16.v017f30ed004c:fca0ce7cd19274833df226cd6746d71ce4025b784a81bd5b8512730f5d34a9df
workflow-aggregator:608.v67378e9d3db_1:7b94227c1afa01bb262c14919ad4a333412f1b51d947c0f21909ec2daff357dc
workflow-api:1413.v2ff1a_5e720fa_:f4adbd6b34a2a0b643a12b898110bd976350142eff6322efda21efacbccb6835
workflow-basic-steps:1098.v808b_fd7f8cf4:93449eb494658d065d097e8c54f707c98c9ce3e54da2fb98281b0a0487154eaf
workflow-cps:4395.v738456a_5da_6b_:2af278f3012f294165db715bfa608045feaf781a6c7c85b5d7ab1ee5b707f021
workflow-durable-task-step:1479.v56e587f413a_7:a0f0f1464ce3592f76d0f0079ce9fc2d4272594f995bf3d1a7ede4cd5031452e
workflow-job:1609.v8926e7962024:1f63a3dc4e9f8bfbde7b759530da4073e105a92fee3b647962d981de223ac8f5
workflow-multibranch:842.v3a_b_59b_57b_e6e:af26afd93b5d730d203d8f58d1e104712ad1a7ddcf6837886d3272b1c0057e46
workflow-scm-step:487.v41313a_96b_65d:532fc247cba83845df3c7fccaabfc3cb1f637729b145211728bcb974a3a67552
workflow-step-api:724.v538c2362b_dfb_:887491de444174228471993b0b2db958db2e7fb577857c8516c58e9618049896
workflow-support:1015.v785e5a_b_b_8b_22:914ee717ab8c1d60d0d3ea49a1af11e4ea65c1e74c0b44dc3522f9a2fe5b2a8e
+57
View File
@@ -0,0 +1,57 @@
# Manual runner migration evidence
Requested by Vincent on 14 November 2026, Eastern time. Server timestamps below
are UTC on 15 November. No commit, push, new registration or scope change occurred.
- Baseline 04:24 UTC: 1,967 MiB RAM, 860 MiB available, 338 MiB swap used;
root disk 55% used, 11 GiB available (rounded by df).
- Exported the existing compiler image, verified the transfer archive SHA-256
`faf56b61af1187b6dad0f1e27b1ec47bed282ffe52aee9c458c13a88ee02849a`,
then loaded it on The-Ocean. Image ID matches the original tested image:
`sha256:5d24657a4578977fc7709165b82fc869f09a654a58ab4a0c8defd9d2cd662d5d`.
- Stopped the idle laptop runner before copying its existing registration
directly over pinned SSH into the remote Docker volume. Identity was
validated quietly, mode 0600; no value was output or written into the repo.
Name `ssw590-vince-local`, label `latex-local`, capacity one and repository
scope remain unchanged. The laptop volume/image are retained as fallback.
- At 04:31 UTC the remote daemon declared successfully. The initial 96 MiB
daemon cap was insufficient during action setup: Docker recorded an OOM
event at 04:32:18 and restart count 1. Run 12 attempt 2 / job 13 was canceled.
Its failure log is retained; its orphan container, network and two task-only
volumes were removed after validation, preserving shared volumes.
- Raised only the daemon to 192 MiB RAM / 256 MiB RAM+swap, with GOMEMLIMIT
128 MiB and 0.25 CPU. Compiler job caps remain 512 MiB / 768 MiB, 0.5 CPU,
256 PIDs, no published ports and no automatic job Docker socket mount.
- [Run 12, attempt 3, job 14](https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/actions/runs/12/jobs/14)
succeeded on the remote runner. Source is reviewed main commit
`8beefde2a4983888effb79526e527303e60a1a82`; this reruns Assignment 7 source,
not the uncommitted Assignment 8 preparation. Setup 2m33s, checkout 9s,
compile 1m42s, PDF upload 5s, diagnostics upload 2s, completion 1s; total 4m32s.
- Diagnostics supplied by Vincent in `build/evidence/run-12/` confirm source
SHA, run 12, suffix `+build.12.8beefde`, TeX Live 2022, latexmk 4.79,
Git 2.39.5 and Node 22.23.3. The PDF is 9,059,039 bytes and its SHA-256
matches diagnostics:
`f81fd73d8fd975d8d61164948a977c4048ee93e38b656904334835f6b5c29c8b`.
Its title was visually verified as `5.1+build.12.8beefde`.
- Browser download waiting timed out and the debugger then detached. Vincent
supplied diagnostics; the exact attempt-3 PDF was retrieved using read-only
artifact metadata and gzip payload over pinned administrator SSH, without
changing server data. Original expired attempt-1 metadata was preserved.
- At 04:41 UTC during compilation: 738 MiB host RAM available, 354 MiB swap
used; sampled compiler working set 142.4 MiB, daemon 20.43 MiB. A later
idle check found no active jobs, daemon restarts 0 and no current OOM flag.
These samples do not prove concurrency capacity or uninterrupted service.
- The idle daemon restarted and declared successfully again at 04:55:52 UTC.
`unless-stopped` is configured; a complete Droplet reboot was not performed.
- Final post-migration check: all ten service/agent/builder containers running;
Gitea, Jenkins login and Grafana login returned private HTTP 200. Host RAM
available 840 MiB, swap used 358 MiB, root disk 61% used with 9.2 GiB
available after removing the verified compiler transfer archive. Both laptop
daemons were confirmed exited. Protected identities and prior evidence remain.
Raw logs, runtime checks and artifact verification are under ignored
`build/evidence/assignment8-manual-runner/`; the user-provided diagnostics and
verified CI PDF remain in `build/evidence/run-12/`. Existing service checks and
the final local manual build are recorded separately. Both active runners
now run on The-Ocean; keep manual compilation and delivery releases sequential.
The assignment's actual app releases and recovery evidence remain pending.
+78
View File
@@ -0,0 +1,78 @@
# Manual Actions runner on The-Ocean
Vincent requested this migration on 14 November 2026 after moving the Jenkins
delivery agent. This replaces the active laptop runner; it does not create
another registration or expand its repository scope. The historical runner
name `ssw590-vince-local` and label `latex-local` remain for workflow compatibility.
The container is `ssw590-manual-runner`, under `/opt/ssw590-manual-runner`.
## Configuration and ownership
- Gitea runner 2.3.0, pinned to the same official image digest as the laptop.
- Same tested compiler image `ssw590-manual-ci:20261007`, ID
`sha256:5d24657a4578977fc7709165b82fc869f09a654a58ab4a0c8defd9d2cd662d5d`.
- Runner: 192 MiB RAM / 256 MiB RAM+swap, 0.25 CPU, one job at a time.
The first 96 MiB trial was killed during action setup; that attempt is retained
in migration evidence. Compiler jobs have a separate 512 MiB / 768 MiB cap,
0.5 CPU and 256 PID cap. Resource limits are ceilings, not reserved memory.
- Runner and job containers publish no ports. Existing Gitea HTTPS and TLS
verification remain enabled. Cache server stays disabled.
- Registration lives in the host's `ssw590-local-runner-data` Docker volume,
`/data/.runner`, mode 0600 in a 0700 directory. Never print it, place it in
Git or share it as evidence. The stopped laptop copy is an intentional fallback.
- `unless-stopped` reconnects the daemon after Docker/host restarts. No server
reboot is needed for installation. Only restart an idle runner.
- Admission checks pause new jobs below 3 GiB free disk or 600 MiB available
host RAM. This does not reserve resources or lock Jenkins out. Run manual
builds and Jenkins delivery releases sequentially on this single-CPU host.
- VS maintains the runner; BY retains Droplet administration. Existing Droplet
billing applies; no new instance or plan change was made.
The runner can administer host Docker. Automatic socket mounting into jobs is
disabled, jobs are not privileged, capabilities are dropped, and arbitrary
workflow bind mounts remain disallowed. Runner 2.x does not comprehensively
filter workflow container options, so only the trusted team may edit these
workflows. Co-location gives a compromised Docker-authorized workflow a path
to the shared host; these settings are not strong isolation from untrusted code.
See [official runner configuration](https://docs.gitea.com/runner/2/configuration/).
## Reconnect and stop
From an authorized administrator SSH session:
```sh
sh /opt/ssw590-manual-runner/start.sh
cd /opt/ssw590-manual-runner
docker compose ps
docker compose logs --tail 30
python3 verify.py
# Only when idle:
docker compose stop
```
The start helper requires existing identity and compiler image; it never
registers a new runner. `verify.py` validates identity quietly and prints only
non-secret runtime settings. It can capture compiler-job limits while a job runs.
No account token is required in shell arguments, environment or repository.
## Migration and fallback
The migration exported the existing compiler image, verified the transfer
archive SHA-256 and loaded image ID, stopped the laptop daemon, then streamed
its existing registration directly from Docker Desktop through pinned SSH into
the remote Docker volume using `import-identity.sh`. The import refuses to
overwrite an identity. It is a one-time operation; do not rerun it here.
Original laptop volumes and images remain intact.
To return temporarily to the laptop, first stop the remote runner while idle,
then use `gitea/local-runner/runner.ps1 -Action Start -AllowLaptopFallback`.
Stop the laptop copy before restarting the remote one. Never connect both
copies of the registration. The label intentionally remains `latex-local`.
After grading, only when instructed, retain needed evidence, stop this runner
and remove only its explicitly identified container, network and state volume.
Retire the Gitea registration only when no fallback is needed. Never prune the
host or remove shared Gitea/Jenkins/proxy/monitoring state.
Source for image/state handling:
[Gitea Docker installation](https://docs.gitea.com/runner/2/installation/docker/).
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
# Pause fetching new jobs when the shared host has less than 600 MiB available.
# This is admission control, not a reservation or cross-engine execution lock.
set -eu
awk '/^MemAvailable:/ { found=1; if ($2 < 614400) exit 1 } END { if (!found) exit 1 }' /proc/meminfo
+32
View File
@@ -0,0 +1,32 @@
name: ssw590-manual-runner
services:
runner:
image: docker.io/gitea/runner@sha256:66d80966792e621c9761c47919644198d35fd1c297e9a01e69ed3c1ae37db0c7
container_name: ssw590-manual-runner
working_dir: /data
entrypoint: ["gitea-runner"]
command: ["--config", "/config.yaml", "daemon"]
restart: unless-stopped
stop_grace_period: 70s
environment:
GOMEMLIMIT: 128MiB
volumes:
- runner-data:/data
- ./config.yaml:/config.yaml:ro
- ./admission-check.sh:/admission-check.sh:ro
- /var/run/docker.sock:/var/run/docker.sock
mem_limit: 192m
memswap_limit: 256m
cpus: 0.25
pids_limit: 128
security_opt: ["no-new-privileges:true"]
cap_drop: ["ALL"]
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes:
runner-data:
external: true
name: ssw590-local-runner-data
+24
View File
@@ -0,0 +1,24 @@
log:
level: info
runner:
file: /data/.runner
capacity: 1
timeout: 30m
shutdown_timeout: 60s
insecure: false
labels:
- "latex-local:docker://ssw590-manual-ci:20261007"
cache:
enabled: false
container:
privileged: false
valid_volumes: []
docker_host: "-"
force_pull: false
options: "--memory=512m --memory-swap=768m --cpus=0.5 --pids-limit=256 --cap-drop=ALL --security-opt=no-new-privileges"
health_check:
enabled: true
min_free_disk_space_mb: 3072
script: /admission-check.sh
interval: 15s
timeout: 5s
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# Root-operated, one-time stdin import. Never print or stage registration in Git.
set -eu
test "$(id -u)" = 0
docker volume create ssw590-local-runner-data >/dev/null
docker run --rm -i --network none --user 0:0 --entrypoint sh \
--mount type=volume,source=ssw590-local-runner-data,target=/data \
docker.io/gitea/runner@sha256:66d80966792e621c9761c47919644198d35fd1c297e9a01e69ed3c1ae37db0c7 \
-c 'set -eu; test ! -e /data/.runner; umask 077; cat > /data/.runner; test -s /data/.runner; chmod 700 /data; chmod 600 /data/.runner'
echo 'Registration imported into protected Docker volume; values not printed.'
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# Root-operated reconnect only; an existing protected registration is required.
set -eu
cd /opt/ssw590-manual-runner
docker image inspect ssw590-manual-ci:20261007 >/dev/null
docker volume inspect ssw590-local-runner-data >/dev/null
docker compose config --quiet
docker compose run --rm -T --no-deps --entrypoint sh runner -c 'test -s /data/.runner'
docker compose up -d
docker compose ps
+59
View File
@@ -0,0 +1,59 @@
"""Read-only, non-secret runner/runtime checks. Run as root on The-Ocean."""
import json
import stat
import subprocess
from datetime import datetime, timezone
from pathlib import Path
def run(*args):
return subprocess.check_output(args, text=True).strip()
template = ('{"state":{{json .State}},"host":{{json .HostConfig}},'
'"mounts":{{json .Mounts}},"image":{{json .Config.Image}},'
'"restart_count":{{.RestartCount}}}')
def inspect(name):
# Fetch selected fields, never container environment variables.
info = json.loads(run('docker', 'inspect', '--format', template, name))
state, host = info['state'], info['host']
return {
'name': name, 'image': info['image'], 'running': state['Running'],
'oom_killed': state['OOMKilled'], 'memory_bytes': host['Memory'],
'restart_count': info['restart_count'],
'memory_swap_bytes': host['MemorySwap'], 'nano_cpus': host['NanoCpus'],
'restart_policy': host['RestartPolicy']['Name'],
'port_bindings': host['PortBindings'],
'mount_destinations': [mount['Destination'] for mount in info['mounts']],
}
root = Path(run('docker', 'volume', 'inspect', '--format', '{{.Mountpoint}}', 'ssw590-local-runner-data'))
identity = root / '.runner'
registration = json.loads(identity.read_text())
assert registration.get('name') == 'ssw590-vince-local'
assert registration.get('address', '').rstrip('/') == 'https://git.yebilly.me'
assert isinstance(registration.get('token'), str) and registration['token']
assert stat.S_IMODE(identity.stat().st_mode) == 0o600
# Registration is checked in memory only. Do not serialize any of its values.
report = {'observed_at': datetime.now(timezone.utc).isoformat(),
'registration_validated_without_output': True, 'identity_mode': '0600',
'runner': inspect('ssw590-manual-runner'), 'active_jobs': []}
assert report['runner']['running'] and not report['runner']['oom_killed']
for name in run('docker', 'ps', '--format', '{{.Names}}').splitlines():
if name.startswith('GITEA-ACTIONS-TASK-'):
job = inspect(name)
assert job['memory_bytes'] == 512 * 1024 * 1024
assert job['memory_swap_bytes'] == 768 * 1024 * 1024
assert job['nano_cpus'] == 500000000
assert '/var/run/docker.sock' not in job['mount_destinations']
report['active_jobs'].append(job)
report['admission_check'] = run('docker', 'exec', 'ssw590-manual-runner', 'sh', '-c', '/admission-check.sh && echo passed')
report['compiler_image_id'] = run('docker', 'image', 'inspect', '--format', '{{.Id}}', 'ssw590-manual-ci:20261007')
assert report['compiler_image_id'] == 'sha256:5d24657a4578977fc7709165b82fc869f09a654a58ab4a0c8defd9d2cd662d5d'
report['memory'] = run('free', '-m')
report['disk'] = run('df', '-h', '/')
report['result'] = 'passed'
print(json.dumps(report, indent=2))
+7
View File
@@ -1,5 +1,12 @@
# Local Gitea runner (Assignment 5 preparation)
**Current placement, 14 November 2026:** the active runner has moved to
The-Ocean. This directory preserves the original laptop configuration and
historical setup. See [`../droplet-runner/README.md`](../droplet-runner/README.md).
The laptop copy is stopped; Register/Start now require `-AllowLaptopFallback`
after stopping the remote copy. Never run both registrations simultaneously.
The setup instructions below describe the original October installation.
Run from the repository root in PowerShell with Docker Desktop's Linux engine running:
```powershell
+5 -1
View File
@@ -1,9 +1,13 @@
[CmdletBinding()]
param(
[ValidateSet('Check', 'Register', 'Start', 'Logs', 'Stop')]
[string]$Action = 'Check'
[string]$Action = 'Check',
[switch]$AllowLaptopFallback
)
$ErrorActionPreference = 'Stop'
if ($Action -in @('Register', 'Start') -and -not $AllowLaptopFallback) {
throw 'This runner now runs on The-Ocean. Stop the remote copy first, then pass -AllowLaptopFallback for an intentional laptop fallback. Never run both copies of the registration.'
}
$composeFile = Join-Path $PSScriptRoot 'compose.yaml'
$composeArgs = @('compose', '--project-name', 'ssw590-local-runner', '-f', $composeFile)
$runnerImage = 'docker.io/gitea/runner@sha256:66d80966792e621c9761c47919644198d35fd1c297e9a01e69ed3c1ae37db0c7'
+28 -1
View File
@@ -14,7 +14,34 @@ discuss repository visibility with the other group member before publication.
No registration token, runner identity file, private key, or account credential
is copied. Hints-only Hosts/Passwords records are retained.
## Build and status
## Local PDF for review and submission
From repository root, use the existing TinyTeX installation:
```powershell
./manual/latex/makefilePowerShell.ps1 -Action pdf
```
The helper detects the shared `../Tools/LaTeX/TinyTeX` installation. For a
different existing installation, set `DEVOPS_LATEX_BIN` to its `bin/windows`
directory first. It runs the full bibliography, glossary, acronym, index,
and cross-reference sequence and replaces
`manual/2026F-SSW-590-DevOps-Group-1.pdf`. That PDF and compiler intermediates
are ignored by Git; sources and evidence remain versioned. Docker and an
Actions artifact download are unnecessary for this local build. Local builds
show the human document version without claiming an Actions run number.
After reviewing the PDF, remove generated LaTeX intermediates with:
```powershell
./manual/latex/makefilePowerShell.ps1 -Action clean
```
The PDF is retained. Continue using Gitea Actions for automated build evidence;
keep historical run artifacts already required by the manual. New local
revisions reuse this one PDF rather than creating more run folders.
## Historical Assignment 5 build evidence
See [compiler and workflow instructions](../ci/manual/README.md).
Gitea run 1 succeeded for commit `828f6c5` (issue #12), including checkout,
+27 -8
View File
@@ -1,9 +1,28 @@
This group document records the SSW 590 coursework and its supporting
commands, designs, and evidence. Assignment 5 automates compilation of the
LaTeX manual through Gitea Actions, using a repository-scoped Docker runner
on Vincent's laptop while Gitea remains on the DigitalOcean droplet. The
workflow checks out the triggering revision, compiles with a recorded TeX
Live toolchain, adds run and commit identifiers to the PDF version, and
uploads the PDF and build diagnostics. Two successful source-change runs,
an intentional compiler failure, and a successful repair demonstrate the
workflow. Earlier chapters retain the group's prior assignment results.
commands, designs, and evidence. Assignment 8 implements secure delivery with
a trusted Jenkins agent, locked Flask/Gunicorn service, security gates,
Ansible, scoped deployment credentials and recovery runbooks. The prerequisite
jobs, DNS/TLS and deliberate Jenkins test/secret blocks passed. The reviewed v1
images were published with passing scans. After the SSH and health-deadline
corrections were reviewed, Jenkins builds 5 and 6 promoted v1 and v2 by exact
digest through separate staging/production environments. Both unchanged reruns
passed with zero changes; Vincent approved each production operation. The
production probe and Grafana panel are live. One failed availability sample
was observed during v2 replacement; zero downtime is not claimed. The actual
release records and staging-only fault still require review before the healthy
production rollback and failed-staging recovery demonstrations.
This draft is not ready for submission.
Assignment 7 introduced site reliability
engineering: Prometheus, Grafana OSS, Node Exporter, and Blackbox Exporter
run as four pinned containers beside Gitea and Jenkins on the originally 1\,GiB
DigitalOcean droplet, with Grafana at \url{https://metrics.yebilly.me/login}
for approved networks only. A dashboard shows host CPU, memory, and disk and
the HTTPS availability of Gitea and Jenkins. A 99\% availability objective is
defined and measured, and three alert rules (service availability, disk
space, and collection health) notify the team's Discord channel. Each was
shown firing and resolving; the availability rule through a planned Jenkins
outage that was detected in about two minutes and recovered about a minute
after restart. Earlier chapters retain the group's prior assignment
results, including the Jenkins merge gate and the Gitea Actions manual build.
On November 14 the team resized the droplet to 2\,GiB without enlarging its
disk, updated packages and verified the existing services.
+529
View File
@@ -521,3 +521,532 @@ replace review of the final workflow-generated PDF. No commit, push,
merge, issue closure, or submission was performed by Codex. Final evidence
update push, successful artifact review, group pull-request review/merge,
issue \#12 closure, and submission remain human workflow steps.
\section{Assignment 6 Jenkins Capacity and Test Preparation}
Date: October 19--21, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Inputs: instructor manual version 1.38 supplied by Vincent, the authorized
DigitalOcean droplet view, repository instructions, Vincent's reported resize
constraint and choice to test the existing droplet, terminal screenshots, and
downloaded capacity measurements. Codex prepared isolated core-only experiments;
Vincent ran them through his authenticated SSH connection. The first timed out.
After Vincent authorized stopping the graded Color Buttons app, the second
demonstrated core startup and 24 successful sampled Gitea HTTP checks. No kernel
out-of-memory event was recorded; final container accounting nevertheless
included about 80\,MiB RAM plus 212\,MiB swap. This is not evidence of plugin or
build capacity. Human/AI correction: the raw result claimed a 60-second idle
window, but recorded successful HTTP samples span only 54 seconds. Codex
preserved the evidence and prepared a corrected, unexecuted core script whose
timer starts after a successful response.
Vincent requested a portable human/Claude handoff for Billy Ye. Codex assembled
selected non-secret references, original evidence, scripts, structured state,
the prior team PDF and integrity hashes. The instructor PDF was missing at its
previous location when packaging; that limitation was identified explicitly.
On October 21, Vincent reported school-network connection timeouts. Read-only
checks confirmed that the attached Cloud Firewall allowed the measured source
IPv4, Gitea HTTPS responded, and TCP 22 timed out. The location/cause of filtering
was not proven. No firewall change, reboot or package upgrade was made by Codex.
Vincent asked Codex to prepare and explain the next test. The versioned test
sources include a host-side Python controller, disposable container
bootstrap, explicit Pipeline/Gitea plugin requests, plugin archive inventory,
trusted initialization hook, sample Python pipeline, fault/regression checks
and a readable runbook. The prepared test covers constrained installation,
plugin activation, a corrected 60-second healthy observation, then serial
passing, intentionally failing and repaired calculation tests. It retains
resource and Gitea checks, separate RAM/swap accounting, targeted cleanup and
a detached deadline. It adds no production credential, public Jenkins endpoint,
webhook, merge check, persistent service or paid resource. The controller's
single executor is restricted by the experiment's trusted local fixture; it
does not establish the final production build boundary.
Verification used: nine local Python regression/fault checks passed, including
the actual sample application's pass/failure/repair sequence; Git Bash accepted
the bootstrap syntax. Official plugin documentation supplied version/baseline
checks. Docker was initially off; Vincent then enabled it and authorized local
verification. The first local attempt exhausted the installer's 128\,MiB Java
heap while reading the plugin catalog, before Jenkins started; Docker did not
report a kernel OOM kill. Codex separated laptop-only plugin preparation
(768\,MiB RAM, 512\,MiB heap) from runtime. The official installer prepared
59 versioned and hashed plugin archives, and its temporary container was removed.
The revised runtime kept the original limits: 256\,MiB RAM, 512\,MiB for RAM
plus swap, half a CPU and a 128\,MiB heap. All 59 plugins loaded; healthy HTTP
samples spanned 65.39 seconds before the job ran. Three serial Jenkins builds
produced success, the intended unit-test failure, and repaired success. Peak
simultaneous accounted RAM plus swap was about 389.5\,MiB, with zero recorded
container OOM events. Cleanup succeeded and no experiment containers remained.
This demonstrates local Jenkins execution, not capacity beside Gitea on the
droplet. The laptop Docker VM had substantially more host resources; local mode
recorded the unmeasured droplet host/Gitea fields as null. Original failed and
successful evidence was retained. The upload package includes the resolved
plugin archives so the droplet need not repeat the larger catalog-resolution
step. Remaining work includes the guarded droplet run, actual Gitea integration and
merge-gate exercise, and the Assignment 6 report chapter. Hosts and Passwords
tables remain unchanged because no persistent service or real integration
credential was added. Existing deployment files and evidence were preserved;
no commit, push, merge or submission was performed by Codex.
\section{Assignment 6 Jenkins Deployment, Merge Gate, and Chapter}
Date: October 21--23, 2026; Tool: Anthropic Claude Code (Claude Opus 5.5);
Human: Billy Ye, with Vincent Sun as reviewer.
Inputs: instructor manual version 1.38 (Chapter 4), Vincent's two handoff
packages (capacity evidence, the prepared \texttt{ci/jenkins-capacity} test
and plugin bundle, and the patch for the preceding record), the repository
and its AI guidance, Billy's decisions (Jenkins on the existing droplet,
Claude runs droplet commands over SSH with Billy approving each step,
browser allowlist of Stevens 155.246.0.0/16 plus team addresses, and the
instructor's Python pricing example), and Billy's dated screenshots. Billy
loaded his SSH key into the Windows agent and typed its passphrase himself;
Claude never saw the passphrase, the Jenkins initial password, any account
password, or the \texttt{jenkins-bot} token.
Claude read the droplet state, ran Vincent's guarded test unchanged
(first run aborted on upload permissions it introduced; fixed with
\texttt{chmod}; second run passed), wrote the Dockerfile, plugin lockfile,
Compose, Caddy, and README changes, deployed Jenkins after backing up the Compose and Caddy files and with a
monitored rollout, and pushed the feature commits after Billy asked.
Billy performed every web-interface step (DNS, Jenkins setup and security,
bot account and token, credential, job, webhook, branch protection, PR
creation, merge); Vincent reviewed and approved PR~\#15.
Human/AI corrections: the plugin installer exhausted a 128\,MiB heap, so
Claude replaced it with hashed \texttt{curl} downloads; the 128\,MiB runtime
heap hung the web interface, so Claude doubled the container limits with a
recorded reason; Claude had dropped \texttt{matrix-auth} when adopting
Vincent's bundle, which Billy discovered when the option was missing, and
it was added; Billy's question about the build-view screenshot showed no
stage view was installed, so \texttt{pipeline-graph-view} was added. Claude
redacted a Jenkins reporting-endpoint ID and personal browser details from
screenshots.
Outputs used: the deployment files and application/test/\texttt{Jenkinsfile}
in PR~\#15; the command log retained under ignored
\texttt{build/evidence/}; \ChapterRef{JenkinsCI}; updated Hosts and Passwords
tables; glossary terms; title page, abstract, Document History; this record.
Unresolved: three theme plugins installed through the web interface are not
in the lockfile; the course deadline was reported as Friday but not checked
on the course page by Claude; the final PDF needs the Gitea Actions runner
on Vincent's laptop. No submission was performed by Claude.
\section{Assignment 6 Access-Path Correction}
Date: October 23, 2026; Tool: Anthropic Claude Code (Claude Opus 5.5);
Human: Billy Ye.
Inputs: an independent model review of the version 4.0 PDF, which noted that
the instructor access path (campus or Stevens VPN) had not been tested;
Billy's GlobalProtect connection to \texttt{sitvpn.stevens.edu} and his
redacted settings screenshot. Claude checked the public address and routing
table on Billy's laptop while the VPN was connected: the address was
unchanged and only 155.246.0.0/16 used the VPN adapter, so the VPN is
split-tunnel. Human decision: state the campus network plus addresses added
on request as the approved path. Outputs used: corrected access-path text,
an exposure-table row, the GlobalProtect figure, the Caddyfile comment,
version 4.1 and its history row. Billy's residential address was kept out of
the report. Vincent then tested from campus Wi-Fi \texttt{Stevens-Net}
(public address 155.246.151.38) and the sign-in page loaded; Claude combined
his screenshots into one figure, blurring the password field and profile
icon. A friend reportedly on campus saw a blank page (the 403); his network
and address were not recorded, so no conclusion is drawn from it.
\section{Assignment 6 Run-9 Review and Final Corrections}
Date: October 23, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Inputs: Vincent's request to review the run-9 PDF, instructor manual version
1.38, the repository's AI guidance, public Gitea commit/status/review records,
and Vincent's approval to correct the documentation while leaving the three
theme plugins unchanged. Codex reviewed the Jenkins chapter, updated tables,
history, and AI records visually; checked the artifact ZIP and PDF links;
and confirmed the recorded failed/repaired statuses, approval, and merge
against Gitea. A read-only HTTPS check returned the Jenkins sign-in page
with certificate verification passing. No authenticated Jenkins inspection
or new droplet experiment was performed during this review.
Human/AI corrections: the PDF linked a 60-plugin lockfile at the initial
deployment merge while describing the later 63-plugin set. Codex changed
that link to the recorded revision \texttt{ac18f11}, retaining historical
PR and run links. It clarified that \emph{Build Now} uses the revision
selected for that run and does not establish a clean workspace or the same
commit as an earlier run; clean local reproduction now calls for a fresh
clone and the recorded commit ID. It separated the observed delivery timeout
from the suspected CPU/discovery cause and made timeout tuning conditional.
At Vincent's direction, the theme plugins were left unchanged; the existing
security-check result is explicitly limited to its 63 checked versions.
Outputs used: these corrections in \ChapterRef{JenkinsCI}, version 4.2,
the dated Document History entry, and this record. Prior Billy/Claude
records and original run-9 evidence are preserved. Hosts and Passwords
tables are unchanged because no deployed service, account, or credential
changed. The revision is checked through the complete local TinyTeX build,
diagnostic inspection, and visual review of the affected PDF pages.
No commit, push, remote configuration change, or submission is performed
as part of this correction.
\section{Assignment 7 Monitoring Deployment, Tests, and Chapter}
Date: October 27--28, 2026; Tool: Anthropic Claude Code (Claude Opus 5.5);
Human: Billy Ye, with Vincent Sun as verifier and reviewer.
Inputs: instructor manual version 1.42 (Chapter 5), found in Billy's
downloads after Billy asked to implement ``chapter 5 of this manual''; the
repository and its AI guidance; Billy's decisions (measure capacity before
any resize and then try a capped deployment on the 1\,GiB plan, alerts to a
Discord webhook, hostname \texttt{metrics.yebilly.me}, Claude running droplet
commands over SSH with Billy approving each step, disabling four unused host
services after Claude showed the disk and boot checks); Billy's DNS record,
Discord channel and webhook, issue \#19, secrets file, Grafana login,
screenshots, pushes, and improvement issues \#20 and \#21.
Claude synced both checkouts, measured the baseline, chose and verified
pinned image digests, wrote the \texttt{monitoring/} configuration, the
Caddy and Compose changes, the dashboard, alert rules, and README runbooks;
validated them locally (Compose, \texttt{promtool}, \texttt{caddy validate},
and a throwaway Grafana run); deployed them after backing up the Caddy files;
ran the exposure, contact-point, capacity-alert, outage, persistence, and SLO
queries; and wrote \ChapterRef{SREMonitoring}, the Hosts and Passwords
updates, glossary terms, title page, abstract, and Document History. Billy
typed every secret himself: Claude never saw the Grafana password or the
webhook URL. API calls read the password from the Grafana container's
environment without printing it.
Human/AI corrections: the local Grafana run rejected an alert template
written with \texttt{\$\$labels}; the deployed Grafana could not read its
configuration after the Windows upload (fixed with \texttt{chmod}); Grafana~13
had removed the old contact-point test endpoint, so the replacement was found
from its own error message; one Grafana login from Claude failed because a
password was read from the file with untrimmed whitespace; the first
build-check before the outage matched the \texttt{ps} header and aborted
before anything was stopped; one SLO query was first evaluated at the wrong
time and was rerun; Billy's partial home IP address was removed from the
evidence file before commit; the push from Claude's shell failed
authentication, so Billy pushed and re-authorized Git Credential Manager.
Billy's questions about the CPU readings led to the I/O-wait finding and the
dashboard change.
Review and corrections: at Billy's request, Claude had an independent
subagent audit the chapter against the instructor's requirements. Claude
checked its findings against the evidence (two of its ``unsupported''
claims were supported by earlier output and a figure) and, with Billy's
approval, added a collection-health rule and tested it by stopping Blackbox
Exporter, ran Blackbox Exporter as non-root, compared CPU counters with
\texttt{/proc/stat}, and corrected four figures and the overstated
no-data claim. Billy replaced the Grafana administrator password himself;
Claude confirmed the old value was rejected and removed it from the
secrets file without printing it.
Outputs used: commits \texttt{d3a5e6b} and \texttt{b6cf080}, the chapter
commits on \texttt{feature/issue-19-monitoring} (PR \#22);
\texttt{monitoring/EVIDENCE.md}; \ChapterRef{SREMonitoring}; this record.
Assumptions and unresolved items: the title-page assignment title comes
from the Canvas page Billy showed (``\#7 Grafana and Promethous SRE --
Group''), with the spelling of Prometheus corrected; the acknowledgement was given to Claude before the restart, and
Billy's Discord reply came later; Billy created Vincent's Grafana
account \texttt{vsun1} as Viewer; the 24-hour SLO was not evaluated; the manual-PDF build needs
Vincent's runner when the branch is merged. No pull request, merge, or
submission was performed by Claude.
\section{Assignment 7 Run-11 Review, TCP Evidence, and Final Corrections}
Date: October 28, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Inputs: Vincent's request to double-check Billy's completed Assignment 7,
instructor manual version 1.42 Chapter 5, the run-11 artifact, repository AI
guidance, versioned monitoring configuration and evidence, and public Gitea
statuses and reviews. Vincent authorized the corrections and requested one
locally compiled PDF in the repository, excluded from Git. Codex inspected
the chapter and supporting figures, compared configuration and dashboard
queries with the rubric, and verified the final PR head, approval, merge,
and successful run-11 status. Chrome connected to Gitea; a subsequent
project-tab operation timed out, so no authenticated Jenkins/Grafana audit
or remote settings change was performed in this correction.
Human/AI corrections: Codex identified changing branch links, incomplete TCP
evidence from HTTP code 000, outdated review timestamps, and conclusions
stronger than the timing, sampling, or resource measurements supported.
Vincent ran the supplied external PowerShell loop on his laptop and moved
its CSV into the repository's ignored evidence directory. All 18 outcomes
matched: TCP 80/443 succeeded and seven private ports failed on both IPv4
and IPv6. Codex preserved the raw file and made a versioned copy replacing
only the local Wi-Fi name with a generic network description. The reusable
script preserves that loop with parameters; its syntax is checked without
claiming another network test. The CSV timestamps are completion times.
Outputs used: version 5.1; the new TCP table and reproduction command;
deployment links pinned to merge \texttt{34c4c74}; final approval/check and
run-11 links; qualified notification-delay, missing-sample, and memory-pressure
conclusions; a Document History entry; and this record. The local build helper
now discovers the shared TinyTeX path from the actual repository nesting;
local build instructions and PDF ignore rules retain one replaceable PDF.
The complete TinyTeX build includes the bibliography, glossary, acronym list,
index, and final reference passes, followed by diagnostic and visual review.
Billy/Claude records and original evidence are preserved. Hosts and Passwords
tables are unchanged because no deployed service, account, or credential
changed. The missed pre-deployment build observation remains a limitation;
later results do not recreate it. Commits, pushes, peer approval, and submission
remain with the group. This local revision is not described as an Actions
artifact or as already approved in Gitea.
\section{Assignment 8 Secure Delivery Preparation and Agent Setup}
Date: November 14, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Inputs: Vincent's request to implement the next assignment today, instructor
manual 1.43 Chapter 6 and Examples.zip, the Canvas assignment page, repository
AI requirements/guide, earlier configuration, and live read-only service checks.
Vincent retained commits/pushes and reported Billy unavailable until tonight.
Codex read the assignment, preserved prior work, verified remote main
\texttt{8beefde}, and created \texttt{codex/assignment8-secure-delivery}.
It adapted the instructor's v1 and Ansible starters, locked dependencies and
tool images, prepared a dedicated delivery pipeline, scan policy, immutable
release validation, idempotence gate, failure modes, observer and runbooks.
The original instructor authorship remains identified.
Human/AI corrections and execution: Vincent supplied his encrypted-key SSH
command and enabled Windows ssh-agent, initially also unloading the key; Codex
explained reloading it and keeping passphrases out of chat. Browser-console
and network limitations were distinguished from successful access. Vincent
resized The-Ocean to 2\,GiB while retaining disk size and applied host updates;
Codex verified resource and existing-service status. With authorization to
continue setup, Codex backed up Jenkins/Gitea, configured the restricted deploy
key and root sudo, separate package-scoped tokens under vsun1, folder-scoped
Jenkins credentials, exclusive laptop agent and disabled release job. Secret
values were transferred only through protected runtime storage and were not
printed or placed in Git. Agent prerequisite build 1 passed with real credential
binding, strict SSH host-key checking and noninteractive sudo.
Checks/corrections: local v1 tests passed; a generated wrong-price test failed
as intended; the scanner-supported synthetic fixture blocked delivery; the
dependency audit and final runtime-image gate passed their configured policies.
Earlier Debian and installer-containing Alpine scans failed and were retained;
Codex selected the Alpine runtime and removed unused pip/ensurepip without
adding scanner exceptions. The installed Jenkins parser rejected the initial
timestamps option because its plugin is absent; Codex removed that option and
retained explicit UTC evidence. Browser editor insertion briefly concatenated
two validation snippets; the editor was cleared and the read-only validation
repeated successfully. The host setup script compiled against installed plugin
classes before application. Ansible syntax and agent Compose checks passed.
Outputs used: \ChapterRef{SecureDelivery}, version 6.0 preparation, the adapted
application/toolchain, pipeline and control tests, bootstrap, runbooks, issue
draft, planned proxy and production-monitoring additions, actual prerequisite
inventory, Hosts/Passwords hints, history and this record. Existing Billy/Claude
records are unchanged. Source/configuration release SHAs and registry digests
have not been invented. The local preflight image explicitly identifies itself
as uncommitted preparation, not a reviewed release.
Unresolved items: application DNS requires the domain owner's access; distinct
names are explicitly required, so path-only routing was rejected as a substitute.
Vincent/Billy must create the issue, commit/push and review/merge v1 and later
changes. Real Jenkins blocked-gate runs, v1/v2 publication, interactive production
approvals, idempotence, both recovery exercises, timing/monitoring correlation
and final submission review remain pending. Proxy/monitoring additions are not
deployed before DNS and healthy production. No commit, push, peer review,
production approval or submission was performed by Codex.
Later on November 14, Vincent explicitly authorized Codex to make the local
preparation commit \texttt{bf28adc}; Vincent pushed it, and Codex verified the
remote branch and passing Jenkins head check. At Vincent's further request,
Codex prepared \path{delivery/BILLY-CLAUDE-DNS-HANDOFF.md} for Billy/Claude,
including the two selected A records, Namecheap instructions checked against
official documentation, current public DNS observations, verification commands
and a DNS-only boundary. The provider's default nameservers and existing
Gitea/Jenkins/Grafana A records were observed; the two new names still returned
NXDOMAIN. No DNS setting was changed, and the handoff itself grants no account
authorization. Billy must authorize DNS work in his own session.
Later that evening, Vincent directed moving the delivery agent onto the now
2\,GiB droplet because campus Wi-Fi had blocked SSH and the final presentation
must demonstrate the workflow. Codex checked repository state and host capacity,
transferred the existing tool image with matching archive SHA-256 and image ID,
stopped the laptop copy, and reused the protected node identity on The-Ocean.
It added a private WebSocket route, host-gateway SSH mapping with the existing
pinned key alias, 512/768 MiB agent and 256/384 MiB BuildKit RAM/RAM+swap caps,
half a CPU each, a guarded laptop fallback and versioned verification helpers.
The first builder setup exposed a socket-group mismatch (laptop 0, host 987);
the helper was corrected to detect the host group, and Docker access succeeded.
The first browser build request used stale session state; reloading allowed the
existing preflight job to run. Build 2 passed with real credential binding,
strict SSH verification and sudo. A separate 87-second preparation trial passed
control/app tests, source/dependency checks, capped build, full image gate and
temporary HTTP smoke. Swap increased and agent memory-limit events occurred;
no OOM kill was recorded. Existing services passed private HTTP checks, and
agent restart/reconnect passed. This does not establish full release performance.
An initial CLI artifact download returned HTTP 403; evidence was retrieved over
authorized SSH instead. A complex shell diagnostic had a quoting error and was
replaced by a versioned read-only Python check. No credential values were output.
Codex updated the diagram, current host/credential hints, runbooks, DNS handoff,
preparation evidence, history and this log, and rebuilt/reviewed the local manual.
The older PDF runner remains on the laptop; campus browser access still needs
rehearsal. Shared-host Docker administration is an explicit lab trade-off.
No firewall rule, credential scope, review requirement or production approval
was relaxed. DNS, assessed releases and recovery exercises remain pending.
No additional commit or push was authorized or performed for this migration.
\section{Actions Runner Migration for the Presentation}
Date requested: November 14, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Vincent then explicitly requested moving the first (Gitea Actions) runner to
the droplet too. Codex read the runner/workflow sources and repository rules,
checked headroom, and transferred the tested compiler image with matching
archive checksum and image ID. It stopped the idle laptop daemon before
streaming the existing registration over pinned SSH into protected Docker
storage. No registration value was printed, staged in the repository, or
replaced; the legacy name/label and repository scope were preserved.
Codex added versioned remote Compose, admission, reconnect/import and read-only
verification helpers plus a guarded laptop fallback. The first 96 MiB daemon
cap was too low: a real OOM event and restart occurred during action setup.
Codex canceled that attempt, retained its log and runtime evidence, raised
the daemon to 192/256 MiB RAM/RAM+swap with 0.25 CPU, and retried. Separate
compiler job limits remained 512/768 MiB and 0.5 CPU. Run 12 attempt 3, job 14,
passed checkout, compilation and both uploads in 4m32s. It used reviewed main
\texttt{8beefde}, not the uncommitted Assignment 8 source. After a browser
download-wait timeout and debugger detachment, Vincent supplied diagnostics
in run-12. Codex retrieved the exact PDF through read-only artifact metadata
and storage over SSH, verified its checksum against those diagnostics, and
visually checked \texttt{5.1+build.12.8beefde}. This does not demonstrate the
pending application releases or recovery exercises.
The corrected daemon had no restart during the successful run; idle restart
and declaration succeeded at 04:55:52 UTC on November 15. Codex identified
the canceled job's orphaned resources for cleanup, preserved registration and
shared services, and updated operations, migration evidence, host/credential
hints, history and this record. Both active runners are on The-Ocean; no new
cloud instance or resize was made. Resource admission does not coordinate
Jenkins, so manual builds and delivery releases must run sequentially. Shared
Docker authority remains a documented trust trade-off. Campus browser rehearsal,
DNS and assessed delivery remain pending. No further commit or push was requested.
\section{DNS, HTTPS and Team Account Check}
Date: November 15, 2026; Tool: OpenAI Codex; Human: Vincent Sun; DNS: Billy Ye.
Vincent reported that Billy had added the records but HTTPS was unavailable,
and asked for server-side correction. Codex checked repository instructions,
status, official Caddy HTTPS documentation, live DNS, proxy configuration and
container state. It verified that the prepared routes were absent and app
backends undeployed. A guarded helper first stopped on CRLF/LF comparison;
normalizing only line endings confirmed the earlier routes matched. Codex
validated the candidate, saved a protected backup and gracefully reloaded Caddy
while preserving the bind inode, prior routes, allowlists and certificate state.
Google/Cloudflare answers and normal curl/Python checks verified DNS, trusted
hostname-matching TLS and HTTP 308 redirects. HTTPS 502 was correctly recorded
as missing backend deployment, not a certificate failure or healthy release.
Existing service checks passed. No DNS account, firewall or application release
was changed; production monitoring remains pending.
Vincent also requested a team-account check for access recovery. Codex queried
only account IDs/status/role flags and Jenkins profile-header IDs, never password
hashes, tokens or email fields. The expected Billy accounts were present, and
the existing vsun1 Gitea site-admin role was confirmed and corrected in the
hints table. Grafana's vsun1 remains Viewer. No password was recovered or reset,
and no permission was changed. Codex explained the distinction between checking
an account, recovering a password-manager copy and resetting an existing login.
It updated current readiness records, the preserved DNS handoff, history and
this log, then rebuilt and visually checked the local manual. Source changes
remain uncommitted; peer review, app releases, approvals and recoveries remain pending.
\section{Delivery Gates and SSH Correction}
Date: November 15, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Vincent reported the merge complete and asked Codex to continue and finish the
assignment, then requested continuation after his usage limit reset. Codex read
the repository requirements and guide, verified PR~\#24's latest Billy review
and merged main \texttt{09731ac}, and synchronized a clean local branch
\texttt{codex/assignment8-release-evidence}. Vincent retains commits/pushes;
no additional commit or push was authorized or performed.
After the merge-triggered Actions manual build finished, Codex enabled the
reviewed pricing job and initialized a MODE choice parameter for its first
negative demonstration. The Jenkinsfile then installed its normal parameters.
Pricing builds 1 and 2 actually stopped the wrong-price and synthetic-secret
fixtures before publication/deployment. Build 3 passed normal tests and all
security gates and published/pulled a real v1 digest, but Ansible's default
PTY request conflicted with the deploy key's intentional no-PTY restriction.
Gathering Facts was unreachable with zero changes; no app or production
approval was reached. Earlier plain-SSH prerequisites had not exercised
Ansible's default terminal behavior, so they had missed this integration gap.
Codex checked the official Ansible 2.21 SSH option documentation, set the
inventory's \texttt{ansible\_ssh\_use\_tty=false}, and extended the administrator
preflight to bind the existing credentials and run \texttt{id -u} through
Ansible/become without a terminal. Preflight build 3 passed and returned 0.
The job's read-only command reports CHANGED by module default; this is not an
application deployment/idempotence result. No key restriction, host pin,
credential scope, review gate or human approval was weakened.
Codex preserved exact reports and metadata over pinned SSH, wrote dated
non-secret evidence and a focused PR description, updated this chapter/history
and the incomplete draft status, and rebuilt/reviewed the local PDF. The
source correction must be committed, reviewed and merged before a new v1 run.
Published-but-undeployed attempt records are not presented as known-good
rollback records. Successful promotions, human approvals, both recoveries and
monitoring correlation remain unexecuted.
\section{Pricing Health Deadline and v2 Preparation}
Date: November 15, 2026 Eastern (November 16 UTC); Tool: OpenAI Codex;
Human: Vincent Sun. After Vincent reported the fix merged, Codex checked the
repository requirements/status, verified Billy's PR~\#25 approval and merge
\texttt{a19fab3}, synchronized a clean branch and ran pricing build 4. Tests,
scans, publication and initial staging verification passed. The unchanged
rerun stopped because Docker reported the container unhealthy; no production
approval or deployment occurred. The noninteractive SSH correction worked.
Codex inspected only the staging container's health/state, logs, resource
counters and public health endpoint. Probes near three seconds sometimes hit
the three-second deadline; the app later recovered without restart and no OOM
kill was recorded. Codex tested a ten-second overall deadline in an isolated
temporary container using the same reviewed image and constraints, with no
network, published port or proxy alias. Eight checks passed in 2.817--5.660
seconds; CPU throttling occurred, but no diagnostic memory-limit/OOM event.
The diagnostic container was removed by its exact created ID. Its code/raw
JSON and actual build-4 reports were preserved. Existing staging was unchanged.
Codex changed only the image's overall health deadline, retaining the two-second
HTTP request timeout and other health/security/resource settings. It prepared
the required v2 source/test change locally; three functional and twelve control
tests passed. Docker Desktop was unavailable, so the functional tests used the
existing Windows Flask installation (Werkzeug 3.1.8 rather than the deployment
lock's 3.1.9); this was not represented as a passed locked Jenkins release.
Both remote runners remain independent of the laptop Docker daemon.
To reduce review cycles, Codex prepared instructions for two commits in one PR:
v1 health correction first, then v2 app/tests. A merge commit must preserve
both reviewed source SHAs for explicit Jenkins selection. No commit, push,
review or production approval was performed by Codex. It updated current
staging inventory, architecture, evidence, runbooks, history and this log,
and rebuilt/visually reviewed the ignored local PDF. Successful releases,
unchanged reruns, human approvals, known-good records and both recovery
exercises remain pending.
\section{Reviewed Releases and Production Monitoring}
Date: November 15, 2026 Eastern (November 16 UTC); Tool: OpenAI Codex;
Human: Vincent Sun; Reviewer: Billy Ye. Vincent reported the merge complete
and asked Codex to continue. Codex reread repository requirements/status,
verified Billy's PR~\#26 review and the preserved v1/v2 commits, synchronized
main and created a local recovery-evidence branch. It waited for Actions
workflow 15 to finish before running the two delivery releases sequentially.
No source commit or push was performed by Codex.
Build 5 selected v1 source/configuration \texttt{34f26e6}; build 6 selected v2
\texttt{6bddbfb}. Both passed actual tests, scans, staging deployment and
unchanged reruns. Codex requested a real human approval at each Jenkins input;
Vincent clicked the approvals himself. Codex verified the recorded
\texttt{vsun1} identities and UTC times (03:04:01 and 03:11:18), subsequent
production assertions and SUCCESS results. It copied the four exact generated
selectors unchanged, verified them and preserved full archives, scan hashes,
recaps and timing summaries. V1 total 30 and v2 total 36 were actual pipeline
checks in both environments, not inferred from source alone.
After healthy v1, Codex applied the previously reviewed production probe/panel
using a guarded administrator helper: compare prior probes/panels, validate,
back up, preserve bind inodes, SIGHUP Prometheus and observe Grafana provisioning.
The first dry-run cleanup used Prometheus's non-root service user for a
root-owned temporary file; it was corrected before live application. A legacy
Grafana SQL lookup returned no dashboard row, so it was not treated as proof.
The earlier Grafana tab could not be attached; a fresh tab in the same Chrome
session displayed the actual provisioned panel and data. Live Prometheus
queries confirmed the new probe, prior targets and reload success. Official
Prometheus/Grafana documentation supported the reload/provisioning procedure.
No credentials, allowlists, retention or existing alerts were changed.
Post-release HTTPS captures verified both healthy v2 containers, exact source,
total 36 and invalid-input HTTP 400. The production history contained one
HTTP 502 sample at 03:11:54.602 UTC during v2 replacement, bounded by successful
samples 60 seconds apart. Codex preserved this interruption rather than claiming
zero downtime or an unobserved notification. It prepared the successful records
and staging-only bind-mismatch patch for review, with an intermediate bad commit
and immediate revert so final main remains correct. Both recovery executions
still require those reviewed commits and measured evidence. Codex updated
current inventory, architecture, runbooks, history and this record, then rebuilt
and visually checked the ignored local PDF. Existing Billy/Claude records and
historical execution evidence were preserved.

Some files were not shown because too many files have changed in this diff Show More