status: each box reports its instances' egress read-back (#328)
The status tick asks root's GET /egress (5 s timeout) and publishes each listed host's report in the private Metrics block as "egress", with the agent's own policy state (provision.PolicyReadStates) where root's report has none. Under claims, under_claims is published only for a row that carries an allow. A failed read, or a box with no control channel, leaves the field absent; a box with nothing reported publishes no egress key.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+395
−4
internal/host/agent.go+11 −2internal/host/egress_status.go+97 −0internal/host/egress_status_test.go+181 −0internal/status/contract_test.go+10 −1internal/status/snapshot.go+23 −1internal/status/snapshot_test.go+73 −0
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 0b19d9d3e..ccfaa4582 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -396,6 +396,9 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| var act edge.Activator |
| var svc *activator.Service |
| + // egressStatus is root's GET /egress for the status tick (#328): set |
| + // with the control channel below, and left nil on a box without one. |
| + var egressStatus egressStatusReader |
| started := make(chan struct{}) |
| var startupDone <-chan struct{} |
| if cfg != nil { |
| @@ -455,6 +458,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // what the rest of this process already knows about the box. |
| ctl := instancectl.NewClient(controlsock.Path) |
| eb.Control = ctl |
| + egressStatus = ctl |
| // A grant or revoke the agent converged into the registry reaches |
| // root on the next 2 s beat rather than root's 30 s loop (#328). |
| go egressNudgeLoop(agentCtx, reg, ctl) |
| @@ -824,7 +828,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // sees them (cfg.HostWrites.Enabled, set by configureWakeClaims). |
| buildStateClaims := cfg != nil && cfg.HostWrites.Enabled |
| collectBuildStates := func() (map[string]status.BuildStatePins, error) { return buildStatePins(reg, buildStateClaims) } |
| - go statusLoop(reg, svc, collectBuildStates) |
| + go statusLoop(reg, svc, collectBuildStates, egressStatus) |
| // 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() |
| @@ -3926,7 +3930,7 @@ func upstreamStates() map[string][]status.UpstreamState { |
| // logging that every 5 minutes forever would bury the log in noise. Any |
| // OTHER acquire error (a real S3/credential problem) is logged, same as any |
| // other tick failure. |
| -func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func() (map[string]status.BuildStatePins, error)) { |
| +func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func() (map[string]status.BuildStatePins, error), egressStatus egressStatusReader) { |
| ctx := context.Background() |
| // bucket is read for the lease key alone (lease.Acquire below), which a |
| // fleet box never reaches: shouldSkipPublisherElection short-circuits the |
| @@ -4131,6 +4135,11 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func |
| // The update-settings protocol this box enforces, and root's last |
| // decision per instance (settings spec §4.3). Private Metrics only. |
| fillUpdateProbes(&p, reg, release.OptDir()) |
| + // Each instance's egress read-back as root last asserted it, with |
| + // the agent's own policy state where root has none (#328). Root's |
| + // local socket and an in-memory map: no store request. Private |
| + // Metrics only: hosts. |
| + p.Egress = egressStatusProbe(egressStatus, routes, provision.PolicyReadStates()) |
| // A fleet box (CARLOS_FLEET set) never gets here as a contender: it |
| // self-reports only, never attempting the election at all — no |
diff --git a/internal/host/egress_status.go b/internal/host/egress_status.go| new file mode 100644 |
| index 000000000..b9ad0d673 |
| --- /dev/null |
| +++ b/internal/host/egress_status.go |
| @@ -0,0 +1,97 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "log" |
| + "strings" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// egressStatusTimeout bounds the status tick's GET /egress to root. |
| +const egressStatusTimeout = 5 * time.Second |
| + |
| +// egressStatusReader is root's GET /egress; *instancectl.Client satisfies it. |
| +type egressStatusReader interface { |
| + EgressStatus(context.Context) (instancectl.EgressStatus, error) |
| +} |
| + |
| +// egressStatusErrs counts the status tick's failed GET /egress in a row, |
| +// so a root that stays unreachable logs once and then hourly. |
| +var egressStatusErrs atomic.Int64 |
| + |
| +// egressStatusProbe is the box snapshot's per-host egress read-back (#328, |
| +// spec §4.4): root's last report for each host this box lists, as root |
| +// read it back from systemd, so the console shows what is in force. |
| +// |
| +// Before claims the agent is the one that verifies an app's policy (plan |
| +// 1), and on a policy it cannot use it empties the row's column, so root |
| +// only ever sees no allow. agentStates (provision.PolicyReadStates) puts |
| +// the agent's word back: an instance row whose "<account>/<app>" has an |
| +// entry, and whose root report has no State, gets State "unreadable", |
| +// "unverifiable" or "expired". Root's own State and Detail stand as root |
| +// sent them. |
| +// |
| +// Under claims (ruling 9) root reports under_claims for every slice it |
| +// asserts; that is published only for a row that carries an allow, so an |
| +// operator who granted one sees why it is not in force and a box with no |
| +// policy publishes nothing new. A host with nothing to say (no address |
| +// held, none refused, no state) is left out, and so is a host the box no |
| +// longer lists. |
| +// |
| +// A nil c (no control channel on this box), or a failed read, is nil: not |
| +// reported, which is not the same as nothing allowed. The read is root's |
| +// local socket, with a 5 s timeout: no store request. |
| +func egressStatusProbe(c egressStatusReader, rows []registry.Route, agentStates map[string]string) map[string]status.HostEgress { |
| + if c == nil { |
| + return nil |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), egressStatusTimeout) |
| + defer cancel() |
| + st, err := c.EgressStatus(ctx) |
| + if err != nil { |
| + if n := egressStatusErrs.Add(1); n == 1 || n%12 == 0 { |
| + log.Printf("agent: status tick: egress read-back (#%d): %v", n, err) |
| + } |
| + return nil |
| + } |
| + egressStatusErrs.Store(0) |
| + |
| + var out map[string]status.HostEgress |
| + for _, rt := range rows { |
| + rep := st.Hosts[rt.Host] |
| + h := status.HostEgress{Allowed: rep.Allowed, Refused: rep.Refused, State: rep.State, Detail: rep.Detail} |
| + if h.State == instancectl.EgressUnderClaims && strings.TrimSpace(rt.EgressAllow) == "" { |
| + continue |
| + } |
| + if h.State == "" && rt.Kind == "instance" && rt.Account != "" && rt.App != "" { |
| + h.State = agentPolicyState(agentStates[rt.Account+"/"+rt.App]) |
| + } |
| + if h.State == "" && h.Detail == "" && len(h.Allowed) == 0 && len(h.Refused) == 0 { |
| + continue |
| + } |
| + if out == nil { |
| + out = map[string]status.HostEgress{} |
| + } |
| + out[rt.Host] = h |
| + } |
| + return out |
| +} |
| + |
| +// agentPolicyState maps provision.PolicyReadStates' value to the status |
| +// word: "policy unreadable" to "unreadable", and so on. Anything else is "". |
| +func agentPolicyState(v string) string { |
| + switch v { |
| + case "policy unreadable": |
| + return instancectl.EgressUnreadable |
| + case "policy unverifiable": |
| + return "unverifiable" // the agent's alone: root never reports it |
| + case "policy expired": |
| + return instancectl.EgressExpired |
| + } |
| + return "" |
| +} |
diff --git a/internal/host/egress_status_test.go b/internal/host/egress_status_test.go| new file mode 100644 |
| index 000000000..909690cb7 |
| --- /dev/null |
| +++ b/internal/host/egress_status_test.go |
| @@ -0,0 +1,181 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// fakeEgressStatus answers GET /egress with st, or err, and records the |
| +// deadline it was asked under. |
| +type fakeEgressStatus struct { |
| + st instancectl.EgressStatus |
| + err error |
| + calls int |
| + deadline time.Duration |
| +} |
| + |
| +func (f *fakeEgressStatus) EgressStatus(ctx context.Context) (instancectl.EgressStatus, error) { |
| + f.calls++ |
| + if d, ok := ctx.Deadline(); ok { |
| + f.deadline = time.Until(d) |
| + } |
| + return f.st, f.err |
| +} |
| + |
| +func rootReports(r map[string]instancectl.EgressReport) *fakeEgressStatus { |
| + return &fakeEgressStatus{st: instancectl.EgressStatus{Hosts: r}} |
| +} |
| + |
| +func egressStatusRow(host, account, app, allow string) registry.Route { |
| + return registry.Route{Host: host, Kind: "instance", Account: account, App: app, EgressAllow: allow} |
| +} |
| + |
| +func TestEgressStatusProbeConvertsAndFailsQuiet(t *testing.T) { |
| + t.Parallel() |
| + rows := []registry.Route{ |
| + egressStatusRow("shop-a.example.com", "abc", "shop", "10.0.5.20 10.0.0.0/8"), |
| + egressStatusRow("shop-b.example.com", "abc", "shop", "10.0.5.20"), |
| + egressStatusRow("shop-c.example.com", "zzz", "blog", ""), |
| + } |
| + c := rootReports(map[string]instancectl.EgressReport{ |
| + "shop-a.example.com": {Allowed: []string{"10.0.5.20"}, Refused: []string{"10.0.0.0/8: too wide"}}, |
| + "shop-b.example.com": {Allowed: []string{"10.0.5.20"}, State: instancectl.EgressFailing, Detail: "set-property: exit status 1"}, |
| + // Asserted with nothing wanted and nothing held: nothing to say. |
| + "shop-c.example.com": {}, |
| + // A report for a host this box no longer lists is not published. |
| + "gone.example.com": {Allowed: []string{"10.0.5.21"}}, |
| + }) |
| + got := egressStatusProbe(c, rows, nil) |
| + want := map[string]status.HostEgress{ |
| + "shop-a.example.com": {Allowed: []string{"10.0.5.20"}, Refused: []string{"10.0.0.0/8: too wide"}}, |
| + "shop-b.example.com": {Allowed: []string{"10.0.5.20"}, State: "failing", Detail: "set-property: exit status 1"}, |
| + } |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("probe = %+v\nwant %+v", got, want) |
| + } |
| + if c.calls != 1 || c.deadline <= 0 || c.deadline > egressStatusTimeout { |
| + t.Fatalf("asked root %d times under a %s deadline, want once under at most %s", c.calls, c.deadline, egressStatusTimeout) |
| + } |
| + |
| + // Root unreachable: the field is absent ("not reported"), never an |
| + // empty table that would read as "nothing allowed". |
| + failing := &fakeEgressStatus{err: errors.New("dial unix /run/carlos/control.sock: connect: no such file or directory")} |
| + if got := egressStatusProbe(failing, rows, map[string]string{"abc/shop": "policy expired"}); got != nil { |
| + t.Fatalf("a failed read = %+v, want nil", got) |
| + } |
| + // No control channel on this box: nothing asked, nothing published. |
| + if got := egressStatusProbe(nil, rows, map[string]string{"abc/shop": "policy expired"}); got != nil { |
| + t.Fatalf("no client = %+v, want nil", got) |
| + } |
| + // Root reports nothing at all: no table. |
| + if got := egressStatusProbe(rootReports(nil), rows, nil); got != nil { |
| + t.Fatalf("no reports = %+v, want nil", got) |
| + } |
| +} |
| + |
| +func TestEgressStatusProbeCarriesTheAgentsPolicyState(t *testing.T) { |
| + t.Parallel() |
| + rows := []registry.Route{egressStatusRow("shop-a.example.com", "abc", "shop", "")} |
| + agent := map[string]string{"abc/shop": "policy expired"} |
| + |
| + // Before claims the agent empties the column, so root asserted an |
| + // empty allow and has nothing to say: the agent's word is the state. |
| + got := egressStatusProbe(rootReports(map[string]instancectl.EgressReport{"shop-a.example.com": {}}), rows, agent) |
| + if want := (status.HostEgress{State: "expired"}); got["shop-a.example.com"].State != want.State || len(got) != 1 { |
| + t.Fatalf("root {} with policy expired = %+v, want %+v", got, want) |
| + } |
| + // Root's own state stands. |
| + got = egressStatusProbe(rootReports(map[string]instancectl.EgressReport{ |
| + "shop-a.example.com": {State: instancectl.EgressFailing, Detail: "read back: timeout; nothing written"}, |
| + }), rows, agent) |
| + if h := got["shop-a.example.com"]; h.State != "failing" || h.Detail != "read back: timeout; nothing written" { |
| + t.Fatalf("root failing with policy expired = %+v, want failing kept", h) |
| + } |
| + |
| + // Each of plan 1's words maps to its status word; unverifiable is |
| + // never a root state but is still published. |
| + for word, want := range map[string]string{ |
| + "policy unreadable": "unreadable", |
| + "policy unverifiable": "unverifiable", |
| + "policy expired": "expired", |
| + } { |
| + got := egressStatusProbe(rootReports(map[string]instancectl.EgressReport{"shop-a.example.com": {}}), rows, |
| + map[string]string{"abc/shop": word}) |
| + if got["shop-a.example.com"].State != want { |
| + t.Errorf("%q = %+v, want state %q", word, got, want) |
| + } |
| + } |
| + |
| + // A row root has not reported on yet still carries the agent's word; |
| + // a word this code does not know, another app's word, and a sidecar |
| + // member's row (which never has a policy) do not. |
| + rows = []registry.Route{ |
| + egressStatusRow("shop-b.example.com", "abc", "shop", ""), |
| + egressStatusRow("blog.example.com", "zzz", "blog", ""), |
| + egressStatusRow("odd.example.com", "bab", "odd", ""), |
| + {Host: "side.shop.abc.sidecar.internal", Kind: "sidecar", Account: "abc", App: "shop"}, |
| + } |
| + got = egressStatusProbe(rootReports(nil), rows, map[string]string{"abc/shop": "policy expired", "bab/odd": "policy mislaid"}) |
| + want := map[string]status.HostEgress{"shop-b.example.com": {State: "expired"}} |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("probe = %+v\nwant %+v", got, want) |
| + } |
| +} |
| + |
| +func TestEgressStatusProbeCarriesDetail(t *testing.T) { |
| + t.Parallel() |
| + const detail = "side.shop.abc.sidecar.internal is a sidecar member, which runs flat" |
| + rows := []registry.Route{egressStatusRow("shop-a.example.com", "abc", "shop", "10.0.5.20")} |
| + got := egressStatusProbe(rootReports(map[string]instancectl.EgressReport{ |
| + "shop-a.example.com": {State: instancectl.EgressNotNested, Detail: detail}, |
| + }), rows, nil) |
| + if h := got["shop-a.example.com"]; h.State != "not_nested" || h.Detail != detail { |
| + t.Fatalf("probe = %+v, want root's state and detail unchanged", got) |
| + } |
| +} |
| + |
| +func TestEgressStatusProbeShowsUnderClaimsOnlyWhereGranted(t *testing.T) { |
| + t.Parallel() |
| + underClaims := instancectl.EgressReport{State: instancectl.EgressUnderClaims, Detail: claimsEgressDetail} |
| + c := rootReports(map[string]instancectl.EgressReport{ |
| + "shop-a.example.com": underClaims, |
| + "shop-b.example.com": underClaims, |
| + }) |
| + |
| + rows := []registry.Route{ |
| + egressStatusRow("shop-a.example.com", "abc", "shop", "10.0.5.20"), |
| + egressStatusRow("shop-b.example.com", "zzz", "blog", ""), |
| + } |
| + got := egressStatusProbe(c, rows, nil) |
| + want := map[string]status.HostEgress{ |
| + "shop-a.example.com": {State: "under_claims", Detail: "not yet supported under claims"}, |
| + } |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("probe = %+v\nwant %+v", got, want) |
| + } |
| + |
| + // No row carries an allow: nothing new is published, and the box's |
| + // snapshot has no egress key. |
| + rows[0].EgressAllow = "" |
| + got = egressStatusProbe(c, rows, nil) |
| + if len(got) != 0 { |
| + t.Fatalf("probe = %+v, want empty", got) |
| + } |
| + box := status.CollectBox(rows, status.Probes{MachineID: "m", Release: "v1", Egress: got}, time.Now()) |
| + raw, err := json.Marshal(box) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(string(raw), `"egress"`) { |
| + t.Fatalf("snapshot carries an egress key: %s", raw) |
| + } |
| +} |
diff --git a/internal/status/contract_test.go b/internal/status/contract_test.go| index 011e17935..c8ec27e2f 100644 |
| --- a/internal/status/contract_test.go |
| +++ b/internal/status/contract_test.go |
| @@ -82,7 +82,7 @@ var allowedBoxKeys = map[string][]string{ |
| "": {"generated_at", "label", "region", "routes", "load", "capacity", "replication", "adoption_running", "config_path_running", "restart_path_running", "expired_canaries", "metrics"}, |
| "routes": {"static", "resident", "hibernating", "awake", "asleep"}, |
| "replication": {"healthy", "lag_seconds"}, |
| - "metrics": {"mem_total_bytes", "mem_avail_bytes", "load1", "disk_free_bytes", "release", "tunnel", "route_versions", "upstreams", "layout", "config_refusals", "config_refusals_total", "release_refusals", "proof_waits", "config_guard", "build_states", "build_states_err", "update_settings", "updates"}, |
| + "metrics": {"mem_total_bytes", "mem_avail_bytes", "load1", "disk_free_bytes", "release", "tunnel", "route_versions", "upstreams", "layout", "config_refusals", "config_refusals_total", "release_refusals", "proof_waits", "config_guard", "build_states", "build_states_err", "update_settings", "updates", "egress"}, |
| "metrics.route_versions": {wildcardAnyKey}, |
| "metrics.upstreams": {wildcardAnyKey}, |
| "metrics.upstreams.*[]": {"addr", "up", "since", "fails", "last_error"}, |
| @@ -111,6 +111,10 @@ var allowedBoxKeys = map[string][]string{ |
| // carries it. |
| "metrics.updates": {wildcardAnyKey}, |
| "metrics.updates.*": {"desired", "reason", "detail", "baking", "major", "pending", "completed", "completed_failed", "account", "app"}, |
| + // egress (#328) is host -> root's read-back of that host's slice allow, |
| + // in the private block only; the values are pinned to the field level. |
| + "metrics.egress": {wildcardAnyKey}, |
| + "metrics.egress.*": {"allowed", "refused", "state", "detail"}, |
| } |
| // allowedFleetKeys are THE schema for Fleet's JSON output. Same friction as |
| @@ -368,6 +372,11 @@ func fixtureProbes() status.Probes { |
| Updates: map[string]status.HostUpdates{ |
| "contract-decided.internal": {Desired: "v2", Reason: "major", Detail: "v2", Baking: "v3", Major: &contractMajor, Pending: 4, Completed: 3, CompletedFailed: true, Account: "bab", App: "km"}, |
| }, |
| + // One host's egress read-back, so metrics.egress is exercised by the |
| + // allowlist walk too. |
| + Egress: map[string]status.HostEgress{ |
| + "contract-egress.internal": {Allowed: []string{"10.0.5.20"}, Refused: []string{"10.0.0.0/8: too wide"}, State: "failing", Detail: "set-property failed"}, |
| + }, |
| ConfigGuard: "bypassed (CARLOS_NO_SEALED_CONFIG)", |
| MemFrac: &memFrac, |
| DiskFrac: &diskFrac, |
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go| index 4dd9ef44a..4881ecb38 100644 |
| --- a/internal/status/snapshot.go |
| +++ b/internal/status/snapshot.go |
| @@ -189,6 +189,21 @@ type Probes struct { |
| // host. Private Metrics only: Updates names hosts and builds. |
| UpdateSettings int |
| Updates map[string]HostUpdates |
| + // Egress is root's read-back of each instance's egress allow (#328), |
| + // with the agent's own policy state where root has none. nil or empty |
| + // means no host reported. Private Metrics only: it names hosts. |
| + Egress map[string]HostEgress |
| +} |
| + |
| +// HostEgress is one instance's egress read-back (#328, spec §4.4): the |
| +// addresses its slice holds, the entries refused and why, and a state word |
| +// with its detail when the allow is not simply in force. Everything is |
| +// omitempty: a field with nothing to say is absent. |
| +type HostEgress struct { |
| + Allowed []string `json:"allowed,omitempty"` |
| + Refused []string `json:"refused,omitempty"` |
| + State string `json:"state,omitempty"` |
| + Detail string `json:"detail,omitempty"` |
| } |
| // HostUpdates is root's last update decision for one instance, for the |
| @@ -626,6 +641,12 @@ type BoxMetrics struct { |
| // operator scanning snapshots sees only the boxes that are exposed. A |
| // fixed phrase, never a value from the environment. |
| ConfigGuard string `json:"config_guard,omitempty"` |
| + // Egress is, per instance this box hosts that has something to say, |
| + // root's read-back of its slice's egress allow (#328), or the agent's |
| + // policy state where root has none. Host-keyed and private like |
| + // RouteVersions. Omitted when empty, so a box with no egress policy |
| + // publishes exactly what it did before the field existed. |
| + Egress map[string]HostEgress `json:"egress,omitempty"` |
| } |
| // UpdateSettingsProtocol is the BoxMetrics.UpdateSettings a binary reports |
| @@ -1045,7 +1066,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| len(routeVersions) > 0 || len(routeServing) > 0 || len(aliasReadings) > 0 || len(p.Upstreams) > 0 || |
| len(routeDBBytes) > 0 || p.Layout != nil || len(p.ConfigRefusals) > 0 || len(p.ReleaseRefusals) > 0 || len(p.ProofWaits) > 0 || p.Rollout != nil || p.ConfigGuard != "" || |
| p.Alerts != nil || p.GeoIP != nil || len(p.BuildStates) > 0 || p.BuildStatesErr != "" || |
| - p.UpdateSettings != 0 || len(p.Updates) > 0 { |
| + p.UpdateSettings != 0 || len(p.Updates) > 0 || len(p.Egress) > 0 { |
| box.Metrics = &BoxMetrics{ |
| ConsoleProcesses: p.ConsoleProcesses, |
| ActivationID: p.ActivationID, ActivationComplete: p.ActivationComplete, |
| @@ -1088,6 +1109,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| BuildStatesErr: p.BuildStatesErr, |
| UpdateSettings: p.UpdateSettings, |
| Updates: p.Updates, |
| + Egress: p.Egress, |
| } |
| } |
diff --git a/internal/status/snapshot_test.go b/internal/status/snapshot_test.go| index 286e2dfea..b735044bf 100644 |
| --- a/internal/status/snapshot_test.go |
| +++ b/internal/status/snapshot_test.go |
| @@ -189,3 +189,76 @@ func TestCollectBoxCarriesTheServingBuild(t *testing.T) { |
| t.Error("a platform alias carries a serving build") |
| } |
| } |
| + |
| +// TestCollectBoxCarriesEgress pins Probes.Egress (#328): root's per-host |
| +// read-back reaches the private Metrics block under "egress", hostname |
| +// keyed, and counts on its own toward "something is known". The public |
| +// fleet feed never carries it. |
| +func TestCollectBoxCarriesEgress(t *testing.T) { |
| + at := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC) |
| + eg := map[string]HostEgress{ |
| + "shop-a.example.com": {Allowed: []string{"10.0.5.20"}, Refused: []string{"10.0.0.0/8: too wide"}}, |
| + "shop-b.example.com": {State: "under_claims", Detail: "not yet supported under claims"}, |
| + } |
| + b := CollectBox(nil, Probes{Egress: eg}, at) |
| + if b.Metrics == nil { |
| + t.Fatal("egress alone must produce a metrics block") |
| + } |
| + if got := b.Metrics.Egress["shop-a.example.com"]; len(got.Allowed) != 1 || got.Allowed[0] != "10.0.5.20" || len(got.Refused) != 1 { |
| + t.Fatalf("metrics.egress = %+v", b.Metrics.Egress) |
| + } |
| + out, err := json.Marshal(b) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, want := range []string{ |
| + `"egress":{"shop-a.example.com":{"allowed":["10.0.5.20"],"refused":["10.0.0.0/8: too wide"]}`, |
| + `"shop-b.example.com":{"state":"under_claims","detail":"not yet supported under claims"}`, |
| + } { |
| + if !strings.Contains(string(out), want) { |
| + t.Errorf("json lacks %s: %s", want, out) |
| + } |
| + } |
| + s := release.NewDirStore(t.TempDir()) |
| + if err := WriteBox(context.Background(), s, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := BuildFleet(context.Background(), s, nil, at, 5*time.Minute) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fb, _ := json.Marshal(f) |
| + if strings.Contains(string(fb), "egress") || strings.Contains(string(fb), "shop-a.example.com") { |
| + t.Fatalf("fleet.json leaked the egress read-back: %s", fb) |
| + } |
| +} |
| + |
| +// TestCollectBoxOmitsEmptyEgress: a box with no host reported (nil or an |
| +// empty map) publishes byte-identically to one built before the field |
| +// existed: no "egress" key, and no Metrics block on its account. |
| +func TestCollectBoxOmitsEmptyEgress(t *testing.T) { |
| + at := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC) |
| + routes := []registry.Route{{Host: "shop-a.example.com", Kind: "instance", Version: "v1"}} |
| + base := Probes{MachineID: "m", Release: "v1"} |
| + want, err := json.Marshal(CollectBox(routes, base, at)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, eg := range map[string]map[string]HostEgress{"nil": nil, "empty": {}} { |
| + p := base |
| + p.Egress = eg |
| + got, err := json.Marshal(CollectBox(routes, p, at)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if string(got) != string(want) { |
| + t.Errorf("%s: snapshot changed:\n got %s\nwant %s", name, got, want) |
| + } |
| + if strings.Contains(string(got), "egress") { |
| + t.Errorf("%s: snapshot carries an egress key: %s", name, got) |
| + } |
| + if b := CollectBox(nil, Probes{Egress: eg}, at); b.Metrics != nil { |
| + t.Errorf("%s: no egress and nothing else known must mean no metrics block", name) |
| + } |
| + } |
| +} |