diff --git a/ansible/ci/playbooks/playbook.yml b/ansible/ci/playbooks/playbook.yml index 26f8e3db..af36a5da 100644 --- a/ansible/ci/playbooks/playbook.yml +++ b/ansible/ci/playbooks/playbook.yml @@ -49,8 +49,23 @@ # 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's +# 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; 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 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 @@ -65,7 +80,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 mail, the baseline, the overlay, Docker, the cache servers, +# the slots. # # Tags: every play carries its layer (`host`, `ci`) and every role its own # name. @@ -196,7 +212,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,9 +223,93 @@ 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] + + # 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 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: >- + {%- 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 -%} + {%- 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 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') -%} + {%- endif -%} + {{ wrong }} + 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_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 + ansible.builtin.command: + argv: + - logger + - --tag + - plexus-ci + - --priority + - user.warning + - >- + 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] } diff --git a/ansible/ci/playbooks/vars/vault.yml b/ansible/ci/playbooks/vars/vault.yml index 28b4a902..bc97f6ba 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,16 @@ 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. An item that is missing, + # 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 } + - { 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/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index b0bcf336..748c7a8e 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -68,8 +68,17 @@ # 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. 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, @@ -208,10 +217,15 @@ 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 +# 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-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 24531eb3..47e695ee 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-jit +++ b/ansible/ci/roles/actions_runners/files/ci-runner-jit @@ -33,9 +33,33 @@ esac name="$HOST-$instance" out=/run/ci-runner/$instance.env +# 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. -trap 'echo "ci-runner-jit: minting the config of $name failed" >&2; sleep 30' ERR +minting_failed() { + echo "ci-runner-jit: minting the config of $name failed" >&2 + sleep 30 +} +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..ec0b5345 --- /dev/null +++ b/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold @@ -0,0 +1,31 @@ +#!/bin/sh +# 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 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. 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} +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 +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 95162578..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] + 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,6 +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 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 @@ -272,6 +285,48 @@ WantedBy=multi-user.target notify: [Reload systemd, Restart the slots] +# 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 + state: directory + owner: root + group: root + mode: "0755" + +- 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 + group: root + mode: "0644" + content: | + [Service] + 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 @@ -290,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 @@ -311,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: diff --git a/ansible/host/roles/mail/defaults/main.yml b/ansible/host/roles/mail/defaults/main.yml index 328e4257..3d4f08de 100644 --- a/ansible/host/roles/mail/defaults/main.yml +++ b/ansible/host/roles/mail/defaults/main.yml @@ -15,6 +15,14 @@ # 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. 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). mail_unattended_upgrades: true diff --git a/ansible/host/roles/mail/tasks/main.yml b/ansible/host/roles/mail/tasks/main.yml index 4f84eaa9..192a7004 100644 --- a/ansible/host/roles/mail/tasks/main.yml +++ b/ansible/host/roles/mail/tasks/main.yml @@ -30,6 +30,25 @@ mode: "0644" notify: Restart postfix + # 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.replace: + path: /etc/postfix/master.cf + regexp: '^(smtp\s+inet\s.*)$' + 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 diff --git a/newborns/runner-host-mail.test.ts b/newborns/runner-host-mail.test.ts new file mode 100644 index 00000000..d853cf84 --- /dev/null +++ b/newborns/runner-host-mail.test.ts @@ -0,0 +1,683 @@ +// 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, 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, or one that lacks a field, leaves one +// 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 +// slots included: one mail for a unit that fails (BuildKit, a cache server, a +// 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'; +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, 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, time +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"): + 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") + 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'; +/** 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 = ''; +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)); +/** 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 () => { + 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('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 }); + 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, /\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); + } 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']); + 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 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 ${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-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 ${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 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 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'); + 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.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(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(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 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 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', + `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 () => { + 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'); + } + }); + + 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); + }); +}); 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 f5e88e6f..c8d9e184 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, connect_server, 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, connect_server, 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/ci_runner_host_user_data/main.tf b/terraform/ci_runner_host_user_data/main.tf index e71dd610..32f057a7 100644 --- a/terraform/ci_runner_host_user_data/main.tf +++ b/terraform/ci_runner_host_user_data/main.tf @@ -15,8 +15,9 @@ # # The role is the implementation: the playbook installs the vault's CLI and # reads every other secret from the vault itself, among them the credentials -# and the token of a Connect server (connect_server). The user-data states the -# host and holds no logic. +# and the token of a Connect server (connect_server) and the tenant's mail +# relay, 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. # # A setting added after the module first shipped is written only where it # differs from the role's default, so that taking it replaces no host: the diff --git a/terraform/hcloud_ci_runner_host/main.tf b/terraform/hcloud_ci_runner_host/main.tf index e249a154..ac59a5a9 100644 --- a/terraform/hcloud_ci_runner_host/main.tf +++ b/terraform/hcloud_ci_runner_host/main.tf @@ -15,6 +15,11 @@ # 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 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 # poll the forge, and the cache servers listen on loopback and, with