| 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. |
| +} |