8000 🚀 Refactor & fixing bugs by abahmed · Pull Request #485 · 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
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ jobs:
esac

# Match the exact SemVer shapes. A loose "does not contain -rc"
# filter would treat v1.0.0-beta.1 as a stable tag, and every version
# filter would treat v1.0.0 as a stable tag, and every version
# computed from it would then be wrong.
STABLE_TAGS=$(git tag -l 'v[0-9]*' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V || true)
LATEST_STABLE=$(echo "$STABLE_TAGS" | tail -1)
Expand Down
14 changes: 14 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,21 @@ linters:
default: none
enable:
- errcheck
- forbidigo
- gocritic
- gocyclo
- govet
- ineffassign
- unparam
- unused
settings:
forbidigo:
forbid:
# Providers must call util.Send: it is the one place that turns HTTP
# statuses into success / rate-limited / permanent / retryable. A
# provider with its own http.NewRequest gets its own status bugs.
- pattern: '^http\.(NewRequest|NewRequestWithContext|Post|Get|Head|PostForm)$'
msg: "alert providers must send through util.Send, not raw net/http"
govet:
disable:
- inline
Expand All @@ -34,6 +42,12 @@ linters:
# Informer wiring is declarative; ignoring AddEventHandler is noise.
- path: "internal/controller"
linters: [errcheck]
# The raw-HTTP rule is only about alert providers; util.Send is where the
# one allowed http.NewRequest lives.
- linters: [forbidigo]
path-except: "^internal/alert/"
- linters: [forbidigo]
path: "^internal/alert/util/"

formatters:
enable:
Expand Down
39 changes: 35 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Dependency direction flows downward; never import upward.
| `internal/handler` | Turns raw Kubernetes objects into candidate incidents (filters + hints) |
| `internal/filter` | Detect-time suppression filters (pod status, owners, reasons) |
| `internal/config` | Config loading/validation, suppression index builder |
| `internal/correlation` | Incident lifecycle (create/update/resolve/skip), grouping, cooldowns |
| `internal/correlation` | Incident lifecycle (create/update/resolve/skip), attribution, grouping, cooldowns. The **only** emitter of notifications (`emit.go`) |
| `internal/insight` | Cause/impact/recent-change analysis over the dependency graph |
| `internal/event`, `internal/context`, `internal/model` | Shared types |
| `internal/alert/*` | One subpackage per provider + routing/retry/ratelimit plumbing |
Expand All @@ -42,8 +42,29 @@ Dependency direction flows downward; never import upward.

Rules of thumb:

- `model` / `event` / `context` / `constant` must stay leaf packages.
- `model` / `event` / `context` / `constant` / `format` must stay leaf packages.
- Provider packages under `alert/` only depend on `model`, `message`, `config`, and `alert/util`.
- Providers that talk HTTP call `alert/util.Send`; never `net/http` directly (the linter
enforces this). Send is where a status code becomes success, rate-limited, permanent or
retryable — a provider must not have its own opinion.
- Nothing outside `correlation` calls `AlertManager.NotifyIncident` for incidents. The
handler feeds `Engine.Process` and stops; the engine announces every decision — live
events, resolves, group flushes, renotify, mass failures — through `LifecycleHook`, so
audit, diagnosis and delivery cannot diverge between paths.
- When a hint carries a fact a renderer needs (a memory limit, a probe endpoint, a delay),
put it in `model.Facts` next to the hint. Renderers read facts; they never parse the hint.
- `model.Incident` is five embedded parts — `Subject`, `Status`, `Evidence`, `Attribution`,
`Delivery` — each with one writer (see the type comment). Reads are promoted
(`inc.Reason`, `inc.Count`); composite literals name the part. `PersistedIncident` stays
flat: it is the on-disk format and must not change shape.
- `filter.Context` is `Sources` (read-only lookups the handler sets once) + the object under
evaluation + `Findings` (what detectors concluded). A filter never writes `Sources`.
- The handler gets its informer-backed lookups in one `handler.Listers` value via
`SetListers`, after all informers are wired. Do not add per-lister setters back to the
`Handler` interface; a nil lister means "that monitor is off".
- Time-based decisions read an injected clock (`filter.Sources.Now`, `handler.now`,
`Engine.now`, `insight.Engine.now`, `ReportBuilder.now`), not `time.Now()` directly, so
"unready for 5 minutes" is testable without waiting 5 minutes.
- Keep files focused; ~400 lines is the soft ceiling — split by responsibility within the
same package rather than growing a god file.

Expand All @@ -69,8 +90,11 @@ The controller watches many resource kinds through one abstraction:
1. Add a pipeline field to `Controller` and construct it in `New()` with a name matching
the ChangeTracker label (set `track` explicitly if the label differs from the name).
2. Write a `wire*` function in `wiring.go` using `watch()` (or `listen()`), returning any
factories the shutdown path needs.
3. Call it from `New()`, wire its `syncFn`, add it to `allPipelines()`.
factories the shutdown path needs. It stores the lister on the `Controller`; it does not
talk to the handler.
3. Call it from `New()`, wire its `syncFn`, add it to `allPipelines()`, and add the lister to
the single `handler.Listers{...}` value `New()` hands to `SetListers` (plus a field on
`handler.Listers` itself).
4. If it needs periodic sweeps (like control-plane pods), check `startWorkers` in `Run()`.
5. Add its graph edges in `graph_resources.go` if insight analysis should see it.

