carlos / platform Public

host: root-runner witness for the ingress drain order (W6 task 9)

TestRootIngressDrainOrder{Restart,AutoRestart,VerbAsk} and the
TestRootRebootIngressDrainOrder pair run the region HA terminate fixture
with the drain armed: fixed admission, region HA, target groups in the
runner's account and region, and a fake target health reader swapped into
the agent process (this test binary) through newIngressReader. Journal
timestamps prove the drain unit's ExecStop ends before any tenant stop
and the edge's SIGTERM; a request loop through the edge sees no failure
before step 3. The cross-release rollback and gate-failure cases are not
built: they need a second (pre-W6 rootrunner) binary and a two-version
apply fixture.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c82c1f6fd7e1fcb82f11bef0ce174e634e51b542 parent e62afc4
3 files changed, +808 −4
  • internal/host/haplacement_root_linux_test.go +13 −4
  • internal/host/haterminate_rootrunner_linux_test.go +5 −0
  • internal/host/ingressdrain_rootrunner_linux_test.go +790 −0

Intent

Human

<task-notification> <task-id>a05ab0c152ab72e3c</task-id> <tool-use-id>toolu_015nc5oWppCuN8NwZhWzyUKk</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a373aecd-faa9-4b83-8736-ff726fb2d3af/tasks/a05ab0c152ab72e3c.output</output-file> <status>completed</status> <summary>Agent "Implement W6 Task 10 (docs)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. I fixed all three review findings and the recovery wording. I left finding 4 (copy review) to you, as asked. Commits: e62afc45 (runbook only), on top of 1e6f138e. Not pushed. File changed: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/w6-build/docs/region-ha-runbook.md 1. The runbook no longer presents `withdrawn` as proof. It is what the target groups reported, plus a 10 s settle, and zero errors is a measured target. Both places list all the spec §3 exclusions. 2. `target group retention:` now has two causes: attributes not applied, or a failure to build the reader or read the attributes. It tells operators to read the error first. 3. `the agent's drain socket is not answering` no longer means only that the edge stopped. It also covers a box with region HA off or no target-group key, so the `not_armed` reasons and the setup step now say which line to expect. Recovery: the recovery verb does not ask for the drain. Its systemctl restart still runs the drain unit's stop if that unit is active, using the binary then on disk. Concerns: both commits printed the same `packed-refs.lock` error, but both landed on w6-ingress-drain (HEAD = branch = e62afc45). Report (fix round appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/w6-build/.superpowers/sdd/2026-11-10-fixed-edge-ingress-drain/task-10-report.md</result> <usage><subagent_tokens>107164</subagent_tokens><tool_uses>4</tool_uses><duration_ms>47154</duration_ms></usage> </task-notification>

