From 7f72774fa9a4d656dd818a15b283d190a005de11 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 02:32:41 +0100 Subject: [PATCH 01/11] test: a runner host mails its tenant through the relay of its vault's item mail-relay (PLX-253) A newborn of its own, beside runner-host.test.ts, with a stand-in relay on the host's loopback that takes STARTTLS and AUTH and records what it is handed, and a forge that refuses mintings when told: a host without the item is set up and says so in its journal; with it, one mail per failed unit and for a disk over the housekeeping's threshold, none for one failed minting, one saying for how long for a slot that cannot mint past the threshold, no SMTP port on the loopback the slots share, and a refusing relay said in the journal. Co-Authored-By: Claude Opus --- newborns/runner-host-mail.test.ts | 509 ++++++++++++++++++++++++++++++ 1 file changed, 509 insertions(+) create mode 100644 newborns/runner-host-mail.test.ts diff --git a/newborns/runner-host-mail.test.ts b/newborns/runner-host-mail.test.ts new file mode 100644 index 00000000..d27b5c42 --- /dev/null +++ b/newborns/runner-host-mail.test.ts @@ -0,0 +1,509 @@ +// What a runner host mails its tenant, set up by one run of plexus.ci.playbook +// on itself as runner-host.test.ts sets one up (its header says how), with the +// same stand-ins for the vault's CLI and the forge, and two more: a mail relay +// on the host's loopback that takes STARTTLS and AUTH, as a tenant's relay +// does, and records every message it is handed, and a runner that waits for a +// job that never comes, in place of a slot's container. The forge refuses to +// mint a slot's runner config when the test says so. The relay's address, +// credentials, sender and recipient are the vault's item mail-relay. +// +// A host whose vault has no mail-relay is set up all the same, runs its slots, +// and says in its journal that it sends no mail. With the item, the host mails +// through the relay, with the item's credentials, from its sender to its +// recipient, and takes no mail over SMTP from what shares its loopback, the +// slots included: one mail for a unit that fails (BuildKit, a cache server, a +// slot's container), one for a disk fuller than the housekeeping's threshold, +// none for a slot whose minting failed once, and one, saying for how long, for +// a slot whose minting has failed for longer than the threshold the run gives +// (actions_runners_slot_alert_after); never one per attempt. A relay that +// refuses is said in the journal, and the host is set up all the same. Nothing +// reaches a real vault, App, relay or mailbox. Needs Docker and the network, +// as the newborns do. +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { after, before, describe, test } from 'node:test'; +import { close, open, put, sh, tryRun, until } from './helpers.ts'; + +const WORKSPACE = join(import.meta.dirname, '..'); +const NAME = 'runner-a'; +const IMAGE = 'plx-newborn-runner-host-ansible:trixie'; +const DOCKERFILE = `FROM debian:trixie +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \\ + systemd systemd-sysv dbus ansible python3-apt iproute2 ca-certificates curl openssl openssh-server sudo \\ + && rm -rf /var/lib/apt/lists/* +CMD ["/sbin/init"] +`; +const TOKEN = 'a-service-account-token'; +const VAULT: Record = { + 'github-app/client-id': 'vault-app-client-id', + 'bucket-turbo/endpoint': 'http://127.0.0.1:9', + 'bucket-turbo/region': 'us-east-1', + 'bucket-turbo/access-key-id': 'vault-shared-access-key', + 'bucket-turbo/secret-access-key': 'vault-shared-secret-key', + 'bucket-turbo-trusted/access-key-id': 'vault-trusted-access-key', + 'bucket-turbo-trusted/secret-access-key': 'vault-trusted-secret-key', +}; +/** The item that names the relay, which the vault holds from the second run on. */ +const RELAY: Record = { + 'mail-relay/server': '127.0.0.1', + 'mail-relay/port': '2525', + 'mail-relay/mode': 'starttls', + 'mail-relay/username': 'vault-relay-username', + 'mail-relay/password': 'vault-relay-password', + 'mail-relay/from-address': 'ci-hosts@example.org', + 'mail-relay/mailto': 'alerts@example.org', +}; +const OP = `#!/bin/sh +[ -n "\${OP_SERVICE_ACCOUNT_TOKEN:-}" ] || { echo "op: no service account token" >&2; exit 1; } +[ "$1" = read ] || { echo "op stand-in: only read" >&2; exit 2; } +for ref; do :; done +file=/stand-in/vault/\${ref#op://} +[ -f "$file" ] || { echo "[ERROR] could not read secret '$ref'" >&2; exit 1; } +cat "$file" +`; +/** + * The forge, as far as ci-runner-jit asks it. A minting is refused (500) while + * /var/lib/stand-in/refuse-mint says `always`, or as many times as the number + * it holds; each minting it answers, and each it refuses, is a line of a log. + */ +const FORGE = `import http.server, json, os, ssl +REFUSE = "/var/lib/stand-in/refuse-mint" +def refused(): + try: + left = open(REFUSE).read().strip() + except FileNotFoundError: + return False + if left == "always": return True + if int(left) <= 0: return False + open(REFUSE, "w").write(str(int(left) - 1)) + return True +class Api(http.server.BaseHTTPRequestHandler): + def answer(self, status, body): + data = json.dumps(body).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + def do_GET(self): + if self.path.endswith("/installation"): return self.answer(200, {"id": 1}) + if "/runner-groups" in self.path: return self.answer(200, {"runner_groups": [{"id": 1, "name": "Default"}]}) + if "/actions/runners?" in self.path: return self.answer(200, {"runners": []}) + self.answer(404, {}) + def do_POST(self): + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + if self.path.endswith("/access_tokens"): return self.answer(201, {"token": "t"}) + if self.path.endswith("/generate-jitconfig"): + refuse = refused() + with open("/var/log/forge-stand-in.jsonl", "a") as log: + log.write(json.dumps({"name": json.loads(body)["name"], "refused": refuse}) + "\\n") + if refuse: return self.answer(500, {"message": "stand-in refuses"}) + return self.answer(201, {"encoded_jit_config": "e30="}) + self.answer(404, {}) + def log_message(self, *args): pass +server = http.server.ThreadingHTTPServer(("127.0.0.1", 443), Api) +context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +context.load_cert_chain("/etc/forge-stand-in/api.crt", "/etc/forge-stand-in/api.key") +server.socket = context.wrap_socket(server.socket, server_side=True) +server.serve_forever() +`; +/** + * The tenant's mail relay on 127.0.0.1:2525: STARTTLS with a certificate of + * its own, then AUTH PLAIN or LOGIN, which it refuses (535) while + * /var/lib/stand-in/relay-refuse exists; a message only after AUTH. Each + * message it takes is a line of a log: the credentials, the envelope, the text. + */ +const RELAY_SERVER = `import base64, json, os, re, socketserver, ssl +CONTEXT = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +CONTEXT.load_cert_chain("/etc/relay-stand-in/relay.crt", "/etc/relay-stand-in/relay.key") +class Session(socketserver.StreamRequestHandler): + def reply(self, line): + self.wfile.write((line + "\\r\\n").encode()) + self.wfile.flush() + def read(self): + return self.rfile.readline().decode(errors="replace").rstrip("\\r\\n") + def handle(self): + tls, auth, sender, recipients = False, None, None, [] + self.reply("220 relay.example.org ESMTP stand-in") + while True: + line = self.read() + if not line: return + verb, _, arg = line.partition(" ") + verb = verb.upper() + if verb in ("EHLO", "HELO"): + offers = ["relay.example.org"] + (["AUTH PLAIN LOGIN"] if tls else ["STARTTLS"]) + for i, offer in enumerate(offers): self.reply(("250 " if i == len(offers) - 1 else "250-") + offer) + elif verb == "STARTTLS" and not tls: + self.reply("220 2.0.0 go ahead") + self.connection = CONTEXT.wrap_socket(self.connection, server_side=True) + self.rfile = self.connection.makefile("rb") + self.wfile = self.connection.makefile("wb") + tls = True + elif verb == "AUTH" and tls: + mechanism, _, initial = arg.partition(" ") + if mechanism.upper() == "PLAIN": + if not initial: + self.reply("334 ") + initial = self.read() + _, username, password = base64.b64decode(initial).decode().split("\\0") + else: + self.reply("334 VXNlcm5hbWU6") + username = base64.b64decode(self.read()).decode() + self.reply("334 UGFzc3dvcmQ6") + password = base64.b64decode(self.read()).decode() + if os.path.exists("/var/lib/stand-in/relay-refuse"): + self.reply("535 5.7.8 Authentication credentials invalid") + else: + auth = {"username": username, "password": password} + self.reply("235 2.7.0 Authentication successful") + elif verb == "MAIL": + if not auth: + self.reply("530 5.7.0 Authentication required") + continue + sender, recipients = re.search(r"<([^>]*)>", arg).group(1), [] + self.reply("250 2.1.0 Ok") + elif verb == "RCPT": + recipients.append(re.search(r"<([^>]*)>", arg).group(1)) + self.reply("250 2.1.5 Ok") + elif verb == "DATA": + self.reply("354 End data with .") + text = [] + while True: + data = self.read() + if data == ".": break + text.append(data[1:] if data.startswith("..") else data) + with open("/var/log/relay-stand-in.jsonl", "a") as log: + log.write(json.dumps({"auth": auth, "from": sender, "to": recipients, "text": "\\n".join(text)}) + "\\n") + self.reply("250 2.0.0 Ok: queued") + elif verb == "RSET": + sender, recipients = None, [] + self.reply("250 2.0.0 Ok") + elif verb == "NOOP": + self.reply("250 2.0.0 Ok") + elif verb == "QUIT": + self.reply("221 2.0.0 Bye") + return + else: + self.reply("502 5.5.2 Error: command not recognized") +class Server(socketserver.ThreadingTCPServer): + allow_reuse_address = True + daemon_threads = True +Server(("127.0.0.1", 2525), Session).serve_forever() +`; +/** A slot's runner, waiting for a job that never comes; a stop ends it as docker run reports SIGTERM. */ +const RUNNER = `#!/bin/sh +trap 'exit 143' TERM +while :; do sleep 1 & wait $!; done +`; +const CERTIFICATES = `set -eu +mkdir -p /etc/forge-stand-in && cd /etc/forge-stand-in +openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 2 -subj /CN=stand-in-ca 2>/dev/null +openssl req -newkey rsa:2048 -nodes -keyout api.key -out api.csr -subj /CN=api.github.com 2>/dev/null +printf 'subjectAltName=DNS:api.github.com\\nextendedKeyUsage=serverAuth\\n' >ext +openssl x509 -req -in api.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out api.crt -days 2 -extfile ext 2>/dev/null +cp ca.crt /usr/local/share/ca-certificates/forge-stand-in.crt && update-ca-certificates >/dev/null +mkdir -p /etc/relay-stand-in && cd /etc/relay-stand-in +openssl req -x509 -newkey rsa:2048 -nodes -keyout relay.key -out relay.crt -days 2 -subj /CN=relay.example.org 2>/dev/null +mkdir -p /var/lib/stand-in +`; +/** The threshold the run gives, in seconds: past it a slot that cannot mint mails. */ +const ALERT_AFTER = 60; +const VALUES = { + ci_owner: 'acme', + actions_runners_slots: { repo: { count: 1, memory: '1g' } }, + actions_runners_image: 'busybox:1.37', + netbird_enabled: false, + base_kernel_hardening: false, + actions_runners_slot_alert_after: ALERT_AFTER, +}; +const SLOT = 'ci-runner@repo-1.service'; + +let here = ''; +let host = ''; +let adminKey = ''; + +const onHost = (...command: string[]) => sh('docker', ['exec', host, ...command], here); +const shellOnHost = (line: string) => tryRun('docker', ['exec', host, 'sh', '-c', line], here); + +before(async () => { + here = await open('runner-host-mail', { registry: false }); + put(here, { + 'image/Dockerfile': DOCKERFILE, + 'stand-in/bin/op': OP, + 'stand-in/forge.py': FORGE, + 'stand-in/relay.py': RELAY_SERVER, + 'stand-in/runner': RUNNER, + }); + for (const [field, value] of Object.entries(VAULT)) put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); + await sh('chmod', ['+x', join(here, 'stand-in/bin/op'), join(here, 'stand-in/runner')], here); + await sh('docker', ['build', '-q', '-t', IMAGE, join(here, 'image')], here); + const started = ( + await sh( + 'docker', + [ + 'run', + '-d', + '--rm', + '--name', + `plx-newborn-${process.pid}-runner-host-mail`, + '--privileged', + '--cgroupns=private', + '--hostname', + NAME, + '--add-host', + 'api.github.com:127.0.0.1', + '--tmpfs', + '/run', + '--tmpfs', + '/run/lock', + '-v', + '/var/lib/docker', + '-v', + '/var/lib/buildkit', + '--cpus', + '4', + '--memory', + '6g', + '--pids-limit', + '2000', + '-v', + `${join(WORKSPACE, 'ansible')}:/collections/ansible_collections/plexus:ro`, + '-v', + `${join(here, 'stand-in')}:/stand-in`, + IMAGE, + ], + here, + ) + ).match(/^[0-9a-f]{64}$/m); + host = started?.[0] ?? ''; + if (!host) throw new Error('docker run printed no container id'); + await until('the host to finish booting', async () => { + const state = await tryRun('docker', ['exec', host, 'systemctl', 'is-system-running', '--wait'], here); + return /^(running|degraded)$/m.test(state.output); + }); + await onHost('sh', '-c', CERTIFICATES); + await onHost('systemd-run', '--unit', 'forge-stand-in', 'python3', '/stand-in/forge.py'); + await onHost('systemd-run', '--unit', 'relay-stand-in', 'python3', '/stand-in/relay.py'); + await onHost('sh', '-c', 'openssl genrsa -out /stand-in/vault/acme-ci-host/github-app/private-key 2048 2>/dev/null'); + await onHost('ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-C', 'ada@example.invalid', '-f', '/root/ada'); + adminKey = (await onHost('cat', '/root/ada.pub')).trim(); + // The slots run the stand-in runner in place of a container, from their first start. + await onHost( + 'sh', + '-c', + 'mkdir -p /etc/systemd/system/ci-runner@.service.d && printf "[Service]\\nExecStart=\\nExecStart=/stand-in/runner %%i\\n" >/etc/systemd/system/ci-runner@.service.d/stand-in.conf', + ); +}); + +after(async () => { + if (host) await tryRun('docker', ['rm', '-f', '-v', host], here); + await close(); +}); + +/** One run of the playbook on the host as its user-data starts it; unfailing. */ +async function play(args: string[] = []) { + return tryRun( + 'docker', + [ + 'exec', + host, + 'env', + `OP_SERVICE_ACCOUNT_TOKEN=${TOKEN}`, + 'PATH=/stand-in/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + 'ANSIBLE_COLLECTIONS_PATH=/collections', + 'ANSIBLE_NOCOLOR=1', + 'ansible-playbook', + 'plexus.ci.playbook', + '-e', + JSON.stringify({ ...VALUES, iam_admins: [{ name: 'ada', ssh_keys: [adminKey] }] }), + ...args, + ], + here, + ); +} + +interface Mail { + auth: { username: string; password: string } | null; + from: string; + to: string[]; + text: string; +} +/** A message's headers and its body as read, decoded where it is quoted-printable (systemctl's status is UTF-8). */ +function readable(text: string): string { + const end = text.indexOf('\n\n'); + const [head, body] = end < 0 ? [text, ''] : [text.slice(0, end), text.slice(end + 2)]; + if (!/^Content-Transfer-Encoding: quoted-printable$/im.test(head)) return text; + const bytes = body + .replace(/=\n/g, '') + .replace(/=([0-9A-F]{2})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))); + return `${head}\n\n${Buffer.from(bytes, 'latin1').toString('utf8')}`; +} +/** Every message the relay has taken, its text readable. */ +async function mails(): Promise { + const log = (await shellOnHost('cat /var/log/relay-stand-in.jsonl 2>/dev/null')).output.trim(); + if (!log) return []; + return log.split('\n').map((line) => { + const mail: Mail = JSON.parse(line); + return { ...mail, text: readable(mail.text) }; + }); +} +/** The messages whose subject names the unit. */ +const about = async (unit: string) => + (await mails()).filter((mail) => new RegExp(`^Subject: .*${unit.replace(/[.@]/g, '\\$&')}`, 'm').test(mail.text)); +/** Until the relay has one message about the unit; that message. */ +async function oneMailAbout(unit: string, limit = 90_000): Promise { + await until(`a mail about ${unit}`, async () => (await about(unit)).length > 0, limit); + return (await about(unit))[0] as Mail; +} +/** Until nothing is left to send: no failure mail being written, and Postfix's queue empty. */ +async function settled() { + await until( + 'the host to have sent what it had', + async () => { + const writing = await shellOnHost('systemctl list-units --plain --no-legend "failure-mail@*" --state=activating'); + const queue = await shellOnHost('mailq'); + return writing.output.trim() === '' && /Mail queue is empty/.test(queue.output); + }, + 120_000, + ); +} +/** A slot's mintings the forge answered or refused, in order. */ +async function mintings(): Promise<{ name: string; refused: boolean }[]> { + const log = (await shellOnHost('cat /var/log/forge-stand-in.jsonl 2>/dev/null')).output.trim(); + return log ? log.split('\n').map((line) => JSON.parse(line)) : []; +} +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +describe('a runner host mails its tenant', () => { + test('a host whose vault has no item mail-relay is set up all the same, runs its slots, and says in its journal that it sends no mail', async () => { + const ran = await play(); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await onHost('systemctl', 'is-active', SLOT, 'ci-buildkit')).trim(), 'active\nactive'); + const journal = await onHost('journalctl', '--no-pager', '-t', 'plexus-ci'); + assert.match(journal, /sends no mail/); + assert.match(journal, /acme-ci-host/); + assert.match(journal, /mail-relay/); + assert.equal((await shellOnHost('dpkg -s postfix')).ok, false); + }); + + test('with the item, a run at -vvv passes and prints none of it, and the host takes no mail over SMTP from its loopback, which the slots share', async () => { + for (const [field, value] of Object.entries(RELAY)) put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); + const ran = await play(['-vvv']); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + for (const field of ['username', 'password']) + assert.equal(ran.output.includes(RELAY[`mail-relay/${field}`] ?? '?'), false, field); + assert.equal((await onHost('systemctl', 'is-active', 'postfix')).trim(), 'active'); + assert.equal((await onHost('ss', '-Hltn', 'sport = :25')).trim(), ''); + }); + + test('a unit that fails, BuildKit or a cache server, is one mail each, through the relay with the item’s credentials, from its sender to its recipient', async () => { + for (const unit of ['ci-buildkit.service', 'ci-turbo-cache@shared.service']) { + await onHost('systemctl', 'kill', '--signal=SIGKILL', unit); + const mail = await oneMailAbout(unit); + assert.deepEqual(mail.auth, { username: 'vault-relay-username', password: 'vault-relay-password' }); + assert.equal(mail.from, 'ci-hosts@example.org'); + assert.deepEqual(mail.to, ['alerts@example.org']); + assert.match(mail.text, new RegExp(`^Subject: \\[${NAME}\\] `, 'm')); + } + await settled(); + assert.equal((await about('ci-buildkit.service')).length, 1); + assert.equal((await about('ci-turbo-cache@shared.service')).length, 1); + }); + + test('a disk fuller than the housekeeping’s threshold is one mail that says how full, however often the housekeeping finds it', async () => { + // The disk is the test machine's: the threshold goes under what it holds instead. + const used = Number((await onHost('sh', '-c', "df --output=pcent / | tail -1 | tr -dc '0-9'")).trim()); + await onHost( + 'sh', + '-c', + `mkdir -p /etc/systemd/system/ci-runner-housekeeping.service.d && printf "[Service]\\nEnvironment=DISK_ALERT_PERCENT=${Math.max(used - 1, 0)}\\n" >/etc/systemd/system/ci-runner-housekeeping.service.d/stand-in.conf && systemctl daemon-reload`, + ); + try { + for (let run = 0; run < 2; run++) + assert.equal((await shellOnHost('systemctl start ci-runner-housekeeping.service')).ok, false); + const mail = await oneMailAbout('ci-runner-housekeeping.service'); + assert.match(mail.text, /root file system \d+% used/); + assert.match(mail.text, new RegExp(`above ${Math.max(used - 1, 0)}%`)); + await settled(); + assert.equal((await about('ci-runner-housekeeping.service')).length, 1); + } finally { + await onHost( + 'sh', + '-c', + 'rm -r /etc/systemd/system/ci-runner-housekeeping.service.d && systemctl daemon-reload && systemctl reset-failed ci-runner-housekeeping.service', + ); + } + }); + + test('a slot whose minting fails once mails nobody; one whose minting has failed for longer than the threshold mails once, saying for how long', async () => { + const before = (await mintings()).length; + // One failed attempt: ci-runner-jit asks three times before it gives up. + await onHost('sh', '-c', 'echo 3 >/var/lib/stand-in/refuse-mint'); + await onHost('systemctl', 'restart', '--no-block', SLOT); + await until( + 'the slot to mint again after one failed attempt', + async () => { + const since = (await mintings()).slice(before); + return since.some((minting) => minting.refused) && since.at(-1)?.refused === false; + }, + 180_000, + ); + await until( + 'the slot to run again', + async () => (await shellOnHost(`systemctl is-active ${SLOT}`)).output.trim() === 'active', + ); + await sleep((ALERT_AFTER + 15) * 1000); + await settled(); + assert.deepEqual(await about(SLOT), []); + + await onHost('sh', '-c', 'echo always >/var/lib/stand-in/refuse-mint'); + try { + const refusedFrom = Date.now(); + await onHost('systemctl', 'restart', '--no-block', SLOT); + const mail = await oneMailAbout(SLOT, 5 * 60_000); + assert.ok(Date.now() - refusedFrom >= ALERT_AFTER * 1000, 'mailed before the threshold'); + assert.match(mail.text, /has failed .*for 1 min/); + // Two more attempts, each refused: no further mail. + const attempts = (await mintings()).length; + await until('two more refused attempts', async () => (await mintings()).length >= attempts + 6, 180_000); + await settled(); + assert.equal((await about(SLOT)).length, 1); + } finally { + await onHost('rm', '-f', '/var/lib/stand-in/refuse-mint'); + } + await until( + 'the slot to run again', + async () => (await shellOnHost(`systemctl is-active ${SLOT}`)).output.trim() === 'active', + 180_000, + ); + }); + + test('a slot whose container fails is one mail at once, as any unit', async () => { + // As if a day had passed since the slot's last mail. + await onHost('rm', '-f', `/var/lib/failure-mail/${SLOT}`); + const earlier = (await about(SLOT)).length; + await onHost('systemctl', 'kill', '--signal=SIGKILL', '--kill-whom=main', SLOT); + await until('a second mail about the slot', async () => (await about(SLOT)).length > earlier, 60_000); + await settled(); + assert.equal((await about(SLOT)).length, earlier + 1); + }); + + test('a relay that refuses is said in the journal, and the host is set up all the same', async () => { + await onHost('touch', '/var/lib/stand-in/relay-refuse'); + try { + const before = (await mails()).length; + await onHost('systemctl', 'kill', '--signal=SIGKILL', 'ci-turbo-cache@trusted.service'); + await until( + 'Postfix to say the relay refused', + async () => /535 5\.7\.8/.test((await shellOnHost('journalctl --no-pager -t postfix/smtp')).output), + 120_000, + ); + assert.equal((await mails()).length, before); + const ran = await play(); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await onHost('systemctl', 'is-active', SLOT)).trim(), 'active'); + } finally { + await onHost('rm', '-f', '/var/lib/stand-in/relay-refuse'); + } + }); +}); From b8a4c31a54d83202a237ab66d28fd4ec3d87a8cd Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 02:53:37 +0100 Subject: [PATCH 02/11] plexus.ci: a runner host mails its tenant through the relay of its vault's item mail-relay (PLX-253) The playbook mounts the host baseline's mail role as the platform's does, with mail_smtp from the vault's optional item mail-relay (server, port, mode, username, password, from-address, mailto). A vault without the whole item fails no run: the host is set up, sends no mail, and says so in its journal (logger, tag plexus-ci). The mail role gains mail_loopback_smtp, true by default, so app hosts stay as they are: false comments out master.cf's `smtp inet`, since a runner host's slots share its loopback and would otherwise mail as the host. Co-Authored-By: Claude Opus --- ansible/ci/playbooks/playbook.yml | 66 +++++++++++++++++++++-- ansible/ci/playbooks/vars/vault.yml | 17 +++++- ansible/host/roles/mail/defaults/main.yml | 7 +++ ansible/host/roles/mail/tasks/main.yml | 11 ++++ 4 files changed, 94 insertions(+), 7 deletions(-) diff --git a/ansible/ci/playbooks/playbook.yml b/ansible/ci/playbooks/playbook.yml index 26f8e3db..9f0c5ae0 100644 --- a/ansible/ci/playbooks/playbook.yml +++ b/ansible/ci/playbooks/playbook.yml @@ -49,8 +49,17 @@ # with the vault's CLI, `op`, which the second play installs from the # vendor's repository where the host has none (plexus.ci.actions_runners, # vault_cli). The playbook reads every other secret from there itself (vars/vault.yml names the items -# and fields), and none is passed in. A runner host sends no mail: no mail -# relay is mounted, and a failed unit shows in the journal alone. +# and fields), and none is passed in. +# +# The host mails the tenant through the tenant's relay, as an app host does +# (plexus.host.mail): what it needs, the relay, its credentials, the sender +# and the recipient, is the vault's item mail-relay. It mails once a day at +# most per unit, when a unit fails: BuildKit, a cache server, a slot, the +# housekeeping, which fails on a disk fuller than +# actions_runners_disk_alert_percent. The host takes no mail over SMTP, since its slots share its loopback. A vault +# without the whole item fails no run: the host is set up, sends no mail, and +# says so in its journal. A relay that refuses fails no run either; Postfix +# says so in the journal at each try. # # The first play locks the host down: the values are checked before # anything changes, then the jobs' user takes the runner image's uid, the @@ -65,7 +74,8 @@ # for a run that logged in as root over SSH, which this one never did, so it # is told the first admin's name instead. The handlers of the first play run # even when a task of it fails. The second play reads the vault and sets up -# the rest: the baseline, the overlay, Docker, the cache servers, the slots. +# the rest: the baseline, the mail, the overlay, Docker, the cache servers, +# the slots. # # Tags: every play carries its layer (`host`, `ci`) and every role its own # name. @@ -196,7 +206,7 @@ vars: unread: >- {%- set unread = [] -%} - {%- for read in ci_vault_read.results if read.rc is defined and read.rc != 0 -%} + {%- for read in ci_vault_read.results if read.rc is defined and read.rc != 0 and not read.item.optional | default(false) -%} {%- set _ = unread.append(read.item.item ~ '/' ~ read.item.field ~ ' (' ~ (read.stderr | trim) ~ ')') -%} {%- endfor -%} {{ unread }} @@ -207,12 +217,58 @@ ansible.builtin.set_fact: "{{ ci_vault[item].var }}": "{{ ci_vault_read.results[item].stdout }}" loop: "{{ range(ci_vault | length) | list }}" - when: ci_vault_read.results[item].rc is defined + when: ci_vault_read.results[item].rc | default(1) == 0 + no_log: true + tags: [always] + + - name: What the vault did not give of the mail relay + ansible.builtin.set_fact: + ci_mail_unread: >- + {%- set unread = [] -%} + {%- for read in ci_vault_read.results if read.item.item == 'mail-relay' and read.rc | default(1) != 0 -%} + {%- set _ = unread.append(read.item.item ~ '/' ~ read.item.field ~ ' (' ~ (read.stderr | default('') | trim) ~ ')') -%} + {%- endfor -%} + {{ unread }} + tags: [always] + + - name: Hand the mail relay to the mail role + ansible.builtin.set_fact: + mail_smtp: + server: "{{ ci_mail_server }}" + port: "{{ ci_mail_port }}" + mode: "{{ ci_mail_mode }}" + username: "{{ ci_mail_username }}" + password: "{{ ci_mail_password }}" + from_address: "{{ ci_mail_from_address }}" + mailto: "{{ ci_mail_mailto }}" + when: ci_mail_unread | length == 0 no_log: true tags: [always] + + # Under cloud-init the run's output is a log nobody reads; the journal is + # where an admin looks first. + - name: Say in the journal that the host sends no mail + ansible.builtin.command: + argv: + - logger + - --tag + - plexus-ci + - --priority + - user.warning + - >- + This host sends no mail: the vault {{ ci_owner }}-ci-host gave no + {{ ci_mail_unread | join('; no ') }}. A failed unit, a disk over the + housekeeping's threshold and a slot that cannot register show in + this journal alone. + when: ci_mail_unread | length > 0 and mail_smtp | default({}) | length == 0 + changed_when: false + tags: [mail] roles: - { role: plexus.host.base, tags: [base] } - { role: plexus.host.upgrades, tags: [upgrades] } + # Before the units it reports on start; its port on loopback closed, + # since the slots share the host's network. + - { role: plexus.host.mail, tags: [mail], mail_loopback_smtp: false } - { role: plexus.host.netbird, tags: [netbird], when: netbird_enabled | bool } # Its images are the runner housekeeping's (actions_runners). - { role: plexus.host.docker, tags: [docker], docker_image_prune: false } diff --git a/ansible/ci/playbooks/vars/vault.yml b/ansible/ci/playbooks/vars/vault.yml index 28b4a902..2f9fb99c 100644 --- a/ansible/ci/playbooks/vars/vault.yml +++ b/ansible/ci/playbooks/vars/vault.yml @@ -1,8 +1,9 @@ --- # What the playbook reads from the host's vault, -ci-host, and # into which variable: the one place the items and fields are named. An -# entry with `when` is read only where that holds; a variable given on the -# command line wins over what is read. +# entry with `when` is read only where that holds; an `optional` one fails +# no run when the vault lacks it; a variable given on the command line wins +# over what is read. ci_vault: - { var: actions_runners_app_client_id, item: github-app, field: client-id } - { var: actions_runners_app_private_key, item: github-app, field: private-key } @@ -17,3 +18,15 @@ ci_vault: - { var: actions_runners_connect_credentials, item: 1password-connect, field: credentials, when: actions_runners_connect } - { var: actions_runners_connect_token, item: 1password-connect, field: token, when: actions_runners_connect } - { var: netbird_setup_key, item: netbird, field: setup-key, when: netbird_enabled } + # The tenant's mail relay, which the host mails through (plexus.host.mail, + # its mail_smtp): the relay's name or address, its port, `starttls` or + # `tls` (implicit TLS), the relay's user and password, the sender every + # mail goes from and the one mailbox it goes to. A vault without the whole + # item leaves the host without mail, which it says in its journal. + - { var: ci_mail_server, item: mail-relay, field: server, optional: true } + - { var: ci_mail_port, item: mail-relay, field: port, optional: true } + - { var: ci_mail_mode, item: mail-relay, field: mode, optional: true } + - { var: ci_mail_username, item: mail-relay, field: username, optional: true } + - { var: ci_mail_password, item: mail-relay, field: password, optional: true } + - { var: ci_mail_from_address, item: mail-relay, field: from-address, optional: true } + - { var: ci_mail_mailto, item: mail-relay, field: mailto, optional: true } diff --git a/ansible/host/roles/mail/defaults/main.yml b/ansible/host/roles/mail/defaults/main.yml index 328e4257..18bff302 100644 --- a/ansible/host/roles/mail/defaults/main.yml +++ b/ansible/host/roles/mail/defaults/main.yml @@ -15,6 +15,13 @@ # Empty leaves the host's mail as it is. mail_smtp: {} +# Postfix takes the host's own mail from sendmail(1), which mail(1), cron and +# failure-mail use, and also over SMTP on loopback, port 25, from whatever +# reaches the host's loopback. False closes that port, for a host whose +# loopback runs code that is not to mail as the host: a runner host, whose +# slots share its network. Set once: true again does not reopen it. +mail_loopback_smtp: true + # Have unattended-upgrades mail when an upgrade fails (never on success). mail_unattended_upgrades: true diff --git a/ansible/host/roles/mail/tasks/main.yml b/ansible/host/roles/mail/tasks/main.yml index 4f84eaa9..14f1c216 100644 --- a/ansible/host/roles/mail/tasks/main.yml +++ b/ansible/host/roles/mail/tasks/main.yml @@ -30,6 +30,17 @@ mode: "0644" notify: Restart postfix + # The service `smtp inet` of master.cf, as Debian ships it; the line + # commented out, which no regexp then matches again. + - name: Close the SMTP port on loopback + ansible.builtin.lineinfile: + path: /etc/postfix/master.cf + regexp: '^(smtp\s+inet\s.*)$' + line: '#\1' + backrefs: true + when: not mail_loopback_smtp + notify: Restart postfix + - name: Enable Postfix ansible.builtin.systemd_service: name: postfix From 036b65afdd5fe23db868d2ff0373c8d537926ec1 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 03:00:17 +0100 Subject: [PATCH 03/11] plexus.ci: a slot's mail waits until its minting has failed for a few minutes, and says for how long (PLX-253) A slot fails as a unit at every failed attempt and is started again, so the host's mail on a failed unit would mail one refusal of the forge. ci-runner-jit keeps the first failed attempt of a row in /run/ci-runner/.failing, which a minting that succeeds, or a stop, removes, and says at each failure for how long the slot has failed. A drop-in of failure-mail@ adds an ExecCondition, ci-runner-mail-hold, which holds back the mail on a slot until that row is actions_runners_slot_alert_after old (300 s); a slot whose container failed, and every other unit, mails at once. The retry loop and its cadence are unchanged; the mail role's daily interval keeps it to one mail. The headers of the playbook, of both Terraform modules and of the template's root ci/ name the vault's item mail-relay. Co-Authored-By: Claude Opus --- ansible/ci/playbooks/playbook.yml | 9 +++-- .../roles/actions_runners/defaults/main.yml | 15 +++++++-- .../roles/actions_runners/files/ci-runner-jit | 29 ++++++++++++++-- .../actions_runners/files/ci-runner-mail-hold | 33 +++++++++++++++++++ .../ci/roles/actions_runners/tasks/main.yml | 29 +++++++++++++++- .../main.tf.jinja | 2 +- terraform/ci_runner_host_user_data/main.tf | 5 +-- terraform/hcloud_ci_runner_host/main.tf | 8 +++++ 8 files changed, 119 insertions(+), 11 deletions(-) create mode 100644 ansible/ci/roles/actions_runners/files/ci-runner-mail-hold diff --git a/ansible/ci/playbooks/playbook.yml b/ansible/ci/playbooks/playbook.yml index 9f0c5ae0..112e4ff9 100644 --- a/ansible/ci/playbooks/playbook.yml +++ b/ansible/ci/playbooks/playbook.yml @@ -54,9 +54,12 @@ # The host mails the tenant through the tenant's relay, as an app host does # (plexus.host.mail): what it needs, the relay, its credentials, the sender # and the recipient, is the vault's item mail-relay. It mails once a day at -# most per unit, when a unit fails: BuildKit, a cache server, a slot, the -# housekeeping, which fails on a disk fuller than -# actions_runners_disk_alert_percent. The host takes no mail over SMTP, since its slots share its loopback. A vault +# most per unit: when a unit fails (BuildKit, a cache server, a slot's +# container, the housekeeping, which fails on a disk fuller than +# actions_runners_disk_alert_percent), and when a slot has failed to mint its +# runner config for longer than actions_runners_slot_alert_after, saying for +# how long; one failed minting mails nobody (plexus.ci.actions_runners). The +# host takes no mail over SMTP, since its slots share its loopback. A vault # without the whole item fails no run: the host is set up, sends no mail, and # says so in its journal. A relay that refuses fails no run either; Postfix # says so in the journal at each try. diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index b0bcf336..6f61d27d 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -68,8 +68,15 @@ # file a repo slot reads (turbo_cache). The role opens no port: the runner # polls the forge. # -# A runner host sends no mail: the playbook mounts no mail relay, so a failed -# unit, the housekeeping's disk alert among them, shows in the journal alone. +# Where the playbook sets up the host's mail (plexus.host.mail), a unit that +# fails is a mail, at most once a day per unit: a slot's container, BuildKit, +# the housekeeping, which fails on a disk fuller than +# actions_runners_disk_alert_percent. A slot fails at every attempt that +# fails, and is started again: one whose minting failed is held back from the +# mail until the minting has failed for actions_runners_slot_alert_after +# (files/ci-runner-mail-hold), so that one refusal of the forge mails nobody +# and a slot that cannot register does, with how long in its journal. Without +# the host's mail every failure shows in the journal alone. # Where the slots register: `org` at the organisation, in a runner group of # it, `repo` on one repository (they are then that repository's alone, @@ -212,6 +219,10 @@ actions_runners_connect_port: 8080 # fails when the root file system is fuller than this afterwards. actions_runners_disk_alert_percent: 85 +# How long, in seconds, a slot's minting fails at every attempt before the +# host mails about it; an attempt takes about 50 s with the wait after it. +actions_runners_slot_alert_after: 300 + # The BuildKit service (§ 8 PLX-Delivery): one buildkitd on the host, the # systemd unit ci-buildkit, through which the publish step of a job builds # and pushes its image without a Docker daemon of its own, with buildx's diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-jit b/ansible/ci/roles/actions_runners/files/ci-runner-jit index 24531eb3..c578ccc8 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-jit +++ b/ansible/ci/roles/actions_runners/files/ci-runner-jit @@ -34,8 +34,32 @@ name="$HOST-$instance" out=/run/ci-runner/$instance.env # A failure waits before it fails, so that a forge outage costs one attempt -# per slot every half minute rather than every restart interval. -trap 'echo "ci-runner-jit: minting the config of $name failed" >&2; sleep 30' ERR +# per slot every half minute rather than every restart interval. It also +# keeps the time of the first of the failed attempts in a row, in $failing, +# and says, as it fails, for how long the slot has failed: the host's mail +# on a failed unit (plexus.host.mail) holds back a slot's while the minting +# has failed for less than a few minutes (ci-runner-mail-hold), and the +# mail, which carries the slot's journal, then says for how long. A minting +# that succeeds ends the row. +failing=/run/ci-runner/$instance.failing +minting_failed() { + local since took + echo "ci-runner-jit: minting the config of $name failed" >&2 + mkdir -p /run/ci-runner + [ -s "$failing" ] || date +%s >"$failing" + sleep 30 + since=$(cat "$failing") + took=$(($(date +%s) - since)) + if [ "$took" -ge 3600 ]; then + took="$((took / 3600)) h $((took % 3600 / 60)) min" + elif [ "$took" -ge 60 ]; then + took="$((took / 60)) min $((took % 60)) s" + else + took="$took s" + fi + echo "ci-runner-jit: $name has failed to mint its config at every attempt for $took, since $(date -u -d "@$since" '+%Y-%m-%d %H:%M:%S UTC')" >&2 +} +trap minting_failed ERR forge_login @@ -92,4 +116,5 @@ done umask 077 mkdir -p /run/ci-runner printf 'ACTIONS_RUNNER_INPUT_JITCONFIG=%s\n' "$jit" >"$out" +rm -f "$failing" echo "$name: registered on $base with $labels" diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold b/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold new file mode 100644 index 00000000..18b57b69 --- /dev/null +++ b/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold @@ -0,0 +1,33 @@ +#!/bin/sh +# Holds back the host's mail on a failed slot while the slot's minting has +# failed for less than ALERT_AFTER seconds (ExecCondition of +# failure-mail@.service, plexus.host.mail, by a drop-in of this role). +# Managed by Ansible (actions_runners). +# +# A slot fails as a unit at every failed attempt and is started again; a +# failed unit starts failure-mail@, which mails the unit's status and +# journal at most once a day (mail_failure_interval). One forge that refuses +# one minting is no news, a slot that has not registered for minutes is: +# jobs queue. So the mail on a slot whose minting failed waits until +# ci-runner-jit has kept the first failed attempt of the row for +# ALERT_AFTER seconds (/run/ci-runner/.failing, which a minting that +# succeeds removes); the slot's journal, which the mail carries, then says +# for how long. A slot whose container failed after it minted, and every +# other unit, is mailed at once, as on any host. Exits 0 to mail, 1 to hold +# back, which systemd counts as no failure of failure-mail@. +# +# ALERT_AFTER=300 ci-runner-mail-hold ci-runner@repo-1.service; echo $? +set -eu +unit=${1:?the unit that failed, e.g. ci-runner@repo-1.service} +case $unit in + ci-runner@*.service) ;; + *) exit 0 ;; +esac +slot=${unit#ci-runner@} +slot=${slot%.service} +since=$(cat "/run/ci-runner/$slot.failing" 2>/dev/null) || exit 0 +[ -n "$since" ] || exit 0 +if [ $(($(date +%s) - since)) -lt "${ALERT_AFTER:?}" ]; then + echo "ci-runner-mail-hold: the minting of $slot has failed for less than $ALERT_AFTER s; no mail yet" + exit 1 +fi diff --git a/ansible/ci/roles/actions_runners/tasks/main.yml b/ansible/ci/roles/actions_runners/tasks/main.yml index 95162578..e1add153 100644 --- a/ansible/ci/roles/actions_runners/tasks/main.yml +++ b/ansible/ci/roles/actions_runners/tasks/main.yml @@ -107,7 +107,7 @@ owner: root group: root mode: "0755" - loop: [ci-runner-jit, ci-runner-unregister, ci-runner-slot, ci-connect-refresh, ci-runner-housekeeping] + loop: [ci-runner-jit, ci-runner-unregister, ci-runner-slot, ci-connect-refresh, ci-runner-housekeeping, ci-runner-mail-hold] - name: Create the shared caches ansible.builtin.file: @@ -259,6 +259,9 @@ ExecStart=/usr/local/sbin/ci-runner-slot %i ExecStopPost=-/usr/bin/docker rm --force --volumes ci-runner-%i ExecStopPost=-/usr/bin/rm -f /run/ci-runner/%i.env + # A slot stopped in a failed minting's wait ends the row of failures + # (ci-runner-jit, ci-runner-mail-hold); a failed end keeps it. + ExecStopPost=-/bin/sh -c '[ "$$SERVICE_RESULT" != success ] || rm -f /run/ci-runner/%i.failing' TimeoutStartSec=5min TimeoutStopSec=1min SuccessExitStatus=143 @@ -272,6 +275,30 @@ WantedBy=multi-user.target notify: [Reload systemd, Restart the slots] +# The host's mail on a failed unit (plexus.host.mail, where the playbook sets +# it up) waits on a slot whose minting has failed until it has for +# actions_runners_slot_alert_after (files/ci-runner-mail-hold). A drop-in of +# the unit that sends it, harmless on a host without it. +- name: Create the drop-in directory of the failure mail + ansible.builtin.file: + path: /etc/systemd/system/failure-mail@.service.d + state: directory + owner: root + group: root + mode: "0755" + +- name: Hold back the mail on a slot that has not failed to mint for long + ansible.builtin.copy: + dest: /etc/systemd/system/failure-mail@.service.d/20-ci-runner.conf + owner: root + group: root + mode: "0644" + content: | + [Service] + Environment=ALERT_AFTER={{ actions_runners_slot_alert_after }} + ExecCondition=/usr/local/sbin/ci-runner-mail-hold %i + notify: Reload systemd + - name: Install the housekeeping service ansible.builtin.copy: dest: /etc/systemd/system/ci-runner-housekeeping.service diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja index 95f7ade0..5c49f216 100644 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja @@ -1,5 +1,5 @@ # Generated from plexus-ms/tooling, templates/repo-operations: edit the template, never this file. -# One runner host per entry of `hosts` (hosts.auto.tfvars). A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. +# One runner host per entry of `hosts` (hosts.auto.tfvars). A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. A host reads what it needs from the vault {{ github_org }}-ci-host, among it the item mail-relay (server, port, mode, username, password, from-address, mailto), the relay through which it mails the tenant when a unit fails, its disk passes the housekeeping's threshold or a slot cannot register; without the item a host is set up all the same, sends no mail and says so in its journal, and a host takes a new item only when it is replaced. terraform { required_providers { hcloud = { diff --git a/terraform/ci_runner_host_user_data/main.tf b/terraform/ci_runner_host_user_data/main.tf index 55949897..ee982db2 100644 --- a/terraform/ci_runner_host_user_data/main.tf +++ b/terraform/ci_runner_host_user_data/main.tf @@ -14,8 +14,9 @@ # - installs the collections, then runs plexus.ci.playbook on the host. # # The role is the implementation: the playbook installs the vault's CLI and -# reads every other secret from the vault itself. The user-data states the -# host and holds no logic. +# reads every other secret from the vault itself, the tenant's mail relay +# among them, the item mail-relay, without which the host sends no mail and +# says so in its journal. The user-data states the host and holds no logic. # # The output carries the one secret, so it is sensitive, and so is the state # or plan file of a caller that keeps it. The text is a function of the diff --git a/terraform/hcloud_ci_runner_host/main.tf b/terraform/hcloud_ci_runner_host/main.tf index 12926633..6868626e 100644 --- a/terraform/hcloud_ci_runner_host/main.tf +++ b/terraform/hcloud_ci_runner_host/main.tf @@ -14,6 +14,14 @@ # does too, and the state keeps a hash of it: the module marks it sensitive, # which keeps it out of the plan's text, not out of the files. # +# The vault's item mail-relay (server, port, mode, username, password, +# from-address, mailto) is the tenant's mail relay, through which the host +# mails the tenant when a unit of its own fails, its disk passes the +# housekeeping's threshold, or a slot cannot register for minutes. A vault +# without it gives a host that is set up all the same, sends no mail, and +# says so in its journal; a host takes a new item only when it is replaced. +# The playbook's vars/vault.yml names every item it reads. +# # What the module creates: the machine, and a firewall attached to it at # creation. A runner host needs nothing inbound at the provider: the slots # poll the forge, and the cache servers listen on loopback and, with From 7b016c2898e946d79a3f839c826b56d4f0af4506 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 03:30:50 +0100 Subject: [PATCH 04/11] test: a runner host's mail survives a partial item, a failed mail role, and a failure of the same unit earlier that day (PLX-253) New and changed cases of the runner host's mail newborn, ahead of the code: an item that lacks a field, leaves one empty or names an unknown mode is no item, and a field on the command line counts; a mail role that fails fails no run; the disk check mails although the housekeeping mailed that day; a slot that cannot register mails although its container failed that day; the row of failed mintings fails towards mailing (a row or a threshold that is no number, a stop between two attempts, a minting systemd ends for its time); mail_loopback_smtp opens the port again and closes it. Co-Authored-By: Claude Opus 5.5 --- newborns/runner-host-mail.test.ts | 243 +++++++++++++++++++++++++----- 1 file changed, 205 insertions(+), 38 deletions(-) diff --git a/newborns/runner-host-mail.test.ts b/newborns/runner-host-mail.test.ts index d27b5c42..a22a2c74 100644 --- a/newborns/runner-host-mail.test.ts +++ b/newborns/runner-host-mail.test.ts @@ -4,21 +4,30 @@ // on the host's loopback that takes STARTTLS and AUTH, as a tenant's relay // does, and records every message it is handed, and a runner that waits for a // job that never comes, in place of a slot's container. The forge refuses to -// mint a slot's runner config when the test says so. The relay's address, -// credentials, sender and recipient are the vault's item mail-relay. +// mint a slot's runner config, or keeps the minting waiting, when the test +// says so. The relay's address, credentials, sender and recipient are the +// vault's item mail-relay. // -// A host whose vault has no mail-relay is set up all the same, runs its slots, -// and says in its journal that it sends no mail. With the item, the host mails +// A host whose vault has no mail-relay, or one that lacks a field, leaves one +// empty or names a mode Postfix does not know, is set up all the same, runs +// its slots, and says in its journal that it sends no mail and why; a field +// given on the command line counts. So is a host whose mail role fails, here +// on a Postfix that cannot be installed. With the item, the host mails // through the relay, with the item's credentials, from its sender to its // recipient, and takes no mail over SMTP from what shares its loopback, the // slots included: one mail for a unit that fails (BuildKit, a cache server, a -// slot's container), one for a disk fuller than the housekeeping's threshold, -// none for a slot whose minting failed once, and one, saying for how long, for -// a slot whose minting has failed for longer than the threshold the run gives -// (actions_runners_slot_alert_after); never one per attempt. A relay that -// refuses is said in the journal, and the host is set up all the same. Nothing -// reaches a real vault, App, relay or mailbox. Needs Docker and the network, -// as the newborns do. +// slot's container), one for a disk fuller than the threshold whatever the +// housekeeping failed at before, none for a slot whose minting failed once, +// and one, saying for how long, for a slot whose minting has failed for +// longer than the threshold the run gives (actions_runners_slot_alert_after), +// whatever its container failed at before; never one per attempt. The row of +// failed mintings fails towards mailing: a row that holds no number or a +// threshold that is none mails at once, a stop between two attempts leaves no +// row for the next start, and a minting systemd ends for its time counts. A +// relay that refuses is said in the journal, and the host is set up all the +// same. The SMTP port on loopback opens again and closes again with +// mail_loopback_smtp. Nothing reaches a real vault, App, relay or mailbox. +// Needs Docker and the network, as the newborns do. import assert from 'node:assert/strict'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; @@ -64,9 +73,10 @@ cat "$file" /** * The forge, as far as ci-runner-jit asks it. A minting is refused (500) while * /var/lib/stand-in/refuse-mint says `always`, or as many times as the number - * it holds; each minting it answers, and each it refuses, is a line of a log. + * it holds, and keeps it waiting for a minute while /var/lib/stand-in/hang-mint + * exists; each minting it answers, and each it refuses, is a line of a log. */ -const FORGE = `import http.server, json, os, ssl +const FORGE = `import http.server, json, os, ssl, time REFUSE = "/var/lib/stand-in/refuse-mint" def refused(): try: @@ -94,6 +104,7 @@ class Api(http.server.BaseHTTPRequestHandler): body = self.rfile.read(int(self.headers.get("Content-Length", 0))) if self.path.endswith("/access_tokens"): return self.answer(201, {"token": "t"}) if self.path.endswith("/generate-jitconfig"): + if os.path.exists("/var/lib/stand-in/hang-mint"): time.sleep(60) refuse = refused() with open("/var/log/forge-stand-in.jsonl", "a") as log: log.write(json.dumps({"name": json.loads(body)["name"], "refused": refuse}) + "\\n") @@ -217,6 +228,10 @@ const VALUES = { actions_runners_slot_alert_after: ALERT_AFTER, }; const SLOT = 'ci-runner@repo-1.service'; +/** The unit that says a slot cannot register, of a mail budget apart from the slot's. */ +const CANNOT = 'ci-runner-cannot-register@repo-1.service'; +/** The row of the slot's failed mintings. */ +const ROW = '/run/ci-runner/repo-1.failing'; let here = ''; let host = ''; @@ -373,6 +388,16 @@ async function mintings(): Promise<{ name: string; refused: boolean }[]> { return log ? log.split('\n').map((line) => JSON.parse(line)) : []; } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +/** What the playbook said last in the journal. */ +const lastSaid = async () => + (await onHost('journalctl', '--no-pager', '-t', 'plexus-ci', '-o', 'cat', '-n', '1')).trim(); +/** Until the slot runs. */ +const slotRuns = () => + until( + 'the slot to run again', + async () => (await shellOnHost(`systemctl is-active ${SLOT}`)).output.trim() === 'active', + 180_000, + ); describe('a runner host mails its tenant', () => { test('a host whose vault has no item mail-relay is set up all the same, runs its slots, and says in its journal that it sends no mail', async () => { @@ -386,6 +411,46 @@ describe('a runner host mails its tenant', () => { assert.equal((await shellOnHost('dpkg -s postfix')).ok, false); }); + test('an item that lacks a field, leaves one empty or names an unknown mode is no item: the run passes and the journal says what is wrong; a field given on the command line counts', async () => { + const partial: Record = { ...RELAY, 'mail-relay/port': '', 'mail-relay/mode': 'pigeon' }; + delete partial['mail-relay/mailto']; + for (const [field, value] of Object.entries(partial)) + put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); + try { + const ran = await play(['-e', JSON.stringify({ ci_mail_mailto: 'alerts@example.org' })]); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await onHost('systemctl', 'is-active', SLOT)).trim(), 'active'); + const said = await lastSaid(); + assert.match(said, /sends no mail/); + assert.match(said, /\bport\b/); + assert.match(said, /\bpigeon\b/); + assert.doesNotMatch(said, /mailto/); + assert.equal((await shellOnHost('dpkg -s postfix')).ok, false); + } finally { + await onHost('rm', '-r', '/stand-in/vault/acme-ci-host/mail-relay'); + } + }); + + test('a mail role that fails, as where Postfix cannot be installed, fails no run: the slots run, and the journal says the host sends no mail', async () => { + for (const [field, value] of Object.entries(RELAY)) put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); + await onHost( + 'sh', + '-c', + 'printf "Package: postfix\\nPin: version *\\nPin-Priority: -1\\n" >/etc/apt/preferences.d/stand-in-no-postfix', + ); + try { + const ran = await play(); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await onHost('systemctl', 'is-active', SLOT)).trim(), 'active'); + const said = await lastSaid(); + assert.match(said, /sends no mail/); + assert.match(said, /plexus\.host\.mail/); + assert.equal((await shellOnHost('dpkg -s postfix')).ok, false); + } finally { + await onHost('rm', '/etc/apt/preferences.d/stand-in-no-postfix'); + } + }); + test('with the item, a run at -vvv passes and prints none of it, and the host takes no mail over SMTP from its loopback, which the slots share', async () => { for (const [field, value] of Object.entries(RELAY)) put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); const ran = await play(['-vvv']); @@ -410,32 +475,44 @@ describe('a runner host mails its tenant', () => { assert.equal((await about('ci-turbo-cache@shared.service')).length, 1); }); - test('a disk fuller than the housekeeping’s threshold is one mail that says how full, however often the housekeeping finds it', async () => { + test('a disk fuller than the threshold is one mail that says how full, however often it is found, and whatever the housekeeping failed at before that day', async () => { // The disk is the test machine's: the threshold goes under what it holds instead. const used = Number((await onHost('sh', '-c', "df --output=pcent / | tail -1 | tr -dc '0-9'")).trim()); + const threshold = Math.max(used - 1, 0); + const units = '/etc/systemd/system'; await onHost( 'sh', '-c', - `mkdir -p /etc/systemd/system/ci-runner-housekeeping.service.d && printf "[Service]\\nEnvironment=DISK_ALERT_PERCENT=${Math.max(used - 1, 0)}\\n" >/etc/systemd/system/ci-runner-housekeeping.service.d/stand-in.conf && systemctl daemon-reload`, + `mkdir -p ${units}/ci-runner-housekeeping.service.d ${units}/ci-runner-disk.service.d && printf "[Service]\\nEnvironment=IMAGE=127.0.0.1:9/nowhere:1\\n" >${units}/ci-runner-housekeeping.service.d/stand-in.conf && printf "[Service]\\nEnvironment=DISK_ALERT_PERCENT=${threshold}\\n" >${units}/ci-runner-disk.service.d/stand-in.conf && systemctl daemon-reload`, ); try { + // A pull that fails, earlier the same day: the housekeeping's one mail of the day. + assert.equal((await shellOnHost('systemctl start ci-runner-housekeeping.service')).ok, false); + await oneMailAbout('ci-runner-housekeeping.service'); for (let run = 0; run < 2; run++) - assert.equal((await shellOnHost('systemctl start ci-runner-housekeeping.service')).ok, false); - const mail = await oneMailAbout('ci-runner-housekeeping.service'); + assert.equal((await shellOnHost('systemctl start ci-runner-disk.service')).ok, false); + const mail = await oneMailAbout('ci-runner-disk.service'); assert.match(mail.text, /root file system \d+% used/); - assert.match(mail.text, new RegExp(`above ${Math.max(used - 1, 0)}%`)); + assert.match(mail.text, new RegExp(`above ${threshold}%`)); await settled(); + assert.equal((await about('ci-runner-disk.service')).length, 1); assert.equal((await about('ci-runner-housekeeping.service')).length, 1); } finally { - await onHost( - 'sh', - '-c', - 'rm -r /etc/systemd/system/ci-runner-housekeeping.service.d && systemctl daemon-reload && systemctl reset-failed ci-runner-housekeeping.service', + await shellOnHost( + `rm -r ${units}/ci-runner-housekeeping.service.d ${units}/ci-runner-disk.service.d; systemctl daemon-reload; systemctl reset-failed ci-runner-housekeeping.service ci-runner-disk.service`, ); } }); - test('a slot whose minting fails once mails nobody; one whose minting has failed for longer than the threshold mails once, saying for how long', async () => { + test('a slot whose container fails is one mail at once, as any unit', async () => { + await onHost('systemctl', 'kill', '--signal=SIGKILL', '--kill-whom=main', SLOT); + await oneMailAbout(SLOT, 60_000); + await settled(); + assert.equal((await about(SLOT)).length, 1); + await slotRuns(); + }); + + test('a slot whose minting fails once mails nobody; one whose minting has failed for longer than the threshold mails once, saying for how long, although its container failed the same day', async () => { const before = (await mintings()).length; // One failed attempt: ci-runner-jit asks three times before it gives up. await onHost('sh', '-c', 'echo 3 >/var/lib/stand-in/refuse-mint'); @@ -454,38 +531,114 @@ describe('a runner host mails its tenant', () => { ); await sleep((ALERT_AFTER + 15) * 1000); await settled(); - assert.deepEqual(await about(SLOT), []); + assert.equal((await about(SLOT)).length, 1, 'the container’s mail alone'); + assert.deepEqual(await about(CANNOT), []); await onHost('sh', '-c', 'echo always >/var/lib/stand-in/refuse-mint'); try { const refusedFrom = Date.now(); await onHost('systemctl', 'restart', '--no-block', SLOT); - const mail = await oneMailAbout(SLOT, 5 * 60_000); + const mail = await oneMailAbout(CANNOT, 5 * 60_000); assert.ok(Date.now() - refusedFrom >= ALERT_AFTER * 1000, 'mailed before the threshold'); assert.match(mail.text, /has failed .*for 1 min/); // Two more attempts, each refused: no further mail. const attempts = (await mintings()).length; await until('two more refused attempts', async () => (await mintings()).length >= attempts + 6, 180_000); await settled(); - assert.equal((await about(SLOT)).length, 1); + assert.equal((await about(CANNOT)).length, 1); + assert.equal((await about(SLOT)).length, 1, 'the container’s mail alone'); } finally { await onHost('rm', '-f', '/var/lib/stand-in/refuse-mint'); } - await until( - 'the slot to run again', - async () => (await shellOnHost(`systemctl is-active ${SLOT}`)).output.trim() === 'active', - 180_000, + await slotRuns(); + }); + + test('the row of a slot’s failed mintings fails towards mailing: a row that holds no number, or a threshold that is none, mails at once and says so', async () => { + // By hand, for a slot this host does not run. + const row = '/run/ci-runner/repo-9.failing'; + const now = (minus = 0) => `read up _ ${row}`; + const cannot = (after = '60') => + shellOnHost(`ALERT_AFTER=${after} /usr/local/sbin/ci-runner-cannot-register repo-9 2>&1`); + const hold = () => shellOnHost('/usr/local/sbin/ci-runner-mail-hold ci-runner@repo-9.service 2>&1'); + try { + // No row: nothing to say, and a failure of the slot is mailed. + await onHost('rm', '-f', row); + assert.equal((await cannot()).ok, true); + assert.equal((await hold()).ok, true); + // A row younger than the threshold: no mail yet, of either. + await onHost('sh', '-c', `mkdir -p /run/ci-runner && ${now()}`); + assert.equal((await cannot()).ok, true); + assert.equal((await hold()).ok, false); + // Older: the mail, which says for how long. + await onHost('sh', '-c', now(150)); + const old = await cannot(); + assert.equal(old.ok, false); + assert.match(old.output, /for 2 min \d+ s/); + // A row that holds no number: both mail, and the mail says what the row holds. + await onHost('sh', '-c', `echo garbage >${row}`); + const garbage = await cannot(); + assert.equal(garbage.ok, false); + assert.match(garbage.output, /garbage/); + assert.equal((await hold()).ok, true); + // A threshold that is no number: the mail, which says so. + await onHost('sh', '-c', now()); + const soon = await cannot('soon'); + assert.equal(soon.ok, false); + assert.match(soon.output, /soon/); + } finally { + await onHost('rm', '-f', row); + } + }); + + test('a slot stopped between two failed attempts starts a new row when it is started again', async () => { + // A wait between the attempts long enough to stop the slot in. + const gap = '/etc/systemd/system/ci-runner@.service.d/stand-in-gap.conf'; + await onHost( + 'sh', + '-c', + `printf "[Service]\\nRestartSec=40s\\n" >${gap} && systemctl daemon-reload && echo always >/var/lib/stand-in/refuse-mint`, ); + try { + await onHost('systemctl', 'restart', '--no-block', SLOT); + await until( + 'the slot to wait between two attempts', + async () => (await shellOnHost(`systemctl show -P SubState ${SLOT}`)).output.trim() === 'auto-restart', + 180_000, + ); + const first = (await onHost('cat', ROW)).trim(); + await onHost('systemctl', 'stop', SLOT); + assert.equal((await onHost('cat', ROW)).trim(), first, 'the stop came between two attempts'); + await sleep(2000); + const attempts = (await mintings()).length; + await onHost('systemctl', 'start', '--no-block', SLOT); + await until('a new attempt', async () => (await mintings()).length > attempts, 120_000); + assert.notEqual((await onHost('cat', ROW)).trim(), first); + } finally { + await onHost('sh', '-c', `rm -f ${gap} /var/lib/stand-in/refuse-mint && systemctl daemon-reload`); + } + await slotRuns(); }); - test('a slot whose container fails is one mail at once, as any unit', async () => { - // As if a day had passed since the slot's last mail. - await onHost('rm', '-f', `/var/lib/failure-mail/${SLOT}`); - const earlier = (await about(SLOT)).length; - await onHost('systemctl', 'kill', '--signal=SIGKILL', '--kill-whom=main', SLOT); - await until('a second mail about the slot', async () => (await about(SLOT)).length > earlier, 60_000); - await settled(); - assert.equal((await about(SLOT)).length, earlier + 1); + test('a minting that hangs until systemd ends it counts in the row', async () => { + const limit = '/etc/systemd/system/ci-runner@.service.d/stand-in-timeout.conf'; + await onHost( + 'sh', + '-c', + `printf "[Service]\\nTimeoutStartSec=20s\\n" >${limit} && systemctl daemon-reload && touch /var/lib/stand-in/hang-mint`, + ); + try { + assert.equal((await shellOnHost(`test -e ${ROW}`)).ok, false, 'a row before the test'); + await onHost('systemctl', 'restart', '--no-block', SLOT); + await until( + 'systemd to end the minting', + async () => (await shellOnHost(`systemctl show -P Result ${SLOT}`)).output.trim() === 'timeout', + 120_000, + ); + assert.equal((await shellOnHost(`test -s ${ROW}`)).ok, true); + } finally { + await onHost('sh', '-c', `rm -f ${limit} /var/lib/stand-in/hang-mint && systemctl daemon-reload`); + } + await slotRuns(); }); test('a relay that refuses is said in the journal, and the host is set up all the same', async () => { @@ -506,4 +659,18 @@ describe('a runner host mails its tenant', () => { await onHost('rm', '-f', '/var/lib/stand-in/relay-refuse'); } }); + + test('mail_loopback_smtp true opens the SMTP port on loopback again, false closes it, and a run after that changes nothing there', async () => { + const listens = async () => (await onHost('ss', '-Hltn', 'sport = :25')).trim() !== ''; + const opened = await play(['--tags', 'mail', '-e', JSON.stringify({ mail_loopback_smtp: true })]); + assert.equal(opened.ok, true, opened.output.slice(-6000)); + await until('Postfix to listen on port 25', listens, 30_000); + const closed = await play(['--tags', 'mail']); + assert.equal(closed.ok, true, closed.output.slice(-6000)); + await until('Postfix to listen on port 25 no more', async () => !(await listens()), 30_000); + const again = await play(['--tags', 'mail']); + assert.equal(again.ok, true, again.output.slice(-6000)); + assert.match(again.output, /TASK \[plexus\.host\.mail : Close the SMTP port on loopback\][^\n]*\nok: /); + assert.equal(await listens(), false); + }); }); From be3d060b992ec38928f23ac23d2b39d755d08adf Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 03:48:42 +0100 Subject: [PATCH 05/11] test: the hung minting starts from a running slot (PLX-253) Co-Authored-By: Claude Opus 5.5 --- newborns/runner-host-mail.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/newborns/runner-host-mail.test.ts b/newborns/runner-host-mail.test.ts index a22a2c74..8dddb298 100644 --- a/newborns/runner-host-mail.test.ts +++ b/newborns/runner-host-mail.test.ts @@ -621,6 +621,7 @@ describe('a runner host mails its tenant', () => { test('a minting that hangs until systemd ends it counts in the row', async () => { const limit = '/etc/systemd/system/ci-runner@.service.d/stand-in-timeout.conf'; + await slotRuns(); await onHost( 'sh', '-c', From 12a4d1a7d286c9dd530b315bbe3dee85ba37dfb8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 04:05:02 +0100 Subject: [PATCH 06/11] plexus.ci: the disk and a slot that cannot register are units of their own, with a mail budget of their own (PLX-253) ci-runner-disk, hourly by its own timer, is the disk check the housekeeping ran after its pull: a pull that failed earlier the same day no longer takes the disk's mail, and one that fails for a full disk no longer keeps the check from running. ci-runner-cannot-register@, started by the slot's ExecStopPost after an attempt that failed, fails once the row of failed mintings is older than actions_runners_slot_alert_after and says for how long; a container of the slot that failed earlier the same day takes nothing from its mail. The slot's own mail is held back for a failed minting alone. The row fails towards mailing: it holds the host's uptime, which no time step moves; it is written as an attempt starts, so that one systemd ends for its time counts; a start that is no restart of systemd's begins a new one; a row or a threshold that holds no number mails at once and says so. Co-Authored-By: Claude Opus 5.5 --- .../roles/actions_runners/defaults/main.yml | 21 ++--- .../files/ci-runner-cannot-register | 48 +++++++++++ .../actions_runners/files/ci-runner-disk | 18 +++++ .../files/ci-runner-housekeeping | 16 ++-- .../roles/actions_runners/files/ci-runner-jit | 42 +++++----- .../actions_runners/files/ci-runner-mail-hold | 41 +++++----- .../ci/roles/actions_runners/tasks/main.yml | 80 +++++++++++++++---- 7 files changed, 187 insertions(+), 79 deletions(-) create mode 100755 ansible/ci/roles/actions_runners/files/ci-runner-cannot-register create mode 100755 ansible/ci/roles/actions_runners/files/ci-runner-disk diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index 6f61d27d..748c7a8e 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -70,13 +70,15 @@ # # Where the playbook sets up the host's mail (plexus.host.mail), a unit that # fails is a mail, at most once a day per unit: a slot's container, BuildKit, -# the housekeeping, which fails on a disk fuller than -# actions_runners_disk_alert_percent. A slot fails at every attempt that -# fails, and is started again: one whose minting failed is held back from the -# mail until the minting has failed for actions_runners_slot_alert_after -# (files/ci-runner-mail-hold), so that one refusal of the forge mails nobody -# and a slot that cannot register does, with how long in its journal. Without -# the host's mail every failure shows in the journal alone. +# the housekeeping. Two units exist to fail, so that a mail says so, each with +# a budget of its own: ci-runner-disk, hourly, on a disk fuller than +# actions_runners_disk_alert_percent, and ci-runner-cannot-register@, +# on a slot whose minting has failed at every attempt for +# actions_runners_slot_alert_after, which says for how long. A slot fails at +# every attempt that fails, and is started again; its own mail is held back +# for a failed minting (files/ci-runner-mail-hold), so that one refusal of the +# forge mails nobody. Without the host's mail every failure shows in the +# journal alone. # Where the slots register: `org` at the organisation, in a runner group of # it, `repo` on one repository (they are then that repository's alone, @@ -215,8 +217,9 @@ actions_runners_connect_uid: 999 actions_runners_connect_port: 8080 # Housekeeping, hourly: the registry pair onto this week's buckets, the -# pinned image pulled, stopped containers, unused images and volumes removed; -# fails when the root file system is fuller than this afterwards. +# pinned image pulled, stopped containers, unused images and volumes removed. +# The disk check, hourly too, a unit of its own: fails when the root file +# system is fuller than this, in percent. actions_runners_disk_alert_percent: 85 # How long, in seconds, a slot's minting fails at every attempt before the diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-cannot-register b/ansible/ci/roles/actions_runners/files/ci-runner-cannot-register new file mode 100755 index 00000000..b3e20e94 --- /dev/null +++ b/ansible/ci/roles/actions_runners/files/ci-runner-cannot-register @@ -0,0 +1,48 @@ +#!/bin/sh +# Says that a slot cannot register, as a unit that fails, so that the host's +# mail on a failed unit (plexus.host.mail) mails it with a daily budget of its +# own (ci-runner-cannot-register@.service): a container of the slot that +# failed earlier the same day takes nothing from it. Managed by Ansible +# (actions_runners). +# +# The slot's ExecStopPost starts it after every attempt that failed. It fails +# when the slot's row of failed mintings, /run/ci-runner/.failing (the +# host's uptime in seconds as the row's first attempt started, which +# ci-runner-jit writes), is older than ALERT_AFTER seconds, and says for how +# long; the mail carries what it says and the slot's last lines. Without a +# row, or with a younger one, it exits 0 and nobody is mailed. It fails +# towards mailing: a row or a threshold that is no number fails at once and +# says what it holds. Hand-runnable as root: +# +# ALERT_AFTER=300 ci-runner-cannot-register repo-1; echo $? +slot=${1:?the slot, e.g. repo-1} +row=/run/ci-runner/$slot.failing +[ -e "$row" ] || exit 0 +since=$(cat "$row" 2>/dev/null) +after=${ALERT_AFTER:-} + +fail() { + echo "ci-runner-cannot-register: $*" + echo "The last lines of ci-runner@$slot.service:" + journalctl --no-pager -o cat -n 20 -u "ci-runner@$slot.service" || true + exit 1 +} + +case $since in + '' | *[!0-9]*) fail "the slot $slot has failed to mint its runner config, and its row $row holds no number but '$since'" ;; +esac +case $after in + '' | *[!0-9]*) fail "the slot $slot has failed to mint its runner config, and the threshold ALERT_AFTER is no number but '$after'" ;; +esac +read -r up _ &2 + exit 1 +fi diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping index eef6a646..0e822470 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping +++ b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping @@ -1,12 +1,13 @@ #!/bin/sh # Hourly housekeeping of a CI runner host. Managed by Ansible # (actions_runners); IMAGE, PULL (false for an image built on the host), -# REGISTRY (true | false), REGISTRY_IMAGE and DISK_ALERT_PERCENT come from -# the unit's environment. Hand-runnable as root: +# REGISTRY (true | false) and REGISTRY_IMAGE come from the unit's +# environment. How full the disk is, ci-runner-disk says, a unit of its own. +# Hand-runnable as root: # IMAGE=ghcr.io/plexus-ms/ci-runner: PULL=true REGISTRY=true \ -# REGISTRY_IMAGE=registry:2 DISK_ALERT_PERCENT=85 ci-runner-housekeeping +# REGISTRY_IMAGE=registry:2 ci-runner-housekeeping set -eu -: "${IMAGE:?}" "${PULL:?}" "${REGISTRY:?}" "${REGISTRY_IMAGE:?}" "${DISK_ALERT_PERCENT:?}" +: "${IMAGE:?}" "${PULL:?}" "${REGISTRY:?}" "${REGISTRY_IMAGE:?}" # The registry pair onto this week's buckets, first: a failure here is the # one that costs every run of the week a cold cache. @@ -31,10 +32,3 @@ done # The BuildKit service (ci-buildkit) keeps its cache in /var/lib/buildkit, # outside this daemon, and bounds it by its own garbage collection; nothing # here touches it, since a build may be using it. - -used=$(df --output=pcent / | tail -1 | tr -dc '0-9') -echo "root file system ${used}% used" -if [ "$used" -gt "$DISK_ALERT_PERCENT" ]; then - echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the repo slots' caches: the pnpm store, mise, corepack, Playwright), docker system df, and du -sh /var/lib/buildkit against maxUsedSpace in /etc/buildkit/buildkitd.toml" >&2 - exit 1 -fi diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-jit b/ansible/ci/roles/actions_runners/files/ci-runner-jit index c578ccc8..47e695ee 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-jit +++ b/ansible/ci/roles/actions_runners/files/ci-runner-jit @@ -33,31 +33,31 @@ esac name="$HOST-$instance" out=/run/ci-runner/$instance.env -# A failure waits before it fails, so that a forge outage costs one attempt -# per slot every half minute rather than every restart interval. It also -# keeps the time of the first of the failed attempts in a row, in $failing, -# and says, as it fails, for how long the slot has failed: the host's mail -# on a failed unit (plexus.host.mail) holds back a slot's while the minting -# has failed for less than a few minutes (ci-runner-mail-hold), and the -# mail, which carries the slot's journal, then says for how long. A minting -# that succeeds ends the row. +# The row of failed attempts, $failing: the host's uptime in seconds as the +# row's first attempt started, a clock no time step moves and that starts +# again with /run at a boot. Each attempt starts the row where there is none, +# so that an attempt systemd ends for its time counts too, and a minting that +# succeeds ends it. A start of the slot that is not one of systemd's restarts +# (NRestarts 0) begins a new row, since a stop between two attempts runs no +# ExecStopPost and leaves the old one. After an attempt that failed the +# slot's ExecStopPost starts ci-runner-cannot-register@, which mails +# once the row is older than a few minutes; ci-runner-mail-hold keeps the +# slot's own mail for a container that failed after it minted. failing=/run/ci-runner/$instance.failing +mkdir -p /run/ci-runner +if [ "$(systemctl show -P NRestarts "ci-runner@$instance.service")" = 0 ]; then + rm -f "$failing" +fi +if [ ! -e "$failing" ]; then + read -r up _ "$failing" +fi + +# A failure waits before it fails, so that a forge outage costs one attempt +# per slot every half minute rather than every restart interval. minting_failed() { - local since took echo "ci-runner-jit: minting the config of $name failed" >&2 - mkdir -p /run/ci-runner - [ -s "$failing" ] || date +%s >"$failing" sleep 30 - since=$(cat "$failing") - took=$(($(date +%s) - since)) - if [ "$took" -ge 3600 ]; then - took="$((took / 3600)) h $((took % 3600 / 60)) min" - elif [ "$took" -ge 60 ]; then - took="$((took / 60)) min $((took % 60)) s" - else - took="$took s" - fi - echo "ci-runner-jit: $name has failed to mint its config at every attempt for $took, since $(date -u -d "@$since" '+%Y-%m-%d %H:%M:%S UTC')" >&2 } trap minting_failed ERR diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold b/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold index 18b57b69..0a57e421 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold +++ b/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold @@ -1,23 +1,20 @@ #!/bin/sh -# Holds back the host's mail on a failed slot while the slot's minting has -# failed for less than ALERT_AFTER seconds (ExecCondition of -# failure-mail@.service, plexus.host.mail, by a drop-in of this role). -# Managed by Ansible (actions_runners). +# Holds back the host's mail on a slot that failed in its minting +# (ExecCondition of failure-mail@.service, plexus.host.mail, by a drop-in of +# this role): ci-runner-cannot-register@ mails that, once the minting +# has failed for a few minutes, with a daily budget of its own. Managed by +# Ansible (actions_runners). # -# A slot fails as a unit at every failed attempt and is started again; a -# failed unit starts failure-mail@, which mails the unit's status and -# journal at most once a day (mail_failure_interval). One forge that refuses -# one minting is no news, a slot that has not registered for minutes is: -# jobs queue. So the mail on a slot whose minting failed waits until -# ci-runner-jit has kept the first failed attempt of the row for -# ALERT_AFTER seconds (/run/ci-runner/.failing, which a minting that -# succeeds removes); the slot's journal, which the mail carries, then says -# for how long. A slot whose container failed after it minted, and every -# other unit, is mailed at once, as on any host. Exits 0 to mail, 1 to hold -# back, which systemd counts as no failure of failure-mail@. +# A slot fails as a unit at every attempt that fails, and is started again. +# The slot's row of failed mintings, /run/ci-runner/.failing, which +# ci-runner-jit writes as an attempt starts and removes once it has minted, +# tells a minting that failed from a container that failed after it: the +# second is mailed at once, as every other unit is. It fails towards mailing: +# a row that is missing or holds no number lets the slot's mail go. Exits 0 +# to mail, 1 to hold back, which systemd counts as no failure of +# failure-mail@. # -# ALERT_AFTER=300 ci-runner-mail-hold ci-runner@repo-1.service; echo $? -set -eu +# ci-runner-mail-hold ci-runner@repo-1.service; echo $? unit=${1:?the unit that failed, e.g. ci-runner@repo-1.service} case $unit in ci-runner@*.service) ;; @@ -26,8 +23,8 @@ esac slot=${unit#ci-runner@} slot=${slot%.service} since=$(cat "/run/ci-runner/$slot.failing" 2>/dev/null) || exit 0 -[ -n "$since" ] || exit 0 -if [ $(($(date +%s) - since)) -lt "${ALERT_AFTER:?}" ]; then - echo "ci-runner-mail-hold: the minting of $slot has failed for less than $ALERT_AFTER s; no mail yet" - exit 1 -fi +case $since in + '' | *[!0-9]*) exit 0 ;; +esac +echo "ci-runner-mail-hold: $slot failed in its minting; ci-runner-cannot-register@$slot.service mails that" +exit 1 diff --git a/ansible/ci/roles/actions_runners/tasks/main.yml b/ansible/ci/roles/actions_runners/tasks/main.yml index e1add153..c579b038 100644 --- a/ansible/ci/roles/actions_runners/tasks/main.yml +++ b/ansible/ci/roles/actions_runners/tasks/main.yml @@ -107,7 +107,15 @@ owner: root group: root mode: "0755" - loop: [ci-runner-jit, ci-runner-unregister, ci-runner-slot, ci-connect-refresh, ci-runner-housekeeping, ci-runner-mail-hold] + loop: + - ci-runner-jit + - ci-runner-unregister + - ci-runner-slot + - ci-connect-refresh + - ci-runner-housekeeping + - ci-runner-disk + - ci-runner-cannot-register + - ci-runner-mail-hold - name: Create the shared caches ansible.builtin.file: @@ -259,9 +267,11 @@ ExecStart=/usr/local/sbin/ci-runner-slot %i ExecStopPost=-/usr/bin/docker rm --force --volumes ci-runner-%i ExecStopPost=-/usr/bin/rm -f /run/ci-runner/%i.env - # A slot stopped in a failed minting's wait ends the row of failures - # (ci-runner-jit, ci-runner-mail-hold); a failed end keeps it. - ExecStopPost=-/bin/sh -c '[ "$$SERVICE_RESULT" != success ] || rm -f /run/ci-runner/%i.failing' + # A slot stopped while it mints ends the row of failed mintings + # (ci-runner-jit); an attempt that failed keeps it, and asks whether the + # row is old enough to mail about (ci-runner-cannot-register). + ExecStopPost=-/bin/sh -c 'if [ "$$SERVICE_RESULT" = success ]; then rm -f /run/ci-runner/%i.failing; \ + else systemctl start --no-block ci-runner-cannot-register@%i.service; fi' TimeoutStartSec=5min TimeoutStopSec=1min SuccessExitStatus=143 @@ -275,10 +285,29 @@ WantedBy=multi-user.target notify: [Reload systemd, Restart the slots] -# The host's mail on a failed unit (plexus.host.mail, where the playbook sets -# it up) waits on a slot whose minting has failed until it has for -# actions_runners_slot_alert_after (files/ci-runner-mail-hold). A drop-in of -# the unit that sends it, harmless on a host without it. +# A slot that cannot register is a unit that fails, once its minting has +# failed for actions_runners_slot_alert_after, so that the host's mail on a +# failed unit (plexus.host.mail, where the playbook sets it up) mails it with +# a budget of its own (files/ci-runner-cannot-register). The slot's own mail +# is held back for a failed minting and goes for a failed container +# (files/ci-runner-mail-hold), by a drop-in of the unit that sends it, +# harmless on a host without it. +- name: Install the unit that says a slot cannot register + ansible.builtin.copy: + dest: /etc/systemd/system/ci-runner-cannot-register@.service + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Say whether the CI runner slot %i has failed to register for long + + [Service] + Type=oneshot + Environment=ALERT_AFTER={{ actions_runners_slot_alert_after }} + ExecStart=/usr/local/sbin/ci-runner-cannot-register %i + notify: Reload systemd + - name: Create the drop-in directory of the failure mail ansible.builtin.file: path: /etc/systemd/system/failure-mail@.service.d @@ -287,7 +316,7 @@ group: root mode: "0755" -- name: Hold back the mail on a slot that has not failed to mint for long +- name: Hold back the slot's own mail on a failed minting ansible.builtin.copy: dest: /etc/systemd/system/failure-mail@.service.d/20-ci-runner.conf owner: root @@ -295,7 +324,6 @@ mode: "0644" content: | [Service] - Environment=ALERT_AFTER={{ actions_runners_slot_alert_after }} ExecCondition=/usr/local/sbin/ci-runner-mail-hold %i notify: Reload systemd @@ -317,19 +345,37 @@ Environment=PULL={{ (not actions_runners_image_build | bool) | lower }} Environment=REGISTRY={{ actions_runners_registry | bool | lower }} Environment=REGISTRY_IMAGE={{ actions_runners_registry_image }} - Environment=DISK_ALERT_PERCENT={{ actions_runners_disk_alert_percent }} ExecStart=/usr/local/sbin/ci-runner-housekeeping notify: Reload systemd -- name: Install the housekeeping timer +# How full the disk is, a unit apart from the housekeeping: the host's mail +# goes at most once a day per unit, and a pull that failed that day, or +# fails for a full disk, is to take neither the check nor its mail with it. +- name: Install the disk check ansible.builtin.copy: - dest: /etc/systemd/system/ci-runner-housekeeping.timer + dest: /etc/systemd/system/ci-runner-disk.service owner: root group: root mode: "0644" content: | [Unit] - Description=CI runner host housekeeping + Description=CI runner host disk check + + [Service] + Type=oneshot + Environment=DISK_ALERT_PERCENT={{ actions_runners_disk_alert_percent }} + ExecStart=/usr/local/sbin/ci-runner-disk + notify: Reload systemd + +- name: Install the timers of the housekeeping and the disk check + ansible.builtin.copy: + dest: /etc/systemd/system/ci-runner-{{ item }}.timer + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Hourly ci-runner-{{ item }} [Timer] OnCalendar=hourly @@ -338,16 +384,18 @@ [Install] WantedBy=timers.target + loop: [housekeeping, disk] notify: Reload systemd - name: Flush handlers ansible.builtin.meta: flush_handlers -- name: Enable the housekeeping timer +- name: Enable the timers of the housekeeping and the disk check ansible.builtin.systemd_service: - name: ci-runner-housekeeping.timer + name: ci-runner-{{ item }}.timer enabled: true state: started + loop: [housekeeping, disk] - name: Enable and start the slots ansible.builtin.systemd_service: From 0562500c98eb4b7f3021121536e8290322b53203 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 04:05:13 +0100 Subject: [PATCH 07/11] plexus.ci: a partial item, an empty field, an unknown mode or a failing mail role leave a host set up and say why it sends no mail (PLX-253) What is wrong with the mail relay is computed from the variables, so that a ci_mail_* given on the command line counts, as vars/vault.yml says of every variable; an empty field counts as missing, and a mode other than starttls or tls is said. The mail role runs first in the second play, in a block whose rescue says in the journal what failed, so that a Postfix that cannot be installed fails no run and stops no slot. Co-Authored-By: Claude Opus 5.5 --- ansible/ci/playbooks/playbook.yml | 82 +++++++++++++++++++++-------- ansible/ci/playbooks/vars/vault.yml | 5 +- 2 files changed, 62 insertions(+), 25 deletions(-) diff --git a/ansible/ci/playbooks/playbook.yml b/ansible/ci/playbooks/playbook.yml index 112e4ff9..1402eca4 100644 --- a/ansible/ci/playbooks/playbook.yml +++ b/ansible/ci/playbooks/playbook.yml @@ -55,14 +55,17 @@ # (plexus.host.mail): what it needs, the relay, its credentials, the sender # and the recipient, is the vault's item mail-relay. It mails once a day at # most per unit: when a unit fails (BuildKit, a cache server, a slot's -# container, the housekeeping, which fails on a disk fuller than -# actions_runners_disk_alert_percent), and when a slot has failed to mint its +# container, the housekeeping), when the disk is fuller than +# actions_runners_disk_alert_percent, and when a slot has failed to mint its # runner config for longer than actions_runners_slot_alert_after, saying for -# how long; one failed minting mails nobody (plexus.ci.actions_runners). The -# host takes no mail over SMTP, since its slots share its loopback. A vault -# without the whole item fails no run: the host is set up, sends no mail, and -# says so in its journal. A relay that refuses fails no run either; Postfix -# says so in the journal at each try. +# how long; the last two are units of their own, so that no other failure of +# the day takes their mail, and one failed minting mails nobody +# (plexus.ci.actions_runners). The host takes no mail over SMTP, since its +# slots share its loopback. An item that is missing, lacks a field, leaves one +# empty or names a mode Postfix does not know fails no run: the host is set +# up, sends no mail, and says so and why in its journal; so does a mail role +# that fails. A relay that refuses fails no run either; Postfix says so in the +# journal at each try. # # The first play locks the host down: the values are checked before # anything changes, then the jobs' user takes the runner image's uid, the @@ -77,7 +80,7 @@ # for a run that logged in as root over SSH, which this one never did, so it # is told the first admin's name instead. The handlers of the first play run # even when a task of it fails. The second play reads the vault and sets up -# the rest: the baseline, the mail, the overlay, Docker, the cache servers, +# the rest: the mail, the baseline, the overlay, Docker, the cache servers, # the slots. # # Tags: every play carries its layer (`host`, `ci`) and every role its own @@ -224,14 +227,28 @@ no_log: true tags: [always] - - name: What the vault did not give of the mail relay + # From the variables, not from the reads, so that one given on the command + # line counts. A field that is empty counts as missing; a mode is one the + # mail role knows. Anything wrong leaves the host without mail. + - name: What is wrong with the mail relay ansible.builtin.set_fact: - ci_mail_unread: >- - {%- set unread = [] -%} - {%- for read in ci_vault_read.results if read.item.item == 'mail-relay' and read.rc | default(1) != 0 -%} - {%- set _ = unread.append(read.item.item ~ '/' ~ read.item.field ~ ' (' ~ (read.stderr | default('') | trim) ~ ')') -%} + ci_mail_wrong: >- + {%- set fields = ci_vault | selectattr('item', 'eq', 'mail-relay') | list -%} + {%- set lacks = [] -%} + {%- for entry in fields if lookup('ansible.builtin.vars', entry.var, default='') | string | trim | length == 0 -%} + {%- set _ = lacks.append(entry.field) -%} {%- endfor -%} - {{ unread }} + {%- set wrong = [] -%} + {%- if lacks | length == fields | length -%} + {%- set _ = wrong.append('the vault ' ~ ci_owner ~ '-ci-host has no item mail-relay') -%} + {%- elif lacks | length > 0 -%} + {%- set _ = wrong.append('the item mail-relay of the vault ' ~ ci_owner ~ '-ci-host lacks ' ~ lacks | join(', ')) -%} + {%- endif -%} + {%- set mode = lookup('ansible.builtin.vars', 'ci_mail_mode', default='') | string | trim -%} + {%- if mode | length > 0 and mode not in ['starttls', 'tls'] -%} + {%- set _ = wrong.append('the item mail-relay names the mode ' ~ mode ~ ', which is neither starttls nor tls') -%} + {%- endif -%} + {{ wrong }} tags: [always] - name: Hand the mail relay to the mail role @@ -244,10 +261,33 @@ password: "{{ ci_mail_password }}" from_address: "{{ ci_mail_from_address }}" mailto: "{{ ci_mail_mailto }}" - when: ci_mail_unread | length == 0 + when: ci_mail_wrong | length == 0 no_log: true tags: [always] + # Before the roles, so that a unit of theirs that fails is mailed about + # from its first start, a slot whose first run cannot register among them, + # and rescued, so that a mail role that fails (a Postfix that cannot be + # installed) fails no run: the host is set up all the same and says so + # below. Its port on loopback closed, since the slots share the host's + # network. + - name: The host's mail + when: ci_mail_wrong | length == 0 + tags: [mail] + block: + - name: The mail role + ansible.builtin.import_role: + name: plexus.host.mail + vars: + mail_loopback_smtp: false + rescue: + - name: What failed of the mail role + ansible.builtin.set_fact: + ci_mail_wrong: + - >- + the role plexus.host.mail failed at '{{ ansible_failed_task.name | default('?') }}': + {{ ansible_failed_result.msg | default('') | truncate(400) }} + # Under cloud-init the run's output is a log nobody reads; the journal is # where an admin looks first. - name: Say in the journal that the host sends no mail @@ -259,19 +299,15 @@ - --priority - user.warning - >- - This host sends no mail: the vault {{ ci_owner }}-ci-host gave no - {{ ci_mail_unread | join('; no ') }}. A failed unit, a disk over the - housekeeping's threshold and a slot that cannot register show in - this journal alone. - when: ci_mail_unread | length > 0 and mail_smtp | default({}) | length == 0 + This host sends no mail: {{ ci_mail_wrong | join('; ') }}. A failed + unit, a disk over its threshold and a slot that cannot register + show in this journal alone. + when: ci_mail_wrong | length > 0 changed_when: false tags: [mail] roles: - { role: plexus.host.base, tags: [base] } - { role: plexus.host.upgrades, tags: [upgrades] } - # Before the units it reports on start; its port on loopback closed, - # since the slots share the host's network. - - { role: plexus.host.mail, tags: [mail], mail_loopback_smtp: false } - { role: plexus.host.netbird, tags: [netbird], when: netbird_enabled | bool } # Its images are the runner housekeeping's (actions_runners). - { role: plexus.host.docker, tags: [docker], docker_image_prune: false } diff --git a/ansible/ci/playbooks/vars/vault.yml b/ansible/ci/playbooks/vars/vault.yml index 2f9fb99c..bd76f161 100644 --- a/ansible/ci/playbooks/vars/vault.yml +++ b/ansible/ci/playbooks/vars/vault.yml @@ -21,8 +21,9 @@ ci_vault: # The tenant's mail relay, which the host mails through (plexus.host.mail, # its mail_smtp): the relay's name or address, its port, `starttls` or # `tls` (implicit TLS), the relay's user and password, the sender every - # mail goes from and the one mailbox it goes to. A vault without the whole - # item leaves the host without mail, which it says in its journal. + # mail goes from and the one mailbox it goes to. An item that is missing, + # lacks a field, leaves one empty or names another mode leaves the host + # without mail, which it says in its journal. - { var: ci_mail_server, item: mail-relay, field: server, optional: true } - { var: ci_mail_port, item: mail-relay, field: port, optional: true } - { var: ci_mail_mode, item: mail-relay, field: mode, optional: true } From 50d91c1f358989d96e27c0e245e975057dcb6965 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 04:05:23 +0100 Subject: [PATCH 08/11] plexus.host.mail: mail_loopback_smtp true opens the port again, restoring the line false commented out (PLX-253) False comments out smtp inet behind a mark of the role's; true restores the marked line alone, so a line commented out by hand stays. On a host with the default the file is unchanged. Co-Authored-By: Claude Opus 5.5 --- ansible/host/roles/mail/defaults/main.yml | 3 ++- ansible/host/roles/mail/tasks/main.yml | 18 +++++++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/ansible/host/roles/mail/defaults/main.yml b/ansible/host/roles/mail/defaults/main.yml index 18bff302..3d4f08de 100644 --- a/ansible/host/roles/mail/defaults/main.yml +++ b/ansible/host/roles/mail/defaults/main.yml @@ -19,7 +19,8 @@ mail_smtp: {} # failure-mail use, and also over SMTP on loopback, port 25, from whatever # reaches the host's loopback. False closes that port, for a host whose # loopback runs code that is not to mail as the host: a runner host, whose -# slots share its network. Set once: true again does not reopen it. +# slots share its network. True again opens it, restoring the line that +# false commented out. mail_loopback_smtp: true # Have unattended-upgrades mail when an upgrade fails (never on success). diff --git a/ansible/host/roles/mail/tasks/main.yml b/ansible/host/roles/mail/tasks/main.yml index 14f1c216..192a7004 100644 --- a/ansible/host/roles/mail/tasks/main.yml +++ b/ansible/host/roles/mail/tasks/main.yml @@ -30,17 +30,25 @@ mode: "0644" notify: Restart postfix - # The service `smtp inet` of master.cf, as Debian ships it; the line - # commented out, which no regexp then matches again. + # The service `smtp inet` of master.cf, as Debian ships it: commented out + # behind a mark of this role's, and that line alone restored, so that a + # line commented out by hand stays as it is. - name: Close the SMTP port on loopback - ansible.builtin.lineinfile: + ansible.builtin.replace: path: /etc/postfix/master.cf regexp: '^(smtp\s+inet\s.*)$' - line: '#\1' - backrefs: true + replace: '#closed by mail_loopback_smtp: \1' when: not mail_loopback_smtp notify: Restart postfix + - name: Open the SMTP port on loopback + ansible.builtin.replace: + path: /etc/postfix/master.cf + regexp: '^#closed by mail_loopback_smtp: (.*)$' + replace: '\1' + when: mail_loopback_smtp + notify: Restart postfix + - name: Enable Postfix ansible.builtin.systemd_service: name: postfix From f82a5df85276937651de81e9cbdb794ee599991b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 04:05:33 +0100 Subject: [PATCH 09/11] terraform, repo-operations: the headers name the item mail-relay and point to vars/vault.yml for its fields (PLX-253) Co-Authored-By: Claude Opus 5.5 --- .../main.tf.jinja | 2 +- terraform/hcloud_ci_runner_host/main.tf | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja index 5c49f216..b843fc0b 100644 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja @@ -1,5 +1,5 @@ # Generated from plexus-ms/tooling, templates/repo-operations: edit the template, never this file. -# One runner host per entry of `hosts` (hosts.auto.tfvars). A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. A host reads what it needs from the vault {{ github_org }}-ci-host, among it the item mail-relay (server, port, mode, username, password, from-address, mailto), the relay through which it mails the tenant when a unit fails, its disk passes the housekeeping's threshold or a slot cannot register; without the item a host is set up all the same, sends no mail and says so in its journal, and a host takes a new item only when it is replaced. +# One runner host per entry of `hosts` (hosts.auto.tfvars). A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. A host mails the tenant through the relay of the item mail-relay in the vault {{ github_org }}-ci-host; plexus.ci's playbooks/vars/vault.yml states its fields. terraform { required_providers { hcloud = { diff --git a/terraform/hcloud_ci_runner_host/main.tf b/terraform/hcloud_ci_runner_host/main.tf index 6868626e..3cc253c7 100644 --- a/terraform/hcloud_ci_runner_host/main.tf +++ b/terraform/hcloud_ci_runner_host/main.tf @@ -14,13 +14,10 @@ # does too, and the state keeps a hash of it: the module marks it sensitive, # which keeps it out of the plan's text, not out of the files. # -# The vault's item mail-relay (server, port, mode, username, password, -# from-address, mailto) is the tenant's mail relay, through which the host -# mails the tenant when a unit of its own fails, its disk passes the -# housekeeping's threshold, or a slot cannot register for minutes. A vault -# without it gives a host that is set up all the same, sends no mail, and -# says so in its journal; a host takes a new item only when it is replaced. -# The playbook's vars/vault.yml names every item it reads. +# The host mails the tenant through the relay that the vault's item +# mail-relay names; plexus.ci's playbooks/vars/vault.yml states its fields. +# Without the item a host is set up all the same, sends no mail, and says so +# in its journal; a host takes a new item only when it is replaced. # # What the module creates: the machine, and a firewall attached to it at # creation. A runner host needs nothing inbound at the provider: the slots From d77c621a862c95e7d9416ee765a10f3d4393d643 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 04:34:57 +0100 Subject: [PATCH 10/11] test: a port that is no number is no item, and the journal names it (PLX-253) Co-Authored-By: Claude Opus 5.5 --- newborns/runner-host-mail.test.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/newborns/runner-host-mail.test.ts b/newborns/runner-host-mail.test.ts index 8dddb298..d853cf84 100644 --- a/newborns/runner-host-mail.test.ts +++ b/newborns/runner-host-mail.test.ts @@ -9,9 +9,9 @@ // vault's item mail-relay. // // A host whose vault has no mail-relay, or one that lacks a field, leaves one -// empty or names a mode Postfix does not know, is set up all the same, runs -// its slots, and says in its journal that it sends no mail and why; a field -// given on the command line counts. So is a host whose mail role fails, here +// empty, names a port that is no number or a mode Postfix does not know, is +// set up all the same, runs its slots, and says in its journal that it sends +// no mail and why; a field given on the command line counts. So is a host whose mail role fails, here // on a Postfix that cannot be installed. With the item, the host mails // through the relay, with the item's credentials, from its sender to its // recipient, and takes no mail over SMTP from what shares its loopback, the @@ -411,8 +411,13 @@ describe('a runner host mails its tenant', () => { assert.equal((await shellOnHost('dpkg -s postfix')).ok, false); }); - test('an item that lacks a field, leaves one empty or names an unknown mode is no item: the run passes and the journal says what is wrong; a field given on the command line counts', async () => { - const partial: Record = { ...RELAY, 'mail-relay/port': '', 'mail-relay/mode': 'pigeon' }; + test('an item that lacks a field, leaves one empty, names a port that is no number or an unknown mode is no item: the run passes and the journal says what is wrong; a field given on the command line counts', async () => { + const partial: Record = { + ...RELAY, + 'mail-relay/username': '', + 'mail-relay/port': 'twenty-five', + 'mail-relay/mode': 'pigeon', + }; delete partial['mail-relay/mailto']; for (const [field, value] of Object.entries(partial)) put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); @@ -422,7 +427,8 @@ describe('a runner host mails its tenant', () => { assert.equal((await onHost('systemctl', 'is-active', SLOT)).trim(), 'active'); const said = await lastSaid(); assert.match(said, /sends no mail/); - assert.match(said, /\bport\b/); + assert.match(said, /\busername\b/); + assert.match(said, /\btwenty-five\b/); assert.match(said, /\bpigeon\b/); assert.doesNotMatch(said, /mailto/); assert.equal((await shellOnHost('dpkg -s postfix')).ok, false); From e4b94f3af81d0da0745accbba9dd7464aeca57da Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Thu, 3 Dec 2026 04:36:37 +0100 Subject: [PATCH 11/11] plexus.ci: a port that is no number is named and leaves the host without mail; the hold says what a held-back minting's mail rests on (PLX-253) Co-Authored-By: Claude Opus 5.5 --- ansible/ci/playbooks/playbook.yml | 17 +++++++++++------ ansible/ci/playbooks/vars/vault.yml | 4 ++-- .../actions_runners/files/ci-runner-mail-hold | 7 ++++--- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/ansible/ci/playbooks/playbook.yml b/ansible/ci/playbooks/playbook.yml index 1402eca4..af36a5da 100644 --- a/ansible/ci/playbooks/playbook.yml +++ b/ansible/ci/playbooks/playbook.yml @@ -62,10 +62,10 @@ # the day takes their mail, and one failed minting mails nobody # (plexus.ci.actions_runners). The host takes no mail over SMTP, since its # slots share its loopback. An item that is missing, lacks a field, leaves one -# empty or names a mode Postfix does not know fails no run: the host is set -# up, sends no mail, and says so and why in its journal; so does a mail role -# that fails. A relay that refuses fails no run either; Postfix says so in the -# journal at each try. +# empty or names a port that is no number or a mode Postfix does not know +# fails no run: the host is set up, sends no mail, and says so and why in its +# journal; so does a mail role that fails. A relay that refuses fails no run +# either; Postfix says so in the journal at each try. # # The first play locks the host down: the values are checked before # anything changes, then the jobs' user takes the runner image's uid, the @@ -228,8 +228,9 @@ tags: [always] # From the variables, not from the reads, so that one given on the command - # line counts. A field that is empty counts as missing; a mode is one the - # mail role knows. Anything wrong leaves the host without mail. + # line counts. A field that is empty counts as missing; a port is digits, + # and a mode one the mail role knows. Anything wrong leaves the host + # without mail. - name: What is wrong with the mail relay ansible.builtin.set_fact: ci_mail_wrong: >- @@ -244,6 +245,10 @@ {%- elif lacks | length > 0 -%} {%- set _ = wrong.append('the item mail-relay of the vault ' ~ ci_owner ~ '-ci-host lacks ' ~ lacks | join(', ')) -%} {%- endif -%} + {%- set port = lookup('ansible.builtin.vars', 'ci_mail_port', default='') | string | trim -%} + {%- if port | length > 0 and port is not match('^[0-9]+$') -%} + {%- set _ = wrong.append('the item mail-relay names the port ' ~ port ~ ', which is no number') -%} + {%- endif -%} {%- set mode = lookup('ansible.builtin.vars', 'ci_mail_mode', default='') | string | trim -%} {%- if mode | length > 0 and mode not in ['starttls', 'tls'] -%} {%- set _ = wrong.append('the item mail-relay names the mode ' ~ mode ~ ', which is neither starttls nor tls') -%} diff --git a/ansible/ci/playbooks/vars/vault.yml b/ansible/ci/playbooks/vars/vault.yml index bd76f161..bc97f6ba 100644 --- a/ansible/ci/playbooks/vars/vault.yml +++ b/ansible/ci/playbooks/vars/vault.yml @@ -22,8 +22,8 @@ ci_vault: # its mail_smtp): the relay's name or address, its port, `starttls` or # `tls` (implicit TLS), the relay's user and password, the sender every # mail goes from and the one mailbox it goes to. An item that is missing, - # lacks a field, leaves one empty or names another mode leaves the host - # without mail, which it says in its journal. + # lacks a field, leaves one empty, or names a port that is no number or + # another mode leaves the host without mail, which it says in its journal. - { var: ci_mail_server, item: mail-relay, field: server, optional: true } - { var: ci_mail_port, item: mail-relay, field: port, optional: true } - { var: ci_mail_mode, item: mail-relay, field: mode, optional: true } diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold b/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold index 0a57e421..ec0b5345 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold +++ b/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold @@ -10,9 +10,10 @@ # ci-runner-jit writes as an attempt starts and removes once it has minted, # tells a minting that failed from a container that failed after it: the # second is mailed at once, as every other unit is. It fails towards mailing: -# a row that is missing or holds no number lets the slot's mail go. Exits 0 -# to mail, 1 to hold back, which systemd counts as no failure of -# failure-mail@. +# a row that is missing or holds no number lets the slot's mail go. A failed +# minting it holds back is mailed only if the slot's ExecStopPost can start +# ci-runner-cannot-register@. Exits 0 to mail, 1 to hold back, which +# systemd counts as no failure of failure-mail@. # # ci-runner-mail-hold ci-runner@repo-1.service; echo $? unit=${1:?the unit that failed, e.g. ci-runner@repo-1.service}