carlos / platform Public

host: ingress drain driver and its socket routes on fixed boxes

The agent-side W6 drain (spec 4.1, 4.2): arming per ruling 5, step 1
through the edge and lbhealth, step 2 polling the target groups every
2 s with a 10 s settle and a 90 s cap, step 3 through the edge with a
30 s connection wait, a report, and the 3-minute exit through a seam.
One drain per process; a repeat joins. POST /v1/ingress/drain (bounded
at 140 s, the drain goes on if the caller leaves) and GET
/v1/ingress/status on the drain socket, now served on a fixed box whose
ingress drain is configured; there /v1/drain/* answers 404. Group
members are unchanged and answer group_member.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b7f428a46526544fc29eae9bb63f564048a7efa9 parent f37152d
7 files changed, +1,506 −13
  • internal/host/agent.go +35 −9
  • internal/host/hadrain_socket.go +43 −1
  • internal/host/hadrain_socket_linux.go +1 −1
  • internal/host/hadrain_socket_other.go +3 −2
  • internal/host/ingressdrain.go +566 −0
  • internal/host/ingressdrain_socket_linux_test.go +58 −0
  • internal/host/ingressdrain_test.go +800 −0

Intent

Human

<task-notification> <task-id>a1a34d61307c3ca38</task-id> <tool-use-id>toolu_017T3yv2xhx7HSAE1cS3bjFB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a373aecd-faa9-4b83-8736-ff726fb2d3af/tasks/a1a34d61307c3ca38.output</output-file> <status>completed</status> <summary>Agent "Implement W6 Task 3 (edge)" 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. Both review findings are fixed and committed on `w6-ingress-drain`. **Commits:** - `f37152de` edge: :80 joins the ingress drain; HA drain transitions under one lock - `fd382cd8` edge: ingress drain step 1 and step 3, guarded against the HA drain (the original task) **Tests:** The drain tests pass, including the 2 new regression tests: run 3 times, then once under `-race` together with `TestDrainConnections*`. `go build ./...`, the darwin and windows builds, and `internal/host -run Drain` also pass. I didn't rerun the 850 s full edge package. **Concerns:** - The exported signatures are unchanged. - :80 now has its own request tracker that only the ingress drain uses. So step 1 adds `Connection: close` there, and step 3 counts its requests, cuts them at the bound and waits for them to end. It never gets §25's barrier. `edge.go` and the tests now build both public servers the same way, so the tests check the real :80 wiring. - My first version of the new :80 test was wrong: :80 already answered `Connection: close` during a §25 drain before this change, because §25 turns keep-alives off on both servers. The test now checks only that :80 is not refused. - `EndConnectionDrain` and `DrainConnections` now hold the same lock as the ingress start for their whole state change. The regression test failed when its test hook sat in the old gap and passes now. - The commit printed a `packed-refs.lock` error (another git process, likely the host agent), but the branch did move to `f37152de`. - The uncommitted `internal/host` changes belong to the other agent. I left them alone. - The report is not committed because `.superpowers/` is gitignored. **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/w6-build/.superpowers/sdd/2026-11-10-fixed-edge-ingress-drain/task-3-report.md (fix round 1 added at the end)</result> <usage><subagent_tokens>130521</subagent_tokens><tool_uses>12</tool_uses><duration_ms>695100</duration_ms></usage> </task-notification>

Attributed to this commit: 10.3 g CO₂e (1,224,666 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/agent.go b/internal/host/agent.go
index 4803d52fd..3a779dd68 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1146,8 +1146,24 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// tunnelLoop is handed off to its own goroutine rather than called here —
// calling it directly would block the front door forever.
var shutdownDeadline time.Time
+ // The fixed box's ingress drain (W6, ingressdrain.go). Its arming is
+ // read when a drain is asked for, so an identity IMDS answers late
+ // still arms it. The agent's own shutdown disarms its 3-minute exit.
+ ingress := newIngressDrain(func() ingressArming {
+ return ingressDrainArming(os.Getenv, admission, lease.CurrentSelf())
+ }, lbhealth.Default)
+ if ingressDrainServed(os.Getenv, admission) {
+ if a := ingress.arm(); a.Answer == ingressArmed {
+ log.Printf("agent: ingress drain armed for %d target group(s)", len(a.Groups))
+ } else {
+ log.Printf("agent: ingress drain not armed yet: %s", a.Reason)
+ }
+ }
edgeOpts := append([]edge.RunOption{
- edge.WithShutdownStarted(func(at time.Time) { shutdownDeadline = at.Add(agentShutdownBudget) }),
+ edge.WithShutdownStarted(func(at time.Time) {
+ shutdownDeadline = at.Add(agentShutdownBudget)
+ ingress.shutdownStarted()
+ }),
// Certificate issuance is a deployment-global duty, so it runs where
// the housekeeper runs (housekeeper.go). The gate goes DOWN into the
// edge as a func — this package imports internal/edge and never the
@@ -1208,6 +1224,11 @@ func runAgent(args []string, buildClaims ClaimFactory) {
return w != nil && w.demoServingAllowed(rt, now)
}, &demoGate)
demoEdge.Store(e)
+ ingress.setEdge(e)
+ // The agent-user-only drain socket's routes (hadrain_socket.go):
+ // the group drain's, set below on a group member, and the ingress
+ // drain's.
+ driver := &haDrainSocket{ingress: ingress}
e.SetHAIngressLookup(boxHAIngress.lookup)
armedGroupReaders.Store(&groupReaderSource{snapshot: e.GroupReaderSnapshot})
// Read the current hub view on each private socket request.
@@ -1232,15 +1253,10 @@ func runAgent(args []string, buildClaims ClaimFactory) {
svc.SetPeerDrainView(e.PeerDraining)
e.SetPeerDrainedHook(svc.DropHoldersNaming)
e.SetPeerUndrainedHook(svc.AllowHoldersNaming)
- // The drain driver and its agent-user-only socket (hadrain.go),
- // on group members only: the drain verbs are theirs.
+ // The group drain driver (hadrain.go), on group members
+ // only: the drain verbs are theirs.
if admission != nil && admission.group {
- driver := newDrainDriver(svc, e, boxDrain, groupStartFence.read)
- healthWG.Add(1)
- go func() {
- defer healthWG.Done()
- serveHADrainSocket(healthCtx, haDrainSocketPath, driver)
- }()
+ driver.group = newDrainDriver(svc, e, boxDrain, groupStartFence.read)
}
svc.SetDutyView(func(rt registry.Route) boxchoice.WakeSnapshot {
if rt.IsSidecar() {
@@ -1254,6 +1270,16 @@ func runAgent(args []string, buildClaims ClaimFactory) {
})
}
}
+ // The drain socket: on a group member for its drain verbs, and on a
+ // fixed box whose ingress drain is configured, for the drain unit
+ // and the root verbs (W6 §5.2).
+ if driver.group != nil || ingressDrainServed(os.Getenv, admission) {
+ healthWG.Add(1)
+ go func() {
+ defer healthWG.Done()
+ serveHADrainSocket(healthCtx, haDrainSocketPath, driver)
+ }()
+ }
go tunnelLoop(e)
// The edge owns the health probers, so its state table is only
// reachable once it exists — statusLoop (already running above) reads
diff --git a/internal/host/hadrain_socket.go b/internal/host/hadrain_socket.go
index 1b378d53f..c389ea3c9 100644
--- a/internal/host/hadrain_socket.go
+++ b/internal/host/hadrain_socket.go
@@ -19,6 +19,16 @@ package host
//
// A step runs on the agent, not on the request: a caller that goes away
// leaves it running, and asking again with the same transaction joins it.
+//
+// Those routes are a group member's only. The same socket also serves the
+// fixed box's ingress drain (W6, ingressdrain.go), on a fixed box whose
+// ingress drain is configured and on group members (which answer
+// group_member):
+//
+// POST /v1/ingress/drain start or join; the report
+// GET /v1/ingress/status arming and the report so far
+//
+// On a fixed box the /v1/drain/* routes answer 404.
import (
"bytes"
@@ -29,6 +39,7 @@ import (
"io"
"net"
"net/http"
+ "strings"
"time"
)
@@ -52,7 +63,38 @@ type drainError struct {
Error string `json:"error"`
}
-// handler is the socket's HTTP surface over d.
+// drainSocketServer is what serveHADrainSocket serves.
+type drainSocketServer interface {
+ handler() http.Handler
+}
+
+// haDrainSocket is the socket's whole surface: the group drain's routes
+// when group is set (a group member), 404 otherwise, and the ingress
+// drain's routes when ingress is set.
+type haDrainSocket struct {
+ group *drainDriver
+ ingress *ingressDrain
+}
+
+func (s *haDrainSocket) handler() http.Handler {
+ group := http.NotFoundHandler()
+ if s.group != nil {
+ group = s.group.handler()
+ }
+ var ingress http.Handler
+ if s.ingress != nil {
+ ingress = s.ingress.handler()
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if ingress != nil && strings.HasPrefix(r.URL.Path, "/v1/ingress/") {
+ ingress.ServeHTTP(w, r)
+ return
+ }
+ group.ServeHTTP(w, r)
+ })
+}
+
+// handler is the socket's group drain surface over d.
func (d *drainDriver) handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
diff --git a/internal/host/hadrain_socket_linux.go b/internal/host/hadrain_socket_linux.go
index 0abacb53e..566b1b0cc 100644
--- a/internal/host/hadrain_socket_linux.go
+++ b/internal/host/hadrain_socket_linux.go
@@ -35,7 +35,7 @@ type drainPeerKey struct{}
// serveHADrainSocket serves d on path until ctx ends. Errors are logged:
// a box without the socket cannot be drained, and the verb says so.
-func serveHADrainSocket(ctx context.Context, path string, d *drainDriver) {
+func serveHADrainSocket(ctx context.Context, path string, d drainSocketServer) {
if err := serveHADrain(ctx, path, d.handler()); err != nil && ctx.Err() == nil {
log.Printf("agent: drain socket %s: %v", path, err)
}
diff --git a/internal/host/hadrain_socket_other.go b/internal/host/hadrain_socket_other.go
index e89d177ad..a17b3f5a1 100644
--- a/internal/host/hadrain_socket_other.go
+++ b/internal/host/hadrain_socket_other.go
@@ -4,5 +4,6 @@ package host
import "context"
-// The drain socket is Linux-only, as group members are.
-func serveHADrainSocket(context.Context, string, *drainDriver) {}
+// The drain socket is Linux-only, as group members and the boxes the
+// ingress drain unit runs on are.
+func serveHADrainSocket(context.Context, string, drainSocketServer) {}
diff --git a/internal/host/ingressdrain.go b/internal/host/ingressdrain.go
new file mode 100644
index 000000000..f1a5d73d0
--- /dev/null
+++ b/internal/host/ingressdrain.go
@@ -0,0 +1,566 @@
+package host
+
+// The fixed box's ingress drain driver (W6 spec §4.1, §4.2): before a
+// planned stop of the edge, fail the load balancer health check while
+// serving on, wait until the target groups report the box withdrawn, then
+// close the public listeners gracefully, and answer a report. It runs on
+// the agent, not on the request: the drain unit's ExecStop and the root
+// verbs reach it through the drain socket (hadrain_socket.go), a caller
+// that goes away leaves it running, and a second caller joins it. One
+// drain per agent process.
+//
+// Group members never run it: their planned paths go through §25's Standby
+// transaction (hadrain.go), and they answer group_member.
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/ingresshealth"
+ "github.com/carlosframework/platform/internal/ingresshealth/awstg"
+)
+
+// The drain's timings (spec §4.2). The cap is from the request; the
+// settle runs after the target groups first report the box withdrawn and
+// may end past the cap (the drain unit's 150 s stop timeout allows the
+// cap, the settle, the connection wait and slack).
+var (
+ ingressPollEvery = 2 * time.Second
+ ingressSettle = 10 * time.Second
+ ingressCap = 90 * time.Second
+ ingressConnWait = 30 * time.Second
+ ingressExitAfter = 3 * time.Minute
+ // ingressReadBound bounds one read of the target groups, so a hung
+ // call cannot hold the drain past its cap by more than this.
+ ingressReadBound = 5 * time.Second
+ // ingressCallBound is how long POST /v1/ingress/drain waits for the
+ // report before answering the drain as it stands.
+ ingressCallBound = 140 * time.Second
+)
+
+// ingressPorts are the ports the box is registered on in its target
+// groups: the edge's :80 and :443.
+var ingressPorts = []int32{80, 443}
+
+// The key that names the box's target groups (spec §4.1).
+const ingressTargetGroupsKey = "CARLOS_INGRESS_TARGET_GROUPS"
+
+// Arming answers.
+const (
+ ingressArmed = "armed"
+ ingressNotArmed = "not_armed"
+ ingressGroupMember = "group_member"
+)
+
+// Verdicts.
+const (
+ ingressWithdrawn = "withdrawn"
+ ingressUnverified = "unverified"
+)
+
+// ingressEdge is the edge's half of the drain (internal/edge
+// ingressdrain.go): step 1's Connection: close switch and step 3's
+// graceful close.
+type ingressEdge interface {
+ BeginIngressDrain() error
+ CloseIngress(ctx context.Context, wait time.Duration) (edge.IngressClose, error)
+}
+
+// ingressHealth is the load balancer health answer's drain condition
+// (lbhealth.State).
+type ingressHealth interface {
+ SetIngressDrain(on bool)
+}
+
+// ingressReaderFunc builds the target-health reader for groups in region.
+type ingressReaderFunc func(ctx context.Context, region string, groups []string) (ingresshealth.Reader, error)
+
+// newIngressReader is the AWS adapter, from the box's own credentials.
+var newIngressReader ingressReaderFunc = func(ctx context.Context, region string, groups []string) (ingresshealth.Reader, error) {
+ return awstg.Load(ctx, region, groups)
+}
+
+// ingressClock is the drain's time, a seam so tests run the whole state
+// machine on a fake clock.
+type ingressClock struct {
+ now func() time.Time
+ sleep func(time.Duration)
+ // after runs f after d, and returns a stop that cancels it.
+ after func(d time.Duration, f func()) (stop func() bool)
+}
+
+var realIngressClock = ingressClock{
+ now: time.Now,
+ sleep: time.Sleep,
+ after: func(d time.Duration, f func()) func() bool { return time.AfterFunc(d, f).Stop },
+}
+
+// ingressArming is whether this box has a drain (spec §4.1), and with
+// what.
+type ingressArming struct {
+ Answer string
+ Reason string
+ Groups []string
+ Region string
+ Self ingresshealth.Self
+}
+
+// ingressDrainArming decides §4.1 for this box: armed only on a fixed box
+// (tenant admission the fixed kind, not a group member) whose load
+// balancer health answer is armed (CARLOS_REGION_HA on) and whose
+// CARLOS_INGRESS_TARGET_GROUPS names target groups in its own account and
+// region. A box with no tenant admission is not_armed: it never answers
+// the health check 200, so it cannot be a target taking flows.
+func ingressDrainArming(getenv func(string) string, admission *fixedAdmission, self hafresh.Self) ingressArming {
+ no := func(reason string) ingressArming { return ingressArming{Answer: ingressNotArmed, Reason: reason} }
+ switch {
+ case admission != nil && admission.group:
+ return ingressArming{Answer: ingressGroupMember, Reason: "a group member leaves the load balancer through the region HA drain"}
+ case !regionHAEnabled(getenv):
+ return no("region HA is off (CARLOS_REGION_HA)")
+ case admission == nil:
+ return no("the box has no tenant admission (CARLOS_GROUP_ADMISSION)")
+ }
+ value := getenv(ingressTargetGroupsKey)
+ if strings.TrimSpace(value) == "" {
+ return no("no target groups are named (" + ingressTargetGroupsKey + ")")
+ }
+ if self.IID == "" {
+ return no("the box's instance id is not known")
+ }
+ groups, err := ingresshealth.ParseTargetGroups(value, self.Account, self.Region)
+ if err != nil {
+ return no(err.Error())
+ }
+ return ingressArming{Answer: ingressArmed, Groups: groups, Region: self.Region,
+ Self: ingresshealth.Self{InstanceID: self.IID, Ports: slices.Clone(ingressPorts)}}
+}
+
+// ingressDrainServed is whether a box that is not a group member serves
+// the drain socket: a fixed box with region HA on whose host.env names
+// target groups. The names are checked when a drain is asked for, against
+// the box's identity then, and a box whose names do not check answers
+// not_armed with the reason.
+func ingressDrainServed(getenv func(string) string, admission *fixedAdmission) bool {
+ return admission != nil && !admission.group && regionHAEnabled(getenv) && strings.TrimSpace(getenv(ingressTargetGroupsKey)) != ""
+}
+
+// ingressReport is the drain's answer (spec §4.2 step 4).
+type ingressReport struct {
+ V int `json:"v"`
+ Incarnation string `json:"incarnation"`
+ // Result is running or done for a drain; not_armed, group_member or
+ // refused when none ran, with Reason saying why.
+ Result string `json:"result"`
+ Reason string `json:"reason,omitempty"`
+ // Verdict is withdrawn or unverified once step 2 has ended; Reasons
+ // says why it is unverified.
+ Verdict string `json:"verdict,omitempty"`
+ Reasons []string `json:"reasons,omitempty"`
+ TargetGroups []string `json:"target_groups,omitempty"`
+ // When the drain started and each step ended.
+ StartedAt *time.Time `json:"started_at,omitempty"`
+ HealthFailedAt *time.Time `json:"health_failed_at,omitempty"`
+ WaitEndedAt *time.Time `json:"wait_ended_at,omitempty"`
+ ListenersClosedAt *time.Time `json:"listeners_closed_at,omitempty"`
+ FinishedAt *time.Time `json:"finished_at,omitempty"`
+ // Reads counts the target-health reads; Polls keeps the first and
+ // every one that differs from the one before (the states over time).
+ Reads int `json:"reads"`
+ Polls []ingressPoll `json:"polls,omitempty"`
+ // Step 3: edge-held streams closed, requests finished during the
+ // connection wait, requests cut at its bound, and any error.
+ HeldClosed int `json:"held_closed"`
+ Finished int `json:"finished"`
+ Closed int `json:"closed"`
+ CloseError string `json:"close_error,omitempty"`
+}
+
+type ingressPoll struct {
+ At time.Time `json:"at"`
+ Error string `json:"error,omitempty"`
+ Groups []ingressPollGroup `json:"groups,omitempty"`
+}
+
+type ingressPollGroup struct {
+ TargetGroup string `json:"target_group"`
+ Self []ingressPollTarget `json:"self"`
+ OtherHealthy int `json:"other_healthy"`
+}
+
+type ingressPollTarget struct {
+ Port int32 `json:"port"`
+ State ingresshealth.State `json:"state"`
+ Reason string `json:"reason,omitempty"`
+}
+
+func (p ingressPoll) same(q ingressPoll) bool {
+ if p.Error != q.Error || len(p.Groups) != len(q.Groups) {
+ return false
+ }
+ for i := range p.Groups {
+ a, b := p.Groups[i], q.Groups[i]
+ if a.TargetGroup != b.TargetGroup || a.OtherHealthy != b.OtherHealthy || !slices.Equal(a.Self, b.Self) {
+ return false
+ }
+ }
+ return true
+}
+
+func (r *ingressReport) clone() *ingressReport {
+ if r == nil {
+ return nil
+ }
+ c := *r
+ c.Reasons = slices.Clone(r.Reasons)
+ c.TargetGroups = slices.Clone(r.TargetGroups)
+ c.Polls = slices.Clone(r.Polls)
+ return &c
+}
+
+// ingressStatus answers GET /v1/ingress/status.
+type ingressStatus struct {
+ Incarnation string `json:"incarnation"`
+ Armed string `json:"armed"`
+ Reason string `json:"reason,omitempty"`
+ TargetGroups []string `json:"target_groups,omitempty"`
+ Report *ingressReport `json:"report"`
+}
+
+// ingressDrain is the driver.
+type ingressDrain struct {
+ arm func() ingressArming
+ health ingressHealth
+ reader ingressReaderFunc
+ clock ingressClock
+ // exit ends the process; os.Exit in production.
+ exit func(code int)
+
+ mu sync.Mutex
+ edge ingressEdge
+ // armed, report and done are set once, by the drain that runs.
+ armed ingressArming
+ report *ingressReport
+ done chan struct{}
+ // stopExit cancels the 3-minute exit; stopping is set once the
+ // agent's own shutdown has begun, after which the exit never runs.
+ stopExit func() bool
+ stopping bool
+}
+
+func newIngressDrain(arm func() ingressArming, health ingressHealth) *ingressDrain {
+ return &ingressDrain{arm: arm, health: health, reader: newIngressReader, clock: realIngressClock, exit: os.Exit}
+}
+
+// setEdge hands the driver the running edge. A drain asked for before is
+// not_armed.
+func (d *ingressDrain) setEdge(e ingressEdge) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.edge = e
+}
+
+// shutdownStarted is the agent's SIGTERM: the stop the drain was for has
+// come, so the 3-minute exit must not cut the shutdown short.
+func (d *ingressDrain) shutdownStarted() {
+ if d == nil {
+ return
+ }
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.stopping = true
+ if d.stopExit != nil {
+ d.stopExit()
+ }
+}
+
+// start starts the drain, or joins the one already started (running or
+// done), and returns its completion. When no drain runs it returns nil
+// and the answer saying why.
+func (d *ingressDrain) start() (<-chan struct{}, *ingressReport) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if d.done != nil {
+ return d.done, nil
+ }
+ arm := d.arm()
+ if arm.Answer == ingressArmed && d.edge == nil {
+ arm = ingressArming{Answer: ingressNotArmed, Reason: "the edge is not running"}
+ }
+ if arm.Answer != ingressArmed {
+ return nil, &ingressReport{V: 1, Incarnation: agentIncarnation, Result: arm.Answer, Reason: arm.Reason}
+ }
+ now := d.clock.now()
+ d.armed = arm
+ d.report = &ingressReport{V: 1, Incarnation: agentIncarnation, Result: "running", StartedAt: &now, TargetGroups: slices.Clone(arm.Groups)}
+ d.done = make(chan struct{})
+ go d.run(d.edge, arm, d.report, d.done)
+ return d.done, nil
+}
+
+// snapshot is a copy of the drain's report, nil before one started.
+func (d *ingressDrain) snapshot() *ingressReport {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.report.clone()
+}
+
+func (d *ingressDrain) status() ingressStatus {
+ d.mu.Lock()
+ arm, rep := d.armed, d.report.clone()
+ d.mu.Unlock()
+ if rep == nil {
+ arm = d.arm()
+ }
+ return ingressStatus{Incarnation: agentIncarnation, Armed: arm.Answer, Reason: arm.Reason, TargetGroups: arm.Groups, Report: rep}
+}
+
+// note changes the report under the lock, so status reads a whole one.
+func (d *ingressDrain) note(f func()) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ f()
+}
+
+func (d *ingressDrain) stamp(at **time.Time) {
+ t := d.clock.now()
+ d.note(func() { *at = &t })
+}
+
+func (d *ingressDrain) run(e ingressEdge, arm ingressArming, rep *ingressReport, done chan struct{}) {
+ defer close(done)
+ // Step 1: Connection: close on every response, then the health check
+ // fails. Nothing is refused. The edge refuses while a region HA
+ // connection drain is on, and then nothing changes.
+ if err := e.BeginIngressDrain(); err != nil {
+ t := d.clock.now()
+ d.note(func() { rep.Result, rep.Reason, rep.FinishedAt = "refused", err.Error(), &t })
+ log.Printf("agent: ingress drain refused: %v", err)
+ return
+ }
+ d.health.SetIngressDrain(true)
+ d.stamp(&rep.HealthFailedAt)
+ log.Printf("agent: ingress drain: health check failing; waiting for %d target group(s) to withdraw the box", len(arm.Groups))
+
+ // Step 2.
+ verdict, reasons := d.wait(arm, rep)
+ t := d.clock.now()
+ d.note(func() { rep.Verdict, rep.Reasons, rep.WaitEndedAt = verdict, reasons, &t })
+
+ // Step 3. From here the box serves nothing on its public ports, so
+ // the agent ends itself if the stop does not come.
+ out, err := e.CloseIngress(context.Background(), ingressConnWait)
+ t = d.clock.now()
+ d.note(func() {
+ rep.ListenersClosedAt = &t
+ rep.HeldClosed, rep.Finished, rep.Closed = out.HeldClosed, out.Finished, out.Closed
+ if err != nil {
+ rep.CloseError = err.Error()
+ }
+ })
+ d.mu.Lock()
+ if !d.stopping {
+ d.stopExit = d.clock.after(ingressExitAfter, d.exitWithoutStop)
+ }
+ d.mu.Unlock()
+
+ // Step 4.
+ t = d.clock.now()
+ d.note(func() { rep.Result, rep.FinishedAt = "done", &t })
+ why := ""
+ if len(reasons) > 0 {
+ why = ": " + strings.Join(reasons, "; ")
+ }
+ log.Printf("agent: ingress drain done: %s%s; listeners closed, %d request(s) finished, %d cut, %d held stream(s) closed", verdict, why, out.Finished, out.Closed, out.HeldClosed)
+ if err != nil {
+ log.Printf("agent: ingress drain: closing the listeners: %v", err)
+ }
+}
+
+// exitWithoutStop is the 3-minute exit (spec §4.2): the drain closed the
+// listeners and no stop followed, so the agent exits and systemd restarts
+// it through admission and two passing health checks.
+func (d *ingressDrain) exitWithoutStop() {
+ d.mu.Lock()
+ stopping := d.stopping
+ d.mu.Unlock()
+ if stopping {
+ return
+ }
+ log.Printf("agent: ingress drain ended without a stop; exiting")
+ d.exit(1)
+}
+
+// wait is step 2: poll the target groups until every one reports the box
+// withdrawn with another target healthy, and that holds through the
+// settle; or until the cap. It never refuses: the stop is coming either
+// way, so it answers a verdict and the drain goes on.
+func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport) (string, []string) {
+ start := d.clock.now()
+ capAt := start.Add(ingressCap)
+ var reasons []string
+
+ rd, buildErr := d.reader(context.Background(), arm.Region, arm.Groups)
+ read := func() (ingresshealth.Verdict, error) {
+ if buildErr != nil {
+ return ingresshealth.Verdict{}, fmt.Errorf("target health reader: %w", buildErr)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), ingressReadBound)
+ defer cancel()
+ return rd.Withdrawn(ctx, arm.Self)
+ }
+
+ // Retention, once, before the first poll (spec §8): with connections
+ // reset at the unhealthy mark the drain cannot claim withdrawn. It
+ // still waits for the withdrawal, which keeps new flows away.
+ if buildErr != nil {
+ reasons = append(reasons, fmt.Sprintf("target group retention: target health reader: %v", buildErr))
+ } else {
+ ctx, cancel := context.WithTimeout(context.Background(), ingressReadBound)
+ rets, err := rd.Retention(ctx)
+ cancel()
+ if err != nil {
+ reasons = append(reasons, fmt.Sprintf("target group retention: %v", err))
+ }
+ for _, r := range rets {
+ if p := r.Problem(); p != "" {
+ reasons = append(reasons, fmt.Sprintf("target group retention: target group %s: %s", r.TargetGroup, p))
+ }
+ }
+ }
+
+ checkedStart := false
+ var settleFrom time.Time
+ for {
+ v, err := read()
+ now := d.clock.now()
+ d.record(rep, now, v, err)
+ if err == nil && !checkedStart {
+ // The first answer: a box already not healthy has been so for
+ // an unknown time, and its retention may be running out.
+ checkedStart = true
+ for _, g := range v.Groups {
+ if !g.Healthy() {
+ reasons = append(reasons, fmt.Sprintf("not healthy at start: target group %s reports %s", g.TargetGroup, g.State()))
+ }
+ }
+ }
+ if err == nil && v.Withdrawn() && v.OthersHealthy() {
+ if settleFrom.IsZero() {
+ settleFrom = now
+ }
+ if now.Sub(settleFrom) >= ingressSettle {
+ if len(reasons) > 0 {
+ return ingressUnverified, reasons
+ }
+ return ingressWithdrawn, nil
+ }
+ } else {
+ // Not withdrawn, or it did not hold: the settle starts again
+ // from the next withdrawn answer, if one comes before the cap.
+ settleFrom = time.Time{}
+ if !now.Before(capAt) {
+ return ingressUnverified, append(reasons, capReasons(v, err)...)
+ }
+ }
+ d.clock.sleep(ingressPollEvery)
+ }
+}
+
+// capReasons names what held the drain at the cap: the read error, each
+// target group that has not withdrawn the box with its state, and each
+// with no other healthy target (the load balancer fails open, spec §8).
+func capReasons(v ingresshealth.Verdict, err error) []string {
+ if err != nil {
+ return []string{fmt.Sprintf("read failed: %v", err)}
+ }
+ var out []string
+ for _, g := range v.Groups {
+ if !g.Withdrawn() {
+ out = append(out, fmt.Sprintf("target group %s reports %s", g.TargetGroup, g.State()))
+ }
+ }
+ for _, g := range v.Groups {
+ if g.OtherHealthy < 1 {
+ out = append(out, fmt.Sprintf("no other healthy target: target group %s", g.TargetGroup))
+ }
+ }
+ if len(out) == 0 {
+ // Unreachable with the reader's contract (an empty verdict comes
+ // only with an error), kept so a verdict is never silent.
+ out = append(out, "no target group answered")
+ }
+ return out
+}
+
+// record counts a read and keeps it if it differs from the last kept.
+func (d *ingressDrain) record(rep *ingressReport, at time.Time, v ingresshealth.Verdict, err error) {
+ p := ingressPoll{At: at}
+ if err != nil {
+ p.Error = err.Error()
+ }
+ for _, g := range v.Groups {
+ pg := ingressPollGroup{TargetGroup: g.TargetGroup, OtherHealthy: g.OtherHealthy, Self: []ingressPollTarget{}}
+ for _, e := range g.Self {
+ pg.Self = append(pg.Self, ingressPollTarget{Port: e.Port, State: e.State, Reason: e.Reason})
+ }
+ p.Groups = append(p.Groups, pg)
+ }
+ d.note(func() {
+ rep.Reads++
+ if n := len(rep.Polls); n == 0 || !rep.Polls[n-1].same(p) {
+ rep.Polls = append(rep.Polls, p)
+ }
+ })
+}
+
+// handler serves the drain's routes on the drain socket:
+//
+// POST /v1/ingress/drain start or join; answers the report when the
+// drain ends, or as it stands after 140 s
+// GET /v1/ingress/status arming and the report so far
+//
+// Both answer 200 with JSON. A box with no drain answers the drain with
+// result not_armed or group_member and the reason.
+func (d *ingressDrain) handler() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.RawQuery != "" {
+ http.NotFound(w, r)
+ return
+ }
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/v1/ingress/status":
+ _ = json.NewEncoder(w).Encode(d.status())
+ case r.Method == http.MethodPost && r.URL.Path == "/v1/ingress/drain":
+ done, answer := d.start()
+ if done == nil {
+ _ = json.NewEncoder(w).Encode(answer)
+ return
+ }
+ t := time.NewTimer(ingressCallBound)
+ defer t.Stop()
+ select {
+ case <-done:
+ case <-t.C:
+ case <-r.Context().Done():
+ // The caller went away; the drain goes on here.
+ return
+ }
+ _ = json.NewEncoder(w).Encode(d.snapshot())
+ default:
+ http.NotFound(w, r)
+ }
+ })
+}
diff --git a/internal/host/ingressdrain_socket_linux_test.go b/internal/host/ingressdrain_socket_linux_test.go
new file mode 100644
index 000000000..edde6b9dc
--- /dev/null
+++ b/internal/host/ingressdrain_socket_linux_test.go
@@ -0,0 +1,58 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "net/http"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/ingresshealth"
+)
+
+// The fixed box's socket over the real listener: the same peer rule as a
+// group member's (SO_PEERCRED, the agent's user only), the ingress routes
+// served, the group drain's routes 404.
+func TestIngressDrainSocketOnAFixedBox(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(4*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ dir, err := os.MkdirTemp("", "hi")
+ must(t, err)
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ path := filepath.Join(dir, "s", "drain.sock")
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() { defer close(done); serveHADrainSocket(ctx, path, &haDrainSocket{ingress: f.d}) }()
+ t.Cleanup(func() { cancel(); <-done })
+ waitSocket(t, path)
+ c := newDrainClient(path)
+
+ setDrainPeer(t, func(uint32) bool { return false })
+ var st ingressStatus
+ if err := c.call(context.Background(), http.MethodGet, "/v1/ingress/status", nil, &st); err == nil {
+ t.Fatal("a refused peer was served the status")
+ }
+ if err := c.call(context.Background(), http.MethodPost, "/v1/ingress/drain", nil, nil); err == nil || f.d.snapshot() != nil {
+ t.Fatalf("a refused peer started a drain: %v", err)
+ }
+
+ drainPeerSeam.Store(nil) // production's rule: this test's user is the agent's
+ if err := c.call(context.Background(), http.MethodGet, "/v1/ingress/status", nil, &st); err != nil || st.Armed != ingressArmed {
+ t.Fatalf("status: %+v %v", st, err)
+ }
+ if _, err := c.status(context.Background()); err == nil || err.Error() != "drain socket answered 404" {
+ t.Fatalf("group drain status on a fixed box: %v", err)
+ }
+ if _, err := c.step(context.Background(), "withdraw", "t1", []string{}); err == nil || err.Error() != "drain socket answered 404" {
+ t.Fatalf("group withdraw on a fixed box: %v", err)
+ }
+
+ cctx, ccancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer ccancel()
+ var rep ingressReport
+ if err := c.call(cctx, http.MethodPost, "/v1/ingress/drain", nil, &rep); err != nil || rep.Result != "done" || rep.Verdict != ingressWithdrawn {
+ t.Fatalf("drain: %+v %v", rep, err)
+ }
+}
diff --git a/internal/host/ingressdrain_test.go b/internal/host/ingressdrain_test.go
new file mode 100644
index 000000000..c952c6f01
--- /dev/null
+++ b/internal/host/ingressdrain_test.go
@@ -0,0 +1,800 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/ingresshealth"
+)
+
+const (
+ tgA = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge-80/0123456789abcdef"
+ tgB = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge-443/fedcba9876543210"
+)
+
+var ingressTestSelf = hafresh.Self{Ref: "leo", IID: "i-0123456789abcdef0", Account: "123456789012", Region: "eu-west-1"}
+
+// fakeIngressClock is the drain's clock: sleep moves time on at once, and
+// after records what would run later.
+type fakeIngressClock struct {
+ mu sync.Mutex
+ t time.Time
+ pending []fakeAfter
+}
+
+type fakeAfter struct {
+ d time.Duration
+ f func()
+ stopped *bool
+}
+
+func (c *fakeIngressClock) clock() ingressClock {
+ return ingressClock{
+ now: func() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t },
+ sleep: func(d time.Duration) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.t = c.t.Add(d)
+ },
+ after: func(d time.Duration, f func()) func() bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ stopped := new(bool)
+ c.pending = append(c.pending, fakeAfter{d: d, f: f, stopped: stopped})
+ return func() bool { c.mu.Lock(); defer c.mu.Unlock(); was := !*stopped; *stopped = true; return was }
+ },
+ }
+}
+
+func (c *fakeIngressClock) afters() []fakeAfter {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return slices.Clone(c.pending)
+}
+
+// fakeTargetHealth answers each read from script, by the time since the
+// drain's clock started.
+type fakeTargetHealth struct {
+ clock *fakeIngressClock
+ start time.Time
+ script func(at time.Duration) (ingresshealth.Verdict, error)
+ retention []ingresshealth.Retention
+ retErr error
+ // gate, when set, holds the first read until it is closed.
+ gate chan struct{}
+
+ mu sync.Mutex
+ reads int
+ retReads int
+ selves []ingresshealth.Self
+}
+
+func (f *fakeTargetHealth) Withdrawn(_ context.Context, self ingresshealth.Self) (ingresshealth.Verdict, error) {
+ f.mu.Lock()
+ f.reads++
+ first := f.reads == 1
+ f.selves = append(f.selves, self)
+ f.mu.Unlock()
+ if first && f.gate != nil {
+ <-f.gate
+ }
+ f.clock.mu.Lock()
+ at := f.clock.t.Sub(f.start)
+ f.clock.mu.Unlock()
+ return f.script(at)
+}
+
+func (f *fakeTargetHealth) Retention(context.Context) ([]ingresshealth.Retention, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.retReads++
+ if f.retErr != nil {
+ return nil, f.retErr
+ }
+ if f.retention != nil {
+ return f.retention, nil
+ }
+ return []ingresshealth.Retention{
+ {TargetGroup: tgA, TerminationOff: true, DrainingInterval: 180 * time.Second},
+ {TargetGroup: tgB, TerminationOff: true, DrainingInterval: 180 * time.Second},
+ }, nil
+}
+
+type fakeIngressEdge struct {
+ mu sync.Mutex
+ calls []string
+ beginErr error
+ out edge.IngressClose
+ closeErr error
+ waits []time.Duration
+ health *fakeIngressHealth
+ // healthAtClose is whether the health check was failing when step 3
+ // began.
+ healthAtClose bool
+}
+
+func (e *fakeIngressEdge) BeginIngressDrain() error {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ e.calls = append(e.calls, "begin")
+ return e.beginErr
+}
+
+func (e *fakeIngressEdge) CloseIngress(_ context.Context, wait time.Duration) (edge.IngressClose, error) {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ e.calls = append(e.calls, "close")
+ e.waits = append(e.waits, wait)
+ e.healthAtClose = e.health.on()
+ return e.out, e.closeErr
+}
+
+func (e *fakeIngressEdge) called() []string {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ return slices.Clone(e.calls)
+}
+
+type fakeIngressHealth struct {
+ mu sync.Mutex
+ set []bool
+}
+
+func (h *fakeIngressHealth) SetIngressDrain(on bool) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.set = append(h.set, on)
+}
+
+func (h *fakeIngressHealth) on() bool {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return len(h.set) > 0 && h.set[len(h.set)-1]
+}
+
+type ingressFixture struct {
+ d *ingressDrain
+ clock *fakeIngressClock
+ tg *fakeTargetHealth
+ edge *fakeIngressEdge
+ health *fakeIngressHealth
+ exits *[]int
+}
+
+func newIngressFixture(t *testing.T, script func(at time.Duration) (ingresshealth.Verdict, error)) *ingressFixture {
+ t.Helper()
+ c := &fakeIngressClock{t: time.Unix(1_000_000, 0)}
+ tg := &fakeTargetHealth{clock: c, start: c.t, script: script}
+ h := &fakeIngressHealth{}
+ e := &fakeIngressEdge{health: h}
+ env := map[string]string{"CARLOS_REGION_HA": "true", ingressTargetGroupsKey: tgA + "," + tgB}
+ admission := &fixedAdmission{}
+ d := newIngressDrain(func() ingressArming {
+ return ingressDrainArming(func(k string) string { return env[k] }, admission, ingressTestSelf)
+ }, h)
+ d.clock = c.clock()
+ d.reader = func(_ context.Context, region string, groups []string) (ingresshealth.Reader, error) {
+ if region != "eu-west-1" || !slices.Equal(groups, []string{tgA, tgB}) {
+ t.Errorf("reader for %s %v", region, groups)
+ }
+ return tg, nil
+ }
+ exits := &[]int{}
+ d.exit = func(code int) { *exits = append(*exits, code) }
+ d.setEdge(e)
+ return &ingressFixture{d: d, clock: c, tg: tg, edge: e, health: h, exits: exits}
+}
+
+// drain runs one drain to its end and returns the report.
+func (f *ingressFixture) drain(t *testing.T) *ingressReport {
+ t.Helper()
+ done, answer := f.d.start()
+ if done == nil {
+ t.Fatalf("no drain ran: %+v", answer)
+ }
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the drain never ended")
+ }
+ return f.d.snapshot()
+}
+
+// group is one target group's answer: this box on :80 and :443 in state,
+// and others other healthy targets.
+func group(tg string, state ingresshealth.State, others int) ingresshealth.Group {
+ return ingresshealth.Group{TargetGroup: tg, OtherHealthy: others,
+ Self: []ingresshealth.Entry{{Port: 80, State: state}, {Port: 443, State: state}}}
+}
+
+func verdict(groups ...ingresshealth.Group) ingresshealth.Verdict {
+ return ingresshealth.Verdict{Groups: groups}
+}
+
+// healthyUntil is a target group pair that reports this box healthy until
+// at, then a and b, with one other healthy target throughout.
+func healthyUntil(at time.Duration, a, b ingresshealth.State) func(time.Duration) (ingresshealth.Verdict, error) {
+ return func(now time.Duration) (ingresshealth.Verdict, error) {
+ if now < at {
+ return verdict(group(tgA, ingresshealth.StateHealthy, 1), group(tgB, ingresshealth.StateHealthy, 1)), nil
+ }
+ return verdict(group(tgA, a, 1), group(tgB, b, 1)), nil
+ }
+}
+
+func elapsed(rep *ingressReport, at *time.Time) time.Duration {
+ return at.Sub(*rep.StartedAt)
+}
+
+func TestIngressDrainArming(t *testing.T) {
+ fixed, member := &fixedAdmission{}, &fixedAdmission{group: true}
+ full := map[string]string{"CARLOS_REGION_HA": "true", ingressTargetGroupsKey: tgA + ", " + tgB}
+ with := func(k, v string) map[string]string {
+ m := map[string]string{}
+ for kk, vv := range full {
+ m[kk] = vv
+ }
+ m[k] = v
+ return m
+ }
+ noIID := ingressTestSelf
+ noIID.IID = ""
+ noRegion := ingressTestSelf
+ noRegion.Region = ""
+ for _, c := range []struct {
+ name string
+ env map[string]string
+ admission *fixedAdmission
+ self hafresh.Self
+ answer string
+ reason string
+ served bool
+ }{
+ {"armed", full, fixed, ingressTestSelf, ingressArmed, "", true},
+ {"group member", full, member, ingressTestSelf, ingressGroupMember, "region HA drain", false},
+ {"region HA off", with("CARLOS_REGION_HA", ""), fixed, ingressTestSelf, ingressNotArmed, "region HA is off", false},
+ {"region HA false", with("CARLOS_REGION_HA", "false"), fixed, ingressTestSelf, ingressNotArmed, "region HA is off", false},
+ {"no admission", full, nil, ingressTestSelf, ingressNotArmed, "no tenant admission", false},
+ {"no key", with(ingressTargetGroupsKey, ""), fixed, ingressTestSelf, ingressNotArmed, "no target groups", false},
+ {"blank key", with(ingressTargetGroupsKey, " "), fixed, ingressTestSelf, ingressNotArmed, "no target groups", false},
+ {"bad key", with(ingressTargetGroupsKey, tgA+","+tgA), fixed, ingressTestSelf, ingressNotArmed, "entry 2 repeats entry 1", true},
+ {"other account", with(ingressTargetGroupsKey, strings.Replace(tgA, "123456789012", "210987654321", 1)), fixed, ingressTestSelf, ingressNotArmed, "account 210987654321", true},
+ {"no instance id", full, fixed, noIID, ingressNotArmed, "instance id is not known", true},
+ {"no region", full, fixed, noRegion, ingressNotArmed, "region is unknown", true},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ getenv := func(k string) string { return c.env[k] }
+ a := ingressDrainArming(getenv, c.admission, c.self)
+ if a.Answer != c.answer || !strings.Contains(a.Reason, c.reason) {
+ t.Fatalf("arming = %+v, want %s with %q", a, c.answer, c.reason)
+ }
+ if c.answer == ingressArmed {
+ if !slices.Equal(a.Groups, []string{tgA, tgB}) || a.Region != "eu-west-1" ||
+ a.Self.InstanceID != ingressTestSelf.IID || !slices.Equal(a.Self.Ports, []int32{80, 443}) {
+ t.Fatalf("armed with %+v", a)
+ }
+ }
+ if got := ingressDrainServed(getenv, c.admission); got != c.served {
+ t.Fatalf("served = %v, want %v", got, c.served)
+ }
+ })
+ }
+}
+
+// Step 1, step 2's settle, step 3 and the report, in order: withdrawn only
+// after the states held for 10 s, not at the first withdrawn read.
+func TestIngressDrainWithdrawnAfterTheSettle(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthyDraining))
+ f.edge.out = edge.IngressClose{HeldClosed: 1, Finished: 3, Closed: 2}
+ rep := f.drain(t)
+ if rep.Result != "done" || rep.Verdict != ingressWithdrawn || len(rep.Reasons) != 0 {
+ t.Fatalf("report %+v", rep)
+ }
+ if got := elapsed(rep, rep.WaitEndedAt); got != 16*time.Second {
+ t.Fatalf("the wait ended at %s; want the first withdrawn read (6s) plus the 10s settle", got)
+ }
+ if got := elapsed(rep, rep.HealthFailedAt); got != 0 {
+ t.Fatalf("health failed at %s", got)
+ }
+ if !slices.Equal(f.edge.called(), []string{"begin", "close"}) || !f.edge.healthAtClose || !slices.Equal(f.edge.waits, []time.Duration{30 * time.Second}) {
+ t.Fatalf("edge calls %v, waits %v, health failing at close %v", f.edge.called(), f.edge.waits, f.edge.healthAtClose)
+ }
+ if !slices.Equal(f.health.set, []bool{true}) {
+ t.Fatalf("health switch %v", f.health.set)
+ }
+ if rep.HeldClosed != 1 || rep.Finished != 3 || rep.Closed != 2 || rep.ListenersClosedAt == nil || rep.FinishedAt == nil {
+ t.Fatalf("step 3 report %+v", rep)
+ }
+ // Reads every 2 s: 0, 2, 4 healthy; 6..16 withdrawn. Two kept polls,
+ // the states over time.
+ if rep.Reads != 9 || len(rep.Polls) != 2 || rep.Polls[0].Groups[0].Self[0].State != ingresshealth.StateHealthy ||
+ rep.Polls[1].Groups[1].Self[1].State != ingresshealth.StateUnhealthyDraining || rep.Polls[1].At.Sub(*rep.StartedAt) != 6*time.Second {
+ t.Fatalf("reads %d, polls %+v", rep.Reads, rep.Polls)
+ }
+ f.tg.mu.Lock()
+ self := f.tg.selves[0]
+ retReads := f.tg.retReads
+ f.tg.mu.Unlock()
+ if self.InstanceID != ingressTestSelf.IID || !slices.Equal(self.Ports, []int32{80, 443}) || retReads != 1 {
+ t.Fatalf("read as %+v; retention read %d times", self, retReads)
+ }
+}
+
+// A state that flips back during the settle restarts it; the verdict needs
+// the states to hold through a whole settle.
+func TestIngressDrainSettleRestartsOnAFlip(t *testing.T) {
+ f := newIngressFixture(t, func(at time.Duration) (ingresshealth.Verdict, error) {
+ a, s := ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy
+ if at < 6*time.Second || at == 10*time.Second {
+ s = ingresshealth.StateHealthy
+ }
+ if at < 6*time.Second {
+ a = ingresshealth.StateHealthy
+ }
+ return verdict(group(tgA, a, 1), group(tgB, s, 1)), nil
+ })
+ rep := f.drain(t)
+ if rep.Verdict != ingressWithdrawn || elapsed(rep, rep.WaitEndedAt) != 22*time.Second {
+ t.Fatalf("verdict %s at %s, want withdrawn at 22s (12s + settle)", rep.Verdict, elapsed(rep, rep.WaitEndedAt))
+ }
+}
+
+// The settle may end past the cap, but a flip after the cap ends the wait
+// unverified, naming the group.
+func TestIngressDrainFlipAfterTheCap(t *testing.T) {
+ f := newIngressFixture(t, func(at time.Duration) (ingresshealth.Verdict, error) {
+ a, b := ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy
+ if at < 86*time.Second || at >= 92*time.Second {
+ a = ingresshealth.StateHealthy
+ }
+ if at < 86*time.Second {
+ b = ingresshealth.StateHealthy
+ }
+ return verdict(group(tgA, a, 1), group(tgB, b, 1)), nil
+ })
+ rep := f.drain(t)
+ if rep.Verdict != ingressUnverified || elapsed(rep, rep.WaitEndedAt) != 92*time.Second ||
+ !slices.Equal(rep.Reasons, []string{"target group " + tgA + " reports healthy"}) {
+ t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt))
+ }
+
+ // Withdrawn at 86 s and holding: the settle ends at 96 s, withdrawn.
+ f = newIngressFixture(t, healthyUntil(86*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ rep = f.drain(t)
+ if rep.Verdict != ingressWithdrawn || elapsed(rep, rep.WaitEndedAt) != 96*time.Second {
+ t.Fatalf("verdict %s at %s", rep.Verdict, elapsed(rep, rep.WaitEndedAt))
+ }
+}
+
+// Only unhealthy and unhealthy.draining count; anything else at the cap is
+// unverified, naming the group and its state. absent and unknown included.
+func TestIngressDrainStatesThatNeverCount(t *testing.T) {
+ for _, s := range []ingresshealth.State{ingresshealth.StateDraining, ingresshealth.StateUnused, ingresshealth.StateHealthy,
+ ingresshealth.StateInitial, ingresshealth.StateUnknown, ingresshealth.StateUnavailable} {
+ t.Run(string(s), func(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(4*time.Second, ingresshealth.StateUnhealthy, s))
+ rep := f.drain(t)
+ if rep.Verdict != ingressUnverified || elapsed(rep, rep.WaitEndedAt) != 90*time.Second ||
+ !slices.Equal(rep.Reasons, []string{"target group " + tgB + " reports " + string(s)}) {
+ t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt))
+ }
+ if !slices.Equal(f.edge.called(), []string{"begin", "close"}) {
+ t.Fatalf("the drain did not go on to step 3: %v", f.edge.called())
+ }
+ })
+ }
+ t.Run("absent", func(t *testing.T) {
+ f := newIngressFixture(t, func(at time.Duration) (ingresshealth.Verdict, error) {
+ return verdict(group(tgA, ingresshealth.StateUnhealthy, 1), ingresshealth.Group{TargetGroup: tgB, OtherHealthy: 1}), nil
+ })
+ rep := f.drain(t)
+ want := []string{"not healthy at start: target group " + tgA + " reports unhealthy",
+ "not healthy at start: target group " + tgB + " reports absent",
+ "target group " + tgB + " reports absent"}
+ if rep.Verdict != ingressUnverified || !slices.Equal(rep.Reasons, want) {
+ t.Fatalf("verdict %s %q", rep.Verdict, rep.Reasons)
+ }
+ })
+}
+
+// Retention that would reset connections, or that cannot be read, makes
+// the verdict unverified however the wait goes; the wait itself is the
+// same.
+func TestIngressDrainRetention(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.tg.retention = []ingresshealth.Retention{
+ {TargetGroup: tgA, TerminationOff: true, DrainingInterval: 180 * time.Second},
+ {TargetGroup: tgB, TerminationOff: false, DrainingInterval: 300 * time.Second},
+ }
+ rep := f.drain(t)
+ if rep.Verdict != ingressUnverified || elapsed(rep, rep.WaitEndedAt) != 16*time.Second ||
+ !slices.Equal(rep.Reasons, []string{"target group retention: target group " + tgB + ": unhealthy connection termination is on"}) {
+ t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt))
+ }
+
+ f = newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.tg.retention = []ingresshealth.Retention{
+ {TargetGroup: tgA, TerminationOff: true, DrainingInterval: 120 * time.Second},
+ {TargetGroup: tgB, TerminationOff: true, DrainingInterval: 180 * time.Second},
+ }
+ rep = f.drain(t)
+ if rep.Verdict != ingressUnverified || len(rep.Reasons) != 1 || !strings.HasPrefix(rep.Reasons[0], "target group retention: target group "+tgA+": draining interval 2m0s") {
+ t.Fatalf("verdict %s %q", rep.Verdict, rep.Reasons)
+ }
+
+ f = newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.tg.retErr = errors.New("target group " + tgA + ": describe target group attributes: AccessDenied")
+ rep = f.drain(t)
+ if rep.Verdict != ingressUnverified || !slices.Equal(rep.Reasons, []string{"target group retention: target group " + tgA + ": describe target group attributes: AccessDenied"}) {
+ t.Fatalf("verdict %s %q", rep.Verdict, rep.Reasons)
+ }
+}
+
+// A box not healthy at the first read has been out for an unknown time.
+func TestIngressDrainNotHealthyAtStart(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(0, ingresshealth.StateUnhealthyDraining, ingresshealth.StateUnhealthy))
+ rep := f.drain(t)
+ want := []string{"not healthy at start: target group " + tgA + " reports unhealthy.draining",
+ "not healthy at start: target group " + tgB + " reports unhealthy"}
+ if rep.Verdict != ingressUnverified || !slices.Equal(rep.Reasons, want) || elapsed(rep, rep.WaitEndedAt) != 10*time.Second {
+ t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt))
+ }
+
+ // Initial at the start counts the same.
+ f = newIngressFixture(t, func(at time.Duration) (ingresshealth.Verdict, error) {
+ s := ingresshealth.StateInitial
+ if at >= 4*time.Second {
+ s = ingresshealth.StateUnhealthy
+ }
+ return verdict(group(tgA, s, 1), group(tgB, ingresshealth.StateHealthy, 1)), nil
+ })
+ rep = f.drain(t)
+ if rep.Verdict != ingressUnverified || len(rep.Reasons) == 0 || rep.Reasons[0] != "not healthy at start: target group "+tgA+" reports initial" {
+ t.Fatalf("verdict %s %q", rep.Verdict, rep.Reasons)
+ }
+}
+
+// The healthy-peer count from the unfiltered read: withdrawn needs another
+// healthy target in every group; the last healthy target waits out the cap
+// and reports no other healthy target.
+func TestIngressDrainHealthyPeers(t *testing.T) {
+ f := newIngressFixture(t, func(at time.Duration) (ingresshealth.Verdict, error) {
+ if at < 4*time.Second {
+ return verdict(group(tgA, ingresshealth.StateHealthy, 2), group(tgB, ingresshealth.StateHealthy, 0)), nil
+ }
+ return verdict(group(tgA, ingresshealth.StateUnhealthy, 2), group(tgB, ingresshealth.StateUnhealthy, 0)), nil
+ })
+ rep := f.drain(t)
+ if rep.Verdict != ingressUnverified || elapsed(rep, rep.WaitEndedAt) != 90*time.Second ||
+ !slices.Equal(rep.Reasons, []string{"no other healthy target: target group " + tgB}) {
+ t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt))
+ }
+ if rep.Polls[0].Groups[0].OtherHealthy != 2 || rep.Polls[0].Groups[1].OtherHealthy != 0 {
+ t.Fatalf("polls %+v", rep.Polls)
+ }
+
+ // A peer turns healthy at 30 s: withdrawn at 40 s.
+ f = newIngressFixture(t, func(at time.Duration) (ingresshealth.Verdict, error) {
+ if at == 0 {
+ return verdict(group(tgA, ingresshealth.StateHealthy, 1), group(tgB, ingresshealth.StateHealthy, 0)), nil
+ }
+ others := 0
+ if at >= 30*time.Second {
+ others = 1
+ }
+ return verdict(group(tgA, ingresshealth.StateUnhealthy, 1), group(tgB, ingresshealth.StateUnhealthy, others)), nil
+ })
+ rep = f.drain(t)
+ if rep.Verdict != ingressWithdrawn || elapsed(rep, rep.WaitEndedAt) != 40*time.Second {
+ t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt))
+ }
+}
+
+// Read errors: polled on, and at the cap the verdict names the error. A
+// read that recovers before the cap is fine.
+func TestIngressDrainReadErrors(t *testing.T) {
+ boom := errors.New("target group " + tgB + ": describe target health: throttled")
+ f := newIngressFixture(t, func(time.Duration) (ingresshealth.Verdict, error) { return ingresshealth.Verdict{}, boom })
+ rep := f.drain(t)
+ if rep.Verdict != ingressUnverified || elapsed(rep, rep.WaitEndedAt) != 90*time.Second ||
+ !slices.Equal(rep.Reasons, []string{"read failed: " + boom.Error()}) || rep.Reads != 46 || len(rep.Polls) != 1 || rep.Polls[0].Error != boom.Error() {
+ t.Fatalf("verdict %s %q at %s, %d reads, polls %+v", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt), rep.Reads, rep.Polls)
+ }
+
+ // Errors until 20 s, then healthy, then withdrawn at 24 s.
+ f = newIngressFixture(t, func(at time.Duration) (ingresshealth.Verdict, error) {
+ if at < 20*time.Second {
+ return ingresshealth.Verdict{}, boom
+ }
+ return healthyUntil(24*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)(at)
+ })
+ rep = f.drain(t)
+ if rep.Verdict != ingressWithdrawn || elapsed(rep, rep.WaitEndedAt) != 34*time.Second {
+ t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt))
+ }
+
+ // A reader that cannot be built: unverified on retention and at the
+ // cap, and the drain still closes the listeners.
+ f = newIngressFixture(t, nil)
+ f.d.reader = func(context.Context, string, []string) (ingresshealth.Reader, error) {
+ return nil, errors.New("no credentials")
+ }
+ rep = f.drain(t)
+ want := []string{"target group retention: target health reader: no credentials", "read failed: target health reader: no credentials"}
+ if rep.Verdict != ingressUnverified || !slices.Equal(rep.Reasons, want) || !slices.Equal(f.edge.called(), []string{"begin", "close"}) {
+ t.Fatalf("verdict %s %q, edge %v", rep.Verdict, rep.Reasons, f.edge.called())
+ }
+}
+
+// One drain per process: a second ask joins the running drain, and an ask
+// after it ended gets the same report without draining again.
+func TestIngressDrainJoins(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.tg.gate = make(chan struct{})
+ first, _ := f.d.start()
+ second, _ := f.d.start()
+ if first == nil || first != second {
+ t.Fatal("the second ask did not join the first")
+ }
+ if rep := f.d.snapshot(); rep.Result != "running" {
+ t.Fatalf("while running: %+v", rep)
+ }
+ close(f.tg.gate)
+ <-first
+ a := f.d.snapshot()
+ third, _ := f.d.start()
+ <-third
+ b := f.d.snapshot()
+ if third != first || a.Result != "done" || b.Result != "done" || *a.FinishedAt != *b.FinishedAt || a.Reads != b.Reads {
+ t.Fatalf("after the drain: %+v then %+v", a, b)
+ }
+ if got := f.edge.called(); !slices.Equal(got, []string{"begin", "close"}) {
+ t.Fatalf("edge calls %v", got)
+ }
+ if n := len(f.clock.afters()); n != 1 {
+ t.Fatalf("%d exits scheduled", n)
+ }
+}
+
+// Three minutes after step 3 the agent exits non-zero, unless its own
+// shutdown began first.
+func TestIngressDrainExitsThreeMinutesAfterStepThree(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(0, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.drain(t)
+ as := f.clock.afters()
+ if len(as) != 1 || as[0].d != 3*time.Minute {
+ t.Fatalf("scheduled %+v", as)
+ }
+ if len(*f.exits) != 0 {
+ t.Fatal("exited at step 3")
+ }
+ as[0].f()
+ if !slices.Equal(*f.exits, []int{1}) {
+ t.Fatalf("exits %v", *f.exits)
+ }
+
+ // The stop came: shutdown cancels the exit, and a timer that fires
+ // anyway (the race) does not exit either.
+ f = newIngressFixture(t, healthyUntil(0, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.drain(t)
+ f.d.shutdownStarted()
+ as = f.clock.afters()
+ if len(as) != 1 || !*as[0].stopped {
+ t.Fatalf("the exit was not cancelled: %+v", as)
+ }
+ as[0].f()
+ if len(*f.exits) != 0 {
+ t.Fatalf("exited during shutdown: %v", *f.exits)
+ }
+
+ // Shutdown before step 3 ends: no exit is scheduled at all.
+ f = newIngressFixture(t, healthyUntil(0, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.d.shutdownStarted()
+ f.drain(t)
+ if n := len(f.clock.afters()); n != 0 {
+ t.Fatalf("%d exits scheduled during shutdown", n)
+ }
+ var nilDrain *ingressDrain
+ nilDrain.shutdownStarted()
+}
+
+// The §25 guard: the edge refuses step 1 while a connection drain is on,
+// and then nothing changes.
+func TestIngressDrainRefusedByTheEdge(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(0, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.edge.beginErr = edge.ErrConnectionDrainOn
+ rep := f.drain(t)
+ if rep.Result != "refused" || rep.Reason != edge.ErrConnectionDrainOn.Error() || rep.Verdict != "" {
+ t.Fatalf("report %+v", rep)
+ }
+ if len(f.health.set) != 0 || !slices.Equal(f.edge.called(), []string{"begin"}) || len(f.clock.afters()) != 0 || f.tg.reads != 0 {
+ t.Fatalf("a refused drain changed something: health %v, edge %v, exits %d, reads %d", f.health.set, f.edge.called(), len(f.clock.afters()), f.tg.reads)
+ }
+}
+
+// A box with no drain answers at once, and nothing runs.
+func TestIngressDrainNotArmedAnswers(t *testing.T) {
+ f := newIngressFixture(t, nil)
+ f.d.arm = func() ingressArming { return ingressArming{Answer: ingressGroupMember, Reason: "member"} }
+ done, ans := f.d.start()
+ if done != nil || ans.Result != ingressGroupMember || ans.Reason != "member" || ans.Incarnation != agentIncarnation {
+ t.Fatalf("answer %+v", ans)
+ }
+ f = newIngressFixture(t, nil)
+ f.d.setEdge(nil)
+ if done, ans := f.d.start(); done != nil || ans.Result != ingressNotArmed || ans.Reason != "the edge is not running" {
+ t.Fatalf("no edge: %+v", ans)
+ }
+ if f.d.snapshot() != nil || len(f.edge.called()) != 0 || len(f.health.set) != 0 {
+ t.Fatal("a drain ran")
+ }
+}
+
+func ingressAsk(t *testing.T, h http.Handler, ctx context.Context, method, path string) (*httptest.ResponseRecorder, map[string]any) {
+ t.Helper()
+ req := httptest.NewRequest(method, "http://agent"+path, nil).WithContext(ctx)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ var body map[string]any
+ if rec.Code == http.StatusOK {
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("%s %s: %q: %v", method, path, rec.Body.String(), err)
+ }
+ }
+ return rec, body
+}
+
+// The routes: status before and after, the drain's report, unknown paths
+// and queries refused.
+func TestIngressDrainRoutes(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ h := (&haDrainSocket{ingress: f.d}).handler()
+ ctx := context.Background()
+
+ rec, st := ingressAsk(t, h, ctx, http.MethodGet, "/v1/ingress/status")
+ if rec.Code != http.StatusOK || st["armed"] != ingressArmed || st["report"] != nil || st["incarnation"] != agentIncarnation ||
+ rec.Header().Get("Cache-Control") != "no-store" {
+ t.Fatalf("status before: %d %v", rec.Code, st)
+ }
+ for _, p := range []struct{ method, path string }{
+ {http.MethodGet, "/v1/ingress/drain"},
+ {http.MethodPost, "/v1/ingress/status"},
+ {http.MethodPost, "/v1/ingress/drain?x=1"},
+ {http.MethodPost, "/v1/ingress/other"},
+ } {
+ if rec, _ := ingressAsk(t, h, ctx, p.method, p.path); rec.Code != http.StatusNotFound {
+ t.Fatalf("%s %s answered %d", p.method, p.path, rec.Code)
+ }
+ }
+ if f.d.snapshot() != nil {
+ t.Fatal("a refused ask started a drain")
+ }
+
+ rec, rep := ingressAsk(t, h, ctx, http.MethodPost, "/v1/ingress/drain")
+ if rec.Code != http.StatusOK || rep["result"] != "done" || rep["verdict"] != ingressWithdrawn {
+ t.Fatalf("drain: %d %v", rec.Code, rep)
+ }
+ _, st = ingressAsk(t, h, ctx, http.MethodGet, "/v1/ingress/status")
+ if r, _ := st["report"].(map[string]any); st["armed"] != ingressArmed || r["result"] != "done" {
+ t.Fatalf("status after: %v", st)
+ }
+ // A repeat joins and gets the same report.
+ _, again := ingressAsk(t, h, ctx, http.MethodPost, "/v1/ingress/drain")
+ if again["finished_at"] != rep["finished_at"] || again["reads"] != rep["reads"] {
+ t.Fatalf("repeat: %v, first %v", again, rep)
+ }
+}
+
+// On a box with no drain the route answers why, at once.
+func TestIngressDrainRouteNotArmed(t *testing.T) {
+ f := newIngressFixture(t, nil)
+ f.d.arm = func() ingressArming {
+ return ingressArming{Answer: ingressNotArmed, Reason: "region HA is off (CARLOS_REGION_HA)"}
+ }
+ h := f.d.handler()
+ _, ans := ingressAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain")
+ if ans["result"] != ingressNotArmed || ans["reason"] != "region HA is off (CARLOS_REGION_HA)" {
+ t.Fatalf("answer %v", ans)
+ }
+ _, st := ingressAsk(t, h, context.Background(), http.MethodGet, "/v1/ingress/status")
+ if st["armed"] != ingressNotArmed || st["reason"] != "region HA is off (CARLOS_REGION_HA)" {
+ t.Fatalf("status %v", st)
+ }
+}
+
+// A caller that goes away before step 3 changes nothing: the drain runs to
+// the end on the agent, and the next ask gets its report.
+func TestIngressDrainCallerGoesAway(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.tg.gate = make(chan struct{})
+ h := f.d.handler()
+ ctx, cancel := context.WithCancel(context.Background())
+ answered := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ req := httptest.NewRequest(http.MethodPost, "http://agent/v1/ingress/drain", nil).WithContext(ctx)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ answered <- rec
+ }()
+ // The drain is in step 2, its first read held.
+ for f.d.snapshot() == nil {
+ time.Sleep(time.Millisecond)
+ }
+ cancel()
+ rec := <-answered
+ if rec.Body.Len() != 0 {
+ t.Fatalf("the gone caller was answered %q", rec.Body.String())
+ }
+ if got := f.edge.called(); !slices.Equal(got, []string{"begin"}) {
+ t.Fatalf("edge calls %v before the wait ended", got)
+ }
+ close(f.tg.gate)
+ _, rep := ingressAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain")
+ if rep["result"] != "done" || rep["verdict"] != ingressWithdrawn || !slices.Equal(f.edge.called(), []string{"begin", "close"}) {
+ t.Fatalf("report %v, edge %v", rep, f.edge.called())
+ }
+}
+
+// The route is bounded: past the bound it answers the drain as it stands,
+// and the drain goes on.
+func TestIngressDrainRouteBound(t *testing.T) {
+ old := ingressCallBound
+ ingressCallBound = 20 * time.Millisecond
+ t.Cleanup(func() { ingressCallBound = old })
+ f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.tg.gate = make(chan struct{})
+ h := f.d.handler()
+ _, rep := ingressAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain")
+ if rep["result"] != "running" || rep["health_failed_at"] == nil {
+ t.Fatalf("bounded answer %v", rep)
+ }
+ close(f.tg.gate)
+ ingressCallBound = old
+ _, rep = ingressAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain")
+ if rep["result"] != "done" {
+ t.Fatalf("report %v", rep)
+ }
+}
+
+// The socket's routes by box: on a fixed box the group drain's routes
+// answer 404 and the ingress routes are served; on a group member both
+// are, and the ingress drain answers group_member.
+func TestDrainSocketRoutesByBox(t *testing.T) {
+ f := newIngressFixture(t, nil)
+ fixed := (&haDrainSocket{ingress: f.d}).handler()
+ for _, p := range []struct{ method, path string }{
+ {http.MethodGet, "/v1/drain/status"},
+ {http.MethodPost, "/v1/drain/withdraw"},
+ {http.MethodPost, "/v1/drain/move"},
+ {http.MethodPost, "/v1/drain/cancel"},
+ } {
+ if rec, _ := ingressAsk(t, fixed, context.Background(), p.method, p.path); rec.Code != http.StatusNotFound {
+ t.Fatalf("fixed box: %s %s answered %d", p.method, p.path, rec.Code)
+ }
+ }
+ if rec, _ := ingressAsk(t, fixed, context.Background(), http.MethodGet, "/v1/ingress/status"); rec.Code != http.StatusOK {
+ t.Fatalf("fixed box: ingress status %d", rec.Code)
+ }
+
+ member := newIngressDrain(func() ingressArming {
+ return ingressDrainArming(func(string) string { return "true" }, &fixedAdmission{group: true}, ingressTestSelf)
+ }, &fakeIngressHealth{})
+ g := newDrainDriver(&fakeDrainAct{}, &fakeDrainEdge{}, &fakeMarks{}, func() fenceState { return fenceState{} })
+ both := (&haDrainSocket{group: g, ingress: member}).handler()
+ if rec, st := ingressAsk(t, both, context.Background(), http.MethodGet, "/v1/drain/status"); rec.Code != http.StatusOK || st["result"] != "none" {
+ t.Fatalf("member: drain status %d %v", rec.Code, st)
+ }
+ if _, ans := ingressAsk(t, both, context.Background(), http.MethodPost, "/v1/ingress/drain"); ans["result"] != ingressGroupMember {
+ t.Fatalf("member: ingress drain %v", ans)
+ }
+}