← Commit history
Publish 0.1.0
18 files changed
+900
SKILL.md+104docs/hero.pnginstall.sh+4package.json+63screenshots/showcase.pngscripts/install.py+15scripts/uninstall.py+16skills/adom-bluegreen/SKILL.md+104skills/adom-bluegreen/examples/ready-bun.ts+23skills/adom-bluegreen/examples/ready-node.js+18skills/adom-bluegreen/examples/ready-python.py+38skills/adom-bluegreen/examples/service.conf.example+15skills/adom-bluegreen/scripts/bluegreen.sh+284skills/adom-bluegreen/scripts/boot-hook.sh+46skills/adom-bluegreen/scripts/install.sh+37skills/adom-bluegreen/scripts/probe.sh+16skills/adom-bluegreen/tests/selftest.sh+113uninstall.sh+4SKILL.mdadded+104@@ -0,0 +1,104 @@+---+name: adom-bluegreen+description: Zero-failed-request deploys for an Adom service container. nginx front door, blue and green slots as git worktrees, a flip only when the new build reports ready at the new commit, and the old slot stopped only after it has served every request it accepted. Use when a service restarts in place on every push (and is down while it warms), when someone asks for blue-green, zero downtime, rolling or hitless deploys, or when a service needs a /ready endpoint. Trigger words - blue-green, blue green deploy, zero downtime, zero failed requests, hitless deploy, service down while it updates, watchdog restart, /ready endpoint, readiness probe, drain in-flight requests, adom-bluegreen.+---++# adom-bluegreen++A service container that pulls `origin/main` and restarts in place is down for as long as the new+process takes to warm up. Component Ocean took 60-120 s to load its data, so every push was a+minute or two of outage for every caller. Ray, 2026-09-22: *"for anything production-dependent I+consider this unacceptable ... it has to be 0 failed requests."*++This kit is what took CO to zero. Measured on the live service: a cron-driven deploy had **0 failures+in 1,372 requests** and a manual one **0 in 2,365**. The kit's own self-test measured **0 in 5,709**+across a deploy and **0 in 7,659** while a broken build was refused.++## How it works++```+ public URL ──> :PUBLIC_PORT nginx (front door; reloads never drop a request)+ ├── :BLUE_PORT blue slot (git worktree at commit A)+ └── :GREEN_PORT green slot (git worktree at commit B)+```++Every 2 minutes cron runs `bluegreen.sh <service.conf>`. When `origin/BRANCH` has a new commit:++1. It is checked out and started in the **idle** slot, while the live slot keeps serving.+2. The front door flips only when the new slot's `/ready` answers **200 with that exact commit**.+ Anything else (it crashed, it never warmed, it runs the wrong commit) means no flip. The commit is+ recorded in `failed_sha` and never retried. The old slot keeps serving.+3. nginx reloads gracefully. New requests go to the new slot and requests already in progress+ finish where they are.+4. The old slot is stopped only once it has **finished every request it accepted** (its `/ready`+ reports `inflight` 0 for 5 s).++If the live slot dies while the other is warm, traffic fails over to it. The only remaining outage+is a true cold start (container restart), when nothing is running anyway.++## Adopting it on a service (about 15 minutes)++1. **Add the `/ready` contract** to the service. Copy the pattern from `examples/` (Bun, Node, Python):+ ```+ GET /ready -> 200 {"ready":true, "git_sha":"<$BLUEGREEN_SHA>", "inflight":<n>} when warm+ -> 503 {"ready":false, ...} while warming+ ```+ - Listen on `$PORT`; the kit sets it per slot.+ - `git_sha` echoes `$BLUEGREEN_SHA`; the kit sets it too, so the app never has to read `.git`.+ - `ready` must mean *everything* callers need is loaded, not just "the port is open". CO's first+ version flipped before its passive value index was attached, and value filters would have+ answered 503.+ - `inflight` counts requests in progress, excluding `/ready`. It's optional; without it the old+ slot gets a timed 90 s drain.+ - Push this first and let the old deploy mechanism ship it.+2. **Write the config** from `examples/service.conf.example` and keep it under `/home`: `NAME`,+ `REPO_DIR`, `BRANCH`, the three ports, `START_CMD` (one plain command, run in the slot directory),+ `INSTALL_CMD`, and `SHARED` (gitignored state such as `data`, symlinked into both slots).+3. **Stop the old auto-deploy** (its cron line or watchdog) so two deployers don't fight.+4. **Install:** `bash scripts/install.sh ~/my-service.conf`, adding `--boot-hook` on images whose+ entrypoint only starts sshd. It checks the config, installs nginx and schedules the watchdog.+5. **Adopt the port:**+ - If the service already listens on `PUBLIC_PORT`, set `LEGACY_STOP_CMD` to how to stop it.+ - The first pass warms a slot, stops the legacy process and starts nginx in its place.+ - That handoff is the **one moment** two processes would need the same port, so there is a gap of+ milliseconds. Do it during a container restart (nothing is listening then anyway) or at a quiet+ time. Every deploy after it is zero-failure.+6. **Prove it:** start `scripts/probe.sh http://127.0.0.1:PUBLIC_PORT/ 300 4` on the container, push a+ commit, and read the last line. It must say `0 failed`.++Check before you trust it on a new container: `bash tests/selftest.sh 3490` runs a real deploy of a+throwaway app on spare ports (cold start, deploy under load with slow requests, a never-ready build)+and must end `10 passed, 0 failed`. It touches nothing else.++## Operating it++| | |+|---|---|+| where traffic goes | `bash scripts/bluegreen.sh <conf> status`, or `curl :PUBLIC_PORT/__bluegreen` |+| is my push live? | `/__bluegreen` shows its sha, usually 2-4 min after the push |+| logs | `~/.bluegreen/<NAME>/bluegreen.log`, `blue.log`, `green.log`, `nginx-error.log` |+| a deploy failed | `~/.bluegreen/<NAME>/failed_sha`; read `<slot>.log`; push a fix (a new sha retries) |+| roll back | `git revert` and push: a rollback is just another zero-failure deploy |+| stop deploying | remove the cron line; both slots and nginx keep serving |++## Traps this kit already handles (do not reintroduce them)++- **Never `pkill -f`.** It matches the watchdog's own command line and kills both slots. Processes+ are found through `/proc` by working directory and exact command.+- **`$!` after `cd dir && cmd &` is a wrapper shell, not the server.** Killing it leaves the server+ holding its port, and the next deploy into that slot fails.+- **Every launched process must drop the lock fd** (`exec 9>&-` first in its subshell). A child that+ inherits it holds the lock for life, every later pass exits at `flock`, and deploys silently stop+ with no error anywhere. CO hit this twice.+- **`git reset` rewrites the running watchdog script** under bash, which reads it by offset. The+ script re-runs itself from a private copy first.+- **Never replace a front door that is serving.** Two processes cannot share a port, so any handoff+ is a gap. nginx changes its config by reload, keeping the socket. A new front door is adopted+ only at a cold start.+- **Don't name a bash array `PORT`.** Bash cannot export an array, so `export PORT=...` silently does+ nothing and the app starts without its port. The self-test caught this.+- **What the container cannot do:** there's no `NET_ADMIN` and `/proc/sys` is read-only, so there's+ no iptables and no `tcp_migrate_req`. The edge port mapping can be added or removed but never+ re-pointed. That is why the front door is a long-lived nginx on the mapped port.+- **nginx lives in `/usr`, which a container rebuild resets.** The watchdog reinstalls it at the next+ cold start. Keep the config and the service's state under `/home`.
docs/hero.pngadded⋯ 1 unchanged line ⋯
install.shadded+4@@ -0,0 +1,4 @@+#!/bin/sh+set -eu+SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+exec python3 "$SCRIPT_DIR/scripts/install.py" "$@"
package.jsonadded+63@@ -0,0 +1,63 @@+{+ "name": "adom-bluegreen",+ "slug": "adom-bluegreen",+ "title": "Adom Blue-Green",+ "version": "0.1.0",+ "type": "skill",+ "description": "Zero-failed-request deploys for any Adom service container: an nginx front door, blue and green slots, a flip only when the new build reports ready at the new commit, and the old slot stopped only after it has served every request it accepted.",+ "brief": "Blue-green deploys with zero failed requests for service containers. Proven on Component Ocean.",+ "license": "MIT",+ "files": [+ "package.json",+ "SKILL.md",+ "README.md",+ "install.sh",+ "uninstall.sh",+ "scripts/install.py",+ "scripts/uninstall.py",+ "skills/**",+ "docs/hero.png",+ "screenshots/showcase.png"+ ],+ "scripts": {+ "install": "./install.sh",+ "uninstall": "./uninstall.sh"+ },+ "dependencies": {},+ "tags": [+ "deploy",+ "blue-green",+ "zero-downtime",+ "service-container",+ "nginx",+ "devops"+ ],+ "discovery_triggers": [+ "blue-green deploy",+ "zero downtime deploy",+ "my service is down while it updates",+ "zero failed requests",+ "hitless deploy",+ "add a /ready endpoint",+ "readiness probe for my service"+ ],+ "org": "adom",+ "discovery_pitch": "Use when a service container is down while it updates: deploys it with zero failed requests.",+ "sample_prompts": [+ {+ "label": "Make my service zero-downtime",+ "prompt": "my service is down for two minutes every time I push; set up adom-bluegreen on it"+ },+ {+ "label": "Add a /ready endpoint",+ "prompt": "add the adom-bluegreen /ready contract to this server, with an in-flight counter"+ },+ {+ "label": "Prove a deploy dropped nothing",+ "prompt": "run the adom-bluegreen probe while I push and tell me how many requests failed"+ }+ ],+ "hero": {+ "path": "docs/hero.png"+ }+}
screenshots/showcase.pngadded⋯ 1 unchanged line ⋯
scripts/install.pyadded+15@@ -0,0 +1,15 @@+#!/usr/bin/env python3+"""Install this package's skill (adom-bluegreen) into Claude and Codex homes."""+import argparse, json, os, shutil+from pathlib import Path+ROOT=Path(__file__).resolve().parents[1]+parser=argparse.ArgumentParser();parser.add_argument('--home',type=Path,help='Isolated home for validation');args=parser.parse_args()+home=args.home or Path.home()+codex=home/'.codex' if args.home else Path(os.environ.get('CODEX_HOME',str(home/'.codex')))+for destination in [home/'.claude/skills',codex/'skills']:+ for source in sorted((ROOT/'skills').iterdir()):+ if not (source/'SKILL.md').is_file():continue+ target=destination/source.name+ target.mkdir(parents=True,exist_ok=True)+ shutil.copytree(source,target,dirs_exist_ok=True)+ print(target)
scripts/uninstall.pyadded+16@@ -0,0 +1,16 @@+#!/usr/bin/env python3+"""Remove only unchanged files installed by this package; preserve local edits."""+import argparse,os+from pathlib import Path+root=Path(__file__).resolve().parents[1]+p=argparse.ArgumentParser();p.add_argument('--home',type=Path);args=p.parse_args()+home=args.home or Path.home();codex=home/'.codex' if args.home else Path(os.environ.get('CODEX_HOME',str(home/'.codex')))+for base in [home/'.claude/skills',codex/'skills']:+ for source in sorted((root/'skills').iterdir()):+ target=base/source.name+ for file in source.rglob('*'):+ out=target/file.relative_to(source)+ if file.is_file() and out.is_file() and out.read_bytes()==file.read_bytes():out.unlink()+ if target.exists():+ for d in sorted([p for p in target.rglob('*') if p.is_dir()]+[target],key=lambda p:len(p.parts),reverse=True):+ if not any(d.iterdir()):d.rmdir()
skills/adom-bluegreen/SKILL.mdadded+104@@ -0,0 +1,104 @@+---+name: adom-bluegreen+description: Zero-failed-request deploys for an Adom service container. nginx front door, blue and green slots as git worktrees, a flip only when the new build reports ready at the new commit, and the old slot stopped only after it has served every request it accepted. Use when a service restarts in place on every push (and is down while it warms), when someone asks for blue-green, zero downtime, rolling or hitless deploys, or when a service needs a /ready endpoint. Trigger words - blue-green, blue green deploy, zero downtime, zero failed requests, hitless deploy, service down while it updates, watchdog restart, /ready endpoint, readiness probe, drain in-flight requests, adom-bluegreen.+---++# adom-bluegreen++A service container that pulls `origin/main` and restarts in place is down for as long as the new+process takes to warm up. Component Ocean took 60-120 s to load its data, so every push was a+minute or two of outage for every caller. Ray, 2026-09-22: *"for anything production-dependent I+consider this unacceptable ... it has to be 0 failed requests."*++This kit is what took CO to zero. Measured on the live service: a cron-driven deploy had **0 failures+in 1,372 requests** and a manual one **0 in 2,365**. The kit's own self-test measured **0 in 5,709**+across a deploy and **0 in 7,659** while a broken build was refused.++## How it works++```+ public URL ──> :PUBLIC_PORT nginx (front door; reloads never drop a request)+ ├── :BLUE_PORT blue slot (git worktree at commit A)+ └── :GREEN_PORT green slot (git worktree at commit B)+```++Every 2 minutes cron runs `bluegreen.sh <service.conf>`. When `origin/BRANCH` has a new commit:++1. It is checked out and started in the **idle** slot, while the live slot keeps serving.+2. The front door flips only when the new slot's `/ready` answers **200 with that exact commit**.+ Anything else (it crashed, it never warmed, it runs the wrong commit) means no flip. The commit is+ recorded in `failed_sha` and never retried. The old slot keeps serving.+3. nginx reloads gracefully. New requests go to the new slot and requests already in progress+ finish where they are.+4. The old slot is stopped only once it has **finished every request it accepted** (its `/ready`+ reports `inflight` 0 for 5 s).++If the live slot dies while the other is warm, traffic fails over to it. The only remaining outage+is a true cold start (container restart), when nothing is running anyway.++## Adopting it on a service (about 15 minutes)++1. **Add the `/ready` contract** to the service. Copy the pattern from `examples/` (Bun, Node, Python):+ ```+ GET /ready -> 200 {"ready":true, "git_sha":"<$BLUEGREEN_SHA>", "inflight":<n>} when warm+ -> 503 {"ready":false, ...} while warming+ ```+ - Listen on `$PORT`; the kit sets it per slot.+ - `git_sha` echoes `$BLUEGREEN_SHA`; the kit sets it too, so the app never has to read `.git`.+ - `ready` must mean *everything* callers need is loaded, not just "the port is open". CO's first+ version flipped before its passive value index was attached, and value filters would have+ answered 503.+ - `inflight` counts requests in progress, excluding `/ready`. It's optional; without it the old+ slot gets a timed 90 s drain.+ - Push this first and let the old deploy mechanism ship it.+2. **Write the config** from `examples/service.conf.example` and keep it under `/home`: `NAME`,+ `REPO_DIR`, `BRANCH`, the three ports, `START_CMD` (one plain command, run in the slot directory),+ `INSTALL_CMD`, and `SHARED` (gitignored state such as `data`, symlinked into both slots).+3. **Stop the old auto-deploy** (its cron line or watchdog) so two deployers don't fight.+4. **Install:** `bash scripts/install.sh ~/my-service.conf`, adding `--boot-hook` on images whose+ entrypoint only starts sshd. It checks the config, installs nginx and schedules the watchdog.+5. **Adopt the port:**+ - If the service already listens on `PUBLIC_PORT`, set `LEGACY_STOP_CMD` to how to stop it.+ - The first pass warms a slot, stops the legacy process and starts nginx in its place.+ - That handoff is the **one moment** two processes would need the same port, so there is a gap of+ milliseconds. Do it during a container restart (nothing is listening then anyway) or at a quiet+ time. Every deploy after it is zero-failure.+6. **Prove it:** start `scripts/probe.sh http://127.0.0.1:PUBLIC_PORT/ 300 4` on the container, push a+ commit, and read the last line. It must say `0 failed`.++Check before you trust it on a new container: `bash tests/selftest.sh 3490` runs a real deploy of a+throwaway app on spare ports (cold start, deploy under load with slow requests, a never-ready build)+and must end `10 passed, 0 failed`. It touches nothing else.++## Operating it++| | |+|---|---|+| where traffic goes | `bash scripts/bluegreen.sh <conf> status`, or `curl :PUBLIC_PORT/__bluegreen` |+| is my push live? | `/__bluegreen` shows its sha, usually 2-4 min after the push |+| logs | `~/.bluegreen/<NAME>/bluegreen.log`, `blue.log`, `green.log`, `nginx-error.log` |+| a deploy failed | `~/.bluegreen/<NAME>/failed_sha`; read `<slot>.log`; push a fix (a new sha retries) |+| roll back | `git revert` and push: a rollback is just another zero-failure deploy |+| stop deploying | remove the cron line; both slots and nginx keep serving |++## Traps this kit already handles (do not reintroduce them)++- **Never `pkill -f`.** It matches the watchdog's own command line and kills both slots. Processes+ are found through `/proc` by working directory and exact command.+- **`$!` after `cd dir && cmd &` is a wrapper shell, not the server.** Killing it leaves the server+ holding its port, and the next deploy into that slot fails.+- **Every launched process must drop the lock fd** (`exec 9>&-` first in its subshell). A child that+ inherits it holds the lock for life, every later pass exits at `flock`, and deploys silently stop+ with no error anywhere. CO hit this twice.+- **`git reset` rewrites the running watchdog script** under bash, which reads it by offset. The+ script re-runs itself from a private copy first.+- **Never replace a front door that is serving.** Two processes cannot share a port, so any handoff+ is a gap. nginx changes its config by reload, keeping the socket. A new front door is adopted+ only at a cold start.+- **Don't name a bash array `PORT`.** Bash cannot export an array, so `export PORT=...` silently does+ nothing and the app starts without its port. The self-test caught this.+- **What the container cannot do:** there's no `NET_ADMIN` and `/proc/sys` is read-only, so there's+ no iptables and no `tcp_migrate_req`. The edge port mapping can be added or removed but never+ re-pointed. That is why the front door is a long-lived nginx on the mapped port.+- **nginx lives in `/usr`, which a container rebuild resets.** The watchdog reinstalls it at the next+ cold start. Keep the config and the service's state under `/home`.
skills/adom-bluegreen/examples/ready-bun.tsadded+23@@ -0,0 +1,23 @@+// The adom-bluegreen /ready contract in a Bun server. Copy the three marked parts.+// 200 {"ready":true,"git_sha":...,"inflight":n} once warm; 503 while warming. Port comes from PORT.+let warm = false; // (1) flip to true when startup work is done+let inflight = 0; // (2) requests in progress, for an exact drain+loadEverything().then(() => { warm = true; }); // e.g. open databases, fill caches++async function app(req: Request): Promise<Response> {+ return new Response('hello'); // your existing handler+}++Bun.serve({+ port: Number(process.env.PORT) || 3000,+ async fetch(req) {+ if (new URL(req.url).pathname === '/ready') { // (3) the contract; not counted as in flight+ return Response.json({ ready: warm, git_sha: process.env.BLUEGREEN_SHA ?? null, inflight },+ { status: warm ? 200 : 503, headers: { 'Cache-Control': 'no-store' } });+ }+ inflight++;+ try { return await app(req); } finally { inflight--; }+ },+});++async function loadEverything() { /* ... */ }
skills/adom-bluegreen/examples/ready-node.jsadded+18@@ -0,0 +1,18 @@+// The adom-bluegreen /ready contract in Node (plain http, or Express: see the bottom).+const http = require('node:http');+let warm = false, inflight = 0;+setImmediate(async () => { /* load databases, caches ... */ warm = true; });++const server = http.createServer((req, res) => {+ if (req.url === '/ready') {+ res.writeHead(warm ? 200 : 503, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });+ return res.end(JSON.stringify({ ready: warm, git_sha: process.env.BLUEGREEN_SHA || null, inflight }));+ }+ inflight++;+ res.on('close', () => { inflight--; }); // fires once the response is finished or aborted+ res.end('hello'); // your existing handler+});+server.listen(Number(process.env.PORT) || 3000);++// Express: app.get('/ready', ...same body...) registered FIRST, then+// app.use((req, res, next) => { inflight++; res.on('close', () => inflight--); next(); });
skills/adom-bluegreen/examples/ready-python.pyadded+38@@ -0,0 +1,38 @@+"""The adom-bluegreen /ready contract in Python (standard library; FastAPI at the bottom)."""+import json, os, threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++warm = False; inflight = 0; lock = threading.Lock()+def load_everything():+ global warm+ # ... open databases, fill caches ...+ warm = True+threading.Thread(target=load_everything, daemon=True).start()++class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ global inflight+ if self.path == '/ready':+ body = json.dumps({'ready': warm, 'git_sha': os.environ.get('BLUEGREEN_SHA'), 'inflight': inflight}).encode()+ self.send_response(200 if warm else 503); self.send_header('Content-Type', 'application/json')+ self.send_header('Cache-Control', 'no-store'); self.end_headers(); self.wfile.write(body); return+ with lock: inflight += 1+ try:+ self.send_response(200); self.end_headers(); self.wfile.write(b'hello') # your handler+ finally:+ with lock: inflight -= 1++ThreadingHTTPServer(('0.0.0.0', int(os.environ.get('PORT', 3000))), Handler).serve_forever()++# FastAPI:+# @app.get('/ready')+# def ready(response: Response):+# response.status_code = 200 if warm else 503+# return {'ready': warm, 'git_sha': os.environ.get('BLUEGREEN_SHA'), 'inflight': inflight}+# @app.middleware('http')+# async def count(request, call_next):+# global inflight+# if request.url.path == '/ready': return await call_next(request)+# inflight += 1+# try: return await call_next(request)+# finally: inflight -= 1
skills/adom-bluegreen/examples/service.conf.exampleadded+15@@ -0,0 +1,15 @@+# adom-bluegreen service config (a bash file). Keep it under /home: only /home survives a rebuild.+NAME=my-service # used for state paths and logs+REPO_DIR=$HOME/project # a git checkout of the service; the kit follows origin/BRANCH+BRANCH=main+PUBLIC_PORT=3456 # the port your container's public URL maps to+BLUE_PORT=3457+GREEN_PORT=3458+START_CMD="bun src/server.ts" # one plain command, run inside the slot directory+PORT_ENV=PORT # also export the slot port under this name (e.g. MY_APP_PORT)+INSTALL_CMD="bun install --frozen-lockfile" # run in each new slot before start; empty for none+SHARED="data" # space-separated paths in REPO_DIR (gitignored state) linked into each slot+READY_PATH=/ready+READY_TIMEOUT_S=480 # how long a new build may take to warm before it is failed+DRAIN_MAX_S=600 # cap on waiting for the old slot's in-flight requests+LEGACY_STOP_CMD="" # adopting a server already on PUBLIC_PORT: how to stop it (one time)
skills/adom-bluegreen/scripts/bluegreen.shadded+284@@ -0,0 +1,284 @@+#!/usr/bin/env bash+# adom-bluegreen: zero-failed-request deploys for a service container.+#+# bluegreen.sh <service.conf> one watchdog pass (cron runs it every 2 minutes)+# bluegreen.sh <service.conf> status where traffic goes, which sha each slot runs+#+# Layout for a service NAME:+# :PUBLIC_PORT nginx, the front door. `nginx -s reload` keeps the listening socket and lets old+# workers finish their requests, so a flip never drops one. Never restarted while+# it serves.+# :BLUE_PORT blue slot ($SLOTS_DIR/blue, a detached git worktree of REPO_DIR)+# :GREEN_PORT green slot ($SLOTS_DIR/green)+# $STATE_DIR/active.json the live slot; also served at GET /__bluegreen+#+# A pass, in order:+# 1. REPO_DIR follows origin/BRANCH (this script runs from a private copy, so the reset cannot+# rewrite it mid-run).+# 2. Front door: nginx on PUBLIC_PORT, started only when nothing listens there (a cold start).+# A legacy process on the port is adopted once, after a slot is warm (LEGACY_STOP_CMD).+# 3. The live slot answers; if it died and the other slot is warm, fail over to it.+# 4. Deploy: a new commit on origin/BRANCH is started in the IDLE slot. The front door flips only+# when READY_PATH answers 200 with that exact sha. The old slot is stopped only once it has+# finished every request it accepted (READY_PATH's "inflight" at 0 for 5 s). A build that never+# gets ready is recorded in failed_sha and never served; the old slot keeps serving.+#+# The /ready contract (see examples/): GET READY_PATH ->+# 200 {"ready":true, "git_sha":"<BLUEGREEN_SHA>", "inflight":<n>} when warm+# 503 {"ready":false, ...} while warming+# The kit starts each slot with BLUEGREEN_SHA=<commit> and PORT=<slot port> in the environment.+# "inflight" is optional; without it the old slot gets a timed drain (DRAIN_FALLBACK_S).+#+# Lessons this script encodes (Component Ocean, 2026-09-22):+# - Never `pkill -f`: processes are found through /proc by working directory + exact command.+# - `$!` after `cd dir && cmd &` is a wrapper shell, not the server.+# - Every launched child drops the lock fd FIRST (`exec 9>&-` in its subshell). A child that keeps+# it holds the lock for life, every later pass exits at flock, and deploys silently stop.++set -uo pipefail+CONF="${1:?usage: bluegreen.sh <service.conf> [status]}"+CONF=$(readlink -f "$CONF")+if [ -z "${BLUEGREEN_COPY:-}" ]; then+ _copy=$(mktemp /tmp/bluegreen.XXXXXX.sh) && cp "$0" "$_copy" && BLUEGREEN_COPY=1 exec bash "$_copy" "$CONF" "${@:2}"+fi+trap 'rm -f "$0"' EXIT+set -a; [ -f /etc/environment ] && . /etc/environment; set +a+export PATH="$HOME/.bun/bin:$HOME/.local/bin:/usr/local/bin:/usr/sbin:/usr/bin:/bin:$PATH"++# ── configuration ────────────────────────────────────────────────────────────+NAME="" REPO_DIR="" BRANCH=main PUBLIC_PORT="" BLUE_PORT="" GREEN_PORT="" START_CMD="" PORT_ENV=PORT+INSTALL_CMD="" SHARED="" READY_PATH=/ready READY_TIMEOUT_S=480 DRAIN_MAX_S=600 DRAIN_FALLBACK_S=90+LEGACY_STOP_CMD="" STATE_DIR="" SLOTS_DIR="" CLIENT_MAX_BODY=64m PROXY_TIMEOUT_S=600+# shellcheck disable=SC1090+. "$CONF"+for v in NAME REPO_DIR PUBLIC_PORT BLUE_PORT GREEN_PORT START_CMD; do+ [ -n "${!v}" ] || { echo "bluegreen: $v is not set in $CONF" >&2; exit 2; }+done+STATE_DIR="${STATE_DIR:-$HOME/.bluegreen/$NAME}"+SLOTS_DIR="${SLOTS_DIR:-$HOME/bluegreen-slots/$NAME}"+STATE="$STATE_DIR/active.json"+NGX="$STATE_DIR/nginx"+LOG="$STATE_DIR/bluegreen.log"+# Not named PORT: bash cannot export an array, and `export PORT=<slot port>` below would silently+# do nothing if PORT were this array (the slot then started without its port).+declare -A SLOT_PORT=([blue]="$BLUE_PORT" [green]="$GREEN_PORT")+mkdir -p "$STATE_DIR" "$SLOTS_DIR"++say() { echo "[$(date -Iseconds)] $NAME: $*" >> "$LOG"; }+other_of() { [ "$1" = blue ] && echo green || echo blue; }++# ── probes ───────────────────────────────────────────────────────────────────+ready_json() { curl -s --max-time 5 "http://127.0.0.1:$1$READY_PATH" 2>/dev/null; }+code_of() { curl -s -o /dev/null --max-time 5 -w '%{http_code}' "http://127.0.0.1:$1$READY_PATH" 2>/dev/null; }+answers() { local c; c=$(code_of "$1"); [ -n "$c" ] && [ "$c" != 000 ]; }+is_ready() { [ "$(code_of "$1")" = 200 ]; }+sha_on() { ready_json "$1" | sed -n 's/.*"git_sha" *: *"\([0-9a-f]*\)".*/\1/p'; }+inflight_on() { ready_json "$1" | sed -n 's/.*"inflight" *: *\([0-9]*\).*/\1/p'; }+front_up() { curl -s --max-time 3 "http://127.0.0.1:$PUBLIC_PORT/__bluegreen" 2>/dev/null | grep -q '"slot"'; }+port_taken() { curl -s -o /dev/null --max-time 3 "http://127.0.0.1:$PUBLIC_PORT/" 2>/dev/null; }++active_slot() { local a; a=$(sed -n 's/.*"slot":"\([a-z]*\)".*/\1/p' "$STATE" 2>/dev/null); case "$a" in blue|green) echo "$a" ;; *) echo blue ;; esac; }++# ── processes: /proc, never pid files or pkill ───────────────────────────────+procs() { # dir command-prefix -> pids whose cwd is dir and whose command line starts with the prefix+ local want p; want=$(readlink -f "$1")+ for p in /proc/[0-9]*; do+ [ "$(readlink "$p/cwd" 2>/dev/null)" = "$want" ] || continue+ case "$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null)" in "$2"*) echo "${p#/proc/}" ;; esac+ done+}+slot_running() { [ -n "$(procs "$SLOTS_DIR/$1" "$START_CMD")" ]; }+stop_slot() {+ local pids p; pids=$(procs "$SLOTS_DIR/$1" "$START_CMD"); [ -z "$pids" ] && return 0+ kill $pids 2>/dev/null+ for _ in $(seq 1 15); do slot_running "$1" || return 0; sleep 1; done+ for p in $(procs "$SLOTS_DIR/$1" "$START_CMD"); do kill -9 "$p" 2>/dev/null; done+}++# ── nginx front door ─────────────────────────────────────────────────────────+nginx_running() { local p; p=$(cat "$NGX/nginx.pid" 2>/dev/null); [ -n "$p" ] && tr '\0' ' ' < "/proc/$p/cmdline" 2>/dev/null | grep -q '^nginx: master'; }+write_upstream() { # live slot first; the other as backup, so a refused connection is retried there+ local o; o=$(other_of "$1"); mkdir -p "$NGX"+ printf 'upstream bluegreen_live {\n server 127.0.0.1:%s max_fails=0;\n server 127.0.0.1:%s backup max_fails=0;\n keepalive 32;\n}\n' \+ "${SLOT_PORT[$1]}" "${SLOT_PORT[$o]}" > "$NGX/upstream.conf.tmp" && mv "$NGX/upstream.conf.tmp" "$NGX/upstream.conf"+}+write_nginx_conf() {+ mkdir -p "$NGX/tmp"+ cat > "$NGX/nginx.conf" <<NGINX+# Generated by adom-bluegreen for $NAME. Edits are overwritten on the next cold start.+worker_processes 2;+pid $NGX/nginx.pid;+error_log $STATE_DIR/nginx-error.log warn;+worker_shutdown_timeout ${PROXY_TIMEOUT_S}s; # on a reload, old workers finish what they hold+events { worker_connections 1000; }+http {+ access_log off;+ client_body_temp_path $NGX/tmp/body; proxy_temp_path $NGX/tmp/proxy;+ fastcgi_temp_path $NGX/tmp/fcgi; uwsgi_temp_path $NGX/tmp/uwsgi; scgi_temp_path $NGX/tmp/scgi;+ include $NGX/upstream.conf;+ server {+ listen $PUBLIC_PORT;+ client_max_body_size $CLIENT_MAX_BODY;+ location = /__bluegreen { default_type application/json; add_header Cache-Control no-store; alias $STATE; }+ location / {+ proxy_pass http://bluegreen_live;+ proxy_http_version 1.1;+ proxy_set_header Connection "";+ proxy_set_header Host \$http_host;+ proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto \$scheme;+ proxy_connect_timeout 2s;+ proxy_read_timeout ${PROXY_TIMEOUT_S}s;+ proxy_send_timeout ${PROXY_TIMEOUT_S}s;+ proxy_buffering off;+ # Only a connection failure is retried (on the backup slot), never an answer.+ proxy_next_upstream error timeout;+ proxy_next_upstream_tries 2;+ }+ }+}+NGINX+}+ensure_nginx() {+ command -v nginx >/dev/null 2>&1 && return 0+ # nginx lives in /usr, which a container rebuild resets. This only runs at a cold start.+ say "nginx missing: installing"+ ( exec 9>&-; sudo -n apt-get install -y -qq nginx-light >> "$LOG" 2>&1 || { sudo -n apt-get update -qq >> "$LOG" 2>&1; sudo -n apt-get install -y -qq nginx-light >> "$LOG" 2>&1 || sudo -n apt-get install -y -qq nginx >> "$LOG" 2>&1; } )+ command -v nginx >/dev/null 2>&1+}+start_front() {+ ensure_nginx || { say "cannot install nginx; no front door"; return 1; }+ write_nginx_conf; write_upstream "$(active_slot)"+ ( exec 9>&-; nginx -p "$NGX" -c "$NGX/nginx.conf" >> "$LOG" 2>&1 )+ for _ in $(seq 1 20); do front_up && break; sleep 0.25; done+ front_up && say "front door: nginx on :$PUBLIC_PORT" || { say "nginx did not come up (see $STATE_DIR/nginx-error.log)"; return 1; }+}+set_active() { # slot sha+ printf '{"slot":"%s","port":%s,"sha":"%s","since":"%s"}\n' "$1" "${SLOT_PORT[$1]}" "$2" "$(date -Iseconds)" > "$STATE.tmp" && mv "$STATE.tmp" "$STATE"+ write_upstream "$1"+ if nginx_running; then ( exec 9>&-; nginx -p "$NGX" -c "$NGX/nginx.conf" -s reload >> "$LOG" 2>&1 ) || say "nginx reload FAILED"; fi+ say "live -> $1 (:${SLOT_PORT[$1]}) at ${2:0:12}"+}++# ── slots ────────────────────────────────────────────────────────────────────+start_slot() { # slot sha: build the worktree at sha and launch; does not wait+ local slot=$1 sha=$2 dir="$SLOTS_DIR/$1" s+ stop_slot "$slot"+ if [ ! -e "$dir/.git" ]; then+ git -C "$REPO_DIR" worktree prune >> "$LOG" 2>&1+ git -C "$REPO_DIR" worktree add --detach "$dir" "$sha" >> "$LOG" 2>&1 || { say "worktree add $slot failed"; return 1; }+ else+ git -C "$dir" checkout -q --detach --force "$sha" >> "$LOG" 2>&1 || { say "checkout $slot at $sha failed"; return 1; }+ fi+ for s in $SHARED; do [ -e "$dir/$s" ] || ln -s "$REPO_DIR/$s" "$dir/$s"; done+ if [ -n "$INSTALL_CMD" ]; then ( exec 9>&-; cd "$dir" && bash -c "$INSTALL_CMD" >> "$LOG" 2>&1 ) || { say "install failed in $slot"; return 1; }; fi+ ( exec 9>&-; cd "$dir" && export BLUEGREEN_SHA="$sha" PORT="${SLOT_PORT[$slot]}" "$PORT_ENV=${SLOT_PORT[$slot]}" && \+ setsid nohup bash -c "exec $START_CMD" >> "$STATE_DIR/$slot.log" 2>&1 < /dev/null & )+ say "started $slot (:${SLOT_PORT[$slot]}) at ${sha:0:12}"+}+wait_ready() { # slot sha: until READY_PATH says 200 at exactly this sha+ local t=0 got+ while [ "$t" -lt "$READY_TIMEOUT_S" ]; do+ if is_ready "${SLOT_PORT[$1]}"; then+ got=$(sha_on "${SLOT_PORT[$1]}")+ [ "$got" = "$2" ] && return 0+ [ -z "$got" ] && { say "$1 is ready but $READY_PATH has no git_sha: return BLUEGREEN_SHA there (see examples/)"; return 1; }+ [ "$got" != "$2" ] && { say "$1 is ready but reports ${got:0:12}, not ${2:0:12} (is BLUEGREEN_SHA wired into $READY_PATH?)"; return 1; }+ fi+ sleep 2+ slot_running "$1" || { say "$1 exited while warming (see $STATE_DIR/$1.log)"; return 1; }+ sleep 3; t=$((t + 5))+ done+ say "$1 not ready after ${READY_TIMEOUT_S}s"; return 1+}+drain() { # slot: until it has served every request it accepted+ local t=0 zero=0 n+ sleep 3+ while [ "$t" -lt "$DRAIN_MAX_S" ]; do+ n=$(inflight_on "${SLOT_PORT[$1]}")+ if [ -z "$n" ]; then+ answers "${SLOT_PORT[$1]}" || return 0+ say "$1 does not report inflight: timed drain of ${DRAIN_FALLBACK_S}s"; sleep "$DRAIN_FALLBACK_S"; return 0+ fi+ if [ "$n" = 0 ]; then zero=$((zero + 1)); [ "$zero" -ge 5 ] && { say "$1 drained after ${t}s"; return 0; }; else zero=0; fi+ sleep 1; t=$((t + 1))+ done+ say "$1 still had $(inflight_on "${SLOT_PORT[$1]}") in flight after ${DRAIN_MAX_S}s; stopping it anyway"+}++# ── status ───────────────────────────────────────────────────────────────────+if [ "${2:-}" = status ]; then+ echo "$NAME: front door :$PUBLIC_PORT $(front_up && echo up || echo DOWN)$(nginx_running && echo ' (nginx)')"+ echo " live: $(cat "$STATE" 2>/dev/null || echo none)"+ for s in blue green; do echo " $s :${SLOT_PORT[$s]} $(slot_running "$s" && echo running || echo stopped) ready=$(code_of "${SLOT_PORT[$s]}") sha=$(sha_on "${SLOT_PORT[$s]}" | cut -c1-12) inflight=$(inflight_on "${SLOT_PORT[$s]}")"; done+ [ -f "$STATE_DIR/failed_sha" ] && echo " failed_sha: $(cat "$STATE_DIR/failed_sha")"+ exit 0+fi++exec 9>"$STATE_DIR/bluegreen.lock"+flock -n 9 || exit 0++# ── 1. REPO_DIR follows origin/BRANCH ────────────────────────────────────────+remote=""+if git -C "$REPO_DIR" fetch --quiet origin "$BRANCH" 2>/dev/null; then+ remote=$(git -C "$REPO_DIR" rev-parse "origin/$BRANCH" 2>/dev/null)+ [ -n "$remote" ] && [ "$(git -C "$REPO_DIR" rev-parse HEAD)" != "$remote" ] && git -C "$REPO_DIR" reset -q --hard "$remote" >> "$LOG" 2>&1+fi+[ -z "$remote" ] && remote=$(git -C "$REPO_DIR" rev-parse HEAD)++A=$(active_slot); B=$(other_of "$A")+# A fresh install has no state yet. Write it before anything else: the front door's own health check+# (/__bluegreen) serves this file, and without it a running nginx looks like a stranger on the port.+[ -f "$STATE" ] || printf '{"slot":"%s","port":%s,"sha":"","since":"%s"}\n' "$A" "${SLOT_PORT[$A]}" "$(date -Iseconds)" > "$STATE"++# ── 2. Front door ────────────────────────────────────────────────────────────+if ! front_up; then+ if nginx_running; then say "our nginx runs but /__bluegreen does not answer; restarting it"; ( exec 9>&-; nginx -p "$NGX" -c "$NGX/nginx.conf" -s quit >> "$LOG" 2>&1 ); sleep 1; fi+ if port_taken; then+ # A legacy server holds the port: adopt it ONCE. Warm a slot first so the handoff is only the+ # instant between LEGACY_STOP_CMD and nginx's bind; do it at a quiet time, or during a restart.+ [ -n "$LEGACY_STOP_CMD" ] || { say "something that is not the front door holds :$PUBLIC_PORT; set LEGACY_STOP_CMD to adopt it"; exit 0; }+ if ! is_ready "${SLOT_PORT[$A]}"; then start_slot "$A" "$remote" && wait_ready "$A" "$remote" || { say "adoption: $A never got ready; legacy left serving"; stop_slot "$A"; exit 0; }; fi+ set_active "$A" "$(sha_on "${SLOT_PORT[$A]}")"+ ensure_nginx && write_nginx_conf && write_upstream "$A" || exit 0+ say "adopting :$PUBLIC_PORT from the legacy server"+ ( exec 9>&-; bash -c "$LEGACY_STOP_CMD" >> "$LOG" 2>&1 )+ for _ in $(seq 1 200); do port_taken || break; sleep 0.02; done+ ( exec 9>&-; nginx -p "$NGX" -c "$NGX/nginx.conf" >> "$LOG" 2>&1 )+ front_up && say "adopted: nginx on :$PUBLIC_PORT -> $A" || say "adoption: nginx did not come up"+ exit 0+ fi+ start_front || exit 0+fi++# ── 3. The live slot answers ─────────────────────────────────────────────────+if ! answers "${SLOT_PORT[$A]}"; then+ if is_ready "${SLOT_PORT[$B]}"; then+ say "$A is not answering and $B is warm: failing over"+ set_active "$B" "$(sha_on "${SLOT_PORT[$B]}")"; A=$B; B=$(other_of "$A")+ elif ! slot_running "$A"; then+ say "$A is down and $B is not warm: cold start of $A"+ start_slot "$A" "$remote" && set_active "$A" "$remote"+ exit 0+ else+ exit 0 # alive but not answering yet: still warming+ fi+fi++# ── 4. Deploy origin/BRANCH through the idle slot ────────────────────────────+cur=$(sha_on "${SLOT_PORT[$A]}")+if is_ready "${SLOT_PORT[$A]}" && [ -n "$remote" ] && [ "$cur" != "$remote" ] && [ "$(cat "$STATE_DIR/failed_sha" 2>/dev/null)" != "$remote" ]; then+ say "deploy ${cur:0:12} -> ${remote:0:12} via $B"+ if start_slot "$B" "$remote" && wait_ready "$B" "$remote"; then+ set_active "$B" "$remote"+ say "flipped to $B; draining $A"+ drain "$A"+ stop_slot "$A"+ say "deploy done: $B at ${remote:0:12}"+ else+ echo "$remote" > "$STATE_DIR/failed_sha"+ stop_slot "$B"+ say "deploy of ${remote:0:12} FAILED; $A keeps serving ${cur:0:12}. Push a fix to retry."+ fi+fi+exit 0
skills/adom-bluegreen/scripts/boot-hook.shadded+46@@ -0,0 +1,46 @@+#!/usr/bin/env bash+# Make sshd start cron at container boot. Some Adom service images (default-light) run only+# `sshd -D` as their entrypoint: no systemd, no init, so a restart comes back with no cron, no+# watchdog and no service. sshd is the one thing that starts, so it becomes the hook: /usr/sbin/sshd+# is replaced by a script that starts cron and execs the original (kept as sshd.real).+# Traps: never cp over a running binary (ETXTBSY; use mv); sshd re-execs itself per connection, so+# the wrapper must exec sshd.real with "$@" untouched; every failure is swallowed, since SSH is the+# only way into the container. Origin: Component Ocean service/install-boot-hook.sh.+set -uo pipefail++log() { echo "[$(date -Iseconds)] boot-hook: $*"; }++# Already installed? A shebang on the first line means it is our wrapper.+if head -1 /usr/sbin/sshd 2>/dev/null | grep -q '^#!'; then+ exit 0+fi++sudo -n true 2>/dev/null || { log "no passwordless sudo — cannot install"; exit 0; }++# Whatever is at /usr/sbin/sshd right now must be a working sshd before we move+# it aside and start depending on it.+if ! sudo /usr/sbin/sshd -t >/dev/null 2>&1; then+ log "current /usr/sbin/sshd fails its own config test — refusing to touch it"+ exit 0+fi++log "installing (sshd is not wrapped — first run, or a package update reverted it)"++# rename, not copy: the running daemon holds this inode open.+sudo mv /usr/sbin/sshd /usr/sbin/sshd.real || { log "could not move sshd aside"; exit 0; }++sudo tee /usr/sbin/sshd.wrap >/dev/null <<'HOOK'+#!/bin/sh+/etc/init.d/cron start >/dev/null 2>&1 || true+exec /usr/sbin/sshd.real "$@"+HOOK+sudo chmod 755 /usr/sbin/sshd.wrap++if ! sudo mv /usr/sbin/sshd.wrap /usr/sbin/sshd; then+ # Never leave the container without an sshd at the path the entrypoint uses.+ log "install failed — restoring original"+ sudo mv /usr/sbin/sshd.real /usr/sbin/sshd+ exit 0+fi++log "installed; original preserved at /usr/sbin/sshd.real"
skills/adom-bluegreen/scripts/install.shadded+37@@ -0,0 +1,37 @@+#!/usr/bin/env bash+# adom-bluegreen installer: check a service config, install nginx, schedule the watchdog.+# install.sh <service.conf> [--boot-hook]+# --boot-hook make sshd start cron at container boot (for images whose entrypoint starts only sshd;+# without cron after a restart nothing brings the service back).+# Idempotent. Changes nothing a running service depends on: the first watchdog pass does the work.+set -uo pipefail+CONF=$(readlink -f "${1:?usage: install.sh <service.conf> [--boot-hook]}")+HERE=$(cd "$(dirname "$0")" && pwd)+ok() { printf ' \033[32mok\033[0m %s\n' "$*"; }; bad() { printf ' \033[31mFAIL\033[0m %s\n' "$*"; FAILED=1; }; FAILED=0+NAME="" REPO_DIR="" BRANCH=main PUBLIC_PORT="" BLUE_PORT="" GREEN_PORT="" START_CMD="" READY_PATH=/ready+. "$CONF"+echo "adom-bluegreen: checking $CONF"+for v in NAME REPO_DIR PUBLIC_PORT BLUE_PORT GREEN_PORT START_CMD; do [ -n "${!v}" ] && ok "$v=${!v}" || bad "$v is not set"; done+case "$REPO_DIR" in /home/*) ;; *) bad "REPO_DIR must live under /home (only /home survives a container rebuild)";; esac+git -C "$REPO_DIR" rev-parse --git-dir >/dev/null 2>&1 && ok "REPO_DIR is a git checkout" || bad "REPO_DIR is not a git checkout"+git -C "$REPO_DIR" fetch --quiet origin "$BRANCH" 2>/dev/null && ok "origin/$BRANCH fetches" || bad "cannot fetch origin/$BRANCH"+[ "$PUBLIC_PORT" != "$BLUE_PORT" ] && [ "$PUBLIC_PORT" != "$GREEN_PORT" ] && [ "$BLUE_PORT" != "$GREEN_PORT" ] && ok "three distinct ports" || bad "PUBLIC/BLUE/GREEN ports must differ"+for p in "$BLUE_PORT" "$GREEN_PORT"; do curl -s -o /dev/null --max-time 2 "http://127.0.0.1:$p/" && bad "port $p is already in use"; done+case "$START_CMD" in *\"*|*\'*|*\;*|*\&*|*\|*) bad "START_CMD must be one plain command (no quotes, ;, &, |): it is matched in /proc";; *) ok "START_CMD is a plain command";; esac+for t in curl flock git sed; do command -v $t >/dev/null && ok "$t" || bad "$t missing"; done+if ! command -v nginx >/dev/null; then+ sudo -n apt-get install -y -qq nginx-light >/dev/null 2>&1 || { sudo -n apt-get update -qq >/dev/null 2>&1; sudo -n apt-get install -y -qq nginx-light >/dev/null 2>&1 || sudo -n apt-get install -y -qq nginx >/dev/null 2>&1; }+fi+command -v nginx >/dev/null && ok "nginx $(nginx -v 2>&1 | sed 's/.*\///')" || bad "nginx could not be installed (needs passwordless sudo + apt)"+[ "$FAILED" = 0 ] || { echo "not installed: fix the FAIL lines"; exit 1; }++if [ "${2:-}" = --boot-hook ]; then bash "$HERE/boot-hook.sh" && ok "sshd starts cron at boot"; fi+pgrep -x cron >/dev/null || sudo -n service cron start >/dev/null 2>&1 || true+pgrep -x cron >/dev/null && ok "cron daemon running" || bad "cron is not running: the watchdog will never fire"+LINE="*/2 * * * * bash $HERE/bluegreen.sh $CONF >/dev/null 2>&1"+( crontab -l 2>/dev/null | grep -vF "bluegreen.sh $CONF"; echo "$LINE" ) | crontab -+ok "cron: every 2 min -> bluegreen.sh $CONF"+echo+echo "Next: make $READY_PATH answer the contract (examples/), push it, and watch:"+echo " bash $HERE/bluegreen.sh $CONF status # front door, slots, shas, inflight"+echo " bash $HERE/probe.sh http://127.0.0.1:$PUBLIC_PORT/ 300 4 # during a deploy: must end with 0 failed"
skills/adom-bluegreen/scripts/probe.shadded+16@@ -0,0 +1,16 @@+#!/usr/bin/env bash+# Prove a deploy dropped nothing: N clients hammer URL for S seconds and report every non-2xx/3xx.+# probe.sh <url> [seconds=300] [clients=4]+# Run it on the container (127.0.0.1), start it, push your change, and read the last line.+URL=${1:?usage: probe.sh <url> [seconds] [clients]}; SECS=${2:-300}; N=${3:-4}+D=$(mktemp -d); end=$(( $(date +%s) + SECS ))+for k in $(seq 1 "$N"); do (+ ok=0; bad=0+ while [ "$(date +%s)" -lt "$end" ]; do+ c=$(curl -s -o /dev/null --max-time 60 -w '%{http_code}' "$URL")+ case "$c" in 2??|3??) ok=$((ok+1)) ;; *) bad=$((bad+1)); echo "$(date +%T.%N | cut -c1-12) client$k HTTP $c" >> "$D/fail" ;; esac+ done; echo "$ok $bad" > "$D/$k" ) & done+wait+ok=0; bad=0; for k in $(seq 1 "$N"); do read -r a b < "$D/$k"; ok=$((ok+a)); bad=$((bad+b)); done+[ -f "$D/fail" ] && head -20 "$D/fail"+echo "probe: $ok ok, $bad failed ($N clients, ${SECS}s, $URL)"; rm -rf "$D"; [ "$bad" = 0 ]
skills/adom-bluegreen/tests/selftest.shadded+113@@ -0,0 +1,113 @@+#!/usr/bin/env bash+# adom-bluegreen self-test: a real zero-failed-request deploy on THIS container, on spare ports.+# tests/selftest.sh [public_port=3490] (uses public, public+1, public+2; needs nginx, python3, git)+# Stands up a throwaway app with its own git remote, then:+# 1. cold start: nothing -> nginx + a warm slot;+# 2. deploy v2 under 4 probe clients and a stream of 3-second requests: 0 failed, the slow+# requests that were in flight on the old slot all finish (exact drain), traffic ends on v2;+# 3. deploy a build that never gets ready: never served, recorded as failed_sha, 0 failed.+# Touches nothing outside its own temp dirs and ports; the crontab is not modified.+set -uo pipefail+HERE=$(cd "$(dirname "$0")/.." && pwd); BG="$HERE/scripts/bluegreen.sh"+P=${1:-3490}; T="$HOME/.bluegreen-selftest.$$"; mkdir -p "$T"+pass=0; fail=0; ok() { echo " PASS $*"; pass=$((pass+1)); }; no() { echo " FAIL $*"; fail=$((fail+1)); }+for p in $P $((P+1)) $((P+2)); do curl -s -o /dev/null --max-time 2 "http://127.0.0.1:$p/" && { echo "port $p is in use; pick another base port"; exit 2; }; done++cleanup() {+ [ -f "$T/state/nginx/nginx.pid" ] && nginx -p "$T/state/nginx" -c "$T/state/nginx/nginx.conf" -s quit 2>/dev/null+ for p in /proc/[0-9]*; do case "$(readlink "$p/cwd" 2>/dev/null)" in "$T"/slots/*) kill "${p#/proc/}" 2>/dev/null ;; esac; done+ sleep 1; rm -rf "$T"+}+trap cleanup EXIT++# ── the throwaway app ───────────────────────────────────────────────────────+git init -q --bare "$T/origin.git"+git clone -q "$T/origin.git" "$T/work" 2>/dev/null+cat > "$T/work/app.py" <<'PY'+import json, os, threading, time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+VERSION = open('VERSION').read().strip()+if VERSION == 'broken':+ time.sleep(3600) # a build that never gets ready (and never listens)+warm = False; inflight = 0; lock = threading.Lock()+def load():+ global warm+ time.sleep(4); warm = True # a warm-up, like a real service loading its data+threading.Thread(target=load, daemon=True).start()+class H(BaseHTTPRequestHandler):+ def log_message(self, *a): pass+ def do_GET(self):+ global inflight+ if self.path == '/ready':+ b = json.dumps({'ready': warm, 'git_sha': os.environ.get('BLUEGREEN_SHA'), 'inflight': inflight}).encode()+ self.send_response(200 if warm else 503); self.send_header('Content-Type', 'application/json'); self.end_headers(); self.wfile.write(b); return+ with lock: inflight += 1+ try:+ if self.path == '/slow': time.sleep(3)+ self.send_response(200); self.end_headers(); self.wfile.write(VERSION.encode())+ finally:+ with lock: inflight -= 1+ThreadingHTTPServer(('127.0.0.1', int(os.environ['PORT'])), H).serve_forever()+PY+echo v1 > "$T/work/VERSION"+commit() { echo "$1" > "$T/work/VERSION"; git -C "$T/work" add -A; git -C "$T/work" -c user.email=t@t -c user.name=t commit -qm "$1"; git -C "$T/work" push -q origin HEAD:main 2>/dev/null; git -C "$T/work" rev-parse HEAD; }+v1=$(commit v1)+git clone -q -b main "$T/origin.git" "$T/repo" 2>/dev/null+cat > "$T/svc.conf" <<CONF+NAME=selftest+REPO_DIR=$T/repo+BRANCH=main+PUBLIC_PORT=$P+BLUE_PORT=$((P+1))+GREEN_PORT=$((P+2))+START_CMD="python3 app.py"+STATE_DIR=$T/state+SLOTS_DIR=$T/slots+READY_TIMEOUT_S=40+CONF+run_pass() { bash "$BG" "$T/svc.conf"; }+body() { curl -s --max-time 10 "http://127.0.0.1:$P/"; }++echo "adom-bluegreen self-test on :$P (temp $T)"+# ── 1. cold start ───────────────────────────────────────────────────────────+for _ in 1 2 3 4 5 6 7 8 9 10; do run_pass; [ "$(body)" = v1 ] && break; sleep 2; done+[ "$(body)" = v1 ] && ok "cold start serves v1 through nginx" || no "cold start: front door answered '$(body)'"+curl -s "http://127.0.0.1:$P/__bluegreen" | grep -q '"slot"' && ok "/__bluegreen reports the live slot" || no "/__bluegreen"++# ── 2. deploy v2 under load ─────────────────────────────────────────────────+probe_out=$(mktemp); slow_out=$(mktemp)+bash "$HERE/scripts/probe.sh" "http://127.0.0.1:$P/" 45 4 > "$probe_out" 2>&1 &+PROBE=$!+( s_ok=0; s_bad=0; end=$(( $(date +%s) + 40 ))+ while [ "$(date +%s)" -lt "$end" ]; do c=$(curl -s -o /dev/null --max-time 30 -w '%{http_code}' "http://127.0.0.1:$P/slow"); [ "$c" = 200 ] && s_ok=$((s_ok+1)) || s_bad=$((s_bad+1)); done+ echo "$s_ok $s_bad" > "$slow_out" ) &+SLOW=$!+sleep 3+v2=$(commit v2)+run_pass+[ "$(body)" = v2 ] && ok "deploy flipped traffic to v2" || no "after deploy the front door answers '$(body)'"+grep -q "drained after" "$T/state/bluegreen.log" && ok "old slot drained by its in-flight count ($(grep -o 'drained after [0-9]*s' "$T/state/bluegreen.log" | tail -1))" || no "no exact drain in the log"+wait "$PROBE" "$SLOW"+tail -1 "$probe_out" | grep -q ', 0 failed' && ok "$(tail -1 "$probe_out")" || { no "$(tail -1 "$probe_out")"; cat "$probe_out"; }+read -r so sb < "$slow_out"; [ "$sb" = 0 ] && [ "$so" -gt 0 ] && ok "slow requests across the flip: $so ok, $sb failed" || no "slow requests: $so ok, $sb failed"++# ── 3. a build that never gets ready ────────────────────────────────────────+bash "$HERE/scripts/probe.sh" "http://127.0.0.1:$P/" 55 2 > "$probe_out" 2>&1 &+PROBE=$!+v3=$(commit broken)+run_pass+[ "$(cat "$T/state/failed_sha" 2>/dev/null)" = "$v3" ] && ok "never-ready build recorded as failed_sha" || no "failed_sha is '$(cat "$T/state/failed_sha" 2>/dev/null)'"+[ "$(body)" = v2 ] && ok "v2 kept serving" || no "front door answers '$(body)' after the failed deploy"+run_pass # a second pass must not retry the failed sha+[ "$(grep -c "deploy .* -> ${v3:0:12}" "$T/state/bluegreen.log")" = 1 ] && ok "failed sha is not retried" || no "failed sha was retried"+wait "$PROBE"+tail -1 "$probe_out" | grep -q ', 0 failed' && ok "$(tail -1 "$probe_out")" || { no "$(tail -1 "$probe_out")"; cat "$probe_out"; }++rm -f "$probe_out" "$slow_out"+if [ "$fail" != 0 ]; then+ echo "--- watchdog log"; tail -25 "$T/state/bluegreen.log" 2>/dev/null+ for s in blue green; do echo "--- $s log"; tail -8 "$T/state/$s.log" 2>/dev/null; done+ echo "--- nginx"; tail -5 "$T/state/nginx-error.log" 2>/dev/null+fi+echo "self-test: $pass passed, $fail failed"+[ "$fail" = 0 ]
uninstall.shadded+4@@ -0,0 +1,4 @@+#!/bin/sh+set -eu+SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+exec python3 "$SCRIPT_DIR/scripts/uninstall.py" "$@"