carlos / platform Public

ingresshealth: target-health reader and AWS adapter for the ingress drain

W6 ingress drain spec rev 4 §4.2 step 2 and §8. The core package is
provider-neutral: target states (only unhealthy and unhealthy.draining
count as withdrawn), per-group verdicts with the count of other healthy
targets, the retention check (termination off, draining >= 180 s), the
Reader interface the drain driver will fake, and ParseTargetGroups for
CARLOS_INGRESS_TARGET_GROUPS (own account and region, no empty or
repeated entries). awstg reads DescribeTargetHealth with no target
filter and DescribeTargetGroupAttributes through root's AWS loader.
Not wired into the agent yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 180c57ddbfd5b1b50c9cc0e7ce9ee0d576d72ff5 parent 7329d32
4 files changed, +833 −0
  • internal/ingresshealth/awstg/awstg.go +142 −0
  • internal/ingresshealth/awstg/awstg_test.go +248 −0
  • internal/ingresshealth/ingresshealth.go +259 −0
  • internal/ingresshealth/ingresshealth_test.go +184 −0

Intent

Attributed to this commit: 17.9 g CO₂e (2,268,643 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/ingresshealth/awstg/awstg.go b/internal/ingresshealth/awstg/awstg.go
new file mode 100644
index 000000000..bec352867
--- /dev/null
+++ b/internal/ingresshealth/awstg/awstg.go
@@ -0,0 +1,142 @@
+// Package awstg is the AWS adapter for ingresshealth: it reads Elastic Load
+// Balancing's target health and target group attributes for the target
+// groups a fixed box is registered in (fixed-edge ingress drain spec §4.2
+// step 2, §8). It uses the box's own credentials through root's AWS loader,
+// the same chain as the region HA termination oracle's EC2 reads, and only
+// read-only Describe calls: the box has no ELB write right (region HA
+// §12.2).
+package awstg
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "strconv"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ elbv2 "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
+
+ "github.com/carlosframework/platform/internal/ingresshealth"
+ "github.com/carlosframework/platform/internal/rootaws"
+)
+
+// The target group attributes the drain needs (spec §8).
+const (
+ attrTermination = "target_health_state.unhealthy.connection_termination.enabled"
+ attrDrainingInterval = "target_health_state.unhealthy.draining_interval_seconds"
+)
+
+// API is the two ELB calls the adapter makes, so tests can fake them.
+type API interface {
+ DescribeTargetHealth(context.Context, *elbv2.DescribeTargetHealthInput, ...func(*elbv2.Options)) (*elbv2.DescribeTargetHealthOutput, error)
+ DescribeTargetGroupAttributes(context.Context, *elbv2.DescribeTargetGroupAttributesInput, ...func(*elbv2.Options)) (*elbv2.DescribeTargetGroupAttributesOutput, error)
+}
+
+// Reader is ingresshealth.Reader over a fixed list of target groups.
+type Reader struct {
+ api API
+ groups []string
+}
+
+// New returns a reader of groups (ARNs already checked with
+// ingresshealth.ParseTargetGroups) through api.
+func New(api API, groups []string) *Reader {
+ return &Reader{api: api, groups: slices.Clone(groups)}
+}
+
+// Load builds a reader for groups in region from the box's own
+// credentials, through root's AWS loader. The SDK's own retries are off:
+// the drain polls every 2 s, so one call is one request and a failed read
+// is simply the next poll's to repeat.
+func Load(ctx context.Context, region string, groups []string) (*Reader, error) {
+ cfg, err := rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(region), awsconfig.WithRetryMaxAttempts(1))
+ if err != nil {
+ return nil, err
+ }
+ c := elbv2.NewFromConfig(cfg)
+ return New(ops{health: c.DescribeTargetHealth, attrs: c.DescribeTargetGroupAttributes}, groups), nil
+}
+
+// ops is API from two method values. A *elbv2.Client stored in an
+// interface keeps every ELB method in the binary (see awsinv.factoryFor,
+// discussion #275); method values keep two.
+type ops struct {
+ health func(context.Context, *elbv2.DescribeTargetHealthInput, ...func(*elbv2.Options)) (*elbv2.DescribeTargetHealthOutput, error)
+ attrs func(context.Context, *elbv2.DescribeTargetGroupAttributesInput, ...func(*elbv2.Options)) (*elbv2.DescribeTargetGroupAttributesOutput, error)
+}
+
+func (o ops) DescribeTargetHealth(ctx context.Context, in *elbv2.DescribeTargetHealthInput, opts ...func(*elbv2.Options)) (*elbv2.DescribeTargetHealthOutput, error) {
+ return o.health(ctx, in, opts...)
+}
+
+func (o ops) DescribeTargetGroupAttributes(ctx context.Context, in *elbv2.DescribeTargetGroupAttributesInput, opts ...func(*elbv2.Options)) (*elbv2.DescribeTargetGroupAttributesOutput, error) {
+ return o.attrs(ctx, in, opts...)
+}
+
+// Withdrawn reads each target group's health once, with no Targets filter:
+// one response carries every target, so this box's entries (by instance id
+// and registered port) and the count of other healthy targets come from the
+// same moment.
+func (r *Reader) Withdrawn(ctx context.Context, self ingresshealth.Self) (ingresshealth.Verdict, error) {
+ var v ingresshealth.Verdict
+ for _, arn := range r.groups {
+ out, err := r.api.DescribeTargetHealth(ctx, &elbv2.DescribeTargetHealthInput{TargetGroupArn: aws.String(arn)})
+ if err != nil {
+ // No partial verdict: the groups read so far could look
+ // withdrawn on their own.
+ return ingresshealth.Verdict{}, fmt.Errorf("target group %s: describe target health: %w", arn, err)
+ }
+ g := ingresshealth.Group{TargetGroup: arn}
+ for _, d := range out.TargetHealthDescriptions {
+ if d.Target == nil || d.TargetHealth == nil {
+ continue
+ }
+ state := ingresshealth.State(d.TargetHealth.State)
+ if aws.ToString(d.Target.Id) != self.InstanceID {
+ if state == ingresshealth.StateHealthy {
+ g.OtherHealthy++
+ }
+ continue
+ }
+ port := aws.ToInt32(d.Target.Port)
+ if len(self.Ports) > 0 && !slices.Contains(self.Ports, port) {
+ // This instance on a port the drain was not told about is
+ // neither this box's ingress nor a peer.
+ continue
+ }
+ g.Self = append(g.Self, ingresshealth.Entry{Port: port, State: state, Reason: string(d.TargetHealth.Reason)})
+ }
+ v.Groups = append(v.Groups, g)
+ }
+ return v, nil
+}
+
+// Retention reads each target group's unhealthy-connection attributes once.
+// A missing or unreadable value reads as the load balancer's default or as
+// zero, both of which fail the check: the drain never trusts retention it
+// could not read.
+func (r *Reader) Retention(ctx context.Context) ([]ingresshealth.Retention, error) {
+ var out []ingresshealth.Retention
+ for _, arn := range r.groups {
+ res, err := r.api.DescribeTargetGroupAttributes(ctx, &elbv2.DescribeTargetGroupAttributesInput{TargetGroupArn: aws.String(arn)})
+ if err != nil {
+ return nil, fmt.Errorf("target group %s: describe target group attributes: %w", arn, err)
+ }
+ ret := ingresshealth.Retention{TargetGroup: arn}
+ for _, a := range res.Attributes {
+ val := aws.ToString(a.Value)
+ switch aws.ToString(a.Key) {
+ case attrTermination:
+ ret.TerminationOff = val == "false"
+ case attrDrainingInterval:
+ if n, err := strconv.Atoi(val); err == nil && n > 0 {
+ ret.DrainingInterval = time.Duration(n) * time.Second
+ }
+ }
+ }
+ out = append(out, ret)
+ }
+ return out, nil
+}
diff --git a/internal/ingresshealth/awstg/awstg_test.go b/internal/ingresshealth/awstg/awstg_test.go
new file mode 100644
index 000000000..92a009b66
--- /dev/null
+++ b/internal/ingresshealth/awstg/awstg_test.go
@@ -0,0 +1,248 @@
+package awstg
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ elbv2 "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
+ "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
+
+ "github.com/carlosframework/platform/internal/ingresshealth"
+)
+
+const (
+ tg80 = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge-80/0123456789abcdef"
+ tg443 = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge-443/fedcba9876543210"
+ me = "i-0aaaaaaaaaaaaaaaa"
+ peer = "i-0bbbbbbbbbbbbbbbb"
+ peer2 = "i-0cccccccccccccccc"
+)
+
+var self = ingresshealth.Self{InstanceID: me, Ports: []int32{80, 443}}
+
+type fakeAPI struct {
+ health map[string][]types.TargetHealthDescription
+ healthErr map[string]error
+ attrs map[string][]types.TargetGroupAttribute
+ attrsErr map[string]error
+
+ healthIn []elbv2.DescribeTargetHealthInput
+ attrsIn []elbv2.DescribeTargetGroupAttributesInput
+}
+
+func (f *fakeAPI) DescribeTargetHealth(_ context.Context, in *elbv2.DescribeTargetHealthInput, _ ...func(*elbv2.Options)) (*elbv2.DescribeTargetHealthOutput, error) {
+ f.healthIn = append(f.healthIn, *in)
+ arn := aws.ToString(in.TargetGroupArn)
+ if err := f.healthErr[arn]; err != nil {
+ return nil, err
+ }
+ return &elbv2.DescribeTargetHealthOutput{TargetHealthDescriptions: f.health[arn]}, nil
+}
+
+func (f *fakeAPI) DescribeTargetGroupAttributes(_ context.Context, in *elbv2.DescribeTargetGroupAttributesInput, _ ...func(*elbv2.Options)) (*elbv2.DescribeTargetGroupAttributesOutput, error) {
+ f.attrsIn = append(f.attrsIn, *in)
+ arn := aws.ToString(in.TargetGroupArn)
+ if err := f.attrsErr[arn]; err != nil {
+ return nil, err
+ }
+ return &elbv2.DescribeTargetGroupAttributesOutput{Attributes: f.attrs[arn]}, nil
+}
+
+func target(id string, port int32, state types.TargetHealthStateEnum) types.TargetHealthDescription {
+ return types.TargetHealthDescription{
+ Target: &types.TargetDescription{Id: aws.String(id), Port: aws.Int32(port)},
+ TargetHealth: &types.TargetHealth{State: state},
+ }
+}
+
+func TestWithdrawnReadsUnfilteredAndMapsState(t *testing.T) {
+ f := &fakeAPI{health: map[string][]types.TargetHealthDescription{
+ tg80: {
+ target(peer, 80, types.TargetHealthStateEnumHealthy),
+ target(me, 80, types.TargetHealthStateEnumUnhealthyDraining),
+ target(peer2, 80, types.TargetHealthStateEnumUnhealthy),
+ },
+ tg443: {
+ target(peer, 443, types.TargetHealthStateEnumHealthy),
+ target(peer2, 443, types.TargetHealthStateEnumHealthy),
+ {
+ Target: &types.TargetDescription{Id: aws.String(me), Port: aws.Int32(443)},
+ TargetHealth: &types.TargetHealth{State: types.TargetHealthStateEnumUnhealthy, Reason: types.TargetHealthReasonEnumFailedHealthChecks},
+ },
+ },
+ }}
+ r := New(f, []string{tg80, tg443})
+ v, err := r.Withdrawn(context.Background(), self)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := ingresshealth.Verdict{Groups: []ingresshealth.Group{
+ {TargetGroup: tg80, Self: []ingresshealth.Entry{{Port: 80, State: ingresshealth.StateUnhealthyDraining}}, OtherHealthy: 1},
+ {TargetGroup: tg443, Self: []ingresshealth.Entry{{Port: 443, State: ingresshealth.StateUnhealthy, Reason: "Target.FailedHealthChecks"}}, OtherHealthy: 2},
+ }}
+ if !reflect.DeepEqual(v, want) {
+ t.Fatalf("verdict\n got %+v\nwant %+v", v, want)
+ }
+ if !v.Withdrawn() || !v.OthersHealthy() {
+ t.Fatalf("withdrawn %v others %v", v.Withdrawn(), v.OthersHealthy())
+ }
+ // One read per group per call, and never a Targets filter: the peer
+ // count comes from the same response.
+ if len(f.healthIn) != 2 {
+ t.Fatalf("%d reads", len(f.healthIn))
+ }
+ for i, in := range f.healthIn {
+ if in.Targets != nil || in.Include != nil {
+ t.Fatalf("read %d filtered: %+v", i, in)
+ }
+ if got := aws.ToString(in.TargetGroupArn); got != []string{tg80, tg443}[i] {
+ t.Fatalf("read %d asked %s", i, got)
+ }
+ }
+}
+
+func TestWithdrawnStateMapping(t *testing.T) {
+ for _, c := range []struct {
+ state types.TargetHealthStateEnum
+ withdrawn bool
+ }{
+ {types.TargetHealthStateEnumUnhealthy, true},
+ {types.TargetHealthStateEnumUnhealthyDraining, true},
+ {types.TargetHealthStateEnumHealthy, false},
+ {types.TargetHealthStateEnumInitial, false},
+ {types.TargetHealthStateEnumDraining, false},
+ {types.TargetHealthStateEnumUnused, false},
+ {types.TargetHealthStateEnumUnavailable, false},
+ {"some.new.state", false},
+ } {
+ t.Run(string(c.state), func(t *testing.T) {
+ f := &fakeAPI{health: map[string][]types.TargetHealthDescription{
+ tg80: {target(me, 80, c.state), target(peer, 80, types.TargetHealthStateEnumHealthy)},
+ }}
+ v, err := New(f, []string{tg80}).Withdrawn(context.Background(), self)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := v.Groups[0].State(); string(got) != string(c.state) {
+ t.Fatalf("state %q", got)
+ }
+ if v.Withdrawn() != c.withdrawn {
+ t.Fatalf("withdrawn = %v", v.Withdrawn())
+ }
+ })
+ }
+}
+
+// Only this instance on its registered ports is this box. The same instance
+// on a port it was not told about is ignored (neither self nor a peer), and
+// a peer that is not healthy is not counted.
+func TestWithdrawnMatchesInstanceAndPort(t *testing.T) {
+ f := &fakeAPI{health: map[string][]types.TargetHealthDescription{
+ tg80: {
+ target(me, 8080, types.TargetHealthStateEnumHealthy),
+ target(me, 80, types.TargetHealthStateEnumUnhealthy),
+ target(peer, 80, types.TargetHealthStateEnumDraining),
+ target(peer2, 80, types.TargetHealthStateEnumInitial),
+ {Target: nil, TargetHealth: &types.TargetHealth{State: types.TargetHealthStateEnumHealthy}},
+ {Target: &types.TargetDescription{Id: aws.String(peer)}, TargetHealth: nil},
+ },
+ }}
+ v, err := New(f, []string{tg80}).Withdrawn(context.Background(), self)
+ if err != nil {
+ t.Fatal(err)
+ }
+ g := v.Groups[0]
+ if !reflect.DeepEqual(g.Self, []ingresshealth.Entry{{Port: 80, State: ingresshealth.StateUnhealthy}}) {
+ t.Fatalf("self %+v", g.Self)
+ }
+ if g.OtherHealthy != 0 || v.OthersHealthy() {
+ t.Fatalf("other healthy %d", g.OtherHealthy)
+ }
+
+ // Not registered at all: absent, never withdrawn.
+ f.health[tg80] = []types.TargetHealthDescription{target(peer, 80, types.TargetHealthStateEnumHealthy)}
+ v, err = New(f, []string{tg80}).Withdrawn(context.Background(), self)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if v.Groups[0].State() != ingresshealth.StateAbsent || v.Withdrawn() || v.Groups[0].OtherHealthy != 1 {
+ t.Fatalf("absent: %+v", v.Groups[0])
+ }
+}
+
+func TestWithdrawnReadErrorNamesTheGroup(t *testing.T) {
+ f := &fakeAPI{
+ health: map[string][]types.TargetHealthDescription{tg80: {target(me, 80, types.TargetHealthStateEnumUnhealthy)}},
+ healthErr: map[string]error{tg443: errors.New("AccessDenied")},
+ }
+ v, err := New(f, []string{tg80, tg443}).Withdrawn(context.Background(), self)
+ if err == nil || !strings.Contains(err.Error(), tg443) || !strings.Contains(err.Error(), "AccessDenied") {
+ t.Fatalf("err %v", err)
+ }
+ // tg80 alone looks withdrawn; a partial verdict must not be returned.
+ if len(v.Groups) != 0 || v.Withdrawn() {
+ t.Fatalf("partial verdict %+v", v)
+ }
+}
+
+func attrs(kv ...string) []types.TargetGroupAttribute {
+ var out []types.TargetGroupAttribute
+ for i := 0; i < len(kv); i += 2 {
+ out = append(out, types.TargetGroupAttribute{Key: aws.String(kv[i]), Value: aws.String(kv[i+1])})
+ }
+ return out
+}
+
+func TestRetention(t *testing.T) {
+ const term, interval = "target_health_state.unhealthy.connection_termination.enabled", "target_health_state.unhealthy.draining_interval_seconds"
+ f := &fakeAPI{attrs: map[string][]types.TargetGroupAttribute{
+ tg80: attrs("deregistration_delay.timeout_seconds", "30", term, "false", interval, "180"),
+ tg443: attrs(term, "true", interval, "0"),
+ }}
+ got, err := New(f, []string{tg80, tg443}).Retention(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []ingresshealth.Retention{
+ {TargetGroup: tg80, TerminationOff: true, DrainingInterval: 180 * time.Second},
+ {TargetGroup: tg443, TerminationOff: false, DrainingInterval: 0},
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("retention\n got %+v\nwant %+v", got, want)
+ }
+ if !got[0].OK() || got[1].OK() {
+ t.Fatalf("OK: %v %v", got[0].OK(), got[1].OK())
+ }
+
+ // Missing or unreadable settings fail safe: termination on, interval 0.
+ for name, a := range map[string][]types.TargetGroupAttribute{
+ "missing": nil,
+ "garbage": attrs(term, "no", interval, "three minutes"),
+ "interval only": attrs(interval, "600"),
+ "negative": attrs(term, "false", interval, "-5"),
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := &fakeAPI{attrs: map[string][]types.TargetGroupAttribute{tg80: a}}
+ got, err := New(f, []string{tg80}).Retention(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got[0].OK() {
+ t.Fatalf("accepted %+v", got[0])
+ }
+ })
+ }
+
+ f = &fakeAPI{attrsErr: map[string]error{tg80: errors.New("Throttling")}}
+ if got, err := New(f, []string{tg80}).Retention(context.Background()); got != nil || err == nil || !strings.Contains(err.Error(), tg80) || !strings.Contains(err.Error(), "Throttling") {
+ t.Fatalf("err %v", err)
+ }
+}
+
+// The adapter satisfies the core's interface.
+var _ ingresshealth.Reader = (*Reader)(nil)
diff --git a/internal/ingresshealth/ingresshealth.go b/internal/ingresshealth/ingresshealth.go
new file mode 100644
index 000000000..89a54d3e8
--- /dev/null
+++ b/internal/ingresshealth/ingresshealth.go
@@ -0,0 +1,259 @@
+// Package ingresshealth answers the W6 ingress drain's one question about
+// the load balancer (fixed-edge ingress drain spec §4.1, §4.2 step 2): has
+// it stopped sending this box new flows? It holds the provider-neutral
+// shape of the answer and the interface the drain driver reads it through.
+// The AWS adapter, which reads Elastic Load Balancing's own target health,
+// is the awstg subpackage; this package imports no cloud SDK, so a box off
+// AWS builds it and simply has no reader and no drain.
+//
+// A reader makes one read per call. Polling, the settle and the cap are
+// the driver's.
+package ingresshealth
+
+import (
+ "context"
+ "fmt"
+ "regexp"
+ "strings"
+ "time"
+)
+
+// State is a target's health as the load balancer reports it. The values
+// are Elastic Load Balancing's, kept as strings so a state the code has
+// never seen is carried through and counts as not withdrawn.
+type State string
+
+const (
+ StateInitial State = "initial"
+ StateHealthy State = "healthy"
+ StateUnhealthy State = "unhealthy"
+ StateUnhealthyDraining State = "unhealthy.draining"
+ StateUnused State = "unused"
+ StateDraining State = "draining"
+ StateUnavailable State = "unavailable"
+ // StateAbsent is this package's own: the target group listed no entry
+ // for this box at all.
+ StateAbsent State = "absent"
+)
+
+// Withdrawn reports whether s means the load balancer sends the target no
+// new flows. Only unhealthy and unhealthy.draining do. draining and unused
+// are deregistration, and AWS notes a deregistering target may still get
+// new connections while the change propagates; the ingress drain never
+// deregisters, so seeing them means something else is going on.
+func (s State) Withdrawn() bool {
+ return s == StateUnhealthy || s == StateUnhealthyDraining
+}
+
+// Self is how a reader finds this box's own entries in a target group's
+// unfiltered answer: by instance id, on the ports it is registered on (80
+// and 443). An empty Ports matches the instance on any port.
+type Self struct {
+ InstanceID string
+ Ports []int32
+}
+
+// Entry is one of this box's registrations in a target group.
+type Entry struct {
+ Port int32
+ State State
+ Reason string // the load balancer's reason code, when it gives one
+}
+
+// Group is one target group's answer at one read.
+type Group struct {
+ TargetGroup string
+ // Self is this box's entries, in the order the load balancer listed
+ // them. Empty when the box is not registered in the group.
+ Self []Entry
+ // OtherHealthy counts the group's healthy targets that are not this
+ // box, from the same response. Zero means the load balancer may fail
+ // open (spec §8).
+ OtherHealthy int
+}
+
+// Withdrawn reports whether the group lists this box and every entry it
+// lists is withdrawn.
+func (g Group) Withdrawn() bool {
+ if len(g.Self) == 0 {
+ return false
+ }
+ for _, e := range g.Self {
+ if !e.State.Withdrawn() {
+ return false
+ }
+ }
+ return true
+}
+
+// Healthy reports whether the group lists this box and every entry is
+// healthy. The drain's "healthy at start" check reads it.
+func (g Group) Healthy() bool {
+ if len(g.Self) == 0 {
+ return false
+ }
+ for _, e := range g.Self {
+ if e.State != StateHealthy {
+ return false
+ }
+ }
+ return true
+}
+
+// State summarises the group for a report: StateAbsent with no entry, the
+// first entry that is not withdrawn if there is one (the one holding the
+// drain up), and otherwise the first entry's.
+func (g Group) State() State {
+ if len(g.Self) == 0 {
+ return StateAbsent
+ }
+ for _, e := range g.Self {
+ if !e.State.Withdrawn() {
+ return e.State
+ }
+ }
+ return g.Self[0].State
+}
+
+// Verdict is one read of every target group the box is registered in.
+type Verdict struct {
+ Groups []Group
+}
+
+// Withdrawn reports whether every group has withdrawn this box. A verdict
+// with no groups proves nothing and is not withdrawn.
+func (v Verdict) Withdrawn() bool {
+ if len(v.Groups) == 0 {
+ return false
+ }
+ for _, g := range v.Groups {
+ if !g.Withdrawn() {
+ return false
+ }
+ }
+ return true
+}
+
+// OthersHealthy reports whether every group has at least one healthy
+// target other than this box. A verdict with no groups has none.
+func (v Verdict) OthersHealthy() bool {
+ if len(v.Groups) == 0 {
+ return false
+ }
+ for _, g := range v.Groups {
+ if g.OtherHealthy < 1 {
+ return false
+ }
+ }
+ return true
+}
+
+// MinDrainingInterval is the shortest unhealthy draining interval the drain
+// accepts: the 90 s cap, 10 s settle and 30 s connection wait are 130 s,
+// with 50 s of margin (spec §8).
+const MinDrainingInterval = 180 * time.Second
+
+// Retention is a target group's handling of connections to a target that
+// turns unhealthy. The drain needs those connections kept, not reset.
+type Retention struct {
+ TargetGroup string
+ // TerminationOff is true when the group does not reset connections to
+ // a target the moment it turns unhealthy. The load balancer's default
+ // is to reset them, so an unreadable or missing setting is false.
+ TerminationOff bool
+ // DrainingInterval is how long an unhealthy target keeps its existing
+ // connections. Zero when unreadable or missing.
+ DrainingInterval time.Duration
+}
+
+// Problem says why r does not keep connections long enough for the drain,
+// or "" when it does.
+func (r Retention) Problem() string {
+ if !r.TerminationOff {
+ return "unhealthy connection termination is on"
+ }
+ if r.DrainingInterval < MinDrainingInterval {
+ return fmt.Sprintf("draining interval %s is below %s", r.DrainingInterval, MinDrainingInterval)
+ }
+ return ""
+}
+
+// OK reports whether r keeps connections long enough for the drain.
+func (r Retention) OK() bool { return r.Problem() == "" }
+
+// Reader reads the load balancer's view of this box. Each call is one read
+// of every target group the reader was built with.
+type Reader interface {
+ // Withdrawn reads every target group's health once. On a read error
+ // it returns an empty verdict (never a partial one, which could look
+ // withdrawn) and an error naming the target group.
+ Withdrawn(ctx context.Context, self Self) (Verdict, error)
+ // Retention reads every target group's unhealthy-connection settings
+ // once, one entry per group in order; on a read error, none and an
+ // error naming the group. The drain calls it once, before its first
+ // poll.
+ Retention(ctx context.Context) ([]Retention, error)
+}
+
+var (
+ arnPartition = regexp.MustCompile(`^aws(-[a-z]+)*$`)
+ // targetGroupResource is ELB's target group resource: a name of 1 to
+ // 32 letters, digits and hyphens, and a 16-hex-digit id.
+ targetGroupResource = regexp.MustCompile(`^targetgroup/[A-Za-z0-9-]{1,32}/[0-9a-f]{16}$`)
+)
+
+// ParseTargetGroups parses CARLOS_INGRESS_TARGET_GROUPS: a comma-separated
+// list of target group ARNs, each in the box's own account and region. It
+// refuses the whole value on an empty entry (so an empty value is refused;
+// callers treat a missing key as "no drain" before calling), a repeated
+// entry, or any entry that is not an Elastic Load Balancing target group
+// ARN in account and region. Spaces around entries are ignored.
+func ParseTargetGroups(value, account, region string) ([]string, error) {
+ if account == "" {
+ return nil, fmt.Errorf("ingress target groups: the box's account is unknown")
+ }
+ if region == "" {
+ return nil, fmt.Errorf("ingress target groups: the box's region is unknown")
+ }
+ var out []string
+ seen := map[string]int{}
+ for i, raw := range strings.Split(value, ",") {
+ n := i + 1
+ arn := strings.TrimSpace(raw)
+ if arn == "" {
+ return nil, fmt.Errorf("ingress target groups: entry %d is empty", n)
+ }
+ if first, ok := seen[arn]; ok {
+ return nil, fmt.Errorf("ingress target groups: entry %d repeats entry %d", n, first)
+ }
+ seen[arn] = n
+ if err := checkTargetGroupARN(arn, account, region); err != nil {
+ return nil, fmt.Errorf("ingress target groups: entry %d %q: %w", n, arn, err)
+ }
+ out = append(out, arn)
+ }
+ return out, nil
+}
+
+func checkTargetGroupARN(arn, account, region string) error {
+ parts := strings.Split(arn, ":")
+ if len(parts) != 6 || parts[0] != "arn" {
+ return fmt.Errorf("not an ARN")
+ }
+ if !arnPartition.MatchString(parts[1]) {
+ return fmt.Errorf("partition %q is not an AWS partition", parts[1])
+ }
+ if parts[2] != "elasticloadbalancing" {
+ return fmt.Errorf("not an elasticloadbalancing ARN")
+ }
+ if parts[3] != region {
+ return fmt.Errorf("region %s, not the box's %s", parts[3], region)
+ }
+ if parts[4] != account {
+ return fmt.Errorf("account %s, not the box's %s", parts[4], account)
+ }
+ if !targetGroupResource.MatchString(parts[5]) {
+ return fmt.Errorf("not a target group")
+ }
+ return nil
+}
diff --git a/internal/ingresshealth/ingresshealth_test.go b/internal/ingresshealth/ingresshealth_test.go
new file mode 100644
index 000000000..8753d36c3
--- /dev/null
+++ b/internal/ingresshealth/ingresshealth_test.go
@@ -0,0 +1,184 @@
+package ingresshealth
+
+import (
+ "go/parser"
+ "go/token"
+ "path/filepath"
+ "reflect"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+const (
+ acct = "123456789012"
+ region = "eu-west-1"
+ tg80 = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge-80/0123456789abcdef"
+ tg443 = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge-443/fedcba9876543210"
+)
+
+// Only unhealthy and unhealthy.draining mean the load balancer has stopped
+// sending this box new flows. draining and unused are deregistration, which
+// AWS says may still receive new connections while it propagates.
+func TestStateWithdrawn(t *testing.T) {
+ for s, want := range map[State]bool{
+ StateUnhealthy: true,
+ StateUnhealthyDraining: true,
+ StateHealthy: false,
+ StateInitial: false,
+ StateDraining: false,
+ StateUnused: false,
+ StateUnavailable: false,
+ StateAbsent: false,
+ State("future.state"): false,
+ State(""): false,
+ } {
+ if got := s.Withdrawn(); got != want {
+ t.Errorf("%q.Withdrawn() = %v, want %v", s, got, want)
+ }
+ }
+}
+
+func TestGroupAndVerdict(t *testing.T) {
+ e := func(port int32, s State) Entry { return Entry{Port: port, State: s} }
+ cases := []struct {
+ name string
+ g Group
+ withdrawn, healthy bool
+ state State
+ }{
+ {"not registered", Group{}, false, false, StateAbsent},
+ {"healthy", Group{Self: []Entry{e(80, StateHealthy)}}, false, true, StateHealthy},
+ {"unhealthy", Group{Self: []Entry{e(80, StateUnhealthy)}}, true, false, StateUnhealthy},
+ {"unhealthy.draining", Group{Self: []Entry{e(80, StateUnhealthyDraining)}}, true, false, StateUnhealthyDraining},
+ {"draining", Group{Self: []Entry{e(80, StateDraining)}}, false, false, StateDraining},
+ {"unused", Group{Self: []Entry{e(80, StateUnused)}}, false, false, StateUnused},
+ {"one port still healthy", Group{Self: []Entry{e(80, StateUnhealthy), e(443, StateHealthy)}}, false, false, StateHealthy},
+ {"both ports withdrawn", Group{Self: []Entry{e(80, StateUnhealthy), e(443, StateUnhealthyDraining)}}, true, false, StateUnhealthy},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ if got := c.g.Withdrawn(); got != c.withdrawn {
+ t.Errorf("Withdrawn = %v", got)
+ }
+ if got := c.g.Healthy(); got != c.healthy {
+ t.Errorf("Healthy = %v", got)
+ }
+ if got := c.g.State(); got != c.state {
+ t.Errorf("State = %q, want %q", got, c.state)
+ }
+ })
+ }
+
+ out := Group{TargetGroup: tg80, Self: []Entry{e(80, StateUnhealthy)}, OtherHealthy: 1}
+ in := Group{TargetGroup: tg443, Self: []Entry{e(443, StateHealthy)}, OtherHealthy: 0}
+ if (Verdict{}).Withdrawn() || (Verdict{}).OthersHealthy() {
+ t.Fatal("an empty verdict proves nothing")
+ }
+ if v := (Verdict{Groups: []Group{out, in}}); v.Withdrawn() || v.OthersHealthy() {
+ t.Fatalf("mixed verdict: withdrawn %v others %v", v.Withdrawn(), v.OthersHealthy())
+ }
+ out2 := out
+ out2.TargetGroup = tg443
+ if v := (Verdict{Groups: []Group{out, out2}}); !v.Withdrawn() || !v.OthersHealthy() {
+ t.Fatalf("withdrawn verdict: withdrawn %v others %v", v.Withdrawn(), v.OthersHealthy())
+ }
+}
+
+func TestRetention(t *testing.T) {
+ cases := []struct {
+ r Retention
+ problem string
+ }{
+ {Retention{TerminationOff: true, DrainingInterval: 180 * time.Second}, ""},
+ {Retention{TerminationOff: true, DrainingInterval: 3600 * time.Second}, ""},
+ {Retention{TerminationOff: false, DrainingInterval: 180 * time.Second}, "unhealthy connection termination is on"},
+ {Retention{TerminationOff: true, DrainingInterval: 179 * time.Second}, "draining interval 2m59s is below 3m0s"},
+ {Retention{}, "unhealthy connection termination is on"},
+ }
+ for _, c := range cases {
+ if got := c.r.Problem(); got != c.problem {
+ t.Errorf("%+v: Problem = %q, want %q", c.r, got, c.problem)
+ }
+ if c.r.OK() != (c.problem == "") {
+ t.Errorf("%+v: OK = %v", c.r, c.r.OK())
+ }
+ }
+}
+
+func TestParseTargetGroups(t *testing.T) {
+ got, err := ParseTargetGroups(tg80+", "+tg443, acct, region)
+ if err != nil || !reflect.DeepEqual(got, []string{tg80, tg443}) {
+ t.Fatalf("ParseTargetGroups = %v, %v", got, err)
+ }
+ if got, err := ParseTargetGroups(tg80, acct, region); err != nil || !reflect.DeepEqual(got, []string{tg80}) {
+ t.Fatalf("one ARN = %v, %v", got, err)
+ }
+ cn := "arn:aws-cn:elasticloadbalancing:cn-north-1:123456789012:targetgroup/edge/0123456789abcdef"
+ if _, err := ParseTargetGroups(cn, acct, "cn-north-1"); err != nil {
+ t.Fatalf("aws-cn partition refused: %v", err)
+ }
+
+ for _, c := range []struct{ name, value, account, region, want string }{
+ {"empty value", "", acct, region, "entry 1 is empty"},
+ {"blank value", " ", acct, region, "entry 1 is empty"},
+ {"trailing comma", tg80 + ",", acct, region, "entry 2 is empty"},
+ {"empty middle", tg80 + ",," + tg443, acct, region, "entry 2 is empty"},
+ {"duplicate", tg80 + "," + tg80, acct, region, "entry 2 repeats entry 1"},
+ {"duplicate with spaces", tg80 + ", " + tg80 + " ", acct, region, "entry 2 repeats entry 1"},
+ {"other account", strings.Replace(tg80, acct, "210987654321", 1), acct, region, "account 210987654321, not the box's 123456789012"},
+ {"other region", strings.Replace(tg80, region, "us-east-1", 1), acct, region, "region us-east-1, not the box's eu-west-1"},
+ {"load balancer ARN", "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/ingress/0123456789abcdef", acct, region, "not a target group"},
+ {"listener ARN", "arn:aws:elasticloadbalancing:eu-west-1:123456789012:listener/net/ingress/0123456789abcdef/0123456789abcdef", acct, region, "not a target group"},
+ {"other service", "arn:aws:ec2:eu-west-1:123456789012:targetgroup/edge-80/0123456789abcdef", acct, region, "not an elasticloadbalancing ARN"},
+ {"not an ARN", "edge-80", acct, region, "not an ARN"},
+ {"bad partition", "arn:gcp:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge-80/0123456789abcdef", acct, region, "partition"},
+ {"short id", "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge-80/0123", acct, region, "not a target group"},
+ {"extra path", tg80 + "/x", acct, region, "not a target group"},
+ {"bad name", "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge_80/0123456789abcdef", acct, region, "not a target group"},
+ {"inner space", "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge 80/0123456789abcdef", acct, region, "not a target group"},
+ {"no box account", tg80, "", region, "the box's account is unknown"},
+ {"no box region", tg80, acct, "", "the box's region is unknown"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ got, err := ParseTargetGroups(c.value, c.account, c.region)
+ if err == nil || !strings.Contains(err.Error(), c.want) {
+ t.Fatalf("ParseTargetGroups(%q) = %v, %v; want error containing %q", c.value, got, err, c.want)
+ }
+ if got != nil {
+ t.Fatalf("a refusal returned ARNs %v", got)
+ }
+ })
+ }
+}
+
+// The core package stays provider-neutral: the AWS SDK lives in the
+// adapter (awstg), so hostenv and the drain driver can use these types
+// without importing AWS.
+func TestCoreImportsNoAWS(t *testing.T) {
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ checked := 0
+ for _, path := range files {
+ if strings.HasSuffix(path, "_test.go") {
+ continue
+ }
+ f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
+ if err != nil {
+ t.Fatal(err)
+ }
+ checked++
+ for _, imp := range f.Imports {
+ p, _ := strconv.Unquote(imp.Path.Value)
+ if strings.HasPrefix(p, "github.com/aws/") || strings.HasSuffix(p, "/ingresshealth/awstg") {
+ t.Errorf("%s imports %s", path, p)
+ }
+ }
+ }
+ if checked == 0 {
+ t.Fatal("no production files checked")
+ }
+}