diff --git a/plugins/k8s/.apm/.gitkeep b/plugins/k8s/.apm/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/plugins/k8s/.apm/skills/k8s-diagnose/SKILL.md b/plugins/k8s/.apm/skills/k8s-diagnose/SKILL.md new file mode 100644 index 0000000..29349d6 --- /dev/null +++ b/plugins/k8s/.apm/skills/k8s-diagnose/SKILL.md @@ -0,0 +1,92 @@ +--- +name: k8s-diagnose +description: > + Use when a Kubernetes workload is unhealthy — pods not Ready, crash-looping or Pending — or + `flux-diagnose` hands over a pod problem. Read-only kubectl triage. Not Flux reconcile or + source status -> `flux-diagnose`. Not app code bugs -> `diagnose`. +compatibility: Requires kubectl and a kubeconfig the caller supplies, exported or as a path, + bound to the built-in view ClusterRole or a wider read-only role. +allowed-tools: Bash Read +metadata: + category: k8s + version: "0.1.0" + source_keys: + - adr-0032-action-tiers + - delivery-guard-kubectl-allowlist +--- + +## Gotchas + +- `The connection to the server localhost:8080 was refused` means kubectl found no kubeconfig, + not that a cluster is down. Never pick credentials yourself: no `--kubeconfig`, `--context`, + `--as` or `--token`, no `kubectl config use-context`, no filesystem search. +- The `view` role reads no Secrets, nodes, PersistentVolumes or StorageClasses. A Forbidden there + is a gap to report, not a reason to retry another way. +- `describe`, `-o yaml` and logs print inline env values and whatever the app logs. Quote only the + lines that prove a finding and redact anything that looks like a credential. + +## Command tiers + +Run only the Read row. Anything else, listed or not, goes back to the caller as a +recommendation. + +| Tier | Commands | +|---|---| +| Read | `kubectl auth can-i`, `api-resources`, `explain`; `get` and `describe` on any kind but Secrets (`-o wide`, `-o jsonpath`); `logs` (`--previous`, `--tail`, `-c`, `--all-containers`); `events --for`; `top pod` when the metrics API is served | +| Propose | None: the caller opens the fix PR | +| Apply-by-merge | The fix itself: a manifest change in the repo, applied by Flux after an approved merge | +| Odd job | None: `flux reconcile` is HITL-only | +| Never | `apply`, `create`, `delete`, `edit`, `patch`, `label`, `annotate`, `scale`, `set`, `rollout restart`, `rollout undo`, `cordon`, `drain`, `taint`, `exec`, `attach`, `port-forward`, `cp`, `debug`, `proxy`, live `diff`; `get secret -o …`, `describe secret`, `get --raw` on Secrets, `config view --raw` | + +## Step 1 — Check access + +No namespace given → stop and report `need a namespace`, so the caller can supply one; never +sweep `--all-namespaces`. + +Run every command in the environment the caller gave. Given a kubeconfig path, prefix each command +with `KUBECONFIG=`: an `export` does not carry between shell calls. + +Run `kubectl auth can-i list pods -n `: + +- `yes` → continue. +- `no` → stop and report `rbac gap: cannot list pods in `. +- Any connection, certificate or `Unauthorized` error, or no kubeconfig → stop and report + `no cluster access: `. + +A later Forbidden does not stop the run; record it under Gaps. + +## Step 2 — Resolve the target to pods + +- **Pod** → that pod. +- **Workload** (Deployment, StatefulSet, DaemonSet, Job) → + `kubectl describe / -n `, then `kubectl get pods -n -l '' -o wide` + with `` copied verbatim from the describe output's `Selector:` line, never rebuilt + from `matchLabels`, which drops `matchExpressions`. +- **Namespace** → `kubectl get pods -n -o wide` and + `kubectl get deploy,sts,ds,job,pvc,svc -n `. + +A pod is unhealthy when its phase is not `Running` or `Succeeded`, its READY count is short, or +its restart count is climbing. Target not found → a finding; if the repo should create it, Flux +likely never applied it: hand to `flux-diagnose`. + +## Step 3 — Triage each unhealthy pod + +If any pod is unhealthy, read `references/symptoms.md`: run its baseline commands on each +unhealthy pod, then follow its symptom row. + +## Step 4 — Check storage and Services + +If the target's scope holds a PVC or a Service, read `references/symptoms.md` Gotchas and +§Storage and Services: a PVC not `Bound` or a Service with no ready endpoints is a finding. + +## Step 5 — Report + +```text +k8s-diagnose: in — +- — evidence: `` +Likely cause: +Gaps: +``` + +Never apply a fix; name the manifest change for the caller's PR. When the +cause sits in the Flux layer, end with `hand to flux-diagnose: `. diff --git a/plugins/k8s/.apm/skills/k8s-diagnose/references/sources.md b/plugins/k8s/.apm/skills/k8s-diagnose/references/sources.md new file mode 100644 index 0000000..f9c0781 --- /dev/null +++ b/plugins/k8s/.apm/skills/k8s-diagnose/references/sources.md @@ -0,0 +1,19 @@ +# Sources + +## adr-0032-action-tiers + +- **URL:** (repo decision record — not a plugin research corpus entry) +- **Description:** The five action tiers (Read, Propose, Apply-by-merge, Odd job, Never), the `view`-ClusterRole kubeconfig that excludes Secrets, and the rule that every infrastructure change applies by approved merge. Grounds the tier table, the RBAC gaps, and "never apply a fix". +- **Research doc:** none — repo decision record, not a plugin research corpus entry +- **Basis:** docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md +- **Contributing files:** SKILL.md, references/symptoms.md +- **Status:** `extracted` + +## delivery-guard-kubectl-allowlist + +- **URL:** (repo code — not a plugin research corpus entry) +- **Description:** The delivery guard hook's `kubectl` read-verb allowlist and its Secret denials (`get secret -o`, `get --raw` on Secrets, `config view --raw`, live `diff`). Every command the skill names stays inside it. +- **Research doc:** none — repo code, not a plugin research corpus entry +- **Basis:** plugins/delivery/.apm/hooks/guard.py +- **Contributing files:** SKILL.md, references/symptoms.md +- **Status:** `extracted` diff --git a/plugins/k8s/.apm/skills/k8s-diagnose/references/symptoms.md b/plugins/k8s/.apm/skills/k8s-diagnose/references/symptoms.md new file mode 100644 index 0000000..819ffc8 --- /dev/null +++ b/plugins/k8s/.apm/skills/k8s-diagnose/references/symptoms.md @@ -0,0 +1,60 @@ +--- +source_keys: + - adr-0032-action-tiers + - delivery-guard-kubectl-allowlist +--- + +# Symptoms, evidence and likely causes + +Every command here is Read tier. `

` is the pod, `` the container, `` the namespace. Keep +log reads short: `--tail=50` unless the error is further back. + +## Gotchas + +- On a crash-looping pod, plain `kubectl logs` shows the fresh container, which has often printed + nothing yet. The crash is in `--previous`. +- Events expire (one hour by default), so "no events" does not mean nothing happened. A + container's `lastState` survives and is the durable record. + +## Selectors + +The `Selector:` line of `kubectl describe` on a workload already renders `matchExpressions` in +set-based form (`tier in (web,api)`, `!canary`). A selector rebuilt from `matchLabels` alone drops +those terms and matches too many pods, so copy the line verbatim. + +## Baseline for every unhealthy pod + +```bash +kubectl describe pod

-n +kubectl get pod

-n -o jsonpath='{range .status.initContainerStatuses[*]}init/{.name} ready={.ready} restarts={.restartCount} waiting={.state.waiting.reason} last={.lastState.terminated.reason} exit={.lastState.terminated.exitCode}{"\n"}{end}{range .status.containerStatuses[*]}{.name} ready={.ready} restarts={.restartCount} waiting={.state.waiting.reason} last={.lastState.terminated.reason} exit={.lastState.terminated.exitCode}{"\n"}{end}' +kubectl events -n --for pod/

+``` + +The second prints one status line per container. Its `waiting=` and `last=` reasons, with the +pod's phase and events, give the symptom. + +## Pod and container symptoms + +| Symptom | Evidence | Likely causes | +|---|---|---| +| `CrashLoopBackOff`, or `last=Error` | `kubectl logs

-n -c --previous --tail=50`; the `exit=` code | exit 1 or 2: the app failed at start (bad config, missing dependency, failed migration). 126/127: command not executable or not found (wrong image or `command:`). 137: killed, see OOMKilled and Liveness kill rows. 143: SIGTERM, a stop the app did not survive | +| `last=OOMKilled` | `kubectl get pod

-n -o jsonpath='{.spec.containers[*].resources}'`; `kubectl top pod

-n --containers` if `kubectl api-resources --api-group=metrics.k8s.io` lists `pods` | Memory limit below the app's working set, or a leak (usage climbs across restarts) | +| Liveness kill: `Unhealthy` events saying `Liveness probe failed`, then restarts with exit 137 | `kubectl get pod

-n -o jsonpath='{.spec.containers[*].livenessProbe}'`; current `kubectl logs

-n -c --tail=50` | Probe path or port does not match the app; `initialDelaySeconds` or `failureThreshold` shorter than the app's start time; app deadlocked | +| `Running` but not Ready: `Readiness probe failed` events | readiness probe spec as above; the container's `ports`; current logs | Probe path or port wrong; a dependency the readiness check calls is down | +| `ImagePullBackOff` or `ErrImagePull` | The `Failed` event's message; `kubectl get pod

-n -o jsonpath='{.spec.imagePullSecrets}'` (names only) | `not found` or `manifest unknown`: wrong image or tag. `unauthorized` or `pull access denied`: missing or wrong pull secret. `i/o timeout` or `dial tcp`: registry unreachable from the node | +| `CreateContainerConfigError` | The `Failed` event names the missing ConfigMap, Secret or key; `kubectl get configmap -n ` for a ConfigMap; `kubectl get sealedsecret -n ` then `kubectl describe sealedsecret -n ` when a SealedSecret should produce the Secret | Object not created yet, wrong name or key, or the SealedSecret failed to unseal (its status says why). Never try to read the Secret itself | +| `Init:…` (`Init:CrashLoopBackOff`, `Init:0/1` stuck) | `kubectl logs

-n -c --previous --tail=50`, or without `--previous` while it is still running | The init container's own failure or wait, usually a dependency it polls | +| `Pending` | The `FailedScheduling` event message | `Insufficient cpu` or `memory`: requests exceed free capacity. `didn't match Pod's node affinity/selector`: selector or affinity names no node. `untolerated taint`: missing toleration. `unbound immediate PersistentVolumeClaims`: see Storage below. Node details are Forbidden under `view`; quote the message instead | +| `ContainerCreating` for minutes | `FailedMount`, `FailedAttachVolume` or `FailedCreatePodSandBox` events | Volume not attachable or still held by another node; a referenced ConfigMap or Secret volume missing; CNI fault on the node | +| `Evicted` or `Failed` with a node-pressure reason | `kubectl get pod

-n -o jsonpath='{.status.reason}: {.status.message}'` | Node ran short of memory or disk; the pod's requests are too low to protect it | +| Job failed: `BackoffLimitExceeded` | `kubectl describe job/ -n `; logs of its newest failed pod, with `--previous` if it restarted in place | The job's own error in those logs | + +No row fits → report the container status line and the newest `Warning` events as findings, with +likely cause `undetermined`. + +## Storage and Services + +| Check | Evidence | Likely causes | +|---|---|---| +| PVC not `Bound` | `kubectl get pvc -n `; `kubectl describe pvc -n ` events | `WaitForFirstConsumer`: normal until a pod using it schedules, so look at that pod. `no persistent volumes available` or `storageclass … not found`: no matching class or volume. `ProvisioningFailed`: the provisioner's message says why. PersistentVolumes and StorageClasses are Forbidden under `view`; report that gap | +| Service with no ready endpoints | `kubectl get svc -n `; `kubectl get endpointslices -n -l kubernetes.io/service-name=`, falling back to `kubectl get endpoints -n ` if EndpointSlices are Forbidden; `kubectl get svc -n -o jsonpath='{.spec.selector}'` against `kubectl get pods -n --show-labels` | Selector matches no pod labels; matching pods exist but none is Ready (triage those pods); `targetPort` names a port the container does not expose | diff --git a/plugins/k8s/apm.yml b/plugins/k8s/apm.yml index 3cefae3..bb34e6d 100644 --- a/plugins/k8s/apm.yml +++ b/plugins/k8s/apm.yml @@ -1,5 +1,5 @@ name: k8s -version: 0.1.0 +version: 0.2.0 description: Skills for read-only diagnosis of workloads on a Kubernetes cluster. author: name: Mortis