host: trust routes only when armed; validate answers; warn metric off
Review fixes for Task 5. The drain socket carries /v1/edge/ only on a box with CARLOS_INGRESS_PROXY_SOURCES (newAgentDrainSocket), so other boxes answer 404 as before; a 404 reads host.env to say not armed or a stale agent. Trust answers are presence-aware and validated in the child and in root. The socket and the metric counter source are tested over a real *edge.Edge through a small test seam in internal/edge. memwatch warns when it stays off on an armed box.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+502
−94
internal/edge/proxyingress_seam.go+12 −0internal/host/agent.go+3 −8internal/host/edgetrust.go+183 −45internal/host/edgetrust_linux_test.go+60 −0internal/host/edgetrust_test.go+71 −19internal/host/edgetrust_wiring_test.go+124 −0internal/host/memwatch.go+49 −22
Intent
diff --git a/internal/edge/proxyingress_seam.go b/internal/edge/proxyingress_seam.go| new file mode 100644 |
| index 000000000..2df0bb4ab |
| --- /dev/null |
| +++ b/internal/edge/proxyingress_seam.go |
| @@ -0,0 +1,12 @@ |
| +package edge |
| + |
| +import "net/netip" |
| + |
| +// ArmProxyIngressForTest arms e for PROXY protocol as Serve does with |
| +// CARLOS_INGRESS_PROXY_SOURCES naming trusted, its barrier file under |
| +// dataDir. TEST SEAM: it exists so other packages' tests (the agent's drain |
| +// socket and trust metric, internal/host) can drive a real armed *Edge |
| +// without Serve. Production arms only through Serve (loadProxyIngress). |
| +func (e *Edge) ArmProxyIngressForTest(trusted []netip.Addr, dataDir string) error { |
| + return e.armProxyIngress(trusted, dataDir) |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 01dbac446..b77c3e24b 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -203,7 +203,6 @@ import ( |
| "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/moves" |
| "github.com/carlosframework/platform/internal/provision" |
| - "github.com/carlosframework/platform/internal/proxyproto" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/replicas" |
| @@ -1085,12 +1084,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| go statusLoop(reg, svc, collectBuildStates, egressStatus, boxJudge, func() bool { return demoEdge.Load().DemoMovedReady() }) |
| // The memory early-warning (memory-pressure spec §2.4): per box, gated |
| // by CARLOS_HOST_METRICS — one log line and nothing else where unset. |
| - go memwatchLoop(func() (proxyproto.Counters, bool) { |
| - if e := demoEdge.Load(); e != nil { |
| - return e.ProxyCounters() |
| - } |
| - return proxyproto.Counters{}, false |
| - }) |
| + go memwatchLoop(edgeProxyCounters(&demoEdge)) |
| go domainsLoop(reg, peekAcmeCache(args), claims.Writes.Enabled) |
| go instancesLoop(reg, claims.Writes, bs, boxJudge, claims.Providers.Provision) |
| // The deployment-global election, armed BEFORE the loops it gates so a |
| @@ -1261,7 +1255,8 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // 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, edge: e} |
| + // The edge's trust routes only on a box armed for PROXY protocol. |
| + driver := newAgentDrainSocket(ingress, e, os.Getenv) |
| e.SetHAIngressLookup(boxHAIngress.lookup) |
| armedGroupReaders.Store(&groupReaderSource{snapshot: e.GroupReaderSnapshot}) |
| // Read the current hub view on each private socket request. |
diff --git a/internal/host/edgetrust.go b/internal/host/edgetrust.go| index 82bc1046c..c998bb345 100644 |
| --- a/internal/host/edgetrust.go |
| +++ b/internal/host/edgetrust.go |
| @@ -32,6 +32,7 @@ import ( |
| "net/http" |
| "os" |
| "strings" |
| + "sync/atomic" |
| "time" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| @@ -65,6 +66,29 @@ func drainSocketServed(groupMember bool, getenv func(string) string, admission * |
| return groupMember || ingressDrainServed(getenv, admission) || proxySourcesSet(getenv) |
| } |
| +// newAgentDrainSocket is the agent's drain socket surface: the ingress |
| +// drain's routes, and the edge's trust routes only on a box whose host.env |
| +// arms it for PROXY protocol, so a box without the key answers /v1/edge/ |
| +// with 404 as before them. runAgent sets the group drain on members. |
| +func newAgentDrainSocket(ingress *ingressDrain, e trustEdge, getenv func(string) string) *haDrainSocket { |
| + s := &haDrainSocket{ingress: ingress} |
| + if proxySourcesSet(getenv) { |
| + s.edge = e |
| + } |
| + return s |
| +} |
| + |
| +// edgeProxyCounters is the trust metric's counter source over the agent's |
| +// edge pointer: false until the edge runs, and while it is not armed. |
| +func edgeProxyCounters(current *atomic.Pointer[edge.Edge]) func() (proxyproto.Counters, bool) { |
| + return func() (proxyproto.Counters, bool) { |
| + if e := current.Load(); e != nil { |
| + return e.ProxyCounters() |
| + } |
| + return proxyproto.Counters{}, false |
| + } |
| +} |
| + |
| // trustCounters is proxyproto.Counters without the per-node map, under the |
| // names the journal line uses (spec §4.5). |
| type trustCounters struct { |
| @@ -86,19 +110,128 @@ type trustStatus struct { |
| ProxiedByNode map[string]uint64 `json:"proxied_by_node"` |
| } |
| -// trustResult is any of the three routes' answers, as the drain call child |
| -// carries it to root (drainCallResult.Trust). Armed is absent from an armed |
| -// edge's barrier and resume answers. Persisted (false) and Error are set |
| -// only on a barrier the edge raised but could not write to its file: up in |
| -// the running edge, down after a restart. |
| +// trustChange is the barrier and resume routes' answer. Persisted (false) |
| +// and Error are set only on a barrier the edge raised but could not write |
| +// to its file: up in the running edge, down after a restart. |
| +type trustChange struct { |
| + Barrier bool `json:"barrier"` |
| + Closed *int `json:"closed,omitempty"` |
| + Persisted *bool `json:"persisted,omitempty"` |
| + Error string `json:"error,omitempty"` |
| +} |
| + |
| +// trustOff is the barrier and resume answer of an edge not armed. |
| +type trustOff struct { |
| + Armed bool `json:"armed"` |
| + Barrier bool `json:"barrier"` |
| +} |
| + |
| +// trustResult is any of the three routes' answers on the wire, as the |
| +// drain call child reads it from the socket and carries it to root |
| +// (drainCallResult.Trust). Every field is presence-aware, so an answer |
| +// missing what its op requires is refused (validTrust), never read as a |
| +// zero: a lost barrier field is not "down". ProxiedByNode is not omitted |
| +// when nil, so an empty object and an absent one stay apart. |
| type trustResult struct { |
| - Armed *bool `json:"armed,omitempty"` |
| - Barrier bool `json:"barrier"` |
| - Closed *int `json:"closed,omitempty"` |
| - Persisted *bool `json:"persisted,omitempty"` |
| - Error string `json:"error,omitempty"` |
| - Counters *trustCounters `json:"counters,omitempty"` |
| - ProxiedByNode map[string]uint64 `json:"proxied_by_node,omitempty"` |
| + Armed *bool `json:"armed,omitempty"` |
| + Barrier *bool `json:"barrier,omitempty"` |
| + Closed *int `json:"closed,omitempty"` |
| + Persisted *bool `json:"persisted,omitempty"` |
| + Error string `json:"error,omitempty"` |
| + Counters *trustCountersWire `json:"counters,omitempty"` |
| + ProxiedByNode map[string]uint64 `json:"proxied_by_node"` |
| +} |
| + |
| +// trustCountersWire is trustCounters with each counter's presence. |
| +type trustCountersWire struct { |
| + Proxied *uint64 `json:"proxied,omitempty"` |
| + NoClient *uint64 `json:"no_client,omitempty"` |
| + NoClientRefused *uint64 `json:"no_client_refused,omitempty"` |
| + Ignored *uint64 `json:"ignored,omitempty"` |
| + IgnoredPrivate *uint64 `json:"ignored_private,omitempty"` |
| + MarkerTrusted *uint64 `json:"marker_trusted,omitempty"` |
| + Malformed *uint64 `json:"malformed,omitempty"` |
| + Timeout *uint64 `json:"timeout,omitempty"` |
| +} |
| + |
| +// counters is c with every counter present, ok false when one is absent. |
| +func (c *trustCountersWire) counters() (trustCounters, bool) { |
| + if c == nil { |
| + return trustCounters{}, false |
| + } |
| + for _, p := range []*uint64{c.Proxied, c.NoClient, c.NoClientRefused, c.Ignored, c.IgnoredPrivate, c.MarkerTrusted, c.Malformed, c.Timeout} { |
| + if p == nil { |
| + return trustCounters{}, false |
| + } |
| + } |
| + return trustCounters{ |
| + Proxied: *c.Proxied, NoClient: *c.NoClient, NoClientRefused: *c.NoClientRefused, Ignored: *c.Ignored, |
| + IgnoredPrivate: *c.IgnoredPrivate, MarkerTrusted: *c.MarkerTrusted, Malformed: *c.Malformed, Timeout: *c.Timeout, |
| + }, true |
| +} |
| + |
| +// errTrustIncomplete is an agent's trust answer without what its op |
| +// requires. |
| +var errTrustIncomplete = errors.New("the agent answered nothing usable") |
| + |
| +// trustAnswer is what an op's answer t says, once validTrust accepts it. |
| +type trustAnswer int |
| + |
| +const ( |
| + trustAnswerNotArmed trustAnswer = iota + 1 |
| + trustAnswerStatus |
| + trustAnswerRaised |
| + trustAnswerRaisedNotPersisted |
| + trustAnswerLowered |
| +) |
| + |
| +// validTrust reads t as op's answer: every field the answer needs present, |
| +// nothing another answer carries. The child checks it before it prints, |
| +// and root again before it acts. |
| +func validTrust(op string, t *trustResult) (trustAnswer, error) { |
| + if t == nil { |
| + return 0, errTrustIncomplete |
| + } |
| + change := t.Counters == nil && t.ProxiedByNode == nil |
| + switch { |
| + case t.Armed != nil && !*t.Armed: |
| + // Not armed: the barrier and resume answer is exactly |
| + // {"armed":false,"barrier":false}; status carries the rest too. |
| + if t.Barrier == nil || *t.Barrier || t.Closed != nil || t.Persisted != nil || t.Error != "" { |
| + return 0, errTrustIncomplete |
| + } |
| + if op == "trust-status" { |
| + if _, ok := t.Counters.counters(); !ok || t.ProxiedByNode == nil { |
| + return 0, errTrustIncomplete |
| + } |
| + } else if !change { |
| + return 0, errTrustIncomplete |
| + } |
| + return trustAnswerNotArmed, nil |
| + case op == "trust-status": |
| + if _, ok := t.Counters.counters(); t.Armed == nil || !ok || t.Barrier == nil || t.ProxiedByNode == nil || |
| + t.Closed != nil || t.Persisted != nil || t.Error != "" { |
| + return 0, errTrustIncomplete |
| + } |
| + return trustAnswerStatus, nil |
| + case t.Armed != nil || !change || t.Barrier == nil: |
| + return 0, errTrustIncomplete |
| + case op == "trust-barrier": |
| + if !*t.Barrier || t.Closed == nil || *t.Closed < 0 { |
| + return 0, errTrustIncomplete |
| + } |
| + switch { |
| + case t.Persisted == nil && t.Error == "": |
| + return trustAnswerRaised, nil |
| + case t.Persisted != nil && !*t.Persisted && t.Error != "": |
| + return trustAnswerRaisedNotPersisted, nil |
| + } |
| + case op == "trust-resume": |
| + if !*t.Barrier && t.Closed == nil && t.Persisted == nil && t.Error == "" { |
| + return trustAnswerLowered, nil |
| + } |
| + } |
| + return 0, errTrustIncomplete |
| } |
| func barrierWord(up bool) string { |
| @@ -108,12 +241,6 @@ func barrierWord(up bool) string { |
| return "down" |
| } |
| -// trustNotArmed is the barrier and resume answer of an edge not armed. |
| -func trustNotArmed() trustResult { |
| - armed := false |
| - return trustResult{Armed: &armed} |
| -} |
| - |
| func trustStatusOf(e trustEdge) trustStatus { |
| c, armed := e.ProxyCounters() |
| s := trustStatus{ |
| @@ -148,14 +275,14 @@ func edgeTrustHandler(e trustEdge) http.Handler { |
| closed, err := e.RaiseTrustBarrier() |
| switch { |
| case errors.Is(err, edge.ErrProxyProtocolOff): |
| - _ = json.NewEncoder(w).Encode(trustNotArmed()) |
| + _ = json.NewEncoder(w).Encode(trustOff{}) |
| case errors.Is(err, edge.ErrBarrierNotPersisted): |
| // The edge raised the flag and swept all the same: the |
| // barrier is up, and the answer says it, with why a |
| // restart would lower it. The verb fails on it. |
| log.Printf("agent: edge trust barrier raised by the root verb, NOT persisted; %d trusted connections closed: %v", closed, err) |
| persisted := false |
| - _ = json.NewEncoder(w).Encode(trustResult{Barrier: true, Closed: &closed, Persisted: &persisted, Error: err.Error()}) |
| + _ = json.NewEncoder(w).Encode(trustChange{Barrier: true, Closed: &closed, Persisted: &persisted, Error: err.Error()}) |
| case err != nil: |
| // Whether the flag went up despite the error is the edge's |
| // to say; report it with the error rather than guess. |
| @@ -165,13 +292,13 @@ func edgeTrustHandler(e trustEdge) http.Handler { |
| _ = json.NewEncoder(w).Encode(drainError{Error: msg}) |
| default: |
| log.Printf("agent: edge trust barrier raised by the root verb; %d trusted connections closed", closed) |
| - _ = json.NewEncoder(w).Encode(trustResult{Barrier: true, Closed: &closed}) |
| + _ = json.NewEncoder(w).Encode(trustChange{Barrier: true, Closed: &closed}) |
| } |
| case r.Method == http.MethodPost && r.URL.Path == "/v1/edge/trust-resume": |
| err := e.ResumeTrust() |
| switch { |
| case errors.Is(err, edge.ErrProxyProtocolOff): |
| - _ = json.NewEncoder(w).Encode(trustNotArmed()) |
| + _ = json.NewEncoder(w).Encode(trustOff{}) |
| case err != nil: |
| msg := fmt.Sprintf("%v (barrier %s in the running edge)", err, barrierWord(e.TrustBarrierUp())) |
| log.Printf("agent: edge trust barrier: %s", msg) |
| @@ -179,7 +306,7 @@ func edgeTrustHandler(e trustEdge) http.Handler { |
| _ = json.NewEncoder(w).Encode(drainError{Error: msg}) |
| default: |
| log.Print("agent: edge trust barrier lowered by the root verb") |
| - _ = json.NewEncoder(w).Encode(trustResult{Barrier: false}) |
| + _ = json.NewEncoder(w).Encode(trustChange{Barrier: false}) |
| } |
| default: |
| http.NotFound(w, r) |
| @@ -197,17 +324,22 @@ func edgeTrustVerb(verb string) bool { |
| return verb == "trust-barrier" || verb == "trust-resume" || verb == "trust-status" |
| } |
| -// trust asks the agent's edge for one trust op. |
| +// trust asks the agent's edge for one trust op. An answer without what |
| +// the op requires is an error (validTrust), so the child never passes on |
| +// a zero. |
| func (c *drainClient) trust(ctx context.Context, op string) (*trustResult, error) { |
| method, path := http.MethodPost, "/v1/edge/"+op |
| if op == "trust-status" { |
| method, path = http.MethodGet, "/v1/edge/trust" |
| } |
| - var r trustResult |
| + var r *trustResult |
| if err := c.call(ctx, method, path, nil, &r); err != nil { |
| return nil, err |
| } |
| - return &r, nil |
| + if _, err := validTrust(op, r); err != nil { |
| + return nil, err |
| + } |
| + return r, nil |
| } |
| const edgeTrustHelp = `Usage: carlos system edge {trust-barrier|trust-resume|trust-status} |
| @@ -276,39 +408,46 @@ func (cmd edgeTrustCommand) run(ctx context.Context, args []string, out, stderr |
| } |
| return fail(1, errDrainAgentDown.Error()) |
| case r.NoRoute: |
| - return fail(1, "the agent has no trust barrier (an older release)") |
| + // A socket without the routes: a box not armed (whose socket |
| + // serves other verbs), or an agent older than the routes or not |
| + // restarted since the key was set. host.env tells which. |
| + if getenv, err := cmd.hostEnv(); err == nil && !proxySourcesSet(getenv) { |
| + return fail(2, errEdgeNotArmed.Error()) |
| + } |
| + return fail(1, "the agent does not serve the trust routes: an older release, or not restarted since the key was set") |
| case r.Error != "": |
| return fail(1, oneLine(r.Error)) |
| } |
| t := r.Trust |
| - if t == nil { |
| - return fail(1, "the agent answered nothing usable") |
| + answer, err := validTrust(verb, t) |
| + if err != nil { |
| + return fail(1, err.Error()) |
| } |
| var line any |
| - switch { |
| - case t.Armed != nil && !*t.Armed: |
| + switch answer { |
| + case trustAnswerNotArmed: |
| if verb == "trust-status" { |
| if err := json.NewEncoder(out).Encode(trustStatusLine(t)); err != nil { |
| return 1 |
| } |
| } |
| return fail(2, errEdgeNotArmed.Error()) |
| - case verb == "trust-status" && t.Armed != nil && t.Counters != nil: |
| + case trustAnswerStatus: |
| line = trustStatusLine(t) |
| - case verb == "trust-barrier" && t.Armed == nil && t.Barrier && t.Closed != nil && t.Persisted != nil && !*t.Persisted && t.Error != "": |
| + case trustAnswerRaisedNotPersisted: |
| // Up in the running edge, not on disk: print it as it is and fail, |
| // so the operator sees the barrier is up and will not survive a |
| // restart. |
| - if err := json.NewEncoder(out).Encode(trustResult{Barrier: true, Closed: t.Closed, Persisted: t.Persisted, Error: t.Error}); err != nil { |
| + if err := json.NewEncoder(out).Encode(trustChange{Barrier: true, Closed: t.Closed, Persisted: t.Persisted, Error: t.Error}); err != nil { |
| return 1 |
| } |
| return fail(1, "the trust barrier is up in the running edge but not persisted, so a restart would come up without it: "+oneLine(t.Error)) |
| - case verb == "trust-barrier" && t.Armed == nil && t.Barrier && t.Closed != nil && t.Persisted == nil && t.Error == "": |
| - line = trustResult{Barrier: true, Closed: t.Closed} |
| - case verb == "trust-resume" && t.Armed == nil && !t.Barrier && t.Closed == nil && t.Persisted == nil && t.Error == "": |
| - line = trustResult{Barrier: false} |
| + case trustAnswerRaised: |
| + line = trustChange{Barrier: true, Closed: t.Closed} |
| + case trustAnswerLowered: |
| + line = trustChange{Barrier: false} |
| default: |
| - return fail(1, "the agent answered nothing usable") |
| + return fail(1, errTrustIncomplete.Error()) |
| } |
| if err := json.NewEncoder(out).Encode(line); err != nil { |
| return 1 |
| @@ -316,13 +455,12 @@ func (cmd edgeTrustCommand) run(ctx context.Context, args []string, out, stderr |
| return 0 |
| } |
| -// trustStatusLine is a status answer as trust-status prints it: every |
| -// field present, proxied_by_node an object even when empty. |
| +// trustStatusLine is a status answer validTrust accepted, as trust-status |
| +// prints it: every field present, proxied_by_node an object even when |
| +// empty. |
| func trustStatusLine(t *trustResult) trustStatus { |
| - s := trustStatus{Armed: t.Armed != nil && *t.Armed, Barrier: t.Barrier, ProxiedByNode: map[string]uint64{}} |
| - if t.Counters != nil { |
| - s.Counters = *t.Counters |
| - } |
| + counters, _ := t.Counters.counters() |
| + s := trustStatus{Armed: *t.Armed, Barrier: *t.Barrier, Counters: counters, ProxiedByNode: map[string]uint64{}} |
| for a, n := range t.ProxiedByNode { |
| s.ProxiedByNode[a] = n |
| } |
diff --git a/internal/host/edgetrust_linux_test.go b/internal/host/edgetrust_linux_test.go| index e5b23c90a..81d310e64 100644 |
| --- a/internal/host/edgetrust_linux_test.go |
| +++ b/internal/host/edgetrust_linux_test.go |
| @@ -7,9 +7,12 @@ import ( |
| "context" |
| "errors" |
| "fmt" |
| + "net" |
| + "net/http" |
| "os" |
| "path/filepath" |
| "strings" |
| + "sync/atomic" |
| "testing" |
| "github.com/carlosframework/platform/internal/edge" |
| @@ -85,3 +88,60 @@ func TestEdgeTrustVerbsOverTheSocket(t *testing.T) { |
| t.Fatalf("no agent: %d %q", code, errOut) |
| } |
| } |
| + |
| +// TestDrainCallTrustRefusesIncomplete: an agent answer missing what its op |
| +// requires (null, empty, no barrier, a counter or proxied_by_node absent) |
| +// is an error from the child, never a zero result, and the verb fails. |
| +func TestDrainCallTrustRefusesIncomplete(t *testing.T) { |
| + dir, err := os.MkdirTemp("", "et") |
| + must(t, err) |
| + t.Cleanup(func() { os.RemoveAll(dir) }) |
| + path := filepath.Join(dir, "t.sock") |
| + l, err := net.Listen("unix", path) |
| + must(t, err) |
| + var body atomic.Value |
| + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Write([]byte(body.Load().(string))) |
| + })} |
| + go srv.Serve(l) |
| + t.Cleanup(func() { srv.Close() }) |
| + call := socketDrainCall(newDrainClient(path)) |
| + const counters = `{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0}` |
| + for _, tc := range []struct { |
| + op, body string |
| + ok bool |
| + }{ |
| + {"trust-resume", `{"barrier":false}`, true}, |
| + {"trust-resume", `null`, false}, |
| + {"trust-resume", `{}`, false}, |
| + {"trust-resume", `{"barrier":true}`, false}, |
| + {"trust-barrier", `{"barrier":true,"closed":0}`, true}, |
| + {"trust-barrier", `{"closed":1}`, false}, |
| + {"trust-barrier", `{"barrier":true}`, false}, |
| + {"trust-barrier", `{"barrier":true,"closed":1,"persisted":false}`, false}, |
| + {"trust-barrier", `{"barrier":true,"closed":1,"persisted":false,"error":"edge: not persisted"}`, true}, |
| + {"trust-barrier", `{"armed":false,"barrier":false}`, true}, |
| + {"trust-status", `{"armed":true,"barrier":false,"counters":` + counters + `,"proxied_by_node":{}}`, true}, |
| + {"trust-status", `{"armed":true,"counters":` + counters + `,"proxied_by_node":{}}`, false}, |
| + {"trust-status", `{"armed":true,"barrier":false,"counters":{"proxied":1},"proxied_by_node":{}}`, false}, |
| + {"trust-status", `{"armed":true,"barrier":false,"counters":` + counters + `}`, false}, |
| + {"trust-status", `{"armed":true,"barrier":false,"counters":` + counters + `,"proxied_by_node":null}`, false}, |
| + {"trust-status", `{"barrier":false,"counters":` + counters + `,"proxied_by_node":{}}`, false}, |
| + {"trust-status", `null`, false}, |
| + } { |
| + body.Store(tc.body) |
| + r, err := call(context.Background(), tc.op, "", nil) |
| + if err != nil || r.AgentDown || r.NoRoute { |
| + t.Fatalf("%s %s: %+v %v", tc.op, tc.body, r, err) |
| + } |
| + if got := r.Trust != nil && r.Error == ""; got != tc.ok { |
| + t.Fatalf("%s %s: accepted %v, want %v (%+v)", tc.op, tc.body, got, tc.ok, r) |
| + } |
| + cmd := edgeTrustCommand{euid: func() int { return 0 }, call: call, |
| + hostEnv: func() (func(string) string, error) { return envOf(nil), nil }} |
| + var out, errOut bytes.Buffer |
| + if code := cmd.run(context.Background(), []string{tc.op}, &out, &errOut); !tc.ok && (code != 1 || out.Len() != 0) { |
| + t.Fatalf("%s %s: verb exit %d out %q", tc.op, tc.body, code, out.String()) |
| + } |
| + } |
| +} |
diff --git a/internal/host/edgetrust_test.go b/internal/host/edgetrust_test.go| index 4cfc56041..931a3d3f1 100644 |
| --- a/internal/host/edgetrust_test.go |
| +++ b/internal/host/edgetrust_test.go |
| @@ -111,8 +111,9 @@ func serveTrust(t *testing.T, h http.Handler, method, target string) (int, strin |
| } |
| // TestEdgeTrustRoutes: the three /v1/edge/ routes on the drain socket |
| -// answer the barrier, the resume and the status, an unarmed edge answers |
| -// armed false, and a query string or another method is 404. |
| +// answer the barrier, the resume and the status, and a query string or |
| +// another method is 404. On a box without CARLOS_INGRESS_PROXY_SOURCES the |
| +// agent's socket has no /v1/edge/ routes at all: 404, as before them. |
| func TestEdgeTrustRoutes(t *testing.T) { |
| f := &fakeTrustEdge{armed: true, closed: 3, counters: trustCountersFixture()} |
| h := (&haDrainSocket{edge: f}).handler() |
| @@ -159,7 +160,25 @@ func TestEdgeTrustRoutes(t *testing.T) { |
| t.Fatalf("failed raise: %d %s", code, body) |
| } |
| - off := (&haDrainSocket{edge: &fakeTrustEdge{}}).handler() |
| + // Dormant: the agent's socket on a box without the key serves no |
| + // /v1/edge/ route, whatever edge it runs. |
| + for _, e := range []*fakeTrustEdge{{}, {armed: true}} { |
| + h := newAgentDrainSocket(nil, e, envOf(nil)).handler() |
| + for _, tc := range []struct{ method, target string }{ |
| + {http.MethodGet, "/v1/edge/trust"}, {http.MethodPost, "/v1/edge/trust-barrier"}, {http.MethodPost, "/v1/edge/trust-resume"}, |
| + } { |
| + if code, _ := serveTrust(t, h, tc.method, tc.target); code != http.StatusNotFound { |
| + t.Fatalf("unarmed box (edge armed %v) %s %s: %d, want 404", e.armed, tc.method, tc.target, code) |
| + } |
| + } |
| + if e.raised != 0 || e.resumed != 0 { |
| + t.Fatalf("an unarmed box's socket reached the edge: raised %d resumed %d", e.raised, e.resumed) |
| + } |
| + } |
| + |
| + // Defensive only (the key set but the edge unarmed cannot happen: the |
| + // edge refuses to start on a value it cannot read): armed false. |
| + off := edgeTrustHandler(&fakeTrustEdge{}) |
| if code, body := serveTrust(t, off, http.MethodGet, "/v1/edge/trust"); code != 200 || |
| body != `{"armed":false,"barrier":false,"counters":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0},"proxied_by_node":{}}` { |
| t.Fatalf("unarmed status: %d %s", code, body) |
| @@ -176,6 +195,20 @@ func TestEdgeTrustRoutes(t *testing.T) { |
| } |
| } |
| +// TestAgentDrainSocketEdgeRoutes: the agent's socket carries the edge |
| +// only on a box whose host.env arms it. |
| +func TestAgentDrainSocketEdgeRoutes(t *testing.T) { |
| + f := &fakeTrustEdge{armed: true} |
| + if s := newAgentDrainSocket(nil, f, envOf(map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": "172.31.29.110"})); s.edge == nil { |
| + t.Fatal("an armed box's socket has no edge") |
| + } |
| + for _, v := range []string{"", " ", "8.8.8.8"} { |
| + if s := newAgentDrainSocket(nil, f, envOf(map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": v})); s.edge != nil { |
| + t.Fatalf("CARLOS_INGRESS_PROXY_SOURCES=%q: the socket carries the edge", v) |
| + } |
| + } |
| +} |
| + |
| // TestDrainSocketServedWhenArmed: a fixed box with only |
| // CARLOS_INGRESS_PROXY_SOURCES serves the socket; nothing set, it does not. |
| func TestDrainSocketServedWhenArmed(t *testing.T) { |
| @@ -318,12 +351,16 @@ func TestTrustMetricFromEnv(t *testing.T) { |
| // TestDrainCallTrustRoundTrip: root reads the child's trust answer, whose |
| // shape parseDrainCall checks strictly. |
| func TestDrainCallTrustRoundTrip(t *testing.T) { |
| - armed, closed := true, 2 |
| + armed, up, down, closed := true, true, false, 2 |
| + status := trustResult{Armed: &armed, Barrier: &up, Counters: zeroCountersWire(), ProxiedByNode: map[string]uint64{"172.31.29.110": 1}} |
| + empty := status |
| + empty.ProxiedByNode = map[string]uint64{} |
| for _, want := range []trustResult{ |
| - {Barrier: true, Closed: &closed}, |
| - {Barrier: false}, |
| - {Barrier: true, Closed: &closed, Persisted: new(bool), Error: "edge: not persisted"}, |
| - {Armed: &armed, Barrier: true, Counters: &trustCounters{Proxied: 1, MarkerTrusted: 2}, ProxiedByNode: map[string]uint64{"172.31.29.110": 1}}, |
| + {Barrier: &up, Closed: &closed}, |
| + {Barrier: &down}, |
| + {Barrier: &up, Closed: &closed, Persisted: new(bool), Error: "edge: not persisted"}, |
| + status, |
| + empty, |
| } { |
| b, err := json.Marshal(drainCallResult{V: 1, Trust: &want}) |
| if err != nil { |
| @@ -338,6 +375,9 @@ func TestDrainCallTrustRoundTrip(t *testing.T) { |
| if !bytes.Equal(got, exp) { |
| t.Fatalf("round trip %s, want %s", got, exp) |
| } |
| + if want.Armed != nil && r.Trust.ProxiedByNode == nil { |
| + t.Fatalf("%s: proxied_by_node lost its presence", b) |
| + } |
| } |
| if _, err := parseDrainCall([]byte(`{"v":1,"trust":{"barrier":true,"other":1}}`)); err == nil { |
| t.Fatal("an unknown trust field was accepted") |
| @@ -362,8 +402,8 @@ func TestDrainCallTrustRoundTrip(t *testing.T) { |
| // the child: the one JSON line each prints, not-armed as exit 2, the |
| // agent's failures as exit 1, and arguments and root checked first. |
| func TestEdgeTrustVerbAnswers(t *testing.T) { |
| - armed, notArmed, closed := true, false, 4 |
| - status := &trustResult{Armed: &armed, Counters: &trustCounters{}, ProxiedByNode: nil} |
| + armed, notArmed, up, down, closed := true, false, true, false, 4 |
| + status := &trustResult{Armed: &armed, Barrier: &down, Counters: zeroCountersWire(), ProxiedByNode: map[string]uint64{}} |
| run := func(r drainCallResult, callErr error, hostEnv string, euid int, args ...string) (int, string, string, []string) { |
| var asked []string |
| cmd := edgeTrustCommand{ |
| @@ -399,26 +439,32 @@ func TestEdgeTrustVerbAnswers(t *testing.T) { |
| out string |
| errOut string |
| }{ |
| - {"barrier", drainCallResult{V: 1, Trust: &trustResult{Barrier: true, Closed: &closed}}, nil, "", 0, []string{"trust-barrier"}, 0, `{"barrier":true,"closed":4}` + "\n", ""}, |
| - {"resume", drainCallResult{V: 1, Trust: &trustResult{}}, nil, "", 0, []string{"trust-resume"}, 0, `{"barrier":false}` + "\n", ""}, |
| + {"barrier", drainCallResult{V: 1, Trust: &trustResult{Barrier: &up, Closed: &closed}}, nil, "", 0, []string{"trust-barrier"}, 0, `{"barrier":true,"closed":4}` + "\n", ""}, |
| + {"resume", drainCallResult{V: 1, Trust: &trustResult{Barrier: &down}}, nil, "", 0, []string{"trust-resume"}, 0, `{"barrier":false}` + "\n", ""}, |
| + {"resume, empty answer", drainCallResult{V: 1, Trust: &trustResult{}}, nil, "", 0, []string{"trust-resume"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| + {"status, no barrier", drainCallResult{V: 1, Trust: &trustResult{Armed: &armed, Counters: zeroCountersWire(), ProxiedByNode: map[string]uint64{}}}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| + {"status, no proxied_by_node", drainCallResult{V: 1, Trust: &trustResult{Armed: &armed, Barrier: &down, Counters: zeroCountersWire()}}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| + {"status, a counter missing", drainCallResult{V: 1, Trust: &trustResult{Armed: &armed, Barrier: &down, Counters: &trustCountersWire{Proxied: new(uint64)}, ProxiedByNode: map[string]uint64{}}}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| + {"barrier, no closed", drainCallResult{V: 1, Trust: &trustResult{Barrier: &up}}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| {"status", drainCallResult{V: 1, Trust: status}, nil, "", 0, []string{"trust-status"}, 0, |
| `{"armed":true,"barrier":false,"counters":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0},"proxied_by_node":{}}` + "\n", ""}, |
| - {"status unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: ¬Armed, Counters: &trustCounters{}}}, nil, "", 0, []string{"trust-status"}, 2, |
| + {"status unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: ¬Armed, Barrier: &down, Counters: zeroCountersWire(), ProxiedByNode: map[string]uint64{}}}, nil, "", 0, []string{"trust-status"}, 2, |
| `{"armed":false,"barrier":false,"counters":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0},"proxied_by_node":{}}` + "\n", |
| "edge: this box is not armed for PROXY protocol\n"}, |
| - {"barrier unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: ¬Armed}}, nil, "", 0, []string{"trust-barrier"}, 2, "", "edge: this box is not armed for PROXY protocol\n"}, |
| - {"resume unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: ¬Armed}}, nil, "", 0, []string{"trust-resume"}, 2, "", "edge: this box is not armed for PROXY protocol\n"}, |
| + {"barrier unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: ¬Armed, Barrier: &down}}, nil, "", 0, []string{"trust-barrier"}, 2, "", "edge: this box is not armed for PROXY protocol\n"}, |
| + {"resume unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: ¬Armed, Barrier: &down}}, nil, "", 0, []string{"trust-resume"}, 2, "", "edge: this box is not armed for PROXY protocol\n"}, |
| {"no socket, host.env unarmed", drainCallResult{V: 1, AgentDown: true, Error: "dial"}, nil, "", 0, []string{"trust-status"}, 2, "", "edge: this box is not armed for PROXY protocol\n"}, |
| {"no socket, host.env armed", drainCallResult{V: 1, AgentDown: true, Error: "dial"}, nil, "172.31.29.110", 0, []string{"trust-barrier"}, 1, "", "edge: the agent's drain socket is not answering\n"}, |
| - {"older agent", drainCallResult{V: 1, NoRoute: true, Error: "404"}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: the agent has no trust barrier (an older release)\n"}, |
| + {"no route, host.env unarmed", drainCallResult{V: 1, NoRoute: true, Error: "404"}, nil, "", 0, []string{"trust-barrier"}, 2, "", "edge: this box is not armed for PROXY protocol\n"}, |
| + {"no route, host.env armed", drainCallResult{V: 1, NoRoute: true, Error: "404"}, nil, "172.31.29.110", 0, []string{"trust-status"}, 1, "", "edge: the agent does not serve the trust routes: an older release, or not restarted since the key was set\n"}, |
| {"agent error", drainCallResult{V: 1, Error: "edge: write trust barrier: disk\nfull"}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: edge: write trust barrier: disk full\n"}, |
| {"child failed", drainCallResult{}, errors.New("the drain call failed"), "", 0, []string{"trust-barrier"}, 1, "", "edge: the drain call failed\n"}, |
| {"no answer", drainCallResult{V: 1}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| - {"barrier not persisted", drainCallResult{V: 1, Trust: &trustResult{Barrier: true, Closed: &closed, Persisted: ¬Armed, Error: "edge: trust barrier raised in the running edge, not persisted: disk\nfull"}}, nil, "", 0, []string{"trust-barrier"}, 1, |
| + {"barrier not persisted", drainCallResult{V: 1, Trust: &trustResult{Barrier: &up, Closed: &closed, Persisted: ¬Armed, Error: "edge: trust barrier raised in the running edge, not persisted: disk\nfull"}}, nil, "", 0, []string{"trust-barrier"}, 1, |
| `{"barrier":true,"closed":4,"persisted":false,"error":"edge: trust barrier raised in the running edge, not persisted: disk\nfull"}` + "\n", |
| "edge: the trust barrier is up in the running edge but not persisted, so a restart would come up without it: edge: trust barrier raised in the running edge, not persisted: disk full\n"}, |
| - {"persisted on resume", drainCallResult{V: 1, Trust: &trustResult{Persisted: ¬Armed, Error: "x"}}, nil, "", 0, []string{"trust-resume"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| - {"wrong shape", drainCallResult{V: 1, Trust: &trustResult{}}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| + {"persisted on resume", drainCallResult{V: 1, Trust: &trustResult{Barrier: &down, Persisted: ¬Armed, Error: "x"}}, nil, "", 0, []string{"trust-resume"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| + {"wrong shape", drainCallResult{V: 1, Trust: &trustResult{Barrier: &down}}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| } { |
| code, out, errOut, asked := run(tc.r, tc.callErr, tc.hostEnv, tc.euid, tc.args...) |
| if code != tc.code || out != tc.out || errOut != tc.errOut || len(asked) != 1 || asked[0] != tc.args[0] { |
| @@ -440,3 +486,9 @@ func TestEdgeTrustVerbAnswers(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// zeroCountersWire is a status answer's counters, every one present. |
| +func zeroCountersWire() *trustCountersWire { |
| + z := func() *uint64 { return new(uint64) } |
| + return &trustCountersWire{Proxied: z(), NoClient: z(), NoClientRefused: z(), Ignored: z(), IgnoredPrivate: z(), MarkerTrusted: z(), Malformed: z(), Timeout: z()} |
| +} |
diff --git a/internal/host/edgetrust_wiring_test.go b/internal/host/edgetrust_wiring_test.go| new file mode 100644 |
| index 000000000..c54770eff |
| --- /dev/null |
| +++ b/internal/host/edgetrust_wiring_test.go |
| @@ -0,0 +1,124 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/proxyproto" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// TestAgentTrustWiringWithARealEdge: the agent's socket and the metric's |
| +// counter source, built as runAgent builds them, over a real *edge.Edge. |
| +// Unarmed, the socket has no /v1/edge/ route and the source says unarmed; |
| +// armed, a raise through the socket puts the barrier up in the edge and |
| +// on disk, and a resume takes it down from both. |
| +func TestAgentTrustWiringWithARealEdge(t *testing.T) { |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + noErr(t, err) |
| + t.Cleanup(func() { reg.Close() }) |
| + e, err := edge.New(reg, nil) |
| + noErr(t, err) |
| + |
| + var current atomic.Pointer[edge.Edge] |
| + counters := edgeProxyCounters(¤t) |
| + if _, ok := counters(); ok { |
| + t.Fatal("before the edge runs, the metric source says armed") |
| + } |
| + current.Store(e) |
| + if _, ok := counters(); ok { |
| + t.Fatal("an unarmed edge's metric source says armed") |
| + } |
| + for _, env := range []map[string]string{nil, {"CARLOS_INGRESS_PROXY_SOURCES": "172.31.29.110"}} { |
| + h := newAgentDrainSocket(nil, e, envOf(env)).handler() |
| + code, body := serveTrust(t, h, http.MethodPost, "/v1/edge/trust-barrier") |
| + if env == nil && code != http.StatusNotFound { |
| + t.Fatalf("unarmed box: %d %s, want 404", code, body) |
| + } |
| + if env != nil && (code != 200 || body != `{"armed":false,"barrier":false}`) { |
| + t.Fatalf("key set, edge unarmed: %d %s", code, body) |
| + } |
| + } |
| + |
| + dir := t.TempDir() |
| + noErr(t, e.ArmProxyIngressForTest([]netip.Addr{netip.MustParseAddr("172.31.29.110")}, dir)) |
| + if c, ok := counters(); !ok || c.NoClientRefused != 0 { |
| + t.Fatalf("an armed edge's metric source: %+v %v", c, ok) |
| + } |
| + if newAgentDrainSocket(nil, e, envOf(nil)).edge != nil { |
| + t.Fatal("a box without the key carries even an armed edge") |
| + } |
| + h := newAgentDrainSocket(nil, e, envOf(map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": "172.31.29.110"})).handler() |
| + file := filepath.Join(dir, "edge", "trust-barrier") |
| + if code, body := serveTrust(t, h, http.MethodPost, "/v1/edge/trust-barrier"); code != 200 || body != `{"barrier":true,"closed":0}` { |
| + t.Fatalf("raise: %d %s", code, body) |
| + } |
| + if _, err := os.Stat(file); err != nil || !e.TrustBarrierUp() { |
| + t.Fatalf("after the raise: file %v, up %v", err, e.TrustBarrierUp()) |
| + } |
| + if code, body := serveTrust(t, h, http.MethodGet, "/v1/edge/trust"); code != 200 || !strings.HasPrefix(body, `{"armed":true,"barrier":true,"counters":{`) || !strings.HasSuffix(body, `"proxied_by_node":{}}`) { |
| + t.Fatalf("status: %d %s", code, body) |
| + } |
| + if code, body := serveTrust(t, h, http.MethodPost, "/v1/edge/trust-resume"); code != 200 || body != `{"barrier":false}` { |
| + t.Fatalf("resume: %d %s", code, body) |
| + } |
| + if _, err := os.Stat(file); !errors.Is(err, os.ErrNotExist) || e.TrustBarrierUp() { |
| + t.Fatalf("after the resume: file %v, up %v", err, e.TrustBarrierUp()) |
| + } |
| +} |
| + |
| +// TestMemwatchWarnsWhenTrustMetricOff: on a box armed for PROXY protocol, |
| +// every way memwatch stays off names the trust metric; an unarmed box's |
| +// lines are as before. |
| +func TestMemwatchWarnsWhenTrustMetricOff(t *testing.T) { |
| + armed := map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": "172.31.29.110"} |
| + metrics := map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": "172.31.29.110", "CARLOS_HOST_METRICS": "cloudwatch"} |
| + okConfig := func(context.Context) (aws.Config, error) { return aws.Config{Region: "eu-west-1"}, nil } |
| + badConfig := func(context.Context) (aws.Config, error) { return aws.Config{}, errors.New("no credentials") } |
| + okID := func() (string, error) { return "i-0123", nil } |
| + badID := func() (string, error) { return "", errors.New("no IMDS") } |
| + for _, tc := range []struct { |
| + name string |
| + env map[string]string |
| + config func(context.Context) (aws.Config, error) |
| + id func() (string, error) |
| + warn bool |
| + }{ |
| + {"metrics unset", armed, okConfig, okID, true}, |
| + {"metrics another value", map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": "172.31.29.110", "CARLOS_HOST_METRICS": "true"}, okConfig, okID, true}, |
| + {"no aws config", metrics, badConfig, okID, true}, |
| + {"no instance id", metrics, okConfig, badID, true}, |
| + {"unarmed, metrics unset", nil, okConfig, okID, false}, |
| + {"unarmed, no instance id", map[string]string{"CARLOS_HOST_METRICS": "cloudwatch"}, okConfig, badID, false}, |
| + } { |
| + var lines []string |
| + logf := func(format string, args ...any) { lines = append(lines, format) } |
| + w := newMemwatch(context.Background(), envOf(tc.env), logf, memwatchDeps{ |
| + loadConfig: tc.config, placement: func() string { return "" }, instanceID: tc.id, |
| + trustCounters: func() (proxyproto.Counters, bool) { return proxyproto.Counters{}, false }, |
| + }) |
| + if w != nil { |
| + t.Fatalf("%s: memwatch armed", tc.name) |
| + } |
| + warned := strings.Contains(strings.Join(lines, "\n"), "IngressProxyTrustViolations") |
| + if warned != tc.warn { |
| + t.Fatalf("%s: trust warning %v, want %v: %q", tc.name, warned, tc.warn, lines) |
| + } |
| + } |
| +} |
| + |
| +func noErr(t *testing.T, err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/host/memwatch.go b/internal/host/memwatch.go| index 5631d7414..0d59e61b1 100644 |
| --- a/internal/host/memwatch.go |
| +++ b/internal/host/memwatch.go |
| @@ -98,20 +98,50 @@ func memwatchArmed(getenv func(string) string) (armed bool, why string) { |
| // trustCounters reads the running edge's PROXY protocol counters for the |
| // trust-violation metric (false before the edge runs, or unarmed). |
| func memwatchLoop(trustCounters func() (proxyproto.Counters, bool)) { |
| - if armed, why := memwatchArmed(os.Getenv); !armed { |
| - log.Printf("agent: memwatch disabled (%s)", why) |
| + ctx := context.Background() |
| + w := newMemwatch(ctx, os.Getenv, log.Printf, memwatchDeps{ |
| + loadConfig: func(ctx context.Context) (aws.Config, error) { return rootaws.LoadDefaultConfig(ctx) }, placement: readPlacementRegion, |
| + instanceID: imdsInstanceID, trustCounters: trustCounters, |
| + }) |
| + if w == nil { |
| return |
| } |
| - ctx := context.Background() |
| + for now := range time.Tick(memwatchPeriod) { |
| + w.tick(ctx, now) |
| + } |
| +} |
| + |
| +// memwatchDeps are what arming memwatch reaches outside the process. |
| +type memwatchDeps struct { |
| + loadConfig func(context.Context) (aws.Config, error) |
| + placement func() string |
| + instanceID func() (string, error) |
| + trustCounters func() (proxyproto.Counters, bool) |
| +} |
| + |
| +// newMemwatch is memwatchLoop's arming: the duty, or nil (logged) when it |
| +// stays off. On a box armed for PROXY protocol, staying off also turns off |
| +// the trust-violation metric, the S3 alarm's only source, so each way off |
| +// says so as a warning (edge PPv2 spec §4.5, §6.1). |
| +func newMemwatch(ctx context.Context, getenv func(string) string, logf func(string, ...any), d memwatchDeps) *memwatch { |
| + off := func(format string, args ...any) *memwatch { |
| + logf(format, args...) |
| + if proxySourcesSet(getenv) { |
| + logf("memwatch: WARNING: this box is armed for PROXY protocol and IngressProxyTrustViolations is not published, so the trust-violation alarm cannot fire for it") |
| + } |
| + return nil |
| + } |
| + if armed, why := memwatchArmed(getenv); !armed { |
| + return off("agent: memwatch disabled (%s)", why) |
| + } |
| // Region comes from the default chain — AWS_REGION in host.env, else |
| // IMDS. A compatible-store deployment that points AWS_REGION at its |
| // own object store (internal/lease/endpoint.go's note) would aim the |
| // CloudWatch client at nonsense, which is one more reason this duty |
| // is opt-in per box rather than on wherever credentials resolve. |
| - cfg, err := rootaws.LoadDefaultConfig(ctx) |
| + cfg, err := d.loadConfig(ctx) |
| if err != nil { |
| - log.Printf("agent: memwatch disabled: load aws config: %v", err) |
| - return |
| + return off("agent: memwatch disabled: load aws config: %v", err) |
| } |
| // The metric goes to the box's OWN region, not host.env's AWS_REGION: |
| // the flagship sets AWS_REGION=eu-west-1 fleet-wide (it names the |
| @@ -120,33 +150,30 @@ func memwatchLoop(trustCounters func() (proxyproto.Counters, bool)) { |
| // creates each box's alarm in the box's region, so three alarms would |
| // have watched an empty namespace forever. IMDS placement wins; "" (not |
| // on EC2) keeps the chain's answer. |
| - cfg = groupMetricsAWSConfig(cfg, readPlacementRegion(), groupReferenced(os.Getenv)) |
| - id, err := imdsInstanceID() |
| + cfg = groupMetricsAWSConfig(cfg, d.placement(), groupReferenced(getenv)) |
| + id, err := d.instanceID() |
| if err != nil { |
| - log.Printf("agent: memwatch disabled: instance id: %v", err) |
| - return |
| + return off("agent: memwatch disabled: instance id: %v", err) |
| } |
| - w := memwatch{ |
| + w := &memwatch{ |
| put: putMetricFunc(cloudwatch.NewFromConfig(cfg).PutMetricData), |
| instanceID: id, |
| mem: readMemBytes, |
| pressure: readPressureFile, |
| - logf: log.Printf, |
| + logf: logf, |
| } |
| - w.admission = admissionMetricsFromEnv(os.Getenv, armedFixedAdmission.Load(), readRoleRegionConfig, func(ctx context.Context) (time.Duration, error) { |
| + w.admission = admissionMetricsFromEnv(getenv, armedFixedAdmission.Load(), readRoleRegionConfig, func(ctx context.Context) (time.Duration, error) { |
| return readChronyTracking(ctx, exec.CommandContext) |
| }) |
| - if os.Getenv("CARLOS_GROUP_ADMISSION") == "1" && w.admission == nil { |
| - log.Print("memwatch: admission metrics are disabled; group boxes require admission state, a deployment bucket, region configuration, and a verified launch binding") |
| - } |
| - w.trust = trustMetricFromEnv(os.Getenv, readRoleRegionConfig, trustCounters) |
| - if w.trust == nil && proxySourcesSet(os.Getenv) { |
| - log.Print("memwatch: the trust-violation metric is disabled; a box armed for PROXY protocol requires a deployment bucket and region configuration") |
| + if getenv("CARLOS_GROUP_ADMISSION") == "1" && w.admission == nil { |
| + logf("memwatch: admission metrics are disabled; group boxes require admission state, a deployment bucket, region configuration, and a verified launch binding") |
| } |
| - log.Printf("agent: memwatch armed (%s in %s, every %s, instance %s)", memwatchNamespace, cfg.Region, memwatchPeriod, id) |
| - for now := range time.Tick(memwatchPeriod) { |
| - w.tick(ctx, now) |
| + w.trust = trustMetricFromEnv(getenv, readRoleRegionConfig, d.trustCounters) |
| + if w.trust == nil && proxySourcesSet(getenv) { |
| + logf("memwatch: WARNING: IngressProxyTrustViolations is disabled; a box armed for PROXY protocol requires a deployment bucket and region configuration") |
| } |
| + logf("agent: memwatch armed (%s in %s, every %s, instance %s)", memwatchNamespace, cfg.Region, memwatchPeriod, id) |
| + return w |
| } |
| // tick reads, builds, puts. A failed read skips the tick (a zero would look |