Skip to content

feat: add ephemeral debug containers to pods - #55

Merged
zjy365 merged 27 commits into
mainfrom
feat/pod-ephemeral-debug
Oct 22, 2026
Merged

zjy365 merged 27 commits into
mainfrom
feat/pod-ephemeral-debug

Conversation

@zjy365

@zjy365 zjy365 commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

Motivation

Many production pods run minimal or distroless images that ship no shell and no debugging tools. When such a pod misbehaves there is nothing to exec into, and rebuilding the image (or editing the workload spec) just to get a shell is intrusive and triggers rollouts. Kubernetes solves this with ephemeral containers: a temporary container injected into the running pod's namespace for inspection. This PR brings that capability to Aster with kubectl debug semantics — the workload spec is never modified, the owning deployment never rolls, and the debug container is removed together with the pod.

API

New core endpoint:

POST /v1/pods/debug
{
  "contextId": "dev",
  "namespace": "apps",
  "podName": "web",
  "container": {
    "name": "",                      // optional; generated when omitted
    "image": "busybox:1.36",         // required
    "command": ["/bin/sh", "-c"],    // optional
    "args": ["ps aux"],              // optional
    "targetContainerName": "app",    // optional
    "env": [{"name": "TRACE", "value": "1"}]  // optional
  }
}

The handler GETs the current pod, appends one entry to spec.ephemeralContainers, and issues the update through the pods/ephemeralcontainers subresource using the session manager's typed core clients. The response echoes the stored entry (with the resolved generated name).

Defaults (kubectl debug parity)

  • Name: a uniquely generated debugger-<suffix> when omitted, checked against existing ephemeral container names; explicit duplicate names are rejected before the write.
  • Process namespace sharing: via targetContainerName (the mechanism kubectl uses). The pod-level shareProcessNamespace field is immutable after creation, so it is deliberately left untouched.
  • TTY/stdin off: this is an inject-then-inspect action, not an interactive session.
  • Termination message policy: ReadFile, matching kubectl.

Scope is add-only: removing finished ephemeral containers is intentionally out of scope (the API server prunes nothing, but entries are harmless and die with the pod).

Input caps mirror the exec endpoint philosophy and are enforced twice — at the RPC boundary (validate.go) and again in the service: bounded argv (32 entries, 4096 chars each), bounded env (64 entries), and the standard name/image/namespace length caps. API server errors keep their shape (404 for missing pods, 400 for subresource rejections like an unknown target container).

Desktop UI

  • New "Add debug container" action on the pod detail header (inline and in the More menu).
  • Dialog with: image (required, defaults to busybox:1.36), optional name, optional command (quoted arguments supported, unquoted commas/spaces separate arguments), and a target container picker fed by the pod's spec containers.
  • Submitting is the confirmation; the dialog states that the owning workload template is not modified and the container is removed with the pod. Failures stay inline in the open dialog.
  • On success the injection lands in the session operation journal (same format as other writes) and the pod detail refreshes; the containers overview gains an "Ephemeral debug containers" block with a debug badge so injected entries are visible at a glance.
  • Wired through the DesktopApi allowlist chain exactly like the other pod actions: shared/types.ts → desktop-tauri.ts → new pods_debug Tauri command → sidecar HTTP.

Testing

  • Go (fake clientset, following the existing manager test patterns): append semantics (existing ephemeral containers survive), generated unique naming, explicit-name duplicate rejection, target/env/command passthrough, stdin/tty off, regular pod spec untouched, the update actually hitting the ephemeralcontainers subresource, missing pod (404 shape) and subresource rejection (Invalid shape).
  • RPC: endpoint happy path and validation matrix (missing/oversized fields, argv and env caps).
  • Frontend: unit tests for the dialog's command parsing and the pod YAML ephemeralContainers projection; a renderer smoke test covers the full dialog flow (submit, request payload, journal + overview surfacing, rejected injection error) with overlap/overflow inspection.
  • Verified: go -C core test -race ./..., go -C core vet ./..., pnpm typecheck, pnpm test, pnpm build, cargo test + cargo clippy, and the full renderer Playwright smoke suite (63 passed).

Notes

  • Per the repo's shell-change requirement, a manual pnpm dev run against a real kubeconfig was not performed in this environment; the Tauri command is a thin authenticated proxy identical in shape to pods_exec/pods_portforward_start, and the renderer flow is covered by the smoke suite.
  • The dialog exposes image/name/command/target; the API additionally accepts args and env for future use (e.g. a CLI or richer form).

Follow-ups

  • Surfacing ephemeral container status (waiting/running/terminated) in the pod detail once the API server reports it.
  • An "exec into debug container" affordance once an interactive terminal surface exists.