Expand All @@ -96,3 +120,10 @@ Some quirks are load-bearing. Preserve them unless a change explicitly says othe
- Exit code 137 with a reason other than `OOMKilled` is a plain SIGKILL, not an OOM.
- Suppression consolidation: deprecated `ignore*` fields become synthetic `SilenceRule`s in
`appendIgnoreFieldSilences`; keep both paths reading the unified index.
- `Engine.processLocked` runs five stages in a fixed order — baseline, attribution (node →
shared dependency → owning workload), cooldown, identity, announcement. Attribution comes
*before* cooldown on purpose: a pod whose key is cooling down is still its owner's symptom
and must keep being counted against it. Add a new kind of cause to `attribution.go`, not
as a new check in `processLocked`.
- The audit skip reasons `baseline`, `node_inhibition`, `mass_failure`,
`cascading_suppression`, `cooldown` are stable strings people grep for.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,15 @@ overcommit, repeating OOMs and more — lives in the [configuration reference](.
after a hold-down and revives silently past a cooldown
- 🔇 **Smart grouping** — related failures coalesce into one notification, re-notified on a
gentle cooldown, batch-resolved together
- 📊 **Mass-failure detection** — 30% of a shared dependency down → one blast-radius alert,
auto-resolved when it recovers
- 📊 **Mass-failure detection** — 30% of a shared dependency down → one blast-radius alert
that *replaces* the per-workload alerts rather than arriving alongside them, auto-resolved
when it recovers
- 🚨 **Escalation & re-notify** — repeated crashes climb severity, and long-lived incidents
nudge you again so nothing is forgotten
- 📜 **Audit log** — every decision (create / update / resolve / skip) as structured JSON
- 📜 **Audit log** — every decision (create / update / resolve / skip) as structured JSON,
with suppressions recorded on change rather than on every poll
- 🕳️ **Knows when it was blind** — kwatch stamps its own liveness, so if it was down while your
cluster wasn't, the next startup message says how long nobody was watching
- ♻️ **Live config** — change severity via `KwatchConfig` CRDs without restarting
- 🔁 **Delivery resilience** — per-provider routes, retries, and fallback, with a dead-letter
view for the rare message that can't be sent
Expand Down
2 changes: 1 addition & 1 deletion RELEASES.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Versions are always computed from existing tags — maintainers never type a ver
only choose which part moves.

> **Tag hygiene:** only `-rc.<N>` pre-releases are recognised. The workflow matches
> `vX.Y.Z` for stable tags and `vX.Y.Z-rc.<N>` for RCs, exactly. A tag like `v1.0.0-beta.1`
> `vX.Y.Z` for stable tags and `vX.Y.Z-rc.<N>` for RCs, exactly. A tag like `v1.0.0-rc.1`
> is ignored by both, so do not create other pre-release forms — the version computation
> will behave as if it does not exist.

Expand Down
1 change: 1 addition & 0 deletions deploy/chart/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ podLabels: {}
#
# smartGrouping:
# windowSeconds: 60
# namespaceFanOutThreshold: 3 # owners failing the same way in one namespace → one alert
config: {}

# -- Configure the upgrader/update checker (nested under config in the ConfigMap)
Expand Down
10 changes: 6 additions & 4 deletions deploy/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ data:
maxRecentLogLines: <number> # also caps logs/events in alert message blocks (default 50)
ignoreFailedGracefulShutdown: <boolean>
ignoreDisruptionTerminations: <boolean> # skip pods evicted during node drains (default true)
reportStartupBaseline: <boolean> # send one startup summary of pre-existing issues (default true)
reportStartupBaseline: <boolean> # send one startup summary of pre-existing issues (default true).
# Issues already present at startup are otherwise quiet for 24h, so keep this on.
containerRestartThreshold: <number> # alert if a container restarts this many times (0 = off, default 0)
workers: <number> # parallel reconcile workers (default 1)

Expand Down Expand Up @@ -73,7 +74,7 @@ data:
maxBaseline: 5000 # max baseline entries (default 5000)
escalation:
enabled: <boolean> # auto-escalate severity by restart count (default true)
tiers: [3, 10, 50] # restart thresholds: 3→"high", 10→"critical"
tiers: [3, 10] # restart thresholds: 3→"high", 10→"critical" (nothing above critical)
# renotify:
# intervalBySeverity:
# default: <minutes> # renotify interval per severity (0 = off)
Expand All @@ -90,7 +91,7 @@ data:

rolloutMonitor:
enabled: <boolean>
# sustainedMinutes: <minutes> # Debounce before alerting (default 2)
# sustainedMinutes: <minutes> # Debounce before alerting (default 5; Kubernetes' own progressDeadlineSeconds is 600)

daemonSetMonitor:
enabled: <boolean>
Expand Down Expand Up @@ -181,7 +182,8 @@ data:
# different workload owners within a time window into a single notification.
# Enabled by default; disable by setting windowSeconds to 0.
smartGrouping:
windowSeconds: <int> # grouping window in seconds (default 60)
windowSeconds: <int> # grouping window in seconds (default 60, 0 = off)
namespaceFanOutThreshold: <int> # owners failing the same way in one namespace before they collapse into one alert (default 3, 0 = off)

# ── Templates / Runbooks ──────────────────────────────
# templates:
Expand Down
Loading
Loading
0