Files
nmon/internal/reach/rows.go
jleung f85c3ef781
Some checks failed
ci / lint (push) Has been cancelled
ci / test (ubuntu-24.04-arm) (push) Has been cancelled
ci / test (ubuntu-latest) (push) Has been cancelled
ci / postgres (push) Has been cancelled
ci / openapi (push) Has been cancelled
M3: Go API per UI contract, embedded UI, openapi compat check, nmon-devtools, live gate + screenshots; M4 WP1 reachability and dependency suppression
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lx9FNLG2CqeBbVGGd9bFsP
2026-10-22 20:34:14 +00:00

311 lines
8.9 KiB
Go

package reach
import (
"context"
"encoding/json"
"strings"
"time"
"github.com/v10networks/nmon/internal/store"
)
// want is what a device's current verdict asks of one alert row.
type want int
const (
wantKeep want = iota // the verdict does not settle it; leave the row alone
wantActive // the condition holds
wantInactive // the condition cleared; resolve and announce if it was announced
wantQuiet // superseded by a worse condition; close without announcing
)
// target is one alert row a device can have: the down alert, or one warning reason.
type target struct {
rule, reason string
hold time.Duration // condition must last this long before it fires
}
func (t target) key(slug string) string { return t.rule + "|" + slug + "||" + t.reason }
func (e *Evaluator) holdFor(reason string) time.Duration {
if reason == ReasonICMPFiltered || reason == ReasonSNMPUnreachable {
return e.o.WarnHold
}
return 0
}
// wants maps a verdict to what it asks of a row of the given rule and reason.
func wants(v devView, rule, reason string) want {
if reason == ReasonICMPUnsupported { // independent of the verdict
if v.noICMP {
return wantActive
}
return wantInactive
}
if v.last == Unknown {
return wantKeep
}
switch rule {
case RuleDown:
if v.last == Down {
return wantActive
}
return wantInactive
default:
switch {
case v.last == Warning && v.reason == reason:
return wantActive
case v.last == Down:
return wantQuiet
}
return wantInactive
}
}
// applyRows moves every device's alert rows to match its verdict and delivers.
func (e *Evaluator) applyRows(ctx context.Context, now time.Time, p *pass) {
byDev := map[string][]*store.Alert{}
for _, r := range e.rows {
byDev[r.DeviceSlug] = append(byDev[r.DeviceSlug], r)
}
for _, slug := range p.slugs {
v := p.view[slug]
seen := map[string]bool{}
for _, r := range byDev[slug] {
seen[r.SeriesKey] = true
t := target{rule: r.Rule, reason: r.Component, hold: e.holdFor(r.Component)}
e.step(ctx, now, p, slug, r, t, v)
}
if v.paused {
continue
}
if v.noICMP && !seen[target{rule: RuleWarning, reason: ReasonICMPUnsupported}.key(slug)] {
e.step(ctx, now, p, slug, nil, target{rule: RuleWarning, reason: ReasonICMPUnsupported}, v)
}
switch v.last {
case Down:
e.stepNew(ctx, now, p, slug, target{rule: RuleDown}, v, seen)
case Warning:
t := target{rule: RuleWarning, reason: v.reason, hold: e.holdFor(v.reason)}
e.stepNew(ctx, now, p, slug, t, v, seen)
}
}
// Rows of devices that are no longer tracked are retired by refresh; here only deliveries remain.
}
func (e *Evaluator) stepNew(ctx context.Context, now time.Time, p *pass, slug string, t target, v devView, seen map[string]bool) {
if !seen[t.key(slug)] {
e.step(ctx, now, p, slug, nil, t, v)
}
}
// step advances one row (nil when the incident does not exist yet) and delivers.
func (e *Evaluator) step(ctx context.Context, now time.Time, p *pass, slug string, r *store.Alert, t target, v devView) {
if v.paused { // maintenance and degraded leave rows exactly as they are and hold deliveries
return
}
w := wants(v, t.rule, t.reason)
if r != nil && flapExpired(now, r) {
exitFlap(now, r)
}
if r == nil {
if w != wantActive {
return
}
r = e.newRow(ctx, now, slug, t)
}
switch w {
case wantActive:
activate(now, r, t.hold)
case wantInactive:
if !deactivate(now, r) {
e.dropPending(ctx, r)
return
}
case wantQuiet:
if closeQuiet(now, r) {
e.dropPending(ctx, r)
return
}
}
if !e.save(ctx, r) {
return
}
e.deliver(ctx, now, p, r)
if r.State == store.AlertResolved && r.NotifyPending == "" {
delete(e.rows, r.SeriesKey)
}
}
func (e *Evaluator) newRow(ctx context.Context, now time.Time, slug string, t target) *store.Alert {
r := &store.Alert{
Rule: t.rule, SeriesKey: t.key(slug), DeviceSlug: slug, Component: t.reason,
Severity: "critical", State: store.AlertPending, BaseState: store.AlertPending,
PendingSince: &now, FlapChanges: "[]",
}
if t.rule == RuleWarning {
r.Severity = "warning"
}
if prev, err := e.o.Store.LatestAlertBySeries(ctx, r.SeriesKey); err == nil {
r.FlapChanges = prev.FlapChanges // flap history survives across incidents
}
r.Summary, r.Description = describe(r)
e.rows[r.SeriesKey] = r
return r
}
func describe(r *store.Alert) (summary, desc string) {
if r.Rule == RuleDown {
return r.DeviceSlug + " is down", r.DeviceSlug + " is not reachable"
}
return r.DeviceSlug + " warning: " + r.Component, r.DeviceSlug + " reachability warning (" + r.Component + ")"
}
func (e *Evaluator) save(ctx context.Context, r *store.Alert) bool {
r.LastEvalAt = ptr(e.o.Clock.Now())
if err := e.o.Store.UpsertAlertState(ctx, r); err != nil {
e.log.Error("persist reachability alert", "key", r.SeriesKey, "err", err)
return false
}
return true
}
func (e *Evaluator) dropPending(ctx context.Context, r *store.Alert) {
if r.ID != 0 {
if err := e.o.Store.DeletePendingAlert(ctx, r.ID); err != nil {
e.log.Error("drop pending reachability alert", "key", r.SeriesKey, "err", err)
}
}
delete(e.rows, r.SeriesKey)
}
// retireRows closes the rows of a device that left the inventory without announcing anything.
func (e *Evaluator) retireRows(ctx context.Context, slug string) {
for k, r := range e.rows {
if r.DeviceSlug != slug {
continue
}
r.State, r.BaseState, r.NotifyPending, r.FlappingUntil = store.AlertRetired, store.AlertRetired, "", nil
r.ClearedAt = ptr(e.o.Clock.Now())
e.save(ctx, r)
delete(e.rows, k)
}
}
func ptr(t time.Time) *time.Time { return &t }
// activate moves a row toward firing: after its hold, the condition fires.
func activate(now time.Time, r *store.Alert, hold time.Duration) {
switch r.BaseState {
case store.AlertFiring:
return
case store.AlertResolved: // inside a flapping period: the condition returned
r.BaseState, r.PendingSince, r.ClearedAt = store.AlertPending, ptr(now), nil
}
if r.PendingSince == nil {
r.PendingSince = ptr(now)
}
if now.Sub(*r.PendingSince) >= hold {
fire(now, r)
}
}
// deactivate resolves a firing row. It returns false when the row was only
// pending outside a flapping period and should be deleted.
func deactivate(now time.Time, r *store.Alert) bool {
switch r.BaseState {
case store.AlertPending:
if !inFlap(now, r) {
return false
}
r.BaseState, r.ClearedAt = store.AlertResolved, ptr(now)
case store.AlertFiring:
resolve(now, r)
}
return true
}
// closeQuiet ends a warning that a worse condition replaced. It returns true
// when the row never fired and should be deleted instead of kept as history.
func closeQuiet(now time.Time, r *store.Alert) bool {
if r.BaseState == store.AlertPending {
return true
}
if r.State != store.AlertResolved {
r.State, r.BaseState, r.ClearedAt = store.AlertResolved, store.AlertResolved, ptr(now)
r.FlappingUntil = nil
}
r.NotifyPending = ""
return false
}
func fire(now time.Time, r *store.Alert) {
r.BaseState, r.ClearedAt = store.AlertFiring, nil
if r.FiredAt == nil {
r.FiredAt = ptr(now)
}
changed(now, r, NotifyFiring)
}
func resolve(now time.Time, r *store.Alert) {
r.BaseState, r.ClearedAt = store.AlertResolved, ptr(now)
changed(now, r, NotifyResolved)
}
// changed records a firing or resolved change: it sets the visible state,
// counts the change for flap damping and picks the notification. Entering
// flapping replaces the change that tipped the count over; while flapping
// nothing is sent.
func changed(now time.Time, r *store.Alert, note string) {
if inFlap(now, r) {
r.State = store.AlertFlapping
return
}
cut := now.Add(-FlapWindow).UnixMilli()
var kept []int64
for _, t := range parseChanges(r.FlapChanges) {
if t > cut {
kept = append(kept, t)
}
}
kept = append(kept, now.UnixMilli())
if len(kept) > FlapMax {
r.State, r.FlappingUntil, r.NotifyPending = store.AlertFlapping, ptr(now.Add(FlapHold)), NotifyFlapping
} else {
r.State, r.NotifyPending = r.BaseState, note
}
b, _ := json.Marshal(kept)
r.FlapChanges = string(b)
}
func parseChanges(s string) []int64 {
var t []int64
_ = json.Unmarshal([]byte(s), &t)
return t
}
func inFlap(now time.Time, r *store.Alert) bool {
return r.FlappingUntil != nil && now.Before(*r.FlappingUntil)
}
func flapExpired(now time.Time, r *store.Alert) bool {
return r.FlappingUntil != nil && !now.Before(*r.FlappingUntil)
}
// exitFlap ends a flapping period: the row takes its underlying state and one
// notification with that state goes out (a non-firing base reads as resolved).
func exitFlap(now time.Time, r *store.Alert) {
r.FlappingUntil, r.FlapChanges = nil, "[]"
if r.BaseState == store.AlertFiring {
r.State, r.NotifyPending = store.AlertFiring, NotifyFiring
return
}
r.BaseState, r.State = store.AlertResolved, store.AlertResolved
if r.ClearedAt == nil {
r.ClearedAt = ptr(now)
}
r.PendingSince, r.NotifyPending = nil, NotifyResolved
}
func joinSlugs(s []string) string { return strings.Join(s, ", ") }