One-click handoff from the context picker to the user's own terminal:
the shell stages a single-context kubeconfig in a 0600 temp file and
opens the user's terminal (iTerm2, WezTerm, Kitty, Ghostty, then
Terminal.app) with KUBECONFIG pointing at it, a banner naming the
context, and an interactive shell.

- core: POST /v1/contexts/export narrows the merged kubeconfig to
  exactly the requested context (same first-wins precedence as listing
  and connecting) and returns the YAML to the shell only.
- shell: new terminal module owns detection (bundle existence plus CLI
  binaries on PATH), staging (0700 dir, 0600 files, random names),
  exit cleanup of registered files, and a startup sweep of leftovers
  from crashed runs. Launches are fire-and-forget with null stdio; no
  terminal output flows back and no kubectl command is wrapped.
- renderer: "Open kubectl" action in the picker footer, disabled with
  an explanatory tooltip when no local kubectl is found (probed via
  `kubectl version --client`; aster never installs or downloads one).
  Only the context id crosses renderer -> shell; kubeconfig contents
  never reach the renderer and are never logged.

macOS only in this release; Windows and Linux are out of scope.
Upgrading a release required typing a chart version blind. The core now
serves GET /v1/helm/chart-versions: it fetches the repository index
through the helm getters (credentials from the user's repositories.yaml,
anonymous for unconfigured URLs, matching the upgrade path), parses the
entries for the chart and returns the newest 100 versions in descending
semver order with version, appVersion, created and description. Unknown
charts answer with the not-found envelope; unreachable or invalid
repositories and indexes return clear errors; the lookup is stateless.

The upgrade dialog's version input becomes a combobox over that list:
keyboard-first (arrows move/open, Enter picks, Escape dismisses the list,
typing filters), showing version, appVersion and age. When the list
cannot be loaded the field degrades to manual entry with a notice, so an
offline or private repository never blocks an upgrade.
Cordoning a node for maintenance previously meant hand-editing
spec.unschedulable, and safely emptying it meant a terminal outside the
app. The core now owns both operations:

- POST /v1/nodes/cordon flips spec.unschedulable through a strategic
  merge patch, reporting whether the node actually changed.
- POST /v1/nodes/drain cordons first (kubectl parity), classifies every
  pod against the kubectl drain blockers, then evicts through the
  eviction API so PodDisruptionBudgets are enforced server-side;
  progress streams as ndjson (per-pod evicting/evicted/failed/skipped
  events, PDB-blocked retries with capped backoff, final summary).

The desktop shell forwards the endpoints through the DesktopApi
allowlist and the node detail page gains Cordon/Uncordon (confirmed
toggle driven by the live YAML) and a Drain dialog with the four drain
options, streaming progress, and journal entries.
Select two or more kubeconfig contexts in the cluster picker and the
resource table shows one kind + namespace scope merged across all of
them, with a Cluster column marking each row's source. The renderer
fans out ordinary single-context list requests and merges the pages
client-side; no changes to the Go sidecar or the Rust shell.

- ContextPicker gains a multi-select mode (checkboxes, aggregate
  indication, capped at 8 clusters) beside the unchanged radio flow.
- useAggregateResourceList: snapshot-only fan-out per (cluster,
  namespace) cell, per-cluster degradation with retry, load-more
  continuing every cluster's next page.
- Row identity prefixes the uid with the context id; sourceContextId
  routes detail, diagnostics, and mutations back to the row's cluster.
- Namespace inventory unions the selected clusters; the same scope
  applies to each (missing namespaces simply return no rows).
- Single-cluster behavior is unchanged: one selected context takes the
  exact previous code path.
The active port-forward list lived only in the renderer's memory, so a
reload lost sight of forwards the sidecar still owned and there was no
single surface to review or reclaim them. The sidecar is now the source
of truth for listing.

- core: read-only GET /v1/portforwards (optional contextId filter) that
  exposes the existing forward registry as sessions with id, contextId,
  namespace, resourceRef (kind/name), localPort, targetPort, startedAt
  and the resolved backing pod. Start/stop semantics are unchanged.
- desktop: the session read is wired through the DesktopApi allowlist
  chain (shared types, Tauri invoke adapter, Rust command).
- renderer: a toolbar badge counts active forwards across contexts and
  opens a panel listing every session (cluster, resource, local->target
  port, age, status) with per-row Stop and a client-side Stop all that
  reuses the existing stop endpoint. The panel reconciles the sidecar
  list with the renderer registry: the server wins for known ids, and
  rows only the sidecar knows (e.g. after renderer state loss) render
  read-only with a stop. The per-resource Ports tab flow is unchanged.
Resource tables showed a fixed column set per kind, but different teams
watch different fields, and for custom resources the useful fields depend
entirely on the CRD. This lets each operator choose which columns a kind's
table shows and in what order, persisted per kind.

- Column picker popover from the resource pane heading: checkbox list of
  every offered column, per-row up/down buttons, and a keyboard-first
  flow (Space toggles, ArrowUp/ArrowDown reorders, Escape closes) in line
  with the rest of the table's roving-tabindex UX.
