cli: EGRESS in status --layout and instances list; apps show marks fleet addresses (#328)
The console joins each host's egress read-back (status.BoxMetrics.Egress) into the status --layout rows and the instance list (fresh boxes only, as db_bytes), with the held addresses the fleet-address report found on a box as conflicts. The policy GET names the allowed addresses in that report, matched against the allow as it stands now. The CLI shows an EGRESS column in both tables, marks those addresses "!" in apps show, and apps set --egress-allow names the boxes it could not check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+545
−25
apimode.go+4 −0apps_policy.go+16 −1apps_policy_test.go+63 −0instances_cli.go+98 −13instances_cli_test.go+84 −0internal/console/apiinstances.go+21 −2internal/console/apiinstances_test.go+63 −0internal/console/apipolicy.go+18 −1internal/console/apipolicy_test.go+28 −0internal/console/apistatuslayout.go+35 −1internal/console/apistatuslayout_test.go+68 −0status_instances.go+13 −6status_instances_test.go+34 −1
diff --git a/apimode.go b/apimode.go| index 9409fb48b..143cec3c1 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -3365,6 +3365,10 @@ type apiInstanceRecord struct { |
| Updates *apiUpdatesJoin `json:"update_report"` |
| UpdatesSetting string `json:"updates"` |
| SettingsDefault bool `json:"settings_default"` |
| + // Egress is the instance's egress read-back from its box, with the |
| + // console's conflicts (#328). nil from an older console and for a host |
| + // no fresh box reports: the EGRESS column prints a dash. |
| + Egress *apiEgress `json:"egress,omitempty"` |
| } |
| // apiUpdatesJoin mirrors the console's updatesJoinView |
diff --git a/apps_policy.go b/apps_policy.go| index b47f8037d..3fb68eb3e 100644 |
| --- a/apps_policy.go |
| +++ b/apps_policy.go |
| @@ -20,6 +20,7 @@ import ( |
| "fmt" |
| "log" |
| "net/http" |
| + "slices" |
| "sort" |
| "strings" |
| @@ -43,6 +44,7 @@ the app's boxes within seconds once they run a release that applies it.` |
| appsPolicyChanged = "the policy changed while this ran. Run it again" |
| appsSetEgressDone = "%s instances may reach %s" |
| appsSetEgressCleared = "%s instances have no egress allow" |
| + appsSetEgressNotChecked = "Not checked against these boxes, which publish no address list: %s." |
| appsSetSizeDone = "%s instances run at %s unless an instance has its own size" |
| appsSetSizeCleared = "%s instances run at the build's size unless an instance has its own size" |
| instancesSetSizeDone = "%s runs at %s" |
| @@ -84,6 +86,9 @@ type apiAppPolicy struct { |
| ETag string `json:"etag"` |
| NotChecked []string `json:"not_checked"` |
| Stale []string `json:"stale_overrides"` |
| + // EgressConflicts is the allowed addresses the console's fleet-address |
| + // report found on a fleet box (#328); absent from an older console. |
| + EgressConflicts []string `json:"egress_conflicts"` |
| } |
| // apiPolicyBody is the part of the policy object (apppolicy.Policy) the CLI |
| @@ -238,6 +243,9 @@ func appsSetPolicyRun(ctx context.Context, sess *apiSession, acct apiAcct, app s |
| } else { |
| fmt.Fprintf(stdout, appsSetEgressDone+"\n", app, strings.Join(got.Policy.EgressAllow, ", ")) |
| } |
| + if len(got.NotChecked) > 0 { |
| + fmt.Fprintf(stdout, appsSetEgressNotChecked+"\n", strings.Join(got.NotChecked, ", ")) |
| + } |
| } |
| if c.DefaultSize != nil { |
| if got.Policy.DefaultSize == "" { |
| @@ -312,7 +320,14 @@ func appsShowRun(ctx context.Context, sess *apiSession, acct apiAcct, app string |
| p := got.Policy |
| egress := appsShowNone |
| if len(p.EgressAllow) > 0 { |
| - egress = strings.Join(p.EgressAllow, ", ") |
| + shown := make([]string, len(p.EgressAllow)) |
| + for i, a := range p.EgressAllow { |
| + shown[i] = a |
| + if slices.Contains(got.EgressConflicts, a) { |
| + shown[i] = "!" + a |
| + } |
| + } |
| + egress = strings.Join(shown, ", ") |
| } |
| fmt.Fprintf(stdout, appsShowEgress+"\n", egress) |
| def := appsShowBuildSize |
diff --git a/apps_policy_test.go b/apps_policy_test.go| index 8218e3e58..bffd18b06 100644 |
| --- a/apps_policy_test.go |
| +++ b/apps_policy_test.go |
| @@ -280,6 +280,69 @@ func TestAppsShowPrintsThePolicy(t *testing.T) { |
| } |
| } |
| +// TestAppsShowMarksConflicts (#328): a configured address the console's |
| +// report found on a fleet box is marked "!". An address in the report that |
| +// the app no longer allows is not shown, and an old console's reply, with no |
| +// egress_conflicts, marks nothing. |
| +func TestAppsShowMarksConflicts(t *testing.T) { |
| + out := captureStdout(t) |
| + c := &policyConsole{getBody: `{"policy":{"v":1,"egress_allow":["10.0.5.20","fd00:5::20"]},` + |
| + `"etag":"e1","not_checked":[],"egress_conflicts":["fd00:5::20","10.0.5.30"]}`} |
| + if err := appsShowRun(context.Background(), c.session(t), apiAcct{Seg: "bab"}, "shop"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := "egress allow 10.0.5.20, !fd00:5::20\ndefault size the build's size\n"; out.String() != want { |
| + t.Fatalf("stdout = %q, want %q", out.String(), want) |
| + } |
| + |
| + out.Reset() |
| + c = &policyConsole{getBody: `{"policy":{"v":1,"egress_allow":["10.0.5.20"]},"etag":"e1","not_checked":[]}`} |
| + if err := appsShowRun(context.Background(), c.session(t), apiAcct{Seg: "bab"}, "shop"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := "egress allow 10.0.5.20\ndefault size the build's size\n"; out.String() != want { |
| + t.Fatalf("old console: stdout = %q, want %q", out.String(), want) |
| + } |
| +} |
| + |
| +// TestAppsSetPrintsNotChecked: after the allow line, the boxes the grant |
| +// check could not read are named, only when there are some. |
| +func TestAppsSetPrintsNotChecked(t *testing.T) { |
| + out := captureStdout(t) |
| + change, err := policyChangeFor(t, "--egress-allow", "10.0.5.20") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := &policyConsole{getBody: `{"policy":{"v":1},"etag":""}`, |
| + putBody: `{"policy":{"v":1,"egress_allow":["10.0.5.20"]},"etag":"e1","not_checked":["box-c"]}`} |
| + if err := appsSetRun(context.Background(), c.session(t), apiAcct{Seg: "bab"}, "shop", nil, nil, change); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := fmt.Sprintf(appsSetEgressDone+"\n", "shop", "10.0.5.20") + fmt.Sprintf(appsSetEgressNotChecked+"\n", "box-c") |
| + if out.String() != want { |
| + t.Fatalf("stdout = %q, want %q", out.String(), want) |
| + } |
| + if want := "Not checked against these boxes, which publish no address list: box-c.\n"; !strings.HasSuffix(out.String(), want) { |
| + t.Fatalf("stdout = %q, want it to end %q", out.String(), want) |
| + } |
| + |
| + for _, nc := range []string{`"not_checked":[]`, `"not_checked":["box-c","box-d"]`} { |
| + out.Reset() |
| + c = &policyConsole{getBody: `{"policy":{"v":1},"etag":""}`, |
| + putBody: `{"policy":{"v":1,"egress_allow":["10.0.5.20"]},"etag":"e1",` + nc + `}`} |
| + if err := appsSetRun(context.Background(), c.session(t), apiAcct{Seg: "bab"}, "shop", nil, nil, change); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := fmt.Sprintf(appsSetEgressDone+"\n", "shop", "10.0.5.20") |
| + if nc != `"not_checked":[]` { |
| + want += fmt.Sprintf(appsSetEgressNotChecked+"\n", "box-c, box-d") |
| + } |
| + if out.String() != want { |
| + t.Fatalf("%s: stdout = %q, want %q", nc, out.String(), want) |
| + } |
| + } |
| +} |
| + |
| func TestAppsSetWithoutPolicyFlagsSendsNoPolicyRequest(t *testing.T) { |
| captureStdout(t) |
| var d doorLog |
diff --git a/instances_cli.go b/instances_cli.go| index 1824a8012..2844c6212 100644 |
| --- a/instances_cli.go |
| +++ b/instances_cli.go |
| @@ -27,10 +27,12 @@ import ( |
| "errors" |
| "flag" |
| "fmt" |
| + "io" |
| "log" |
| "net/http" |
| "net/url" |
| "os" |
| + "slices" |
| "strings" |
| "github.com/carlosframework/platform/internal/appconfig" |
| @@ -451,8 +453,86 @@ func upstreamsCell(ups []apiUpstreamState) string { |
| return fmt.Sprintf("%d/%d", up, len(ups)) |
| } |
| +// apiEgress mirrors the console's apiEgress (internal/console/apistatuslayout.go): |
| +// one host's egress allow as root read it back from its slice, plus the held |
| +// addresses the console's fleet-address report found on a fleet box. |
| +type apiEgress struct { |
| + Allowed []string `json:"allowed,omitempty"` |
| + Conflicts []string `json:"conflicts,omitempty"` // allowed addresses a fleet box now holds |
| + Refused []string `json:"refused,omitempty"` |
| + State string `json:"state,omitempty"` |
| + Detail string `json:"detail,omitempty"` |
| +} |
| + |
| +// Copy: drafts for plan 2 Task 17's review (#328). egressStateWords maps a |
| +// box's state code (status.HostEgress.State) to the word the EGRESS cell |
| +// shows after "!"; a code missing here shows as sent. |
| +var egressStateWords = map[string]string{ |
| + "failing": "failing", |
| + "unreadable": "policy unreadable", |
| + "unverifiable": "policy unverifiable", |
| + "expired": "policy expired", |
| + "not_nested": "box not wholly nested", |
| + "under_claims": "not yet supported under claims", |
| +} |
| + |
| +const ( |
| + egressRefusedWord = "refused" |
| + egressReasonLabel = "egress: " |
| +) |
| + |
| +// egressCell is the EGRESS column (#328): the addresses the instance's slice |
| +// holds, comma-joined, each one a fleet box holds marked "!", or "-" for |
| +// none; then " !<word>" when the allow is not simply in force: the state |
| +// word, else "refused" when the box dropped an entry. nil (an old console, |
| +// or a box that reported nothing for the host) is "-". |
| +func egressCell(e *apiEgress) string { |
| + if e == nil { |
| + return "-" |
| + } |
| + cell := "-" |
| + if len(e.Allowed) > 0 { |
| + held := make([]string, len(e.Allowed)) |
| + for i, a := range e.Allowed { |
| + held[i] = a |
| + if slices.Contains(e.Conflicts, a) { |
| + held[i] = "!" + a |
| + } |
| + } |
| + cell = strings.Join(held, ",") |
| + } |
| + switch { |
| + case e.State != "": |
| + word, ok := egressStateWords[e.State] |
| + if !ok { |
| + word = e.State |
| + } |
| + cell += " !" + word |
| + case len(e.Refused) > 0: |
| + cell += " !" + egressRefusedWord |
| + } |
| + return cell |
| +} |
| + |
| +// egressReason is what status --layout's REASON cell adds for the host's |
| +// egress: "egress: " and the entries the box refused, then its detail, or "" |
| +// when there are none. |
| +func egressReason(e *apiEgress) string { |
| + if e == nil { |
| + return "" |
| + } |
| + parts := slices.Clone(e.Refused) |
| + if e.Detail != "" { |
| + parts = append(parts, e.Detail) |
| + } |
| + if len(parts) == 0 { |
| + return "" |
| + } |
| + return egressReasonLabel + strings.Join(parts, "; ") |
| +} |
| + |
| const ( |
| - instancesListHeader = "HOST\tREGION\tCHANNEL\tPOOL\tINSTALLED\tSERVING\tHEALTH\tUPSTREAMS\tDB\tCREATED\tBY\tREASON" |
| + instancesListHeader = "HOST\tREGION\tCHANNEL\tPOOL\tINSTALLED\tSERVING\tHEALTH\tUPSTREAMS\tDB\tEGRESS\tCREATED\tBY\tREASON" |
| instancesListRetryHint = "a build that failed is tried again on every box with carlos promote --app %s --retry <version> <channel>, or on one instance with carlos instances retry --app %s <host>" |
| ) |
| @@ -555,6 +635,22 @@ func anyHeld(recs []apiInstanceRecord) bool { |
| return false |
| } |
| +// printInstancesList is `carlos instances list`'s table. |
| +func printInstancesList(out io.Writer, recs []apiInstanceRecord) { |
| + w := newTable(out) |
| + fmt.Fprintln(w, instancesListHeader+"\t"+"SEED") |
| + for _, r := range recs { |
| + rowHealth := r.Health |
| + if rowHealth == "" { |
| + rowHealth = "—" // an old console: the field predates it, not "unhealthy" |
| + } |
| + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", r.Host, r.Region, r.Channel, r.Pool, |
| + installedCell(r), servingCell(r), rowHealth, upstreamsCell(r.Upstreams), humanBytes(r.DBBytes), |
| + egressCell(r.Egress), r.CreatedAt, r.CreatedBy, reasonCell(r), seedCell(r)) |
| + } |
| + w.Flush() |
| +} |
| + |
| func runInstancesList(args []string) { |
| fs := flag.NewFlagSet("instances list", flag.ExitOnError) |
| app := appFlag(fs, "app whose instance records to list") |
| @@ -572,18 +668,7 @@ func runInstancesList(args []string) { |
| if err != nil { |
| log.Fatalf("instances list: %v", err) |
| } |
| - w := newTable(stdout) |
| - fmt.Fprintln(w, instancesListHeader+"\t"+"SEED") |
| - for _, r := range recs { |
| - rowHealth := r.Health |
| - if rowHealth == "" { |
| - rowHealth = "—" // an old console: the field predates it, not "unhealthy" |
| - } |
| - fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", r.Host, r.Region, r.Channel, r.Pool, |
| - installedCell(r), servingCell(r), rowHealth, upstreamsCell(r.Upstreams), humanBytes(r.DBBytes), |
| - r.CreatedAt, r.CreatedBy, reasonCell(r), seedCell(r)) |
| - } |
| - w.Flush() |
| + printInstancesList(stdout, recs) |
| // Spec §8.4: a held build is retried everywhere by `promote --retry`, or |
| // on one instance by `instances retry`. Said once, under the table, only |
| // when something is held. |
diff --git a/instances_cli_test.go b/instances_cli_test.go| index 395408395..1de2ad2d6 100644 |
| --- a/instances_cli_test.go |
| +++ b/instances_cli_test.go |
| @@ -8,9 +8,13 @@ |
| package main |
| import ( |
| + "bytes" |
| "context" |
| + "encoding/json" |
| "net/http" |
| "net/http/httptest" |
| + "slices" |
| + "strings" |
| "testing" |
| "github.com/carlosframework/platform/internal/provision" |
| @@ -97,6 +101,86 @@ func TestUpstreamsCell(t *testing.T) { |
| } |
| } |
| +// TestEgressCellTable pins the EGRESS cell (#328): what the instance's slice |
| +// holds, a fleet box's address marked, and the state word when the allow is |
| +// not simply in force. |
| +func TestEgressCellTable(t *testing.T) { |
| + two := []string{"10.0.5.20", "fd00:5::20"} |
| + cases := []struct { |
| + name string |
| + e *apiEgress |
| + want string |
| + }{ |
| + {"nil: an old console, or nothing reported", nil, "-"}, |
| + {"none", &apiEgress{}, "-"}, |
| + {"two allowed", &apiEgress{Allowed: two}, "10.0.5.20,fd00:5::20"}, |
| + {"one conflict", &apiEgress{Allowed: two, Conflicts: []string{"fd00:5::20"}}, "10.0.5.20,!fd00:5::20"}, |
| + {"a conflict not held is not shown", &apiEgress{Allowed: []string{"10.0.5.20"}, Conflicts: []string{"10.0.5.30"}}, "10.0.5.20"}, |
| + {"failing", &apiEgress{Allowed: two, State: "failing"}, "10.0.5.20,fd00:5::20 !failing"}, |
| + {"unreadable", &apiEgress{State: "unreadable"}, "- !policy unreadable"}, |
| + {"unverifiable", &apiEgress{State: "unverifiable"}, "- !policy unverifiable"}, |
| + {"expired", &apiEgress{State: "expired"}, "- !policy expired"}, |
| + {"not nested", &apiEgress{State: "not_nested", Detail: "flat row shop-b.example.com"}, "- !box not wholly nested"}, |
| + {"under claims", &apiEgress{State: "under_claims", Detail: "not yet supported under claims"}, "- !not yet supported under claims"}, |
| + {"an unknown state shows as sent", &apiEgress{State: "later"}, "- !later"}, |
| + {"refused only", &apiEgress{Allowed: []string{"10.0.5.20"}, Refused: []string{"10.0.5.1: an address of this box"}}, "10.0.5.20 !refused"}, |
| + {"a state outranks refused", &apiEgress{Refused: []string{"x"}, State: "failing"}, "- !failing"}, |
| + } |
| + for _, c := range cases { |
| + if got := egressCell(c.e); got != c.want { |
| + t.Errorf("%s: egressCell = %q, want %q", c.name, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +// TestInstancesListShowsEgress: the list's EGRESS column sits right after DB |
| +// and before CREATED (plan 3 puts SIZE between DB and EGRESS), and an old |
| +// console's record, which has no egress key, reads "-". |
| +func TestInstancesListShowsEgress(t *testing.T) { |
| + var recs []apiInstanceRecord |
| + body := `[ |
| + {"host":"shop-a.example.com","channel":"stable","health":"running","db_bytes":2048, |
| + "egress":{"allowed":["10.0.5.20","fd00:5::20"],"conflicts":["fd00:5::20"]}}, |
| + {"host":"shop-b.example.com","channel":"stable","health":"running","egress":{"state":"expired"}}, |
| + {"host":"shop-c.example.com","channel":"stable","health":"running"} |
| + ]` |
| + if err := json.Unmarshal([]byte(body), &recs); err != nil { |
| + t.Fatal(err) |
| + } |
| + var buf bytes.Buffer |
| + printInstancesList(&buf, recs) |
| + lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") |
| + head := strings.Fields(lines[0]) |
| + db := slices.Index(head, "DB") |
| + if db < 0 || db+2 >= len(head) || head[db+1] != "EGRESS" || head[db+2] != "CREATED" { |
| + t.Fatalf("heading = %q, want EGRESS between DB and CREATED", lines[0]) |
| + } |
| + // cell is the row's text under a heading: the table pads every column |
| + // to one width, so a heading's offset is its column's on every line. |
| + cell := func(host, col, next string) string { |
| + from, to := strings.Index(lines[0], col), strings.Index(lines[0], next) |
| + for _, l := range lines[1:] { |
| + if strings.HasPrefix(l, host+" ") { |
| + return strings.TrimSpace(l[from:to]) |
| + } |
| + } |
| + t.Fatalf("no row for %s:\n%s", host, buf.String()) |
| + return "" |
| + } |
| + for _, c := range []struct{ host, db, egress string }{ |
| + {"shop-a.example.com", "2.0KB", "10.0.5.20,!fd00:5::20"}, |
| + {"shop-b.example.com", "-", "- !policy expired"}, |
| + {"shop-c.example.com", "-", "-"}, |
| + } { |
| + if got := cell(c.host, "DB", "EGRESS"); got != c.db { |
| + t.Errorf("%s DB = %q, want %q", c.host, got, c.db) |
| + } |
| + if got := cell(c.host, "EGRESS", "CREATED"); got != c.egress { |
| + t.Errorf("%s EGRESS = %q, want %q\n%s", c.host, got, c.egress, buf.String()) |
| + } |
| + } |
| +} |
| + |
| // TestParseAddrList pins the given-vs-absent split -addr/-addrs share |
| // (Task 8): a flag never named on the command line must return nil (the |
| // wire's "leave/default"), never mistaken for the empty list an explicitly |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 110867b64..c01804f0b 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -210,6 +210,12 @@ type instanceListRecord struct { |
| // CLI can tell an instance on a box that ignores settings from one that |
| // never asked for any. |
| SettingsDefault bool `json:"settings_default"` |
| + // Egress is this host's egress read-back as its box last sent it |
| + // (status.BoxMetrics.Egress, #328), joined under DBBytes' rules, with |
| + // the fleet-address report's conflicts. Absent when no fresh box |
| + // reports one, which is most hosts: a host with no allow and nothing to |
| + // say is not reported. |
| + Egress *apiEgress `json:"egress,omitempty"` |
| } |
| // instanceHealth computes each record host's health word the same way the |
| @@ -349,6 +355,7 @@ type boxJoin struct { |
| serving map[string]string |
| upstreams map[string][]status.UpstreamState |
| dbBytes map[string]int64 |
| + egress map[string]status.HostEgress |
| rollouts map[string]rolloutView |
| updates map[string]updatesJoinView |
| } |
| @@ -463,6 +470,13 @@ func (j boxJoin) dbSize(host string) *int64 { |
| return &n |
| } |
| +// egressFor is the join's egress view for host, nil when no fresh box |
| +// reported one, with conflicts (egressConflicts) marked. |
| +func (j boxJoin) egressFor(host string, conflicts map[string]string) *apiEgress { |
| + h, ok := j.egress[host] |
| + return egressView(h, ok, conflicts) |
| +} |
| + |
| // loadBoxJoin builds boxJoin from every NON-STALE box's own |
| // private Metrics block (status/boxes/*.json), through status.LoadBoxes — |
| // the same loader the operator fleet page's HostRows reads through |
| @@ -596,7 +610,7 @@ func recordFleets(recs []provision.Record) map[string]bool { |
| // has its boxes reads them once. |
| func joinBoxes(boxes []status.Box, now time.Time) boxJoin { |
| j := boxJoin{versions: map[string]string{}, serving: map[string]string{}, upstreams: map[string][]status.UpstreamState{}, |
| - dbBytes: map[string]int64{}, rollouts: map[string]rolloutView{}} |
| + dbBytes: map[string]int64{}, egress: map[string]status.HostEgress{}, rollouts: map[string]rolloutView{}} |
| for _, b := range boxes { |
| if b.Metrics == nil || status.BoxStale(b, now, status.SnapshotPeriod) { |
| continue |
| @@ -613,6 +627,9 @@ func joinBoxes(boxes []status.Box, now time.Time) boxJoin { |
| for host, n := range b.Metrics.RouteDBBytes { |
| j.dbBytes[host] = n |
| } |
| + for host, e := range b.Metrics.Egress { |
| + j.egress[host] = e |
| + } |
| j.foldRollout(b, true) |
| j.foldUpdates(b, true) |
| } |
| @@ -790,6 +807,7 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) { |
| } |
| } |
| health := s.instanceHealth(ctx, recs) |
| + conflicts := s.egressConflicts() |
| counts := map[string]int{} |
| matched := make([]instanceListRecord, 0, len(recs)) |
| for _, rec := range recs { |
| @@ -809,7 +827,8 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) { |
| ServedBy: served[rec.Host], Gated: rec.Gate != "", DBBytes: join.dbSize(rec.Host), |
| Rollout: join.rollout(rec.Host, acct.Sqid, app), |
| UpdateReport: join.update(rec.Host, acct.Sqid, app), |
| - SettingsDefault: provision.EffectiveUpdates(rec, policy).Default()}) |
| + SettingsDefault: provision.EffectiveUpdates(rec, policy).Default(), |
| + Egress: join.egressFor(rec.Host, conflicts)}) |
| } |
| total := len(matched) |
| // provision.ListRecords returns records host-sorted and nothing above |
diff --git a/internal/console/apiinstances_test.go b/internal/console/apiinstances_test.go| index 7bd168219..f10052478 100644 |
| --- a/internal/console/apiinstances_test.go |
| +++ b/internal/console/apiinstances_test.go |
| @@ -2632,6 +2632,69 @@ func TestAPIInstanceListDBBytes(t *testing.T) { |
| } |
| } |
| +// TestAPIInstancesJoinsEgress (#328): egress joins from a FRESH box's |
| +// Metrics.Egress under db_bytes' rules: absent for a host no box reports, |
| +// and dropped for a host whose only reporting box has gone stale. Conflicts |
| +// are the held addresses the fleet-address report found on a box. |
| +func TestAPIInstancesJoinsEgress(t *testing.T) { |
| + t.Parallel() |
| + fx, token := instanceFixture(t, "code-inst-egress") |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + enableInstances(t, fx, "shop", provision.Manifest{Schema: 1, App: "shop", Domain: "example.com", |
| + Channel: "stable", Regions: []string{"ie"}, Seed: []string{"seed"}}) |
| + u := instancesURL(fx, "bab", "shop") |
| + for _, h := range []string{"shop-a.example.com", "shop-b.example.com", "shop-c.example.com"} { |
| + if code, _, out := rawReq(t, http.MethodPost, u, token, |
| + fmt.Sprintf(`{"host":%q,"region":"ie"}`, h)); code != http.StatusCreated { |
| + t.Fatalf("create %s = %d %s", h, code, out) |
| + } |
| + } |
| + fresh := status.CollectBox(nil, status.Probes{MachineID: "box1"}, time.Now()) |
| + fresh.Metrics = &status.BoxMetrics{Egress: map[string]status.HostEgress{ |
| + "shop-a.example.com": {Allowed: []string{"10.0.5.20", "fd00:5::20"}, State: "failing"}, |
| + }} |
| + if err := status.WriteBox(context.Background(), fx.rel, fresh); err != nil { |
| + t.Fatal(err) |
| + } |
| + stale := status.CollectBox(nil, status.Probes{MachineID: "box2"}, time.Now().Add(-time.Hour)) |
| + stale.Metrics = &status.BoxMetrics{Egress: map[string]status.HostEgress{ |
| + "shop-c.example.com": {Allowed: []string{"10.0.5.20"}}, |
| + }} |
| + if err := status.WriteBox(context.Background(), fx.rel, stale); err != nil { |
| + t.Fatal(err) |
| + } |
| + setEgressConflicts(fx.srv, map[string]string{"10.0.5.20": "box-b"}) |
| + |
| + code, _, out := rawReq(t, http.MethodGet, u, token, "") |
| + if code != http.StatusOK { |
| + t.Fatalf("list = %d %s", code, out) |
| + } |
| + var list struct { |
| + Instances []struct { |
| + Host string `json:"host"` |
| + Egress json.RawMessage `json:"egress"` |
| + } `json:"instances"` |
| + } |
| + if err := json.Unmarshal([]byte(out), &list); err != nil { |
| + t.Fatalf("list body %s: %v", out, err) |
| + } |
| + want := map[string]string{ |
| + "shop-a.example.com": `{"allowed":["10.0.5.20","fd00:5::20"],"conflicts":["10.0.5.20"],"state":"failing"}`, |
| + "shop-b.example.com": ``, |
| + "shop-c.example.com": ``, |
| + } |
| + if len(list.Instances) != len(want) { |
| + t.Fatalf("instances = %s", out) |
| + } |
| + for _, r := range list.Instances { |
| + if string(r.Egress) != want[r.Host] { |
| + t.Errorf("%s egress = %s, want %s", r.Host, r.Egress, want[r.Host]) |
| + } |
| + } |
| +} |
| + |
| // TestAPIInstanceCreateReplicaFields pins the create door's replica rails |
| // (#162): role and placement travel together or not at all; a valid replica |
| // create lands role on the record, in the bucket, canonicalized; the home's |
diff --git a/internal/console/apipolicy.go b/internal/console/apipolicy.go| index 43033fa27..3a806fb4c 100644 |
| --- a/internal/console/apipolicy.go |
| +++ b/internal/console/apipolicy.go |
| @@ -99,6 +99,9 @@ type policyReply struct { |
| ETag string `json:"etag"` |
| NotChecked []string `json:"not_checked"` |
| Stale []string `json:"stale_overrides,omitempty"` |
| + // EgressConflicts (GET only) is the policy's allowed addresses that the |
| + // fleet-address report last found on a fleet box (#328). |
| + EgressConflicts []string `json:"egress_conflicts,omitempty"` |
| } |
| // policyLock is the app's policy mutex, the store's (Store.AppPolicyLock), so |
| @@ -421,7 +424,21 @@ func (s *Server) handleAPIPolicyGet(w http.ResponseWriter, r *http.Request) { |
| } |
| w.Header().Set("ETag", etag) |
| writeJSON(w, http.StatusOK, policyReply{Policy: base, ETag: etag, NotChecked: []string{}, |
| - Stale: s.staleOverrides(ctx, acct, app, base)}) |
| + Stale: s.staleOverrides(ctx, acct, app, base), EgressConflicts: policyEgressConflicts(base, s.egressConflicts())}) |
| +} |
| + |
| +// policyEgressConflicts is p's allowed addresses that are in the report's |
| +// conflicts, in p's order. The report is keyed by address alone and keeps |
| +// an address until its next pass, so it is matched against the allow as it |
| +// stands now: an address since revoked is not named. |
| +func policyEgressConflicts(p apppolicy.Policy, conflicts map[string]string) []string { |
| + var out []string |
| + for _, a := range p.EgressAllow { |
| + if _, ok := conflicts[a]; ok { |
| + out = append(out, a) |
| + } |
| + } |
| + return out |
| } |
| // policyPrecondition is the write's compare-and-swap target: If-Match's |
diff --git a/internal/console/apipolicy_test.go b/internal/console/apipolicy_test.go| index 43301b145..10f642768 100644 |
| --- a/internal/console/apipolicy_test.go |
| +++ b/internal/console/apipolicy_test.go |
| @@ -320,6 +320,34 @@ func TestPolicyPutSetsAuditsAndBumps(t *testing.T) { |
| } |
| } |
| +// TestPolicyGetCarriesEgressConflicts (#328): the GET names the configured |
| +// addresses the fleet-address report found on a box, matched against the |
| +// app's allow as it stands now. The report is keyed by address alone and |
| +// keeps a revoked address until its next pass; that address is not named. |
| +// With no finding the key is absent. |
| +func TestPolicyGetCarriesEgressConflicts(t *testing.T) { |
| + t.Parallel() |
| + fx := newPolicyFx(t, "code-policy-conflicts") |
| + first := fx.mustPut(t, "shop", `{"egress_allow":["10.0.5.20","10.0.5.21","fd00:5::20"]}`, policyCreate) |
| + if _, _, out := policyReq(t, fx.consoleFixture, http.MethodGet, "shop", fx.owner, "", nil); strings.Contains(out, "egress_conflicts") { |
| + t.Fatalf("no finding, yet GET = %s", out) |
| + } |
| + setEgressConflicts(fx.srv, map[string]string{"10.0.5.20": "box-a", "fd00:5::20": "box-b", "10.0.5.99": "box-c"}) |
| + if got := fx.get(t, "shop").EgressConflicts; !slices.Equal(got, []string{"10.0.5.20", "fd00:5::20"}) { |
| + t.Fatalf("egress_conflicts = %v, want 10.0.5.20 and fd00:5::20", got) |
| + } |
| + // A partial revoke: fd00:5::20 is still in the report until its next |
| + // pass, but no longer allowed. |
| + fx.mustPut(t, "shop", `{"egress_allow":["10.0.5.20","10.0.5.21"]}`, policyIfMatch(first.ETag)) |
| + if got := fx.get(t, "shop").EgressConflicts; !slices.Equal(got, []string{"10.0.5.20"}) { |
| + t.Fatalf("after the revoke egress_conflicts = %v, want 10.0.5.20 alone", got) |
| + } |
| + // Another app's GET names only its own allowed addresses. |
| + if got := fx.get(t, "shop-b").EgressConflicts; got != nil { |
| + t.Fatalf("shop-b egress_conflicts = %v, want none", got) |
| + } |
| +} |
| + |
| func TestPolicyPutIsCompareAndSwap(t *testing.T) { |
| t.Parallel() |
| fx := newPolicyFx(t, "code-policy-cas") |
diff --git a/internal/console/apistatuslayout.go b/internal/console/apistatuslayout.go| index 9471f25e4..89f06fe92 100644 |
| --- a/internal/console/apistatuslayout.go |
| +++ b/internal/console/apistatuslayout.go |
| @@ -29,6 +29,37 @@ type apiStatusLayoutRow struct { |
| // Note is the pass's last non-refusal event for the host (what a move |
| // quarantined or kept aside). Additive; an old CLI ignores it. |
| Note string `json:"note,omitempty"` |
| + // Egress is the host's egress read-back as its box last sent it |
| + // (status.BoxMetrics.Egress, #328), nil when the box reports none. |
| + // Additive; an old CLI ignores it. |
| + Egress *apiEgress `json:"egress,omitempty"` |
| +} |
| + |
| +// apiEgress is one host's egress allow as root read it back from its slice |
| +// (status.HostEgress), plus Conflicts: the held addresses the fleet-address |
| +// report (egressReportPass) last found on a fleet box. |
| +type apiEgress struct { |
| + Allowed []string `json:"allowed,omitempty"` |
| + Conflicts []string `json:"conflicts,omitempty"` // allowed addresses a fleet box now holds |
| + Refused []string `json:"refused,omitempty"` |
| + State string `json:"state,omitempty"` |
| + Detail string `json:"detail,omitempty"` |
| +} |
| + |
| +// egressView is h on the wire, nil when the box reported nothing for the |
| +// host. conflicts is egressConflicts' map, keyed by address: an address the |
| +// slice holds is a conflict whichever app's allow put it on the report. |
| +func egressView(h status.HostEgress, ok bool, conflicts map[string]string) *apiEgress { |
| + if !ok { |
| + return nil |
| + } |
| + e := &apiEgress{Allowed: h.Allowed, Refused: h.Refused, State: h.State, Detail: h.Detail} |
| + for _, a := range h.Allowed { |
| + if _, hit := conflicts[a]; hit { |
| + e.Conflicts = append(e.Conflicts, a) |
| + } |
| + } |
| + return e |
| } |
| // apiStatusLayoutBox is one box's layout report: the mode it last converged |
| @@ -101,6 +132,7 @@ func (s *Server) handleAPIStatusLayout(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| now := time.Now() |
| + conflicts := s.egressConflicts() |
| out := make([]apiStatusLayoutBox, 0, len(boxes)) |
| for _, b := range boxes { |
| if b.Metrics == nil || b.Metrics.Layout == nil { |
| @@ -110,7 +142,9 @@ func (s *Server) handleAPIStatusLayout(w http.ResponseWriter, r *http.Request) { |
| } |
| rows := make([]apiStatusLayoutRow, 0, len(b.Metrics.Layout.Rows)) |
| for host, rl := range b.Metrics.Layout.Rows { |
| - rows = append(rows, apiStatusLayoutRow{Host: host, Layout: rl.Layout, Reason: rl.Reason, Note: rl.Note}) |
| + eg, ok := b.Metrics.Egress[host] |
| + rows = append(rows, apiStatusLayoutRow{Host: host, Layout: rl.Layout, Reason: rl.Reason, Note: rl.Note, |
| + Egress: egressView(eg, ok, conflicts)}) |
| } |
| sort.Slice(rows, func(i, j int) bool { return rows[i].Host < rows[j].Host }) |
| out = append(out, apiStatusLayoutBox{ |
diff --git a/internal/console/apistatuslayout_test.go b/internal/console/apistatuslayout_test.go| index c0f81efb9..9a65ab6c3 100644 |
| --- a/internal/console/apistatuslayout_test.go |
| +++ b/internal/console/apistatuslayout_test.go |
| @@ -208,3 +208,71 @@ func TestLayoutMixedNeedsANestedAndAFlatRow(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// setEgressConflicts stands in for a fleet-address report pass's findings |
| +// (egressReportPass): address -> the box that holds it. |
| +func setEgressConflicts(s *Server, m map[string]string) { |
| + s.egressReport.mu.Lock() |
| + defer s.egressReport.mu.Unlock() |
| + s.egressReport.conflicts = m |
| +} |
| + |
| +// TestAPIStatusLayoutCarriesEgressAndConflicts (#328): each row carries its |
| +// box's egress read-back for the host as the box sent it, plus Conflicts, |
| +// the held addresses the fleet-address report found on a box. A host with no |
| +// read-back has no egress key. |
| +func TestAPIStatusLayoutCarriesEgressAndConflicts(t *testing.T) { |
| + t.Parallel() |
| + fx := newConsoleFixture(t) |
| + token := cliToken(t, fx, "paul@keymail.dev", "code-apistatuslayoutegress") |
| + if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + b := status.CollectBox(nil, status.Probes{Release: "v1", |
| + Layout: &status.LayoutReport{Mode: "nested", Rows: map[string]status.RowLayout{ |
| + "shop-a.example.com": {Layout: "nested"}, |
| + "shop-b.example.com": {Layout: "nested"}, |
| + "shop-c.example.com": {Layout: "nested"}, |
| + }}, |
| + Egress: map[string]status.HostEgress{ |
| + "shop-a.example.com": {Allowed: []string{"10.0.5.20", "fd00:5::20"}}, |
| + "shop-b.example.com": {Allowed: []string{"10.0.5.21"}, Refused: []string{"10.0.5.1: an address of this box"}, |
| + State: "failing", Detail: "restarted to close 10.0.5.22"}, |
| + }, |
| + }, time.Now()) |
| + b.Label = "box-a" |
| + if err := status.WriteBox(context.Background(), fx.rel, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + setEgressConflicts(fx.srv, map[string]string{"fd00:5::20": "box-b", "10.0.5.99": "box-c"}) |
| + |
| + code, body := getBearer(t, fx.ts.URL+"/api/cli/status/layout", token) |
| + if code != http.StatusOK { |
| + t.Fatalf("GET /api/cli/status/layout = %d %q", code, body) |
| + } |
| + var out struct { |
| + Boxes []struct { |
| + Box string `json:"box"` |
| + Rows []struct { |
| + Host string `json:"host"` |
| + Egress json.RawMessage `json:"egress"` |
| + } `json:"rows"` |
| + } `json:"boxes"` |
| + } |
| + if err := json.Unmarshal(body, &out); err != nil { |
| + t.Fatalf("unreadable: %v: %s", err, body) |
| + } |
| + if len(out.Boxes) != 1 || len(out.Boxes[0].Rows) != 3 { |
| + t.Fatalf("boxes = %s", body) |
| + } |
| + want := map[string]string{ |
| + "shop-a.example.com": `{"allowed":["10.0.5.20","fd00:5::20"],"conflicts":["fd00:5::20"]}`, |
| + "shop-b.example.com": `{"allowed":["10.0.5.21"],"refused":["10.0.5.1: an address of this box"],"state":"failing","detail":"restarted to close 10.0.5.22"}`, |
| + "shop-c.example.com": ``, |
| + } |
| + for _, r := range out.Boxes[0].Rows { |
| + if string(r.Egress) != want[r.Host] { |
| + t.Errorf("%s egress = %s, want %s", r.Host, r.Egress, want[r.Host]) |
| + } |
| + } |
| +} |
diff --git a/status_instances.go b/status_instances.go| index 2eb8b11bc..bc0aa0879 100644 |
| --- a/status_instances.go |
| +++ b/status_instances.go |
| @@ -144,6 +144,9 @@ type statusLayoutRow struct { |
| Layout string `json:"layout"` |
| Reason string `json:"reason"` |
| Note string `json:"note"` |
| + // Egress is the host's egress read-back (#328); nil from an older |
| + // console or when the box reports none. |
| + Egress *apiEgress `json:"egress"` |
| } |
| // statusLayoutBox is one box's layout report. |
| @@ -210,7 +213,7 @@ func statusLayout(w io.Writer, consoleFlag string) error { |
| // column widths would drift the heading away from what was reviewed the |
| // moment any cell is wider than its header word. |
| func printStatusLayout(w io.Writer, boxes []statusLayoutBox) { |
| - type line struct{ box, host, layout, reason string } |
| + type line struct{ box, host, layout, egress, reason string } |
| var lines []line |
| for _, b := range boxes { |
| name := b.Box |
| @@ -227,13 +230,16 @@ func printStatusLayout(w io.Writer, boxes []statusLayoutBox) { |
| // A note is an event, not a refusal; it shares the column so |
| // the heading stays the approved one. |
| reason := r.Reason |
| - if r.Note != "" { |
| + for _, more := range []string{r.Note, egressReason(r.Egress)} { |
| + if more == "" { |
| + continue |
| + } |
| if reason != "" { |
| reason += "; " |
| } |
| - reason += r.Note |
| + reason += more |
| } |
| - lines = append(lines, line{name, r.Host, r.Layout, reason}) |
| + lines = append(lines, line{name, r.Host, r.Layout, egressCell(r.Egress), reason}) |
| } |
| } |
| if len(lines) == 0 { |
| @@ -246,9 +252,10 @@ func printStatusLayout(w io.Writer, boxes []statusLayoutBox) { |
| } |
| return lines[i].host < lines[j].host |
| }) |
| - fmt.Fprintln(w, "BOX HOST LAYOUT REASON") |
| + // Plan 3's SIZE goes right before EGRESS. |
| + fmt.Fprintln(w, "BOX HOST LAYOUT EGRESS REASON") |
| for _, l := range lines { |
| - fmt.Fprintf(w, "%s %s %s %s\n", l.box, l.host, l.layout, dashIfEmpty(l.reason)) |
| + fmt.Fprintf(w, "%s %s %s %s %s\n", l.box, l.host, l.layout, l.egress, dashIfEmpty(l.reason)) |
| } |
| // A box with flat, foreign or external rows beside nested ones, or |
| // under a nested intent, is the loud case: each of those still shares |
diff --git a/status_instances_test.go b/status_instances_test.go| index b8d9d09ad..d66969b4e 100644 |
| --- a/status_instances_test.go |
| +++ b/status_instances_test.go |
| @@ -3,6 +3,7 @@ package main |
| import ( |
| "bytes" |
| "context" |
| + "encoding/json" |
| "fmt" |
| "net/http" |
| "net/http/httptest" |
| @@ -64,7 +65,7 @@ func TestPrintStatusLayoutRendersSortedAndMarksStale(t *testing.T) { |
| printStatusLayout(&buf, boxes) |
| out := buf.String() |
| - if !strings.Contains(out, "BOX HOST LAYOUT REASON") { |
| + if !strings.Contains(out, "BOX HOST LAYOUT EGRESS REASON") { |
| t.Fatalf("missing the approved heading:\n%s", out) |
| } |
| if !strings.Contains(out, "alpha (stale)") { |
| @@ -154,6 +155,38 @@ func TestStatusLayoutListDecodesBoxes(t *testing.T) { |
| } |
| } |
| +// TestStatusLayoutShowsEgress (#328): the EGRESS column sits between LAYOUT |
| +// and REASON (plan 3 puts SIZE right before it), shows what each slice |
| +// holds with a fleet box's address marked, and the REASON cell carries the |
| +// refusal or detail after the layout's own reason. An old console's row, |
| +// which has no egress key, reads "-". |
| +func TestStatusLayoutShowsEgress(t *testing.T) { |
| + var boxes []statusLayoutBox |
| + body := `[{"box":"ie-1","mode":"nested","rows":[ |
| + {"host":"shop-a.example.com","layout":"nested","egress":{"allowed":["10.0.5.20","fd00:5::20"],"conflicts":["10.0.5.20"]}}, |
| + {"host":"shop-b.example.com","layout":"foreign","reason":"db and socket are neither default", |
| + "egress":{"allowed":["10.0.5.20"],"refused":["10.0.5.1: an address of this box"]}}, |
| + {"host":"shop-c.example.com","layout":"nested","egress":{"state":"not_nested","detail":"flat row shop-d.example.com"}}, |
| + {"host":"shop-d.example.com","layout":"flat"}]}]` |
| + if err := json.Unmarshal([]byte(body), &boxes); err != nil { |
| + t.Fatal(err) |
| + } |
| + var buf bytes.Buffer |
| + printStatusLayout(&buf, boxes) |
| + out := buf.String() |
| + for _, want := range []string{ |
| + "BOX HOST LAYOUT EGRESS REASON\n", |
| + "ie-1 shop-a.example.com nested !10.0.5.20,fd00:5::20 " + dashIfEmpty("") + "\n", |
| + "ie-1 shop-b.example.com foreign 10.0.5.20 !refused db and socket are neither default; egress: 10.0.5.1: an address of this box\n", |
| + "ie-1 shop-c.example.com nested - !box not wholly nested egress: flat row shop-d.example.com\n", |
| + "ie-1 shop-d.example.com flat - " + dashIfEmpty("") + "\n", |
| + } { |
| + if !strings.Contains(out, want) { |
| + t.Errorf("missing %q in:\n%s", want, out) |
| + } |
| + } |
| +} |
| + |
| // Boxes that disagree about their mode get one warning naming both |
| // sides; a stale box is left out of it, and agreement gets none. |
| func TestPrintStatusLayoutWarnsWhenBoxesDisagreeAboutTheMode(t *testing.T) { |