Attributed to this commit: 41.8 g CO₂e (5,359,205 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on w6-ingress-drain, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/host/haplacement_root_linux_test.go b/internal/host/haplacement_root_linux_test.go
index 232d1ab4a..95be74719 100644
--- a/internal/host/haplacement_root_linux_test.go
+++ b/internal/host/haplacement_root_linux_test.go
@@ -601,7 +601,10 @@ func newColdRootHarness(t *testing.T, mode string, wrapS3 ...func(http.Handler)
egressRootPrereqs(t)
uid, gid := generationRunnerRegistryUser(t)
deploymentDir := lifecycleHome + "/deployment"
- if mode == "terminate" {
+ // The W6 ingress drain witness (ingressdrain_rootrunner_linux_test.go)
+ // runs the terminate fixture's real agent, with its drain armed.
+ terminateLike := mode == "terminate" || mode == ingressRootMode
+ if terminateLike {
deploymentDir = "/data/terminate-deployment"
}
for _, path := range []string{lifecycleHome, "/data", "/opt/carlos", "/run/carlos", "/run/carlos-control", "/etc/carlos", "/var/lib/carlos-claims", "/var/lib/carlos-release"} {
@@ -706,9 +709,12 @@ func newColdRootHarness(t *testing.T, mode string, wrapS3 ...func(http.Handler)
return string(out), err
}
units := []string{"carlos-edge.service", "carlos-instance-probe.service"}
- if mode == "terminate" {
+ if terminateLike {
units = append(units, "carlos-instance-gen@.service")
}
+ if mode == ingressRootMode {
+ units = append(units, ingressRootDrainUnit)
+ }
for _, name := range units {
raw, err := unitsFS.ReadFile("units/" + name)
lifecycleCheck(t, "production unit", err)
@@ -726,6 +732,9 @@ func newColdRootHarness(t *testing.T, mode string, wrapS3 ...func(http.Handler)
_, err = store.Put(t.Context(), "control/edge-mesh-key", []byte(strings.Repeat("a", 64)), "")
lifecycleCheck(t, "mesh key", err)
env := map[string]string{"COLD_ROOT_SHARED": lifecycleHome, "RHASIM_MUTATE": os.Getenv("RHASIM_MUTATE"), "COLD_ROOT_MODE": mode, "COLD_ROOT_BOX": "leo", "COLD_ROOT_HTTPS": "127.0.0.1:443", "PLAN14_LIFECYCLE_GUARD": "1", "CARLOS_HOST_CLAIM": "", "CARLOS_REGION_HA": "true", "CARLOS_HIBERNATE_BUCKET": "data", "CARLOS_HIBERNATE_REGION": "eu-west-1", "CARLOS_HIBERNATE_PREFIX": "instances", "CARLOS_DATA_DIR": "/data", "CARLOS_OPT_DIR": "/opt/carlos", "CARLOS_DEPLOYMENT_DIR": deploymentDir, "CARLOS_DEPLOYMENT_BUCKET": actor.ControlBucket, "CARLOS_RELEASE_PUBKEY": base64.StdEncoding.EncodeToString(key.Public().(ed25519.PublicKey)), "CARLOS_SECRETS_KEY": secret, "CARLOS_S3_ENDPOINT": activationS3Fixture(t, store), "COLD_ROOT_DATA_ENDPOINT": server.URL, "AWS_ACCESS_KEY_ID": "test-key", "AWS_SECRET_ACCESS_KEY": "test-secret", "AWS_EC2_METADATA_DISABLED": "true", "AWS_CONFIG_FILE": "/nonexistent", "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent", "AWS_REGION": "eu-west-1", "SSL_CERT_FILE": caFile, "TMPDIR": "/run/carlos", "PATH": os.Getenv("PATH")}
+ if mode == ingressRootMode {
+ ingressRootEnv(t, env)
+ }
var lines []string
for name, value := range env {
lines = append(lines, name+"="+value)
@@ -761,7 +770,7 @@ func newColdRootHarness(t *testing.T, mode string, wrapS3 ...func(http.Handler)
lifecycleCheck(t, "stage signed app", err)
lifecycleCheck(t, "point live", release.PointLive("/opt/carlos", lifecycleHost, "bab", "v1", "lifecycle"))
lifecycleCheck(t, "point sibling live", release.PointLive("/opt/carlos", lifecycleSibling, "bab", "v1", "lifecycle"))
- if mode == "terminate" {
+ if terminateLike {
for _, host := range []string{lifecycleHost, lifecycleSibling} {
lifecycleCheck(t, "install managed fixture build", release.MaterializeHost(t.Context(), reg, store, key.Public().(ed25519.PublicKey), "/opt/carlos", "/data", host))
row, err := reg.Get(host)
@@ -843,7 +852,7 @@ func newColdRootHarness(t *testing.T, mode string, wrapS3 ...func(http.Handler)
lifecycleCheck(t, "scenario environment", os.WriteFile("/etc/carlos/host.env", []byte(strings.Join(envLines, "\n")+"\n"), 0600))
out, err = ctl("start", "carlos-edge.service")
lifecycleCheck(t, out, err)
- if mode == "terminate" {
+ if terminateLike {
f := &coldRootHarness{t: t, model: model, store: store, reg: reg, ctl: ctl, env: env}
f.waitLeo()
return f
diff --git a/internal/host/haterminate_rootrunner_linux_test.go b/internal/host/haterminate_rootrunner_linux_test.go
index e81bf16bf..5a666fe03 100644
--- a/internal/host/haterminate_rootrunner_linux_test.go
+++ b/internal/host/haterminate_rootrunner_linux_test.go
@@ -71,6 +71,11 @@ func init() {
// This payload uses the agent entry and shutdown code, including its generation
// arming checks. The cold placement payload normally composes a smaller service.
func terminateRootAgent(t *testing.T) {
+ // The W6 ingress drain witness runs this same agent with a fake target
+ // health reader in place of the AWS adapter (the runner has no NLB).
+ if os.Getenv(ingressRootFakeEnv) == "1" {
+ ingressRootArmFake()
+ }
store := release.NewDirStore(os.Getenv("CARLOS_DEPLOYMENT_DIR"))
t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "")
t.Setenv("CARLOS_S3_ENDPOINT", os.Getenv("COLD_ROOT_DATA_ENDPOINT"))
diff --git a/internal/host/ingressdrain_rootrunner_linux_test.go b/internal/host/ingressdrain_rootrunner_linux_test.go
new file mode 100644
index 000000000..04200e3b7
--- /dev/null
+++ b/internal/host/ingressdrain_rootrunner_linux_test.go
@@ -0,0 +1,790 @@
+//go:build linux && rootrunner
+
+package host
+
+// W6 ingress drain, root runner witness (spec §9 "Root runner, real
+// systemd", §5.2, §5.3). It runs the region HA terminate fixture
+// (haterminate_rootrunner_linux_test.go, newColdRootHarness "terminate"):
+// the real agent under the production carlos-edge.service and guard, a real
+// HA tenant in a carlos-instance-gen@ unit, and the production
+// carlos-edge-drain.service with its edge Upholds= and tenant Before=. The
+// agent is a fixed box (CARLOS_GROUP_ADMISSION=1, not a group member) with
+// region HA on and CARLOS_INGRESS_TARGET_GROUPS naming two syntactically
+// valid target groups in the runner's own account and region, read from
+// IMDS.
+//
+// The runner has no NLB. The agent process is this test binary, so the
+// fake target health reader replaces the package's newIngressReader seam
+// in that process only (ingressRootArmFake, armed by an environment key the
+// fixture writes into host.env); no production code changes. The fake
+// reports the box healthy with one healthy peer until 10 s after the drain
+// builds its reader (the drain's start), then unhealthy; both target
+// groups keep unhealthy connections (termination off, 300 s draining).
+//
+// Evidence comes from the journal (PID 1's structured unit messages and the
+// drain unit's own output) and from a request loop this process runs
+// against the edge on 127.0.0.1:443. Network: IMDS only, plus loopback.
+//
+// Run each top-level test alone, on a fresh runner: each claims the
+// fixture's exclusive paths and units.
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/ingresshealth"
+)
+
+const (
+ ingressRootMode = "ingress-drain"
+ ingressRootFakeEnv = "W6_INGRESS_ROOT_FAKE"
+ ingressRootDrainUnit = "carlos-edge-drain.service"
+ ingressRootEdgeUnit = "carlos-edge.service"
+ // The fake turns the box unhealthy this long after the drain starts.
+ ingressRootUnhealthyAfter = 10 * time.Second
+ // A request started this close to step 3 may still be on a connection
+ // whose headers have not all arrived when Shutdown runs: spec §3
+ // refuses that case up front, so the loop does not count it.
+ ingressRootStep3Guard = 50 * time.Millisecond
+)
+
+// systemd's catalogue message ids for unit job messages.
+const (
+ sdUnitStopping = "de5b426a63be47a7b6ac3eaac82e2f6f"
+ sdUnitStopped = "9d1aaa27d60140bd96365438aad20286"
+ sdUnitSuccess = "7ad2d189f7e94e70a38c781354912448"
+ sdUnitFailed = "d9b373ed55a64feb8242e02dbe79a49c"
+)
+
+// The drain unit's ExecStop runs /opt/carlos/carlos __ingress-drain, and
+// /opt/carlos/carlos is this test binary in the fixture: dispatch the
+// production entry before the testing package parses anything.
+func init() {
+ if len(os.Args) >= 2 && os.Args[1] == "__ingress-drain" {
+ os.Exit(RunIngressDrain(os.Args[2:], os.Stdout))
+ }
+}
+
+// ingressRootFake is the target health the runner's agent reads.
+type ingressRootFake struct {
+ start time.Time
+ groups []string
+}
+
+func (f *ingressRootFake) Withdrawn(_ context.Context, self ingresshealth.Self) (ingresshealth.Verdict, error) {
+ state := ingresshealth.StateHealthy
+ if time.Since(f.start) >= ingressRootUnhealthyAfter {
+ state = ingresshealth.StateUnhealthy
+ }
+ var v ingresshealth.Verdict
+ for _, tg := range f.groups {
+ g := ingresshealth.Group{TargetGroup: tg, OtherHealthy: 1}
+ for _, port := range self.Ports {
+ g.Self = append(g.Self, ingresshealth.Entry{Port: port, State: state})
+ }
+ v.Groups = append(v.Groups, g)
+ }
+ return v, nil
+}
+
+func (f *ingressRootFake) Retention(context.Context) ([]ingresshealth.Retention, error) {
+ var out []ingresshealth.Retention
+ for _, tg := range f.groups {
+ out = append(out, ingresshealth.Retention{TargetGroup: tg, TerminationOff: true, DrainingInterval: 300 * time.Second})
+ }
+ return out, nil
+}
+
+// ingressRootArmFake runs in the agent process (terminateRootAgent).
+func ingressRootArmFake() {
+ newIngressReader = func(_ context.Context, region string, groups []string) (ingresshealth.Reader, error) {
+ log.Printf("ingress root fixture: fake target health for %d group(s) in %s: healthy until %s from now, then unhealthy", len(groups), region, ingressRootUnhealthyAfter)
+ return &ingressRootFake{start: time.Now(), groups: groups}, nil
+ }
+}
+
+// ingressRootEnv arms the drain in the fixture's host.env (spec §4.1): a
+// fixed box (tenant admission the fixed kind), region HA on (the fixture
+// already sets it), and target groups in the runner's own account and
+// region. Fixed admission needs the change index and the protected region
+// config its role reader reads (boxroles.go); with no role records the box
+// serves.
+func ingressRootEnv(t *testing.T, env map[string]string) {
+ t.Helper()
+ _, account, region, err := readIdentity(&http.Client{Timeout: 5 * time.Second}, imdsBase)
+ lifecycleCheck(t, "runner identity", err)
+ groups := []string{
+ fmt.Sprintf("arn:aws:elasticloadbalancing:%s:%s:targetgroup/w6-root-https/0123456789abcdef", region, account),
+ fmt.Sprintf("arn:aws:elasticloadbalancing:%s:%s:targetgroup/w6-root-http/fedcba9876543210", region, account),
+ }
+ parsed, err := ingresshealth.ParseTargetGroups(strings.Join(groups, ","), account, region)
+ lifecycleCheck(t, "fixture target groups", err)
+ if len(parsed) != 2 {
+ t.Fatalf("fixture target groups: %v", parsed)
+ }
+ // terminateRootAgent is the agent entry for this fixture.
+ env["COLD_ROOT_MODE"] = "terminate"
+ env[ingressRootFakeEnv] = "1"
+ env["CARLOS_GROUP_ADMISSION"] = "1"
+ env["CARLOS_CHANGE_INDEX"] = "read"
+ env[ingressTargetGroupsKey] = strings.Join(groups, ",")
+ path := roleRegionConfigPath
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
+ lifecycleCheck(t, "exclusive region config", err)
+ _, err = f.WriteString(`{"v":1,"region_code":"ie","placement":"ie"}` + "\n")
+ lifecycleCheck(t, "region config", errors.Join(err, f.Close()))
+}
+
+// ingressRootPrereqs checks what the witness decides (spec §5.2): the
+// drain unit is kept started by the edge's Upholds=, which needs systemd
+// 249 or later.
+func ingressRootPrereqs(t *testing.T) {
+ t.Helper()
+ if os.Geteuid() != 0 {
+ t.Fatal("requires the designated throwaway root runner")
+ }
+ out, err := exec.Command("systemctl", "--version").Output()
+ lifecycleCheck(t, "systemd version", err)
+ fields := strings.Fields(string(out))
+ if len(fields) < 2 || fields[0] != "systemd" {
+ t.Fatalf("systemd version: %q", out)
+ }
+ v, err := strconv.Atoi(fields[1])
+ lifecycleCheck(t, "systemd version number", err)
+ t.Logf("systemd %d", v)
+ if v < 249 {
+ t.Fatalf("systemd %d has no Upholds=; spec §5.2 needs Wants= on this image", v)
+ }
+}
+
+// ingressRootFixture is the running fixture: the agent, its tenant awake
+// and the drain unit up.
+type ingressRootFixture struct {
+ t *testing.T
+ f *coldRootHarness
+ request *http.Request
+}
+
+func newIngressRootFixture(t *testing.T) *ingressRootFixture {
+ ingressRootPrereqs(t)
+ f := newColdRootHarness(t, ingressRootMode)
+ req, err := http.NewRequest("GET", "https://"+lifecycleHost+"/", nil)
+ lifecycleCheck(t, "request template", err)
+ coldRootAuthorize(t, req)
+ x := &ingressRootFixture{t: t, f: f, request: req}
+ x.awaitServing("first wake")
+ return x
+}
+
+// awaitServing waits for the tenant to answer through the edge (admission
+// open, tenant awake), and for the drain unit to be active.
+func (x *ingressRootFixture) awaitServing(why string) {
+ t := x.t
+ t.Helper()
+ client := coldRootClient(t, "127.0.0.1:443")
+ defer client.CloseIdleConnections()
+ deadline := time.Now().Add(3 * time.Minute)
+ last := ""
+ for {
+ ok, detail := ingressRootGet(client, x.request)
+ if ok {
+ break
+ }
+ last = detail
+ if time.Now().After(deadline) {
+ t.Fatalf("%s: tenant never served through the edge: %s\n%s", why, last, ingressRootAdmissionLog())
+ }
+ time.Sleep(time.Second)
+ }
+ deadline = time.Now().Add(30 * time.Second)
+ for {
+ out, _ := exec.Command("systemctl", "is-active", ingressRootDrainUnit).Output()
+ if strings.TrimSpace(string(out)) == "active" {
+ break
+ }
+ if time.Now().After(deadline) {
+ status, _ := exec.Command("systemctl", "status", "--no-pager", ingressRootDrainUnit).CombinedOutput()
+ t.Fatalf("%s: drain unit not active (Upholds=): %s\n%s", why, out, status)
+ }
+ time.Sleep(200 * time.Millisecond)
+ }
+ t.Logf("%s: tenant serving, drain unit active", why)
+}
+
+func ingressRootAdmissionLog() string {
+ out, _ := exec.Command("journalctl", "-b", "--no-pager", "-u", ingressRootEdgeUnit, "-n", "400").CombinedOutput()
+ var keep []string
+ for _, l := range strings.Split(string(out), "\n") {
+ if strings.Contains(l, "admission") || strings.Contains(l, "ingress") || strings.Contains(l, "change index") || strings.Contains(l, "role") {
+ keep = append(keep, l)
+ }
+ }
+ return strings.Join(keep, "\n")
+}
+
+func ingressRootGet(client *http.Client, tmpl *http.Request) (bool, string) {
+ resp, err := client.Do(tmpl.Clone(context.Background()))
+ if err != nil {
+ return false, err.Error()
+ }
+ defer resp.Body.Close()
+ body := make([]byte, 64)
+ n, _ := resp.Body.Read(body)
+ if resp.StatusCode != 200 || string(body[:n]) != "lifecycle tenant" {
+ return false, fmt.Sprintf("%d %q", resp.StatusCode, body[:n])
+ }
+ return true, ""
+}
+
+// tenantUnits is every unit bound to the edge other than the drain unit:
+// the spec's tenant units (§5.2). The awake tenant's generation unit must
+// be among them, and the drain unit must be bound too.
+func (x *ingressRootFixture) tenantUnits() map[string]bool {
+ t := x.t
+ t.Helper()
+ out, err := exec.Command("systemctl", "show", ingressRootEdgeUnit, "-p", "BoundBy", "--value").Output()
+ lifecycleCheck(t, "edge BoundBy", err)
+ units := map[string]bool{}
+ drain, gen := false, false
+ for _, u := range strings.Fields(string(out)) {
+ if u == ingressRootDrainUnit {
+ drain = true
+ continue
+ }
+ units[u] = true
+ if strings.HasPrefix(u, "carlos-instance-gen@") {
+ if active, _ := exec.Command("systemctl", "is-active", u).Output(); strings.TrimSpace(string(active)) == "active" {
+ gen = true
+ }
+ }
+ }
+ if !drain || !gen {
+ t.Fatalf("edge BoundBy %q: want the drain unit and an active tenant generation unit", out)
+ }
+ for u := range units {
+ before, err := exec.Command("systemctl", "show", u, "-p", "Before", "--value").Output()
+ lifecycleCheck(t, "tenant Before", err)
+ if !slices.Contains(strings.Fields(string(before)), ingressRootDrainUnit) {
+ t.Fatalf("tenant unit %s is not Before= the drain unit: %q", u, before)
+ }
+ }
+ t.Logf("tenant units: %v", ingressRootKeys(units))
+ return units
+}
+
+func ingressRootKeys(m map[string]bool) []string {
+ var out []string
+ for k := range m {
+ out = append(out, k)
+ }
+ sort.Strings(out)
+ return out
+}
+
+// IngressRootSample is one request of the loop.
+type IngressRootSample struct {
+ Start time.Time `json:"start"`
+ End time.Time `json:"end"`
+ OK bool `json:"ok"`
+ Close bool `json:"close"`
+ Detail string `json:"detail,omitempty"`
+}
+
+// ingressRootLoop is the request loop through the edge: two workers, each
+// one request at a time.
+type ingressRootLoop struct {
+ mu sync.Mutex
+ samples []IngressRootSample
+ cancel context.CancelFunc
+ wg sync.WaitGroup
+}
+
+func (x *ingressRootFixture) startLoop() *ingressRootLoop {
+ ctx, cancel := context.WithCancel(context.Background())
+ l := &ingressRootLoop{cancel: cancel}
+ for range 2 {
+ client := coldRootClient(x.t, "127.0.0.1:443")
+ client.Timeout = 40 * time.Second
+ l.wg.Add(1)
+ go func() {
+ defer l.wg.Done()
+ defer client.CloseIdleConnections()
+ for ctx.Err() == nil {
+ s := IngressRootSample{Start: time.Now()}
+ resp, err := client.Do(x.request.Clone(ctx))
+ if err != nil {
+ s.Detail = err.Error()
+ } else {
+ body := make([]byte, 64)
+ n, _ := resp.Body.Read(body)
+ resp.Body.Close()
+ s.Close = resp.Close
+ s.OK = resp.StatusCode == 200 && string(body[:n]) == "lifecycle tenant"
+ if !s.OK {
+ s.Detail = fmt.Sprintf("%d %q", resp.StatusCode, body[:n])
+ }
+ }
+ s.End = time.Now()
+ if ctx.Err() != nil && !s.OK {
+ return
+ }
+ l.mu.Lock()
+ l.samples = append(l.samples, s)
+ l.mu.Unlock()
+ time.Sleep(50 * time.Millisecond)
+ }
+ }()
+ }
+ x.t.Cleanup(l.stop)
+ return l
+}
+
+func (l *ingressRootLoop) stop() {
+ l.cancel()
+ l.wg.Wait()
+}
+
+func (l *ingressRootLoop) snapshot() []IngressRootSample {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return append([]IngressRootSample(nil), l.samples...)
+}
+
+// checkIngressRootLoop is spec §9's "request loop at 0 failures until step
+// 3": every request started before the listeners began to close succeeded,
+// requests went on being served during the drain, and they carried
+// Connection: close (step 1).
+func checkIngressRootLoop(t *testing.T, samples []IngressRootSample, rep *ingressReport) {
+ t.Helper()
+ step1, step3 := *rep.HealthFailedAt, *rep.WaitEndedAt
+ var failed []IngressRootSample
+ before, during, closing := 0, 0, 0
+ for _, s := range samples {
+ if !s.Start.Before(step3.Add(-ingressRootStep3Guard)) {
+ continue
+ }
+ if !s.OK {
+ failed = append(failed, s)
+ continue
+ }
+ if s.Start.Before(step1) {
+ before++
+ } else {
+ during++
+ if s.Close {
+ closing++
+ }
+ }
+ }
+ t.Logf("request loop: %d sample(s); before step 3: %d served before the drain, %d during it (%d with Connection: close), %d failed", len(samples), before, during, closing, len(failed))
+ if len(failed) > 0 {
+ if len(failed) > 5 {
+ failed = failed[:5]
+ }
+ t.Fatalf("requests failed before step 3 (%s): %+v", step3.Format(time.RFC3339Nano), failed)
+ }
+ if before == 0 || during < 5 || closing == 0 {
+ t.Fatalf("request loop too thin to witness the drain: before=%d during=%d closing=%d", before, during, closing)
+ }
+}
+
+// journalEntry is one journalctl -o json record, the fields read here.
+type journalEntry struct {
+ At time.Time
+ MessageID string
+ Unit string // UNIT=, the unit PID 1 writes about
+ Source string // _SYSTEMD_UNIT=, the unit that wrote it
+ PID string
+ Message string
+}
+
+// ingressRootJournal reads PID 1's records and the edge's and drain unit's
+// own output, from since on, in the journal's order. Extra args select the
+// boot (-b, -b -1).
+func ingressRootJournal(t *testing.T, since time.Time, boot ...string) []journalEntry {
+ t.Helper()
+ _ = exec.Command("journalctl", "--sync").Run()
+ args := append([]string{"--no-pager", "-o", "json", "--since", since.Add(-2*time.Second).UTC().Format("2006-01-02 15:04:05") + " UTC"}, boot...)
+ args = append(args, "_PID=1", "+", "_SYSTEMD_UNIT="+ingressRootDrainUnit, "_SYSTEMD_UNIT="+ingressRootEdgeUnit)
+ out, err := exec.Command("journalctl", args...).Output()
+ lifecycleCheck(t, "journal", err)
+ var entries []journalEntry
+ sc := bufio.NewScanner(strings.NewReader(string(out)))
+ sc.Buffer(make([]byte, 1<<20), 16<<20)
+ for sc.Scan() {
+ var raw map[string]json.RawMessage
+ if json.Unmarshal(sc.Bytes(), &raw) != nil {
+ continue
+ }
+ field := func(k string) string {
+ v, ok := raw[k]
+ if !ok {
+ return ""
+ }
+ var s string
+ if json.Unmarshal(v, &s) == nil {
+ return s
+ }
+ var b []byte
+ var ints []int
+ if json.Unmarshal(v, &ints) == nil {
+ for _, i := range ints {
+ b = append(b, byte(i))
+ }
+ return string(b)
+ }
+ return ""
+ }
+ us, err := strconv.ParseInt(field("__REALTIME_TIMESTAMP"), 10, 64)
+ if err != nil {
+ continue
+ }
+ e := journalEntry{At: time.UnixMicro(us), MessageID: field("MESSAGE_ID"), Unit: field("UNIT"), Source: field("_SYSTEMD_UNIT"), PID: field("_PID"), Message: field("MESSAGE")}
+ if e.At.Before(since) {
+ continue
+ }
+ entries = append(entries, e)
+ }
+ lifecycleCheck(t, "journal scan", sc.Err())
+ return entries
+}
+
+func (e journalEntry) pid1(id, unit string) bool {
+ return e.PID == "1" && e.MessageID == id && e.Unit == unit
+}
+
+// ingressRootStop is one stop of the edge as the journal shows it.
+type ingressRootStop struct {
+ DrainStopping, DrainEnd time.Time
+ TenantStop, EdgeStopping time.Time
+ TenantUnit string
+ Lines []string // the drain unit's own output
+ Report *ingressReport
+ ReportAt time.Time
+}
+
+// ingressRootOrder reads one stop of the edge from entries and checks spec
+// §9's order: the drain unit's ExecStop ended before any tenant unit's
+// first stop and before the edge's SIGTERM (its stop job: the edge has no
+// ExecStop, so systemd signals it as the job starts). With killed set the
+// edge died first: there is no edge stop job, and the drain must have ended
+// within a second, having found the agent gone.
+func ingressRootOrder(t *testing.T, entries []journalEntry, tenants map[string]bool, killed bool) ingressRootStop {
+ t.Helper()
+ var s ingressRootStop
+ stopIdx, endIdx, tenantIdx, edgeIdx := -1, -1, -1, -1
+ for i, e := range entries {
+ switch {
+ case stopIdx < 0 && e.pid1(sdUnitStopping, ingressRootDrainUnit):
+ stopIdx, s.DrainStopping = i, e.At
+ case stopIdx >= 0 && endIdx < 0 && (e.pid1(sdUnitSuccess, ingressRootDrainUnit) || e.pid1(sdUnitStopped, ingressRootDrainUnit) || e.pid1(sdUnitFailed, ingressRootDrainUnit)):
+ endIdx, s.DrainEnd = i, e.At
+ case tenantIdx < 0 && e.PID == "1" && e.MessageID == sdUnitStopping && tenants[e.Unit]:
+ tenantIdx, s.TenantStop, s.TenantUnit = i, e.At, e.Unit
+ case edgeIdx < 0 && e.pid1(sdUnitStopping, ingressRootEdgeUnit):
+ edgeIdx, s.EdgeStopping = i, e.At
+ }
+ if e.Source == ingressRootDrainUnit && e.PID != "1" && stopIdx >= 0 && endIdx < 0 {
+ s.Lines = append(s.Lines, e.Message)
+ if js, ok := strings.CutPrefix(e.Message, "ingress drain report: "); ok {
+ var rep ingressReport
+ lifecycleCheck(t, "drain report", json.Unmarshal([]byte(js), &rep))
+ s.Report, s.ReportAt = &rep, e.At
+ }
+ }
+ }
+ t.Logf("journal: drain stopping %s, drain ended %s, first tenant stop %s (%s), edge stop job %s", ts(s.DrainStopping), ts(s.DrainEnd), ts(s.TenantStop), s.TenantUnit, ts(s.EdgeStopping))
+ for _, l := range s.Lines {
+ t.Logf("drain unit: %s", l)
+ }
+ if stopIdx < 0 || endIdx < 0 {
+ t.Fatal("the journal shows no complete stop of the drain unit")
+ }
+ if tenantIdx < 0 {
+ t.Fatal("the journal shows no stop of a tenant unit")
+ }
+ if tenantIdx < endIdx || s.TenantStop.Before(s.DrainEnd) {
+ t.Fatalf("tenant unit %s began stopping at %s, before the drain's ExecStop ended at %s", s.TenantUnit, ts(s.TenantStop), ts(s.DrainEnd))
+ }
+ if killed {
+ if took := s.DrainEnd.Sub(s.DrainStopping); took > time.Second {
+ t.Fatalf("the drain took %s after the agent was killed; want under 1 s", took)
+ }
+ if s.Report != nil || !strings.Contains(strings.Join(s.Lines, "\n"), "not answering") {
+ t.Fatalf("the drain after a kill must find the agent gone and run nothing: %q", s.Lines)
+ }
+ return s
+ }
+ if edgeIdx < 0 {
+ t.Fatal("the journal shows no stop job for the edge")
+ }
+ if edgeIdx < endIdx || s.EdgeStopping.Before(s.DrainEnd) {
+ t.Fatalf("the edge's stop (SIGTERM) began at %s, before the drain's ExecStop ended at %s", ts(s.EdgeStopping), ts(s.DrainEnd))
+ }
+ if s.Report == nil {
+ t.Fatalf("the drain unit logged no report: %q", s.Lines)
+ }
+ rep := s.Report
+ if rep.Result != "done" || rep.Verdict != ingressWithdrawn || rep.StartedAt == nil || rep.HealthFailedAt == nil || rep.WaitEndedAt == nil || rep.ListenersClosedAt == nil || rep.FinishedAt == nil {
+ t.Fatalf("drain report: want done and withdrawn with every step's time: %+v", rep)
+ }
+ if len(rep.TargetGroups) != 2 {
+ t.Fatalf("drain report target groups: %v", rep.TargetGroups)
+ }
+ // The fake withdraws the box 10 s after the drain starts; the settle
+ // adds 10 s. Less than that means the drain did not wait for it.
+ if waited := rep.WaitEndedAt.Sub(*rep.StartedAt); waited < 2*ingressRootUnhealthyAfter-time.Second {
+ t.Fatalf("drain waited %s for the target groups; the fake needs 10 s and the settle 10 s more", waited)
+ }
+ if s.ReportAt.After(s.DrainEnd) || rep.FinishedAt.After(s.DrainEnd) {
+ t.Fatalf("drain report at %s (finished %s) is after the drain unit's stop ended at %s", ts(s.ReportAt), ts(*rep.FinishedAt), ts(s.DrainEnd))
+ }
+ return s
+}
+
+func ts(t time.Time) string {
+ if t.IsZero() {
+ return "-"
+ }
+ return t.UTC().Format("15:04:05.000000")
+}
+
+// afterRestart is spec §9's "drain unit active again after the restart",
+// with the tenant serving through the new agent.
+func (x *ingressRootFixture) afterRestart(why string) {
+ x.f.waitLeo()
+ x.awaitServing(why)
+}
+
+// TestRootIngressDrainOrderRestart: `systemctl restart carlos-edge` on a
+// fixed box with one awake tenant serving a request loop through the edge.
+func TestRootIngressDrainOrderRestart(t *testing.T) {
+ x := newIngressRootFixture(t)
+ tenants := x.tenantUnits()
+ loop := x.startLoop()
+ time.Sleep(2 * time.Second)
+ since := time.Now()
+ out, err := exec.Command("systemctl", "restart", ingressRootEdgeUnit).CombinedOutput()
+ lifecycleCheck(t, "restart "+string(out), err)
+ stop := ingressRootOrder(t, ingressRootJournal(t, since), tenants, false)
+ loop.stop()
+ checkIngressRootLoop(t, loop.snapshot(), stop.Report)
+ x.afterRestart("after restart")
+}
+
+// TestRootIngressDrainOrderAutoRestart: the agent is killed (SIGKILL to the
+// edge's main process) and systemd restarts it (Restart=always, which the
+// fixture otherwise turns off). The drain unit, stopped because its edge
+// stopped (BindsTo=), finds the socket dead and exits within 1 s, still
+// ahead of the tenants; Upholds= starts it again with the edge.
+func TestRootIngressDrainOrderAutoRestart(t *testing.T) {
+ x := newIngressRootFixture(t)
+ dropin := "/run/systemd/system/" + ingressRootEdgeUnit + ".d/20-w6-auto-restart.conf"
+ f, err := os.OpenFile(dropin, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
+ lifecycleCheck(t, "exclusive restart drop-in", err)
+ _, err = f.WriteString("[Service]\nRestart=always\n")
+ lifecycleCheck(t, "restart drop-in", errors.Join(err, f.Close()))
+ t.Cleanup(func() { _ = os.Remove(dropin); _ = exec.Command("systemctl", "daemon-reload").Run() })
+ out, err := exec.Command("systemctl", "daemon-reload").CombinedOutput()
+ lifecycleCheck(t, "daemon-reload "+string(out), err)
+ restart, err := exec.Command("systemctl", "show", ingressRootEdgeUnit, "-p", "Restart", "--value").Output()
+ lifecycleCheck(t, "edge Restart", err)
+ if strings.TrimSpace(string(restart)) != "always" {
+ t.Fatalf("edge Restart=%q", restart)
+ }
+ tenants := x.tenantUnits()
+ pid, err := exec.Command("systemctl", "show", ingressRootEdgeUnit, "-p", "MainPID", "--value").Output()
+ lifecycleCheck(t, "edge main pid", err)
+ since := time.Now()
+ out, err = exec.Command("systemctl", "kill", "--kill-whom=main", "--signal=KILL", ingressRootEdgeUnit).CombinedOutput()
+ lifecycleCheck(t, "kill "+string(out), err)
+ deadline := time.Now().Add(2 * time.Minute)
+ for {
+ now, _ := exec.Command("systemctl", "show", ingressRootEdgeUnit, "-p", "MainPID", "--value").Output()
+ state, _ := exec.Command("systemctl", "is-active", ingressRootEdgeUnit).Output()
+ if p := strings.TrimSpace(string(now)); p != "0" && p != strings.TrimSpace(string(pid)) && strings.TrimSpace(string(state)) == "active" {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("the edge did not restart on its own: pid %s state %s", now, state)
+ }
+ time.Sleep(200 * time.Millisecond)
+ }
+ x.afterRestart("after automatic restart")
+ ingressRootOrder(t, ingressRootJournal(t, since), tenants, true)
+}
+
+// TestRootIngressDrainOrderVerbAsk is the root verbs' half of spec §5.3 on
+// real systemd: root asks for the drain through the production drain-call
+// child (execIngressDrain: this binary re-executed from its pinned
+// /proc/self/exe, dropped to carlos, over the agent's socket), as apply and
+// rollback do before their quiesce and swap; then the edge restarts as
+// they would restart it, and the drain unit's ExecStop joins the drain
+// already done (the same report, answered at once) ahead of every tenant.
+// It does not swap binaries: the cross-release rollback and the
+// gate-failure apply need a pre-W6 build (see the task 9 report).
+func TestRootIngressDrainOrderVerbAsk(t *testing.T) {
+ x := newIngressRootFixture(t)
+ tenants := x.tenantUnits()
+ loop := x.startLoop()
+ time.Sleep(2 * time.Second)
+ since := time.Now()
+ ctx, cancel := context.WithTimeout(context.Background(), ingressAskBound+10*time.Second)
+ defer cancel()
+ r, err := execIngressDrain(ctx)
+ lifecycleCheck(t, "the verbs' drain call", err)
+ for _, l := range ingressCallLines(r) {
+ t.Logf("verb: %s", l)
+ }
+ asked := time.Now()
+ rep := r.Ingress
+ if rep == nil || rep.Result != "done" || rep.Verdict != ingressWithdrawn || rep.WaitEndedAt == nil || rep.HealthFailedAt == nil || rep.StartedAt == nil {
+ t.Fatalf("the verbs' drain: want done and withdrawn: %+v", r)
+ }
+ loop.stop()
+ checkIngressRootLoop(t, loop.snapshot(), rep)
+ out, err := exec.Command("systemctl", "restart", ingressRootEdgeUnit).CombinedOutput()
+ lifecycleCheck(t, "restart "+string(out), err)
+ stop := ingressRootOrder(t, ingressRootJournal(t, since), tenants, false)
+ if !stop.DrainStopping.After(asked) {
+ t.Fatalf("the drain unit began stopping at %s, before the verb's drain answered at %s", ts(stop.DrainStopping), ts(asked))
+ }
+ if !stop.Report.StartedAt.Equal(*rep.StartedAt) || stop.Report.Incarnation != rep.Incarnation {
+ t.Fatalf("the drain unit ran a second drain instead of joining the verb's: %+v vs %+v", stop.Report, rep)
+ }
+ if took := stop.DrainEnd.Sub(stop.DrainStopping); took > 2*time.Second {
+ t.Fatalf("joining a finished drain took %s", took)
+ }
+ x.afterRestart("after the verb's drain and restart")
+}
+
+// The reboot pair. Phase 1 runs the fixture in a transient unit that
+// outlives the edge at shutdown (the terminate witness's pattern), so
+// nothing tears it down before the reboot, and records what phase 2 needs
+// under ingressRootRebootDir. Phase 2 reads the previous boot's journal.
+
+const ingressRootRebootDir = "/var/lib/w6-ingress-reboot"
+const ingressRootRebootUnit = "w6-ingress-reboot-witness.service"
+
+type ingressRootRebootState struct {
+ BootID string `json:"boot_id"`
+ ReadyAt time.Time `json:"ready_at"`
+ Tenants []string `json:"tenants"`
+}
+
+func TestRootRebootIngressDrainOrderPhase1(t *testing.T) {
+ if os.Geteuid() != 0 {
+ t.Fatal("requires the designated throwaway root runner")
+ }
+ if os.Getenv("W6_INGRESS_REBOOT_PAYLOAD") == "1" {
+ ingressRootRebootPayload(t)
+ return
+ }
+ lifecycleCheck(t, "exclusive reboot state", os.Mkdir(ingressRootRebootDir, 0700))
+ // Phase 2 reads the previous boot: the journal must persist.
+ if _, err := os.Stat("/var/log/journal"); errors.Is(err, os.ErrNotExist) {
+ lifecycleCheck(t, "persistent journal", os.Mkdir("/var/log/journal", 0755))
+ _ = exec.Command("systemd-tmpfiles", "--create", "--prefix", "/var/log/journal").Run()
+ }
+ out, err := exec.Command("journalctl", "--flush").CombinedOutput()
+ lifecycleCheck(t, "journal flush "+string(out), err)
+ exe, err := os.Executable()
+ lifecycleCheck(t, "witness executable", err)
+ out, err = exec.Command("systemd-run", "--unit="+ingressRootRebootUnit, "--property=Type=exec", "--property=Before="+ingressRootEdgeUnit, "--property=After=network.target", "--property=DefaultDependencies=yes", "--property=TimeoutStopSec=90s", "--setenv=W6_INGRESS_REBOOT_PAYLOAD=1", "--setenv=TMPDIR=/var/tmp", exe, "-test.run=^TestRootRebootIngressDrainOrderPhase1$", "-test.v", "-test.timeout=60m").CombinedOutput()
+ lifecycleCheck(t, string(out), err)
+ deadline := time.Now().Add(10 * time.Minute)
+ for time.Now().Before(deadline) {
+ if raw, err := os.ReadFile(filepath.Join(ingressRootRebootDir, "state.json")); err == nil {
+ t.Logf("READY %s", raw)
+ return
+ }
+ if out, err := exec.Command("systemctl", "is-active", ingressRootRebootUnit).CombinedOutput(); err != nil {
+ journal, _ := exec.Command("journalctl", "-b", "--no-pager", "-n", "200", "-u", ingressRootRebootUnit, "-u", ingressRootEdgeUnit, "-u", ingressRootDrainUnit).CombinedOutput()
+ t.Fatalf("witness stopped: %s\n%s", out, journal)
+ }
+ time.Sleep(time.Second)
+ }
+ journal, _ := exec.Command("journalctl", "-b", "--no-pager", "-n", "200", "-u", ingressRootRebootUnit, "-u", ingressRootEdgeUnit).CombinedOutput()
+ t.Fatalf("witness readiness timeout:\n%s", journal)
+}
+
+func ingressRootRebootPayload(t *testing.T) {
+ stopped := make(chan os.Signal, 1)
+ signal.Notify(stopped, syscall.SIGTERM, syscall.SIGINT)
+ defer signal.Stop(stopped)
+ x := newIngressRootFixture(t)
+ tenants := x.tenantUnits()
+ loop := x.startLoop()
+ boot, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
+ lifecycleCheck(t, "boot id", err)
+ state, err := json.Marshal(ingressRootRebootState{BootID: strings.TrimSpace(string(boot)), ReadyAt: time.Now(), Tenants: ingressRootKeys(tenants)})
+ lifecycleCheck(t, "reboot state", err)
+ ingressRootWriteDurable(t, "state.json", state)
+ <-stopped
+ // The edge has stopped (this unit is ordered after it at shutdown):
+ // keep what the loop saw for phase 2.
+ loop.cancel()
+ samples, err := json.Marshal(loop.snapshot())
+ lifecycleCheck(t, "loop samples", err)
+ ingressRootWriteDurable(t, "samples.json", samples)
+ // Shutdown owns the machine now; no fixture cleanups.
+ os.Exit(0)
+}
+
+func ingressRootWriteDurable(t *testing.T, name string, raw []byte) {
+ t.Helper()
+ tmp := filepath.Join(ingressRootRebootDir, "."+name)
+ f, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ lifecycleCheck(t, "state file", err)
+ _, err = f.Write(raw)
+ err = errors.Join(err, f.Sync(), f.Close())
+ lifecycleCheck(t, "state write", err)
+ lifecycleCheck(t, "state rename", os.Rename(tmp, filepath.Join(ingressRootRebootDir, name)))
+ dir, err := os.Open(ingressRootRebootDir)
+ lifecycleCheck(t, "state dir", err)
+ lifecycleCheck(t, "state dir sync", errors.Join(dir.Sync(), dir.Close()))
+}
+
+func TestRootRebootIngressDrainOrderPhase2(t *testing.T) {
+ if os.Geteuid() != 0 {
+ t.Fatal("requires the designated throwaway root runner")
+ }
+ raw, err := os.ReadFile(filepath.Join(ingressRootRebootDir, "state.json"))
+ lifecycleCheck(t, "phase 1 state", err)
+ var state ingressRootRebootState
+ lifecycleCheck(t, "phase 1 state decode", json.Unmarshal(raw, &state))
+ boot, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
+ lifecycleCheck(t, "boot id", err)
+ if strings.TrimSpace(string(boot)) == state.BootID {
+ t.Fatal("phase 2 runs in phase 1's boot; the runner did not reboot")
+ }
+ tenants := map[string]bool{}
+ for _, u := range state.Tenants {
+ tenants[u] = true
+ }
+ stop := ingressRootOrder(t, ingressRootJournal(t, state.ReadyAt, "-b", "-1"), tenants, false)
+ raw, err = os.ReadFile(filepath.Join(ingressRootRebootDir, "samples.json"))
+ lifecycleCheck(t, "phase 1 request loop", err)
+ var samples []IngressRootSample
+ lifecycleCheck(t, "phase 1 request loop decode", json.Unmarshal(raw, &samples))
+ checkIngressRootLoop(t, samples, stop.Report)
+ // The runner is terminated after this phase; the fixture it left on
+ // disk goes with it.
+}