Compare commits

...

29 Commits

Author SHA1 Message Date
brynmailer-mdc b3d2071319 refactor(daemon): reuse endOpSpan in the mounter and correct its comments
The contract spans end through the existing endOpSpan, the adapter's doc
comment fits three lines, and configureEBSProvider no longer claims its
provider is the only one wired, since the mounter builds its own.
2026-11-03 10:50:12 +10:00
brynmailer-mdc 702f3304fa test(daemon): cover a not_found unpublish and a legacy no-responder
An unpublish answered not_found counts as sealed for Unmount and
UnmountOne, and a mount that finds no responder on the legacy subject
re-reads capabilities, so a provider restarted at version 3 takes the next
mount over the contract.
2026-11-03 10:49:57 +10:00
brynmailer-mdc c5e4d49a4f fix(daemon): roll back a mount over the route the mount took
Mount's rollback re-read the route, so after a failure that dropped the
cached one a contract-published volume could be unmounted over legacy
ebs.unmount. The rollback now takes the route the mounts took. Unmount,
unmountOne and the rollback share one seal path that is given the route,
replacing the per-route helpers and their error out-parameter.
2026-11-03 10:49:17 +10:00
brynmailer-mdc c40b0aba1f fix(ebs): let NATSProvider requests buffer through a reconnect
request refused whenever the connection was not connected, which includes
reconnecting, while the legacy subjects' plain nats request buffers and
sends once the connection is back. Only a nil or closed connection now
refuses.
2026-11-03 10:47:34 +10:00
brynmailer-mdc 7574a8b75f fix(daemon): give the contract unpublish its own seal budget
DetachVolume bounds its context for the unplug and then seals, so an
unpublish on that context got whatever the unplug left. The mounter now
detaches the unpublish from the caller's cancellation, keeping the trace,
so NATSProvider's data-movement timeout governs the seal as
unmountSealTimeout does on the legacy path.
2026-11-03 10:46:10 +10:00
brynmailer-mdc d586a0cf8e fix(daemon): treat a publish reply with no usable export as an ambiguous mount
NATSProvider.PublishVolume now wraps ErrNoPublishedVolume and
ErrInvalidExport, keeping its messages. The mounter turns either, and an
export it cannot apply, into vm.ErrMountAmbiguous, so hot attach runs its
defensive unmount and Mount's rollback unpublishes the failing volume as
well as those already published.
2026-11-03 10:45:22 +10:00
brynmailer-mdc 550de9ef50 feat(daemon): mount and unmount through PublishVolume behind the local provider's version 3
The mounter asks its own node's provider for capabilities on the per-node
subject and, when version 3 is listed, mounts and unmounts every volume
through PublishVolume and UnpublishVolume at version 1, recording the
published export on the request. Otherwise it keeps the legacy
ebs.<node>.mount and unmount subjects.

A retry-later or not_found refusal and a publish with no responder back off
as ErrMountRetryable, so restore keeps the legacy retry. No responder on
any mount or unmount drops the cached route so the next call re-reads
capabilities. An unpublish takes the provider's data-movement budget.
2026-11-03 10:26:21 +10:00
Bryn Mailer 89c7fac5e3 feat(daemon): lock a cluster to one EBS provider (#1428)
* feat(config): refuse a spinifex.toml whose nodes resolve to different EBS providers

* feat(daemon): lock a cluster to one EBS provider in spinifex-cluster-config

The first daemon records its provider at ebs-provider with Create, which
also backfills an existing cluster. A daemon whose provider differs from
the recorded one refuses to start, naming both providers and the recovery.

* fix(config): compare only explicit EBS providers across nodes

A generated spinifex.toml writes no ebs stanza for peers, so treating an
absent peer provider as viperblockd refused every non-default cluster.

* fix(daemon): exit on an EBS provider lock refusal and refuse a malformed lock

A mismatch now exits 1 so the unit shows failed. A recorded value that
does not decode or names no supported provider is a distinct permanent
refusal quoting the raw value. Permanence is a sentinel matched with
errors.Is, and the cluster-config bucket is declared beside the others.

* style(daemon): align JetStreamManager fields
2026-11-03 09:41:38 +10:00
Bryn Mailer 54ecdde17e feat(ebs): contract schema version 3 for the provider data path (#1436)
* feat(ebs): contract schema version 3 for the provider data path

Servers accept schema versions 1 to 3 and answer every request in the
version it was sent at, while every client still sends version 1.

Version 3 adds no_seal to UnpublishVolumeRequest, refused below 3, and
torn_down to UnpublishVolumeResponse. UnpublishVolume now returns an
UnpublishedVolume so the torn-down result reaches callers.

A publish refused because another node holds the volume returns
volume_held_elsewhere at version 3 and volume_in_use below it, which is
what v1.23.0 returns. A read-only mismatch on republish stays
volume_in_use at every version.

GetCapabilities lists the contract versions served and is also answered
on a per-node subject. The unsealed-writes subject is part of
EBSProvider, and write-through providers answer it with nothing held. A
fence-notice event subject and message are defined. Unpublish gets the
data-movement timeout.

The memory provider, natsserve and qemunbdd implement all of this. A
qemunbdd republish whose qemu-nbd has died re-exports the volume instead
of returning the dead socket.

* feat(viperblock): serve contract schema version 3 from viperblockd

Every provider subject replies in its request's version, and
GetCapabilities lists the contract versions and is also served on the
node's own capabilities subject.

PublishVolume no longer returns an existing entry early. It goes through
mountVolume, which hands back a live export and drops and remounts one
whose nbdkit has died. Mount failures map to not_found, held_elsewhere
(version 3 only, volume_in_use below it), volume_in_use for a mode
mismatch, unavailable for a backing or lease store that is not ready,
and internal otherwise.

UnpublishVolume with no_seal abandons the export without sealing it,
and reports whether an export was torn down.

* test(ebs): conformance cases for contract schema version 3

Every provider run through the suite now has to:
- list ascending contract versions including the legacy one, answer each
  in that version, and refuse an unlisted one without changing state;
- refuse a publish elsewhere with volume_held_elsewhere only at version 3
  and volume_in_use at versions 1 and 2;
- refuse a republish in the other access mode as volume_in_use, never
  held elsewhere;
- report torn_down truthfully, refuse no_seal below version 3, and either
  honour no_seal at version 3 or refuse it as unsupported;
- answer the unsealed-writes query with a subset of what was asked.

SuiteConfig.KillExport lets a provider whose export is a process prove
that a republish after the export died returns a serving export.
qemunbdd and viperblockd supply it.

* fix(ebs): stop a running export before remounting over its lost socket

An export whose socket is gone was treated as dead even while its
process ran, and a republish started a second export beside it. A
client connected before the socket went keeps writing through the old
process, so that made two writers on one volume.

qemunbdd now SIGTERMs that qemu-nbd and waits for it to exit before
exporting again. viperblockd stops the nbdkit through unmountVolume, so
the old copy is sealed as a normal unmount would seal it. If the process
will not stop, the publish is refused as unavailable and the entry is
kept for the next attempt.

* test(viperblock): give the no-seal tests a seal they could reach

The no-seal unpublish and abandon tests left BaseDir empty, so
volumeNeedsSeal was false and no path could seal whatever the code did.
Both now create local state under BaseDir first, and check that a seal
is reachable before asserting none ran.

* refactor(ebs): leave version rules to the provider and trim the v3 surface

The provider decides what a request's version allows, so natsserve no
longer gates TornDown or held-elsewhere on it: classifyError takes no
version, and the reply carries what the provider returned. viperblockd
applies the TornDown rule in unpublishVolume, its provider half.

The unpublish handlers check the version once, through
CheckUnpublishVersion, and classify its refusal. Each handler binds its
reply version once.

UnpublishedVolume is reduced to TornDown. movesData classifies a subject
by its parsed verb, which replaces isNodeSubject and the owner-verb
list. nodeSubjectWildcard is unexported. The conformance suite reads
capabilities once.

* test(ebs): check v3 success replies, timeouts and refusals end to end

- Unpublish is sized as data movement, and publish, unsealed writes and
  per-node capabilities keep the caller's timeout.
- A mount whose lease store or backing store is not ready reaches the
  wire as unavailable.
- A successful publish replies in the request's version at every served
  version, in natsserve and in viperblockd. Every natsserve case now gets
  its own seeded provider, so none relies on an earlier case's state.
  The conformance republish runs at every listed version.
- viperblockd's per-node capabilities list the versions it serves.
- A no_seal unpublish above the served version is refused, and the
  export is neither torn down nor sealed.
- The dead-entry republish test asserts unconditionally. The snapshot
  lease test runs against real volume state and asserts nothing was
  written. The conformance torn-down case skips a provider that does
  not list version 3.

* fix(ebs): wrap the stop failure behind an unavailable publish

The refusal now wraps the stop error as well as ErrUnavailable, so a
caller can still inspect why the old export did not stop. Also fixes
import order and spacing that the linter flagged in the new tests.
2026-11-03 09:41:19 +10:00
Julian Sommer f48e246019 release: update go.mod for v1.24.0 2026-11-03 09:17:48 +10:00
Julian Sommer 00943e9789 chore: update ui images 2026-11-03 09:11:10 +10:00
Julian Sommer 5889b87c37 chore: frontend lint cleanup 2026-11-03 09:10:08 +10:00
Julian Sommer 29de13586f chore: coverage 2026-11-03 08:24:00 +10:00
Ben Duncan 1438319ad7 fix(admin): read the newest network test by its claim key, so a listing never leaves it out (#1464)
* fix(admin): read the newest network test by its claim key, so a listing never leaves it out

* fix(admin): keep the newest-test lookup additive, so it never fails a listing
2026-11-02 16:23:40 -06:00
Julian Sommer 75574edf3b fix(route53): omit Marker from ListHostedZones when none was sent and word NoSuchChange and three InvalidInput errors as AWS does (#1463) 2026-11-03 09:21:19 +11:00
Julian Sommer 17a3248d27 fix(rds): accept every RDS SourceType in DescribeEvents (#1462) 2026-11-03 09:20:10 +11:00
Julian Sommer dd4e8cb869 fix(rds): accept an empty Filters Values list except where AWS refuses it, and refuse an unknown engine on DescribeDBParameterGroups (#1461) 2026-11-03 09:18:53 +11:00
Julian Sommer 0fc4b6655e fix(rds): return AWS's error messages for missing DB instances, snapshots and parameter groups, duplicate groups and unknown parameters (#1460) 2026-11-03 09:17:04 +11:00
Josh Siviour de28c6781e feat(lambda): run the test-link agent over the authenticated TCP link (#1453)
The lambdatestlink agent now loads its identity, seals fw_cfg and dials the
host exactly as the normal agent does, then carries the test stream over
that mutual-TLS connection instead of a device path. Nothing tenant-facing
starts until the host's first valid frame: a refusal after the handshake,
an early close or a shutdown never starts the bootstrap. Each VM serves one
invocation and then stops.

The normal agent is unchanged and still accepts no invocations. The tagged
tests join the race tier for the two packages that carry the build tag.
2026-11-03 07:45:45 +10:00
Ben Duncan 6fb73c2ddd fix: find node planes from the node's configuration, and admit only a node's own address as a network test target (#1455)
* fix: find node planes from the node's configuration, and admit only a node's own address as a network test target

Node facts looked for planes only on br-wan, br-lan and br-vpc, so a host
whose addresses sit on plain NICs (a Vultr or OCI VM) reported no planes:
the topology had no links, every port read unused, and Run test stayed
disabled. Each plane now resolves to the device holding the node's
configured address: ovn-encap-ip for vpc, the node's own host for lan,
and vpcd.external_interface (or the bridge it is a port of) for wan, with
the br-* names as the fallback.

A run request now names its target node, and the client admits only the
address that node reports for the plane. The old subnet rule refused
legitimate WAN tests on Vultr, where each VM has its own /23, and admitted
strangers sharing a cloud subnet.

The network test's selects showed their raw values (__all__) because Base
UI's Select needs its options as items to render a label.

* fix(ui): list a plane on a plain NIC without an empty bridge, and note a shared LAN port as well as a shared bridge

* fix(vultr): turn on public addresses in the default subnets once the Vultr pool is live

* fix(ui): say where an RDS database goes, and how to use another VPC, when no DB subnet group exists
2026-11-02 15:27:42 -06:00
Ben Duncan 433c417512 test: keep the slog duration lint out of -race builds, where go/types races while loading export data (#1456) 2026-11-02 14:10:28 -06:00
Ben Duncan 59f1368a69 test(e2e): dump the IMDS datapath when a restarted guest never answers SSH (#1450)
A stop/start that leaves the guest stuck in cloud-init-local waiting on
IMDS fails the restart SSH probe, but the diagnostics only captured the
EIP/OVN side, which was healthy. Capture br-imds flows, the endpoint's
link, addresses, sysctls, reply rule and route, the responder listener
and conntrack too, so the next occurrence names the broken hop.
2026-11-02 12:44:03 -06:00
Ben Duncan 8bcdcd9155 fix(rds-agent): stop a command blocked on a backup hold from keeping out its release (#1449)
* fix(rds-agent): stop a command blocked on a backup hold from keeping out its release

The agent ran commands one at a time inside its poll loop. A MariaDB
ALTER USER issued while an automated backup held BACKUP STAGE blocked at
its commit, so the unquiesce that would release the hold could never be
delivered: the rotation timed out at the API while the new password was
already live in memory, and the instance stayed backing-up.

Commands now run on their own goroutines while the agent keeps polling,
re-published copies of a running or answered command are ignored, and a
finished reply cuts the current poll short so it is carried at once.
MariaDB SetPassword also waits for any hold to end before it runs, for
less than the control plane's budget, so a rotation that cannot finish
fails before touching the engine.

* fix(rds-agent): keep engine commands serial and bound every command by its budget

Engine-mutating commands go back to running one at a time on a single
lane, as before; only unquiesce runs beside it, so a command blocked on a
backup hold still cannot keep out the release.

Each command is bounded by its type's control-plane budget, now exported
as rdsinstance.CommandBudget and measured from receipt. A command whose
budget ran out while it queued is answered as expired and never run, so
a stale quiesce cannot put the engine in backup mode. Quiesce takes its
bookkeeping lock within its context, and the MariaDB ALTER USER carries a
lock_wait_timeout from what is left of the budget.

* test(rds): rotate the MariaDB master password through an automated backup

Opens the backup window on purpose and rotates the password back and
forth until one rotation is in flight while the instance reports
backing-up, asserting each outcome is whole and that the backup releases
the engine. Every suite create now pins its backup and maintenance
windows clear of the run, so no other subtest's outcome depends on the
hour the cell runs.

* fix(rds): cap an agent command by the budget its issuer has left

The agent measured each command's deadline from receipt, so a first copy
delayed by a gateway or bus outage was granted a whole fresh budget when
its issuer had nearly given up; a late quiesce could then take a hold
nobody would release. The issuer now stamps every republished copy with
the budget it has left, a duration that needs no clock agreement, and the
agent uses the smaller of that and its own type budget.
2026-11-02 12:43:57 -06:00
Ben Duncan 5bd975d493 fix(ci): wait for memory before the ISO cells boot their nodes (#1446) 2026-11-02 12:43:52 -06:00
Ben Duncan 69df9ea9bf feat(ui): console feedback v1 and the admin Nodes view (#1454)
* feat(ui): console feedback round: state tones, inline tags, filter bar and form fixes

Settled states go green and transitions yellow with a spinner, status text is
lowercase, tags are edited inline row by row, every list filters through one
filter bar, long cells truncate with a tooltip and times are relative.

EC2 launch takes a Name and offers ICMP echo, and leaves Placement Group out
when no group is available. RDS create is reordered with engine tiles and
window pickers. Route 53 records get bulk delete, a TTL select, value labels
that follow the type, and NS. Tooltips use the popover tokens, and the console
is sized over a 110% root.

* feat(ui): size RDS instance classes and give each record value its own input

An RDS class is a db.-prefixed EC2 type, so the class picker shows its vCPUs
and memory in every option and under the field, as the EC2 launch form does,
on create, modify and restore.

A Route 53 record's values were one textarea, which let a line break into a
value. Each value is now a single-line input with Add value; Enter starts the
next one, a pasted list splits into rows, and CNAME takes exactly one.

* fix(ui): open a DNS record for editing from the keyboard

* feat: admin node inventory, topology, live host metrics and network test

Each node collects its hardware facts as root at daemon start (dmidecode,
ethtool, networkctl LLDP where available) into /etc/spinifex/node-facts, and
the daemon serves them with its plane wiring over NATS.

New admin-only actions, refused for every account but the system admin
account regardless of policy:

- GetNodeFacts: hardware, NICs, LLDP neighbours and planes per node
- GetNodeMetrics: live CPU, memory and per-plane traffic for one node
- StartNetworkTest / DescribeNetworkTests: iperf2 between nodes over a
  chosen plane, both directions, one test cluster-wide at a time, recorded
  in KV and converged asynchronously

The iperf listener runs only for the duration of a run, without
capabilities, on TCP 5001, which the peers firewall rule now allows. A run
refuses any target outside the node's own plane subnet.

The console gains a node panel (hardware, network, metrics, network test
with a dial scaled to the port's line rate) and a topology view built with
@xyflow/react. setup.sh installs dmidecode and iperf.

* test: cover the node insight handlers and the facts file mode

* feat: report every CPU flag in node facts

* feat(ui): node table on the dashboard, every CPU flag and a readable topology

The dashboard's nodes section is the Nodes page table, open by default, and a
row opens that node. Ready reads green, capacity sorts by most available, and
the processor's features tip lists every flag. Topology draws one row per
port with switches in a muted card, highlights a node's links on hover, and
offers a left-to-right layout beside top-down.

* chore(ui): rebuild dist

* fix: align the CPU facts fields

* fix: bound the network test server start and read ARM CPU features and cores

* chore(ui): rebuild dist

* test(ui): pin the instances baseline clock and take the screenshots from CI's Playwright image

* fix: retry a network test claim whose holder released it mid-check
2026-11-02 10:23:35 -06:00
Josh Siviour eafad1a37e feat(lambda): start the bootstrap unprivileged with no_new_privs (#1452)
StartBootstrap sets no_new_privs on a dedicated locked OS thread and
starts the bootstrap from it, as uid/gid 993 with no supplementary groups
and only the environment it is given. The thread is never unlocked, so
the flag never reaches the agent's other threads, and no dynamic loader
runs before no_new_privs is set. The test-only agent start uses it
instead of running the bootstrap as root. The normal agent still accepts
no invocations.
2026-11-02 23:37:36 +10:00
Josh Siviour 22cca42bf4 feat(lambda): authenticate the guest's control connection at startup (invocation disabled) (#1451)
* feat(lambda): open the authenticated control connection at guest startup

A normal lambda-agent build now reads its per-generation identity from
fw_cfg, unloads qemu_fw_cfg and refuses to start unless the fw_cfg tree is
gone, then dials the host under the pinned mutual TLS and holds the
connection. It accepts no invocations and never starts the bootstrap: any
data from the host fails closed until the message protocol exists.

The image loads qemu_fw_cfg and the virtio_net chain and configures the
guest interface from opt/spinifex/netcfg, as other system VMs do. The
lambdatestlink build also seals fw_cfg before starting the bootstrap.

* test(lambda): bound startup test waits and report host accept errors
2026-11-02 22:37:36 +10:00
Josh Siviour 814b15097b feat(operator): record ADR-0008:S9 quiescence evidence on the deletion job (#1447)
* feat(iam): record quiescence evidence on the deletion job, with the L09 scope unresolved until the final inventory re-read

* fix(iam): cite ADR-0008:S9 as the basis for the STS consumer
2026-11-02 22:17:30 +10:00
Josh Siviour a541ee312d feat(lambda): add the runtime image, guest agent and authenticated TCP control connection (not wired) (#1448)
* feat(lambda): add the Lambda runtime image and guest agent

* fix(lambda): stop the guest agent after a timed-out invocation

* docs(lambda): declare the L-GUEST executor-to-agent contract

* refactor(vm): remove the unused virtio-serial port builder

Lambda guest control moves to TCP over the microVM's network, so no
caller needs SerialPorts. This reverts d7905107b.

* fix(lambda): drop the serial carrier from guest startup and keep virtio-net

run-agent no longer waits for a carrier device named on the kernel
command line, init loads virtio_net instead of virtio_console, and the
image keeps virtio_net's failover and net_failover dependencies. The
normal agent still refuses to start without an authenticated transport.

* feat(lambda): authenticate the guest's TCP control connection with pinned mutual TLS

hostlink loads the per-generation identity from fw_cfg and dials the host
over TLS 1.3 with ALPN spinifex-lambda-guest/1. VerifyPeer requires exactly
the pinned certificate, validates it, and checks its single URI SAN names
the expected scope and role. The L-GUEST contract now describes this
transport; message framing and fencing stay open, and the normal agent
still refuses to start.

* feat(lambda): add the host end of the guest's TCP mutual TLS connection

guestconn creates fresh host and guest identities for each environment
generation, produces the fw_cfg entries the guest reads, and accepts only
that generation's exact guest certificate. Peers on the untrusted bridge
that fail the handshake are closed and the listener keeps waiting until
its context ends; the cancel callback finishes before the deadline is
cleared so the listener can be reused.

The pinned-certificate check and the L-GUEST vocabulary move to
foundation/pki and contracts/lambda/v1 so both ends share them.

* docs(lambda): describe the shared connection vocabulary in the contract README
2026-11-02 22:09:58 +10:00
1128 changed files with 25699 additions and 4360 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 151 KiB

+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# Usage: wait-for-memory.sh <MiB>
#
# Waits until the runner's MemAvailable reaches <MiB>, then returns. Runners on
# one host share its RAM, and a neighbour's build holds several GiB for a few
# minutes, so one sample taken during it is not a verdict on the host.
# Gives up after MEM_WAIT_TIMEOUT_S and names the biggest processes.
#
# Env: MEM_WAIT_TIMEOUT_S (900), MEM_WAIT_POLL_S (30), MEMINFO (/proc/meminfo).
set -uo pipefail
want_mb="${1:?usage: $0 <MiB>}"
timeout_s="${MEM_WAIT_TIMEOUT_S:-900}"
poll_s="${MEM_WAIT_POLL_S:-30}"
meminfo="${MEMINFO:-/proc/meminfo}"
avail_mb() { awk '/^MemAvailable:/ {print int($2 / 1024)}' "$meminfo"; }
start=$SECONDS
while :; do
have=$(avail_mb)
if [ -n "$have" ] && [ "$have" -ge "$want_mb" ]; then
echo "memory: ${have} MiB available, need ${want_mb} MiB"
exit 0
fi
waited=$(( SECONDS - start ))
if [ "$waited" -ge "$timeout_s" ]; then
echo "::error::need ${want_mb} MiB available, have ${have:-unknown} MiB after waiting ${waited}s"
ps -eo rss,pid,args --sort=-rss | head -11 | cut -c1-200
exit 1
fi
echo "memory: ${have:-unknown} MiB available, need ${want_mb} MiB; waiting (${waited}s of ${timeout_s}s)"
sleep "$poll_s"
done
+47
View File
@@ -0,0 +1,47 @@
#!/bin/sh
# wait-for-memory_test.sh — drives wait-for-memory.sh against a fake meminfo
# that a background writer changes mid-wait, so each verdict is checked without
# a loaded host.
set -eu
SCRIPT_DIR=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
WAIT="$SCRIPT_DIR/wait-for-memory.sh"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
fails=0
pass() { echo " ok - $1"; }
fail() { echo " FAIL - $1"; fails=$((fails + 1)); }
meminfo() { printf 'MemTotal: 65536000 kB\nMemAvailable: %s kB\n' "$(( $1 * 1024 ))" > "$TMP/meminfo"; }
MEMINFO="$TMP/meminfo"
MEM_WAIT_POLL_S=1
export MEMINFO MEM_WAIT_POLL_S
meminfo 30000
if MEM_WAIT_TIMEOUT_S=5 bash "$WAIT" 26624 > "$TMP/out" 2>&1; then
pass "enough memory returns at once"
else
fail "enough memory returns at once: $(cat "$TMP/out")"
fi
meminfo 21577
( sleep 2; meminfo 30000 ) &
if MEM_WAIT_TIMEOUT_S=20 bash "$WAIT" 26624 > "$TMP/out" 2>&1 && grep -q waiting "$TMP/out"; then
pass "memory freed mid-wait is admitted"
else
fail "memory freed mid-wait is admitted: $(cat "$TMP/out")"
fi
wait
meminfo 21577
if MEM_WAIT_TIMEOUT_S=2 bash "$WAIT" 26624 > "$TMP/out" 2>&1; then
fail "memory that never frees fails: exited 0"
elif grep -q '::error::need 26624 MiB available, have 21577 MiB' "$TMP/out" && grep -q 'RSS' "$TMP/out"; then
pass "memory that never frees fails and names the biggest processes"
else
fail "memory that never frees fails and names the biggest processes: $(cat "$TMP/out")"
fi
[ "$fails" -eq 0 ] || { echo "wait-for-memory: $fails failed"; exit 1; }
echo "wait-for-memory: all passed"
+9 -8
View File
@@ -1057,9 +1057,6 @@ jobs:
{ echo "::error::br-wan not permitted in /etc/qemu/bridge.conf"; exit 1; }
command -v sshpass >/dev/null ||
{ echo "::error::sshpass not installed"; exit 1; }
free_mb=$(free -m | awk '/^Mem:/ {print $7}')
[ "$free_mb" -ge 8192 ] ||
{ echo "::error::need 8 GiB available, have ${free_mb} MiB"; exit 1; }
# A 40G image on tmpfs competes with the 8 GiB the VM itself needs.
fstype=$(df --output=fstype "$TMPDIR" | tail -1 | tr -d ' ')
[ "$fstype" != tmpfs ] ||
@@ -1090,6 +1087,10 @@ jobs:
ssh-keygen -t ed25519 -N "" -f "$HOME/.ssh/$k" -C "$k-ci"
done
# The node's 8 GiB, claimed when the VM boots rather than at preflight.
- name: Wait for memory
run: mulga/spinifex/.github/scripts/wait-for-memory.sh 8192
# Boots the ISO, installs unattended, reads the lease off the serial
# console, runs the in-guest smoke test, and installs the key for the
# next step.
@@ -1301,15 +1302,10 @@ jobs:
ref: ${{ steps.siblings.outputs.bluebottle }}
path: mulga/bluebottle
# 3 x 8 GiB plus 9 sparse 40G disks, before the instances the cluster
# launches on top.
- name: Preflight
run: |
set -euo pipefail
mkdir -p "$TMPDIR"
free_mb=$(free -m | awk '/^Mem:/ {print $7}')
[ "$free_mb" -ge 26624 ] ||
{ echo "::error::need 26 GiB available, have ${free_mb} MiB"; exit 1; }
fstype=$(df --output=fstype "$TMPDIR" | tail -1 | tr -d ' ')
[ "$fstype" != tmpfs ] ||
{ echo "::error::$TMPDIR is tmpfs — nine node disks would be in RAM"; exit 1; }
@@ -1332,6 +1328,11 @@ jobs:
# formation port. Both land with mulga-yxtda and the bridged WAN mode;
# until then this cell proves the cluster forms and survives, not that a
# customer can use it.
# 3 x 8 GiB plus headroom for the instances the cluster launches on top,
# claimed when the nodes boot rather than at preflight.
- name: Wait for memory
run: mulga/spinifex/.github/scripts/wait-for-memory.sh 26624
- name: Install, form and verify the cluster
working-directory: mulga/scripts/iso-builder
run: |
+3
View File
@@ -24,6 +24,9 @@ build/microvm/qboot.LICENSE
build/microvm/sqs-worker/vmlinuz
build/microvm/sqs-worker/initramfs.cpio.gz
build/microvm/sqs-worker/.stage.*/
build/microvm/lambda-runtime/vmlinuz
build/microvm/lambda-runtime/initramfs.cpio.gz
build/microvm/lambda-runtime/.stage.*/
build/qboot/
!spinifex/runtime/roles/spinifexui/frontend/dist/
tmp/
+19 -3
View File
@@ -169,7 +169,7 @@ go_local_srcs = $(shell GOWORK=off CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go list
# worker as separate processes. A separate artifact from the LB image above.
SQS_WORKER_MICROVM_OUT_DIR := $(MICROVM_OUT_DIR)/sqs-worker
SQS_WORKER_MICROVM_ARTIFACTS := $(SQS_WORKER_MICROVM_OUT_DIR)/vmlinuz $(SQS_WORKER_MICROVM_OUT_DIR)/initramfs.cpio.gz
SQS_WORKER_MICROVM_INPUTS := scripts/build-sqs-store-microvm-image.sh scripts/lib/sqs-store-microvm-publish.sh $(SQS_WORKER_MICROVM_OUT_DIR)/init.sh $(SQS_WORKER_MICROVM_OUT_DIR)/inittab $(addprefix $(SQS_WORKER_MICROVM_OUT_DIR)/,sqs-worker-lib.sh sqs-worker-prepare sqs-worker-store sqs-worker-ready sqs-worker-stop) bin/nats-server bin/sqs-worker
SQS_WORKER_MICROVM_INPUTS := scripts/build-sqs-store-microvm-image.sh scripts/lib/microvm-image.sh scripts/lib/sqs-store-microvm-publish.sh $(SQS_WORKER_MICROVM_OUT_DIR)/init.sh $(SQS_WORKER_MICROVM_OUT_DIR)/inittab $(addprefix $(SQS_WORKER_MICROVM_OUT_DIR)/,sqs-worker-lib.sh sqs-worker-prepare sqs-worker-store sqs-worker-ready sqs-worker-stop) bin/nats-server bin/sqs-worker
$(SQS_WORKER_MICROVM_ARTIFACTS) &: $(SQS_WORKER_MICROVM_INPUTS)
./scripts/build-sqs-store-microvm-image.sh
@@ -180,6 +180,20 @@ bin/sqs-worker: go.mod go.sum $$(call go_local_srcs,./cmd/sqs-worker)
build-sqs-worker-microvm-image: $(SQS_WORKER_MICROVM_ARTIFACTS) ## Build the SQS microVM kernel and initramfs
# The Lambda runtime microVM image. Built on demand; not shipped or installed.
LAMBDA_RUNTIME_MICROVM_OUT_DIR := $(MICROVM_OUT_DIR)/lambda-runtime
LAMBDA_RUNTIME_MICROVM_ARTIFACTS := $(LAMBDA_RUNTIME_MICROVM_OUT_DIR)/vmlinuz $(LAMBDA_RUNTIME_MICROVM_OUT_DIR)/initramfs.cpio.gz
LAMBDA_RUNTIME_MICROVM_INPUTS := scripts/build-lambda-runtime-microvm-image.sh scripts/lib/microvm-image.sh $(addprefix $(LAMBDA_RUNTIME_MICROVM_OUT_DIR)/,init.sh inittab run-agent) bin/lambda-agent
$(LAMBDA_RUNTIME_MICROVM_ARTIFACTS) &: $(LAMBDA_RUNTIME_MICROVM_INPUTS)
./scripts/build-lambda-runtime-microvm-image.sh
bin/lambda-agent: go.mod go.sum $$(call go_local_srcs,./cmd/lambda-agent)
@mkdir -p bin
GOWORK=off CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags '-s -w' -o $@ ./cmd/lambda-agent
build-lambda-runtime-microvm-image: $(LAMBDA_RUNTIME_MICROVM_ARTIFACTS) ## Build the Lambda runtime microVM kernel and initramfs (not shipped)
# qboot is the microvm firmware. The source tarball ships with each release
# because qboot is GPL-2.0.
QBOOT_COMMIT := $(shell sed -n 's/^QBOOT_COMMIT="\(.*\)"$$/\1/p' scripts/build-qboot.sh)
@@ -241,7 +255,8 @@ test-build-scripts:
echo "-- $$t"; \
sh "$$t" || exit 1; \
done
shellcheck -S warning .github/scripts/hypervisor-disk-preflight.sh .github/scripts/hypervisor-disk-preflight_test.sh
shellcheck -S warning .github/scripts/hypervisor-disk-preflight.sh .github/scripts/hypervisor-disk-preflight_test.sh \
.github/scripts/wait-for-memory.sh .github/scripts/wait-for-memory_test.sh
@echo -e "\n....Running shellcheck over build/scripts/**/*.sh + the node scripts...."
shellcheck -S warning $$(find build/scripts -name '*.sh' | sort) $(NODE_SCRIPTS)
shellcheck -S warning -x scripts/build-oracle-appliance.sh $$(find scripts/appliance -name '*.sh' | sort)
@@ -312,6 +327,7 @@ test-cover:
test-race:
@echo -e "\n....Running tests with race detector for $(GO_PROJECT_NAME)...."
$(_Q)LOG_IGNORE=1 SPINIFEX_SQS_R3=1 go test $(GOTESTFLAGS) -race -timeout 300s ./spinifex/... ./cmd/... ./internal/... ./contracts/... ./architecture/... $(_RACEQ)
$(_Q)LOG_IGNORE=1 go test $(GOTESTFLAGS) -race -tags=lambdatestlink -timeout 120s ./cmd/lambda-agent/ ./spinifex/agents/lambda/hostlink/ $(_RACEQ)
# Unit tests for in-repo GitHub Actions (e.g. .github/actions/e2e-analyze).
# Kept out of `test-cover` so coverage % isn't diluted by CI-only tooling.
@@ -522,7 +538,7 @@ distro-arm64:
distro-clean:
rm -rf dist/
.PHONY: test-package-check build build-ui test-ui-e2e ui-e2e-container ui-baselines build-installer build-lb-agent build-ecs-agent build-system-image build-eks-node-image import-eks-node-image publish-eks-node-image build-ecs-node-image import-ecs-node-image build-rds-postgres-image import-rds-postgres-image build-rds-mariadb-image import-rds-mariadb-image build-microvm-image build-sqs-worker-microvm-image install-microvm install-sqs-worker-microvm go_build preflight test test-cover test-race diff-coverage bench fuzz test-actions test-images test-build-scripts test-harness test-integration generate-aws-model-coverage aws-model-coverage test-segscan-oracle \
.PHONY: test-package-check build build-ui test-ui-e2e ui-e2e-container ui-baselines build-installer build-lb-agent build-ecs-agent build-system-image build-eks-node-image import-eks-node-image publish-eks-node-image build-ecs-node-image import-ecs-node-image build-rds-postgres-image import-rds-postgres-image build-rds-mariadb-image import-rds-mariadb-image build-microvm-image build-sqs-worker-microvm-image build-lambda-runtime-microvm-image install-microvm install-sqs-worker-microvm go_build preflight test test-cover test-race diff-coverage bench fuzz test-actions test-images test-build-scripts test-harness test-integration generate-aws-model-coverage aws-model-coverage test-segscan-oracle \
deploy reinstall clean \
install-system install-go install-aws quickinstall \
lint fix govulncheck nilaway \
+1 -1
View File
@@ -113,7 +113,7 @@ aws ec2 describe-instance-types
## Web Console
<p align="center">
<img src=".github/assets/spinifex-ui.jpg" alt="Spinifex web console dashboard" width="900">
<img src=".github/assets/dashboard.webp" alt="Spinifex web console dashboard" width="900">
</p>
Spinifex ships with a built-in web console for your instances, volumes, buckets, networks, and IAM. See [Launching the Web UI](https://docs.mulgadc.com/docs/setting-up-your-cluster#7-launching-the-web-ui).
+68
View File
@@ -0,0 +1,68 @@
#!/bin/sh
mount -t proc proc /proc
mount -t sysfs sys /sys
mount -t devtmpfs dev /dev
# modprobe needs a usable modules.dep; insmod by explicit path does not, so
# fall back to it. Handles .ko and .ko.gz.
load_mod() {
modprobe "$1" 2>/dev/null && return 0
for ko in $(find /lib/modules -name "$1.ko" -o -name "$1.ko.gz" 2>/dev/null); do
insmod "$ko" 2>/dev/null && return 0
case "$ko" in
*.gz) gunzip -c "$ko" >/tmp/mod.ko 2>/dev/null \
&& insmod /tmp/mod.ko 2>/dev/null && return 0 ;;
esac
done
return 1
}
# lambda-agent reads its identity from fw_cfg and unloads qemu_fw_cfg before
# anything else runs. virtio_net needs net_failover and failover, and the
# insmod fallback resolves no dependencies, so load the chain bottom-up.
load_mod qemu_fw_cfg || echo "[init] qemu_fw_cfg did not load" >/dev/console
load_mod failover || true
load_mod net_failover || true
load_mod virtio_net || echo "[init] virtio_net did not load" >/dev/console
ip link set lo up
# The guest's addresses come from the same netcfg entry as other system VMs.
NETCFG=/sys/firmware/qemu_fw_cfg/by_name/opt/spinifex/netcfg/raw
i=0
while [ "$i" -lt 25 ] && [ ! -f "$NETCFG" ]; do
sleep 0.04
i=$((i + 1))
done
if [ -f "$NETCFG" ]; then
# shellcheck source=/dev/null
. "$NETCFG"
for n in 0 1 2 3 4 5; do
eval mac=\$NIC${n}_MAC
[ -z "$mac" ] && continue
iface=""
for _ in 1 2 3 4 5; do
iface=$(ip -o link | awk -v m="$mac" 'tolower($0) ~ tolower(m) {print $2}' | tr -d :)
[ -n "$iface" ] && break
sleep 0.02
done
if [ -z "$iface" ]; then
echo "[init] no interface for MAC $mac (NIC$n)" >/dev/console
continue
fi
cidr="" gw="" default="" rdst="" rvia=""
eval cidr=\$NIC${n}_CIDR
eval gw=\$NIC${n}_GW
eval default=\$NIC${n}_DEFAULT
eval rdst=\$NIC${n}_ROUTE_DST
eval rvia=\$NIC${n}_ROUTE_VIA
ip link set "$iface" up
[ -n "$cidr" ] && ip addr add "$cidr" dev "$iface"
[ "$default" = "1" ] && [ -n "$gw" ] && ip route add default via "$gw" dev "$iface"
[ -n "$rdst" ] && [ -n "$rvia" ] && ip route add "$rdst" via "$rvia" dev "$iface"
done
else
# lambda-agent then fails to reach the host and the guest powers off.
echo "[init] fw_cfg netcfg not available" >/dev/console
fi
exec /sbin/init
+6
View File
@@ -0,0 +1,6 @@
# The power button loads here, not in /init: busybox init has its SIGUSR2
# (poweroff) handler installed before sysinit runs, so a press can never reach
# the pre-exec shell PID 1. A press before this line is lost; the host re-sends.
::sysinit:/sbin/modprobe tiny_power_button power_signal=12
::once:/usr/local/lib/lambda-runtime/run-agent
::ctrlaltdel:/sbin/reboot
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# Runs the Lambda guest agent, then powers the guest off whatever its status.
/usr/local/bin/lambda-agent >/dev/console 2>&1
status=$?
echo "[run-agent] lambda-agent exited with status $status" >/dev/console
poweroff -f
+2 -1
View File
@@ -1,4 +1,4 @@
# spinifex-unit-version: 5
# spinifex-unit-version: 6
[Unit]
Description=Spinifex Daemon (VM Orchestration)
PartOf=spinifex.target
@@ -15,6 +15,7 @@ Slice=spinifex-system.slice
User=spinifex-daemon
Group=spinifex
ExecStartPre=/usr/local/bin/spx admin hostnet check
ExecStartPre=-+/usr/local/bin/spx admin node-facts collect
ExecStart=/usr/local/bin/spx service spinifex start
Restart=on-failure
RestartSec=5
+48
View File
@@ -0,0 +1,48 @@
package main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"github.com/mulgadc/spinifex/spinifex/agents/lambda/hostlink"
)
// Exit statuses: the guest refused to start, the control connection failed,
// or the host closed it.
const (
exitRefused = 2
exitLink = 1
exitClosed = 0
)
type startup struct {
fwCfgDir string
fwCfgRoot string
unload func() error
}
func defaultStartup() startup {
return startup{fwCfgDir: hostlink.FwCfgDir, fwCfgRoot: hostlink.FwCfgRoot, unload: hostlink.UnloadFwCfg}
}
// connect loads the identity, seals fw_cfg whether or not the load succeeded,
// then dials the host. Under TLS 1.3 a host refusal is seen only on first read.
func (s startup) connect(ctx context.Context) (*tls.Conn, int, error) {
id, loadErr := hostlink.LoadIdentity(s.fwCfgDir)
if err := hostlink.SealFwCfg(s.fwCfgRoot, s.unload); err != nil {
return nil, exitRefused, errors.Join(loadErr, err)
}
if loadErr != nil {
return nil, exitRefused, loadErr
}
conn, err := hostlink.Dial(ctx, id)
if err != nil {
if ctx.Err() != nil {
err = fmt.Errorf("%w: %w", err, context.Cause(ctx))
}
return nil, exitLink, err
}
return conn, 0, nil
}
+98
View File
@@ -0,0 +1,98 @@
package main
import (
"context"
"crypto/tls"
"net"
"os"
"path/filepath"
"testing"
"time"
lambdav1 "github.com/mulgadc/spinifex/contracts/lambda/v1"
"github.com/mulgadc/spinifex/spinifex/runtime/compute/lambda/guestconn"
"github.com/stretchr/testify/require"
)
const scope lambdav1.Scope = "ap-southeast-2/000000000001/fn-1/env-1/gen-1"
// guest is a fake fw_cfg tree; unload removes it as unloading the module would.
type guest struct {
root string
unloads int
sealedAt chan struct{}
}
func newGuest(t *testing.T, entries map[string][]byte) *guest {
t.Helper()
g := &guest{root: filepath.Join(t.TempDir(), "qemu_fw_cfg"), sealedAt: make(chan struct{}, 1)}
for name, b := range entries {
dir := filepath.Join(g.root, "by_name", lambdav1.FwCfgPrefix, name)
require.NoError(t, os.MkdirAll(dir, 0o700))
require.NoError(t, os.WriteFile(filepath.Join(dir, "raw"), b, 0o600))
}
return g
}
func (g *guest) startup() startup {
return startup{
fwCfgDir: filepath.Join(g.root, "by_name", lambdav1.FwCfgPrefix),
fwCfgRoot: g.root,
unload: func() error {
g.unloads++
g.sealedAt <- struct{}{}
return os.RemoveAll(g.root)
},
}
}
type host struct {
ln *net.TCPListener
gen *guestconn.Generation
conn chan accepted
}
func newHost(t *testing.T) *host {
t.Helper()
ln, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
require.NoError(t, err)
t.Cleanup(func() { ln.Close() })
gen, err := guestconn.NewGeneration(scope, time.Hour)
require.NoError(t, err)
return &host{ln: ln, gen: gen, conn: make(chan accepted, 1)}
}
func (h *host) entries() map[string][]byte { return h.gen.GuestEntries(h.ln.Addr().String()) }
type accepted struct {
conn *tls.Conn
err error
}
// accept runs the host end until ctx ends and reports what it accepted.
func (h *host) accept(ctx context.Context) {
go func() {
c, err := h.gen.AcceptGuest(ctx, h.ln, 2*time.Second)
h.conn <- accepted{c, err}
}()
}
// guest waits for the host to authenticate the guest.
func (h *host) guest(t *testing.T) *tls.Conn {
t.Helper()
a := wait(t, h.conn, "host to authenticate the guest")
require.NoError(t, a.err)
return a.conn
}
// wait bounds every test wait so a stalled host or startup fails promptly.
func wait[T any](t *testing.T, ch <-chan T, what string) T {
t.Helper()
select {
case v := <-ch:
return v
case <-time.After(10 * time.Second):
t.Fatalf("timed out waiting for %s", what)
panic("unreachable")
}
}
+24
View File
@@ -0,0 +1,24 @@
// lambda-agent runs inside a Lambda guest.
//
// A normal build reads its per-generation identity from fw_cfg, unloads
// fw_cfg so nothing started later can read the guest key, and opens the
// authenticated control connection to the host. It accepts no invocations and
// never starts the function's bootstrap: the message protocol and grant
// fencing do not exist yet. The agent never listens for the host.
//
// A lambdatestlink build opens the same connection, then relays one invocation
// over a test carrier for local proofs; the carrier is not the guest protocol.
package main
import (
"context"
"flag"
"os"
)
func main() { os.Exit(run()) }
func run() int {
flag.Parse()
return start(context.Background())
}
+56
View File
@@ -0,0 +1,56 @@
//go:build !lambdatestlink
package main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log/slog"
)
// errNoProtocol is returned when the host sends anything: this build defines no
// message protocol, so it accepts no work.
var errNoProtocol = errors.New("host sent data, but this build accepts no invocations")
func start(ctx context.Context) int {
code, err := defaultStartup().run(ctx)
if err != nil {
slog.Error("lambda-agent stopping", "exit", code, "err", err)
}
return code
}
// run authenticates to the host and holds the connection until it closes.
func (s startup) run(ctx context.Context) (int, error) {
conn, code, err := s.connect(ctx)
if err != nil {
return code, err
}
defer conn.Close()
slog.Info("control connection open; invocations are not enabled in this build", "host", conn.RemoteAddr().String())
if err := awaitHostClose(ctx, conn); err != nil {
return exitLink, err
}
return exitClosed, nil
}
// awaitHostClose reads until the host closes the connection. Under TLS 1.3 a
// host that rejects the guest certificate is only seen here, on first read.
func awaitHostClose(ctx context.Context, conn *tls.Conn) error {
stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
defer stop()
n, err := conn.Read(make([]byte, 1))
switch {
case n > 0:
return errNoProtocol
case errors.Is(err, io.EOF):
return nil
case ctx.Err() != nil:
return fmt.Errorf("control connection: %w", context.Cause(ctx))
default:
return fmt.Errorf("control connection: %w", err)
}
}
+171
View File
@@ -0,0 +1,171 @@
//go:build !lambdatestlink
package main
import (
"context"
"errors"
"net"
"os"
"testing"
"time"
lambdav1 "github.com/mulgadc/spinifex/contracts/lambda/v1"
"github.com/mulgadc/spinifex/spinifex/runtime/compute/lambda/guestconn"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type result struct {
code int
err error
}
func runAsync(ctx context.Context, s startup) <-chan result {
out := make(chan result, 1)
go func() {
code, err := s.run(ctx)
out <- result{code, err}
}()
return out
}
func TestStartupAuthenticatesAfterSealingFwCfg(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
h := newHost(t)
h.accept(ctx)
g := newGuest(t, h.entries())
done := runAsync(ctx, g.startup())
conn := h.guest(t)
select {
case <-g.sealedAt:
default:
t.Fatal("guest dialled before fw_cfg was sealed")
}
_, err := os.Stat(g.root)
assert.ErrorIs(t, err, os.ErrNotExist, "fw_cfg still readable while connected")
require.NoError(t, conn.Close())
res := wait(t, done, "startup to return")
assert.Equal(t, exitClosed, res.code)
assert.NoError(t, res.err)
assert.Equal(t, 1, g.unloads)
}
func TestStartupRefusesHostData(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
h := newHost(t)
h.accept(ctx)
done := runAsync(ctx, newGuest(t, h.entries()).startup())
conn := h.guest(t)
defer conn.Close()
_, err := conn.Write([]byte{0})
require.NoError(t, err)
res := wait(t, done, "startup to return")
assert.Equal(t, exitLink, res.code)
assert.ErrorIs(t, res.err, errNoProtocol)
}
// The host pins another generation's guest; the guest learns of the refusal
// on its first read and fails with a link error, never a clean close.
func TestStartupFailsWhenHostRefusesGuest(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
h := newHost(t)
h.accept(ctx)
other, err := guestconn.NewGeneration(scope, time.Hour)
require.NoError(t, err)
entries := h.entries()
wrong := other.GuestEntries(h.ln.Addr().String())
entries[lambdav1.EntryGuestKey], entries[lambdav1.EntryGuestCert] = wrong[lambdav1.EntryGuestKey], wrong[lambdav1.EntryGuestCert]
g := newGuest(t, entries)
res := wait(t, runAsync(ctx, g.startup()), "startup to return")
assert.Equal(t, exitLink, res.code)
require.Error(t, res.err)
assert.Contains(t, res.err.Error(), "bad certificate")
assert.Equal(t, 1, g.unloads)
select {
case a := <-h.conn:
require.Error(t, a.err, "host accepted a guest it does not pin")
default:
}
}
func TestStartupRefusesWithoutDialling(t *testing.T) {
h := newHost(t)
cases := map[string]struct {
entries map[string][]byte
unload func(g *guest) func() error
want string
}{
"missing entry": {
entries: func() map[string][]byte { e := h.entries(); delete(e, lambdav1.EntryHostCert); return e }(),
want: "read host-cert",
},
"fw_cfg stays readable": {
entries: h.entries(),
unload: func(*guest) func() error { return func() error { return errors.New("module is built in") } },
want: "fw_cfg still readable",
},
"unload claims success but tree remains": {
entries: h.entries(),
unload: func(*guest) func() error { return func() error { return nil } },
want: "unload reported success",
},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
g := newGuest(t, tc.entries)
s := g.startup()
if tc.unload != nil {
s.unload = tc.unload(g)
}
code, err := s.run(context.Background())
assert.Equal(t, exitRefused, code)
assert.ErrorContains(t, err, tc.want)
})
}
// Nothing dialled the host in any case above.
require.NoError(t, h.ln.SetDeadline(time.Now().Add(50*time.Millisecond)))
_, err := h.ln.Accept()
var ne net.Error
require.ErrorAs(t, err, &ne)
assert.True(t, ne.Timeout())
}
// A missing entry still seals fw_cfg: the key may be present even when
// another entry is not.
func TestStartupSealsEvenWhenIdentityIsIncomplete(t *testing.T) {
h := newHost(t)
e := h.entries()
delete(e, lambdav1.EntryHostAddr)
g := newGuest(t, e)
code, err := g.startup().run(context.Background())
assert.Equal(t, exitRefused, code)
assert.ErrorContains(t, err, "read host-addr")
assert.Equal(t, 1, g.unloads)
_, statErr := os.Stat(g.root)
assert.ErrorIs(t, statErr, os.ErrNotExist)
}
func TestStartupStopsWithContext(t *testing.T) {
ctx, cancel := context.WithCancelCause(context.Background())
defer cancel(nil)
h := newHost(t)
h.accept(ctx)
done := runAsync(ctx, newGuest(t, h.entries()).startup())
conn := h.guest(t)
defer conn.Close()
reason := errors.New("guest shutting down")
cancel(reason)
res := wait(t, done, "startup to return")
assert.Equal(t, exitLink, res.code)
assert.ErrorIs(t, res.err, reason)
}
+128
View File
@@ -0,0 +1,128 @@
//go:build lambdatestlink
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/exec"
"time"
"github.com/mulgadc/spinifex/spinifex/agents/lambda/agent"
"github.com/mulgadc/spinifex/spinifex/agents/lambda/hostlink"
"github.com/mulgadc/spinifex/spinifex/agents/lambda/runtimeapi"
)
const (
runtimeAddr = "127.0.0.1:9001"
taskRoot = "/var/task"
)
var handler = flag.String("handler", os.Getenv("_HANDLER"), "function handler passed to the bootstrap")
// testlink relays one invocation over the test carrier on the authenticated
// connection; the carrier is not the guest protocol.
type testlink struct {
startup
runtimeAddr string
startBootstrap func(ctx context.Context, env []string) (*exec.Cmd, error)
}
func start(ctx context.Context) int {
t := testlink{
startup: defaultStartup(),
runtimeAddr: runtimeAddr,
startBootstrap: func(ctx context.Context, env []string) (*exec.Cmd, error) {
return agent.StartBootstrap(ctx, taskRoot+"/bootstrap", env, os.Stdout, os.Stderr)
},
}
code, err := t.run(ctx)
if err != nil {
slog.Error("lambda-agent stopping", "exit", code, "err", err)
}
return code
}
func (t testlink) run(parent context.Context) (int, error) {
conn, code, err := t.connect(parent)
if err != nil {
return code, err
}
defer conn.Close()
link := hostlink.NewTestStream(conn)
// The handshake can return before the host refuses the guest, so nothing
// tenant-facing starts until the host's first valid frame arrives.
first, err := link.Next(parent)
if errors.Is(err, hostlink.ErrShutdown) {
return exitClosed, nil
}
if err != nil {
return exitLink, fmt.Errorf("first frame from host: %w", err)
}
if parent.Err() != nil {
return exitLink, context.Cause(parent)
}
srv := runtimeapi.New()
ln, err := net.Listen("tcp", t.runtimeAddr)
if err != nil {
return exitLink, fmt.Errorf("listen runtime api: %w", err)
}
hs := &http.Server{Handler: srv.Handler(), ReadHeaderTimeout: 10 * time.Second}
go func() { _ = hs.Serve(ln) }()
defer hs.Close()
ctx, cancel := context.WithCancelCause(parent)
defer cancel(nil)
cmd, err := t.startBootstrap(ctx, []string{
"AWS_LAMBDA_RUNTIME_API=" + ln.Addr().String(),
"_HANDLER=" + *handler,
"LAMBDA_TASK_ROOT=" + taskRoot,
"PATH=/bin:/sbin:/usr/bin",
})
if err != nil {
return exitLink, fmt.Errorf("start bootstrap: %w", err)
}
exited := make(chan struct{})
go func() {
defer close(exited)
err := cmd.Wait()
cancel(fmt.Errorf("bootstrap exited: %w", err))
}()
err = agent.Run(ctx, &oneInvocation{Link: link, first: &first}, srv)
cancel(errors.New("agent stopping"))
<-exited
if err != nil {
return exitLink, err
}
return exitClosed, nil
}
// oneInvocation serves the host's first request and then stops the agent:
// each test VM runs a single invocation.
type oneInvocation struct {
hostlink.Link
first *hostlink.Request
}
var _ hostlink.Link = (*oneInvocation)(nil)
func (o *oneInvocation) Next(ctx context.Context) (hostlink.Request, error) {
if err := ctx.Err(); err != nil {
return hostlink.Request{}, err
}
if o.first == nil {
return hostlink.Request{}, hostlink.ErrShutdown
}
req := *o.first
o.first = nil
return req, nil
}
+179
View File
@@ -0,0 +1,179 @@
//go:build lambdatestlink
package main
import (
"bytes"
"context"
"io"
"net/http"
"os"
"os/exec"
"testing"
"time"
lambdav1 "github.com/mulgadc/spinifex/contracts/lambda/v1"
"github.com/mulgadc/spinifex/spinifex/agents/lambda/hostlink"
"github.com/mulgadc/spinifex/spinifex/runtime/compute/lambda/guestconn"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const helperEnv = "LAMBDA_AGENT_TEST_BOOTSTRAP"
// TestHelperBootstrap is the fake function bootstrap, run as a subprocess: it
// echoes one invocation through the Runtime API, then waits for the next.
func TestHelperBootstrap(t *testing.T) {
if os.Getenv(helperEnv) != "1" {
return
}
base := "http://" + os.Getenv("AWS_LAMBDA_RUNTIME_API") + "/2018-06-01/runtime/invocation/"
resp, err := http.Get(base + "next")
require.NoError(t, err)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
resp.Body.Close()
id := resp.Header.Get("Lambda-Runtime-Aws-Request-Id")
post, err := http.Post(base+id+"/response", "application/json", bytes.NewReader(body))
require.NoError(t, err)
post.Body.Close()
_, _ = http.Get(base + "next")
}
type bootstrapStarts struct {
n int
started chan struct{}
}
func (b *bootstrapStarts) testlink(g *guest) testlink {
b.started = make(chan struct{}, 1)
return testlink{
startup: g.startup(),
runtimeAddr: "127.0.0.1:0",
startBootstrap: func(ctx context.Context, env []string) (*exec.Cmd, error) {
b.n++
b.started <- struct{}{}
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestHelperBootstrap$")
cmd.Env = append(env, helperEnv+"=1")
return cmd, cmd.Start()
},
}
}
func runTestlinkAsync(ctx context.Context, tl testlink) <-chan result {
out := make(chan result, 1)
go func() {
code, err := tl.run(ctx)
out <- result{code, err}
}()
return out
}
type result struct {
code int
err error
}
func TestTestlinkServesOneInvocationThenStops(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
h := newHost(t)
h.accept(ctx)
var b bootstrapStarts
done := runTestlinkAsync(ctx, b.testlink(newGuest(t, h.entries())))
conn := h.guest(t)
defer conn.Close()
select {
case <-b.started:
t.Fatal("bootstrap started before the host sent a frame")
case <-time.After(100 * time.Millisecond):
}
hs := hostlink.NewTestStream(conn)
req := hostlink.Request{GrantID: "g-1", AttemptID: "a-1", RequestID: "r-1", DeadlineMs: time.Now().Add(5 * time.Second).UnixMilli(), Payload: []byte(`{"a":40,"b":2}`)}
require.NoError(t, hs.HostSend(req))
got, err := hs.HostResult(ctx)
require.NoError(t, err)
assert.Equal(t, hostlink.Response{GrantID: "g-1", AttemptID: "a-1", RequestID: "r-1", Payload: req.Payload}, got)
// A second invocation on the same VM is never served. The agent may
// already have closed the connection, so a failed send is a refusal too.
second := req
second.RequestID = "r-2"
sendErr := hs.HostSend(second)
res := wait(t, done, "agent to stop after one invocation")
assert.Equal(t, exitClosed, res.code)
assert.NoError(t, res.err)
if sendErr == nil {
_, err = hs.HostResult(ctx)
assert.Error(t, err, "agent answered a second invocation")
}
assert.Equal(t, 1, b.n)
}
func TestTestlinkShutdownBeforeInvocationNeverStartsBootstrap(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
h := newHost(t)
h.accept(ctx)
var b bootstrapStarts
done := runTestlinkAsync(ctx, b.testlink(newGuest(t, h.entries())))
conn := h.guest(t)
defer conn.Close()
require.NoError(t, hostlink.NewTestStream(conn).HostShutdown())
res := wait(t, done, "agent to stop")
assert.Equal(t, exitClosed, res.code)
assert.NoError(t, res.err)
assert.Zero(t, b.n)
}
// The guest's handshake completes, but the host pins another generation's
// guest; the refusal arrives on first read and the bootstrap never starts.
func TestTestlinkHostRefusalNeverStartsBootstrap(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
h := newHost(t)
h.accept(ctx)
other, err := guestconn.NewGeneration(scope, time.Hour)
require.NoError(t, err)
entries := h.entries()
wrong := other.GuestEntries(h.ln.Addr().String())
entries[lambdav1.EntryGuestKey], entries[lambdav1.EntryGuestCert] = wrong[lambdav1.EntryGuestKey], wrong[lambdav1.EntryGuestCert]
var b bootstrapStarts
res := wait(t, runTestlinkAsync(ctx, b.testlink(newGuest(t, entries))), "agent to stop")
assert.Equal(t, exitLink, res.code)
require.Error(t, res.err)
assert.Contains(t, res.err.Error(), "bad certificate")
assert.Zero(t, b.n)
}
func TestTestlinkHostCloseBeforeFrameNeverStartsBootstrap(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
h := newHost(t)
h.accept(ctx)
var b bootstrapStarts
done := runTestlinkAsync(ctx, b.testlink(newGuest(t, h.entries())))
require.NoError(t, h.guest(t).Close())
res := wait(t, done, "agent to stop")
assert.Equal(t, exitLink, res.code)
assert.ErrorContains(t, res.err, "first frame from host")
assert.Zero(t, b.n)
}
// A cancelled context is reported before the buffered request is delivered,
// and the request stays undelivered.
func TestOneInvocationHonoursCancelledContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
o := &oneInvocation{first: &hostlink.Request{RequestID: "r-1"}}
_, err := o.Next(ctx)
require.ErrorIs(t, err, context.Canceled)
req, err := o.Next(context.Background())
require.NoError(t, err)
assert.Equal(t, "r-1", req.RequestID)
}
+217
View File
@@ -0,0 +1,217 @@
package clusterv1
import "regexp"
const (
// NodeFactsSubject fans out a request for each daemon's hardware and
// cabling description. Its reply payload is NodeFacts.
NodeFactsSubject = "spinifex.node.facts"
nodeNetTestPrefix = "spinifex.node.nettest."
)
var nodeIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
// ValidNodeID reports whether a node name is safe to place in a subject: no
// NATS token separator or wildcard can get through.
func ValidNodeID(node string) bool {
return nodeIDPattern.MatchString(node)
}
// NodeFactsOfSubject asks one node alone for its NodeFacts.
func NodeFactsOfSubject(node string) string {
return NodeFactsSubject + "." + node
}
// NetTestServeSubject asks one node to start a one-shot throughput server.
func NetTestServeSubject(node string) string {
return nodeNetTestPrefix + node + ".serve"
}
// NetTestRunSubject asks one node to run the client side of a throughput test.
func NetTestRunSubject(node string) string {
return nodeNetTestPrefix + node + ".run"
}
// Planes a node's NICs can carry, named as the installer names them.
const (
PlaneWAN = "wan"
PlaneLAN = "lan"
PlaneVPC = "vpc"
)
// NetTestPort is the TCP port reserved for node-to-node throughput tests.
const NetTestPort = 5001
// NodeFacts describes one node's hardware, OS and cabling. Fields a host
// cannot report are left empty, and Sources says why.
type NodeFacts struct {
Node string `json:"node"`
CollectedAt string `json:"collected_at,omitempty"`
FormFactor string `json:"form_factor"`
Virt string `json:"virt,omitempty"`
System SystemFacts `json:"system"`
OS OSFacts `json:"os"`
CPU CPUFacts `json:"cpu"`
Memory MemoryFacts `json:"memory"`
NICs []NICFacts `json:"nics"`
Planes []PlaneFacts `json:"planes"`
Sources map[string]string `json:"sources"`
}
// SystemFacts is the machine's identity from DMI.
type SystemFacts struct {
Vendor string `json:"vendor,omitempty"`
Product string `json:"product,omitempty"`
Family string `json:"family,omitempty"`
Version string `json:"version,omitempty"`
Serial string `json:"serial,omitempty"`
UUID string `json:"uuid,omitempty"`
ChassisType string `json:"chassis_type,omitempty"`
ChassisAsset string `json:"chassis_asset,omitempty"`
BoardVendor string `json:"board_vendor,omitempty"`
BoardProduct string `json:"board_product,omitempty"`
BoardSerial string `json:"board_serial,omitempty"`
BIOSVendor string `json:"bios_vendor,omitempty"`
BIOSVersion string `json:"bios_version,omitempty"`
BIOSDate string `json:"bios_date,omitempty"`
DeviceModel string `json:"device_model,omitempty"`
}
// OSFacts names the running OS and Spinifex build.
type OSFacts struct {
Name string `json:"name,omitempty"`
Kernel string `json:"kernel,omitempty"`
Arch string `json:"arch,omitempty"`
Version string `json:"spx_version,omitempty"`
Commit string `json:"spx_commit,omitempty"`
UptimeSeconds int64 `json:"uptime_seconds,omitempty"`
Hostname string `json:"hostname,omitempty"`
}
// CPUFacts summarises the sockets. Threads and Cores are totals. Features are
// the flags worth naming; Flags is every flag the CPU reports.
type CPUFacts struct {
Model string `json:"model,omitempty"`
Vendor string `json:"vendor,omitempty"`
Sockets int `json:"sockets"`
CoresPerSocket int `json:"cores_per_socket,omitempty"`
Cores int `json:"cores"`
Threads int `json:"threads"`
MaxMHz int `json:"max_mhz,omitempty"`
CurrentMHz int `json:"current_mhz,omitempty"`
Virtualization string `json:"virtualization,omitempty"`
Features []string `json:"features,omitempty"`
Flags []string `json:"flags,omitempty"`
}
// MemoryFacts groups identical DIMMs so a 32-slot board reads as one line.
type MemoryFacts struct {
TotalBytes uint64 `json:"total_bytes"`
SlotsUsed int `json:"slots_used"`
SlotsTotal int `json:"slots_total"`
MaxCapacity string `json:"max_capacity,omitempty"`
ECC string `json:"ecc,omitempty"`
Groups []MemoryGroup `json:"groups"`
OSTotalBytes uint64 `json:"os_total_bytes,omitempty"`
OSAvailBytes uint64 `json:"os_available_bytes,omitempty"`
HugePageBytes uint64 `json:"huge_page_bytes,omitempty"`
}
// MemoryGroup is a set of DIMMs alike in every field shown. ConfiguredMTs
// below SpeedMTs means the board runs them slower than rated.
type MemoryGroup struct {
Count int `json:"count"`
SizeBytes uint64 `json:"size_bytes"`
Type string `json:"type,omitempty"`
TypeDetail string `json:"type_detail,omitempty"`
FormFactor string `json:"form_factor,omitempty"`
SpeedMTs int `json:"speed_mts,omitempty"`
ConfiguredMTs int `json:"configured_mts,omitempty"`
Manufacturer string `json:"manufacturer,omitempty"`
PartNumber string `json:"part_number,omitempty"`
Rank string `json:"rank,omitempty"`
Serials []string `json:"serials,omitempty"`
}
// NICFacts is one physical network interface and, where LLDP reports it, the
// switch port it is cabled to.
type NICFacts struct {
Name string `json:"name"`
MAC string `json:"mac,omitempty"`
Driver string `json:"driver,omitempty"`
Firmware string `json:"firmware,omitempty"`
BusInfo string `json:"bus_info,omitempty"`
Model string `json:"model,omitempty"`
SpeedMbps int `json:"speed_mbps,omitempty"`
MaxMbps int `json:"max_mbps,omitempty"`
Duplex string `json:"duplex,omitempty"`
Port string `json:"port,omitempty"`
MTU int `json:"mtu,omitempty"`
State string `json:"state"`
Master string `json:"master,omitempty"`
Planes []string `json:"planes,omitempty"`
Neighbor *LLDPNeighbor `json:"neighbor,omitempty"`
}
// LLDPNeighbor is what the switch on the other end of a NIC advertises.
type LLDPNeighbor struct {
ChassisID string `json:"chassis_id"`
SystemName string `json:"system_name,omitempty"`
SystemDescription string `json:"system_description,omitempty"`
PortID string `json:"port_id,omitempty"`
PortDescription string `json:"port_description,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
}
// PlaneFacts is the address a plane uses on this node and the NICs under it.
type PlaneFacts struct {
Plane string `json:"plane"`
Bridge string `json:"bridge,omitempty"`
Address string `json:"address,omitempty"`
Prefix int `json:"prefix,omitempty"`
NICs []string `json:"nics,omitempty"`
MTU int `json:"mtu,omitempty"`
}
// NetTestServeRequest starts a server bound to the node's address on Plane.
type NetTestServeRequest struct {
Plane string `json:"plane"`
DurationSeconds int `json:"duration_seconds"`
}
// NetTestServeResponse names the address the server listens on.
type NetTestServeResponse struct {
Address string `json:"address,omitempty"`
Port int `json:"port,omitempty"`
Error string `json:"error,omitempty"`
}
// NetTestRunRequest runs the client towards Address from the node's own
// address on Plane. Address must be what Target reports for that plane.
type NetTestRunRequest struct {
Plane string `json:"plane"`
Target string `json:"target"`
Address string `json:"address"`
Port int `json:"port"`
DurationSeconds int `json:"duration_seconds"`
Streams int `json:"streams"`
}
// NetTestRunResponse is one direction of a pair's measurement.
type NetTestRunResponse struct {
SourceAddress string `json:"source_address,omitempty"`
BitsPerSecond float64 `json:"bits_per_second"`
Bytes int64 `json:"bytes"`
Seconds float64 `json:"seconds"`
Streams int `json:"streams"`
StreamBPS []float64 `json:"stream_bps,omitempty"`
RTTMinMillis float64 `json:"rtt_min_ms,omitempty"`
RTTAvgMillis float64 `json:"rtt_avg_ms,omitempty"`
RTTMaxMillis float64 `json:"rtt_max_ms,omitempty"`
PacketLoss float64 `json:"packet_loss_percent,omitempty"`
LinkMbps int `json:"link_mbps,omitempty"`
MTU int `json:"mtu,omitempty"`
Tool string `json:"tool,omitempty"`
Error string `json:"error,omitempty"`
}
+66
View File
@@ -0,0 +1,66 @@
# Lambda v1 contracts
This package will own the Lambda process contracts declared by ADR-0009:S13.
It holds the L-GUEST declaration and, in `guest.go`, the connection vocabulary both ends share: the scope, the URI SAN roles, the ALPN identifier and the fw_cfg entry names. The transport and authentication are decided (ADR-0009:S17); the invocation message types and framing are not chosen, so no message types are defined here.
It is not an AWS tenant-facing API.
## L-GUEST: node executor to guest agent
**Owner:** the Lambda domain.
**Producers and consumers:** the node-local executor (`runtime/compute/lambda`) and the in-guest Lambda agent (`agents/lambda`), in both directions.
**Operations:** bootstrap with scoped material, readiness, invoke, completion, bounded logs, shutdown.
**Transport:** TCP over the microVM's network (ADR-0009:S17).
The agent dials one connection to a listener the executor owns for the environment, and the guest exposes no listener for host control.
At most one authenticated control connection is active per environment, and the agent may reconnect; how a prior connection and its in-flight work are handled is open (ADR-0009 M1).
The network is shared and untrusted: no source address, port or bridge membership is identity or authority.
Tenant code may be able to reach the listener, but it cannot open the agent's connection or key material, so any connection it makes fails authentication.
**Authentication:** mutual TLS 1.3, bound to the environment ID and realization generation, using material the user runtime cannot read (ADR-0009:S17).
For each generation the executor creates ephemeral self-signed host and guest certificates whose single URI SAN is `spinifex-lambda://<Region>/<account>/<function ID>/<environment ID>/<generation>/<role>`, with role `host` or `guest`.
Each end validates the peer certificate against the one pinned peer certificate and separately requires that URI SAN with the opposite role; hostname verification is not relied on.
ALPN carries the L-GUEST major version, `spinifex-lambda-guest/1`, and an unsupported version fails the handshake.
Under TLS 1.3 the guest's handshake can complete before the host refuses its certificate, so the guest treats the connection as accepted only after the host's first message.
**Bootstrap material:** the executor passes these fw_cfg entries under `opt/spinifex/lambda/`, and the agent reads them as root and unloads `qemu_fw_cfg` before user code starts.
| Entry | Content |
|---|---|
| `guest-key` | Guest private key, PEM |
| `guest-cert` | Guest certificate, PEM |
| `host-cert` | The one pinned host certificate, PEM |
| `expect` | `<Region>/<account>/<function ID>/<environment ID>/<generation>` |
| `host-addr` | Host listener as `host:port` |
The guest's own interface settings come from `opt/spinifex/netcfg`, the entry other system VMs use.
The agent unloads `qemu_fw_cfg` even when an entry is missing, and refuses to start if the fw_cfg tree is still readable afterwards.
Until the message format exists, the agent authenticates and holds the connection but accepts no host message and starts no user code.
**Authority:** one environment's attempt only.
The user runtime never holds these keys, and sharing the guest with the agent gives user code no platform authority.
**Idempotency and fencing:** an invoke carries the attempt-grant identity and the attempt ID.
The agent accepts a run command only under a current grant, and a completion under a superseded grant is discarded and reported.
How a grant is enforced and proven ended is open (ADR-0009 M1).
**Errors and versions:** the agent and executor fail closed on an unknown protocol version or an identity mismatch.
**Readiness:** environment readiness needs authenticated, current-generation agent evidence; a running hypervisor process does not count.
**Payloads:** the contract must carry a synchronous payload and response of up to 6 MB and an asynchronous payload of up to 1 MB, plus framing, over a path whose size bound is declared.
How payloads move is open (ADR-0009 M3).
### Compatibility boundary
The agent ships inside the runtime image pinned by each published version, so it is outside the coordinated release train.
The executor supports every L-GUEST major carried by a still-supported runtime image.
Retiring an image follows a published runtime-deprecation lifecycle that blocks create and update before it blocks invoke.
Evidence required before the first agent image ships: a function on an old image invoked by a new executor, and the reverse during rollback.
## L-RUNTIME
The guest agent serves the AWS Lambda Runtime API, version `2018-06-01`, to the user runtime at `AWS_LAMBDA_RUNTIME_API`.
Spinifex does not version this AWS contract, and conformance is measured against AWS.
+54
View File
@@ -0,0 +1,54 @@
// Package lambdav1 holds the Lambda process-contract vocabulary shared by the
// node executor and the guest agent. See README.md for the declarations.
package lambdav1
import (
"fmt"
"strings"
)
// ALPNv1 names L-GUEST major version 1; a peer offering any other fails the handshake.
const ALPNv1 = "spinifex-lambda-guest/1"
// FwCfgPrefix prefixes every fw_cfg entry the executor passes the guest.
const FwCfgPrefix = "opt/spinifex/lambda/"
// fw_cfg entry names under FwCfgPrefix.
const (
EntryGuestKey = "guest-key"
EntryGuestCert = "guest-cert"
EntryHostCert = "host-cert"
EntryScope = "expect"
EntryHostAddr = "host-addr"
)
// Roles named as the last URI SAN path segment.
const (
RoleHost = "host"
RoleGuest = "guest"
)
const uriScheme = "spinifex-lambda"
// Scope names one environment generation:
// Region/account/function ID/environment ID/generation.
type Scope string
// ParseScope accepts exactly five non-empty, slash-separated segments.
func ParseScope(s string) (Scope, error) {
parts := strings.Split(s, "/")
if len(parts) != 5 {
return "", fmt.Errorf("lambdav1: scope %q: want 5 segments, got %d", s, len(parts))
}
for _, p := range parts {
if p == "" || strings.ContainsAny(p, " \t\r\n?#%") {
return "", fmt.Errorf("lambdav1: scope %q: empty or invalid segment", s)
}
}
return Scope(s), nil
}
// URI is the single URI SAN a certificate for role in this scope carries.
func (s Scope) URI(role string) string {
return uriScheme + "://" + string(s) + "/" + role
}
+20
View File
@@ -0,0 +1,20 @@
package lambdav1
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParseScope(t *testing.T) {
s, err := ParseScope("ap-southeast-2/000000000001/fn-1/env-1/gen-1")
require.NoError(t, err)
assert.Equal(t, "spinifex-lambda://ap-southeast-2/000000000001/fn-1/env-1/gen-1/host", s.URI(RoleHost))
for _, bad := range []string{
"", "a/b/c/d", "a/b/c/d/e/f", "a//c/d/e", "a/b/c/d/e/", "a/b/c/d/e?x", "a/b/c/d/e#x", "a b/b/c/d/e",
} {
_, err := ParseScope(bad)
assert.Error(t, err, bad)
}
}
+62
View File
@@ -74,3 +74,65 @@ type ListAccountsResponse struct {
Accounts []AccountSummary `json:"accounts"`
Count int `json:"count"`
}
// IAMQuiescence is the coordinator's recorded view of IAM quiescence for one
// fence. Recording only: it admits nothing, and QuiescedScope stays empty until
// a final inventory re-read exists to catch a late write.
type IAMQuiescence struct {
OperationID string `json:"operationId"`
Fence uint64 `json:"fence"`
Generation uint64 `json:"generation"`
QuiescedScope []string `json:"quiescedScope"`
Unresolved []UnresolvedScope `json:"unresolved"`
Consumers []ConsumerBasis `json:"consumers"`
Writers []AccountedWriter `json:"writers"`
Inventory []InventoryStatus `json:"inventory"`
EvaluatedAt string `json:"evaluatedAt"`
}
// UnresolvedScope names a scope or writer that blocks quiescence, with a fixed
// reason. It is never a timeout.
type UnresolvedScope struct {
Scope string `json:"scope"`
Class string `json:"class"`
Reason string `json:"reason"`
}
// ConsumerBasis cites an enforcement consumer and the accepted contract that
// lets it count as having applied the generation.
type ConsumerBasis struct {
Consumer string `json:"consumer"`
Basis string `json:"basis"`
}
// AccountedWriter is a writer that cannot be fenced and is covered by the
// owner's inventory instead. Ref names the tracked work that closes the gap.
type AccountedWriter struct {
Writer string `json:"writer"`
Basis string `json:"basis"`
Ref string `json:"ref"`
}
// InventoryStatus is the owner inventory's status for one kind at evaluation.
type InventoryStatus struct {
Kind string `json:"kind"`
Status string `json:"status"`
}
// Classes of an UnresolvedScope.
const (
UnresolvedClassFence = "fence"
UnresolvedClassConsumer = "consumer"
UnresolvedClassWriter = "writer"
)
// Fixed reasons of an UnresolvedScope.
const (
ReasonFenceMismatch = "fence-mismatch"
ReasonIAMReadbackFailed = "iam-readback-failed"
ReasonNoAcceptedEnforcement = "no-accepted-enforcement-contract"
ReasonNoCompleteOwnerInventory = "no-complete-owner-inventory"
ReasonParticipantNotDeclared = "participant-not-declared"
ReasonOwnerInventoryIncomplete = "owner-inventory-incomplete"
ReasonFinalInventoryRereadNotWired = "final-inventory-reread-not-wired"
)
+53
View File
@@ -0,0 +1,53 @@
package telemetryv1
import "regexp"
// Node live subjects mirror the instance ones, keyed by node name. Only the
// super-admin account's gateway handler subscribes to them.
const (
nodeLiveWatchSubjectPrefix = "telemetry.watch.node."
nodeLiveSampleSubjectPrefix = "telemetry.live.node."
)
var liveNodePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
// ValidLiveNode reports whether a node name is safe to place in a subject.
func ValidLiveNode(node string) bool {
return liveNodePattern.MatchString(node)
}
// NodeLiveWatchSubject is where a viewer asks a node to keep sampling itself.
// A request on it is answered with a NodeLiveRing.
func NodeLiveWatchSubject(node string) string {
return nodeLiveWatchSubjectPrefix + node
}
// NodeLiveSampleSubject carries one NodeLiveSample per period while watched.
func NodeLiveSampleSubject(node string) string {
return nodeLiveSampleSubjectPrefix + node
}
// NodeLiveRing answers a watch with the samples newer than its SinceMillis.
type NodeLiveRing struct {
Samples []NodeLiveSample `json:"samples"`
}
// NodeLiveSample is one host measurement. Rates are per second over the
// interval ending at TimeMillis.
type NodeLiveSample struct {
TimeMillis int64 `json:"t"`
CPUPercent float64 `json:"cpu"`
// MemoryUsedPercent is used memory less page cache, as free(1) reports it.
MemoryUsedPercent float64 `json:"mem"`
Load1 float64 `json:"load1"`
// Planes holds the traffic of each plane's physical NICs, keyed wan, lan, vpc.
Planes map[string]NodeLivePlane `json:"planes"`
}
// NodeLivePlane is one plane's traffic from the host's side.
type NodeLivePlane struct {
NetworkIn float64 `json:"netIn"`
NetworkOut float64 `json:"netOut"`
PacketsIn float64 `json:"pktIn"`
PacketsOut float64 `json:"pktOut"`
}
+1 -1
View File
@@ -340,7 +340,7 @@ spx get vms
Spinifex ships with a built-in web console — an alternative to the AWS CLI, SDKs, and Terraform, analogous to the AWS Management Console. Every action in the UI is a standard AWS SigV4 API call, so the same IAM policies and audit behaviour apply.
<p align="center">
<img src="../../../.github/assets/spinifex-ui.jpg" alt="Spinifex Web UI" width="900">
<img src="../../../.github/assets/dashboard.webp" alt="Spinifex Web UI" width="900">
</p>
### Open the Console
+2
View File
@@ -2413,6 +2413,7 @@
"ListAssociatedAccessPolicies",
"ListClusters",
"ListInternalAddons",
"ListInternalWorkers",
"ListNodegroups",
"ListTagsForResource",
"PublishInternal",
@@ -2502,6 +2503,7 @@
"extra": [
"GetRecoveryDirective",
"ListInternalAddons",
"ListInternalWorkers",
"PublishInternal",
"WebhookTokenReview"
]
+2 -1
View File
@@ -903,7 +903,7 @@ spot-price: On owned hardware there is no spot-to-on-demand price differential,
## eks
`2017-11-01` — 27 of 70 modelled operations implemented (38.6%), 0 stubbed, 0 not applicable, 4 registered outside the pinned model.
`2017-11-01` — 27 of 70 modelled operations implemented (38.6%), 0 stubbed, 0 not applicable, 5 registered outside the pinned model.
### Not implemented
@@ -955,6 +955,7 @@ spot-price: On owned hardware there is no spot-to-on-demand price differential,
- `GetRecoveryDirective`
- `ListInternalAddons`
- `ListInternalWorkers`
- `PublishInternal`
- `WebhookTokenReview`
+1 -1
View File
@@ -633,7 +633,7 @@ ssh -i ~/.ssh/oci-spx ubuntu@"$(head -1 .validate-vm-multi/hosts)" \
If this returns a list of available instance types, your installation is working.
<p align="center">
<img src="../../.github/assets/spinifex-ui.jpg" alt="Spinifex Web UI" width="900">
<img src="../../.github/assets/dashboard.webp" alt="Spinifex Web UI" width="900">
</p>
+2 -1
View File
@@ -99,6 +99,7 @@ behavior in other words.
| 4432 | Formation server | HTTPS | Cluster (bootstrap only) | Cluster join coordination; active only while a join token is valid. Binds the node's `--bind` (lan) address. See *Formation port lifecycle* below. | Short-lived bearer token + TLS¹ |
| 4222 | spinifex-nats (client) | NATS + TLS | Cluster | Internal service bus for EC2/EBS/VPC/S3 handlers | Token + mutual TLS (cluster CA) |
| 4248 | spinifex-nats (cluster) | NATS + TLS | Cluster | Inter-node NATS federation | Token + mutual TLS (cluster CA) |
| 5001 | iperf2 (admin network test) | TCP | Cluster, any plane | Throughput test between two nodes, started only by the super-admin account. Listens on one plane address for the length of one test, then exits. Runs with no capabilities. | None — peer-scoped by firewall, and the client may only target its own plane subnet |
| 5300 | northstar | DNS (UDP + TCP) | Cluster | Forward target for every node's per-instance DNS shim, dialled cross-node. Binds the wildcard by design. | None — restrict by firewall |
| 6660 | predastore (blob node) | QUIC / UDP | Cluster | Erasure-coded object shard transport between hosts. Multi-node clusters only — see *Predastore ports* below. | TLS 1.3, server certificate verified against the cluster CA |
| 7660 | predastore (meta node) | QUIC / UDP | Cluster | Raft consensus over global state — buckets and the object index — between hosts. Multi-node clusters only. | TLS 1.3, server certificate verified against the cluster CA |
@@ -221,7 +222,7 @@ table inet spinifex_filter {
# Cluster, from peer nodes only. Replace with your nodes' lan-plane
# addresses — a CIDR does not generalise to nodes on different subnets.
ip saddr { 10.0.1.1, 10.0.1.2, 10.0.1.3 } tcp dport { 4222, 4248, 4432, 5300, 6641, 6642, 6643, 6644, 8660 } accept
ip saddr { 10.0.1.1, 10.0.1.2, 10.0.1.3 } tcp dport { 4222, 4248, 4432, 5001, 5300, 6641, 6642, 6643, 6644, 8660 } accept
ip saddr { 10.0.1.1, 10.0.1.2, 10.0.1.3 } udp dport { 5300, 6660, 7660 } accept
# Encap, from peer chassis only. Replace with your nodes' vpc-plane
+78 -21
View File
@@ -24,7 +24,7 @@ All colours are OKLCH and come from mulgadc.com, so product and site match.
| Token | Use |
|---|---|
| `background` | The app page. Warm off-white in light, ink `#14181D` in dark. |
| `card`, `popover` | Raised surfaces. White in light, about `#1B2027` in dark. |
| `card`, `popover` | Raised surfaces. White in light, about `#1B2027` in dark. `popover` is every floating surface: tooltips, popovers, menus and pickers. |
| `muted`, `secondary`, `accent` | Hover rows, secondary buttons, quiet fills. |
| `border` | Every divider and card edge. `#DCD8CE` in light, `oklch(1 0 0 / 8%)` in dark. |
| `brand` | Brand orange `#EE4B12`, for the logo and decoration only. It fails text contrast, so it never carries text. |
@@ -39,15 +39,22 @@ Each status has a solid token plus `-foreground` (text on a tinted background),
| Status | Hue | AWS states |
|---|---|---|
| `success` | green | running, available, completed, healthy |
| `warning` | brand yellow `#F5B500` | pending, stopping, creating, modifying, deleting, draining |
| `danger` | cool red, hue 17 | stopped, error, failed, unhealthy, unavailable |
| `success` | green | settled and good: running, available, active, associated, attached, in-use, healthy, ok, main |
| `warning` | brand yellow `#F5B500` | changing state and will settle: pending, stopping, creating, modifying, deleting, draining |
| `caution` | orange, hue 58 | works but needs attention: degraded, impaired, insufficient-data |
| `danger` | cool red, hue 17 | stopped, error, failed, update-failed, unhealthy, unavailable, blackhole |
| `info` | blue | informational notes |
| `neutral` | grey `#9AA1A8` | terminated (muted text), and any unmapped state |
| `neutral` | grey `#9AA1A8` | gone or absent (terminated, deleted, no) in muted text, and any unmapped state |
`stopped` is danger because EC2 reads it that way, although RDS treats it as a resting state; splitting the map by service is its own change.
`StateBadge` (`src/components/state-badge.tsx`) is the only mapping from an AWS state to a tone, and it exposes the result as `data-tone` for tests.
Its tones are `success`, `progress` (the yellow `warning` token), `caution`, `danger`, `muted` and `neutral`.
A `progress` state carries the submit button's spinning loader, so a launching instance reads as work under way; `StatusBadge` does not, because its yellow can mean waiting on the user, as a zone's `pending nameservers` does.
It shows every state lowercase with hyphens, as EC2 writes them, so EKS's `ACTIVE` reads `active` and Bedrock's `IN_PROGRESS` reads `in-progress`; the API value, filters and CLI panels keep AWS's case.
A good or settled state is always green, never grey, and a status that is not an API state, such as a cluster's health, uses `StatusBadge` with a tone rather than a `Badge`.
The orange of `caution` is kept clear of the primary accent's hue, which marks actions and never a status.
`Badge`'s default variant is the brand primary and is never used for a status; a label that is not a status, such as `default v3` or `Leader`, uses a `secondary` or `outline` `Badge`.
Every status badge measures above 4.8:1 against its tinted background in both themes.
**Danger is separated from the primary accent by hue alone in dark mode**: the two have the same lightness.
@@ -67,18 +74,21 @@ Colour is never the only key: label every series.
| UI text, tables and forms | Geist (`font-sans`) |
| IDs, ARNs, IPs, CIDRs, code and eyebrow labels | JetBrains Mono (`font-mono`), with `tabular-nums` for figures |
| Step | Size | Use |
|---|---|---|
| `2xl` | 26px | page title (`PageHeading`) |
| `xl` | 22px | section heading |
| `lg` | 17px | |
| `base` | 15px | |
| `sm` | 14px | body and table default |
| `xs` | 13px | badges, secondary text |
| `2xs` | 12px | mono eyebrow labels |
| Step | rem | At the default 16px browser font | Use |
|---|---|---|---|
| `2xl` | 1.625 | 28.6px | page title (`PageHeading`) |
| `xl` | 1.375 | 24.2px | section heading |
| `lg` | 1.0625 | 18.7px | |
| `base` | 0.9375 | 16.5px | |
| `sm` | 0.875 | 15.4px | body and table default |
| `xs` | 0.8125 | 14.3px | badges, secondary text |
| `2xs` | 0.75 | 13.2px | mono eyebrow labels |
The scale sits a step above Tailwind's defaults, as consoles such as Vultr's do, because 13px body text read as cramped on a wide screen.
Code blocks are set at 12px (`--text-code-block`) so a long command still fits.
The root font size is 110% (`html` in `src/styles.css`), so one rem is 17.6px at the browser default.
Everything is sized in rem, so text, spacing and breakpoints scale together, as they would at 110% browser zoom, and a user's own font-size setting still applies.
The scale sits above Tailwind's defaults, as consoles such as Vultr's do, because the console read as small on a wide screen at 100%.
Code blocks are set at 0.75rem (`--text-code-block`) so a long command still fits.
Size new things in rem through the type and spacing scales, never in px, or they will not scale with the rest.
### Primary and contrast
@@ -169,6 +179,22 @@ Every other list is a `DataTable`, and the test also fails when an allowed file
| S13 | a component outside `ui/` renders a raw `<input>`, `<select>` or `<textarea>` |
| S15 | a route imports the `ui/alert` primitive instead of using `ErrorBanner` |
Rules that ADR-0016 does not yet number are named by what they hold until their amendment is accepted:
| Rule | Fails when |
|---|---|
| status pills come from StateBadge or StatusBadge | a component outside `ui/` renders `<Badge>` with the default variant |
| status pills come from StateBadge or StatusBadge | a file outside `state-badge.tsx` builds a `rounded-full` pill on a status colour |
| floating surfaces follow the theme | a file fills with `bg-foreground` or `text-background`, or a tooltip, popover, hover card, menu, select or combobox is not on `bg-popover` and `text-popover-foreground` |
| expanding a panel keeps its tab | a `fullPage` link does not pass `search={{ tab }}` |
| resource tags are edited in place | `PanelTags` or `TagsEditor` comes back |
| lists filter through one FilterBar | a component other than `FilterBar` imports `ui/toggle-group` |
| a component handed a form reads errors through `useFormState` | a file typed with `UseFormReturn` reads `form.formState` |
The last one matters because the console builds with the React compiler and the unit tests run without it.
With the compiler on, a child handed a react-hook-form object is cached on that object, whose identity never changes, so errors read from `form.formState` never draw and the submit looks dead.
`useFormState({ control })` subscribes the child itself.
An exception is named in that rule's allowlist with its reason, and the test fails when an allowed file stops needing it.
S11, S14 and S16 are held by review, since none has a shape in the source a test can read without false alarms.
@@ -177,7 +203,7 @@ S11, S14 and S16 are held by review, since none has a shape in the source a test
`src/lib/nav.ts` is the one description of the console's navigation.
The sidebar, the command palette and the breadcrumbs all read it, and `nav.test.ts` checks every destination against the generated route tree, so a renamed route fails a test rather than leaving a dead link.
- **Sidebar.** Groups take generic names rather than AWS's service marks: Compute, Databases, Authentication and Object Storage, not EC2, RDS, IAM and S3. Pages and the rest of the console keep the AWS names, and each group's `service` keeps its AWS name findable in the command palette, where typing it exactly ranks that group first. Each service group folds, and a folded group stays folded across reloads (`localStorage["spinifex-ui-nav-collapsed"]`). Navigating into a folded group unfolds it so the active item shows, and it can then be folded again, the current group included. On a phone the sidebar is a sheet, and any navigation closes it.
- **Sidebar.** Groups take generic names rather than AWS's service marks: Compute, Databases, Authentication and Object Storage, not EC2, RDS, IAM and S3. Pages and the rest of the console keep the AWS names, and each group's `service` keeps its AWS name findable in the command palette, where typing it exactly ranks that group first. Each service group folds, and a folded group stays folded across reloads (`localStorage["spinifex-ui-nav-collapsed"]`). Navigating into a folded group unfolds it so the active item shows, and it can then be folded again, the current group included. Folding animates through the `nav` variant of `CollapsibleContent`, opening over 200ms and closing over 150ms, and switches at once under reduced motion. On a phone the sidebar is a sheet, and any navigation closes it.
- **Command palette.** ⌘K or Ctrl K, or the Search button in the header. It lists every page the user can reach, every create flow (`create` on a nav item), and a theme toggle. It is navigation only, with no resource search yet.
- **Breadcrumbs.** Service, then list page, then the resource or the create flow. A resource ID is set in mono. On a phone only the last crumb shows.
- **Sign in.** The sign-in card sits over the shell on a light, barely blurred overlay rather than on a page of its own, so the console stays in view. The shell behind it is `inert`, which keeps pointer, keyboard and screen reader out of it until the user signs in.
@@ -202,8 +228,13 @@ So columns drop out when a side panel narrows the list as well as on a small scr
List pages keep their filter, state and sort in the URL, so a filtered view can be bookmarked, shared and survives a reload.
EC2 Instances is the reference page (`ec2/(instances)/-components/instances-page.tsx`):
- The first column names the resource: the `Name` tag in the primary colour, with the ID in mono beneath it, opening its side panel.
- The first column is the instance ID in mono, opening its side panel, and the second its `Name` tag.
- A long value ends in an ellipsis and shows in full on hover (`TruncatedText`), so it never widens its column.
- A time column shows a relative time, `33 min ago` or `8 months ago`, with the full timestamp on hover (`RelativeTime`).
- A Tags column shows one tag key as a pill and `+N` for the rest, and hover lists every tag with its value (`TagPills`); it leaves out `Name`, which has its own column.
- Below `md`, only the ID, Name and State columns remain.
- Bulk actions appear above the table once a row is selected. Each action counts only the selected instances it applies to, so a mixed selection never sends a call that must fail, and Terminate asks first and lists every ID.
- Search and state filters sit in one `FilterBar` (`src/components/filter-bar.tsx`) above the table: a search box, an optional set of choices with counts, and Clear filters while anything is filtered.
- An empty account gets a call to action, and an empty filter result says the filters are why.
VPCs and Internet gateways follow the same pattern.
@@ -219,6 +250,12 @@ Every list with a delete action has row checkboxes. Selecting a row shows `Selec
- **The bulk delete and the panel's delete are the same function.** Where a single delete is several calls, such as removing dependants first, the sequence lives in one place and both use it.
- The verb follows the AWS console: Release for an Elastic IP, Deregister for an image.
### Lists inside a panel
A list inside a panel tab, such as a hosted zone's records, is a `DataTable` with row checkboxes, and a click on a row opens it for editing in a `FormPanel`.
Rows the user cannot change, such as a zone's own SOA and NS, are muted and cannot be selected (`isRowActionable`).
A batch delete uses the service's batch call where it has one, so Route 53 removes the whole selection in one `ChangeResourceRecordSets`.
### Typed confirmation
A delete that cannot be walked back asks the user to type a word first, as the AWS console does before deleting a volume.
@@ -264,13 +301,24 @@ Modelled on UniFi's console: a click on a row opens the resource in a panel besi
- **URL.** The panel is search state on the list route: `selected=<id>`, `tab=overview|monitoring|settings`, and `create=true`. Defaults are stripped, so a closed panel leaves the plain list address. Opening or closing a panel pushes a history entry, so Back closes it; a tab or filter change replaces the entry.
- **Layout.** From `lg` (1024px) the panel is fixed to the right edge, full height below the header, flush with no outer margin, and it slides in over the list. The list keeps its width and columns underneath, so nothing reflows when a panel opens, and a soft gradient on the panel's left edge reads as the panel lying on top. Below `lg` there is no room to share, so the panel replaces the list as a full page with a back arrow. `useWideLayout` decides, through `matchMedia`.
- **`DetailPanel`.** A header with the resource's own page (left) and close (right), the title and its ID, a summary of state and quick actions, then icon tabs with tooltips. Escape closes it unless a dialog or menu is open over it. Closing slides the panel out over 150ms, or at once under reduced motion. Each tab, and a create form, sits in its own error boundary, so a failed query shows in the panel and the list keeps working.
- **Contents.** `PanelSection` is a folding card, `PanelFields` and `PanelField` a label and value list, with `copy` for a one-click copy of IDs and addresses, and `PanelTags` the tag list. Create forms take an `onClose(id?)` prop: embedded, they hide their back link and heading, and a create selects the new resource.
- **Contents.** `PanelSection` is a folding card, `PanelFields` and `PanelField` a label and value list, with `copy` for a one-click copy of IDs and addresses, and `InlineTags` the tag list. Create forms take an `onClose(id?)` prop: embedded, they hide their back link and heading, and a create selects the new resource.
- **One component is both the panel and the page.** Each resource has a single details component (`InstanceDetails`, `VpcDetails`, `InternetGatewayDetails`) that takes `layout="auto" | "page"`. The list renders it as the panel; `/ec2/describe-instances/$id` and its kind render the same component as a page, as one centred column under a standard left-aligned heading, with state and actions on the right and text tabs. A feature added to the panel is on the page by construction, and the page ignores Escape and has a back arrow in place of close. Expanding the panel to its page keeps the tab, and query results such as fetched console output come along from the cache.
- **A click on the list's background closes the panel**, as UniFi's does. A row selects another resource instead, and links, buttons and inputs keep their own behaviour. Selecting rows for a bulk action closes it too, so the bulk bar and the panel never compete.
- **Actions.** State actions sit in the summary as a button group, and the rest go in an Actions menu, Unikraft style. Stop, Reboot and every destructive action confirm in a dialog.
- **Loading.** A panel or page still loading shows `PanelSpinner`, a centred spinner on the background, not a grey skeleton block.
- **`DetailCard`, `DetailRow` and `ListCard` are retired.** Every resource page uses the panel sections instead.
### Tags
`InlineTags` (`src/components/inline-tags.tsx`) shows a resource's tags in its panel and edits them in place.
Each row has a pencil, which turns the key and value into inputs and becomes a tick to save, and a bin to remove the tag; `+ Add tag` appends a row being edited.
Enter saves and Escape cancels the row without closing the panel.
Every row saves on its own request through the service's own tagging call, and a failure shows beside its row.
AWS has no rename, so changing a key puts the new key and then removes the old one, and a failure between the two leaves both rather than neither.
Keys are 1 to 128 characters with no `aws:` prefix and no duplicates, and values up to 256.
Without `onPut` and `onRemove` it is read-only, as for a system image or an AWS-managed policy.
Panels use the per-service wrappers in `src/components/resource-tags.tsx` and the writers in `src/mutations/tags.ts` rather than wiring the calls themselves.
### Forms from a resource's panel
A form that acts on an open resource, such as attaching a volume, scaling a node group or adding a listener, opens in `FormPanel` (`src/components/form-panel.tsx`), never in a dialog.
@@ -285,8 +333,16 @@ Every create flow opens in the side panel over its list, through `CreatePanel`,
- **URL.** `create=true` opens it, plus a list-local field where the flow needs context (`volume` for a snapshot, `instance` for an RDS snapshot, `launch=service|task` on ECS clusters). The old `create-*` addresses redirect to the list with the panel open, so links and bookmarks keep working.
- **Form.** The fields come in the order AWS asks for them. Settings that are on or off are `Switch`es, and a multi-select picker (subnets, security groups) is a `SwitchList`, a boxed list with one switch per row. Checkboxes only select table rows.
- **CLI.** Every create form ends with a `CliCommandPanel` showing the AWS CLI commands that send the same request, built from the form's live values and only the flags the console actually sends.
- **Submit.** `FormActions` turns the submit button into a spinner with its pending label in place, and `FormLock`, a native `<fieldset disabled>`, disables every control above it until the request settles. Nothing above the form appears or moves, and the panel does not scroll.
- **CLI.** Every create form ends with a `CliCommandPanel` showing the AWS CLI commands that send the same request, built from the form's live values and only the flags the console actually sends. The commands wrap to the panel's width and never scroll sideways; Copy takes the unwrapped text.
- **Sections.** Related fields are grouped in `PanelSection` boxes, as the instance launch form groups Image, Instance, Network and Root volume.
- **Nothing to pick, no field.** An optional picker with nothing usable to choose, such as Launch Template or Placement Group with none available, is left out of the form rather than shown holding only `none`.
- **Advanced settings.** Settings most users leave at their defaults sit in a collapsed Advanced settings section, which opens by itself when a field inside it fails validation.
- **Choices with a mark.** A few named products, such as database engines or distributions, are `ChoiceTile`s with the product's own mark from `src/assets/`, not a select. One that cannot be used stays visible and disabled, saying why.
- **Durations and windows.** A duration is a select of presets with the AWS default first and named (`Auto (5 min)` for a record's TTL), keeping a custom value the API returned. A time window, such as an RDS backup or maintenance window, is a day, start time and length picker that refuses an overlap before submitting.
- **Labels by type.** Where one field means different things by type, its label follows the type, as a record's value reads `IPv4 address` for A and `Mail server` for MX.
- **Long pickers.** A `SwitchList` that can run long, such as security groups, scrolls inside its box rather than pushing the form down.
- **Help.** A field's longer explanation goes in an (i) beside its label, through the `info` prop of `TextField` and `SelectField`, rather than in text under the field. Text under a field is for what the user must know before submitting.
- **Submit.** `FormActions` cross-fades the submit label into a spinner with its pending label over 150ms, at one width, so the button never changes size, and `FormLock`, a native `<fieldset disabled>`, disables every control above it until the request settles. Nothing above the form appears or moves, and the panel does not scroll.
- **Failure.** A refused request shows beside the button through `FormActions`'s `error`, and the form unlocks. The handler wraps only the mutation call in `try`, with an empty `catch` that returns, because react-hook-form rethrows whatever the handler throws and the error is already on screen from the mutation's state.
- **Success.** `onClose(id)` closes the panel and selects the new resource, where the list has a panel to select it in.
- **Appliance images.** A create that needs an ECS, EKS or RDS appliance image shows the missing-image callout inside its panel, never on the list, and only the step that needs the image is blocked.
@@ -306,6 +362,7 @@ A gap of more than three sample periods breaks the line rather than drawing acro
## Dates
`formatDateTime` writes the AWS console's form in the viewer's zone, `2026/06/04 02:00 GMT-5`, with a 24-hour clock and UTC as plain `GMT`.
In a table the time is relative (`relativeTime` in `src/lib/relative-time.ts`), rounded down to the largest whole unit, and the full form shows on hover.
## Testing
+1 -1
View File
@@ -255,7 +255,7 @@ The same profile is set up on node 1, if you prefer to work from there:
If this returns a list of available instance types, your installation is working.
<p align="center">
<img src="../../.github/assets/spinifex-ui.jpg" alt="Spinifex Web UI" width="900">
<img src="../../.github/assets/dashboard.webp" alt="Spinifex Web UI" width="900">
</p>
<p align="center"><em>The Spinifex web console, on port 3000 of node 1.</em></p>
+4 -4
View File
@@ -27,10 +27,10 @@ require (
github.com/klauspost/cpuid/v2 v2.4.1
github.com/miekg/dns v1.1.73
github.com/minio/highwayhash v1.0.4
github.com/mulgadc/bluebottle v1.23.0
github.com/mulgadc/northstar v1.23.0
github.com/mulgadc/predastore v1.23.0
github.com/mulgadc/viperblock v1.23.0
github.com/mulgadc/bluebottle v1.24.0
github.com/mulgadc/northstar v1.24.0
github.com/mulgadc/predastore v1.24.0
github.com/mulgadc/viperblock v1.24.0
github.com/nats-io/nats-server/v2 v2.15.2
github.com/nats-io/nats.go v1.55.0
github.com/nats-io/nkeys v0.4.16
+8 -8
View File
@@ -301,14 +301,14 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/mulgadc/bluebottle v1.23.0 h1:h2BOSBDrNjIHA7QUeWX9xci2zcIHWsB1Ky0Q///QPaI=
github.com/mulgadc/bluebottle v1.23.0/go.mod h1:eWfnT7nGgG93oChqMoTlGv2onPVZ2bVGSyg4nKl1s7I=
github.com/mulgadc/northstar v1.23.0 h1:5oeFDB3fifzFb+I5nDAXsewt2rYdEbrUsHl7gwxPZ5k=
github.com/mulgadc/northstar v1.23.0/go.mod h1:zZtrmR8ITOhZZQrVbCJQUBpOUiblA2kogKh0Oi5xh/8=
github.com/mulgadc/predastore v1.23.0 h1:JpjhDyF1CLTLGDmXrYPSFRImDXfu5L2zeXdiHPHwtNw=
github.com/mulgadc/predastore v1.23.0/go.mod h1:y5nBVTX+E+6G2z9xkH9gkecglKbUGnCCitd7d8ZZaJ8=
github.com/mulgadc/viperblock v1.23.0 h1:/HZDVVw6/tiq497AVjMeEG+dLn4du4pcbBSiwZKCamg=
github.com/mulgadc/viperblock v1.23.0/go.mod h1:frYnDTsFF0MTl7dP84fcO4PsyWvHMb8EQQFIPajxai0=
github.com/mulgadc/bluebottle v1.24.0 h1:7rwzW4n0lo3KWGpuUYiQ8KhIFNV/4o1AChrEp79PCKE=
github.com/mulgadc/bluebottle v1.24.0/go.mod h1:BzyzOpzpzAyKhGYppwcOIEQRqMASc6IoKCBhaaODXbQ=
github.com/mulgadc/northstar v1.24.0 h1:2RtBUCMNvwmkqTlTi1Ve5/9Hkqe6gWWUVMkSQ0nhbhY=
github.com/mulgadc/northstar v1.24.0/go.mod h1:0NfFxVWt2ZZQzZ7ObfsEJ2O7lL1yjKKf3ZGF4poH0QM=
github.com/mulgadc/predastore v1.24.0 h1:YECc+vOmZRQYaMMjKmJOnFcKZ7cOgTr3b7Sb4JmgmDU=
github.com/mulgadc/predastore v1.24.0/go.mod h1:+EKnT7S5POYhUPE6ZS5mvMR6TS735P0m9UsOrQ88TAg=
github.com/mulgadc/viperblock v1.24.0 h1:i4WNGvfnDeYppqohWDH5qGpUrchl4qpTqyQxj/BV7nk=
github.com/mulgadc/viperblock v1.24.0/go.mod h1:iY4bdiXYdGbxBrJe1zizGGh65yBGEta9CWlIhpgHne0=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
+97
View File
@@ -0,0 +1,97 @@
#!/bin/bash
# build-lambda-runtime-microvm-image.sh — build the Lambda runtime microVM kernel
# + initramfs: a guest running the Lambda guest agent, with virtio-net for its
# host control connection. It is not shipped.
#
# Inputs:
# $REPO_ROOT/build/microvm/lambda-runtime/{init.sh,inittab,run-agent}
# $REPO_ROOT/bin/lambda-agent (make bin/lambda-agent)
#
# Outputs:
# $REPO_ROOT/build/microvm/lambda-runtime/vmlinuz
# $REPO_ROOT/build/microvm/lambda-runtime/initramfs.cpio.gz
#
# Rootfs strategy and module stripping: scripts/lib/microvm-image.sh.
# shellcheck disable=SC2034 # variables are consumed by the sourced library
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BUILD_DIR="$REPO_ROOT/build/microvm/lambda-runtime"
INIT_SH="$BUILD_DIR/init.sh"
INITTAB="$BUILD_DIR/inittab"
RUN_AGENT="$BUILD_DIR/run-agent"
LAMBDA_AGENT_BIN="$REPO_ROOT/bin/lambda-agent"
TAG="[build-lambda-runtime-microvm-image]"
ALPINE_VERSION="${ALPINE_VERSION:-3.24}"
ALPINE_MIRROR="${ALPINE_MIRROR:-https://dl-cdn.alpinelinux.org/alpine}"
# kmod: the image's own depmod/modprobe rebuild module metadata. busybox ships ip.
ALPINE_PACKAGES="busybox linux-virt kmod ca-certificates"
# tiny_power_button turns the ACPI power button into a signal busybox init
# handles as poweroff.
MICROVM_EXTRA_MODULES="${MICROVM_EXTRA_MODULES:-tiny_power_button}"
# virtio_net needs failover and net_failover, which the virtio* glob misses.
MICROVM_EXTRA_KEEP_GLOBS=("*failover*.ko*")
MICROVM_GATE_MODULES="qemu_fw_cfg virtio_net"
# shellcheck source=lib/microvm-image.sh
source "$REPO_ROOT/scripts/lib/microvm-image.sh"
echo "$TAG repo root: $REPO_ROOT"
echo "$TAG build dir: $BUILD_DIR"
microvm_check_tools
for f in "$INIT_SH" "$INITTAB" "$RUN_AGENT"; do
if [ ! -f "$f" ]; then
echo "ERROR: $f not found — cannot build initramfs" >&2
exit 1
fi
done
if [ ! -x "$LAMBDA_AGENT_BIN" ]; then
echo "ERROR: $LAMBDA_AGENT_BIN not found — run 'make bin/lambda-agent'" >&2
exit 1
fi
if ! file -b "$LAMBDA_AGENT_BIN" | grep -q "statically linked"; then
echo "ERROR: $LAMBDA_AGENT_BIN is not statically linked — it cannot run on the musl guest" >&2
exit 1
fi
microvm_init_dirs
microvm_make_rootfs
microvm_empty_dev
echo "$TAG installing init, inittab, run-agent and lambda-agent..."
install -m 0755 "$INIT_SH" "$CHROOT_DIR/init"
install -m 0644 "$INITTAB" "$CHROOT_DIR/etc/inittab"
mkdir -p "$CHROOT_DIR/usr/local/lib/lambda-runtime" "$CHROOT_DIR/usr/local/bin"
install -m 0755 "$RUN_AGENT" "$CHROOT_DIR/usr/local/lib/lambda-runtime/run-agent"
install -m 0755 "$LAMBDA_AGENT_BIN" "$CHROOT_DIR/usr/local/bin/lambda-agent"
# Function-code mountpoint and scratch space ship empty.
mkdir -p "$CHROOT_DIR/var/task" "$CHROOT_DIR/tmp" \
"$CHROOT_DIR/proc" "$CHROOT_DIR/sys" "$CHROOT_DIR/dev" "$CHROOT_DIR/etc/ssl/certs"
# The bootstrap runs unprivileged, so / must be traversable (mktemp -d makes it
# 0700) and nothing it runs from may be group-writable.
chmod 0755 "$CHROOT_DIR" "$CHROOT_DIR/var/task" "$CHROOT_DIR/usr/local/lib/lambda-runtime"
microvm_locate_kernel
microvm_strip_modules
microvm_strip_rootfs
microvm_stage_kernel
microvm_pack_initramfs
# Nothing reaches $BUILD_DIR until the staged pair passes these checks.
for out in vmlinuz initramfs.cpio.gz; do
if [ ! -s "$STAGE_DIR/$out" ]; then
echo "ERROR: staged $out is missing or empty" >&2
exit 1
fi
done
if ! gzip -t "$STAGE_DIR/initramfs.cpio.gz"; then
echo "ERROR: staged initramfs.cpio.gz is not valid gzip" >&2
exit 1
fi
mv -f "$STAGE_DIR/vmlinuz" "$BUILD_DIR/vmlinuz"
mv -f "$STAGE_DIR/initramfs.cpio.gz" "$BUILD_DIR/initramfs.cpio.gz"
echo ""
echo "$TAG done."
+18 -347
View File
@@ -18,6 +18,7 @@
# 1. apk available on host → install directly into a temp chroot (Alpine CI/CD)
# 2. docker available → run alpine container, export filesystem
# 3. podman available → same via podman
# shellcheck disable=SC2034 # variables are consumed by the sourced library
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
@@ -44,21 +45,19 @@ ALPINE_PACKAGES="busybox linux-virt iproute2 ca-certificates e2fsprogs kmod"
# button (QMP system_powerdown) into a signal busybox init handles as poweroff.
MICROVM_EXTRA_MODULES="${MICROVM_EXTRA_MODULES:-ext4 tiny_power_button}"
# Module file globs kept on top of virtio*/*fw_cfg*: virtio_net deps for live migration.
MICROVM_EXTRA_KEEP_GLOBS=("*failover*.ko*")
# Modules the image modprobe must resolve, beyond the extras.
MICROVM_GATE_MODULES="qemu_fw_cfg virtio_net"
# shellcheck source=lib/microvm-image.sh
source "$REPO_ROOT/scripts/lib/microvm-image.sh"
echo "$TAG repo root: $REPO_ROOT"
echo "$TAG build dir: $BUILD_DIR"
mkdir -p "$BUILD_DIR"
# --- Verify non-negotiable tools ---
# fakeroot is mandatory: device nodes are written into the cpio archive inside a
# faked-root environment so no real device node is ever created on the host
# filesystem (which previously required sudo mknod and risked clobbering host
# /dev/null on cleanup).
for tool in cpio gzip find fakeroot; do
if ! command -v "$tool" >/dev/null 2>&1; then
echo "ERROR: required tool not found: $tool" >&2
exit 1
fi
done
microvm_check_tools
if [ ! -x "$SQS_WORKER_BIN" ]; then
echo "ERROR: $SQS_WORKER_BIN not found — run 'make bin/sqs-worker'" >&2
@@ -90,100 +89,11 @@ if [ "$nats_server_version" != "$NATS_SERVER_PIN" ]; then
fi
echo "$TAG nats-server: $nats_server_version (matches go.mod)"
# --- Create chroot ---
CHROOT_DIR=$(mktemp -d)
# Guard: every destructive op below targets "$CHROOT_DIR/...". An empty or
# unexpected value would aim rm -rf at the host (e.g. /dev). Refuse anything that
# is not a freshly-created temp dir.
case "${CHROOT_DIR:?mktemp -d returned empty}" in
/tmp/*|/var/tmp/*|"${TMPDIR:-/nonexistent}"/*) ;;
*) echo "ERROR: refusing to use unexpected CHROOT_DIR: $CHROOT_DIR" >&2; exit 1 ;;
esac
# Outputs are written here first, beside $BUILD_DIR so publishing is a rename.
STAGE_DIR=$(mktemp -d "$BUILD_DIR/.stage.XXXXXX")
CONTAINER_TOOL=""
CONTAINER_CID=""
cleanup() {
echo "$TAG cleaning up chroot: $CHROOT_DIR"
rm -rf "$CHROOT_DIR"
rm -rf "${STAGE_DIR:?}"
if [ -n "$CONTAINER_CID" ] && [ -n "$CONTAINER_TOOL" ]; then
echo "$TAG cleaning up container: $CONTAINER_CID"
$CONTAINER_TOOL rm -f "$CONTAINER_CID" >/dev/null 2>&1 || true
fi
}
trap cleanup EXIT
microvm_init_dirs
# --- Populate rootfs ---
# Strategy 1: native apk (Alpine hosts, CI)
if command -v apk >/dev/null 2>&1; then
echo "$TAG rootfs: native apk"
mkdir -p \
"$CHROOT_DIR/etc/apk" \
"$CHROOT_DIR/lib/apk/db" \
"$CHROOT_DIR/var/cache/apk"
cat > "$CHROOT_DIR/etc/apk/repositories" <<EOF
${ALPINE_MIRROR}/v${ALPINE_VERSION}/main
${ALPINE_MIRROR}/v${ALPINE_VERSION}/community
EOF
apk add \
--root "$CHROOT_DIR" \
--arch x86_64 \
--no-cache \
--allow-untrusted \
--initdb \
$ALPINE_PACKAGES
microvm_make_rootfs
# Strategy 2: docker -> BuildKit local export.
# Do NOT use `docker export` here. On Docker's overlay2 driver it leaks the
# container's overlay mount (the mount survives `docker rm`), orphaning layers
# under /var/lib/docker that only a daemon restart reclaims; on a busy CI host
# this grows without bound. `buildx --output type=local` writes the image
# filesystem straight to a directory and releases every mount, so nothing leaks.
elif command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
echo "$TAG rootfs: docker buildx --output type=local (alpine:${ALPINE_VERSION})"
BUILD_CTX=$(mktemp -d)
cat > "$BUILD_CTX/Dockerfile" <<DOCKERFILE
FROM alpine:${ALPINE_VERSION}
RUN apk add --no-cache ${ALPINE_PACKAGES}
DOCKERFILE
docker buildx build \
--platform linux/amd64 \
--output "type=local,dest=${CHROOT_DIR}" \
"$BUILD_CTX"
rm -rf "$BUILD_CTX"
# Strategy 3: podman -> run + export. Podman's store does not exhibit the docker
# overlay2 export-mount leak, and podman has no buildx.
elif command -v podman >/dev/null 2>&1; then
echo "$TAG rootfs: podman export (alpine:${ALPINE_VERSION})"
CONTAINER_TOOL=podman
CONTAINER_CID=$(podman run -d \
"alpine:${ALPINE_VERSION}" \
sh -c "apk add --no-cache ${ALPINE_PACKAGES}")
exit_code=$(podman wait "$CONTAINER_CID")
if [ "$exit_code" != "0" ]; then
echo "ERROR: package installation failed in container (exit $exit_code)" >&2
exit 1
fi
podman export "$CONTAINER_CID" | tar -x -C "$CHROOT_DIR"
else
echo "ERROR: no rootfs build tool available." >&2
echo " Install one of: apk (Alpine), docker, podman" >&2
exit 1
fi
# --- /dev: empty mountpoint only ---
# tar extraction without root silently creates 0-byte regular files for device
# nodes. Drop them and leave an empty /dev mountpoint. The two static nodes the
# kernel needs (/dev/console to wire init's stdio, /dev/null) are written into
# the cpio archive under fakeroot at pack time — NOT created on the host. init
# mounts devtmpfs over /dev as its first action for everything else at runtime.
rm -rf "${CHROOT_DIR:?}/dev"
mkdir "$CHROOT_DIR/dev"
microvm_empty_dev
# --- Place init script ---
echo "$TAG installing init.sh as /init..."
@@ -227,30 +137,8 @@ mkdir -p \
"$CHROOT_DIR/dev" \
"$CHROOT_DIR/etc/ssl/certs"
# --- Locate kernel ---
KERNEL_IMG=$(find "$CHROOT_DIR/boot" -name "vmlinuz*" | sort | tail -1)
if [ -z "$KERNEL_IMG" ]; then
echo "ERROR: no vmlinuz found in $CHROOT_DIR/boot" >&2
exit 1
fi
echo "$TAG kernel image: $KERNEL_IMG"
KERNEL_VER=$(basename "$KERNEL_IMG" | sed 's/vmlinuz-//')
KERNEL_CONFIG="$CHROOT_DIR/boot/config-${KERNEL_VER}"
# --- Assert fw_cfg module ---
if ! find "$CHROOT_DIR/lib/modules" \
-name "qemu_fw_cfg.ko*" \
-o -name "fw_cfg_sysfs.ko*" \
| grep -q .; then
if ! grep -q "CONFIG_FW_CFG_SYSFS=y" "$KERNEL_CONFIG" 2>/dev/null; then
echo "ERROR: qemu_fw_cfg module missing from initramfs — fw_cfg reads will fail at boot" >&2
exit 1
fi
echo "$TAG fw_cfg: built-in (CONFIG_FW_CFG_SYSFS=y)"
else
echo "$TAG fw_cfg: module found in lib/modules"
fi
microvm_locate_kernel
# --- Assert ext4 userspace tools (data volume) ---
for fs_tool in mkfs.ext4 e2fsck; do
@@ -261,227 +149,10 @@ for fs_tool in mkfs.ext4 e2fsck; do
done
echo "$TAG e2fsprogs: mkfs.ext4 + e2fsck present"
# --- Strip kernel modules (Phase 2 keep-list approach) ---
# Only modules needed by a virtio-mmio microvm guest are kept:
# virtio*.ko* — virtio bus, net, blk, rng, console, and helpers
# *fw_cfg*.ko* — QEMU fw_cfg sysfs driver (delivers boot blobs)
# *failover*.ko* — net_failover + failover (virtio_net deps for live migration)
# $MICROVM_EXTRA_MODULES — ext4 by default, plus dependency closure
# All other loadable modules are removed. Drivers compiled into the kernel
# (CONFIG_VIRTIO_MMIO=y etc.) are unaffected — they live in vmlinuz, not here.
# module_path prints a module's kernel/ path from the stock modules.dep, by
# name or modules.alias; it fails when the module is not loadable.
module_path() {
local kdir="$1" name="${2//-/_}" path alias_target
path=$(awk -F: -v n="$name" '{ f = $1; sub(/.*\//, "", f); sub(/\.ko(\.gz|\.xz|\.zst)?$/, "", f);
gsub(/-/, "_", f); if (f == n) { print $1; exit } }' "$kdir/modules.dep")
if [ -z "$path" ] && [ -f "$kdir/modules.alias" ]; then
alias_target=$(awk -v n="$2" '$1 == "alias" && $2 == n { print $3; exit }' "$kdir/modules.alias")
[ -n "$alias_target" ] && [ "$alias_target" != "$2" ] && path=$(module_path "$kdir" "$alias_target")
fi
[ -n "$path" ] && printf '%s\n' "$path"
}
# module_builtin reports whether a module name is compiled into the kernel.
module_builtin() {
local kdir="$1" name="${2//-/_}"
[ -f "$kdir/modules.builtin" ] || return 1
awk -v n="$name" '{ f = $0; sub(/.*\//, "", f); sub(/\.ko$/, "", f); gsub(/-/, "_", f);
if (f == n) { found = 1; exit } } END { exit !found }' "$kdir/modules.builtin"
}
# image_kmod runs the image's own kmod (depmod, modprobe) through its musl
# loader, so module metadata matches the guest's modprobe without a host kmod.
image_kmod() {
"$CHROOT_DIR/lib/ld-musl-x86_64.so.1" --library-path "$CHROOT_DIR/lib:$CHROOT_DIR/usr/lib" \
--argv0 "$1" "$CHROOT_DIR/bin/kmod" "${@:2}"
}
echo "$TAG stripping kernel modules to virtio+fw_cfg+${MICROVM_EXTRA_MODULES} only..."
for kver_dir in "$CHROOT_DIR/lib/modules"/*/; do
kver="$(basename "$kver_dir")"
kernel_dir="$kver_dir/kernel"
[ -d "$kernel_dir" ] || continue
if [ ! -s "$kver_dir/modules.dep" ]; then
echo "ERROR: stock ${kver_dir}modules.dep missing — cannot resolve module dependencies" >&2
exit 1
fi
# Extra modules start the closure; the glob families are kept as found.
keep_list=$(mktemp)
: > "$keep_list"
for name in $MICROVM_EXTRA_MODULES; do
if ! path=$(module_path "$kver_dir" "$name"); then
if module_builtin "$kver_dir" "$name"; then continue; fi
echo "ERROR: module $name is neither loadable nor built into $kver" >&2
exit 1
fi
echo "$path" >> "$keep_list"
done
# Close over modules.dep hard dependencies and modules.softdep pre:/post:
# names until the set stops growing. A softdep must be loadable or built in.
while :; do
before=$(sort -u "$keep_list" | wc -l)
for path in $(sort -u "$keep_list"); do
awk -F': ' -v p="$path" '$1 == p { n = split($2, d, " "); for (i = 1; i <= n; i++) print d[i] }' \
"$kver_dir/modules.dep" >> "$keep_list"
mod=$(basename "$path"); mod="${mod%%.ko*}"; mod="${mod//-/_}"
[ -f "$kver_dir/modules.softdep" ] || continue
for soft in $(awk -v n="$mod" '{ m = $2; gsub(/-/, "_", m) }
$1 == "softdep" && m == n { for (i = 3; i <= NF; i++) if ($i != "pre:" && $i != "post:") print $i }' \
"$kver_dir/modules.softdep"); do
if soft_path=$(module_path "$kver_dir" "$soft"); then
echo "$soft_path" >> "$keep_list"
elif ! module_builtin "$kver_dir" "$soft"; then
echo "ERROR: softdep $soft of $mod is neither loadable nor built into $kver" >&2
exit 1
fi
done
done
after=$(sort -u "$keep_list" | wc -l)
[ "$before" -eq "$after" ] && break
done
extra_names=$(sort -u "$keep_list" | while read -r p; do m=$(basename "$p"); m="${m%%.ko*}"; echo "${m//-/_}"; done)
(cd "$kver_dir" && find kernel -name "virtio*.ko*" -o -name "*fw_cfg*.ko*" \
-o -name "*failover*.ko*") >> "$keep_list"
# Copy the keeper set out, preserving each kernel/ relative path.
tmp_keep=$(mktemp -d)
while read -r rel; do
rel="${rel#kernel/}"
mkdir -p "$tmp_keep/$(dirname "$rel")"
cp "$kernel_dir/$rel" "$tmp_keep/$rel"
done < <(sort -u "$keep_list")
rm -f "$keep_list"
# Replace kernel module tree with the keeper set.
rm -rf "$kernel_dir"
mkdir -p "$kernel_dir"
# Restore each kept file into the same relative path.
(cd "$tmp_keep" && find . -name "*.ko*" | while read -r f; do
dest_dir="$kernel_dir/$(dirname "${f#./}")"
mkdir -p "$dest_dir"
cp "$f" "$dest_dir/"
done)
rm -rf "$tmp_keep"
# Decompress kept modules to plain .ko. Alpine ships .ko.gz, but a host
# kmod that lacks gzip support (e.g. Debian trixie's kmod 34) silently
# produces an EMPTY modules.dep from compressed modules — the guest's
# modprobe then no-ops and qemu_fw_cfg never loads. Plain .ko sidesteps the
# host-kmod dependency entirely and the guest needs no decompressor either.
find "$kernel_dir" -name "*.ko.gz" -exec gunzip -f {} +
# Independent closure gate: each extra-closure module's own .modinfo depends=
# must name a kept module or a built-in, so a resolver bug fails here.
kept_names=$(find "$kernel_dir" -name "*.ko" -exec basename {} .ko \; | tr '-' '_' | sort -u)
while read -r ko; do
ko_name=$(basename "$ko" .ko); ko_name="${ko_name//-/_}"
grep -qx "$ko_name" <<< "$extra_names" || continue
deps=$(tr '\0' '\n' < "$ko" | grep -a -m1 '^depends=' | cut -d= -f2 | tr ',' ' ' || true)
for dep in $deps; do
dep="${dep//-/_}"
if ! grep -qx "$dep" <<< "$kept_names" && ! module_builtin "$kver_dir" "$dep"; then
echo "ERROR: $(basename "$ko") depends on $dep, which is neither kept nor built in" >&2
exit 1
fi
done
done < <(find "$kernel_dir" -name "*.ko")
for name in $MICROVM_EXTRA_MODULES; do
if ! grep -qx "${name//-/_}" <<< "$kept_names" && ! module_builtin "$kver_dir" "$name"; then
echo "ERROR: required module $name missing from the stripped module tree" >&2
exit 1
fi
done
echo "$TAG extra module closure: $(echo "$extra_names" | tr '\n' ' ')"
echo "$TAG modules kept: $(echo "$kept_names" | tr '\n' ' ')"
# Rebuild module metadata with the image's own kmod, the binary the guest's
# modprobe runs, so no host depmod is needed. Stock indexes still name .ko.gz
# files, so they are removed first and a failed rebuild cannot ship them.
for f in dep dep.bin alias alias.bin softdep weakdep symbols symbols.bin \
builtin.bin builtin.alias.bin devname; do
rm -f "$kver_dir/modules.$f"
done
if ! image_kmod depmod -b "$CHROOT_DIR" "$kver"; then
echo "ERROR: image depmod failed for $kver" >&2
exit 1
fi
if [ ! -s "$kver_dir/modules.dep" ] || [ ! -s "$kver_dir/modules.dep.bin" ]; then
echo "ERROR: ${kver_dir}modules.dep or modules.dep.bin missing or empty after depmod" >&2
exit 1
fi
# Resolution gate: the image's modprobe must resolve every required module
# to plain .ko files present in the stripped tree.
for name in $MICROVM_EXTRA_MODULES qemu_fw_cfg virtio_net; do
module_builtin "$kver_dir" "$name" && continue
if ! plan=$(image_kmod modprobe -d "$CHROOT_DIR" -S "$kver" --show-depends "$name"); then
echo "ERROR: image modprobe cannot resolve $name for $kver" >&2
exit 1
fi
while read -r verb path _; do
[ "$verb" = "insmod" ] || continue
case "$path" in
"$CHROOT_DIR/lib/modules/$kver/kernel/"*.ko) [ -f "$path" ] && continue ;;
esac
echo "ERROR: modprobe plan for $name names $path, not a kept plain .ko" >&2
exit 1
done <<< "$plan"
echo "$TAG modprobe $name: $(awk '{ n = split($2, a, "/"); printf "%s ", a[n] }' <<< "$plan")"
done
done
# --- Strip package-manager artifacts (not needed at runtime) ---
echo "$TAG stripping package manager artifacts..."
rm -rf \
"$CHROOT_DIR/lib/apk" \
"$CHROOT_DIR/var/cache/apk" \
"$CHROOT_DIR/etc/apk" \
"$CHROOT_DIR/usr/share/man" \
"$CHROOT_DIR/usr/share/doc" \
"$CHROOT_DIR/usr/share/apk" \
"$CHROOT_DIR/usr/include" \
"$CHROOT_DIR/usr/lib/pkgconfig"
# --- Strip debug symbols from binaries ---
# nats-server in /usr/local/bin is left as built (-s -w), so the shipped bytes
# are the ones whose version was checked above.
echo "$TAG stripping debug symbols from binaries..."
find "$CHROOT_DIR/usr/sbin" "$CHROOT_DIR/usr/bin" \
"$CHROOT_DIR/sbin" "$CHROOT_DIR/bin" \
-type f 2>/dev/null | while read -r bin; do
strip --strip-all "$bin" 2>/dev/null || true
done
# --- Copy vmlinuz out before stripping /boot from chroot ---
VMLINUZ_OUT="$STAGE_DIR/vmlinuz"
echo "$TAG copying kernel: $VMLINUZ_OUT"
cp "$KERNEL_IMG" "$VMLINUZ_OUT"
# Drop /boot from the chroot — vmlinuz, Alpine's stock initramfs-virt, System.map
# and kernel config all live here (~25 MiB). None are needed at runtime: the
# guest already has the kernel loaded by QEMU's -kernel, and Alpine's initramfs
# is unused because we replace it with our own /init. Leaving /boot in the cpio
# nearly doubles uncompressed initramfs size and forces a 512 MiB guest just to
# survive decompression.
rm -rf "${CHROOT_DIR:?}/boot"
# --- Build initramfs ---
INITRAMFS_OUT="$STAGE_DIR/initramfs.cpio.gz"
echo "$TAG building initramfs: $INITRAMFS_OUT"
# Create the static device nodes and pack the archive inside a single fakeroot
# session: mknod/cpio see faked device entries and write real char-device
# records into the cpio, while the host filesystem never gets an actual node.
fakeroot sh -c '
cd "$1" || exit 1
mknod -m 600 dev/console c 5 1
mknod -m 666 dev/null c 1 3
find . | cpio --quiet -o -H newc | gzip -9 > "$2"
' _ "$CHROOT_DIR" "$INITRAMFS_OUT"
microvm_strip_modules
microvm_strip_rootfs
microvm_stage_kernel
microvm_pack_initramfs
# --- Gate the staged pair, then publish it ---
# Nothing reaches $BUILD_DIR until every gate passes, so a failed build cannot
+391
View File
@@ -0,0 +1,391 @@
#!/bin/bash
# microvm-image.sh — shared steps for the microVM image builders, sourced by
# build-sqs-store-microvm-image.sh and build-lambda-runtime-microvm-image.sh.
#
# The caller sets before use:
# TAG log prefix
# BUILD_DIR output directory; STAGE_DIR is created beside it
# ALPINE_VERSION, ALPINE_MIRROR, ALPINE_PACKAGES
# MICROVM_EXTRA_MODULES modules kept by name, with their dependency closure
# MICROVM_GATE_MODULES modules the image modprobe must resolve, beyond the extras
# MICROVM_EXTRA_KEEP_GLOBS bash array of module file globs kept on top of virtio*/*fw_cfg*
# Functions set CHROOT_DIR, STAGE_DIR, KERNEL_IMG and KERNEL_VER for the caller.
microvm_check_tools() {
# --- Verify non-negotiable tools ---
# fakeroot is mandatory: device nodes are written into the cpio archive inside a
# faked-root environment so no real device node is ever created on the host
# filesystem (which previously required sudo mknod and risked clobbering host
# /dev/null on cleanup).
for tool in cpio gzip find fakeroot; do
if ! command -v "$tool" >/dev/null 2>&1; then
echo "ERROR: required tool not found: $tool" >&2
exit 1
fi
done
}
microvm_init_dirs() {
# --- Create chroot ---
CHROOT_DIR=$(mktemp -d)
# Guard: every destructive op below targets "$CHROOT_DIR/...". An empty or
# unexpected value would aim rm -rf at the host (e.g. /dev). Refuse anything that
# is not a freshly-created temp dir.
case "${CHROOT_DIR:?mktemp -d returned empty}" in
/tmp/*|/var/tmp/*|"${TMPDIR:-/nonexistent}"/*) ;;
*) echo "ERROR: refusing to use unexpected CHROOT_DIR: $CHROOT_DIR" >&2; exit 1 ;;
esac
# Outputs are written here first, beside $BUILD_DIR so publishing is a rename.
STAGE_DIR=$(mktemp -d "$BUILD_DIR/.stage.XXXXXX")
CONTAINER_TOOL=""
CONTAINER_CID=""
trap microvm_cleanup EXIT
}
microvm_cleanup() {
echo "$TAG cleaning up chroot: $CHROOT_DIR"
rm -rf "$CHROOT_DIR"
rm -rf "${STAGE_DIR:?}"
if [ -n "$CONTAINER_CID" ] && [ -n "$CONTAINER_TOOL" ]; then
echo "$TAG cleaning up container: $CONTAINER_CID"
$CONTAINER_TOOL rm -f "$CONTAINER_CID" >/dev/null 2>&1 || true
fi
}
# microvm_make_rootfs populates $CHROOT_DIR from ALPINE_PACKAGES.
microvm_make_rootfs() {
# --- Populate rootfs ---
# Strategy 1: native apk (Alpine hosts, CI)
if command -v apk >/dev/null 2>&1; then
echo "$TAG rootfs: native apk"
mkdir -p \
"$CHROOT_DIR/etc/apk" \
"$CHROOT_DIR/lib/apk/db" \
"$CHROOT_DIR/var/cache/apk"
cat > "$CHROOT_DIR/etc/apk/repositories" <<EOF
${ALPINE_MIRROR}/v${ALPINE_VERSION}/main
${ALPINE_MIRROR}/v${ALPINE_VERSION}/community
EOF
apk add \
--root "$CHROOT_DIR" \
--arch x86_64 \
--no-cache \
--allow-untrusted \
--initdb \
$ALPINE_PACKAGES
# Strategy 2: docker -> BuildKit local export.
# Do NOT use `docker export` here. On Docker's overlay2 driver it leaks the
# container's overlay mount (the mount survives `docker rm`), orphaning layers
# under /var/lib/docker that only a daemon restart reclaims; on a busy CI host
# this grows without bound. `buildx --output type=local` writes the image
# filesystem straight to a directory and releases every mount, so nothing leaks.
elif command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
echo "$TAG rootfs: docker buildx --output type=local (alpine:${ALPINE_VERSION})"
BUILD_CTX=$(mktemp -d)
cat > "$BUILD_CTX/Dockerfile" <<DOCKERFILE
FROM alpine:${ALPINE_VERSION}
RUN apk add --no-cache ${ALPINE_PACKAGES}
DOCKERFILE
docker buildx build \
--platform linux/amd64 \
--output "type=local,dest=${CHROOT_DIR}" \
"$BUILD_CTX"
rm -rf "$BUILD_CTX"
# Strategy 3: podman -> run + export. Podman's store does not exhibit the docker
# overlay2 export-mount leak, and podman has no buildx.
elif command -v podman >/dev/null 2>&1; then
echo "$TAG rootfs: podman export (alpine:${ALPINE_VERSION})"
CONTAINER_TOOL=podman
CONTAINER_CID=$(podman run -d \
"alpine:${ALPINE_VERSION}" \
sh -c "apk add --no-cache ${ALPINE_PACKAGES}")
exit_code=$(podman wait "$CONTAINER_CID")
if [ "$exit_code" != "0" ]; then
echo "ERROR: package installation failed in container (exit $exit_code)" >&2
exit 1
fi
podman export "$CONTAINER_CID" | tar -x -C "$CHROOT_DIR"
else
echo "ERROR: no rootfs build tool available." >&2
echo " Install one of: apk (Alpine), docker, podman" >&2
exit 1
fi
}
microvm_empty_dev() {
# --- /dev: empty mountpoint only ---
# tar extraction without root silently creates 0-byte regular files for device
# nodes. Drop them and leave an empty /dev mountpoint. The two static nodes the
# kernel needs (/dev/console to wire init's stdio, /dev/null) are written into
# the cpio archive under fakeroot at pack time — NOT created on the host. init
# mounts devtmpfs over /dev as its first action for everything else at runtime.
rm -rf "${CHROOT_DIR:?}/dev"
mkdir "$CHROOT_DIR/dev"
}
# microvm_locate_kernel finds the kernel and asserts fw_cfg is loadable or built in.
microvm_locate_kernel() {
# --- Locate kernel ---
KERNEL_IMG=$(find "$CHROOT_DIR/boot" -name "vmlinuz*" | sort | tail -1)
if [ -z "$KERNEL_IMG" ]; then
echo "ERROR: no vmlinuz found in $CHROOT_DIR/boot" >&2
exit 1
fi
echo "$TAG kernel image: $KERNEL_IMG"
KERNEL_VER=$(basename "$KERNEL_IMG" | sed 's/vmlinuz-//')
KERNEL_CONFIG="$CHROOT_DIR/boot/config-${KERNEL_VER}"
# --- Assert fw_cfg module ---
if ! find "$CHROOT_DIR/lib/modules" \
-name "qemu_fw_cfg.ko*" \
-o -name "fw_cfg_sysfs.ko*" \
| grep -q .; then
if ! grep -q "CONFIG_FW_CFG_SYSFS=y" "$KERNEL_CONFIG" 2>/dev/null; then
echo "ERROR: qemu_fw_cfg module missing from initramfs — fw_cfg reads will fail at boot" >&2
exit 1
fi
echo "$TAG fw_cfg: built-in (CONFIG_FW_CFG_SYSFS=y)"
else
echo "$TAG fw_cfg: module found in lib/modules"
fi
}
# --- Strip kernel modules (Phase 2 keep-list approach) ---
# Only modules needed by a virtio-mmio microvm guest are kept:
# virtio*.ko* — virtio bus, net, blk, rng, console, and helpers
# *fw_cfg*.ko* — QEMU fw_cfg sysfs driver (delivers boot blobs)
# $MICROVM_EXTRA_KEEP_GLOBS — caller-named module file globs
# $MICROVM_EXTRA_MODULES — caller-named modules, plus dependency closure
# All other loadable modules are removed. Drivers compiled into the kernel
# (CONFIG_VIRTIO_MMIO=y etc.) are unaffected — they live in vmlinuz, not here.
# module_path prints a module's kernel/ path from the stock modules.dep, by
# name or modules.alias; it fails when the module is not loadable.
module_path() {
local kdir="$1" name="${2//-/_}" path alias_target
path=$(awk -F: -v n="$name" '{ f = $1; sub(/.*\//, "", f); sub(/\.ko(\.gz|\.xz|\.zst)?$/, "", f);
gsub(/-/, "_", f); if (f == n) { print $1; exit } }' "$kdir/modules.dep")
if [ -z "$path" ] && [ -f "$kdir/modules.alias" ]; then
alias_target=$(awk -v n="$2" '$1 == "alias" && $2 == n { print $3; exit }' "$kdir/modules.alias")
[ -n "$alias_target" ] && [ "$alias_target" != "$2" ] && path=$(module_path "$kdir" "$alias_target")
fi
[ -n "$path" ] && printf '%s\n' "$path"
}
# module_builtin reports whether a module name is compiled into the kernel.
module_builtin() {
local kdir="$1" name="${2//-/_}"
[ -f "$kdir/modules.builtin" ] || return 1
awk -v n="$name" '{ f = $0; sub(/.*\//, "", f); sub(/\.ko$/, "", f); gsub(/-/, "_", f);
if (f == n) { found = 1; exit } } END { exit !found }' "$kdir/modules.builtin"
}
# image_kmod runs the image's own kmod (depmod, modprobe) through its musl
# loader, so module metadata matches the guest's modprobe without a host kmod.
image_kmod() {
"$CHROOT_DIR/lib/ld-musl-x86_64.so.1" --library-path "$CHROOT_DIR/lib:$CHROOT_DIR/usr/lib" \
--argv0 "$1" "$CHROOT_DIR/bin/kmod" "${@:2}"
}
microvm_strip_modules() {
echo "$TAG stripping kernel modules to virtio+fw_cfg+${MICROVM_EXTRA_MODULES} only..."
for kver_dir in "$CHROOT_DIR/lib/modules"/*/; do
kver="$(basename "$kver_dir")"
kernel_dir="$kver_dir/kernel"
[ -d "$kernel_dir" ] || continue
if [ ! -s "$kver_dir/modules.dep" ]; then
echo "ERROR: stock ${kver_dir}modules.dep missing — cannot resolve module dependencies" >&2
exit 1
fi
# Extra modules start the closure; the glob families are kept as found.
keep_list=$(mktemp)
: > "$keep_list"
for name in $MICROVM_EXTRA_MODULES; do
if ! path=$(module_path "$kver_dir" "$name"); then
if module_builtin "$kver_dir" "$name"; then continue; fi
echo "ERROR: module $name is neither loadable nor built into $kver" >&2
exit 1
fi
echo "$path" >> "$keep_list"
done
# Close over modules.dep hard dependencies and modules.softdep pre:/post:
# names until the set stops growing. A softdep must be loadable or built in.
while :; do
before=$(sort -u "$keep_list" | wc -l)
for path in $(sort -u "$keep_list"); do
awk -F': ' -v p="$path" '$1 == p { n = split($2, d, " "); for (i = 1; i <= n; i++) print d[i] }' \
"$kver_dir/modules.dep" >> "$keep_list"
mod=$(basename "$path"); mod="${mod%%.ko*}"; mod="${mod//-/_}"
[ -f "$kver_dir/modules.softdep" ] || continue
for soft in $(awk -v n="$mod" '{ m = $2; gsub(/-/, "_", m) }
$1 == "softdep" && m == n { for (i = 3; i <= NF; i++) if ($i != "pre:" && $i != "post:") print $i }' \
"$kver_dir/modules.softdep"); do
if soft_path=$(module_path "$kver_dir" "$soft"); then
echo "$soft_path" >> "$keep_list"
elif ! module_builtin "$kver_dir" "$soft"; then
echo "ERROR: softdep $soft of $mod is neither loadable nor built into $kver" >&2
exit 1
fi
done
done
after=$(sort -u "$keep_list" | wc -l)
[ "$before" -eq "$after" ] && break
done
extra_names=$(sort -u "$keep_list" | while read -r p; do m=$(basename "$p"); m="${m%%.ko*}"; echo "${m//-/_}"; done)
find_args=(-name "virtio*.ko*" -o -name "*fw_cfg*.ko*")
for glob in ${MICROVM_EXTRA_KEEP_GLOBS[@]+"${MICROVM_EXTRA_KEEP_GLOBS[@]}"}; do
find_args+=(-o -name "$glob")
done
(cd "$kver_dir" && find kernel "${find_args[@]}") >> "$keep_list"
# Copy the keeper set out, preserving each kernel/ relative path.
tmp_keep=$(mktemp -d)
while read -r rel; do
rel="${rel#kernel/}"
mkdir -p "$tmp_keep/$(dirname "$rel")"
cp "$kernel_dir/$rel" "$tmp_keep/$rel"
done < <(sort -u "$keep_list")
rm -f "$keep_list"
# Replace kernel module tree with the keeper set.
rm -rf "$kernel_dir"
mkdir -p "$kernel_dir"
# Restore each kept file into the same relative path.
(cd "$tmp_keep" && find . -name "*.ko*" | while read -r f; do
dest_dir="$kernel_dir/$(dirname "${f#./}")"
mkdir -p "$dest_dir"
cp "$f" "$dest_dir/"
done)
rm -rf "$tmp_keep"
# Decompress kept modules to plain .ko. Alpine ships .ko.gz, but a host
# kmod that lacks gzip support (e.g. Debian trixie's kmod 34) silently
# produces an EMPTY modules.dep from compressed modules — the guest's
# modprobe then no-ops and qemu_fw_cfg never loads. Plain .ko sidesteps the
# host-kmod dependency entirely and the guest needs no decompressor either.
find "$kernel_dir" -name "*.ko.gz" -exec gunzip -f {} +
# Independent closure gate: each extra-closure module's own .modinfo depends=
# must name a kept module or a built-in, so a resolver bug fails here.
kept_names=$(find "$kernel_dir" -name "*.ko" -exec basename {} .ko \; | tr '-' '_' | sort -u)
while read -r ko; do
ko_name=$(basename "$ko" .ko); ko_name="${ko_name//-/_}"
grep -qx "$ko_name" <<< "$extra_names" || continue
deps=$(tr '\0' '\n' < "$ko" | grep -a -m1 '^depends=' | cut -d= -f2 | tr ',' ' ' || true)
for dep in $deps; do
dep="${dep//-/_}"
if ! grep -qx "$dep" <<< "$kept_names" && ! module_builtin "$kver_dir" "$dep"; then
echo "ERROR: $(basename "$ko") depends on $dep, which is neither kept nor built in" >&2
exit 1
fi
done
done < <(find "$kernel_dir" -name "*.ko")
for name in $MICROVM_EXTRA_MODULES; do
if ! grep -qx "${name//-/_}" <<< "$kept_names" && ! module_builtin "$kver_dir" "$name"; then
echo "ERROR: required module $name missing from the stripped module tree" >&2
exit 1
fi
done
echo "$TAG extra module closure: $(echo "$extra_names" | tr '\n' ' ')"
echo "$TAG modules kept: $(echo "$kept_names" | tr '\n' ' ')"
# Rebuild module metadata with the image's own kmod, the binary the guest's
# modprobe runs, so no host depmod is needed. Stock indexes still name .ko.gz
# files, so they are removed first and a failed rebuild cannot ship them.
for f in dep dep.bin alias alias.bin softdep weakdep symbols symbols.bin \
builtin.bin builtin.alias.bin devname; do
rm -f "$kver_dir/modules.$f"
done
if ! image_kmod depmod -b "$CHROOT_DIR" "$kver"; then
echo "ERROR: image depmod failed for $kver" >&2
exit 1
fi
if [ ! -s "$kver_dir/modules.dep" ] || [ ! -s "$kver_dir/modules.dep.bin" ]; then
echo "ERROR: ${kver_dir}modules.dep or modules.dep.bin missing or empty after depmod" >&2
exit 1
fi
# Resolution gate: the image's modprobe must resolve every required module
# to plain .ko files present in the stripped tree.
for name in $MICROVM_EXTRA_MODULES $MICROVM_GATE_MODULES; do
module_builtin "$kver_dir" "$name" && continue
if ! plan=$(image_kmod modprobe -d "$CHROOT_DIR" -S "$kver" --show-depends "$name"); then
echo "ERROR: image modprobe cannot resolve $name for $kver" >&2
exit 1
fi
while read -r verb path _; do
[ "$verb" = "insmod" ] || continue
case "$path" in
"$CHROOT_DIR/lib/modules/$kver/kernel/"*.ko) [ -f "$path" ] && continue ;;
esac
echo "ERROR: modprobe plan for $name names $path, not a kept plain .ko" >&2
exit 1
done <<< "$plan"
echo "$TAG modprobe $name: $(awk '{ n = split($2, a, "/"); printf "%s ", a[n] }' <<< "$plan")"
done
done
}
# microvm_strip_rootfs drops package-manager artifacts and debug symbols.
microvm_strip_rootfs() {
# --- Strip package-manager artifacts (not needed at runtime) ---
echo "$TAG stripping package manager artifacts..."
rm -rf \
"$CHROOT_DIR/lib/apk" \
"$CHROOT_DIR/var/cache/apk" \
"$CHROOT_DIR/etc/apk" \
"$CHROOT_DIR/usr/share/man" \
"$CHROOT_DIR/usr/share/doc" \
"$CHROOT_DIR/usr/share/apk" \
"$CHROOT_DIR/usr/include" \
"$CHROOT_DIR/usr/lib/pkgconfig"
# --- Strip debug symbols from binaries ---
echo "$TAG stripping debug symbols from binaries..."
find "$CHROOT_DIR/usr/sbin" "$CHROOT_DIR/usr/bin" \
"$CHROOT_DIR/sbin" "$CHROOT_DIR/bin" \
-type f 2>/dev/null | while read -r bin; do
strip --strip-all "$bin" 2>/dev/null || true
done
}
# microvm_stage_kernel copies vmlinuz to $STAGE_DIR, then drops /boot from the chroot.
microvm_stage_kernel() {
# --- Copy vmlinuz out before stripping /boot from chroot ---
VMLINUZ_OUT="$STAGE_DIR/vmlinuz"
echo "$TAG copying kernel: $VMLINUZ_OUT"
cp "$KERNEL_IMG" "$VMLINUZ_OUT"
# Drop /boot from the chroot — vmlinuz, Alpine's stock initramfs-virt, System.map
# and kernel config all live here (~25 MiB). None are needed at runtime: the
# guest already has the kernel loaded by QEMU's -kernel, and Alpine's initramfs
# is unused because we replace it with our own /init. Leaving /boot in the cpio
# nearly doubles uncompressed initramfs size and forces a 512 MiB guest just to
# survive decompression.
rm -rf "${CHROOT_DIR:?}/boot"
}
microvm_pack_initramfs() {
# --- Build initramfs ---
INITRAMFS_OUT="$STAGE_DIR/initramfs.cpio.gz"
echo "$TAG building initramfs: $INITRAMFS_OUT"
# Create the static device nodes and pack the archive inside a single fakeroot
# session: mknod/cpio see faked device entries and write real char-device
# records into the cpio, while the host filesystem never gets an actual node.
fakeroot sh -c '
cd "$1" || exit 1
mknod -m 600 dev/console c 5 1
mknod -m 666 dev/null c 1 3
find . | cpio --quiet -o -H newc | gzip -9 > "$2"
' _ "$CHROOT_DIR" "$INITRAMFS_OUT"
}
+4 -2
View File
@@ -732,7 +732,8 @@ table inet spinifex_filter {
# inventory and running instances to anyone who asks. 8660 is
# predastore's unauthenticated /healthz and /readyz, which name the
# peers a gate cannot reach, so it belongs here for the same reason.
ip saddr $spinifex_peers tcp dport { 4222, 4248, 4432, 5300, 6641, 6642, 6643, 6644, 8660 } accept
# 5001 is the admin network test, listening only while one runs.
ip saddr $spinifex_peers tcp dport { 4222, 4248, 4432, 5001, 5300, 6641, 6642, 6643, 6644, 8660 } accept
ip saddr $spinifex_peers udp dport { 5300, 6660, 7660 } accept
# Encap plane, peer-scoped: Geneve, IKE, NAT-T and ESP. Geneve is a
@@ -1309,6 +1310,7 @@ qemu-utils gdisk ovmf qemu-efi-aarch64 less
libvirt-daemon-system libvirt-clients
pciutils
jq curl iproute2 iputils-arping ethtool netcat-openbsd wget unzip xz-utils file
dmidecode iperf
ovn-central ovn-host openvswitch-switch openvswitch-ipsec strongswan-charon dhcpcd-base
chrony nftables"
@@ -1318,7 +1320,7 @@ chrony nftables"
OL_RUNTIME_PACKAGES="nbdkit nbdkit-basic-filters
qemu-kvm qemu-img edk2-ovmf seabios-bin less
pciutils
jq curl iproute iputils ethtool nmap-ncat wget unzip xz file
jq curl iproute iputils ethtool nmap-ncat wget unzip xz file dmidecode
ovn25.03-central ovn25.03-host openvswitch3.5 openvswitch3.5-ipsec libreswan dhcpcd
chrony nftables iptables-nft systemd-resolved"
@@ -329,6 +329,18 @@ restart_spinifex() {
die "$NODE_NAME never logged its Vultr allocator; see journalctl -u spinifex-daemon on $IP"
}
# public_default_subnets turns on auto-assign for the default subnets formation
# created before the Vultr pool existed, as AWS default subnets have it. Later
# accounts are seeded with it by the daemon, which now sees the pool.
public_default_subnets() {
log "auto-assigning public addresses in the default subnets"
on 'export AWS_PROFILE=spinifex
for s in $(aws ec2 describe-subnets --filters Name=default-for-az,Values=true \
--query "Subnets[?MapPublicIpOnLaunch==\`false\`].SubnetId" --output text); do
aws ec2 modify-subnet-attribute --subnet-id "$s" --map-public-ip-on-launch || exit 1
done' || die "could not turn on public addresses in the default subnets on $IP"
}
import_image() {
log "importing $IMAGE"
on "spx admin images import --name $IMAGE --config /etc/spinifex/spinifex.toml >/root/image-import.log 2>&1" ||
@@ -368,6 +380,7 @@ cmd_up() {
for_nodes pool configure_pool
for_nodes restart restart_spinifex
IP="${IPS[0]}"
done_step public || { public_default_subnets; mark_step public; }
if [ -n "$IMAGE" ]; then done_step image || { import_image; mark_step image; }; fi
write_profile
log "ready: https://$IP:9999 (profile $PROFILE)"
+91
View File
@@ -0,0 +1,91 @@
// Package agent runs the guest loop: take a request from the host link, hand
// it to the function runtime, and report the outcome back.
package agent
import (
"context"
"errors"
"fmt"
"time"
"github.com/mulgadc/spinifex/spinifex/agents/lambda/hostlink"
"github.com/mulgadc/spinifex/spinifex/agents/lambda/runtimeapi"
)
const (
errTypeTimedOut = "Sandbox.Timedout"
errTypeUnknown = "Runtime.Unknown"
)
// ErrInvocationTimedOut stops the agent after it reports a timed-out
// invocation, because the runtime may still be running it.
var ErrInvocationTimedOut = errors.New("invocation timed out; environment must not serve another request")
// Run serves requests from link until the host asks for shutdown (nil), the
// runtime reports an init error, an invocation times out, ctx ends, or the
// link fails. GrantID and AttemptID are echoed to the host unchanged.
func Run(ctx context.Context, link hostlink.Link, srv *runtimeapi.Server) error {
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil)
go func() {
select {
case <-srv.InitFailed():
ie, _ := srv.InitError()
cancel(fmt.Errorf("runtime init error %q: %s", ie.Type, ie.Body))
case <-ctx.Done():
}
}()
for {
req, err := link.Next(ctx)
if errors.Is(err, hostlink.ErrShutdown) {
return nil
}
if err != nil {
return cause(ctx, err)
}
res, err := srv.Invoke(ctx, runtimeapi.Invocation{
RequestID: req.RequestID,
FunctionARN: req.FunctionARN,
Deadline: time.UnixMilli(req.DeadlineMs),
TraceID: req.TraceID,
Payload: req.Payload,
})
timedOut := errors.Is(err, runtimeapi.ErrDeadlineExceeded)
if err != nil {
if ctx.Err() != nil {
return cause(ctx, err)
}
res = failure(err)
}
resp := hostlink.Response{
GrantID: req.GrantID,
AttemptID: req.AttemptID,
RequestID: req.RequestID,
Payload: res.Payload,
FunctionError: res.FunctionError,
}
if err := link.Complete(ctx, resp); err != nil {
return cause(ctx, err)
}
if timedOut {
return ErrInvocationTimedOut
}
}
}
func cause(ctx context.Context, err error) error {
if ctx.Err() != nil {
return context.Cause(ctx)
}
return err
}
func failure(err error) runtimeapi.Result {
errType := errTypeUnknown
if errors.Is(err, runtimeapi.ErrDeadlineExceeded) {
errType = errTypeTimedOut
}
return runtimeapi.Result{Payload: runtimeapi.ErrorBody(err.Error(), errType), FunctionError: errType}
}
+142
View File
@@ -0,0 +1,142 @@
package agent
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/mulgadc/spinifex/spinifex/agents/lambda/hostlink"
"github.com/mulgadc/spinifex/spinifex/agents/lambda/runtimeapi"
)
const api = "/2018-06-01/runtime/"
// fakeLink feeds scripted requests and records completions.
type fakeLink struct {
reqs []hostlink.Request
got chan hostlink.Response
}
var _ hostlink.Link = (*fakeLink)(nil)
func (l *fakeLink) Next(ctx context.Context) (hostlink.Request, error) {
if len(l.reqs) == 0 {
return hostlink.Request{}, hostlink.ErrShutdown
}
r := l.reqs[0]
l.reqs = l.reqs[1:]
return r, nil
}
func (l *fakeLink) Complete(ctx context.Context, r hostlink.Response) error {
l.got <- r
return nil
}
// runtime polls next and answers using reply.
func runtime(t *testing.T, base string, reply func(id string, body []byte) (path string, out string)) {
t.Helper()
go func() {
for {
resp, err := http.Get(base + api + "invocation/next")
if err != nil {
return
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
id := resp.Header.Get("Lambda-Runtime-Aws-Request-Id")
path, out := reply(id, body)
r, err := http.Post(base+api+"invocation/"+id+path, "application/json", strings.NewReader(out))
if err != nil {
return
}
r.Body.Close()
}
}()
}
func deadline(d time.Duration) int64 { return time.Now().Add(d).UnixMilli() }
func TestRunServesRequestsAndEchoesIDs(t *testing.T) {
srv := runtimeapi.New()
ts := httptest.NewServer(srv.Handler())
defer ts.Close()
runtime(t, ts.URL, func(id string, body []byte) (string, string) {
if string(body) == "bad" {
return "/error", `{"errorMessage":"no"}`
}
return "/response", "echo:" + string(body)
})
link := &fakeLink{
got: make(chan hostlink.Response, 4),
reqs: []hostlink.Request{
{GrantID: "g1", AttemptID: "a1", RequestID: "r1", FunctionARN: "arn", DeadlineMs: deadline(2 * time.Second), Payload: []byte("one")},
{GrantID: "g2", AttemptID: "a2", RequestID: "r2", FunctionARN: "arn", DeadlineMs: deadline(2 * time.Second), Payload: []byte("bad")},
},
}
require.NoError(t, Run(context.Background(), link, srv))
r1, r2 := <-link.got, <-link.got
assert.Equal(t, hostlink.Response{GrantID: "g1", AttemptID: "a1", RequestID: "r1", Payload: []byte("echo:one")}, r1)
assert.Equal(t, "g2", r2.GrantID)
assert.Equal(t, "a2", r2.AttemptID)
assert.Equal(t, "Unhandled", r2.FunctionError)
}
func TestRunReportsTimeoutAndStops(t *testing.T) {
srv := runtimeapi.New() // no runtime polling: the invocation expires
link := &fakeLink{
got: make(chan hostlink.Response, 2),
reqs: []hostlink.Request{
{GrantID: "g", AttemptID: "a", RequestID: "r", DeadlineMs: deadline(30 * time.Millisecond)},
{GrantID: "g2", AttemptID: "a2", RequestID: "r2", DeadlineMs: deadline(2 * time.Second)},
},
}
require.ErrorIs(t, Run(context.Background(), link, srv), ErrInvocationTimedOut)
r := <-link.got
assert.Equal(t, "Sandbox.Timedout", r.FunctionError)
assert.Equal(t, "g", r.GrantID)
assert.Len(t, link.reqs, 1, "the next request must not be taken")
assert.Empty(t, link.got, "nothing else is reported")
}
// blockLink blocks in Next until ctx ends.
type blockLink struct{ fakeLink }
func (blockLink) Next(ctx context.Context) (hostlink.Request, error) {
<-ctx.Done()
return hostlink.Request{}, ctx.Err()
}
func TestRunStopsOnInitError(t *testing.T) {
srv := runtimeapi.New()
ts := httptest.NewServer(srv.Handler())
defer ts.Close()
r, err := http.Post(ts.URL+api+"init/error", "application/json", strings.NewReader(`{"errorMessage":"x"}`))
require.NoError(t, err)
r.Body.Close()
err = Run(context.Background(), &blockLink{}, srv)
require.Error(t, err)
assert.Contains(t, err.Error(), "init error")
}
type errLink struct{ fakeLink }
func (errLink) Next(context.Context) (hostlink.Request, error) {
return hostlink.Request{}, errors.New("link down")
}
func TestRunReturnsLinkError(t *testing.T) {
err := Run(context.Background(), &errLink{}, runtimeapi.New())
require.EqualError(t, err, "link down")
}
+54
View File
@@ -0,0 +1,54 @@
//go:build linux
package agent
import (
"context"
"fmt"
"io"
"os/exec"
goruntime "runtime"
"syscall"
"time"
"golang.org/x/sys/unix"
)
// sandboxID is the uid and gid the function's bootstrap runs as.
const sandboxID = 993
// StartBootstrap starts the function's bootstrap at path as the sandbox uid and
// gid with no supplementary groups, with no_new_privs, and with exactly env.
// The caller waits on the returned command.
func StartBootstrap(ctx context.Context, path string, env []string, stdout, stderr io.Writer) (*exec.Cmd, error) {
cred := &syscall.Credential{Uid: sandboxID, Gid: sandboxID, Groups: []uint32{}}
return startBootstrap(ctx, path, env, stdout, stderr, cred)
}
func startBootstrap(ctx context.Context, path string, env []string, stdout, stderr io.Writer, cred *syscall.Credential) (*exec.Cmd, error) {
cmd := exec.CommandContext(ctx, path)
// A nil Env inherits the agent's environment; the bootstrap gets only env.
cmd.Env = append([]string{}, env...)
cmd.Stdout, cmd.Stderr = stdout, stderr
if cred != nil {
cmd.SysProcAttr = &syscall.SysProcAttr{Credential: cred}
}
cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }
cmd.WaitDelay = 5 * time.Second
started := make(chan error, 1)
go func() {
// no_new_privs is per thread and the child inherits it from this one. The
// thread is never unlocked, so Go ends it when this goroutine returns.
goruntime.LockOSThread()
if err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {
started <- fmt.Errorf("set no_new_privs: %w", err)
return
}
started <- cmd.Start()
}()
if err := <-started; err != nil {
return nil, err
}
return cmd, nil
}
@@ -0,0 +1,171 @@
//go:build linux
package agent
import (
"bytes"
"context"
"io"
"os"
"os/exec"
"path/filepath"
goruntime "runtime"
"strings"
"syscall"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// statusProbe writes an executable that prints its own credential lines.
func statusProbe(t *testing.T) string {
t.Helper()
// The sandbox uid must be able to reach the probe through the test's dirs.
dir := t.TempDir()
require.NoError(t, os.Chmod(filepath.Dir(dir), 0o755))
require.NoError(t, os.Chmod(dir, 0o755))
path := filepath.Join(dir, "bootstrap")
script := "#!/bin/sh\ngrep -E '^(Uid|Gid|Groups|NoNewPrivs):' /proc/self/status\n"
require.NoError(t, os.WriteFile(path, []byte(script), 0o755))
return path
}
func statusLines(t *testing.T, out []byte) map[string]string {
t.Helper()
lines := map[string]string{}
for l := range strings.SplitSeq(strings.TrimSpace(string(out)), "\n") {
k, v, ok := strings.Cut(l, ":")
require.True(t, ok, "status line %q", l)
lines[k] = strings.Join(strings.Fields(v), " ")
}
return lines
}
// run starts a bootstrap with the given credential and returns its stdout.
func run(t *testing.T, path string, env []string, sandbox bool) []byte {
t.Helper()
var out bytes.Buffer
start := startBootstrap
if sandbox {
start = func(ctx context.Context, p string, e []string, o, s io.Writer, _ *syscall.Credential) (*exec.Cmd, error) {
return StartBootstrap(ctx, p, e, o, s)
}
}
cmd, err := start(context.Background(), path, env, &out, os.Stderr, nil)
require.NoError(t, err)
require.NoError(t, cmd.Wait())
return out.Bytes()
}
// threadNoNewPrivs reads no_new_privs for the calling OS thread.
func threadNoNewPrivs(t *testing.T) string {
t.Helper()
b, err := os.ReadFile("/proc/thread-self/status")
require.NoError(t, err)
return statusLines(t, grepLines(b, "NoNewPrivs:"))["NoNewPrivs"]
}
func grepLines(b []byte, prefix string) []byte {
var keep []string
for l := range strings.SplitSeq(string(b), "\n") {
if strings.HasPrefix(l, prefix) {
keep = append(keep, l)
}
}
return []byte(strings.Join(keep, "\n"))
}
func TestStartBootstrapSetsNoNewPrivsWithoutChangingTheCaller(t *testing.T) {
goruntime.LockOSThread()
defer goruntime.UnlockOSThread()
if threadNoNewPrivs(t) != "0" {
t.Skip("test thread already has no_new_privs; the child would inherit it")
}
out := run(t, statusProbe(t), nil, false)
assert.Equal(t, "1", statusLines(t, out)["NoNewPrivs"])
assert.Equal(t, "0", threadNoNewPrivs(t), "the calling thread must keep no_new_privs unset")
}
func TestStartBootstrapDropsToSandboxIdentity(t *testing.T) {
if os.Geteuid() != 0 {
t.Skip("dropping to the sandbox uid needs root")
}
lines := statusLines(t, run(t, statusProbe(t), nil, true))
assert.Equal(t, "993 993 993 993", lines["Uid"])
assert.Equal(t, "993 993 993 993", lines["Gid"])
assert.Empty(t, lines["Groups"])
assert.Equal(t, "1", lines["NoNewPrivs"])
}
// A tenant LD_PRELOAD constructor runs before the bootstrap's main; it must
// already see no_new_privs, so no loader runs before the flag is set.
func TestStartBootstrapPreloadConstructorSeesNoNewPrivs(t *testing.T) {
goruntime.LockOSThread()
defer goruntime.UnlockOSThread()
if threadNoNewPrivs(t) != "0" {
t.Skip("test thread already has no_new_privs; the check would pass vacuously")
}
cc, err := exec.LookPath("cc")
if err != nil {
t.Skip("no C compiler for the preload library")
}
bootstrap, err := exec.LookPath("true")
require.NoError(t, err)
dir := t.TempDir()
src := filepath.Join(dir, "preload.c")
lib := filepath.Join(dir, "preload.so")
require.NoError(t, os.WriteFile(src, []byte(preloadSource), 0o644))
build := exec.Command(cc, "-shared", "-fPIC", "-o", lib, src)
build.Stderr = os.Stderr
require.NoError(t, build.Run())
out := run(t, bootstrap, []string{"LD_PRELOAD=" + lib}, false)
assert.Equal(t, "preload NoNewPrivs: 1", strings.Join(strings.Fields(string(out)), " "))
}
const preloadSource = `#include <stdio.h>
#include <string.h>
__attribute__((constructor)) static void report(void) {
char line[256];
FILE *f = fopen("/proc/self/status", "r");
if (!f)
return;
while (fgets(line, sizeof line, f))
if (strncmp(line, "NoNewPrivs:", 11) == 0)
printf("preload %s", line);
fclose(f);
fflush(stdout);
}
`
func TestStartBootstrapDoesNotInheritAgentEnvironment(t *testing.T) {
t.Setenv("ZZ_AGENT_SECRET", "must-not-leak")
probe, err := exec.LookPath("env")
require.NoError(t, err)
for name, env := range map[string][]string{"nil": nil, "empty": {}, "given": {"ONLY=this"}} {
out := run(t, probe, env, false)
// Never print the captured environment: an inherited one may hold secrets.
if strings.TrimSuffix(string(out), "\n") != strings.Join(env, "\n") {
t.Errorf("%s: bootstrap environment is not exactly the one given", name)
}
}
}
// Without root the sandbox credential cannot be applied, so the exported entry
// point must refuse rather than run the bootstrap as the caller.
func TestStartBootstrapAsNonRootRefusesInsteadOfKeepingCallerIdentity(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root can apply the sandbox credential")
}
_, err := StartBootstrap(context.Background(), statusProbe(t), nil, nil, nil)
assert.ErrorIs(t, err, syscall.EPERM)
}
func TestStartBootstrapMissingExecutableFails(t *testing.T) {
_, err := startBootstrap(context.Background(), filepath.Join(t.TempDir(), "bootstrap"), nil, nil, nil, nil)
assert.Error(t, err)
}
+41
View File
@@ -0,0 +1,41 @@
// Package hostlink is the guest's boundary to host control: an authenticated
// TCP connection under per-generation mutual TLS. The message protocol over it
// is not yet chosen; implementations of Link are carriers.
package hostlink
import (
"context"
"errors"
)
// ErrShutdown is returned by Link.Next when the host asks the agent to stop.
var ErrShutdown = errors.New("hostlink: host requested shutdown")
// Request is one invocation from the host. GrantID and AttemptID are opaque
// to the agent and are echoed unchanged in the Response.
type Request struct {
GrantID string `json:"grant_id"`
AttemptID string `json:"attempt_id"`
RequestID string `json:"request_id"`
FunctionARN string `json:"function_arn"`
TraceID string `json:"trace_id,omitempty"`
DeadlineMs int64 `json:"deadline_ms"`
Payload []byte `json:"payload"`
}
// Response is the outcome of a Request. FunctionError is empty on success.
type Response struct {
GrantID string `json:"grant_id"`
AttemptID string `json:"attempt_id"`
RequestID string `json:"request_id"`
Payload []byte `json:"payload"`
FunctionError string `json:"function_error,omitempty"`
}
// Link carries invocations from the host to the guest and results back.
type Link interface {
// Next blocks for the next request, or returns ErrShutdown.
Next(ctx context.Context) (Request, error)
// Complete reports the outcome of a request.
Complete(ctx context.Context, resp Response) error
}
+42
View File
@@ -0,0 +1,42 @@
package hostlink
import (
"errors"
"fmt"
"io/fs"
"os"
"golang.org/x/sys/unix"
)
// FwCfgRoot is the sysfs tree the qemu_fw_cfg module exposes; removing the
// module removes every entry under it, including the guest key.
const FwCfgRoot = "/sys/firmware/qemu_fw_cfg"
// UnloadFwCfg removes the qemu_fw_cfg module from the running kernel.
func UnloadFwCfg() error {
if err := unix.DeleteModule("qemu_fw_cfg", 0); err != nil {
return fmt.Errorf("hostlink: unload qemu_fw_cfg: %w", err)
}
return nil
}
// SealFwCfg makes fw_cfg unreadable for the rest of the boot. It succeeds only
// once root is gone, so a built-in or busy module fails closed rather than
// leaving the guest key readable by code started later.
func SealFwCfg(root string, unload func() error) error {
if _, err := os.Stat(root); errors.Is(err, fs.ErrNotExist) {
return nil
} else if err != nil {
return fmt.Errorf("hostlink: fw_cfg: %w", err)
}
unloadErr := unload()
_, err := os.Stat(root)
if errors.Is(err, fs.ErrNotExist) {
return nil
}
if unloadErr == nil {
unloadErr = errors.New("unload reported success")
}
return fmt.Errorf("hostlink: fw_cfg still readable at %s: %w", root, errors.Join(unloadErr, err))
}
@@ -0,0 +1,43 @@
package hostlink
import (
"errors"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func fwCfgTree(t *testing.T) string {
t.Helper()
root := filepath.Join(t.TempDir(), "qemu_fw_cfg")
require.NoError(t, os.MkdirAll(filepath.Join(root, "by_name"), 0o700))
return root
}
func TestSealFwCfg(t *testing.T) {
t.Run("already absent needs no unload", func(t *testing.T) {
called := false
require.NoError(t, SealFwCfg(filepath.Join(t.TempDir(), "absent"), func() error { called = true; return nil }))
assert.False(t, called)
})
t.Run("unload removes the tree", func(t *testing.T) {
root := fwCfgTree(t)
require.NoError(t, SealFwCfg(root, func() error { return os.RemoveAll(root) }))
})
t.Run("unload fails and the tree remains", func(t *testing.T) {
builtIn := errors.New("module is built in")
err := SealFwCfg(fwCfgTree(t), func() error { return builtIn })
assert.ErrorIs(t, err, builtIn)
assert.ErrorContains(t, err, "still readable")
})
t.Run("unload succeeds but the tree remains", func(t *testing.T) {
assert.ErrorContains(t, SealFwCfg(fwCfgTree(t), func() error { return nil }), "unload reported success")
})
t.Run("unload errors after removing the tree", func(t *testing.T) {
root := fwCfgTree(t)
require.NoError(t, SealFwCfg(root, func() error { _ = os.RemoveAll(root); return errors.New("late") }))
})
}
@@ -0,0 +1,163 @@
//go:build lambdatestlink
package hostlink
import (
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"sync"
)
// maxFrame bounds one frame: a 6 MiB payload as base64 plus headroom.
const maxFrame = (6<<20+2)/3*4 + 64<<10
const (
typeInvoke = "invoke"
typeShutdown = "shutdown"
typeResult = "result"
)
// ErrFrameTooLarge is returned for a frame beyond the size bound.
var ErrFrameTooLarge = errors.New("hostlink: frame too large")
type frame struct {
Type string `json:"type"`
Request *Request `json:"request,omitempty"`
Response *Response `json:"response,omitempty"`
}
// TestStream is a test-only carrier over an io.ReadWriter, framing JSON with
// a 4-byte big-endian length. It is not the guest protocol.
type TestStream struct {
rw io.ReadWriter
in chan frame
wmu sync.Mutex
err error // set before in is closed
}
var _ Link = (*TestStream)(nil)
// NewTestStream starts reading frames from rw.
func NewTestStream(rw io.ReadWriter) *TestStream {
s := &TestStream{rw: rw, in: make(chan frame)}
go s.readLoop()
return s
}
func (s *TestStream) readLoop() {
defer close(s.in)
for {
f, err := readFrame(s.rw)
if err != nil {
s.err = err
return
}
s.in <- f
}
}
func (s *TestStream) recv(ctx context.Context) (frame, error) {
select {
case f, ok := <-s.in:
if !ok {
return frame{}, s.err
}
return f, nil
case <-ctx.Done():
return frame{}, ctx.Err()
}
}
// Next implements Link.
func (s *TestStream) Next(ctx context.Context) (Request, error) {
f, err := s.recv(ctx)
if err != nil {
return Request{}, err
}
switch f.Type {
case typeShutdown:
return Request{}, ErrShutdown
case typeInvoke:
if f.Request == nil {
return Request{}, errors.New("hostlink: invoke frame without request")
}
return *f.Request, nil
default:
return Request{}, fmt.Errorf("hostlink: unexpected frame type %q", f.Type)
}
}
// Complete implements Link.
func (s *TestStream) Complete(ctx context.Context, resp Response) error {
if err := ctx.Err(); err != nil {
return err
}
return s.write(frame{Type: typeResult, Response: &resp})
}
// HostSend writes an invoke frame, as the host side of the carrier.
func (s *TestStream) HostSend(req Request) error {
return s.write(frame{Type: typeInvoke, Request: &req})
}
// HostShutdown writes a shutdown frame, as the host side of the carrier.
func (s *TestStream) HostShutdown() error {
return s.write(frame{Type: typeShutdown})
}
// HostResult reads a result frame, as the host side of the carrier.
func (s *TestStream) HostResult(ctx context.Context) (Response, error) {
f, err := s.recv(ctx)
if err != nil {
return Response{}, err
}
if f.Type != typeResult || f.Response == nil {
return Response{}, fmt.Errorf("hostlink: unexpected frame type %q", f.Type)
}
return *f.Response, nil
}
func (s *TestStream) write(f frame) error {
b, err := json.Marshal(f)
if err != nil {
return err
}
if len(b) > maxFrame {
return ErrFrameTooLarge
}
buf := make([]byte, 4+len(b))
binary.BigEndian.PutUint32(buf, uint32(len(b)))
copy(buf[4:], b)
s.wmu.Lock()
defer s.wmu.Unlock()
_, err = s.rw.Write(buf)
return err
}
func readFrame(r io.Reader) (frame, error) {
var hdr [4]byte
if _, err := io.ReadFull(r, hdr[:]); err != nil {
return frame{}, err
}
n := binary.BigEndian.Uint32(hdr[:])
if n > maxFrame {
return frame{}, ErrFrameTooLarge
}
body := make([]byte, n)
if _, err := io.ReadFull(r, body); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return frame{}, err
}
var f frame
if err := json.Unmarshal(body, &f); err != nil {
return frame{}, fmt.Errorf("hostlink: bad frame: %w", err)
}
return f, nil
}
@@ -0,0 +1,73 @@
//go:build lambdatestlink
package hostlink
import (
"context"
"encoding/binary"
"net"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// pair returns the guest carrier and the raw host end of a pipe.
func pair(t *testing.T) (*TestStream, net.Conn) {
t.Helper()
g, h := net.Pipe()
t.Cleanup(func() { g.Close(); h.Close() })
return NewTestStream(g), h
}
func TestRoundTrip(t *testing.T) {
guest, host := pair(t)
hostEnd := NewTestStream(host)
req := Request{GrantID: "g", AttemptID: "a", RequestID: "r", FunctionARN: "arn", TraceID: "t", DeadlineMs: 42, Payload: []byte{0, 1, 2, 255}}
go func() { _ = hostEnd.HostSend(req) }()
got, err := guest.Next(context.Background())
require.NoError(t, err)
assert.Equal(t, req, got)
resp := Response{GrantID: "g", AttemptID: "a", RequestID: "r", Payload: []byte("out"), FunctionError: "Unhandled"}
go func() { _ = guest.Complete(context.Background(), resp) }()
gotResp, err := hostEnd.HostResult(context.Background())
require.NoError(t, err)
assert.Equal(t, resp, gotResp)
}
func TestOversizeFrameRefused(t *testing.T) {
guest, host := pair(t)
go func() {
var hdr [4]byte
binary.BigEndian.PutUint32(hdr[:], maxFrame+1)
_, _ = host.Write(hdr[:])
}()
_, err := guest.Next(context.Background())
require.ErrorIs(t, err, ErrFrameTooLarge)
err = guest.Complete(context.Background(), Response{Payload: make([]byte, maxFrame)})
require.ErrorIs(t, err, ErrFrameTooLarge)
}
func TestTruncatedFrameErrors(t *testing.T) {
guest, host := pair(t)
go func() {
var hdr [4]byte
binary.BigEndian.PutUint32(hdr[:], 100)
_, _ = host.Write(append(hdr[:], []byte(`{"type"`)...))
host.Close()
}()
_, err := guest.Next(context.Background())
require.Error(t, err)
assert.NotErrorIs(t, err, ErrShutdown)
}
func TestShutdownSurfaced(t *testing.T) {
guest, host := pair(t)
hostEnd := NewTestStream(host)
go func() { _ = hostEnd.HostShutdown() }()
_, err := guest.Next(context.Background())
require.ErrorIs(t, err, ErrShutdown)
}
+115
View File
@@ -0,0 +1,115 @@
package hostlink
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"time"
lambdav1 "github.com/mulgadc/spinifex/contracts/lambda/v1"
"github.com/mulgadc/spinifex/spinifex/foundation/pki"
)
// FwCfgDir is where the guest kernel exposes the executor's fw_cfg entries.
const FwCfgDir = FwCfgRoot + "/by_name/" + lambdav1.FwCfgPrefix
// Identity is the guest's material for one environment generation.
type Identity struct {
Cert tls.Certificate
HostCert *x509.Certificate
Scope lambdav1.Scope
HostAddr string
}
// LoadIdentity reads the executor's fw_cfg entries from dir.
func LoadIdentity(dir string) (Identity, error) {
read := func(name string) ([]byte, error) {
b, err := os.ReadFile(filepath.Join(dir, name, "raw"))
if err != nil {
return nil, fmt.Errorf("hostlink: read %s: %w", name, err)
}
return b, nil
}
var id Identity
keyPEM, err := read(lambdav1.EntryGuestKey)
if err != nil {
return id, err
}
certPEM, err := read(lambdav1.EntryGuestCert)
if err != nil {
return id, err
}
hostPEM, err := read(lambdav1.EntryHostCert)
if err != nil {
return id, err
}
scope, err := read(lambdav1.EntryScope)
if err != nil {
return id, err
}
addr, err := read(lambdav1.EntryHostAddr)
if err != nil {
return id, err
}
if id.Cert, err = tls.X509KeyPair(certPEM, keyPEM); err != nil {
return Identity{}, fmt.Errorf("hostlink: guest key pair: %w", err)
}
blk, rest := pem.Decode(hostPEM)
if blk == nil || blk.Type != "CERTIFICATE" || len(strings.TrimSpace(string(rest))) != 0 {
return Identity{}, errors.New("hostlink: host certificate: want exactly one PEM certificate")
}
if id.HostCert, err = x509.ParseCertificate(blk.Bytes); err != nil {
return Identity{}, fmt.Errorf("hostlink: host certificate: %w", err)
}
if id.Scope, err = lambdav1.ParseScope(strings.TrimSpace(string(scope))); err != nil {
return Identity{}, err
}
id.HostAddr = strings.TrimSpace(string(addr))
if _, _, err := net.SplitHostPort(id.HostAddr); err != nil {
return Identity{}, fmt.Errorf("hostlink: host address: %w", err)
}
return id, nil
}
// ClientConfig is the guest's TLS 1.3 configuration. The host has no DNS name,
// so VerifyConnection checks the pinned host certificate and its URI SAN.
func (id Identity) ClientConfig() *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS13,
MaxVersion: tls.VersionTLS13,
Certificates: []tls.Certificate{id.Cert},
NextProtos: []string{lambdav1.ALPNv1},
InsecureSkipVerify: true, //nolint:gosec // VerifyConnection performs full validation against the pinned host certificate.
VerifyConnection: func(cs tls.ConnectionState) error {
if cs.NegotiatedProtocol != lambdav1.ALPNv1 {
return fmt.Errorf("hostlink: application protocol %q, want %q", cs.NegotiatedProtocol, lambdav1.ALPNv1)
}
return pki.VerifyPinned(cs.PeerCertificates, id.HostCert, x509.ExtKeyUsageServerAuth, id.Scope.URI(lambdav1.RoleHost))
},
}
}
// Dial opens the authenticated control connection to the host. Under TLS 1.3
// the host may still refuse the guest's certificate after Dial returns; that
// surfaces on the first read, so the caller must not treat Dial as acceptance.
func Dial(ctx context.Context, id Identity) (*tls.Conn, error) {
d := tls.Dialer{NetDialer: &net.Dialer{Timeout: 10 * time.Second}, Config: id.ClientConfig()}
c, err := d.DialContext(ctx, "tcp", id.HostAddr)
if err != nil {
return nil, fmt.Errorf("hostlink: dial host %s: %w", id.HostAddr, err)
}
tc, ok := c.(*tls.Conn)
if !ok {
_ = c.Close()
return nil, fmt.Errorf("hostlink: dial host %s: unexpected connection type %T", id.HostAddr, c)
}
return tc, nil
}
+291
View File
@@ -0,0 +1,291 @@
package hostlink
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"net/url"
"os"
"path/filepath"
"testing"
"time"
lambdav1 "github.com/mulgadc/spinifex/contracts/lambda/v1"
"github.com/mulgadc/spinifex/spinifex/foundation/pki"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
gen1 lambdav1.Scope = "ap-southeast-2/000000000001/fn-1/env-1/gen-1"
gen2 lambdav1.Scope = "ap-southeast-2/000000000001/fn-1/env-1/gen-2"
)
type testIdent struct {
cert tls.Certificate
leaf *x509.Certificate
certPEM []byte
keyPEM []byte
}
func newTestIdent(t *testing.T, scope lambdav1.Scope, role string) testIdent {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
u, err := url.Parse(scope.URI(role))
require.NoError(t, err)
usage := x509.ExtKeyUsageServerAuth
if role == lambdav1.RoleGuest {
usage = x509.ExtKeyUsageClientAuth
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: role},
NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{usage},
BasicConstraintsValid: true, URIs: []*url.URL{u},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
require.NoError(t, err)
kder, err := x509.MarshalECPrivateKey(key)
require.NoError(t, err)
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kder})
c, err := tls.X509KeyPair(certPEM, keyPEM)
require.NoError(t, err)
leaf, err := x509.ParseCertificate(der)
require.NoError(t, err)
return testIdent{cert: c, leaf: leaf, certPEM: certPEM, keyPEM: keyPEM}
}
// hostConfig is the host end as the executor will run it: it pins one guest
// certificate and checks its URI SAN with the shared pki.VerifyPinned.
func hostConfig(host testIdent, pinGuest *x509.Certificate, scope lambdav1.Scope) *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{host.cert},
ClientAuth: tls.RequireAnyClientCert, NextProtos: []string{lambdav1.ALPNv1},
VerifyConnection: func(cs tls.ConnectionState) error {
return pki.VerifyPinned(cs.PeerCertificates, pinGuest, x509.ExtKeyUsageClientAuth, scope.URI(lambdav1.RoleGuest))
},
}
}
// serve accepts one connection with cfg, writes "ok" if the handshake
// succeeds, and returns the address and the host's handshake result.
func serve(t *testing.T, cfg *tls.Config) (string, <-chan error) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
t.Cleanup(func() { ln.Close() })
done := make(chan error, 1)
go func() {
raw, err := ln.Accept()
if err != nil {
done <- err
return
}
defer raw.Close()
tc := tls.Server(raw, cfg)
_ = tc.SetDeadline(time.Now().Add(5 * time.Second))
err = tc.Handshake()
if err == nil {
_, err = tc.Write([]byte("ok"))
}
done <- err
}()
return ln.Addr().String(), done
}
func guestIdentity(guest, pinHost testIdent, scope lambdav1.Scope, addr string) Identity {
return Identity{Cert: guest.cert, HostCert: pinHost.leaf, Scope: scope, HostAddr: addr}
}
func dialAndRead(t *testing.T, id Identity) (string, error) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c, err := Dial(ctx, id)
if err != nil {
return "", err
}
defer c.Close()
_ = c.SetReadDeadline(time.Now().Add(5 * time.Second))
buf := make([]byte, 2)
n, err := c.Read(buf)
return string(buf[:n]), err
}
func TestDialMutualAuthentication(t *testing.T) {
host, guest := newTestIdent(t, gen1, lambdav1.RoleHost), newTestIdent(t, gen1, lambdav1.RoleGuest)
addr, hostErr := serve(t, hostConfig(host, guest.leaf, gen1))
got, err := dialAndRead(t, guestIdentity(guest, host, gen1, addr))
require.NoError(t, err)
assert.Equal(t, "ok", got)
require.NoError(t, <-hostErr)
}
func TestDialRefusesHost(t *testing.T) {
guest := newTestIdent(t, gen1, lambdav1.RoleGuest)
pinned := newTestIdent(t, gen1, lambdav1.RoleHost)
cases := []struct {
name string
host testIdent
pin testIdent
mutate func(*tls.Config)
wantErr string
}{
{"unpinned host certificate", newTestIdent(t, gen1, lambdav1.RoleHost), pinned, nil, "peer certificate"},
{"pinned certificate of a later generation", newTestIdent(t, gen2, lambdav1.RoleHost), testIdent{}, nil, "peer identity mismatch"},
{"guest role presented as host", newTestIdent(t, gen1, lambdav1.RoleGuest), testIdent{}, nil, "peer certificate"},
{"no application protocol", pinned, pinned, func(c *tls.Config) { c.NextProtos = nil }, "application protocol"},
{"TLS 1.2 only", pinned, pinned, func(c *tls.Config) { c.MinVersion, c.MaxVersion = tls.VersionTLS12, tls.VersionTLS12 }, "protocol version"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
pin := tc.pin
if pin.leaf == nil {
pin = tc.host // the guest pins exactly what is presented
}
cfg := hostConfig(tc.host, guest.leaf, gen1)
if tc.mutate != nil {
tc.mutate(cfg)
}
addr, _ := serve(t, cfg)
_, err := dialAndRead(t, guestIdentity(guest, pin, gen1, addr))
require.Error(t, err)
assert.Contains(t, err.Error(), tc.wantErr)
})
}
}
// newCASignedHost returns a CA and a host leaf it signed carrying the same URI
// SAN as a legitimate host certificate.
func newCASignedHost(t *testing.T, scope lambdav1.Scope) (ca testIdent, leaf tls.Certificate) {
t.Helper()
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
u, err := url.Parse(scope.URI(lambdav1.RoleHost))
require.NoError(t, err)
caTmpl := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "ca"},
NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true, IsCA: true, URIs: []*url.URL{u},
}
caDER, err := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey)
require.NoError(t, err)
caCert, err := x509.ParseCertificate(caDER)
require.NoError(t, err)
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "host"},
NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
URIs: []*url.URL{u},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, caCert, &key.PublicKey, caKey)
require.NoError(t, err)
return testIdent{leaf: caCert}, tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
}
// Trusting the pin as a root is not enough: a different leaf it signed, with
// the right URI SAN, must still be refused.
func TestDialRefusesLeafSignedByPin(t *testing.T) {
guest := newTestIdent(t, gen1, lambdav1.RoleGuest)
ca, leaf := newCASignedHost(t, gen1)
for name, chain := range map[string][][]byte{
"leaf only": leaf.Certificate,
"leaf with CA": {leaf.Certificate[0], ca.leaf.Raw},
} {
t.Run(name, func(t *testing.T) {
cfg := hostConfig(testIdent{}, guest.leaf, gen1)
cfg.Certificates = []tls.Certificate{{Certificate: chain, PrivateKey: leaf.PrivateKey}}
addr, _ := serve(t, cfg)
_, err := dialAndRead(t, guestIdentity(guest, ca, gen1, addr))
require.Error(t, err)
assert.Regexp(t, "not the pinned certificate|want exactly the pinned one", err.Error())
})
}
}
func TestHostRefusalSurfacesOnFirstRead(t *testing.T) {
host, guest := newTestIdent(t, gen1, lambdav1.RoleHost), newTestIdent(t, gen1, lambdav1.RoleGuest)
other := newTestIdent(t, gen1, lambdav1.RoleGuest)
addr, hostErr := serve(t, hostConfig(host, other.leaf, gen1))
_, err := dialAndRead(t, guestIdentity(guest, host, gen1, addr))
require.Error(t, err)
assert.Contains(t, err.Error(), "bad certificate")
assert.ErrorContains(t, <-hostErr, "peer certificate")
}
func TestHostRefusesGuestOfAnotherGeneration(t *testing.T) {
host, guest := newTestIdent(t, gen1, lambdav1.RoleHost), newTestIdent(t, gen2, lambdav1.RoleGuest)
addr, hostErr := serve(t, hostConfig(host, guest.leaf, gen1))
_, err := dialAndRead(t, guestIdentity(guest, host, gen1, addr))
require.Error(t, err)
assert.ErrorIs(t, <-hostErr, pki.ErrPeerIdentity)
}
func writeEntries(t *testing.T, entries map[string][]byte) string {
t.Helper()
dir := t.TempDir()
for name, b := range entries {
require.NoError(t, os.MkdirAll(filepath.Join(dir, name), 0o700))
require.NoError(t, os.WriteFile(filepath.Join(dir, name, "raw"), b, 0o600))
}
return dir
}
func validEntries(t *testing.T) map[string][]byte {
host, guest := newTestIdent(t, gen1, lambdav1.RoleHost), newTestIdent(t, gen1, lambdav1.RoleGuest)
return map[string][]byte{
lambdav1.EntryGuestKey: guest.keyPEM, lambdav1.EntryGuestCert: guest.certPEM, lambdav1.EntryHostCert: host.certPEM,
lambdav1.EntryScope: []byte(string(gen1) + "\n"), lambdav1.EntryHostAddr: []byte("10.15.8.1:18443\n"),
}
}
func TestLoadIdentity(t *testing.T) {
id, err := LoadIdentity(writeEntries(t, validEntries(t)))
require.NoError(t, err)
assert.Equal(t, gen1, id.Scope)
assert.Equal(t, "10.15.8.1:18443", id.HostAddr)
require.Len(t, id.HostCert.URIs, 1)
assert.Equal(t, gen1.URI(lambdav1.RoleHost), id.HostCert.URIs[0].String())
}
func TestLoadIdentityRejects(t *testing.T) {
other := newTestIdent(t, gen1, lambdav1.RoleGuest)
cases := []struct {
name string
edit func(map[string][]byte)
wantErr string
}{
{"missing entry", func(e map[string][]byte) { delete(e, lambdav1.EntryHostCert) }, "read host-cert"},
{"key does not match certificate", func(e map[string][]byte) { e[lambdav1.EntryGuestKey] = other.keyPEM }, "guest key pair"},
{"two host certificates", func(e map[string][]byte) {
e[lambdav1.EntryHostCert] = append(e[lambdav1.EntryHostCert], e[lambdav1.EntryHostCert]...)
}, "exactly one PEM"},
{"host certificate not PEM", func(e map[string][]byte) { e[lambdav1.EntryHostCert] = []byte("nope") }, "exactly one PEM"},
{"short scope", func(e map[string][]byte) { e[lambdav1.EntryScope] = []byte("ap-southeast-2/000000000001/fn-1") }, "want 5 segments"},
{"address without port", func(e map[string][]byte) { e[lambdav1.EntryHostAddr] = []byte("10.15.8.1") }, "host address"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
e := validEntries(t)
tc.edit(e)
_, err := LoadIdentity(writeEntries(t, e))
assert.ErrorContains(t, err, tc.wantErr)
})
}
}
+285
View File
@@ -0,0 +1,285 @@
// Package runtimeapi serves the AWS Lambda Runtime API (version 2018-06-01)
// inside the guest, handing one invocation at a time to the function runtime.
package runtimeapi
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"sync"
"time"
)
// MaxResponseBytes is the largest response payload a runtime may post.
const MaxResponseBytes = 6291456
const (
// ErrTypeResponseTooLarge is the function error for an oversize response.
ErrTypeResponseTooLarge = "Function.ResponseSizeTooLarge"
// ErrTypeUnhandled is the function error when the runtime names no type.
ErrTypeUnhandled = "Unhandled"
errTypeInvalidRequestID = "InvalidRequestID"
errTypeTooLarge = "RequestEntityTooLarge"
errTypeInvalidRequest = "InvalidRequest"
headerRequestID = "Lambda-Runtime-Aws-Request-Id"
headerDeadline = "Lambda-Runtime-Deadline-Ms"
headerARN = "Lambda-Runtime-Invoked-Function-Arn"
headerTraceID = "Lambda-Runtime-Trace-Id"
headerErrorType = "Lambda-Runtime-Function-Error-Type"
maxInitErrorBytes = 1 << 20
)
var (
// ErrBusy is returned by Invoke while another invocation is in flight.
ErrBusy = errors.New("runtimeapi: an invocation is already in flight")
// ErrDeadlineExceeded is returned by Invoke when the deadline passes.
ErrDeadlineExceeded = errors.New("runtimeapi: invocation deadline exceeded")
// ErrInvalidInvocation is returned by Invoke for an invocation with no request ID.
ErrInvalidInvocation = errors.New("runtimeapi: invocation has no request id")
)
// Invocation is one event handed to the runtime.
type Invocation struct {
RequestID string
FunctionARN string
Deadline time.Time
TraceID string
Payload []byte
}
// Result is what the runtime answered. FunctionError is empty on success and
// otherwise the error type.
type Result struct {
Payload []byte
FunctionError string
}
// InitError is an initialisation failure reported by the runtime.
type InitError struct {
Type string
Body []byte
}
type flight struct {
inv Invocation
taken bool
done chan Result
}
// Server implements the Runtime API for a single in-flight invocation.
type Server struct {
mu sync.Mutex
cur *flight
wake chan struct{}
initOnce sync.Once
initDone chan struct{}
initErr InitError
}
// New returns a Server with no invocation in flight.
func New() *Server {
return &Server{wake: make(chan struct{}, 1), initDone: make(chan struct{})}
}
// InitFailed is closed once the runtime reports an init error.
func (s *Server) InitFailed() <-chan struct{} { return s.initDone }
// InitError returns the reported init error, if any.
func (s *Server) InitError() (InitError, bool) {
select {
case <-s.initDone:
return s.initErr, true
default:
return InitError{}, false
}
}
// Invoke hands inv to the runtime and blocks until the runtime posts a
// response or error, the deadline passes, or ctx ends.
func (s *Server) Invoke(ctx context.Context, inv Invocation) (Result, error) {
if inv.RequestID == "" {
return Result{}, ErrInvalidInvocation
}
f := &flight{inv: inv, done: make(chan Result, 1)}
s.mu.Lock()
if s.cur != nil {
s.mu.Unlock()
return Result{}, ErrBusy
}
s.cur = f
s.mu.Unlock()
select {
case s.wake <- struct{}{}:
default:
}
timer := time.NewTimer(time.Until(inv.Deadline))
defer timer.Stop()
var cause error
select {
case res := <-f.done:
return res, nil
case <-timer.C:
cause = ErrDeadlineExceeded
case <-ctx.Done():
cause = ctx.Err()
}
s.mu.Lock()
if s.cur == f {
s.cur = nil
s.mu.Unlock()
return Result{}, cause
}
s.mu.Unlock()
// Completed while we were giving up; the result is already queued.
return <-f.done, nil
}
// Handler returns the Runtime API routes.
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /2018-06-01/runtime/invocation/next", s.next)
mux.HandleFunc("POST /2018-06-01/runtime/invocation/{id}/response", s.response)
mux.HandleFunc("POST /2018-06-01/runtime/invocation/{id}/error", s.invocationError)
mux.HandleFunc("POST /2018-06-01/runtime/init/error", s.initError)
return mux
}
func (s *Server) next(w http.ResponseWriter, r *http.Request) {
for {
s.mu.Lock()
f := s.cur
if f != nil && !f.taken {
f.taken = true
s.mu.Unlock()
h := w.Header()
h.Set(headerRequestID, f.inv.RequestID)
h.Set(headerDeadline, strconv.FormatInt(f.inv.Deadline.UnixMilli(), 10))
h.Set(headerARN, f.inv.FunctionARN)
if f.inv.TraceID != "" {
h.Set(headerTraceID, f.inv.TraceID)
}
_, _ = w.Write(f.inv.Payload)
return
}
s.mu.Unlock()
select {
case <-s.wake:
case <-r.Context().Done():
return
}
}
}
// claimable reports whether id names the delivered, uncompleted invocation.
func (s *Server) claimable(id string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.cur != nil && s.cur.taken && s.cur.inv.RequestID == id
}
// complete finishes the invocation named id, reporting whether it was live.
func (s *Server) complete(id string, res Result) bool {
s.mu.Lock()
defer s.mu.Unlock()
f := s.cur
if f == nil || !f.taken || f.inv.RequestID != id {
return false
}
s.cur = nil
f.done <- res
return true
}
func (s *Server) response(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if !s.claimable(id) {
invalidID(w, id)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, MaxResponseBytes+1))
if err != nil {
writeError(w, http.StatusBadRequest, errTypeInvalidRequest, "read body: "+err.Error())
return
}
if len(body) > MaxResponseBytes {
msg := "Response payload size exceeded maximum allowed payload size (" + strconv.Itoa(MaxResponseBytes) + " bytes)."
s.complete(id, Result{Payload: ErrorBody(msg, ErrTypeResponseTooLarge), FunctionError: ErrTypeResponseTooLarge})
writeError(w, http.StatusRequestEntityTooLarge, errTypeTooLarge, msg)
return
}
if !s.complete(id, Result{Payload: body}) {
invalidID(w, id)
return
}
writeStatus(w)
}
func (s *Server) invocationError(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if !s.claimable(id) {
invalidID(w, id)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, MaxResponseBytes))
if err != nil {
writeError(w, http.StatusBadRequest, errTypeInvalidRequest, "read body: "+err.Error())
return
}
errType := r.Header.Get(headerErrorType)
if errType == "" {
errType = ErrTypeUnhandled
}
if !s.complete(id, Result{Payload: body, FunctionError: errType}) {
invalidID(w, id)
return
}
writeStatus(w)
}
func (s *Server) initError(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(io.LimitReader(r.Body, maxInitErrorBytes))
s.initOnce.Do(func() {
s.initErr = InitError{Type: r.Header.Get(headerErrorType), Body: body}
close(s.initDone)
})
writeStatus(w)
}
func invalidID(w http.ResponseWriter, id string) {
writeError(w, http.StatusBadRequest, errTypeInvalidRequestID, "Invalid request ID: "+id)
}
func writeStatus(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"status":"OK"}`))
}
func writeError(w http.ResponseWriter, code int, errType, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_, _ = w.Write(ErrorBody(msg, errType))
}
type errorPayload struct {
ErrorMessage string `json:"errorMessage"`
ErrorType string `json:"errorType"`
}
// ErrorBody renders the Lambda error document for msg and errType.
func ErrorBody(msg, errType string) []byte {
b, err := json.Marshal(errorPayload{ErrorMessage: msg, ErrorType: errType})
if err != nil {
return []byte(`{"errorType":"Runtime.Unknown"}`)
}
return b
}
@@ -0,0 +1,292 @@
package runtimeapi
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const base = "/2018-06-01/runtime/"
type invokeOut struct {
res Result
err error
}
func start(t *testing.T) (*Server, *httptest.Server) {
t.Helper()
s := New()
ts := httptest.NewServer(s.Handler())
t.Cleanup(ts.Close)
return s, ts
}
func invokeAsync(s *Server, inv Invocation) <-chan invokeOut {
ch := make(chan invokeOut, 1)
go func() {
res, err := s.Invoke(context.Background(), inv)
ch <- invokeOut{res, err}
}()
return ch
}
func post(t *testing.T, url string, body []byte, hdr map[string]string) (*http.Response, []byte) {
t.Helper()
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
require.NoError(t, err)
for k, v := range hdr {
req.Header.Set(k, v)
}
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp, b
}
func get(t *testing.T, url string) (*http.Response, []byte) {
t.Helper()
resp, err := http.Get(url)
require.NoError(t, err)
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp, b
}
func inv(id string, d time.Duration) Invocation {
return Invocation{
RequestID: id,
FunctionARN: "arn:aws:lambda:ap-southeast-2:000000000001:function:f",
Deadline: time.Now().Add(d),
Payload: []byte(`{"a":1}`),
}
}
func errType(t *testing.T, body []byte) string {
t.Helper()
var e map[string]string
require.NoError(t, json.Unmarshal(body, &e))
assert.NotEmpty(t, e["errorMessage"])
return e["errorType"]
}
func TestNextResponseRoundTrip(t *testing.T) {
s, ts := start(t)
in := inv("req-1", 2*time.Second)
in.TraceID = "Root=1-abc"
out := invokeAsync(s, in)
resp, body := get(t, ts.URL+base+"invocation/next")
require.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, `{"a":1}`, string(body))
assert.Equal(t, "req-1", resp.Header.Get("Lambda-Runtime-Aws-Request-Id"))
assert.Equal(t, strconv.FormatInt(in.Deadline.UnixMilli(), 10), resp.Header.Get("Lambda-Runtime-Deadline-Ms"))
assert.Equal(t, in.FunctionARN, resp.Header.Get("Lambda-Runtime-Invoked-Function-Arn"))
assert.Equal(t, "Root=1-abc", resp.Header.Get("Lambda-Runtime-Trace-Id"))
r, _ := post(t, ts.URL+base+"invocation/req-1/response", []byte(`{"sum":3}`), nil)
assert.Equal(t, http.StatusAccepted, r.StatusCode)
got := <-out
require.NoError(t, got.err)
assert.Equal(t, `{"sum":3}`, string(got.res.Payload))
assert.Empty(t, got.res.FunctionError)
}
func TestTraceHeaderOmittedWhenUnset(t *testing.T) {
s, ts := start(t)
invokeAsync(s, inv("req-1", time.Second))
resp, _ := get(t, ts.URL+base+"invocation/next")
_, present := resp.Header["Lambda-Runtime-Trace-Id"]
assert.False(t, present)
}
func TestErrorPostKeepsBodyAndType(t *testing.T) {
s, ts := start(t)
out := invokeAsync(s, inv("req-1", 2*time.Second))
get(t, ts.URL+base+"invocation/next")
body := []byte(`{"errorMessage":"boom","errorType":"Custom"}`)
r, _ := post(t, ts.URL+base+"invocation/req-1/error", body, map[string]string{"Lambda-Runtime-Function-Error-Type": "Custom"})
assert.Equal(t, http.StatusAccepted, r.StatusCode)
got := <-out
require.NoError(t, got.err)
assert.Equal(t, "Custom", got.res.FunctionError)
assert.JSONEq(t, string(body), string(got.res.Payload))
}
func TestErrorPostWithoutTypeIsUnhandled(t *testing.T) {
s, ts := start(t)
out := invokeAsync(s, inv("req-1", 2*time.Second))
get(t, ts.URL+base+"invocation/next")
post(t, ts.URL+base+"invocation/req-1/error", []byte(`{}`), nil)
assert.Equal(t, "Unhandled", (<-out).res.FunctionError)
}
func TestUnknownAndRepeatedIDRefused(t *testing.T) {
s, ts := start(t)
r, b := post(t, ts.URL+base+"invocation/nope/response", []byte("x"), nil)
assert.Equal(t, http.StatusBadRequest, r.StatusCode)
assert.Equal(t, "InvalidRequestID", errType(t, b))
out := invokeAsync(s, inv("req-1", 2*time.Second))
get(t, ts.URL+base+"invocation/next")
post(t, ts.URL+base+"invocation/req-1/response", []byte("ok"), nil)
<-out
r, b = post(t, ts.URL+base+"invocation/req-1/response", []byte("again"), nil)
assert.Equal(t, http.StatusBadRequest, r.StatusCode)
assert.Equal(t, "InvalidRequestID", errType(t, b))
r, _ = post(t, ts.URL+base+"invocation/req-1/error", []byte("{}"), nil)
assert.Equal(t, http.StatusBadRequest, r.StatusCode)
}
func TestResponseNotAcceptedBeforeDelivery(t *testing.T) {
s, ts := start(t)
invokeAsync(s, inv("req-1", time.Second))
r, _ := post(t, ts.URL+base+"invocation/req-1/response", []byte("early"), nil)
assert.Equal(t, http.StatusBadRequest, r.StatusCode)
}
func TestOversizeResponse(t *testing.T) {
s, ts := start(t)
out := invokeAsync(s, inv("req-1", 5*time.Second))
get(t, ts.URL+base+"invocation/next")
r, b := post(t, ts.URL+base+"invocation/req-1/response", make([]byte, MaxResponseBytes+1), nil)
assert.Equal(t, http.StatusRequestEntityTooLarge, r.StatusCode)
assert.Equal(t, "RequestEntityTooLarge", errType(t, b))
got := <-out
require.NoError(t, got.err)
assert.Equal(t, "Function.ResponseSizeTooLarge", got.res.FunctionError)
assert.Equal(t, "Function.ResponseSizeTooLarge", errType(t, got.res.Payload))
}
func TestResponseAtLimitAccepted(t *testing.T) {
s, ts := start(t)
out := invokeAsync(s, inv("req-1", 5*time.Second))
get(t, ts.URL+base+"invocation/next")
r, _ := post(t, ts.URL+base+"invocation/req-1/response", make([]byte, MaxResponseBytes), nil)
assert.Equal(t, http.StatusAccepted, r.StatusCode)
got := <-out
require.NoError(t, got.err)
assert.Len(t, got.res.Payload, MaxResponseBytes)
}
func TestDeadlineExpiryRefusesLateResponse(t *testing.T) {
s, ts := start(t)
out := invokeAsync(s, inv("req-1", 40*time.Millisecond))
get(t, ts.URL+base+"invocation/next")
got := <-out
require.ErrorIs(t, got.err, ErrDeadlineExceeded)
r, b := post(t, ts.URL+base+"invocation/req-1/response", []byte("late"), nil)
assert.Equal(t, http.StatusBadRequest, r.StatusCode)
assert.Equal(t, "InvalidRequestID", errType(t, b))
// The slot is free again for the next invocation.
out = invokeAsync(s, inv("req-2", 2*time.Second))
resp, _ := get(t, ts.URL+base+"invocation/next")
assert.Equal(t, "req-2", resp.Header.Get("Lambda-Runtime-Aws-Request-Id"))
post(t, ts.URL+base+"invocation/req-2/response", []byte("ok"), nil)
require.NoError(t, (<-out).err)
}
func TestConcurrentInvokeRefused(t *testing.T) {
s, ts := start(t)
out := invokeAsync(s, inv("req-1", 2*time.Second))
require.Eventually(t, func() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.cur != nil
}, time.Second, time.Millisecond)
_, err := s.Invoke(context.Background(), inv("req-2", time.Second))
require.ErrorIs(t, err, ErrBusy)
get(t, ts.URL+base+"invocation/next")
post(t, ts.URL+base+"invocation/req-1/response", []byte("ok"), nil)
require.NoError(t, (<-out).err)
}
func TestInvokeContextCancel(t *testing.T) {
s, _ := start(t)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
_, err := s.Invoke(ctx, inv("req-1", time.Minute))
done <- err
}()
cancel()
require.ErrorIs(t, <-done, context.Canceled)
}
func TestNextBlocksUntilInvoke(t *testing.T) {
s, ts := start(t)
type got struct {
resp *http.Response
body []byte
}
ch := make(chan got, 1)
go func() {
resp, err := http.Get(ts.URL + base + "invocation/next") //nolint:noctx // test client
if err != nil {
ch <- got{}
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
ch <- got{resp, body}
}()
select {
case <-ch:
t.Fatal("next returned before any invocation")
case <-time.After(50 * time.Millisecond):
}
out := invokeAsync(s, inv("req-1", 2*time.Second))
g := <-ch
require.NotNil(t, g.resp, "next request failed")
assert.Equal(t, "req-1", g.resp.Header.Get("Lambda-Runtime-Aws-Request-Id"))
post(t, ts.URL+base+"invocation/req-1/response", []byte("ok"), nil)
require.NoError(t, (<-out).err)
}
func TestInitErrorRecorded(t *testing.T) {
s, ts := start(t)
_, ok := s.InitError()
require.False(t, ok)
r, _ := post(t, ts.URL+base+"init/error", []byte(`{"errorMessage":"bad"}`), map[string]string{"Lambda-Runtime-Function-Error-Type": "Runtime.InitError"})
assert.Equal(t, http.StatusAccepted, r.StatusCode)
select {
case <-s.InitFailed():
default:
t.Fatal("InitFailed not closed")
}
ie, ok := s.InitError()
require.True(t, ok)
assert.Equal(t, "Runtime.InitError", ie.Type)
assert.JSONEq(t, `{"errorMessage":"bad"}`, string(ie.Body))
}
func TestInvokeRequiresRequestID(t *testing.T) {
s := New()
_, err := s.Invoke(context.Background(), Invocation{Deadline: time.Now().Add(time.Second)})
require.ErrorIs(t, err, ErrInvalidInvocation)
}
+8 -4
View File
@@ -763,10 +763,11 @@ func TestPollDBCommandsOutput_MatchesGatewayShape(t *testing.T) {
// either side's tags fails here.
payload := awsxml.QueryResponsePayload("PollDBCommands", &rdsawsapi.PollDBCommandsOutput{
Commands: []rdsinstance.Command{{
CommandID: "cmd-1",
Type: "reload-parameters",
Parameters: []rdsinstance.Parameter{{Name: "work_mem", Value: "8MB"}},
IssuedAt: &issued,
CommandID: "cmd-1",
Type: "reload-parameters",
Parameters: []rdsinstance.Parameter{{Name: "work_mem", Value: "8MB"}},
IssuedAt: &issued,
RemainingBudgetMs: 29500,
}},
})
body, err := awsxml.Marshal(payload)
@@ -802,6 +803,9 @@ func TestPollDBCommandsOutput_MatchesGatewayShape(t *testing.T) {
if cmd.IssuedAt == nil || !cmd.IssuedAt.Equal(issued) {
t.Errorf("IssuedAt = %v, want %v", cmd.IssuedAt, issued)
}
if cmd.RemainingBudgetMs != 29500 {
t.Errorf("RemainingBudgetMs = %d, want 29500: a copy that loses it is granted a fresh budget", cmd.RemainingBudgetMs)
}
}
func readFile(t *testing.T, path string) string {
+177 -5
View File
@@ -2,10 +2,13 @@ package agent
import (
"context"
"errors"
"fmt"
"log/slog"
"slices"
"strconv"
"strings"
"sync"
"time"
rdsinstance "github.com/mulgadc/spinifex/spinifex/domains/rds/instance"
@@ -90,35 +93,96 @@ func commandParams(cmd rdsinstance.Command) map[string]string {
// line rate for as long as it stays broken.
const pollErrorBackoff = 5 * time.Second
// How many finished command IDs are remembered, so a copy the issuer re-published
// while the command ran is not executed a second time.
const completedCommandMemory = 64
// How many engine commands may wait behind the one running. Past this a command
// is refused at once rather than queued behind work its issuer will not outlive.
const serialQueueDepth = 16
// The budget for a type the control plane does not issue. Such a command is
// answered as unsupported before it could use any of it.
const fallbackCommandBudget = 30 * time.Second
// The only command that runs beside the serial lane. It releases the backup hold
// an engine command can be blocked on, so it must never queue behind one.
func outOfBand(commandType string) bool {
return commandType == rdsinstance.CommandUnquiesce
}
// A command waiting its turn on the serial lane, with the moment its issuer
// stops waiting for it.
type queuedCommand struct {
cmd rdsinstance.Command
deadline time.Time
}
// The agent's command channel: a long poll that carries back the replies for
// whatever the previous poll delivered.
// whatever earlier polls delivered. Engine commands run one at a time on a single
// lane; the release of a backup hold runs beside it, so it cannot be kept out.
type commander struct {
cp controlPlane
id identity
registry commandRegistry
wait time.Duration
// The control plane's budget per type, capped by the remaining budget the
// issuer stamps on each copy and measured from receipt. IssuedAt is not
// compared: the guest clock is not trusted against the host's.
budget func(commandType string) time.Duration
serial chan queuedCommand
mu sync.Mutex
// Cleared only once a poll has carried them, so a failed poll re-delivers
// rather than dropping the result of work the guest actually did.
pending []rdsinstance.CommandReply
// Queued or running, so a re-published copy is not queued a second time.
inFlight map[string]struct{}
// Oldest first, bounded by completedCommandMemory.
completed []string
// Ends the poll in progress, so a reply that finished during it rides the
// next one rather than waiting out the window. Nil between polls.
interruptPoll func()
interrupted bool
running sync.WaitGroup
}
func newCommander(cp controlPlane, registry commandRegistry, wait time.Duration) *commander {
if wait <= 0 {
wait = defaultPollWait
}
return &commander{cp: cp, registry: registry, wait: wait}
return &commander{
cp: cp,
registry: registry,
wait: wait,
budget: controlPlaneBudget,
serial: make(chan queuedCommand, serialQueueDepth),
inFlight: make(map[string]struct{}),
}
}
func controlPlaneBudget(commandType string) time.Duration {
if budget, ok := rdsinstance.CommandBudget(commandType); ok {
return budget
}
return fallbackCommandBudget
}
func (c *commander) Run(ctx context.Context) {
defer c.running.Wait()
c.running.Go(func() { c.serveSerial(ctx) })
for {
if ctx.Err() != nil {
return
}
commands, err := c.cp.PollCommands(ctx, c.id, c.pending, c.wait)
commands, sent, err := c.poll(ctx)
if err != nil {
if ctx.Err() != nil {
return
}
if errors.Is(err, errReplyReady) {
continue
}
slog.Warn("rds-agent: command poll failed", "err", err)
select {
case <-ctx.Done():
@@ -127,14 +191,122 @@ func (c *commander) Run(ctx context.Context) {
}
continue
}
c.pending = nil
c.mu.Lock()
c.pending = c.pending[sent:]
c.mu.Unlock()
for _, cmd := range commands {
c.pending = append(c.pending, c.execute(ctx, cmd))
c.dispatch(ctx, cmd)
}
}
}
// Reports that a poll was ended early so a finished reply can ride the next one.
var errReplyReady = errors.New("a command reply is ready")
// One long poll carrying every reply ready when it starts. It is cut short when
// another reply becomes ready, so a finished command is never answered a whole
// poll window late. Returns how many pending replies the poll carried.
func (c *commander) poll(ctx context.Context) ([]rdsinstance.Command, int, error) {
pollCtx, cancel := context.WithCancel(ctx)
defer cancel()
c.mu.Lock()
replies := slices.Clone(c.pending)
c.interruptPoll, c.interrupted = cancel, false
c.mu.Unlock()
commands, err := c.cp.PollCommands(pollCtx, c.id, replies, c.wait)
c.mu.Lock()
interrupted := c.interrupted
c.interruptPoll = nil
c.mu.Unlock()
if err != nil {
if interrupted && ctx.Err() == nil {
return nil, 0, errReplyReady
}
return nil, 0, err
}
return commands, len(replies), nil
}
// Routes cmd to its lane unless it is already queued, running or answered: the
// issuer re-publishes until it has a reply, so the same ID arrives again.
func (c *commander) dispatch(ctx context.Context, cmd rdsinstance.Command) {
c.mu.Lock()
_, queued := c.inFlight[cmd.CommandID]
if queued || slices.Contains(c.completed, cmd.CommandID) {
c.mu.Unlock()
slog.Debug("rds-agent: duplicate command ignored", "commandID", cmd.CommandID, "type", cmd.Type)
return
}
c.inFlight[cmd.CommandID] = struct{}{}
c.mu.Unlock()
q := queuedCommand{cmd: cmd, deadline: time.Now().Add(c.budgetFor(cmd))}
if outOfBand(cmd.Type) {
c.running.Go(func() { c.runQueued(ctx, q) })
return
}
select {
case c.serial <- q:
default:
c.finish(cmd, failedReply(cmd, "the agent is busy; too many commands are waiting"))
}
}
// The type's budget, or what the issuer had left when it published this copy if
// that is less: a copy delayed in transit must not be granted a fresh budget its
// issuer will not wait out.
func (c *commander) budgetFor(cmd rdsinstance.Command) time.Duration {
budget := c.budget(cmd.Type)
if cmd.RemainingBudgetMs > 0 {
budget = min(budget, time.Duration(cmd.RemainingBudgetMs)*time.Millisecond)
}
return budget
}
func (c *commander) serveSerial(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case q := <-c.serial:
c.runQueued(ctx, q)
}
}
}
// Runs a command inside what is left of its issuer's budget. One whose budget
// ran out while it waited is answered as expired and never touches the engine,
// since its issuer has already reported it failed.
func (c *commander) runQueued(ctx context.Context, q queuedCommand) {
if !time.Now().Before(q.deadline) {
slog.Warn("rds-agent: command expired before it ran", "commandID", q.cmd.CommandID, "type", q.cmd.Type)
c.finish(q.cmd, failedReply(q.cmd, "the command expired before the agent could run it"))
return
}
cmdCtx, cancel := context.WithDeadline(ctx, q.deadline)
defer cancel()
c.finish(q.cmd, c.execute(cmdCtx, q.cmd))
}
func (c *commander) finish(cmd rdsinstance.Command, reply rdsinstance.CommandReply) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.inFlight, cmd.CommandID)
c.completed = append(c.completed, cmd.CommandID)
if len(c.completed) > completedCommandMemory {
c.completed = c.completed[len(c.completed)-completedCommandMemory:]
}
c.pending = append(c.pending, reply)
if c.interruptPoll != nil {
c.interruptPoll()
c.interrupted = true
}
}
// Every command gets a reply: the issuer is blocked on this command ID, so a
// silent drop costs it a full timeout.
func (c *commander) execute(ctx context.Context, cmd rdsinstance.Command) rdsinstance.CommandReply {
+354 -15
View File
@@ -3,6 +3,9 @@ package agent
import (
"context"
"errors"
"fmt"
"slices"
"sync"
"testing"
"time"
@@ -70,9 +73,9 @@ func TestCommander_UnknownTypeRepliesFailedNotDropped(t *testing.T) {
}
}
// The reply for work the guest actually did rides the next poll. A poll that
// The reply for work the guest actually did rides a later poll. A poll that
// fails must not consume it, or the issuer never learns the outcome.
func TestCommander_RunCarriesRepliesOnTheNextPoll(t *testing.T) {
func TestCommander_RunCarriesRepliesOnALaterPoll(t *testing.T) {
cp := newFakeControlPlane()
cp.pollQueue = [][]rdsinstance.Command{
{{CommandID: "cmd-1", Type: "reload-parameters"}},
@@ -87,19 +90,15 @@ func TestCommander_RunCarriesRepliesOnTheNextPoll(t *testing.T) {
done := make(chan struct{})
go func() { c.Run(ctx); close(done) }()
waitFor(t, func() bool {
replies := cp.snapshotReplies()
return len(replies) >= 2 && len(replies[1]) == 1
}, "the reply to ride the second poll")
waitFor(t, func() bool { return len(repliesFor(cp, "cmd-1")) > 0 }, "the reply to ride a later poll")
cancel()
<-done
replies := cp.snapshotReplies()
if len(replies[0]) != 0 {
if replies := cp.snapshotReplies(); len(replies[0]) != 0 {
t.Errorf("first poll carried replies %+v, want none", replies[0])
}
if got := replies[1][0]; got.CommandID != "cmd-1" || got.Status != rdsinstance.CommandStatusSucceeded {
t.Errorf("second poll carried %+v, want the succeeded reply for cmd-1", got)
if got := repliesFor(cp, "cmd-1")[0]; got.Status != rdsinstance.CommandStatusSucceeded {
t.Errorf("the poll carried %+v, want the succeeded reply for cmd-1", got)
}
}
@@ -141,16 +140,19 @@ func TestCommander_RetainsAndRetriesTheCompletePendingBatch(t *testing.T) {
done = make(chan struct{})
go func() { c.Run(ctx); close(done) }()
waitFor(t, func() bool {
return len(cp.snapshotReplies()) >= 3
}, "the retained batch to succeed and the new reply to reach the following poll")
return len(repliesFor(cp, "cmd-3")) > 0
}, "the retained batch to succeed and the new reply to reach a later poll")
cancel()
<-done
replies = cp.snapshotReplies()
assert.Equal(t, pending, replies[1], "the complete failed batch must be retried in order")
require.Len(t, replies[2], 1)
assert.Equal(t, "cmd-3", replies[2][0].CommandID)
assert.Equal(t, rdsinstance.CommandStatusSucceeded, replies[2][0].Status)
assert.Equal(t, rdsinstance.CommandStatusSucceeded, repliesFor(cp, "cmd-3")[0].Status)
for _, later := range replies[2:] {
for _, reply := range later {
assert.Equal(t, "cmd-3", reply.CommandID, "a batch a poll carried must not be sent again")
}
}
}
// A poll error must not spin the loop: without a backoff a gateway that is down
@@ -171,3 +173,340 @@ func TestCommander_BacksOffAfterAFailedPoll(t *testing.T) {
t.Errorf("polled %d times in 200ms against a broken channel, want 1", polls)
}
}
// A MariaDB statement that commits waits out a held BACKUP STAGE, and the
// release is itself a command. Run one at a time, the release would queue behind
// the statement it is meant to unblock until the hold's own deadline.
func TestCommander_ABlockedCommandDoesNotKeepOutTheRelease(t *testing.T) {
cp := newFakeControlPlane()
cp.pollQueue = [][]rdsinstance.Command{
{{CommandID: "cmd-password", Type: rdsinstance.CommandSetPassword}},
{{CommandID: "cmd-release", Type: rdsinstance.CommandUnquiesce}},
}
released := make(chan struct{})
registry := commandRegistry{
rdsinstance.CommandSetPassword: func(ctx context.Context, _ rdsinstance.Command) (string, error) {
select {
case <-released:
return "", nil
case <-ctx.Done():
return "", ctx.Err()
}
},
rdsinstance.CommandUnquiesce: func(context.Context, rdsinstance.Command) (string, error) {
close(released)
return "", nil
},
}
c := newCommander(cp, registry, 10*time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done := make(chan struct{})
go func() { c.Run(ctx); close(done) }()
waitFor(t, func() bool {
return len(repliesFor(cp, "cmd-password")) > 0 && len(repliesFor(cp, "cmd-release")) > 0
}, "both the release and the command it unblocked to be answered")
cancel()
<-done
for _, id := range []string{"cmd-password", "cmd-release"} {
assert.Equal(t, rdsinstance.CommandStatusSucceeded, repliesFor(cp, id)[0].Status, id)
}
}
// The issuer re-publishes until it has a reply, so a command still running is
// delivered again. Running the copy would rotate a password twice or open a
// second backup alongside the first.
func TestCommander_ARepublishedCommandRunsOnce(t *testing.T) {
cp := newFakeControlPlane()
cmd := rdsinstance.Command{CommandID: "cmd-1", Type: "reload-parameters"}
cp.pollQueue = [][]rdsinstance.Command{{cmd}, {cmd}}
var mu sync.Mutex
runs := 0
secondDelivered := make(chan struct{})
registry := commandRegistry{
"reload-parameters": func(ctx context.Context, _ rdsinstance.Command) (string, error) {
mu.Lock()
runs++
mu.Unlock()
select {
case <-secondDelivered:
case <-ctx.Done():
}
return "done", nil
},
}
c := newCommander(cp, registry, 10*time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done := make(chan struct{})
go func() { c.Run(ctx); close(done) }()
// The third poll means both copies have been handed to the commander.
waitFor(t, func() bool { return len(cp.snapshotReplies()) >= 3 }, "both copies to be delivered")
close(secondDelivered)
waitFor(t, func() bool { return len(repliesFor(cp, "cmd-1")) > 0 }, "the reply")
cancel()
<-done
mu.Lock()
defer mu.Unlock()
assert.Equal(t, 1, runs, "a re-published copy of a running command must not run again")
}
// Every reply to id carried on any poll so far.
func repliesFor(cp *fakeControlPlane, id string) []rdsinstance.CommandReply {
var out []rdsinstance.CommandReply
for _, batch := range cp.snapshotReplies() {
for _, reply := range batch {
if reply.CommandID == id {
out = append(out, reply)
}
}
}
return out
}
// A copy can arrive after the handler has returned but before a poll has
// carried its reply. The in-flight set has already let go of it then, so only
// the completed set stops it running a second time.
func TestCommander_ACopyArrivingBeforeTheReplyIsCarriedDoesNotRunAgain(t *testing.T) {
var mu sync.Mutex
runs := map[string]int{}
handler := func(_ context.Context, cmd rdsinstance.Command) (string, error) {
mu.Lock()
runs[cmd.CommandID]++
mu.Unlock()
return "", nil
}
c := newCommander(nil, commandRegistry{"reload-parameters": handler}, time.Second)
ctx := t.Context()
go c.serveSerial(ctx)
first := rdsinstance.Command{CommandID: "cmd-1", Type: "reload-parameters"}
c.dispatch(ctx, first)
waitFor(t, func() bool { return len(c.pendingReplies()) == 1 }, "the first run's reply to be pending")
c.dispatch(ctx, first)
// The lane is FIFO, so once this one has answered a queued copy would have run.
c.dispatch(ctx, rdsinstance.Command{CommandID: "cmd-2", Type: "reload-parameters"})
waitFor(t, func() bool {
return slices.ContainsFunc(c.pendingReplies(), func(r rdsinstance.CommandReply) bool { return r.CommandID == "cmd-2" })
}, "the following command's reply")
mu.Lock()
defer mu.Unlock()
assert.Equal(t, 1, runs["cmd-1"], "a copy arriving before the reply was carried must not run")
assert.Len(t, c.pendingReplies(), 2, "the copy must not be answered a second time either")
}
// A quiesce that waited out its issuer's budget behind another command would
// put the engine in backup mode for a snapshot nobody is taking.
func TestCommander_AStaleQuiesceNeverTakesAHold(t *testing.T) {
cp := newFakeControlPlane()
cp.pollQueue = [][]rdsinstance.Command{
{{CommandID: "cmd-apply", Type: rdsinstance.CommandApplyParams}},
{{CommandID: "cmd-quiesce", Type: rdsinstance.CommandQuiesce, Parameters: []rdsinstance.Parameter{
{Name: rdsinstance.CommandParamQuiesceLabel, Value: "orders-db-automated"},
{Name: rdsinstance.CommandParamQuiesceDeadlineSeconds, Value: "360"},
}}},
}
engine := &fakeEngine{}
registry := newCommandRegistry(engine, &fakeStorage{})
applying, release := make(chan struct{}), make(chan struct{})
registry[rdsinstance.CommandApplyParams] = func(ctx context.Context, _ rdsinstance.Command) (string, error) {
close(applying)
<-release
return "", nil
}
c := newCommander(cp, registry, 10*time.Millisecond)
c.budget = func(commandType string) time.Duration {
if commandType == rdsinstance.CommandQuiesce {
return 50 * time.Millisecond
}
return controlPlaneBudget(commandType)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done := make(chan struct{})
go func() { c.Run(ctx); close(done) }()
<-applying
waitFor(t, func() bool { return len(cp.snapshotReplies()) >= 3 }, "the quiesce to be delivered behind the apply")
time.Sleep(100 * time.Millisecond)
close(release)
waitFor(t, func() bool { return len(repliesFor(cp, "cmd-quiesce")) > 0 }, "the quiesce to be answered")
cancel()
<-done
reply := repliesFor(cp, "cmd-quiesce")[0]
assert.Equal(t, rdsinstance.CommandStatusFailed, reply.Status)
assert.Contains(t, reply.Message, "expired")
assert.Empty(t, engine.label, "an expired quiesce must never reach the engine")
}
// Engine commands still run one at a time: a parameter apply rewrites the
// option file a graceful stop would otherwise race.
func TestCommander_AParameterApplyNeverRunsAlongsideAnEngineStop(t *testing.T) {
cp := newFakeControlPlane()
cp.pollQueue = [][]rdsinstance.Command{
{{CommandID: "cmd-apply", Type: rdsinstance.CommandApplyParams}},
{{CommandID: "cmd-stop", Type: rdsinstance.CommandStopEngine}},
}
var mu sync.Mutex
active, most := 0, 0
release := make(chan struct{})
// Each holds the lane until released, so two running at once are both seen
// whichever is scheduled first.
engineWork := func(context.Context, rdsinstance.Command) (string, error) {
mu.Lock()
active++
most = max(most, active)
mu.Unlock()
<-release
mu.Lock()
active--
mu.Unlock()
return "", nil
}
registry := commandRegistry{
rdsinstance.CommandApplyParams: engineWork,
rdsinstance.CommandStopEngine: engineWork,
}
c := newCommander(cp, registry, 10*time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done := make(chan struct{})
go func() { c.Run(ctx); close(done) }()
waitFor(t, func() bool { return len(cp.snapshotReplies()) >= 3 }, "the stop to be delivered behind the apply")
time.Sleep(50 * time.Millisecond)
close(release)
waitFor(t, func() bool { return len(repliesFor(cp, "cmd-stop")) > 0 }, "the stop to be answered")
cancel()
<-done
mu.Lock()
defer mu.Unlock()
assert.Equal(t, 1, most, "the engine stop ran while the parameter apply was still running")
}
// The agent bounds each command by its issuer's budget, so a type the control
// plane has no budget for would run on a guess.
func TestCommandRegistry_EveryTypeHasAControlPlaneBudget(t *testing.T) {
for commandType := range newCommandRegistry(&fakeEngine{}, &fakeStorage{}) {
if _, ok := rdsinstance.CommandBudget(commandType); !ok {
t.Errorf("%s has no control-plane budget", commandType)
}
}
}
func (c *commander) pendingReplies() []rdsinstance.CommandReply {
c.mu.Lock()
defer c.mu.Unlock()
return slices.Clone(c.pending)
}
// The first copy can reach the agent late, after a gateway or bus outage, with
// its issuer about to give up. A quiesce granted a fresh budget then would take
// a hold nobody is left to release.
func TestCommander_AQuiesceStampedNearlyOutOfBudgetNeverTakesAHold(t *testing.T) {
cp := newFakeControlPlane()
cp.pollQueue = [][]rdsinstance.Command{
{{CommandID: "cmd-apply", Type: rdsinstance.CommandApplyParams}},
{{CommandID: "cmd-quiesce", Type: rdsinstance.CommandQuiesce, RemainingBudgetMs: 50, Parameters: []rdsinstance.Parameter{
{Name: rdsinstance.CommandParamQuiesceLabel, Value: "orders-db-automated"},
{Name: rdsinstance.CommandParamQuiesceDeadlineSeconds, Value: "360"},
}}},
}
engine := &fakeEngine{}
registry := newCommandRegistry(engine, &fakeStorage{})
applying, release := make(chan struct{}), make(chan struct{})
registry[rdsinstance.CommandApplyParams] = func(context.Context, rdsinstance.Command) (string, error) {
close(applying)
<-release
return "", nil
}
c := newCommander(cp, registry, 10*time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done := make(chan struct{})
go func() { c.Run(ctx); close(done) }()
<-applying
waitFor(t, func() bool { return len(cp.snapshotReplies()) >= 3 }, "the quiesce to be delivered behind the apply")
// The quiesce was received before the third poll began, so its stamped budget
// has run out 50ms after this point.
queuedAt := time.Now()
waitFor(t, func() bool { return time.Since(queuedAt) > 50*time.Millisecond }, "the stamped budget to pass")
close(release)
waitFor(t, func() bool { return len(repliesFor(cp, "cmd-quiesce")) > 0 }, "the quiesce to be answered")
cancel()
<-done
reply := repliesFor(cp, "cmd-quiesce")[0]
assert.Equal(t, rdsinstance.CommandStatusFailed, reply.Status)
assert.Contains(t, reply.Message, "expired")
assert.Empty(t, engine.label, "a quiesce whose issuer had all but given up must never reach the engine")
}
// A full lane refuses at once rather than queueing work its issuer will not
// outlive, and the refusal is the command's answer: a re-published copy must
// not slip in once the lane has room.
func TestCommander_AFullLaneRefusesAtOnceAndNeverRunsTheCommand(t *testing.T) {
var mu sync.Mutex
runs := map[string]int{}
running, release := make(chan struct{}, 1), make(chan struct{})
handler := func(_ context.Context, cmd rdsinstance.Command) (string, error) {
mu.Lock()
runs[cmd.CommandID]++
mu.Unlock()
if cmd.CommandID == "cmd-blocker" {
running <- struct{}{}
<-release
}
return "", nil
}
c := newCommander(nil, commandRegistry{"reload-parameters": handler}, time.Second)
ctx := t.Context()
go c.serveSerial(ctx)
c.dispatch(ctx, rdsinstance.Command{CommandID: "cmd-blocker", Type: "reload-parameters"})
<-running
for i := range serialQueueDepth {
c.dispatch(ctx, rdsinstance.Command{CommandID: fmt.Sprintf("cmd-queued-%d", i), Type: "reload-parameters"})
}
overflow := rdsinstance.Command{CommandID: "cmd-overflow", Type: "reload-parameters"}
c.dispatch(ctx, overflow)
refused := slices.IndexFunc(c.pendingReplies(), func(r rdsinstance.CommandReply) bool { return r.CommandID == overflow.CommandID })
require.GreaterOrEqual(t, refused, 0, "a full lane must answer at once, before anything ahead of it finishes")
assert.Equal(t, rdsinstance.CommandStatusFailed, c.pendingReplies()[refused].Status)
assert.Contains(t, c.pendingReplies()[refused].Message, "busy")
close(release)
last := fmt.Sprintf("cmd-queued-%d", serialQueueDepth-1)
waitFor(t, func() bool {
return slices.ContainsFunc(c.pendingReplies(), func(r rdsinstance.CommandReply) bool { return r.CommandID == last })
}, "the queue to drain")
c.dispatch(ctx, overflow)
// FIFO again: once this answers, a copy let onto the lane would have run.
c.dispatch(ctx, rdsinstance.Command{CommandID: "cmd-after", Type: "reload-parameters"})
waitFor(t, func() bool {
return slices.ContainsFunc(c.pendingReplies(), func(r rdsinstance.CommandReply) bool { return r.CommandID == "cmd-after" })
}, "the command after the re-published copy")
mu.Lock()
defer mu.Unlock()
assert.Zero(t, runs[overflow.CommandID], "a refused command must never run")
answers := 0
for _, r := range c.pendingReplies() {
if r.CommandID == overflow.CommandID {
answers++
}
}
assert.Equal(t, 1, answers, "a re-published copy of a refused command must be ignored, not answered again")
}
+37 -9
View File
@@ -94,6 +94,8 @@ type mariadbEngine struct {
socket string
rcService string
service string
// How long a password rotation waits for a backup hold to end.
holdWait time.Duration
}
var _ engine = (*mariadbEngine)(nil)
@@ -151,6 +153,7 @@ func newMariaDBEngine(cfg Config, rules controlPlaneRules, run commandRunner, st
socket: mariadbSocketPath(cfg),
rcService: cfg.RCService,
service: cfg.EngineService,
holdWait: mariadbPasswordHoldWait,
parameterManager: parameterManager{
probe: probe,
params: parameterStore{
@@ -380,6 +383,11 @@ SET SESSION slow_query_log = 0;
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
`
// ALTER USER can take effect in memory and then wait at its commit for a held
// BACKUP STAGE to end. Waiting for the agent's own hold before the statement, for
// less than the control plane's budget, keeps that hold from half-applying it.
const mariadbPasswordHoldWait = 20 * time.Second
// Rotates the master's password. The statement is built here rather than by the
// client, which has neither psql's identifier interpolation nor its parameter
// quoting, and it rides stdin so it is never visible in the process table.
@@ -395,16 +403,34 @@ func (e *mariadbEngine) SetPassword(ctx context.Context, username, password stri
return fmt.Errorf("refusing to set the password of role %q: %w", username, err)
}
// Only the agent's own backup hold is waited out before the statement. A lock
// someone else holds, such as a customer FTWRL, is met inside it and ended by
// lock_wait_timeout, by which point the password may already have changed.
escaped := sqlLiteral(password)
sql := fmt.Sprintf("%sALTER USER '%s'@'%s' IDENTIFIED BY '%s';\n",
mariadbSessionGuard, username, mariadbMasterHost, escaped)
if _, err := e.clientRun(ctx, sql); err != nil {
// The client echoes the failing statement, which carries the escaped form
// of the password rather than the raw one — so redacting only the raw one
// would leak exactly the passwords that needed escaping.
return fmt.Errorf("apply the master password: %s", redact(redact(err.Error(), password), escaped))
return e.outsideHold(ctx, e.holdWait, func() error {
// Computed after the hold wait, so the statement gets only what is left.
sql := fmt.Sprintf("%sSET SESSION lock_wait_timeout = %d;\nALTER USER '%s'@'%s' IDENTIFIED BY '%s';\n",
mariadbSessionGuard, statementLockWait(ctx), username, mariadbMasterHost, escaped)
if _, err := e.clientRun(ctx, sql); err != nil {
// The client echoes the failing statement, which carries the escaped form
// of the password rather than the raw one — so redacting only the raw one
// would leak exactly the passwords that needed escaping.
return fmt.Errorf("apply the master password: %s", redact(redact(err.Error(), password), escaped))
}
return nil
})
}
// The server-side lock wait for a statement, in whole seconds: what remains of
// ctx less a margin for the reply, so the server gives up its wait before the
// client is killed. A ctx with no deadline gets the full password budget.
func statementLockWait(ctx context.Context) int {
const replyMargin = 2 * time.Second
remaining := mariadbPasswordHoldWait
if deadline, ok := ctx.Deadline(); ok {
remaining = time.Until(deadline) - replyMargin
}
return nil
return max(1, int(remaining.Seconds()))
}
// Installs the resolved set and applies the half a running server can adopt.
@@ -714,7 +740,9 @@ func (e *mariadbEngine) Quiesce(ctx context.Context, label string, hold time.Dur
// Held across the whole start, so a second quiesce waits and then finds the
// first one's hold rather than opening a concurrent backup alongside it.
e.mu.Lock()
if err := e.lockWithin(ctx); err != nil {
return err
}
defer e.mu.Unlock()
if e.held != nil {
return fmt.Errorf("the engine is already quiesced for backup %s", e.held.label)
@@ -1151,3 +1151,123 @@ func TestMariaDBEngine_EveryResolvedDynamicValueRenders(t *testing.T) {
}
}
}
// ALTER USER under a held BACKUP STAGE swaps the password in memory and then
// waits at its commit, so a rotation issued mid-backup must not reach the
// engine until the hold is released.
func TestMariaDBEngine_SetPasswordWaitsForTheBackupHoldToEnd(t *testing.T) {
runner := &recordingRunner{}
engine := newTestMariaDBEngine(t, runner.run)
engine.startSess = func(context.Context, command) (engineSession, error) { return &fakeSession{}, nil }
if err := engine.Quiesce(context.Background(), "orders-db-automated", time.Minute); err != nil {
t.Fatalf("Quiesce: %v", err)
}
rotated := make(chan error, 1)
go func() { rotated <- engine.SetPassword(context.Background(), "mulgamaster", "n3w-pw") }()
select {
case err := <-rotated:
t.Fatalf("SetPassword returned %v while the engine was held for a backup", err)
case <-time.After(3 * holdPollInterval):
}
if err := engine.Unquiesce(context.Background()); err != nil {
t.Fatalf("Unquiesce: %v", err)
}
select {
case err := <-rotated:
if err != nil {
t.Fatalf("SetPassword after the release: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("SetPassword did not run once the hold was released")
}
if len(runner.calls) != 1 || !strings.Contains(runner.calls[0].Stdin, "ALTER USER") {
t.Errorf("ran %d commands, want the one rotation after the release", len(runner.calls))
}
}
// A hold that outlasts the wait fails the rotation before anything is sent, so
// the control plane's error is the truth rather than half of it.
func TestMariaDBEngine_SetPasswordFailsUntouchedWhenTheHoldOutlastsItsWait(t *testing.T) {
runner := &recordingRunner{}
engine := newTestMariaDBEngine(t, runner.run)
engine.holdWait = 3 * holdPollInterval
engine.startSess = func(context.Context, command) (engineSession, error) { return &fakeSession{}, nil }
if err := engine.Quiesce(context.Background(), "orders-db-automated", time.Minute); err != nil {
t.Fatalf("Quiesce: %v", err)
}
if err := engine.SetPassword(context.Background(), "mulgamaster", "n3w-pw"); err == nil {
t.Fatal("SetPassword succeeded while the engine stayed held for a backup")
}
if len(runner.calls) != 0 {
t.Errorf("ran %d commands against a held engine, want none", len(runner.calls))
}
}
// The wait has to end before the control plane gives up on the command, or the
// rotation can still land after the caller was told it failed.
func TestMariaDBEngine_PasswordHoldWaitFitsInsideTheControlPlaneTimeout(t *testing.T) {
budget, ok := rdsinstance.CommandBudget(rdsinstance.CommandSetPassword)
if !ok {
t.Fatal("the control plane has no budget for set-password")
}
if mariadbPasswordHoldWait >= budget-5*time.Second {
t.Errorf("a %s hold wait leaves under 5s of the control plane's %s set-password budget for the statement", mariadbPasswordHoldWait, budget)
}
}
// The statement is bounded by what is left of the command, so the server gives
// up a lock wait before the client is killed under it.
func TestMariaDBEngine_SetPasswordBoundsTheStatementByTheRemainingBudget(t *testing.T) {
runner := &recordingRunner{}
engine := newTestMariaDBEngine(t, runner.run)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := engine.SetPassword(ctx, "mulgamaster", "n3w-pw"); err != nil {
t.Fatalf("SetPassword: %v", err)
}
sql := runner.calls[0].Stdin
at := strings.Index(sql, "SET SESSION lock_wait_timeout = ")
if at < 0 || at > strings.Index(sql, "ALTER USER") {
t.Fatalf("SQL %q does not bound the statement's lock wait before it runs", sql)
}
var seconds int
if _, err := fmt.Sscanf(sql[at:], "SET SESSION lock_wait_timeout = %d;", &seconds); err != nil {
t.Fatalf("parse the lock wait: %v", err)
}
if seconds < 1 || seconds > 8 {
t.Errorf("lock wait = %ds with 10s of budget left, want it inside the budget less the reply margin", seconds)
}
}
// A quiesce that cannot get the hold bookkeeping must give up with its command,
// not wait on the mutex after its issuer has moved on.
func TestMariaDBEngine_QuiesceGivesUpWaitingForTheBookkeepingWithItsContext(t *testing.T) {
engine := newTestMariaDBEngine(t, (&recordingRunner{}).run)
started := 0
engine.startSess = func(context.Context, command) (engineSession, error) {
started++
return &fakeSession{}, nil
}
engine.mu.Lock()
defer engine.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 3*holdPollInterval)
defer cancel()
done := make(chan error, 1)
go func() { done <- engine.Quiesce(ctx, "orders-db-automated", time.Minute) }()
select {
case err := <-done:
if err == nil {
t.Fatal("Quiesce succeeded without the bookkeeping lock")
}
case <-time.After(5 * time.Second):
t.Fatal("Quiesce waited on the bookkeeping past its context")
}
if started != 0 {
t.Errorf("opened %d backup sessions, want none", started)
}
}
+3 -1
View File
@@ -516,7 +516,9 @@ func (e *postgresEngine) Quiesce(ctx context.Context, label string, hold time.Du
// Held across the whole start, so a second quiesce waits and then finds the
// first one's hold rather than opening a concurrent backup alongside it.
e.mu.Lock()
if err := e.lockWithin(ctx); err != nil {
return err
}
defer e.mu.Unlock()
if e.held != nil {
return fmt.Errorf("the engine is already quiesced for backup %s", e.held.label)
+42
View File
@@ -114,6 +114,48 @@ func (q *quiesceState) releaseHold(ctx context.Context, releaseSQL string) error
return nil
}
// Takes mu, giving up when ctx ends. A quiesce that cannot get the bookkeeping
// inside its budget must fail rather than start a backup its issuer abandoned.
func (q *quiesceState) lockWithin(ctx context.Context) error {
for !q.mu.TryLock() {
select {
case <-ctx.Done():
return fmt.Errorf("wait for the backup bookkeeping: %w", ctx.Err())
case <-time.After(holdPollInterval):
}
}
return nil
}
// How often a statement waiting for a backup hold to end looks again.
const holdPollInterval = 100 * time.Millisecond
// Runs fn while no backup hold is on the engine, and keeps a new one from
// starting until it returns. A hold that outlasts wait fails the call before fn
// has touched the engine.
func (q *quiesceState) outsideHold(ctx context.Context, wait time.Duration, fn func() error) error {
deadline := time.NewTimer(wait)
defer deadline.Stop()
for {
// Not Lock: a quiesce holds mu while its stages wait on their own locks,
// and this wait has to stay bounded by ctx and wait.
if q.mu.TryLock() {
if q.held == nil {
defer q.mu.Unlock()
return fn()
}
q.mu.Unlock()
}
select {
case <-ctx.Done():
return ctx.Err()
case <-deadline.C:
return fmt.Errorf("the engine is still held for a backup after %s", wait)
case <-time.After(holdPollInterval):
}
}
}
// The deadline. Ending the session is enough — both engines release the hold
// with it — so this never has to reach the engine itself.
func (q *quiesceState) expire(label string) {
+33 -3
View File
@@ -5,6 +5,7 @@ package config
import (
"fmt"
"log/slog"
"maps"
"net/netip"
"os"
"path/filepath"
@@ -355,6 +356,11 @@ type EBSConfig struct {
CacheSizeMB *int `json:"CacheSizeMB" mapstructure:"cache_size_mb"`
}
// SupportedEBSProvider reports whether name is a provider a node may run.
func SupportedEBSProvider(name string) bool {
return name == EBSProviderViperblockd || name == EBSProviderQEMUNBD
}
// ResolvedProvider normalizes an empty Provider to EBSProviderViperblockd,
// the default provider.
func (c EBSConfig) ResolvedProvider() string {
@@ -801,6 +807,27 @@ func validateVultrPool(cc *ClusterConfig, p ExternalPool) error {
return nil
}
// validateSingleEBSProvider refuses nodes whose explicit [nodes.<name>.ebs]
// providers differ. A peer stanza without one is unknown, not the default: the
// generated config omits it, and the cluster's KV lock is the authoritative check.
func validateSingleEBSProvider(cc *ClusterConfig) error {
var first, want string
for _, name := range slices.Sorted(maps.Keys(cc.Nodes)) {
if !viper.IsSet("nodes." + name + ".ebs.provider") {
continue
}
got := cc.Nodes[name].EBS.ResolvedProvider()
if first == "" {
first, want = name, got
continue
}
if got != want {
return fmt.Errorf("config: [nodes.%s.ebs] provider resolves to %q but [nodes.%s.ebs] resolves to %q; every node in a cluster must use the same EBS provider", first, want, name, got)
}
}
return nil
}
func validateClusterConfig(cc *ClusterConfig) error {
if viper.IsSet("network.external_dhcp") {
return fmt.Errorf("config: [network] external_dhcp is no longer supported; remove the key (static WAN-pool allocation only)")
@@ -809,9 +836,9 @@ func validateClusterConfig(cc *ClusterConfig) error {
if viper.IsSet("nodes." + nodeName + ".vpcd.dhcp_bind_bridge") {
return fmt.Errorf("config: [nodes.%s.vpcd] dhcp_bind_bridge is no longer supported; remove the key (vpcd no longer runs a DHCP client)", nodeName)
}
switch nodeCfg.EBS.Provider {
case "", EBSProviderViperblockd, EBSProviderQEMUNBD:
case EBSProviderEmbedded:
switch {
case nodeCfg.EBS.Provider == "", SupportedEBSProvider(nodeCfg.EBS.Provider):
case nodeCfg.EBS.Provider == EBSProviderEmbedded:
// Refuse rather than silently upgrade: the embedded engine is gone,
// and starting anyway would migrate this node's volumes to
// ebsmetadata one-way without the operator ever asking for it.
@@ -829,6 +856,9 @@ func validateClusterConfig(cc *ClusterConfig) error {
return fmt.Errorf("config: [nodes.%s.ebs] cache_size_mb=%d must not be negative; use 0 to disable the cache, or remove the key for the default of %d", nodeName, *c, DefaultCacheSizeMB)
}
}
if err := validateSingleEBSProvider(cc); err != nil {
return err
}
if err := validateNorthstarCluster(cc); err != nil {
return err
+39
View File
@@ -1108,6 +1108,45 @@ provider = "bogus"
assert.Contains(t, err.Error(), `provider="bogus"`)
}
func TestLoadConfig_EBSProvider_SingleProviderPerCluster(t *testing.T) {
stanza := func(node, provider string) string {
return fmt.Sprintf("[nodes.%s.ebs]\nprovider = %q\n", node, provider)
}
cases := []struct {
name string
ebs []string
wantErr string
}{
{"all unset", []string{"", "", ""}, ""},
{"explicit viperblockd beside unset peers", []string{"", stanza("n2", EBSProviderViperblockd), ""}, ""},
{"explicit qemunbd beside unset peers", []string{stanza("n1", EBSProviderQEMUNBD), "", ""}, ""},
{"all explicit qemunbd", []string{stanza("n1", EBSProviderQEMUNBD), stanza("n2", EBSProviderQEMUNBD), stanza("n3", EBSProviderQEMUNBD)}, ""},
{"two explicit providers differ", []string{stanza("n1", EBSProviderQEMUNBD), stanza("n2", EBSProviderViperblockd), ""},
`[nodes.n1.ebs] provider resolves to "qemunbd" but [nodes.n2.ebs] resolves to "viperblockd"`},
{"only the third node differs", []string{stanza("n1", EBSProviderViperblockd), stanza("n2", EBSProviderViperblockd), stanza("n3", EBSProviderQEMUNBD)},
`[nodes.n1.ebs] provider resolves to "viperblockd" but [nodes.n3.ebs] resolves to "qemunbd"`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
body := "node = \"n1\"\n"
for i, ebs := range tc.ebs {
body += fmt.Sprintf("\n[nodes.n%d]\nregion = \"us-east-1\"\n%s", i+1, ebs)
}
resetViper(t)
path := filepath.Join(t.TempDir(), "spinifex.toml")
require.NoError(t, os.WriteFile(path, []byte(body), 0600))
_, err := LoadConfig(path)
if tc.wantErr == "" {
require.NoError(t, err)
return
}
require.Error(t, err)
assert.Contains(t, err.Error(), tc.wantErr)
})
}
}
func TestEBSConfig_ResolvedTunablesDefault(t *testing.T) {
var c EBSConfig
assert.Equal(t, DefaultNBDKitThreads, c.ResolvedThreads())
+3 -2
View File
@@ -201,8 +201,9 @@ type PollDBCommandsInput struct {
Replies []rdsinstance.CommandReply `locationName:"Replies" locationNameList:"member"`
}
// PollDBCommandsOutput holds at most one command per poll: each is a discrete guest operation the
// agent must complete and report before the next is safe to issue.
// PollDBCommandsOutput holds at most one command per poll. The agent runs engine commands one at a
// time in arrival order and answers on a later poll; only unquiesce runs beside them, so it can release
// a backup hold a queued command is waiting on. A command that outlives its type's budget is not run.
type PollDBCommandsOutput struct {
Commands []rdsinstance.Command `locationName:"Commands" locationNameList:"member"`
}
@@ -112,6 +112,9 @@ func TestDescribeDBEngineVersions_AppliesTypedParametersAndFilters(t *testing.T)
{"status filter", map[string]string{
"Filters.Filter.1.Name": "status", "Filters.Filter.1.Values.Value.1": "available",
}, rdsengine.SupportedEngines()},
{"engine filter with empty values", map[string]string{
"Filters.Filter.1.Name": "engine", "Filters.Filter.1.Values": "",
}, rdsengine.SupportedEngines()},
// A query for a row that does not exist is empty; only a request to build
// something that cannot exist is refused.
{"unpinned version", map[string]string{"EngineVersion": "17"}, []string{}},
@@ -230,8 +233,6 @@ func TestDescribeCatalogs_RejectMalformedFilters(t *testing.T) {
}{
{"no values", map[string]string{"Filters.Filter.1.Name": "engine"},
awserrors.ErrorInvalidParameterCombination, "The values list cannot be null for the filter engine."},
{"empty values", map[string]string{"Filters.Filter.1.Name": "engine", "Filters.Filter.1.Values": ""},
awserrors.ErrorInvalidParameterCombination, "The values list cannot be null for the filter engine."},
{"no name", map[string]string{"Filters.Filter.1.Values.Value.1": "postgres"},
awserrors.ErrorInvalidParameterValue, "Unrecognized filter name: null"},
{"name case", map[string]string{"Filters.Filter.1.Name": "Engine", "Filters.Filter.1.Values.Value.1": "postgres"},
+2 -2
View File
@@ -213,8 +213,8 @@ func TestMariaDBCatalog_RejectsBadValues(t *testing.T) {
cases := []struct {
name, param, value, want string
}{
{"UnknownName", "not_a_setting", "1", "is not a parameter this engine exposes"},
{"PostgresSetting", "work_mem", "16384", "is not a parameter this engine exposes"},
{"UnknownName", "not_a_setting", "1", "Could not find parameter with name: "},
{"PostgresSetting", "work_mem", "16384", "Could not find parameter with name: "},
{"NotAnInteger", "max_connections", "many", "takes an integer"},
{"BelowRange", "max_connections", "1", "outside its allowed range"},
{"BufferPoolBelowMinimum", "innodb_buffer_pool_size", "1048576", "outside its allowed range"},
+1 -1
View File
@@ -219,7 +219,7 @@ func (e Engine) ValidateParameterValue(name, value string) (ParameterSpec, error
spec, ok := e.LookupParameter(name)
if !ok {
return ParameterSpec{}, awserrors.Errorf(awserrors.ErrorInvalidParameterValue,
"%q is not a parameter this engine exposes", name)
"Could not find parameter with name: %s", name)
}
if !spec.IsModifiable {
return ParameterSpec{}, awserrors.Errorf(awserrors.ErrorInvalidParameterValue,
@@ -169,7 +169,7 @@ func TestValidateParameterValue_RejectsBadInput(t *testing.T) {
cases := []struct {
name, param, value, want string
}{
{"UnknownName", "not_a_setting", "1", "is not a parameter this engine exposes"},
{"UnknownName", "not_a_setting", "1", "Could not find parameter with name: "},
{"NotAnInteger", "max_connections", "many", "takes an integer"},
{"BelowRange", "max_connections", "1", "outside its allowed range"},
{"AboveRange", "max_connections", "500000", "outside its allowed range"},
+4
View File
@@ -137,6 +137,10 @@ type Command struct {
Type string `json:"type" locationName:"Type"`
Parameters []Parameter `json:"parameters,omitempty" locationName:"Parameters" locationNameList:"member" xml:"Parameters>member"`
IssuedAt *time.Time `json:"issuedAt,omitempty" locationName:"IssuedAt" type:"timestamp"`
// How much of the issuer's budget was left when this copy was published. A
// duration rather than a deadline, so the guest needs no clock agreement with
// the host; zero means the issuer predates the field.
RemainingBudgetMs int64 `json:"remainingBudgetMs,omitempty" locationName:"RemainingBudgetMs"`
}
// CommandReply is the agent's result for a command from an earlier poll, carried on the next poll
+26 -4
View File
@@ -75,6 +75,24 @@ const (
commandRepublishEvery = 2 * time.Second
)
// How long the control plane waits for each command type by default. The agent
// reads the same table, so it never starts work its issuer has stopped waiting for.
var commandBudgets = map[string]time.Duration{
CommandSetPassword: setPasswordTimeout,
CommandApplyParams: defaultApplyParamsTimeout,
CommandStopEngine: stopEngineTimeout,
CommandGrowFilesystem: growFilesystemTimeout,
CommandQuiesce: quiesceTimeout,
CommandUnquiesce: unquiesceTimeout,
}
// CommandBudget returns how long the control plane waits for a reply to a
// command of this type, and false for a type it never issues.
func CommandBudget(commandType string) (time.Duration, bool) {
budget, ok := commandBudgets[commandType]
return budget, ok
}
// ErrCommandUnreachable means the agent was unreachable or missed the command's
// budget. Callers that can degrade — the graceful engine stop — check for this;
// callers that must not, like a password rotation, surface it as retryable.
@@ -152,10 +170,6 @@ func (s *Service) issueCommand(ctx context.Context, accountID, dbInstanceIdentif
Parameters: params,
IssuedAt: &issuedAt,
}
data, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
// Subscribed before the first publish, so a reply cannot land in the gap
// between the command going out and the issuer starting to listen.
@@ -173,7 +187,15 @@ func (s *Service) issueCommand(ctx context.Context, accountID, dbInstanceIdentif
defer cancel()
subject := BusCommandSubject(accountID, dbInstanceIdentifier)
deadline, _ := deadlineCtx.Deadline()
for {
// Stamped per copy, so a copy that reaches the agent late carries only what
// its issuer has left rather than a whole fresh budget.
cmd.RemainingBudgetMs = max(time.Until(deadline).Milliseconds(), 1)
data, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
if err := s.nc.Publish(subject, data); err != nil {
return nil, fmt.Errorf("rds: publish %s command to %s: %w", commandType, dbInstanceIdentifier, err)
}
@@ -2,6 +2,7 @@ package instance
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -80,3 +81,26 @@ func TestIssueCommand_CorrelatesTheReplyByCommandID(t *testing.T) {
require.NotEmpty(t, issued)
assert.Equal(t, issued[0].CommandID, reply.CommandID)
}
// Each copy carries what its issuer has left, so a copy that reaches the agent
// late cannot be granted a whole budget its issuer is about to give up on.
func TestIssueCommand_StampsEachCopyWithTheBudgetLeft(t *testing.T) {
t.Parallel()
h := newLifecycleHarness(t, false)
h.agent.silenceType(CommandQuiesce)
const budget = 4500 * time.Millisecond
_, err := h.svc.issueCommand(t.Context(), testAccountID, testDBID, CommandQuiesce, budget, nil)
require.ErrorIs(t, err, ErrCommandUnreachable)
issued := h.agent.received()
require.GreaterOrEqual(t, len(issued), 2, "the issuer must have re-published at least once")
for i, copied := range issued {
assert.Positive(t, copied.RemainingBudgetMs, "copy %d carries no remaining budget", i)
assert.LessOrEqual(t, copied.RemainingBudgetMs, budget.Milliseconds(), "copy %d", i)
if i > 0 {
assert.LessOrEqual(t, copied.RemainingBudgetMs, issued[i-1].RemainingBudgetMs-commandRepublishEvery.Milliseconds()/2,
"copy %d was stamped with as much budget as the copy before it", i)
}
}
}
+2 -3
View File
@@ -2,7 +2,6 @@ package instance
import (
"context"
"errors"
"slices"
"strings"
"unicode/utf8"
@@ -39,7 +38,7 @@ func (s *Service) DescribeDBInstances(ctx context.Context, input *rds.DescribeDB
// A named instance the filters exclude is reported as absent rather than
// returned anyway, so the two halves of one request cannot disagree.
if matches != nil && !matches(rec) {
return nil, errors.New(awserrors.ErrorDBInstanceNotFound)
return nil, awserrors.Errorf(awserrors.ErrorDBInstanceNotFound, "DBInstance %s not found.", id)
}
return &rds.DescribeDBInstancesOutput{DBInstances: []*rds.DBInstance{s.projectDBInstance(rec)}}, nil
}
@@ -134,7 +133,7 @@ func (s *Service) getDBInstance(ctx context.Context, kv *kvstore.Bucket, id stri
return nil, 0, err
}
if !found {
return nil, 0, errors.New(awserrors.ErrorDBInstanceNotFound)
return nil, 0, awserrors.Errorf(awserrors.ErrorDBInstanceNotFound, "DBInstance %s not found.", id)
}
return &rec, rev, nil
}
@@ -61,6 +61,8 @@ func TestDescribeDBInstances_NamedMissingInstanceIsAnError(t *testing.T) {
}, testAccountID)
require.Error(t, err)
assert.Contains(t, err.Error(), awserrors.ErrorDBInstanceNotFound)
_, message, _ := awserrors.ResolveErrorDetail(err)
assert.Equal(t, "DBInstance no-such-db not found.", message)
}
func TestDescribeDBInstances_NamedInstanceProjectsTheRecord(t *testing.T) {
+19 -13
View File
@@ -37,14 +37,29 @@ const (
defaultEventDuration = time.Hour
)
// AWS's SourceType values. Only the ones some phase actually writes are
// defined; an unknown one from a request is rejected rather than matched
// against nothing, which would look like a resource with no history.
// The SourceType values some phase actually writes.
const (
EventSourceTypeDBInstance = "db-instance"
EventSourceTypeDBSnapshot = "db-snapshot"
)
// Every SourceType in AWS's model. A read of one nothing writes is answered with
// no events, as AWS answers a source that emitted none; a value outside the
// model is rejected rather than matched against nothing.
var eventSourceTypes = []string{
"blue-green-deployment",
"custom-engine-version",
"db-cluster",
"db-cluster-snapshot",
EventSourceTypeDBInstance,
"db-parameter-group",
"db-proxy",
"db-security-group",
"db-shard-group",
EventSourceTypeDBSnapshot,
"zero-etl",
}
// AWS's event categories. A customer filters and subscribes on these, so the
// strings are AWS's exactly, spaces included.
const (
@@ -59,15 +74,6 @@ const (
EventCategoryRecovery = "recovery"
)
func validEventSourceType(sourceType string) bool {
switch sourceType {
case EventSourceTypeDBInstance, EventSourceTypeDBSnapshot:
return true
default:
return false
}
}
// Event is one entry in a resource's ring.
type Event struct {
SourceIdentifier string `json:"sourceIdentifier"`
@@ -168,7 +174,7 @@ func (s *Service) DescribeEvents(ctx context.Context, input *rds.DescribeEventsI
}
sourceType := aws.StringValue(input.SourceType)
sourceIdentifier := aws.StringValue(input.SourceIdentifier)
if sourceType != "" && !validEventSourceType(sourceType) {
if sourceType != "" && !slices.Contains(eventSourceTypes, sourceType) {
return nil, awserrors.Errorf(awserrors.ErrorInvalidParameterValue,
"SourceType %q is not an RDS event source", sourceType)
}
+18 -1
View File
@@ -102,6 +102,23 @@ func TestDescribeEvents_ReadsAcrossResourcesAndScopesToOneWhenAsked(t *testing.T
assert.Equal(t, []string{"snapshot event"}, messagesOf(scoped))
}
// AWS accepts every SourceType in its model; one that emits no events reads as
// an empty list, not an error.
func TestDescribeEvents_AcceptsEveryModelSourceTypeWithNoEvents(t *testing.T) {
t.Parallel()
svc := newTestService(t)
seedEvent(t, svc, EventSourceTypeDBInstance, testDBID, time.Now().UTC(), "instance event")
for _, sourceType := range []string{"db-parameter-group", "db-security-group", "db-cluster",
"db-cluster-snapshot", "custom-engine-version", "db-proxy", "blue-green-deployment",
"db-shard-group", "zero-etl"} {
out, err := svc.DescribeEvents(t.Context(),
&rds.DescribeEventsInput{SourceType: aws.String(sourceType), Duration: aws.Int64(60)}, testAccountID)
require.NoError(t, err, sourceType)
assert.Empty(t, out.Events, sourceType)
}
}
// A truncated read carries a Marker, so a client can tell the list was cut and
// resume from it.
func TestDescribeEvents_PagesOldestFirst(t *testing.T) {
@@ -136,7 +153,7 @@ func TestDescribeEvents_RejectsMalformedRequests(t *testing.T) {
SourceIdentifier: aws.String(testDBID),
}, awserrors.ErrorInvalidParameterCombination},
{"UnknownSourceType", &rds.DescribeEventsInput{
SourceType: aws.String("db-cluster"),
SourceType: aws.String("db-table"),
}, awserrors.ErrorInvalidParameterValue},
{"EndBeforeStart", &rds.DescribeEventsInput{
StartTime: aws.Time(time.Now()),
+16 -3
View File
@@ -31,10 +31,17 @@ type Filter struct {
Values []string
}
// AWS refuses an empty value list on these names, each in its own words, and
// accepts one on any other name without narrowing by it.
var emptyValuesRefusals = map[string]string{
filterDBInstanceID: "The list of DB Instance Identifiers must not be empty.",
filterParameterName: "The list of ParameterNames must not be empty.",
filterSnapshotType: "Invalid value '' for filter snapshot-type",
}
// ReadFilters validates Filters against the names one Describe call recognises,
// in AWS's order: an unknown name, compared case-sensitively, before an absent
// value list. The query parser reads an empty list as absent, so both answer
// the same.
// or empty value list.
func ReadFilters(filters []*rds.Filter, recognised ...string) ([]Filter, error) {
out := make([]Filter, 0, len(filters))
for _, entry := range filters {
@@ -45,10 +52,16 @@ func ReadFilters(filters []*rds.Filter, recognised ...string) ([]Filter, error)
if entry == nil || entry.Name == nil || !slices.Contains(recognised, name) {
return nil, awserrors.Errorf(awserrors.ErrorInvalidParameterValue, "Unrecognized filter name: %s", name)
}
if len(entry.Values) == 0 {
if entry.Values == nil {
return nil, awserrors.Errorf(awserrors.ErrorInvalidParameterCombination,
"The values list cannot be null for the filter %s.", name)
}
if len(entry.Values) == 0 {
if msg, refused := emptyValuesRefusals[name]; refused {
return nil, awserrors.Errorf(awserrors.ErrorInvalidParameterCombination, "%s", msg)
}
continue
}
out = append(out, Filter{Name: name, Values: aws.StringValueSlice(entry.Values)})
}
return out, nil
+29 -1
View File
@@ -30,10 +30,16 @@ func TestReadFilters_AnswersAsAWSDoes(t *testing.T) {
"unknown first": {[]*rds.Filter{{Name: aws.String("bogus")}}, awserrors.ErrorInvalidParameterValue, "Unrecognized filter name: bogus"},
"no values": {[]*rds.Filter{{Name: aws.String("engine")}}, awserrors.ErrorInvalidParameterCombination,
"The values list cannot be null for the filter engine."},
"empty db-instance-id": {filter(filterDBInstanceID), awserrors.ErrorInvalidParameterCombination,
"The list of DB Instance Identifiers must not be empty."},
"empty parameter-name": {filter(filterParameterName), awserrors.ErrorInvalidParameterCombination,
"The list of ParameterNames must not be empty."},
"empty snapshot-type": {filter(filterSnapshotType), awserrors.ErrorInvalidParameterCombination,
"Invalid value '' for filter snapshot-type"},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
_, err := ReadFilters(tc.filters, filterEngine)
_, err := ReadFilters(tc.filters, filterEngine, filterDBInstanceID, filterParameterName, filterSnapshotType)
require.Error(t, err)
assert.Contains(t, err.Error(), tc.code)
assert.Contains(t, err.Error(), tc.msg)
@@ -43,6 +49,10 @@ func TestReadFilters_AnswersAsAWSDoes(t *testing.T) {
got, err := ReadFilters(append(filter(filterEngine, "postgres"), filter(filterEngine, "mariadb")...), filterEngine)
require.NoError(t, err)
assert.Equal(t, []Filter{{filterEngine, []string{"postgres"}}, {filterEngine, []string{"mariadb"}}}, got)
got, err = ReadFilters(append(filter(filterEngine), filter(filterStatus, "available")...), filterEngine, filterStatus)
require.NoError(t, err)
assert.Equal(t, []Filter{{filterStatus, []string{"available"}}}, got, "an empty list narrows nothing")
}
// AWS applies parameter-name, matching names in any case, and accepts data-type
@@ -144,6 +154,24 @@ func TestRecognisedFiltersThatDoNotNarrow(t *testing.T) {
}
}
// AWS checks each engine value against its own engine names, not just the ones
// this platform runs.
func TestDescribeDBParameterGroups_RefusesUnknownEngine(t *testing.T) {
t.Parallel()
h := newCreateHarness(t, "")
describe := func(values ...string) error {
_, err := h.svc.DescribeDBParameterGroups(t.Context(),
&rds.DescribeDBParameterGroupsInput{Filters: filter(filterEngine, values...)}, testAccountID)
return err
}
require.NoError(t, describe("aurora-postgresql", "postgres"))
err := describe("postgres", "nope")
require.Error(t, err)
assert.Contains(t, err.Error(), awserrors.ErrorInvalidParameterValue)
assert.Contains(t, err.Error(), "Unrecognized engine name: nope")
}
// AWS ignores Filters here entirely, even an unknown or malformed entry.
func TestDescribeDBSubnetGroups_IgnoresFilters(t *testing.T) {
t.Parallel()
@@ -26,6 +26,17 @@ const maxParametersPerModify = 20
// reach across the boundary to the other.
const defaultParameterGroupPrefix = "default."
// Every engine AWS offers, not only the ones this platform runs, as the
// CreateDBInstance API reference lists them.
var awsEngineNames = []string{
"aurora-mysql", "aurora-postgresql",
"custom-oracle-ee", "custom-oracle-ee-cdb", "custom-oracle-se2", "custom-oracle-se2-cdb",
"custom-sqlserver-ee", "custom-sqlserver-se", "custom-sqlserver-web", "custom-sqlserver-dev",
"db2-ae", "db2-ce", "db2-se", "mariadb", "mysql",
"oracle-ee", "oracle-ee-cdb", "oracle-se2", "oracle-se2-cdb", "postgres",
"sqlserver-dev-ee", "sqlserver-ee", "sqlserver-se", "sqlserver-ex", "sqlserver-web",
}
// AWS's own ApplyMethod values, echoed back on DescribeDBParameters.
const (
ApplyMethodImmediate = "immediate"
@@ -88,10 +99,22 @@ func (s *Service) DescribeDBParameterGroups(ctx context.Context, input *rds.Desc
if input == nil {
input = &rds.DescribeDBParameterGroupsInput{}
}
// AWS recognises both names and narrows by neither.
if _, err := ReadFilters(input.Filters, filterDBParameterGroupFamily, filterEngine); err != nil {
// AWS recognises both names and narrows by neither, but refuses an engine
// value it does not offer.
filters, err := ReadFilters(input.Filters, filterDBParameterGroupFamily, filterEngine)
if err != nil {
return nil, err
}
for _, f := range filters {
if f.Name != filterEngine {
continue
}
for _, value := range f.Values {
if !slices.Contains(awsEngineNames, value) {
return nil, awserrors.Errorf(awserrors.ErrorInvalidParameterValue, "Unrecognized engine name: %s", value)
}
}
}
if name := aws.StringValue(input.DBParameterGroupName); name != "" {
rec, err := s.parameterGroups().Get(ctx, accountID, name)
if err != nil {
@@ -156,6 +156,8 @@ func TestCreateDBParameterGroup_RejectsADuplicateName(t *testing.T) {
require.Error(t, err)
assert.Equal(t, awserrors.ErrorDBParameterGroupAlreadyExists, awserrors.ValidErrorCodeFromError(err),
"the code has to survive resolution or the client sees a 500")
_, message, _ := awserrors.ResolveErrorDetail(err)
assert.Equal(t, "Parameter group "+testParameterGroup+" already exists", message)
}
// The default group is what CreateDBInstance resolves when a request names none,
@@ -210,6 +212,8 @@ func TestDescribeDBParameterGroups_RejectsAnUnknownName(t *testing.T) {
require.Error(t, err)
assert.Equal(t, awserrors.ErrorDBParameterGroupNotFound, awserrors.ValidErrorCodeFromError(err),
"the code has to survive resolution or the client sees a 500")
_, message, _ := awserrors.ResolveErrorDetail(err)
assert.Equal(t, "DBParameterGroup not found: absent", message)
// A default.* name for an engine that does not exist is a not-found too,
// rather than a group that resolves to nothing.
@@ -457,7 +461,7 @@ func TestModifyDBParameterGroup_RejectsBadRequests(t *testing.T) {
want string
}{
{"UnknownParameter", modifyParameters(testParameterGroup, parameter("not_a_setting", "1", "")),
"is not a parameter this engine exposes"},
"Could not find parameter with name: not_a_setting"},
{"OutOfRange", modifyParameters(testParameterGroup, parameter("max_connections", "999999", "")),
"outside its allowed range"},
{"Formula", modifyParameters(testParameterGroup, parameter("shared_buffers", "{DBInstanceClassMemory/32768}", "")),
+1 -1
View File
@@ -632,7 +632,7 @@ func (s *Service) getDBSnapshot(ctx context.Context, kv *kvstore.Bucket, id stri
return nil, 0, err
}
if !found {
return nil, 0, awserrors.Errorf(awserrors.ErrorDBSnapshotNotFound, "DB snapshot %s not found", id)
return nil, 0, awserrors.Errorf(awserrors.ErrorDBSnapshotNotFound, "DBSnapshot not found: %s", id)
}
return &rec, rev, nil
}
@@ -381,6 +381,8 @@ func TestDescribeDBSnapshots_NamedSnapshotThatDoesNotExistIsAnError(t *testing.T
}, testAccountID)
require.Error(t, err)
assert.Contains(t, err.Error(), awserrors.ErrorDBSnapshotNotFound)
_, message, _ := awserrors.ResolveErrorDetail(err)
assert.Equal(t, "DBSnapshot not found: "+testSnapshotID+"", message)
}
// A filter this phase cannot honour is rejected, because a silently
@@ -162,6 +162,8 @@ func TestCreateDBSubnetGroup_RejectsADuplicateName(t *testing.T) {
require.Error(t, err)
assert.Equal(t, awserrors.ErrorDBSubnetGroupAlreadyExists, awserrors.ValidErrorCodeFromError(err),
"the code has to survive resolution or the client sees a 500")
_, message, _ := awserrors.ResolveErrorDetail(err)
assert.Equal(t, "The DB subnet group '"+testSubnetGroup+"' already exists.", message)
}
func TestDescribeDBSubnetGroups_ListsAndNames(t *testing.T) {
+2 -2
View File
@@ -66,7 +66,7 @@ func (o *Owner) Create(ctx context.Context, accountID string, spec Spec) (*Recor
if _, err := kvstore.On[Record](kv).Create(ctx, MetaKey(spec.Name), rec); err != nil {
if errors.Is(err, kvstore.ErrExists) {
return nil, awserrors.Errorf(awserrors.ErrorDBParameterGroupAlreadyExists,
"DB parameter group %s already exists", spec.Name)
"Parameter group %s already exists", spec.Name)
}
return nil, err
}
@@ -217,7 +217,7 @@ func get(ctx context.Context, kv *kvstore.Bucket, accountID, name string) (*Reco
if engine, ok := rdsengine.EngineForDefaultParameterGroup(name); ok {
return defaultRecord(engine, accountID), 0, nil
}
return nil, 0, awserrors.Errorf(awserrors.ErrorDBParameterGroupNotFound, "DB parameter group %s not found", name)
return nil, 0, awserrors.Errorf(awserrors.ErrorDBParameterGroupNotFound, "DBParameterGroup not found: %s", name)
}
// The implicit group, identical for every account. It carries no tags and no stored values, so it
+1 -1
View File
@@ -77,7 +77,7 @@ func (o *Owner) Create(ctx context.Context, accountID string, spec Spec) (*Recor
if _, err := kvstore.On[Record](kv).Create(ctx, Key(spec.Name), rec); err != nil {
if errors.Is(err, kvstore.ErrExists) {
return nil, awserrors.Errorf(awserrors.ErrorDBSubnetGroupAlreadyExists,
"DB subnet group %s already exists", spec.Name)
"The DB subnet group '%s' already exists.", spec.Name)
}
return nil, err
}
+4 -7
View File
@@ -197,9 +197,6 @@ func (s *Service) ListHostedZones(ctx context.Context, in *route53.ListHostedZon
MaxItems: aws.String(strconv.Itoa(limit)),
Marker: in.Marker,
}
if out.Marker == nil {
out.Marker = aws.String("")
}
if truncated {
out.NextMarker = aws.String(zones[start+limit].ID)
}
@@ -217,7 +214,7 @@ func (s *Service) ListHostedZonesByName(ctx context.Context, in *route53.ListHos
}
dnsName := normalizeName(aws.StringValue(in.DNSName))
if startID != "" && dnsName == "" {
return nil, awserrors.Errorf(awserrors.ErrorInvalidInput, "HostedZoneId requires DNSName")
return nil, awserrors.Errorf(awserrors.ErrorInvalidInput, "The specified marker is not valid.")
}
zones, err := s.sortedZones(ctx, account, compareByName)
if err != nil {
@@ -388,7 +385,7 @@ func (s *Service) GetChange(ctx context.Context, in *route53.GetChangeInput, acc
id := BareChangeID(aws.StringValue(in.Id))
c, err := s.store.GetChange(ctx, account, id)
if errors.Is(err, kvstore.ErrNotFound) {
return nil, awserrors.Errorf(awserrors.ErrorNoSuchChange, "A change with the specified change ID does not exist: %s", id)
return nil, awserrors.Errorf(awserrors.ErrorNoSuchChange, "Could not find resource with ID: %s", id)
}
if err != nil {
return nil, internal("get change", err)
@@ -561,7 +558,7 @@ func maxItems(raw *string, ceiling int) (int, error) {
}
n, err := strconv.Atoi(*raw)
if err != nil || n < 1 {
return 0, awserrors.Errorf(awserrors.ErrorInvalidInput, "MaxItems must be a positive integer")
return 0, awserrors.Errorf(awserrors.ErrorInvalidInput, "maxitems must be a positive integer.")
}
return min(n, ceiling), nil
}
@@ -573,7 +570,7 @@ func taggedZoneID(resourceType, id string) (string, error) {
case route53.TagResourceTypeHealthcheck:
return "", awserrors.Errorf(awserrors.ErrorRoute53NoSuchHealthCheck, "No health check exists with the ID %s", id)
default:
return "", awserrors.Errorf(awserrors.ErrorInvalidInput, "ResourceType must be hostedzone or healthcheck")
return "", awserrors.Errorf(awserrors.ErrorInvalidInput, "Invalid resource type: %s", resourceType)
}
}
+18
View File
@@ -662,3 +662,21 @@ func TestModelBoundViolationsAreInvalidInput(t *testing.T) {
_, err := svc.ListResourceRecordSets(ctx, &r53.ListResourceRecordSetsInput{HostedZoneId: aws.String(id), StartRecordName: aws.String("example.com"), StartRecordType: aws.String("HTTPS")}, acctA)
require.NoError(t, err, "the model's RRType includes types the v1 SDK predates")
}
func TestListAndLookupErrorsMatchAWS(t *testing.T) {
svc := newService(t)
id := createZone(t, svc, acctA, "example.com")
out, err := svc.ListHostedZones(ctx, &r53.ListHostedZonesInput{}, acctA)
require.NoError(t, err)
assert.Nil(t, out.Marker)
_, err = svc.GetChange(ctx, &r53.GetChangeInput{Id: aws.String("C0000000000000000PROBE")}, acctA)
assert.Equal(t, "Could not find resource with ID: C0000000000000000PROBE", requireCode(t, err, awserrors.ErrorNoSuchChange))
_, err = svc.ListTagsForResource(ctx, &r53.ListTagsForResourceInput{ResourceType: aws.String("bogus"), ResourceId: aws.String(id)}, acctA)
assert.Equal(t, "Invalid resource type: bogus", requireCode(t, err, awserrors.ErrorInvalidInput))
_, err = svc.ListHostedZones(ctx, &r53.ListHostedZonesInput{MaxItems: aws.String("0")}, acctA)
assert.Equal(t, "maxitems must be a positive integer.", requireCode(t, err, awserrors.ErrorInvalidInput))
_, err = svc.ListHostedZonesByName(ctx, &r53.ListHostedZonesByNameInput{HostedZoneId: aws.String(id)}, acctA)
assert.Equal(t, "The specified marker is not valid.", requireCode(t, err, awserrors.ErrorInvalidInput))
}
+3 -2
View File
@@ -31,7 +31,7 @@ type VolumeService interface {
// Publisher is the provider pair used to reach the new volume's blocks.
type Publisher interface {
PublishVolume(context.Context, ebsprovider.PublishVolumeRequest) (*ebsprovider.PublishedVolume, error)
UnpublishVolume(context.Context, ebsprovider.UnpublishVolumeRequest) error
UnpublishVolume(context.Context, ebsprovider.UnpublishVolumeRequest) (*ebsprovider.UnpublishedVolume, error)
}
// Request names the volume to create.
@@ -204,9 +204,10 @@ func (p *Preparer) fill(ctx context.Context, volumeID, image string) error {
func (p *Preparer) unpublish(ctx context.Context, volumeID string) error {
cctx, cancel := p.cleanupContext(ctx)
defer cancel()
return p.Provider.UnpublishVolume(cctx, ebsprovider.UnpublishVolumeRequest{
_, err := p.Provider.UnpublishVolume(cctx, ebsprovider.UnpublishVolumeRequest{
Versioned: ebsprovider.NewVersioned(), VolumeID: volumeID, NodeID: p.NodeID,
})
return err
}
// fail discards the volume when its export is known closed and otherwise
@@ -105,14 +105,17 @@ func (h *harness) PublishVolume(_ context.Context, req ebsprovider.PublishVolume
return &ebsprovider.PublishedVolume{VolumeID: req.VolumeID, NodeID: req.NodeID, Export: export}, nil
}
func (h *harness) UnpublishVolume(ctx context.Context, req ebsprovider.UnpublishVolumeRequest) error {
func (h *harness) UnpublishVolume(ctx context.Context, req ebsprovider.UnpublishVolumeRequest) (*ebsprovider.UnpublishedVolume, error) {
h.record("unpublish " + req.VolumeID + " on " + req.NodeID)
h.unpublishCtxOK = ctx.Err() == nil
if h.unpublishBlocks {
<-ctx.Done()
return ctx.Err()
return nil, ctx.Err()
}
return h.unpublishErr
if h.unpublishErr != nil {
return nil, h.unpublishErr
}
return &ebsprovider.UnpublishedVolume{}, nil
}
func (h *harness) preparer(t *testing.T) *Preparer {
+37
View File
@@ -0,0 +1,37 @@
package pki
import (
"bytes"
"crypto/x509"
"errors"
"fmt"
)
// ErrPeerIdentity is returned when a pinned peer certificate does not carry
// the expected URI SAN.
var ErrPeerIdentity = errors.New("pki: peer identity mismatch")
// VerifyPinned requires chain to be exactly the pinned certificate, valid now
// for usage, whose only URI SAN is wantURI. Trusting the pin as a root alone
// would also accept other leaves it signed, so the DER is compared first.
func VerifyPinned(chain []*x509.Certificate, pinned *x509.Certificate, usage x509.ExtKeyUsage, wantURI string) error {
if pinned == nil {
return errors.New("pki: no pinned peer certificate")
}
if len(chain) != 1 {
return fmt.Errorf("pki: peer sent %d certificates, want exactly the pinned one", len(chain))
}
leaf := chain[0]
if !bytes.Equal(leaf.Raw, pinned.Raw) {
return errors.New("pki: peer certificate is not the pinned certificate")
}
roots := x509.NewCertPool()
roots.AddCert(pinned)
if _, err := leaf.Verify(x509.VerifyOptions{Roots: roots, KeyUsages: []x509.ExtKeyUsage{usage}}); err != nil {
return fmt.Errorf("pki: peer certificate: %w", err)
}
if len(leaf.URIs) != 1 || leaf.URIs[0].String() != wantURI {
return fmt.Errorf("%w: got %v, want %s", ErrPeerIdentity, leaf.URIs, wantURI)
}
return nil
}
+67
View File
@@ -0,0 +1,67 @@
package pki
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"math/big"
"net/url"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func pinnedCert(t *testing.T, uris ...string) *x509.Certificate {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
}
for _, s := range uris {
u, err := url.Parse(s)
require.NoError(t, err)
tmpl.URIs = append(tmpl.URIs, u)
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
require.NoError(t, err)
c, err := x509.ParseCertificate(der)
require.NoError(t, err)
return c
}
func TestVerifyPinned(t *testing.T) {
const want = "spinifex-lambda://r/a/f/e/g/guest"
pin := pinnedCert(t, want)
other := pinnedCert(t, want)
twoURIs := pinnedCert(t, want, "spinifex-lambda://r/a/f/e/g/host")
require.NoError(t, VerifyPinned([]*x509.Certificate{pin}, pin, x509.ExtKeyUsageClientAuth, want))
cases := []struct {
name string
chain []*x509.Certificate
pin *x509.Certificate
usage x509.ExtKeyUsage
uri string
msg string
}{
{"no pin", []*x509.Certificate{pin}, nil, x509.ExtKeyUsageClientAuth, want, "no pinned peer certificate"},
{"empty chain", nil, pin, x509.ExtKeyUsageClientAuth, want, "sent 0 certificates"},
{"extra chain certificate", []*x509.Certificate{pin, other}, pin, x509.ExtKeyUsageClientAuth, want, "sent 2 certificates"},
{"same identity, other key", []*x509.Certificate{other}, pin, x509.ExtKeyUsageClientAuth, want, "not the pinned certificate"},
{"wrong usage", []*x509.Certificate{pin}, pin, x509.ExtKeyUsageServerAuth, want, "incompatible key usage"},
{"wrong URI", []*x509.Certificate{pin}, pin, x509.ExtKeyUsageClientAuth, "spinifex-lambda://r/a/f/e/g2/guest", "identity mismatch"},
{"second URI", []*x509.Certificate{twoURIs}, twoURIs, x509.ExtKeyUsageClientAuth, want, "identity mismatch"},
}
for _, tc := range cases {
err := VerifyPinned(tc.chain, tc.pin, tc.usage, tc.uri)
assert.ErrorContains(t, err, tc.msg, tc.name)
}
assert.ErrorIs(t, VerifyPinned([]*x509.Certificate{pin}, pin, x509.ExtKeyUsageClientAuth, "x://y"), ErrPeerIdentity)
}
@@ -1,3 +1,8 @@
// Left out of -race builds: go/packages loads export data concurrently and
// go/types races on it (golang/go#81122). The lint is static, so the plain
// test run covers it.
//go:build !race
package otelsetup_test
import (
+4
View File
@@ -146,6 +146,10 @@ func setFieldValue(field reflect.Value, value string) error {
field.SetBytes([]byte(value))
return nil
}
// The Query protocol sends an empty list as its bare key with no value.
if value == "" {
field.Set(reflect.MakeSlice(field.Type(), 0, 0))
}
case reflect.String:
field.SetString(value)
+15
View File
@@ -713,6 +713,21 @@ func TestQueryParamsToStruct_CreateLaunchTemplateNestedData(t *testing.T) {
*input.LaunchTemplateData.InstanceMarketOptions.SpotOptions.ValidUntil)
}
// The Query protocol sends an empty list as its bare key, which must not read
// as an absent one.
func TestQueryParamsToStruct_EmptyListIsNotAbsent(t *testing.T) {
var input rds.DescribeDBEngineVersionsInput
err := QueryParamsToStruct(map[string]string{
"Filters.Filter.1.Name": "engine", "Filters.Filter.1.Values": "",
"Filters.Filter.2.Name": "status",
}, &input)
require.NoError(t, err)
require.Len(t, input.Filters, 2)
assert.NotNil(t, input.Filters[0].Values)
assert.Empty(t, input.Filters[0].Values)
assert.Nil(t, input.Filters[1].Values)
}
func TestParseArgs(t *testing.T) {
t.Run("indexed members stay distinct keys", func(t *testing.T) {
got, err := ParseArgs("Action=DescribeTags&ResourceArns.member.1=a&ResourceArns.member.2=b")
+31 -1
View File
@@ -8,6 +8,8 @@ import (
"slices"
"sort"
"time"
operatorv1 "github.com/mulgadc/spinifex/contracts/operator/v1"
)
// AccountStatusTerminating mirrors iamdomain.AccountStatusTerminating.
@@ -29,6 +31,10 @@ type Engine struct {
// and this is the only view into it while it runs.
OnStage func(ctx context.Context, stage StageResult)
// OnQuiesced receives the recorded quiescence evaluation once the account is
// TERMINATING and before the first stage. It records evidence and gates nothing.
OnQuiesced func(ctx context.Context, quiescence operatorv1.IAMQuiescence)
// ec2Inventory is EC2's read-only platform inventory. Only DryRun consults
// it, and only to log a comparison; no teardown or Inventory call does.
ec2Inventory ec2PlatformInventory
@@ -118,9 +124,13 @@ func (e *Engine) Teardown(ctx context.Context, req Request) (*Result, error) {
return e.Inventory(ctx, req.AccountID)
}
if _, err := e.Accounts.QuiesceAccount(req.AccountID, req.OperationID, req.Fence); err != nil {
generation, err := e.Accounts.QuiesceAccount(req.AccountID, req.OperationID, req.Fence)
if err != nil {
return nil, fmt.Errorf("quiesce account: %w", err)
}
if e.OnQuiesced != nil {
e.OnQuiesced(ctx, e.evaluateQuiescence(ctx, req, generation))
}
e.logger().InfoContext(ctx, "Account teardown started",
"accountID", account.AccountID, "accountName", account.AccountName, "force", req.Force)
@@ -325,3 +335,23 @@ func containsResource(resources []Resource, want Resource) bool {
func SortReapers(reapers []Reaper) {
sort.SliceStable(reapers, func(i, j int) bool { return reapers[i].Stage() < reapers[j].Stage() })
}
// evaluateQuiescence reads back what the quiesce wrote and, only if the fence
// is confirmed, asks EC2 for its platform inventory within a short budget.
func (e *Engine) evaluateQuiescence(ctx context.Context, req Request, generation uint64) operatorv1.IAMQuiescence {
ev := QuiesceEvidence{
OperationID: req.OperationID, Fence: req.Fence, Generation: generation, EvaluatedAt: time.Now(),
}
ev.Account, ev.ReadbackErr = e.Accounts.GetAccount(req.AccountID)
if _, confirmed := fenceReadback(ev); confirmed && e.ec2Inventory != nil {
budget := ec2PlatformShadowBudget
if e.ec2PlatformShadowBudget > 0 {
budget = e.ec2PlatformShadowBudget
}
inventoryCtx, cancel := context.WithTimeout(ctx, budget)
defer cancel()
reply := e.ec2Inventory.PlatformInventory(inventoryCtx, req.AccountID, req.OperationID)
ev.Inventory = &reply
}
return EvaluateQuiescence(ev)
}
@@ -61,6 +61,8 @@ func (f *fakeAccounts) QuiesceAccount(_, operationID string, fence uint64) (uint
f.statuses = append(f.statuses, AccountStatusTerminating)
f.quiesces = append(f.quiesces, quiesceCall{operationID, fence})
f.account.Status = AccountStatusTerminating
f.account.Generation = 1
f.account.TerminationOp = &TerminationOp{OperationID: operationID, Fence: fence}
return 1, nil
}
@@ -0,0 +1,164 @@
package accountlifecycle
import (
"time"
ec2v1 "github.com/mulgadc/spinifex/contracts/ec2/v1"
operatorv1 "github.com/mulgadc/spinifex/contracts/operator/v1"
)
// finalInventoryRereadWired says whether anything re-reads the owner inventory
// before the account record goes. Until it does, a write landing after the
// reaper stage is orphaned, so no kind may be recorded as quiesced.
var finalInventoryRereadWired = false
// QuiesceEvidence is what the engine read after QuiesceAccount returned.
type QuiesceEvidence struct {
OperationID string
Fence uint64
Generation uint64
// Account is the IAM record read back after the quiesce.
Account *Account
ReadbackErr error
Inventory *ec2v1.PlatformInventoryReply
EvaluatedAt time.Time
}
// enforcementConsumers are the consumers with an accepted contract for the
// account admission fact. Predastore is deliberately absent: it has none.
var enforcementConsumers = []operatorv1.ConsumerBasis{
{Consumer: "awsgw-admission", Basis: "ADR-0005:S7"},
{Consumer: "ecr-registry", Basis: "ADR-0005:S7"},
{Consumer: "sts-mint-gate", Basis: "ADR-0008:S9 (IAM-owned)"},
}
// accountedWriters cannot be fenced and are covered by the owner inventory.
var accountedWriters = []operatorv1.AccountedWriter{
{Writer: "daemon-nats-handlers", Basis: "owner-inventory", Ref: "mulga-tpoz4"},
}
// ec2PlatformKinds are the kinds the first scope covers. The inventory's own
// tag-index kind belongs to a different register row and is not part of it.
var ec2PlatformKinds = []string{
ec2v1.PlatformKindKeyPair,
ec2v1.PlatformKindPlacementGroup,
ec2v1.PlatformKindLaunchTemplate,
}
type unresolvedEntry struct {
scope, class, reason string
}
// otherScopes lists every scope the first exercise does not cover, by name.
// A register row family missing from here would read as quiesced by omission.
var otherScopes = []unresolvedEntry{
{"ec2-instances", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"ec2-spot-requests", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"ebs-volumes", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"ec2-snapshots-images", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"ec2-vpc", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"host-network", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"ec2-account-settings", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"ec2-tag-index", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"iam", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"elbv2", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"acm", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"eks", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"ecs", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"rds", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"dns", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"ochre", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"quota", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"idempotency", operatorv1.UnresolvedClassWriter, operatorv1.ReasonNoCompleteOwnerInventory},
{"s3", operatorv1.UnresolvedClassConsumer, operatorv1.ReasonNoAcceptedEnforcement},
{"ecr", operatorv1.UnresolvedClassConsumer, operatorv1.ReasonNoAcceptedEnforcement},
{"lambda", operatorv1.UnresolvedClassWriter, operatorv1.ReasonParticipantNotDeclared},
{"sqs", operatorv1.UnresolvedClassWriter, operatorv1.ReasonParticipantNotDeclared},
}
// EvaluateQuiescence applies ADR-0008:S9's three conditions to the evidence and
// records what holds. A fence the read-back does not confirm stops everything
// else; otherwise every scope is listed, and none is reported quiesced yet.
func EvaluateQuiescence(ev QuiesceEvidence) operatorv1.IAMQuiescence {
out := operatorv1.IAMQuiescence{
OperationID: ev.OperationID,
Fence: ev.Fence,
Generation: ev.Generation,
QuiescedScope: []string{},
Unresolved: []operatorv1.UnresolvedScope{},
Consumers: []operatorv1.ConsumerBasis{},
Writers: []operatorv1.AccountedWriter{},
Inventory: []operatorv1.InventoryStatus{},
EvaluatedAt: ev.EvaluatedAt.UTC().Format(time.RFC3339),
}
if reason, ok := fenceReadback(ev); !ok {
out.Unresolved = append(out.Unresolved, operatorv1.UnresolvedScope{
Scope: "all", Class: operatorv1.UnresolvedClassFence, Reason: reason,
})
return out
}
out.Consumers = append(out.Consumers, enforcementConsumers...)
out.Writers = append(out.Writers, accountedWriters...)
for _, kind := range ec2PlatformKinds {
status, complete := kindInventory(ev.Inventory, kind)
out.Inventory = append(out.Inventory, operatorv1.InventoryStatus{Kind: kind, Status: status})
switch {
case !complete:
out.Unresolved = append(out.Unresolved, writerEntry("ec2-"+kind, operatorv1.ReasonOwnerInventoryIncomplete))
case !finalInventoryRereadWired:
out.Unresolved = append(out.Unresolved, writerEntry("ec2-"+kind, operatorv1.ReasonFinalInventoryRereadNotWired))
default:
out.QuiescedScope = append(out.QuiescedScope, kind)
}
}
for _, entry := range otherScopes {
out.Unresolved = append(out.Unresolved, operatorv1.UnresolvedScope{
Scope: entry.scope, Class: entry.class, Reason: entry.reason,
})
}
return out
}
func writerEntry(scope, reason string) operatorv1.UnresolvedScope {
return operatorv1.UnresolvedScope{Scope: scope, Class: operatorv1.UnresolvedClassWriter, Reason: reason}
}
// fenceReadback is condition 1: the operation record and the IAM account record
// hold the same operation, fence and generation.
func fenceReadback(ev QuiesceEvidence) (reason string, ok bool) {
if ev.ReadbackErr != nil || ev.Account == nil {
return operatorv1.ReasonIAMReadbackFailed, false
}
op := ev.Account.TerminationOp
if ev.Account.Status != AccountStatusTerminating || op == nil ||
op.OperationID != ev.OperationID || op.Fence != ev.Fence || ev.Account.Generation != ev.Generation {
return operatorv1.ReasonFenceMismatch, false
}
return "", true
}
// kindInventory reports one kind's status and whether the owner scan was
// complete. A missing or repeated kind, or no reply at all, is incomplete.
func kindInventory(reply *ec2v1.PlatformInventoryReply, kind string) (status string, complete bool) {
if reply == nil {
return ec2v1.PlatformStatusScanIncomplete, false
}
var found *ec2v1.PlatformKindReport
for i := range reply.Kinds {
if reply.Kinds[i].Kind != kind {
continue
}
if found != nil {
return ec2v1.PlatformStatusScanIncomplete, false
}
found = &reply.Kinds[i]
}
if found == nil || found.Status == ec2v1.PlatformStatusScanIncomplete {
return ec2v1.PlatformStatusScanIncomplete, false
}
return found.Status, true
}
@@ -0,0 +1,281 @@
package accountlifecycle
//test:in-package — the evaluator, its scope table and the engine hook are
// unexported, and the table is what keeps a scope from reading as quiesced by omission.
import (
"context"
"errors"
"slices"
"testing"
"time"
ec2v1 "github.com/mulgadc/spinifex/contracts/ec2/v1"
operatorv1 "github.com/mulgadc/spinifex/contracts/operator/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func confirmedEvidence() QuiesceEvidence {
return QuiesceEvidence{
OperationID: "op-1", Fence: 2, Generation: 5,
Account: &Account{
AccountID: testAccountID, Status: AccountStatusTerminating, Generation: 5,
TerminationOp: &TerminationOp{OperationID: "op-1", Fence: 2},
},
Inventory: completeInventory(),
EvaluatedAt: time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC),
}
}
func completeInventory() *ec2v1.PlatformInventoryReply {
reply := &ec2v1.PlatformInventoryReply{AccountID: testAccountID}
for _, kind := range ec2v1.PlatformKinds() {
reply.Kinds = append(reply.Kinds, ec2v1.PlatformKindReport{Kind: kind, Status: ec2v1.PlatformStatusObservedClean})
}
return reply
}
func unresolvedFor(q operatorv1.IAMQuiescence, scope string) []operatorv1.UnresolvedScope {
var out []operatorv1.UnresolvedScope
for _, entry := range q.Unresolved {
if entry.Scope == scope {
out = append(out, entry)
}
}
return out
}
// With the fence confirmed and every L09 kind scanned complete, the evidence is
// recorded but no kind is quiesced: nothing re-reads the inventory before the
// account record goes, so a late write would be orphaned (ADR-0008:S9 condition 3).
func TestEvaluateQuiescenceRecordsEvidenceButQuiescesNothingWithoutAFinalReread(t *testing.T) {
q := EvaluateQuiescence(confirmedEvidence())
assert.Equal(t, "op-1", q.OperationID)
assert.Equal(t, uint64(2), q.Fence)
assert.Equal(t, uint64(5), q.Generation)
assert.Empty(t, q.QuiescedScope)
assert.NotNil(t, q.QuiescedScope, "evaluated-and-empty must serialise as [] not null")
for _, kind := range ec2PlatformKinds {
assert.Equal(t, []operatorv1.UnresolvedScope{{
Scope: "ec2-" + kind, Class: operatorv1.UnresolvedClassWriter,
Reason: operatorv1.ReasonFinalInventoryRereadNotWired,
}}, unresolvedFor(q, "ec2-"+kind))
}
assert.ElementsMatch(t, []operatorv1.InventoryStatus{
{Kind: ec2v1.PlatformKindKeyPair, Status: ec2v1.PlatformStatusObservedClean},
{Kind: ec2v1.PlatformKindPlacementGroup, Status: ec2v1.PlatformStatusObservedClean},
{Kind: ec2v1.PlatformKindLaunchTemplate, Status: ec2v1.PlatformStatusObservedClean},
}, q.Inventory)
assert.Equal(t, []operatorv1.AccountedWriter{{Writer: "daemon-nats-handlers", Basis: "owner-inventory", Ref: "mulga-tpoz4"}}, q.Writers)
assert.Equal(t, "2026-11-02T00:00:00Z", q.EvaluatedAt)
}
// The wiring step flips this switch; the complete kinds are then, and only then, named.
func TestEvaluateQuiescenceNamesCompleteKindsOnceTheRereadIsWired(t *testing.T) {
finalInventoryRereadWired = true
t.Cleanup(func() { finalInventoryRereadWired = false })
ev := confirmedEvidence()
ev.Inventory.Kinds[1].Status = ec2v1.PlatformStatusScanIncomplete
q := EvaluateQuiescence(ev)
assert.Equal(t, []string{ec2v1.PlatformKindKeyPair, ec2v1.PlatformKindLaunchTemplate}, q.QuiescedScope)
assert.Equal(t, operatorv1.ReasonOwnerInventoryIncomplete, unresolvedFor(q, "ec2-placement-group")[0].Reason)
}
func TestEvaluateQuiescenceRecordsAnIncompleteInventoryPerKind(t *testing.T) {
cases := map[string]func(*QuiesceEvidence){
"one kind scan-incomplete": func(ev *QuiesceEvidence) { ev.Inventory.Kinds[0].Status = ec2v1.PlatformStatusScanIncomplete },
"kind missing": func(ev *QuiesceEvidence) { ev.Inventory.Kinds = ev.Inventory.Kinds[1:] },
"kind repeated": func(ev *QuiesceEvidence) {
ev.Inventory.Kinds = append(ev.Inventory.Kinds, ev.Inventory.Kinds[0])
},
}
for name, mutate := range cases {
t.Run(name, func(t *testing.T) {
ev := confirmedEvidence()
mutate(&ev)
q := EvaluateQuiescence(ev)
got := unresolvedFor(q, "ec2-key-pair")
require.Len(t, got, 1)
assert.Equal(t, operatorv1.ReasonOwnerInventoryIncomplete, got[0].Reason)
assert.Equal(t, operatorv1.ReasonFinalInventoryRereadNotWired, unresolvedFor(q, "ec2-launch-template")[0].Reason,
"the other kinds keep their own result")
})
}
t.Run("no reply at all", func(t *testing.T) {
ev := confirmedEvidence()
ev.Inventory = nil
q := EvaluateQuiescence(ev)
for _, kind := range ec2PlatformKinds {
assert.Equal(t, operatorv1.ReasonOwnerInventoryIncomplete, unresolvedFor(q, "ec2-"+kind)[0].Reason)
}
})
}
// Condition 1: a read-back that does not confirm the operation, fence and
// generation records nothing as quiesced and evaluates nothing else.
func TestEvaluateQuiescenceRecordsNothingWhenTheFenceIsNotConfirmed(t *testing.T) {
cases := map[string]struct {
mutate func(*QuiesceEvidence)
reason string
}{
"not terminating": {func(ev *QuiesceEvidence) { ev.Account.Status = "ACTIVE" }, operatorv1.ReasonFenceMismatch},
"no operation": {func(ev *QuiesceEvidence) { ev.Account.TerminationOp = nil }, operatorv1.ReasonFenceMismatch},
"other operation": {func(ev *QuiesceEvidence) { ev.Account.TerminationOp.OperationID = "op-2" }, operatorv1.ReasonFenceMismatch},
"higher fence in IAM": {func(ev *QuiesceEvidence) { ev.Account.TerminationOp.Fence = 3 }, operatorv1.ReasonFenceMismatch},
"other generation": {func(ev *QuiesceEvidence) { ev.Account.Generation = 6 }, operatorv1.ReasonFenceMismatch},
"read-back failed": {func(ev *QuiesceEvidence) { ev.Account, ev.ReadbackErr = nil, errors.New("kv down") }, operatorv1.ReasonIAMReadbackFailed},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
finalInventoryRereadWired = true
t.Cleanup(func() { finalInventoryRereadWired = false })
ev := confirmedEvidence()
tc.mutate(&ev)
q := EvaluateQuiescence(ev)
assert.Empty(t, q.QuiescedScope)
assert.Equal(t, []operatorv1.UnresolvedScope{{Scope: "all", Class: operatorv1.UnresolvedClassFence, Reason: tc.reason}}, q.Unresolved)
assert.Empty(t, q.Consumers)
assert.Empty(t, q.Writers)
assert.Empty(t, q.Inventory)
})
}
}
// Every scope outside the first exercise is named. The expected list is the
// lifecycle register's rows other than L01, L02 and L09, so a new row has to be
// added here and in the table rather than reading as quiesced by omission.
func TestEveryOtherScopeIsRecordedUnresolvedByName(t *testing.T) {
want := []string{
"ec2-instances", "ec2-spot-requests", "ebs-volumes", "ec2-snapshots-images", "ec2-vpc",
"host-network", "ec2-account-settings", "ec2-tag-index", "iam", "elbv2", "acm", "eks", "ecs",
"rds", "dns", "ochre", "quota", "idempotency", "s3", "ecr", "lambda", "sqs",
}
q := EvaluateQuiescence(confirmedEvidence())
for _, scope := range want {
got := unresolvedFor(q, scope)
require.Len(t, got, 1, scope)
assert.NotEmpty(t, got[0].Reason, scope)
}
assert.Len(t, q.Unresolved, len(want)+len(ec2PlatformKinds), "no scope beyond the register and the three kinds")
for _, entry := range otherScopes {
assert.False(t, slices.Contains(ec2PlatformKinds, entry.scope), entry.scope)
}
}
// Predastore has no accepted enforcement contract, so the scopes it admits writes
// for stay unresolved and it is never cited as a consumer, even once the
// re-read is wired and every L09 kind is complete.
func TestPredastoreIsNeverCitedAndItsScopesNeverQuiesce(t *testing.T) {
finalInventoryRereadWired = true
t.Cleanup(func() { finalInventoryRereadWired = false })
q := EvaluateQuiescence(confirmedEvidence())
for _, scope := range []string{"s3", "ecr"} {
got := unresolvedFor(q, scope)
require.Len(t, got, 1)
assert.Equal(t, operatorv1.UnresolvedClassConsumer, got[0].Class)
assert.Equal(t, operatorv1.ReasonNoAcceptedEnforcement, got[0].Reason)
assert.NotContains(t, q.QuiescedScope, scope)
}
for _, consumer := range q.Consumers {
assert.NotContains(t, consumer.Consumer, "predastore")
want := "ADR-0005:S7"
if consumer.Consumer == "sts-mint-gate" {
want = "ADR-0008:S9 (IAM-owned)"
}
assert.Equal(t, want, consumer.Basis)
}
assert.Equal(t, []string{"awsgw-admission", "ecr-registry", "sts-mint-gate"},
[]string{q.Consumers[0].Consumer, q.Consumers[1].Consumer, q.Consumers[2].Consumer})
}
type stubInventory struct {
reply ec2v1.PlatformInventoryReply
calls int
}
func (s *stubInventory) PlatformInventory(context.Context, string, string) ec2v1.PlatformInventoryReply {
s.calls++
return s.reply
}
// The hook fires once, after the quiesce and before the first stage, carrying the
// operation, fence and generation the quiesce returned.
func TestTeardownReportsQuiescenceAfterTheQuiesceAndBeforeTheFirstStage(t *testing.T) {
accounts := newFakeAccounts()
var events []string
reaper := &fakeReaper{kind: "volume", stage: StageStorage, resources: []Resource{{Kind: "volume", ID: "vol-1"}}}
engine := quietEngine(accounts, reaper)
inventory := &stubInventory{reply: *completeInventory()}
engine.ec2Inventory = inventory
var got operatorv1.IAMQuiescence
engine.OnQuiesced = func(_ context.Context, q operatorv1.IAMQuiescence) {
events = append(events, "quiesced")
assert.Equal(t, 0, reaper.deletesAttempted, "no stage may have run yet")
assert.Equal(t, AccountStatusTerminating, accounts.account.Status)
got = q
}
engine.OnStage = func(context.Context, StageResult) {
if len(events) == 0 || events[len(events)-1] != "stage" {
events = append(events, "stage")
}
}
req := request()
req.OperationID, req.Fence = "op-7", 3
_, err := engine.Teardown(context.Background(), req)
require.NoError(t, err)
assert.Equal(t, []string{"quiesced", "stage"}, events)
assert.Equal(t, "op-7", got.OperationID)
assert.Equal(t, uint64(3), got.Fence)
assert.Equal(t, uint64(1), got.Generation)
assert.Equal(t, 1, inventory.calls)
assert.True(t, accounts.deleted, "recording must not change the legacy teardown")
}
// A fence the read-back does not confirm must not spend an inventory call, and a
// failed read-back must not stop the teardown: this step records and gates nothing.
func TestTeardownRecordsAFailedReadbackAndStillRunsEveryStage(t *testing.T) {
accounts := newFakeAccounts()
engine := quietEngine(accounts)
inventory := &stubInventory{reply: *completeInventory()}
engine.ec2Inventory = inventory
var got operatorv1.IAMQuiescence
engine.OnQuiesced = func(_ context.Context, q operatorv1.IAMQuiescence) { got = q }
accounts.getErr = nil
engine.Accounts = &readbackFails{fakeAccounts: accounts}
req := request()
req.OperationID, req.Fence = "op-1", 1
_, err := engine.Teardown(context.Background(), req)
require.NoError(t, err)
require.Len(t, got.Unresolved, 1)
assert.Equal(t, operatorv1.ReasonIAMReadbackFailed, got.Unresolved[0].Reason)
assert.Zero(t, inventory.calls)
assert.True(t, accounts.deleted)
}
// readbackFails serves the pre-quiesce read and fails the one after it.
type readbackFails struct {
*fakeAccounts
reads int
}
func (r *readbackFails) GetAccount(id string) (*Account, error) {
r.reads++
if r.reads > 1 {
return nil, errors.New("kv down")
}
return r.fakeAccounts.GetAccount(id)
}
@@ -106,9 +106,14 @@ func (a *IAMAccounts) GetAccount(accountID string) (*Account, error) {
if err != nil {
return nil, err
}
return &Account{
out := &Account{
AccountID: account.AccountID, AccountName: account.AccountName, Status: account.Status,
}, nil
Generation: account.Generation,
}
if op := account.TerminationOp; op != nil {
out.TerminationOp = &TerminationOp{OperationID: op.OperationID, Fence: op.Fence}
}
return out, nil
}
func (a *IAMAccounts) QuiesceAccount(accountID, operationID string, fence uint64) (uint64, error) {
@@ -136,6 +136,16 @@ type Account struct {
AccountID string
AccountName string
Status string
// Generation and TerminationOp are what a quiesce read-back compares.
Generation uint64
TerminationOp *TerminationOp
}
// TerminationOp mirrors the operation and fence IAM holds on a terminating account.
type TerminationOp struct {
OperationID string
Fence uint64
}
// Request is one teardown.
+11
View File
@@ -85,6 +85,9 @@ type accountDeletionJob struct {
Holder string `json:"holder,omitempty"`
LeaseUntil string `json:"leaseUntil,omitempty"`
Takeovers []deletionTakeover `json:"takeovers,omitempty"`
// IAM is the quiescence evaluation made under the current fence. A takeover
// starts without one and the new holder records its own.
IAM *operatorv1.IAMQuiescence `json:"iam,omitempty"`
}
// deletionTakeover records one change of holder.
@@ -258,6 +261,7 @@ func (d Deps) runAccountDeletion(
ctx, cancel := context.WithTimeout(context.Background(), accountDeletionTimeout)
tracker := &deletionTracker{jobs: jobs, job: job, revision: revision, cancel: cancel}
engine.OnStage = tracker.stageFinished
engine.OnQuiesced = tracker.quiesced
go func() {
defer cancel()
@@ -297,6 +301,13 @@ func (t *deletionTracker) stageFinished(ctx context.Context, stage accountteardo
t.persist(ctx)
}
func (t *deletionTracker) quiesced(ctx context.Context, quiescence operatorv1.IAMQuiescence) {
t.mu.Lock()
t.job.IAM = &quiescence
t.mu.Unlock()
t.persist(ctx)
}
func (t *deletionTracker) finished(ctx context.Context, result *accountteardown.Result, err error) {
t.mu.Lock()
if result != nil {
@@ -0,0 +1,141 @@
package admin
//test:in-package — the job record, the tracker and the takeover that clears the
// evaluation are unexported.
import (
"encoding/json"
"strings"
"sync/atomic"
"testing"
"time"
operatorv1 "github.com/mulgadc/spinifex/contracts/operator/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func sampleQuiescence(fence uint64) operatorv1.IAMQuiescence {
return operatorv1.IAMQuiescence{
OperationID: "op-1", Fence: fence, Generation: 4,
QuiescedScope: []string{},
Unresolved: []operatorv1.UnresolvedScope{{
Scope: "ec2-key-pair", Class: operatorv1.UnresolvedClassWriter,
Reason: operatorv1.ReasonFinalInventoryRereadNotWired,
}},
Consumers: []operatorv1.ConsumerBasis{{Consumer: "awsgw-admission", Basis: "ADR-0005:S7"}},
Writers: []operatorv1.AccountedWriter{{Writer: "daemon-nats-handlers", Basis: "owner-inventory", Ref: "mulga-tpoz4"}},
Inventory: []operatorv1.InventoryStatus{{Kind: "key-pair", Status: "observed-clean-at-scan-time"}},
EvaluatedAt: "2026-11-02T00:00:00Z",
}
}
// A normal deletion leaves the evaluation on the record, read back from the real
// IAM account record, and DescribeAccountDeletion returns it.
func TestDeletionRecordCarriesTheIAMQuiescence(t *testing.T) {
gw := newDeleteAccountGateway(t)
account := newTenantAccount(t, gw, "tenant@example.com")
_, err := gw.deleteAccount(t.Context(),
deleteAccountBody(t, account.AccountID, "tenant@example.com", deleteClientToken))
require.NoError(t, err)
require.Eventually(t, func() bool {
return describeDeletion(t, gw, account.AccountID).State == operatorv1.DeletionStateCompleted
}, 30*time.Second, 100*time.Millisecond)
stored := describeDeletion(t, gw, account.AccountID)
require.NotNil(t, stored.IAM)
assert.Equal(t, stored.OperationID, stored.IAM.OperationID)
assert.Equal(t, uint64(1), stored.IAM.Fence)
assert.Positive(t, stored.IAM.Generation)
assert.Empty(t, stored.IAM.QuiescedScope)
assert.NotEmpty(t, stored.IAM.Unresolved)
assert.Len(t, stored.IAM.Consumers, 3)
// The stubbed cluster answers the inventory subject with an empty body, which
// is an incomplete inventory, and recording that must not fail the teardown.
for _, kind := range []string{"ec2-key-pair", "ec2-placement-group", "ec2-launch-template"} {
var reasons []string
for _, entry := range stored.IAM.Unresolved {
if entry.Scope == kind {
reasons = append(reasons, entry.Reason)
}
}
assert.Equal(t, []string{operatorv1.ReasonOwnerInventoryIncomplete}, reasons, kind)
}
}
// The evaluation belongs to a fence: a holder that has been taken over cannot
// write it into the new holder's record.
func TestSupersededHolderCannotWriteTheQuiescence(t *testing.T) {
gw := newDeleteAccountGateway(t)
jobs, err := gw.accountDeletionStore(t.Context())
require.NoError(t, err)
const accountID = "000000000042"
holderA, revisionA, err := claimAs(t, jobs, accountID, strings.Repeat("a", 32), "node-a")
require.NoError(t, err)
var cancelled atomic.Bool
trackerA := &deletionTracker{jobs: jobs, job: holderA, revision: revisionA, cancel: func() { cancelled.Store(true) }}
expireLease(t, jobs, accountID)
_, _, err = claimAs(t, jobs, accountID, strings.Repeat("b", 32), "node-b")
require.NoError(t, err)
trackerA.quiesced(t.Context(), sampleQuiescence(1))
assert.True(t, cancelled.Load())
stored := describeDeletion(t, gw, accountID)
assert.Equal(t, uint64(2), stored.Fence)
assert.Nil(t, stored.IAM, "the old holder's evaluation must not land under the new fence")
}
// A takeover starts without the previous fence's evaluation, and the new holder
// records its own under the new fence.
func TestTakeoverClearsTheQuiescenceAndTheNewHolderRecordsItsOwn(t *testing.T) {
gw := newDeleteAccountGateway(t)
jobs, err := gw.accountDeletionStore(t.Context())
require.NoError(t, err)
const accountID = "000000000042"
holderA, revisionA, err := claimAs(t, jobs, accountID, strings.Repeat("a", 32), "node-a")
require.NoError(t, err)
trackerA := &deletionTracker{jobs: jobs, job: holderA, revision: revisionA}
trackerA.quiesced(t.Context(), sampleQuiescence(1))
require.NotNil(t, describeDeletion(t, gw, accountID).IAM)
expireLease(t, jobs, accountID)
holderB, revisionB, err := claimAs(t, jobs, accountID, strings.Repeat("b", 32), "node-b")
require.NoError(t, err)
assert.Nil(t, holderB.IAM)
assert.Nil(t, describeDeletion(t, gw, accountID).IAM, "the record shows no evaluation until the new holder makes one")
trackerB := &deletionTracker{jobs: jobs, job: holderB, revision: revisionB}
trackerB.quiesced(t.Context(), sampleQuiescence(2))
stored := describeDeletion(t, gw, accountID)
require.NotNil(t, stored.IAM)
assert.Equal(t, uint64(2), stored.IAM.Fence)
}
// The field is optional on the wire: a record from before it decodes without it
// and prints without it, and one with it keeps the lists as arrays.
func TestAdminWire_DeletionJobIAMIsOptional(t *testing.T) {
var old accountDeletionJob
require.NoError(t, json.Unmarshal([]byte(`{"deletionId":"d","accountId":"000000000042","state":"RUNNING"}`), &old))
assert.Nil(t, old.IAM)
encoded, err := json.Marshal(old)
require.NoError(t, err)
assert.NotContains(t, string(encoded), `"iam"`)
quiescence := sampleQuiescence(1)
data, err := json.Marshal(accountDeletionJob{DeletionID: "d", AccountID: "000000000042", State: "RUNNING", IAM: &quiescence})
require.NoError(t, err)
var raw map[string]json.RawMessage
require.NoError(t, json.Unmarshal(data, &raw))
goldenJSON(t, raw["iam"], `{
"operationId":"op-1","fence":1,"generation":4,"quiescedScope":[],
"unresolved":[{"scope":"ec2-key-pair","class":"writer","reason":"final-inventory-reread-not-wired"}],
"consumers":[{"consumer":"awsgw-admission","basis":"ADR-0005:S7"}],
"writers":[{"writer":"daemon-nats-handlers","basis":"owner-inventory","ref":"mulga-tpoz4"}],
"inventory":[{"kind":"key-pair","status":"observed-clean-at-scan-time"}],
"evaluatedAt":"2026-11-02T00:00:00Z"}`)
}
+1 -1
View File
@@ -76,7 +76,7 @@ func ImportImage(ctx context.Context, provider ebsprovider.EBSProvider, opts Imp
// Unpublish regardless: a volume left published cannot be snapshotted or
// attached, and on the failure path it would strand the export too.
if err := provider.UnpublishVolume(ctx, ebsprovider.UnpublishVolumeRequest{
if _, err := provider.UnpublishVolume(ctx, ebsprovider.UnpublishVolumeRequest{
Versioned: ebsprovider.NewVersioned(),
VolumeID: opts.VolumeID,
NodeID: opts.NodeID,

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