- Per-kind persistence in localStorage (ordered visible ids) following
  the existing renderer-side preference patterns; Reset to default drops
  the kind's entry. Unknown kinds and unknown stored ids fall back to
  the default set, and the table never renders empty.
- Extra columns beyond the fixed set: a curated registry of fields the
  core already projects (images, addresses, ports, RBAC summaries, ...)
  offered when loaded rows carry data, plus cheap client-side discovery
  of scalar spec/status fields from the currently loaded rows (capped,
  deduped, frequency-ranked). Missing values render empty, never error.
- The virtualized table renders the dynamic column set through one grid
  template; summed track floors become a min-width so many columns keep
  horizontal scrolling working with the header tracking the viewport.

Renderer-only: no core/ or shell changes. Covered by unit tests
(persistence, derivation/dedup/cap, ordering) and a Playwright smoke
test (visibility, reorder, per-kind isolation, persistence across
reload, horizontal scroll alignment, reset).
Many production pods run minimal or distroless images without a shell, so
there is nothing to exec into when something goes wrong. Add a
kubectl-debug-style action that injects an ephemeral debug container into a
running pod through the pods/ephemeralcontainers subresource: the workload
spec is never modified, the owning deployment never rolls, and the debug
container disappears with the pod.

- Core: POST /v1/pods/debug builds the ephemeral container entry with
  kubectl-style defaults (generated unique "debugger-" name when omitted,
  process-namespace sharing via targetContainer, stdin/tty off) and issues
  the subresource update through the session manager's typed core clients.
  Input caps mirror the exec endpoint (bounded argv, env, name/image
  lengths) at both the RPC boundary and the service.
- Desktop: "Add debug container" action on the pod detail page opens a
  dialog (image defaults to busybox:1.36; optional name, command, target
  container). Successful injections land in the operation journal, refresh
  the pod detail, and surface an "Ephemeral debug containers" section under
  the containers overview. Wired through the DesktopApi allowlist and the
  Tauri shell like the other pod actions.

Tests: Go unit tests with the fake clientset cover append semantics,
generated naming, target/env passthrough, duplicate names, missing pods and
subresource rejection; rpc tests cover the endpoint and validation;
renderer smoke suite covers the dialog flow end to end.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Deploying aster with  Cloudflare Pages  Cloudflare Pages

Latest commit: d45acac
Status: ✅  Deploy successful!
Preview URL: https://1af1834b.aster-7wc.pages.dev
Branch Preview URL: https://feat-pod-ephemeral-debug.aster-7wc.pages.dev

View logs

@zjy365

zjy365 commented Oct 17, 2026

Copy link
Copy Markdown
Owner Author

Initial review notes — subresource semantics verified (GET → append → UpdateEphemeralContainers, collision handling for explicit names, kubectl-style generated suffixes, argv/env caps at the service layer). One small follow-up: there is no retry on a resourceVersion conflict between the GET and the subresource update, so a pod that changes shape mid-flight fails the whole request. kubectl debug retries the read-modify-write on conflict. A bounded retry loop (2–3 attempts) around the GET+append+update would make concurrent edits (e.g. another ephemeral container being added) benign. Not blocking — the error message already propagates cleanly.

zjy365 added 20 commits October 22, 2026 16:27
…w' into HEAD

# Conflicts:
#	apps/desktop/src/renderer/views/ContextPicker.tsx
# Conflicts:
#	apps/desktop/src/renderer/App.tsx
#	apps/desktop/tests/renderer-smoke.spec.ts
…into HEAD

# Conflicts:
#	apps/desktop/src-tauri/src/lib.rs
#	apps/desktop/src/renderer/lib/desktop-tauri.ts
#	apps/desktop/src/shared/types.ts
#	apps/desktop/tests/live/shim.ts
#	apps/desktop/tests/renderer-smoke.spec.ts
#	core/internal/resources/types.go
#	core/internal/rpc/server.go
…HEAD

# Conflicts:
#	apps/desktop/src/renderer/App.tsx
#	apps/desktop/src/renderer/components/ResourceTable.tsx
#	apps/desktop/tests/renderer-smoke.spec.ts
# Conflicts:
#	apps/desktop/src/renderer/App.tsx
#	apps/desktop/src/renderer/detail/resource-actions.ts
#	apps/desktop/src/renderer/hooks/useMutation.ts
#	core/internal/rpc/server_test.go
…HEAD

# Conflicts:
#	apps/desktop/src/renderer/detail/ResourceDetailView.tsx
@zjy365
zjy365 merged commit 24e9614 into main Oct 22, 2026
1 of 2 checks passed
@zjy365
zjy365 deleted the feat/pod-ephemeral-debug branch November 12, 2026 03:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant