8000 Add production incident intelligence and evidence-aware alerts by abahmed · Pull Request #516 · abahmed/kwatch · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7

- name: Initialize CodeQL
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4
uses: github/codeql-action/init@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4
uses: github/codeql-action/analyze@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4
with:
category: "/language:${{matrix.language}}"
2 changes: 1 addition & 1 deletion .github/workflows/scorecard.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ jobs:
publish_results: true

- name: Upload Scorecard results
uses: github/codeql-action/upload-sarif@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4
uses: github/codeql-action/upload-sarif@1c5b675653bb5c22dbe9b12b556ec555138e09fd # v4
with:
sarif_file: scorecard-results.sarif
1 change: 0 additions & 1 deletion api/v1alpha1/types.go
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ type KwatchConfigSpec struct {
IngressMonitor MonitorConfig `json:"ingressMonitor,omitempty"`
NetworkPolicyMonitor MonitorConfig `json:"networkPolicyMonitor,omitempty"`
ClusterResourceMonitor MonitorConfig `json:"clusterResourceMonitor,omitempty"`
RuntimeMetricsMonitor MonitorConfig `json:"runtimeMetricsMonitor,omitempty"`
KubeletTelemetryMonitor MonitorConfig `json:"kubeletTelemetryMonitor,omitempty"`
Crd MonitorConfig `json:"crd,omitempty"`
SmartGrouping MonitorConfig `json:"smartGrouping,omitempty"`
Expand Down
1 change: 0 additions & 1 deletion api/v1alpha1/zz_generated.deepcopy.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,6 @@ func deepCopySpecMaps(in, out *KwatchConfigSpec) {
out.IngressMonitor = deepCopyMonitorConfig(in.IngressMonitor)
out.NetworkPolicyMonitor = deepCopyMonitorConfig(in.NetworkPolicyMonitor)
out.ClusterResourceMonitor = deepCopyMonitorConfig(in.ClusterResourceMonitor)
out.RuntimeMetricsMonitor = deepCopyMonitorConfig(in.RuntimeMetricsMonitor)
out.ActiveProbeMonitor = deepCopyMonitorConfig(in.ActiveProbeMonitor)
out.KubeletTelemetryMonitor = deepCopyMonitorConfig(in.KubeletTelemetryMonitor)
out.Crd = deepCopyMonitorConfig(in.Crd)
Expand Down
5 changes: 2 additions & 3 deletions deploy/chart/templates/kwatchconfig-crd.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ spec:
adaptiveThresholds:
type: boolean
includeEvents:
description: >-
Deprecated and ignored. Kwatch analyzes events internally.
type: boolean
includeLogs:
type: boolean
Expand Down Expand Up @@ -246,9 +248,6 @@ spec:
clusterResourceMonitor:
type: object
x-kubernetes-preserve-unknown-fields: true
runtimeMetricsMonitor:
type: object
x-kubernetes-preserve-unknown-fields: true
tlsMonitor:
type: object
properties:
Expand Down
3 changes: 0 additions & 3 deletions deploy/chart/templates/rbac.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ rules:
- apiGroups: [""]
resources: ["events", "nodes", "nodes/proxy", "pods", "pods/log", "pods/proxy", "persistentvolumeclaims", "configmaps", "secrets", "resourcequotas", "limitranges", "endpoints"]
verbs: ["get", "watch", "list"]
- apiGroups: ["metrics.k8s.io"]
resources: ["pods"]
verbs: ["get", "watch", "list"]
- nonResourceURLs: ["/readyz", "/readyz/*"]
verbs: ["get"]
- apiGroups: [""]
Expand Down
8 changes: 1 addition & 7 deletions deploy/config-catalog.meta.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ workers|Performance|Number of Kubernetes work queues processed in parallel.|acti
resyncSeconds|Performance|Periodic safety resync interval in seconds; zero keeps event-driven mode.|active|
maxRecentLogLines|Alerts|Maximum recent log lines attached to an incident.|active|
containerRestartThreshold|Alerts|Alert when a container reaches this cumulative restart count; zero disables it.|active|
includeEvents|Alerts|Include recent Kubernetes events in incident messages.|active|
includeLogs|Alerts|Include recent container logs in incident messages.|active|
message.includePrivateLogAddresses|Alerts|Keep private application addresses visible in evidence; credentials remain redacted.|active|
namespaces|Scope|Comma-separated namespaces to watch; leave empty to watch every namespace.|active|
namespaceSelector|Scope|Kubernetes label selector used to choose namespaces.|active|
reasons|Scope|Comma-separated event reasons to allow or exclude with a leading !.|active|
includeEvents|Alerts|Deprecated compatibility field; Kwatch analyzes events internally.|deprecated|
ignoreFailedGracefulShutdown|Noise reduction|Ignore forceful container termination during an intentional shutdown.|active|
ignoreDisruptionTerminations|Noise reduction|Ignore pods being deliberately evicted, preempted, or disrupted.|active|
adaptiveThresholds|Noise reduction|Add bounded grace during normal partial rollouts.|active|
Expand Down Expand Up @@ -73,12 +73,6 @@ nodeResourceMonitor.filesystemWarningPercent|Monitors|Node filesystem usage warn
nodeResourceMonitor.filesystemCriticalPercent|Monitors|Node filesystem usage critical threshold.|active|
nodeResourceMonitor.inodeWarningPercent|Monitors|Node inode usage warning threshold.|active|
nodeResourceMonitor.inodeCriticalPercent|Monitors|Node inode usage critical threshold.|active|
runtimeMetricsMonitor.enabled|Monitors|Use metrics.k8s.io when available for workload usage diagnostics.|active|
runtimeMetricsMonitor.intervalSeconds|Monitors|Seconds between runtime metrics checks.|active|
runtimeMetricsMonitor.memoryWarningPercent|Monitors|Memory usage warning percentage when metrics.k8s.io is available.|active|
runtimeMetricsMonitor.memoryCriticalPercent|Monitors|Memory usage critical percentage when metrics.k8s.io is available.|active|
runtimeMetricsMonitor.cpuWarningPercent|Monitors|CPU usage warning percentage when metrics.k8s.io is available.|active|
runtimeMetricsMonitor.cpuCriticalPercent|Monitors|CPU usage critical percentage when metrics.k8s.io is available.|active|
clusterAutoscalerMonitor.enabled|Monitors|Watch built-in cluster-autoscaler evidence from Kubernetes resources and events.|active|
tlsMonitor.threshold|Monitors|Days before certificate expiry to warn.|active|
tlsMonitor.criticalThreshold|Monitors|Days before certificate expiry for a high-severity alert.|active|
Expand Down
8 changes: 1 addition & 7 deletions deploy/config-catalog.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ workers|integer|1|Performance|Number of Kubernetes work queues processed in para
resyncSeconds|integer|0|Performance|Periodic safety resync interval in seconds; zero keeps event-driven mode.|active|
maxRecentLogLines|integer|50|Alerts|Maximum recent log lines attached to an incident.|active|
containerRestartThreshold|integer|0|Alerts|Alert when a container reaches this cumulative restart count; zero disables it.|active|
includeEvents|boolean|true|Alerts|Include recent Kubernetes events in incident messages.|active|
includeLogs|boolean|true|Alerts|Include recent container logs in incident messages.|active|
message.includePrivateLogAddresses|boolean|false|Alerts|Keep private application addresses visible in evidence; credentials remain redacted.|active|
namespaces|list|all|Scope|Comma-separated namespaces to watch; leave empty to watch every namespace.|active|
Expand Down Expand Up @@ -72,12 +71,6 @@ nodeResourceMonitor.filesystemWarningPercent|float|90|Monitors|Node filesystem u
nodeResourceMonitor.filesystemCriticalPercent|float|95|Monitors|Node filesystem usage critical threshold.|active|
nodeResourceMonitor.inodeWarningPercent|float|90|Monitors|Node inode usage warning threshold.|active|
nodeResourceMonitor.inodeCriticalPercent|float|95|Monitors|Node inode usage critical threshold.|active|
runtimeMetricsMonitor.enabled|boolean|false|Monitors|Use metrics.k8s.io when available for workload usage diagnostics.|active|
runtimeMetricsMonitor.intervalSeconds|integer|60|Monitors|Seconds between runtime metrics checks.|active|
runtimeMetricsMonitor.memoryWarningPercent|integer|90|Monitors|Memory usage warning percentage when metrics.k8s.io is available.|active|
runtimeMetricsMonitor.memoryCriticalPercent|integer|95|Monitors|Memory usage critical percentage when metrics.k8s.io is available.|active|
runtimeMetricsMonitor.cpuWarningPercent|integer|90|Monitors|CPU usage warning percentage when metrics.k8s.io is available.|active|
runtimeMetricsMonitor.cpuCriticalPercent|integer|100|Monitors|CPU usage critical percentage when metrics.k8s.io is available.|active|
clusterAutoscalerMonitor.enabled|boolean|true|Monitors|Watch built-in cluster-autoscaler evidence from Kubernetes resources and events.|active|
tlsMonitor.threshold|integer|30|Monitors|Days before certificate expiry to warn.|active|
tlsMonitor.criticalThreshold|integer|3|Monitors|Days before certificate expiry for a high-severity alert.|active|
Expand Down Expand Up @@ -146,3 +139,4 @@ ignoreNodeReasons|list|legacy|Compatibility|Legacy node-reason suppression field
ignoreNodeMessages|list|legacy|Compatibility|Legacy node-message suppression field.|deprecated|silences
heartbeatMonitor.url|string|empty|Security|External dead-man heartbeat URL; stored only through a mounted Secret.|secret|
healthCheck.diagnosticsToken|string|empty|Security|Bearer token for diagnostic endpoints; stored only through a mounted Secret.|secret|
includeEvents|boolean|empty|Alerts|Deprecated compatibility field; Kwatch analyzes events internally.|deprecated|
1 change: 0 additions & 1 deletion deploy/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ stringData:
- "<optional_substring>"
namespaceSelector:
"<label_selector>" # k8s label selector, mutually exclusive with namespaces
includeEvents: <boolean> # include events section in alerts (default true)
includeLogs: <boolean> # include logs section in alerts (default true)

# ── Severity ──────────────────────────────────────────
Expand Down
5 changes: 2 additions & 3 deletions deploy/crd.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ spec:
adaptiveThresholds:
type: boolean
includeEvents:
description: >-
Deprecated and ignored. Kwatch analyzes events internally.
type: boolean
includeLogs:
type: boolean
Expand Down Expand Up @@ -246,9 +248,6 @@ spec:
clusterResourceMonitor:
type: object
x-kubernetes-preserve-unknown-fields: true
runtimeMetricsMonitor:
type: object
x-kubernetes-preserve-unknown-fields: true
tlsMonitor:
type: object
properties:
Expand Down
3 changes: 0 additions & 3 deletions deploy/deploy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ rules:
- apiGroups: [""]
resources: ["events", "nodes", "nodes/proxy", "pods", "pods/log", "pods/proxy", "persistentvolumeclaims", "configmaps", "secrets", "resourcequotas", "limitranges", "endpoints"]
verbs: ["get", "watch", "list"]
- apiGroups: ["metrics.k8s.io"]
resources: ["pods"]
verbs: ["get", "watch", "list"]
- nonResourceURLs: ["/readyz", "/readyz/*"]
verbs: ["get"]
- apiGroups: [""]
Expand Down
39 changes: 19 additions & 20 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ talks to the outside world.
| `app.logFormatter` | Log format: `text` (default) or `json` |
| `app.insecureSkipTLSVerify` | 🔓 Skip TLS verification on outbound HTTP (default: false) |
| `app.caBundlePath` | 📜 Path to a PEM CA bundle for outbound HTTP |
| `includeEvents` | 📋 Include K8s events in alerts (default: true). At most the 40 most recent are attached; older ones are summarised as `... N earlier event(s) omitted`. A churning pod can accumulate hundreds, and an unbounded list pushes the message past the chat provider's size limits, which loses the whole alert rather than just the surplus |
| `includeEvents` | ⚠️ Deprecated compatibility field; Kwatch always analyzes events internally. Use the incident message content and `includeLogs` for notification rendering. |
| `includeLogs` | 📋 Include container logs in alerts (default: true) |
| `message.includePrivateLogAddresses` | 🌐 Keep private application addresses visible in evidence; credentials remain redacted (default: false) |

Expand Down Expand Up @@ -193,9 +193,9 @@ workloads. The ClusterRole covers:

Watched resources need only `get`, `list`, and `watch`. Optional monitors expose
`unavailable` or `rbacDenied` when an API is not served or a permission is
missing; the controller continues with the remaining monitors. Metrics Server,
Prometheus, a service mesh, and a cloud-provider API are not required for core
Kubernetes object monitoring.
missing; the controller continues with the remaining monitors. Metrics API
evidence, Prometheus, a service mesh, and a cloud-provider API are not required
for core Kubernetes object monitoring.

The `/security` capability audit is scoped to the monitors enabled in the
loaded configuration: disabled rollout, TLS, storage, networking, admission,
Expand Down Expand Up @@ -553,8 +553,17 @@ no Agent or Prometheus installation is required.
| `kubeletTelemetryMonitor.runtimeErrorRateWarning` | ⚠️ Kubelet runtime errors/sec warning (default: 1) |
| `kubeletTelemetryMonitor.runtimeErrorRateCritical` | 🚨 Kubelet runtime errors/sec critical (default: 10) |

`runtimeMetricsMonitor` is an optional legacy Metrics Server integration and is
disabled by default. It is not required for standalone CPU/memory monitoring.
### 📈 Metrics API evidence

Kwatch automatically checks the optional Kubernetes Metrics API when diagnosing
HPA and metrics-related failures. It inspects the
`v1beta1.metrics.k8s.io` APIService and its backing Service EndpointSlices to
distinguish an unregistered API, an unavailable service, and an API that is
currently healthy.

There is no `runtimeMetricsMonitor` configuration. If the Metrics API is
missing or unavailable, Kwatch records that as bounded diagnostic evidence; it
does not create a synthetic incident.

For dynamically watched CRDs, `crd.failureConditions` can override the default
failure rules. Use entries such as `Ready=False`, `Available=Unknown`,
Expand All @@ -570,18 +579,8 @@ point below the configured critical threshold; the critical threshold itself
never changes. Baselines are persisted when telemetry persistence is enabled
and are discarded after the normal stale-state window.

The optional `runtimeMetricsMonitor` requires an additional `metrics.k8s.io`
read permission and a Metrics Server; the shipped RBAC deliberately does not
grant that unused permission by default.

| Parameter | What it does |
|:---|---|
| `runtimeMetricsMonitor.enabled` | 📊 Use Metrics Server data for workload usage diagnostics (default: false) |
| `runtimeMetricsMonitor.intervalSeconds` | ⏱️ Seconds between Metrics Server checks (default: 60) |
| `runtimeMetricsMonitor.memoryWarningPercent` | ⚠️ Memory usage warning percentage (default: 90) |
| `runtimeMetricsMonitor.memoryCriticalPercent` | 🚨 Memory usage critical percentage (default: 95) |
| `runtimeMetricsMonitor.cpuWarningPercent` | ⚠️ CPU usage warning percentage (default: 90) |
| `runtimeMetricsMonitor.cpuCriticalPercent` | 🚨 CPU usage critical percentage (default: 100) |
The Metrics API evidence above is collected automatically when the optional API
is present. It does not require a separate monitor or configuration block.

### 💥 OOM Pattern Monitor

Expand Down Expand Up @@ -676,8 +675,8 @@ silences:
```

The match is a case-sensitive substring of an attached Event message. It
suppresses the whole incident; `includeEvents` only controls whether matching
or non-matching Events are rendered in the notification.
suppresses the whole incident; event evidence is analyzed internally and is
rendered according to the provider's incident format.

### 🚫 Inhibition — no double alerts

Expand Down
4 changes: 2 additions & 2 deletions docs/contributor-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ and engine, but each owns one analysis concern.

Supporting monitors follow the same rule. `internal/probe` separates target
configuration, lifecycle dispatch, graph linking, protocol probes, automatic
Service discovery, and failure-state transitions. `internal/metricsapi`
separates construction, lifecycle, API collection, and threshold policy.
Service discovery, and failure-state transitions. Metrics API evidence is
collected by the application and analyzed through `internal/insight`.
`internal/statuswatch` separates construction, configuration compilation,
informer lifecycle, static processing, CRD handling, and admission handling.
`internal/resource` separates lifecycle, filesystem signals, and node
Expand Down
2 changes: 1 addition & 1 deletion docs/feature-permissions.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Use this matrix when disabling features for a least-privilege deployment.
| Network and admission | Services, Endpoints, EndpointSlices, Ingresses, NetworkPolicies, webhook and admission policy resources | get/list/watch |
| Storage and PVC | PersistentVolumeClaims, PersistentVolumes, StorageClasses, VolumeAttachments, CSI drivers, snapshots | get/list/watch |
| Kubelet and logs | `nodes/proxy`, `pods/log`, `pods/proxy` | get/list/watch |
| Optional metrics | `metrics.k8s.io/pods` | get/list/watch |
| Metrics API evidence | APIService `v1beta1.metrics.k8s.io`, Services, EndpointSlices | get/list/watch |
| RBAC health | SelfSubjectAccessReviews | create |
| CRD overlay | KwatchConfig and CustomResourceDefinitions | get/list/watch |
| Persistence and election | Namespaced ConfigMaps and Leases | create/get/update/patch/watch |
Expand Down
8 changes: 5 additions & 3 deletions docs/kubernetes-coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,11 @@ the categories below intentionally use different signal sources.
mount/unmount and provisioning failures continue to come from Kubernetes
Warning Events and PVC/PV status.
- Runtime metrics: built-in kubelet Summary API collection of actual
per-container CPU and memory usage against declared limits. The optional
Metrics API integration is retained for users who already run Metrics Server,
but is disabled by default and is not required.
per-container CPU and memory usage against declared limits.
- Metrics API evidence: HPA and metrics-related failures are enriched by the
optional `v1beta1.metrics.k8s.io` APIService and backing EndpointSlice health.
Missing or unavailable Metrics APIs remain capability evidence, not synthetic
incidents; there is no separate Metrics Server monitor configuration.
- Active probes: opt-in HTTP, TCP, and DNS checks for explicitly configured
targets through `activeProbeMonitor`, with consecutive-failure and recovery
thresholds. Targets are never inferred automatically from Services.
Expand Down
23 changes: 19 additions & 4 deletions internal/alert/email/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,12 @@ func (e *Email) SendMessage(ctx context.Context, s string) error {
func (e *Email) buildMessageSubjectAndBody(
ev *event.Event) (string, string) {
subject := "⛑ Kwatch alert"
if ev.ContainerName != "" {
subject = fmt.Sprintf("⛑ Kwatch detected a crash in pod %s", ev.ContainerName)
if narrative := strings.TrimSpace(ev.Narrative); narrative != "" {
subject = emailFirstLine(narrative, 150)
} else if ev.ContainerName != "" {
subject = fmt.Sprintf(
"⛑ Kwatch detected a crash in pod %s", ev.ContainerName,
)
} else if ev.PodName != "" {
subject = fmt.Sprintf("⛑ Kwatch detected a crash in pod %s", ev.PodName)
}
Expand All @@ -143,15 +147,18 @@ func (e *Email) buildMessageSubjectAndBody(
}

body := strings.Join(parts, "\n")
if narrative := strings.TrimSpace(ev.Narrative); narrative != "" {
body = narrative
}

if ev.IncludeLogs {
if ev.Narrative == "" && ev.IncludeLogs {
logs := strings.TrimSpace(ev.Logs)
if len(logs) > 0 {
body += "\n\nLogs:\n" + logs
}
}

if ev.IncludeEvents {
if ev.Narrative == "" && ev.IncludeEvents {
events := strings.TrimSpace(ev.Events)
if len(events) > 0 {
body += "\n\nEvents:\n" + events
Expand All @@ -160,3 +167,11 @@ func (e *Email) buildMessageSubjectAndBody(

return subject, body
}

func emailFirstLine(value string, limit int) string {
line := strings.SplitN(strings.TrimSpace(value), "\n", 2)[0]
if len(line) <= limit {
return line
}
return line[:limit-1] + "…"
}
Loading
Loading
0