From 080f0401804c7c639dc9f68d088c4a0742c4e022 Mon Sep 17 00:00:00 2001 From: pvishwa3 Date: Sun, 20 Sep 2026 11:14:42 -0400 Subject: [PATCH 1/7] =?UTF-8?q?mcp:=20`rtz=20mcp`=20=E2=80=94=20stdio=20br?= =?UTF-8?q?idge=20to=20the=20hosted=20Runtimez=20MCP=20endpoint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Forwards newline-delimited JSON-RPC from stdin to POST /eac/mcp with the CLI's credential (bearer + the same JWT refresh path as Do), writes the answers to stdout, acknowledges notifications silently (202), echoes the negotiated MCP-Protocol-Version after initialize, injects the context/--cluster as the default `cluster` argument of tools/call when the client passed none, and turns 401/403 into a JSON-RPC error that names `rtz login`. No tool logic lives here — the catalog is the server's. Co-Authored-By: Claude Fable 5.1 --- README.md | 18 ++++ internal/api/client.go | 55 ++++++++++ internal/cli/mcp.go | 215 +++++++++++++++++++++++++++++++++++++++ internal/cli/mcp_test.go | 201 ++++++++++++++++++++++++++++++++++++ internal/cli/root.go | 1 + 5 files changed, 490 insertions(+) create mode 100644 internal/cli/mcp.go create mode 100644 internal/cli/mcp_test.go diff --git a/README.md b/README.md index 61f16b7..09ac11a 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,24 @@ computed from missing evidence is the most dangerous output this tool could prod - `rca explain` states whether the answer came from a model, a cache replay, or a deterministic gate — the prose alone does not reveal which. +## MCP server (Claude Code and other agents) + +`rtz mcp` serves the Runtimez MCP server over stdio, so an MCP client can ask Runtimez +instead of guessing: what is running, what changed, ranked risk findings, the upgrade +readiness ledger with the vendor's verbatim rule text, and a pre-merge manifest check. It +is a bridge — every message is forwarded to the hosted endpoint (`POST /eac/mcp`) with this +CLI's credential, so the tool catalog is exactly the server's and every tool is read-only. + +```bash +claude mcp add runtimez -- rtz mcp # uses the current context +claude mcp add runtimez -- rtz mcp --context prod --cluster prod-eu +``` + +Remote clients (Claude Code `--transport http`, Cursor, claude.ai connectors) can skip the +CLI and point at `https:///eac/mcp` with `Authorization: Bearer rk_...` (an API key +with the `api:read` scope). A `--cluster` (or the context's cluster) is injected as the +default `cluster` argument when the client did not pass one. + ## Everyday commands ```bash diff --git a/internal/api/client.go b/internal/api/client.go index 76c65e4..8e3331c 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -255,3 +255,58 @@ func Post[T any](ctx context.Context, c *Client, path string, query url.Values, } return out, nil } + +// RawResponse is one un-decoded HTTP exchange — for protocols that are not the ApiResponse +// envelope, such as the MCP JSON-RPC endpoint the `rtz mcp` bridge forwards to. +type RawResponse struct { + Status int + ContentType string + Body []byte +} + +// PostRaw sends a JSON body and returns the response as-is (no envelope unwrapping, no +// retries — the caller owns the protocol). The credential handling is the same as Do: bearer +// header, pre-emptive refresh, and one refresh-and-retry on a 401 for a JWT credential. +// headers are added verbatim on top of the defaults. +func (c *Client) PostRaw(ctx context.Context, path string, headers map[string]string, body []byte) (*RawResponse, error) { + if c.Creds != nil && c.Creds.NeedsRefresh() { + _ = c.refresh(ctx) + } + resp, err := c.postRawOnce(ctx, path, headers, body) + if err == nil && resp.Status == http.StatusUnauthorized && c.Creds != nil && c.Creds.Kind == auth.KindJWT { + if rerr := c.refresh(ctx); rerr == nil { + return c.postRawOnce(ctx, path, headers, body) + } + } + return resp, err +} + +func (c *Client) postRawOnce(ctx context.Context, path string, headers map[string]string, body []byte) (*RawResponse, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.URL(path, nil), bytes.NewReader(body)) + if err != nil { + return nil, fmt.Errorf("build request: %w", err) + } + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "rtz/"+version.Version) + if c.Creds != nil { + if bearer := c.Creds.Bearer(); bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + } + for k, v := range headers { + if v != "" { + req.Header.Set(k, v) + } + } + resp, err := c.HTTP.Do(req) + if err != nil { + return nil, fmt.Errorf("POST %s: %w", path, err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20)) + if err != nil { + return nil, fmt.Errorf("POST %s: read response: %w", path, err) + } + return &RawResponse{Status: resp.StatusCode, ContentType: resp.Header.Get("Content-Type"), Body: raw}, nil +} diff --git a/internal/cli/mcp.go b/internal/cli/mcp.go new file mode 100644 index 0000000..368bc88 --- /dev/null +++ b/internal/cli/mcp.go @@ -0,0 +1,215 @@ +package cli + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/spf13/cobra" +) + +// mcpPath is the hosted MCP endpoint on eac (Streamable HTTP, stateless JSON responses). +const mcpPath = "/eac/mcp" + +// mcpProtocolHeader is echoed back once the server has negotiated a version at initialize. +const mcpProtocolHeader = "MCP-Protocol-Version" + +// JSON-RPC error codes the bridge itself emits (server errors are forwarded untouched). +const ( + mcpErrUnauthorized = -32001 + mcpErrTransport = -32603 +) + +// mcpMaxLine bounds one JSON-RPC message on stdin; a manifest for +// runtimez_readiness_evaluate_manifest is the largest legitimate payload (256 KB server-side). +const mcpMaxLine = 4 << 20 + +func newMcpCmd() *cobra.Command { + return &cobra.Command{ + Use: "mcp", + Short: "Serve the Runtimez MCP server over stdio (Claude Code, Cursor, any MCP client)", + Long: `Bridge stdio JSON-RPC to the hosted Runtimez MCP endpoint using this CLI's credential. + +There is no tool logic here: every message is forwarded to POST ` + mcpPath + ` on the +configured API and the answer is written back, so the catalog is exactly the hosted +server's. A --cluster (or the selected context's cluster) is injected as the default +"cluster" argument of tools/call when the client did not pass one. + + claude mcp add runtimez -- rtz mcp + claude mcp add runtimez -- rtz mcp --context prod --cluster prod-eu`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + e, err := loadEnv(cmd, true) + if err != nil { + return err + } + b := &mcpBridge{ + post: func(ctx context.Context, headers map[string]string, body []byte) (int, []byte, error) { + resp, err := e.client.PostRaw(ctx, mcpPath, headers, body) + if err != nil { + return 0, nil, err + } + return resp.Status, resp.Body, nil + }, + defaultCluster: e.cluster, + out: cmd.OutOrStdout(), + errOut: cmd.ErrOrStderr(), + } + return b.serve(cmd.Context(), cmd.InOrStdin()) + }, + } +} + +// mcpBridge forwards newline-delimited JSON-RPC messages to the hosted endpoint. +type mcpBridge struct { + post func(ctx context.Context, headers map[string]string, body []byte) (int, []byte, error) + defaultCluster string + out io.Writer + errOut io.Writer + protocolVersion string +} + +func (b *mcpBridge) serve(ctx context.Context, in io.Reader) error { + sc := bufio.NewScanner(in) + sc.Buffer(make([]byte, 0, 64<<10), mcpMaxLine) + for sc.Scan() { + line := bytes.TrimSpace(sc.Bytes()) + if len(line) == 0 { + continue + } + if err := b.handle(ctx, line); err != nil { + return err + } + } + if err := sc.Err(); err != nil { + return fmt.Errorf("read stdin: %w", err) + } + return nil +} + +// handle forwards one message. It returns an error only for a broken stdout; every protocol +// or transport failure is answered on stdout as a JSON-RPC error so the client can recover. +func (b *mcpBridge) handle(ctx context.Context, line []byte) error { + var msg map[string]json.RawMessage + if err := json.Unmarshal(line, &msg); err != nil { + return b.write(jsonRPCError(nil, -32700, "invalid JSON on stdin", nil)) + } + id, hasID := msg["id"] + method := strings.Trim(string(msg["method"]), `"`) + + if b.defaultCluster != "" && method == "tools/call" { + if patched, ok := injectCluster(line, b.defaultCluster); ok { + line = patched + } + } + + headers := map[string]string{mcpProtocolHeader: b.protocolVersion} + status, body, err := b.post(ctx, headers, line) + if err != nil { + fmt.Fprintf(b.errOut, "rtz mcp: %v\n", err) + if !hasID { + return nil + } + return b.write(jsonRPCError(id, mcpErrTransport, "runtimez API unreachable: "+err.Error(), nil)) + } + + switch { + case status == http.StatusAccepted, status == http.StatusNoContent: + return nil // notification or client response acknowledged; nothing to relay + case status == http.StatusUnauthorized, status == http.StatusForbidden: + fmt.Fprintf(b.errOut, "rtz mcp: HTTP %d from %s — run `rtz login` or set RTZ_TOKEN to an api:read key\n", status, mcpPath) + if !hasID { + return nil + } + return b.write(jsonRPCError(id, mcpErrUnauthorized, + "not authorized: run `rtz login` or set RTZ_TOKEN to an API key with the api:read scope", nil)) + case status >= 200 && status < 300: + if method == "initialize" { + b.protocolVersion = negotiatedVersion(body) + } + return b.write(body) + default: + if json.Valid(body) && bytes.Contains(body, []byte(`"jsonrpc"`)) { + return b.write(body) // the server already answered in JSON-RPC (400s do) + } + if !hasID { + return nil + } + return b.write(jsonRPCError(id, mcpErrTransport, fmt.Sprintf("runtimez API returned HTTP %d", status), + map[string]any{"status": status})) + } +} + +func (b *mcpBridge) write(body []byte) error { + body = bytes.TrimRight(body, "\r\n") + if len(body) == 0 { + return nil + } + if _, err := b.out.Write(append(body, '\n')); err != nil { + return fmt.Errorf("write stdout: %w", err) + } + return nil +} + +// injectCluster adds params.arguments.cluster when the call has an arguments object without +// one. Anything malformed is left for the server to reject. +func injectCluster(line []byte, cluster string) ([]byte, bool) { + var msg map[string]any + if err := json.Unmarshal(line, &msg); err != nil { + return nil, false + } + params, ok := msg["params"].(map[string]any) + if !ok { + return nil, false + } + args, ok := params["arguments"].(map[string]any) + if !ok { + if _, present := params["arguments"]; present { + return nil, false + } + args = map[string]any{} + } + if v, present := args["cluster"]; present && v != nil && v != "" { + return nil, false + } + args["cluster"] = cluster + params["arguments"] = args + msg["params"] = params + out, err := json.Marshal(msg) + if err != nil { + return nil, false + } + return out, true +} + +func negotiatedVersion(body []byte) string { + var resp struct { + Result struct { + ProtocolVersion string `json:"protocolVersion"` + } `json:"result"` + } + if err := json.Unmarshal(body, &resp); err != nil { + return "" + } + return resp.Result.ProtocolVersion +} + +func jsonRPCError(id json.RawMessage, code int, message string, data any) []byte { + errObj := map[string]any{"code": code, "message": message} + if data != nil { + errObj["data"] = data + } + msg := map[string]any{"jsonrpc": "2.0", "error": errObj} + if len(id) > 0 { + msg["id"] = id + } else { + msg["id"] = nil + } + out, _ := json.Marshal(msg) + return out +} diff --git a/internal/cli/mcp_test.go b/internal/cli/mcp_test.go new file mode 100644 index 0000000..a319c1c --- /dev/null +++ b/internal/cli/mcp_test.go @@ -0,0 +1,201 @@ +package cli + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +// mcpBackend stands in for eac's /eac/mcp: it records what the bridge sent and answers per +// method the way the real endpoint does (JSON for requests, 202 for notifications). +type mcpBackend struct { + mu sync.Mutex + requests []recordedMcpRequest + token string +} + +type recordedMcpRequest struct { + protocolHeader string + auth string + body map[string]any +} + +func (m *mcpBackend) handler(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != mcpPath || r.Method != http.MethodPost { + w.WriteHeader(http.StatusNotFound) + return + } + raw, _ := io.ReadAll(r.Body) + var body map[string]any + _ = json.Unmarshal(raw, &body) + m.mu.Lock() + m.requests = append(m.requests, recordedMcpRequest{ + protocolHeader: r.Header.Get(mcpProtocolHeader), auth: r.Header.Get("Authorization"), body: body}) + m.mu.Unlock() + + if r.Header.Get("Authorization") != "Bearer "+m.token { + w.WriteHeader(http.StatusUnauthorized) + return + } + id, hasID := body["id"] + if !hasID { + w.WriteHeader(http.StatusAccepted) + return + } + w.Header().Set("Content-Type", "application/json") + var result any + switch body["method"] { + case "initialize": + result = map[string]any{"protocolVersion": "2025-06-18", "serverInfo": map[string]any{"name": "runtimez"}} + case "tools/list": + result = map[string]any{"tools": []map[string]any{{"name": "runtimez_whoami"}}} + case "tools/call": + params, _ := body["params"].(map[string]any) + result = map[string]any{"echo": params["arguments"], "isError": false} + default: + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": id, + "error": map[string]any{"code": -32601, "message": "method not found"}}) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": id, "result": result}) +} + +func runMcp(t *testing.T, stdin string) (string, int) { + t.Helper() + var out bytes.Buffer + root := newRootCmd() + root.SetOut(&out) + root.SetErr(io.Discard) + root.SetIn(strings.NewReader(stdin)) + root.SetArgs([]string{"mcp"}) + code := ExitOK + if err := root.Execute(); err != nil { + code = codeFor(err) + out.WriteString("error: " + err.Error() + "\n") + } + return out.String(), code +} + +func lines(s string) []map[string]any { + var out []map[string]any + for _, l := range strings.Split(strings.TrimSpace(s), "\n") { + if l == "" { + continue + } + var m map[string]any + if err := json.Unmarshal([]byte(l), &m); err != nil { + panic("non-JSON line on stdout: " + l) + } + out = append(out, m) + } + return out +} + +func TestMcpBridgeForwardsRequestsAcknowledgesNotificationsAndInjectsCluster(t *testing.T) { + be := &mcpBackend{token: "rk_test"} + srv := httptest.NewServer(http.HandlerFunc(be.handler)) + defer srv.Close() + isolate(t, srv) + t.Setenv("RTZ_CLUSTER", "c1") + + stdin := strings.Join([]string{ + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}`, + `{"jsonrpc":"2.0","method":"notifications/initialized"}`, + `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`, + `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"runtimez_cluster_get","arguments":{}}}`, + `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"runtimez_cluster_get","arguments":{"cluster":"staging"}}}`, + `{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"runtimez_whoami"}}`, + }, "\n") + "\n" + + out, code := runMcp(t, stdin) + if code != ExitOK { + t.Fatalf("exit = %d, output:\n%s", code, out) + } + got := lines(out) + if len(got) != 5 { + t.Fatalf("expected 5 responses (the notification has none), got %d:\n%s", len(got), out) + } + if got[0]["id"].(float64) != 1 || got[1]["id"].(float64) != 2 { + t.Errorf("responses out of order or ids lost: %v", got) + } + + // The default cluster is injected only when the client passed none. + echo := func(i int) map[string]any { + res, _ := got[i]["result"].(map[string]any) + args, _ := res["echo"].(map[string]any) + return args + } + if echo(2)["cluster"] != "c1" { + t.Errorf("tools/call without cluster should carry the context cluster, got %v", echo(2)) + } + if echo(3)["cluster"] != "staging" { + t.Errorf("an explicit cluster must be kept, got %v", echo(3)) + } + if echo(4)["cluster"] != "c1" { + t.Errorf("a call with no arguments object should still get the default cluster, got %v", echo(4)) + } + + // Every request carried the bearer; the protocol header appears only after initialize. + if len(be.requests) != 6 { + t.Fatalf("backend saw %d requests, want 6", len(be.requests)) + } + for i, r := range be.requests { + if r.auth != "Bearer rk_test" { + t.Errorf("request %d auth = %q", i, r.auth) + } + } + if be.requests[0].protocolHeader != "" { + t.Errorf("initialize must not carry a protocol version yet, got %q", be.requests[0].protocolHeader) + } + if be.requests[2].protocolHeader != "2025-06-18" { + t.Errorf("post-initialize requests must echo the negotiated version, got %q", be.requests[2].protocolHeader) + } +} + +func TestMcpBridgeTurnsAuthFailuresIntoJsonRpcErrors(t *testing.T) { + be := &mcpBackend{token: "rk_other"} + srv := httptest.NewServer(http.HandlerFunc(be.handler)) + defer srv.Close() + isolate(t, srv) + + out, code := runMcp(t, `{"jsonrpc":"2.0","id":9,"method":"tools/list"}`+"\n") + if code != ExitOK { + t.Fatalf("the bridge must keep serving after a 401; exit = %d:\n%s", code, out) + } + got := lines(out) + if len(got) != 1 { + t.Fatalf("want one error response, got %d:\n%s", len(got), out) + } + errObj, _ := got[0]["error"].(map[string]any) + if errObj["code"].(float64) != mcpErrUnauthorized || !strings.Contains(errObj["message"].(string), "rtz login") { + t.Errorf("unexpected error payload: %v", got[0]) + } + if got[0]["id"].(float64) != 9 { + t.Errorf("error must carry the request id, got %v", got[0]["id"]) + } +} + +func TestMcpBridgeForwardsServerJsonRpcErrorsAndRejectsBadStdin(t *testing.T) { + be := &mcpBackend{token: "rk_test"} + srv := httptest.NewServer(http.HandlerFunc(be.handler)) + defer srv.Close() + isolate(t, srv) + + out, _ := runMcp(t, "not json\n"+`{"jsonrpc":"2.0","id":2,"method":"resources/list"}`+"\n") + got := lines(out) + if len(got) != 2 { + t.Fatalf("want 2 responses, got %d:\n%s", len(got), out) + } + if e, _ := got[0]["error"].(map[string]any); e["code"].(float64) != -32700 { + t.Errorf("bad stdin should be a parse error, got %v", got[0]) + } + if e, _ := got[1]["error"].(map[string]any); e["code"].(float64) != -32601 { + t.Errorf("the server's own JSON-RPC error must be forwarded untouched, got %v", got[1]) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 9c53d3f..e44b92b 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -108,6 +108,7 @@ No kubeconfig, no cluster VPN, no browser.`, newMetricsCmd(), newAskCmd(), newUpgradeCmd(), + newMcpCmd(), ) return root } From 86a8424e2f06b862289e49f2cba1949276c7662c Mon Sep 17 00:00:00 2001 From: pvishwa3 Date: Sat, 17 Oct 2026 19:39:14 -0400 Subject: [PATCH 2/7] feat(tui): k9s-style restyle, pod describe, events decoded from spec - Tab strip, titled rounded panels, semantic cell colour, type-aware column sort, and real s/i/w/0/[/] bindings so the hint bar only advertises keys that exist. - describe covers Pods (k8s.ParsePodDetail + view.podDetail). - Correlated events: type/reason/message/count/lastTimestamp/involvedObject live inside the spec JSON; decode them with k8s.ParseEvent instead of top-level keys (every describe rendered blank event rows before). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0178ctkmt3CJYuTzySDeSgSe --- internal/api/resources.go | 32 +-- internal/cli/rca.go | 68 +----- internal/k8s/event.go | 50 ++++ internal/k8s/poddetail.go | 210 +++++++++++++++++ internal/k8s/poddetail_test.go | 205 ++++++++++++++++ internal/k8s/service.go | 37 +++ internal/render/render.go | 36 ++- internal/tui/app.go | 271 +++++++++++++++++++-- internal/tui/app_test.go | 119 +++++++++- internal/tui/ask.go | 292 +++++++++++++++++++++++ internal/tui/chrome_test.go | 250 ++++++++++++++++++++ internal/tui/paint.go | 124 ++++++++++ internal/tui/panel.go | 106 +++++++++ internal/tui/render.go | 377 +++++++++++++++++++++++++----- internal/tui/sort.go | 121 ++++++++++ internal/tui/styles.go | 64 +++-- internal/tui/table.go | 114 +++++++-- internal/tui/troubleshoot_test.go | 293 +++++++++++++++++++++++ internal/tui/views.go | 259 +++++++++++++++++--- internal/view/detail_test.go | 96 ++++++++ internal/view/rca.go | 93 ++++++++ internal/view/view.go | 120 +++++++++- 22 files changed, 3077 insertions(+), 260 deletions(-) create mode 100644 internal/k8s/event.go create mode 100644 internal/k8s/poddetail.go create mode 100644 internal/k8s/poddetail_test.go create mode 100644 internal/k8s/service.go create mode 100644 internal/tui/ask.go create mode 100644 internal/tui/chrome_test.go create mode 100644 internal/tui/paint.go create mode 100644 internal/tui/panel.go create mode 100644 internal/tui/sort.go create mode 100644 internal/tui/troubleshoot_test.go create mode 100644 internal/view/detail_test.go create mode 100644 internal/view/rca.go diff --git a/internal/api/resources.go b/internal/api/resources.go index 6457071..96a3371 100644 --- a/internal/api/resources.go +++ b/internal/api/resources.go @@ -72,30 +72,20 @@ type WorkloadDetail struct { ReplicaSets []k8s.Resource `json:"replicaSets"` } -// Event is a correlated Kubernetes event. The backend returns warnings first, capped at 50. -// Field names vary across agent versions, so the alternates are decoded rather than guessed. +// Event is a correlated Kubernetes event row. The backend returns warnings first, capped at +// 50 (KubeResourceClickHouseRepository.getCorrelatedEvents), and projects only these four +// columns — type, reason, message and count live inside Spec, exactly as they do for every +// other resource. Verified against 49 live events: the spec always carries reason, message, +// type, count, lastTimestamp and involvedObject. type Event struct { - Type string `json:"type"` - Reason string `json:"reason"` - Message string `json:"message"` - Count int `json:"count"` - InvolvedObject string `json:"involvedObject"` - Namespace string `json:"namespace"` - Name string `json:"name"` - LastTimestamp string `json:"lastTimestamp"` - EventTime string `json:"eventTime"` - FirstTimestamp string `json:"firstTimestamp"` + UID string `json:"uid"` + Name string `json:"name"` + Spec string `json:"spec"` + CreatedAt string `json:"createdAt"` } -// When picks whichever timestamp this event actually carries. -func (e Event) When() string { - for _, ts := range []string{e.LastTimestamp, e.EventTime, e.FirstTimestamp} { - if ts != "" { - return ts - } - } - return "" -} +// Info decodes the spec blob into the fields worth rendering. +func (e Event) Info() k8s.EventInfo { return k8s.ParseEvent(e.Spec, e.CreatedAt) } // Detail fetches one workload with its pods, events and related objects. kind is optional // and disambiguates a name shared by two controller kinds in one namespace. diff --git a/internal/cli/rca.go b/internal/cli/rca.go index 14b3547..064f2b4 100644 --- a/internal/cli/rca.go +++ b/internal/cli/rca.go @@ -9,6 +9,7 @@ import ( "github.com/runtimez-com/runtimez-cli/internal/api" "github.com/runtimez-com/runtimez-cli/internal/render" + "github.com/runtimez-com/runtimez-cli/internal/view" ) // clusterEnv resolves the env plus a required org and cluster — the preamble every @@ -110,75 +111,10 @@ func runWorkloadRCA(cmd *cobra.Command, e *env, orgID, clusterID, ref string) er return e.printer.Print(r, nil) } - out := cmd.OutOrStdout() - fmt.Fprintf(out, "%s/%s (%s)\n", r.Namespace, r.Name, render.Dash(r.Kind)) - fmt.Fprintf(out, " Restarts: %d\n", r.RestartCount) - if r.K8sReason != "" { - fmt.Fprintf(out, " Reason: %s\n", r.K8sReason) - } - if r.OOMKilled { - fmt.Fprintln(out, " OOMKilled: yes") - } - if r.ExitCode != nil { - fmt.Fprintf(out, " Exit code: %d\n", *r.ExitCode) - } - if r.TerminatedAt != "" { - fmt.Fprintf(out, " Terminated: %s\n", r.TerminatedAt) - } - if r.TerminationSummary != "" { - fmt.Fprintf(out, " Summary: %s\n", r.TerminationSummary) - } - - // App health is only meaningful when traces reached the backend; printing 0% error and - // 0ms p99 for a workload with no telemetry would read as a perfectly healthy service. - if r.AppHealthAvailable { - fmt.Fprintf(out, " Requests: %d, %.2f%% errors, p99 %dms\n", - r.RequestCount, r.ErrorRatePct, r.P99LatencyMs) - } else { - fmt.Fprintln(out, " App health: no trace data for this workload") - } - - if len(r.WarningEvents) > 0 { - fmt.Fprintf(out, "\nWarning events (%d)\n", len(r.WarningEvents)) - for _, ev := range r.WarningEvents { - fmt.Fprintf(out, " %s %s %s\n", - render.Dash(ev.LastTimestamp), render.Dash(ev.Reason), truncateLine(ev.Message, 70)) - } - } - - fmt.Fprintf(out, "\nLog tail (%d lines)\n", len(r.LogTailLines)) - if !r.TermLogsAvailable { - fmt.Fprintln(out, " termination logs not collected for this workload") - } - for _, l := range r.LogTailLines { - fmt.Fprintf(out, " %s\n", truncateLine(l, 100)) - } - - if len(r.SpansInFlight) > 0 { - fmt.Fprintf(out, "\nSpans in flight at failure (%d)\n", len(r.SpansInFlight)) - for _, s := range r.SpansInFlight { - fmt.Fprintf(out, " %s %s %s %dms\n", - s.TraceID, truncateLine(s.SpanName, 40), render.Dash(s.StatusCode), s.DurationMs) - } - } - - printEdges(cmd, "Upstream", r.Upstream) - printEdges(cmd, "Downstream", r.Downstream) + view.WorkloadRCA(cmd.OutOrStdout(), r) return nil } -func printEdges(cmd *cobra.Command, title string, edges []api.DependencyEdge) { - if len(edges) == 0 { - return - } - out := cmd.OutOrStdout() - fmt.Fprintf(out, "\n%s (%d)\n", title, len(edges)) - for _, e := range edges { - fmt.Fprintf(out, " %s/%s %s %d bytes\n", - render.Dash(e.Namespace), render.Dash(e.OwnerName), render.Dash(e.OwnerKind), e.Bytes) - } -} - func newRcaExplainCmd() *cobra.Command { var force bool diff --git a/internal/k8s/event.go b/internal/k8s/event.go new file mode 100644 index 0000000..ef2f8da --- /dev/null +++ b/internal/k8s/event.go @@ -0,0 +1,50 @@ +package k8s + +// EventInfo is a Kubernetes event as the backend actually returns it. +// +// The row carries uid/name/createdAt and everything worth reading — type, reason, message, +// count, the object it is about — lives inside the `spec` JSON string, the same shape every +// other resource uses. Decoding those as top-level JSON keys yields a struct that is empty +// except for the name, which renders as a table of blanks rather than as an error. +type EventInfo struct { + Type string + Reason string + Message string + Count int + LastTimestamp string + InvolvedKind string + InvolvedName string +} + +// ParseEvent reads one event's spec blob. createdAt is the fallback timestamp for an event +// whose spec carries no lastTimestamp. +func ParseEvent(spec, createdAt string) EventInfo { + s := parse(spec) + involved := s.child("involvedObject") + + count, _ := s.num("count") + ts := s.str("lastTimestamp") + if ts == "" { + // Some agent versions have written the alternates; fall through to the row's own + // creation time rather than rendering an event with no time at all. + for _, k := range []string{"eventTime", "firstTimestamp"} { + if v := s.str(k); v != "" { + ts = v + break + } + } + } + if ts == "" { + ts = createdAt + } + + return EventInfo{ + Type: s.str("type"), + Reason: s.str("reason"), + Message: s.str("message"), + Count: count, + LastTimestamp: ts, + InvolvedKind: involved.str("kind"), + InvolvedName: involved.str("name"), + } +} diff --git a/internal/k8s/poddetail.go b/internal/k8s/poddetail.go new file mode 100644 index 0000000..1b4c560 --- /dev/null +++ b/internal/k8s/poddetail.go @@ -0,0 +1,210 @@ +package k8s + +// The shapes here were read off the live agent payload, not assumed. A pod's spec carries +// containers[{name,image,resources{requests,limits},command,imagePullPolicy,livenessProbe, +// readinessProbe,startupProbe}], initContainers, nodeName, serviceAccountName; its status +// carries phase, qosClass, restartCount, lastRestartAt, containerStatuses[{name,image,ready, +// restartCount,state{type,startedAt},lastTerminated{reason,exitCode,finishedAt,message}}], +// initContainerStatuses and conditions. +// +// Notably ABSENT, so nothing here renders them: podIP, hostIP and startTime. The agent's +// curated flatten does not send them, and a column of blanks reads as "the pod has no IP". + +// Container is one container, with its spec and its status merged. +type Container struct { + Name string + Image string + Init bool + + Ready bool + Restarts int + + // State is the running/waiting/terminated word, with the reason when there is one — + // "waiting: CrashLoopBackOff" is the whole answer to why a pod is not up. + State string + StateReason string + + LastTerminatedReason string + LastExitCode int + HasLastExitCode bool + LastFinishedAt string + + CPURequest, CPULimit string + MemRequest, MemLimit string + + // Probes names the probes that are configured, because a readiness probe that never + // passes is the usual reason a Running pod is not Ready. + Probes []string +} + +// Condition is one pod condition. +type Condition struct { + Type string + Status string + Reason string + Message string +} + +// PodDetail is everything the describe pane shows for a single pod. +type PodDetail struct { + Pod + QoS string + ServiceAccount string + HostNetwork bool + Containers []Container + Conditions []Condition + MissingContainers bool // the payload carried no container detail at all +} + +// ParsePodDetail merges a pod's spec and status into one view. +func ParsePodDetail(r Resource) PodDetail { + spec := parse(r.Spec) + status := parse(r.Status) + + d := PodDetail{ + Pod: ParsePod(r), + QoS: status.str("qosClass"), + ServiceAccount: spec.str("serviceAccountName"), + } + if hn, isBool := spec["hostNetwork"].(bool); isBool { + d.HostNetwork = hn + } + + d.Containers = append(d.Containers, + mergeContainers(spec.list("initContainers"), status.list("initContainerStatuses"), true)...) + d.Containers = append(d.Containers, + mergeContainers(spec.list("containers"), status.list("containerStatuses"), false)...) + d.MissingContainers = len(d.Containers) == 0 + + for _, c := range status.list("conditions") { + m, isMap := c.(map[string]any) + if !isMap { + continue + } + o := obj(m) + d.Conditions = append(d.Conditions, Condition{ + Type: o.str("type"), Status: o.str("status"), + Reason: o.str("reason"), Message: o.str("message"), + }) + } + return d +} + +// mergeContainers joins spec and status entries by name. A container present in only one of +// them still appears: a status with no spec happens mid-rollout, and a spec with no status +// is a container that has not started, which is exactly what someone is looking for. +func mergeContainers(specs, statuses []any, init bool) []Container { + byName := map[string]*Container{} + order := []string{} + + get := func(name string) *Container { + if c, ok := byName[name]; ok { + return c + } + c := &Container{Name: name, Init: init} + byName[name] = c + order = append(order, name) + return c + } + + for _, raw := range specs { + m, isMap := raw.(map[string]any) + if !isMap { + continue + } + o := obj(m) + c := get(o.str("name")) + c.Image = o.str("image") + res := o.child("resources") + req, lim := res.child("requests"), res.child("limits") + c.CPURequest, c.CPULimit = req.str("cpu"), lim.str("cpu") + c.MemRequest, c.MemLimit = req.str("memory"), lim.str("memory") + for _, p := range []string{"livenessProbe", "readinessProbe", "startupProbe"} { + if on, isBool := o[p].(bool); isBool && on { + c.Probes = append(c.Probes, probeShortName(p)) + } + } + } + + for _, raw := range statuses { + m, isMap := raw.(map[string]any) + if !isMap { + continue + } + o := obj(m) + c := get(o.str("name")) + if c.Image == "" { + c.Image = o.str("image") + } + if ready, isBool := o["ready"].(bool); isBool { + c.Ready = ready + } + c.Restarts, _ = o.num("restartCount") + + st := o.child("state") + c.State = st.str("type") + c.StateReason = st.str("reason") + + // lastState is the standard k8s key; the agent flattens it to lastTerminated. + last := o.child("lastTerminated") + if len(last) == 0 { + last = o.child("lastState").child("terminated") + } + c.LastTerminatedReason = last.str("reason") + c.LastFinishedAt = last.str("finishedAt") + if code, ok := last.num("exitCode"); ok { + c.LastExitCode, c.HasLastExitCode = code, true + } + } + + out := make([]Container, 0, len(order)) + for _, n := range order { + out = append(out, *byName[n]) + } + return out +} + +func probeShortName(key string) string { + switch key { + case "livenessProbe": + return "liveness" + case "readinessProbe": + return "readiness" + case "startupProbe": + return "startup" + } + return key +} + +// StateLabel is the state with its reason folded in. +func (c Container) StateLabel() string { + switch { + case c.State == "" && c.StateReason == "": + return "" + case c.StateReason == "": + return c.State + case c.State == "": + return c.StateReason + default: + return c.State + ": " + c.StateReason + } +} + +// Resources renders "10m/50m" style request/limit pairs, and says which side is unset — +// an unlimited container is a fact worth seeing, not a blank. +func pairOrDash(request, limit string) string { + if request == "" && limit == "" { + return "-" + } + r, l := request, limit + if r == "" { + r = "-" + } + if l == "" { + l = "-" + } + return r + "/" + l +} + +func (c Container) CPU() string { return pairOrDash(c.CPURequest, c.CPULimit) } +func (c Container) Mem() string { return pairOrDash(c.MemRequest, c.MemLimit) } diff --git a/internal/k8s/poddetail_test.go b/internal/k8s/poddetail_test.go new file mode 100644 index 0000000..88aec6f --- /dev/null +++ b/internal/k8s/poddetail_test.go @@ -0,0 +1,205 @@ +package k8s + +import "testing" + +// These payloads are copied from a live agent response, not invented. A parser tested only +// against a shape someone imagined passes while the real one decodes to blanks — which is +// exactly how the Events table shipped empty. +const livePodSpec = `{ + "nodeName": "k3d-dev-cluster-agent-2", + "hostNetwork": false, + "containers": [{ + "name": "app", + "image": "busybox:1.36", + "resources": {"requests": {"cpu": "10m", "memory": "16Mi"}, + "limits": {"cpu": "50m", "memory": "32Mi"}}, + "livenessProbe": false, "readinessProbe": true, "startupProbe": false + }], + "initContainers": [], + "serviceAccountName": "default" +}` + +const livePodStatus = `{ + "phase": "Running", + "qosClass": "Burstable", + "restartCount": 15, + "lastRestartAt": "2026-09-06T12:51:52Z", + "containerStatuses": [{ + "name": "app", + "image": "docker.io/library/busybox:1.36", + "ready": false, + "restartCount": 15, + "state": {"type": "running", "startedAt": "2026-09-06T12:51:52Z"}, + "lastTerminated": {"reason": "Completed", "exitCode": 0, + "finishedAt": "2026-09-06T12:51:52Z", "message": null} + }], + "initContainerStatuses": [], + "conditions": [ + {"type": "Initialized", "status": "True"}, + {"type": "Ready", "status": "False", "reason": "ContainersNotReady", + "message": "containers with unready status: [app]"} + ] +}` + +func TestParsePodDetailMergesSpecAndStatus(t *testing.T) { + d := ParsePodDetail(Resource{ + Kind: "Pod", Namespace: "rtzflags", Name: "flg-stall-subject-688899b5cb-fr2k8", + Spec: livePodSpec, Status: livePodStatus, + }) + + if d.QoS != "Burstable" || d.NodeName != "k3d-dev-cluster-agent-2" { + t.Errorf("QoS=%q node=%q", d.QoS, d.NodeName) + } + if d.ServiceAccount != "default" { + t.Errorf("account = %q", d.ServiceAccount) + } + if len(d.Containers) != 1 { + t.Fatalf("containers = %d, want 1", len(d.Containers)) + } + + c := d.Containers[0] + // The spec image is what was asked for; the status image is what the runtime resolved. + // Showing the spec one keeps `describe` comparable with the manifest. + if c.Image != "busybox:1.36" { + t.Errorf("image = %q, want the spec image", c.Image) + } + if c.Ready { + t.Error("container reported ready when status says false") + } + if c.Restarts != 15 { + t.Errorf("restarts = %d", c.Restarts) + } + if got := c.StateLabel(); got != "running" { + t.Errorf("state = %q", got) + } + if c.CPU() != "10m/50m" || c.Mem() != "16Mi/32Mi" { + t.Errorf("cpu=%q mem=%q", c.CPU(), c.Mem()) + } + // A readiness probe that never passes is the usual reason a Running pod is not Ready, + // so which probes exist has to be on screen. + if len(c.Probes) != 1 || c.Probes[0] != "readiness" { + t.Errorf("probes = %v, want [readiness]", c.Probes) + } + if c.LastTerminatedReason != "Completed" || !c.HasLastExitCode || c.LastExitCode != 0 { + t.Errorf("lastTerminated = %q exit=%d has=%v", + c.LastTerminatedReason, c.LastExitCode, c.HasLastExitCode) + } + if len(d.Conditions) != 2 || d.Conditions[1].Reason != "ContainersNotReady" { + t.Errorf("conditions = %+v", d.Conditions) + } +} + +// Exit code 0 is a real value and "no exit code recorded" is a different one. Collapsing +// them hides a clean exit behind the same dash as a container that never terminated. +func TestZeroExitCodeIsDistinctFromNoExitCode(t *testing.T) { + with := ParsePodDetail(Resource{Kind: "Pod", Status: `{"containerStatuses":[ + {"name":"a","lastTerminated":{"reason":"Completed","exitCode":0}}]}`}) + if !with.Containers[0].HasLastExitCode || with.Containers[0].LastExitCode != 0 { + t.Error("exit code 0 was not recorded") + } + without := ParsePodDetail(Resource{Kind: "Pod", Status: `{"containerStatuses":[ + {"name":"a","state":{"type":"running"}}]}`}) + if without.Containers[0].HasLastExitCode { + t.Error("a container that never terminated reported an exit code") + } +} + +// A pod whose payload carried no containers is an agent-version question, not a workload +// one, and the renderer has to be able to tell them apart. +func TestMissingContainerDetailIsFlagged(t *testing.T) { + d := ParsePodDetail(Resource{Kind: "Pod", Status: `{"phase":"Running"}`}) + if !d.MissingContainers { + t.Error("a payload with no containers was not flagged") + } +} + +func TestInitContainersAreMarkedAndComeFirst(t *testing.T) { + d := ParsePodDetail(Resource{Kind: "Pod", + Spec: `{"initContainers":[{"name":"migrate","image":"m:1"}],"containers":[{"name":"app","image":"a:1"}]}`, + Status: `{"initContainerStatuses":[{"name":"migrate","ready":true}],"containerStatuses":[{"name":"app","ready":true}]}`}) + if len(d.Containers) != 2 { + t.Fatalf("containers = %d", len(d.Containers)) + } + if d.Containers[0].Name != "migrate" || !d.Containers[0].Init { + t.Errorf("first = %+v, want the init container", d.Containers[0]) + } + if d.Containers[1].Init { + t.Error("app was marked as an init container") + } +} + +// A container in the spec but not yet in the status has not started — which is precisely +// what someone describing a stuck pod is looking for, so it must not be dropped. +func TestContainerPresentInOnlyOneHalfStillAppears(t *testing.T) { + d := ParsePodDetail(Resource{Kind: "Pod", + Spec: `{"containers":[{"name":"app","image":"a:1"},{"name":"sidecar","image":"s:1"}]}`, + Status: `{"containerStatuses":[{"name":"app","ready":true}]}`}) + if len(d.Containers) != 2 { + t.Fatalf("containers = %d, want both", len(d.Containers)) + } + if d.Containers[1].Name != "sidecar" || d.Containers[1].StateLabel() != "" { + t.Errorf("unstarted container = %+v", d.Containers[1]) + } +} + +// The event's fields live inside the spec blob. Decoding them as top-level keys yields a +// struct that is empty except for the name — a table of blanks, which is what shipped. +func TestParseEventReadsTheSpecBlob(t *testing.T) { + e := ParseEvent(`{"reason":"Unhealthy","message":"Readiness probe failed:","type":"Warning", + "count":11268,"lastTimestamp":"2026-09-06T12:10:01Z", + "involvedObject":{"kind":"Pod","name":"flg-stall-subject-688899b5cb-fr2k8","namespace":"rtzflags"}}`, "") + + if e.Type != "Warning" || e.Reason != "Unhealthy" || e.Count != 11268 { + t.Errorf("type=%q reason=%q count=%d", e.Type, e.Reason, e.Count) + } + if e.LastTimestamp != "2026-09-06T12:10:01Z" { + t.Errorf("lastTimestamp = %q", e.LastTimestamp) + } + if e.InvolvedKind != "Pod" || e.InvolvedName == "" { + t.Errorf("involvedObject = %s/%s", e.InvolvedKind, e.InvolvedName) + } +} + +// An event with no timestamp in its spec still has the row's creation time, and rendering +// "" for an event we can date is a needless loss. +func TestEventFallsBackToTheRowTimestamp(t *testing.T) { + e := ParseEvent(`{"reason":"Killing","type":"Normal"}`, "2026-09-06T09:00:00Z") + if e.LastTimestamp != "2026-09-06T09:00:00Z" { + t.Errorf("lastTimestamp = %q", e.LastTimestamp) + } +} + +// Logs and traces are indexed under the workload's name, not the pod's. Recovering it by +// trimming "the last two segments" would mangle any workload whose own name has a dash — +// the pod carries the exact hash to remove. +func TestServiceNameStripsExactlyTheReplicaSetHash(t *testing.T) { + cases := []struct { + name string + r Resource + want string + }{ + {"dashed workload name", Resource{ + Kind: "Pod", Name: "flg-stall-subject-688899b5cb-fr2k8", + OwnerKind: "ReplicaSet", OwnerName: "flg-stall-subject-688899b5cb", + Labels: `{"pod-template-hash":"688899b5cb"}`}, "flg-stall-subject"}, + {"explicit app label wins", Resource{ + Kind: "Pod", Name: "checkout-gateway-5b865fbfcb-2jd59", + OwnerKind: "ReplicaSet", OwnerName: "checkout-gateway-5b865fbfcb", + Labels: `{"app":"checkout-gateway","pod-template-hash":"5b865fbfcb"}`}, "checkout-gateway"}, + {"statefulset owner is already the name", Resource{ + Kind: "Pod", Name: "postgres-0", OwnerKind: "StatefulSet", OwnerName: "postgres", + Labels: `{}`}, "postgres"}, + {"no hash label leaves the owner alone", Resource{ + Kind: "Pod", Name: "orphan-xyz", OwnerKind: "ReplicaSet", OwnerName: "orphan-abc123", + Labels: `{}`}, "orphan-abc123"}, + {"a controller is its own service", Resource{ + Kind: "Deployment", Name: "checkout-gateway", Labels: `{}`}, "checkout-gateway"}, + {"a bare pod falls back to its own name", Resource{ + Kind: "Pod", Name: "debug-shell", Labels: `{}`}, "debug-shell"}, + } + for _, c := range cases { + if got := ServiceNameFor(c.r); got != c.want { + t.Errorf("%s: got %q, want %q", c.name, got, c.want) + } + } +} diff --git a/internal/k8s/service.go b/internal/k8s/service.go new file mode 100644 index 0000000..b0c45c0 --- /dev/null +++ b/internal/k8s/service.go @@ -0,0 +1,37 @@ +package k8s + +import "strings" + +// ServiceNameFor derives the name a workload's telemetry is indexed under, so a drill-down +// from a pod row can find its logs and traces. +// +// A pod is named --, and its ReplicaSet owner is +// named -. The hash is not guessed: it is on the pod as the +// pod-template-hash label, so the deployment name is recovered by removing exactly that +// suffix. Trimming "the last two dash-separated segments" would mangle any workload whose +// own name contains a dash. +func ServiceNameFor(r Resource) string { + labels := obj(parse(r.Labels)) + + // An explicit service name wins: someone who set it meant it. + for _, key := range []string{ + "app.kubernetes.io/name", + "app", + "k8s-app", + } { + if v := labels.str(key); v != "" { + return v + } + } + + if r.Kind == "Pod" && r.OwnerName != "" { + owner := r.OwnerName + if r.OwnerKind == "ReplicaSet" { + if hash := labels.str("pod-template-hash"); hash != "" { + owner = strings.TrimSuffix(owner, "-"+hash) + } + } + return owner + } + return r.Name +} diff --git a/internal/render/render.go b/internal/render/render.go index cbfb6be..5141176 100644 --- a/internal/render/render.go +++ b/internal/render/render.go @@ -92,21 +92,33 @@ func (p *Printer) Print(data any, table *Table) error { } } +// Widened returns the table with its wide columns folded in, or the table itself when it +// has none. One definition so `-o wide` and the TUI's `w` key show the same columns. +func (t *Table) Widened() *Table { + if t == nil || len(t.WideHeaders) == 0 { + return t + } + out := &Table{ + Headers: append(append([]string{}, t.Headers...), t.WideHeaders...), + Rows: make([][]string, len(t.Rows)), + EmptyMessage: t.EmptyMessage, + } + for i, r := range t.Rows { + extra := []string{} + if i < len(t.WideRows) { + extra = t.WideRows[i] + } + out.Rows[i] = append(append([]string{}, r...), extra...) + } + return out +} + func (p *Printer) printTable(t *Table) error { + if p.Format == FormatWide { + t = t.Widened() + } headers := t.Headers rows := t.Rows - if p.Format == FormatWide && len(t.WideHeaders) > 0 { - headers = append(append([]string{}, headers...), t.WideHeaders...) - merged := make([][]string, len(rows)) - for i, r := range rows { - extra := []string{} - if i < len(t.WideRows) { - extra = t.WideRows[i] - } - merged[i] = append(append([]string{}, r...), extra...) - } - rows = merged - } if len(rows) == 0 { msg := t.EmptyMessage diff --git a/internal/tui/app.go b/internal/tui/app.go index 471d640..d7e945c 100644 --- a/internal/tui/app.go +++ b/internal/tui/app.go @@ -16,6 +16,7 @@ import ( "github.com/runtimez-com/runtimez-cli/internal/api" "github.com/runtimez-com/runtimez-cli/internal/k8s" + "github.com/runtimez-com/runtimez-cli/internal/render" ) type mode int @@ -26,6 +27,7 @@ const ( modeCommand modeDetail modeHelp + modeAsk ) // Options configures a session. @@ -48,6 +50,9 @@ type Model struct { view viewDef namespace string + // scope is the workload the drill-down keys act on. It survives a view switch on + // purpose — that is what makes l, r, c and t a chain rather than four separate lookups. + scope scope data dataset visible []int // indices into the table's rows that survive the filter @@ -58,9 +63,25 @@ type Model struct { input textinput.Model filter string + // sortCol is -1 while the server's own ordering stands; `s` walks it across the + // columns and `i` flips the direction. + sortCol int + sortDesc bool + wide bool + // shown is the table actually drawn — data.table, or its widened form. Cached rather + // than rebuilt per frame: widening copies every row, and a 5000-row listing would pay + // that on every keystroke. + shown *render.Table + + // history is the trail of view names `[` and `]` walk, in visit order. + history []string + histPos int + detail *api.WorkloadDetail detailRef string + ask askState + loading bool paused bool lastUpdated time.Time @@ -99,7 +120,11 @@ func New(opts Options) Model { in.Prompt = "" in.CharLimit = 120 - return Model{opts: opts, view: v, input: in, loading: true} + return Model{ + opts: opts, view: v, input: in, loading: true, + sortCol: -1, + history: []string{name}, histPos: 0, + } } func (m Model) Init() tea.Cmd { @@ -111,16 +136,21 @@ func (m Model) tick() tea.Cmd { } func (m Model) fetch() tea.Cmd { - o, v, ns := m.opts, m.view, m.namespace + o, v := m.opts, m.view + req := fetchReq{Client: o.Client, OrgID: o.OrgID, ClusterID: o.ClusterID, Namespace: m.namespace} // A view that ignores the namespace scope must not be handed one, or the :ns filter - // would appear to apply to screens it has no effect on. + // would appear to apply to screens it has no effect on. Same for the workload scope: a + // screen that cannot narrow by it must not look as though it did. if !v.namespaced { - ns = "" + req.Namespace = "" + } + if v.scopable { + req.Scope = m.scope } return func() tea.Msg { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - d, err := v.fetch(ctx, o.Client, o.OrgID, o.ClusterID, ns) + d, err := v.fetch(ctx, req) return rowsMsg{data: d, err: err} } } @@ -158,7 +188,10 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } m.err = nil m.data = msg.data - m.status = msg.data.notice + // The caveat travels with the data and is rendered from it; copying it into + // status printed it twice. + m.status = "" + m.rebuildShown() m.applyFilter() m.lastUpdated = time.Now() return m, nil @@ -178,6 +211,29 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.detail, m.detailRef, m.mode = msg.detail, msg.ref, modeDetail return m, nil + case askFrameMsg: + if !msg.open { + // The channel closed: the run is over one way or another. + m.ask.busy = false + return m, nil + } + m.ask.appendFrame(msg.frame) + m.ask.offset = 0 + return m, waitFrame(m.ask.frames) + + case askAnswerMsg: + m.ask.busy = false + m.ask.appendAnswer(msg.answer, msg.err) + m.ask.offset = 0 + // The run is over, so drop the subscription. Leaving it open holds an SSE + // connection and a goroutine per question for as long as the pane is open — the + // flag command stops listening here too. + if m.ask.cancel != nil { + m.ask.cancel() + m.ask.cancel = nil + } + return m, nil + case tea.KeyMsg: return m.handleKey(msg) } @@ -185,7 +241,12 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - // Ctrl-C always quits, whatever is focused. + // The ask pane owns Ctrl-C while a run is live — there it means "stop the agent", the + // same contract the flag command has — so it gets first refusal on every key. + if m.mode == modeAsk { + return m.handleAskKey(msg) + } + // Everywhere else Ctrl-C quits, whatever is focused. if msg.Type == tea.KeyCtrlC { return m, tea.Quit } @@ -262,9 +323,18 @@ func (m Model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, textinput.Blink case "esc": - if m.filter != "" { + // One step at a time, narrowest first: the filter is what was typed most recently, + // so clearing both at once would throw away a scope the user is still working in. + switch { + case m.filter != "": m.filter = "" m.applyFilter() + m.status = "" + return m, nil + case !m.scope.empty(): + m.scope = scope{} + m.loading, m.status = true, "scope cleared" + return m, m.fetch() } m.status = "" return m, nil @@ -308,17 +378,64 @@ func (m Model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { } // Detail exists for workload controllers only; saying so beats opening a blank pane. if !isDescribable(r.Kind) { - m.status = fmt.Sprintf("no detail view for %s — describe covers Deployment, StatefulSet and DaemonSet", r.Kind) + m.status = fmt.Sprintf("no detail view for %s — describe covers Pod, Deployment, StatefulSet and DaemonSet", r.Kind) return m, nil } m.loading = true return m, m.fetchDetail(r) - case "l", "r", "a": - // Reserved in the roadmap; claiming the key now while doing nothing would read as a - // broken binding. - m.status = fmt.Sprintf("%q arrives with logs, risk and ask in a later milestone", msg.String()) + case "s": + // Walk the columns, then off the end back to the server's order — which is a real + // state, not a missing one, and has to be reachable again. + m.cycleSort() return m, nil + + case "i": + if m.sortCol < 0 { + m.status = "nothing is sorted yet — press s to pick a column" + return m, nil + } + m.sortDesc = !m.sortDesc + m.applyFilter() + return m, nil + + case "w": + if m.data.table == nil || len(m.data.table.WideHeaders) == 0 { + m.status = "this view has no extra columns" + return m, nil + } + m.wide = !m.wide + m.rebuildShown() + // The widened table has more columns, so a sort pinned to an index still points at + // the same column: the extras are appended, never inserted. + m.applyFilter() + return m, nil + + case "0": + if m.namespace == "" { + m.status = "already showing every namespace" + return m, nil + } + m.namespace = "" + m.loading, m.status = true, "showing all namespaces" + return m, m.fetch() + + case "[": + return m.stepHistory(-1) + case "]": + return m.stepHistory(1) + + case "l": + return m.drillDown("logs") + case "r": + return m.drillDown("rca") + case "c": + return m.drillDown("changes") + case "t": + return m.drillDown("traces") + + case "a": + return m.openAsk() } return m, nil } @@ -348,11 +465,8 @@ func (m Model) runCommand(raw string) (tea.Model, tea.Cmd) { return m, m.fetch() } - if v, ok := views[name]; ok { - m.view = v - m.cursor, m.offset, m.filter = 0, 0, "" - m.loading, m.status = true, "" - return m, m.fetch() + if _, ok := views[name]; ok { + return m.switchView(name) } if milestone, planned := plannedViews[name]; planned { m.status = fmt.Sprintf("%q is not a view here — see %s", name, milestone) @@ -362,9 +476,86 @@ func (m Model) runCommand(raw string) (tea.Model, tea.Cmd) { return m, nil } +// drillDown scopes to the row under the cursor and opens a view about it. On a screen with +// no resource behind the row it opens the view unscoped and says so, rather than silently +// showing the whole cluster under a heading that reads like one workload. +func (m Model) drillDown(name string) (tea.Model, tea.Cmd) { + if r, ok := m.selected(); ok { + m.scope = scopeOf(r) + } else if m.scope.empty() { + m.status = "nothing selected — " + name + " is cluster-wide" + } + return m.switchView(name) +} + +// switchView loads a view by name and records the move so `[` can undo it. +func (m Model) switchView(name string) (tea.Model, tea.Cmd) { + v, ok := views[name] + if !ok { + m.status = fmt.Sprintf("unknown view %q", name) + return m, nil + } + if m.histPos < len(m.history)-1 { + // Moving somewhere new from the middle of the trail abandons the forward branch, + // the way a browser does. + m.history = m.history[:m.histPos+1] + } + if len(m.history) == 0 || m.history[m.histPos] != name { + m.history = append(m.history, name) + m.histPos = len(m.history) - 1 + } + return m.loadView(v) +} + +// loadView resets everything that belongs to the outgoing screen. The sort is one of them: +// column 3 means something different on every view, so carrying it over would silently +// order the new table by whatever happens to sit there. +func (m Model) loadView(v viewDef) (tea.Model, tea.Cmd) { + m.view = v + m.cursor, m.offset, m.filter = 0, 0, "" + m.sortCol, m.sortDesc, m.wide = -1, false, false + m.shown = nil + m.loading, m.status = true, "" + return m, m.fetch() +} + +func (m Model) stepHistory(delta int) (tea.Model, tea.Cmd) { + next := m.histPos + delta + if next < 0 || next >= len(m.history) { + if delta < 0 { + m.status = "no earlier view" + } else { + m.status = "no later view" + } + return m, nil + } + m.histPos = next + return m.loadView(views[m.history[next]]) +} + +// cycleSort advances the sort one step: unsorted → column 0 → … → last column → unsorted. +func (m *Model) cycleSort() { + t := m.activeTable() + if t == nil || len(t.Headers) == 0 { + return + } + m.sortCol++ + if m.sortCol >= len(t.Headers) { + m.sortCol = -1 + m.sortDesc = false + m.status = "sorted by the server's own order" + } else { + m.status = "sorted by " + strings.ToLower(t.Headers[m.sortCol]) + } + m.applyFilter() +} + +// isDescribable names the kinds the detail pane can render. The backend's +// /workloads/{ns}/{name}/detail takes any kind — it looks the row up by kind/namespace/name +// — so this list is about having a renderer, not about what the API allows. func isDescribable(kind string) bool { switch kind { - case "Deployment", "StatefulSet", "DaemonSet": + case "Deployment", "StatefulSet", "DaemonSet", "Pod": return true } return false @@ -383,6 +574,9 @@ func (m *Model) applyFilter() { m.visible = append(m.visible, i) } } + if m.sortCol >= 0 { + sortRows(m.activeTable().Rows, m.visible, m.sortCol, m.sortDesc) + } m.clampCursor() } @@ -424,11 +618,46 @@ func (m Model) selected() (k8s.Resource, bool) { return m.data.resources[idx], true } -// bodyHeight is the row budget: total minus header block, column header and footer. +// bodyHeight is the row budget: the window minus everything the chrome occupies. It is +// derived from the same pieces View draws, so the two cannot disagree about how many rows +// fit — a disagreement shows up as a clipped last row or a scroll that stops early. func (m Model) bodyHeight() int { - h := m.height - 6 + if m.height <= 0 { + return 20 + } + chrome := 1 + // tab strip + 1 + // column header inside the table panel + 2 + // the table panel's own border + 2 // hint line + status line + if m.contextPanelShown() { + chrome += panelHeight(contextPanelLines, m.screenWidth()) + } + h := m.height - chrome if h < 1 { return 1 } return h } + +// contextPanelLines is the height of the context panel's body — seven facts, and the key +// columns are never taller than that. +const contextPanelLines = 7 + +func (m Model) contextPanelShown() bool { return m.height <= 0 || m.height >= 20 } + +// activeTable is what gets drawn: the view's table, widened when `w` is on. +func (m Model) activeTable() *render.Table { + if m.shown != nil { + return m.shown + } + return m.data.table +} + +// rebuildShown recomputes the drawn table after the data or the wide toggle changes. +func (m *Model) rebuildShown() { + if m.wide { + m.shown = m.data.table.Widened() + return + } + m.shown = m.data.table +} diff --git a/internal/tui/app_test.go b/internal/tui/app_test.go index dcaaec7..0e52ae6 100644 --- a/internal/tui/app_test.go +++ b/internal/tui/app_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "strings" + "sync" "testing" "time" @@ -30,6 +31,80 @@ type fakeClient struct { changes *api.Changes logs *api.LogPage traces *api.TracePage + rca *api.WorkloadRCA + + // what the last call was scoped to — the point of the drill-down keys + lastLogService string + lastTraceQuery string + lastRCARef string + lastChangesRef string + + // agent stubs: enough to drive a whole investigation with no backend + answer *api.AgentAnswer + askErr error + askedQuestion string + streamFrames []api.StreamFrame + streamID string + cancelledStream string + mu sync.Mutex +} + +// The agent stubs let a test drive a whole investigation without a backend: frames are +// pushed through the same callback the real SSE reader uses. +func (f *fakeClient) Ask(_ context.Context, _, _ string, q api.AgentQuery) (*api.AgentAnswer, error) { + f.askedQuestion = q.Query + if f.askErr != nil { + return nil, f.askErr + } + if f.answer == nil { + return &api.AgentAnswer{Answer: "no findings", SessionID: "s-1"}, nil + } + return f.answer, nil +} + +func (f *fakeClient) StreamInvestigation(ctx context.Context, _, _, streamID string, fn func(api.StreamFrame) error) error { + f.mu.Lock() + f.streamID = streamID + f.mu.Unlock() + for _, fr := range f.streamFrames { + if err := fn(fr); err != nil { + return err + } + } + <-ctx.Done() + return ctx.Err() +} + +func (f *fakeClient) CancelInvestigation(_ context.Context, _, _, streamID string) error { + f.mu.Lock() + f.cancelledStream = streamID + f.mu.Unlock() + return nil +} + +// cancelled reads the bookkeeping the stream goroutine also writes. +func (f *fakeClient) cancelled() string { + f.mu.Lock() + defer f.mu.Unlock() + return f.cancelledStream +} + +func (f *fakeClient) WorkloadRCA(_ context.Context, _, _, ns, name, _ string) (*api.WorkloadRCA, error) { + f.calls++ + f.lastRCARef = ns + "/" + name + if f.rca == nil { + return &api.WorkloadRCA{Namespace: ns, Name: name}, f.err + } + return f.rca, f.err +} + +func (f *fakeClient) WorkloadChanges(_ context.Context, _, _, ns, name string, _, _ int) (*api.Changes, error) { + f.calls++ + f.lastChangesRef = ns + "/" + name + if f.changes == nil { + return &api.Changes{}, f.err + } + return f.changes, f.err } func (f *fakeClient) Resources(_ context.Context, _, _, kind, ns string) ([]k8s.Resource, error) { @@ -63,16 +138,18 @@ func (f *fakeClient) SlowOperations(_ context.Context, _, _, _, _ string, _ int) return f.slowOps, f.err } -func (f *fakeClient) SearchLogs(_ context.Context, _ api.LogSearch) (*api.LogPage, error) { +func (f *fakeClient) SearchLogs(_ context.Context, req api.LogSearch) (*api.LogPage, error) { f.calls++ + f.lastLogService = req.ServiceName if f.logs == nil { return &api.LogPage{}, f.err } return f.logs, f.err } -func (f *fakeClient) ListTraces(_ context.Context, _ api.TraceListRequest) (*api.TracePage, error) { +func (f *fakeClient) ListTraces(_ context.Context, req api.TraceListRequest) (*api.TracePage, error) { f.calls++ + f.lastTraceQuery = req.Query if f.traces == nil { return &api.TracePage{}, f.err } @@ -297,21 +374,47 @@ func TestUnknownCommandIsReported(t *testing.T) { } } -// Detail exists for workload controllers only; opening a blank pane on a Pod would read as -// a failure rather than an absence. -func TestDescribeOnANonWorkloadExplainsInstead(t *testing.T) { - c := &fakeClient{rows: pods()} - m := newModel(t, c) +// A kind with no renderer says so rather than opening a pane the code cannot fill. Services +// are the case: the backend would answer, but there is nothing here that knows how to draw +// one, and a blank pane reads as a failure rather than an absence. +func TestDescribeOnAKindWithNoRendererExplainsInstead(t *testing.T) { + c := &fakeClient{rows: []k8s.Resource{ + {Kind: "Service", Namespace: "payments", Name: "checkout", Spec: `{"type":"ClusterIP"}`}, + }} + m := New(Options{Client: c, OrgID: "org1", ClusterID: "c1", Refresh: 10 * time.Millisecond}) + m2, _ := m.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) + m = m2.(Model) + m3, _ := m.Update(rowsMsg{data: dataset{ + table: view.TableFor("Service", c.rows, true), resources: c.rows}}) + m = m3.(Model) m = key(m, "d") if c.detailName != "" { - t.Errorf("a detail request was made for a Pod: %q", c.detailName) + t.Errorf("a detail request was made for a Service: %q", c.detailName) } if !strings.Contains(m.status, "no detail view") { t.Errorf("status = %q", m.status) } } +// Pods are the most-described object on the screen, and the pane covers them. +func TestDescribeOnAPodRequestsItsDetail(t *testing.T) { + c := &fakeClient{rows: pods()} + m := newModel(t, c) + next, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("d")}) + m = next.(Model) + if cmd == nil { + t.Fatal("pressing d on a Pod issued no request") + } + cmd() + if c.detailName == "" { + t.Error("no detail request was made for a Pod") + } + if strings.Contains(m.status, "no detail view") { + t.Errorf("Pod was refused: %q", m.status) + } +} + func TestDescribeOpensTheDetailPane(t *testing.T) { c := &fakeClient{ rows: []k8s.Resource{{Kind: "Deployment", Namespace: "payments", Name: "checkout", diff --git a/internal/tui/ask.go b/internal/tui/ask.go new file mode 100644 index 0000000..28fa531 --- /dev/null +++ b/internal/tui/ask.go @@ -0,0 +1,292 @@ +package tui + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + + "github.com/runtimez-com/runtimez-cli/internal/api" +) + +// The ask pane is the agent's investigation, live. It matters that it streams: an agent +// that thinks for forty seconds behind a blank screen is indistinguishable from one that +// has hung, and the early steps — which tool it reached for first — are usually the most +// informative part of the run. + +// askState is the conversation pane. +type askState struct { + input textinput.Model + lines []string + busy bool + streamID string + sessionID string + // cancel stops the local subscription. The server-side run is stopped separately, via + // CancelInvestigation: dropping the connection alone leaves the agent burning a slot. + cancel context.CancelFunc + frames chan api.StreamFrame + offset int +} + +type askFrameMsg struct { + frame api.StreamFrame + open bool +} + +type askAnswerMsg struct { + answer *api.AgentAnswer + err error +} + +// openAsk starts a conversation, seeded with whatever is selected. +func (m Model) openAsk() (tea.Model, tea.Cmd) { + if r, ok := m.selected(); ok { + m.scope = scopeOf(r) + } + + in := textinput.New() + in.Prompt = "" + in.CharLimit = 400 + if !m.scope.empty() { + in.SetValue("What is wrong with " + m.scope.ref() + "?") + } + in.Focus() + + m.ask = askState{input: in} + m.mode = modeAsk + if m.scope.empty() { + m.ask.lines = []string{metaStyle.Render("Ask about this cluster. Select a row first to ask about one workload.")} + } else { + m.ask.lines = []string{metaStyle.Render("Asking about " + m.scope.ref() + " — edit the question, then enter.")} + } + return m, textinput.Blink +} + +// submitAsk subscribes to the stream and then asks, in that order. The reverse races the +// first frames, and the steps that get lost are the early ones that explain what the agent +// decided to look at. +func (m Model) submitAsk() (tea.Model, tea.Cmd) { + question := strings.TrimSpace(m.ask.input.Value()) + if question == "" || m.ask.busy { + return m, nil + } + + o := m.opts + streamID := api.NewStreamID() + ctx, cancel := context.WithCancel(context.Background()) + frames := make(chan api.StreamFrame, 64) + + m.ask.busy = true + m.ask.streamID = streamID + m.ask.cancel = cancel + m.ask.frames = frames + m.ask.lines = append(m.ask.lines, "", keyStyle.Render("› ")+question) + m.ask.input.SetValue("") + + sessionID := m.ask.sessionID + go func() { + defer close(frames) + _ = o.Client.StreamInvestigation(ctx, o.OrgID, o.ClusterID, streamID, func(f api.StreamFrame) error { + select { + case frames <- f: + case <-ctx.Done(): + return ctx.Err() + } + return nil + }) + }() + + askCmd := func() tea.Msg { + a, err := o.Client.Ask(ctx, o.OrgID, o.ClusterID, api.AgentQuery{ + Query: question, + SessionID: sessionID, + StartSession: sessionID == "", + StreamID: streamID, + }) + return askAnswerMsg{answer: a, err: err} + } + return m, tea.Batch(waitFrame(frames), askCmd) +} + +// waitFrame turns the next frame on the channel into a message. Re-issued on every frame, +// which is how a Bubble Tea model consumes a stream without blocking its update loop. +func waitFrame(ch chan api.StreamFrame) tea.Cmd { + return func() tea.Msg { + f, open := <-ch + return askFrameMsg{frame: f, open: open} + } +} + +// cancelAsk stops the run on the server as well as locally. +func (m Model) cancelAsk() tea.Cmd { + if m.ask.cancel != nil { + m.ask.cancel() + } + o, streamID := m.opts, m.ask.streamID + if streamID == "" { + return nil + } + return func() tea.Msg { + // A fresh context: the one that was just cancelled cannot carry the cancel call. + ctx, done := context.WithTimeout(context.Background(), 10*time.Second) + defer done() + _ = o.Client.CancelInvestigation(ctx, o.OrgID, o.ClusterID, streamID) + return nil + } +} + +func (m Model) handleAskKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.Type { + case tea.KeyCtrlC: + // While a run is live, Ctrl-C means "stop the agent", not "quit the tool" — the + // same contract `rtz ask` has. A second press quits. + if m.ask.busy { + cmd := m.cancelAsk() + m.ask.busy = false + m.ask.lines = append(m.ask.lines, warnStyle.Render(" cancelled")) + return m, cmd + } + return m, tea.Quit + + case tea.KeyEsc: + var cmd tea.Cmd + if m.ask.busy { + cmd = m.cancelAsk() + } + m.mode = modeNormal + m.ask = askState{} + return m, cmd + + case tea.KeyEnter: + return m.submitAsk() + + case tea.KeyPgUp: + m.ask.offset -= 5 + if m.ask.offset < 0 { + m.ask.offset = 0 + } + return m, nil + + case tea.KeyPgDown: + m.ask.offset += 5 + return m, nil + } + + var cmd tea.Cmd + m.ask.input, cmd = m.ask.input.Update(msg) + return m, cmd +} + +// appendFrame renders one streamed frame into the transcript. +func (a *askState) appendFrame(f api.StreamFrame) { + switch f.Type { + case "step": + switch f.Phase { + case "thinking": + if f.Thought != "" { + a.lines = append(a.lines, fmt.Sprintf(" %d. %s", f.Step, f.Thought)) + } + if f.Tool != "" { + a.lines = append(a.lines, metaStyle.Render(" → "+f.Tool+" "+truncateAsk(f.Args, 60))) + } + case "observation": + if f.ResultSummary != "" { + a.lines = append(a.lines, metaStyle.Render(" ← "+truncateAsk(f.ResultSummary, 100))) + } + } + case "error": + a.lines = append(a.lines, errStyle.Render(" ! "+f.Message)) + case "cancelled": + a.lines = append(a.lines, warnStyle.Render(" cancelled")) + } +} + +// appendAnswer renders the finished investigation. +func (a *askState) appendAnswer(ans *api.AgentAnswer, err error) { + switch { + case errors.Is(err, context.Canceled): + return // the cancel line is already there + case err != nil: + a.lines = append(a.lines, errStyle.Render(" error: "+err.Error())) + return + case ans == nil: + a.lines = append(a.lines, metaStyle.Render(" no answer was returned")) + return + } + + if ans.SessionID != "" { + a.sessionID = ans.SessionID + } + a.lines = append(a.lines, "") + if v := ans.Verdict; v != nil && v.Headline != "" { + a.lines = append(a.lines, headerStyle.Render(v.Headline)) + if v.Confidence != "" { + // Confidence is HIGH/MEDIUM/LOW, never a percentage — rendering it as one + // would invent a precision the agent never claimed. + a.lines = append(a.lines, metaStyle.Render(" confidence "+v.Confidence)) + } + } + for _, line := range strings.Split(strings.TrimRight(ans.Answer, "\n"), "\n") { + a.lines = append(a.lines, line) + } + if ans.HitStepLimit { + a.lines = append(a.lines, + warnStyle.Render(" the agent hit its step limit — this answer is partial")) + } +} + +func truncateAsk(s string, max int) string { + s = strings.ReplaceAll(s, "\n", " ") + if len(s) <= max { + return s + } + return s[:max-1] + "…" +} + +// askView draws the transcript with the prompt pinned to the bottom. +func (m Model) askView() string { + height := m.bodyHeight() + if height < 3 { + height = 3 + } + body := height - 2 // one line for the prompt, one for the separator + + lines := m.ask.lines + start := len(lines) - body - m.ask.offset + if start < 0 { + start = 0 + } + end := start + body + if end > len(lines) { + end = len(lines) + } + + var b strings.Builder + for _, l := range lines[start:end] { + b.WriteString(l + "\n") + } + for i := end - start; i < body; i++ { + b.WriteByte('\n') + } + + prompt := keyStyle.Render("› ") + m.ask.input.View() + if m.ask.busy { + prompt = metaStyle.Render(" working… ") + warnStyle.Render("ctrl+c") + metaStyle.Render(" stops the agent") + } + b.WriteString(prompt) + + title := "ask" + if !m.scope.empty() { + title += " · " + m.scope.ref() + } + return m.tabStrip() + "\n" + + panel(title, b.String(), m.screenWidth()) + "\n" + + footerStyle.Render(" "+keyStyle.Render("enter")+" send "+ + keyStyle.Render("ctrl+c")+" stop "+ + keyStyle.Render("esc")+" close "+ + keyStyle.Render("pgup/pgdn")+" scroll") +} diff --git a/internal/tui/chrome_test.go b/internal/tui/chrome_test.go new file mode 100644 index 0000000..2ef0b99 --- /dev/null +++ b/internal/tui/chrome_test.go @@ -0,0 +1,250 @@ +package tui + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +// A column sorts the way it reads or it is worse than unsorted: an operator scanning for +// the oldest pod trusts the arrow, and a lexicographic "10m before 9m" quietly lies. +func TestSortRecoversTheTypeTheTextEncodes(t *testing.T) { + cases := []struct{ a, b string }{ + {"9m", "10m"}, // durations, not strings + {"45s", "2m"}, // across units + {"3h", "2d"}, // across units again + {"370Mi", "1Gi"}, // byte suffixes + {"LOW", "HIGH"}, // severity has an order, and it is not alphabetical + {"MEDIUM", "CRITICAL"}, + {"2", "10"}, // plain counts + {"1/3", "2/3"}, // ready ratios sort by how many are up + } + for _, c := range cases { + rows := [][]string{{c.b}, {c.a}} + vis := []int{0, 1} + sortRows(rows, vis, 0, false) + if rows[vis[0]][0] != c.a { + t.Errorf("ascending %q vs %q put %q first", c.a, c.b, rows[vis[0]][0]) + } + } +} + +// An absent value is not a zero. Sorting "" to the top of an ascending latency column +// would put the rows we know nothing about where the fastest ones belong. +func TestAbsentValuesSortAfterRealOnes(t *testing.T) { + rows := [][]string{{""}, {"5"}, {"-"}, {"1"}} + vis := []int{0, 1, 2, 3} + sortRows(rows, vis, 0, false) + if got := rows[vis[0]][0]; got != "1" { + t.Fatalf("first = %q, want 1", got) + } + if got := rows[vis[1]][0]; got != "5" { + t.Fatalf("second = %q, want 5", got) + } +} + +func TestSortCyclesThroughColumnsAndBackToServerOrder(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + cols := len(m.data.table.Headers) + + for i := 0; i < cols; i++ { + m = key(m, "s") + if m.sortCol != i { + t.Fatalf("after %d presses sortCol = %d, want %d", i+1, m.sortCol, i) + } + } + // One more press has to reach the unsorted state, not wrap straight to column 0 — + // otherwise the server's own order becomes unreachable once you leave it. + m = key(m, "s") + if m.sortCol != -1 { + t.Fatalf("sortCol = %d after the last column, want -1", m.sortCol) + } + if !strings.Contains(m.status, "server") { + t.Errorf("returning to the unsorted state was not announced: %q", m.status) + } +} + +func TestSortMarkerNamesTheSortedColumnAndItsDirection(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + if strings.Contains(m.View(), "↑") || strings.Contains(m.View(), "↓") { + t.Error("unsorted table drew a sort arrow") + } + m = key(m, "s") // NAMESPACE + if !strings.Contains(m.View(), "NAMESPACE ↑") { + t.Errorf("ascending marker missing:\n%s", m.View()) + } + m = key(m, "i") + if !strings.Contains(m.View(), "NAMESPACE ↓") { + t.Errorf("inverted marker missing:\n%s", m.View()) + } +} + +func TestInvertWithoutASortSaysSoRatherThanDoingNothing(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m = key(m, "i") + if !strings.Contains(m.status, "press s") { + t.Errorf("status = %q", m.status) + } +} + +func TestWideRevealsTheExtraColumns(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + if strings.Contains(m.View(), "CONTROLLED BY") { + t.Error("wide columns shown before w was pressed") + } + m = key(m, "w") + out := m.View() + for _, want := range []string{"NODE", "CONTROLLED BY"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q after w:\n%s", want, out) + } + } + m = key(m, "w") + if strings.Contains(m.View(), "CONTROLLED BY") { + t.Error("w did not toggle back") + } +} + +func TestHistoryWalksBackAndForward(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m = typeIn(key(m, ":"), "deploy") + m = submit(t, m) + if m.view.Title != "Deployments" { + t.Fatalf("view = %q", m.view.Title) + } + + m = key(m, "[") + if m.view.Title != "Pods" { + t.Fatalf("back landed on %q, want Pods", m.view.Title) + } + m = key(m, "]") + if m.view.Title != "Deployments" { + t.Fatalf("forward landed on %q, want Deployments", m.view.Title) + } + m = key(m, "]") + if !strings.Contains(m.status, "no later view") { + t.Errorf("walking off the end was silent: %q", m.status) + } +} + +func TestAllNamespacesKeyClearsTheScope(t *testing.T) { + c := &fakeClient{rows: pods()} + m := newModel(t, c) + m = submit(t, typeIn(key(m, ":"), "ns payments")) + if m.namespace != "payments" { + t.Fatalf("namespace = %q", m.namespace) + } + m = key(m, "0") + if m.namespace != "" { + t.Fatalf("0 left namespace %q", m.namespace) + } +} + +// A screen that says nothing while the data underneath has stopped moving is how someone +// concludes an incident is over. +func TestPausedStateIsVisibleOnScreen(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + if !strings.Contains(m.View(), "live") { + t.Errorf("no live marker:\n%s", m.View()) + } + m = key(m, "p") + out := m.View() + if !strings.Contains(out, "paused") || strings.Contains(out, "● live") { + t.Errorf("paused screen still reads as live:\n%s", out) + } +} + +// The frame is decoration; the rows are not. On a terminal too short or too narrow for the +// chrome the data has to survive, not the box. +func TestChromeYieldsToTheDataOnASmallTerminal(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + + short, _ := m.Update(tea.WindowSizeMsg{Width: 120, Height: 16}) + out := short.(Model).View() + if strings.Contains(out, "Context:") { + t.Errorf("context panel survived a 16-row terminal:\n%s", out) + } + if !strings.Contains(out, "checkout-1") { + t.Errorf("rows lost on a short terminal:\n%s", out) + } + + narrow, _ := m.Update(tea.WindowSizeMsg{Width: 24, Height: 30}) + out = narrow.(Model).View() + if strings.Contains(out, "╭") { + t.Errorf("box drawn at 24 columns:\n%s", out) + } +} + +// An off-by-one in the border arithmetic is invisible in a screenshot and glaring on a real +// terminal, where the right-hand edge zig-zags. +func TestEveryChromeLineIsExactlyTheTerminalWidth(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + for _, w := range []int{80, 100, 132, 180} { + sized, _ := m.Update(tea.WindowSizeMsg{Width: w, Height: 34}) + for i, line := range strings.Split(sized.(Model).View(), "\n") { + if !strings.ContainsAny(line, "╭│╰") { + continue // only the framed lines carry the promise + } + if got := lipgloss.Width(line); got != w { + t.Errorf("width %d: line %d is %d columns:\n%s", w, i, got, line) + } + } + } +} + +// Every key the chrome advertises has to be a key the model accepts. A hint bar that names +// a binding the binary does not have sends someone hunting during the hour they can least +// afford it. +func TestAdvertisedKeysAreAllHandled(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + out := m.View() + for _, k := range []string{"s", "i", "w", "d", "0", "p", "?", "q", "l", "r"} { + if !strings.Contains(out, k) { + continue + } + before := m + after := key(m, k) + if k == "q" { + continue // quits; nothing to compare + } + if after.status == before.status && after.view.Title == before.view.Title && + after.mode == before.mode && after.sortCol == before.sortCol && + after.wide == before.wide && after.paused == before.paused && + after.loading == before.loading { + t.Errorf("key %q is advertised but changed nothing", k) + } + } +} + +func TestScoreColumnsAreLeftUncoloured(t *testing.T) { + // Higher is worse on a risk score and better on an upgrade-readiness score, so one + // colour rule would be confidently wrong on one of them. + if got := cellTone("SCORE", "95"); got != toneNone { + t.Errorf("SCORE tone = %v, want toneNone", got) + } + if got := cellTone("STATUS", "CrashLoopBackOff"); got != toneBad { + t.Errorf("CrashLoopBackOff tone = %v, want toneBad", got) + } + if got := cellTone("READY", "0/3"); got != toneBad { + t.Errorf("0/3 tone = %v, want toneBad", got) + } + if got := cellTone("READY", "2/3"); got != toneWarn { + t.Errorf("2/3 tone = %v, want toneWarn", got) + } + if got := cellTone("RESTARTS", "0"); got != toneNone { + t.Errorf("0 restarts tone = %v, want toneNone", got) + } +} + +// A finished pod is evidence, not noise: it stays listed, dimmed, rather than disappearing. +func TestCompletedRowsAreMutedNotHidden(t *testing.T) { + headers := []string{"NAME", "STATUS"} + if !rowMuted(headers, []string{"backup-1", "Succeeded"}) { + t.Error("a Succeeded row was not muted") + } + if rowMuted(headers, []string{"api-7", "Running"}) { + t.Error("a Running row was muted") + } +} diff --git a/internal/tui/paint.go b/internal/tui/paint.go new file mode 100644 index 0000000..d5d55b8 --- /dev/null +++ b/internal/tui/paint.go @@ -0,0 +1,124 @@ +package tui + +import ( + "strconv" + "strings" +) + +// tone is what an operator should feel about a cell. Colour is derived from it rather than +// chosen at each call site, so "red" means the same thing on every screen. +type tone int + +const ( + toneNone tone = iota + toneOK + toneWarn + toneBad + toneMuted // finished, or otherwise no longer worth attention +) + +// statusWords maps the vocabulary the API actually returns. Anything unrecognised stays +// uncoloured — inventing a colour for a word we have not seen would assert a health +// judgement we did not make. +var statusWords = map[string]tone{ + "RUNNING": toneOK, "READY": toneOK, "ACTIVE": toneOK, "HEALTHY": toneOK, + "BOUND": toneOK, "OK": toneOK, "PASS": toneOK, "PASSED": toneOK, "TRUE": toneOK, + "AVAILABLE": toneOK, "LOW": toneOK, "NONE": toneOK, "CLEAN": toneOK, + + "SUCCEEDED": toneMuted, "COMPLETED": toneMuted, "COMPLETE": toneMuted, + + "PENDING": toneWarn, "CONTAINERCREATING": toneWarn, "PODINITIALIZING": toneWarn, + "INIT": toneWarn, "PROGRESSING": toneWarn, "WARN": toneWarn, "WARNING": toneWarn, + "MEDIUM": toneWarn, "DEGRADED": toneWarn, "NOTREADY": toneWarn, "TERMINATING": toneWarn, + "UNSCHEDULABLE": toneWarn, "PARTIAL": toneWarn, "STALE": toneWarn, + + "FAILED": toneBad, "ERROR": toneBad, "CRASHLOOPBACKOFF": toneBad, + "IMAGEPULLBACKOFF": toneBad, "ERRIMAGEPULL": toneBad, "OOMKILLED": toneBad, + "EVICTED": toneBad, "CRITICAL": toneBad, "HIGH": toneBad, "FAIL": toneBad, + "FAILING": toneBad, "FALSE": toneBad, "BLOCKED": toneBad, "UNKNOWN": toneBad, +} + +// statusColumns are the headers whose value is a verdict rather than a measurement. +var statusColumns = map[string]bool{ + "STATUS": true, "PHASE": true, "STATE": true, "HEALTH": true, "SEVERITY": true, + "VERDICT": true, "RESULT": true, "RISK": true, "LEVEL": true, "TIER": true, + "READINESS": true, "CONDITION": true, +} + +// cellTone reads one cell in the light of its column header. +// +// Deliberately NOT coloured: any column named SCORE. A risk score is worse when it is +// higher and an upgrade-readiness score is better when it is higher, so one rule would be +// wrong on one of them — and a confidently wrong colour is read as a fact. +func cellTone(header, value string) tone { + v := strings.TrimSpace(value) + if v == "" || v == "-" || v == "" || v == "" { + return toneNone + } + h := strings.ToUpper(strings.TrimSpace(header)) + + switch { + case statusColumns[h]: + return statusWords[strings.ToUpper(v)] + + case h == "RESTARTS": + n, err := strconv.Atoi(v) + switch { + case err != nil: + return toneNone + case n == 0: + return toneNone + case n < 5: + return toneWarn + default: + return toneBad + } + + case h == "READY": + return readyTone(v) + + case h == "ERRORS", h == "ERROR RATE", h == "FAILURES": + if f, err := strconv.ParseFloat(strings.TrimSuffix(v, "%"), 64); err == nil && f > 0 { + return toneWarn + } + return toneNone + } + return toneNone +} + +// readyTone reads a "3/5" ratio. Zero of something wanted is an outage; short of the +// target is a wobble; matching is fine. +func readyTone(v string) tone { + num, den, ok := strings.Cut(v, "/") + if !ok { + return toneNone + } + r, err1 := strconv.Atoi(strings.TrimSpace(num)) + d, err2 := strconv.Atoi(strings.TrimSpace(den)) + if err1 != nil || err2 != nil || d <= 0 { + return toneNone + } + switch { + case r >= d: + return toneOK + case r == 0: + return toneBad + default: + return toneWarn + } +} + +// rowMuted reports whether a whole row has finished its life — a completed Job pod, say. +// Those stay listed (they are evidence) but must not compete for attention with what is +// still running. +func rowMuted(headers, row []string) bool { + for i, h := range headers { + if i >= len(row) || !statusColumns[strings.ToUpper(strings.TrimSpace(h))] { + continue + } + if statusWords[strings.ToUpper(strings.TrimSpace(row[i]))] == toneMuted { + return true + } + } + return false +} diff --git a/internal/tui/panel.go b/internal/tui/panel.go new file mode 100644 index 0000000..fe75ad2 --- /dev/null +++ b/internal/tui/panel.go @@ -0,0 +1,106 @@ +package tui + +import ( + "strings" + + "github.com/charmbracelet/lipgloss" +) + +// The chrome is drawn by hand rather than with lipgloss borders because the title sits IN +// the top rule — "╭─ pods [186] ─────╮" — which a plain border cannot express. Doing it +// here keeps the arithmetic in one place instead of at every call site. + +const ( + minPanelWidth = 30 // below this a box costs more columns than it earns + borderCost = 4 // two border runes plus a space of padding either side +) + +// panel wraps body in a titled box exactly width columns wide. Lines longer than the box +// are clipped, never wrapped: a wrapped table row reads as two rows. +func panel(title, body string, width int) string { + if width < minPanelWidth { + // Too narrow to frame — the content is what matters, so give it every column. + return body + } + inner := width - borderCost + + var b strings.Builder + b.WriteString(topRule(title, width)) + b.WriteByte('\n') + for _, line := range strings.Split(body, "\n") { + line = clip(line, inner) + pad := inner - lipgloss.Width(line) + if pad < 0 { + pad = 0 + } + b.WriteString(borderStyle.Render("│") + " " + line + strings.Repeat(" ", pad) + " " + borderStyle.Render("│")) + b.WriteByte('\n') + } + b.WriteString(borderStyle.Render("╰" + strings.Repeat("─", width-2) + "╯")) + return b.String() +} + +// topRule is "╭─ title ────╮", with the title dropped when it would leave no rule at all. +func topRule(title string, width int) string { + if title == "" { + return borderStyle.Render("╭" + strings.Repeat("─", width-2) + "╮") + } + title = clip(title, width-8) + // "╭─ " + title + " " + fill + "╮" must come to exactly width. + fill := width - 5 - lipgloss.Width(title) + if fill < 1 { + return borderStyle.Render("╭" + strings.Repeat("─", width-2) + "╮") + } + return borderStyle.Render("╭─ ") + headerStyle.Render(title) + " " + + borderStyle.Render(strings.Repeat("─", fill)+"╮") +} + +// panelHeight is how many rows a panel of n body lines occupies. +func panelHeight(bodyLines, width int) int { + if width < minPanelWidth { + return bodyLines + } + return bodyLines + 2 +} + +// columns lays blocks side by side with a gap, for the key-hint columns in the header. +func columns(gap int, blocks ...string) string { + rendered := make([][]string, 0, len(blocks)) + widths := make([]int, 0, len(blocks)) + height := 0 + for _, blk := range blocks { + if blk == "" { + continue + } + lines := strings.Split(blk, "\n") + w := 0 + for _, l := range lines { + if lw := lipgloss.Width(l); lw > w { + w = lw + } + } + rendered = append(rendered, lines) + widths = append(widths, w) + if len(lines) > height { + height = len(lines) + } + } + + var b strings.Builder + for row := 0; row < height; row++ { + for i, lines := range rendered { + cell := "" + if row < len(lines) { + cell = lines[row] + } + b.WriteString(cell) + if i < len(rendered)-1 { + b.WriteString(strings.Repeat(" ", widths[i]-lipgloss.Width(cell)+gap)) + } + } + if row < height-1 { + b.WriteByte('\n') + } + } + return b.String() +} diff --git a/internal/tui/render.go b/internal/tui/render.go index 0a52147..797f622 100644 --- a/internal/tui/render.go +++ b/internal/tui/render.go @@ -8,104 +8,357 @@ import ( "github.com/charmbracelet/lipgloss" "github.com/runtimez-com/runtimez-cli/internal/k8s" + "github.com/runtimez-com/runtimez-cli/internal/version" "github.com/runtimez-com/runtimez-cli/internal/view" ) -// View renders the whole screen: a header naming what you are looking at, the body, and a -// footer carrying state and the next available keys. +// Screen layout, top to bottom: a tab strip naming what is in focus, a titled panel of +// context and keys, the table in its own titled panel, then hints and a status line. +// +// Every key drawn in the chrome is a key handleNormalKey actually accepts. A hint bar that +// advertises a binding the binary does not have is worse than no hint bar — it sends the +// operator looking for a feature during the one hour they cannot afford to. + +const logo = "┬─┐┬ ┬┌┐┌┌┬┐┬┌┬┐┌─┐┌─┐\n" + + "├┬┘│ ││││ │ ││││├┤ ┌─┘\n" + + "┴└─└─┘┘└┘ ┴ ┴┴ ┴└─┘└─┘" + +// View renders the whole screen. func (m Model) View() string { if m.mode == modeHelp { return m.helpView() } + if m.mode == modeAsk { + return m.askView() + } if m.mode == modeDetail && m.detail != nil { return m.detailView() } var b strings.Builder - b.WriteString(m.header()) - b.WriteString("\n\n") - b.WriteString(m.body()) - b.WriteString("\n") + b.WriteString(m.tabStrip()) + b.WriteByte('\n') + if head := m.contextPanel(); head != "" { + b.WriteString(head) + b.WriteByte('\n') + } + b.WriteString(m.bodyPanel()) + b.WriteByte('\n') b.WriteString(m.footer()) return b.String() } -func (m Model) header() string { +// screenWidth is the usable column count, with a floor so a zero-size model (no +// WindowSizeMsg yet) still renders something readable rather than nothing. +func (m Model) screenWidth() int { + if m.width < 20 { + return 100 + } + return m.width +} + +func (m Model) tabStrip() string { + left := chipStyle.Render(" "+m.view.Title+" ") + " " + + metaStyle.Render(m.scopeLabel()) + m.breadcrumb() + " " + + footerStyle.Render(keyStyle.Render(":")+" commands "+ + keyStyle.Render("/")+" filter "+ + keyStyle.Render("?")+" help") + + right := metaStyle.Render(m.identity() + " · rtz " + version.Version) + return spread(left, right, m.screenWidth()) +} + +func (m Model) identity() string { + if m.opts.ContextName != "" { + return m.opts.ContextName + } + return "no context" +} + +// breadcrumb names the workload the drill-down keys are acting on. Without it, a logs +// screen scoped to one pod is indistinguishable from the cluster-wide one. +func (m Model) breadcrumb() string { + if m.scope.empty() { + return "" + } + marker := valueStyle.Render(m.scope.ref()) + if !m.view.scopable { + // Say plainly that this screen ignores the scope rather than implying it applies. + return metaStyle.Render(" · scope ") + marker + metaStyle.Render(" (not applied here)") + } + return metaStyle.Render(" · ") + marker +} + +func (m Model) scopeLabel() string { + if m.namespace == "" { + return "all namespaces" + } + return "namespace " + m.namespace +} + +// contextPanel is the box naming what you are pointed at and which keys act on it. It is +// dropped on a short terminal, where rows are worth more than orientation. +func (m Model) contextPanel() string { + if m.height > 0 && m.height < 20 { + return "" + } + cluster := m.opts.ClusterName if cluster == "" { cluster = m.opts.ClusterID } - - title := headerStyle.Render("rtz") + " " + headerStyle.Render(m.view.Title) ns := m.namespace if ns == "" { - ns = "all namespaces" + ns = "" + } + count := "—" + if m.data.table != nil { + count = k8s.Itoa(len(m.data.table.Rows)) + } + + scopeText := metaStyle.Render(" — select a row") + if !m.scope.empty() { + // Clipped: a long pod name would otherwise push the key columns off the panel and + // cost every hint its label. The full reference is in the tab strip above. + scopeText = valueStyle.Render(clip(m.scope.ref(), 30)) + if m.scope.Service != "" && m.scope.Service != m.scope.Name { + scopeText += metaStyle.Render(" → " + clip(m.scope.Service, 22)) + } } - meta := metaStyle.Render(fmt.Sprintf("%s · %s · %s", cluster, ns, m.opts.APIURL)) - return title + " " + meta + + facts := field("Context", valueStyle.Render(m.identity())) + "\n" + + field("Cluster", valueStyle.Render(cluster)) + "\n" + + field("API", urlStyle.Render(m.opts.APIURL)) + "\n" + + field("Namespace", valueStyle.Render(ns)) + "\n" + + field("Resource", valueStyle.Render(m.view.Title)) + "\n" + + field("Scope", scopeText) + "\n" + + field("Count", valueStyle.Render(count)) + + blocks := []string{facts, keyBlock( + [2]string{"↵", "describe"}, + [2]string{"l", "its logs"}, + [2]string{"r", "its root cause"}, + [2]string{"c", "its changes"}, + [2]string{"t", "its traces"}, + [2]string{"a", "ask about it"}, + ), keyBlock( + [2]string{"/", "filter"}, + [2]string{":", "command"}, + [2]string{"s", "sort column"}, + [2]string{"i", "invert sort"}, + [2]string{"w", "wide columns"}, + [2]string{"0", "all namespaces"}, + ), keyBlock( + [2]string{"p", "pause refresh"}, + [2]string{"ctrl+r", "refresh now"}, + [2]string{"g G", "top / bottom"}, + [2]string{"[ ]", "back / forward"}, + [2]string{"esc", "clear filter/scope"}, + [2]string{"q", "quit"}, + )} + + body := columns(3, blocks...) + // The wordmark is the first thing to go: it is decoration, and the key columns are not. + if m.screenWidth() >= 118 { + body = alignRight(body, logoStyle.Render(logo), m.screenWidth()-borderCost) + } + return panel(cluster, body, m.screenWidth()) +} + +func field(label, value string) string { + return labelStyle.Render(lipgloss.NewStyle().Width(11).Render(label+":")) + value +} + +// keyBlock sizes its key column to its own widest key, so a block holding only short keys +// is not padded out to make room for one in a different block. +func keyBlock(rows ...[2]string) string { + w := 0 + for _, r := range rows { + if n := lipgloss.Width(r[0]); n > w { + w = n + } + } + lines := make([]string, 0, len(rows)) + for _, r := range rows { + lines = append(lines, keyStyle.Render(lipgloss.NewStyle().Width(w+1).Render(r[0]))+metaStyle.Render(r[1])) + } + return strings.Join(lines, "\n") +} + +// bodyPanel is the data, framed and titled with what it is and how much of it there is. +func (m Model) bodyPanel() string { + title := m.view.Title + if m.data.table != nil { + if n, total := len(m.visible), len(m.data.table.Rows); n != total { + title += fmt.Sprintf(" [%d/%d]", n, total) + } else { + title += fmt.Sprintf(" [%d]", total) + } + } + return panel(title, m.body(), m.screenWidth()) } func (m Model) body() string { + height := m.bodyHeight() + pad := func(s string) string { + // Keep the frame a constant height so the screen does not jump between an error, + // a loading state and data. + lines := strings.Count(s, "\n") + 1 + if lines < height+1 { + s += strings.Repeat("\n", height+1-lines) + } + return s + } + switch { case m.err != nil: - return errStyle.Render("error: " + m.err.Error()) + return pad(errStyle.Render("error: " + m.err.Error())) + case m.data.body != "": + // Some screens are prose, not rows — a root cause is a narrative. + return pad(clipLines(m.data.body, height+1)) case m.loading && len(m.visible) == 0: - return metaStyle.Render("loading…") + return pad(metaStyle.Render("loading…")) case m.data.table == nil || len(m.data.table.Rows) == 0: - return metaStyle.Render("No resources found.") + msg := "No resources found." + if m.data.table != nil && m.data.table.EmptyMessage != "" { + msg = m.data.table.EmptyMessage + } + return pad(metaStyle.Render(msg)) case len(m.visible) == 0: // An empty result and a filter that matched nothing are different facts. - return metaStyle.Render(fmt.Sprintf("No rows match %q — esc clears the filter.", m.filter)) + return pad(metaStyle.Render(fmt.Sprintf("No rows match %q — esc clears the filter.", m.filter))) } - return renderTable(m.data.table, m.visible, m.cursor, m.offset, m.width, m.bodyHeight()) + + return pad(renderTable(m.activeTable(), tableOpts{ + visible: m.visible, cursor: m.cursor, offset: m.offset, + width: m.screenWidth() - borderCost, height: height, + sortCol: m.sortCol, sortDesc: m.sortDesc, + })) } func (m Model) footer() string { // While typing, the input line replaces the hints — that is what the user is looking at. switch m.mode { case modeFilter: - return keyStyle.Render("/") + m.input.View() + return keyStyle.Render(" /") + m.input.View() case modeCommand: - return keyStyle.Render(":") + m.input.View() + return keyStyle.Render(" :") + m.input.View() } + hints := " " + strings.Join([]string{ + hint(":", "command"), hint("/", "filter"), hint("d", "describe"), + hint("l", "logs"), hint("r", "rca"), hint("c", "changes"), hint("t", "traces"), + hint("a", "ask"), hint("s", "sort"), hint("w", "wide"), + hint("?", "help"), hint("q", "quit"), + }, " ") + var left []string - if n := len(m.visible); m.data.table != nil { - total := len(m.data.table.Rows) + if m.data.table != nil { + n, total := len(m.visible), len(m.data.table.Rows) if n == total { - left = append(left, fmt.Sprintf("%d rows", total)) + left = append(left, fmt.Sprintf("%d %s", total, plural(total, "row"))) } else { - left = append(left, fmt.Sprintf("%d of %d rows", n, total)) + left = append(left, fmt.Sprintf("%d of %d %s", n, total, plural(total, "row"))) } } if m.filter != "" { left = append(left, "filter: "+m.filter) } + if m.wide { + left = append(left, "wide") + } if !m.lastUpdated.IsZero() { left = append(left, "updated "+k8s.Duration(sinceUpdate(m))+" ago") } - if m.paused { - left = append(left, warnStyle.Render("paused")) + + status := footerStyle.Render(" " + strings.Join(left, " · ")) + if m.data.notice != "" { + status += " " + warnStyle.Render(m.data.notice) } - if m.loading { - left = append(left, "loading…") + if m.status != "" { + status += " " + warnStyle.Render(m.status) } - status := "" - if m.status != "" { - status = " " + warnStyle.Render(m.status) + return hints + "\n" + spread(status, m.liveMarker()+" ", m.screenWidth()) +} + +// liveMarker says whether what is on screen is still tracking the cluster. "paused" has to +// be visible: a stale screen read as live is how someone concludes an incident is over. +func (m Model) liveMarker() string { + switch { + case m.err != nil: + return errStyle.Render("● error") + case m.paused: + return warnStyle.Render("❚❚ paused") + case m.loading: + return metaStyle.Render("◌ loading") + default: + return okStyle.Render("● live") } +} - hints := footerStyle.Render(strings.Join([]string{ - keyStyle.Render(":") + "cmd", - keyStyle.Render("/") + "filter", - keyStyle.Render("d") + "escribe", - keyStyle.Render("p") + "ause", - keyStyle.Render("?") + "help", - keyStyle.Render("q") + "uit", - }, " ")) +// clipLines keeps a prose body inside the pane and says when it was cut. +func clipLines(body string, max int) string { + lines := strings.Split(body, "\n") + if len(lines) <= max { + return body + } + lines = lines[:max-1] + lines = append(lines, metaStyle.Render("… truncated — the flag command prints it all")) + return strings.Join(lines, "\n") +} - return footerStyle.Render(strings.Join(left, " · ")) + status + "\n" + hints +func hint(key, label string) string { + return keyStyle.Render(key) + footerStyle.Render(" "+label) +} + +func plural(n int, word string) string { + if n == 1 { + return word + } + return word + "s" +} + +// alignRight puts a multi-line block flush against the right edge of another, top-aligned. +func alignRight(body, right string, width int) string { + rightLines := strings.Split(right, "\n") + rw := 0 + for _, l := range rightLines { + if w := lipgloss.Width(l); w > rw { + rw = w + } + } + bodyLines := strings.Split(body, "\n") + bw := 0 + for _, l := range bodyLines { + if w := lipgloss.Width(l); w > bw { + bw = w + } + } + if bw+rw+2 > width { + return body + } + for i := range bodyLines { + if i >= len(rightLines) { + continue + } + pad := width - lipgloss.Width(bodyLines[i]) - lipgloss.Width(rightLines[i]) + if pad < 1 { + pad = 1 + } + bodyLines[i] += strings.Repeat(" ", pad) + rightLines[i] + } + return strings.Join(bodyLines, "\n") +} + +// spread pushes right to the right-hand edge, degrading to a single space when the two +// halves do not both fit. +func spread(left, right string, width int) string { + gap := width - lipgloss.Width(left) - lipgloss.Width(right) + if gap < 1 { + gap = 1 + } + return left + strings.Repeat(" ", gap) + right } func (m Model) detailView() string { @@ -114,28 +367,35 @@ func (m Model) detailView() string { body := buf.String() // Keep the pane inside the window; the detail of a big workload is longer than a screen. - if m.height > 4 { + if m.height > 6 { lines := strings.Split(body, "\n") - if len(lines) > m.height-4 { - lines = lines[:m.height-4] - lines = append(lines, metaStyle.Render(" … truncated — use `rtz describe "+m.detailRef+"` for the full output")) + if len(lines) > m.height-6 { + lines = lines[:m.height-6] + lines = append(lines, metaStyle.Render("… truncated — `rtz describe "+m.detailRef+"` prints it all")) } body = strings.Join(lines, "\n") } - return headerStyle.Render("rtz describe ") + headerStyle.Render(m.detailRef) + "\n\n" + - body + "\n" + footerStyle.Render(keyStyle.Render("esc")+" back "+keyStyle.Render("q")+" back") + return m.tabStrip() + "\n" + + panel("describe "+m.detailRef, body, m.screenWidth()) + "\n" + + footerStyle.Render(" "+keyStyle.Render("esc")+" back "+keyStyle.Render("q")+" back") } func (m Model) helpView() string { - rows := [][2]string{ + keys := [][2]string{ {"↑ ↓ / j k", "move"}, {"pgup pgdn", "page"}, {"g / G", "top / bottom"}, {"enter, d", "describe the selected workload"}, {"/", "filter the visible rows"}, {":", "command bar"}, - {"esc", "clear the filter, or close a pane"}, + {"s / i", "sort by the next column / invert the order"}, + {"w", "wide columns, when the view has extras"}, + {"0", "clear the namespace scope"}, + {"[ / ]", "back / forward through the views you visited"}, + {"l r c t", "the selection's logs, root cause, changes, traces"}, + {"a", "ask the agent about the selection"}, + {"esc", "clear the filter, then the scope, then close a pane"}, {"p", "pause or resume auto-refresh"}, {"ctrl+r", "refresh now"}, {"?", "this help"}, @@ -143,28 +403,29 @@ func (m Model) helpView() string { } var b strings.Builder - b.WriteString(headerStyle.Render("Keys") + "\n\n") - for _, r := range rows { - b.WriteString(" " + keyStyle.Render(lipgloss.NewStyle().Width(12).Render(r[0])) + r[1] + "\n") + b.WriteString(headerStyle.Render("Keys") + "\n") + for _, r := range keys { + b.WriteString(keyStyle.Render(lipgloss.NewStyle().Width(12).Render(r[0])) + r[1] + "\n") } - - b.WriteString("\n" + headerStyle.Render("Commands") + "\n\n") + b.WriteString("\n" + headerStyle.Render("Commands") + "\n") for _, c := range [][2]string{ {":pods, :deploy, :sts, :ds", "resource views"}, {":svc, :ing, :nodes, :jobs", "resource views"}, {":all", "every kind"}, - {":risk, :signals, :changes", "reliability views"}, + {":triage", "what is failing right now"}, + {":risk, :rca, :signals, :changes", "reliability views"}, {":logs, :traces", "observability views"}, {":ns ", "scope to a namespace (bare :ns clears it)"}, {":q", "quit"}, } { - b.WriteString(" " + keyStyle.Render(lipgloss.NewStyle().Width(26).Render(c[0])) + c[1] + "\n") + b.WriteString(keyStyle.Render(lipgloss.NewStyle().Width(26).Render(c[0])) + c[1] + "\n") } - b.WriteString("\n" + metaStyle.Render( - "Every view here has a flag equivalent — :deploy is `rtz get deploy`, d is `rtz describe`.") + "\n") - b.WriteString("\n" + footerStyle.Render("press any key to return")) - return b.String() + "Every view here has a flag equivalent — :deploy is `rtz get deploy`, d is `rtz describe`.")) + + return m.tabStrip() + "\n" + + panel("keys", b.String(), m.screenWidth()) + "\n" + + footerStyle.Render(" press any key to return") } // sinceUpdate is elapsed time since the last successful fetch. diff --git a/internal/tui/sort.go b/internal/tui/sort.go new file mode 100644 index 0000000..8ca040a --- /dev/null +++ b/internal/tui/sort.go @@ -0,0 +1,121 @@ +package tui + +import ( + "sort" + "strconv" + "strings" +) + +// Sorting works on the rendered cells, because those are what the operator is looking at. +// The comparator recovers the type the text encodes — an age, a size, a count, a severity — +// so a column sorts the way it reads rather than the way ASCII orders it. "9m" before +// "10m" and CRITICAL before LOW are both wrong under a plain string sort. + +// severityRank orders the words that have an inherent order but not an alphabetical one. +var severityRank = map[string]int{ + "NONE": 0, "CLEAN": 0, "OK": 0, "PASS": 0, "PASSED": 0, + "INFO": 1, "LOW": 2, "MEDIUM": 3, "MODERATE": 3, + "HIGH": 4, "CRITICAL": 5, "FAIL": 5, "FAILED": 5, "BLOCKED": 5, +} + +// unitScale covers the suffixes k8s and telemetry values carry. +var unitScale = map[string]float64{ + "s": 1, "m": 60, "h": 3600, "d": 86400, // durations, as k8s.Duration writes them + "ms": 0.001, "us": 0.000001, "ns": 0.000000001, + "ki": 1 << 10, "mi": 1 << 20, "gi": 1 << 30, "ti": 1 << 40, + "k": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, + "%": 1, +} + +// sortValue turns a cell into something orderable: a number when one can be recovered, +// otherwise the lowercased text. +func sortValue(cell string) (float64, string, bool) { + s := strings.TrimSpace(cell) + if s == "" || s == "-" || s == "" || s == "" { + // Absent values sort last in either direction rather than pretending to be zero. + return 0, "￿", false + } + if r, ok := severityRank[strings.ToUpper(s)]; ok { + return float64(r), "", true + } + if n, ok := parseQuantity(s); ok { + return n, "", true + } + // "3/5" and "12/12" sort by how many are up, which is what the eye is scanning for. + if num, _, cut := strings.Cut(s, "/"); cut { + if n, ok := parseQuantity(num); ok { + return n, "", true + } + } + return 0, strings.ToLower(s), false +} + +// parseQuantity reads a number with an optional unit suffix: 42, 1.5, 370Mi, 3h, 98%. +func parseQuantity(s string) (float64, bool) { + i := 0 + for i < len(s) && (s[i] == '-' || s[i] == '+' || s[i] == '.' || (s[i] >= '0' && s[i] <= '9')) { + i++ + } + if i == 0 { + return 0, false + } + n, err := strconv.ParseFloat(s[:i], 64) + if err != nil { + return 0, false + } + suffix := strings.TrimSpace(s[i:]) + if suffix == "" { + return n, true + } + // Byte units are case-insensitive in practice; SI ones are not (m is minutes, M is mega). + if scale, ok := unitScale[strings.ToLower(suffix)]; ok && strings.ContainsAny(suffix, "iI") { + return n * scale, true + } + if scale, ok := unitScale[suffix]; ok { + return n * scale, true + } + if scale, ok := unitScale[strings.ToLower(suffix)]; ok { + return n * scale, true + } + return 0, false +} + +// sortRows orders the visible index list by one column. The sort is stable, so rows that +// tie stay in the order the server returned them instead of shuffling on every refresh. +func sortRows(rows [][]string, visible []int, col int, desc bool) { + if col < 0 { + return + } + cell := func(i int) string { + r := rows[i] + if col >= len(r) { + return "" + } + return r[col] + } + sort.SliceStable(visible, func(a, b int) bool { + na, sa, oka := sortValue(cell(visible[a])) + nb, sb, okb := sortValue(cell(visible[b])) + var less bool + switch { + case oka && okb: + if na == nb { + return false + } + less = na < nb + case oka != okb: + // Numbers before text, both directions, so a stray "" cannot displace + // the ordering of the real values. + return oka + default: + if sa == sb { + return false + } + less = sa < sb + } + if desc { + return !less + } + return less + }) +} diff --git a/internal/tui/styles.go b/internal/tui/styles.go index 2867ed0..f274674 100644 --- a/internal/tui/styles.go +++ b/internal/tui/styles.go @@ -2,20 +2,56 @@ package tui import "github.com/charmbracelet/lipgloss" -// Colors are set with ANSI 256 indices rather than hex so the UI inherits the user's own -// terminal theme instead of imposing a palette that fights it. +// Colors are ANSI-256 indices rather than hex so the UI sits inside the user's own terminal +// theme instead of imposing one that fights it. They are adaptive because a palette tuned +// for a dark terminal goes unreadable on a light one, and plenty of people run light. +// +// NO_COLOR and a non-TTY are handled below lipgloss by termenv's profile detection, so +// nothing here needs to branch on them. var ( - accent = lipgloss.Color("42") // green — the runtimez accent - dim = lipgloss.Color("244") - warnColor = lipgloss.Color("214") - errColor = lipgloss.Color("203") + accent = lipgloss.AdaptiveColor{Light: "63", Dark: "141"} // violet — the chrome + okColor = lipgloss.AdaptiveColor{Light: "28", Dark: "42"} // green — healthy + infoColor = lipgloss.AdaptiveColor{Light: "31", Dark: "116"} // cyan — values + linkColor = lipgloss.AdaptiveColor{Light: "25", Dark: "111"} // blue — URLs + warnColor = lipgloss.AdaptiveColor{Light: "130", Dark: "214"} // amber + errColor = lipgloss.AdaptiveColor{Light: "160", Dark: "203"} // red + dim = lipgloss.AdaptiveColor{Light: "245", Dark: "244"} + faint = lipgloss.AdaptiveColor{Light: "250", Dark: "240"} // rows that no longer matter + onAccent = lipgloss.AdaptiveColor{Light: "231", Dark: "236"} // text ON the accent bar +) - headerStyle = lipgloss.NewStyle().Bold(true).Foreground(accent) - metaStyle = lipgloss.NewStyle().Foreground(dim) - colStyle = lipgloss.NewStyle().Bold(true).Foreground(dim) - selStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("231")).Background(lipgloss.Color("238")) - footerStyle = lipgloss.NewStyle().Foreground(dim) - errStyle = lipgloss.NewStyle().Foreground(errColor) - warnStyle = lipgloss.NewStyle().Foreground(warnColor) - keyStyle = lipgloss.NewStyle().Bold(true).Foreground(accent) +var ( + headerStyle = lipgloss.NewStyle().Bold(true).Foreground(accent) + metaStyle = lipgloss.NewStyle().Foreground(dim) + labelStyle = lipgloss.NewStyle().Foreground(dim) + valueStyle = lipgloss.NewStyle().Foreground(infoColor) + urlStyle = lipgloss.NewStyle().Foreground(linkColor) + colStyle = lipgloss.NewStyle().Bold(true).Foreground(dim) + sortColStyle = lipgloss.NewStyle().Bold(true).Foreground(accent) + selStyle = lipgloss.NewStyle().Bold(true).Foreground(onAccent).Background(accent) + footerStyle = lipgloss.NewStyle().Foreground(dim) + errStyle = lipgloss.NewStyle().Foreground(errColor) + warnStyle = lipgloss.NewStyle().Foreground(warnColor) + okStyle = lipgloss.NewStyle().Foreground(okColor) + mutedStyle = lipgloss.NewStyle().Foreground(faint) + keyStyle = lipgloss.NewStyle().Bold(true).Foreground(accent) + borderStyle = lipgloss.NewStyle().Foreground(accent) + chipStyle = lipgloss.NewStyle().Bold(true).Foreground(onAccent).Background(accent) + logoStyle = lipgloss.NewStyle().Foreground(faint) ) + +// toneStyle maps a cell's semantic reading to how it is drawn. Kept in one place so a +// status colour means the same thing on every screen. +func toneStyle(t tone) lipgloss.Style { + switch t { + case toneOK: + return okStyle + case toneWarn: + return warnStyle + case toneBad: + return errStyle + case toneMuted: + return mutedStyle + } + return lipgloss.NewStyle() +} diff --git a/internal/tui/table.go b/internal/tui/table.go index 3ad14d4..e12bc46 100644 --- a/internal/tui/table.go +++ b/internal/tui/table.go @@ -8,38 +8,48 @@ import ( "github.com/runtimez-com/runtimez-cli/internal/render" ) +// tableOpts is everything the table draw needs beyond the data itself. +type tableOpts struct { + visible []int + cursor, offset int + width, height int + sortCol int // -1 when the server's own order is in effect + sortDesc bool +} + // renderTable draws the visible slice of a table with the cursor row highlighted. // // Column widths come from the content, then get trimmed right-to-left when the terminal is // too narrow: the leftmost columns are the identifying ones (namespace, name), so they are // the last to lose space. -func renderTable(t *render.Table, visible []int, cursor, offset, width, height int) string { +func renderTable(t *render.Table, o tableOpts) string { if t == nil || len(t.Headers) == 0 { return "" } - if height < 1 { - height = 1 + if o.height < 1 { + o.height = 1 } - widths := columnWidths(t, visible, width) + headers := headerCells(t.Headers, o.sortCol, o.sortDesc) + widths := columnWidths(headers, t, o.visible, o.width) var b strings.Builder - b.WriteString(colStyle.Render(padRow(t.Headers, widths))) + b.WriteString(paintHeader(headers, widths, o.sortCol)) b.WriteByte('\n') - end := offset + height - if end > len(visible) { - end = len(visible) + end := o.offset + o.height + if end > len(o.visible) { + end = len(o.visible) } - for i := offset; i < end; i++ { - row := t.Rows[visible[i]] - line := padRow(row, widths) - if i == cursor { - // Pad to full width so the highlight reads as a bar, not a ragged patch. - line = lipgloss.NewStyle().Width(width).Render(line) + for i := o.offset; i < end; i++ { + row := t.Rows[o.visible[i]] + if i == o.cursor { + // Pad to full width so the highlight reads as a bar, not a ragged patch. The + // selected row drops per-cell colour: two colour schemes on one line fight. + line := lipgloss.NewStyle().Width(o.width).Render(padRow(row, widths)) b.WriteString(selStyle.Render(line)) } else { - b.WriteString(line) + b.WriteString(paintRow(t.Headers, row, widths)) } if i < end-1 { b.WriteByte('\n') @@ -48,9 +58,77 @@ func renderTable(t *render.Table, visible []int, cursor, offset, width, height i return b.String() } -func columnWidths(t *render.Table, visible []int, max int) []int { - widths := make([]int, len(t.Headers)) - for i, h := range t.Headers { +// headerCells appends the sort marker to the sorted column, so the arrow the eye looks for +// is attached to the column it actually describes. +func headerCells(headers []string, sortCol int, desc bool) []string { + out := make([]string, len(headers)) + copy(out, headers) + if sortCol >= 0 && sortCol < len(out) { + if desc { + out[sortCol] += " ↓" + } else { + out[sortCol] += " ↑" + } + } + return out +} + +func paintHeader(headers []string, widths []int, sortCol int) string { + cells := make([]string, len(headers)) + for i, h := range headers { + cells[i] = clip(h, widths[i]) + if i == sortCol { + cells[i] = sortColStyle.Render(cells[i]) + } else { + cells[i] = colStyle.Render(cells[i]) + } + } + return joinCells(cells, headers, widths) +} + +func paintRow(headers, row []string, widths []int) string { + muted := rowMuted(headers, row) + cells := make([]string, len(widths)) + plain := make([]string, len(widths)) + for i := range widths { + v := "" + if i < len(row) { + v = row[i] + } + v = clip(v, widths[i]) + plain[i] = v + switch { + case muted: + cells[i] = mutedStyle.Render(v) + case i < len(headers): + if tn := cellTone(headers[i], v); tn != toneNone { + cells[i] = toneStyle(tn).Render(v) + } else { + cells[i] = v + } + default: + cells[i] = v + } + } + return joinCells(cells, plain, widths) +} + +// joinCells lays styled cells on the grid. Padding is measured from the unstyled text +// because escape sequences occupy no columns. +func joinCells(styled, plain []string, widths []int) string { + var b strings.Builder + for i, w := range widths { + b.WriteString(styled[i]) + if i < len(widths)-1 { + b.WriteString(strings.Repeat(" ", w-lipgloss.Width(plain[i])+2)) + } + } + return b.String() +} + +func columnWidths(headers []string, t *render.Table, visible []int, max int) []int { + widths := make([]int, len(headers)) + for i, h := range headers { widths[i] = lipgloss.Width(h) } for _, idx := range visible { diff --git a/internal/tui/troubleshoot_test.go b/internal/tui/troubleshoot_test.go new file mode 100644 index 0000000..f9763ca --- /dev/null +++ b/internal/tui/troubleshoot_test.go @@ -0,0 +1,293 @@ +package tui + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/k8s" +) + +// drill runs a key and delivers the command's message, the way the runtime would. Dropping +// the command is how a test ends up asserting against a model that never made the request. +func drill(t *testing.T, m Model, k string) Model { + t.Helper() + next, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(k)}) + m = next.(Model) + if cmd == nil { + return m + } + if msg := cmd(); msg != nil { + next, _ = m.Update(msg) + m = next.(Model) + } + return m +} + +// The whole point of the drill-down keys: the request that goes out has to be about the +// row under the cursor. A scoped-looking screen showing cluster-wide data is worse than no +// screen, because it reads as evidence about the workload. +func TestDrillDownScopesTheRequestToTheSelectedRow(t *testing.T) { + c := &fakeClient{rows: pods()} + m := newModel(t, c) + m = key(m, "down") // ledger-9, owned by no controller in the fixture + + m = drill(t, m, "l") + if m.view.Title != "Logs" { + t.Fatalf("l opened %q", m.view.Title) + } + if c.lastLogService != "ledger-9" { + t.Errorf("logs were fetched for %q, want ledger-9", c.lastLogService) + } + + m = drill(t, m, "r") + if c.lastRCARef != "payments/ledger-9" { + t.Errorf("rca was fetched for %q", c.lastRCARef) + } + + m = drill(t, m, "c") + if c.lastChangesRef != "payments/ledger-9" { + t.Errorf("changes were fetched for %q", c.lastChangesRef) + } + + m = drill(t, m, "t") + if !strings.Contains(c.lastTraceQuery, `serviceName : "ledger-9"`) { + t.Errorf("trace query = %q, want a serviceName filter", c.lastTraceQuery) + } +} + +// The scope has to be visible. An operator who cannot see what a screen is about will read +// it as being about the cluster. +func TestScopeIsVisibleAndClearedByEscape(t *testing.T) { + c := &fakeClient{rows: pods()} + m := newModel(t, c) + m = drill(t, m, "l") + + if !strings.Contains(m.View(), "payments/checkout-1") { + t.Errorf("scope not shown on screen:\n%s", m.View()) + } + + // esc clears the filter first, and only then the scope: they were set at different + // times and throwing away both at once discards work the user is still doing. + m.filter = "abc" + m = key(m, "esc") + if m.scope.empty() { + t.Error("esc cleared the scope while a filter was still set") + } + m = key(m, "esc") + if !m.scope.empty() { + t.Error("second esc did not clear the scope") + } +} + +// A screen that cannot narrow by the scope must say so rather than implying it did. +func TestUnscopableViewSaysTheScopeDoesNotApply(t *testing.T) { + c := &fakeClient{rows: pods()} + m := newModel(t, c) + m = drill(t, m, "l") // sets a scope + m = submit(t, typeIn(key(m, ":"), "signals")) + + out := m.View() + if !strings.Contains(out, "not applied here") { + t.Errorf("unscopable view did not disclaim the scope:\n%s", out) + } +} + +// Logs with no scope are cluster-wide, and the notice has to say which it is — otherwise +// an empty scoped view and a quiet cluster look identical. +func TestLogsStateWhetherTheyAreScoped(t *testing.T) { + c := &fakeClient{rows: pods()} + m := newModel(t, c) + + m = submit(t, typeIn(key(m, ":"), "logs")) + if msg := cmdMsg(t, m, "logs"); !strings.Contains(msg, "all services") { + t.Errorf("unscoped logs notice = %q", msg) + } + + m = newModel(t, c) + m = drill(t, m, "l") + if !strings.Contains(m.data.notice, "service checkout-1") { + t.Errorf("scoped logs notice = %q", m.data.notice) + } +} + +func cmdMsg(t *testing.T, m Model, view string) string { + t.Helper() + d, err := views[view].fetch(t.Context(), fetchReq{Client: &fakeClient{}, OrgID: "o", ClusterID: "c"}) + if err != nil { + t.Fatal(err) + } + return d.notice +} + +// Triage ranks what is failing. A completed Job pod is not a problem; a Running pod with +// restarts is, and a Pending pod looks calm and is not. +func TestTriageKeepsWhatIsActuallyWrong(t *testing.T) { + rows := []k8s.Resource{ + {Kind: "Pod", Namespace: "a", Name: "done", Status: `{"phase":"Succeeded"}`}, + {Kind: "Pod", Namespace: "a", Name: "healthy", Status: `{"phase":"Running","restartCount":0}`}, + {Kind: "Pod", Namespace: "a", Name: "flapping", Status: `{"phase":"Running","restartCount":7}`}, + {Kind: "Pod", Namespace: "a", Name: "stuck", Status: `{"phase":"Pending"}`}, + {Kind: "Pod", Namespace: "a", Name: "dead", Status: `{"phase":"Failed"}`}, + } + d, err := triageView.fetch(t.Context(), fetchReq{ + Client: &fakeClient{rows: rows}, OrgID: "o", ClusterID: "c"}) + if err != nil { + t.Fatal(err) + } + + body := renderRows(d) + for _, want := range []string{"flapping", "stuck", "dead", "restarting", "not scheduled"} { + if !strings.Contains(body, want) { + t.Errorf("triage dropped %q:\n%s", want, body) + } + } + for _, unwanted := range []string{"healthy", "done"} { + if strings.Contains(body, unwanted) { + t.Errorf("triage listed the healthy pod %q:\n%s", unwanted, body) + } + } +} + +// A partial triage said to be complete is worse than no triage: "nothing is failing" is a +// conclusion, and it must not be reached from a source that did not answer. +func TestTriageSaysWhenASourceIsMissing(t *testing.T) { + d, err := triageView.fetch(t.Context(), fetchReq{ + Client: &failingRCAClient{fakeClient: fakeClient{rows: nil}}, OrgID: "o", ClusterID: "c"}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(d.notice, "auto-RCA unavailable") { + t.Errorf("notice = %q, want the missing source named", d.notice) + } +} + +var errBoom = errors.New("boom") + +type failingRCAClient struct{ fakeClient } + +func (f *failingRCAClient) AutoRCA(_ context.Context, _, _, _, _ string) (*api.AutoRCA, error) { + return nil, errBoom +} + +func renderRows(d dataset) string { + var b strings.Builder + if d.table != nil { + for _, r := range d.table.Rows { + b.WriteString(strings.Join(r, " ") + "\n") + } + b.WriteString(d.table.EmptyMessage) + } + b.WriteString(d.body) + return b.String() +} + +// The ask pane must subscribe before it asks. The reverse races the first frames, and the +// early steps are the ones that explain what the agent decided to look at. +func TestAskStreamsFramesThenTheAnswer(t *testing.T) { + c := &fakeClient{ + rows: pods(), + streamFrames: []api.StreamFrame{ + {Type: "step", Phase: "thinking", Step: 1, Thought: "checking restarts", Tool: "getPods"}, + {Type: "step", Phase: "observation", ResultSummary: "12 restarts in 1h"}, + }, + answer: &api.AgentAnswer{ + Answer: "the readiness probe never passes", + SessionID: "s-42", + Verdict: &api.AgentVerdict{Headline: "Readiness probe failing", Confidence: "HIGH"}, + }, + } + m := newModel(t, c) + m = key(m, "down") + m = key(m, "a") + + if m.mode != modeAsk { + t.Fatal("a did not open the ask pane") + } + // Seeded with the selection, so the common case is one keystroke and enter. + if !strings.Contains(m.ask.input.Value(), "payments/ledger-9") { + t.Errorf("question not seeded with the selection: %q", m.ask.input.Value()) + } + + next, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m = next.(Model) + if !m.ask.busy { + t.Fatal("submitting did not mark the pane busy") + } + m = pump(t, m, cmd, 8) + + out := m.View() + for _, want := range []string{"checking restarts", "getPods", "12 restarts in 1h", + "Readiness probe failing", "confidence HIGH", "the readiness probe never passes"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in the transcript:\n%s", want, out) + } + } + if m.ask.sessionID != "s-42" { + t.Errorf("session not retained: %q", m.ask.sessionID) + } +} + +// Ctrl-C in a live run stops the agent server-side. Dropping the connection alone leaves it +// burning a slot long after the person walked away. +func TestCtrlCCancelsTheRunOnTheServer(t *testing.T) { + c := &fakeClient{rows: pods()} + m := newModel(t, c) + m = key(m, "a") + + next, _ := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m = next.(Model) + + sent := m.ask.streamID + if sent == "" { + t.Fatal("no stream id was minted for the run") + } + + next, cmd := m.Update(tea.KeyMsg{Type: tea.KeyCtrlC}) + m = next.(Model) + if cmd != nil { + cmd() + } + if got := c.cancelled(); got != sent { + t.Errorf("cancelled %q but the run was %q", got, sent) + } + if m.ask.busy { + t.Error("pane still busy after cancel") + } +} + +// pump delivers messages the way the runtime would, up to a bound so a test cannot hang. +func pump(t *testing.T, m Model, cmd tea.Cmd, max int) Model { + t.Helper() + cmds := []tea.Cmd{cmd} + for i := 0; i < max && len(cmds) > 0; i++ { + c := cmds[0] + cmds = cmds[1:] + if c == nil { + continue + } + done := make(chan tea.Msg, 1) + go func() { done <- c() }() + select { + case msg := <-done: + if msg == nil { + continue + } + if batch, isBatch := msg.(tea.BatchMsg); isBatch { + cmds = append(cmds, batch...) + continue + } + next, nextCmd := m.Update(msg) + m = next.(Model) + cmds = append(cmds, nextCmd) + case <-time.After(2 * time.Second): + t.Fatal("a command blocked for 2s") + } + } + return m +} diff --git a/internal/tui/views.go b/internal/tui/views.go index f66e2b9..9cff711 100644 --- a/internal/tui/views.go +++ b/internal/tui/views.go @@ -2,6 +2,8 @@ package tui import ( "context" + "fmt" + "strings" "time" "github.com/runtimez-com/runtimez-cli/internal/api" @@ -21,6 +23,51 @@ type Client interface { AutoRCA(ctx context.Context, orgID, clusterID, from, to string) (*api.AutoRCA, error) SlowOperations(ctx context.Context, orgID, clusterID, from, to string, limit int) (*api.SlowOperations, error) Changes(ctx context.Context, orgID, clusterID string, sinceHours, page, size int) (*api.Changes, error) + WorkloadRCA(ctx context.Context, orgID, clusterID, namespace, name, kind string) (*api.WorkloadRCA, error) + WorkloadChanges(ctx context.Context, orgID, clusterID, namespace, name string, page, size int) (*api.Changes, error) + Ask(ctx context.Context, orgID, clusterID string, q api.AgentQuery) (*api.AgentAnswer, error) + StreamInvestigation(ctx context.Context, orgID, clusterID, streamID string, fn func(api.StreamFrame) error) error + CancelInvestigation(ctx context.Context, orgID, clusterID, streamID string) error +} + +// scope is the object the screen is currently about. +// +// Without it a drill-down key can only ever mean "the whole cluster", which is the +// difference between a viewer and something you can troubleshoot with: you find the +// crashing pod, then have to leave and retype its name somewhere else. +type scope struct { + Kind string + Namespace string + Name string + // Service is the name this workload's telemetry is indexed under — usually the + // controller name rather than the pod's. + Service string +} + +func (s scope) empty() bool { return s.Name == "" } + +func (s scope) ref() string { + if s.Namespace == "" { + return s.Name + } + return s.Namespace + "/" + s.Name +} + +// scopeOf builds a scope from a selected row. +func scopeOf(r k8s.Resource) scope { + return scope{ + Kind: r.Kind, Namespace: r.Namespace, Name: r.Name, + Service: k8s.ServiceNameFor(r), + } +} + +// fetchReq is everything a view needs to load itself. +type fetchReq struct { + Client Client + OrgID string + ClusterID string + Namespace string + Scope scope } // dataset is what a view produces: the table to draw, plus the Kubernetes rows behind it @@ -30,8 +77,11 @@ type dataset struct { table *render.Table resources []k8s.Resource // notice is a caveat that belongs on screen with the data — missing signals, an - // unscanned cluster — rather than in a log the operator never sees. + // unscanned cluster, a listing that is cluster-wide when you expected it scoped — + // rather than in a log the operator never sees. notice string + // body replaces the table for screens that are prose rather than rows. + body string } // viewDef is one navigable screen. @@ -41,27 +91,30 @@ type viewDef struct { Kind string // namespaced marks views that honour the :ns scope. namespaced bool - fetch func(ctx context.Context, c Client, orgID, clusterID, namespace string) (dataset, error) + // scopable marks views that change when a workload is selected. A view that is not + // scopable keeps the scope in the header but does not pretend to narrow by it. + scopable bool + fetch func(ctx context.Context, r fetchReq) (dataset, error) } // resourceView builds a standard Kubernetes listing. func resourceView(title, kind string) viewDef { return viewDef{ Title: title, Kind: kind, namespaced: true, - fetch: func(ctx context.Context, c Client, org, cluster, ns string) (dataset, error) { - rows, err := c.Resources(ctx, org, cluster, kind, ns) + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + rows, err := r.Client.Resources(ctx, r.OrgID, r.ClusterID, kind, r.Namespace) if err != nil { return dataset{}, err } - return dataset{table: view.TableFor(kind, rows, ns == ""), resources: rows}, nil + return dataset{table: view.TableFor(kind, rows, r.Namespace == ""), resources: rows}, nil }, } } var riskView = viewDef{ Title: "Workload risk", - fetch: func(ctx context.Context, c Client, org, cluster, _ string) (dataset, error) { - p, err := c.WorkloadRiskPosture(ctx, org, cluster) + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.WorkloadRiskPosture(ctx, r.OrgID, r.ClusterID) if err != nil { return dataset{}, err } @@ -75,8 +128,8 @@ var riskView = viewDef{ var signalsView = viewDef{ Title: "Slow operations", - fetch: func(ctx context.Context, c Client, org, cluster, _ string) (dataset, error) { - res, err := c.SlowOperations(ctx, org, cluster, "", "", 50) + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + res, err := r.Client.SlowOperations(ctx, r.OrgID, r.ClusterID, "", "", 50) if err != nil { return dataset{}, err } @@ -85,54 +138,199 @@ var signalsView = viewDef{ } var logsView = viewDef{ - Title: "Logs", - fetch: func(ctx context.Context, c Client, org, cluster, _ string) (dataset, error) { + Title: "Logs", scopable: true, + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { end := time.Now() - page, err := c.SearchLogs(ctx, api.LogSearch{ + req := api.LogSearch{ StartDate: api.EpochMs(end.Add(-time.Hour)), EndDate: api.EpochMs(end), - ClusterID: cluster, Limit: 200, - }) + ClusterID: r.ClusterID, Limit: 200, + } + req.ServiceName = r.Scope.Service + + page, err := r.Client.SearchLogs(ctx, req) if err != nil { return dataset{}, err } - d := dataset{table: view.LogsTable(page.Data), notice: "last hour"} + d := dataset{table: view.LogsTable(page.Data), notice: logScopeNotice(r.Scope)} if page.Total > int64(len(page.Data)) { - d.notice = "last hour — showing " + itoa(len(page.Data)) + " of " + itoa64(page.Total) + d.notice += " — showing " + itoa(len(page.Data)) + " of " + itoa64(page.Total) } return d, nil }, } +// logScopeNotice says out loud whether the lines on screen belong to the selected workload +// or to the whole cluster. Mistaking one for the other is how an operator concludes a +// workload is silent when it is only unselected. +func logScopeNotice(s scope) string { + if s.Service == "" { + return "last hour, all services" + } + return "last hour, service " + s.Service +} + var tracesView = viewDef{ - Title: "Traces", - fetch: func(ctx context.Context, c Client, org, cluster, _ string) (dataset, error) { + Title: "Traces", scopable: true, + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { end := time.Now() - page, err := c.ListTraces(ctx, api.TraceListRequest{ + req := api.TraceListRequest{ StartDate: api.EpochMs(end.Add(-time.Hour)), EndDate: api.EpochMs(end), - ClusterID: cluster, Limit: 100, SortBy: "durationNano", SortOrder: "desc", - }) + ClusterID: r.ClusterID, Limit: 100, SortBy: "durationNano", SortOrder: "desc", + } + notice := "last hour, slowest first" + if svc := r.Scope.Service; svc != "" { + // KQL, per KqlTranslator: serviceName is an allow-listed column and the value is + // quoted. An untranslatable query is a 400, not a silent full-window match. + req.Query = fmt.Sprintf("serviceName : %q", svc) + notice += ", service " + svc + } + page, err := r.Client.ListTraces(ctx, req) if err != nil { return dataset{}, err } - return dataset{table: view.TracesTable(page.Data), notice: "last hour, slowest first"}, nil + return dataset{table: view.TracesTable(page.Data), notice: notice}, nil }, } var changesView = viewDef{ - Title: "Changes", - fetch: func(ctx context.Context, c Client, org, cluster, _ string) (dataset, error) { - res, err := c.Changes(ctx, org, cluster, 168, 0, 100) + Title: "Changes", scopable: true, + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + if !r.Scope.empty() { + res, err := r.Client.WorkloadChanges(ctx, r.OrgID, r.ClusterID, + r.Scope.Namespace, r.Scope.Name, 0, 100) + if err != nil { + return dataset{}, err + } + return dataset{ + table: view.ChangesTable(res.Items), + notice: "changes to " + r.Scope.ref(), + }, nil + } + res, err := r.Client.Changes(ctx, r.OrgID, r.ClusterID, 168, 0, 100) if err != nil { return dataset{}, err } - d := dataset{table: view.ChangesTable(res.Items)} + d := dataset{table: view.ChangesTable(res.Items), notice: "cluster-wide, last 7 days"} if res.Total > int64(len(res.Items)) { - d.notice = "showing the most recent " + itoa(len(res.Items)) + " of " + itoa64(res.Total) + d.notice += " — showing the most recent " + itoa(len(res.Items)) + " of " + itoa64(res.Total) } return d, nil }, } +// rcaView is the per-workload root cause. It needs a subject: an RCA with no workload is +// not a smaller answer, it is a different question, which is what :triage is for. +var rcaView = viewDef{ + Title: "Root cause", scopable: true, + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + if r.Scope.empty() { + return dataset{ + table: &render.Table{EmptyMessage: "Select a workload first — press r on a row, or :triage for what is failing now."}, + }, nil + } + res, err := r.Client.WorkloadRCA(ctx, r.OrgID, r.ClusterID, + r.Scope.Namespace, r.Scope.Name, r.Scope.Kind) + if err != nil { + return dataset{}, err + } + return dataset{ + body: view.WorkloadRCAText(res), + notice: "root cause for " + r.Scope.ref(), + }, nil + }, +} + +// triageView answers "what do I look at first" instead of "what exists". It merges the +// auto-RCA suspect with every pod that is not healthy right now, because a control plane +// that has not yet scored a workload should not hide a pod that is crash-looping. +var triageView = viewDef{ + Title: "Triage", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + pods, podErr := r.Client.Resources(ctx, r.OrgID, r.ClusterID, "Pod", "") + rca, rcaErr := r.Client.AutoRCA(ctx, r.OrgID, r.ClusterID, "", "") + + // Neither source is required: a cluster with no RCA still has unhealthy pods worth + // showing, and vice versa. Only a total failure is an error. + if podErr != nil && rcaErr != nil { + return dataset{}, podErr + } + + t := &render.Table{ + Headers: []string{"WHY", "NAMESPACE", "NAME", "STATUS", "RESTARTS", "AGE"}, + EmptyMessage: "Nothing is failing right now — every pod is Running or Succeeded.", + } + var rows []k8s.Resource + var notes []string + + if rcaErr != nil { + notes = append(notes, "auto-RCA unavailable") + } else if rca != nil && rca.Degraded && rca.TopSuspect != nil { + s := rca.TopSuspect + t.Rows = append(t.Rows, []string{ + "top suspect", s.Namespace, s.Name, + fmt.Sprintf("%s (%d)", s.Level, s.Score), "-", "-", + }) + rows = append(rows, k8s.Resource{ + Kind: s.Kind, Namespace: s.Namespace, Name: s.Name, + }) + } + + if podErr != nil { + notes = append(notes, "pod listing unavailable") + } + for _, p := range unhealthyPods(pods) { + d := k8s.ParsePod(p) + t.Rows = append(t.Rows, []string{ + triageReason(d), d.Namespace, d.Name, d.Phase, + itoa(d.Restarts), k8s.Age(d.CreatedAt), + }) + rows = append(rows, p) + } + + out := dataset{table: t, resources: rows} + if len(notes) > 0 { + // A partial answer said to be complete is worse than no answer. + out.notice = "partial: " + strings.Join(notes, ", ") + } + return out, nil + }, +} + +// unhealthyPods keeps anything an operator would stop on. Succeeded is excluded — a +// completed Job pod is not a problem — but Pending is included, because a pod that cannot +// schedule looks calm and is not. +func unhealthyPods(pods []k8s.Resource) []k8s.Resource { + var out []k8s.Resource + for _, p := range pods { + d := k8s.ParsePod(p) + switch d.Phase { + case "Succeeded", "Completed": + continue + case "Running": + // Restarts are the signal a Running pod is not actually well. + if d.Restarts > 0 { + out = append(out, p) + } + default: + out = append(out, p) + } + } + return out +} + +func triageReason(d k8s.Pod) string { + switch { + case d.Phase == "Running" && d.Restarts > 0: + return "restarting" + case d.Phase == "Pending": + return "not scheduled" + case d.Phase == "Failed": + return "failed" + default: + return strings.ToLower(d.Phase) + } +} + // views is the command-bar registry. Names match the CLI's vocabulary so one set of words // covers both surfaces. var views = map[string]viewDef{ @@ -157,15 +355,14 @@ var views = map[string]viewDef{ "changes": changesView, "logs": logsView, "traces": tracesView, + "rca": rcaView, + "triage": triageView, } // plannedViews name screens that exist in the roadmap but not yet in the binary, so the // command bar can say "not yet" instead of silently doing nothing. var plannedViews = map[string]string{ - // ask is interactive rather than tabular; it lives at `rtz ask` until the UI grows a - // conversation pane. - "ask": "the `rtz ask` command", - "upgrade": "M5", + "upgrade": "the `rtz upgrade check` command", } func joinWords(items []string) string { diff --git a/internal/view/detail_test.go b/internal/view/detail_test.go new file mode 100644 index 0000000..24a0622 --- /dev/null +++ b/internal/view/detail_test.go @@ -0,0 +1,96 @@ +package view + +import ( + "strings" + "testing" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/k8s" +) + +func podFixture() *api.WorkloadDetail { + return &api.WorkloadDetail{ + Workload: &k8s.Resource{ + Kind: "Pod", Namespace: "rtzflags", Name: "flg-stall-subject-688899b5cb-fr2k8", + OwnerKind: "ReplicaSet", OwnerName: "flg-stall-subject-688899b5cb", + Labels: `{"app":"flg-stall-subject"}`, + Spec: `{"nodeName":"agent-2","serviceAccountName":"default","containers":[ + {"name":"app","image":"busybox:1.36","readinessProbe":true, + "resources":{"requests":{"cpu":"10m","memory":"16Mi"}, + "limits":{"cpu":"50m","memory":"32Mi"}}}]}`, + Status: `{"phase":"Running","qosClass":"Burstable","restartCount":15, + "containerStatuses":[{"name":"app","ready":false,"restartCount":15, + "state":{"type":"running"}, + "lastTerminated":{"reason":"Completed","exitCode":0}}], + "conditions":[{"type":"Ready","status":"False","reason":"ContainersNotReady", + "message":"containers with unready status: [app]"}]}`, + }, + Events: []api.Event{{ + Name: "flg-stall-subject.18d2", + Spec: `{"reason":"Unhealthy","message":"Readiness probe failed:","type":"Warning", + "count":11268,"lastTimestamp":"2026-09-06T12:10:01Z", + "involvedObject":{"kind":"Pod","name":"flg-stall-subject-688899b5cb-fr2k8"}}`, + }}, + } +} + +func TestPodDetailRendersWhatAPodActuallyHas(t *testing.T) { + var b strings.Builder + Detail(&b, podFixture()) + out := b.String() + + for _, want := range []string{ + "Kind: Pod", "Phase: Running", "Node: agent-2", + "Owner: ReplicaSet/flg-stall-subject-688899b5cb", "QoS: Burstable", + "Containers (1)", "busybox:1.36", "10m/50m", "16Mi/32Mi", "readiness", + "Last terminated (1)", "Completed", + "Conditions (1)", "ContainersNotReady", + } { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + + // A pod has no ready-replica ratio and owns no pods. Printing "Ready: 0/0" and + // "Pods (0)" reads as two findings when they are only the wrong questions. + for _, unwanted := range []string{"Ready: 0/0", "Pods (0)", "ReplicaSets ("} { + if strings.Contains(out, unwanted) { + t.Errorf("controller-shaped section %q leaked into the pod pane:\n%s", unwanted, out) + } + } +} + +// The regression this pins: every field but the name lives inside the event's spec blob, so +// decoding them as top-level keys renders a table of blanks — and a blank Events table +// looks like a healthy workload. +func TestEventsRenderTheirContentNotBlanks(t *testing.T) { + var b strings.Builder + Detail(&b, podFixture()) + out := b.String() + + for _, want := range []string{"Warning", "Unhealthy", "11268", "Readiness probe failed:"} { + if !strings.Contains(out, want) { + t.Errorf("event field %q missing from:\n%s", want, out) + } + } + if strings.Contains(out, " ") { + t.Errorf("events rendered as blanks:\n%s", out) + } +} + +// Controllers keep the renderer they had; the pod branch must not have taken theirs. +func TestControllerDetailStillRendersItsOwnShape(t *testing.T) { + var b strings.Builder + Detail(&b, &api.WorkloadDetail{ + Workload: &k8s.Resource{Kind: "Deployment", Namespace: "payments", Name: "checkout", + Spec: `{"replicas":3}`, Status: `{"readyReplicas":2}`}, + Pods: []k8s.Resource{{Kind: "Pod", Namespace: "payments", Name: "checkout-a", + Status: `{"phase":"Running"}`}}, + }) + out := b.String() + for _, want := range []string{"Kind: Deployment", "Ready: 2/3", "Pods (1)", "checkout-a"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } +} diff --git a/internal/view/rca.go b/internal/view/rca.go new file mode 100644 index 0000000..7c866d2 --- /dev/null +++ b/internal/view/rca.go @@ -0,0 +1,93 @@ +package view + +import ( + "fmt" + "io" + "strings" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/render" +) + +// WorkloadRCA renders one workload's root-cause evidence. +// +// Lifted out of internal/cli so `rtz rca` and the TUI's :rca screen are one definition +// rather than two that drift — the same reason internal/view exists at all. +func WorkloadRCA(w io.Writer, r *api.WorkloadRCA) { + if r == nil { + fmt.Fprintln(w, "no root-cause data for this workload") + return + } + + fmt.Fprintf(w, "%s/%s (%s)\n", r.Namespace, r.Name, render.Dash(r.Kind)) + fmt.Fprintf(w, " Restarts: %d\n", r.RestartCount) + if r.K8sReason != "" { + fmt.Fprintf(w, " Reason: %s\n", r.K8sReason) + } + if r.OOMKilled { + fmt.Fprintln(w, " OOMKilled: yes") + } + if r.ExitCode != nil { + fmt.Fprintf(w, " Exit code: %d\n", *r.ExitCode) + } + if r.TerminatedAt != "" { + fmt.Fprintf(w, " Terminated: %s\n", r.TerminatedAt) + } + if r.TerminationSummary != "" { + fmt.Fprintf(w, " Summary: %s\n", r.TerminationSummary) + } + + // App health is only meaningful when traces reached the backend; printing 0% error and + // 0ms p99 for a workload with no telemetry would read as a perfectly healthy service. + if r.AppHealthAvailable { + fmt.Fprintf(w, " Requests: %d, %.2f%% errors, p99 %dms\n", + r.RequestCount, r.ErrorRatePct, r.P99LatencyMs) + } else { + fmt.Fprintln(w, " App health: no trace data for this workload") + } + + if len(r.WarningEvents) > 0 { + fmt.Fprintf(w, "\nWarning events (%d)\n", len(r.WarningEvents)) + for _, ev := range r.WarningEvents { + fmt.Fprintf(w, " %s %s %s\n", + render.Dash(ev.LastTimestamp), render.Dash(ev.Reason), truncate(ev.Message, 70)) + } + } + + fmt.Fprintf(w, "\nLog tail (%d lines)\n", len(r.LogTailLines)) + if !r.TermLogsAvailable { + fmt.Fprintln(w, " termination logs not collected for this workload") + } + for _, l := range r.LogTailLines { + fmt.Fprintf(w, " %s\n", truncate(l, 100)) + } + + if len(r.SpansInFlight) > 0 { + fmt.Fprintf(w, "\nSpans in flight at failure (%d)\n", len(r.SpansInFlight)) + for _, s := range r.SpansInFlight { + fmt.Fprintf(w, " %s %s %s %dms\n", + s.TraceID, truncate(s.SpanName, 40), render.Dash(s.StatusCode), s.DurationMs) + } + } + + rcaEdges(w, "Upstream", r.Upstream) + rcaEdges(w, "Downstream", r.Downstream) +} + +func rcaEdges(w io.Writer, title string, edges []api.DependencyEdge) { + if len(edges) == 0 { + return + } + fmt.Fprintf(w, "\n%s (%d)\n", title, len(edges)) + for _, e := range edges { + fmt.Fprintf(w, " %s/%s %s %d bytes\n", + render.Dash(e.Namespace), render.Dash(e.OwnerName), render.Dash(e.OwnerKind), e.Bytes) + } +} + +// WorkloadRCAText is the string form, for the TUI's body pane. +func WorkloadRCAText(r *api.WorkloadRCA) string { + var b strings.Builder + WorkloadRCA(&b, r) + return b.String() +} diff --git a/internal/view/view.go b/internal/view/view.go index 6718f09..dcd5359 100644 --- a/internal/view/view.go +++ b/internal/view/view.go @@ -142,6 +142,10 @@ func genericTable(rows []k8s.Resource, showNS bool) *render.Table { } func Detail(w io.Writer, d *api.WorkloadDetail) { + if d.Workload != nil && d.Workload.Kind == "Pod" { + podDetail(w, d) + return + } wl := k8s.ParseWorkload(*d.Workload) fmt.Fprintf(w, "%s/%s\n", wl.Namespace, wl.Name) @@ -165,17 +169,7 @@ func Detail(w io.Writer, d *api.WorkloadDetail) { printIndented(w, t) } - section(w, "Events", len(d.Events)) - if len(d.Events) > 0 { - t := &render.Table{Headers: []string{"TYPE", "REASON", "COUNT", "AGE", "MESSAGE"}} - for _, ev := range d.Events { - t.Rows = append(t.Rows, []string{ - render.Dash(ev.Type), render.Dash(ev.Reason), strconv.Itoa(ev.Count), - k8s.Age(ev.When()), truncate(ev.Message, 80), - }) - } - printIndented(w, t) - } + eventsSection(w, d.Events) relatedSection(w, "Services", d.Services, func(r k8s.Resource) []string { s := k8s.ParseService(r) @@ -251,3 +245,107 @@ func truncate(s string, max int) string { } return s[:max-1] + "…" } + +// eventsSection renders correlated events. The backend caps at 50 and ranks Warnings first. +func eventsSection(w io.Writer, events []api.Event) { + section(w, "Events", len(events)) + if len(events) == 0 { + return + } + t := &render.Table{Headers: []string{"TYPE", "REASON", "COUNT", "AGE", "MESSAGE"}} + for _, ev := range events { + e := ev.Info() + t.Rows = append(t.Rows, []string{ + render.Dash(e.Type), render.Dash(e.Reason), strconv.Itoa(e.Count), + k8s.Age(e.LastTimestamp), truncate(e.Message, 80), + }) + } + printIndented(w, t) +} + +// podDetail is the single-pod pane. A pod is not a controller: it has no ready-replica +// ratio and owns no pods, so the controller renderer's Ready and Pods sections would print +// "0/0" and "Pods (0)" — both read as findings when they are only the wrong questions. +func podDetail(w io.Writer, d *api.WorkloadDetail) { + p := k8s.ParsePodDetail(*d.Workload) + + fmt.Fprintf(w, "%s/%s\n", p.Namespace, p.Name) + fmt.Fprintf(w, " Kind: Pod\n") + fmt.Fprintf(w, " Phase: %s\n", p.Phase) + fmt.Fprintf(w, " Node: %s\n", render.Dash(p.NodeName)) + if p.OwnerKind != "" { + fmt.Fprintf(w, " Owner: %s/%s\n", p.OwnerKind, p.OwnerName) + } + if p.QoS != "" { + fmt.Fprintf(w, " QoS: %s\n", p.QoS) + } + restarts := strconv.Itoa(p.Restarts) + if p.Restarts > 0 && p.LastRestartAt != "" { + restarts += " (last " + k8s.Age(p.LastRestartAt) + " ago)" + } + fmt.Fprintf(w, " Restarts: %s\n", restarts) + fmt.Fprintf(w, " Age: %s\n", k8s.Age(p.CreatedAt)) + if p.ServiceAccount != "" { + fmt.Fprintf(w, " Account: %s\n", p.ServiceAccount) + } + if p.HostNetwork { + fmt.Fprintf(w, " Network: hostNetwork\n") + } + if labels := d.Workload.LabelsOf(); len(labels) > 0 { + fmt.Fprintf(w, " Labels: %s\n", formatLabels(labels)) + } + + section(w, "Containers", len(p.Containers)) + if p.MissingContainers { + // Distinguish "this pod has no containers" — impossible — from a payload that did + // not carry them, which is an agent-version question, not a workload one. + fmt.Fprintln(w, " no container detail in this record — the agent did not report it") + } else { + t := &render.Table{Headers: []string{"NAME", "IMAGE", "READY", "RESTARTS", "STATE", "CPU R/L", "MEM R/L", "PROBES"}} + for _, c := range p.Containers { + name := c.Name + if c.Init { + name += " (init)" + } + t.Rows = append(t.Rows, []string{ + name, render.Dash(c.Image), strconv.FormatBool(c.Ready), strconv.Itoa(c.Restarts), + c.StateLabel(), c.CPU(), c.Mem(), render.Dash(strings.Join(c.Probes, ",")), + }) + } + printIndented(w, t) + } + + var terminated []k8s.Container + for _, c := range p.Containers { + if c.LastTerminatedReason != "" || c.HasLastExitCode { + terminated = append(terminated, c) + } + } + if len(terminated) > 0 { + section(w, "Last terminated", len(terminated)) + t := &render.Table{Headers: []string{"CONTAINER", "REASON", "EXIT", "WHEN"}} + for _, c := range terminated { + exit := "-" + if c.HasLastExitCode { + exit = strconv.Itoa(c.LastExitCode) + } + t.Rows = append(t.Rows, []string{ + c.Name, render.Dash(c.LastTerminatedReason), exit, k8s.Age(c.LastFinishedAt), + }) + } + printIndented(w, t) + } + + section(w, "Conditions", len(p.Conditions)) + if len(p.Conditions) > 0 { + t := &render.Table{Headers: []string{"TYPE", "STATUS", "REASON", "MESSAGE"}} + for _, c := range p.Conditions { + t.Rows = append(t.Rows, []string{ + c.Type, c.Status, render.Dash(c.Reason), truncate(c.Message, 60), + }) + } + printIndented(w, t) + } + + eventsSection(w, d.Events) +} From d209daf5790dabb9d8d4f15f240dcdb3a3c40821 Mon Sep 17 00:00:00 2001 From: pvishwa3 Date: Sat, 17 Oct 2026 20:10:33 -0400 Subject: [PATCH 3/7] feat: capacity, maintain and add-on workspace commands; lossless -o json MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brings the CLI up to the eac features merged since September. - rtz capacity [--section pools|nodes|blocked|storage|network|batch|special], capacity trend|cost|namespaces|fleet. Section names match the MCP runtimez_capacity_summary tool. - rtz maintain items (--within, --fail-on-days → exit 4, --platform), maintain packages, maintain dependents|impact //. readFailed exits 1: an incomplete list never reads as "nothing due". - rtz addons nodepools|cluster-autoscaler|ingress|mesh|gitops|vpc-cni|ebs-csi [object] with --fail-on. A non-OK workspace status (not detected, never synced, rules off) is stated, and never passes a gate. - upgrade check: add-ons that must move, patch currency, per-application impact. - -o json|yaml on all of these (and upgrade check) print the full server document via api.GetPayload; integers stay exact in YAML. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0178ctkmt3CJYuTzySDeSgSe --- README.md | 51 ++++ internal/api/addons.go | 416 +++++++++++++++++++++++++++++++++ internal/api/capacity.go | 409 ++++++++++++++++++++++++++++++++ internal/api/client.go | 54 +++++ internal/api/maintain.go | 195 ++++++++++++++++ internal/api/upgrade.go | 52 ++++- internal/cli/addons.go | 429 ++++++++++++++++++++++++++++++++++ internal/cli/addons_test.go | 190 +++++++++++++++ internal/cli/capacity.go | 350 +++++++++++++++++++++++++++ internal/cli/capacity_test.go | 273 ++++++++++++++++++++++ internal/cli/maintain.go | 310 ++++++++++++++++++++++++ internal/cli/maintain_test.go | 216 +++++++++++++++++ internal/cli/root.go | 3 + internal/cli/sections.go | 52 +++++ internal/cli/upgrade.go | 45 +++- internal/cli/upgrade_test.go | 35 +++ internal/view/addons.go | 292 +++++++++++++++++++++++ internal/view/capacity.go | 389 ++++++++++++++++++++++++++++++ internal/view/maintain.go | 121 ++++++++++ internal/view/reliability.go | 54 +++++ internal/view/units.go | 168 +++++++++++++ internal/view/units_test.go | 16 ++ 22 files changed, 4112 insertions(+), 8 deletions(-) create mode 100644 internal/api/addons.go create mode 100644 internal/api/capacity.go create mode 100644 internal/api/maintain.go create mode 100644 internal/cli/addons.go create mode 100644 internal/cli/addons_test.go create mode 100644 internal/cli/capacity.go create mode 100644 internal/cli/capacity_test.go create mode 100644 internal/cli/maintain.go create mode 100644 internal/cli/maintain_test.go create mode 100644 internal/cli/sections.go create mode 100644 internal/view/addons.go create mode 100644 internal/view/capacity.go create mode 100644 internal/view/maintain.go create mode 100644 internal/view/units.go create mode 100644 internal/view/units_test.go diff --git a/README.md b/README.md index 09ac11a..6c9ea4a 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,57 @@ otherwise reads exactly like one built on fresh data. Extended-support costs are `upgrade fleet` reports clusters it could not analyse rather than folding them into a pass. +`upgrade check` also lists the add-ons that must move with Kubernetes, how many patches the +cluster is behind, and an **Applications** section: per namespace, what the app team must +change before the upgrade and what is only affected by it. + +## Capacity + +```bash +rtz capacity # headroom per axis, node pools, pending pods +rtz capacity --section blocked # every pending pod and why (pools|nodes|blocked|storage|network|batch|special) +rtz capacity trend --days 30 # growth and days until each pool is full +rtz capacity cost # node cost per pool and the levers that change it +rtz capacity namespaces # requests, quota and pending pods per namespace +rtz capacity fleet # every cluster, soonest-full first +``` + +Usage gaps (nodes with no samples), truncated rows, uncollected quotas and unpriced nodes +are stated as warnings — an unread figure prints `?` or `unpriced`, never `0`. + +## Maintain + +```bash +rtz maintain items --within 90 # support deadlines across the org, soonest first +rtz maintain items --fail-on-days 30 # CI: exit 4 when a deadline is 30 days away or less +rtz maintain packages --ecosystem maven --q log4j +rtz maintain dependents data/StatefulSet/postgres # who connects to it +rtz maintain impact data/StatefulSet/postgres --target 17 +``` + +Platform items (Kubernetes, add-ons, system workloads) are hidden unless `--platform` — +`rtz upgrade check` owns those. A list the backend could not finish reading exits 1. + +## Add-on workspaces + +```bash +rtz addons nodepools [name] # Karpenter (alias: karpenter) +rtz addons cluster-autoscaler [group] # alias: ca +rtz addons ingress [ns/name] # Traefik routes (alias: traefik) +rtz addons mesh [ns/name] # Istio (alias: istio) +rtz addons gitops [ns/name] # Argo CD (alias: argocd) +rtz addons vpc-cni [node] # Amazon VPC CNI +rtz addons ebs-csi [node] # Amazon EBS CSI +rtz addons istio --fail-on high # CI gate on add-on findings +``` + +Without an argument each lists its objects with the worst finding; with one it prints that +object's findings with the command that verifies each. An add-on that is not installed, not +synced or has its rules off says so instead of printing an empty table. + +`-o json` / `-o yaml` on every command above prints the full server document, not the subset +the tables show. + ## Pre-merge gate ```bash diff --git a/internal/api/addons.go b/internal/api/addons.go new file mode 100644 index 0000000..50e1a98 --- /dev/null +++ b/internal/api/addons.go @@ -0,0 +1,416 @@ +package api + +import ( + "context" + "net/url" + "time" +) + +// The add-on workspaces (Karpenter, Cluster Autoscaler, Traefik ingress, Istio mesh, Argo CD, +// Amazon VPC CNI, Amazon EBS CSI) share one envelope: a status that is "OK" only when the +// add-on was found and read, a message saying why otherwise, and rows that each carry the +// rule findings ("reasons") that explain their state. + +// WorkspaceHead is the part of every workspace response that says how far to trust it. +type WorkspaceHead struct { + Status string `json:"status"` + Message string `json:"message"` + LastSyncAt *time.Time `json:"lastSyncAt"` + Addon *struct { + AddonID string `json:"addonId"` + DisplayName string `json:"displayName"` + Version string `json:"version"` + RuleCount int `json:"ruleCount"` + RulesEvaluated bool `json:"rulesEvaluated"` + } `json:"addon"` + Counts map[string]int `json:"counts"` +} + +// OK reports whether the add-on was found and read. Every other status is a "we could not +// see", never a clean bill of health. +func (h WorkspaceHead) OK() bool { return h.Status == "" || h.Status == "OK" } + +// AddonReason is one rule finding attached to a workspace row. +type AddonReason struct { + RuleID string `json:"ruleId"` + Severity string `json:"severity"` + Title string `json:"title"` + Message string `json:"message"` + Recommendation string `json:"recommendation"` + VerifyCommand string `json:"verifyCommand"` + ObjectKind string `json:"objectKind"` + ObjectRef string `json:"objectRef"` +} + +// WorkspaceEvent is a Kubernetes event in a workspace detail. +type WorkspaceEvent struct { + At *time.Time `json:"at"` + Type string `json:"type"` + Reason string `json:"reason"` + Message string `json:"message"` + ObjectKind string `json:"objectKind"` + ObjectName string `json:"objectName"` + Count *int `json:"count"` +} + +// --- Karpenter node pools ---------------------------------------------------- + +// NodePoolRow is one Karpenter NodePool. +type NodePoolRow struct { + Name string `json:"name"` + State string `json:"state"` + StateDetail string `json:"stateDetail"` + Nodes *int64 `json:"nodes"` + Weight *int `json:"weight"` + ConsolidationPolicy string `json:"consolidationPolicy"` + NodeClaimCount int `json:"nodeClaimCount"` + DriftedCount int `json:"driftedCount"` + NotReadyNodeCount int `json:"notReadyNodeCount"` + Reasons []AddonReason `json:"reasons"` +} + +// NodePools is the Karpenter workspace list. +type NodePools struct { + WorkspaceHead + Header *struct { + Controller *struct { + Version string `json:"version"` + } `json:"controller"` + ManagedBy string `json:"managedBy"` + } `json:"header"` + NodePools []NodePoolRow `json:"nodePools"` +} + +// NodePoolDetail is one NodePool with its claims and events. +type NodePoolDetail struct { + WorkspaceHead + NodePool *NodePoolRow `json:"nodePool"` + NodeClaims []struct { + Name string `json:"name"` + Phase string `json:"phase"` + PhaseReason string `json:"phaseReason"` + InstanceType string `json:"instanceType"` + CapacityType string `json:"capacityType"` + Zone string `json:"zone"` + NodeName string `json:"nodeName"` + Drifted bool `json:"drifted"` + } `json:"nodeClaims"` + Events []WorkspaceEvent `json:"events"` + EventsAvailable bool `json:"eventsAvailable"` +} + +func (c *Client) NodePools(ctx context.Context, orgID, clusterID string) (*Payload[NodePools], error) { + return GetPayload[NodePools](ctx, c, clusterPath(orgID, clusterID, "/autoscaling/nodepools"), nil) +} + +func (c *Client) NodePool(ctx context.Context, orgID, clusterID, name string) (*Payload[NodePoolDetail], error) { + return GetPayload[NodePoolDetail](ctx, c, + clusterPath(orgID, clusterID, "/autoscaling/nodepools/"+url.PathEscape(name)), nil) +} + +// --- Cluster Autoscaler node groups ------------------------------------------ + +// NodeGroupRow is one Cluster Autoscaler node group. +type NodeGroupRow struct { + Name string `json:"name"` + State string `json:"state"` + Detail string `json:"detail"` + Target *int `json:"target"` + MinSize *int `json:"minSize"` + MaxSize *int `json:"maxSize"` + NodeCount int `json:"nodeCount"` + Reasons []AddonReason `json:"reasons"` +} + +// NodeGroups is the Cluster Autoscaler workspace list. +type NodeGroups struct { + WorkspaceHead + Header *struct { + AutoscalerStatus string `json:"autoscalerStatus"` + StatusStale bool `json:"statusStale"` + Reasons []AddonReason `json:"reasons"` + } `json:"header"` + NodeGroups []NodeGroupRow `json:"nodeGroups"` +} + +// NodeGroupDetail is one node group with its nodes and events. +type NodeGroupDetail struct { + WorkspaceHead + NodeGroup *NodeGroupRow `json:"nodeGroup"` + Nodes []struct { + Name string `json:"name"` + Ready *bool `json:"ready"` + ScaleDownDisabled bool `json:"scaleDownDisabled"` + InstanceType string `json:"instanceType"` + Zone string `json:"zone"` + } `json:"nodes"` + Events []WorkspaceEvent `json:"events"` + EventsAvailable bool `json:"eventsAvailable"` +} + +func (c *Client) NodeGroups(ctx context.Context, orgID, clusterID string) (*Payload[NodeGroups], error) { + return GetPayload[NodeGroups](ctx, c, clusterPath(orgID, clusterID, "/autoscaling/cluster-autoscaler"), nil) +} + +func (c *Client) NodeGroup(ctx context.Context, orgID, clusterID, name string) (*Payload[NodeGroupDetail], error) { + return GetPayload[NodeGroupDetail](ctx, c, + clusterPath(orgID, clusterID, "/autoscaling/cluster-autoscaler/nodegroup"), url.Values{"name": {name}}) +} + +// --- Ingress routes (Traefik) ------------------------------------------------- + +// IngressRouteRow is one route (Ingress, IngressRoute, HTTPRoute …). +type IngressRouteRow struct { + Kind string `json:"kind"` + Namespace string `json:"namespace"` + Name string `json:"name"` + State string `json:"state"` + StateWhy string `json:"stateWhy"` + Matches []struct { + Hosts []string `json:"hosts"` + Paths []string `json:"paths"` + } `json:"matches"` + Reasons []AddonReason `json:"reasons"` +} + +// IngressRoutes is the Ingress workspace list. +type IngressRoutes struct { + WorkspaceHead + Routes []IngressRouteRow `json:"routes"` +} + +// IngressRouteDetail is one route with the workloads behind it. +type IngressRouteDetail struct { + WorkspaceHead + Route *IngressRouteRow `json:"route"` + BackendWorkloads []struct { + Kind string `json:"kind"` + Namespace string `json:"namespace"` + Name string `json:"name"` + Service string `json:"service"` + } `json:"backendWorkloads"` +} + +func (c *Client) IngressRoutes(ctx context.Context, orgID, clusterID string) (*Payload[IngressRoutes], error) { + return GetPayload[IngressRoutes](ctx, c, clusterPath(orgID, clusterID, "/ingress/routes"), nil) +} + +func (c *Client) IngressRoute(ctx context.Context, orgID, clusterID, namespace, name, kind string) (*Payload[IngressRouteDetail], error) { + return GetPayload[IngressRouteDetail](ctx, c, + clusterPath(orgID, clusterID, "/ingress/routes/"+url.PathEscape(namespace)+"/"+url.PathEscape(name)), kindQuery(kind)) +} + +// --- Mesh workloads (Istio) --------------------------------------------------- + +// MeshWorkloadRow is one workload's mesh state. +type MeshWorkloadRow struct { + Kind string `json:"kind"` + Namespace string `json:"namespace"` + Name string `json:"name"` + State string `json:"state"` + StateWhy string `json:"stateWhy"` + Proxy *struct { + Status string `json:"status"` + PodsMeshed int `json:"podsMeshed"` + Pods int `json:"pods"` + Version string `json:"version"` + } `json:"proxy"` + Mtls *struct { + Mode string `json:"mode"` + Known bool `json:"known"` + } `json:"mtls"` + Reasons []AddonReason `json:"reasons"` +} + +// MeshWorkloads is the Mesh workspace list. +type MeshWorkloads struct { + WorkspaceHead + Workloads []MeshWorkloadRow `json:"workloads"` +} + +// MeshWorkloadDetail is one workload with its pods' proxy facts. +type MeshWorkloadDetail struct { + WorkspaceHead + Workload *MeshWorkloadRow `json:"workload"` + Pods []struct { + Name string `json:"name"` + Meshed bool `json:"meshed"` + NativeSidecar bool `json:"nativeSidecar"` + Version string `json:"version"` + Revision string `json:"revision"` + OptedOut bool `json:"optedOut"` + } `json:"pods"` +} + +func (c *Client) MeshWorkloads(ctx context.Context, orgID, clusterID string) (*Payload[MeshWorkloads], error) { + return GetPayload[MeshWorkloads](ctx, c, clusterPath(orgID, clusterID, "/mesh/workloads"), nil) +} + +func (c *Client) MeshWorkload(ctx context.Context, orgID, clusterID, namespace, name, kind string) (*Payload[MeshWorkloadDetail], error) { + return GetPayload[MeshWorkloadDetail](ctx, c, + clusterPath(orgID, clusterID, "/mesh/workloads/"+url.PathEscape(namespace)+"/"+url.PathEscape(name)), kindQuery(kind)) +} + +// --- GitOps applications (Argo CD) ------------------------------------------- + +// GitOpsAppRow is one Argo CD Application. +type GitOpsAppRow struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + Project string `json:"project"` + Sync string `json:"sync"` + Health string `json:"health"` + OperationPhase string `json:"operationPhase"` + State string `json:"state"` + Reasons []AddonReason `json:"reasons"` +} + +// GitOpsApps is the GitOps workspace list. +type GitOpsApps struct { + WorkspaceHead + Applications []GitOpsAppRow `json:"applications"` +} + +// GitOpsAppDetail is one Application with the workloads it deploys. +type GitOpsAppDetail struct { + WorkspaceHead + Application *GitOpsAppRow `json:"application"` + Workloads []struct { + Kind string `json:"kind"` + Namespace string `json:"namespace"` + Name string `json:"name"` + DesiredReplicas *int `json:"desiredReplicas"` + ReadyReplicas *int `json:"readyReplicas"` + TrackedBy string `json:"trackedBy"` + } `json:"workloads"` +} + +func (c *Client) GitOpsApps(ctx context.Context, orgID, clusterID string) (*Payload[GitOpsApps], error) { + return GetPayload[GitOpsApps](ctx, c, clusterPath(orgID, clusterID, "/gitops/applications"), nil) +} + +func (c *Client) GitOpsApp(ctx context.Context, orgID, clusterID, namespace, name string) (*Payload[GitOpsAppDetail], error) { + return GetPayload[GitOpsAppDetail](ctx, c, + clusterPath(orgID, clusterID, "/gitops/applications/"+url.PathEscape(namespace)+"/"+url.PathEscape(name)), nil) +} + +// --- Amazon VPC CNI ----------------------------------------------------------- + +// VpcCniNodeRow is one node's pod-IP state. +type VpcCniNodeRow struct { + Name string `json:"name"` + State string `json:"state"` + StateDetail string `json:"stateDetail"` + InstanceType string `json:"instanceType"` + Zone string `json:"zone"` + MaxPods *int `json:"maxPods"` + IPMax *int `json:"ipMax"` + IPUsable *int `json:"ipUsable"` + IPAssigned *int `json:"ipAssigned"` + EnisAllocated *int `json:"enisAllocated"` + EnisMax *int `json:"enisMax"` + CNIPodRestarts *int `json:"cniPodRestarts"` + Reasons []AddonReason `json:"reasons"` +} + +// VpcCni is the Networking workspace list. +type VpcCni struct { + WorkspaceHead + Header *struct { + CNIVersion string `json:"cniVersion"` + NetworkPolicyEnforcement string `json:"networkPolicyEnforcement"` + Reasons []AddonReason `json:"reasons"` + } `json:"header"` + Nodes []VpcCniNodeRow `json:"nodes"` +} + +// VpcCniNodeDetail is one node with its ipamd / AWS API error counts. +type VpcCniNodeDetail struct { + WorkspaceHead + Node *VpcCniNodeRow `json:"node"` + Errors []struct { + Family string `json:"family"` + Key string `json:"key"` + Detail string `json:"detail"` + LastHour int `json:"lastHour"` + LastDay int `json:"lastDay"` + LastSeen *time.Time `json:"lastSeen"` + } `json:"errors"` +} + +func (c *Client) VpcCni(ctx context.Context, orgID, clusterID string) (*Payload[VpcCni], error) { + return GetPayload[VpcCni](ctx, c, clusterPath(orgID, clusterID, "/networking/vpc-cni"), nil) +} + +func (c *Client) VpcCniNode(ctx context.Context, orgID, clusterID, name string) (*Payload[VpcCniNodeDetail], error) { + return GetPayload[VpcCniNodeDetail](ctx, c, + clusterPath(orgID, clusterID, "/networking/vpc-cni/node"), url.Values{"name": {name}}) +} + +// --- Amazon EBS CSI ----------------------------------------------------------- + +// EbsCsiNodeRow is one node's EBS attach state. +type EbsCsiNodeRow struct { + Name string `json:"name"` + State string `json:"state"` + NodeReady *bool `json:"nodeReady"` + DriverRegistered *bool `json:"driverRegistered"` + Attached *int `json:"attached"` + Limit *int `json:"limit"` + FailingAttachments int `json:"failingAttachments"` + Reasons []AddonReason `json:"reasons"` +} + +// EbsCsiAttachment is one VolumeAttachment. +type EbsCsiAttachment struct { + Name string `json:"name"` + Node string `json:"node"` + PersistentVolume string `json:"persistentVolume"` + Attached bool `json:"attached"` + Problem string `json:"problem"` + Message string `json:"message"` + Since *time.Time `json:"since"` + Reasons []AddonReason `json:"reasons"` +} + +// EbsCsi is the Storage workspace list. +type EbsCsi struct { + WorkspaceHead + Header *struct { + DriverVersion string `json:"driverVersion"` + ControllerReady string `json:"controllerReady"` + NodePluginReady string `json:"nodePluginReady"` + } `json:"header"` + Nodes []EbsCsiNodeRow `json:"nodes"` + Attachments []EbsCsiAttachment `json:"attachments"` + ClusterReasons []AddonReason `json:"clusterReasons"` + Workloads []struct { + Kind string `json:"kind"` + Namespace string `json:"namespace"` + Name string `json:"name"` + Reasons []AddonReason `json:"reasons"` + } `json:"workloads"` +} + +// EbsCsiNodeDetail is one node with its attachments. +type EbsCsiNodeDetail struct { + WorkspaceHead + Node *EbsCsiNodeRow `json:"node"` + Attachments []EbsCsiAttachment `json:"attachments"` +} + +func (c *Client) EbsCsi(ctx context.Context, orgID, clusterID string) (*Payload[EbsCsi], error) { + return GetPayload[EbsCsi](ctx, c, clusterPath(orgID, clusterID, "/storage/ebs-csi"), nil) +} + +func (c *Client) EbsCsiNode(ctx context.Context, orgID, clusterID, name string) (*Payload[EbsCsiNodeDetail], error) { + return GetPayload[EbsCsiNodeDetail](ctx, c, + clusterPath(orgID, clusterID, "/storage/ebs-csi/node"), url.Values{"name": {name}}) +} + +func kindQuery(kind string) url.Values { + if kind == "" { + return nil + } + return url.Values{"kind": {kind}} +} diff --git a/internal/api/capacity.go b/internal/api/capacity.go new file mode 100644 index 0000000..eec9245 --- /dev/null +++ b/internal/api/capacity.go @@ -0,0 +1,409 @@ +package api + +import ( + "context" + "fmt" + "net/url" + "strconv" + "time" +) + +// The capacity types below are the subset of the backend's CapacityResponse family that the +// tables render. The full document is kept alongside (Payload.Raw) for -o json|yaml. + +// Res is a CPU / memory pair. A nil field means the backend did not know the value. +type Res struct { + CPUMillicores *int64 `json:"cpuMillicores"` + MemoryBytes *int64 `json:"memoryBytes"` +} + +// Capacity is one cluster's schedulable capacity from its last sync. +type Capacity struct { + Status string `json:"status"` + Message string `json:"message"` + LastSyncAt *time.Time `json:"lastSyncAt"` + ComputedAt *time.Time `json:"computedAt"` + Autoscaler *struct { + State string `json:"state"` + Acting bool `json:"acting"` + Detail string `json:"detail"` + ManagedBy string `json:"managedBy"` + } `json:"autoscaler"` + Usage *struct { + Status string `json:"status"` + Reason string `json:"reason"` + NodesWithSamples int `json:"nodesWithSamples"` + NodesWithoutSamples int `json:"nodesWithoutSamples"` + } `json:"usage"` + Headroom []struct { + Axis string `json:"axis"` + Unit string `json:"unit"` + Allocatable *int64 `json:"allocatable"` + Requested *int64 `json:"requested"` + RequestsCommitmentPct *float64 `json:"requestsCommitmentPct"` + Used *int64 `json:"used"` + UsedPct *float64 `json:"usedPct"` + Headroom *int64 `json:"headroom"` + LargestFit *int64 `json:"largestFit"` + LargestFitNode string `json:"largestFitNode"` + } `json:"headroom"` + ClusterCeiling *struct { + MaxNodes *int `json:"maxNodes"` + CurrentNodes int `json:"currentNodes"` + Source string `json:"source"` + Reason string `json:"reason"` + } `json:"clusterCeiling"` + Pools []CapacityPool `json:"pools"` + Nodes []struct { + Name string `json:"name"` + Pool string `json:"pool"` + Zone string `json:"zone"` + InstanceType string `json:"instanceType"` + CapacityType string `json:"capacityType"` + Eligible bool `json:"eligible"` + Exclusion string `json:"exclusion"` + Allocatable *Res `json:"allocatable"` + Requested *Res `json:"requested"` + Used *Res `json:"used"` + Headroom *Res `json:"headroom"` + Pods int `json:"pods"` + } `json:"nodes"` + Blocked []struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + OwnerKind string `json:"ownerKind"` + OwnerName string `json:"ownerName"` + PendingSeconds *int64 `json:"pendingSeconds"` + State string `json:"state"` + PrimaryCategory string `json:"primaryCategory"` + CapacityShortfall bool `json:"capacityShortfall"` + Message string `json:"message"` + NominatedNode string `json:"nominatedNode"` + VerifyCommand string `json:"verifyCommand"` + } `json:"blocked"` + BlockedSummary *struct { + Total int `json:"total"` + Listed int `json:"listed"` + CapacityShortfall int `json:"capacityShortfall"` + Gated int `json:"gated"` + Nominated int `json:"nominated"` + ByCategory map[string]int `json:"byCategory"` + EventsRead bool `json:"eventsRead"` + EventsTruncated bool `json:"eventsTruncated"` + } `json:"blockedSummary"` + Flags *struct { + NodeRowsTruncated bool `json:"nodeRowsTruncated"` + PodRowsTruncated bool `json:"podRowsTruncated"` + Nodeless bool `json:"nodeless"` + Notes []string `json:"notes"` + } `json:"flags"` + Storage *struct { + Status string `json:"status"` + Reason string `json:"reason"` + Metrics string `json:"metrics"` + MetricsReason string `json:"metricsReason"` + PVCs []struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + Phase string `json:"phase"` + StorageClass string `json:"storageClass"` + CapacityBytes *int64 `json:"capacityBytes"` + UsedBytes *int64 `json:"usedBytes"` + UsedPct *float64 `json:"usedPct"` + DaysToFull *float64 `json:"daysToFull"` + Forecast string `json:"forecast"` + MountedBy string `json:"mountedBy"` + UsageReason string `json:"usageReason"` + } `json:"pvcs"` + PVCsNotListed int `json:"pvcsNotListed"` + Pending []struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + StorageClass string `json:"storageClass"` + Reason string `json:"reason"` + Problem bool `json:"problem"` + PendingSeconds *int64 `json:"pendingSeconds"` + } `json:"pending"` + Notes []string `json:"notes"` + } `json:"storage"` + Network *struct { + Status string `json:"status"` + Reason string `json:"reason"` + CNIVersion string `json:"cniVersion"` + PodsWaitingForIP *int `json:"podsWaitingForIp"` + Pools []struct { + Name string `json:"name"` + Nodes int `json:"nodes"` + IPHeadroom *int64 `json:"ipHeadroom"` + SlotHeadroom *int64 `json:"slotHeadroom"` + NodesIPsFirst int `json:"nodesIpsFirst"` + LaunchableNodes *int `json:"launchableNodes"` + LaunchableReason string `json:"launchableReason"` + SubnetExhausted bool `json:"subnetExhausted"` + LaunchSubnets []string `json:"launchSubnets"` + } `json:"pools"` + Notes []string `json:"notes"` + } `json:"network"` + Batch *struct { + Status string `json:"status"` + Message string `json:"message"` + Collected bool `json:"collected"` + PendingJobs int `json:"pendingJobs"` + PendingPods int `json:"pendingPods"` + Verdicts map[string]int `json:"verdicts"` + Jobs []struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + CronJob string `json:"cronJob"` + Running int `json:"running"` + Pending int `json:"pending"` + OldestPendingSeconds *int64 `json:"oldestPendingSeconds"` + } `json:"jobs"` + JobsNotListed int `json:"jobsNotListed"` + CronJobs []struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + Schedule string `json:"schedule"` + Suspended bool `json:"suspended"` + ActiveRuns int `json:"activeRuns"` + Verdict string `json:"verdict"` + VerdictReason string `json:"verdictReason"` + } `json:"cronJobs"` + CronJobsNotListed int `json:"cronJobsNotListed"` + Notes []string `json:"notes"` + } `json:"batch"` + Special *struct { + Status string `json:"status"` + Reason string `json:"reason"` + Resources []struct { + Name string `json:"name"` + Kind string `json:"kind"` + Unit string `json:"unit"` + Allocatable *int64 `json:"allocatable"` + Requested int64 `json:"requested"` + RequestedPct *float64 `json:"requestedPct"` + Free *int64 `json:"free"` + NodesOffered int `json:"nodesOffering"` + BlockedPods int `json:"blockedPods"` + } `json:"resources"` + Notes []string `json:"notes"` + } `json:"special"` +} + +// CapacityPool is one node pool's capacity. +type CapacityPool struct { + Name string `json:"name"` + Source string `json:"source"` + AutoscalerState string `json:"autoscalerState"` + Nodes int `json:"nodes"` + EligibleNodes int `json:"eligibleNodes"` + Allocatable *Res `json:"allocatable"` + Requested *Res `json:"requested"` + Used *Res `json:"used"` + Headroom *Res `json:"headroom"` + CPURequestsCommitmentPct *float64 `json:"cpuRequestsCommitmentPct"` + MemoryRequestsCommitmentPct *float64 `json:"memoryRequestsCommitmentPct"` + CPUUsedPct *float64 `json:"cpuUsedPct"` + MemoryUsedPct *float64 `json:"memoryUsedPct"` + Pods int `json:"pods"` + AllocatablePods *int64 `json:"allocatablePods"` + NodeCeiling *int64 `json:"nodeCeiling"` + RoomToGrow *struct { + Nodes *int64 `json:"nodes"` + AtCeiling bool `json:"atCeiling"` + CeilingSource string `json:"ceilingSource"` + Reason string `json:"reason"` + } `json:"roomToGrow"` +} + +// Capacity fetches the cluster's capacity model. +func (c *Client) Capacity(ctx context.Context, orgID, clusterID string) (*Payload[Capacity], error) { + return GetPayload[Capacity](ctx, c, clusterPath(orgID, clusterID, "/capacity"), nil) +} + +// CapacityForecast is one axis's days-to-full projection. +type CapacityForecast struct { + Axis string `json:"axis"` + Status string `json:"status"` + Reason string `json:"reason"` + Days *int `json:"days"` + FullOn string `json:"fullOn"` + CurrentPct *float64 `json:"currentPct"` + Basis string `json:"basis"` +} + +// CapacityTrend is the daily capacity history and its forecast. +type CapacityTrend struct { + Status string `json:"status"` + Message string `json:"message"` + Days int `json:"days"` + From string `json:"from"` + To string `json:"to"` + Target float64 `json:"target"` + TargetSource string `json:"targetSource"` + MinDays int `json:"minDays"` + DaysCollected int `json:"daysCollected"` + Pools []struct { + Name string `json:"name"` + Source string `json:"source"` + Autoscaled bool `json:"autoscaled"` + CPU *CapacityForecast `json:"cpu"` + Memory *CapacityForecast `json:"memory"` + Grade *struct { + Status string `json:"status"` + CPUPct *float64 `json:"cpuPct"` + MemoryPct *float64 `json:"memoryPct"` + TargetPct float64 `json:"targetPct"` + Reason string `json:"reason"` + } `json:"grade"` + } `json:"pools"` + Growth []struct { + Namespace string `json:"namespace"` + CPUDelta int64 `json:"cpuDelta"` + MemoryDelta int64 `json:"memoryDelta"` + Appeared bool `json:"appeared"` + Gone bool `json:"gone"` + } `json:"growth"` + Notes []string `json:"notes"` +} + +// CapacityTrend fetches the trend; days 0 lets the backend pick its default window. +func (c *Client) CapacityTrend(ctx context.Context, orgID, clusterID string, days int) (*Payload[CapacityTrend], error) { + q := url.Values{} + if days > 0 { + q.Set("days", strconv.Itoa(days)) + } + return GetPayload[CapacityTrend](ctx, c, clusterPath(orgID, clusterID, "/capacity/trend"), q) +} + +// CapacityCost is the cluster's node cost at list (or Cost Explorer) prices. +type CapacityCost struct { + Status string `json:"status"` + Message string `json:"message"` + PriceSource *struct { + Provider string `json:"provider"` + Label string `json:"label"` + OnDemandSource string `json:"onDemandSource"` + OnDemandDate string `json:"onDemandDate"` + AgeDays *int64 `json:"ageDays"` + } `json:"priceSource"` + Nodes int `json:"nodes"` + PricedNodes int `json:"pricedNodes"` + ClusterHourly *float64 `json:"clusterHourly"` + ClusterMonthly *float64 `json:"clusterMonthly"` + EffectiveMonthly *float64 `json:"effectiveMonthly"` + Pools []struct { + Pool string `json:"pool"` + Source string `json:"source"` + Nodes int `json:"nodes"` + PricedNodes int `json:"pricedNodes"` + Hourly *float64 `json:"hourly"` + Monthly *float64 `json:"monthly"` + CPURequestsPct *float64 `json:"cpuRequestsPct"` + MemoryRequestsPct *float64 `json:"memoryRequestsPct"` + } `json:"pools"` + Levers []struct { + ID string `json:"id"` + Label string `json:"label"` + Saving bool `json:"saving"` + Monthly *float64 `json:"monthly"` + Basis string `json:"basis"` + Reason string `json:"reason"` + ActsIn string `json:"actsIn"` + } `json:"levers"` + Coverage *struct { + State string `json:"state"` + Detail string `json:"detail"` + } `json:"coverage"` + Notes []string `json:"notes"` +} + +// CapacityCost fetches the Cost tab. +func (c *Client) CapacityCost(ctx context.Context, orgID, clusterID string) (*Payload[CapacityCost], error) { + return GetPayload[CapacityCost](ctx, c, clusterPath(orgID, clusterID, "/capacity/cost"), nil) +} + +// CapacityNamespaces is per-namespace requests, quotas and QoS. +type CapacityNamespaces struct { + Status string `json:"status"` + Message string `json:"message"` + QuotasCollected bool `json:"quotasCollected"` + Namespaces []struct { + Namespace string `json:"namespace"` + Pods int `json:"pods"` + PendingPods int `json:"pendingPods"` + Requested *Res `json:"requested"` + Used *Res `json:"used"` + CPUShare *float64 `json:"cpuShare"` + MemoryShare *float64 `json:"memoryShare"` + QuotaStatus string `json:"quotaStatus"` + Fullest *struct { + Resource string `json:"resource"` + Hard string `json:"hard"` + Used string `json:"used"` + Pct *float64 `json:"pct"` + } `json:"fullest"` + } `json:"namespaces"` + Notes []string `json:"notes"` +} + +// CapacityNamespaces fetches the Namespaces section. +func (c *Client) CapacityNamespaces(ctx context.Context, orgID, clusterID string) (*Payload[CapacityNamespaces], error) { + return GetPayload[CapacityNamespaces](ctx, c, clusterPath(orgID, clusterID, "/capacity/namespaces"), nil) +} + +// FleetAxis is one resource axis summed over clusters. +type FleetAxis struct { + Allocatable *int64 `json:"allocatable"` + Requested *int64 `json:"requested"` + RequestsCommitmentPct *float64 `json:"requestsCommitmentPct"` + Used *int64 `json:"used"` + UsedPct *float64 `json:"usedPct"` + Headroom *int64 `json:"headroom"` +} + +// FleetSoonestFull names the pool and axis that fills first. +type FleetSoonestFull struct { + ClusterName string `json:"clusterName"` + Pool string `json:"pool"` + Axis string `json:"axis"` + Days *int `json:"days"` + FullOn string `json:"fullOn"` + Status string `json:"status"` +} + +// FleetCapacity is capacity across the org's clusters. +type FleetCapacity struct { + ClustersTotal int `json:"clustersTotal"` + ClustersAnalyzed int `json:"clustersAnalyzed"` + Truncated bool `json:"truncated"` + Totals *struct { + ClustersCounted int `json:"clustersCounted"` + CountedFromEarlierSync int `json:"countedFromEarlierSync"` + NotCounted map[string]int `json:"notCounted"` + CPU *FleetAxis `json:"cpu"` + Memory *FleetAxis `json:"memory"` + Pending *int `json:"pending"` + CapacityShortfall *int `json:"capacityShortfall"` + SoonestFull *FleetSoonestFull `json:"soonestFull"` + } `json:"totals"` + Clusters []struct { + ClusterID string `json:"clusterId"` + Name string `json:"name"` + Status string `json:"status"` + Reason string `json:"reason"` + CPU *FleetAxis `json:"cpu"` + Memory *FleetAxis `json:"memory"` + Pending *int `json:"pending"` + CapacityShortfall *int `json:"capacityShortfall"` + AutoscalerState string `json:"autoscalerState"` + SoonestFull *FleetSoonestFull `json:"soonestFull"` + Grade string `json:"grade"` + FromEarlierSync bool `json:"fromEarlierSync"` + } `json:"clusters"` +} + +// FleetCapacity fetches capacity for every cluster in the org. +func (c *Client) FleetCapacity(ctx context.Context, orgID string) (*Payload[FleetCapacity], error) { + return GetPayload[FleetCapacity](ctx, c, fmt.Sprintf("/eac/api/1.0/orgs/%s/capacity/fleet", orgID), nil) +} diff --git a/internal/api/client.go b/internal/api/client.go index 8e3331c..473c135 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -310,3 +310,57 @@ func (c *Client) postRawOnce(ctx context.Context, path string, headers map[strin } return &RawResponse{Status: resp.StatusCode, ContentType: resp.Header.Get("Content-Type"), Body: raw}, nil } + +// Payload is a response decoded twice: Typed is the subset a table renders, Raw is the whole +// server document. Structured output (-o json|yaml) prints Raw, because the typed struct only +// carries the fields a table needs and re-encoding it would silently drop the rest. +type Payload[T any] struct { + Typed T + Raw any +} + +// GetPayload is Get that also keeps the full document for lossless structured output. +func GetPayload[T any](ctx context.Context, c *Client, path string, query url.Values) (*Payload[T], error) { + raw, err := c.Do(ctx, http.MethodGet, path, query, nil) + if err != nil { + return nil, err + } + p := &Payload[T]{} + if len(raw) == 0 || string(raw) == "null" { + return p, nil + } + if err := json.Unmarshal(raw, &p.Typed); err != nil { + return nil, fmt.Errorf("decode %s: %w", path, err) + } + d := json.NewDecoder(bytes.NewReader(raw)) + d.UseNumber() + if err := d.Decode(&p.Raw); err != nil { + return nil, fmt.Errorf("decode %s: %w", path, err) + } + p.Raw = exactNumbers(p.Raw) + return p, nil +} + +// exactNumbers turns json.Number into int64 where it is integral, float64 otherwise. A plain +// decode makes every number a float64, and YAML then prints a byte count as 1.073741824e+09; +// json.Number left as is prints as a quoted string in YAML. +func exactNumbers(v any) any { + switch t := v.(type) { + case map[string]any: + for k, e := range t { + t[k] = exactNumbers(e) + } + case []any: + for i, e := range t { + t[i] = exactNumbers(e) + } + case json.Number: + if i, err := t.Int64(); err == nil { + return i + } + if f, err := t.Float64(); err == nil { + return f + } + } + return v +} diff --git a/internal/api/maintain.go b/internal/api/maintain.go new file mode 100644 index 0000000..4265dc3 --- /dev/null +++ b/internal/api/maintain.go @@ -0,0 +1,195 @@ +package api + +import ( + "context" + "fmt" + "net/url" + "strconv" + "time" +) + +// MaintainItem is one lifecycle item (Kubernetes, an add-on, a runtime, a data service) and +// its next support deadline. +type MaintainItem struct { + ClusterID string `json:"clusterId"` + ClusterName string `json:"clusterName"` + ItemKey string `json:"itemKey"` + ItemType string `json:"itemType"` + DisplayName string `json:"displayName"` + Version string `json:"version"` + Cycle string `json:"cycle"` + Location string `json:"location"` + Product string `json:"product"` + Deadline string `json:"deadline"` + DeadlineKind string `json:"deadlineKind"` + DaysLeft *int `json:"daysLeft"` + SupportState string `json:"supportState"` + Source string `json:"source"` + SourceURL string `json:"sourceUrl"` + Confidence string `json:"confidence"` + Owner string `json:"owner"` + Note string `json:"note"` + Platform bool `json:"platform"` +} + +// MaintainList is the org's Maintain items. +type MaintainList struct { + Items []MaintainItem `json:"items"` + ReadFailed bool `json:"readFailed"` + Truncated bool `json:"truncated"` +} + +// MaintainItems fetches every Maintain item the caller can see. +func (c *Client) MaintainItems(ctx context.Context, orgID string) (*Payload[MaintainList], error) { + return GetPayload[MaintainList](ctx, c, fmt.Sprintf("/eac/api/1.0/orgs/%s/maintain/items", orgID), nil) +} + +// MaintainInventory is the fleet's running packages, most-used first. +type MaintainInventory struct { + Ecosystem string `json:"ecosystem"` + Q string `json:"q"` + Page int `json:"page"` + Size int `json:"size"` + Total int `json:"total"` + Items []struct { + Ecosystem string `json:"ecosystem"` + Name string `json:"name"` + Versions []string `json:"versions"` + VersionsCapped bool `json:"versionsCapped"` + Workloads int `json:"workloads"` + Pods int `json:"pods"` + EOL *struct { + Product string `json:"product"` + Cycle string `json:"cycle"` + Deadline string `json:"deadline"` + DaysLeft *int `json:"daysLeft"` + SupportState string `json:"supportState"` + } `json:"eol"` + } `json:"items"` + WorkloadsWithPackageList int `json:"workloadsWithPackageList"` + WorkloadsWithoutPackageList int `json:"workloadsWithoutPackageList"` + ReadFailed bool `json:"readFailed"` + Truncated bool `json:"truncated"` +} + +// MaintainInventory fetches one page of the package inventory. +func (c *Client) MaintainInventory(ctx context.Context, orgID, ecosystem, q string, page, size int) (*Payload[MaintainInventory], error) { + v := url.Values{} + if ecosystem != "" { + v.Set("ecosystem", ecosystem) + } + if q != "" { + v.Set("q", q) + } + v.Set("page", strconv.Itoa(page)) + v.Set("size", strconv.Itoa(size)) + return GetPayload[MaintainInventory](ctx, c, + fmt.Sprintf("/eac/api/1.0/orgs/%s/maintain/packages/inventory", orgID), v) +} + +// DataServiceRef names one data service (a database, cache, broker) inside a cluster. +type DataServiceRef struct { + ClusterID, Namespace, Kind, Name string +} + +func (r DataServiceRef) query() url.Values { + v := url.Values{} + v.Set("clusterId", r.ClusterID) + v.Set("namespace", r.Namespace) + v.Set("kind", r.Kind) + v.Set("name", r.Name) + return v +} + +// DataServiceInbound is the callers that could not be named (via a node port, a load +// balancer, or nothing we can see). +type DataServiceInbound struct { + Reported bool `json:"reported"` + Truncated bool `json:"truncated"` + ViaNode int64 `json:"viaNode"` + Other int64 `json:"other"` +} + +// DataServiceDependents is who connects to a data service. +type DataServiceDependents struct { + Coverage string `json:"coverage"` + LastSnapshotAt *time.Time `json:"lastSnapshotAt"` + NodesExpected int `json:"nodesExpected"` + NodesReported int `json:"nodesReported"` + Services []string `json:"services"` + Dependents []struct { + Namespace string `json:"namespace"` + Kind string `json:"kind"` + Name string `json:"name"` + Via string `json:"via"` + Port int `json:"port"` + LastSeen *time.Time `json:"lastSeen"` + Sockets int64 `json:"sockets"` + Role string `json:"role"` + Pooler string `json:"pooler"` + ClusterName string `json:"clusterName"` + } `json:"dependents"` + Truncated bool `json:"truncated"` + ReadFailed bool `json:"readFailed"` + PlatformExcluded int `json:"platformExcluded"` + Inbound *DataServiceInbound `json:"inbound"` + OtherClustersHidden int `json:"otherClustersHidden"` +} + +// DataServiceDependents fetches the blast radius of one data service. +func (c *Client) DataServiceDependents(ctx context.Context, orgID string, ref DataServiceRef) (*Payload[DataServiceDependents], error) { + return GetPayload[DataServiceDependents](ctx, c, + fmt.Sprintf("/eac/api/1.0/orgs/%s/maintain/data-services/dependents", orgID), ref.query()) +} + +// DataServiceImpact is what breaks if one data service is upgraded to a target version. +type DataServiceImpact struct { + Product string `json:"product"` + DisplayName string `json:"displayName"` + CurrentVersion string `json:"currentVersion"` + Target string `json:"target"` + TargetDefaulted bool `json:"targetDefaulted"` + RulePack bool `json:"rulePack"` + Operator string `json:"operator"` + UpgradeNotes []struct { + ID string `json:"id"` + Since string `json:"since"` + Severity string `json:"severity"` + Title string `json:"title"` + } `json:"upgradeNotes"` + Coverage string `json:"coverage"` + Dependents []struct { + Namespace string `json:"namespace"` + Kind string `json:"kind"` + Name string `json:"name"` + Verdict string `json:"verdict"` + Reason string `json:"reason"` + ClusterName string `json:"clusterName"` + Drivers []struct { + Driver string `json:"driver"` + Version string `json:"version"` + } `json:"drivers"` + Via []string `json:"via"` + } `json:"dependents"` + Summary *struct { + BumpDriver int `json:"bumpDriver"` + Unknown int `json:"unknown"` + Review int `json:"review"` + Ready int `json:"ready"` + } `json:"summary"` + PlatformExcluded int `json:"platformExcluded"` + Truncated bool `json:"truncated"` + ReadFailed bool `json:"readFailed"` + Inbound *DataServiceInbound `json:"inbound"` + OtherClustersHidden int `json:"otherClustersHidden"` +} + +// DataServiceImpact fetches the upgrade impact; an empty target lets the backend pick one. +func (c *Client) DataServiceImpact(ctx context.Context, orgID string, ref DataServiceRef, target string) (*Payload[DataServiceImpact], error) { + v := ref.query() + if target != "" { + v.Set("target", target) + } + return GetPayload[DataServiceImpact](ctx, c, + fmt.Sprintf("/eac/api/1.0/orgs/%s/maintain/data-services/impact", orgID), v) +} diff --git a/internal/api/upgrade.go b/internal/api/upgrade.go index 032c615..fab8199 100644 --- a/internal/api/upgrade.go +++ b/internal/api/upgrade.go @@ -39,6 +39,50 @@ type UpgradeReadiness struct { Status string `json:"status"` Detail string `json:"detail"` } `json:"coverage"` + // AppImpact groups the findings by the namespace (application) they hit: what an app team + // must change before the upgrade, and what is only affected by it. + AppImpact *struct { + Applications []struct { + Namespace string `json:"namespace"` + MustChange []AppImpactItem `json:"mustChange"` + Affected []AppImpactItem `json:"affected"` + } `json:"applications"` + PlatformFindings int `json:"platformFindings"` + UnattributedObjects int `json:"unattributedObjects"` + NamespacesRead bool `json:"namespacesRead"` + } `json:"appImpact"` + // AddonHops are add-ons that must move before (or right after) Kubernetes does. + AddonHops []struct { + AddonID string `json:"addonId"` + InstalledVersion string `json:"installedVersion"` + RequiredVersion string `json:"requiredVersion"` + Reason string `json:"reason"` + KubernetesFirst bool `json:"kubernetesFirst"` + ThenVersion string `json:"thenVersion"` + } `json:"addonHops"` + PatchCurrency *struct { + CurrentVersion string `json:"currentVersion"` + LatestPatchVersion string `json:"latestPatchVersion"` + PatchesBehind int `json:"patchesBehind"` + UpToDate bool `json:"upToDate"` + Status string `json:"status"` + Advisory string `json:"advisory"` + DataSourced bool `json:"dataSourced"` + } `json:"patchCurrency"` +} + +// AppImpactItem is one upgrade finding as it lands on an application. +type AppImpactItem struct { + RuleID string `json:"ruleId"` + Title string `json:"title"` + Severity string `json:"severity"` + AppliesAtVersion string `json:"appliesAtVersion"` + Addon string `json:"addon"` + Impact string `json:"impact"` + Recommendation string `json:"recommendation"` + VerifyCommand string `json:"verifyCommand"` + Objects []string `json:"objects"` + Component string `json:"component"` } // FleetUpgradeItem is one cluster's row in the fleet view. @@ -60,16 +104,12 @@ type FleetUpgradeItem struct { // UpgradeReadiness fetches one cluster's readiness. targetVersion is optional; the backend // picks the implied next version when it is empty. -func (c *Client) UpgradeReadiness(ctx context.Context, orgID, clusterID, targetVersion string) (*UpgradeReadiness, error) { +func (c *Client) UpgradeReadiness(ctx context.Context, orgID, clusterID, targetVersion string) (*Payload[UpgradeReadiness], error) { q := url.Values{} if targetVersion != "" { q.Set("targetVersion", targetVersion) } - out, err := Get[UpgradeReadiness](ctx, c, clusterPath(orgID, clusterID, "/upgrade-readiness"), q) - if err != nil { - return nil, err - } - return &out, nil + return GetPayload[UpgradeReadiness](ctx, c, clusterPath(orgID, clusterID, "/upgrade-readiness"), q) } // FleetUpgradeReadiness fetches every cluster's readiness at its implied target. diff --git a/internal/cli/addons.go b/internal/cli/addons.go new file mode 100644 index 0000000..6af42cf --- /dev/null +++ b/internal/cli/addons.go @@ -0,0 +1,429 @@ +package cli + +import ( + "context" + "fmt" + "io" + "strconv" + "strings" + + "github.com/spf13/cobra" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/render" + "github.com/runtimez-com/runtimez-cli/internal/view" +) + +func newAddonsCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "addons", + Aliases: []string{"addon"}, + Short: "Add-on workspaces: Karpenter, Cluster Autoscaler, Traefik, Istio, Argo CD, VPC CNI, EBS CSI", + Long: `Each add-on workspace lists its objects with their state and the rule findings behind it. +Pass an object to see its findings, the command that verifies each, and its detail. + +--fail-on exits 4 when any listed finding reaches that severity.`, + } + cmd.AddCommand( + addonCmd(addonSpec[api.NodePools, api.NodePoolDetail]{ + use: "nodepools [name]", aliases: []string{"karpenter", "np"}, what: "Karpenter NodePools", + list: (*api.Client).NodePools, + detail: func(c *api.Client, ctx context.Context, org, cl string, a []string, _ string) (*api.Payload[api.NodePoolDetail], error) { + return c.NodePool(ctx, org, cl, a[0]) + }, + head: func(l *api.NodePools) api.WorkspaceHead { return l.WorkspaceHead }, + rows: func(e *env, w io.Writer, l *api.NodePools) ([]api.AddonReason, error) { + if h := l.Header; h != nil && h.ManagedBy != "" { + fmt.Fprintf(w, " Managed by %s\n", h.ManagedBy) + } + var rs []api.AddonReason + for _, p := range l.NodePools { + rs = append(rs, p.Reasons...) + } + return rs, printSection(e, w, "NodePools", view.NodePoolsTable(l.NodePools)) + }, + show: func(e *env, w io.Writer, d *api.NodePoolDetail) error { + if d.NodePool == nil { + return nil + } + stateLine(w, "NodePool "+d.NodePool.Name, d.NodePool.State, d.NodePool.StateDetail) + return detailSections(e, w, d.NodePool.Reasons, + section{"NodeClaims", view.NodeClaimsTable(d)}, + eventsSection(d.Events, d.EventsAvailable)) + }, + }), + addonCmd(addonSpec[api.NodeGroups, api.NodeGroupDetail]{ + use: "cluster-autoscaler [nodegroup]", aliases: []string{"ca"}, what: "Cluster Autoscaler node groups", + list: (*api.Client).NodeGroups, + detail: func(c *api.Client, ctx context.Context, org, cl string, a []string, _ string) (*api.Payload[api.NodeGroupDetail], error) { + return c.NodeGroup(ctx, org, cl, a[0]) + }, + head: func(l *api.NodeGroups) api.WorkspaceHead { return l.WorkspaceHead }, + rows: func(e *env, w io.Writer, l *api.NodeGroups) ([]api.AddonReason, error) { + var rs []api.AddonReason + if h := l.Header; h != nil { + fmt.Fprintf(w, " Autoscaler status: %s\n", render.Dash(h.AutoscalerStatus)) + if h.StatusStale { + fmt.Fprintln(w, " (the status ConfigMap is stale — CA may not be running)") + } + rs = append(rs, h.Reasons...) + if len(h.Reasons) > 0 { + if err := printSection(e, w, "Cluster-wide findings", view.ReasonsTable(h.Reasons)); err != nil { + return nil, err + } + } + } + for _, g := range l.NodeGroups { + rs = append(rs, g.Reasons...) + } + return rs, printSection(e, w, "Node groups", view.NodeGroupsTable(l.NodeGroups)) + }, + show: func(e *env, w io.Writer, d *api.NodeGroupDetail) error { + if d.NodeGroup == nil { + return nil + } + stateLine(w, "Node group "+d.NodeGroup.Name, d.NodeGroup.State, d.NodeGroup.Detail) + return detailSections(e, w, d.NodeGroup.Reasons, + section{"Nodes", view.NodeGroupNodesTable(d)}, + eventsSection(d.Events, d.EventsAvailable)) + }, + }), + addonCmd(addonSpec[api.IngressRoutes, api.IngressRouteDetail]{ + use: "ingress [namespace/name]", aliases: []string{"traefik", "routes"}, what: "Traefik ingress routes", kindFlag: true, + list: (*api.Client).IngressRoutes, + detail: func(c *api.Client, ctx context.Context, org, cl string, a []string, kind string) (*api.Payload[api.IngressRouteDetail], error) { + return c.IngressRoute(ctx, org, cl, a[0], a[1], kind) + }, + head: func(l *api.IngressRoutes) api.WorkspaceHead { return l.WorkspaceHead }, + rows: func(e *env, w io.Writer, l *api.IngressRoutes) ([]api.AddonReason, error) { + var rs []api.AddonReason + for _, r := range l.Routes { + rs = append(rs, r.Reasons...) + } + return rs, printSection(e, w, "Routes", view.IngressRoutesTable(l.Routes)) + }, + show: func(e *env, w io.Writer, d *api.IngressRouteDetail) error { + if d.Route == nil { + return nil + } + stateLine(w, d.Route.Kind+" "+d.Route.Namespace+"/"+d.Route.Name, d.Route.State, d.Route.StateWhy) + return detailSections(e, w, d.Route.Reasons, section{"Backend workloads", view.BackendWorkloadsTable(d)}) + }, + }), + addonCmd(addonSpec[api.MeshWorkloads, api.MeshWorkloadDetail]{ + use: "mesh [namespace/name]", aliases: []string{"istio"}, what: "Istio mesh workloads", kindFlag: true, + list: (*api.Client).MeshWorkloads, + detail: func(c *api.Client, ctx context.Context, org, cl string, a []string, kind string) (*api.Payload[api.MeshWorkloadDetail], error) { + return c.MeshWorkload(ctx, org, cl, a[0], a[1], kind) + }, + head: func(l *api.MeshWorkloads) api.WorkspaceHead { return l.WorkspaceHead }, + rows: func(e *env, w io.Writer, l *api.MeshWorkloads) ([]api.AddonReason, error) { + var rs []api.AddonReason + for _, m := range l.Workloads { + rs = append(rs, m.Reasons...) + } + return rs, printSection(e, w, "Workloads", view.MeshWorkloadsTable(l.Workloads)) + }, + show: func(e *env, w io.Writer, d *api.MeshWorkloadDetail) error { + if d.Workload == nil { + return nil + } + stateLine(w, d.Workload.Kind+" "+d.Workload.Namespace+"/"+d.Workload.Name, d.Workload.State, d.Workload.StateWhy) + return detailSections(e, w, d.Workload.Reasons, section{"Pods", view.MeshPodsTable(d)}) + }, + }), + addonCmd(addonSpec[api.GitOpsApps, api.GitOpsAppDetail]{ + use: "gitops [namespace/name]", aliases: []string{"argocd", "apps"}, what: "Argo CD Applications", + list: (*api.Client).GitOpsApps, + detail: func(c *api.Client, ctx context.Context, org, cl string, a []string, _ string) (*api.Payload[api.GitOpsAppDetail], error) { + return c.GitOpsApp(ctx, org, cl, a[0], a[1]) + }, + head: func(l *api.GitOpsApps) api.WorkspaceHead { return l.WorkspaceHead }, + rows: func(e *env, w io.Writer, l *api.GitOpsApps) ([]api.AddonReason, error) { + var rs []api.AddonReason + for _, a := range l.Applications { + rs = append(rs, a.Reasons...) + } + return rs, printSection(e, w, "Applications", view.GitOpsAppsTable(l.Applications)) + }, + show: func(e *env, w io.Writer, d *api.GitOpsAppDetail) error { + if d.Application == nil { + return nil + } + a := d.Application + stateLine(w, "Application "+a.Namespace+"/"+a.Name, a.State, "sync "+render.Dash(a.Sync)+", health "+render.Dash(a.Health)) + return detailSections(e, w, a.Reasons, section{"Workloads", view.GitOpsWorkloadsTable(d)}) + }, + }), + addonCmd(addonSpec[api.VpcCni, api.VpcCniNodeDetail]{ + use: "vpc-cni [node]", aliases: []string{"cni"}, what: "Amazon VPC CNI nodes", + list: (*api.Client).VpcCni, + detail: func(c *api.Client, ctx context.Context, org, cl string, a []string, _ string) (*api.Payload[api.VpcCniNodeDetail], error) { + return c.VpcCniNode(ctx, org, cl, a[0]) + }, + head: func(l *api.VpcCni) api.WorkspaceHead { return l.WorkspaceHead }, + rows: func(e *env, w io.Writer, l *api.VpcCni) ([]api.AddonReason, error) { + var rs []api.AddonReason + if h := l.Header; h != nil { + fmt.Fprintf(w, " CNI %s · network policy %s\n", render.Dash(h.CNIVersion), render.Dash(h.NetworkPolicyEnforcement)) + rs = append(rs, h.Reasons...) + if len(h.Reasons) > 0 { + if err := printSection(e, w, "Cluster-wide findings", view.ReasonsTable(h.Reasons)); err != nil { + return nil, err + } + } + } + for _, n := range l.Nodes { + rs = append(rs, n.Reasons...) + } + return rs, printSection(e, w, "Nodes", view.VpcCniNodesTable(l.Nodes)) + }, + show: func(e *env, w io.Writer, d *api.VpcCniNodeDetail) error { + if d.Node == nil { + return nil + } + stateLine(w, "Node "+d.Node.Name, d.Node.State, d.Node.StateDetail) + return detailSections(e, w, d.Node.Reasons, section{"Errors", view.VpcCniErrorsTable(d)}) + }, + }), + addonCmd(addonSpec[api.EbsCsi, api.EbsCsiNodeDetail]{ + use: "ebs-csi [node]", aliases: []string{"ebs"}, what: "Amazon EBS CSI nodes", + list: (*api.Client).EbsCsi, + detail: func(c *api.Client, ctx context.Context, org, cl string, a []string, _ string) (*api.Payload[api.EbsCsiNodeDetail], error) { + return c.EbsCsiNode(ctx, org, cl, a[0]) + }, + head: func(l *api.EbsCsi) api.WorkspaceHead { return l.WorkspaceHead }, + rows: func(e *env, w io.Writer, l *api.EbsCsi) ([]api.AddonReason, error) { + var rs []api.AddonReason + if h := l.Header; h != nil { + fmt.Fprintf(w, " Driver %s · controller %s · node plugin %s\n", render.Dash(h.DriverVersion), + render.Dash(h.ControllerReady), render.Dash(h.NodePluginReady)) + } + rs = append(rs, l.ClusterReasons...) + if len(l.ClusterReasons) > 0 { + if err := printSection(e, w, "Cluster-wide findings", view.ReasonsTable(l.ClusterReasons)); err != nil { + return nil, err + } + } + for _, n := range l.Nodes { + rs = append(rs, n.Reasons...) + } + if err := printSection(e, w, "Nodes", view.EbsCsiNodesTable(l.Nodes)); err != nil { + return nil, err + } + var failing []api.EbsCsiAttachment + for _, a := range l.Attachments { + rs = append(rs, a.Reasons...) + if !a.Attached || a.Problem != "" { + failing = append(failing, a) + } + } + if err := printSection(e, w, "Failing attachments", view.EbsCsiAttachmentsTable(failing)); err != nil { + return nil, err + } + var wr []api.AddonReason + for _, wl := range l.Workloads { + for _, r := range wl.Reasons { + if r.ObjectRef == "" { + r.ObjectKind, r.ObjectRef = wl.Kind, wl.Namespace+"/"+wl.Name + } + wr = append(wr, r) + } + } + rs = append(rs, wr...) + return rs, printSection(e, w, "Workloads stuck on EBS", view.ReasonsTable(wr)) + }, + show: func(e *env, w io.Writer, d *api.EbsCsiNodeDetail) error { + if d.Node == nil { + return nil + } + stateLine(w, "Node "+d.Node.Name, d.Node.State, "") + return detailSections(e, w, d.Node.Reasons, section{"Attachments", view.EbsCsiAttachmentsTable(d.Attachments)}) + }, + }), + ) + return cmd +} + +// addonSpec is one workspace: L is its list response, D its detail response. +type addonSpec[L, D any] struct { + use, what string + aliases []string + kindFlag bool + list func(*api.Client, context.Context, string, string) (*api.Payload[L], error) + detail func(c *api.Client, ctx context.Context, org, cluster string, args []string, kind string) (*api.Payload[D], error) + head func(*L) api.WorkspaceHead + rows func(*env, io.Writer, *L) ([]api.AddonReason, error) + show func(*env, io.Writer, *D) error +} + +// detailHead reads the status fields every detail response embeds. +func detailHead(d any) api.WorkspaceHead { + switch v := d.(type) { + case *api.NodePoolDetail: + return v.WorkspaceHead + case *api.NodeGroupDetail: + return v.WorkspaceHead + case *api.IngressRouteDetail: + return v.WorkspaceHead + case *api.MeshWorkloadDetail: + return v.WorkspaceHead + case *api.GitOpsAppDetail: + return v.WorkspaceHead + case *api.VpcCniNodeDetail: + return v.WorkspaceHead + case *api.EbsCsiNodeDetail: + return v.WorkspaceHead + } + return api.WorkspaceHead{} +} + +func addonCmd[L, D any](s addonSpec[L, D]) *cobra.Command { + var failOn, kind string + nsName := strings.Contains(s.use, "namespace/name") + + cmd := &cobra.Command{ + Use: s.use, + Aliases: s.aliases, + Short: s.what + ", with their findings", + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + threshold, err := failOnThreshold(failOn) + if err != nil { + return err + } + var ref []string + if len(args) == 1 { + if nsName { + if ref, err = splitRef(args[0], 2, "/"); err != nil { + return err + } + } else { + ref = args + } + } + e, orgID, clusterID, err := clusterEnv(cmd) + if err != nil { + return err + } + out, warn := cmd.OutOrStdout(), cmd.ErrOrStderr() + + if ref != nil { + p, err := s.detail(e.client, cmd.Context(), orgID, clusterID, ref, kind) + if err != nil { + return err + } + if e.printer.Format.Structured() { + return e.printer.Print(p.Raw, nil) + } + h := detailHead(&p.Typed) + if !h.OK() { + warnStatus(warn, s.what, h.Status, h.Message) + return nil + } + return s.show(e, out, &p.Typed) + } + + p, err := s.list(e.client, cmd.Context(), orgID, clusterID) + if err != nil { + return err + } + h := s.head(&p.Typed) + if e.printer.Format.Structured() { + if err := e.printer.Print(p.Raw, nil); err != nil { + return err + } + if !h.OK() { + return nil + } + var discard strings.Builder + rs, err := s.rows(&env{printer: &render.Printer{Out: &discard, Format: render.FormatTable}}, &discard, &p.Typed) + if err != nil { + return err + } + return gate(threshold, severities(rs), "add-on findings") + } + addonHeader(out, h, s.what) + if !h.OK() { + // Not installed, never synced, rules off: say so instead of an empty table, and + // keep --fail-on from passing a cluster nobody could read. + warnStatus(warn, s.what, h.Status, h.Message) + if threshold > 0 { + fmt.Fprintf(warn, "warning: %s were not evaluated — --fail-on has nothing to gate\n", s.what) + } + return nil + } + if h.Addon != nil && !h.Addon.RulesEvaluated { + fmt.Fprintf(warn, "warning: %s rules were not evaluated — an empty findings column is not \"no findings\"\n", h.Addon.DisplayName) + } + rs, err := s.rows(e, out, &p.Typed) + if err != nil { + return err + } + return gate(threshold, severities(rs), "add-on findings") + }, + } + cmd.Flags().StringVar(&failOn, "fail-on", "", "exit 4 when a listed finding reaches this severity") + if s.kindFlag { + cmd.Flags().StringVar(&kind, "kind", "", "object kind when a namespace/name is ambiguous") + } + return cmd +} + +func addonHeader(w io.Writer, h api.WorkspaceHead, what string) { + name := what + if a := h.Addon; a != nil && a.DisplayName != "" { + name = a.DisplayName + if a.Version != "" { + name += " " + a.Version + } + if a.RuleCount > 0 { + name += " · " + strconv.Itoa(a.RuleCount) + " rules" + } + } + fmt.Fprintf(w, "%s (synced %s ago)\n", name, view.Since(h.LastSyncAt)) + if len(h.Counts) > 0 { + fmt.Fprintf(w, " %s\n", view.Counts(h.Counts)) + } +} + +func severities(rs []api.AddonReason) []string { + out := make([]string, 0, len(rs)) + for _, r := range rs { + out = append(out, r.Severity) + } + return out +} + +func stateLine(w io.Writer, what, state, why string) { + fmt.Fprintf(w, "%s: %s", what, render.Dash(state)) + if why = strings.TrimSpace(why); why != "" { + fmt.Fprintf(w, " — %s", why) + } + fmt.Fprintln(w) +} + +type section struct { + title string + table *render.Table +} + +func eventsSection(evs []api.WorkspaceEvent, available bool) section { + t := view.EventsTable(evs) + if !available { + t.EmptyMessage = "Events were not available for this sync." + } + return section{"Events", t} +} + +func detailSections(e *env, w io.Writer, reasons []api.AddonReason, more ...section) error { + if err := printSection(e, w, "Findings", view.ReasonsTable(reasons)); err != nil { + return err + } + for _, s := range more { + if err := printSection(e, w, s.title, s.table); err != nil { + return err + } + } + return nil +} diff --git a/internal/cli/addons_test.go b/internal/cli/addons_test.go new file mode 100644 index 0000000..7271322 --- /dev/null +++ b/internal/cli/addons_test.go @@ -0,0 +1,190 @@ +package cli + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func addonHead(name string) map[string]any { + return map[string]any{"addonId": strings.ToLower(name), "displayName": name, "version": "1.2.0", + "ruleCount": 30, "rulesEvaluated": true} +} + +func TestAddonsNodePoolsListsFindingsAndGates(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/autoscaling/nodepools": map[string]any{ + "status": "OK", "addon": addonHead("Karpenter"), "lastSyncAt": "2026-10-17T10:00:00Z", + "counts": map[string]int{"HEALTHY": 1, "DEGRADED": 1}, + "header": map[string]any{"managedBy": "EKS Auto Mode"}, + "nodePools": []map[string]any{ + {"name": "default", "state": "HEALTHY", "nodes": 3, "nodeClaimCount": 3}, + {"name": "gpu", "state": "DEGRADED", "nodes": 0, "nodeClaimCount": 1, "driftedCount": 1, + "reasons": []map[string]any{ + {"ruleId": "karpenter-limit-reached", "severity": "HIGH", "title": "NodePool at its cpu limit"}, + {"ruleId": "karpenter-drift", "severity": "LOW", "title": "Drifted claim"}, + }}, + }, + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "addons", "nodepools") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + for _, want := range []string{"Karpenter 1.2.0 · 30 rules", "DEGRADED=1 HEALTHY=1", "Managed by EKS Auto Mode", + "NodePools (2)", "gpu", "HIGH NodePool at its cpu limit"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + if _, code := run(t, "addons", "karpenter", "--fail-on", "high"); code != ExitPolicy { + t.Errorf("a HIGH finding against --fail-on high exited %d", code) + } + if _, code := run(t, "addons", "nodepools", "--fail-on", "critical"); code != ExitOK { + t.Errorf("--fail-on critical with no CRITICAL exited %d", code) + } + if _, code := run(t, "addons", "nodepools", "-o", "json", "--fail-on", "high"); code != ExitPolicy { + t.Errorf("--fail-on did not gate under -o json (exit %d)", code) + } + if _, code := run(t, "addons", "nodepools", "--fail-on", "hgh"); code != ExitUsage { + t.Errorf("a typo in --fail-on was accepted (exit %d)", code) + } +} + +// An add-on that is not installed must say so, and must never pass a gate. +func TestAddonsNotDetectedIsStatedNotEmpty(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/mesh/workloads": map[string]any{ + "status": "NOT_DETECTED", "message": "no istiod Deployment found", + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "addons", "istio", "--fail-on", "high") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + for _, want := range []string{"NOT_DETECTED", "no istiod Deployment found", "--fail-on has nothing to gate"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + if strings.Contains(out, "No workloads.") { + t.Errorf("an undetected add-on rendered as an empty table:\n%s", out) + } +} + +func TestAddonsRulesNotEvaluatedWarns(t *testing.T) { + head := addonHead("Argo CD") + head["rulesEvaluated"] = false + srv := resourceServer(t, map[string]any{clusterBase + "/gitops/applications": map[string]any{ + "status": "OK", "addon": head, + "applications": []map[string]any{{"namespace": "argocd", "name": "shop", "sync": "Synced", "health": "Healthy"}}, + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, _ := run(t, "addons", "gitops") + if !strings.Contains(out, "rules were not evaluated") { + t.Errorf("unevaluated rules not surfaced:\n%s", out) + } +} + +func TestAddonsIngressDetailPathAndKind(t *testing.T) { + var path, kind string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path, kind = r.URL.Path, r.URL.Query().Get("kind") + w.Write([]byte(`{"success":true,"data":{"status":"OK", + "route":{"kind":"IngressRoute","namespace":"shop","name":"web","state":"BROKEN","stateWhy":"backend Service missing", + "reasons":[{"ruleId":"traefik-backend-missing","severity":"CRITICAL","title":"Backend Service does not exist", + "verifyCommand":"kubectl -n shop get svc web","objectKind":"Service","objectRef":"shop/web"}]}, + "backendWorkloads":[{"kind":"Deployment","namespace":"shop","name":"web","service":"web"}]}}`)) + })) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "addons", "ingress", "shop/web", "--kind", "IngressRoute") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + if path != clusterBase+"/ingress/routes/shop/web" || kind != "IngressRoute" { + t.Errorf("path = %q kind = %q", path, kind) + } + for _, want := range []string{"IngressRoute shop/web: BROKEN — backend Service missing", "Findings (1)", + "CRITICAL", "kubectl -n shop get svc web", "Service shop/web", "Backend workloads (1)"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + if out, code := run(t, "addons", "ingress", "web"); code != ExitUsage { + t.Errorf("a ref without a namespace exited %d:\n%s", code, out) + } +} + +func TestAddonsNodeDetailUsesNameQuery(t *testing.T) { + var path, name string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path, name = r.URL.Path, r.URL.Query().Get("name") + w.Write([]byte(`{"success":true,"data":{"status":"OK", + "node":{"name":"ip-10-0-1-5","state":"IP_EXHAUSTED","ipAssigned":29,"ipUsable":29,"ipMax":29}, + "errors":[{"family":"ipamd","key":"InsufficientCidrBlocks","lastHour":4,"lastDay":40}]}}`)) + })) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "addons", "vpc-cni", "ip-10-0-1-5") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + if path != clusterBase+"/networking/vpc-cni/node" || name != "ip-10-0-1-5" { + t.Errorf("path = %q name = %q", path, name) + } + if !strings.Contains(out, "IP_EXHAUSTED") || !strings.Contains(out, "InsufficientCidrBlocks") { + t.Errorf("detail not rendered:\n%s", out) + } +} + +func TestAddonsDetailNotFoundIsStated(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/autoscaling/nodepools/nope": map[string]any{ + "status": "NOT_FOUND", "message": "no NodePool named nope", + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, _ := run(t, "addons", "nodepools", "nope") + if !strings.Contains(out, "NOT_FOUND") || !strings.Contains(out, "no NodePool named nope") { + t.Errorf("missing row not stated:\n%s", out) + } +} + +func TestAddonsEbsCsiShowsFailingAttachmentsAndStuckWorkloads(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/storage/ebs-csi": map[string]any{ + "status": "OK", "addon": addonHead("Amazon EBS CSI"), + "header": map[string]any{"driverVersion": "v1.38.1", "controllerReady": "2/2", "nodePluginReady": "3/3"}, + "nodes": []map[string]any{{"name": "n1", "state": "OK", "attached": 3, "limit": 25}}, + "attachments": []map[string]any{ + {"name": "csi-ok", "node": "n1", "persistentVolume": "pv-a", "attached": true}, + {"name": "csi-bad", "node": "n1", "persistentVolume": "pv-b", "attached": false, "problem": "ATTACH_FAILED", + "message": "volume is in another AZ"}, + }, + "workloads": []map[string]any{{"kind": "StatefulSet", "namespace": "data", "name": "pg", + "reasons": []map[string]any{{"ruleId": "ebs-az-mismatch", "severity": "HIGH", "title": "Volume and node in different zones"}}}}, + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "addons", "ebs-csi") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + for _, want := range []string{"Driver v1.38.1", "3/25", "Failing attachments (1)", "csi-bad", "another AZ", + "Workloads stuck on EBS (1)", "StatefulSet data/pg", "different zones"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + if strings.Contains(out, "csi-ok") { + t.Errorf("a healthy attachment was listed as failing:\n%s", out) + } +} diff --git a/internal/cli/capacity.go b/internal/cli/capacity.go new file mode 100644 index 0000000..310abe3 --- /dev/null +++ b/internal/cli/capacity.go @@ -0,0 +1,350 @@ +package cli + +import ( + "fmt" + "io" + "slices" + "strings" + + "github.com/spf13/cobra" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/render" + "github.com/runtimez-com/runtimez-cli/internal/view" +) + +func newCapacityCmd() *cobra.Command { + var section string + + cmd := &cobra.Command{ + Use: "capacity", + Short: "Schedulable capacity: headroom, pools, pending pods", + Long: `Schedulable capacity of the selected cluster from its last sync. + +Without --section it prints a bounded summary: headroom per axis, one row per node pool, and +the pending-pod count. --section prints one part in full: ` + strings.Join(view.CapacitySections, ", ") + `.`, + Example: ` rtz capacity + rtz capacity --section blocked + rtz capacity --section storage -o wide + rtz capacity trend --days 30`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + if section != "" && !slices.Contains(view.CapacitySections, section) { + return usageErrorf("unknown --section %q — use one of %s", section, strings.Join(view.CapacitySections, ", ")) + } + e, orgID, clusterID, err := clusterEnv(cmd) + if err != nil { + return err + } + p, err := e.client.Capacity(cmd.Context(), orgID, clusterID) + if err != nil { + return err + } + if e.printer.Format.Structured() { + return e.printer.Print(p.Raw, nil) + } + c := &p.Typed + out, warn := cmd.OutOrStdout(), cmd.ErrOrStderr() + warnStatus(warn, "capacity", c.Status, c.Message) + if section == "" { + return printCapacitySummary(e, out, warn, c) + } + return printCapacitySection(e, out, warn, c, section) + }, + } + cmd.Flags().StringVar(§ion, "section", "", "print one section in full: "+strings.Join(view.CapacitySections, "|")) + cmd.AddCommand(newCapacityTrendCmd(), newCapacityCostCmd(), newCapacityNamespacesCmd(), newCapacityFleetCmd()) + return cmd +} + +func printCapacitySummary(e *env, out, warn io.Writer, c *api.Capacity) error { + fmt.Fprintf(out, "Capacity (synced %s ago)\n", view.Since(c.LastSyncAt)) + if a := c.Autoscaler; a != nil { + acting := "" + if a.Acting { + acting = ", acting" + } + fmt.Fprintf(out, " Autoscaler: %s%s", render.Dash(a.State), acting) + if a.ManagedBy != "" { + fmt.Fprintf(out, " (managed by %s)", a.ManagedBy) + } + fmt.Fprintln(out) + } + if cc := c.ClusterCeiling; cc != nil && cc.MaxNodes != nil { + fmt.Fprintf(out, " Node ceiling: %d of %d (%s)\n", cc.CurrentNodes, *cc.MaxNodes, render.Dash(cc.Source)) + } + if u := c.Usage; u != nil { + warnStatus(warn, "usage", u.Status, u.Reason) + if u.NodesWithoutSamples > 0 { + fmt.Fprintf(warn, "warning: %d node(s) have no usage samples — USED columns cover only %d node(s)\n", + u.NodesWithoutSamples, u.NodesWithSamples) + } + } + warnCapacityFlags(warn, c) + + if err := printSection(e, out, "Headroom", view.HeadroomTable(c)); err != nil { + return err + } + if err := printSection(e, out, "Pools", view.PoolsTable(c.Pools)); err != nil { + return err + } + if b := c.BlockedSummary; b != nil { + fmt.Fprintf(out, "\nPending pods: %d (%d capacity shortfall, %d gated, %d nominated)", b.Total, + b.CapacityShortfall, b.Gated, b.Nominated) + if len(b.ByCategory) > 0 { + fmt.Fprintf(out, " — %s", view.Counts(b.ByCategory)) + } + fmt.Fprintln(out) + if b.Total > 0 { + fmt.Fprintln(out, " rtz capacity --section blocked for each pod and why") + } + if !b.EventsRead { + fmt.Fprintln(warn, "warning: scheduler events were not read — pending reasons may be missing") + } + } + return nil +} + +func warnCapacityFlags(w io.Writer, c *api.Capacity) { + f := c.Flags + if f == nil { + return + } + if f.NodeRowsTruncated { + fmt.Fprintln(w, "warning: node rows were truncated — per-node figures are incomplete") + } + if f.PodRowsTruncated { + fmt.Fprintln(w, "warning: pod rows were truncated — requested figures are a lower bound") + } + if f.Nodeless { + fmt.Fprintln(w, "warning: no nodes were synced for this cluster") + } + for _, n := range f.Notes { + fmt.Fprintf(w, "note: %s\n", n) + } +} + +func printCapacitySection(e *env, out, warn io.Writer, c *api.Capacity, section string) error { + switch section { + case "pools": + return e.printer.Print(nil, view.PoolsTable(c.Pools)) + case "nodes": + warnCapacityFlags(warn, c) + return e.printer.Print(nil, view.CapacityNodesTable(c)) + case "blocked": + if b := c.BlockedSummary; b != nil && b.Listed < b.Total { + fmt.Fprintf(warn, "note: %d of %d pending pods listed\n", b.Listed, b.Total) + } + return e.printer.Print(nil, view.BlockedTable(c)) + case "storage": + if s := c.Storage; s != nil { + warnStatus(warn, "storage", s.Status, s.Reason) + warnStatus(warn, "volume metrics", s.Metrics, s.MetricsReason) + if s.PVCsNotListed > 0 { + fmt.Fprintf(warn, "note: %d more claims not listed\n", s.PVCsNotListed) + } + defer printNotes(out, s.Notes) + } else { + fmt.Fprintln(warn, "warning: storage was not reported for this cluster") + } + return e.printer.Print(nil, view.StorageTable(c)) + case "network": + if n := c.Network; n != nil { + warnStatus(warn, "network", n.Status, n.Reason) + if n.PodsWaitingForIP != nil && *n.PodsWaitingForIP > 0 { + fmt.Fprintf(out, "Pods waiting for an IP: %d\n", *n.PodsWaitingForIP) + } + defer printNotes(out, n.Notes) + } else { + fmt.Fprintln(warn, "warning: pod networking was not reported for this cluster") + } + return e.printer.Print(nil, view.NetworkTable(c)) + case "batch": + if b := c.Batch; b != nil { + warnStatus(warn, "batch", b.Status, b.Message) + if !b.Collected { + fmt.Fprintln(warn, "warning: Jobs and CronJobs were not collected — an empty list is not \"no batch\"") + } + defer printNotes(out, b.Notes) + } + return e.printer.Print(nil, view.BatchTable(c)) + case "special": + if s := c.Special; s != nil { + warnStatus(warn, "special resources", s.Status, s.Reason) + defer printNotes(out, s.Notes) + } + return e.printer.Print(nil, view.SpecialTable(c)) + } + return usageErrorf("unknown --section %q", section) +} + +func newCapacityTrendCmd() *cobra.Command { + var days int + cmd := &cobra.Command{ + Use: "trend", + Short: "Capacity growth and days until each pool is full", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + if days < 0 { + return usageErrorf("--days must be positive") + } + e, orgID, clusterID, err := clusterEnv(cmd) + if err != nil { + return err + } + p, err := e.client.CapacityTrend(cmd.Context(), orgID, clusterID, days) + if err != nil { + return err + } + if e.printer.Format.Structured() { + return e.printer.Print(p.Raw, nil) + } + t, out := &p.Typed, cmd.OutOrStdout() + warnStatus(cmd.ErrOrStderr(), "trend", t.Status, t.Message) + if t.DaysCollected < t.MinDays { + fmt.Fprintf(cmd.ErrOrStderr(), "warning: %d of %d days collected — forecasts are not available yet\n", + t.DaysCollected, t.MinDays) + } + fmt.Fprintf(out, "Trend %s → %s (%d days), requests target %.0f%% (%s)\n", + render.Dash(t.From), render.Dash(t.To), t.Days, t.Target, render.Dash(t.TargetSource)) + if err := printSection(e, out, "Pools", view.CapacityTrendTable(t)); err != nil { + return err + } + printNotes(out, t.Notes) + return nil + }, + } + cmd.Flags().IntVar(&days, "days", 0, "window in days (backend default when unset)") + return cmd +} + +func newCapacityCostCmd() *cobra.Command { + return &cobra.Command{ + Use: "cost", + Short: "Node cost per pool and the levers that change it", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + e, orgID, clusterID, err := clusterEnv(cmd) + if err != nil { + return err + } + p, err := e.client.CapacityCost(cmd.Context(), orgID, clusterID) + if err != nil { + return err + } + if e.printer.Format.Structured() { + return e.printer.Print(p.Raw, nil) + } + c, out, warn := &p.Typed, cmd.OutOrStdout(), cmd.ErrOrStderr() + warnStatus(warn, "cost", c.Status, c.Message) + fmt.Fprintf(out, "Cluster: %s/month (%s/hour), %d of %d nodes priced\n", + view.Money(c.ClusterMonthly), view.Money(c.ClusterHourly), c.PricedNodes, c.Nodes) + // A list price and a negotiated rate look identical once printed; name the source. + if s := c.PriceSource; s != nil { + fmt.Fprintf(out, " Prices: %s", render.Dash(firstNonEmpty(s.Label, s.OnDemandSource, s.Provider))) + if s.OnDemandDate != "" { + fmt.Fprintf(out, " as of %s", s.OnDemandDate) + } + fmt.Fprintln(out) + } + if c.EffectiveMonthly != nil { + fmt.Fprintf(out, " Effective (after commitments): %s/month\n", view.Money(c.EffectiveMonthly)) + } + if c.PricedNodes < c.Nodes { + fmt.Fprintf(warn, "warning: %d node(s) unpriced — totals cover priced nodes only\n", c.Nodes-c.PricedNodes) + } + if cv := c.Coverage; cv != nil { + warnStatus(warn, "commitment coverage", cv.State, cv.Detail) + } + if err := printSection(e, out, "Pools", view.CapacityCostTable(c)); err != nil { + return err + } + if err := printSection(e, out, "Levers", view.CostLeversTable(c)); err != nil { + return err + } + printNotes(out, c.Notes) + return nil + }, + } +} + +func newCapacityNamespacesCmd() *cobra.Command { + return &cobra.Command{ + Use: "namespaces", + Aliases: []string{"ns"}, + Short: "Requests, quota and pending pods per namespace", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + e, orgID, clusterID, err := clusterEnv(cmd) + if err != nil { + return err + } + p, err := e.client.CapacityNamespaces(cmd.Context(), orgID, clusterID) + if err != nil { + return err + } + if e.printer.Format.Structured() { + return e.printer.Print(p.Raw, nil) + } + n := &p.Typed + warnStatus(cmd.ErrOrStderr(), "namespaces", n.Status, n.Message) + if !n.QuotasCollected { + fmt.Fprintln(cmd.ErrOrStderr(), "warning: ResourceQuotas were not collected — QUOTA reads NOT_COLLECTED, not \"no quota\"") + } + if err := e.printer.Print(nil, view.CapacityNamespacesTable(n)); err != nil { + return err + } + printNotes(cmd.OutOrStdout(), n.Notes) + return nil + }, + } +} + +func newCapacityFleetCmd() *cobra.Command { + return &cobra.Command{ + Use: "fleet", + Short: "Capacity across every cluster in the org", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + e, err := loadEnv(cmd, true) + if err != nil { + return err + } + orgID, err := e.requireOrg() + if err != nil { + return err + } + p, err := e.client.FleetCapacity(cmd.Context(), orgID) + if err != nil { + return err + } + if e.printer.Format.Structured() { + return e.printer.Print(p.Raw, nil) + } + f, out, warn := &p.Typed, cmd.OutOrStdout(), cmd.ErrOrStderr() + if tot := f.Totals; tot != nil { + fmt.Fprintf(out, "Fleet: %d clusters counted of %d", tot.ClustersCounted, f.ClustersTotal) + if tot.CPU != nil { + fmt.Fprintf(out, ", CPU requests %s", view.Pct(tot.CPU.RequestsCommitmentPct)) + } + if tot.Memory != nil { + fmt.Fprintf(out, ", memory requests %s", view.Pct(tot.Memory.RequestsCommitmentPct)) + } + fmt.Fprintln(out) + if s := tot.SoonestFull; s != nil && s.Days != nil { + fmt.Fprintf(out, " Fills first: %s %s %s in %s\n", render.Dash(s.ClusterName), s.Pool, s.Axis, view.Days(s.Days)) + } + if len(tot.NotCounted) > 0 { + fmt.Fprintf(warn, "warning: clusters not counted in the totals: %s\n", view.Counts(tot.NotCounted)) + } + if tot.CountedFromEarlierSync > 0 { + fmt.Fprintf(warn, "note: %d cluster(s) counted from an earlier sync\n", tot.CountedFromEarlierSync) + } + } + if f.Truncated { + fmt.Fprintln(warn, "warning: the cluster list was truncated") + } + return printSection(e, out, "Clusters", view.FleetCapacityTable(f)) + }, + } +} diff --git a/internal/cli/capacity_test.go b/internal/cli/capacity_test.go new file mode 100644 index 0000000..55b8d11 --- /dev/null +++ b/internal/cli/capacity_test.go @@ -0,0 +1,273 @@ +package cli + +import ( + "encoding/json" + "strings" + "testing" +) + +// capacityFixture mirrors CapacityResponse: units on the wire are millicores and bytes, and +// percentages are already 0-100. +func capacityFixture() map[string]any { + return map[string]any{ + "status": "OK", "lastSyncAt": "2026-10-17T10:00:00Z", + "autoscaler": map[string]any{"state": "KARPENTER", "acting": true, "managedBy": "EKS Auto Mode"}, + "usage": map[string]any{"status": "OK", "nodesWithSamples": 2, "nodesWithoutSamples": 1}, + "headroom": []map[string]any{ + {"axis": "cpu", "unit": "millicores", "allocatable": 8000, "requested": 6000, "requestsCommitmentPct": 75.0, + "used": 2500, "usedPct": 31.3, "headroom": 2000, "largestFit": 1500, "largestFitNode": "ip-10-0-1-5"}, + {"axis": "memory", "unit": "bytes", "allocatable": 34359738368, "requested": 17179869184, + "requestsCommitmentPct": 50.0, "headroom": 17179869184}, + }, + "pools": []map[string]any{{ + "name": "default", "source": "karpenter", "nodes": 3, "pods": 41, "allocatablePods": 110, + "cpuRequestsCommitmentPct": 75.0, "memoryRequestsCommitmentPct": 50.0, + "headroom": map[string]any{"cpuMillicores": 2000, "memoryBytes": 17179869184}, + "roomToGrow": map[string]any{"nodes": 7, "atCeiling": false}, + }}, + "blocked": []map[string]any{ + {"namespace": "shop", "name": "cart-abc", "ownerKind": "Deployment", "ownerName": "cart", + "pendingSeconds": 600, "primaryCategory": "INSUFFICIENT_CPU", "capacityShortfall": true, + "message": "0/3 nodes are available: 3 Insufficient cpu."}, + {"namespace": "shop", "name": "cart-def", "pendingSeconds": 30, "primaryCategory": "GATED"}, + }, + "blockedSummary": map[string]any{"total": 2, "listed": 2, "capacityShortfall": 1, "gated": 1, + "byCategory": map[string]int{"INSUFFICIENT_CPU": 1, "GATED": 1}, "eventsRead": true}, + "flags": map[string]any{"podRowsTruncated": true}, + "storage": map[string]any{"status": "OK", "metrics": "PARTIAL", "metricsReason": "kubelet stats missing on 1 node", + "pvcs": []map[string]any{ + {"namespace": "data", "name": "pg-0", "phase": "Bound", "storageClass": "gp3", + "capacityBytes": 107374182400, "usedBytes": 96636764160, "usedPct": 90.0, "daysToFull": 4.2, + "forecast": "OK", "mountedBy": "StatefulSet/pg"}, + }, + "pending": []map[string]any{{"namespace": "data", "name": "pg-1", "storageClass": "gp3", + "reason": "WaitForFirstConsumer", "pendingSeconds": 120}}, + }, + } +} + +func TestCapacitySummaryRendersHeadroomPoolsAndPending(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/capacity": capacityFixture()}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "capacity") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + for _, want := range []string{ + "KARPENTER, acting", "EKS Auto Mode", + "Headroom (2)", "8000m", "6000m", "75%", "32.0Gi", "16.0Gi", + "Pools (1)", "default", "+7 nodes", "41/110", + "Pending pods: 2 (1 capacity shortfall, 1 gated", "GATED=1 INSUFFICIENT_CPU=1", + "rtz capacity --section blocked", + } { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + // "We could not see" is stated: one node without samples, truncated pod rows. + for _, want := range []string{"1 node(s) have no usage samples", "pod rows were truncated"} { + if !strings.Contains(out, want) { + t.Errorf("caveat %q not surfaced:\n%s", want, out) + } + } +} + +func TestCapacitySectionBlockedLongestWaitingFirst(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/capacity": capacityFixture()}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "capacity", "--section", "blocked") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + if i, j := strings.Index(out, "cart-abc"), strings.Index(out, "cart-def"); i < 0 || j < 0 || i > j { + t.Errorf("longest-pending pod not first:\n%s", out) + } + if !strings.Contains(out, "Deployment/cart") || !strings.Contains(out, "Insufficient cpu") { + t.Errorf("owner or scheduler message missing:\n%s", out) + } +} + +func TestCapacitySectionStorageWarnsOnPartialMetrics(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/capacity": capacityFixture()}) + defer srv.Close() + isolateCluster(t, srv) + + out, _ := run(t, "capacity", "--section", "storage") + for _, want := range []string{"pg-0", "90%", "4d", "100.0Gi", "pg-1", "Pending", "volume metrics: PARTIAL"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } +} + +// A typo must never silently fall back to the summary. +func TestCapacityRejectsUnknownSection(t *testing.T) { + srv := resourceServer(t, map[string]any{}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "capacity", "--section", "nodez") + if code != ExitUsage { + t.Fatalf("exit = %d, want %d:\n%s", code, ExitUsage, out) + } +} + +// A cluster that was never synced must read as "not known", not as an empty, healthy one. +func TestCapacityNonOKStatusIsStated(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/capacity": map[string]any{ + "status": "NEVER_SYNCED", "message": "the agent has not reported this cluster yet", + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, _ := run(t, "capacity") + if !strings.Contains(out, "NEVER_SYNCED") || !strings.Contains(out, "has not reported") { + t.Errorf("non-OK status not surfaced:\n%s", out) + } +} + +// -o json prints the server document, not the trimmed struct the tables use. +func TestCapacityJSONIsLossless(t *testing.T) { + fx := capacityFixture() + fx["supply"] = map[string]any{"fieldTheCLIDoesNotType": 42} + srv := resourceServer(t, map[string]any{clusterBase + "/capacity": fx}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "capacity", "-o", "json") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + var got map[string]any + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatalf("not JSON: %v\n%s", err, out) + } + if got["supply"].(map[string]any)["fieldTheCLIDoesNotType"] != float64(42) { + t.Errorf("an untyped field was dropped:\n%s", out) + } + if strings.Contains(out, "e+") { + t.Errorf("a byte count was printed in exponent form:\n%s", out) + } +} + +func TestCapacityYAMLKeepsExactIntegers(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/capacity": capacityFixture()}) + defer srv.Close() + isolateCluster(t, srv) + + out, _ := run(t, "capacity", "-o", "yaml") + if !strings.Contains(out, "allocatable: 34359738368") { + t.Errorf("byte count not printed exactly:\n%s", out) + } +} + +func TestCapacityTrendSaysWhenStillCollecting(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/capacity/trend": map[string]any{ + "status": "COLLECTING", "message": "3 of 7 days collected", "days": 30, "minDays": 7, "daysCollected": 3, + "target": 80.0, "targetSource": "environment", + "pools": []map[string]any{{"name": "default", + "cpu": map[string]any{"axis": "cpu", "status": "COLLECTING", "currentPct": 62.0}, + "memory": map[string]any{"axis": "memory", "status": "OK", "days": 21, "fullOn": "2026-11-07", "currentPct": 70.0}, + "grade": map[string]any{"status": "TIGHT"}}}, + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, _ := run(t, "capacity", "trend") + for _, want := range []string{"COLLECTING", "3 of 7 days collected", "default", "TIGHT", "62%", "21d"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } +} + +func TestCapacityTrendPassesDays(t *testing.T) { + var got string + srv := capture(t, &got, "days") + defer srv.Close() + isolateCluster(t, srv) + + if _, code := run(t, "capacity", "trend", "--days", "14"); code != ExitOK { + t.Fatal("trend failed") + } + if got != "14" { + t.Errorf("days = %q, want 14", got) + } +} + +// An unpriced node is not a free node. +func TestCapacityCostFlagsUnpricedNodes(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/capacity/cost": map[string]any{ + "status": "OK", "nodes": 4, "pricedNodes": 3, "clusterMonthly": 1234.5, "clusterHourly": 1.69, + "priceSource": map[string]any{"label": "AWS list price", "onDemandDate": "2026-10-01"}, + "pools": []map[string]any{ + {"pool": "default", "nodes": 3, "pricedNodes": 3, "monthly": 1234.5, "hourly": 1.69}, + {"pool": "gpu", "nodes": 1, "pricedNodes": 0}, + }, + "levers": []map[string]any{{"label": "Move default to spot", "saving": true, "monthly": 420.0, "actsIn": "default"}}, + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, _ := run(t, "capacity", "cost") + for _, want := range []string{"$1234.50/month", "3 of 4 nodes priced", "AWS list price as of 2026-10-01", + "1 node(s) unpriced", "unpriced", "Move default to spot", "$420.00"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } +} + +func TestCapacityNamespacesWarnsWhenQuotasUncollected(t *testing.T) { + srv := resourceServer(t, map[string]any{clusterBase + "/capacity/namespaces": map[string]any{ + "status": "OK", "quotasCollected": false, + "namespaces": []map[string]any{ + {"namespace": "small", "pods": 2, "cpuShare": 10.0, "quotaStatus": "NOT_COLLECTED", + "requested": map[string]any{"cpuMillicores": 200, "memoryBytes": 268435456}}, + {"namespace": "big", "pods": 20, "pendingPods": 3, "cpuShare": 90.0, "quotaStatus": "QUOTA", + "requested": map[string]any{"cpuMillicores": 1800, "memoryBytes": 2147483648}, + "fullest": map[string]any{"resource": "requests.cpu", "hard": "2", "used": "1800m", "pct": 90.0}}, + }, + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, _ := run(t, "capacity", "namespaces") + if i, j := strings.Index(out, "big"), strings.Index(out, "small"); i < 0 || j < 0 || i > j { + t.Errorf("largest CPU share not first:\n%s", out) + } + for _, want := range []string{"requests.cpu 1800m/2 (90%)", "ResourceQuotas were not collected"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } +} + +func TestCapacityFleetSoonestFullFirst(t *testing.T) { + srv := resourceServer(t, map[string]any{"/eac/api/1.0/orgs/org1/capacity/fleet": map[string]any{ + "clustersTotal": 3, "clustersAnalyzed": 2, + "totals": map[string]any{"clustersCounted": 2, "notCounted": map[string]int{"NEVER_SYNCED": 1}, + "cpu": map[string]any{"requestsCommitmentPct": 60.0}}, + "clusters": []map[string]any{ + {"clusterId": "c-late", "name": "late", "status": "OK", "soonestFull": map[string]any{"pool": "a", "axis": "cpu", "days": 90}}, + {"clusterId": "c-soon", "name": "soon", "status": "OK", "soonestFull": map[string]any{"pool": "b", "axis": "memory", "days": 5}}, + }, + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "capacity", "fleet") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + if i, j := strings.Index(out, "soon"), strings.Index(out, "late"); i < 0 || j < 0 || i > j { + t.Errorf("soonest-full cluster not first:\n%s", out) + } + if !strings.Contains(out, "not counted in the totals: NEVER_SYNCED=1") { + t.Errorf("uncounted clusters not surfaced:\n%s", out) + } +} diff --git a/internal/cli/maintain.go b/internal/cli/maintain.go new file mode 100644 index 0000000..31eac86 --- /dev/null +++ b/internal/cli/maintain.go @@ -0,0 +1,310 @@ +package cli + +import ( + "errors" + "fmt" + "io" + + "github.com/spf13/cobra" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/render" + "github.com/runtimez-com/runtimez-cli/internal/view" +) + +func newMaintainCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "maintain", + Short: "End-of-life deadlines, running packages, and data-service upgrade impact", + } + cmd.AddCommand(newMaintainItemsCmd(), newMaintainPackagesCmd(), newMaintainDependentsCmd(), newMaintainImpactCmd()) + return cmd +} + +// errReadFailed is returned after printing whatever did come back: a list the backend could +// not finish reading must never exit 0, or a CI job reads it as "nothing due". +func errReadFailed(what string) error { + return &ExitError{Code: ExitFailure, Err: errors.New(what + ": the backend could not read all of it — the list is incomplete")} +} + +func newMaintainItemsCmd() *cobra.Command { + var within, failOnDays int + var platform bool + + cmd := &cobra.Command{ + Use: "items", + Short: "Support deadlines across the org, soonest first", + Long: `Every Maintain item — Kubernetes, add-ons, runtimes and OS releases in images, data +services — with its next support deadline. + +--fail-on-days N exits 4 when any listed item's deadline is N days away or less (or past).`, + Example: ` rtz maintain items --within 90 + rtz maintain items --fail-on-days 30`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + if within < -1 || failOnDays < -1 { + return usageErrorf("--within and --fail-on-days take a day count of 0 or more") + } + e, err := loadEnv(cmd, true) + if err != nil { + return err + } + orgID, err := e.requireOrg() + if err != nil { + return err + } + p, err := e.client.MaintainItems(cmd.Context(), orgID) + if err != nil { + return err + } + items := make([]api.MaintainItem, 0, len(p.Typed.Items)) + kept := make([]bool, len(p.Typed.Items)) + hiddenPlatform := 0 + for i, it := range p.Typed.Items { + if it.Platform && !platform { + hiddenPlatform++ + continue + } + if within >= 0 && (it.DaysLeft == nil || *it.DaysLeft > within) { + continue + } + kept[i] = true + items = append(items, it) + } + if e.printer.Format.Structured() { + // The filters apply to the full document too, row for row: typed and raw items + // are decoded from the same array, in the same order. + if doc, ok := p.Raw.(map[string]any); ok { + if raw, ok := doc["items"].([]any); ok && len(raw) == len(kept) { + out := make([]any, 0, len(items)) + for i, r := range raw { + if kept[i] { + out = append(out, r) + } + } + doc["items"] = out + } + } + if err := e.printer.Print(p.Raw, nil); err != nil { + return err + } + } else { + if err := e.printer.Print(nil, view.MaintainItemsTable(items)); err != nil { + return err + } + warn := cmd.ErrOrStderr() + if hiddenPlatform > 0 { + fmt.Fprintf(warn, "note: %d platform item(s) (Kubernetes, add-ons, system workloads) hidden — --platform to include; `rtz upgrade check` covers them\n", hiddenPlatform) + } + if p.Typed.Truncated { + fmt.Fprintln(warn, "warning: the item list was truncated") + } + } + if p.Typed.ReadFailed { + return errReadFailed("maintain items") + } + if failOnDays >= 0 { + due := 0 + for _, it := range items { + if it.DaysLeft != nil && *it.DaysLeft <= failOnDays { + due++ + } + } + if due > 0 { + return &ExitError{Code: ExitPolicy, Err: fmt.Errorf("%d item(s) within %d days of a support deadline", due, failOnDays)} + } + } + return nil + }, + } + cmd.Flags().IntVar(&within, "within", -1, "only items whose deadline is this many days away or less") + cmd.Flags().IntVar(&failOnDays, "fail-on-days", -1, "exit 4 when an item's deadline is this many days away or less") + cmd.Flags().BoolVar(&platform, "platform", false, "include platform items (Kubernetes, add-ons, system workloads)") + return cmd +} + +func newMaintainPackagesCmd() *cobra.Command { + var ecosystem, q string + var page, size int + + cmd := &cobra.Command{ + Use: "packages", + Short: "Packages running across the fleet, most-used first, with end-of-life", + Example: " rtz maintain packages --ecosystem maven --q log4j", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + if page < 0 || size < 1 { + return usageErrorf("--page must be 0 or more and --size at least 1") + } + e, err := loadEnv(cmd, true) + if err != nil { + return err + } + orgID, err := e.requireOrg() + if err != nil { + return err + } + p, err := e.client.MaintainInventory(cmd.Context(), orgID, ecosystem, q, page, size) + if err != nil { + return err + } + if e.printer.Format.Structured() { + if err := e.printer.Print(p.Raw, nil); err != nil { + return err + } + } else { + inv := &p.Typed + if err := e.printer.Print(nil, view.InventoryTable(inv)); err != nil { + return err + } + warn := cmd.ErrOrStderr() + fmt.Fprintf(warn, "page %d · %d of %d packages\n", inv.Page, len(inv.Items), inv.Total) + if inv.WorkloadsWithoutPackageList > 0 { + fmt.Fprintf(warn, "warning: %d workload(s) have no package list yet (%d do) — they are not in these counts\n", + inv.WorkloadsWithoutPackageList, inv.WorkloadsWithPackageList) + } + } + if p.Typed.ReadFailed { + return errReadFailed("maintain packages") + } + return nil + }, + } + cmd.Flags().StringVar(&ecosystem, "ecosystem", "", "only this ecosystem (maven, npm, pypi, go …)") + cmd.Flags().StringVar(&q, "q", "", "package name contains") + cmd.Flags().IntVar(&page, "page", 0, "page number, from 0") + cmd.Flags().IntVar(&size, "size", 50, "packages per page") + return cmd +} + +// dataServiceRef resolves // in the selected cluster. +func dataServiceRef(cmd *cobra.Command, ref string) (*env, string, api.DataServiceRef, error) { + parts, err := splitRef(ref, 3, "//, e.g. data/StatefulSet/postgres") + if err != nil { + return nil, "", api.DataServiceRef{}, err + } + e, orgID, clusterID, err := clusterEnv(cmd) + if err != nil { + return nil, "", api.DataServiceRef{}, err + } + return e, orgID, api.DataServiceRef{ClusterID: clusterID, Namespace: parts[0], Kind: parts[1], Name: parts[2]}, nil +} + +func newMaintainDependentsCmd() *cobra.Command { + return &cobra.Command{ + Use: "dependents //", + Short: "Workloads that connect to a data service (its blast radius)", + Example: " rtz maintain dependents data/StatefulSet/postgres", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + e, orgID, ref, err := dataServiceRef(cmd, args[0]) + if err != nil { + return err + } + p, err := e.client.DataServiceDependents(cmd.Context(), orgID, ref) + if err != nil { + return err + } + if e.printer.Format.Structured() { + if err := e.printer.Print(p.Raw, nil); err != nil { + return err + } + } else { + d, out := &p.Typed, cmd.OutOrStdout() + fmt.Fprintf(out, "%s/%s/%s — coverage %s, %d of %d nodes reporting, last snapshot %s ago\n", + ref.Namespace, ref.Kind, ref.Name, render.Dash(d.Coverage), d.NodesReported, d.NodesExpected, + view.Since(d.LastSnapshotAt)) + if err := printSection(e, out, "Dependents", view.DependentsTable(d)); err != nil { + return err + } + warnDependents(cmd.ErrOrStderr(), d.NodesReported, d.NodesExpected, d.Truncated, + d.PlatformExcluded, d.OtherClustersHidden, d.Inbound) + } + if p.Typed.ReadFailed { + return errReadFailed("dependents") + } + return nil + }, + } +} + +func newMaintainImpactCmd() *cobra.Command { + var target string + cmd := &cobra.Command{ + Use: "impact //", + Short: "What breaks if a data service is upgraded, per dependent", + Long: `Each workload that connects to the data service, judged against the target version: +BUMP_DRIVER (a stated break), UNKNOWN (nothing to judge by — never read as fine), REVIEW, READY.`, + Example: " rtz maintain impact data/StatefulSet/postgres --target 17", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + e, orgID, ref, err := dataServiceRef(cmd, args[0]) + if err != nil { + return err + } + p, err := e.client.DataServiceImpact(cmd.Context(), orgID, ref, target) + if err != nil { + return err + } + if e.printer.Format.Structured() { + if err := e.printer.Print(p.Raw, nil); err != nil { + return err + } + } else { + im, out, warn := &p.Typed, cmd.OutOrStdout(), cmd.ErrOrStderr() + name := firstNonEmpty(im.DisplayName, im.Product, ref.Name) + fmt.Fprintf(out, "%s %s → %s", name, render.Dash(im.CurrentVersion), render.Dash(im.Target)) + if im.TargetDefaulted { + fmt.Fprint(out, " (default target)") + } + fmt.Fprintln(out) + if im.Operator != "" { + fmt.Fprintf(out, " Operator: %s\n", im.Operator) + } + if s := im.Summary; s != nil { + fmt.Fprintf(out, " Dependents: %d bump driver · %d unknown · %d review · %d ready\n", + s.BumpDriver, s.Unknown, s.Review, s.Ready) + } + if !im.RulePack { + fmt.Fprintf(warn, "warning: no upgrade rule pack for %s — verdicts cannot name breaking changes\n", name) + } + if err := printSection(e, out, "Dependents", view.ImpactTable(im)); err != nil { + return err + } + if len(im.UpgradeNotes) > 0 { + fmt.Fprintf(out, "\nUpgrade notes (%d)\n", len(im.UpgradeNotes)) + for _, n := range im.UpgradeNotes { + fmt.Fprintf(out, " %s %s %s\n", render.Dash(n.Severity), render.Dash(n.Since), n.Title) + } + } + warnDependents(warn, -1, -1, im.Truncated, im.PlatformExcluded, im.OtherClustersHidden, im.Inbound) + } + if p.Typed.ReadFailed { + return errReadFailed("impact") + } + return nil + }, + } + cmd.Flags().StringVar(&target, "target", "", "target version (backend default when unset)") + return cmd +} + +// warnDependents states what the dependents list cannot include. reported/expected < 0 skips +// the node-coverage line. +func warnDependents(w io.Writer, reported, expected int, truncated bool, platform, otherClusters int, in *api.DataServiceInbound) { + if expected >= 0 && reported < expected { + fmt.Fprintf(w, "warning: only %d of %d nodes reported connections — dependents on the others are missing\n", reported, expected) + } + if truncated { + fmt.Fprintln(w, "warning: the dependents list was truncated") + } + if platform > 0 { + fmt.Fprintf(w, "note: %d platform workload(s) excluded\n", platform) + } + if otherClusters > 0 { + fmt.Fprintf(w, "note: %d dependent(s) in clusters you cannot see are hidden\n", otherClusters) + } + if in != nil && in.Reported && (in.ViaNode > 0 || in.Other > 0) { + fmt.Fprintf(w, "note: callers that could not be named: %d via a node, %d other\n", in.ViaNode, in.Other) + } +} diff --git a/internal/cli/maintain_test.go b/internal/cli/maintain_test.go new file mode 100644 index 0000000..f04f3fa --- /dev/null +++ b/internal/cli/maintain_test.go @@ -0,0 +1,216 @@ +package cli + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +// capture records one query parameter of every request and answers with an empty payload. +func capture(t *testing.T, got *string, param string) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *got = r.URL.Query().Get(param) + w.Write([]byte(`{"success":true,"data":{}}`)) + })) +} + +const maintainBase = "/eac/api/1.0/orgs/org1/maintain" + +func maintainItems(readFailed bool) map[string]any { + return map[string]any{ + "readFailed": readFailed, + "items": []map[string]any{ + {"clusterName": "prod", "itemType": "RUNTIME", "displayName": "Node.js 18", "version": "18.20", + "deadline": "2026-11-01", "daysLeft": 15, "supportState": "ENDING", "location": "shop/Deployment/web"}, + {"clusterName": "prod", "itemType": "DATA_SERVICE", "displayName": "PostgreSQL 13", "version": "13.14", + "deadline": "2025-11-13", "daysLeft": -338, "supportState": "EOL", "location": "data/StatefulSet/pg"}, + {"clusterName": "prod", "itemType": "KUBERNETES", "displayName": "Kubernetes 1.31", "daysLeft": 40, "platform": true}, + {"clusterName": "prod", "itemType": "RUNTIME", "displayName": "Python 3.12", "daysLeft": 700}, + {"clusterName": "prod", "itemType": "RUNTIME", "displayName": "Mystery runtime"}, + }, + } +} + +func TestMaintainItemsSoonestFirstPlatformHidden(t *testing.T) { + srv := resourceServer(t, map[string]any{maintainBase + "/items": maintainItems(false)}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "maintain", "items") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + pg, node, py, mystery := strings.Index(out, "PostgreSQL"), strings.Index(out, "Node.js"), + strings.Index(out, "Python"), strings.Index(out, "Mystery") + if !(pg >= 0 && pg < node && node < py && py < mystery) { + t.Errorf("not soonest-first with unknown deadlines last:\n%s", out) + } + if !strings.Contains(out, "338d ago") { + t.Errorf("a past deadline does not read as past:\n%s", out) + } + if strings.Contains(out, "Kubernetes 1.31") || !strings.Contains(out, "1 platform item(s)") { + t.Errorf("platform item shown or its hiding not stated:\n%s", out) + } + if out, _ := run(t, "maintain", "items", "--platform"); !strings.Contains(out, "Kubernetes 1.31") { + t.Errorf("--platform did not include it:\n%s", out) + } +} + +func TestMaintainItemsWithinFilters(t *testing.T) { + srv := resourceServer(t, map[string]any{maintainBase + "/items": maintainItems(false)}) + defer srv.Close() + isolateCluster(t, srv) + + out, _ := run(t, "maintain", "items", "--within", "30") + if !strings.Contains(out, "Node.js") || !strings.Contains(out, "PostgreSQL") { + t.Errorf("items inside the window missing:\n%s", out) + } + if strings.Contains(out, "Python") || strings.Contains(out, "Mystery") { + t.Errorf("items outside the window (or with no deadline) listed:\n%s", out) + } +} + +func TestMaintainItemsFailOnDaysGates(t *testing.T) { + srv := resourceServer(t, map[string]any{maintainBase + "/items": maintainItems(false)}) + defer srv.Close() + isolateCluster(t, srv) + + if out, code := run(t, "maintain", "items", "--fail-on-days", "30"); code != ExitPolicy { + t.Errorf("deadline in 15d against --fail-on-days 30 exited %d, want %d:\n%s", code, ExitPolicy, out) + } + // A lapsed deadline (PostgreSQL, 338 days ago) is the most due of all. + if _, code := run(t, "maintain", "items", "--fail-on-days", "0"); code != ExitPolicy { + t.Errorf("a past-due item did not fail --fail-on-days 0 (exit %d)", code) + } + if _, code := run(t, "maintain", "items", "--fail-on-days", "-5"); code != ExitUsage { + t.Errorf("a negative day count was accepted (exit %d)", code) + } +} + +// A list the backend could not finish reading must never exit 0. +func TestMaintainItemsReadFailedExitsNonZero(t *testing.T) { + srv := resourceServer(t, map[string]any{maintainBase + "/items": maintainItems(true)}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "maintain", "items") + if code != ExitFailure || !strings.Contains(out, "incomplete") { + t.Errorf("readFailed exit = %d, want %d:\n%s", code, ExitFailure, out) + } + if _, code := run(t, "maintain", "items", "-o", "json"); code != ExitFailure { + t.Errorf("readFailed under -o json exited %d", code) + } +} + +func TestMaintainPackagesStatesUnscannedWorkloads(t *testing.T) { + var q url.Values + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q = r.URL.Query() + w.Write([]byte(`{"success":true,"data":{"page":0,"size":50,"total":1, + "workloadsWithPackageList":8,"workloadsWithoutPackageList":3, + "items":[{"ecosystem":"maven","name":"log4j-core","versions":["2.17.1","2.14.0"],"workloads":4,"pods":9, + "eol":{"supportState":"EOL","deadline":"2024-01-01","daysLeft":-655}}]}}`)) + })) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "maintain", "packages", "--ecosystem", "maven", "--q", "log4j") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + if q.Get("ecosystem") != "maven" || q.Get("q") != "log4j" || q.Get("size") != "50" { + t.Errorf("query = %v", q) + } + for _, want := range []string{"log4j-core", "2.17.1,2.14.0", "EOL 2024-01-01", "655d ago", "3 workload(s) have no package list"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } +} + +func TestMaintainImpactScopesToSelectedClusterAndOrdersVerdicts(t *testing.T) { + var q url.Values + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q = r.URL.Query() + w.Write([]byte(`{"success":true,"data":{"product":"postgresql","displayName":"PostgreSQL", + "currentVersion":"13.14","target":"17","rulePack":true, + "summary":{"bumpDriver":1,"unknown":1,"review":0,"ready":1}, + "dependents":[ + {"namespace":"shop","kind":"Deployment","name":"ok-app","verdict":"READY"}, + {"namespace":"shop","kind":"Deployment","name":"mystery","verdict":"UNKNOWN","reason":"no driver seen"}, + {"namespace":"shop","kind":"Deployment","name":"old-jdbc","verdict":"BUMP_DRIVER", + "reason":"SCRAM needs pgjdbc 42.2+","drivers":[{"driver":"pgjdbc","version":"9.4"}]}], + "inbound":{"reported":true,"viaNode":2,"other":0}}}`)) + })) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "maintain", "impact", "data/StatefulSet/pg", "--target", "17") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + if q.Get("clusterId") != "c1" || q.Get("namespace") != "data" || q.Get("kind") != "StatefulSet" || + q.Get("name") != "pg" || q.Get("target") != "17" { + t.Errorf("query = %v", q) + } + b, u, r := strings.Index(out, "old-jdbc"), strings.Index(out, "mystery"), strings.Index(out, "ok-app") + if !(b >= 0 && b < u && u < r) { + t.Errorf("verdicts not ordered BUMP_DRIVER, UNKNOWN, READY:\n%s", out) + } + for _, want := range []string{"PostgreSQL 13.14 → 17", "1 bump driver · 1 unknown", "pgjdbc 9.4", "2 via a node"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } +} + +func TestMaintainDependentsWarnsOnPartialNodeCoverage(t *testing.T) { + srv := resourceServer(t, map[string]any{maintainBase + "/data-services/dependents": map[string]any{ + "coverage": "PARTIAL", "nodesExpected": 3, "nodesReported": 2, + "dependents": []map[string]any{{"namespace": "shop", "kind": "Deployment", "name": "api", + "via": "Service/pg", "port": 5432, "sockets": 12}}, + }}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "maintain", "dependents", "data/StatefulSet/pg") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + for _, want := range []string{"Dependents (1)", "api", "Service/pg", "5432", "only 2 of 3 nodes reported"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } +} + +func TestMaintainRefMustHaveThreeParts(t *testing.T) { + srv := resourceServer(t, map[string]any{}) + defer srv.Close() + isolateCluster(t, srv) + + if out, code := run(t, "maintain", "impact", "data/pg"); code != ExitUsage { + t.Errorf("a two-part ref exited %d, want %d:\n%s", code, ExitUsage, out) + } +} + +// -o json keeps every server field but still honours the filters. +func TestMaintainItemsJSONHonoursFilters(t *testing.T) { + srv := resourceServer(t, map[string]any{maintainBase + "/items": maintainItems(false)}) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "maintain", "items", "--within", "30", "-o", "json") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + if !strings.Contains(out, "Node.js 18") || strings.Contains(out, "Python") || strings.Contains(out, "Kubernetes 1.31") { + t.Errorf("filters not applied to -o json:\n%s", out) + } + if !strings.Contains(out, `"location": "shop/Deployment/web"`) { + t.Errorf("server fields dropped:\n%s", out) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index e44b92b..24aade6 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -108,6 +108,9 @@ No kubeconfig, no cluster VPN, no browser.`, newMetricsCmd(), newAskCmd(), newUpgradeCmd(), + newCapacityCmd(), + newMaintainCmd(), + newAddonsCmd(), newMcpCmd(), ) return root diff --git a/internal/cli/sections.go b/internal/cli/sections.go new file mode 100644 index 0000000..8b9d659 --- /dev/null +++ b/internal/cli/sections.go @@ -0,0 +1,52 @@ +package cli + +import ( + "fmt" + "io" + "strings" + + "github.com/runtimez-com/runtimez-cli/internal/render" +) + +// printSection prints a titled table. The count is stated even when it is zero: "Pending +// pods (0)" is a finding, whereas an omitted section reads as "not checked". +func printSection(e *env, w io.Writer, title string, t *render.Table) error { + fmt.Fprintf(w, "\n%s (%d)\n", title, len(t.Rows)) + return e.printer.Print(nil, t) +} + +// warnStatus states a section the backend could not fully read. status "" or "OK" is silent; +// anything else is a "we could not see", never health. +func warnStatus(w io.Writer, what, status, reason string) { + if s := strings.ToUpper(strings.TrimSpace(status)); s == "" || s == "OK" { + return + } + if reason = strings.TrimSpace(reason); reason != "" { + fmt.Fprintf(w, "warning: %s: %s — %s\n", what, status, reason) + return + } + fmt.Fprintf(w, "warning: %s: %s\n", what, status) +} + +// printNotes prints the backend's caveats under a section. +func printNotes(w io.Writer, notes []string) { + for _, n := range notes { + if n = strings.TrimSpace(n); n != "" { + fmt.Fprintf(w, " note: %s\n", n) + } + } +} + +// splitRef parses "/" or "//". +func splitRef(ref string, parts int, shape string) ([]string, error) { + p := strings.Split(ref, "/") + if len(p) != parts { + return nil, usageErrorf("expected %s, got %q", shape, ref) + } + for _, s := range p { + if strings.TrimSpace(s) == "" { + return nil, usageErrorf("expected %s, got %q", shape, ref) + } + } + return p, nil +} diff --git a/internal/cli/upgrade.go b/internal/cli/upgrade.go index 9f3b3cd..cf2f993 100644 --- a/internal/cli/upgrade.go +++ b/internal/cli/upgrade.go @@ -47,12 +47,13 @@ Without --target the backend evaluates the implied next minor version.`, return err } - r, err := e.client.UpgradeReadiness(cmd.Context(), orgID, clusterID, target) + p, err := e.client.UpgradeReadiness(cmd.Context(), orgID, clusterID, target) if err != nil { return err } + r := &p.Typed if e.printer.Format.Structured() { - if err := e.printer.Print(r, nil); err != nil { + if err := e.printer.Print(p.Raw, nil); err != nil { return err } } else { @@ -60,6 +61,9 @@ Without --target the backend evaluates the implied next minor version.`, if err := e.printer.Print(r.Findings, view.FindingsTable(r.Findings)); err != nil { return err } + if err := printUpgradeImpact(e, cmd.OutOrStdout(), r); err != nil { + return err + } warnReadinessQuality(cmd.ErrOrStderr(), r) } @@ -99,6 +103,43 @@ func printReadiness(cmd *cobra.Command, r *api.UpgradeReadiness) { fmt.Fprintln(out) } +// printUpgradeImpact adds the sections newer backends return: add-ons that must move, patch +// currency, and the per-application view. Each is skipped when the backend sent nothing, so +// an older backend prints exactly what it did before. +func printUpgradeImpact(e *env, out io.Writer, r *api.UpgradeReadiness) error { + if len(r.AddonHops) > 0 { + if err := printSection(e, out, "Add-ons that must move", view.AddonHopsTable(r)); err != nil { + return err + } + } + if pc := r.PatchCurrency; pc != nil && !pc.UpToDate && pc.PatchesBehind > 0 { + label := "" + if !pc.DataSourced { + label = " (unsourced)" + } + fmt.Fprintf(out, "\nPatch: %s is %d patch(es) behind %s%s\n", render.Dash(pc.CurrentVersion), pc.PatchesBehind, + render.Dash(pc.LatestPatchVersion), label) + if pc.Advisory != "" { + fmt.Fprintf(out, " %s\n", pc.Advisory) + } + } + if ai := r.AppImpact; ai != nil { + if err := printSection(e, out, "Applications", view.AppImpactTable(r)); err != nil { + return err + } + if ai.PlatformFindings > 0 { + fmt.Fprintf(out, " %d finding(s) are platform-only (no application object)\n", ai.PlatformFindings) + } + if !ai.NamespacesRead { + fmt.Fprintln(out, " note: namespaces were not read — findings could not all be placed on an application") + } + if ai.UnattributedObjects > 0 { + fmt.Fprintf(out, " note: %d object(s) could not be placed on an application\n", ai.UnattributedObjects) + } + } + return nil +} + // warnReadinessQuality surfaces the fields that say how much the verdict is worth. A // readiness score built on stale or partial data reads exactly like one built on fresh // complete data. diff --git a/internal/cli/upgrade_test.go b/internal/cli/upgrade_test.go index 5eddafb..c8630e1 100644 --- a/internal/cli/upgrade_test.go +++ b/internal/cli/upgrade_test.go @@ -251,3 +251,38 @@ func TestRiskCheckCleanBundleSaysSo(t *testing.T) { func writeFile(path, content string) error { return os.WriteFile(path, []byte(content), 0o600) } + +func TestUpgradeCheckShowsAppImpactHopsAndPatch(t *testing.T) { + srv := resourceServer(t, map[string]any{ + clusterBase + "/upgrade-readiness": map[string]any{ + "currentVersion": "1.33", "targetVersion": "1.34", "score": 40, "riskLevel": "MEDIUM", "findings": []any{}, + "addonHops": []map[string]any{{"addonId": "istio", "installedVersion": "1.26.2", "requiredVersion": "1.27.0", + "reason": "1.26 does not support Kubernetes 1.34"}}, + "patchCurrency": map[string]any{"currentVersion": "1.33.1", "latestPatchVersion": "1.33.5", + "patchesBehind": 4, "upToDate": false, "dataSourced": true}, + "appImpact": map[string]any{"namespacesRead": true, "platformFindings": 2, + "applications": []map[string]any{{"namespace": "shop", + "mustChange": []map[string]any{{"ruleId": "k8s-134-x", "title": "Remove flowcontrol v1beta3", + "severity": "HIGH", "appliesAtVersion": "1.34", "objects": []string{"FlowSchema/a", "FlowSchema/b"}}}, + "affected": []map[string]any{{"title": "Sidecar probe race", "severity": "LOW", "addon": "istio"}}}}}, + "remediation": map[string]any{"untypedButKept": true}, + }, + }) + defer srv.Close() + isolateCluster(t, srv) + + out, code := run(t, "upgrade", "check") + if code != ExitOK { + t.Fatalf("exit = %d:\n%s", code, out) + } + for _, want := range []string{"Add-ons that must move (1)", "istio", "1.27.0", "before Kubernetes", + "1.33.1 is 4 patch(es) behind 1.33.5", "Applications (2)", "must change", "Remove flowcontrol v1beta3", + "FlowSchema/a +1", "affected", "2 finding(s) are platform-only"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + if out, _ := run(t, "upgrade", "check", "-o", "json"); !strings.Contains(out, "untypedButKept") { + t.Errorf("-o json dropped a field the CLI does not type:\n%s", out) + } +} diff --git a/internal/view/addons.go b/internal/view/addons.go new file mode 100644 index 0000000..dc53869 --- /dev/null +++ b/internal/view/addons.go @@ -0,0 +1,292 @@ +package view + +import ( + "sort" + "strconv" + "strings" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/render" +) + +// Every add-on list table ends in the same two columns — how many findings the row carries +// and the worst one — so a reader scanning any workspace looks in the same place. + +func findingCells(rs []api.AddonReason) (string, string) { + w := WorstReason(rs) + if w == nil { + return "0", "" + } + return strconv.Itoa(len(rs)), w.Severity + " " + truncate(w.Title, 60) +} + +// ReasonsTable lists one row's findings, worst first, with the command that verifies each. +func ReasonsTable(rs []api.AddonReason) *render.Table { + rows := append([]api.AddonReason(nil), rs...) + sort.SliceStable(rows, func(i, j int) bool { + a, _ := api.SeverityRank(rows[i].Severity) + b, _ := api.SeverityRank(rows[j].Severity) + return a > b + }) + t := &render.Table{ + Headers: []string{"SEVERITY", "RULE", "TITLE", "OBJECT", "VERIFY"}, + WideHeaders: []string{"MESSAGE", "RECOMMENDATION"}, + EmptyMessage: "No findings.", + } + for _, r := range rows { + obj := strings.TrimSpace(r.ObjectKind + " " + r.ObjectRef) + t.Rows = append(t.Rows, []string{ + render.Dash(r.Severity), render.Dash(r.RuleID), render.Dash(truncate(r.Title, 70)), + render.Dash(obj), render.Dash(r.VerifyCommand), + }) + t.WideRows = append(t.WideRows, []string{render.Dash(r.Message), render.Dash(r.Recommendation)}) + } + return t +} + +// EventsTable lists a workspace detail's events, newest first. +func EventsTable(evs []api.WorkspaceEvent) *render.Table { + rows := append([]api.WorkspaceEvent(nil), evs...) + sort.SliceStable(rows, func(i, j int) bool { + if rows[i].At == nil || rows[j].At == nil { + return rows[j].At == nil && rows[i].At != nil + } + return rows[i].At.After(*rows[j].At) + }) + t := &render.Table{ + Headers: []string{"AGE", "TYPE", "REASON", "OBJECT", "MESSAGE"}, + EmptyMessage: "No events.", + } + for _, e := range rows { + t.Rows = append(t.Rows, []string{ + Since(e.At), render.Dash(e.Type), render.Dash(e.Reason), + render.Dash(strings.TrimSpace(e.ObjectKind + "/" + e.ObjectName)), render.Dash(truncate(e.Message, 90)), + }) + } + return t +} + +func NodePoolsTable(rows []api.NodePoolRow) *render.Table { + t := &render.Table{ + Headers: []string{"NODEPOOL", "STATE", "NODES", "CLAIMS", "DRIFTED", "NOT READY", "FINDINGS", "WORST"}, + WideHeaders: []string{"WEIGHT", "CONSOLIDATION", "DETAIL"}, + EmptyMessage: "No NodePools.", + } + for _, p := range rows { + n, w := findingCells(p.Reasons) + t.Rows = append(t.Rows, []string{p.Name, render.Dash(p.State), Int64(p.Nodes), strconv.Itoa(p.NodeClaimCount), + strconv.Itoa(p.DriftedCount), strconv.Itoa(p.NotReadyNodeCount), n, w}) + t.WideRows = append(t.WideRows, []string{Int(p.Weight), render.Dash(p.ConsolidationPolicy), render.Dash(p.StateDetail)}) + } + return t +} + +func NodeClaimsTable(d *api.NodePoolDetail) *render.Table { + t := &render.Table{ + Headers: []string{"NODECLAIM", "PHASE", "TYPE", "CAPACITY", "ZONE", "NODE", "DRIFTED", "REASON"}, + EmptyMessage: "No NodeClaims.", + } + for _, c := range d.NodeClaims { + drift := "no" + if c.Drifted { + drift = "yes" + } + t.Rows = append(t.Rows, []string{c.Name, render.Dash(c.Phase), render.Dash(c.InstanceType), render.Dash(c.CapacityType), + render.Dash(c.Zone), render.Dash(c.NodeName), drift, render.Dash(c.PhaseReason)}) + } + return t +} + +func NodeGroupsTable(rows []api.NodeGroupRow) *render.Table { + t := &render.Table{ + Headers: []string{"NODEGROUP", "STATE", "NODES", "TARGET", "MIN", "MAX", "FINDINGS", "WORST"}, + WideHeaders: []string{"DETAIL"}, + EmptyMessage: "No node groups.", + } + for _, g := range rows { + n, w := findingCells(g.Reasons) + t.Rows = append(t.Rows, []string{g.Name, render.Dash(g.State), strconv.Itoa(g.NodeCount), + Int(g.Target), Int(g.MinSize), Int(g.MaxSize), n, w}) + t.WideRows = append(t.WideRows, []string{render.Dash(g.Detail)}) + } + return t +} + +func NodeGroupNodesTable(d *api.NodeGroupDetail) *render.Table { + t := &render.Table{ + Headers: []string{"NODE", "READY", "TYPE", "ZONE", "SCALE-DOWN DISABLED"}, + EmptyMessage: "No nodes in this group.", + } + for _, n := range d.Nodes { + sd := "no" + if n.ScaleDownDisabled { + sd = "yes" + } + t.Rows = append(t.Rows, []string{n.Name, Bool(n.Ready), render.Dash(n.InstanceType), render.Dash(n.Zone), sd}) + } + return t +} + +func IngressRoutesTable(rows []api.IngressRouteRow) *render.Table { + t := &render.Table{ + Headers: []string{"NAMESPACE", "KIND", "NAME", "HOSTS", "STATE", "FINDINGS", "WORST"}, + WideHeaders: []string{"WHY"}, + EmptyMessage: "No routes.", + } + for _, r := range rows { + var hosts []string + for _, m := range r.Matches { + hosts = append(hosts, m.Hosts...) + } + n, w := findingCells(r.Reasons) + t.Rows = append(t.Rows, []string{r.Namespace, r.Kind, r.Name, render.Dash(truncate(strings.Join(dedupe(hosts), ","), 40)), + render.Dash(r.State), n, w}) + t.WideRows = append(t.WideRows, []string{render.Dash(r.StateWhy)}) + } + return t +} + +func BackendWorkloadsTable(d *api.IngressRouteDetail) *render.Table { + t := &render.Table{ + Headers: []string{"NAMESPACE", "KIND", "NAME", "SERVICE"}, + EmptyMessage: "No backend workloads resolved.", + } + for _, b := range d.BackendWorkloads { + t.Rows = append(t.Rows, []string{b.Namespace, b.Kind, b.Name, render.Dash(b.Service)}) + } + return t +} + +func MeshWorkloadsTable(rows []api.MeshWorkloadRow) *render.Table { + t := &render.Table{ + Headers: []string{"NAMESPACE", "KIND", "NAME", "PROXY", "MESHED", "MTLS", "STATE", "FINDINGS", "WORST"}, + WideHeaders: []string{"PROXY VERSION", "WHY"}, + EmptyMessage: "No workloads.", + } + for _, m := range rows { + proxy, meshed, version, mtls := unknown, unknown, "", unknown + if p := m.Proxy; p != nil { + proxy, meshed, version = render.Dash(p.Status), strconv.Itoa(p.PodsMeshed)+"/"+strconv.Itoa(p.Pods), render.Dash(p.Version) + } + if x := m.Mtls; x != nil && x.Known { + mtls = render.Dash(x.Mode) + } + n, w := findingCells(m.Reasons) + t.Rows = append(t.Rows, []string{m.Namespace, m.Kind, m.Name, proxy, meshed, mtls, render.Dash(m.State), n, w}) + t.WideRows = append(t.WideRows, []string{version, render.Dash(m.StateWhy)}) + } + return t +} + +func MeshPodsTable(d *api.MeshWorkloadDetail) *render.Table { + t := &render.Table{ + Headers: []string{"POD", "MESHED", "NATIVE SIDECAR", "VERSION", "REVISION", "OPTED OUT"}, + EmptyMessage: "No pods.", + } + yn := func(b bool) string { + if b { + return "yes" + } + return "no" + } + for _, p := range d.Pods { + t.Rows = append(t.Rows, []string{p.Name, yn(p.Meshed), yn(p.NativeSidecar), render.Dash(p.Version), + render.Dash(p.Revision), yn(p.OptedOut)}) + } + return t +} + +func GitOpsAppsTable(rows []api.GitOpsAppRow) *render.Table { + t := &render.Table{ + Headers: []string{"NAMESPACE", "APPLICATION", "PROJECT", "SYNC", "HEALTH", "STATE", "FINDINGS", "WORST"}, + WideHeaders: []string{"OPERATION"}, + EmptyMessage: "No Applications.", + } + for _, a := range rows { + n, w := findingCells(a.Reasons) + t.Rows = append(t.Rows, []string{a.Namespace, a.Name, render.Dash(a.Project), render.Dash(a.Sync), + render.Dash(a.Health), render.Dash(a.State), n, w}) + t.WideRows = append(t.WideRows, []string{render.Dash(a.OperationPhase)}) + } + return t +} + +func GitOpsWorkloadsTable(d *api.GitOpsAppDetail) *render.Table { + t := &render.Table{ + Headers: []string{"NAMESPACE", "KIND", "NAME", "READY", "TRACKED BY"}, + EmptyMessage: "No workloads deployed by this Application.", + } + for _, w := range d.Workloads { + t.Rows = append(t.Rows, []string{w.Namespace, w.Kind, w.Name, Int(w.ReadyReplicas) + "/" + Int(w.DesiredReplicas), + render.Dash(w.TrackedBy)}) + } + return t +} + +func VpcCniNodesTable(rows []api.VpcCniNodeRow) *render.Table { + t := &render.Table{ + Headers: []string{"NODE", "STATE", "TYPE", "ZONE", "IPS ASSIGNED", "IPS USABLE", "ENIS", "FINDINGS", "WORST"}, + WideHeaders: []string{"MAX PODS", "CNI RESTARTS", "DETAIL"}, + EmptyMessage: "No nodes.", + } + for _, n := range rows { + f, w := findingCells(n.Reasons) + t.Rows = append(t.Rows, []string{n.Name, render.Dash(n.State), render.Dash(n.InstanceType), render.Dash(n.Zone), + Int(n.IPAssigned), Int(n.IPUsable) + "/" + Int(n.IPMax), Int(n.EnisAllocated) + "/" + Int(n.EnisMax), f, w}) + t.WideRows = append(t.WideRows, []string{Int(n.MaxPods), Int(n.CNIPodRestarts), render.Dash(n.StateDetail)}) + } + return t +} + +func VpcCniErrorsTable(d *api.VpcCniNodeDetail) *render.Table { + t := &render.Table{ + Headers: []string{"FAMILY", "ERROR", "LAST HOUR", "LAST DAY", "LAST SEEN", "DETAIL"}, + EmptyMessage: "No ipamd or AWS API errors recorded.", + } + for _, e := range d.Errors { + t.Rows = append(t.Rows, []string{render.Dash(e.Family), render.Dash(e.Key), strconv.Itoa(e.LastHour), + strconv.Itoa(e.LastDay), Since(e.LastSeen), render.Dash(truncate(e.Detail, 70))}) + } + return t +} + +func EbsCsiNodesTable(rows []api.EbsCsiNodeRow) *render.Table { + t := &render.Table{ + Headers: []string{"NODE", "STATE", "READY", "DRIVER", "ATTACHED", "FAILING", "FINDINGS", "WORST"}, + EmptyMessage: "No nodes.", + } + for _, n := range rows { + f, w := findingCells(n.Reasons) + t.Rows = append(t.Rows, []string{n.Name, render.Dash(n.State), Bool(n.NodeReady), Bool(n.DriverRegistered), + Int(n.Attached) + "/" + Int(n.Limit), strconv.Itoa(n.FailingAttachments), f, w}) + } + return t +} + +func EbsCsiAttachmentsTable(rows []api.EbsCsiAttachment) *render.Table { + t := &render.Table{ + Headers: []string{"ATTACHMENT", "NODE", "VOLUME", "ATTACHED", "PROBLEM", "SINCE", "MESSAGE"}, + EmptyMessage: "No VolumeAttachments.", + } + for _, a := range rows { + att := "no" + if a.Attached { + att = "yes" + } + t.Rows = append(t.Rows, []string{a.Name, render.Dash(a.Node), render.Dash(a.PersistentVolume), att, + render.Dash(a.Problem), Since(a.Since), render.Dash(truncate(a.Message, 70))}) + } + return t +} + +func dedupe(s []string) []string { + seen := map[string]bool{} + out := s[:0:0] + for _, v := range s { + if !seen[v] { + seen[v] = true + out = append(out, v) + } + } + return out +} diff --git a/internal/view/capacity.go b/internal/view/capacity.go new file mode 100644 index 0000000..c3a94c6 --- /dev/null +++ b/internal/view/capacity.go @@ -0,0 +1,389 @@ +package view + +import ( + "sort" + "strconv" + "strings" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/render" +) + +// CapacitySections are the detail sections `rtz capacity --section` accepts. The names match +// the MCP runtimez_capacity_summary tool's, so the same word works in both places. +var CapacitySections = []string{"pools", "nodes", "blocked", "storage", "network", "batch", "special"} + +// HeadroomTable is one row per axis (cpu, memory, pods). +func HeadroomTable(c *api.Capacity) *render.Table { + t := &render.Table{ + Headers: []string{"AXIS", "ALLOCATABLE", "REQUESTED", "REQ %", "USED", "USED %", "HEADROOM", "LARGEST FIT"}, + WideHeaders: []string{"LARGEST FIT NODE"}, + EmptyMessage: "No capacity axes reported.", + } + for _, a := range c.Headroom { + f := axisFormatter(a.Unit) + t.Rows = append(t.Rows, []string{ + a.Axis, f(a.Allocatable), f(a.Requested), Pct(a.RequestsCommitmentPct), + f(a.Used), Pct(a.UsedPct), f(a.Headroom), f(a.LargestFit), + }) + t.WideRows = append(t.WideRows, []string{render.Dash(a.LargestFitNode)}) + } + return t +} + +func axisFormatter(unit string) func(*int64) string { + switch strings.ToLower(unit) { + case "millicores": + return CPU + case "bytes": + return Bytes + default: + return Int64 + } +} + +// PoolsTable is one row per node pool. +func PoolsTable(pools []api.CapacityPool) *render.Table { + t := &render.Table{ + Headers: []string{"POOL", "SOURCE", "NODES", "CPU REQ %", "MEM REQ %", "CPU USED %", "MEM USED %", + "CPU FREE", "MEM FREE", "PODS", "CAN GROW"}, + WideHeaders: []string{"AUTOSCALER", "NODE CEILING", "GROW REASON"}, + EmptyMessage: "No node pools.", + } + for _, p := range pools { + grow, reason := unknown, "" + if g := p.RoomToGrow; g != nil { + reason = g.Reason + switch { + case g.AtCeiling: + grow = "at ceiling" + case g.Nodes != nil: + grow = "+" + strconv.FormatInt(*g.Nodes, 10) + " nodes" + } + } + t.Rows = append(t.Rows, []string{ + p.Name, render.Dash(p.Source), strconv.Itoa(p.Nodes), + Pct(p.CPURequestsCommitmentPct), Pct(p.MemoryRequestsCommitmentPct), + Pct(p.CPUUsedPct), Pct(p.MemoryUsedPct), + CPU(resCPU(p.Headroom)), Bytes(resMem(p.Headroom)), + strconv.Itoa(p.Pods) + "/" + Int64(p.AllocatablePods), grow, + }) + t.WideRows = append(t.WideRows, []string{render.Dash(p.AutoscalerState), Int64(p.NodeCeiling), render.Dash(reason)}) + } + return t +} + +// CapacityNodesTable is one row per node. +func CapacityNodesTable(c *api.Capacity) *render.Table { + t := &render.Table{ + Headers: []string{"NODE", "POOL", "ZONE", "TYPE", "CAPACITY", "PODS", "CPU REQ", "CPU FREE", "MEM REQ", "MEM FREE"}, + WideHeaders: []string{"CPU USED", "MEM USED", "EXCLUDED"}, + EmptyMessage: "No nodes.", + } + for _, n := range c.Nodes { + excl := "" + if !n.Eligible { + excl = render.Dash(n.Exclusion) + } + t.Rows = append(t.Rows, []string{ + n.Name, render.Dash(n.Pool), render.Dash(n.Zone), render.Dash(n.InstanceType), render.Dash(n.CapacityType), + strconv.Itoa(n.Pods), CPU(resCPU(n.Requested)), CPU(resCPU(n.Headroom)), + Bytes(resMem(n.Requested)), Bytes(resMem(n.Headroom)), + }) + t.WideRows = append(t.WideRows, []string{CPU(resCPU(n.Used)), Bytes(resMem(n.Used)), excl}) + } + return t +} + +// BlockedTable lists pods the scheduler could not place, longest-waiting first. +func BlockedTable(c *api.Capacity) *render.Table { + rows := append(c.Blocked[:0:0], c.Blocked...) + sort.SliceStable(rows, func(i, j int) bool { return i64(rows[i].PendingSeconds) > i64(rows[j].PendingSeconds) }) + t := &render.Table{ + Headers: []string{"NAMESPACE", "POD", "OWNER", "PENDING", "CATEGORY", "SHORTFALL", "WHY"}, + WideHeaders: []string{"NOMINATED", "VERIFY"}, + EmptyMessage: "No pending pods.", + } + for _, b := range rows { + owner := "" + if b.OwnerKind != "" { + owner = b.OwnerKind + "/" + b.OwnerName + } + short := "no" + if b.CapacityShortfall { + short = "yes" + } + t.Rows = append(t.Rows, []string{ + b.Namespace, b.Name, owner, Seconds(b.PendingSeconds), render.Dash(b.PrimaryCategory), short, + render.Dash(truncate(b.Message, 80)), + }) + t.WideRows = append(t.WideRows, []string{render.Dash(b.NominatedNode), render.Dash(b.VerifyCommand)}) + } + return t +} + +// StorageTable lists PVCs, fullest first, then pending claims. +func StorageTable(c *api.Capacity) *render.Table { + t := &render.Table{ + Headers: []string{"NAMESPACE", "CLAIM", "PHASE", "CLASS", "SIZE", "USED", "USED %", "DAYS TO FULL", "MOUNTED BY"}, + WideHeaders: []string{"FORECAST", "USAGE NOTE"}, + EmptyMessage: "No persistent volume claims.", + } + if c.Storage == nil { + return t + } + pvcs := append(c.Storage.PVCs[:0:0], c.Storage.PVCs...) + sort.SliceStable(pvcs, func(i, j int) bool { return f64(pvcs[i].UsedPct) > f64(pvcs[j].UsedPct) }) + for _, p := range pvcs { + days := unknown + if p.DaysToFull != nil { + days = strconv.FormatFloat(*p.DaysToFull, 'f', 0, 64) + "d" + } + t.Rows = append(t.Rows, []string{ + p.Namespace, p.Name, render.Dash(p.Phase), render.Dash(p.StorageClass), + Bytes(p.CapacityBytes), Bytes(p.UsedBytes), Pct(p.UsedPct), days, render.Dash(p.MountedBy), + }) + t.WideRows = append(t.WideRows, []string{render.Dash(p.Forecast), render.Dash(p.UsageReason)}) + } + for _, p := range c.Storage.Pending { + t.Rows = append(t.Rows, []string{ + p.Namespace, p.Name, "Pending", render.Dash(p.StorageClass), unknown, unknown, unknown, unknown, "", + }) + t.WideRows = append(t.WideRows, []string{"PENDING " + Seconds(p.PendingSeconds), render.Dash(p.Reason)}) + } + return t +} + +// NetworkTable is pod-IP headroom per pool. +func NetworkTable(c *api.Capacity) *render.Table { + t := &render.Table{ + Headers: []string{"POOL", "NODES", "IP HEADROOM", "SLOT HEADROOM", "IPS RUN OUT FIRST", "LAUNCHABLE", "SUBNET FULL"}, + WideHeaders: []string{"SUBNETS", "LAUNCHABLE REASON"}, + EmptyMessage: "No pool network data.", + } + if c.Network == nil { + return t + } + for _, p := range c.Network.Pools { + full := "no" + if p.SubnetExhausted { + full = "YES" + } + t.Rows = append(t.Rows, []string{ + p.Name, strconv.Itoa(p.Nodes), Int64(p.IPHeadroom), Int64(p.SlotHeadroom), + strconv.Itoa(p.NodesIPsFirst) + " nodes", Int(p.LaunchableNodes), full, + }) + t.WideRows = append(t.WideRows, []string{render.Dash(strings.Join(p.LaunchSubnets, ",")), render.Dash(p.LaunchableReason)}) + } + return t +} + +// BatchTable lists CronJobs with their overlap verdict, then Jobs with pending pods. +func BatchTable(c *api.Capacity) *render.Table { + t := &render.Table{ + Headers: []string{"KIND", "NAMESPACE", "NAME", "VERDICT", "RUNNING", "PENDING", "DETAIL"}, + EmptyMessage: "No Jobs or CronJobs.", + } + if c.Batch == nil { + return t + } + for _, cj := range c.Batch.CronJobs { + detail := cj.Schedule + if cj.Suspended { + detail += " (suspended)" + } + if cj.VerdictReason != "" { + detail += " — " + cj.VerdictReason + } + t.Rows = append(t.Rows, []string{"CronJob", cj.Namespace, cj.Name, render.Dash(cj.Verdict), + strconv.Itoa(cj.ActiveRuns), "-", render.Dash(truncate(detail, 80))}) + } + for _, j := range c.Batch.Jobs { + var parts []string + if j.CronJob != "" { + parts = append(parts, "from CronJob "+j.CronJob) + } + if j.OldestPendingSeconds != nil { + parts = append(parts, "oldest pending "+Seconds(j.OldestPendingSeconds)) + } + t.Rows = append(t.Rows, []string{"Job", j.Namespace, j.Name, "-", + strconv.Itoa(j.Running), strconv.Itoa(j.Pending), render.Dash(strings.Join(parts, ", "))}) + } + return t +} + +// SpecialTable lists GPUs and other extended resources. +func SpecialTable(c *api.Capacity) *render.Table { + t := &render.Table{ + Headers: []string{"RESOURCE", "KIND", "ALLOCATABLE", "REQUESTED", "REQ %", "FREE", "NODES", "BLOCKED PODS"}, + EmptyMessage: "No GPUs or other special resources.", + } + if c.Special == nil { + return t + } + for _, r := range c.Special.Resources { + t.Rows = append(t.Rows, []string{ + r.Name, render.Dash(r.Kind), Int64(r.Allocatable), strconv.FormatInt(r.Requested, 10), + Pct(r.RequestedPct), Int64(r.Free), strconv.Itoa(r.NodesOffered), strconv.Itoa(r.BlockedPods), + }) + } + return t +} + +// CapacityTrendTable is one row per pool: grade and days to full per axis. +func CapacityTrendTable(tr *api.CapacityTrend) *render.Table { + t := &render.Table{ + Headers: []string{"POOL", "GRADE", "CPU NOW", "CPU FULL IN", "MEM NOW", "MEM FULL IN"}, + WideHeaders: []string{"CPU FULL ON", "MEM FULL ON", "GRADE REASON"}, + EmptyMessage: "No pool trends yet.", + } + for _, p := range tr.Pools { + grade, gradeWhy := unknown, "" + if p.Grade != nil { + grade, gradeWhy = render.Dash(p.Grade.Status), p.Grade.Reason + } + cNow, cIn, cOn := forecastCells(p.CPU) + mNow, mIn, mOn := forecastCells(p.Memory) + t.Rows = append(t.Rows, []string{p.Name, grade, cNow, cIn, mNow, mIn}) + t.WideRows = append(t.WideRows, []string{cOn, mOn, render.Dash(gradeWhy)}) + } + return t +} + +// forecastCells renders a forecast; a non-OK status is printed in place of a number so a +// pool still collecting data never reads as "never fills". +func forecastCells(f *api.CapacityForecast) (now, in, on string) { + if f == nil { + return unknown, unknown, unknown + } + now = Pct(f.CurrentPct) + switch { + case f.Days != nil: + in = Days(f.Days) + case f.Status != "": + in = f.Status + default: + in = unknown + } + return now, in, render.Dash(f.FullOn) +} + +// CapacityCostTable is one row per pool, then the levers. +func CapacityCostTable(c *api.CapacityCost) *render.Table { + t := &render.Table{ + Headers: []string{"POOL", "SOURCE", "NODES", "PRICED", "HOURLY", "MONTHLY", "CPU REQ %", "MEM REQ %"}, + EmptyMessage: "No priced pools.", + } + for _, p := range c.Pools { + t.Rows = append(t.Rows, []string{ + p.Pool, render.Dash(p.Source), strconv.Itoa(p.Nodes), strconv.Itoa(p.PricedNodes), + Money(p.Hourly), Money(p.Monthly), Pct(p.CPURequestsPct), Pct(p.MemoryRequestsPct), + }) + } + return t +} + +// CostLeversTable lists the cost levers, savings first. +func CostLeversTable(c *api.CapacityCost) *render.Table { + t := &render.Table{ + Headers: []string{"LEVER", "SAVING", "MONTHLY", "ACTS IN", "WHY"}, + WideHeaders: []string{"BASIS"}, + EmptyMessage: "No cost levers.", + } + for _, l := range c.Levers { + s := "no" + if l.Saving { + s = "yes" + } + t.Rows = append(t.Rows, []string{render.Dash(l.Label), s, Money(l.Monthly), render.Dash(l.ActsIn), + render.Dash(truncate(l.Reason, 80))}) + t.WideRows = append(t.WideRows, []string{render.Dash(l.Basis)}) + } + return t +} + +// CapacityNamespacesTable is one row per namespace, biggest CPU share first. +func CapacityNamespacesTable(n *api.CapacityNamespaces) *render.Table { + rows := append(n.Namespaces[:0:0], n.Namespaces...) + sort.SliceStable(rows, func(i, j int) bool { return f64(rows[i].CPUShare) > f64(rows[j].CPUShare) }) + t := &render.Table{ + Headers: []string{"NAMESPACE", "PODS", "PENDING", "CPU REQ", "CPU SHARE", "MEM REQ", "MEM SHARE", "QUOTA", "FULLEST QUOTA"}, + WideHeaders: []string{"CPU USED", "MEM USED"}, + EmptyMessage: "No namespaces.", + } + for _, ns := range rows { + fullest := "" + if f := ns.Fullest; f != nil { + fullest = f.Resource + " " + f.Used + "/" + f.Hard + " (" + Pct(f.Pct) + ")" + } + t.Rows = append(t.Rows, []string{ + ns.Namespace, strconv.Itoa(ns.Pods), strconv.Itoa(ns.PendingPods), + CPU(resCPU(ns.Requested)), Pct(ns.CPUShare), Bytes(resMem(ns.Requested)), Pct(ns.MemoryShare), + render.Dash(ns.QuotaStatus), fullest, + }) + t.WideRows = append(t.WideRows, []string{CPU(resCPU(ns.Used)), Bytes(resMem(ns.Used))}) + } + return t +} + +// FleetCapacityTable is one row per cluster, soonest-full first. +func FleetCapacityTable(f *api.FleetCapacity) *render.Table { + rows := append(f.Clusters[:0:0], f.Clusters...) + sort.SliceStable(rows, func(i, j int) bool { + return soonest(rows[i].SoonestFull) < soonest(rows[j].SoonestFull) + }) + t := &render.Table{ + Headers: []string{"CLUSTER", "STATUS", "GRADE", "CPU REQ %", "MEM REQ %", "PENDING", "SHORTFALL", "FULLS FIRST", "IN"}, + WideHeaders: []string{"CLUSTER ID", "AUTOSCALER", "NOTE"}, + EmptyMessage: "No clusters.", + } + for _, c := range rows { + first, in := "", unknown + if s := c.SoonestFull; s != nil { + first = s.Pool + " " + s.Axis + if s.Days != nil { + in = Days(s.Days) + } else { + in = render.Dash(s.Status) + } + } + note := c.Reason + if c.FromEarlierSync { + note = strings.TrimSpace("from an earlier sync " + note) + } + t.Rows = append(t.Rows, []string{ + render.Dash(c.Name), render.Dash(c.Status), render.Dash(c.Grade), + axisPct(c.CPU), axisPct(c.Memory), Int(c.Pending), Int(c.CapacityShortfall), first, in, + }) + t.WideRows = append(t.WideRows, []string{c.ClusterID, render.Dash(c.AutoscalerState), render.Dash(note)}) + } + return t +} + +func axisPct(a *api.FleetAxis) string { + if a == nil { + return unknown + } + return Pct(a.RequestsCommitmentPct) +} + +func soonest(s *api.FleetSoonestFull) int { + if s == nil || s.Days == nil { + return 1 << 30 + } + return *s.Days +} + +func i64(v *int64) int64 { + if v == nil { + return -1 + } + return *v +} + +func f64(v *float64) float64 { + if v == nil { + return -1 + } + return *v +} diff --git a/internal/view/maintain.go b/internal/view/maintain.go new file mode 100644 index 0000000..24a3e80 --- /dev/null +++ b/internal/view/maintain.go @@ -0,0 +1,121 @@ +package view + +import ( + "sort" + "strconv" + "strings" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/render" +) + +// MaintainItemsTable lists lifecycle items, soonest deadline first. Items with no known +// deadline sort last: an unknown deadline is not a far one, but it is not the next one either. +func MaintainItemsTable(items []api.MaintainItem) *render.Table { + rows := append([]api.MaintainItem(nil), items...) + sort.SliceStable(rows, func(i, j int) bool { return daysKey(rows[i].DaysLeft) < daysKey(rows[j].DaysLeft) }) + t := &render.Table{ + Headers: []string{"CLUSTER", "TYPE", "ITEM", "VERSION", "DEADLINE", "DAYS LEFT", "SUPPORT", "WHERE"}, + WideHeaders: []string{"KIND", "CONFIDENCE", "OWNER", "PLATFORM", "SOURCE"}, + EmptyMessage: "No Maintain items.", + } + for _, it := range rows { + platform := "no" + if it.Platform { + platform = "yes" + } + t.Rows = append(t.Rows, []string{ + render.Dash(it.ClusterName), render.Dash(it.ItemType), render.Dash(it.DisplayName), + render.Dash(it.Version), render.Dash(it.Deadline), Days(it.DaysLeft), + render.Dash(it.SupportState), render.Dash(it.Location), + }) + t.WideRows = append(t.WideRows, []string{render.Dash(it.DeadlineKind), render.Dash(it.Confidence), + render.Dash(it.Owner), platform, render.Dash(it.SourceURL)}) + } + return t +} + +func daysKey(d *int) int { + if d == nil { + return 1 << 30 + } + return *d +} + +// InventoryTable lists running packages, most-used first (the backend's order). +func InventoryTable(inv *api.MaintainInventory) *render.Table { + t := &render.Table{ + Headers: []string{"ECOSYSTEM", "PACKAGE", "VERSIONS", "WORKLOADS", "PODS", "EOL", "DAYS LEFT"}, + EmptyMessage: "No packages match.", + } + for _, it := range inv.Items { + v := strings.Join(it.Versions, ",") + if it.VersionsCapped { + v += ",…" + } + eol, days := "", "" + if it.EOL != nil { + eol = strings.TrimSpace(it.EOL.SupportState + " " + it.EOL.Deadline) + days = Days(it.EOL.DaysLeft) + } + t.Rows = append(t.Rows, []string{ + render.Dash(it.Ecosystem), it.Name, render.Dash(truncate(v, 40)), + strconv.Itoa(it.Workloads), strconv.Itoa(it.Pods), render.Dash(eol), days, + }) + } + return t +} + +// DependentsTable lists the workloads that connect to a data service. +func DependentsTable(d *api.DataServiceDependents) *render.Table { + t := &render.Table{ + Headers: []string{"NAMESPACE", "KIND", "NAME", "VIA", "PORT", "SOCKETS", "LAST SEEN"}, + WideHeaders: []string{"ROLE", "POOLER", "CLUSTER"}, + EmptyMessage: "No dependents observed.", + } + for _, x := range d.Dependents { + t.Rows = append(t.Rows, []string{ + x.Namespace, x.Kind, x.Name, render.Dash(x.Via), strconv.Itoa(x.Port), + strconv.FormatInt(x.Sockets, 10), Since(x.LastSeen), + }) + t.WideRows = append(t.WideRows, []string{render.Dash(x.Role), render.Dash(x.Pooler), render.Dash(x.ClusterName)}) + } + return t +} + +// ImpactTable lists each dependent's verdict for the upgrade, worst first. +func ImpactTable(im *api.DataServiceImpact) *render.Table { + rows := append(im.Dependents[:0:0], im.Dependents...) + sort.SliceStable(rows, func(i, j int) bool { return verdictRank(rows[i].Verdict) > verdictRank(rows[j].Verdict) }) + t := &render.Table{ + Headers: []string{"NAMESPACE", "KIND", "NAME", "VERDICT", "DRIVERS", "WHY"}, + WideHeaders: []string{"VIA", "CLUSTER"}, + EmptyMessage: "No dependents observed.", + } + for _, x := range rows { + drivers := make([]string, 0, len(x.Drivers)) + for _, d := range x.Drivers { + drivers = append(drivers, strings.TrimSpace(d.Driver+" "+d.Version)) + } + t.Rows = append(t.Rows, []string{ + x.Namespace, x.Kind, x.Name, render.Dash(x.Verdict), + render.Dash(truncate(strings.Join(drivers, ", "), 40)), render.Dash(truncate(x.Reason, 80)), + }) + t.WideRows = append(t.WideRows, []string{render.Dash(strings.Join(x.Via, ",")), render.Dash(x.ClusterName)}) + } + return t +} + +// verdictRank orders impact verdicts so the ones needing action come first. UNKNOWN ranks +// above READY: not knowing whether an app survives is not a pass. +func verdictRank(v string) int { + switch strings.ToUpper(v) { + case "BUMP_DRIVER": + return 3 + case "UNKNOWN": + return 2 + case "REVIEW": + return 1 + } + return 0 +} diff --git a/internal/view/reliability.go b/internal/view/reliability.go index 8c6b1d9..1fde520 100644 --- a/internal/view/reliability.go +++ b/internal/view/reliability.go @@ -183,3 +183,57 @@ func pct(v float64) string { } func ageOf(t time.Time) string { return k8s.Duration(time.Since(t)) } + +// AppImpactTable lists upgrade findings by the application (namespace) they land on: what an +// app team must change first, then what is only affected. +func AppImpactTable(r *api.UpgradeReadiness) *render.Table { + t := &render.Table{ + Headers: []string{"NAMESPACE", "CHANGE", "SEVERITY", "AT", "TITLE", "OBJECTS"}, + WideHeaders: []string{"ADD-ON", "VERIFY"}, + EmptyMessage: "No application is affected.", + } + if r.AppImpact == nil { + return t + } + add := func(ns, change string, it api.AppImpactItem) { + objs := "" + if len(it.Objects) > 0 { + objs = it.Objects[0] + if len(it.Objects) > 1 { + objs += " +" + strconv.Itoa(len(it.Objects)-1) + } + } + t.Rows = append(t.Rows, []string{ns, change, render.Dash(it.Severity), render.Dash(it.AppliesAtVersion), + render.Dash(it.Title), render.Dash(objs)}) + t.WideRows = append(t.WideRows, []string{render.Dash(it.Addon), render.Dash(it.VerifyCommand)}) + } + for _, a := range r.AppImpact.Applications { + for _, it := range a.MustChange { + add(a.Namespace, "must change", it) + } + for _, it := range a.Affected { + add(a.Namespace, "affected", it) + } + } + return t +} + +// AddonHopsTable lists add-ons that must move with the Kubernetes upgrade. +func AddonHopsTable(r *api.UpgradeReadiness) *render.Table { + t := &render.Table{ + Headers: []string{"ADD-ON", "INSTALLED", "REQUIRED", "ORDER", "WHY"}, + EmptyMessage: "No add-on has to move.", + } + for _, h := range r.AddonHops { + order := "before Kubernetes" + if h.KubernetesFirst { + order = "after Kubernetes" + if h.ThenVersion != "" { + order += ", then " + h.ThenVersion + } + } + t.Rows = append(t.Rows, []string{h.AddonID, render.Dash(h.InstalledVersion), render.Dash(h.RequiredVersion), + order, render.Dash(h.Reason)}) + } + return t +} diff --git a/internal/view/units.go b/internal/view/units.go new file mode 100644 index 0000000..e3151df --- /dev/null +++ b/internal/view/units.go @@ -0,0 +1,168 @@ +package view + +import ( + "fmt" + "sort" + "strconv" + "strings" + "time" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/k8s" +) + +// unknown is what a cell says when the backend did not know the value. It is deliberately +// different from "0": an unread figure rendered as zero reads as "nothing there". +const unknown = "?" + +// CPU renders millicores the way kubectl top does: whole cores above 10, else millicores. +func CPU(m *int64) string { + if m == nil { + return unknown + } + v := *m + if v < 0 { + return "-" + CPU(ptr(-v)) + } + if v >= 10000 { + return strconv.FormatFloat(float64(v)/1000, 'f', 1, 64) + } + return strconv.FormatInt(v, 10) + "m" +} + +// Bytes renders a byte count in binary units. +func Bytes(b *int64) string { + if b == nil { + return unknown + } + v := *b + if v < 0 { + return "-" + Bytes(ptr(-v)) + } + const unit = 1024 + if v < unit { + return strconv.FormatInt(v, 10) + "B" + } + div, exp := int64(unit), 0 + for n := v / unit; n >= unit && exp < 4; n /= unit { + div *= unit + exp++ + } + return strconv.FormatFloat(float64(v)/float64(div), 'f', 1, 64) + []string{"Ki", "Mi", "Gi", "Ti", "Pi"}[exp] +} + +// Pct renders a percentage the backend already computed (0-100). +func Pct(p *float64) string { + if p == nil { + return unknown + } + return strconv.FormatFloat(*p, 'f', 0, 64) + "%" +} + +// Money renders a dollar figure; nil means unpriced, which is not $0. +func Money(v *float64) string { + if v == nil { + return "unpriced" + } + return "$" + strconv.FormatFloat(*v, 'f', 2, 64) +} + +// Int renders an optional count. +func Int(v *int) string { + if v == nil { + return unknown + } + return strconv.Itoa(*v) +} + +// Int64 renders an optional count. +func Int64(v *int64) string { + if v == nil { + return unknown + } + return strconv.FormatInt(*v, 10) +} + +// Days renders a days-left figure; negative means already past. +func Days(v *int) string { + if v == nil { + return unknown + } + if *v < 0 { + return fmt.Sprintf("%dd ago", -*v) + } + return strconv.Itoa(*v) + "d" +} + +// Since renders how long ago a timestamp was. +func Since(t *time.Time) string { + if t == nil || t.IsZero() { + return unknown + } + return k8s.Duration(time.Since(*t)) +} + +// Seconds renders an elapsed second count. +func Seconds(s *int64) string { + if s == nil { + return unknown + } + return k8s.Duration(time.Duration(*s) * time.Second) +} + +// Bool renders an optional flag. +func Bool(b *bool) string { + if b == nil { + return unknown + } + if *b { + return "yes" + } + return "no" +} + +// WorstReason is the most severe finding on a row, or nil when there is none. +func WorstReason(rs []api.AddonReason) *api.AddonReason { + var worst *api.AddonReason + worstRank := -1 + for i := range rs { + r, _ := api.SeverityRank(rs[i].Severity) + if r > worstRank { + worst, worstRank = &rs[i], r + } + } + return worst +} + +// Counts renders a map of counts as "a=1 b=2", keys sorted, so output is stable. +func Counts(m map[string]int) string { + if len(m) == 0 { + return "" + } + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + parts := make([]string, 0, len(keys)) + for _, k := range keys { + parts = append(parts, fmt.Sprintf("%s=%d", k, m[k])) + } + return strings.Join(parts, " ") +} + +func ptr[T any](v T) *T { return &v } + +func resCPU(r *api.Res) *int64 { + if r == nil { + return nil + } + return r.CPUMillicores +} + +func resMem(r *api.Res) *int64 { + if r == nil { + return nil + } + return r.MemoryBytes +} diff --git a/internal/view/units_test.go b/internal/view/units_test.go new file mode 100644 index 0000000..444359f --- /dev/null +++ b/internal/view/units_test.go @@ -0,0 +1,16 @@ +package view + +import "testing" + +func TestUnits(t *testing.T) { + i := func(v int64) *int64 { return &v } + for _, c := range []struct{ got, want string }{ + {CPU(i(250)), "250m"}, {CPU(i(9999)), "9999m"}, {CPU(i(16000)), "16.0"}, {CPU(nil), "?"}, {CPU(i(-500)), "-500m"}, + {Bytes(i(512)), "512B"}, {Bytes(i(1536)), "1.5Ki"}, {Bytes(i(34359738368)), "32.0Gi"}, {Bytes(nil), "?"}, + {Days(ptr(0)), "0d"}, {Days(ptr(-3)), "3d ago"}, {Money(nil), "unpriced"}, + } { + if c.got != c.want { + t.Errorf("got %q, want %q", c.got, c.want) + } + } +} From af694abb1a4df1df8d39b39dd138585a341da220 Mon Sep 17 00:00:00 2001 From: pvishwa3 Date: Sat, 17 Oct 2026 20:17:43 -0400 Subject: [PATCH 4/7] feat(tui): capacity, maintain, upgrade and add-on workspace views MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New command-bar views over the same view-package tables as the flag commands: :capacity (:cap), :pending, :storage (:pvc), :maintain (:eol), :upgrade, :nodepools/:karpenter, :ca, :routes/:traefik, :mesh/:istio, :gitops/:argocd, :vpccni/:cni, :ebscsi/:ebs. `:ing` stays the Kubernetes Ingress listing. - enter/d on a row of these screens opens its detail — an add-on object's findings with fix and verify command, a pending pod's scheduler message, a Maintain item, an upgrade item's objects — from dataset.rowText, built from the list response (no extra request) and indexed through the filter/sort. - A non-OK workspace status (not detected, never synced, rules off) is the on-screen notice and the empty state, never a bare empty table. - :upgrade is no longer a planned-view stub; :shield takes its place. - view.SortMaintainItems / SortBlocked / sortReasons: one order shared by the table and its row text; api.BlockedPod named. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0178ctkmt3CJYuTzySDeSgSe --- README.md | 4 +- internal/api/capacity.go | 29 +-- internal/tui/app.go | 22 +- internal/tui/app_test.go | 5 +- internal/tui/render.go | 21 +- internal/tui/views.go | 40 +++- internal/tui/workspaces.go | 382 ++++++++++++++++++++++++++++++++ internal/tui/workspaces_test.go | 277 +++++++++++++++++++++++ internal/view/addons.go | 7 +- internal/view/capacity.go | 10 +- internal/view/detailtext.go | 146 ++++++++++++ internal/view/maintain.go | 11 +- 12 files changed, 925 insertions(+), 29 deletions(-) create mode 100644 internal/tui/workspaces.go create mode 100644 internal/tui/workspaces_test.go create mode 100644 internal/view/detailtext.go diff --git a/README.md b/README.md index 6c9ea4a..20dbede 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,10 @@ Run `rtz` with no arguments for the full-screen UI. | Key | Action | |---|---| | `:` | command bar — `:pods`, `:deploy`, `:sts`, `:ds`, `:svc`, `:ing`, `:nodes`, `:all`, `:risk`, `:signals`, `:changes`, `:logs`, `:traces`, `:ns `, `:q` | +| `:` | capacity and lifecycle — `:capacity`, `:pending`, `:storage`, `:maintain`, `:upgrade` | +| `:` | add-on workspaces — `:karpenter`, `:ca`, `:traefik`, `:istio`, `:argocd`, `:cni`, `:ebs` | | `/` | filter the visible rows as you type | -| `enter` / `d` | describe the selected workload | +| `enter` / `d` | describe the selected workload; on capacity, Maintain, upgrade and add-on screens, open the row's findings with their verify commands | | `p` | pause or resume auto-refresh | | `ctrl+r` | refresh now | | `?` | keys and commands | diff --git a/internal/api/capacity.go b/internal/api/capacity.go index eec9245..a1725bb 100644 --- a/internal/api/capacity.go +++ b/internal/api/capacity.go @@ -68,19 +68,7 @@ type Capacity struct { Headroom *Res `json:"headroom"` Pods int `json:"pods"` } `json:"nodes"` - Blocked []struct { - Namespace string `json:"namespace"` - Name string `json:"name"` - OwnerKind string `json:"ownerKind"` - OwnerName string `json:"ownerName"` - PendingSeconds *int64 `json:"pendingSeconds"` - State string `json:"state"` - PrimaryCategory string `json:"primaryCategory"` - CapacityShortfall bool `json:"capacityShortfall"` - Message string `json:"message"` - NominatedNode string `json:"nominatedNode"` - VerifyCommand string `json:"verifyCommand"` - } `json:"blocked"` + Blocked []BlockedPod `json:"blocked"` BlockedSummary *struct { Total int `json:"total"` Listed int `json:"listed"` @@ -407,3 +395,18 @@ type FleetCapacity struct { func (c *Client) FleetCapacity(ctx context.Context, orgID string) (*Payload[FleetCapacity], error) { return GetPayload[FleetCapacity](ctx, c, fmt.Sprintf("/eac/api/1.0/orgs/%s/capacity/fleet", orgID), nil) } + +// BlockedPod is a pod the scheduler could not place. +type BlockedPod struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + OwnerKind string `json:"ownerKind"` + OwnerName string `json:"ownerName"` + PendingSeconds *int64 `json:"pendingSeconds"` + State string `json:"state"` + PrimaryCategory string `json:"primaryCategory"` + CapacityShortfall bool `json:"capacityShortfall"` + Message string `json:"message"` + NominatedNode string `json:"nominatedNode"` + VerifyCommand string `json:"verifyCommand"` +} diff --git a/internal/tui/app.go b/internal/tui/app.go index d7e945c..79437eb 100644 --- a/internal/tui/app.go +++ b/internal/tui/app.go @@ -79,6 +79,9 @@ type Model struct { detail *api.WorkloadDetail detailRef string + // rowPane is the open detail of a non-resource row (dataset.rowText), drawn in the same + // pane as a describe. + rowPane string ask askState @@ -260,7 +263,7 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case modeDetail: switch msg.String() { case "esc", "q", "enter": - m.mode, m.detail = modeNormal, nil + m.mode, m.detail, m.rowPane = modeNormal, nil, "" } return m, nil } @@ -371,6 +374,10 @@ func (m Model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case "enter", "d": r, ok := m.selected() if !ok { + if text, ok := m.selectedRowText(); ok { + m.rowPane, m.mode = text, modeDetail + return m, nil + } if m.data.table != nil && len(m.data.resources) == 0 { m.status = "this view has no per-row detail — press : to switch to a resource view" } @@ -618,6 +625,19 @@ func (m Model) selected() (k8s.Resource, bool) { return m.data.resources[idx], true } +// selectedRowText is the pre-rendered detail of the row under the cursor, on screens whose +// rows carry one. The visible index points into the table's rows, which rowText mirrors. +func (m Model) selectedRowText() (string, bool) { + if m.cursor < 0 || m.cursor >= len(m.visible) { + return "", false + } + idx := m.visible[m.cursor] + if idx < 0 || idx >= len(m.data.rowText) { + return "", false + } + return m.data.rowText[idx], true +} + // bodyHeight is the row budget: the window minus everything the chrome occupies. It is // derived from the same pieces View draws, so the two cannot disagree about how many rows // fit — a disagreement shows up as a clipped last row or a scroll that stops early. diff --git a/internal/tui/app_test.go b/internal/tui/app_test.go index 0e52ae6..f75f72d 100644 --- a/internal/tui/app_test.go +++ b/internal/tui/app_test.go @@ -32,6 +32,9 @@ type fakeClient struct { logs *api.LogPage traces *api.TracePage rca *api.WorkloadRCA + // workspaces holds canned capacity / maintain / upgrade / add-on responses, keyed by the + // Client method name (see workspaces_test.go). + workspaces map[string]any // what the last call was scoped to — the point of the drill-down keys lastLogService string @@ -355,7 +358,7 @@ func TestCommandNamespaceScopesAndClears(t *testing.T) { func TestPlannedCommandSaysItIsNotBuilt(t *testing.T) { m := newModel(t, &fakeClient{rows: pods()}) m = key(m, ":") - m = typeIn(m, "upgrade") + m = typeIn(m, "shield") m = key(m, "enter") if !strings.Contains(m.status, "not a view here") { diff --git a/internal/tui/render.go b/internal/tui/render.go index 797f622..7de6f6a 100644 --- a/internal/tui/render.go +++ b/internal/tui/render.go @@ -31,6 +31,9 @@ func (m Model) View() string { if m.mode == modeAsk { return m.askView() } + if m.mode == modeDetail && m.rowPane != "" { + return m.rowPaneView() + } if m.mode == modeDetail && m.detail != nil { return m.detailView() } @@ -381,12 +384,22 @@ func (m Model) detailView() string { footerStyle.Render(" "+keyStyle.Render("esc")+" back "+keyStyle.Render("q")+" back") } +func (m Model) rowPaneView() string { + body := strings.TrimRight(m.rowPane, "\n") + if m.height > 6 { + body = clipLines(body, m.height-6) + } + return m.tabStrip() + "\n" + + panel(strings.ToLower(m.view.Title), body, m.screenWidth()) + "\n" + + footerStyle.Render(" "+keyStyle.Render("esc")+" back "+keyStyle.Render("q")+" back") +} + func (m Model) helpView() string { keys := [][2]string{ {"↑ ↓ / j k", "move"}, {"pgup pgdn", "page"}, {"g / G", "top / bottom"}, - {"enter, d", "describe the selected workload"}, + {"enter, d", "describe the selected workload, or open the row's findings"}, {"/", "filter the visible rows"}, {":", "command bar"}, {"s / i", "sort by the next column / invert the order"}, @@ -415,10 +428,14 @@ func (m Model) helpView() string { {":triage", "what is failing right now"}, {":risk, :rca, :signals, :changes", "reliability views"}, {":logs, :traces", "observability views"}, + {":capacity, :pending, :storage", "capacity: pools, pending pods, PVCs"}, + {":maintain, :upgrade", "support deadlines, upgrade impact per app"}, + {":karpenter, :ca, :traefik", "add-on workspaces"}, + {":istio, :argocd, :cni, :ebs", "add-on workspaces"}, {":ns ", "scope to a namespace (bare :ns clears it)"}, {":q", "quit"}, } { - b.WriteString(keyStyle.Render(lipgloss.NewStyle().Width(26).Render(c[0])) + c[1] + "\n") + b.WriteString(keyStyle.Render(lipgloss.NewStyle().Width(32).Render(c[0])) + c[1] + "\n") } b.WriteString("\n" + metaStyle.Render( "Every view here has a flag equivalent — :deploy is `rtz get deploy`, d is `rtz describe`.")) diff --git a/internal/tui/views.go b/internal/tui/views.go index 9cff711..e7a5999 100644 --- a/internal/tui/views.go +++ b/internal/tui/views.go @@ -28,6 +28,18 @@ type Client interface { Ask(ctx context.Context, orgID, clusterID string, q api.AgentQuery) (*api.AgentAnswer, error) StreamInvestigation(ctx context.Context, orgID, clusterID, streamID string, fn func(api.StreamFrame) error) error CancelInvestigation(ctx context.Context, orgID, clusterID, streamID string) error + + // Capacity, Maintain, upgrade readiness and the add-on workspaces. + Capacity(ctx context.Context, orgID, clusterID string) (*api.Payload[api.Capacity], error) + MaintainItems(ctx context.Context, orgID string) (*api.Payload[api.MaintainList], error) + UpgradeReadiness(ctx context.Context, orgID, clusterID, targetVersion string) (*api.Payload[api.UpgradeReadiness], error) + NodePools(ctx context.Context, orgID, clusterID string) (*api.Payload[api.NodePools], error) + NodeGroups(ctx context.Context, orgID, clusterID string) (*api.Payload[api.NodeGroups], error) + IngressRoutes(ctx context.Context, orgID, clusterID string) (*api.Payload[api.IngressRoutes], error) + MeshWorkloads(ctx context.Context, orgID, clusterID string) (*api.Payload[api.MeshWorkloads], error) + GitOpsApps(ctx context.Context, orgID, clusterID string) (*api.Payload[api.GitOpsApps], error) + VpcCni(ctx context.Context, orgID, clusterID string) (*api.Payload[api.VpcCni], error) + EbsCsi(ctx context.Context, orgID, clusterID string) (*api.Payload[api.EbsCsi], error) } // scope is the object the screen is currently about. @@ -82,6 +94,10 @@ type dataset struct { notice string // body replaces the table for screens that are prose rather than rows. body string + // rowText is one pre-rendered detail per table row (same index), for screens whose rows + // are not Kubernetes resources but still have something to open — an add-on object's + // findings, a Maintain item, a pending pod. Built from the list response: no request. + rowText []string } // viewDef is one navigable screen. @@ -357,12 +373,34 @@ var views = map[string]viewDef{ "traces": tracesView, "rca": rcaView, "triage": triageView, + + "capacity": capacityView, + "cap": capacityView, + "pending": pendingView, + "storage": storageView, + "pvc": storageView, + "maintain": maintainView, + "eol": maintainView, + "upgrade": upgradeView, + "nodepools": nodePoolsView, + "karpenter": nodePoolsView, + "ca": nodeGroupsView, + "routes": routesView, + "traefik": routesView, + "mesh": meshView, + "istio": meshView, + "gitops": gitopsView, + "argocd": gitopsView, + "vpccni": vpcCniView, + "cni": vpcCniView, + "ebscsi": ebsCsiView, + "ebs": ebsCsiView, } // plannedViews name screens that exist in the roadmap but not yet in the binary, so the // command bar can say "not yet" instead of silently doing nothing. var plannedViews = map[string]string{ - "upgrade": "the `rtz upgrade check` command", + "shield": "the Attack Paths page in the web app", } func joinWords(items []string) string { diff --git a/internal/tui/workspaces.go b/internal/tui/workspaces.go new file mode 100644 index 0000000..1946f53 --- /dev/null +++ b/internal/tui/workspaces.go @@ -0,0 +1,382 @@ +package tui + +import ( + "context" + "fmt" + "strings" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/render" + "github.com/runtimez-com/runtimez-cli/internal/view" +) + +// Capacity, Maintain, upgrade readiness and the add-on workspaces. Every one of them uses the +// same view package tables as its flag command, and every one turns a status the backend could +// not read into the on-screen notice — an add-on that is not installed must never look like a +// healthy add-on with nothing to report. + +// notReadable is the dataset for a non-OK status: the reason as the notice, and an empty +// state that repeats it instead of "No rows". +func notReadable(what, status, message string) dataset { + msg := what + ": " + status + if message = strings.TrimSpace(message); message != "" { + msg += " — " + message + } + return dataset{table: &render.Table{EmptyMessage: msg}, notice: msg} +} + +func statusOK(s string) bool { return s == "" || strings.EqualFold(s, "OK") } + +func joinNotices(parts ...string) string { + var out []string + for _, p := range parts { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) + } + } + return strings.Join(out, " · ") +} + +var capacityView = viewDef{ + Title: "Capacity", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.Capacity(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + c := &p.Typed + if !statusOK(c.Status) && len(c.Pools) == 0 { + return notReadable("capacity", c.Status, c.Message), nil + } + var notes []string + for _, a := range c.Headroom { + if a.Axis == "pods" { + continue + } + notes = append(notes, a.Axis+" requests "+view.Pct(a.RequestsCommitmentPct)) + } + if b := c.BlockedSummary; b != nil && b.Total > 0 { + notes = append(notes, fmt.Sprintf("%d pending (%d short of capacity) — :pending", b.Total, b.CapacityShortfall)) + } + if u := c.Usage; u != nil && u.NodesWithoutSamples > 0 { + notes = append(notes, fmt.Sprintf("%d node(s) without usage samples", u.NodesWithoutSamples)) + } + if f := c.Flags; f != nil && (f.NodeRowsTruncated || f.PodRowsTruncated) { + notes = append(notes, "rows truncated — figures are a lower bound") + } + return dataset{table: view.PoolsTable(c.Pools), notice: joinNotices(notes...)}, nil + }, +} + +var pendingView = viewDef{ + Title: "Pending pods", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.Capacity(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + c := &p.Typed + if !statusOK(c.Status) && len(c.Blocked) == 0 { + return notReadable("capacity", c.Status, c.Message), nil + } + d := dataset{table: view.BlockedTable(c)} + for _, b := range view.SortBlocked(c) { + d.rowText = append(d.rowText, view.BlockedText(b)) + } + if b := c.BlockedSummary; b != nil { + if b.Listed < b.Total { + d.notice = fmt.Sprintf("%d of %d pending pods listed", b.Listed, b.Total) + } + if !b.EventsRead { + d.notice = joinNotices(d.notice, "scheduler events not read — reasons may be missing") + } + } + return d, nil + }, +} + +var storageView = viewDef{ + Title: "Storage", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.Capacity(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + c := &p.Typed + s := c.Storage + if s == nil { + return notReadable("storage", "NOT_REPORTED", "this cluster's capacity has no storage section"), nil + } + if !statusOK(s.Status) && len(s.PVCs) == 0 { + return notReadable("storage", s.Status, s.Reason), nil + } + d := dataset{table: view.StorageTable(c)} + if !statusOK(s.Metrics) { + d.notice = "volume metrics " + s.Metrics + " — " + s.MetricsReason + } + if s.PVCsNotListed > 0 { + d.notice = joinNotices(d.notice, fmt.Sprintf("%d more claims not listed", s.PVCsNotListed)) + } + return d, nil + }, +} + +// maintainView is org-wide, like the flag command, and hides platform items the same way: +// Kubernetes and add-on deadlines belong to :upgrade. +var maintainView = viewDef{ + Title: "Maintain", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.MaintainItems(ctx, r.OrgID) + if err != nil { + return dataset{}, err + } + var items []api.MaintainItem + hidden := 0 + for _, it := range p.Typed.Items { + if it.Platform { + hidden++ + continue + } + items = append(items, it) + } + d := dataset{table: view.MaintainItemsTable(items)} + for _, it := range view.SortMaintainItems(items) { + d.rowText = append(d.rowText, view.MaintainItemText(it)) + } + var notes []string + if p.Typed.ReadFailed { + notes = append(notes, "the backend could not read every item — this list is incomplete") + } + if p.Typed.Truncated { + notes = append(notes, "list truncated") + } + if hidden > 0 { + notes = append(notes, fmt.Sprintf("%d platform item(s) hidden — see :upgrade", hidden)) + } + d.notice = joinNotices(notes...) + return d, nil + }, +} + +var upgradeView = viewDef{ + Title: "Upgrade impact", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.UpgradeReadiness(ctx, r.OrgID, r.ClusterID, "") + if err != nil { + return dataset{}, err + } + u := &p.Typed + var notes []string + notes = append(notes, fmt.Sprintf("%s → %s, score %d/100 %s", render.Dash(u.CurrentVersion), + render.Dash(u.TargetVersion), u.Score, render.Dash(u.RiskLevel))) + if n := len(u.AddonHops); n > 0 { + notes = append(notes, fmt.Sprintf("%d add-on(s) must move", n)) + } + if u.Stale { + notes = append(notes, "built on STALE inventory") + } + if s := strings.ToUpper(u.ScanStatus); s == "PARTIAL" || s == "INSUFFICIENT_DATA" || s == "STALE" { + notes = append(notes, "scan "+u.ScanStatus+" — blockers may be missing") + } + if u.AppImpact == nil { + // An older backend: fall back to the findings list rather than an empty screen. + notes = append(notes, "no per-application view from this backend — showing findings") + return dataset{table: view.FindingsTable(u.Findings), notice: joinNotices(notes...)}, nil + } + if n := u.AppImpact.PlatformFindings; n > 0 { + notes = append(notes, fmt.Sprintf("%d platform-only finding(s) — `rtz upgrade check`", n)) + } + return dataset{table: view.AppImpactTable(u), rowText: view.AppImpactTexts(u), notice: joinNotices(notes...)}, nil + }, +} + +// workspaceNotice is the line every add-on view carries: the add-on and version it read, +// and whether its rules ran. +func workspaceNotice(h api.WorkspaceHead, extra ...string) string { + var parts []string + if a := h.Addon; a != nil { + parts = append(parts, strings.TrimSpace(a.DisplayName+" "+a.Version)) + if !a.RulesEvaluated { + parts = append(parts, "rules NOT evaluated — an empty findings column is not \"no findings\"") + } + } + return joinNotices(append(parts, extra...)...) +} + +var nodePoolsView = viewDef{ + Title: "Karpenter NodePools", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.NodePools(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + l := &p.Typed + if !l.OK() { + return notReadable("Karpenter", l.Status, l.Message), nil + } + d := dataset{table: view.NodePoolsTable(l.NodePools)} + for _, np := range l.NodePools { + d.rowText = append(d.rowText, view.ReasonsText("NodePool "+np.Name, np.State, np.StateDetail, np.Reasons)) + } + managed := "" + if h := l.Header; h != nil && h.ManagedBy != "" { + managed = "managed by " + h.ManagedBy + } + d.notice = workspaceNotice(l.WorkspaceHead, managed) + return d, nil + }, +} + +var nodeGroupsView = viewDef{ + Title: "Cluster Autoscaler", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.NodeGroups(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + l := &p.Typed + if !l.OK() { + return notReadable("Cluster Autoscaler", l.Status, l.Message), nil + } + d := dataset{table: view.NodeGroupsTable(l.NodeGroups)} + for _, g := range l.NodeGroups { + d.rowText = append(d.rowText, view.ReasonsText("Node group "+g.Name, g.State, g.Detail, g.Reasons)) + } + var extra []string + if h := l.Header; h != nil { + extra = append(extra, "status "+render.Dash(h.AutoscalerStatus)) + if h.StatusStale { + extra = append(extra, "status ConfigMap is STALE — CA may not be running") + } + if n := len(h.Reasons); n > 0 { + extra = append(extra, fmt.Sprintf("%d cluster-wide finding(s) — `rtz addons ca`", n)) + } + } + d.notice = workspaceNotice(l.WorkspaceHead, extra...) + return d, nil + }, +} + +var routesView = viewDef{ + Title: "Ingress routes", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.IngressRoutes(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + l := &p.Typed + if !l.OK() { + return notReadable("ingress", l.Status, l.Message), nil + } + d := dataset{table: view.IngressRoutesTable(l.Routes), notice: workspaceNotice(l.WorkspaceHead)} + for _, rt := range l.Routes { + d.rowText = append(d.rowText, view.ReasonsText(rt.Kind+" "+rt.Namespace+"/"+rt.Name, rt.State, rt.StateWhy, rt.Reasons)) + } + return d, nil + }, +} + +var meshView = viewDef{ + Title: "Mesh workloads", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.MeshWorkloads(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + l := &p.Typed + if !l.OK() { + return notReadable("mesh", l.Status, l.Message), nil + } + d := dataset{table: view.MeshWorkloadsTable(l.Workloads), notice: workspaceNotice(l.WorkspaceHead)} + for _, w := range l.Workloads { + d.rowText = append(d.rowText, view.ReasonsText(w.Kind+" "+w.Namespace+"/"+w.Name, w.State, w.StateWhy, w.Reasons)) + } + return d, nil + }, +} + +var gitopsView = viewDef{ + Title: "Argo CD Applications", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.GitOpsApps(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + l := &p.Typed + if !l.OK() { + return notReadable("Argo CD", l.Status, l.Message), nil + } + d := dataset{table: view.GitOpsAppsTable(l.Applications), notice: workspaceNotice(l.WorkspaceHead)} + for _, a := range l.Applications { + why := "sync " + render.Dash(a.Sync) + ", health " + render.Dash(a.Health) + d.rowText = append(d.rowText, view.ReasonsText("Application "+a.Namespace+"/"+a.Name, a.State, why, a.Reasons)) + } + return d, nil + }, +} + +var vpcCniView = viewDef{ + Title: "Amazon VPC CNI", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.VpcCni(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + l := &p.Typed + if !l.OK() { + return notReadable("VPC CNI", l.Status, l.Message), nil + } + d := dataset{table: view.VpcCniNodesTable(l.Nodes)} + for _, n := range l.Nodes { + d.rowText = append(d.rowText, view.ReasonsText("Node "+n.Name, n.State, n.StateDetail, n.Reasons)) + } + var extra []string + if h := l.Header; h != nil { + extra = append(extra, "network policy "+render.Dash(h.NetworkPolicyEnforcement)) + if n := len(h.Reasons); n > 0 { + extra = append(extra, fmt.Sprintf("%d cluster-wide finding(s) — `rtz addons vpc-cni`", n)) + } + } + d.notice = workspaceNotice(l.WorkspaceHead, extra...) + return d, nil + }, +} + +var ebsCsiView = viewDef{ + Title: "Amazon EBS CSI", + fetch: func(ctx context.Context, r fetchReq) (dataset, error) { + p, err := r.Client.EbsCsi(ctx, r.OrgID, r.ClusterID) + if err != nil { + return dataset{}, err + } + l := &p.Typed + if !l.OK() { + return notReadable("EBS CSI", l.Status, l.Message), nil + } + d := dataset{table: view.EbsCsiNodesTable(l.Nodes)} + for _, n := range l.Nodes { + d.rowText = append(d.rowText, view.ReasonsText("Node "+n.Name, n.State, "", n.Reasons)) + } + failing := 0 + for _, a := range l.Attachments { + if !a.Attached || a.Problem != "" { + failing++ + } + } + var extra []string + if failing > 0 { + extra = append(extra, fmt.Sprintf("%d failing attachment(s)", failing)) + } + if n := len(l.Workloads); n > 0 { + extra = append(extra, fmt.Sprintf("%d workload(s) stuck on EBS", n)) + } + if n := len(l.ClusterReasons); n > 0 { + extra = append(extra, fmt.Sprintf("%d cluster-wide finding(s)", n)) + } + if len(extra) > 0 { + extra = append(extra, "`rtz addons ebs-csi` for the full list") + } + d.notice = workspaceNotice(l.WorkspaceHead, extra...) + return d, nil + }, +} diff --git a/internal/tui/workspaces_test.go b/internal/tui/workspaces_test.go new file mode 100644 index 0000000..a9bdc2e --- /dev/null +++ b/internal/tui/workspaces_test.go @@ -0,0 +1,277 @@ +package tui + +import ( + "context" + "strings" + "testing" + + "github.com/runtimez-com/runtimez-cli/internal/api" +) + +func canned[T any](f *fakeClient, name string) (*api.Payload[T], error) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls++ + if f.err != nil { + return nil, f.err + } + p := &api.Payload[T]{} + if v, ok := f.workspaces[name].(*T); ok { + p.Typed = *v + } + return p, nil +} + +func (f *fakeClient) Capacity(_ context.Context, _, _ string) (*api.Payload[api.Capacity], error) { + return canned[api.Capacity](f, "Capacity") +} +func (f *fakeClient) MaintainItems(_ context.Context, _ string) (*api.Payload[api.MaintainList], error) { + return canned[api.MaintainList](f, "MaintainItems") +} +func (f *fakeClient) UpgradeReadiness(_ context.Context, _, _, _ string) (*api.Payload[api.UpgradeReadiness], error) { + return canned[api.UpgradeReadiness](f, "UpgradeReadiness") +} +func (f *fakeClient) NodePools(_ context.Context, _, _ string) (*api.Payload[api.NodePools], error) { + return canned[api.NodePools](f, "NodePools") +} +func (f *fakeClient) NodeGroups(_ context.Context, _, _ string) (*api.Payload[api.NodeGroups], error) { + return canned[api.NodeGroups](f, "NodeGroups") +} +func (f *fakeClient) IngressRoutes(_ context.Context, _, _ string) (*api.Payload[api.IngressRoutes], error) { + return canned[api.IngressRoutes](f, "IngressRoutes") +} +func (f *fakeClient) MeshWorkloads(_ context.Context, _, _ string) (*api.Payload[api.MeshWorkloads], error) { + return canned[api.MeshWorkloads](f, "MeshWorkloads") +} +func (f *fakeClient) GitOpsApps(_ context.Context, _, _ string) (*api.Payload[api.GitOpsApps], error) { + return canned[api.GitOpsApps](f, "GitOpsApps") +} +func (f *fakeClient) VpcCni(_ context.Context, _, _ string) (*api.Payload[api.VpcCni], error) { + return canned[api.VpcCni](f, "VpcCni") +} +func (f *fakeClient) EbsCsi(_ context.Context, _, _ string) (*api.Payload[api.EbsCsi], error) { + return canned[api.EbsCsi](f, "EbsCsi") +} + +func open(t *testing.T, c *fakeClient, view string) Model { + t.Helper() + m := newModel(t, c) + m = key(m, ":") + m = typeIn(m, view) + return submit(t, m) +} + +func i64p(v int64) *int64 { return &v } +func f64p(v float64) *float64 { return &v } +func intp(v int) *int { return &v } + +func karpenter(status string) *api.NodePools { + l := &api.NodePools{NodePools: []api.NodePoolRow{ + {Name: "default", State: "HEALTHY", Nodes: i64p(3)}, + {Name: "gpu", State: "DEGRADED", StateDetail: "at its cpu limit", Nodes: i64p(0), Reasons: []api.AddonReason{ + {RuleID: "karpenter-limit-reached", Severity: "HIGH", Title: "NodePool at its cpu limit", + VerifyCommand: "kubectl get nodepool gpu -o yaml", Recommendation: "raise spec.limits.cpu"}, + }}, + }} + l.Status = status + return l +} + +// Every new command-bar name resolves, so none of them falls through to "unknown command". +func TestWorkspaceViewsAreRegistered(t *testing.T) { + for _, name := range []string{"capacity", "cap", "pending", "storage", "pvc", "maintain", "eol", "upgrade", + "nodepools", "karpenter", "ca", "routes", "traefik", "mesh", "istio", "gitops", "argocd", + "vpccni", "cni", "ebscsi", "ebs"} { + if _, ok := views[name]; !ok { + t.Errorf(":%s is not a view", name) + } + } + if _, ok := views["ing"]; !ok || views["ing"].Kind != "Ingress" { + t.Error(":ing must stay the Kubernetes Ingress listing") + } +} + +func TestKarpenterViewListsAndOpensFindings(t *testing.T) { + c := &fakeClient{rows: pods(), workspaces: map[string]any{"NodePools": karpenter("OK")}} + m := open(t, c, "karpenter") + + out := m.View() + for _, want := range []string{"Karpenter NodePools", "default", "gpu", "DEGRADED", "HIGH NodePool at its cpu limit"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + + m = key(m, "down") + m = key(m, "enter") + if m.mode != modeDetail { + t.Fatalf("enter on an add-on row did not open its pane (status %q)", m.status) + } + pane := m.View() + for _, want := range []string{"NodePool gpu", "at its cpu limit", "karpenter-limit-reached", + "verify: kubectl get nodepool gpu -o yaml", "fix: raise spec.limits.cpu"} { + if !strings.Contains(pane, want) { + t.Errorf("missing %q in pane:\n%s", want, pane) + } + } + m = key(m, "esc") + if m.mode != modeNormal || m.rowPane != "" { + t.Errorf("esc did not close the pane") + } +} + +// The pane must open the row under the cursor even after a sort reorders the rows. +func TestRowPaneFollowsSort(t *testing.T) { + c := &fakeClient{rows: pods(), workspaces: map[string]any{"NodePools": karpenter("OK")}} + m := open(t, c, "karpenter") + m = key(m, "s") // NODEPOOL ascending: default, gpu + m = key(m, "i") // descending: gpu first + m = key(m, "enter") + if !strings.Contains(m.rowPane, "NodePool gpu") { + t.Errorf("pane opened the wrong row after a sort:\n%s", m.rowPane) + } +} + +// An add-on that is not installed reads as "not installed", never as an empty healthy list. +func TestWorkspaceNonOKStatusIsTheNotice(t *testing.T) { + mesh := &api.MeshWorkloads{} + mesh.Status, mesh.Message = "NOT_DETECTED", "no istiod Deployment found" + c := &fakeClient{rows: pods(), workspaces: map[string]any{"MeshWorkloads": mesh}} + m := open(t, c, "istio") + + out := m.View() + if !strings.Contains(out, "NOT_DETECTED") || !strings.Contains(out, "no istiod Deployment found") { + t.Errorf("non-OK status not on screen:\n%s", out) + } + if strings.Contains(out, "No workloads.") { + t.Errorf("an undetected add-on rendered as an empty list:\n%s", out) + } +} + +func TestWorkspaceRulesNotEvaluatedIsStated(t *testing.T) { + l := karpenter("OK") + l.Addon = &struct { + AddonID string `json:"addonId"` + DisplayName string `json:"displayName"` + Version string `json:"version"` + RuleCount int `json:"ruleCount"` + RulesEvaluated bool `json:"rulesEvaluated"` + }{DisplayName: "Karpenter", Version: "1.2.0"} + c := &fakeClient{rows: pods(), workspaces: map[string]any{"NodePools": l}} + m := open(t, c, "nodepools") + if out := m.View(); !strings.Contains(out, "rules NOT evaluated") || !strings.Contains(out, "Karpenter 1.2.0") { + t.Errorf("unevaluated rules not on screen:\n%s", out) + } +} + +func TestCapacityViewPoolsAndCaveats(t *testing.T) { + cap := &api.Capacity{Status: "OK", + Pools: []api.CapacityPool{{Name: "default", Nodes: 3, Pods: 41, AllocatablePods: i64p(110), + CPURequestsCommitmentPct: f64p(75)}}, + Blocked: []api.BlockedPod{ + {Namespace: "shop", Name: "short-wait", PendingSeconds: i64p(30)}, + {Namespace: "shop", Name: "long-wait", PendingSeconds: i64p(900), PrimaryCategory: "INSUFFICIENT_CPU", + Message: "0/3 nodes are available", VerifyCommand: "kubectl -n shop describe pod long-wait"}, + }, + } + cap.BlockedSummary = &struct { + Total int `json:"total"` + Listed int `json:"listed"` + CapacityShortfall int `json:"capacityShortfall"` + Gated int `json:"gated"` + Nominated int `json:"nominated"` + ByCategory map[string]int `json:"byCategory"` + EventsRead bool `json:"eventsRead"` + EventsTruncated bool `json:"eventsTruncated"` + }{Total: 2, Listed: 2, CapacityShortfall: 1, EventsRead: true} + cap.Usage = &struct { + Status string `json:"status"` + Reason string `json:"reason"` + NodesWithSamples int `json:"nodesWithSamples"` + NodesWithoutSamples int `json:"nodesWithoutSamples"` + }{Status: "OK", NodesWithSamples: 2, NodesWithoutSamples: 1} + c := &fakeClient{rows: pods(), workspaces: map[string]any{"Capacity": cap}} + + out := open(t, c, "capacity").View() + for _, want := range []string{"Capacity", "default", "41/110", "2 pending (1 short of capacity)", "1 node(s) without usage samples"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + + m := open(t, c, "pending") + m = key(m, "enter") // the first row is the longest-waiting pod + for _, want := range []string{"shop/long-wait", "INSUFFICIENT_CPU", "0/3 nodes are available", "verify: kubectl -n shop describe pod long-wait"} { + if !strings.Contains(m.rowPane, want) { + t.Errorf("missing %q in pane:\n%s", want, m.rowPane) + } + } +} + +func TestMaintainViewHidesPlatformAndOpensItem(t *testing.T) { + c := &fakeClient{rows: pods(), workspaces: map[string]any{"MaintainItems": &api.MaintainList{ + ReadFailed: true, + Items: []api.MaintainItem{ + {DisplayName: "Python 3.12", DaysLeft: intp(700)}, + {DisplayName: "Node.js 18", DaysLeft: intp(15), Location: "shop/Deployment/web", SourceURL: "https://endoflife.date/nodejs"}, + {DisplayName: "Kubernetes 1.31", DaysLeft: intp(5), Platform: true}, + }, + }}} + m := open(t, c, "maintain") + out := m.View() + if strings.Contains(out, "Kubernetes 1.31") || !strings.Contains(out, "1 platform item(s) hidden") { + t.Errorf("platform item shown, or its hiding not stated:\n%s", out) + } + if !strings.Contains(out, "this list is incomplete") { + t.Errorf("readFailed not on screen:\n%s", out) + } + m = key(m, "enter") // soonest first: Node.js + if !strings.Contains(m.rowPane, "Node.js 18") || !strings.Contains(m.rowPane, "endoflife.date") { + t.Errorf("pane is not the soonest item:\n%s", m.rowPane) + } +} + +func TestUpgradeViewIsPerApplication(t *testing.T) { + u := &api.UpgradeReadiness{CurrentVersion: "1.33", TargetVersion: "1.34", Score: 40, RiskLevel: "MEDIUM", Stale: true} + u.AppImpact = &struct { + Applications []struct { + Namespace string `json:"namespace"` + MustChange []api.AppImpactItem `json:"mustChange"` + Affected []api.AppImpactItem `json:"affected"` + } `json:"applications"` + PlatformFindings int `json:"platformFindings"` + UnattributedObjects int `json:"unattributedObjects"` + NamespacesRead bool `json:"namespacesRead"` + }{NamespacesRead: true} + u.AppImpact.Applications = append(u.AppImpact.Applications, struct { + Namespace string `json:"namespace"` + MustChange []api.AppImpactItem `json:"mustChange"` + Affected []api.AppImpactItem `json:"affected"` + }{Namespace: "shop", MustChange: []api.AppImpactItem{{Title: "Remove flowcontrol v1beta3", Severity: "HIGH", + Objects: []string{"FlowSchema/a"}, VerifyCommand: "kubectl get flowschemas"}}}) + c := &fakeClient{rows: pods(), workspaces: map[string]any{"UpgradeReadiness": u}} + + m := open(t, c, "upgrade") + out := m.View() + for _, want := range []string{"Upgrade impact", "1.33 → 1.34", "STALE", "shop", "must change", "Remove flowcontrol v1beta3"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + m = key(m, "enter") + if !strings.Contains(m.rowPane, "verify: kubectl get flowschemas") || !strings.Contains(m.rowPane, "FlowSchema/a") { + t.Errorf("pane missing the fix detail:\n%s", m.rowPane) + } +} + +// A resource view must still describe the workload, not a stale row pane. +func TestEnterOnAResourceRowStillDescribes(t *testing.T) { + c := &fakeClient{rows: pods(), workspaces: map[string]any{"NodePools": karpenter("OK")}} + m := open(t, c, "karpenter") + m = key(m, ":") + m = typeIn(m, "pods") + m = submit(t, m) + if len(m.data.rowText) != 0 { + t.Fatalf("rowText leaked into a resource view") + } +} diff --git a/internal/view/addons.go b/internal/view/addons.go index dc53869..74529f9 100644 --- a/internal/view/addons.go +++ b/internal/view/addons.go @@ -22,12 +22,7 @@ func findingCells(rs []api.AddonReason) (string, string) { // ReasonsTable lists one row's findings, worst first, with the command that verifies each. func ReasonsTable(rs []api.AddonReason) *render.Table { - rows := append([]api.AddonReason(nil), rs...) - sort.SliceStable(rows, func(i, j int) bool { - a, _ := api.SeverityRank(rows[i].Severity) - b, _ := api.SeverityRank(rows[j].Severity) - return a > b - }) + rows := sortReasons(rs) t := &render.Table{ Headers: []string{"SEVERITY", "RULE", "TITLE", "OBJECT", "VERIFY"}, WideHeaders: []string{"MESSAGE", "RECOMMENDATION"}, diff --git a/internal/view/capacity.go b/internal/view/capacity.go index c3a94c6..45ca147 100644 --- a/internal/view/capacity.go +++ b/internal/view/capacity.go @@ -97,8 +97,7 @@ func CapacityNodesTable(c *api.Capacity) *render.Table { // BlockedTable lists pods the scheduler could not place, longest-waiting first. func BlockedTable(c *api.Capacity) *render.Table { - rows := append(c.Blocked[:0:0], c.Blocked...) - sort.SliceStable(rows, func(i, j int) bool { return i64(rows[i].PendingSeconds) > i64(rows[j].PendingSeconds) }) + rows := SortBlocked(c) t := &render.Table{ Headers: []string{"NAMESPACE", "POD", "OWNER", "PENDING", "CATEGORY", "SHORTFALL", "WHY"}, WideHeaders: []string{"NOMINATED", "VERIFY"}, @@ -122,6 +121,13 @@ func BlockedTable(c *api.Capacity) *render.Table { return t } +// SortBlocked is the order BlockedTable draws in: longest-waiting first. +func SortBlocked(c *api.Capacity) []api.BlockedPod { + rows := append(c.Blocked[:0:0], c.Blocked...) + sort.SliceStable(rows, func(i, j int) bool { return i64(rows[i].PendingSeconds) > i64(rows[j].PendingSeconds) }) + return rows +} + // StorageTable lists PVCs, fullest first, then pending claims. func StorageTable(c *api.Capacity) *render.Table { t := &render.Table{ diff --git a/internal/view/detailtext.go b/internal/view/detailtext.go new file mode 100644 index 0000000..0646b01 --- /dev/null +++ b/internal/view/detailtext.go @@ -0,0 +1,146 @@ +package view + +import ( + "fmt" + "sort" + "strings" + + "github.com/runtimez-com/runtimez-cli/internal/api" + "github.com/runtimez-com/runtimez-cli/internal/render" +) + +// The functions here render one row's detail as prose, for the TUI's row pane. They read +// only what the list response already carries, so opening a row costs no request. + +// ReasonsText is a row's findings, worst first, each with the command that verifies it. +func ReasonsText(title, state, why string, rs []api.AddonReason) string { + var b strings.Builder + fmt.Fprintf(&b, "%s\n State: %s", title, render.Dash(state)) + if why = strings.TrimSpace(why); why != "" { + fmt.Fprintf(&b, " — %s", why) + } + b.WriteString("\n") + fmt.Fprintf(&b, "\nFindings (%d)\n", len(rs)) + if len(rs) == 0 { + b.WriteString(" No findings.\n") + return b.String() + } + for _, r := range sortReasons(rs) { + fmt.Fprintf(&b, "\n %s %s\n", render.Dash(r.Severity), render.Dash(r.Title)) + if r.RuleID != "" { + fmt.Fprintf(&b, " rule: %s\n", r.RuleID) + } + if obj := strings.TrimSpace(r.ObjectKind + " " + r.ObjectRef); obj != "" { + fmt.Fprintf(&b, " object: %s\n", obj) + } + if r.Message != "" { + fmt.Fprintf(&b, " %s\n", oneLine(r.Message)) + } + if r.Recommendation != "" { + fmt.Fprintf(&b, " fix: %s\n", oneLine(r.Recommendation)) + } + if r.VerifyCommand != "" { + fmt.Fprintf(&b, " verify: %s\n", r.VerifyCommand) + } + } + return b.String() +} + +// sortReasons is worst first; ReasonsTable draws in the same order. +func sortReasons(rs []api.AddonReason) []api.AddonReason { + rows := append([]api.AddonReason(nil), rs...) + sort.SliceStable(rows, func(i, j int) bool { + a, _ := api.SeverityRank(rows[i].Severity) + b, _ := api.SeverityRank(rows[j].Severity) + return a > b + }) + return rows +} + +// MaintainItemText is one Maintain item. +func MaintainItemText(it api.MaintainItem) string { + var b strings.Builder + fmt.Fprintf(&b, "%s %s\n", render.Dash(it.DisplayName), it.Version) + for _, kv := range [][2]string{ + {"cluster", it.ClusterName}, {"where", it.Location}, {"type", it.ItemType}, + {"deadline", strings.TrimSpace(it.Deadline + " " + it.DeadlineKind)}, {"days left", Days(it.DaysLeft)}, + {"support", it.SupportState}, {"confidence", it.Confidence}, {"owner", it.Owner}, + {"source", strings.TrimSpace(it.Source + " " + it.SourceURL)}, {"note", it.Note}, + } { + if strings.TrimSpace(kv[1]) != "" { + fmt.Fprintf(&b, " %-11s %s\n", kv[0]+":", kv[1]) + } + } + return b.String() +} + +// BlockedText is one pending pod and why the scheduler left it. +func BlockedText(p api.BlockedPod) string { + var b strings.Builder + fmt.Fprintf(&b, "%s/%s\n", p.Namespace, p.Name) + if p.OwnerKind != "" { + fmt.Fprintf(&b, " owner: %s/%s\n", p.OwnerKind, p.OwnerName) + } + fmt.Fprintf(&b, " pending: %s\n", Seconds(p.PendingSeconds)) + fmt.Fprintf(&b, " category: %s", render.Dash(p.PrimaryCategory)) + if p.CapacityShortfall { + b.WriteString(" (capacity shortfall)") + } + b.WriteString("\n") + if p.NominatedNode != "" { + fmt.Fprintf(&b, " nominated: %s\n", p.NominatedNode) + } + if p.Message != "" { + fmt.Fprintf(&b, "\n %s\n", oneLine(p.Message)) + } + if p.VerifyCommand != "" { + fmt.Fprintf(&b, "\n verify: %s\n", p.VerifyCommand) + } + return b.String() +} + +// AppImpactTexts is one detail per AppImpactTable row, in the same order. +func AppImpactTexts(r *api.UpgradeReadiness) []string { + if r.AppImpact == nil { + return nil + } + var out []string + add := func(ns, change string, it api.AppImpactItem) { + var b strings.Builder + fmt.Fprintf(&b, "%s — %s\n namespace: %s\n severity: %s\n", render.Dash(it.Title), change, ns, render.Dash(it.Severity)) + for _, kv := range [][2]string{ + {"applies at", it.AppliesAtVersion}, {"add-on", it.Addon}, {"component", it.Component}, {"rule", it.RuleID}, + } { + if kv[1] != "" { + fmt.Fprintf(&b, " %-10s %s\n", kv[0]+":", kv[1]) + } + } + if it.Impact != "" { + fmt.Fprintf(&b, "\n %s\n", oneLine(it.Impact)) + } + if it.Recommendation != "" { + fmt.Fprintf(&b, "\n fix: %s\n", oneLine(it.Recommendation)) + } + if it.VerifyCommand != "" { + fmt.Fprintf(&b, " verify: %s\n", it.VerifyCommand) + } + if len(it.Objects) > 0 { + fmt.Fprintf(&b, "\n objects (%d):\n", len(it.Objects)) + for _, o := range it.Objects { + fmt.Fprintf(&b, " %s\n", o) + } + } + out = append(out, b.String()) + } + for _, a := range r.AppImpact.Applications { + for _, it := range a.MustChange { + add(a.Namespace, "must change", it) + } + for _, it := range a.Affected { + add(a.Namespace, "affected", it) + } + } + return out +} + +func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") } diff --git a/internal/view/maintain.go b/internal/view/maintain.go index 24a3e80..2a29391 100644 --- a/internal/view/maintain.go +++ b/internal/view/maintain.go @@ -12,8 +12,7 @@ import ( // MaintainItemsTable lists lifecycle items, soonest deadline first. Items with no known // deadline sort last: an unknown deadline is not a far one, but it is not the next one either. func MaintainItemsTable(items []api.MaintainItem) *render.Table { - rows := append([]api.MaintainItem(nil), items...) - sort.SliceStable(rows, func(i, j int) bool { return daysKey(rows[i].DaysLeft) < daysKey(rows[j].DaysLeft) }) + rows := SortMaintainItems(items) t := &render.Table{ Headers: []string{"CLUSTER", "TYPE", "ITEM", "VERSION", "DEADLINE", "DAYS LEFT", "SUPPORT", "WHERE"}, WideHeaders: []string{"KIND", "CONFIDENCE", "OWNER", "PLATFORM", "SOURCE"}, @@ -35,6 +34,14 @@ func MaintainItemsTable(items []api.MaintainItem) *render.Table { return t } +// SortMaintainItems is the order MaintainItemsTable draws in, for callers that need a row's +// item back from its index. +func SortMaintainItems(items []api.MaintainItem) []api.MaintainItem { + rows := append([]api.MaintainItem(nil), items...) + sort.SliceStable(rows, func(i, j int) bool { return daysKey(rows[i].DaysLeft) < daysKey(rows[j].DaysLeft) }) + return rows +} + func daysKey(d *int) int { if d == nil { return 1 << 30 From 3840eaeaa919f57991a6d56d22f5470040fb4291 Mon Sep 17 00:00:00 2001 From: pvishwa3 Date: Sat, 17 Oct 2026 22:09:21 -0400 Subject: [PATCH 5/7] =?UTF-8?q?feat(tui):=20command=20menu=20=E2=80=94=20`?= =?UTF-8?q?:`=20lists=20every=20screen=20and=20narrows=20as=20you=20type?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An empty `:` prompt asked the operator to already know the vocabulary. The command bar now opens a grouped menu of every screen with its aliases and a one-line description, ranked as you type (exact, prefix, alias, description, then subsequence for typos); ↑↓ select, tab completes, enter opens the highlighted entry, and an argument (`ns `) runs as typed. An unknown command gets a "did you mean". The menu and the help screen render from one catalog, and a test keeps it in step with the view registry. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0178ctkmt3CJYuTzySDeSgSe --- README.md | 3 +- internal/tui/app.go | 46 +++++- internal/tui/palette.go | 277 +++++++++++++++++++++++++++++++++++ internal/tui/palette_test.go | 209 ++++++++++++++++++++++++++ internal/tui/render.go | 59 ++++---- 5 files changed, 566 insertions(+), 28 deletions(-) create mode 100644 internal/tui/palette.go create mode 100644 internal/tui/palette_test.go diff --git a/README.md b/README.md index 20dbede..aff06bb 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,10 @@ Run `rtz` with no arguments for the full-screen UI. | Key | Action | |---|---| -| `:` | command bar — `:pods`, `:deploy`, `:sts`, `:ds`, `:svc`, `:ing`, `:nodes`, `:all`, `:risk`, `:signals`, `:changes`, `:logs`, `:traces`, `:ns `, `:q` | +| `:` | browse every screen: the menu lists them grouped (resources, reliability, observability, capacity and lifecycle, add-ons) and narrows as you type — `↑↓` select, `tab` complete, `enter` open. A typo gets a "did you mean" | | `:` | capacity and lifecycle — `:capacity`, `:pending`, `:storage`, `:maintain`, `:upgrade` | | `:` | add-on workspaces — `:karpenter`, `:ca`, `:traefik`, `:istio`, `:argocd`, `:cni`, `:ebs` | +| `:` | resources and the rest — `:pods`, `:deploy`, `:sts`, `:ds`, `:svc`, `:ing`, `:nodes`, `:all`, `:risk`, `:signals`, `:changes`, `:logs`, `:traces`, `:ns `, `:q` | | `/` | filter the visible rows as you type | | `enter` / `d` | describe the selected workload; on capacity, Maintain, upgrade and add-on screens, open the row's findings with their verify commands | | `p` | pause or resume auto-refresh | diff --git a/internal/tui/app.go b/internal/tui/app.go index 79437eb..ff7c835 100644 --- a/internal/tui/app.go +++ b/internal/tui/app.go @@ -62,6 +62,8 @@ type Model struct { mode mode input textinput.Model filter string + // palSel is the highlighted row of the command menu while the command bar is open. + palSel int // sortCol is -1 while the server's own ordering stands; `s` walks it across the // columns and `i` flips the direction. @@ -287,13 +289,50 @@ func (m Model) handleInputKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { m.mode = modeNormal m.input.Blur() if wasCommand { + // The highlighted entry is what enter opens. Typed text runs as-is only when it + // carries an argument or nothing in the menu matches it. + if matches := m.paletteMatches(); len(matches) > 0 && !strings.Contains(value, " ") { + value = matches[min(m.palSel, len(matches)-1)].Name + } return m.runCommand(value) } return m, nil } + if m.mode == modeCommand { + n := len(m.paletteMatches()) + switch msg.Type { + case tea.KeyUp, tea.KeyCtrlP, tea.KeyShiftTab: + if m.palSel > 0 { + m.palSel-- + } + return m, nil + case tea.KeyDown, tea.KeyCtrlN: + if m.palSel < n-1 { + m.palSel++ + } + return m, nil + case tea.KeyTab: + if n > 0 && !strings.Contains(m.input.Value(), " ") { + c := m.paletteMatches()[min(m.palSel, n-1)] + fill := c.Name + if c.Arg != "" { + fill += " " + } + m.input.SetValue(fill) + m.input.CursorEnd() + m.palSel = 0 + } + return m, nil + } + } + + before := m.input.Value() var cmd tea.Cmd m.input, cmd = m.input.Update(msg) + if m.mode == modeCommand && m.input.Value() != before { + m.palSel = 0 + } if m.mode == modeFilter { // Filter as you type: waiting for enter to see the effect makes narrowing a guess. m.filter = m.input.Value() @@ -320,6 +359,7 @@ func (m Model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case ":": m.mode = modeCommand + m.palSel = 0 m.input.SetValue("") m.input.Focus() m.status = "" @@ -479,7 +519,11 @@ func (m Model) runCommand(raw string) (tea.Model, tea.Cmd) { m.status = fmt.Sprintf("%q is not a view here — see %s", name, milestone) return m, nil } - m.status = fmt.Sprintf("unknown command %q — press ? for the list", name) + if s := suggestCommand(name); s != "" { + m.status = fmt.Sprintf("unknown command %q — did you mean :%s?", name, s) + return m, nil + } + m.status = fmt.Sprintf("unknown command %q — press : to browse every screen", name) return m, nil } diff --git a/internal/tui/palette.go b/internal/tui/palette.go new file mode 100644 index 0000000..3e835eb --- /dev/null +++ b/internal/tui/palette.go @@ -0,0 +1,277 @@ +package tui + +import ( + "sort" + "strings" + + "github.com/charmbracelet/lipgloss" +) + +// The command bar is also the map of the UI. Typing `:` into an empty prompt asks the +// operator to already know the vocabulary; listing it, narrowing as they type, is what lets +// someone who has never read the help find the screen they need. + +// command is one entry in the command bar. Name is what the menu fills in; Aliases also +// resolve. Arg, when set, is the argument the command takes (""). +type command struct { + Group string + Name string + Aliases []string + Arg string + Desc string +} + +// catalog is every command the bar accepts, in the order the menu and the help screen list +// them. TestCatalogMatchesTheViewRegistry keeps it and the views map in step. +var catalog = []command{ + {Group: "Resources", Name: "pods", Aliases: []string{"po"}, Desc: "Pods"}, + {Group: "Resources", Name: "deploy", Aliases: []string{"deployments"}, Desc: "Deployments"}, + {Group: "Resources", Name: "sts", Aliases: []string{"statefulsets"}, Desc: "StatefulSets"}, + {Group: "Resources", Name: "ds", Aliases: []string{"daemonsets"}, Desc: "DaemonSets"}, + {Group: "Resources", Name: "svc", Aliases: []string{"services"}, Desc: "Services"}, + {Group: "Resources", Name: "ing", Aliases: []string{"ingresses"}, Desc: "Kubernetes Ingresses"}, + {Group: "Resources", Name: "nodes", Aliases: []string{"no"}, Desc: "Nodes"}, + {Group: "Resources", Name: "jobs", Desc: "Jobs"}, + {Group: "Resources", Name: "all", Desc: "Every kind in one list"}, + + {Group: "Reliability", Name: "triage", Desc: "What is failing right now"}, + {Group: "Reliability", Name: "risk", Desc: "Workload risk score and the rules behind it"}, + {Group: "Reliability", Name: "rca", Desc: "Root cause for the selected workload"}, + {Group: "Reliability", Name: "signals", Desc: "Slow operations"}, + {Group: "Reliability", Name: "changes", Desc: "What changed, newest first"}, + + {Group: "Observability", Name: "logs", Desc: "Log search, scoped to the selection"}, + {Group: "Observability", Name: "traces", Desc: "Traces, scoped to the selection"}, + + {Group: "Capacity & lifecycle", Name: "capacity", Aliases: []string{"cap"}, Desc: "Node pools, headroom and pending pods"}, + {Group: "Capacity & lifecycle", Name: "pending", Desc: "Pods the scheduler could not place, and why"}, + {Group: "Capacity & lifecycle", Name: "storage", Aliases: []string{"pvc"}, Desc: "Volume claims, fullest first"}, + {Group: "Capacity & lifecycle", Name: "maintain", Aliases: []string{"eol"}, Desc: "Support deadlines for your workloads, soonest first"}, + {Group: "Capacity & lifecycle", Name: "upgrade", Desc: "What each app must change before the next Kubernetes upgrade"}, + + {Group: "Add-ons", Name: "karpenter", Aliases: []string{"nodepools"}, Desc: "Karpenter NodePools: node provisioning and scaling"}, + {Group: "Add-ons", Name: "ca", Desc: "Cluster Autoscaler node groups and scaling"}, + {Group: "Add-ons", Name: "traefik", Aliases: []string{"routes"}, Desc: "Traefik ingress routes"}, + {Group: "Add-ons", Name: "istio", Aliases: []string{"mesh"}, Desc: "Istio mesh workloads"}, + {Group: "Add-ons", Name: "argocd", Aliases: []string{"gitops"}, Desc: "Argo CD Applications"}, + {Group: "Add-ons", Name: "cni", Aliases: []string{"vpccni"}, Desc: "Amazon VPC CNI nodes and IP capacity"}, + {Group: "Add-ons", Name: "ebs", Aliases: []string{"ebscsi"}, Desc: "Amazon EBS CSI nodes and volume attachments"}, + + {Group: "Navigation", Name: "ns", Aliases: []string{"namespace"}, Arg: "", Desc: "Scope to a namespace; bare :ns shows all"}, + {Group: "Navigation", Name: "q", Aliases: []string{"quit", "exit"}, Desc: "Quit"}, +} + +// names is the command's name followed by its aliases. +func (c command) names() []string { return append([]string{c.Name}, c.Aliases...) } + +// matchCommands ranks the catalog against what is typed. An empty query is the whole +// catalog in its own order. Otherwise: an exact name or alias, then a name prefix, an alias +// prefix, a substring of either, a word in the description, and last a subsequence — so a +// typo like "kapenter" still finds karpenter. Ties keep catalog order. +func matchCommands(query string) []command { + q := strings.ToLower(strings.TrimSpace(strings.TrimPrefix(query, ":"))) + if q == "" { + return append([]command(nil), catalog...) + } + // Once there is an argument the name is settled: show that command and what it takes. + if name, _, hasArg := strings.Cut(q, " "); hasArg { + for _, c := range catalog { + for _, n := range c.names() { + if n == name { + return []command{c} + } + } + } + return nil + } + + type ranked struct { + c command + score int + pos int + } + var out []ranked + for i, c := range catalog { + if s, ok := commandScore(c, q); ok { + out = append(out, ranked{c, s, i}) + } + } + sort.SliceStable(out, func(i, j int) bool { return out[i].score < out[j].score }) + cmds := make([]command, len(out)) + for i, r := range out { + cmds[i] = r.c + } + return cmds +} + +func commandScore(c command, q string) (int, bool) { + best := -1 + consider := func(s int) { + if best < 0 || s < best { + best = s + } + } + for i, n := range c.names() { + switch { + case n == q: + consider(0) + case strings.HasPrefix(n, q) && i == 0: + consider(1) + case strings.HasPrefix(n, q): + consider(2) + case strings.Contains(n, q): + consider(3) + case len(q) >= 3 && isSubsequence(q, n): + consider(5) + } + } + if strings.Contains(strings.ToLower(c.Desc), q) { + consider(4) + } + return best, best >= 0 +} + +func isSubsequence(q, s string) bool { + i := 0 + for _, r := range s { + if i < len(q) && rune(q[i]) == r { + i++ + } + } + return i == len(q) +} + +// suggestCommand is the nearest known name to a mistyped one, for "did you mean". +func suggestCommand(name string) string { + best, bestDist := "", 3 // more than two edits away is a different word, not a typo + for _, c := range catalog { + for _, n := range c.names() { + if d := editDistance(name, n); d < bestDist { + best, bestDist = c.Name, d + } + } + } + return best +} + +func editDistance(a, b string) int { + prev := make([]int, len(b)+1) + for j := range prev { + prev[j] = j + } + for i := 1; i <= len(a); i++ { + cur := make([]int, len(b)+1) + cur[0] = i + for j := 1; j <= len(b); j++ { + cost := 1 + if a[i-1] == b[j-1] { + cost = 0 + } + cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost) + } + prev = cur + } + return prev[len(b)] +} + +// paletteMatches is what the open command bar is offering right now. +func (m Model) paletteMatches() []command { return matchCommands(m.input.Value()) } + +// paletteView takes the table's place while the command bar is open, at the same height, so +// opening it never moves the frame. +func (m Model) paletteView() string { + height := m.bodyHeight() + 1 + if m.height > 0 { + // Everything but the tab strip, the menu's own border and the two footer lines. + height = max(m.height-1-panelHeight(0, m.screenWidth())-2, 1) + } + matches := m.paletteMatches() + q := strings.TrimSpace(m.input.Value()) + grouped := q == "" + + var lines []string + selLine := 0 + switch { + case len(matches) == 0: + msg := "No command matches " + `"` + q + `"` + " — enter runs it as typed, esc cancels." + if s := suggestCommand(strings.ToLower(strings.Fields(q + " ")[0])); s != "" { + msg = "No command matches " + `"` + q + `"` + " — did you mean :" + s + "?" + } + lines = append(lines, metaStyle.Render(msg)) + default: + group := "" + for i, c := range matches { + if grouped && c.Group != group { + if group != "" { + lines = append(lines, "") + } + group = c.Group + lines = append(lines, headerStyle.Render(group)) + } + if i == m.palSel { + selLine = len(lines) + } + lines = append(lines, m.paletteRow(c, i == m.palSel, !grouped)) + } + if strings.Contains(q, " ") { + lines = append(lines, "", metaStyle.Render("enter runs :"+q)) + } + } + + // Keep the highlighted row on screen: scroll the window, never the frame. + start := 0 + if selLine >= height { + start = selLine - height + 1 + } + end := min(start+height, len(lines)) + body := strings.Join(lines[start:end], "\n") + if n := end - start; n < height { + body += strings.Repeat("\n", height-n) + } + + title := "commands" + if !grouped { + title += " [" + itoa(len(matches)) + "/" + itoa(len(catalog)) + "]" + } + return panel(title, body, m.screenWidth()) +} + +func (m Model) paletteRow(c command, selected, showGroup bool) string { + name := c.Name + if c.Arg != "" { + name += " " + c.Arg + } + aliases := strings.Join(c.Aliases, " ") + marker := " " + nameCell := keyStyle.Render(lipgloss.NewStyle().Width(15).Render(name)) + if selected { + marker = keyStyle.Render("▸ ") + nameCell = selStyle.Render(lipgloss.NewStyle().Width(15).Render(name)) + } + row := marker + nameCell + " " + metaStyle.Render(lipgloss.NewStyle().Width(22).Render(clip(aliases, 21))) + c.Desc + if showGroup { + row += metaStyle.Render(" · " + c.Group) + } + return row +} + +type commandGroup struct { + name string + names []string +} + +// commandGroups is the catalog folded by group, for the help screen. +func commandGroups() []commandGroup { + var out []commandGroup + for _, c := range catalog { + if len(out) == 0 || out[len(out)-1].name != c.Group { + out = append(out, commandGroup{name: c.Group}) + } + n := ":" + c.Name + if c.Arg != "" { + n += " " + c.Arg + } + out[len(out)-1].names = append(out[len(out)-1].names, n) + } + return out +} diff --git a/internal/tui/palette_test.go b/internal/tui/palette_test.go new file mode 100644 index 0000000..318ce57 --- /dev/null +++ b/internal/tui/palette_test.go @@ -0,0 +1,209 @@ +package tui + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +func tab(m Model) Model { + next, _ := m.Update(tea.KeyMsg{Type: tea.KeyTab}) + return next.(Model) +} + +// The menu and the registry are one vocabulary: a name the menu offers must open something, +// and a screen the registry has must be findable from the menu. +func TestCatalogMatchesTheViewRegistry(t *testing.T) { + builtins := map[string]bool{"ns": true, "namespace": true, "q": true, "quit": true, "exit": true} + listed := map[string]bool{} + for _, c := range catalog { + for _, n := range c.names() { + if listed[n] { + t.Errorf(":%s is listed twice", n) + } + listed[n] = true + if _, ok := views[n]; !ok && !builtins[n] { + t.Errorf("the menu offers :%s but it opens nothing", n) + } + } + if c.Group == "" || c.Desc == "" { + t.Errorf(":%s needs a group and a description", c.Name) + } + } + for n := range views { + if !listed[n] { + t.Errorf("view :%s is not in the menu", n) + } + } +} + +func TestEmptyCommandBarListsEveryScreenGrouped(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m.height = 80 // tall enough to show the whole catalog without scrolling + m = key(m, ":") + out := m.View() + for _, want := range []string{"Resources", "Reliability", "Observability", "Capacity & lifecycle", "Add-ons", "Navigation", + "karpenter", "nodepools", "Karpenter NodePools", "maintain", "ns ", "↑↓ select", "tab complete"} { + if !strings.Contains(out, want) { + t.Errorf("menu is missing %q", want) + } + } + if strings.Contains(out, "web-1") { + t.Error("the menu should take the table's place, not sit under it") + } +} + +func TestMatchCommandsRanking(t *testing.T) { + first := func(q string) string { + ms := matchCommands(q) + if len(ms) == 0 { + return "" + } + return ms[0].Name + } + for q, want := range map[string]string{ + "ca": "ca", // exact beats the capacity prefix + "cap": "capacity", // alias + "kar": "karpenter", // prefix + "mesh": "istio", // alias + "kapenter": "karpenter", // typo, by subsequence + "po": "pods", + } { + if got := first(q); got != want { + t.Errorf("first match for %q = %q, want %q", q, got, want) + } + } + + names := map[string]bool{} + for _, c := range matchCommands("scal") { + names[c.Name] = true + } + if !names["karpenter"] || !names["ca"] { + t.Errorf(`"scal" should find both autoscalers by description, got %v`, names) + } + if ms := matchCommands("ns pay"); len(ms) != 1 || ms[0].Name != "ns" { + t.Errorf("with an argument the menu shows only that command, got %v", ms) + } + if ms := matchCommands("wibble"); len(ms) != 0 { + t.Errorf("wibble matched %v", ms) + } +} + +func TestEnterOpensTheHighlightedCommand(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m = key(m, ":") + m = typeIn(m, "ist") + m = key(m, "enter") + if m.view.Title != "Mesh workloads" { + t.Errorf("view = %q, want the Istio screen", m.view.Title) + } + + // Arrows move the highlight; enter opens the highlighted row, not the first. + m = key(m, ":") + m = key(m, "down") + m = key(m, "down") + m = key(m, "up") + if m.palSel != 1 { + t.Fatalf("palSel = %d", m.palSel) + } + m = key(m, "enter") + if m.view.Title != "Deployments" { + t.Errorf("view = %q, want the second entry (Deployments)", m.view.Title) + } +} + +func TestTypingResetsTheHighlight(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m = key(m, ":") + m = key(m, "down") + m = key(m, "down") + m = typeIn(m, "e") + if m.palSel != 0 { + t.Errorf("palSel = %d after typing, want 0", m.palSel) + } +} + +func TestTabCompletesTheHighlightedName(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m = key(m, ":") + m = typeIn(m, "karp") + m = tab(m) + if got := m.input.Value(); got != "karpenter" { + t.Errorf("tab filled %q", got) + } + + // A command with an argument is filled with the space, ready for the argument. + m = key(m, "esc") + m = key(m, ":") + m = typeIn(m, "namesp") + m = tab(m) + if got := m.input.Value(); got != "ns " { + t.Errorf("tab filled %q, want %q", got, "ns ") + } + m = typeIn(m, "payments") + if out := m.View(); !strings.Contains(out, "Scope to a namespace") || !strings.Contains(out, "enter runs :ns payments") { + t.Error("with an argument typed, the menu should show the command and what enter will run") + } + m = key(m, "enter") + if m.namespace != "payments" { + t.Errorf("namespace = %q", m.namespace) + } +} + +func TestUnknownCommandSuggestsTheNearestName(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m = key(m, ":") + m = typeIn(m, "kapenterx") + if out := m.View(); !strings.Contains(out, "did you mean :karpenter?") { + t.Error("the menu should suggest the nearest name when nothing matches") + } + m = key(m, "enter") + if !strings.Contains(m.status, "did you mean :karpenter?") { + t.Errorf("status = %q", m.status) + } +} + +// Opening the menu must not move the frame: same line count, nothing wider than the window, +// and the highlight stays on screen however far it is moved. +func TestMenuKeepsTheFrame(t *testing.T) { + for _, size := range [][2]int{{120, 30}, {60, 22}, {200, 50}} { + m := newModel(t, &fakeClient{rows: pods()}) + next, _ := m.Update(tea.WindowSizeMsg{Width: size[0], Height: size[1]}) + m = next.(Model) + before := strings.Count(m.View(), "\n") + + m = key(m, ":") + for i := 0; i < len(catalog)+5; i++ { + m = key(m, "down") + } + out := m.View() + if got := strings.Count(out, "\n"); got != before { + t.Errorf("%dx%d: menu has %d lines, table had %d", size[0], size[1], got, before) + } + for _, line := range strings.Split(out, "\n") { + if w := lipgloss.Width(line); w > size[0] { + t.Errorf("%dx%d: line %d wide: %q", size[0], size[1], w, line) + } + } + if !strings.Contains(out, "Quit") { + t.Errorf("%dx%d: the last entry is highlighted but not on screen", size[0], size[1]) + } + if m.palSel != len(catalog)-1 { + t.Errorf("palSel = %d, want it clamped to the last entry", m.palSel) + } + } +} + +func TestHelpListsCommandsFromTheCatalog(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m.height = 60 + m = key(m, "?") + out := m.View() + for _, c := range catalog { + if !strings.Contains(out, ":"+c.Name) { + t.Errorf("help is missing :%s", c.Name) + } + } +} diff --git a/internal/tui/render.go b/internal/tui/render.go index 7de6f6a..feb6731 100644 --- a/internal/tui/render.go +++ b/internal/tui/render.go @@ -41,6 +41,14 @@ func (m Model) View() string { var b strings.Builder b.WriteString(m.tabStrip()) b.WriteByte('\n') + if m.mode == modeCommand { + // The menu takes the context panel's rows as well as the table's: the whole + // catalog fits on an ordinary terminal, and the frame is still the same height. + b.WriteString(m.paletteView()) + b.WriteByte('\n') + b.WriteString(m.footer()) + return b.String() + } if head := m.contextPanel(); head != "" { b.WriteString(head) b.WriteByte('\n') @@ -61,14 +69,23 @@ func (m Model) screenWidth() int { } func (m Model) tabStrip() string { - left := chipStyle.Render(" "+m.view.Title+" ") + " " + - metaStyle.Render(m.scopeLabel()) + m.breadcrumb() + " " + - footerStyle.Render(keyStyle.Render(":")+" commands "+ - keyStyle.Render("/")+" filter "+ - keyStyle.Render("?")+" help") - + head := chipStyle.Render(" "+m.view.Title+" ") + " " + + metaStyle.Render(m.scopeLabel()) + m.breadcrumb() + keys := " " + footerStyle.Render(keyStyle.Render(":")+" browse screens "+ + keyStyle.Render("/")+" filter "+ + keyStyle.Render("?")+" help") right := metaStyle.Render(m.identity() + " · rtz " + version.Version) - return spread(left, right, m.screenWidth()) + + // On a narrow window the identity goes first, then the key reminder; what is on screen + // stays, clipped rather than wrapped. + w := m.screenWidth() + switch { + case lipgloss.Width(head+keys)+1+lipgloss.Width(right) <= w: + return spread(head+keys, right, w) + case lipgloss.Width(head+keys) <= w: + return head + keys + } + return clip(head, w) } func (m Model) identity() string { @@ -146,7 +163,7 @@ func (m Model) contextPanel() string { [2]string{"a", "ask about it"}, ), keyBlock( [2]string{"/", "filter"}, - [2]string{":", "command"}, + [2]string{":", "browse screens"}, [2]string{"s", "sort column"}, [2]string{"i", "invert sort"}, [2]string{"w", "wide columns"}, @@ -245,11 +262,14 @@ func (m Model) footer() string { case modeFilter: return keyStyle.Render(" /") + m.input.View() case modeCommand: - return keyStyle.Render(" :") + m.input.View() + // Two lines, like the hint and status lines it replaces, so the frame holds still. + return keyStyle.Render(" :") + m.input.View() + "\n" + " " + strings.Join([]string{ + hint("↑↓", "select"), hint("tab", "complete"), hint("enter", "open"), hint("esc", "cancel"), + }, " ") } hints := " " + strings.Join([]string{ - hint(":", "command"), hint("/", "filter"), hint("d", "describe"), + hint(":", "screens"), hint("/", "filter"), hint("d", "describe"), hint("l", "logs"), hint("r", "rca"), hint("c", "changes"), hint("t", "traces"), hint("a", "ask"), hint("s", "sort"), hint("w", "wide"), hint("?", "help"), hint("q", "quit"), @@ -420,22 +440,9 @@ func (m Model) helpView() string { for _, r := range keys { b.WriteString(keyStyle.Render(lipgloss.NewStyle().Width(12).Render(r[0])) + r[1] + "\n") } - b.WriteString("\n" + headerStyle.Render("Commands") + "\n") - for _, c := range [][2]string{ - {":pods, :deploy, :sts, :ds", "resource views"}, - {":svc, :ing, :nodes, :jobs", "resource views"}, - {":all", "every kind"}, - {":triage", "what is failing right now"}, - {":risk, :rca, :signals, :changes", "reliability views"}, - {":logs, :traces", "observability views"}, - {":capacity, :pending, :storage", "capacity: pools, pending pods, PVCs"}, - {":maintain, :upgrade", "support deadlines, upgrade impact per app"}, - {":karpenter, :ca, :traefik", "add-on workspaces"}, - {":istio, :argocd, :cni, :ebs", "add-on workspaces"}, - {":ns ", "scope to a namespace (bare :ns clears it)"}, - {":q", "quit"}, - } { - b.WriteString(keyStyle.Render(lipgloss.NewStyle().Width(32).Render(c[0])) + c[1] + "\n") + b.WriteString("\n" + headerStyle.Render("Commands") + metaStyle.Render(" (press : to browse and search them)") + "\n") + for _, g := range commandGroups() { + b.WriteString(keyStyle.Render(lipgloss.NewStyle().Width(22).Render(g.name)) + strings.Join(g.names, " ") + "\n") } b.WriteString("\n" + metaStyle.Render( "Every view here has a flag equivalent — :deploy is `rtz get deploy`, d is `rtz describe`.")) From f68f00a6d1f3981560fd97ff0cf7e7e5a3e2d6c4 Mon Sep 17 00:00:00 2001 From: pvishwa3 Date: Sat, 17 Oct 2026 22:42:30 -0400 Subject: [PATCH 6/7] =?UTF-8?q?feat(tui):=20group=20tabs=20=E2=80=94=201?= =?UTF-8?q?=E2=80=935=20switch=20group,=20tab=20walks=20the=20group's=20sc?= =?UTF-8?q?reens?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The top of every screen is now two tab lines: the catalog's groups (Resources, Reliability, Observability, Capacity, Add-ons), numbered for the 1–5 keys, and the current group's screens, walked with tab / shift+tab. A number returns to the screen last used in that group; aliases and [ ] history light the right tabs. On a narrow window the labels shorten and a long group drops leading tabs, never the active one; the footer hints drop the least useful ones instead of running past the edge. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0178ctkmt3CJYuTzySDeSgSe --- README.md | 2 + internal/tui/app.go | 17 +++- internal/tui/palette.go | 13 ++- internal/tui/render.go | 54 +++++----- internal/tui/tabs.go | 202 ++++++++++++++++++++++++++++++++++++++ internal/tui/tabs_test.go | 139 ++++++++++++++++++++++++++ 6 files changed, 389 insertions(+), 38 deletions(-) create mode 100644 internal/tui/tabs.go create mode 100644 internal/tui/tabs_test.go diff --git a/README.md b/README.md index aff06bb..702cab1 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ Run `rtz` with no arguments for the full-screen UI. | `:` | capacity and lifecycle — `:capacity`, `:pending`, `:storage`, `:maintain`, `:upgrade` | | `:` | add-on workspaces — `:karpenter`, `:ca`, `:traefik`, `:istio`, `:argocd`, `:cni`, `:ebs` | | `:` | resources and the rest — `:pods`, `:deploy`, `:sts`, `:ds`, `:svc`, `:ing`, `:nodes`, `:all`, `:risk`, `:signals`, `:changes`, `:logs`, `:traces`, `:ns `, `:q` | +| `1`–`5` | switch group — Resources, Reliability, Observability, Capacity, Add-ons — back to the screen you last used there | +| `tab` / `shift+tab` | next / previous screen in the group; the two tab lines at the top show both | | `/` | filter the visible rows as you type | | `enter` / `d` | describe the selected workload; on capacity, Maintain, upgrade and add-on screens, open the row's findings with their verify commands | | `p` | pause or resume auto-refresh | diff --git a/internal/tui/app.go b/internal/tui/app.go index ff7c835..844a90b 100644 --- a/internal/tui/app.go +++ b/internal/tui/app.go @@ -78,6 +78,8 @@ type Model struct { // history is the trail of view names `[` and `]` walk, in visit order. history []string histPos int + // groupLast is the screen last shown in each group, for the 1–5 keys to return to. + groupLast map[string]string detail *api.WorkloadDetail detailRef string @@ -129,7 +131,7 @@ func New(opts Options) Model { opts: opts, view: v, input: in, loading: true, sortCol: -1, history: []string{name}, histPos: 0, - } + }.remember(name) } func (m Model) Init() tea.Cmd { @@ -402,6 +404,13 @@ func (m Model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { m.clampCursor() return m, nil + case "1", "2", "3", "4", "5", "6", "7", "8", "9": + return m.switchGroup(int(msg.String()[0] - '0')) + case "tab": + return m.cycleScreen(1) + case "shift+tab": + return m.cycleScreen(-1) + case "p": m.paused = !m.paused m.status = map[bool]string{true: "auto-refresh paused", false: "auto-refresh resumed"}[m.paused] @@ -555,7 +564,7 @@ func (m Model) switchView(name string) (tea.Model, tea.Cmd) { m.history = append(m.history, name) m.histPos = len(m.history) - 1 } - return m.loadView(v) + return m.remember(name).loadView(v) } // loadView resets everything that belongs to the outgoing screen. The sort is one of them: @@ -581,7 +590,7 @@ func (m Model) stepHistory(delta int) (tea.Model, tea.Cmd) { return m, nil } m.histPos = next - return m.loadView(views[m.history[next]]) + return m.remember(m.history[next]).loadView(views[m.history[next]]) } // cycleSort advances the sort one step: unsorted → column 0 → … → last column → unsorted. @@ -689,7 +698,7 @@ func (m Model) bodyHeight() int { if m.height <= 0 { return 20 } - chrome := 1 + // tab strip + chrome := tabStripLines + // group tabs + screen tabs 1 + // column header inside the table panel 2 + // the table panel's own border 2 // hint line + status line diff --git a/internal/tui/palette.go b/internal/tui/palette.go index 3e835eb..c4709a3 100644 --- a/internal/tui/palette.go +++ b/internal/tui/palette.go @@ -182,8 +182,8 @@ func (m Model) paletteMatches() []command { return matchCommands(m.input.Value() func (m Model) paletteView() string { height := m.bodyHeight() + 1 if m.height > 0 { - // Everything but the tab strip, the menu's own border and the two footer lines. - height = max(m.height-1-panelHeight(0, m.screenWidth())-2, 1) + // Everything but the tab lines, the menu's own border and the two footer lines. + height = max(m.height-tabStripLines-panelHeight(0, m.screenWidth())-2, 1) } matches := m.paletteMatches() q := strings.TrimSpace(m.input.Value()) @@ -275,3 +275,12 @@ func commandGroups() []commandGroup { } return out } + +// groupKeyList is "1 Resources, 2 Reliability, …" for the help screen. +func groupKeyList() string { + var parts []string + for i, g := range tabGroups() { + parts = append(parts, itoa(i+1)+" "+g) + } + return strings.Join(parts, ", ") +} diff --git a/internal/tui/render.go b/internal/tui/render.go index feb6731..483edae 100644 --- a/internal/tui/render.go +++ b/internal/tui/render.go @@ -8,7 +8,6 @@ import ( "github.com/charmbracelet/lipgloss" "github.com/runtimez-com/runtimez-cli/internal/k8s" - "github.com/runtimez-com/runtimez-cli/internal/version" "github.com/runtimez-com/runtimez-cli/internal/view" ) @@ -68,26 +67,6 @@ func (m Model) screenWidth() int { return m.width } -func (m Model) tabStrip() string { - head := chipStyle.Render(" "+m.view.Title+" ") + " " + - metaStyle.Render(m.scopeLabel()) + m.breadcrumb() - keys := " " + footerStyle.Render(keyStyle.Render(":")+" browse screens "+ - keyStyle.Render("/")+" filter "+ - keyStyle.Render("?")+" help") - right := metaStyle.Render(m.identity() + " · rtz " + version.Version) - - // On a narrow window the identity goes first, then the key reminder; what is on screen - // stays, clipped rather than wrapped. - w := m.screenWidth() - switch { - case lipgloss.Width(head+keys)+1+lipgloss.Width(right) <= w: - return spread(head+keys, right, w) - case lipgloss.Width(head+keys) <= w: - return head + keys - } - return clip(head, w) -} - func (m Model) identity() string { if m.opts.ContextName != "" { return m.opts.ContextName @@ -268,12 +247,21 @@ func (m Model) footer() string { }, " ") } - hints := " " + strings.Join([]string{ - hint(":", "screens"), hint("/", "filter"), hint("d", "describe"), - hint("l", "logs"), hint("r", "rca"), hint("c", "changes"), hint("t", "traces"), - hint("a", "ask"), hint("s", "sort"), hint("w", "wide"), - hint("?", "help"), hint("q", "quit"), - }, " ") + // Most useful first; what does not fit the window is dropped rather than wrapped. The + // help screen lists them all. + hints := " " + for _, h := range []string{ + hint(":", "screens"), hint("1-5", "groups"), hint("tab", "next"), hint("/", "filter"), + hint("?", "help"), hint("d", "describe"), hint("l", "logs"), hint("r", "rca"), + hint("c", "changes"), hint("t", "traces"), hint("a", "ask"), hint("s", "sort"), + hint("w", "wide"), hint("q", "quit"), + } { + if lipgloss.Width(hints+h) > m.screenWidth() { + break + } + hints += h + " " + } + hints = strings.TrimRight(hints, " ") var left []string if m.data.table != nil { @@ -392,8 +380,8 @@ func (m Model) detailView() string { // Keep the pane inside the window; the detail of a big workload is longer than a screen. if m.height > 6 { lines := strings.Split(body, "\n") - if len(lines) > m.height-6 { - lines = lines[:m.height-6] + if len(lines) > m.height-7 { + lines = lines[:m.height-7] lines = append(lines, metaStyle.Render("… truncated — `rtz describe "+m.detailRef+"` prints it all")) } body = strings.Join(lines, "\n") @@ -406,8 +394,8 @@ func (m Model) detailView() string { func (m Model) rowPaneView() string { body := strings.TrimRight(m.rowPane, "\n") - if m.height > 6 { - body = clipLines(body, m.height-6) + if m.height > 7 { + body = clipLines(body, m.height-7) } return m.tabStrip() + "\n" + panel(strings.ToLower(m.view.Title), body, m.screenWidth()) + "\n" + @@ -421,7 +409,9 @@ func (m Model) helpView() string { {"g / G", "top / bottom"}, {"enter, d", "describe the selected workload, or open the row's findings"}, {"/", "filter the visible rows"}, - {":", "command bar"}, + {":", "browse and search every screen"}, + {"1 – 5", "switch group: " + groupKeyList()}, + {"tab", "next screen in the group (shift+tab: previous)"}, {"s / i", "sort by the next column / invert the order"}, {"w", "wide columns, when the view has extras"}, {"0", "clear the namespace scope"}, diff --git a/internal/tui/tabs.go b/internal/tui/tabs.go new file mode 100644 index 0000000..78c05af --- /dev/null +++ b/internal/tui/tabs.go @@ -0,0 +1,202 @@ +package tui + +import ( + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + + "github.com/runtimez-com/runtimez-cli/internal/version" +) + +// The two tab lines are the menu kept on screen: the groups of the catalog on top, numbered +// for the 1–5 keys, and the screens of the current group under them, walked with tab. They +// answer "what else is here" without the operator having to ask. + +// tabStripLines is how many rows tabStrip draws; bodyHeight and the panes budget for it. +const tabStripLines = 2 + +// tabLabels shortens a group name for its tab. Groups not listed use their own name. +var tabLabels = map[string]string{"Capacity & lifecycle": "Capacity"} + +// tabGroups is the catalog's groups in order, without Navigation (commands, not screens). +func tabGroups() []string { + var out []string + for _, c := range catalog { + if c.Group == "Navigation" { + continue + } + if len(out) == 0 || out[len(out)-1] != c.Group { + out = append(out, c.Group) + } + } + return out +} + +// groupScreens is the primary names of one group's screens, in catalog order. +func groupScreens(group string) []string { + var out []string + for _, c := range catalog { + if c.Group == group { + out = append(out, c.Name) + } + } + return out +} + +// commandFor resolves a view name or alias to its catalog entry. +func commandFor(name string) (command, bool) { + for _, c := range catalog { + for _, n := range c.names() { + if n == name { + return c, true + } + } + } + return command{}, false +} + +// current is the catalog entry of the screen on show. +func (m Model) current() (command, bool) { + if m.histPos < 0 || m.histPos >= len(m.history) { + return command{}, false + } + return commandFor(m.history[m.histPos]) +} + +// remember records the screen as the one to come back to when its group's number is pressed. +func (m Model) remember(name string) Model { + c, ok := commandFor(name) + if !ok { + return m + } + last := make(map[string]string, len(m.groupLast)+1) + for k, v := range m.groupLast { + last[k] = v + } + last[c.Group] = c.Name + m.groupLast = last + return m +} + +// switchGroup opens group n (1-based) at the screen last used there, or its first screen. +func (m Model) switchGroup(n int) (tea.Model, tea.Cmd) { + groups := tabGroups() + if n < 1 || n > len(groups) { + return m, nil + } + g := groups[n-1] + if cur, ok := m.current(); ok && cur.Group == g { + return m, nil + } + name := m.groupLast[g] + if name == "" { + name = groupScreens(g)[0] + } + return m.switchView(name) +} + +// cycleScreen moves to the next (+1) or previous (-1) screen in the current group, wrapping. +func (m Model) cycleScreen(delta int) (tea.Model, tea.Cmd) { + cur, ok := m.current() + if !ok { + return m, nil + } + screens := groupScreens(cur.Group) + i := indexOf(screens, cur.Name) + next := screens[((i+delta)%len(screens)+len(screens))%len(screens)] + return m.switchView(next) +} + +func indexOf(xs []string, s string) int { + for i, x := range xs { + if x == s { + return i + } + } + return 0 +} + +// tabStrip is the group tabs over the current group's screen tabs. +func (m Model) tabStrip() string { + return m.groupLine() + "\n" + m.screenLine() +} + +func (m Model) groupLine() string { + w := m.screenWidth() + cur, _ := m.current() + right := metaStyle.Render(m.identity() + " · rtz " + version.Version) + + // Full labels, then three letters, then numbers alone: the active group always shows. + for _, short := range []int{0, 3, -1} { + var parts []string + for i, g := range tabGroups() { + label := g + if l, ok := tabLabels[g]; ok { + label = l + } + switch { + case short == -1: + label = "" + case short > 0 && len(label) > short: + label = label[:short] + } + num := itoa(i + 1) + if g == cur.Group { + parts = append(parts, chipStyle.Render(" "+strings.TrimSpace(num+" "+label)+" ")) + continue + } + parts = append(parts, keyStyle.Render(" "+num)+metaStyle.Render(strings.TrimRight(" "+label, " "))) + } + left := strings.Join(parts, " ") + switch { + case lipgloss.Width(left)+1+lipgloss.Width(right) <= w: + return spread(left, right, w) + case lipgloss.Width(left) <= w: + return left + } + } + return clip(chipStyle.Render(" "+m.view.Title+" "), w) +} + +func (m Model) screenLine() string { + w := m.screenWidth() + cur, ok := m.current() + + var tabs []string + active := 0 + if ok { + for i, name := range groupScreens(cur.Group) { + if name == cur.Name { + active = i + tabs = append(tabs, chipStyle.Render(" "+name+" ")) + continue + } + tabs = append(tabs, metaStyle.Render(" "+name+" ")) + } + } else { + tabs = []string{chipStyle.Render(" " + m.view.Title + " ")} + } + + scope := " " + metaStyle.Render(m.scopeLabel()) + m.breadcrumb() + keys := footerStyle.Render(keyStyle.Render("tab") + " next " + keyStyle.Render(":") + " browse " + + keyStyle.Render("/") + " filter " + keyStyle.Render("?") + " help") + + // A long group drops its leading tabs rather than the one on show. + start := 0 + for start < active && lipgloss.Width(strings.Join(tabs[start:], "")) > w-2 { + start++ + } + left := strings.Join(tabs[start:], "") + if start > 0 { + left = metaStyle.Render("‹") + left + } + + switch { + case lipgloss.Width(left+scope)+1+lipgloss.Width(keys) <= w: + return spread(left+scope, keys, w) + case lipgloss.Width(left+scope) <= w: + return left + scope + } + return clip(left, w) +} diff --git a/internal/tui/tabs_test.go b/internal/tui/tabs_test.go new file mode 100644 index 0000000..dc2974d --- /dev/null +++ b/internal/tui/tabs_test.go @@ -0,0 +1,139 @@ +package tui + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + + "github.com/runtimez-com/runtimez-cli/internal/api" +) + +func press(t *testing.T, m Model, msg tea.KeyMsg) Model { + t.Helper() + next, cmd := m.Update(msg) + m = next.(Model) + if cmd != nil { + if out := cmd(); out != nil { + if rows, ok := out.(rowsMsg); ok { + next, _ = m.Update(rows) + m = next.(Model) + } + } + } + return m +} + +func digit(t *testing.T, m Model, d string) Model { + return press(t, m, tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(d)}) +} + +func TestTabLinesShowGroupsAndTheGroupsScreens(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + strip := strings.Split(m.View(), "\n")[:tabStripLines] + for _, want := range []string{"1 Resources", "2 Reliability", "3 Observability", "4 Capacity", "5 Add-ons"} { + if !strings.Contains(strip[0], want) { + t.Errorf("group line is missing %q: %q", want, strip[0]) + } + } + for _, want := range []string{"pods", "deploy", "sts", "nodes", "all", "all namespaces"} { + if !strings.Contains(strip[1], want) { + t.Errorf("screen line is missing %q: %q", want, strip[1]) + } + } + if strings.Contains(strip[1], "karpenter") { + t.Error("the screen line shows only the current group") + } +} + +func TestNumberKeysSwitchGroupAndReturnToTheLastScreen(t *testing.T) { + c := &fakeClient{rows: pods(), workspaces: map[string]any{"NodePools": karpenter("OK")}} + m := newModel(t, c) + + m = digit(t, m, "5") + if m.view.Title != "Karpenter NodePools" { + t.Fatalf("5 opened %q, want the first add-on screen", m.view.Title) + } + if !strings.Contains(strings.Split(m.View(), "\n")[1], "traefik") { + t.Error("after 5 the screen line lists the add-on screens") + } + m = press(t, m, tea.KeyMsg{Type: tea.KeyTab}) + if m.view.Title != "Cluster Autoscaler" { + t.Fatalf("tab opened %q, want the next add-on", m.view.Title) + } + + m = digit(t, m, "1") + if m.view.Title != "Pods" { + t.Fatalf("1 opened %q, want Pods (the last Resources screen)", m.view.Title) + } + m = digit(t, m, "5") + if m.view.Title != "Cluster Autoscaler" { + t.Errorf("5 opened %q, want the add-on screen used last", m.view.Title) + } + + // A number with no group, and 0 (all namespaces), keep their meaning. + m = digit(t, m, "9") + if m.view.Title != "Cluster Autoscaler" { + t.Errorf("9 moved to %q", m.view.Title) + } +} + +func TestTabWrapsWithinTheGroup(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m = press(t, m, tea.KeyMsg{Type: tea.KeyShiftTab}) + if m.view.Title != "All resources" { + t.Errorf("shift+tab from the first screen opened %q, want the last (All resources)", m.view.Title) + } + m = press(t, m, tea.KeyMsg{Type: tea.KeyTab}) + if m.view.Title != "Pods" { + t.Errorf("tab from the last screen opened %q, want the first", m.view.Title) + } +} + +// A screen reached by its alias still lights its own tab, and [ ] keep the tabs in step. +func TestTabsFollowAliasesAndHistory(t *testing.T) { + c := &fakeClient{rows: pods(), workspaces: map[string]any{"MeshWorkloads": &api.MeshWorkloads{}}} + m := open(t, c, "mesh") + if cur, _ := m.current(); cur.Name != "istio" { + t.Fatalf("current = %q, want istio", cur.Name) + } + m = digit(t, m, "5") + if m.view.Title != "Mesh workloads" { + t.Errorf("5 on an add-on screen should stay put, got %q", m.view.Title) + } + m = digit(t, m, "1") + m = key(m, "[") + if cur, _ := m.current(); cur.Group != "Add-ons" { + t.Errorf("after [ the tabs show %q, want Add-ons", cur.Group) + } +} + +// The tab lines never push the frame past the window, and the screen on show stays visible +// however narrow it gets. +func TestTabLinesFitTheWindow(t *testing.T) { + for _, w := range []int{40, 60, 80, 120, 200} { + m := newModel(t, &fakeClient{rows: pods()}) + next, _ := m.Update(tea.WindowSizeMsg{Width: w, Height: 30}) + m = next.(Model) + m = digit(t, m, "5") + m = press(t, m, tea.KeyMsg{Type: tea.KeyShiftTab}) // ebs, the last add-on tab + + out := m.View() + if got := strings.Count(out, "\n") + 1; got != 30 { + t.Errorf("width %d: %d lines, want the window's 30", w, got) + } + lines := strings.Split(out, "\n") + for i, line := range lines { + if lw := lipgloss.Width(line); lw > w { + t.Errorf("width %d: line %d is %d wide: %q", w, i, lw, line) + } + } + if !strings.Contains(lines[1], "ebs") { + t.Errorf("width %d: the active screen tab is not shown: %q", w, lines[1]) + } + if !strings.Contains(lines[0], "5") { + t.Errorf("width %d: the active group tab is not shown: %q", w, lines[0]) + } + } +} From 039779677db75d802c1f89b419cc7a50f239be20 Mon Sep 17 00:00:00 2001 From: pvishwa3 Date: Sat, 17 Oct 2026 22:54:23 -0400 Subject: [PATCH 7/7] feat(tui): animated loader for every API call; drop responses for a screen already left MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Opening a screen (menu, 1–5, tab, [ ], :ns, 0, scope clear) now clears the old rows and shows a spinner naming the screen, with the wait once it passes 2s. Auto-refresh and ctrl+r keep the rows and show the spinner with "refreshing" in the corner; describe shows "describing ns/name"; the ask pane's "working…" spins too. The spinner ticks only while something is loading. Each screen load carries a sequence number, and a response for an older one is dropped: before, switching quickly could draw the previous screen's rows under the new title. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0178ctkmt3CJYuTzySDeSgSe --- internal/cli/tui.go | 1 + internal/tui/app.go | 82 ++++++++++++++++++--- internal/tui/ask.go | 2 +- internal/tui/loader_test.go | 141 ++++++++++++++++++++++++++++++++++++ internal/tui/render.go | 22 +++++- 5 files changed, 233 insertions(+), 15 deletions(-) create mode 100644 internal/tui/loader_test.go diff --git a/internal/cli/tui.go b/internal/cli/tui.go index 209d7ae..4eb1610 100644 --- a/internal/cli/tui.go +++ b/internal/cli/tui.go @@ -39,6 +39,7 @@ func runTUI(cmd *cobra.Command) error { APIURL: e.client.BaseURL, Refresh: flags.refresh, InitialView: flags.initialView, + Animate: true, }) p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithContext(cmd.Context())) diff --git a/internal/tui/app.go b/internal/tui/app.go index 844a90b..9830e33 100644 --- a/internal/tui/app.go +++ b/internal/tui/app.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/charmbracelet/bubbles/spinner" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" @@ -40,6 +41,9 @@ type Options struct { APIURL string Refresh time.Duration InitialView string + // Animate runs the loading spinner. Off in tests, where a ticking spinner would keep + // every command batch alive; the loader still draws, as a still frame. + Animate bool } // Model is the root Bubble Tea model. @@ -89,7 +93,16 @@ type Model struct { ask askState - loading bool + loading bool + // seq numbers each screen load; a response carrying an older number is for a screen + // the operator already left, and drawing it would put old rows under the new title. + seq int + loadStart time.Time + // describing is the workload a describe is waiting on, for the loader to name. + describing string + spin spinner.Model + spinning bool + paused bool lastUpdated time.Time err error @@ -97,6 +110,7 @@ type Model struct { } type rowsMsg struct { + seq int data dataset err error } @@ -123,12 +137,14 @@ func New(opts Options) Model { v = views["pods"] } + sp := spinner.New(spinner.WithSpinner(spinner.Dot), spinner.WithStyle(keyStyle)) + in := textinput.New() in.Prompt = "" in.CharLimit = 120 return Model{ - opts: opts, view: v, input: in, loading: true, + opts: opts, view: v, input: in, loading: true, spin: sp, loadStart: time.Now(), sortCol: -1, history: []string{name}, histPos: 0, }.remember(name) @@ -154,11 +170,12 @@ func (m Model) fetch() tea.Cmd { if v.scopable { req.Scope = m.scope } + seq := m.seq return func() tea.Msg { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() d, err := v.fetch(ctx, req) - return rowsMsg{data: d, err: err} + return rowsMsg{seq: seq, data: d, err: err} } } @@ -173,8 +190,43 @@ func (m Model) fetchDetail(r k8s.Resource) tea.Cmd { } } +// Update handles one message, then starts the spinner if that left something loading. The +// spinner stops itself on the first tick after the loading ends, so an idle screen does not +// redraw ten times a second. func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + next, cmd := m.update(msg) + mm := next.(Model) + if mm.opts.Animate && mm.busy() && !mm.spinning { + mm.spinning = true + return mm, tea.Batch(cmd, mm.spin.Tick) + } + return mm, cmd +} + +// busy is whether anything on screen is waiting on the API. +func (m Model) busy() bool { return m.loading || m.ask.busy } + +// beginLoad starts a new screen load: the old rows, error and caveat go, so the loader +// shows instead of the previous screen's data under the new title. +func (m Model) beginLoad() Model { + m.seq++ + m.loading, m.loadStart, m.err = true, time.Now(), nil + m.data, m.visible, m.shown = dataset{}, nil, nil + m.cursor, m.offset = 0, 0 + return m +} + +func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { + case spinner.TickMsg: + if !m.busy() { + m.spinning = false + return m, nil + } + var cmd tea.Cmd + m.spin, cmd = m.spin.Update(msg) + return m, cmd + case tea.WindowSizeMsg: m.width, m.height = msg.Width, msg.Height return m, nil @@ -185,9 +237,13 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.paused || m.mode != modeNormal { return m, m.tick() } + m.loading = true return m, tea.Batch(m.fetch(), m.tick()) case rowsMsg: + if msg.seq != m.seq { + return m, nil + } m.loading = false if msg.err != nil { m.err = msg.err @@ -204,7 +260,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil case detailMsg: - m.loading = false + m.loading, m.describing = false, "" if msg.err != nil { m.err = msg.err m.mode = modeNormal @@ -378,7 +434,8 @@ func (m Model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, nil case !m.scope.empty(): m.scope = scope{} - m.loading, m.status = true, "scope cleared" + m = m.beginLoad() + m.status = "scope cleared" return m, m.fetch() } m.status = "" @@ -437,7 +494,7 @@ func (m Model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { m.status = fmt.Sprintf("no detail view for %s — describe covers Pod, Deployment, StatefulSet and DaemonSet", r.Kind) return m, nil } - m.loading = true + m.loading, m.describing = true, r.Namespace+"/"+r.Name return m, m.fetchDetail(r) case "s": @@ -473,7 +530,8 @@ func (m Model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, nil } m.namespace = "" - m.loading, m.status = true, "showing all namespaces" + m = m.beginLoad() + m.status = "showing all namespaces" return m, m.fetch() case "[": @@ -517,7 +575,9 @@ func (m Model) runCommand(raw string) (tea.Model, tea.Cmd) { } else { m.status = "namespace: " + arg } - m.loading = true + status := m.status + m = m.beginLoad() + m.status = status return m, m.fetch() } @@ -571,11 +631,11 @@ func (m Model) switchView(name string) (tea.Model, tea.Cmd) { // column 3 means something different on every view, so carrying it over would silently // order the new table by whatever happens to sit there. func (m Model) loadView(v viewDef) (tea.Model, tea.Cmd) { + m = m.beginLoad() m.view = v - m.cursor, m.offset, m.filter = 0, 0, "" + m.filter = "" m.sortCol, m.sortDesc, m.wide = -1, false, false - m.shown = nil - m.loading, m.status = true, "" + m.status = "" return m, m.fetch() } diff --git a/internal/tui/ask.go b/internal/tui/ask.go index 28fa531..e326d19 100644 --- a/internal/tui/ask.go +++ b/internal/tui/ask.go @@ -275,7 +275,7 @@ func (m Model) askView() string { prompt := keyStyle.Render("› ") + m.ask.input.View() if m.ask.busy { - prompt = metaStyle.Render(" working… ") + warnStyle.Render("ctrl+c") + metaStyle.Render(" stops the agent") + prompt = " " + m.spin.View() + metaStyle.Render(" working… ") + warnStyle.Render("ctrl+c") + metaStyle.Render(" stops the agent") } b.WriteString(prompt) diff --git a/internal/tui/loader_test.go b/internal/tui/loader_test.go new file mode 100644 index 0000000..dac684d --- /dev/null +++ b/internal/tui/loader_test.go @@ -0,0 +1,141 @@ +package tui + +import ( + "strings" + "testing" + "time" + + "github.com/charmbracelet/bubbles/spinner" + tea "github.com/charmbracelet/bubbletea" + + "github.com/runtimez-com/runtimez-cli/internal/k8s" +) + +// switchTo opens a view from the command bar without delivering its response. +func switchTo(m Model, name string) (Model, tea.Cmd) { + m = key(m, ":") + m = typeIn(m, name) + next, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + return next.(Model), cmd +} + +// Between leaving a screen and the next one answering, the table area is a loader naming +// the new screen — never the old screen's rows under the new title. +func TestSwitchingScreensShowsTheLoaderNotTheOldRows(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m, _ = switchTo(m, "karpenter") + + out := m.View() + if !strings.Contains(out, "Loading Karpenter NodePools…") { + t.Errorf("no loader for the new screen:\n%s", out) + } + if strings.Contains(out, "checkout-1") { + t.Error("the old screen's rows are still drawn under the new title") + } + if !strings.Contains(out, "loading") { + t.Error("the corner marker should say loading") + } +} + +func TestLoaderShowsTheWaitOnceItIsLong(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m, _ = switchTo(m, "capacity") + if line := m.loaderLine("x"); !strings.HasSuffix(line, "x") { + t.Errorf("a fresh load should not show a wait: %q", line) + } + m.loadStart = time.Now().Add(-5 * time.Second) + if line := m.loaderLine("x"); !strings.Contains(line, "5s") { + t.Errorf("loader = %q, want the 5s wait", line) + } +} + +// A response for a screen already left is dropped. +func TestAResponseForAScreenAlreadyLeftIsDropped(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + stale := m.seq + m, _ = switchTo(m, "karpenter") + + next, _ := m.Update(rowsMsg{seq: stale, data: podDataset(pods())}) + m = next.(Model) + if strings.Contains(m.View(), "checkout-1") { + t.Error("a pods response landed on the Karpenter screen") + } + if !m.loading { + t.Error("the stale response ended the new screen's load") + } + + next, _ = m.Update(rowsMsg{seq: m.seq, data: podDataset([]k8s.Resource{{Kind: "Pod", Namespace: "a", Name: "fresh-1"}})}) + m = next.(Model) + if m.loading || !strings.Contains(m.View(), "fresh-1") { + t.Error("the current screen's response should land") + } +} + +// A refresh keeps the rows and says so in the corner, rather than blanking the table. +func TestRefreshKeepsRowsAndMarksTheCorner(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m = key(m, "ctrl+r") + out := m.View() + if !strings.Contains(out, "checkout-1") { + t.Error("refresh blanked the table") + } + if !strings.Contains(out, "refreshing") { + t.Error("the corner should say refreshing") + } + if strings.Contains(out, "Loading Pods") { + t.Error("a refresh is not a fresh load") + } + + next, _ := m.Update(tickMsg(time.Now())) + if !next.(Model).loading { + t.Error("an auto-refresh should mark the screen as refreshing too") + } +} + +func TestDescribeNamesTheWorkloadWhileLoading(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + next, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("d")}) + m = next.(Model) + if !strings.Contains(m.View(), "describing payments/checkout-1") { + t.Error("describe should name what it is loading") + } + next, _ = m.Update(detailMsg{ref: "payments/checkout-1"}) + if m = next.(Model); m.describing != "" || m.loading { + t.Error("the describe loader should end when the detail lands") + } +} + +// The spinner ticks only while something is loading: an idle screen must not redraw ten +// times a second. +func TestSpinnerRunsOnlyWhileLoading(t *testing.T) { + m := newModel(t, &fakeClient{rows: pods()}) + m.opts.Animate = true + + next, cmd := m.Update(tea.KeyMsg{Type: tea.KeyCtrlR}) + m = next.(Model) + if !m.spinning || cmd == nil { + t.Fatal("starting a load should start the spinner") + } + next, cmd = m.Update(m.spin.Tick()) + if m = next.(Model); cmd == nil { + t.Error("the spinner should keep ticking while loading") + } + + next, _ = m.Update(rowsMsg{seq: m.seq, data: podDataset(pods())}) + m = next.(Model) + next, cmd = m.Update(spinner.TickMsg{ID: m.spin.ID()}) + if m = next.(Model); cmd != nil || m.spinning { + t.Error("the spinner should stop on the first tick after the load ends") + } + + // Off (as in tests), no tick is ever scheduled, but the loader still draws. + m.opts.Animate = false + m.spinning = false + m, _ = switchTo(m, "pending") + if m.spinning { + t.Error("Animate=false must not start the spinner") + } + if !strings.Contains(m.View(), "Loading Pending pods…") { + t.Error("the loader draws without animation") + } +} diff --git a/internal/tui/render.go b/internal/tui/render.go index 483edae..f1ff799 100644 --- a/internal/tui/render.go +++ b/internal/tui/render.go @@ -215,8 +215,10 @@ func (m Model) body() string { case m.data.body != "": // Some screens are prose, not rows — a root cause is a narrative. return pad(clipLines(m.data.body, height+1)) - case m.loading && len(m.visible) == 0: - return pad(metaStyle.Render("loading…")) + case m.loading && m.data.table == nil && m.data.body == "": + // Nothing for this screen has arrived yet. A refresh of a loaded screen keeps its + // rows and says so in the corner instead. + return pad(m.loaderLine("Loading " + m.view.Title + "…")) case m.data.table == nil || len(m.data.table.Rows) == 0: msg := "No resources found." if m.data.table != nil && m.data.table.EmptyMessage != "" { @@ -301,8 +303,12 @@ func (m Model) liveMarker() string { return errStyle.Render("● error") case m.paused: return warnStyle.Render("❚❚ paused") + case m.loading && m.describing != "": + return m.spin.View() + metaStyle.Render(" describing "+clip(m.describing, 40)) + case m.loading && m.data.table == nil && m.data.body == "": + return m.spin.View() + metaStyle.Render(" loading") case m.loading: - return metaStyle.Render("◌ loading") + return m.spin.View() + metaStyle.Render(" refreshing") default: return okStyle.Render("● live") } @@ -446,3 +452,13 @@ func (m Model) helpView() string { func sinceUpdate(m Model) time.Duration { return time.Since(m.lastUpdated) } + +// loaderLine is the spinner and what it is waiting for, with the wait once it is long enough +// to wonder about — a request that is slow and one that is stuck look the same otherwise. +func (m Model) loaderLine(what string) string { + line := m.spin.View() + " " + metaStyle.Render(what) + if d := time.Since(m.loadStart); d >= 2*time.Second && !m.loadStart.IsZero() { + line += metaStyle.Render(" " + k8s.Duration(d)) + } + return line +}