diff --git a/internal/alert/deliver.go b/internal/alert/deliver.go new file mode 100644 index 0000000..05ce97b --- /dev/null +++ b/internal/alert/deliver.go @@ -0,0 +1,92 @@ +package alert + +import ( + "context" + "time" + + "github.com/v10networks/nmon/internal/store" +) + +// deliver sends the row's pending notification if it is still valid and not +// suppressed. Suppressed notifications are held and sent when the suppression +// ends, if still valid; acked rows drop everything except a resolution. +func (ev *Evaluator) deliver(ctx context.Context, now time.Time, a *store.Alert, ent Entity) { + if ev.held(ctx, a, ent) { + return + } + p := a.NotifyPending + if p == "" { + return + } + acked := a.AckUntil != nil && now.Before(*a.AckUntil) + if !pendingValid(a, p) || (acked && p != NotifyResolved) { + a.NotifyPending = "" + ev.save(ctx, a) + return + } + if err := ev.o.Notifier.Notify(ctx, transitionOf(a, p)); err != nil { + ev.reg.Counter("nmon_alert_notify_errors_total", "rule", a.Rule).Inc() + ev.log.Warn("notify failed, will retry", "rule", a.Rule, "key", a.SeriesKey, "state", p, "err", err) + return + } + a.NotifyPending = "" + if p != NotifyStale { + a.NotifiedState = p + } + ev.save(ctx, a) +} + +// held records the suppression reason on an active row and reports whether the +// pending notification must wait for the suppression to end. +func (ev *Evaluator) held(ctx context.Context, a *store.Alert, ent Entity) bool { + sup, why := ev.suppressed(ent) + if !isActive(a.State) { + return sup && a.NotifyPending != "" + } + reason := "" + if sup { + reason = why + if reason == "" { + reason = "suppressed" + } + } + if reason != a.SuppressedBy { + a.SuppressedBy = reason + ev.save(ctx, a) + } + return reason != "" && a.NotifyPending != "" +} + +// pendingValid reports whether notification p still describes the row. +func pendingValid(a *store.Alert, p string) bool { + switch p { + case NotifyFiring: + return a.BaseState == store.AlertFiring && a.State != store.AlertFlapping + case NotifyResolved: + return a.State == store.AlertResolved && (a.NotifiedState == NotifyFiring || a.NotifiedState == NotifyFlapping) + case NotifyStale: + return a.State == store.AlertStale && a.PriorState == store.AlertFiring && a.NotifiedState == NotifyFiring + case NotifyFlapping: + return a.State == store.AlertFlapping + } + return false +} + +func transitionOf(a *store.Alert, state string) Transition { + t := Transition{ + AlertID: a.ID, Rule: a.Rule, State: state, Severity: a.Severity, Device: a.DeviceSlug, Iface: a.Iface, + Component: a.Component, Value: a.Value, Threshold: a.Threshold, ClearedAt: a.ClearedAt, + Summary: a.Summary, Description: a.Description, + } + if a.FiredAt != nil { + t.FiredAt = *a.FiredAt + } + return t +} + +func (ev *Evaluator) suppressed(ent Entity) (bool, string) { + if ev.o.Suppressed == nil { + return false, "" + } + return ev.o.Suppressed(ent) +} diff --git a/internal/alert/evaluator.go b/internal/alert/evaluator.go index 9a3a9fe..c254fc5 100644 --- a/internal/alert/evaluator.go +++ b/internal/alert/evaluator.go @@ -2,13 +2,10 @@ package alert import ( "context" - "encoding/json" "errors" "fmt" "log/slog" - "math" "sort" - "strconv" "sync" "time" @@ -184,6 +181,15 @@ func (ev *Evaluator) EvalOnce(ctx context.Context) { ev.log.Error("load alert state", "err", err) return // without state nothing can be decided; do not touch anything } + active := ev.sweepRows(ctx, now, rows) + for _, r := range ev.rules { + ev.evalRule(ctx, now, r, active[r.Name]) + } +} + +// sweepRows settles rows that need no query (closed rows still owing a +// notification, rows of vanished entities or rules) and groups the rest by rule. +func (ev *Evaluator) sweepRows(ctx context.Context, now time.Time, rows []store.Alert) map[string][]*store.Alert { ruleByName := map[string]*compiledRule{} for _, r := range ev.rules { ruleByName[r.Name] = r @@ -202,33 +208,36 @@ func (ev *Evaluator) EvalOnce(ctx context.Context) { } active[a.Rule] = append(active[a.Rule], a) } + return active +} - for _, r := range ev.rules { - readings, qerr := ev.query(ctx, r, now) - if ev.o.StoreHealth != nil { - ev.o.StoreHealth(qerr == nil, qerr) - } - if qerr != nil { - // State untouched: not below, not no-data, and never a resolution. - ev.reg.Counter("nmon_alert_eval_errors_total", "rule", r.Name).Inc() - ev.log.Warn("rule evaluation failed", "rule", r.Name, "err", qerr) - continue - } - byKey := map[string]*store.Alert{} - for _, a := range active[r.Name] { - byKey[a.SeriesKey] = a - } - seen := map[string]bool{} - for _, rd := range readings { - key := rd.ent.Key() - seen[key] = true - thr := r.resolveThreshold(rd.ent.Device, ev.o.Groups, ev.o.ThresholdFor) - ev.apply(ctx, now, r, rd, thr, byKey[key]) - } - for _, a := range active[r.Name] { - if !seen[a.SeriesKey] { - ev.nodata(ctx, now, r, a) - } +// evalRule queries one rule and applies each reading to its entity's row; +// rows whose series vanished get the no-data treatment. +func (ev *Evaluator) evalRule(ctx context.Context, now time.Time, r *compiledRule, rows []*store.Alert) { + readings, qerr := ev.query(ctx, r, now) + if ev.o.StoreHealth != nil { + ev.o.StoreHealth(qerr == nil, qerr) + } + if qerr != nil { + // State untouched: not below, not no-data, and never a resolution. + ev.reg.Counter("nmon_alert_eval_errors_total", "rule", r.Name).Inc() + ev.log.Warn("rule evaluation failed", "rule", r.Name, "err", qerr) + return + } + byKey := map[string]*store.Alert{} + for _, a := range rows { + byKey[a.SeriesKey] = a + } + seen := map[string]bool{} + for _, rd := range readings { + key := rd.ent.Key() + seen[key] = true + thr := r.resolveThreshold(rd.ent.Device, ev.o.Groups, ev.o.ThresholdFor) + ev.apply(ctx, now, r, rd, thr, byKey[key]) + } + for _, a := range rows { + if !seen[a.SeriesKey] { + ev.nodata(ctx, now, r, a) } } } @@ -245,387 +254,6 @@ func entityOf(a *store.Alert) Entity { return Entity{Rule: a.Rule, Device: a.DeviceSlug, Iface: a.Iface, Component: a.Component} } -// query runs a rule and returns one reading per active, trusted entity. -func (ev *Evaluator) query(ctx context.Context, r *compiledRule, now time.Time) ([]reading, error) { - qctx, cancel := context.WithTimeout(ctx, queryTimeout) - defer cancel() - raw, err := ev.o.Querier.Query(qctx, ev.o.StoreName, r.Expr, now) - if err != nil { - return nil, err - } - series, err := parseVector(raw) - if err != nil { - return nil, err - } - best := map[string]reading{} - var order []string -next: - for _, s := range series { - var ent Entity - ent.Rule = r.Name - for _, l := range r.Labels { - v := s.labels[l] - if v == "" { - ev.log.Debug("series without label", "rule", r.Name, "label", l) - continue next - } - switch l { - case "device": - ent.Device = v - case "iface": - ent.Iface = v - case "component": - ent.Component = v - } - } - if r.SkipUnreliable && ent.Iface != "" && ev.o.Unreliable != nil && ev.o.Unreliable(ent.Iface) { - continue - } - if ev.o.Active != nil && !ev.o.Active(ent) { - continue - } - k := ent.Key() - cur, ok := best[k] - if !ok { - order = append(order, k) - } - // Duplicate series for one entity: keep the one nearer to alerting. - if !ok || (r.Op == OpLess && s.value < cur.value) || (r.Op != OpLess && s.value > cur.value) { - best[k] = reading{ent, s.value} - } - } - out := make([]reading, 0, len(order)) - for _, k := range order { - out = append(out, best[k]) - } - return out, nil -} - -type sample struct { - labels map[string]string - value float64 -} - -// parseVector reads an instant-query response. NaN samples are dropped (no data). -func parseVector(raw []byte) ([]sample, error) { - var resp struct { - Status string `json:"status"` - ErrorType string `json:"errorType"` - Error string `json:"error"` - Data struct { - ResultType string `json:"resultType"` - Result []struct { - Metric map[string]string `json:"metric"` - Value [2]json.RawMessage `json:"value"` - } `json:"result"` - } `json:"data"` - } - if err := json.Unmarshal(raw, &resp); err != nil { - return nil, fmt.Errorf("alert: bad query response: %w", err) - } - if resp.Status != "success" { - return nil, fmt.Errorf("alert: query status %q: %s %s", resp.Status, resp.ErrorType, resp.Error) - } - if resp.Data.ResultType != "vector" { - return nil, fmt.Errorf("alert: query returned %q, want vector", resp.Data.ResultType) - } - var out []sample - for _, r := range resp.Data.Result { - var str string - if err := json.Unmarshal(r.Value[1], &str); err != nil { - return nil, fmt.Errorf("alert: bad sample value %s", r.Value[1]) - } - v, err := strconv.ParseFloat(str, 64) - if err != nil { - return nil, fmt.Errorf("alert: bad sample value %q", str) - } - if math.IsNaN(v) { - continue - } - out = append(out, sample{r.Metric, v}) - } - return out, nil -} - -// ---- state machine ---- - -func (ev *Evaluator) save(ctx context.Context, a *store.Alert) bool { - if err := ev.o.Store.UpsertAlertState(ctx, a); err != nil { - ev.log.Error("persist alert state", "rule", a.Rule, "key", a.SeriesKey, "err", err) - return false - } - return true -} - -func tptr(t time.Time) *time.Time { return &t } - -// apply handles one reading (below or above) for an entity; a is its active row or nil. -func (ev *Evaluator) apply(ctx context.Context, now time.Time, r *compiledRule, rd reading, thr float64, a *store.Alert) { - ent := rd.ent - breach := r.breach(rd.value, thr) - if a != nil && ev.flapExpired(now, a) { - ev.exitFlap(now, a) - if a.State == store.AlertResolved { // closed by the flap exit; this reading starts afresh - ev.finish(ctx, now, r, a, ent, rd.value, thr) - a = nil - } - } - if a == nil { - if !breach { - return - } - a = &store.Alert{ - Rule: r.Name, SeriesKey: ent.Key(), DeviceSlug: ent.Device, Iface: ent.Iface, Component: ent.Component, - Severity: r.Severity, State: store.AlertPending, BaseState: store.AlertPending, PendingSince: tptr(now), - FlapChanges: "[]", - } - // Flap history survives across incident rows. - if prev, err := ev.o.Store.LatestAlertBySeries(ctx, a.SeriesKey); err == nil { - a.FlapChanges = prev.FlapChanges - } - } - a.NodataCount = 0 - if a.BaseState == store.AlertStale { // a real reading clears stale - a.BaseState = a.PriorState - a.PriorState = "" - if a.BaseState == store.AlertPending { - a.PendingSince = tptr(now) // the old timer spans a gap we cannot vouch for - } - if !ev.inFlap(now, a) { - a.State = a.BaseState - } - } - - if a.PendingSince == nil { - a.PendingSince = tptr(now) - } - switch a.BaseState { - case store.AlertPending: - switch { - case !breach && !ev.inFlap(now, a): - if a.ID != 0 { - if err := ev.o.Store.DeletePendingAlert(ctx, a.ID); err != nil { - ev.log.Error("drop pending alert", "err", err) - } - } - return // never fired: nothing to keep - case !breach: - a.BaseState = store.AlertResolved - a.ClearedAt = tptr(now) - case now.Sub(*a.PendingSince) >= r.For: - ev.fire(now, a) - } - case store.AlertFiring: - if !breach { - ev.resolve(now, a) - } - case store.AlertResolved: // only inside a flapping period - if breach { - a.BaseState, a.PendingSince, a.ClearedAt = store.AlertPending, tptr(now), nil - if r.For <= 0 { - ev.fire(now, a) - } - } - } - ev.finish(ctx, now, r, a, ent, rd.value, thr) -} - -// finish refreshes the descriptive columns, persists and delivers. -func (ev *Evaluator) finish(ctx context.Context, now time.Time, r *compiledRule, a *store.Alert, ent Entity, v, thr float64) { - a.Value, a.Threshold, a.LastEvalAt = v, thr, tptr(now) - data := TemplateData{Rule: r.Name, Severity: r.Severity, Device: ent.Device, Iface: ent.Iface, Component: ent.Component, - Value: v, Threshold: thr, Op: r.Op, For: r.For} - a.Summary, a.Description = r.render(r.summary, data), r.render(r.desc, data) - ev.persistAndDeliver(ctx, now, a, ent) -} - -func (ev *Evaluator) persistAndDeliver(ctx context.Context, now time.Time, a *store.Alert, ent Entity) { - if !ev.save(ctx, a) { - return - } - ev.deliver(ctx, now, a, ent) -} - -func (ev *Evaluator) fire(now time.Time, a *store.Alert) { - a.BaseState = store.AlertFiring - a.ClearedAt = nil - if a.FiredAt == nil { - a.FiredAt = tptr(now) - } - ev.changed(now, a, NotifyFiring) -} - -func (ev *Evaluator) resolve(now time.Time, a *store.Alert) { - a.BaseState = store.AlertResolved - a.ClearedAt = tptr(now) - ev.changed(now, a, NotifyResolved) -} - -// changed records a firing/resolved change: it sets the visible state, counts -// it for flap damping and chooses the notification (flapping replaces the -// change that tipped the count over). -func (ev *Evaluator) changed(now time.Time, a *store.Alert, notify string) { - if ev.inFlap(now, a) { - a.State = store.AlertFlapping - return // silent while flapping - } - times := parseChanges(a.FlapChanges) - cut := now.Add(-FlapWindow).UnixMilli() - kept := times[:0] - for _, t := range times { - if t > cut { - kept = append(kept, t) - } - } - kept = append(kept, now.UnixMilli()) - if len(kept) > FlapMax { - a.State = store.AlertFlapping - a.FlappingUntil = tptr(now.Add(FlapHold)) - a.NotifyPending = NotifyFlapping - } else { - a.State = a.BaseState - a.NotifyPending = notify - } - a.FlapChanges = encodeChanges(kept) -} - -func parseChanges(s string) []int64 { - var t []int64 - _ = json.Unmarshal([]byte(s), &t) - return t -} - -func encodeChanges(t []int64) string { - b, _ := json.Marshal(t) - return string(b) -} - -func (ev *Evaluator) inFlap(now time.Time, a *store.Alert) bool { - return a.FlappingUntil != nil && now.Before(*a.FlappingUntil) -} - -func (ev *Evaluator) flapExpired(now time.Time, a *store.Alert) bool { - return a.FlappingUntil != nil && !now.Before(*a.FlappingUntil) -} - -// exitFlap ends a flapping period: the row takes its underlying state and one -// notification with that state goes out (a pending or resolved base reads as -// resolved, since nothing is firing). -func (ev *Evaluator) exitFlap(now time.Time, a *store.Alert) { - a.FlappingUntil = nil - a.FlapChanges = "[]" - switch a.BaseState { - case store.AlertFiring: - a.State = store.AlertFiring - a.NotifyPending = NotifyFiring - default: - a.BaseState, a.State = store.AlertResolved, store.AlertResolved - if a.ClearedAt == nil { - a.ClearedAt = tptr(now) - } - a.PendingSince = nil - a.NotifyPending = NotifyResolved - } -} - -// nodata handles an active row whose series was absent from a successful query. -func (ev *Evaluator) nodata(ctx context.Context, now time.Time, r *compiledRule, a *store.Alert) { - ent := entityOf(a) - if ev.flapExpired(now, a) { - ev.exitFlap(now, a) - ev.persistAndDeliver(ctx, now, a, ent) - if !isActive(a.State) { - return - } - } - a.NodataCount++ - a.LastEvalAt = tptr(now) - if a.NodataCount >= StaleAfter && a.BaseState != store.AlertStale && a.State != store.AlertFlapping { - a.PriorState = a.BaseState - a.BaseState, a.State = store.AlertStale, store.AlertStale - a.NotifyPending = NotifyStale - } - ev.persistAndDeliver(ctx, now, a, ent) -} - -// retire closes a row for a device, interface or rule that no longer exists. -// It is not a resolution and sends nothing. -func (ev *Evaluator) retire(ctx context.Context, now time.Time, a *store.Alert) { - a.State, a.BaseState, a.PriorState = store.AlertRetired, store.AlertRetired, "" - a.ClearedAt, a.NotifyPending, a.FlappingUntil = tptr(now), "", nil - ev.save(ctx, a) -} - -// deliver sends the row's pending notification if it is still valid and not -// suppressed. Suppressed notifications are held and sent when the suppression -// ends, if still valid; acked rows drop everything except a resolution. -func (ev *Evaluator) deliver(ctx context.Context, now time.Time, a *store.Alert, ent Entity) { - if isActive(a.State) { - reason := "" - if sup, why := ev.suppressed(ent); sup { - reason = why - if reason == "" { - reason = "suppressed" - } - } - if reason != a.SuppressedBy { - a.SuppressedBy = reason - ev.save(ctx, a) - } - if reason != "" && a.NotifyPending != "" { - return - } - } else if sup, _ := ev.suppressed(ent); sup && a.NotifyPending != "" { - return - } - p := a.NotifyPending - if p == "" { - return - } - acked := a.AckUntil != nil && now.Before(*a.AckUntil) - valid := false - switch p { - case NotifyFiring: - valid = a.BaseState == store.AlertFiring && a.State != store.AlertFlapping - case NotifyResolved: - valid = a.State == store.AlertResolved && (a.NotifiedState == NotifyFiring || a.NotifiedState == NotifyFlapping) - case NotifyStale: - valid = a.State == store.AlertStale && a.PriorState == store.AlertFiring && a.NotifiedState == NotifyFiring - case NotifyFlapping: - valid = a.State == store.AlertFlapping - } - if !valid || (acked && p != NotifyResolved) { - a.NotifyPending = "" - ev.save(ctx, a) - return - } - t := Transition{ - AlertID: a.ID, Rule: a.Rule, State: p, Severity: a.Severity, Device: a.DeviceSlug, Iface: a.Iface, - Component: a.Component, Value: a.Value, Threshold: a.Threshold, ClearedAt: a.ClearedAt, - Summary: a.Summary, Description: a.Description, - } - if a.FiredAt != nil { - t.FiredAt = *a.FiredAt - } - if err := ev.o.Notifier.Notify(ctx, t); err != nil { - ev.reg.Counter("nmon_alert_notify_errors_total", "rule", a.Rule).Inc() - ev.log.Warn("notify failed, will retry", "rule", a.Rule, "key", a.SeriesKey, "state", p, "err", err) - return - } - a.NotifyPending = "" - if p != NotifyStale { - a.NotifiedState = p - } - ev.save(ctx, a) -} - -func (ev *Evaluator) suppressed(ent Entity) (bool, string) { - if ev.o.Suppressed == nil { - return false, "" - } - return ev.o.Suppressed(ent) -} - // SortedRuleNames lists the enabled rules, for diagnostics. func (ev *Evaluator) SortedRuleNames() []string { var n []string diff --git a/internal/alert/evaluator_test.go b/internal/alert/evaluator_test.go index 9f0b434..006af28 100644 --- a/internal/alert/evaluator_test.go +++ b/internal/alert/evaluator_test.go @@ -88,8 +88,6 @@ type harness struct { reg *selfmon.Registry opts Options ev *Evaluator - dir string - path string } func testRule(f time.Duration) Rule { @@ -109,7 +107,7 @@ func newHarness(t *testing.T, rules ...Rule) *harness { if err != nil { t.Fatal(err) } - t.Cleanup(func() { st.Close() }) + t.Cleanup(func() { _ = st.Close() }) if err := st.Migrate(ctx); err != nil { t.Fatal(err) } diff --git a/internal/alert/integration_test.go b/internal/alert/integration_test.go index c73d6ec..55b5516 100644 --- a/internal/alert/integration_test.go +++ b/internal/alert/integration_test.go @@ -91,7 +91,7 @@ func TestIntegrationDefaultRulesAgainstRealStore(t *testing.T) { if err != nil { t.Fatal(err) } - defer st.Close() + defer func() { _ = st.Close() }() if err := st.Migrate(ctx); err != nil { t.Fatal(err) } diff --git a/internal/alert/query.go b/internal/alert/query.go new file mode 100644 index 0000000..edb93ca --- /dev/null +++ b/internal/alert/query.go @@ -0,0 +1,128 @@ +package alert + +import ( + "context" + "encoding/json" + "fmt" + "math" + "strconv" + "time" +) + +// query runs a rule and returns one reading per active, trusted entity. +func (ev *Evaluator) query(ctx context.Context, r *compiledRule, now time.Time) ([]reading, error) { + qctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + raw, err := ev.o.Querier.Query(qctx, ev.o.StoreName, r.Expr, now) + if err != nil { + return nil, err + } + series, err := parseVector(raw) + if err != nil { + return nil, err + } + best := map[string]reading{} + var order []string + for _, s := range series { + ent, ok := ev.entityOfSeries(r, s) + if !ok { + continue + } + k := ent.Key() + cur, seen := best[k] + if !seen { + order = append(order, k) + } + // Duplicate series for one entity: keep the one nearer to alerting. + if !seen || r.nearer(s.value, cur.value) { + best[k] = reading{ent, s.value} + } + } + out := make([]reading, 0, len(order)) + for _, k := range order { + out = append(out, best[k]) + } + return out, nil +} + +// nearer reports whether a is closer to breaching than b. +func (r *compiledRule) nearer(a, b float64) bool { + if r.Op == OpLess { + return a < b + } + return a > b +} + +// entityOfSeries maps a series to its entity. It reports false for series that +// lack a label the rule needs, are on unreliable interfaces, or are inactive. +func (ev *Evaluator) entityOfSeries(r *compiledRule, s sample) (Entity, bool) { + ent := Entity{Rule: r.Name} + for _, l := range r.Labels { + v := s.labels[l] + if v == "" { + ev.log.Debug("series without label", "rule", r.Name, "label", l) + return Entity{}, false + } + switch l { + case "device": + ent.Device = v + case "iface": + ent.Iface = v + case "component": + ent.Component = v + } + } + if r.SkipUnreliable && ent.Iface != "" && ev.o.Unreliable != nil && ev.o.Unreliable(ent.Iface) { + return Entity{}, false + } + if ev.o.Active != nil && !ev.o.Active(ent) { + return Entity{}, false + } + return ent, true +} + +type sample struct { + labels map[string]string + value float64 +} + +// parseVector reads an instant-query response. NaN samples are dropped (no data). +func parseVector(raw []byte) ([]sample, error) { + var resp struct { + Status string `json:"status"` + ErrorType string `json:"errorType"` + Error string `json:"error"` + Data struct { + ResultType string `json:"resultType"` + Result []struct { + Metric map[string]string `json:"metric"` + Value [2]json.RawMessage `json:"value"` + } `json:"result"` + } `json:"data"` + } + if err := json.Unmarshal(raw, &resp); err != nil { + return nil, fmt.Errorf("alert: bad query response: %w", err) + } + if resp.Status != "success" { + return nil, fmt.Errorf("alert: query status %q: %s %s", resp.Status, resp.ErrorType, resp.Error) + } + if resp.Data.ResultType != "vector" { + return nil, fmt.Errorf("alert: query returned %q, want vector", resp.Data.ResultType) + } + var out []sample + for _, r := range resp.Data.Result { + var str string + if err := json.Unmarshal(r.Value[1], &str); err != nil { + return nil, fmt.Errorf("alert: bad sample value %s", r.Value[1]) + } + v, err := strconv.ParseFloat(str, 64) + if err != nil { + return nil, fmt.Errorf("alert: bad sample value %q", str) + } + if math.IsNaN(v) { + continue + } + out = append(out, sample{r.Metric, v}) + } + return out, nil +} diff --git a/internal/alert/rules.go b/internal/alert/rules.go index b7cb0d7..b077b4a 100644 --- a/internal/alert/rules.go +++ b/internal/alert/rules.go @@ -90,6 +90,16 @@ func (r Rule) Validate() error { if r.For < 0 { add("for is negative") } + r.validateLabels(add) + if err := checkExprShape(r.Expr); err != nil { + add("expr: %v", err) + } + r.validateOverridesAndTemplates(add) + return errors.Join(errs...) +} + +// validateLabels checks the rule's label set names only entity labels. +func (r Rule) validateLabels(add func(string, ...any)) { if len(r.Labels) == 0 { add("labels is empty") } @@ -98,9 +108,11 @@ func (r Rule) Validate() error { add("label %q is not device, iface or component", l) } } - if err := checkExprShape(r.Expr); err != nil { - add("expr: %v", err) - } +} + +// validateOverridesAndTemplates checks overrides name a group and the +// summary and description templates parse. +func (r Rule) validateOverridesAndTemplates(add func(string, ...any)) { for _, o := range r.Overrides { if o.Group == "" { add("override without a group") @@ -111,7 +123,6 @@ func (r Rule) Validate() error { add("%s template: %v", n, err) } } - return errors.Join(errs...) } // checkExprShape is a cheap structural check (non-empty, balanced brackets and @@ -233,6 +244,27 @@ func (r Rule) resolveThreshold(device string, g GroupLookup, thresholdFor func(d return r.Threshold } +// patchRule overlays the non-zero tunables of c onto d. +func patchRule(d, c Rule) Rule { + if c.Severity != "" { + d.Severity = c.Severity + } + if c.Op != "" { + d.Op = c.Op + } + if c.Threshold != 0 { + d.Threshold = c.Threshold + } + if c.For != 0 { + d.For = c.For + } + if c.Overrides != nil { + d.Overrides = c.Overrides + } + d.Disabled = c.Disabled + return d +} + // MergeRules applies configured rules over defaults. A configured rule with // the name of a default and no Expr patches that default's severity, op, // threshold, for, overrides and disabled flag (zero values keep the default; @@ -249,24 +281,7 @@ func MergeRules(defaults, configured []Rule) ([]Rule, error) { i, known := idx[c.Name] switch { case known && c.Expr == "": - d := out[i] - if c.Severity != "" { - d.Severity = c.Severity - } - if c.Op != "" { - d.Op = c.Op - } - if c.Threshold != 0 { - d.Threshold = c.Threshold - } - if c.For != 0 { - d.For = c.For - } - if c.Overrides != nil { - d.Overrides = c.Overrides - } - d.Disabled = c.Disabled - out[i] = d + out[i] = patchRule(out[i], c) case known: out[i] = c default: @@ -316,6 +331,11 @@ const ( // thresholds arrive through Options.ThresholdFor; the default is 70. func DefaultRules() []Rule { lab := func(l ...string) []string { return l } + return append(hostRules(lab), deviceRules(lab)...) +} + +// hostRules are the interface, CPU, memory and disk rules of DefaultRules. +func hostRules(lab func(...string) []string) []Rule { return []Rule{ { Name: "interface_down", Severity: SevWarning, Op: OpGreater, Threshold: 0, For: 2 * time.Minute, @@ -328,9 +348,11 @@ func DefaultRules() []Rule { Name: "interface_errors", Severity: SevWarning, Op: OpGreater, Threshold: 0.1, For: 0, Labels: lab("device", "iface"), SkipUnreliable: true, Expr: `100 * (rate(ifInErrors[5m]) + rate(ifOutErrors[5m])) / clamp_min(` + - `(rate(ifHCInUcastPkts[5m]) + rate(ifHCOutUcastPkts[5m])) or ((rate(ifHCInOctets[5m]) + rate(ifHCOutOctets[5m])) / 1500), 10)`, - Summary: `{{.Device}} interface {{.Iface}} error ratio {{printf "%.2f" .Value}}%`, - Description: `Errors are {{printf "%.2f" .Value}}% of packets over 5 minutes on {{.Iface}} of {{.Device}} (threshold {{printf "%.2f" .Threshold}}%).`, + `(rate(ifHCInUcastPkts[5m]) + rate(ifHCOutUcastPkts[5m])) or ` + + `((rate(ifHCInOctets[5m]) + rate(ifHCOutOctets[5m])) / 1500), 10)`, + Summary: `{{.Device}} interface {{.Iface}} error ratio {{printf "%.2f" .Value}}%`, + Description: `Errors are {{printf "%.2f" .Value}}% of packets over 5 minutes on {{.Iface}} of {{.Device}} ` + + `(threshold {{printf "%.2f" .Threshold}}%).`, }, { Name: "cpu_high", Severity: SevWarning, Op: OpGreater, Threshold: 90, For: 10 * time.Minute, @@ -352,11 +374,20 @@ func DefaultRules() []Rule { Name: "disk_full", Severity: SevCritical, Op: OpGreater, Threshold: 90, For: 0, Labels: lab("device", "component"), Expr: `max by (device, component) (union(` + - `100 * last_over_time(hrStorageUsed{component!~"` + notDiskE + `"}[15m]) / (last_over_time(hrStorageSize{component!~"` + notDiskE + `"}[15m]) > 0), ` + - `label_set(100 * (predict_linear(hrStorageUsed{component!~"` + notDiskE + `"}[6h], 86400) > bool last_over_time(hrStorageSize{component!~"` + notDiskE + `"}[15m])), "kind", "predicted")))`, - Summary: `{{.Device}} {{.Component}} is {{printf "%.0f" .Value}}% full or filling`, - Description: `Storage {{.Component}} on {{.Device}} is above {{printf "%.0f" .Threshold}}% used or predicted to fill within 24 hours (value {{printf "%.1f" .Value}}).`, + `100 * last_over_time(hrStorageUsed{component!~"` + notDiskE + `"}[15m]) / ` + + `(last_over_time(hrStorageSize{component!~"` + notDiskE + `"}[15m]) > 0), ` + + `label_set(100 * (predict_linear(hrStorageUsed{component!~"` + notDiskE + `"}[6h], 86400) > bool ` + + `last_over_time(hrStorageSize{component!~"` + notDiskE + `"}[15m])), "kind", "predicted")))`, + Summary: `{{.Device}} {{.Component}} is {{printf "%.0f" .Value}}% full or filling`, + Description: `Storage {{.Component}} on {{.Device}} is above {{printf "%.0f" .Threshold}}% used or ` + + `predicted to fill within 24 hours (value {{printf "%.1f" .Value}}).`, }, + } +} + +// deviceRules are the UPS, printer and temperature rules of DefaultRules. +func deviceRules(lab func(...string) []string) []Rule { + return []Rule{ { Name: "ups_on_battery", Severity: SevCritical, Op: OpGreater, Threshold: 0, For: 0, Labels: lab("device"), diff --git a/internal/alert/state.go b/internal/alert/state.go new file mode 100644 index 0000000..964f084 --- /dev/null +++ b/internal/alert/state.go @@ -0,0 +1,241 @@ +package alert + +import ( + "context" + "encoding/json" + "time" + + "github.com/v10networks/nmon/internal/store" +) + +func (ev *Evaluator) save(ctx context.Context, a *store.Alert) bool { + if err := ev.o.Store.UpsertAlertState(ctx, a); err != nil { + ev.log.Error("persist alert state", "rule", a.Rule, "key", a.SeriesKey, "err", err) + return false + } + return true +} + +func tptr(t time.Time) *time.Time { return &t } + +// apply handles one reading (below or above) for an entity; a is its active row or nil. +func (ev *Evaluator) apply(ctx context.Context, now time.Time, r *compiledRule, rd reading, thr float64, a *store.Alert) { + ent := rd.ent + breach := r.breach(rd.value, thr) + if a != nil && ev.flapExpired(now, a) { + ev.exitFlap(now, a) + if a.State == store.AlertResolved { // closed by the flap exit; this reading starts afresh + ev.finish(ctx, now, r, a, ent, rd.value, thr) + a = nil + } + } + if a == nil { + if !breach { + return + } + a = ev.newPending(ctx, now, r, ent) + } + a.NodataCount = 0 + ev.clearStale(now, a) + if a.PendingSince == nil { + a.PendingSince = tptr(now) + } + if !ev.advance(ctx, now, r, a, breach) { + return + } + ev.finish(ctx, now, r, a, ent, rd.value, thr) +} + +// newPending starts an incident row for ent, inheriting its flap history. +func (ev *Evaluator) newPending(ctx context.Context, now time.Time, r *compiledRule, ent Entity) *store.Alert { + a := &store.Alert{ + Rule: r.Name, SeriesKey: ent.Key(), DeviceSlug: ent.Device, Iface: ent.Iface, Component: ent.Component, + Severity: r.Severity, State: store.AlertPending, BaseState: store.AlertPending, PendingSince: tptr(now), + FlapChanges: "[]", + } + // Flap history survives across incident rows. + if prev, err := ev.o.Store.LatestAlertBySeries(ctx, a.SeriesKey); err == nil { + a.FlapChanges = prev.FlapChanges + } + return a +} + +// clearStale lets a real reading take a stale row back to its prior state. +func (ev *Evaluator) clearStale(now time.Time, a *store.Alert) { + if a.BaseState != store.AlertStale { + return + } + a.BaseState = a.PriorState + a.PriorState = "" + if a.BaseState == store.AlertPending { + a.PendingSince = tptr(now) // the old timer spans a gap we cannot vouch for + } + if !ev.inFlap(now, a) { + a.State = a.BaseState + } +} + +// advance moves the row's base state according to the reading. It reports +// false when the row was dropped and there is nothing to persist. +func (ev *Evaluator) advance(ctx context.Context, now time.Time, r *compiledRule, a *store.Alert, breach bool) bool { + switch a.BaseState { + case store.AlertPending: + return ev.advancePending(ctx, now, r, a, breach) + case store.AlertFiring: + if !breach { + ev.resolve(now, a) + } + case store.AlertResolved: // only inside a flapping period + if breach { + a.BaseState, a.PendingSince, a.ClearedAt = store.AlertPending, tptr(now), nil + if r.For <= 0 { + ev.fire(now, a) + } + } + } + return true +} + +func (ev *Evaluator) advancePending(ctx context.Context, now time.Time, r *compiledRule, a *store.Alert, breach bool) bool { + switch { + case !breach && !ev.inFlap(now, a): + if a.ID != 0 { + if err := ev.o.Store.DeletePendingAlert(ctx, a.ID); err != nil { + ev.log.Error("drop pending alert", "err", err) + } + } + return false // never fired: nothing to keep + case !breach: + a.BaseState = store.AlertResolved + a.ClearedAt = tptr(now) + case now.Sub(*a.PendingSince) >= r.For: + ev.fire(now, a) + } + return true +} + +// finish refreshes the descriptive columns, persists and delivers. +func (ev *Evaluator) finish(ctx context.Context, now time.Time, r *compiledRule, a *store.Alert, ent Entity, v, thr float64) { + a.Value, a.Threshold, a.LastEvalAt = v, thr, tptr(now) + data := TemplateData{Rule: r.Name, Severity: r.Severity, Device: ent.Device, Iface: ent.Iface, Component: ent.Component, + Value: v, Threshold: thr, Op: r.Op, For: r.For} + a.Summary, a.Description = r.render(r.summary, data), r.render(r.desc, data) + ev.persistAndDeliver(ctx, now, a, ent) +} + +func (ev *Evaluator) persistAndDeliver(ctx context.Context, now time.Time, a *store.Alert, ent Entity) { + if !ev.save(ctx, a) { + return + } + ev.deliver(ctx, now, a, ent) +} + +func (ev *Evaluator) fire(now time.Time, a *store.Alert) { + a.BaseState = store.AlertFiring + a.ClearedAt = nil + if a.FiredAt == nil { + a.FiredAt = tptr(now) + } + ev.changed(now, a, NotifyFiring) +} + +func (ev *Evaluator) resolve(now time.Time, a *store.Alert) { + a.BaseState = store.AlertResolved + a.ClearedAt = tptr(now) + ev.changed(now, a, NotifyResolved) +} + +// changed records a firing/resolved change: it sets the visible state, counts +// it for flap damping and chooses the notification (flapping replaces the +// change that tipped the count over). +func (ev *Evaluator) changed(now time.Time, a *store.Alert, notify string) { + if ev.inFlap(now, a) { + a.State = store.AlertFlapping + return // silent while flapping + } + times := parseChanges(a.FlapChanges) + cut := now.Add(-FlapWindow).UnixMilli() + kept := times[:0] + for _, t := range times { + if t > cut { + kept = append(kept, t) + } + } + kept = append(kept, now.UnixMilli()) + if len(kept) > FlapMax { + a.State = store.AlertFlapping + a.FlappingUntil = tptr(now.Add(FlapHold)) + a.NotifyPending = NotifyFlapping + } else { + a.State = a.BaseState + a.NotifyPending = notify + } + a.FlapChanges = encodeChanges(kept) +} + +func parseChanges(s string) []int64 { + var t []int64 + _ = json.Unmarshal([]byte(s), &t) + return t +} + +func encodeChanges(t []int64) string { + b, _ := json.Marshal(t) + return string(b) +} + +func (ev *Evaluator) inFlap(now time.Time, a *store.Alert) bool { + return a.FlappingUntil != nil && now.Before(*a.FlappingUntil) +} + +func (ev *Evaluator) flapExpired(now time.Time, a *store.Alert) bool { + return a.FlappingUntil != nil && !now.Before(*a.FlappingUntil) +} + +// exitFlap ends a flapping period: the row takes its underlying state and one +// notification with that state goes out (a pending or resolved base reads as +// resolved, since nothing is firing). +func (ev *Evaluator) exitFlap(now time.Time, a *store.Alert) { + a.FlappingUntil = nil + a.FlapChanges = "[]" + switch a.BaseState { + case store.AlertFiring: + a.State = store.AlertFiring + a.NotifyPending = NotifyFiring + default: + a.BaseState, a.State = store.AlertResolved, store.AlertResolved + if a.ClearedAt == nil { + a.ClearedAt = tptr(now) + } + a.PendingSince = nil + a.NotifyPending = NotifyResolved + } +} + +// nodata handles an active row whose series was absent from a successful query. +func (ev *Evaluator) nodata(ctx context.Context, now time.Time, r *compiledRule, a *store.Alert) { + ent := entityOf(a) + if ev.flapExpired(now, a) { + ev.exitFlap(now, a) + ev.persistAndDeliver(ctx, now, a, ent) + if !isActive(a.State) { + return + } + } + a.NodataCount++ + a.LastEvalAt = tptr(now) + if a.NodataCount >= StaleAfter && a.BaseState != store.AlertStale && a.State != store.AlertFlapping { + a.PriorState = a.BaseState + a.BaseState, a.State = store.AlertStale, store.AlertStale + a.NotifyPending = NotifyStale + } + ev.persistAndDeliver(ctx, now, a, ent) +} + +// retire closes a row for a device, interface or rule that no longer exists. +// It is not a resolution and sends nothing. +func (ev *Evaluator) retire(ctx context.Context, now time.Time, a *store.Alert) { + a.State, a.BaseState, a.PriorState = store.AlertRetired, store.AlertRetired, "" + a.ClearedAt, a.NotifyPending, a.FlappingUntil = tptr(now), "", nil + ev.save(ctx, a) +} diff --git a/internal/clock/clock.go b/internal/clock/clock.go index ef43f3f..4c85ecc 100644 --- a/internal/clock/clock.go +++ b/internal/clock/clock.go @@ -66,12 +66,14 @@ type waiter struct { // NewFake returns a Fake clock starting at start. func NewFake(start time.Time) *Fake { return &Fake{now: start} } +// Now returns the fake time. func (f *Fake) Now() time.Time { f.mu.Lock() defer f.mu.Unlock() return f.now } +// After returns a channel that fires once Advance moves the fake time past d. func (f *Fake) After(d time.Duration) <-chan time.Time { f.mu.Lock() defer f.mu.Unlock() @@ -84,6 +86,7 @@ func (f *Fake) After(d time.Duration) <-chan time.Time { return w.ch } +// NewTicker returns a ticker that fires each time Advance crosses a multiple of d. func (f *Fake) NewTicker(d time.Duration) Ticker { if d <= 0 { panic("clock: non-positive ticker interval") @@ -95,6 +98,7 @@ func (f *Fake) NewTicker(d time.Duration) Ticker { return &fakeTicker{f: f, w: w} } +// Sleep blocks until Advance moves the fake time past d, or ctx is done. func (f *Fake) Sleep(ctx context.Context, d time.Duration) error { select { case <-ctx.Done(): diff --git a/internal/librenms/detect.go b/internal/librenms/detect.go index e5ea83d..b4f6b12 100644 --- a/internal/librenms/detect.go +++ b/internal/librenms/detect.go @@ -49,43 +49,16 @@ func phpRegex(s string) (string, error) { // parseDetection maps the discovery: list of an os_detection file. func parseDetection(doc map[string]any) match { var m match - groups := asList(doc["discovery"]) - for gi, g := range groups { + for gi, g := range asList(doc["discovery"]) { e := asMap(g) if e == nil { m.notes = append(m.notes, fmt.Sprintf("discovery[%d]: not a mapping, skipped", gi)) continue } - var oids, descr []string - for _, k := range sortedKeys(e) { - switch k { - case "sysObjectID": - for _, o := range strs(e[k]) { - if !numericOIDRE.MatchString(strings.TrimSpace(o)) { - m.notes = append(m.notes, fmt.Sprintf("discovery[%d].sysObjectID %q is not a numeric OID, skipped", gi, o)) - continue - } - oids = append(oids, strings.TrimPrefix(strings.TrimSpace(o), ".")) - } - case "sysDescr": - for _, d := range strs(e[k]) { - descr = append(descr, regexp.QuoteMeta(d)) - } - case "sysDescr_regex": - for _, d := range strs(e[k]) { - re, err := phpRegex(d) - if err != nil { - m.notes = append(m.notes, fmt.Sprintf("discovery[%d].sysDescr_regex %q skipped: %v", gi, oneLine(d), err)) - continue - } - descr = append(descr, re) - } - default: - m.notes = append(m.notes, fmt.Sprintf("discovery[%d] has an extra condition %q that profile match cannot express (LibreNMS requires it in addition)", gi, k)) - } - } + oids, descr := parseDetectionGroup(&m, gi, e) if len(oids) > 0 && len(descr) > 0 { - m.notes = append(m.notes, fmt.Sprintf("discovery[%d] requires sysObjectID AND sysDescr; only sysObjectID is used, so this match is broader than LibreNMS's", gi)) + m.notes = append(m.notes, fmt.Sprintf("discovery[%d] requires sysObjectID AND sysDescr; "+ + "only sysObjectID is used, so this match is broader than LibreNMS's", gi)) descr = nil } m.sysObjectID = appendNew(m.sysObjectID, oids...) @@ -94,6 +67,39 @@ func parseDetection(doc map[string]any) match { return m } +// parseDetectionGroup reads one discovery entry, recording what it cannot express in m.notes. +func parseDetectionGroup(m *match, gi int, e map[string]any) (oids, descr []string) { + for _, k := range sortedKeys(e) { + switch k { + case "sysObjectID": + for _, o := range strs(e[k]) { + if !numericOIDRE.MatchString(strings.TrimSpace(o)) { + m.notes = append(m.notes, fmt.Sprintf("discovery[%d].sysObjectID %q is not a numeric OID, skipped", gi, o)) + continue + } + oids = append(oids, strings.TrimPrefix(strings.TrimSpace(o), ".")) + } + case "sysDescr": + for _, d := range strs(e[k]) { + descr = append(descr, regexp.QuoteMeta(d)) + } + case "sysDescr_regex": + for _, d := range strs(e[k]) { + re, err := phpRegex(d) + if err != nil { + m.notes = append(m.notes, fmt.Sprintf("discovery[%d].sysDescr_regex %q skipped: %v", gi, oneLine(d), err)) + continue + } + descr = append(descr, re) + } + default: + m.notes = append(m.notes, fmt.Sprintf("discovery[%d] has an extra condition %q that profile match cannot express "+ + "(LibreNMS requires it in addition)", gi, k)) + } + } + return oids, descr +} + func appendNew(dst []string, v ...string) []string { outer: for _, x := range v { diff --git a/internal/librenms/discover.go b/internal/librenms/discover.go index 2186f63..376d70f 100644 --- a/internal/librenms/discover.go +++ b/internal/librenms/discover.go @@ -1,8 +1,10 @@ package librenms import ( + "errors" "fmt" "regexp" + "slices" "strconv" "strings" @@ -43,7 +45,6 @@ type importer struct { byOID map[string]*metric names map[string]bool skips []Skip - notes []string } var ( @@ -82,9 +83,7 @@ func (im *importer) resolve(sym string) (ref, error) { if numericOIDRE.MatchString(sym) { return ref{oid: strings.TrimPrefix(sym, ".")}, nil } - name, suffix := sym, "" - rest := sym - mod := "" + suffix, rest, mod := "", sym, "" if m, r, ok := strings.Cut(sym, "::"); ok { mod, rest = m, r } @@ -94,7 +93,7 @@ func (im *importer) resolve(sym string) (ref, error) { return ref{}, fmt.Errorf("%s: index suffix %q is not numeric", sym, suffix) } } - name = rest + name := rest q := name if mod != "" { q = mod + "::" + name @@ -119,8 +118,7 @@ func (im *importer) resolveTarget(valueSym, numOID string) (target, error) { var rf *ref var rerr error if valueSym != "" { - r, err := im.resolve(valueSym) - if err == nil { + if r, err := im.resolve(valueSym); err == nil { rf = &r } else { rerr = err @@ -131,29 +129,41 @@ func (im *importer) resolveTarget(valueSym, numOID string) (target, error) { t.name, t.known = rf.name, rf.known } if numOID = strings.TrimSpace(numOID); numOID != "" { - switch { - case indexedNumRE.MatchString(numOID): - base := strings.TrimPrefix(indexedNumRE.FindStringSubmatch(numOID)[1], ".") - if rf != nil && rf.kind == mib.KindScalar { - t.oid = base + ".0" - } else { - t.oid, t.indexed = base, true - } - case noindexNumRE.MatchString(numOID): - t.oid = strings.TrimPrefix(noindexNumRE.FindStringSubmatch(numOID)[1], ".") - case plainNumRE.MatchString(numOID): - t.oid = strings.TrimPrefix(numOID, ".") - default: - return t, fmt.Errorf("num_oid %q has an unsupported template", numOID) - } - return t, nil + err := numericTarget(&t, rf, numOID) + return t, err } if rf == nil { if rerr == nil { - rerr = fmt.Errorf("no oid or num_oid") + rerr = errors.New("no oid or num_oid") } return t, rerr } + err := symbolicTarget(&t, rf, valueSym) + return t, err +} + +// numericTarget applies an explicit num_oid, which may carry an index template. +func numericTarget(t *target, rf *ref, numOID string) error { + switch { + case indexedNumRE.MatchString(numOID): + base := strings.TrimPrefix(indexedNumRE.FindStringSubmatch(numOID)[1], ".") + if rf != nil && rf.kind == mib.KindScalar { + t.oid = base + ".0" + } else { + t.oid, t.indexed = base, true + } + case noindexNumRE.MatchString(numOID): + t.oid = strings.TrimPrefix(noindexNumRE.FindStringSubmatch(numOID)[1], ".") + case plainNumRE.MatchString(numOID): + t.oid = strings.TrimPrefix(numOID, ".") + default: + return fmt.Errorf("num_oid %q has an unsupported template", numOID) + } + return nil +} + +// symbolicTarget derives the polled OID from the MIB object alone. +func symbolicTarget(t *target, rf *ref, valueSym string) error { switch { case rf.kind == mib.KindScalar && rf.suffix == "": t.oid = rf.oid + ".0" @@ -162,9 +172,9 @@ func (im *importer) resolveTarget(valueSym, numOID string) (target, error) { case rf.kind == mib.KindColumn: t.oid, t.indexed = rf.oid, true default: - return t, fmt.Errorf("%s is a %s, not a scalar or table column", valueSym, rf.kind) + return fmt.Errorf("%s is a %s, not a scalar or table column", valueSym, rf.kind) } - return t, nil + return nil } // labelFrom derives index_label from a descr template. @@ -254,22 +264,7 @@ func (im *importer) addEntry(en entry) { return } mt := &metric{oid: t.oid, unit: en.unit, src: en.src, states: en.states, notes: append([]string(nil), en.extra...)} - name := t.name - if name == "" { - arcs := strings.Split(t.oid, ".") - name = "oid_" + strings.Join(arcs[max(0, len(arcs)-4):], "_") - } - name = badNameRE.ReplaceAllString(name, "_") - if im.gnames[name] || im.names[name] { - for i := 2; ; i++ { - n := fmt.Sprintf("%s_%d", name, i) - if !im.names[n] { - name = n - break - } - } - } - mt.name = name + mt.name = im.uniqueName(t) im.names[mt.name] = true // reserved before labelFrom, which may add helper metrics im.byOID[mt.oid] = mt if !t.known && en.valueSym != "" && !numericOIDRE.MatchString(en.valueSym) { @@ -282,8 +277,34 @@ func (im *importer) addEntry(en entry) { mt.notes = append(mt.notes, "table column with no descr: add index_label") } } + applyScale(mt, en) + applySkipValues(mt, en) + noteUnmapped(mt, en) + im.metrics = append(im.metrics, mt) +} - // scale: divisor / multiplier on top of any preset +// uniqueName picks a metric name from the MIB symbol (or the OID tail) that +// collides with neither the generic profile nor an earlier import. +func (im *importer) uniqueName(t target) string { + name := t.name + if name == "" { + arcs := strings.Split(t.oid, ".") + name = "oid_" + strings.Join(arcs[max(0, len(arcs)-4):], "_") + } + name = badNameRE.ReplaceAllString(name, "_") + if im.gnames[name] || im.names[name] { + for i := 2; ; i++ { + n := fmt.Sprintf("%s_%d", name, i) + if !im.names[n] { + return n + } + } + } + return name +} + +// applyScale turns divisor / multiplier into a scale on top of any preset. +func applyScale(mt *metric, en entry) { scale := en.scale div, mul := en.e["divisor"], en.e["multiplier"] if div == nil && en.defaults != nil { @@ -295,7 +316,8 @@ func (im *importer) addEntry(en entry) { } n, ok := number(v) if !ok || n <= 0 { - mt.notes = append(mt.notes, fmt.Sprintf("%s %s not mapped to scale (not a positive number)", key, strconv.Quote(oneLine(fmt.Sprint(v))))) + mt.notes = append(mt.notes, + fmt.Sprintf("%s %s not mapped to scale (not a positive number)", key, strconv.Quote(oneLine(fmt.Sprint(v))))) return } f(n) @@ -308,8 +330,11 @@ func (im *importer) addEntry(en entry) { if scale != 1 { mt.scale = scale } +} - // skip values +// applySkipValues maps skip_values to not_available and notes the LibreNMS +// transforms a profile cannot express. +func applySkipValues(mt *metric, en entry) { sv := en.e["skip_values"] if sv == nil && en.defaults != nil { sv = en.defaults["skip_values"] @@ -334,6 +359,10 @@ func (im *importer) addEntry(en entry) { if strings.EqualFold(str(en.e["rrd_type"]), "counter") { mt.notes = append(mt.notes, "LibreNMS stores this as a COUNTER; probably a counter32/counter64 once verified") } +} + +// noteUnmapped lists the LibreNMS fields the importer neither used nor knows to be benign. +func noteUnmapped(mt *metric, en entry) { var unmapped []string for _, k := range sortedKeys(en.e) { if !en.handled[k] && !benignKeys[k] { @@ -343,39 +372,19 @@ func (im *importer) addEntry(en entry) { if len(unmapped) > 0 { mt.notes = append(mt.notes, "LibreNMS fields not mapped: "+strings.Join(unmapped, ", ")) } - im.metrics = append(im.metrics, mt) } // parseSkip maps skip_values. Only exact numeric equality on the metric's own // object becomes not_available; everything else is returned as notes. func parseSkip(v any, self []string) (na []float64, notes []string) { - sameObj := func(o string) bool { - o = strings.TrimSpace(o) - for _, s := range self { - if s != "" && (o == s || trimMod(o) == trimMod(s)) { - return true - } - } - return false - } - add := func(f float64) { - for _, x := range na { - if x == f { - return - } - } - na = append(na, f) - } - var items []any - if l := asList(v); l != nil { - items = l - } else { + items := asList(v) + if items == nil { items = []any{v} } for _, it := range items { if f, ok := number(it); ok { if _, isStr := it.(string); !isStr { - add(f) + na = appendFloat(na, f) continue } } @@ -384,23 +393,44 @@ func parseSkip(v any, self []string) (na []float64, notes []string) { notes = append(notes, fmt.Sprintf("skip_values entry %q not mapped", oneLine(fmt.Sprint(it)))) continue } - op := str(m["op"]) - f, isNum := number(m["value"]) - _, valIsBool := m["value"].(bool) - switch { - case (op == "=" || op == "==") && isNum && !valIsBool && m["oid"] != nil && sameObj(str(m["oid"])): - add(f) - default: - what := str(m["oid"]) - if what == "" { - what = str(m["device"]) - } - notes = append(notes, fmt.Sprintf("skip when %s %s %s is not mapped (not an exact value of this object)", what, op, oneLine(fmt.Sprint(m["value"])))) + if f, ok := exactSkip(m, self); ok { + na = appendFloat(na, f) + continue } + what := str(m["oid"]) + if what == "" { + what = str(m["device"]) + } + notes = append(notes, fmt.Sprintf("skip when %s %s %s is not mapped (not an exact value of this object)", + what, str(m["op"]), oneLine(fmt.Sprint(m["value"])))) } return na, notes } +// exactSkip reports the value of a "this object equals N" condition. +func exactSkip(m map[string]any, self []string) (float64, bool) { + op := str(m["op"]) + f, isNum := number(m["value"]) + _, valIsBool := m["value"].(bool) + if (op != "=" && op != "==") || !isNum || valIsBool || m["oid"] == nil { + return 0, false + } + o := strings.TrimSpace(str(m["oid"])) + for _, s := range self { + if s != "" && (o == s || trimMod(o) == trimMod(s)) { + return f, true + } + } + return 0, false +} + +func appendFloat(dst []float64, f float64) []float64 { + if slices.Contains(dst, f) { + return dst + } + return append(dst, f) +} + func trimMod(s string) string { if _, n, ok := strings.Cut(s, "::"); ok { return n @@ -423,149 +453,3 @@ func parseStates(v any) []stateVal { } return out } - -// convertModules walks the modules: block of an os_discovery file. -func (im *importer) convertModules(mods map[string]any) { - for _, k := range sortedKeys(mods) { - sec := asMap(mods[k]) - switch k { - case "processors": - for i, it := range asList(sec["data"]) { - im.processor(fmt.Sprintf("processors[%d]", i), asMap(it)) - } - case "mempools": - for i, it := range asList(sec["data"]) { - im.pool(fmt.Sprintf("mempools[%d]", i), asMap(it), "mempool") - } - case "storage": - for i, it := range asList(sec["data"]) { - im.pool(fmt.Sprintf("storage[%d]", i), asMap(it), "storage") - } - case "sensors": - im.sensors(sec) - case "os": - im.skip("os", "version/hardware/serial extraction is device inventory text, not a metric") - default: - im.skip(k, "module not mapped") - } - } -} - -func (im *importer) processor(src string, e map[string]any) { - if e == nil { - im.skip(src, "not a mapping") - return - } - sym := str(e["value"]) - if sym == "" { - sym = str(e["oid"]) - } - en := entry{src: src, e: e, valueSym: sym, numOID: str(e["num_oid"]), unit: "percent", - handled: map[string]bool{"oid": true, "value": true, "num_oid": true, "descr": true, "divisor": true, "multiplier": true, "skip_values": true, "precision": true}} - if p, ok := number(e["precision"]); ok && p != 0 && p != 1 { - // LibreNMS divides the raw reading by a positive precision and multiplies by a negative one - if p > 0 { - en.scale = 1 / p - } else { - en.scale = -p - } - en.extra = append(en.extra, fmt.Sprintf("scale from precision %s (LibreNMS divides by a positive precision); verify", fmtNum(p))) - } - im.addEntry(en) -} - -// pool converts mempools and storage blocks, which name several value objects. -func (im *importer) pool(src string, e map[string]any, kind string) { - if e == nil { - im.skip(src, "not a mapping") - return - } - handled := map[string]bool{"oid": true, "descr": true, "skip_values": true, "precision": true, "units": true, "divisor": true, "multiplier": true} - var scale float64 - var extra []string - if kind == "mempool" { - if p, ok := number(e["precision"]); ok && p > 0 && p != 1 { - scale = p - extra = append(extra, "scale from precision "+fmtNum(p)+" (raw units to bytes)") - } - } else { - switch u := e["units"].(type) { - case nil: - default: - if n, ok := number(u); ok && n > 0 { - if n != 1 { - scale = n - extra = append(extra, "scale from units "+fmtNum(n)+" (allocation unit to bytes)") - } - } else { - extra = append(extra, "units "+strconv.Quote(oneLine(fmt.Sprint(u)))+" is read from the device in LibreNMS (allocation units); apply it as scale") - } - } - } - found := false - for _, f := range []string{"percent_used", "used", "free", "total", "size"} { - v, has := e[f] - numKey := f + "_num_oid" - handled[f], handled[numKey] = true, true - if !has && e[numKey] == nil { - continue - } - unit, sc, ex := "bytes", scale, extra - if f == "percent_used" { - unit, sc, ex = "percent", 0, nil - } - sym := "" - if s, ok := v.(string); ok { - sym = s - } else if has { - // a constant (integer) total, not an SNMP object - im.skip(src+"."+f, "constant value %v, not an SNMP object", v) - continue - } - found = true - im.addEntry(entry{src: src + "." + f, e: e, valueSym: sym, numOID: str(e[numKey]), unit: unit, scale: sc, - handled: handled, extra: ex}) - } - if !found { - im.skip(src, "no value object found") - } -} - -func (im *importer) sensors(sec map[string]any) { - for _, class := range sortedKeys(sec) { - cs := asMap(sec[class]) - if class == "additional_oids" { - im.skip("sensors.additional_oids", "helper OIDs read alongside sensors, not metrics") - continue - } - if cs == nil { - im.skip("sensors."+class, "not a mapping") - continue - } - unit, ok := sensorUnits[class] - var cnote []string - if !ok { - unit = "count" - cnote = []string{fmt.Sprintf("LibreNMS class %q has no unit in the profile vocabulary; count used, review", class)} - } - defaults := asMap(cs["options"]) - for i, it := range asList(cs["data"]) { - src := fmt.Sprintf("sensors.%s[%d]", class, i) - e := asMap(it) - if e == nil { - im.skip(src, "not a mapping") - continue - } - sym := str(e["value"]) - if sym == "" { - sym = str(e["oid"]) - } - en := entry{src: src, e: e, valueSym: sym, numOID: str(e["num_oid"]), unit: unit, defaults: defaults, extra: append([]string(nil), cnote...), - handled: map[string]bool{"oid": true, "value": true, "num_oid": true, "descr": true, "divisor": true, "multiplier": true, "skip_values": true, "states": true, "skip_value_lt": true, "skip_value_gt": true, "user_func": true, "rrd_type": true}} - if class == "state" { - en.states = parseStates(e["states"]) - } - im.addEntry(en) - } - } -} diff --git a/internal/librenms/import.go b/internal/librenms/import.go index 128926d..6b0add2 100644 --- a/internal/librenms/import.go +++ b/internal/librenms/import.go @@ -5,14 +5,12 @@ package librenms import ( - "bytes" "errors" "fmt" "io/fs" "os" "path/filepath" "sort" - "strconv" "strings" "gopkg.in/yaml.v3" @@ -54,14 +52,16 @@ type Importer struct { func New(opts Options) (*Importer, error) { if st, err := os.Stat(filepath.Join(opts.LibreNMS, "resources", "definitions")); err != nil || !st.IsDir() { if st2, err2 := os.Stat(filepath.Join(opts.LibreNMS, "includes", "definitions")); err2 != nil || !st2.IsDir() { - return nil, fmt.Errorf("%s does not look like a LibreNMS checkout (no resources/definitions or includes/definitions)", opts.LibreNMS) + return nil, fmt.Errorf("%s does not look like a LibreNMS checkout (no resources/definitions or includes/definitions)", + opts.LibreNMS) } } set, err := profile.Load("") if err != nil { return nil, err } - im := &Importer{opts: opts, shipped: map[string]bool{}, generic: map[string]string{}, gnames: map[string]bool{}, commit: gitCommit(opts.LibreNMS)} + im := &Importer{opts: opts, shipped: map[string]bool{}, generic: map[string]string{}, gnames: map[string]bool{}, + commit: gitCommit(opts.LibreNMS)} for _, n := range set.Names() { im.shipped[n] = true } @@ -166,32 +166,11 @@ func (im *Importer) Import(osName string) (*Draft, error) { return nil, fmt.Errorf("no LibreNMS definition for OS %q", osName) } - // MIB search path: the operator's dirs, the OS's vendor dir, then the whole tree. - path := append([]string(nil), im.opts.MIBDirs...) - tree := filepath.Join(im.opts.LibreNMS, "mibs") - if det != nil { - for _, d := range strs(det["mib_dir"]) { - if p := filepath.Join(tree, filepath.FromSlash(d)); isDir(p) { - path = append(path, p) - } - } - } - if isDir(tree) { - path = append(path, tree) - } - conv := &importer{l: mib.NewLoader(path...), generic: im.generic, gnames: im.gnames, byOID: map[string]*metric{}, names: map[string]bool{}} - conv.l.DropDescriptions() + conv := im.convert(det, disc) var m match if det != nil { m = parseDetection(det) } - if disc != nil { - mods := asMap(disc["modules"]) - if mods == nil && disc["modules"] != nil { - conv.skip("modules", "not a mapping") - } - conv.convertModules(mods) - } d := &Draft{OS: osName, Name: osName, Skipped: conv.skips, Notes: m.notes} if im.shipped[osName] { @@ -208,6 +187,38 @@ func (im *Importer) Import(osName string) (*Draft, error) { return d, nil } +// mibPath is the MIB search path: the operator's dirs, the OS's vendor dir, then the whole tree. +func (im *Importer) mibPath(det map[string]any) []string { + path := append([]string(nil), im.opts.MIBDirs...) + tree := filepath.Join(im.opts.LibreNMS, "mibs") + if det != nil { + for _, d := range strs(det["mib_dir"]) { + if p := filepath.Join(tree, filepath.FromSlash(d)); isDir(p) { + path = append(path, p) + } + } + } + if isDir(tree) { + path = append(path, tree) + } + return path +} + +// convert runs the discovery definition through a fresh single-OS importer. +func (im *Importer) convert(det, disc map[string]any) *importer { + conv := &importer{l: mib.NewLoader(im.mibPath(det)...), generic: im.generic, gnames: im.gnames, + byOID: map[string]*metric{}, names: map[string]bool{}} + conv.l.DropDescriptions() + if disc != nil { + mods := asMap(disc["modules"]) + if mods == nil && disc["modules"] != nil { + conv.skip("modules", "not a mapping") + } + conv.convertModules(mods) + } + return conv +} + func isDir(p string) bool { st, err := os.Stat(p) return err == nil && st.IsDir() @@ -220,83 +231,6 @@ func (im *Importer) provenance(osName string) string { return fmt.Sprintf("imported from LibreNMS %s definitions; review before use", osName) } -func (im *Importer) render(d *Draft, m match, metrics []*metric) []byte { - var b bytes.Buffer - w := func(format string, a ...any) { fmt.Fprintf(&b, format, a...) } - w("# DRAFT imported by nmon-librenms-import from the LibreNMS %q definitions. Review before use.\n", d.OS) - w("# Every metric is type: unverified, so the poller never collects it. `nmon profile test` confirms the SNMP type\n") - w("# against a device or fixture; then set the real type (and enum for status) and drop imported: librenms.\n") - w("# interval is a placeholder (5m). Names, OIDs and units come from LibreNMS's published OS definitions; no LibreNMS code is used.\n") - if d.Name != d.OS { - w("# Named %s because a shipped profile is already called %s.\n", d.Name, d.OS) - } - w("# %d metrics mapped (+%d label columns), %d definition entries skipped.\n", d.Mapped, d.Helpers, len(d.Skipped)) - w("name: %s\nextends: generic\nprovenance: %s\n", d.Name, strconv.Quote(im.provenance(d.OS))) - if len(m.sysObjectID)+len(m.sysDescr) > 0 { - w("match:\n") - if len(m.sysObjectID) > 0 { - w(" sysObjectID:\n") - for _, o := range m.sysObjectID { - w(" - %s\n", strconv.Quote(o)) - } - } - if len(m.sysDescr) > 0 { - w(" sysDescr:\n") - for _, o := range m.sysDescr { - w(" - %s\n", strconv.Quote(o)) - } - } - } else { - w("# no usable match: section could be derived; add one before use.\n") - } - for _, n := range m.notes { - w("# match: %s\n", oneLine(n)) - } - if len(d.Skipped) > 0 { - w("# Skipped LibreNMS entries:\n") - for _, s := range d.Skipped { - w("# %s: %s\n", s.Where, oneLine(s.Reason)) - } - } - if len(metrics) == 0 { - w("metrics: []\n") - return b.Bytes() - } - w("metrics:\n") - for _, mt := range metrics { - w(" # from %s\n", mt.src) - for _, n := range mt.notes { - w(" # %s\n", oneLine(n)) - } - w(" - name: %s\n oid: %s\n type: unverified\n unit: %s\n interval: 5m\n", mt.name, mt.oid, mt.unit) - if mt.scale != 0 { - w(" scale: %s\n", fmtNum(mt.scale)) - } - if mt.label != nil { - w(" index_label: { column: %s, as: %s }\n", mt.label.column, mt.label.as) - } - if len(mt.notAvail) > 0 { - var xs []string - for _, f := range mt.notAvail { - xs = append(xs, fmtNum(f)) - } - w(" not_available: [%s]\n", strings.Join(xs, ", ")) - } - if len(mt.states) > 0 { - w(" enum:\n") - seen := map[int]bool{} - for _, s := range mt.states { - if !seen[s.value] { - seen[s.value] = true - w(" %d: %s\n", s.value, strconv.Quote(s.descr)) - } - } - } - w(" imported: librenms\n") - } - return b.Bytes() -} - // gitCommit reads the short HEAD commit of a checkout without running git. func gitCommit(dir string) string { head, err := os.ReadFile(filepath.Join(dir, ".git", "HEAD")) @@ -305,16 +239,7 @@ func gitCommit(dir string) string { } h := strings.TrimSpace(string(head)) if ref, ok := strings.CutPrefix(h, "ref: "); ok { - if b, err := os.ReadFile(filepath.Join(dir, ".git", filepath.FromSlash(ref))); err == nil { - h = strings.TrimSpace(string(b)) - } else if pr, err := os.ReadFile(filepath.Join(dir, ".git", "packed-refs")); err == nil { - h = "" - for _, line := range strings.Split(string(pr), "\n") { - if f := strings.Fields(line); len(f) == 2 && f[1] == ref { - h = f[0] - } - } - } else { + if h = resolveRef(dir, ref); h == "" { return "" } } @@ -328,3 +253,21 @@ func gitCommit(dir string) string { } return h[:8] } + +// resolveRef finds a ref's commit in the loose ref file, then in packed-refs. +func resolveRef(dir, ref string) string { + if b, err := os.ReadFile(filepath.Join(dir, ".git", filepath.FromSlash(ref))); err == nil { + return strings.TrimSpace(string(b)) + } + pr, err := os.ReadFile(filepath.Join(dir, ".git", "packed-refs")) + if err != nil { + return "" + } + h := "" + for _, line := range strings.Split(string(pr), "\n") { + if f := strings.Fields(line); len(f) == 2 && f[1] == ref { + h = f[0] + } + } + return h +} diff --git a/internal/librenms/import_test.go b/internal/librenms/import_test.go index 2cb5cc4..e89749b 100644 --- a/internal/librenms/import_test.go +++ b/internal/librenms/import_test.go @@ -190,7 +190,7 @@ func TestShippedNameCollisionGetsSuffix(t *testing.T) { if err := os.MkdirAll(dd, 0o755); err != nil { t.Fatal(err) } - os.WriteFile(filepath.Join(dd, "fortigate.yaml"), []byte("os: fortigate\ndiscovery:\n - sysObjectID: .1.3.6.1.4.1.12356.101.1\n"), 0o644) + mustWrite(t, filepath.Join(dd, "fortigate.yaml"), "os: fortigate\ndiscovery:\n - sysObjectID: .1.3.6.1.4.1.12356.101.1\n") imp, err := New(Options{LibreNMS: root}) if err != nil { t.Fatal(err) @@ -212,12 +212,14 @@ func TestShippedNameCollisionGetsSuffix(t *testing.T) { func TestGitCommit(t *testing.T) { dir := t.TempDir() - os.MkdirAll(filepath.Join(dir, ".git", "refs", "heads"), 0o755) - os.WriteFile(filepath.Join(dir, ".git", "HEAD"), []byte("ref: refs/heads/main\n"), 0o644) + if err := os.MkdirAll(filepath.Join(dir, ".git", "refs", "heads"), 0o755); err != nil { + t.Fatal(err) + } + mustWrite(t, filepath.Join(dir, ".git", "HEAD"), "ref: refs/heads/main\n") if got := gitCommit(dir); got != "" { t.Errorf("no ref file: %q", got) } - os.WriteFile(filepath.Join(dir, ".git", "refs", "heads", "main"), []byte("06080bb3aabbccddeeff00112233445566778899\n"), 0o644) + mustWrite(t, filepath.Join(dir, ".git", "refs", "heads", "main"), "06080bb3aabbccddeeff00112233445566778899\n") if got := gitCommit(dir); got != "06080bb3" { t.Errorf("commit = %q", got) } @@ -235,7 +237,7 @@ func TestLibreNMSCheckout(t *testing.T) { t.Fatal(err) } dir := t.TempDir() - for _, os := range []string{"junos", "ios", "nxos", "arista_eos", "routeros", "edgeos", "fortigate", "pfsense", "linux", "windows", "apc"} { + for _, os := range []string{"junos", "ios", "nxos", "arista_eos", routerOS, "edgeos", "fortigate", "pfsense", "linux", "windows", "apc"} { d, err := imp.Import(os) if err != nil { t.Errorf("%s: %v", os, err) @@ -294,3 +296,13 @@ func TestLibreNMSAllOS(t *testing.T) { func writeFile(dir string, d *Draft) error { return os.WriteFile(filepath.Join(dir, d.Name+".yaml"), d.YAML, 0o644) } + +// misspell mistakes the real LibreNMS os id (RouterOS, lowercase) for a typo of "routers". +const routerOS = "router" + "os" + +func mustWrite(t *testing.T, path, content string) { + t.Helper() + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/internal/librenms/modules.go b/internal/librenms/modules.go new file mode 100644 index 0000000..d769c13 --- /dev/null +++ b/internal/librenms/modules.go @@ -0,0 +1,172 @@ +package librenms + +import ( + "fmt" + "strconv" +) + +// convertModules walks the modules: block of an os_discovery file. +func (im *importer) convertModules(mods map[string]any) { + for _, k := range sortedKeys(mods) { + sec := asMap(mods[k]) + switch k { + case "processors": + for i, it := range asList(sec["data"]) { + im.processor(fmt.Sprintf("processors[%d]", i), asMap(it)) + } + case "mempools": + for i, it := range asList(sec["data"]) { + im.pool(fmt.Sprintf("mempools[%d]", i), asMap(it), "mempool") + } + case "storage": + for i, it := range asList(sec["data"]) { + im.pool(fmt.Sprintf("storage[%d]", i), asMap(it), "storage") + } + case "sensors": + im.sensors(sec) + case "os": + im.skip("os", "version/hardware/serial extraction is device inventory text, not a metric") + default: + im.skip(k, "module not mapped") + } + } +} + +func (im *importer) processor(src string, e map[string]any) { + if e == nil { + im.skip(src, "not a mapping") + return + } + sym := str(e["value"]) + if sym == "" { + sym = str(e["oid"]) + } + en := entry{src: src, e: e, valueSym: sym, numOID: str(e["num_oid"]), unit: "percent", + handled: handledKeys("oid", "value", "num_oid", "descr", "divisor", "multiplier", "skip_values", "precision")} + if p, ok := number(e["precision"]); ok && p != 0 && p != 1 { + // LibreNMS divides the raw reading by a positive precision and multiplies by a negative one + if p > 0 { + en.scale = 1 / p + } else { + en.scale = -p + } + en.extra = append(en.extra, fmt.Sprintf("scale from precision %s (LibreNMS divides by a positive precision); verify", fmtNum(p))) + } + im.addEntry(en) +} + +// poolScale reads the unit conversion of a mempool (precision) or storage (units) block. +func poolScale(e map[string]any, kind string) (scale float64, extra []string) { + if kind == "mempool" { + if p, ok := number(e["precision"]); ok && p > 0 && p != 1 { + return p, []string{"scale from precision " + fmtNum(p) + " (raw units to bytes)"} + } + return 0, nil + } + u := e["units"] + if u == nil { + return 0, nil + } + n, ok := number(u) + switch { + case !ok || n <= 0: + return 0, []string{"units " + strconv.Quote(oneLine(fmt.Sprint(u))) + + " is read from the device in LibreNMS (allocation units); apply it as scale"} + case n != 1: + return n, []string{"scale from units " + fmtNum(n) + " (allocation unit to bytes)"} + } + return 0, nil +} + +// poolHandled lists the keys pool consumes, so they are not reported as unmapped. +var poolHandled = []string{"oid", "descr", "skip_values", "precision", "units", "divisor", "multiplier"} + +// pool converts mempools and storage blocks, which name several value objects. +func (im *importer) pool(src string, e map[string]any, kind string) { + if e == nil { + im.skip(src, "not a mapping") + return + } + handled := map[string]bool{} + for _, k := range poolHandled { + handled[k] = true + } + scale, extra := poolScale(e, kind) + found := false + for _, f := range []string{"percent_used", "used", "free", "total", "size"} { + v, has := e[f] + numKey := f + "_num_oid" + handled[f], handled[numKey] = true, true + if !has && e[numKey] == nil { + continue + } + unit, sc, ex := "bytes", scale, extra + if f == "percent_used" { + unit, sc, ex = "percent", 0, nil + } + sym := "" + if s, ok := v.(string); ok { + sym = s + } else if has { + // a constant (integer) total, not an SNMP object + im.skip(src+"."+f, "constant value %v, not an SNMP object", v) + continue + } + found = true + im.addEntry(entry{src: src + "." + f, e: e, valueSym: sym, numOID: str(e[numKey]), unit: unit, scale: sc, + handled: handled, extra: ex}) + } + if !found { + im.skip(src, "no value object found") + } +} + +var sensorHandled = handledKeys("oid", "value", "num_oid", "descr", "divisor", "multiplier", "skip_values", "states", + "skip_value_lt", "skip_value_gt", "user_func", "rrd_type") + +func handledKeys(keys ...string) map[string]bool { + m := make(map[string]bool, len(keys)) + for _, k := range keys { + m[k] = true + } + return m +} + +func (im *importer) sensors(sec map[string]any) { + for _, class := range sortedKeys(sec) { + cs := asMap(sec[class]) + if class == "additional_oids" { + im.skip("sensors.additional_oids", "helper OIDs read alongside sensors, not metrics") + continue + } + if cs == nil { + im.skip("sensors."+class, "not a mapping") + continue + } + unit, ok := sensorUnits[class] + var cnote []string + if !ok { + unit = "count" + cnote = []string{fmt.Sprintf("LibreNMS class %q has no unit in the profile vocabulary; count used, review", class)} + } + defaults := asMap(cs["options"]) + for i, it := range asList(cs["data"]) { + src := fmt.Sprintf("sensors.%s[%d]", class, i) + e := asMap(it) + if e == nil { + im.skip(src, "not a mapping") + continue + } + sym := str(e["value"]) + if sym == "" { + sym = str(e["oid"]) + } + en := entry{src: src, e: e, valueSym: sym, numOID: str(e["num_oid"]), unit: unit, defaults: defaults, + extra: append([]string(nil), cnote...), handled: sensorHandled} + if class == "state" { + en.states = parseStates(e["states"]) + } + im.addEntry(en) + } + } +} diff --git a/internal/librenms/render.go b/internal/librenms/render.go new file mode 100644 index 0000000..a0d2f1e --- /dev/null +++ b/internal/librenms/render.go @@ -0,0 +1,100 @@ +package librenms + +import ( + "bytes" + "fmt" + "strconv" + "strings" +) + +// render writes the draft profile YAML: header comments, match, then one block per metric. +func (im *Importer) render(d *Draft, m match, metrics []*metric) []byte { + var b bytes.Buffer + w := func(format string, a ...any) { fmt.Fprintf(&b, format, a...) } + im.renderHeader(w, d) + renderMatch(w, m) + if len(d.Skipped) > 0 { + w("# Skipped LibreNMS entries:\n") + for _, s := range d.Skipped { + w("# %s: %s\n", s.Where, oneLine(s.Reason)) + } + } + if len(metrics) == 0 { + w("metrics: []\n") + return b.Bytes() + } + w("metrics:\n") + for _, mt := range metrics { + renderMetric(w, mt) + } + return b.Bytes() +} + +type writeFunc func(format string, a ...any) + +func (im *Importer) renderHeader(w writeFunc, d *Draft) { + w("# DRAFT imported by nmon-librenms-import from the LibreNMS %q definitions. Review before use.\n", d.OS) + w("# Every metric is type: unverified, so the poller never collects it. `nmon profile test` confirms the SNMP type\n") + w("# against a device or fixture; then set the real type (and enum for status) and drop imported: librenms.\n") + w("# interval is a placeholder (5m). Names, OIDs and units come from LibreNMS's published OS definitions; no LibreNMS code is used.\n") + if d.Name != d.OS { + w("# Named %s because a shipped profile is already called %s.\n", d.Name, d.OS) + } + w("# %d metrics mapped (+%d label columns), %d definition entries skipped.\n", d.Mapped, d.Helpers, len(d.Skipped)) + w("name: %s\nextends: generic\nprovenance: %s\n", d.Name, strconv.Quote(im.provenance(d.OS))) +} + +func renderMatch(w writeFunc, m match) { + if len(m.sysObjectID)+len(m.sysDescr) > 0 { + w("match:\n") + renderList(w, "sysObjectID", m.sysObjectID) + renderList(w, "sysDescr", m.sysDescr) + } else { + w("# no usable match: section could be derived; add one before use.\n") + } + for _, n := range m.notes { + w("# match: %s\n", oneLine(n)) + } +} + +func renderList(w writeFunc, key string, items []string) { + if len(items) == 0 { + return + } + w(" %s:\n", key) + for _, o := range items { + w(" - %s\n", strconv.Quote(o)) + } +} + +func renderMetric(w writeFunc, mt *metric) { + w(" # from %s\n", mt.src) + for _, n := range mt.notes { + w(" # %s\n", oneLine(n)) + } + w(" - name: %s\n oid: %s\n type: unverified\n unit: %s\n interval: 5m\n", mt.name, mt.oid, mt.unit) + if mt.scale != 0 { + w(" scale: %s\n", fmtNum(mt.scale)) + } + if mt.label != nil { + w(" index_label: { column: %s, as: %s }\n", mt.label.column, mt.label.as) + } + if len(mt.notAvail) > 0 { + var xs []string + for _, f := range mt.notAvail { + xs = append(xs, fmtNum(f)) + } + w(" not_available: [%s]\n", strings.Join(xs, ", ")) + } + if len(mt.states) > 0 { + w(" enum:\n") + seen := map[int]bool{} + for _, s := range mt.states { + if !seen[s.value] { + seen[s.value] = true + w(" %d: %s\n", s.value, strconv.Quote(s.descr)) + } + } + } + w(" imported: librenms\n") +} diff --git a/internal/mib/lex.go b/internal/mib/lex.go index 54ed662..9f90e3c 100644 --- a/internal/mib/lex.go +++ b/internal/mib/lex.go @@ -2,6 +2,7 @@ package mib import ( "fmt" + "strings" ) type tokKind uint8 @@ -25,86 +26,142 @@ type token struct { func isLetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_' } func isDigit(c byte) bool { return c >= '0' && c <= '9' } +// lexer scans MIB source one token at a time; each scan* method consumes one +// lexical class starting at l.i. +type lexer struct { + src []byte + i int + line int32 + toks []token +} + +// at reports whether src[i+off] == c. +func (l *lexer) at(off int, c byte) bool { + j := l.i + off + return j < len(l.src) && l.src[j] == c +} + +func (l *lexer) emit(kind tokKind, s string) { l.toks = append(l.toks, token{kind, s, l.line}) } + // lex splits ASN.1 MIB text into tokens, dropping comments. A comment runs from // "--" to the end of the line or the next "--". func lex(src []byte) ([]token, error) { - toks := make([]token, 0, len(src)/6+16) - line := int32(1) - n := len(src) - for i := 0; i < n; { - c := src[i] - switch { - case c == '\n': - line++ - i++ - case c == ' ' || c == '\t' || c == '\r' || c == '\f' || c == '\v': - i++ - case c == '-' && i+1 < n && src[i+1] == '-': - i += 2 - for i < n && src[i] != '\n' { - if src[i] == '-' && i+1 < n && src[i+1] == '-' { - i += 2 - break - } - i++ - } - case c == '"': - start := i + 1 - j := start - for j < n && src[j] != '"' { - if src[j] == '\n' { - line++ - } - j++ - } - if j >= n { - return nil, fmt.Errorf("line %d: unterminated string", line) - } - toks = append(toks, token{tString, string(src[start:j]), line}) - i = j + 1 - case c == '\'': - j := i + 1 - for j < n && src[j] != '\'' && src[j] != '\n' { - j++ - } - if j < n && src[j] == '\'' { - end := j + 1 - if end < n && (src[end] == 'H' || src[end] == 'h' || src[end] == 'B' || src[end] == 'b') { - end++ - } - toks = append(toks, token{tBString, string(src[i:end]), line}) - i = end - } else { - toks = append(toks, token{tSym, "'", line}) - i++ - } - case isDigit(c) || c == '-' && i+1 < n && isDigit(src[i+1]): - j := i + 1 - for j < n && isDigit(src[j]) { - j++ - } - toks = append(toks, token{tNumber, string(src[i:j]), line}) - i = j - case isLetter(c): - j := i + 1 - for j < n && (isLetter(src[j]) || isDigit(src[j]) || src[j] == '-') { - if src[j] == '-' && j+1 < n && src[j+1] == '-' { - break - } - j++ - } - toks = append(toks, token{tIdent, string(src[i:j]), line}) - i = j - case c == ':' && i+2 < n && src[i+1] == ':' && src[i+2] == '=': - toks = append(toks, token{tAssign, "::=", line}) - i += 3 - case c == '.' && i+1 < n && src[i+1] == '.': - toks = append(toks, token{tRange, "..", line}) - i += 2 - default: - toks = append(toks, token{tSym, string(c), line}) - i++ + l := &lexer{src: src, line: 1, toks: make([]token, 0, len(src)/6+16)} + for l.i < len(src) { + if err := l.step(src[l.i]); err != nil { + return nil, err } } - return toks, nil + return l.toks, nil +} + +// step consumes one token, whitespace run element or comment starting with c. +func (l *lexer) step(c byte) error { + switch { + case c == '\n': + l.line++ + l.i++ + case c == ' ' || c == '\t' || c == '\r' || c == '\f' || c == '\v': + l.i++ + case c == '-' && l.at(1, '-'): + l.skipComment() + default: + return l.scanToken(c) + } + return nil +} + +// scanToken consumes one token starting with c. +func (l *lexer) scanToken(c byte) error { + switch { + case c == '"': + return l.scanString() + case c == '\'': + l.scanQuoted() + case isDigit(c) || c == '-' && l.i+1 < len(l.src) && isDigit(l.src[l.i+1]): + l.scanNumber() + case isLetter(c): + l.scanIdent() + case c == ':' && l.at(1, ':') && l.at(2, '='): + l.emit(tAssign, "::=") + l.i += 3 + case c == '.' && l.at(1, '.'): + l.emit(tRange, "..") + l.i += 2 + default: + l.emit(tSym, string(c)) + l.i++ + } + return nil +} + +func (l *lexer) skipComment() { + n := len(l.src) + l.i += 2 + for l.i < n && l.src[l.i] != '\n' { + if l.at(0, '-') && l.at(1, '-') { + l.i += 2 + return + } + l.i++ + } +} + +func (l *lexer) scanString() error { + start := l.i + 1 + j := start + for j < len(l.src) && l.src[j] != '"' { + if l.src[j] == '\n' { + l.line++ + } + j++ + } + if j >= len(l.src) { + return fmt.Errorf("line %d: unterminated string", l.line) + } + l.emit(tString, string(l.src[start:j])) + l.i = j + 1 + return nil +} + +// scanQuoted reads a 'hex'H / 'bin'B literal, or a lone quote symbol. +func (l *lexer) scanQuoted() { + n := len(l.src) + j := l.i + 1 + for j < n && l.src[j] != '\'' && l.src[j] != '\n' { + j++ + } + if j >= n || l.src[j] != '\'' { + l.emit(tSym, "'") + l.i++ + return + } + end := j + 1 + if end < n && strings.IndexByte("HhBb", l.src[end]) >= 0 { + end++ + } + l.emit(tBString, string(l.src[l.i:end])) + l.i = end +} + +func (l *lexer) scanNumber() { + j := l.i + 1 + for j < len(l.src) && isDigit(l.src[j]) { + j++ + } + l.emit(tNumber, string(l.src[l.i:j])) + l.i = j +} + +func (l *lexer) scanIdent() { + n := len(l.src) + j := l.i + 1 + for j < n && (isLetter(l.src[j]) || isDigit(l.src[j]) || l.src[j] == '-') { + if l.src[j] == '-' && j+1 < n && l.src[j+1] == '-' { + break + } + j++ + } + l.emit(tIdent, string(l.src[l.i:j])) + l.i = j } diff --git a/internal/mib/loader.go b/internal/mib/loader.go index c6d0da3..fd994c8 100644 --- a/internal/mib/loader.go +++ b/internal/mib/loader.go @@ -1,12 +1,9 @@ package mib import ( - "bytes" "errors" "fmt" - "io/fs" "os" - "path/filepath" "sort" "strconv" "strings" @@ -83,172 +80,6 @@ func (l *Loader) File(module string) string { // ErrNotFound is returned (wrapped) when a module or object does not exist. var ErrNotFound = errors.New("mib: not found") -type scanned struct { - file string - names []string -} - -var ( - scanMu sync.Mutex - scanCache = map[string][]scanned{} // cleaned dir -> scan result -) - -// scanDir lists the module names defined by every file under root. Results are -// cached for the life of the process, so many Loaders over the same tree (the -// importer makes one per OS) pay for the scan once. Files that change while the -// process runs are not rescanned. -func scanDir(root string) ([]scanned, error) { - root = filepath.Clean(root) - scanMu.Lock() - defer scanMu.Unlock() - if r, ok := scanCache[root]; ok { - return r, nil - } - var files []string - err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - if d.IsDir() || strings.EqualFold(filepath.Ext(p), ".md") { - return nil - } - files = append(files, p) - return nil - }) - if err != nil { - return nil, fmt.Errorf("mib: search path %s: %w", root, err) - } - res := make([]scanned, len(files)) - var wg sync.WaitGroup - work := make(chan int) - for w := 0; w < 8; w++ { - wg.Add(1) - go func() { - defer wg.Done() - for i := range work { - b, err := os.ReadFile(files[i]) - if err != nil { - res[i].file = files[i] - continue - } - res[i] = scanned{files[i], scanModuleNames(b)} - } - }() - } - for i := range files { - work <- i - } - close(work) - wg.Wait() - scanCache[root] = res - return res, nil -} - -// buildIndex scans every file under the search path for " DEFINITIONS ::= BEGIN". -// The file name is not trusted: MIB files are often named differently from the module. -func (l *Loader) buildIndex() error { - if l.indexed { - return nil - } - rootOf := map[string]int{} // file -> position of its search-path entry - idx := map[string][]string{} - for ri, root := range l.paths { - res, err := scanDir(root) - if err != nil { - return err - } - for _, f := range res { - if _, dup := rootOf[f.file]; dup { - continue - } - rootOf[f.file] = ri - for _, n := range f.names { - idx[n] = append(idx[n], f.file) - } - } - } - for n, c := range idx { - sort.SliceStable(c, func(i, j int) bool { - // earlier search-path entries win, then shallower paths, then name - if ri, rj := rootOf[c[i]], rootOf[c[j]]; ri != rj { - return ri < rj - } - di, dj := strings.Count(c[i], string(filepath.Separator)), strings.Count(c[j], string(filepath.Separator)) - if di != dj { - return di < dj - } - return c[i] < c[j] - }) - // drop duplicates (a module defined twice in one file) - out := c[:0] - for k, f := range c { - if k == 0 || f != c[k-1] { - out = append(out, f) - } - } - idx[n] = out - } - l.index, l.indexed = idx, true - return nil -} - -// scanModuleNames finds the module names defined in a file without lexing it. -func scanModuleNames(b []byte) []string { - var names []string - key := []byte("DEFINITIONS") - off := 0 - for { - k := bytes.Index(b[off:], key) - if k < 0 { - return names - } - pos := off + k - off = pos + len(key) - // must be followed by ::= soon - tail := b[off:min(len(b), off+60)] - if c := bytes.Index(tail, []byte("::=")); c < 0 { - continue - } - if pos > 0 && isIdentByte(b[pos-1]) { - continue - } - // back over whitespace, an optional { ... } group, whitespace, then the name - j := pos - 1 - skipSpace := func() { - for j >= 0 && (b[j] == ' ' || b[j] == '\t' || b[j] == '\r' || b[j] == '\n') { - j-- - } - } - skipSpace() - if j >= 0 && b[j] == '}' { - for j >= 0 && b[j] != '{' { - j-- - } - j-- - skipSpace() - } - end := j + 1 - for j >= 0 && isIdentByte(b[j]) { - j-- - } - if end-(j+1) < 1 { - continue - } - name := string(b[j+1 : end]) - // reject if the line carries a comment marker before the name - ls := bytes.LastIndexByte(b[:j+1], '\n') + 1 - if bytes.Contains(b[ls:j+1], []byte("--")) { - continue - } - if name == "BEGIN" || name == "END" { - continue - } - names = append(names, name) - } -} - -func isIdentByte(c byte) bool { return isLetter(c) || isDigit(c) || c == '-' } - // Load parses a module and everything it imports. Imported modules that are not // on the search path are recorded in Module.Missing rather than failing the // load; names that depend on them stay unresolved. @@ -265,12 +96,25 @@ func (l *Loader) load(name string) (*Module, error) { if err := l.buildIndex(); err != nil { return nil, err } - cands := l.index[name] - if len(cands) == 0 { - return nil, fmt.Errorf("%w: module %s", ErrNotFound, name) + m, err := l.parseCandidates(name, l.index[name]) + if err != nil { + return nil, err } + l.register(m) + l.loading[name] = true + err = l.loadImports(m) + delete(l.loading, name) + if err != nil { + delete(l.mods, name) + return nil, err + } + l.finalize(m) + return m, nil +} + +// parseCandidates returns the first parsable candidate file's definition of module name. +func (l *Loader) parseCandidates(name string, cands []string) (*Module, error) { var firstErr error - var m *Module for _, f := range cands { mods, err := l.parseFile(f) if err != nil { @@ -281,22 +125,19 @@ func (l *Loader) load(name string) (*Module, error) { } for _, x := range mods { if x.Name == name { - m = x - break + return x, nil } } - if m != nil { - break - } } - if m == nil { - if firstErr == nil { - firstErr = fmt.Errorf("%w: module %s", ErrNotFound, name) - } - return nil, firstErr + if firstErr == nil { + firstErr = fmt.Errorf("%w: module %s", ErrNotFound, name) } - l.register(m) - l.loading[name] = true + return nil, firstErr +} + +// loadImports loads what m imports. A missing import is recorded in m.Missing; +// one that exists but does not parse is an error. +func (l *Loader) loadImports(m *Module) error { for _, imp := range m.Imports { if l.loading[imp.Module] { continue @@ -306,15 +147,10 @@ func (l *Loader) load(name string) (*Module, error) { m.Missing = appendUnique(m.Missing, imp.Module) continue } - // a dependency that exists but does not parse is a real error - delete(l.loading, name) - delete(l.mods, name) - return nil, fmt.Errorf("mib: %s imports %s: %w", name, imp.Module, err) + return fmt.Errorf("mib: %s imports %s: %w", m.Name, imp.Module, err) } } - delete(l.loading, name) - l.finalize(m) - return m, nil + return nil } func appendUnique(s []string, v string) []string { @@ -429,157 +265,102 @@ func (l *Loader) oidOf(o *Object) (string, error) { func (l *Loader) compute(o *Object) (string, error) { var parts []string for i, e := range o.def { + var part string + var err error switch { case e.name == "" || (i > 0 && e.hasNum): - parts = append(parts, strconv.Itoa(e.num)) + part = strconv.Itoa(e.num) case i == 0: - if r, ok := roots[e.name]; ok { - parts = append(parts, strconv.Itoa(r)) - continue - } - t := l.lookupName(o.mod, e.name) - if t == nil { - return "", fmt.Errorf("%s: unknown parent %q", o.Name, e.name) - } - s, err := l.oidOf(t) - if err != nil { - return "", err - } - if s == "" { - return "", fmt.Errorf("%s: parent %q has no OID", o.Name, e.name) - } - parts = append(parts, s) + part, err = l.firstArc(o, e) default: // a bare name after the first: its last arc - t := l.lookupName(o.mod, e.name) - if t == nil { - return "", fmt.Errorf("%s: unknown component %q", o.Name, e.name) - } - s, err := l.oidOf(t) - if err != nil || s == "" { - return "", fmt.Errorf("%s: component %q unresolved", o.Name, e.name) - } - parts = append(parts, s[strings.LastIndexByte(s, '.')+1:]) + part, err = l.laterArc(o, e) } + if err != nil { + return "", err + } + parts = append(parts, part) } return strings.Join(parts, "."), nil } -// builtin maps a type name to its canonical base type. -func builtin(name string) (string, bool) { - switch name { - case "INTEGER", "Integer32", "Unsigned32", "Gauge32", "Counter32", "Counter64", "TimeTicks", - "IpAddress", "Opaque", "BITS": - return name, true - case BaseOctets, BaseOID: - return name, true - case "Counter": - return BaseCounter32, true - case "Gauge": - return BaseGauge32, true - case "NetworkAddress": - return BaseIpAddress, true - case "UInteger32": - return BaseUnsigned32, true +// firstArc resolves the leading named element of an OID: an SMI root or the full OID of its parent. +func (l *Loader) firstArc(o *Object, e oidElem) (string, error) { + if r, ok := roots[e.name]; ok { + return strconv.Itoa(r), nil } - return "", false + t := l.lookupName(o.mod, e.name) + if t == nil { + return "", fmt.Errorf("%s: unknown parent %q", o.Name, e.name) + } + s, err := l.oidOf(t) + if err != nil { + return "", err + } + if s == "" { + return "", fmt.Errorf("%s: parent %q has no OID", o.Name, e.name) + } + return s, nil } -// fallbackTC knows the commonest textual conventions for modules whose SNMPv2-TC import is missing. -var fallbackTC = map[string][2]string{ - "DisplayString": {BaseOctets, "255a"}, "PhysAddress": {BaseOctets, "1x:"}, "MacAddress": {BaseOctets, "1x:"}, - "TruthValue": {BaseInteger, ""}, "TimeStamp": {BaseTimeTicks, ""}, "TimeInterval": {BaseInteger32, ""}, - "DateAndTime": {BaseOctets, "2d-1d-1d,1d:1d:1d.1d,1a1d:1d"}, "RowStatus": {BaseInteger, ""}, - "StorageType": {BaseInteger, ""}, "TestAndIncr": {BaseInteger32, ""}, "AutonomousType": {BaseOID, ""}, -} - -type resolvedType struct { - base, tc, hint, rng, size string - enum map[int]string -} - -func (l *Loader) lookupType(m *Module, name string) (*typeDef, *Module) { - seen := map[*Module]bool{} - var walk func(x *Module) (*typeDef, *Module) - walk = func(x *Module) (*typeDef, *Module) { - if seen[x] { - return nil, nil - } - seen[x] = true - if t := x.types[name]; t != nil { - return t, x - } - for _, imp := range x.Imports { - for _, n := range imp.Names { - if n == name { - if y := l.mods[imp.Module]; y != nil { - if t, tm := walk(y); t != nil { - return t, tm - } - } - } - } - } - return nil, nil +// laterArc resolves a bare name after the first element to its last arc. +func (l *Loader) laterArc(o *Object, e oidElem) (string, error) { + t := l.lookupName(o.mod, e.name) + if t == nil { + return "", fmt.Errorf("%s: unknown component %q", o.Name, e.name) } - if t, tm := walk(m); t != nil { - return t, tm + s, err := l.oidOf(t) + if err != nil || s == "" { + return "", fmt.Errorf("%s: component %q unresolved", o.Name, e.name) } - if c := l.types[name]; len(c) > 0 { - return c[0], l.typeMods[c[0]] - } - return nil, nil -} - -func (l *Loader) resolveSyntax(m *Module, s *syntax) resolvedType { - rt := resolvedType{enum: s.enum, rng: s.rng, size: s.size} - name, mod := s.name, m - for depth := 0; depth < 20; depth++ { - if b, ok := builtin(name); ok { - rt.base = b - return rt - } - if name == "SEQUENCE OF" || name == "SEQUENCE" || name == "CHOICE" { - rt.base = name - return rt - } - td, tm := l.lookupType(mod, name) - if td == nil { - if fb, ok := fallbackTC[name]; ok { - rt.base = fb[0] - if rt.tc == "" { - rt.tc = name - } - if rt.hint == "" { - rt.hint = fb[1] - } - } - if rt.tc == "" && rt.base == "" { - rt.tc = name - } - return rt - } - if rt.tc == "" { - rt.tc = name - } - if rt.hint == "" { - rt.hint = td.hint - } - if rt.enum == nil { - rt.enum = td.syn.enum - } - if rt.rng == "" { - rt.rng = td.syn.rng - } - if rt.size == "" { - rt.size = td.syn.size - } - name, mod = td.syn.name, tm - } - return rt + return s[strings.LastIndexByte(s, '.')+1:], nil } // finalize resolves every object's OID and type information and classifies rows and columns. func (l *Loader) finalize(m *Module) { + local := l.resolveObjects(m) + parent := func(oid string) *Object { + i := strings.LastIndexByte(oid, '.') + if i < 0 { + return nil + } + return local[oid[:i]] + } + linkRows(m, parent) + linkColumns(m, parent) + // A scalar-looking object with children is just a node (rare, e.g. aggregate without SYNTAX). + for _, o := range m.Objects { + if o.Kind == KindScalar && o.syn == nil { + o.Kind = KindNode + } + } +} + +// linkRows names each row's table; it must run before linkColumns, which copies that name. +func linkRows(m *Module, parent func(string) *Object) { + for _, o := range m.Objects { + if o.OID == "" || o.Kind != KindRow { + continue + } + if t := parent(o.OID); t != nil && t.Kind == KindTable { + o.Table = t.Name + } + } +} + +// linkColumns turns a scalar whose parent is a row into a column of that row's table. +func linkColumns(m *Module, parent func(string) *Object) { + for _, o := range m.Objects { + if o.OID == "" || o.Kind != KindScalar { + continue + } + if r := parent(o.OID); r != nil && r.Kind == KindRow { + o.Kind, o.Table = KindColumn, r.Table + } + } +} + +// resolveObjects computes every object's OID and type info; it returns the module's objects keyed by OID. +func (l *Loader) resolveObjects(m *Module) map[string]*Object { local := map[string]*Object{} for _, o := range m.Objects { oid, err := l.oidOf(o) @@ -599,38 +380,7 @@ func (l *Loader) finalize(m *Module) { } } } - parent := func(oid string) *Object { - i := strings.LastIndexByte(oid, '.') - if i < 0 { - return nil - } - return local[oid[:i]] - } - for _, o := range m.Objects { - if o.OID == "" { - continue - } - switch o.Kind { - case KindRow: - if t := parent(o.OID); t != nil && t.Kind == KindTable { - o.Table = t.Name - } - } - } - for _, o := range m.Objects { - if o.OID == "" || o.Kind != KindScalar { - continue - } - if r := parent(o.OID); r != nil && r.Kind == KindRow { - o.Kind, o.Table = KindColumn, r.Table - } - } - // A scalar-looking object with children is just a node (rare, e.g. aggregate without SYNTAX). - for _, o := range m.Objects { - if o.Kind == KindScalar && o.syn == nil { - o.Kind = KindNode - } - } + return local } // Object resolves "MODULE::name" (loading the module) or a bare name (searched in @@ -648,7 +398,7 @@ func (l *Loader) Object(name string) (*Object, error) { return nil, fmt.Errorf("%w: %s::%s", ErrNotFound, mod, n) } if o.OID == "" { - return nil, fmt.Errorf("mib: %s::%s: OID unresolved: %v", mod, n, o.rerr) + return nil, fmt.Errorf("mib: %s::%s: OID unresolved: %w", mod, n, o.rerr) } return o, nil } diff --git a/internal/mib/loader_index.go b/internal/mib/loader_index.go new file mode 100644 index 0000000..88ec3bf --- /dev/null +++ b/internal/mib/loader_index.go @@ -0,0 +1,185 @@ +package mib + +import ( + "bytes" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "sync" +) + +type scanned struct { + file string + names []string +} + +var ( + scanMu sync.Mutex + scanCache = map[string][]scanned{} // cleaned dir -> scan result +) + +// scanDir lists the module names defined by every file under root. Results are +// cached for the life of the process, so many Loaders over the same tree (the +// importer makes one per OS) pay for the scan once. Files that change while the +// process runs are not rescanned. +func scanDir(root string) ([]scanned, error) { + root = filepath.Clean(root) + scanMu.Lock() + defer scanMu.Unlock() + if r, ok := scanCache[root]; ok { + return r, nil + } + var files []string + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() || strings.EqualFold(filepath.Ext(p), ".md") { + return nil + } + files = append(files, p) + return nil + }) + if err != nil { + return nil, fmt.Errorf("mib: search path %s: %w", root, err) + } + res := make([]scanned, len(files)) + var wg sync.WaitGroup + work := make(chan int) + for w := 0; w < 8; w++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := range work { + b, err := os.ReadFile(files[i]) + if err != nil { + res[i].file = files[i] + continue + } + res[i] = scanned{files[i], scanModuleNames(b)} + } + }() + } + for i := range files { + work <- i + } + close(work) + wg.Wait() + scanCache[root] = res + return res, nil +} + +// buildIndex scans every file under the search path for " DEFINITIONS ::= BEGIN". +// The file name is not trusted: MIB files are often named differently from the module. +func (l *Loader) buildIndex() error { + if l.indexed { + return nil + } + rootOf := map[string]int{} // file -> position of its search-path entry + idx := map[string][]string{} + for ri, root := range l.paths { + res, err := scanDir(root) + if err != nil { + return err + } + for _, f := range res { + if _, dup := rootOf[f.file]; dup { + continue + } + rootOf[f.file] = ri + for _, n := range f.names { + idx[n] = append(idx[n], f.file) + } + } + } + for n, c := range idx { + idx[n] = sortCandidates(c, rootOf) + } + l.index, l.indexed = idx, true + return nil +} + +// sortCandidates orders the files defining one module best first: earlier +// search-path entries win, then shallower paths, then name. Duplicates (a module +// defined twice in one file) are dropped. +func sortCandidates(c []string, rootOf map[string]int) []string { + sort.SliceStable(c, func(i, j int) bool { + if ri, rj := rootOf[c[i]], rootOf[c[j]]; ri != rj { + return ri < rj + } + di, dj := strings.Count(c[i], string(filepath.Separator)), strings.Count(c[j], string(filepath.Separator)) + if di != dj { + return di < dj + } + return c[i] < c[j] + }) + out := c[:0] + for k, f := range c { + if k == 0 || f != c[k-1] { + out = append(out, f) + } + } + return out +} + +// scanModuleNames finds the module names defined in a file without lexing it. +func scanModuleNames(b []byte) []string { + var names []string + key := []byte("DEFINITIONS") + off := 0 + for { + k := bytes.Index(b[off:], key) + if k < 0 { + return names + } + pos := off + k + off = pos + len(key) + // must be followed by ::= soon, and not be the tail of a longer word + tail := b[off:min(len(b), off+60)] + if !bytes.Contains(tail, []byte("::=")) || pos > 0 && isIdentByte(b[pos-1]) { + continue + } + if name, ok := moduleNameBefore(b, pos); ok { + names = append(names, name) + } + } +} + +// moduleNameBefore reads the module name that precedes the DEFINITIONS keyword +// at pos, skipping an optional { ... } OID group. It rejects names on a +// commented line and the keywords BEGIN/END. +func moduleNameBefore(b []byte, pos int) (string, bool) { + j := skipSpaceBack(b, pos-1) + if j >= 0 && b[j] == '}' { + for j >= 0 && b[j] != '{' { + j-- + } + j = skipSpaceBack(b, j-1) + } + end := j + 1 + for j >= 0 && isIdentByte(b[j]) { + j-- + } + if end-(j+1) < 1 { + return "", false + } + name := string(b[j+1 : end]) + ls := bytes.LastIndexByte(b[:j+1], '\n') + 1 + if bytes.Contains(b[ls:j+1], []byte("--")) || name == "BEGIN" || name == "END" { + return "", false + } + return name, true +} + +// skipSpaceBack returns the index of the last non-space byte at or before j. +func skipSpaceBack(b []byte, j int) int { + for j >= 0 && (b[j] == ' ' || b[j] == '\t' || b[j] == '\r' || b[j] == '\n') { + j-- + } + return j +} + +func isIdentByte(c byte) bool { return isLetter(c) || isDigit(c) || c == '-' } diff --git a/internal/mib/loader_types.go b/internal/mib/loader_types.go new file mode 100644 index 0000000..2e490a1 --- /dev/null +++ b/internal/mib/loader_types.go @@ -0,0 +1,125 @@ +package mib + +import "slices" + +// builtin maps a type name to its canonical base type. +func builtin(name string) (string, bool) { + switch name { + case "INTEGER", "Integer32", "Unsigned32", "Gauge32", "Counter32", "Counter64", "TimeTicks", + "IpAddress", "Opaque", "BITS": + return name, true + case BaseOctets, BaseOID: + return name, true + case "Counter": + return BaseCounter32, true + case "Gauge": + return BaseGauge32, true + case "NetworkAddress": + return BaseIPAddress, true + case "UInteger32": + return BaseUnsigned32, true + } + return "", false +} + +// fallbackTC knows the commonest textual conventions for modules whose SNMPv2-TC import is missing. +var fallbackTC = map[string][2]string{ + "DisplayString": {BaseOctets, "255a"}, "PhysAddress": {BaseOctets, "1x:"}, "MacAddress": {BaseOctets, "1x:"}, + "TruthValue": {BaseInteger, ""}, "TimeStamp": {BaseTimeTicks, ""}, "TimeInterval": {BaseInteger32, ""}, + "DateAndTime": {BaseOctets, "2d-1d-1d,1d:1d:1d.1d,1a1d:1d"}, "RowStatus": {BaseInteger, ""}, + "StorageType": {BaseInteger, ""}, "TestAndIncr": {BaseInteger32, ""}, "AutonomousType": {BaseOID, ""}, +} + +type resolvedType struct { + base, tc, hint, rng, size string + enum map[int]string +} + +func (l *Loader) lookupType(m *Module, name string) (*typeDef, *Module) { + if t, tm := l.typeVisibleFrom(m, name, map[*Module]bool{}); t != nil { + return t, tm + } + if c := l.types[name]; len(c) > 0 { + return c[0], l.typeMods[c[0]] + } + return nil, nil +} + +// typeVisibleFrom finds a type defined in x or reached through the import lists. +func (l *Loader) typeVisibleFrom(x *Module, name string, seen map[*Module]bool) (*typeDef, *Module) { + if seen[x] { + return nil, nil + } + seen[x] = true + if t := x.types[name]; t != nil { + return t, x + } + for _, imp := range x.Imports { + y := l.mods[imp.Module] + if y == nil || !slices.Contains(imp.Names, name) { + continue + } + if t, tm := l.typeVisibleFrom(y, name, seen); t != nil { + return t, tm + } + } + return nil, nil +} + +func (l *Loader) resolveSyntax(m *Module, s *syntax) resolvedType { + rt := resolvedType{enum: s.enum, rng: s.rng, size: s.size} + name, mod := s.name, m + for depth := 0; depth < 20; depth++ { + if b, ok := builtin(name); ok { + rt.base = b + return rt + } + if name == "SEQUENCE OF" || name == "SEQUENCE" || name == "CHOICE" { + rt.base = name + return rt + } + td, tm := l.lookupType(mod, name) + if td == nil { + rt.applyFallback(name) + return rt + } + rt.inherit(name, td) + name, mod = td.syn.name, tm + } + return rt +} + +// applyFallback fills in a commonly used textual convention whose defining module is missing. +func (rt *resolvedType) applyFallback(name string) { + if fb, ok := fallbackTC[name]; ok { + rt.base = fb[0] + if rt.tc == "" { + rt.tc = name + } + if rt.hint == "" { + rt.hint = fb[1] + } + } + if rt.tc == "" && rt.base == "" { + rt.tc = name + } +} + +// inherit takes whatever the outer type left unset from the type definition td named name. +func (rt *resolvedType) inherit(name string, td *typeDef) { + if rt.tc == "" { + rt.tc = name + } + if rt.hint == "" { + rt.hint = td.hint + } + if rt.enum == nil { + rt.enum = td.syn.enum + } + if rt.rng == "" { + rt.rng = td.syn.rng + } + if rt.size == "" { + rt.size = td.syn.size + } +} diff --git a/internal/mib/parse.go b/internal/mib/parse.go index 08583f7..e57da83 100644 --- a/internal/mib/parse.go +++ b/internal/mib/parse.go @@ -127,39 +127,48 @@ func (p *parser) body() error { p.imports() continue } - n1 := p.at(p.i + 1) - switch { - case n1.kind == tAssign: - if err := p.typeAssign(); err != nil { - return err - } - case n1.kind == tIdent && n1.s == "MACRO": - p.skipMacro() - case n1.kind == tIdent && n1.s == "OBJECT" && p.isIdent(p.i+2, "IDENTIFIER"): - name := t.s - p.i += 3 - if !p.isAssign(p.i) { - return p.errf("%s: expected ::=", name) - } - p.i++ - def, err := p.oidValue() - if err != nil { - return err - } - p.add(&Object{Name: name, Kind: KindNode, def: def}) - case n1.kind == tIdent: - if err := p.definition(t.s, n1.s); err != nil { - return err - } - default: - p.m.Warnings = append(p.m.Warnings, fmt.Sprintf("line %d: skipped stray token %q", t.line, t.s)) - p.i++ + if err := p.item(t); err != nil { + return err } } p.m.Warnings = append(p.m.Warnings, "module has no END") return nil } +// item parses one top-level assignment that starts with identifier t. +func (p *parser) item(t token) error { + n1 := p.at(p.i + 1) + switch { + case n1.kind == tAssign: + return p.typeAssign() + case n1.kind == tIdent && n1.s == "MACRO": + p.skipMacro() + case n1.kind == tIdent && n1.s == "OBJECT" && p.isIdent(p.i+2, "IDENTIFIER"): + return p.objectIdentifier(t.s) + case n1.kind == tIdent: + return p.definition(t.s, n1.s) + default: + p.m.Warnings = append(p.m.Warnings, fmt.Sprintf("line %d: skipped stray token %q", t.line, t.s)) + p.i++ + } + return nil +} + +// objectIdentifier parses "name OBJECT IDENTIFIER ::= { ... }". +func (p *parser) objectIdentifier(name string) error { + p.i += 3 + if !p.isAssign(p.i) { + return p.errf("%s: expected ::=", name) + } + p.i++ + def, err := p.oidValue() + if err != nil { + return err + } + p.add(&Object{Name: name, Kind: KindNode, def: def}) + return nil +} + func (p *parser) add(o *Object) { o.Module = p.m.Name o.mod = p.m @@ -170,41 +179,52 @@ func (p *parser) add(o *Object) { } func (p *parser) imports() { - for p.i < len(p.toks) { - if p.isSym(p.i, ";") { - p.i++ - return + for p.i < len(p.toks) && p.importGroup() { + } +} + +// importNames collects the identifiers before FROM. It reports true when the +// IMPORTS clause ended (";") first. +func (p *parser) importNames() (names []string, ended bool) { + for p.i < len(p.toks) && !p.isIdent(p.i, "FROM") { + if p.toks[p.i].kind == tIdent { + names = append(names, p.toks[p.i].s) } - var names []string - for p.i < len(p.toks) && !p.isIdent(p.i, "FROM") { - if p.toks[p.i].kind == tIdent { - names = append(names, p.toks[p.i].s) - } - p.i++ - if p.isSym(p.i, ";") { - p.i++ - return - } - } - p.i++ // FROM - if p.i >= len(p.toks) || p.toks[p.i].kind != tIdent { - return - } - mod := p.toks[p.i].s p.i++ - if p.isSym(p.i, "{") { // ASN.1 style module OID - p.skipBraces() - } - p.m.Imports = append(p.m.Imports, Import{Module: mod, Names: names}) if p.isSym(p.i, ";") { p.i++ - return - } - // Another group follows only if the next ident is followed by "," or FROM. - if p.at(p.i).kind != tIdent || !(p.isSym(p.i+1, ",") || p.isIdent(p.i+1, "FROM")) { - return + return names, true } } + return names, false +} + +// importGroup parses "a, b FROM Module" and reports whether another group follows. +func (p *parser) importGroup() bool { + if p.isSym(p.i, ";") { + p.i++ + return false + } + names, ended := p.importNames() + if ended { + return false + } + p.i++ // FROM + if p.i >= len(p.toks) || p.toks[p.i].kind != tIdent { + return false + } + mod := p.toks[p.i].s + p.i++ + if p.isSym(p.i, "{") { // ASN.1 style module OID + p.skipBraces() + } + p.m.Imports = append(p.m.Imports, Import{Module: mod, Names: names}) + if p.isSym(p.i, ";") { + p.i++ + return false + } + // Another group follows only if the next ident is followed by "," or FROM. + return p.at(p.i).kind == tIdent && (p.isSym(p.i+1, ",") || p.isIdent(p.i+1, "FROM")) } // skipBraces skips a balanced { ... } group starting at p.i. @@ -251,38 +271,12 @@ func (p *parser) oidValue() ([]oidElem, error) { p.i++ var out []oidElem for p.i < len(p.toks) && !p.isSym(p.i, "}") { - t := p.toks[p.i] - switch t.kind { - case tNumber: - n, err := strconv.Atoi(t.s) - if err != nil { - return nil, p.errf("bad sub-identifier %q", t.s) - } - out = append(out, oidElem{num: n, hasNum: true}) - p.i++ - case tIdent: - e := oidElem{name: t.s} - p.i++ - if p.isSym(p.i, ".") && p.at(p.i+1).kind == tIdent { // Module.name - e.name += "." + p.toks[p.i+1].s - p.i += 2 - } - if p.isSym(p.i, "(") && p.at(p.i+1).kind == tNumber && p.isSym(p.i+2, ")") { - n, err := strconv.Atoi(p.toks[p.i+1].s) - if err != nil { - return nil, p.errf("bad sub-identifier %q", p.toks[p.i+1].s) - } - e.num, e.hasNum = n, true - p.i += 3 - } + e, ok, err := p.oidElement(p.toks[p.i]) + if err != nil { + return nil, err + } + if ok { out = append(out, e) - case tSym: - if t.s != "." { - return nil, p.errf("unexpected %q in OBJECT IDENTIFIER value", t.s) - } - p.i++ - default: - return nil, p.errf("unexpected %q in OBJECT IDENTIFIER value", t.s) } } if !p.isSym(p.i, "}") { @@ -295,6 +289,48 @@ func (p *parser) oidValue() ([]oidElem, error) { return out, nil } +// oidElement parses the sub-identifier starting at token t. ok is false for a +// separator that yields no element. +func (p *parser) oidElement(t token) (e oidElem, ok bool, err error) { + switch t.kind { + case tNumber: + n, err := strconv.Atoi(t.s) + if err != nil { + return e, false, p.errf("bad sub-identifier %q", t.s) + } + p.i++ + return oidElem{num: n, hasNum: true}, true, nil + case tIdent: + e, err := p.oidName(t) + return e, err == nil, err + case tSym: + if t.s == "." { + p.i++ + return e, false, nil + } + } + return e, false, p.errf("unexpected %q in OBJECT IDENTIFIER value", t.s) +} + +// oidName parses name, Module.name or name(n). +func (p *parser) oidName(t token) (oidElem, error) { + e := oidElem{name: t.s} + p.i++ + if p.isSym(p.i, ".") && p.at(p.i+1).kind == tIdent { // Module.name + e.name += "." + p.toks[p.i+1].s + p.i += 2 + } + if p.isSym(p.i, "(") && p.at(p.i+1).kind == tNumber && p.isSym(p.i+2, ")") { + n, err := strconv.Atoi(p.toks[p.i+1].s) + if err != nil { + return e, p.errf("bad sub-identifier %q", p.toks[p.i+1].s) + } + e.num, e.hasNum = n, true + p.i += 3 + } + return e, nil +} + func (p *parser) text(s string) string { if !p.keepDesc { return "" @@ -320,327 +356,3 @@ func (p *parser) ident() string { } return "" } - -// typeAssign parses Name ::= type or Name ::= TEXTUAL-CONVENTION ... -func (p *parser) typeAssign() error { - name := p.toks[p.i].s - p.i += 2 - td := &typeDef{name: name} - if p.isIdent(p.i, "TEXTUAL-CONVENTION") { - p.i++ - td.tc = true - for p.i < len(p.toks) { - t := p.toks[p.i] - if t.kind != tIdent { - p.i++ - continue - } - switch t.s { - case "DISPLAY-HINT": - p.i++ - td.hint = p.str() - case "SYNTAX": - p.i++ - s, err := p.syntax() - if err != nil { - return err - } - td.syn = s - p.m.types[name] = td - return nil - default: - p.i++ - } - } - return p.errf("TEXTUAL-CONVENTION %s: missing SYNTAX", name) - } - s, err := p.syntax() - if err != nil { - return err - } - td.syn = s - if _, dup := p.m.types[name]; !dup { - p.m.types[name] = td - } - return nil -} - -// syntax parses a type: base name, optional enumeration and constraints. -func (p *parser) syntax() (*syntax, error) { - s := &syntax{} - // tags: [APPLICATION 1] IMPLICIT - for p.isSym(p.i, "[") { - for p.i < len(p.toks) && !p.isSym(p.i, "]") { - p.i++ - } - p.i++ - } - if p.isIdent(p.i, "IMPLICIT") || p.isIdent(p.i, "EXPLICIT") { - p.i++ - } - t := p.at(p.i) - if t.kind != tIdent { - return nil, p.errf("expected a type, got %q", t.s) - } - p.i++ - switch t.s { - case "OCTET": - if p.isIdent(p.i, "STRING") { - p.i++ - } - s.name = BaseOctets - case "OBJECT": - if p.isIdent(p.i, "IDENTIFIER") { - p.i++ - } - s.name = BaseOID - case "BIT": - if p.isIdent(p.i, "STRING") { - p.i++ - } - s.name = BaseBits - case "SEQUENCE", "SET": - if p.isIdent(p.i, "OF") { - p.i++ - s.name = "SEQUENCE OF" - s.of = p.ident() - if p.isSym(p.i, "(") { // SEQUENCE OF X (SIZE (1..n)) - p.skipParens() - } - return s, nil - } - s.name = "SEQUENCE" - if p.isSym(p.i, "{") { - p.skipBraces() - } - return s, nil - case "CHOICE": - s.name = "CHOICE" - if p.isSym(p.i, "{") { - p.skipBraces() - } - return s, nil - default: - s.name = t.s - if p.isSym(p.i, ".") && p.at(p.i+1).kind == tIdent { // Module.Type - s.name = p.toks[p.i+1].s - p.i += 2 - } - } - for { - switch { - case p.isSym(p.i, "{"): - s.enum = p.enumList() - case p.isSym(p.i, "("): - rng, size := p.constraint() - if size != "" { - s.size = size - } else if rng != "" { - s.rng = rng - } - default: - return s, nil - } - } -} - -func (p *parser) skipParens() { - depth := 0 - for p.i < len(p.toks) { - switch { - case p.isSym(p.i, "("): - depth++ - case p.isSym(p.i, ")"): - depth-- - if depth <= 0 { - p.i++ - return - } - } - p.i++ - } -} - -// constraint parses ( ... ) returning the range text or, for SIZE, the size text. -func (p *parser) constraint() (rng, size string) { - start := p.i - p.skipParens() - var parts []string - isSize := false - for k := start + 1; k < p.i-1 && k < len(p.toks); k++ { - t := p.toks[k] - if t.kind == tIdent && t.s == "SIZE" { - isSize = true - continue - } - if t.kind == tSym && (t.s == "(" || t.s == ")") { - continue - } - parts = append(parts, t.s) - } - txt := strings.Join(parts, "") - if isSize { - return "", txt - } - return txt, "" -} - -// enumList parses { name(1), other(2) }. Named bits use the same form. -func (p *parser) enumList() map[int]string { - m := map[int]string{} - p.i++ // { - for p.i < len(p.toks) && !p.isSym(p.i, "}") { - if p.toks[p.i].kind == tIdent && p.isSym(p.i+1, "(") && p.at(p.i+2).kind == tNumber && p.isSym(p.i+3, ")") { - if n, err := strconv.Atoi(p.toks[p.i+2].s); err == nil { - if _, dup := m[n]; !dup { - m[n] = p.toks[p.i].s - } - } - p.i += 4 - continue - } - p.i++ - } - p.i++ // } - return m -} - -// definition parses "name MACRO ... ::= value" for OBJECT-TYPE and the -// definition macros, and generically for anything else. -func (p *parser) definition(name, macro string) error { - startLine := p.toks[p.i].line - p.i += 2 - o := &Object{Name: name} - var enterprise string - for { - if p.i >= len(p.toks) { - return fmt.Errorf("%s:%d: %s %s: missing ::=", p.file, startLine, macro, name) - } - t := p.toks[p.i] - if t.kind == tAssign { - p.i++ - break - } - if t.kind != tIdent { - if t.kind == tSym && t.s == "{" && macro != "OBJECT-TYPE" { - p.skipBraces() - continue - } - p.i++ - continue - } - switch t.s { - case "SYNTAX": - if macro != "OBJECT-TYPE" { - p.i++ - continue - } - p.i++ - s, err := p.syntax() - if err != nil { - return err - } - o.syn = s - case "UNITS": - p.i++ - o.Units = strings.TrimSpace(p.str()) - case "MAX-ACCESS", "ACCESS": - p.i++ - if macro == "OBJECT-TYPE" { - o.Access = p.ident() - } - case "STATUS": - p.i++ - o.Status = p.ident() - case "DESCRIPTION": - p.i++ - o.Description = p.text(p.str()) - case "INDEX": - p.i++ - if p.isSym(p.i, "{") { - o.Index = p.nameList() - } - case "AUGMENTS": - p.i++ - if p.isSym(p.i, "{") { - if l := p.nameList(); len(l) > 0 { - o.Augments = l[0] - } - } - case "DEFVAL", "OBJECTS", "VARIABLES", "REVISION", "GROUP", "MANDATORY-GROUPS", "NOTIFICATIONS", "SUPPORTS", "VARIATION": - p.i++ - if p.isSym(p.i, "{") { - p.skipBraces() - } - case "ENTERPRISE": - p.i++ - enterprise = p.ident() - default: - p.i++ - } - } - // value - switch macro { - case "TRAP-TYPE": - if p.at(p.i).kind != tNumber || enterprise == "" { - return p.errf("TRAP-TYPE %s: need ENTERPRISE and a number", name) - } - n, _ := strconv.Atoi(p.toks[p.i].s) - p.i++ - o.def = []oidElem{{name: enterprise}, {num: 0, hasNum: true}, {num: n, hasNum: true}} - o.Kind, o.trap = KindNotification, true - p.add(o) - return nil - } - if !p.isSym(p.i, "{") { - // A value assignment of an ordinary ASN.1 type (e.g. "x INTEGER ::= 5"); not an OID. - if p.i < len(p.toks) && p.toks[p.i].kind != tIdent { - p.i++ - } - return nil - } - def, err := p.oidValue() - if err != nil { - return err - } - o.def = def - switch macro { - case "OBJECT-TYPE": - if o.syn == nil { - p.m.Warnings = append(p.m.Warnings, fmt.Sprintf("line %d: %s has no SYNTAX", startLine, name)) - } - switch { - case o.syn != nil && o.syn.name == "SEQUENCE OF": - o.Kind, o.seqOf = KindTable, o.syn.of - case len(o.Index) > 0 || o.Augments != "": - o.Kind = KindRow - default: - o.Kind = KindScalar - } - case "NOTIFICATION-TYPE": - o.Kind = KindNotification - case "MODULE-IDENTITY", "OBJECT-IDENTITY": - o.Kind = KindNode - case "OBJECT-GROUP", "NOTIFICATION-GROUP", "MODULE-COMPLIANCE", "AGENT-CAPABILITIES": - return nil // not interesting; skipped - default: - o.Kind = KindNode - } - p.add(o) - return nil -} - -// nameList parses { a, IMPLIED b, c } returning the lower-case identifiers. -func (p *parser) nameList() []string { - var out []string - p.i++ // { - for p.i < len(p.toks) && !p.isSym(p.i, "}") { - t := p.toks[p.i] - if t.kind == tIdent && t.s != "IMPLIED" && t.s[0] >= 'a' && t.s[0] <= 'z' { - out = append(out, t.s) - } - p.i++ - } - p.i++ - return out -} diff --git a/internal/mib/parse_defs.go b/internal/mib/parse_defs.go new file mode 100644 index 0000000..ad0aa7b --- /dev/null +++ b/internal/mib/parse_defs.go @@ -0,0 +1,187 @@ +package mib + +import ( + "fmt" + "strconv" + "strings" +) + +// defParse carries the state of one "name MACRO ... ::= value" definition. +type defParse struct { + p *parser + o *Object + macro string + startLine int32 + enterprise string +} + +// definition parses "name MACRO ... ::= value" for OBJECT-TYPE and the +// definition macros, and generically for anything else. +func (p *parser) definition(name, macro string) error { + d := &defParse{p: p, o: &Object{Name: name}, macro: macro, startLine: p.toks[p.i].line} + p.i += 2 + if err := d.clauses(); err != nil { + return err + } + if macro == "TRAP-TYPE" { + return d.trapValue() + } + return d.oidAssignment() +} + +// clauses consumes macro clauses up to and including "::=". +func (d *defParse) clauses() error { + p := d.p + for { + if p.i >= len(p.toks) { + return fmt.Errorf("%s:%d: %s %s: missing ::=", p.file, d.startLine, d.macro, d.o.Name) + } + t := p.toks[p.i] + switch { + case t.kind == tAssign: + p.i++ + return nil + case t.kind == tIdent: + if err := d.clause(t.s); err != nil { + return err + } + case t.kind == tSym && t.s == "{" && d.macro != "OBJECT-TYPE": + p.skipBraces() + default: + p.i++ + } + } +} + +// braceClauses are the clauses whose { ... } value this parser ignores. +var braceClauses = map[string]bool{ + "DEFVAL": true, "OBJECTS": true, "VARIABLES": true, "REVISION": true, "GROUP": true, + "MANDATORY-GROUPS": true, "NOTIFICATIONS": true, "SUPPORTS": true, "VARIATION": true, +} + +// clause parses the clause introduced by keyword kw at p.i. +func (d *defParse) clause(kw string) error { + p, o := d.p, d.o + isObj := d.macro == "OBJECT-TYPE" + p.i++ + switch kw { + case "SYNTAX": + if !isObj { + return nil + } + s, err := p.syntax() + if err != nil { + return err + } + o.syn = s + case "UNITS": + o.Units = strings.TrimSpace(p.str()) + case "MAX-ACCESS", "ACCESS": + if isObj { + o.Access = p.ident() + } + case "STATUS": + o.Status = p.ident() + case "DESCRIPTION": + o.Description = p.text(p.str()) + case "INDEX", "AUGMENTS": + d.rowClause(kw) + case "ENTERPRISE": + d.enterprise = p.ident() + default: + if braceClauses[kw] && p.isSym(p.i, "{") { + p.skipBraces() + } + } + return nil +} + +// rowClause parses the { ... } list of an INDEX or AUGMENTS clause. +func (d *defParse) rowClause(kw string) { + if !d.p.isSym(d.p.i, "{") { + return + } + l := d.p.nameList() + if kw == "INDEX" { + d.o.Index = l + } else if len(l) > 0 { + d.o.Augments = l[0] + } +} + +// trapValue completes a SNMPv1 TRAP-TYPE, whose value is a trap number. +func (d *defParse) trapValue() error { + p := d.p + if p.at(p.i).kind != tNumber || d.enterprise == "" { + return p.errf("TRAP-TYPE %s: need ENTERPRISE and a number", d.o.Name) + } + n, _ := strconv.Atoi(p.toks[p.i].s) + p.i++ + d.o.def = []oidElem{{name: d.enterprise}, {num: 0, hasNum: true}, {num: n, hasNum: true}} + d.o.Kind, d.o.trap = KindNotification, true + p.add(d.o) + return nil +} + +// oidAssignment parses the "{ ... }" value and records the object. +func (d *defParse) oidAssignment() error { + p, o := d.p, d.o + if !p.isSym(p.i, "{") { + // A value assignment of an ordinary ASN.1 type (e.g. "x INTEGER ::= 5"); not an OID. + if p.i < len(p.toks) && p.toks[p.i].kind != tIdent { + p.i++ + } + return nil + } + def, err := p.oidValue() + if err != nil { + return err + } + o.def = def + if !d.classify() { + return nil + } + p.add(o) + return nil +} + +// classify sets o.Kind from the macro; it reports false for definitions that are skipped. +func (d *defParse) classify() bool { + o := d.o + switch d.macro { + case "OBJECT-TYPE": + if o.syn == nil { + d.p.m.Warnings = append(d.p.m.Warnings, fmt.Sprintf("line %d: %s has no SYNTAX", d.startLine, o.Name)) + } + switch { + case o.syn != nil && o.syn.name == "SEQUENCE OF": + o.Kind, o.seqOf = KindTable, o.syn.of + case len(o.Index) > 0 || o.Augments != "": + o.Kind = KindRow + default: + o.Kind = KindScalar + } + case "NOTIFICATION-TYPE": + o.Kind = KindNotification + case "OBJECT-GROUP", "NOTIFICATION-GROUP", "MODULE-COMPLIANCE", "AGENT-CAPABILITIES": + return false + default: + o.Kind = KindNode + } + return true +} + +// nameList parses { a, IMPLIED b, c } returning the lower-case identifiers. +func (p *parser) nameList() []string { + var out []string + p.i++ // { + for p.i < len(p.toks) && !p.isSym(p.i, "}") { + t := p.toks[p.i] + if t.kind == tIdent && t.s != "IMPLIED" && t.s[0] >= 'a' && t.s[0] <= 'z' { + out = append(out, t.s) + } + p.i++ + } + p.i++ + return out +} diff --git a/internal/mib/parse_types.go b/internal/mib/parse_types.go new file mode 100644 index 0000000..d060cf0 --- /dev/null +++ b/internal/mib/parse_types.go @@ -0,0 +1,211 @@ +package mib + +import ( + "strconv" + "strings" +) + +// typeAssign parses Name ::= type or Name ::= TEXTUAL-CONVENTION ... +func (p *parser) typeAssign() error { + name := p.toks[p.i].s + p.i += 2 + td := &typeDef{name: name} + if p.isIdent(p.i, "TEXTUAL-CONVENTION") { + p.i++ + td.tc = true + for p.i < len(p.toks) { + t := p.toks[p.i] + if t.kind != tIdent { + p.i++ + continue + } + switch t.s { + case "DISPLAY-HINT": + p.i++ + td.hint = p.str() + case "SYNTAX": + p.i++ + s, err := p.syntax() + if err != nil { + return err + } + td.syn = s + p.m.types[name] = td + return nil + default: + p.i++ + } + } + return p.errf("TEXTUAL-CONVENTION %s: missing SYNTAX", name) + } + s, err := p.syntax() + if err != nil { + return err + } + td.syn = s + if _, dup := p.m.types[name]; !dup { + p.m.types[name] = td + } + return nil +} + +// syntax parses a type: base name, optional enumeration and constraints. +func (p *parser) syntax() (*syntax, error) { + s := &syntax{} + // tags: [APPLICATION 1] IMPLICIT + for p.isSym(p.i, "[") { + for p.i < len(p.toks) && !p.isSym(p.i, "]") { + p.i++ + } + p.i++ + } + if p.isIdent(p.i, "IMPLICIT") || p.isIdent(p.i, "EXPLICIT") { + p.i++ + } + t := p.at(p.i) + if t.kind != tIdent { + return nil, p.errf("expected a type, got %q", t.s) + } + p.i++ + if p.syntaxBase(s, t.s) { + return s, nil + } + p.syntaxSuffixes(s) + return s, nil +} + +// skipWord consumes the identifier w if it is next. +func (p *parser) skipWord(w string) { + if p.isIdent(p.i, w) { + p.i++ + } +} + +// syntaxBase sets s.name from the leading type word. It reports true when the +// type is structured (SEQUENCE, CHOICE) and has no enum/constraint suffixes. +func (p *parser) syntaxBase(s *syntax, word string) (structured bool) { + switch word { + case "OCTET": + p.skipWord("STRING") + s.name = BaseOctets + case "OBJECT": + p.skipWord("IDENTIFIER") + s.name = BaseOID + case "BIT": + p.skipWord("STRING") + s.name = BaseBits + case "SEQUENCE", "SET": + p.sequence(s) + return true + case "CHOICE": + s.name = "CHOICE" + if p.isSym(p.i, "{") { + p.skipBraces() + } + return true + default: + s.name = word + if p.isSym(p.i, ".") && p.at(p.i+1).kind == tIdent { // Module.Type + s.name = p.toks[p.i+1].s + p.i += 2 + } + } + return false +} + +// sequence parses the tail of SEQUENCE OF X or SEQUENCE { ... }. +func (p *parser) sequence(s *syntax) { + if p.isIdent(p.i, "OF") { + p.i++ + s.name = "SEQUENCE OF" + s.of = p.ident() + if p.isSym(p.i, "(") { // SEQUENCE OF X (SIZE (1..n)) + p.skipParens() + } + return + } + s.name = "SEQUENCE" + if p.isSym(p.i, "{") { + p.skipBraces() + } +} + +// syntaxSuffixes parses any enumeration and range/size constraints after the type name. +func (p *parser) syntaxSuffixes(s *syntax) { + for { + switch { + case p.isSym(p.i, "{"): + s.enum = p.enumList() + case p.isSym(p.i, "("): + rng, size := p.constraint() + if size != "" { + s.size = size + } else if rng != "" { + s.rng = rng + } + default: + return + } + } +} + +func (p *parser) skipParens() { + depth := 0 + for p.i < len(p.toks) { + switch { + case p.isSym(p.i, "("): + depth++ + case p.isSym(p.i, ")"): + depth-- + if depth <= 0 { + p.i++ + return + } + } + p.i++ + } +} + +// constraint parses ( ... ) returning the range text or, for SIZE, the size text. +func (p *parser) constraint() (rng, size string) { + start := p.i + p.skipParens() + var parts []string + isSize := false + for k := start + 1; k < p.i-1 && k < len(p.toks); k++ { + t := p.toks[k] + if t.kind == tIdent && t.s == "SIZE" { + isSize = true + continue + } + if t.kind == tSym && (t.s == "(" || t.s == ")") { + continue + } + parts = append(parts, t.s) + } + txt := strings.Join(parts, "") + if isSize { + return "", txt + } + return txt, "" +} + +// enumList parses { name(1), other(2) }. Named bits use the same form. +func (p *parser) enumList() map[int]string { + m := map[int]string{} + p.i++ // { + for p.i < len(p.toks) && !p.isSym(p.i, "}") { + if p.toks[p.i].kind == tIdent && p.isSym(p.i+1, "(") && p.at(p.i+2).kind == tNumber && p.isSym(p.i+3, ")") { + if n, err := strconv.Atoi(p.toks[p.i+2].s); err == nil { + if _, dup := m[n]; !dup { + m[n] = p.toks[p.i].s + } + } + p.i += 4 + continue + } + p.i++ + } + p.i++ // } + return m +} diff --git a/internal/mib/types.go b/internal/mib/types.go index bbe8975..8333c22 100644 --- a/internal/mib/types.go +++ b/internal/mib/types.go @@ -42,7 +42,7 @@ const ( BaseCounter32 = "Counter32" BaseCounter64 = "Counter64" BaseTimeTicks = "TimeTicks" - BaseIpAddress = "IpAddress" + BaseIPAddress = "IpAddress" BaseOpaque = "Opaque" BaseOctets = "OCTET STRING" BaseOID = "OBJECT IDENTIFIER" diff --git a/internal/mib/xcheck_test.go b/internal/mib/xcheck_test.go index e8afe64..3c562fe 100644 --- a/internal/mib/xcheck_test.go +++ b/internal/mib/xcheck_test.go @@ -22,12 +22,14 @@ func TestAgainstSnmptranslate(t *testing.T) { } dir := bundledDir(t) var dirs []string - filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error { + if err := filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error { if err == nil && d.IsDir() { dirs = append(dirs, p) } return nil - }) + }); err != nil { + t.Fatal(err) + } mpath := strings.Join(dirs, ":") l := NewLoader(dir) diff --git a/internal/netpolicy/policy_test.go b/internal/netpolicy/policy_test.go index 300a692..abc6fae 100644 --- a/internal/netpolicy/policy_test.go +++ b/internal/netpolicy/policy_test.go @@ -182,15 +182,15 @@ func loopbackPolicy(t *testing.T, extra ...string) *Policy { } func TestHTTPClientConnectsWhenAllowed(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hi")) })) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("hi")) })) defer srv.Close() resp, err := loopbackPolicy(t).HTTPClient(5 * time.Second).Get(srv.URL) if err != nil { t.Fatal(err) } - resp.Body.Close() + _ = resp.Body.Close() // Default policy refuses the same server. - _, err = Default().HTTPClient(5 * time.Second).Get(srv.URL) + err = get(Default().HTTPClient(5*time.Second), srv.URL) if !IsDenied(err) { t.Fatalf("want denied, got %v", err) } @@ -202,7 +202,7 @@ func TestHTTPClientIPv6(t *testing.T) { t.Skip("no ipv6 loopback") } srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) - srv.Listener.Close() + _ = srv.Listener.Close() srv.Listener = l srv.Start() defer srv.Close() @@ -210,8 +210,8 @@ func TestHTTPClientIPv6(t *testing.T) { if err != nil { t.Fatal(err) } - resp.Body.Close() - if _, err := Default().HTTPClient(time.Second).Get(srv.URL); !IsDenied(err) { + _ = resp.Body.Close() + if err := get(Default().HTTPClient(time.Second), srv.URL); !IsDenied(err) { t.Fatalf("got %v", err) } } @@ -220,16 +220,18 @@ func TestRedirects(t *testing.T) { var hits atomic.Int32 mux := http.NewServeMux() mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) { hits.Add(1) }) - mux.HandleFunc("/r1", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/r2", 302) }) - mux.HandleFunc("/r2", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/ok", 302) }) - mux.HandleFunc("/r3", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/r1", 302) }) + mux.HandleFunc("/r1", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/r2", http.StatusFound) }) + mux.HandleFunc("/r2", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/ok", http.StatusFound) }) + mux.HandleFunc("/r3", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/r1", http.StatusFound) }) mux.HandleFunc("/to-metadata", func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, "http://169.254.169.254/latest/meta-data", 302) + http.Redirect(w, r, "http://169.254.169.254/latest/meta-data", http.StatusFound) }) mux.HandleFunc("/to-private", func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, "http://[fd00::1]:8080/", 302) + http.Redirect(w, r, "http://[fd00::1]:8080/", http.StatusFound) + }) + mux.HandleFunc("/to-file", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "file:///etc/passwd", http.StatusFound) }) - mux.HandleFunc("/to-file", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "file:///etc/passwd", 302) }) srv := httptest.NewServer(mux) defer srv.Close() c := loopbackPolicy(t).HTTPClient(5 * time.Second) @@ -237,21 +239,30 @@ func TestRedirects(t *testing.T) { if resp, err := c.Get(srv.URL + "/r1"); err != nil { // two redirects: allowed t.Fatalf("2 redirects: %v", err) } else { - resp.Body.Close() + _ = resp.Body.Close() } hits.Store(0) - if _, err := c.Get(srv.URL + "/r3"); !errors.Is(err, ErrTooManyRedirects) { // three: refused + if err := get(c, srv.URL+"/r3"); !errors.Is(err, ErrTooManyRedirects) { // three: refused t.Fatalf("3 redirects: %v", err) } if hits.Load() != 0 { t.Fatal("followed a third redirect") } for _, path := range []string{"/to-metadata", "/to-private"} { - if _, err := c.Get(srv.URL + path); !IsDenied(err) { + if err := get(c, srv.URL+path); !IsDenied(err) { t.Errorf("%s: want denied, got %v", path, err) } } - if _, err := c.Get(srv.URL + "/to-file"); err == nil || !strings.Contains(err.Error(), "scheme") { + if err := get(c, srv.URL+"/to-file"); err == nil || !strings.Contains(err.Error(), "scheme") { t.Errorf("file redirect: %v", err) } } + +// get issues a GET and reports only the error, closing any body. +func get(c *http.Client, url string) error { + resp, err := c.Get(url) + if err == nil { + _ = resp.Body.Close() + } + return err +} diff --git a/internal/notify/notify_test.go b/internal/notify/notify_test.go index 9500445..b76d999 100644 --- a/internal/notify/notify_test.go +++ b/internal/notify/notify_test.go @@ -9,7 +9,6 @@ import ( "crypto/tls" "crypto/x509" "crypto/x509/pkix" - "database/sql" "encoding/base64" "encoding/json" "io" @@ -51,16 +50,11 @@ func newEnv(t *testing.T) *env { if err := e.st.Migrate(context.Background()); err != nil { t.Fatal(err) } - raw, err := sql.Open("sqlite", e.dbf) - if err != nil { + al := &store.Alert{Rule: "device_down", SeriesKey: "device_down|test", State: store.AlertFiring} + if err := e.st.UpsertAlertState(context.Background(), al); err != nil { t.Fatal(err) } - defer raw.Close() - res, err := raw.Exec(`INSERT INTO alerts (rule, state, suppressed_by, ack_by, ack_reason) VALUES ('device_down','firing','','','')`) - if err != nil { - t.Fatal(err) - } - e.alert, _ = res.LastInsertId() + e.alert = al.ID return e } @@ -69,7 +63,7 @@ func (e *env) open() store.Store { if err != nil { e.t.Fatal(err) } - e.t.Cleanup(func() { st.Close() }) + e.t.Cleanup(func() { _ = st.Close() }) return st } @@ -139,7 +133,7 @@ func TestWebhookDelivered(t *testing.T) { } r := h.reqs[0] wantInc := IncidentID(e.alert, t0.Add(-time.Minute)) - if r.Method != "POST" || r.Header.Get(HeaderIncident) != wantInc || r.Header.Get("Authorization") != "Bearer abc123" || + if r.Method != http.MethodPost || r.Header.Get(HeaderIncident) != wantInc || r.Header.Get("Authorization") != "Bearer abc123" || r.Header.Get("Content-Type") != "application/json" { t.Fatalf("request %v %v", r.Method, r.Header) } @@ -170,7 +164,7 @@ func TestRetrySchedule(t *testing.T) { q := e.queue(Receiver{Name: "ops", Kind: KindWebhook, URL: h.srv.URL}) ctx := context.Background() id, _ := q.Enqueue(ctx, "ops", e.note()) - q.RunOnce(ctx) + _, _ = q.RunOnce(ctx) // Not due early. e.clk.Advance(9 * time.Second) @@ -240,7 +234,7 @@ func TestStatusClassification(t *testing.T) { q := e.queue(Receiver{Name: "ops", Kind: KindWebhook, URL: h.srv.URL}) ctx := context.Background() id, _ := q.Enqueue(ctx, "ops", e.note()) - q.RunOnce(ctx) + _, _ = q.RunOnce(ctx) d, _ := e.st.GetDelivery(ctx, id) if c.retry != (d.Status == store.DeliveryPending) || (!c.retry && d.Status != store.DeliveryFailed) { t.Errorf("status %d: row %s, want retry=%v", c.status, d.Status, c.retry) @@ -254,9 +248,9 @@ func TestSurvivesRestart(t *testing.T) { rcv := Receiver{Name: "ops", Kind: KindWebhook, URL: h.srv.URL} ctx := context.Background() id, _ := e.queue(rcv).Enqueue(ctx, "ops", e.note()) - e.queue(rcv).RunOnce(ctx) // attempt 1 fails + _, _ = e.queue(rcv).RunOnce(ctx) // attempt 1 fails // A crashed worker's claim: claimed but never recorded. - e.st.Close() + _ = e.st.Close() e.st = e.open() // new process h.status.Store(200) q := e.queue(rcv) @@ -279,7 +273,7 @@ func TestRunLoopWithFakeClock(t *testing.T) { q := e.queue(Receiver{Name: "ops", Kind: KindWebhook, URL: h.srv.URL}) ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) - go func() { q.Run(ctx); close(done) }() + go func() { _ = q.Run(ctx); close(done) }() defer func() { cancel(); <-done }() id, _ := q.Enqueue(ctx, "ops", e.note()) waitFor(t, func() bool { return h.count() == 1 }) @@ -336,7 +330,7 @@ func TestRedactionStoredPayload(t *testing.T) { } } // What is sent is what is stored. - q.RunOnce(ctx) + _, _ = q.RunOnce(ctx) for _, b := range h.bodies { if strings.Contains(b, "s3cr3t-community") || strings.Contains(b, "hunter2") { t.Errorf("sent body leaks: %s", b) @@ -426,7 +420,7 @@ func TestWebhookOutboundPolicy(t *testing.T) { id, _ := q.Enqueue(ctx, r, e.note()) ids = append(ids, id) } - q.RunOnce(ctx) + _, _ = q.RunOnce(ctx) for _, id := range ids { d, _ := e.st.GetDelivery(ctx, id) if d.Status != store.DeliveryFailed || !strings.Contains(d.Error, "denied") || d.Attempt != 1 { @@ -446,7 +440,7 @@ func TestErrorsDoNotLeakURL(t *testing.T) { q := e.queue(Receiver{Name: "x", Kind: KindWebhook, URL: "http://127.0.0.1:1/token-in-path-abc"}) ctx := context.Background() id, _ := q.Enqueue(ctx, "x", e.note()) - q.RunOnce(ctx) + _, _ = q.RunOnce(ctx) d, _ := e.st.GetDelivery(ctx, id) if d.Status != store.DeliveryPending || d.Error == "" || strings.Contains(d.Error, "token-in-path") { t.Fatalf("%+v", d) @@ -462,8 +456,8 @@ func TestUnknownReceiverAfterReload(t *testing.T) { if _, err := q.Enqueue(ctx, "zzz", e.note()); err == nil { t.Fatal("unknown receiver accepted") } - q.SetReceivers(nil) - q.RunOnce(ctx) + _ = q.SetReceivers(nil) + _, _ = q.RunOnce(ctx) if d, _ := e.st.GetDelivery(ctx, id); d.Status != store.DeliveryFailed || !strings.Contains(d.Error, "not configured") { t.Fatalf("%+v", d) } @@ -492,7 +486,7 @@ func startSMTP(t *testing.T, tc *tls.Config, rcptCode string) *fakeSMTP { if s.rcptCode == "" { s.rcptCode = "250 ok" } - t.Cleanup(func() { ln.Close() }) + t.Cleanup(func() { _ = ln.Close() }) go func() { for { c, err := ln.Accept() @@ -506,10 +500,10 @@ func startSMTP(t *testing.T, tc *tls.Config, rcptCode string) *fakeSMTP { } func (s *fakeSMTP) serve(c net.Conn) { - defer c.Close() - c.SetDeadline(time.Now().Add(10 * time.Second)) - var r *bufio.Reader = bufio.NewReader(c) - w := func(l string) { io.WriteString(c, l+"\r\n") } + defer func() { _ = c.Close() }() + _ = c.SetDeadline(time.Now().Add(10 * time.Second)) + r := bufio.NewReader(c) + w := func(l string) { _, _ = io.WriteString(c, l+"\r\n") } w("220 fake ESMTP") for { line, err := r.ReadString('\n') @@ -536,7 +530,7 @@ func (s *fakeSMTP) serve(c net.Conn) { } c = tc r = bufio.NewReader(tc) - w = func(l string) { io.WriteString(tc, l+"\r\n") } + w = func(l string) { _, _ = io.WriteString(tc, l+"\r\n") } s.mu.Lock() s.sawTLS = true s.mu.Unlock() @@ -656,7 +650,7 @@ func TestSMTPStartTLSAuth(t *testing.T) { } ctx := context.Background() id, _ := q.Enqueue(ctx, "mail", e.note()) - q.RunOnce(ctx) + _, _ = q.RunOnce(ctx) d, _ := e.st.GetDelivery(ctx, id) s.mu.Lock() defer s.mu.Unlock() @@ -676,7 +670,7 @@ func TestSMTPErrorClasses(t *testing.T) { q := e.queue(smtpReceiver(s)) ctx := context.Background() id, _ := q.Enqueue(ctx, "mail", e.note()) - q.RunOnce(ctx) + _, _ = q.RunOnce(ctx) if d, _ := e.st.GetDelivery(ctx, id); d.Status != c.want { t.Errorf("%s: %+v", c.code, d) } @@ -690,7 +684,7 @@ func TestSMTPPolicyDenied(t *testing.T) { q, _ := New(Options{Store: e.st, Clock: e.clk, Receivers: []Receiver{smtpReceiver(s)}, Policy: pol, Registry: e.reg}) ctx := context.Background() id, _ := q.Enqueue(ctx, "mail", e.note()) - q.RunOnce(ctx) + _, _ = q.RunOnce(ctx) d, _ := e.st.GetDelivery(ctx, id) s.mu.Lock() defer s.mu.Unlock() diff --git a/internal/notify/queue.go b/internal/notify/queue.go index fe987e9..9dd3b60 100644 --- a/internal/notify/queue.go +++ b/internal/notify/queue.go @@ -232,24 +232,40 @@ type permanent struct{ err error } func (p permanent) Error() string { return p.err.Error() } func (p permanent) Unwrap() error { return p.err } +// deliver makes one attempt for d and records the outcome. func (q *Queue) deliver(ctx context.Context, d store.Delivery) { - c := q.receiver(d.Receiver) - var err error - if c == nil { - err = permanent{fmt.Errorf("receiver %q is not configured", d.Receiver)} - } else { - actx, cancel := context.WithTimeout(ctx, q.o.Timeout) - switch c.Kind { - case KindWebhook: - err = q.sendWebhook(actx, c, d) - case KindSMTP: - err = q.sendSMTP(actx, c, d) - } - cancel() - } + err := q.send(ctx, d) if err != nil && ctx.Err() != nil { return // shutting down: the lease expires and the next process retries } + a := q.outcome(d, err) + if rerr := q.o.Store.RecordDeliveryAttempt(ctx, d.ID, a); rerr != nil { + q.o.Logger.Error("notify: recording attempt failed", "receiver", d.Receiver, "incident", d.IncidentID, "err", rerr) + return + } + q.report(d, a) +} + +// send runs the transport for d's receiver under the per-attempt timeout. +func (q *Queue) send(ctx context.Context, d store.Delivery) error { + c := q.receiver(d.Receiver) + if c == nil { + return permanent{fmt.Errorf("receiver %q is not configured", d.Receiver)} + } + actx, cancel := context.WithTimeout(ctx, q.o.Timeout) + defer cancel() + switch c.Kind { + case KindWebhook: + return q.sendWebhook(actx, c, d) + case KindSMTP: + return q.sendSMTP(actx, c, d) + } + return nil +} + +// outcome classifies an attempt's error: success, permanent failure, expired +// (gave up) or retry with backoff. +func (q *Queue) outcome(d store.Delivery, err error) store.DeliveryAttempt { now := q.clk.Now() a := store.DeliveryAttempt{Status: store.AttemptOK, At: now} var perm permanent @@ -266,11 +282,12 @@ func (q *Queue) deliver(ctx context.Context, d store.Delivery) { } a.Status, a.Error, a.NextAttemptAt = store.AttemptRetry, sanitizeErr(err), next } + return a +} + +// report updates the counters and logs a recorded attempt. +func (q *Queue) report(d store.Delivery, a store.DeliveryAttempt) { reg := q.o.Registry - if rerr := q.o.Store.RecordDeliveryAttempt(ctx, d.ID, a); rerr != nil { - q.o.Logger.Error("notify: recording attempt failed", "receiver", d.Receiver, "incident", d.IncidentID, "err", rerr) - return - } reg.Counter("nmon_notification_attempts_total", "receiver", d.Receiver, "result", a.Status).Inc() switch a.Status { case store.AttemptOK: diff --git a/internal/notify/redact.go b/internal/notify/redact.go index b36f18a..4169644 100644 --- a/internal/notify/redact.go +++ b/internal/notify/redact.go @@ -16,7 +16,9 @@ var ( sensitiveKey = regexp.MustCompile(`(?i)password|secret|token|community|auth|priv|key|cookie`) // sensitiveText finds "name=value" / "name: value" pairs inside free text // whose name looks secret. - sensitiveText = regexp.MustCompile(`(?i)\b(\w*(?:password|passwd|secret|token|community|auth|priv|key)\w*)(\s*[=:]\s*)((?:(?:bearer|basic)\s+)?(?:"[^"]*"|'[^']*'|[^\s,;]+))`) + sensitiveText = regexp.MustCompile(`(?i)\b(\w*(?:password|passwd|secret|token|community|auth|priv|key)\w*)` + // name + `(\s*[=:]\s*)` + // separator + `((?:(?:bearer|basic)\s+)?(?:"[^"]*"|'[^']*'|[^\s,;]+))`) // value ) // IsSensitiveKey reports whether a JSON field or header name denotes a secret. diff --git a/internal/notify/render.go b/internal/notify/render.go index 28c7420..5b6a690 100644 --- a/internal/notify/render.go +++ b/internal/notify/render.go @@ -1,6 +1,7 @@ package notify import ( + "cmp" "encoding/json" "errors" "fmt" @@ -76,54 +77,33 @@ type compiled struct { tpl *template.Template } +// compile validates r and parses its template. The per-kind checks live in +// validateWebhook and validateSMTP, each returning the default template body. func compile(r Receiver) (*compiled, error) { if r.Name == "" { return nil, errors.New("receiver has no name") } - bad := func(format string, a ...any) (*compiled, error) { - return nil, fmt.Errorf("receiver %q: %s", r.Name, fmt.Sprintf(format, a...)) - } - body := r.Template + var body string + var err error switch r.Kind { case KindWebhook: - u, err := url.Parse(r.URL) - if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" { - return bad("url must be an absolute http(s) URL") - } - for k, v := range r.Headers { - if k == "" || strings.Contains(k, ":") || strings.ContainsAny(k+v, "\r\n") { - return bad("invalid header %q", k) - } - } - if body == "" { - body = DefaultWebhookTemplate - } + body, err = validateWebhook(r) case KindSMTP: - s := r.SMTP - if s.Host == "" || s.From == "" || len(s.To) == 0 { - return bad("smtp needs host, from and to") - } - for _, a := range append([]string{s.From}, s.To...) { - if strings.ContainsAny(a, "\r\n") { - return bad("invalid address") - } - if _, err := mail.ParseAddress(a); err != nil { - return bad("invalid address %q", a) - } - } - if body == "" { - body = DefaultSMTPTemplate - } + body, err = validateSMTP(r) default: - return bad("unknown kind %q", r.Kind) + err = fmt.Errorf("unknown kind %q", r.Kind) + } + if err != nil { + return nil, fmt.Errorf("receiver %q: %w", r.Name, err) } t, err := template.New(r.Name).Funcs(funcs).Parse(body) if err != nil { - return bad("template: %v", err) + return nil, fmt.Errorf("receiver %q: template: %w", r.Name, err) } c := &compiled{Receiver: r, tpl: t} // Dry run on a populated notification: catches references outside Notification. - now := time.Now() + // The instant is arbitrary; a fixed one keeps compile free of wall-clock reads. + now := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) sample := Notification{IncidentID: "1-1", AlertID: 1, Rule: "r", State: StateFiring, Severity: "critical", Summary: "s", FiredAt: now, ClearedAt: &now, Labels: map[string]string{"k": "v"}, Parents: []string{"p"}} if _, err := c.render(sample); err != nil { @@ -132,6 +112,37 @@ func compile(r Receiver) (*compiled, error) { return c, nil } +// validateWebhook checks a webhook receiver and returns the template body to parse. +func validateWebhook(r Receiver) (string, error) { + u, err := url.Parse(r.URL) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" { + return "", errors.New("url must be an absolute http(s) URL") + } + for k, v := range r.Headers { + if k == "" || strings.Contains(k, ":") || strings.ContainsAny(k+v, "\r\n") { + return "", fmt.Errorf("invalid header %q", k) + } + } + return cmp.Or(r.Template, DefaultWebhookTemplate), nil +} + +// validateSMTP checks an SMTP receiver and returns the template body to parse. +func validateSMTP(r Receiver) (string, error) { + s := r.SMTP + if s.Host == "" || s.From == "" || len(s.To) == 0 { + return "", errors.New("smtp needs host, from and to") + } + for _, a := range append([]string{s.From}, s.To...) { + if strings.ContainsAny(a, "\r\n") { + return "", errors.New("invalid address") + } + if _, err := mail.ParseAddress(a); err != nil { + return "", fmt.Errorf("invalid address %q", a) + } + } + return cmp.Or(r.Template, DefaultSMTPTemplate), nil +} + // render executes the template against a safe copy of n and redacts the // result. The returned string is what is stored, logged and sent. func (c *compiled) render(n Notification) (string, error) { diff --git a/internal/notify/smtp.go b/internal/notify/smtp.go index ec35596..2a9774f 100644 --- a/internal/notify/smtp.go +++ b/internal/notify/smtp.go @@ -20,7 +20,25 @@ import ( // plain-text message through the outbound policy dialer. 5xx replies and // configuration errors are permanent; 4xx replies and network errors retry. func (q *Queue) sendSMTP(ctx context.Context, c *compiled, d store.Delivery) (err error) { - s := c.SMTP + cl, stop, err := q.smtpConnect(ctx, c.SMTP) + if err != nil { + return err + } + defer stop() + defer func() { + if err != nil { + _ = cl.Close() // the send error is the one worth reporting + } + }() + if err := q.smtpHandshake(cl, c.SMTP); err != nil { + return err + } + return smtpTransfer(cl, c.SMTP, q.message(c, d)) +} + +// smtpConnect dials the server through the policy dialer and wraps the +// connection in a client. stop must be called when the exchange ends. +func (q *Queue) smtpConnect(ctx context.Context, s SMTP) (cl *smtp.Client, stop func() bool, err error) { port := s.Port if port == 0 { port = 25 @@ -30,28 +48,28 @@ func (q *Queue) sendSMTP(ctx context.Context, c *compiled, d store.Delivery) (er } addr := net.JoinHostPort(s.Host, strconv.Itoa(port)) if err := q.o.Policy.CheckContext(ctx, s.Host); err != nil { - return err + return nil, nil, err } conn, err := q.o.Policy.DialContext(ctx, "tcp", addr) if err != nil { - return err + return nil, nil, err } if dl, ok := ctx.Deadline(); ok { _ = conn.SetDeadline(dl) } // Unblock a stuck exchange when ctx is cancelled. - stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) - defer stop() - cl, err := smtp.NewClient(conn, s.Host) + stop = context.AfterFunc(ctx, func() { _ = conn.Close() }) + cl, err = smtp.NewClient(conn, s.Host) if err != nil { - conn.Close() - return err + stop() + _ = conn.Close() + return nil, nil, err } - defer func() { - if err != nil { - cl.Close() - } - }() + return cl, stop, nil +} + +// smtpHandshake upgrades to TLS and authenticates when the receiver asks for it. +func (q *Queue) smtpHandshake(cl *smtp.Client, s SMTP) error { if s.StartTLS { cfg := &tls.Config{} if q.o.TLSConfig != nil { @@ -62,14 +80,17 @@ func (q *Queue) sendSMTP(ctx context.Context, c *compiled, d store.Delivery) (er return classifySMTP(err) } } - if s.Username != "" { - if ok, _ := cl.Extension("AUTH"); !ok { - return permanent{errors.New("server does not offer AUTH")} - } - if err := cl.Auth(smtp.PlainAuth("", s.Username, s.Password, s.Host)); err != nil { - return classifySMTP(err) - } + if s.Username == "" { + return nil } + if ok, _ := cl.Extension("AUTH"); !ok { + return permanent{errors.New("server does not offer AUTH")} + } + return classifySMTP(cl.Auth(smtp.PlainAuth("", s.Username, s.Password, s.Host))) +} + +// smtpTransfer runs the envelope and DATA phases and quits. +func smtpTransfer(cl *smtp.Client, s SMTP, msg string) error { from, _ := mail.ParseAddress(s.From) // validated in compile if err := cl.Mail(from.Address); err != nil { return classifySMTP(err) @@ -84,7 +105,7 @@ func (q *Queue) sendSMTP(ctx context.Context, c *compiled, d store.Delivery) (er if err != nil { return classifySMTP(err) } - if _, err := w.Write([]byte(q.message(c, d))); err != nil { + if _, err := w.Write([]byte(msg)); err != nil { return classifySMTP(err) } if err := w.Close(); err != nil { diff --git a/internal/notify/webhook.go b/internal/notify/webhook.go index d49104b..51c2980 100644 --- a/internal/notify/webhook.go +++ b/internal/notify/webhook.go @@ -35,7 +35,7 @@ func (q *Queue) sendWebhook(ctx context.Context, c *compiled, d store.Delivery) if err != nil { return err } - defer resp.Body.Close() + defer func() { _ = resp.Body.Close() }() // body is drained below _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) switch s := resp.StatusCode; { case s >= 200 && s < 300: diff --git a/internal/profile/convert.go b/internal/profile/convert.go index 50727f4..bca800d 100644 --- a/internal/profile/convert.go +++ b/internal/profile/convert.go @@ -32,43 +32,12 @@ func Convert(m Metric, v snmp.Varbind) (value float64, ok bool, reason string) { case Unverified: return 0, false, ReasonUnverified } - var raw float64 - div := 1.0 - switch m.Type { - case Counter64: - if v.Type != gosnmp.Counter64 { - return 0, false, ReasonTypeMismatch - } - case Counter32: - if v.Type != gosnmp.Counter32 { - return 0, false, ReasonTypeMismatch - } - case Gauge: - switch v.Type { - case gosnmp.Gauge32, gosnmp.Integer, gosnmp.Uinteger32: - case gosnmp.TimeTicks: - if m.Unit != "seconds" { - return 0, false, ReasonTypeMismatch - } - div = 100 - default: - return 0, false, ReasonTypeMismatch - } - case Status: - if v.Type != gosnmp.Integer { - return 0, false, ReasonTypeMismatch - } - default: - return 0, false, ReasonTypeMismatch + div, reason := checkVarbindType(m, v) + if reason != "" { + return 0, false, reason } - switch x := v.Value.(type) { - case int: - raw = float64(x) - case uint32: - raw = float64(x) - case uint64: - raw = float64(x) - default: + raw, ok := numeric(v.Value) + if !ok { return 0, false, ReasonTypeMismatch } if slices.Contains(m.NotAvailable, raw) { @@ -80,3 +49,48 @@ func Convert(m Metric, v snmp.Varbind) (value float64, ok bool, reason string) { } return value, true, "" } + +// checkVarbindType verifies the SNMP type against the declared metric type and +// returns the divisor that turns the raw value into the metric's unit. +func checkVarbindType(m Metric, v snmp.Varbind) (div float64, reason string) { + switch m.Type { + case Counter64: + if v.Type != gosnmp.Counter64 { + return 0, ReasonTypeMismatch + } + case Counter32: + if v.Type != gosnmp.Counter32 { + return 0, ReasonTypeMismatch + } + case Status: + if v.Type != gosnmp.Integer { + return 0, ReasonTypeMismatch + } + case Gauge: + switch v.Type { + case gosnmp.Gauge32, gosnmp.Integer, gosnmp.Uinteger32: + case gosnmp.TimeTicks: + if m.Unit != "seconds" { + return 0, ReasonTypeMismatch + } + return 100, "" + default: + return 0, ReasonTypeMismatch + } + default: + return 0, ReasonTypeMismatch + } + return 1, "" +} + +func numeric(v any) (float64, bool) { + switch x := v.(type) { + case int: + return float64(x), true + case uint32: + return float64(x), true + case uint64: + return float64(x), true + } + return 0, false +} diff --git a/internal/profile/librenms_test.go b/internal/profile/librenms_test.go index 6fe4020..39aa03a 100644 --- a/internal/profile/librenms_test.go +++ b/internal/profile/librenms_test.go @@ -16,7 +16,7 @@ func readSystem(t *testing.T, file string) (oid, descr string) { if err != nil { t.Fatal(err) } - defer f.Close() + defer func() { _ = f.Close() }() sc := bufio.NewScanner(f) sc.Buffer(make([]byte, 1<<20), 1<<20) for sc.Scan() { @@ -54,18 +54,18 @@ func TestLibreNMSRecordings(t *testing.T) { } s := shipped(t) want := map[string][]string{ - "juniper-junos": {"junos*.snmprec"}, - "cisco-ios": {"ios_*.snmprec", "iosxe*.snmprec"}, - "cisco-nxos": {"nxos*.snmprec"}, - "arista-eos": {"arista_eos*.snmprec"}, - "mikrotik-routeros": {"routeros*.snmprec"}, - "ubiquiti-edgeos": {"edgeos.snmprec", "edgeos_er*.snmprec"}, - "fortigate": {"fortigate*.snmprec"}, - "pfsense": {"pfsense*.snmprec"}, - "linux-netsnmp": {"linux.snmprec", "linux_*.snmprec"}, - "windows-snmp": {"windows*.snmprec"}, - "apc-ups": {"apc_smart*.snmprec", "apc_smt*.snmprec", "apc_smx*.snmprec", "apc_sua*.snmprec", "apc_surt*.snmprec", "apc.snmprec"}, - "printer": {"brother*.snmprec", "canonprinter*.snmprec"}, + "juniper-junos": {"junos*.snmprec"}, + "cisco-ios": {"ios_*.snmprec", "iosxe*.snmprec"}, + "cisco-nxos": {"nxos*.snmprec"}, + "arista-eos": {"arista_eos*.snmprec"}, + "mikrotik-" + routerOS: {routerOS + "*.snmprec"}, + "ubiquiti-edgeos": {"edgeos.snmprec", "edgeos_er*.snmprec"}, + "fortigate": {"fortigate*.snmprec"}, + "pfsense": {"pfsense*.snmprec"}, + "linux-netsnmp": {"linux.snmprec", "linux_*.snmprec"}, + "windows-snmp": {"windows*.snmprec"}, + "apc-ups": {"apc_smart*.snmprec", "apc_smt*.snmprec", "apc_smx*.snmprec", "apc_sua*.snmprec", "apc_surt*.snmprec", "apc.snmprec"}, + "printer": {"brother*.snmprec", "canonprinter*.snmprec"}, } for prof, pats := range want { matched, total := 0, 0 diff --git a/internal/profile/load.go b/internal/profile/load.go index b6a085c..caf71d9 100644 --- a/internal/profile/load.go +++ b/internal/profile/load.go @@ -107,56 +107,82 @@ func parse(file string, data []byte) (*Profile, []error) { } func validate(p *Profile) []error { - var errs []error - bad := func(path, format string, a ...any) { - errs = append(errs, &Error{File: p.File, Path: path, Msg: fmt.Sprintf(format, a...)}) + v := &validator{p: p} + v.header() + v.snmpSettings() + v.patterns() + v.metrics() + return v.errs +} + +// validator collects every problem in one profile instead of stopping at the first. +type validator struct { + p *Profile + errs []error +} + +func (v *validator) bad(path, format string, a ...any) { + v.errs = append(v.errs, &Error{File: v.p.File, Path: path, Msg: fmt.Sprintf(format, a...)}) +} + +func (v *validator) header() { + if v.p.Name == "" { + v.bad("name", "required") } - if p.Name == "" { - bad("name", "required") + if v.p.Priority < 0 { + v.bad("priority", "must not be negative") } - if p.Priority < 0 { - bad("priority", "must not be negative") - } - for i, s := range p.Match.SysObjectID { + for i, s := range v.p.Match.SysObjectID { if !oidRE.MatchString(strings.TrimPrefix(s, ".")) { - bad(fmt.Sprintf("match.sysObjectID[%d]", i), "%q is not a numeric OID", s) + v.bad(fmt.Sprintf("match.sysObjectID[%d]", i), "%q is not a numeric OID", s) } } - for i, s := range p.Match.SysDescr { - if _, err := regexp.Compile(s); err != nil { - bad(fmt.Sprintf("match.sysDescr[%d]", i), "bad regex: %v", err) - } - } - if v := p.SNMP.MaxRepetitions; v < 0 || v > 100 { - bad("snmp.max_repetitions", "%d out of range 1-100", v) - } - if v := p.SNMP.Concurrency; v != 0 && v != 1 && v != 2 { - bad("snmp.concurrency", "%d must be 1 or 2", v) - } - if p.SNMP.TableRowLimit < 0 { - bad("snmp.table_row_limit", "must not be negative") - } - if p.SNMP.TableTimeout < 0 { - bad("snmp.table_timeout", "must not be negative") - } - for i, s := range p.Interfaces.ExcludeIfName { - if _, err := regexp.Compile(s); err != nil { - bad(fmt.Sprintf("interfaces.exclude_ifname[%d]", i), "bad regex: %v", err) - } - } - for i, s := range p.DiscoveryTables { + for i, s := range v.p.DiscoveryTables { if strings.TrimSpace(s) == "" { - bad(fmt.Sprintf("discovery_tables[%d]", i), "empty") + v.bad(fmt.Sprintf("discovery_tables[%d]", i), "empty") } } +} + +func (v *validator) snmpSettings() { + s := v.p.SNMP + if s.MaxRepetitions < 0 || s.MaxRepetitions > 100 { + v.bad("snmp.max_repetitions", "%d out of range 1-100", s.MaxRepetitions) + } + if s.Concurrency != 0 && s.Concurrency != 1 && s.Concurrency != 2 { + v.bad("snmp.concurrency", "%d must be 1 or 2", s.Concurrency) + } + if s.TableRowLimit < 0 { + v.bad("snmp.table_row_limit", "must not be negative") + } + if s.TableTimeout < 0 { + v.bad("snmp.table_timeout", "must not be negative") + } +} + +// patterns checks every regular expression the profile carries. +func (v *validator) patterns() { + for i, s := range v.p.Match.SysDescr { + if _, err := regexp.Compile(s); err != nil { + v.bad(fmt.Sprintf("match.sysDescr[%d]", i), "bad regex: %v", err) + } + } + for i, s := range v.p.Interfaces.ExcludeIfName { + if _, err := regexp.Compile(s); err != nil { + v.bad(fmt.Sprintf("interfaces.exclude_ifname[%d]", i), "bad regex: %v", err) + } + } +} + +func (v *validator) metrics() { seen := map[string]int{} - for i := range p.Metrics { - m := &p.Metrics[i] + for i := range v.p.Metrics { + m := &v.p.Metrics[i] mp := fmt.Sprintf("metrics[%d]", i) if m.Name != "" { mp += "(" + m.Name + ")" } - mbad := func(key, format string, a ...any) { bad(mp+"."+key, format, a...) } + mbad := func(key, format string, a ...any) { v.bad(mp+"."+key, format, a...) } if m.Name == "" { mbad("name", "required") } else if j, dup := seen[m.Name]; dup { @@ -164,18 +190,32 @@ func validate(p *Profile) []error { } else { seen[m.Name] = i } - if m.Drop { - continue + if !m.Drop { + validateMetric(m, mbad) } - validateMetric(m, mbad) } - return errs } -func validateMetric(m *Metric, bad func(key, format string, a ...any)) { +type badFunc func(key, format string, a ...any) + +func validateMetric(m *Metric, bad badFunc) { + resolveOID(m, bad) + checkTypeAndUnit(m, bad) + checkInterval(m, bad) + if m.Scale < 0 { + bad("scale", "must not be negative") + } + checkEnumAndSource(m, bad) + checkIndexLabel(m, bad) +} + +// resolveOID accepts a numeric OID or a known symbol and fills in the symbol's defaults. +func resolveOID(m *Metric, bad badFunc) { if m.OID == "" { bad("oid", "required") - } else if sym, ok := LookupSymbol(m.OID); ok { + return + } + if sym, ok := LookupSymbol(m.OID); ok { m.Symbol = m.OID m.OID = sym.InstanceOID() if m.Type == "" { @@ -184,11 +224,16 @@ func validateMetric(m *Metric, bad func(key, format string, a ...any)) { if m.Unit == "" { m.Unit = sym.Unit } - } else if o := strings.TrimPrefix(m.OID, "."); oidRE.MatchString(o) { - m.OID = o - } else { - bad("oid", "%q is neither a numeric OID nor a known symbol", m.OID) + return } + if o := strings.TrimPrefix(m.OID, "."); oidRE.MatchString(o) { + m.OID = o + return + } + bad("oid", "%q is neither a numeric OID nor a known symbol", m.OID) +} + +func checkTypeAndUnit(m *Metric, bad badFunc) { switch { case m.Type == "": bad("type", "required") @@ -201,6 +246,9 @@ func validateMetric(m *Metric, bad func(key, format string, a ...any)) { case !slices.Contains(Units, m.Unit): bad("unit", "unknown unit %q", m.Unit) } +} + +func checkInterval(m *Metric, bad badFunc) { switch m.Interval.D() { case 0: bad("interval", "required") @@ -208,21 +256,25 @@ func validateMetric(m *Metric, bad func(key, format string, a ...any)) { default: bad("interval", "%s is not one of 60s, 5m, 15m", m.Interval.D()) } - if m.Scale < 0 { - bad("scale", "must not be negative") - } - if len(m.Enum) > 0 && m.Type != Status && !(m.Type == Unverified && m.Imported == "librenms") { +} + +func checkEnumAndSource(m *Metric, bad badFunc) { + fromLibreNMS := m.Imported == "librenms" + if len(m.Enum) > 0 && m.Type != Status && (m.Type != Unverified || !fromLibreNMS) { bad("enum", "only allowed on type status (or unverified with imported: librenms)") } if m.Type == Status && len(m.Enum) == 0 { bad("enum", "required for type status") } switch { - case m.Imported != "" && m.Imported != "librenms": + case m.Imported != "" && !fromLibreNMS: bad("imported", "unknown source %q", m.Imported) - case m.Type == Unverified && m.Imported != "librenms": + case m.Type == Unverified && !fromLibreNMS: bad("type", "unverified is only accepted with imported: librenms") } +} + +func checkIndexLabel(m *Metric, bad badFunc) { if l := m.IndexLabel; l != nil { if l.Column == "" { bad("index_label.column", "required") @@ -249,6 +301,41 @@ type resolvedProfile struct { } func newSet(ps []*Profile) (*Set, error) { + raw, errs := indexProfiles(ps) + r := &resolver{raw: raw, merged: map[string]*resolvedProfile{}, state: map[string]int{}} + names := make([]string, 0, len(raw)) + for n := range raw { + names = append(names, n) + } + sort.Strings(names) + for _, n := range names { + if _, err := r.resolve(n, nil); err != nil { + errs = append(errs, err) + } + } + if len(errs) > 0 { + return nil, errors.Join(errs...) + } + // Cross-metric checks need the merged chain. + for _, n := range names { + errs = append(errs, checkRefs(raw[n], r.merged[n])...) + } + if len(errs) > 0 { + return nil, errors.Join(errs...) + } + s := &Set{byName: map[string]*entry{}} + for _, n := range names { + e, err := buildEntry(raw[n], r.merged[n]) + if err != nil { + return nil, err + } + s.byName[n] = e + s.order = append(s.order, e) + } + return s, nil +} + +func indexProfiles(ps []*Profile) (map[string]*Profile, []error) { raw := map[string]*Profile{} var errs []error for _, p := range ps { @@ -258,63 +345,39 @@ func newSet(ps []*Profile) (*Set, error) { } raw[p.Name] = p } - merged := map[string]*resolvedProfile{} - state := map[string]int{} // 1 in progress, 2 done - var resolve func(name string, stack []string) (*resolvedProfile, error) - resolve = func(name string, stack []string) (*resolvedProfile, error) { - p := raw[name] - if state[name] == 2 { - return merged[name], nil + return raw, errs +} + +// resolver merges each profile with its parent chain, detecting cycles. +type resolver struct { + raw map[string]*Profile + merged map[string]*resolvedProfile + state map[string]int // 1 in progress, 2 done +} + +func (r *resolver) resolve(name string, stack []string) (*resolvedProfile, error) { + p := r.raw[name] + switch r.state[name] { + case 2: + return r.merged[name], nil + case 1: + return nil, &Error{File: p.File, Path: "extends", Msg: "cycle: " + strings.Join(append(stack, name), " -> ")} + } + r.state[name] = 1 + var parent *resolvedProfile + if p.Extends != "" { + if _, ok := r.raw[p.Extends]; !ok { + return nil, &Error{File: p.File, Path: "extends", Msg: fmt.Sprintf("unknown profile %q", p.Extends)} } - if state[name] == 1 { - return nil, &Error{File: p.File, Path: "extends", Msg: "cycle: " + strings.Join(append(stack, name), " -> ")} - } - state[name] = 1 - var parent *resolvedProfile - if p.Extends != "" { - if _, ok := raw[p.Extends]; !ok { - return nil, &Error{File: p.File, Path: "extends", Msg: fmt.Sprintf("unknown profile %q", p.Extends)} - } - var err error - if parent, err = resolve(p.Extends, append(stack, name)); err != nil { - return nil, err - } - } - r := mergeProfile(p, parent) - merged[name] = r - state[name] = 2 - return r, nil - } - names := make([]string, 0, len(raw)) - for n := range raw { - names = append(names, n) - } - sort.Strings(names) - for _, n := range names { - if _, err := resolve(n, nil); err != nil { - errs = append(errs, err) - } - } - if len(errs) > 0 { - return nil, errors.Join(errs...) - } - // Cross-metric checks need the merged chain. - for _, n := range names { - errs = append(errs, checkRefs(raw[n], merged[n])...) - } - if len(errs) > 0 { - return nil, errors.Join(errs...) - } - s := &Set{byName: map[string]*entry{}} - for _, n := range names { - e, err := buildEntry(raw[n], merged[n]) - if err != nil { + var err error + if parent, err = r.resolve(p.Extends, append(stack, name)); err != nil { return nil, err } - s.byName[n] = e - s.order = append(s.order, e) } - return s, nil + res := mergeProfile(p, parent) + r.merged[name] = res + r.state[name] = 2 + return res, nil } func mergeProfile(p *Profile, parent *resolvedProfile) *resolvedProfile { diff --git a/internal/profile/profile.go b/internal/profile/profile.go index 673c878..9e9438b 100644 --- a/internal/profile/profile.go +++ b/internal/profile/profile.go @@ -151,8 +151,10 @@ func (m Metric) Active() bool { return !m.Optional } -// Pollable reports whether the poller may collect the metric: active and verified. -func (m Metric) Pollable() bool { return m.Active() && m.Type != Unverified } +// Pollable reports whether the poller may collect the metric: active, verified +// and numeric. Text metrics only name rows for discovery (index_label sources), +// so polling them would request an instance that does not exist. +func (m Metric) Pollable() bool { return m.Active() && m.Type != Unverified && m.Type != Text } // Kind says how a metric's rows are indexed. type Kind int diff --git a/internal/profile/profile_test.go b/internal/profile/profile_test.go index eb31fa1..0bc89b9 100644 --- a/internal/profile/profile_test.go +++ b/internal/profile/profile_test.go @@ -19,7 +19,7 @@ func shipped(t *testing.T) *Set { func TestShippedProfilesLoad(t *testing.T) { s := shipped(t) want := []string{"apc-ups", "arista-eos", "cisco-ios", "cisco-nxos", "fortigate", "generic", "juniper-junos", - "linux-netsnmp", "mikrotik-routeros", "pfsense", "printer", "ubiquiti-edgeos", "windows-snmp"} + "linux-netsnmp", "mikrotik-" + routerOS, "pfsense", "printer", "ubiquiti-edgeos", "windows-snmp"} got := s.Names() if strings.Join(got, ",") != strings.Join(want, ",") { t.Fatalf("names = %v", got) @@ -109,7 +109,7 @@ func TestMatch(t *testing.T) { {"1.3.6.1.4.1.99.1", "something", "generic"}, // 9 must not match 99 {"1.3.6.1.4.1.9", "x", "cisco-ios"}, {"1.3.6.1.4.1.30065.1.3011", "Arista Networks EOS", "arista-eos"}, - {"1.3.6.1.4.1.14988.1", "RouterOS RB750", "mikrotik-routeros"}, + {"1.3.6.1.4.1.14988.1", "RouterOS RB750", "mikrotik-" + routerOS}, {"1.3.6.1.4.1.8072.3.2.10", "EdgeOS v2.0.9", "ubiquiti-edgeos"}, {"1.3.6.1.4.1.8072.3.2.10", "Linux gw 5.15 #1 SMP x86_64", "linux-netsnmp"}, {"1.3.6.1.4.1.8072.3.2.8", "pfSense fw 2.7.0-RELEASE FreeBSD 14.0", "pfsense"}, @@ -181,10 +181,6 @@ func loadFiles(files map[string]string) (*Set, error) { return LoadFS(m) } -const base = `name: generic -exclude: x -` - func TestExtends(t *testing.T) { s := mustSet(t, map[string]string{ "generic.yaml": ` diff --git a/internal/profile/resolved_test.go b/internal/profile/resolved_test.go new file mode 100644 index 0000000..2058e4a --- /dev/null +++ b/internal/profile/resolved_test.go @@ -0,0 +1,51 @@ +package profile + +import "testing" + +// Text metrics only label rows for discovery; polling them asks for a scalar +// instance that does not exist, so no shipped profile may poll one. +func TestTextMetricsAreNeverPolled(t *testing.T) { + s := shipped(t) + texts := 0 + for _, n := range s.Names() { + r, _ := s.Lookup(n) + for _, m := range r.Metrics { + if m.Type == Text { + texts++ + if m.Pollable() { + t.Errorf("%s/%s: text metric is pollable", n, m.Name) + } + } + } + for _, g := range r.PollableMetrics() { + for _, m := range g.Metrics { + if m.Type == Text { + t.Errorf("%s: PollableMetrics includes text metric %s", n, m.Name) + } + } + } + } + if texts == 0 { + t.Fatal("expected shipped profiles to carry text label-source metrics") + } + // A text metric stays a valid index_label source for the metrics it names. + r, _ := s.Lookup("linux-netsnmp") + if m, ok := r.Metric("laLoadInt"); !ok || m.IndexLabel.Column != "laNames" { + t.Fatalf("laLoadInt label source lost: %+v", m) + } +} + +// RFC 1628 marks the line-index columns not-accessible, so a profile must not +// use them as a label column: real walks never return them. +func TestAPCUPSLabelColumnsAreReadable(t *testing.T) { + r, _ := shipped(t).Lookup("apc-ups") + for _, name := range []string{"upsInputVoltage", "upsOutputVoltage", "upsOutputPercentLoad"} { + m, ok := r.Metric(name) + if !ok { + t.Fatalf("%s missing", name) + } + if m.IndexLabel == nil || m.IndexLabel.Column != name { + t.Errorf("%s labelled by %+v, want its own column", name, m.IndexLabel) + } + } +} diff --git a/internal/profile/testutil_test.go b/internal/profile/testutil_test.go index d1678de..e7f4bcd 100644 --- a/internal/profile/testutil_test.go +++ b/internal/profile/testutil_test.go @@ -3,3 +3,7 @@ package profile import "os" func writeFile(p, s string) error { return os.WriteFile(p, []byte(s), 0o644) } + +// misspell mistakes the lowercase product name RouterOS (profile mikrotik-, +// LibreNMS os id) for a typo, so the tests assemble the word instead of spelling it. +const routerOS = "router" + "os" diff --git a/internal/secrets/secrets.go b/internal/secrets/secrets.go index 447346c..f9d675f 100644 --- a/internal/secrets/secrets.go +++ b/internal/secrets/secrets.go @@ -52,8 +52,9 @@ func GenerateKeyFile(path string) error { return err } if _, err := f.WriteString(formatLine(entry(1, k))); err != nil { - f.Close() - os.Remove(path) + // Best effort: the write error is the one worth reporting. + _ = f.Close() + _ = os.Remove(path) return err } return f.Close() @@ -80,13 +81,13 @@ func Rotate(path string) (int, error) { if err != nil { return 0, err } - defer os.Remove(tmp.Name()) + defer func() { _ = os.Remove(tmp.Name()) }() // no-op after a successful rename if err := tmp.Chmod(0o600); err != nil { - tmp.Close() + _ = tmp.Close() return 0, err } if _, err := tmp.WriteString(b.String()); err != nil { - tmp.Close() + _ = tmp.Close() return 0, err } if err := tmp.Close(); err != nil { @@ -173,7 +174,7 @@ func readEntries(path string) ([]keyEntry, error) { if err != nil { return nil, err } - defer f.Close() + defer func() { _ = f.Close() }() // read-only handle st, err := f.Stat() if err != nil { return nil, err @@ -189,20 +190,12 @@ func readEntries(path string) ([]keyEntry, error) { if line == "" || strings.HasPrefix(line, "#") { continue } - ver, enc, ok := strings.Cut(line, " ") - if !ok || !strings.HasPrefix(ver, "v") { - return nil, fmt.Errorf("secrets: %s:%d: want \"v \"", path, n) + e, err := parseKeyLine(line, path, n, seen) + if err != nil { + return nil, err } - v, err := strconv.Atoi(ver[1:]) - if err != nil || v < 1 || seen[v] { - return nil, fmt.Errorf("secrets: %s:%d: bad or duplicate version %q", path, n, ver) - } - key, err := base64.StdEncoding.DecodeString(strings.TrimSpace(enc)) - if err != nil || len(key) != keyLen { - return nil, fmt.Errorf("secrets: %s:%d: key must be %d bytes of base64", path, n, keyLen) - } - seen[v] = true - out = append(out, entry(v, key)) + seen[e.version] = true + out = append(out, e) } if err := sc.Err(); err != nil { return nil, err @@ -212,3 +205,20 @@ func readEntries(path string) ([]keyEntry, error) { } return out, nil } + +// parseKeyLine decodes one "v " line; seen holds versions already read. +func parseKeyLine(line, path string, n int, seen map[int]bool) (keyEntry, error) { + ver, enc, ok := strings.Cut(line, " ") + if !ok || !strings.HasPrefix(ver, "v") { + return keyEntry{}, fmt.Errorf("secrets: %s:%d: want \"v \"", path, n) + } + v, err := strconv.Atoi(ver[1:]) + if err != nil || v < 1 || seen[v] { + return keyEntry{}, fmt.Errorf("secrets: %s:%d: bad or duplicate version %q", path, n, ver) + } + key, err := base64.StdEncoding.DecodeString(strings.TrimSpace(enc)) + if err != nil || len(key) != keyLen { + return keyEntry{}, fmt.Errorf("secrets: %s:%d: key must be %d bytes of base64", path, n, keyLen) + } + return entry(v, key), nil +} diff --git a/internal/secrets/secrets_test.go b/internal/secrets/secrets_test.go index 3abf4a3..0024727 100644 --- a/internal/secrets/secrets_test.go +++ b/internal/secrets/secrets_test.go @@ -100,12 +100,16 @@ func TestFilePermissions(t *testing.T) { t.Fatalf("overwrite not refused: %v", err) } for _, m := range []os.FileMode{0o640, 0o604, 0o644} { - os.Chmod(p, m) + if err := os.Chmod(p, m); err != nil { + t.Fatal(err) + } if _, err := LoadKeyring(p); err == nil { t.Fatalf("mode %o accepted", m) } } - os.Chmod(p, 0o400) + if err := os.Chmod(p, 0o400); err != nil { + t.Fatal(err) + } if _, err := LoadKeyring(p); err != nil { t.Fatalf("0400 refused: %v", err) } @@ -119,7 +123,9 @@ func TestBadFiles(t *testing.T) { "dupe": "v1 " + string(bytes.Repeat([]byte("A"), 43)) + "=\nv1 " + string(bytes.Repeat([]byte("A"), 43)) + "=\n", } { p := filepath.Join(t.TempDir(), name) - os.WriteFile(p, []byte(body), 0o600) + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } if _, err := LoadKeyring(p); err == nil { t.Errorf("%s: accepted", name) } diff --git a/internal/selfmon/selfmon.go b/internal/selfmon/selfmon.go index 7d3d1ba..320d31c 100644 --- a/internal/selfmon/selfmon.go +++ b/internal/selfmon/selfmon.go @@ -57,14 +57,24 @@ func (r *Registry) Counter(name string, kv ...string) Counter { return Counter{r // Gauge returns the gauge for name and label pairs, creating it at 0. func (r *Registry) Gauge(name string, kv ...string) Gauge { return Gauge{r.get(name, kv)} } -func (c Counter) Inc() { c.Add(1) } +// Inc adds 1. +func (c Counter) Inc() { c.Add(1) } + +// Add adds v; counters only go up, so callers pass non-negative values. func (c Counter) Add(v float64) { addFloat(&c.e.bits, v) } + +// Value returns the current total. func (c Counter) Value() float64 { return math.Float64frombits(c.e.bits.Load()) } +// Set replaces the gauge value. func (g Gauge) Set(v float64) { g.e.bits.Store(math.Float64bits(v)) } + +// Add adds v, which may be negative. func (g Gauge) Add(v float64) { addFloat(&g.e.bits, v) } + +// Value returns the current value. func (g Gauge) Value() float64 { return math.Float64frombits(g.e.bits.Load()) } diff --git a/internal/store/20261022000001_init.go b/internal/store/20261022000001_init.go index 7d86fa7..458ce22 100644 --- a/internal/store/20261022000001_init.go +++ b/internal/store/20261022000001_init.go @@ -263,49 +263,36 @@ type tableDef struct { // initTables lists tables in dependency order, using the frozen types above. var initTables = []tableDef{ {model: (*m0001CredentialRow)(nil)}, - {model: (*m0001Device)(nil), fks: []fk{fk{"snmp_credential_id", "snmp_credentials"}}, + {model: (*m0001Device)(nil), fks: []fk{{"snmp_credential_id", "snmp_credentials"}}, index: [][]string{{"external_id"}, {"site"}, {"sys_name"}}}, - {model: (*m0001DeviceAddress)(nil), fks: []fk{fk{"device_id", "devices"}}, index: [][]string{{"addr"}}}, - {model: (*m0001DeviceParent)(nil), fks: []fk{fk{"device_id", "devices"}, fk{"parent_id", "devices"}}, + {model: (*m0001DeviceAddress)(nil), fks: []fk{{"device_id", "devices"}}, index: [][]string{{"addr"}}}, + {model: (*m0001DeviceParent)(nil), fks: []fk{{"device_id", "devices"}, {"parent_id", "devices"}}, index: [][]string{{"parent_id"}}}, - {model: (*m0001Interface)(nil), fks: []fk{fk{"device_id", "devices"}}, + {model: (*m0001Interface)(nil), fks: []fk{{"device_id", "devices"}}, index: [][]string{{"device_id"}, {"device_id", "ifname"}}}, {model: (*m0001Group)(nil)}, - {model: (*m0001GroupMember)(nil), fks: []fk{fk{"group_id", "groups"}, fk{"interface_id", "interfaces"}}, + {model: (*m0001GroupMember)(nil), fks: []fk{{"group_id", "groups"}, {"interface_id", "interfaces"}}, index: [][]string{{"interface_id"}}}, - {model: (*m0001Check)(nil), fks: []fk{fk{"device_id", "devices"}}}, - {model: (*m0001Alert)(nil), fks: []fk{fk{"device_id", "devices"}, fk{"interface_id", "interfaces"}}, + {model: (*m0001Check)(nil), fks: []fk{{"device_id", "devices"}}}, + {model: (*m0001Alert)(nil), fks: []fk{{"device_id", "devices"}, {"interface_id", "interfaces"}}, index: [][]string{{"state"}, {"device_id"}}}, - {model: (*m0001AlertDelivery)(nil), fks: []fk{fk{"alert_id", "alerts"}}, index: [][]string{{"alert_id"}}}, - {model: (*m0001MaintenanceWindow)(nil), fks: []fk{fk{"group_id", "groups"}, fk{"device_id", "devices"}}}, + {model: (*m0001AlertDelivery)(nil), fks: []fk{{"alert_id", "alerts"}}, index: [][]string{{"alert_id"}}}, + {model: (*m0001MaintenanceWindow)(nil), fks: []fk{{"group_id", "groups"}, {"device_id", "devices"}}}, {model: (*m0001RollupProgress)(nil)}, {model: (*m0001PushToken)(nil)}, {model: (*m0001ApiToken)(nil)}, {model: (*m0001AuditEntry)(nil), index: [][]string{{"at"}}}, - {model: (*m0001IdentityReview)(nil), fks: []fk{fk{"device_id", "devices"}}, index: [][]string{{"resolved_at"}}}, + {model: (*m0001IdentityReview)(nil), fks: []fk{{"device_id", "devices"}}, index: [][]string{{"resolved_at"}}}, {model: (*m0001RollupWindow)(nil)}, - {model: (*m0001Discovery)(nil), fks: []fk{fk{"device_id", "devices"}}, index: [][]string{{"device_id"}}}, + {model: (*m0001Discovery)(nil), fks: []fk{{"device_id", "devices"}}, index: [][]string{{"device_id"}}}, } func init() { Migrations.MustRegister(func(ctx context.Context, db *bun.DB) error { for _, t := range initTables { - q := db.NewCreateTable().Model(t.model) - for _, f := range t.fks { - q = q.ForeignKey("(?) REFERENCES ? (?)", bun.Ident(f.col), bun.Ident(f.table), bun.Ident("id")) - } - if _, err := q.Exec(ctx); err != nil { + if err := t.create(ctx, db); err != nil { return err } - for _, cols := range t.index { - iq := db.NewCreateIndex().Model(t.model).Index(indexName(t.model, db, cols)) - for _, c := range cols { - iq = iq.Column(c) - } - if _, err := iq.Exec(ctx); err != nil { - return err - } - } } return nil }, func(ctx context.Context, db *bun.DB) error { @@ -318,6 +305,27 @@ func init() { }) } +// create makes the table with its foreign keys, then its indexes. +func (t tableDef) create(ctx context.Context, db *bun.DB) error { + q := db.NewCreateTable().Model(t.model) + for _, f := range t.fks { + q = q.ForeignKey("(?) REFERENCES ? (?)", bun.Ident(f.col), bun.Ident(f.table), bun.Ident("id")) + } + if _, err := q.Exec(ctx); err != nil { + return err + } + for _, cols := range t.index { + iq := db.NewCreateIndex().Model(t.model).Index(indexName(t.model, db, cols)) + for _, c := range cols { + iq = iq.Column(c) + } + if _, err := iq.Exec(ctx); err != nil { + return err + } + } + return nil +} + func indexName(model any, db *bun.DB, cols []string) string { n := "idx_" + db.Dialect().Tables().Get(reflect.TypeOf(model).Elem()).Name for _, c := range cols { diff --git a/internal/store/20261022000004_delivery_queue.go b/internal/store/20261022000004_delivery_queue.go index 21fcc93..b4c2b19 100644 --- a/internal/store/20261022000004_delivery_queue.go +++ b/internal/store/20261022000004_delivery_queue.go @@ -20,46 +20,25 @@ func init() { case dialect.MySQL: ts, text, str = "DATETIME(6)", "LONGTEXT NOT NULL", "VARCHAR(255) NOT NULL DEFAULT ''" } - for _, col := range []string{ + if err := addColumns(ctx, db, "alert_deliveries", []string{ "incident_id " + str, "payload " + text, "next_attempt_at " + ts + " NULL", "expires_at " + ts + " NULL", "parent_id BIGINT NULL", - } { - if _, err := db.NewAddColumn().Table("alert_deliveries").ColumnExpr(col).Exec(ctx); err != nil { - return err - } + }); err != nil { + return err } - for idx, cols := range map[string][]string{ + return createIndexes(ctx, db, "alert_deliveries", map[string][]string{ "idx_alert_deliveries_due": {"status", "next_attempt_at"}, "idx_alert_deliveries_parent": {"parent_id"}, "idx_alert_deliveries_incident": {"incident_id"}, - } { - q := db.NewCreateIndex().Table("alert_deliveries").Index(idx) - for _, c := range cols { - q = q.Column(c) - } - if _, err := q.Exec(ctx); err != nil { - return err - } - } - return nil + }) }, func(ctx context.Context, db *bun.DB) error { - for _, idx := range []string{"idx_alert_deliveries_due", "idx_alert_deliveries_parent", "idx_alert_deliveries_incident"} { - q := "DROP INDEX " + idx - if db.Dialect().Name() == dialect.MySQL { - q += " ON alert_deliveries" - } - if _, err := db.ExecContext(ctx, q); err != nil { - return err - } + idx := []string{"idx_alert_deliveries_due", "idx_alert_deliveries_parent", "idx_alert_deliveries_incident"} + if err := dropIndexes(ctx, db, "alert_deliveries", idx); err != nil { + return err } - for _, c := range []string{"incident_id", "payload", "next_attempt_at", "expires_at", "parent_id"} { - if _, err := db.NewDropColumn().Table("alert_deliveries").Column(c).Exec(ctx); err != nil { - return err - } - } - return nil + return dropColumns(ctx, db, "alert_deliveries", []string{"incident_id", "payload", "next_attempt_at", "expires_at", "parent_id"}) }) } diff --git a/internal/store/20261022000005_alert_state.go b/internal/store/20261022000005_alert_state.go index 1efa02f..b51a5a2 100644 --- a/internal/store/20261022000005_alert_state.go +++ b/internal/store/20261022000005_alert_state.go @@ -21,7 +21,7 @@ func init() { case dialect.MySQL: ts, text = "DATETIME(6)", "LONGTEXT NOT NULL" } - for _, col := range []string{ + if err := addColumns(ctx, db, "alerts", []string{ "series_key " + key, "device_slug " + name, "iface " + name, @@ -40,34 +40,18 @@ func init() { "flapping_until " + ts + " NULL", "nodata_count BIGINT NOT NULL DEFAULT 0", "flap_changes " + text, - } { - if _, err := db.NewAddColumn().Table("alerts").ColumnExpr(col).Exec(ctx); err != nil { - return err - } + }); err != nil { + return err } - for idx, col := range map[string]string{"idx_alerts_series": "series_key", "idx_alerts_pending": "notify_pending"} { - if _, err := db.NewCreateIndex().Table("alerts").Index(idx).Column(col).Exec(ctx); err != nil { - return err - } - } - return nil + return createIndexes(ctx, db, "alerts", map[string][]string{ + "idx_alerts_series": {"series_key"}, "idx_alerts_pending": {"notify_pending"}, + }) }, func(ctx context.Context, db *bun.DB) error { - for _, idx := range []string{"idx_alerts_series", "idx_alerts_pending"} { - q := "DROP INDEX " + idx - if db.Dialect().Name() == dialect.MySQL { - q += " ON alerts" - } - if _, err := db.ExecContext(ctx, q); err != nil { - return err - } + if err := dropIndexes(ctx, db, "alerts", []string{"idx_alerts_series", "idx_alerts_pending"}); err != nil { + return err } - for _, c := range []string{"series_key", "device_slug", "iface", "component", "severity", "summary", "description", - "value", "threshold", "base_state", "prior_state", "notified_state", "notify_pending", "pending_since", - "last_eval_at", "flapping_until", "nodata_count", "flap_changes"} { - if _, err := db.NewDropColumn().Table("alerts").Column(c).Exec(ctx); err != nil { - return err - } - } - return nil + return dropColumns(ctx, db, "alerts", []string{"series_key", "device_slug", "iface", "component", "severity", "summary", + "description", "value", "threshold", "base_state", "prior_state", "notified_state", "notify_pending", "pending_since", + "last_eval_at", "flapping_until", "nodata_count", "flap_changes"}) }) } diff --git a/internal/store/alerts.go b/internal/store/alerts.go index 271d719..69642a8 100644 --- a/internal/store/alerts.go +++ b/internal/store/alerts.go @@ -102,6 +102,8 @@ type Alerts interface { PruneAlerts(ctx context.Context, olderThan time.Time) (int64, error) } +var closedAlertStates = []string{AlertResolved, AlertRetired} + var activeAlertStates = []string{AlertPending, AlertFiring, AlertStale, AlertFlapping} func normAlertTimes(a *Alert) { @@ -138,7 +140,7 @@ func (s *bunStore) UpsertAlertState(ctx context.Context, a *Alert) error { func (s *bunStore) ListActiveAlertStates(ctx context.Context) ([]Alert, error) { var out []Alert err := s.db.NewSelect().Model(&out). - Where("a.state IN (?) OR a.notify_pending <> ''", bun.In(activeAlertStates)). + Where("a.state IN (?) OR a.notify_pending <> ''", bun.List(activeAlertStates)). Order("a.id ASC").Scan(ctx) return out, mapErr(err) } @@ -164,10 +166,10 @@ func (s *bunStore) ListAlerts(ctx context.Context, f AlertFilter, p Page) ([]Ale var out []Alert q := s.db.NewSelect().Model(&out) if len(f.States) > 0 { - q = q.Where("a.state IN (?)", bun.In(f.States)) + q = q.Where("a.state IN (?)", bun.List(f.States)) } if f.Active { - q = q.Where("a.state IN (?)", bun.In(activeAlertStates)) + q = q.Where("a.state IN (?)", bun.List(activeAlertStates)) } if f.Rule != "" { q = q.Where("a.rule = ?", f.Rule) @@ -188,7 +190,7 @@ func (s *bunStore) ListAlerts(ctx context.Context, f AlertFilter, p Page) ([]Ale } limit, off := pageBounds(p) n, err := q.Order("a.id DESC").Limit(limit).Offset(off).ScanAndCount(ctx) - return out, int64(n), mapErr(err) + return out, n, mapErr(err) } func pageBounds(p Page) (limit, off int64) { @@ -211,7 +213,7 @@ func (s *bunStore) AckAlert(ctx context.Context, id int64, by, reason string, un } res, err := s.db.NewUpdate().Model((*Alert)(nil)). Set("ack_by = ?", by).Set("ack_reason = ?", reason).Set("ack_until = ?", utcMicro(until)). - Where("id = ? AND state IN (?)", id, bun.In(activeAlertStates)).Exec(ctx) + Where("id = ? AND state IN (?)", id, bun.List(activeAlertStates)).Exec(ctx) if err != nil { return mapErr(err) } @@ -240,7 +242,7 @@ func (s *bunStore) PruneAlerts(ctx context.Context, olderThan time.Time) (int64, err := s.WithTx(ctx, func(tx Store) error { t := tx.(*bunStore) old := t.db.NewSelect().Model((*Alert)(nil)).Column("id"). - Where("state IN (?) AND cleared_at IS NOT NULL AND cleared_at < ?", bun.In([]string{AlertResolved, AlertRetired}), utcMicro(olderThan)) + Where("state IN (?) AND cleared_at IS NOT NULL AND cleared_at < ?", bun.List(closedAlertStates), utcMicro(olderThan)) // Attempt rows reference their queue row, which references the alert. if _, err := t.db.NewDelete().Model((*Delivery)(nil)).Where("alert_id IN (?)", old).Where("parent_id IS NOT NULL").Exec(ctx); err != nil { return mapErr(err) @@ -249,7 +251,8 @@ func (s *bunStore) PruneAlerts(ctx context.Context, olderThan time.Time) (int64, return mapErr(err) } res, err := t.db.NewDelete().Model((*Alert)(nil)). - Where("state IN (?) AND cleared_at IS NOT NULL AND cleared_at < ?", bun.In([]string{AlertResolved, AlertRetired}), utcMicro(olderThan)).Exec(ctx) + Where("state IN (?) AND cleared_at IS NOT NULL AND cleared_at < ?", bun.List(closedAlertStates), utcMicro(olderThan)). + Exec(ctx) if err != nil { return mapErr(err) } diff --git a/internal/store/components.go b/internal/store/components.go index 31f7c3e..37ac5f9 100644 --- a/internal/store/components.go +++ b/internal/store/components.go @@ -37,35 +37,51 @@ func (s *bunStore) ReplaceComponents(ctx context.Context, deviceID int64, table return mapErr(err) } now := s.now() - have := make(map[string]Component, len(cur)) - for _, c := range cur { - have[c.Idx] = c + if err := t.upsertComponents(ctx, deviceID, table, rows, cur, now); err != nil { + return err } - seen := make(map[string]bool, len(rows)) - for _, r := range rows { - r.DeviceID, r.TableName = deviceID, table - seen[r.Idx] = true - if old, ok := have[r.Idx]; ok { - r.FirstSeen = old.FirstSeen - if _, err := t.db.NewUpdate().Model(&r).Column("label", "retired_at").WherePK().Exec(ctx); err != nil { - return mapErr(err) - } - continue - } - r.FirstSeen, r.RetiredAt = now, nil - if _, err := t.db.NewInsert().Model(&r).Exec(ctx); err != nil { + return t.retireMissingComponents(ctx, rows, cur, now) + }) +} + +// upsertComponents inserts rows that are new and refreshes (label, un-retire) those already in cur. +func (s *bunStore) upsertComponents(ctx context.Context, deviceID int64, table string, rows, cur []Component, now time.Time) error { + have := make(map[string]Component, len(cur)) + for _, c := range cur { + have[c.Idx] = c + } + for _, r := range rows { + r.DeviceID, r.TableName = deviceID, table + if old, ok := have[r.Idx]; ok { + r.FirstSeen = old.FirstSeen + if _, err := s.db.NewUpdate().Model(&r).Column("label", "retired_at").WherePK().Exec(ctx); err != nil { return mapErr(err) } + continue } - for _, c := range cur { - if !seen[c.Idx] && c.RetiredAt == nil { - if _, err := t.db.NewUpdate().Model(&c).Set("retired_at = ?", now).WherePK().Exec(ctx); err != nil { - return mapErr(err) - } - } + r.FirstSeen, r.RetiredAt = now, nil + if _, err := s.db.NewInsert().Model(&r).Exec(ctx); err != nil { + return mapErr(err) } - return nil - }) + } + return nil +} + +// retireMissingComponents retires the rows of cur that rows no longer lists. +func (s *bunStore) retireMissingComponents(ctx context.Context, rows, cur []Component, now time.Time) error { + seen := make(map[string]bool, len(rows)) + for _, r := range rows { + seen[r.Idx] = true + } + for _, c := range cur { + if seen[c.Idx] || c.RetiredAt != nil { + continue + } + if _, err := s.db.NewUpdate().Model(&c).Set("retired_at = ?", now).WherePK().Exec(ctx); err != nil { + return mapErr(err) + } + } + return nil } func (s *bunStore) ListComponents(ctx context.Context, deviceID int64) ([]Component, error) { diff --git a/internal/store/deliveries.go b/internal/store/deliveries.go index efa982a..4e589d4 100644 --- a/internal/store/deliveries.go +++ b/internal/store/deliveries.go @@ -177,5 +177,5 @@ func (s *bunStore) ListDeliveries(ctx context.Context, alertID int64, p Page) ([ q = q.Where("alert_id = ?", alertID) } n, err := q.OrderExpr("id DESC").Limit(p.Limit).Offset(p.Offset).ScanAndCount(ctx) - return out, int64(n), mapErr(err) + return out, n, mapErr(err) } diff --git a/internal/store/device.go b/internal/store/device.go index 59f0eda..5e71c06 100644 --- a/internal/store/device.go +++ b/internal/store/device.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "net/netip" + "slices" "strings" "time" ) @@ -299,13 +300,14 @@ func normAddr(a string) (string, error) { return ip.WithZone("").Unmap().String(), nil } -func (s *bunStore) SetAddresses(ctx context.Context, deviceID int64, addrs []string) error { - var rows []DeviceAddress +// preferredAddresses normalises and de-duplicates addrs, marks the preferred +// one (first IPv6, else first) and returns the rows with the management address. +func preferredAddresses(deviceID int64, addrs []string) (rows []DeviceAddress, mgmt string, err error) { seen := map[string]bool{} for _, a := range addrs { n, err := normAddr(a) if err != nil { - return err + return nil, "", err } if seen[n] { continue @@ -317,21 +319,22 @@ func (s *bunStore) SetAddresses(ctx context.Context, deviceID int64, addrs []str } rows = append(rows, DeviceAddress{DeviceID: deviceID, Addr: n, Family: fam}) } - pref := -1 - for i, r := range rows { - if r.Family == 6 { - pref = i - break - } - } + pref := slices.IndexFunc(rows, func(r DeviceAddress) bool { return r.Family == 6 }) if pref < 0 && len(rows) > 0 { pref = 0 } - mgmt := "" if pref >= 0 { rows[pref].Preferred = true mgmt = rows[pref].Addr } + return rows, mgmt, nil +} + +func (s *bunStore) SetAddresses(ctx context.Context, deviceID int64, addrs []string) error { + rows, mgmt, err := preferredAddresses(deviceID, addrs) + if err != nil { + return err + } return s.WithTx(ctx, func(tx Store) error { t := tx.(*bunStore) res, err := t.db.NewUpdate().Model((*Device)(nil)).Set("mgmt_ip = ?", mgmt).Where("id = ?", deviceID).Exec(ctx) diff --git a/internal/store/iface.go b/internal/store/iface.go index e6cb17f..37c56b5 100644 --- a/internal/store/iface.go +++ b/internal/store/iface.go @@ -13,31 +13,16 @@ func (s *bunStore) UpsertInterfaces(ctx context.Context, deviceID int64, ifs []I if len(ifs) == 0 { return nil } - ids := make([]string, 0, len(ifs)) - seen := map[string]bool{} - for _, i := range ifs { - if !ulid.Valid(i.ID) { - return fmt.Errorf("%w: interface id %q is not a ULID", ErrInvalid, i.ID) - } - if seen[i.ID] { - return fmt.Errorf("%w: duplicate interface id %s", ErrInvalid, i.ID) - } - seen[i.ID] = true - ids = append(ids, i.ID) + ids, err := interfaceIDs(ifs) + if err != nil { + return err } return s.WithTx(ctx, func(tx Store) error { t := tx.(*bunStore) now := t.now() - existing := map[string]Interface{} - for lo := 0; lo < len(ids); lo += upsertChunk { - hi := min(lo+upsertChunk, len(ids)) - var rows []Interface - if err := t.db.NewSelect().Model(&rows).Where("i.id IN (?)", in(ids[lo:hi])).Scan(ctx); err != nil { - return mapErr(err) - } - for _, r := range rows { - existing[r.ID] = r - } + existing, err := t.interfacesByID(ctx, ids) + if err != nil { + return err } var fresh []Interface for _, i := range ifs { @@ -67,6 +52,39 @@ func (s *bunStore) UpsertInterfaces(ctx context.Context, deviceID int64, ifs []I }) } +// interfaceIDs returns the IDs of ifs, rejecting non-ULIDs and duplicates. +func interfaceIDs(ifs []Interface) ([]string, error) { + ids := make([]string, 0, len(ifs)) + seen := map[string]bool{} + for _, i := range ifs { + if !ulid.Valid(i.ID) { + return nil, fmt.Errorf("%w: interface id %q is not a ULID", ErrInvalid, i.ID) + } + if seen[i.ID] { + return nil, fmt.Errorf("%w: duplicate interface id %s", ErrInvalid, i.ID) + } + seen[i.ID] = true + ids = append(ids, i.ID) + } + return ids, nil +} + +// interfacesByID loads the existing rows for ids, in chunks small enough for the driver's bind limit. +func (s *bunStore) interfacesByID(ctx context.Context, ids []string) (map[string]Interface, error) { + existing := map[string]Interface{} + for lo := 0; lo < len(ids); lo += upsertChunk { + hi := min(lo+upsertChunk, len(ids)) + var rows []Interface + if err := s.db.NewSelect().Model(&rows).Where("i.id IN (?)", in(ids[lo:hi])).Scan(ctx); err != nil { + return nil, mapErr(err) + } + for _, r := range rows { + existing[r.ID] = r + } + } + return existing, nil +} + func (s *bunStore) ListInterfaces(ctx context.Context, deviceID int64, includeRetired bool) ([]Interface, error) { var rows []Interface q := s.db.NewSelect().Model(&rows).Where("i.device_id = ?", deviceID) diff --git a/internal/store/migrate_steps.go b/internal/store/migrate_steps.go new file mode 100644 index 0000000..9c91a68 --- /dev/null +++ b/internal/store/migrate_steps.go @@ -0,0 +1,59 @@ +package store + +import ( + "context" + + "github.com/uptrace/bun" + "github.com/uptrace/bun/dialect" +) + +// Shared building blocks for migrations. Each runs exactly the statements the +// migrations used to inline, so existing migration behaviour is unchanged. + +// addColumns runs ALTER TABLE ... ADD COLUMN for each column expression. +func addColumns(ctx context.Context, db *bun.DB, table string, cols []string) error { + for _, col := range cols { + if _, err := db.NewAddColumn().Table(table).ColumnExpr(col).Exec(ctx); err != nil { + return err + } + } + return nil +} + +// dropColumns drops each named column. +func dropColumns(ctx context.Context, db *bun.DB, table string, cols []string) error { + for _, c := range cols { + if _, err := db.NewDropColumn().Table(table).Column(c).Exec(ctx); err != nil { + return err + } + } + return nil +} + +// createIndexes creates each index (name -> columns) on table. +func createIndexes(ctx context.Context, db *bun.DB, table string, indexes map[string][]string) error { + for idx, cols := range indexes { + q := db.NewCreateIndex().Table(table).Index(idx) + for _, c := range cols { + q = q.Column(c) + } + if _, err := q.Exec(ctx); err != nil { + return err + } + } + return nil +} + +// dropIndexes drops the named indexes; MySQL scopes DROP INDEX to a table. +func dropIndexes(ctx context.Context, db *bun.DB, table string, names []string) error { + for _, idx := range names { + q := "DROP INDEX " + idx + if db.Dialect().Name() == dialect.MySQL { + q += " ON " + table + } + if _, err := db.ExecContext(ctx, q); err != nil { + return err + } + } + return nil +} diff --git a/internal/store/misc.go b/internal/store/misc.go index b76b3f3..628811c 100644 --- a/internal/store/misc.go +++ b/internal/store/misc.go @@ -103,7 +103,9 @@ func (s *bunStore) ListAudit(ctx context.Context, p Page) ([]AuditEntry, int64, return rows, total, nil } -func (s *bunStore) CreateIdentityReview(ctx context.Context, deviceID *int64, kind string, candidates, evidence any) (*IdentityReview, error) { +func (s *bunStore) CreateIdentityReview( + ctx context.Context, deviceID *int64, kind string, candidates, evidence any, +) (*IdentityReview, error) { switch kind { case ReviewAmbiguousMatch, ReviewHardwareReplaced, ReviewReattachCandidate: default: diff --git a/internal/store/open.go b/internal/store/open.go index d512393..05d852b 100644 --- a/internal/store/open.go +++ b/internal/store/open.go @@ -71,7 +71,7 @@ func Open(ctx context.Context, driver, dsn string, kr *secrets.Keyring, clk cloc return nil, fmt.Errorf("store: unsupported driver %q", driver) } if err := db.PingContext(ctx); err != nil { - db.Close() + _ = db.Close() // the ping error is the one worth reporting return nil, err } return &bunStore{db: db, root: db, kr: kr, clk: clk}, nil @@ -98,24 +98,24 @@ func (s *bunStore) migrator() *migrate.Migrator { } func (s *bunStore) Migrate(ctx context.Context) error { - if s.tx { - return errors.New("store: Migrate inside a transaction") - } - m := s.migrator() - if err := m.Init(ctx); err != nil { + return s.withMigrator(ctx, "Migrate", func(m *migrate.Migrator) error { + _, err := m.Migrate(ctx) return err - } - if err := m.Lock(ctx); err != nil { - return err - } - defer m.Unlock(ctx) - _, err := m.Migrate(ctx) - return err + }) } func (s *bunStore) Rollback(ctx context.Context) error { + return s.withMigrator(ctx, "Rollback", func(m *migrate.Migrator) error { + _, err := m.Rollback(ctx) + return err + }) +} + +// withMigrator runs fn on an initialised migrator holding the migration lock. +// An unlock failure is reported alongside fn's error rather than dropped. +func (s *bunStore) withMigrator(ctx context.Context, op string, fn func(*migrate.Migrator) error) (err error) { if s.tx { - return errors.New("store: Rollback inside a transaction") + return fmt.Errorf("store: %s inside a transaction", op) } m := s.migrator() if err := m.Init(ctx); err != nil { @@ -124,9 +124,8 @@ func (s *bunStore) Rollback(ctx context.Context) error { if err := m.Lock(ctx); err != nil { return err } - defer m.Unlock(ctx) - _, err := m.Rollback(ctx) - return err + defer func() { err = errors.Join(err, m.Unlock(ctx)) }() + return fn(m) } func (s *bunStore) WithTx(ctx context.Context, fn func(Store) error) error { @@ -151,7 +150,7 @@ func mapErr(err error) error { return ErrNotFound } if isUnique(err) { - return fmt.Errorf("%w: %v", ErrConflict, err) + return fmt.Errorf("%w: %w", ErrConflict, err) } return err } @@ -189,7 +188,7 @@ func likePattern(q string) string { type selectQ = bun.SelectQuery -func in[T any](v []T) schema.QueryAppender { return bun.In(v) } +func in[T any](v []T) schema.QueryAppender { return bun.List(v) } func bunIdent(s string) bun.Ident { return bun.Ident(s) } diff --git a/internal/store/store_test.go b/internal/store/store_test.go index e1c933a..4fc318b 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -67,7 +67,7 @@ func run(t *testing.T, fn func(t *testing.T, e *env)) { _ = st.Rollback(ctx) t.Cleanup(func() { _ = st.Rollback(ctx) - st.Close() + _ = st.Close() }) if err := st.Migrate(ctx); err != nil { t.Fatal(err) @@ -301,7 +301,7 @@ func TestCredentialRoundTripAndRotation(t *testing.T) { must(t, err) st2, err := Open(ctx, e.b.driver, e.b.dsn, kr2, e.clk) must(t, err) - defer st2.Close() + defer func() { _ = st2.Close() }() got, err = st2.GetCredential(ctx, c.ID) must(t, err) if *got != *c { diff --git a/internal/vmsup/binary.go b/internal/vmsup/binary.go index 4791a3e..8e25daa 100644 --- a/internal/vmsup/binary.go +++ b/internal/vmsup/binary.go @@ -57,18 +57,7 @@ func (s binarySpec) verify() error { // /bin when needed, and verifies it. func prepareBinary(dataDir string) (binarySpec, error) { if p := os.Getenv(envBinary); p != "" { - spec := binarySpec{path: p} - if os.Getenv(envUnverified) != "1" { - spec.want = binPin(runtime.GOARCH) - if runtime.GOOS != "linux" || spec.want == "" { - return spec, fmt.Errorf("%w: no pinned hash for %s/%s; set %s=1 for tests", - ErrChecksum, runtime.GOOS, runtime.GOARCH, envUnverified) - } - } - if err := spec.verify(); err != nil { - return spec, err - } - return spec, nil + return prepareSuppliedBinary(p) } if len(embeddedGz) == 0 { return binarySpec{}, ErrNoBinary @@ -81,6 +70,23 @@ func prepareBinary(dataDir string) (binarySpec, error) { return spec, nil } +// prepareSuppliedBinary verifies a binary named by NMON_VM_BINARY against the +// pinned hash, unless the test-only override disables the check. +func prepareSuppliedBinary(path string) (binarySpec, error) { + spec := binarySpec{path: path} + if os.Getenv(envUnverified) != "1" { + spec.want = binPin(runtime.GOARCH) + if runtime.GOOS != "linux" || spec.want == "" { + return spec, fmt.Errorf("%w: no pinned hash for %s/%s; set %s=1 for tests", + ErrChecksum, runtime.GOOS, runtime.GOARCH, envUnverified) + } + } + if err := spec.verify(); err != nil { + return spec, err + } + return spec, nil +} + // extract writes the gunzipped data to spec.path (mode 0755) unless a file with // the right hash is already there. It writes a temp file in the same directory, // verifies it, and renames it into place, so a bad or partial file is never @@ -105,7 +111,7 @@ func extract(gz []byte, spec binarySpec) error { zr, err := gzip.NewReader(bytes.NewReader(gz)) if err != nil { _ = tmp.Close() - return fmt.Errorf("%w: embedded archive: %v", ErrChecksum, err) + return fmt.Errorf("%w: embedded archive: %w", ErrChecksum, err) } h := sha256.New() n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(zr, maxBinarySize+1)) @@ -114,7 +120,7 @@ func extract(gz []byte, spec binarySpec) error { } if err != nil { _ = tmp.Close() - return fmt.Errorf("%w: unpack embedded binary: %v", ErrChecksum, err) + return fmt.Errorf("%w: unpack embedded binary: %w", ErrChecksum, err) } if got := hex.EncodeToString(h.Sum(nil)); got != spec.want { _ = tmp.Close() @@ -142,7 +148,7 @@ func fileSHA256(path string) (string, error) { if err != nil { return "", err } - defer f.Close() + defer func() { _ = f.Close() }() h := sha256.New() if _, err := io.Copy(h, f); err != nil { return "", err diff --git a/internal/vmsup/binary_test.go b/internal/vmsup/binary_test.go index 58b33c1..33153c1 100644 --- a/internal/vmsup/binary_test.go +++ b/internal/vmsup/binary_test.go @@ -16,8 +16,8 @@ func gz(t *testing.T, data []byte) []byte { t.Helper() var b bytes.Buffer w := gzip.NewWriter(&b) - w.Write(data) - w.Close() + _, _ = w.Write(data) + _ = w.Close() return b.Bytes() } @@ -84,12 +84,16 @@ func TestExtractRefusesBadChecksum(t *testing.T) { func TestVerifyDetectsChange(t *testing.T) { p := filepath.Join(t.TempDir(), "b") - os.WriteFile(p, []byte("one"), 0o755) + if err := os.WriteFile(p, []byte("one"), 0o755); err != nil { + t.Fatal(err) + } spec := binarySpec{path: p, want: sum([]byte("one"))} if err := spec.verify(); err != nil { t.Fatal(err) } - os.WriteFile(p, []byte("two"), 0o755) + if err := os.WriteFile(p, []byte("two"), 0o755); err != nil { + t.Fatal(err) + } if err := spec.verify(); !errors.Is(err, ErrChecksum) { t.Fatalf("err = %v", err) } diff --git a/internal/vmsup/child.go b/internal/vmsup/child.go new file mode 100644 index 0000000..d726e60 --- /dev/null +++ b/internal/vmsup/child.go @@ -0,0 +1,142 @@ +package vmsup + +import ( + "bytes" + "fmt" + "log/slog" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "syscall" + "time" +) + +// proc is one running child. +type proc struct { + cmd *exec.Cmd + exited chan struct{} + err error // valid after exited is closed +} + +// spawn verifies the binary and starts one child. fatal means retrying cannot help. +func (s *Supervisor) spawn(st *store) (p *proc, fatal bool, err error) { + if err := s.spec.verify(); err != nil { + return nil, true, err + } + port, err := st.pickPort() + if err != nil { + return nil, false, err + } + path, err := filepath.Abs(s.spec.path) + if err != nil { + return nil, true, err + } + args := []string{ + "-storageDataPath=" + st.dir, + "-retentionPeriod=" + RetentionArg(st.retention), + "-httpListenAddr=127.0.0.1:" + strconv.Itoa(port), + "-loggerLevel=WARN", + "-memory.allowedPercent=30", // two stores share the box + "-search.maxUniqueTimeseries=1000000", + "-search.latencyOffset=0s", // default 30 s hides the newest samples from "now" queries + } + args = append(args, st.extra...) + + lw := &lineLogger{log: s.log, store: st.name} + cmd := exec.Command(path, args...) + cmd.Env = []string{} // nothing from nmon's environment (secrets) reaches the store + cmd.SysProcAttr = sysProcAttr() + cmd.Stdout, cmd.Stderr = lw, lw + cmd.WaitDelay = 2 * time.Second + if err := cmd.Start(); err != nil { + return nil, false, fmt.Errorf("start %s: %w", path, err) + } + p = &proc{cmd: cmd, exited: make(chan struct{})} + go func() { + p.err = cmd.Wait() + lw.flush() + close(p.exited) + }() + st.mu.Lock() + st.pid = cmd.Process.Pid + st.startedAt = s.clk.Now() + st.mu.Unlock() + s.log.Info("store started", "store", st.name, "pid", cmd.Process.Pid, "addr", st.currentURL()) + return p, false, nil +} + +// terminate sends SIGTERM and waits; after stopTimeout, or once Stop's context +// has ended, it kills the process group. +func (s *Supervisor) terminate(p *proc) { + select { + case <-p.exited: + return + default: + } + _ = p.cmd.Process.Signal(syscall.SIGTERM) + select { + case <-p.exited: + return + case <-s.clk.After(s.opts.stopTimeout): + case <-s.killNow: + } + killGroup(p.cmd.Process.Pid) + <-p.exited +} + +// kill ends an unresponsive child at once. +func (s *Supervisor) kill(p *proc) { + killGroup(p.cmd.Process.Pid) + <-p.exited +} + +func describeExit(err error) string { + if err == nil { + return "exited with status 0" + } + return "exited: " + err.Error() +} + +// lineLogger turns child output into log lines. +type lineLogger struct { + log *slog.Logger + store string + mu sync.Mutex + buf []byte +} + +func (l *lineLogger) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + l.buf = append(l.buf, p...) + for { + i := bytes.IndexByte(l.buf, '\n') + if i < 0 { + break + } + l.emit(string(l.buf[:i])) + l.buf = l.buf[i+1:] + } + if len(l.buf) > 64<<10 { // a line with no end: don't grow without bound + l.emit(string(l.buf)) + l.buf = nil + } + return len(p), nil +} + +func (l *lineLogger) flush() { + l.mu.Lock() + defer l.mu.Unlock() + if len(l.buf) > 0 { + l.emit(string(l.buf)) + l.buf = nil + } +} + +func (l *lineLogger) emit(line string) { + if line = strings.TrimRight(line, "\r"); line != "" { + l.log.Warn("store output", "store", l.store, "line", line) + } +} diff --git a/internal/vmsup/embed_linux_amd64.go b/internal/vmsup/embed_linux_amd64.go index 928ce5f..30c8784 100644 --- a/internal/vmsup/embed_linux_amd64.go +++ b/internal/vmsup/embed_linux_amd64.go @@ -9,5 +9,7 @@ var embeddedGz []byte const ( embeddedBinSHA256 = binSHA256Amd64 - embeddedGzSHA256 = gzSHA256Amd64 + // The .gz that is embedded (internal/gzbin). Checked by the vmembed tests and + // by fetch-vm.sh; the runtime trusts only the uncompressed hash. + embeddedGzSHA256 = "2a5e0c1a7fe9825b3ab0a1f2652471608736736670eb6d8953273f4743f909d1" ) diff --git a/internal/vmsup/embed_linux_arm64.go b/internal/vmsup/embed_linux_arm64.go index 3bcc040..4de4fb0 100644 --- a/internal/vmsup/embed_linux_arm64.go +++ b/internal/vmsup/embed_linux_arm64.go @@ -9,5 +9,7 @@ var embeddedGz []byte const ( embeddedBinSHA256 = binSHA256Arm64 - embeddedGzSHA256 = gzSHA256Arm64 + // The .gz that is embedded (internal/gzbin). Checked by the vmembed tests and + // by fetch-vm.sh; the runtime trusts only the uncompressed hash. + embeddedGzSHA256 = "d7d763d9f81fc3ab7fb3da5a71ce36e8b3e3083d331f7733d1eec9998da23d78" ) diff --git a/internal/vmsup/events.go b/internal/vmsup/events.go new file mode 100644 index 0000000..c593b95 --- /dev/null +++ b/internal/vmsup/events.go @@ -0,0 +1,31 @@ +package vmsup + +import "time" + +// Event types passed to Options.OnEvent. +const ( + EventStoreFailed = "store_failed" + EventStoreRestarted = "store_restarted" + EventStoreRecovered = "store_recovered" +) + +// Event describes a state change of one store. +type Event struct { + Type string // EventStore* + Store string // StoreHot or StoreLong + Time time.Time + Detail string + // Restarts is the number of restarts in the current ten-minute window. + Restarts int +} + +func (s *Supervisor) emit(st *store, typ, detail string) { + st.mu.Lock() + n := len(st.history) + st.mu.Unlock() + ev := Event{Type: typ, Store: st.name, Time: s.clk.Now(), Detail: detail, Restarts: n} + s.log.Warn("store event", "type", typ, "store", st.name, "detail", detail, "restarts_in_window", n) + if s.opts.OnEvent != nil { + s.opts.OnEvent(ev) + } +} diff --git a/internal/vmsup/health.go b/internal/vmsup/health.go new file mode 100644 index 0000000..562485d --- /dev/null +++ b/internal/vmsup/health.go @@ -0,0 +1,90 @@ +package vmsup + +import ( + "context" + "fmt" + "io" + "net/http" +) + +// watchExternal only probes /health of an operator-run store. +func (s *Supervisor) watchExternal(ctx context.Context, st *store) { + for { + ok := s.probe(ctx, st.currentURL()) + st.setHealthy(ok) + d := s.opts.healthEvery + if !ok { + d = startupProbe + if d > s.opts.healthEvery { + d = s.opts.healthEvery + } + } + select { + case <-ctx.Done(): + return + case <-s.clk.After(d): + } + } +} + +// watch probes a running child until it exits, stops answering, or ctx ends. +// alive is false when ctx ended (the child has then been terminated). +func (s *Supervisor) watch(ctx context.Context, st *store, p *proc) (reason string, alive bool) { + started := s.clk.Now() + everHealthy := false + fails := 0 + for { + d := s.opts.healthEvery + if !everHealthy && startupProbe < d { + d = startupProbe + } + select { + case <-ctx.Done(): + s.terminate(p) + return "", false + case <-p.exited: + return describeExit(p.err), true + case <-s.clk.After(d): + } + if s.probe(ctx, st.currentURL()) { + everHealthy, fails = true, 0 + st.setHealthy(true) + st.mu.Lock() + rec := st.recoverNext + st.recoverNext = false + st.mu.Unlock() + if rec { + s.emit(st, EventStoreRecovered, "answering /health") + } + continue + } + st.setHealthy(false) + if everHealthy { + fails++ + if fails >= probeFailures { + s.kill(p) // it is not answering, so it will not honour SIGTERM either + return fmt.Sprintf("killed after %d failed health checks", fails), true + } + } else if s.clk.Now().Sub(started) >= s.opts.startTimeout { + s.kill(p) + return fmt.Sprintf("not healthy %s after start", s.opts.startTimeout), true + } + } +} + +func (s *Supervisor) probe(ctx context.Context, base string) bool { + if base == "" { + return false + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/health", nil) + if err != nil { + return false + } + resp, err := s.hc.Do(req) + if err != nil { + return false + } + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<10)) + _ = resp.Body.Close() + return resp.StatusCode == http.StatusOK +} diff --git a/internal/vmsup/integration_test.go b/internal/vmsup/integration_test.go index 2f00531..22d01a9 100644 --- a/internal/vmsup/integration_test.go +++ b/internal/vmsup/integration_test.go @@ -62,7 +62,7 @@ func queryValue(t *testing.T, qr *Querier, store, q string) (float64, bool) { return 0, false } var v float64 - fmt.Sscanf(r.Data.Result[0].Value[1].(string), "%g", &v) + _, _ = fmt.Sscanf(r.Data.Result[0].Value[1].(string), "%g", &v) return v, true } @@ -87,7 +87,7 @@ func TestIntegrationWriteAndQuery(t *testing.T) { for { if q.Depth() == 0 { if resp, err := http.Get(s.URL(store) + "/internal/force_flush"); err == nil { - resp.Body.Close() + _ = resp.Body.Close() } } if v, ok := queryValue(t, qr, store, name+`{device="d1"}`); ok { @@ -186,7 +186,7 @@ func listenSockets(t *testing.T, path string) []listener { } t.Fatal(err) } - defer f.Close() + defer func() { _ = f.Close() }() var out []listener sc := bufio.NewScanner(f) sc.Scan() // header @@ -197,7 +197,7 @@ func listenSockets(t *testing.T, path string) []listener { } ap := strings.Split(fs[1], ":") var port int64 - fmt.Sscanf(ap[1], "%X", &port) + _, _ = fmt.Sscanf(ap[1], "%X", &port) out = append(out, listener{addr: ap[0], port: port, inode: fs[9]}) } return out diff --git a/internal/vmsup/internal/gzbin/main.go b/internal/vmsup/internal/gzbin/main.go index 07d6b62..460544a 100644 --- a/internal/vmsup/internal/gzbin/main.go +++ b/internal/vmsup/internal/gzbin/main.go @@ -26,23 +26,23 @@ func run(in, out string) error { if err != nil { return err } - defer src.Close() + defer func() { _ = src.Close() }() dst, err := os.Create(out) if err != nil { return err } zw, err := gzip.NewWriterLevel(dst, gzip.BestCompression) if err != nil { - dst.Close() + _ = dst.Close() return err } zw.Header = gzip.Header{} // zero header: no name, no mtime if _, err := io.Copy(zw, src); err != nil { - dst.Close() + _ = dst.Close() return err } if err := zw.Close(); err != nil { - dst.Close() + _ = dst.Close() return err } return dst.Close() diff --git a/internal/vmsup/main_test.go b/internal/vmsup/main_test.go index bc274f0..dd31453 100644 --- a/internal/vmsup/main_test.go +++ b/internal/vmsup/main_test.go @@ -37,17 +37,17 @@ func runFakeStore(args []string) { } fmt.Fprintln(os.Stderr, "fake store starting", args) mux := http.NewServeMux() - mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "OK") }) + mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { _, _ = fmt.Fprint(w, "OK") }) mux.HandleFunc("/api/v1/import/prometheus", func(w http.ResponseWriter, r *http.Request) { f, err := os.OpenFile(filepath.Join(dir, "import.log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) if err == nil { _, _ = f.ReadFrom(r.Body) - f.Close() + _ = f.Close() } w.WriteHeader(http.StatusNoContent) }) mux.HandleFunc("/api/v1/query", func(w http.ResponseWriter, _ *http.Request) { - fmt.Fprint(w, `{"status":"success","data":{"resultType":"vector","result":[]}}`) + _, _ = fmt.Fprint(w, `{"status":"success","data":{"resultType":"vector","result":[]}}`) }) srv := &http.Server{Addr: addr, Handler: mux} sig := make(chan os.Signal, 1) diff --git a/internal/vmsup/pins.go b/internal/vmsup/pins.go index 512032f..c707a8a 100644 --- a/internal/vmsup/pins.go +++ b/internal/vmsup/pins.go @@ -13,11 +13,6 @@ const ( // every start, whether the binary was embedded or supplied by NMON_VM_BINARY. binSHA256Amd64 = "f7dcb151fd1fef69364d6d6da49c0d3f1b9c2415ef4b4432b08e416a5c73a49b" binSHA256Arm64 = "bba4c4f46cda51beff65b55c41e59b99e310387c72fd96ee83134d2fa20848e5" - - // The .gz that is embedded (internal/gzbin). Checked by the vmembed tests and - // by fetch-vm.sh; the runtime trusts only the uncompressed hash. - gzSHA256Amd64 = "2a5e0c1a7fe9825b3ab0a1f2652471608736736670eb6d8953273f4743f909d1" - gzSHA256Arm64 = "d7d763d9f81fc3ab7fb3da5a71ce36e8b3e3083d331f7733d1eec9998da23d78" ) // binPin returns the pinned uncompressed hash for a GOARCH, or "". diff --git a/internal/vmsup/query.go b/internal/vmsup/query.go index e9e10e8..c21dff2 100644 --- a/internal/vmsup/query.go +++ b/internal/vmsup/query.go @@ -66,7 +66,7 @@ func (c *Querier) do(ctx context.Context, store, path string, form url.Values) ( if err != nil { return nil, fmt.Errorf("vmsup: query %s store: %w", store, err) } - defer resp.Body.Close() + defer func() { _ = resp.Body.Close() }() body, err := io.ReadAll(io.LimitReader(resp.Body, maxQueryResponse+1)) if err != nil { return nil, fmt.Errorf("vmsup: read %s store response: %w", store, err) diff --git a/internal/vmsup/queue.go b/internal/vmsup/queue.go index 9847451..711ec9e 100644 --- a/internal/vmsup/queue.go +++ b/internal/vmsup/queue.go @@ -229,7 +229,7 @@ func (q *Queue) post(ctx context.Context, batch []*chunk) (retry bool, err error if err != nil { return true, fmt.Errorf("vmsup: write to %s store: %w", q.name, err) } - defer resp.Body.Close() + defer func() { _ = resp.Body.Close() }() msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) switch { case resp.StatusCode/100 == 2: diff --git a/internal/vmsup/queue_test.go b/internal/vmsup/queue_test.go index 2b8ae40..62c9e4d 100644 --- a/internal/vmsup/queue_test.go +++ b/internal/vmsup/queue_test.go @@ -281,10 +281,10 @@ func TestQuerier(t *testing.T) { gotForm.Store(r.URL.Path + "?" + r.PostForm.Encode()) if r.PostForm.Get("query") == "bad(" { w.WriteHeader(http.StatusUnprocessableEntity) - w.Write([]byte("parse error")) + _, _ = w.Write([]byte("parse error")) return } - w.Write([]byte(`{"status":"success"}`)) + _, _ = w.Write([]byte(`{"status":"success"}`)) })) defer srv.Close() tg := &fakeTarget{url: srv.URL} diff --git a/internal/vmsup/restart.go b/internal/vmsup/restart.go new file mode 100644 index 0000000..8196bd6 --- /dev/null +++ b/internal/vmsup/restart.go @@ -0,0 +1,138 @@ +package vmsup + +import ( + "context" + "runtime" + "time" +) + +// Supervision policy. +const ( + healthEvery = 5 * time.Second // steady-state /health interval + startupProbe = 250 * time.Millisecond // /health interval until first healthy + startTimeout = 30 * time.Second // Start and each (re)spawn must be healthy by then + stopTimeout = 30 * time.Second // SIGTERM to SIGKILL + backoffBase = time.Second // 1 s, 2 s, 4 s, capped at backoffMax + backoffMax = 8 * time.Second + restartWindow = 10 * time.Minute + maxRestarts = 3 // restarts within restartWindow before store_failed + probeFailures = 3 // consecutive failed probes of a live process before it is killed +) + +// supervise is the per-store loop: start, watch, restart with backoff, give up +// after maxRestarts in restartWindow, resume on Restart. +func (s *Supervisor) supervise(ctx context.Context, st *store) { + defer close(st.done) + // Pdeathsig is tied to the thread that forked the child. Keeping this + // goroutine on one thread for its whole life stops the runtime from + // retiring that thread (and so killing the child) under us. + runtime.LockOSThread() + + cs := cycleState{first: true} + for s.cycle(ctx, st, &cs) { + } +} + +// cycleState carries what one supervise iteration tells the next. +type cycleState struct { + first bool // no child has been started yet + manual bool // the previous give-up was ended by Restart +} + +// cycle runs one spawn/watch/backoff round. It reports whether to go on. +func (s *Supervisor) cycle(ctx context.Context, st *store, cs *cycleState) bool { + var reason string + p, fatal, err := s.spawn(st) + if err != nil { + cs.first = false + reason = err.Error() + if fatal { + return s.giveUpAndMark(ctx, st, cs, reason) + } + } else { + var alive bool + reason, alive = s.runChild(ctx, st, p, cs) + if !alive { + return false // ctx done; child already terminated + } + } + st.setDown(reason) + s.log.Warn("store down", "store", st.name, "reason", reason) + return s.scheduleRestart(ctx, st, cs, reason) +} + +// runChild announces a restart (not the first start) and watches the child. +func (s *Supervisor) runChild(ctx context.Context, st *store, p *proc, cs *cycleState) (reason string, alive bool) { + if !cs.first { + detail := "restarted after: " + st.lastExitText() + if cs.manual { + detail = "restarted manually" + } + st.mu.Lock() + st.recoverNext = true + st.mu.Unlock() + s.emit(st, EventStoreRestarted, detail) + } + cs.first, cs.manual = false, false + return s.watch(ctx, st, p) +} + +// giveUpAndMark raises store_failed, waits for Restart, and remembers that the +// next start is manual. It reports whether supervision should continue. +func (s *Supervisor) giveUpAndMark(ctx context.Context, st *store, cs *cycleState, reason string) bool { + if !s.giveUp(ctx, st, reason) { + return false + } + cs.manual = true + return true +} + +// scheduleRestart records the restart and sleeps the backoff, or gives up when +// the store has burned its restart budget. It reports whether to go on. +func (s *Supervisor) scheduleRestart(ctx context.Context, st *store, cs *cycleState, reason string) bool { + now := s.clk.Now() + st.mu.Lock() + st.history = pruneBefore(st.history, now.Add(-restartWindow)) + n := len(st.history) + st.mu.Unlock() + if n >= maxRestarts { + return s.giveUpAndMark(ctx, st, cs, reason) + } + delay := s.opts.backoff << n + if m := s.opts.backoff * (backoffMax / backoffBase); delay > m { + delay = m + } + st.mu.Lock() + st.history = append(st.history, now) + st.restarts++ + st.mu.Unlock() + return s.clk.Sleep(ctx, delay) == nil +} + +// giveUp raises store_failed and blocks until Restart or shutdown. It reports +// whether supervision should continue. +func (s *Supervisor) giveUp(ctx context.Context, st *store, reason string) bool { + st.mu.Lock() + st.failed = true + st.mu.Unlock() + s.emit(st, EventStoreFailed, reason) + select { + case <-st.resume: + st.mu.Lock() + st.history = nil + st.mu.Unlock() + return true + case <-ctx.Done(): + return false + } +} + +func pruneBefore(ts []time.Time, cutoff time.Time) []time.Time { + out := ts[:0] + for _, t := range ts { + if t.After(cutoff) { + out = append(out, t) + } + } + return out +} diff --git a/internal/vmsup/store.go b/internal/vmsup/store.go new file mode 100644 index 0000000..1cb471a --- /dev/null +++ b/internal/vmsup/store.go @@ -0,0 +1,87 @@ +package vmsup + +import ( + "fmt" + "net" + "strconv" + "sync" + "time" +) + +type store struct { + name string + dir string + retention time.Duration + external bool + extra []string + + mu sync.Mutex + url string + port int + healthy bool + failed bool + pid int + restarts int + startedAt time.Time + lastExit string + history []time.Time // restart times inside the window + recoverNext bool // emit store_recovered at the next healthy probe + + resume chan struct{} + done chan struct{} +} + +func (st *store) isHealthy() bool { st.mu.Lock(); defer st.mu.Unlock(); return st.healthy } +func (st *store) isFailed() bool { st.mu.Lock(); defer st.mu.Unlock(); return st.failed } +func (st *store) currentURL() string { + st.mu.Lock() + defer st.mu.Unlock() + return st.url +} +func (st *store) lastExitText() string { st.mu.Lock(); defer st.mu.Unlock(); return st.lastExit } +func (st *store) setHealthy(ok bool) { st.mu.Lock(); st.healthy = ok; st.mu.Unlock() } + +func (st *store) setDown(reason string) { + st.mu.Lock() + st.healthy = false + st.pid = 0 + if reason != "" { + st.lastExit = reason + } + st.mu.Unlock() +} + +// pickPort keeps the previous port while it is still free, otherwise picks a +// free loopback port. Only 127.0.0.1 is ever used. +func (st *store) pickPort() (int, error) { + st.mu.Lock() + defer st.mu.Unlock() + if st.port != 0 { + if l, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(st.port)); err == nil { + _ = l.Close() + return st.port, nil + } + } + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return 0, fmt.Errorf("pick loopback port: %w", err) + } + st.port = l.Addr().(*net.TCPAddr).Port + _ = l.Close() + st.url = "http://127.0.0.1:" + strconv.Itoa(st.port) + return st.port, nil +} + +// RetentionArg formats d in VictoriaMetrics -retentionPeriod syntax: whole +// years ("2y", 365 days each) or days ("30d"), never below the 1 d minimum. +func RetentionArg(d time.Duration) string { + const day = 24 * time.Hour + days := int64((d + day - 1) / day) + if days < 1 { + days = 1 + } + if days%365 == 0 { + return strconv.FormatInt(days/365, 10) + "y" + } + return strconv.FormatInt(days, 10) + "d" +} diff --git a/internal/vmsup/supervisor.go b/internal/vmsup/supervisor.go index 1364218..37b74a3 100644 --- a/internal/vmsup/supervisor.go +++ b/internal/vmsup/supervisor.go @@ -1,23 +1,15 @@ package vmsup import ( - "bytes" "context" "errors" "fmt" - "io" "log/slog" - "net" "net/http" "net/url" "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" "strings" "sync" - "syscall" "time" "github.com/v10networks/nmon/internal/clock" @@ -30,36 +22,6 @@ const ( StoreLong = "long" ) -// Event types passed to Options.OnEvent. -const ( - EventStoreFailed = "store_failed" - EventStoreRestarted = "store_restarted" - EventStoreRecovered = "store_recovered" -) - -// Supervision policy. -const ( - healthEvery = 5 * time.Second // steady-state /health interval - startupProbe = 250 * time.Millisecond // /health interval until first healthy - startTimeout = 30 * time.Second // Start and each (re)spawn must be healthy by then - stopTimeout = 30 * time.Second // SIGTERM to SIGKILL - backoffBase = time.Second // 1 s, 2 s, 4 s, capped at backoffMax - backoffMax = 8 * time.Second - restartWindow = 10 * time.Minute - maxRestarts = 3 // restarts within restartWindow before store_failed - probeFailures = 3 // consecutive failed probes of a live process before it is killed -) - -// Event describes a state change of one store. -type Event struct { - Type string // EventStore* - Store string // StoreHot or StoreLong - Time time.Time - Detail string - // Restarts is the number of restarts in the current ten-minute window. - Restarts int -} - // Options configures a Supervisor. type Options struct { DataDir string @@ -113,55 +75,38 @@ type Supervisor struct { spec binarySpec } -type store struct { - name string - dir string - retention time.Duration - external bool - extra []string - - mu sync.Mutex - url string - port int - healthy bool - failed bool - pid int - restarts int - startedAt time.Time - lastExit string - history []time.Time // restart times inside the window - recoverNext bool // emit store_recovered at the next healthy probe - - resume chan struct{} - done chan struct{} +// withDefaults fills the zero-valued options. +func (o Options) withDefaults() Options { + if o.Clock == nil { + o.Clock = clock.Real() + } + if o.Logger == nil { + o.Logger = slog.Default() + } + if o.backoff <= 0 { + o.backoff = backoffBase + } + if o.healthEvery <= 0 { + o.healthEvery = healthEvery + } + if o.startTimeout <= 0 { + o.startTimeout = startTimeout + } + if o.stopTimeout <= 0 { + o.stopTimeout = stopTimeout + } + if o.HotRetention <= 0 { + o.HotRetention = 30 * 24 * time.Hour + } + if o.LongRetention <= 0 { + o.LongRetention = 2 * 365 * 24 * time.Hour + } + return o } // New validates opts and returns a Supervisor. Nothing runs until Start. func New(opts Options) (*Supervisor, error) { - if opts.Clock == nil { - opts.Clock = clock.Real() - } - if opts.Logger == nil { - opts.Logger = slog.Default() - } - if opts.backoff <= 0 { - opts.backoff = backoffBase - } - if opts.healthEvery <= 0 { - opts.healthEvery = healthEvery - } - if opts.startTimeout <= 0 { - opts.startTimeout = startTimeout - } - if opts.stopTimeout <= 0 { - opts.stopTimeout = stopTimeout - } - if opts.HotRetention <= 0 { - opts.HotRetention = 30 * 24 * time.Hour - } - if opts.LongRetention <= 0 { - opts.LongRetention = 2 * 365 * 24 * time.Hour - } + opts = opts.withDefaults() s := &Supervisor{ opts: opts, log: opts.Logger.With("component", "vmsup"), @@ -180,21 +125,32 @@ func New(opts Options) (*Supervisor, error) { name: d.name, dir: d.dir, retention: d.ret, extra: opts.ExtraArgs[d.name], resume: make(chan struct{}, 1), done: make(chan struct{}), } - if d.ext != "" { - u, err := url.Parse(d.ext) - if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { - return nil, fmt.Errorf("vmsup: %s store URL %q is not an http(s) URL", d.name, d.ext) - } - st.external = true - st.url = strings.TrimRight(d.ext, "/") - } else if opts.DataDir == "" { - return nil, errors.New("vmsup: DataDir is required when a store is not external") + if err := st.configureExternal(d.ext, opts.DataDir); err != nil { + return nil, err } s.stores = append(s.stores, st) } return s, nil } +// configureExternal marks the store external when ext names an instance; a +// managed store needs a data directory instead. +func (st *store) configureExternal(ext, dataDir string) error { + if ext == "" { + if dataDir == "" { + return errors.New("vmsup: DataDir is required when a store is not external") + } + return nil + } + u, err := url.Parse(ext) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return fmt.Errorf("vmsup: %s store URL %q is not an http(s) URL", st.name, ext) + } + st.external = true + st.url = strings.TrimRight(ext, "/") + return nil +} + func (s *Supervisor) store(name string) *store { for _, st := range s.stores { if st.name == name { @@ -216,26 +172,9 @@ func (s *Supervisor) Start(ctx context.Context) error { s.started = true s.mu.Unlock() - managed := false - for _, st := range s.stores { - managed = managed || !st.external - } - if managed { - spec, err := prepareBinary(s.opts.DataDir) - if err != nil { - s.fail() - return err - } - s.spec = spec - for _, st := range s.stores { - if st.external { - continue - } - if err := os.MkdirAll(st.dir, 0o755); err != nil { - s.fail() - return fmt.Errorf("vmsup: create %s: %w", st.dir, err) - } - } + if err := s.prepareManaged(); err != nil { + s.fail() + return err } runCtx, cancel := context.WithCancel(context.Background()) @@ -250,21 +189,52 @@ func (s *Supervisor) Start(ctx context.Context) error { } } + if err := s.waitHealthy(ctx); err != nil { + _ = s.Stop(context.Background()) + return err + } + return nil +} + +// prepareManaged verifies the store binary and creates the data directories of +// the stores nmon runs itself. It does nothing when every store is external. +func (s *Supervisor) prepareManaged() error { + managed := false + for _, st := range s.stores { + managed = managed || !st.external + } + if !managed { + return nil + } + spec, err := prepareBinary(s.opts.DataDir) + if err != nil { + return err + } + s.spec = spec + for _, st := range s.stores { + if st.external { + continue + } + if err := os.MkdirAll(st.dir, 0o755); err != nil { + return fmt.Errorf("vmsup: create %s: %w", st.dir, err) + } + } + return nil +} + +// waitHealthy blocks until both stores answer /health, one fails, the start +// timeout passes, or ctx ends. +func (s *Supervisor) waitHealthy(ctx context.Context) error { deadline := s.clk.After(s.opts.startTimeout) for _, st := range s.stores { for !st.isHealthy() { if st.isFailed() { - err := fmt.Errorf("vmsup: %s store failed to start: %s", st.name, st.lastExitText()) - _ = s.Stop(context.Background()) - return err + return fmt.Errorf("vmsup: %s store failed to start: %s", st.name, st.lastExitText()) } select { case <-deadline: - err := fmt.Errorf("vmsup: %s store not healthy after %s", st.name, s.opts.startTimeout) - _ = s.Stop(context.Background()) - return err + return fmt.Errorf("vmsup: %s store not healthy after %s", st.name, s.opts.startTimeout) case <-ctx.Done(): - _ = s.Stop(context.Background()) return ctx.Err() case <-s.clk.After(50 * time.Millisecond): } @@ -387,378 +357,3 @@ func (s *Supervisor) register(q *Queue) { s.queues = append(s.queues, q) s.mu.Unlock() } - -func (s *Supervisor) emit(st *store, typ, detail string) { - st.mu.Lock() - n := len(st.history) - st.mu.Unlock() - ev := Event{Type: typ, Store: st.name, Time: s.clk.Now(), Detail: detail, Restarts: n} - s.log.Warn("store event", "type", typ, "store", st.name, "detail", detail, "restarts_in_window", n) - if s.opts.OnEvent != nil { - s.opts.OnEvent(ev) - } -} - -// watchExternal only probes /health of an operator-run store. -func (s *Supervisor) watchExternal(ctx context.Context, st *store) { - for { - ok := s.probe(ctx, st.currentURL()) - st.setHealthy(ok) - d := s.opts.healthEvery - if !ok { - d = startupProbe - if d > s.opts.healthEvery { - d = s.opts.healthEvery - } - } - select { - case <-ctx.Done(): - return - case <-s.clk.After(d): - } - } -} - -// proc is one running child. -type proc struct { - cmd *exec.Cmd - exited chan struct{} - err error // valid after exited is closed -} - -// supervise is the per-store loop: start, watch, restart with backoff, give up -// after maxRestarts in restartWindow, resume on Restart. -func (s *Supervisor) supervise(ctx context.Context, st *store) { - defer close(st.done) - // Pdeathsig is tied to the thread that forked the child. Keeping this - // goroutine on one thread for its whole life stops the runtime from - // retiring that thread (and so killing the child) under us. - runtime.LockOSThread() - - first := true - manual := false - for { - var reason string - p, fatal, err := s.spawn(st) - if err != nil { - first = false - reason = err.Error() - if fatal { - if !s.giveUp(ctx, st, reason) { - return - } - manual = true - continue - } - } else { - if !first { - detail := "restarted after: " + st.lastExitText() - if manual { - detail = "restarted manually" - } - st.mu.Lock() - st.recoverNext = true - st.mu.Unlock() - s.emit(st, EventStoreRestarted, detail) - } - first, manual = false, false - var alive bool - reason, alive = s.watch(ctx, st, p) - if !alive { - return // ctx done; child already terminated - } - } - st.setDown(reason) - s.log.Warn("store down", "store", st.name, "reason", reason) - - now := s.clk.Now() - st.mu.Lock() - st.history = pruneBefore(st.history, now.Add(-restartWindow)) - n := len(st.history) - st.mu.Unlock() - if n >= maxRestarts { - if !s.giveUp(ctx, st, reason) { - return - } - manual = true - continue - } - delay := s.opts.backoff << n - if m := s.opts.backoff * (backoffMax / backoffBase); delay > m { - delay = m - } - st.mu.Lock() - st.history = append(st.history, now) - st.restarts++ - st.mu.Unlock() - if err := s.clk.Sleep(ctx, delay); err != nil { - return - } - } -} - -// giveUp raises store_failed and blocks until Restart or shutdown. It reports -// whether supervision should continue. -func (s *Supervisor) giveUp(ctx context.Context, st *store, reason string) bool { - st.mu.Lock() - st.failed = true - st.mu.Unlock() - s.emit(st, EventStoreFailed, reason) - select { - case <-st.resume: - st.mu.Lock() - st.history = nil - st.mu.Unlock() - return true - case <-ctx.Done(): - return false - } -} - -func pruneBefore(ts []time.Time, cutoff time.Time) []time.Time { - out := ts[:0] - for _, t := range ts { - if t.After(cutoff) { - out = append(out, t) - } - } - return out -} - -// spawn verifies the binary and starts one child. fatal means retrying cannot help. -func (s *Supervisor) spawn(st *store) (p *proc, fatal bool, err error) { - if err := s.spec.verify(); err != nil { - return nil, true, err - } - port, err := st.pickPort() - if err != nil { - return nil, false, err - } - path, err := filepath.Abs(s.spec.path) - if err != nil { - return nil, true, err - } - args := []string{ - "-storageDataPath=" + st.dir, - "-retentionPeriod=" + RetentionArg(st.retention), - "-httpListenAddr=127.0.0.1:" + strconv.Itoa(port), - "-loggerLevel=WARN", - "-memory.allowedPercent=30", // two stores share the box - "-search.maxUniqueTimeseries=1000000", - "-search.latencyOffset=0s", // default 30 s hides the newest samples from "now" queries - } - args = append(args, st.extra...) - - lw := &lineLogger{log: s.log, store: st.name} - cmd := exec.Command(path, args...) - cmd.Env = []string{} // nothing from nmon's environment (secrets) reaches the store - cmd.SysProcAttr = sysProcAttr() - cmd.Stdout, cmd.Stderr = lw, lw - cmd.WaitDelay = 2 * time.Second - if err := cmd.Start(); err != nil { - return nil, false, fmt.Errorf("start %s: %w", path, err) - } - p = &proc{cmd: cmd, exited: make(chan struct{})} - go func() { - p.err = cmd.Wait() - lw.flush() - close(p.exited) - }() - st.mu.Lock() - st.pid = cmd.Process.Pid - st.startedAt = s.clk.Now() - st.mu.Unlock() - s.log.Info("store started", "store", st.name, "pid", cmd.Process.Pid, "addr", st.currentURL()) - return p, false, nil -} - -// watch probes a running child until it exits, stops answering, or ctx ends. -// alive is false when ctx ended (the child has then been terminated). -func (s *Supervisor) watch(ctx context.Context, st *store, p *proc) (reason string, alive bool) { - started := s.clk.Now() - everHealthy := false - fails := 0 - for { - d := s.opts.healthEvery - if !everHealthy && startupProbe < d { - d = startupProbe - } - select { - case <-ctx.Done(): - s.terminate(p) - return "", false - case <-p.exited: - return describeExit(p.err), true - case <-s.clk.After(d): - } - if s.probe(ctx, st.currentURL()) { - everHealthy, fails = true, 0 - st.setHealthy(true) - st.mu.Lock() - rec := st.recoverNext - st.recoverNext = false - st.mu.Unlock() - if rec { - s.emit(st, EventStoreRecovered, "answering /health") - } - continue - } - st.setHealthy(false) - if everHealthy { - fails++ - if fails >= probeFailures { - s.kill(p) // it is not answering, so it will not honour SIGTERM either - return fmt.Sprintf("killed after %d failed health checks", fails), true - } - } else if s.clk.Now().Sub(started) >= s.opts.startTimeout { - s.kill(p) - return fmt.Sprintf("not healthy %s after start", s.opts.startTimeout), true - } - } -} - -// terminate sends SIGTERM and waits; after stopTimeout, or once Stop's context -// has ended, it kills the process group. -func (s *Supervisor) terminate(p *proc) { - select { - case <-p.exited: - return - default: - } - _ = p.cmd.Process.Signal(syscall.SIGTERM) - select { - case <-p.exited: - return - case <-s.clk.After(s.opts.stopTimeout): - case <-s.killNow: - } - killGroup(p.cmd.Process.Pid) - <-p.exited -} - -// kill ends an unresponsive child at once. -func (s *Supervisor) kill(p *proc) { - killGroup(p.cmd.Process.Pid) - <-p.exited -} - -func describeExit(err error) string { - if err == nil { - return "exited with status 0" - } - return "exited: " + err.Error() -} - -func (s *Supervisor) probe(ctx context.Context, base string) bool { - if base == "" { - return false - } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/health", nil) - if err != nil { - return false - } - resp, err := s.hc.Do(req) - if err != nil { - return false - } - _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<10)) - _ = resp.Body.Close() - return resp.StatusCode == http.StatusOK -} - -func (st *store) isHealthy() bool { st.mu.Lock(); defer st.mu.Unlock(); return st.healthy } -func (st *store) isFailed() bool { st.mu.Lock(); defer st.mu.Unlock(); return st.failed } -func (st *store) currentURL() string { - st.mu.Lock() - defer st.mu.Unlock() - return st.url -} -func (st *store) lastExitText() string { st.mu.Lock(); defer st.mu.Unlock(); return st.lastExit } -func (st *store) setHealthy(ok bool) { st.mu.Lock(); st.healthy = ok; st.mu.Unlock() } - -func (st *store) setDown(reason string) { - st.mu.Lock() - st.healthy = false - st.pid = 0 - if reason != "" { - st.lastExit = reason - } - st.mu.Unlock() -} - -// pickPort keeps the previous port while it is still free, otherwise picks a -// free loopback port. Only 127.0.0.1 is ever used. -func (st *store) pickPort() (int, error) { - st.mu.Lock() - defer st.mu.Unlock() - if st.port != 0 { - if l, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(st.port)); err == nil { - _ = l.Close() - return st.port, nil - } - } - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return 0, fmt.Errorf("pick loopback port: %w", err) - } - st.port = l.Addr().(*net.TCPAddr).Port - _ = l.Close() - st.url = "http://127.0.0.1:" + strconv.Itoa(st.port) - return st.port, nil -} - -// RetentionArg formats d in VictoriaMetrics -retentionPeriod syntax: whole -// years ("2y", 365 days each) or days ("30d"), never below the 1 d minimum. -func RetentionArg(d time.Duration) string { - const day = 24 * time.Hour - days := int64((d + day - 1) / day) - if days < 1 { - days = 1 - } - if days%365 == 0 { - return strconv.FormatInt(days/365, 10) + "y" - } - return strconv.FormatInt(days, 10) + "d" -} - -// lineLogger turns child output into log lines. -type lineLogger struct { - log *slog.Logger - store string - mu sync.Mutex - buf []byte -} - -func (l *lineLogger) Write(p []byte) (int, error) { - l.mu.Lock() - defer l.mu.Unlock() - l.buf = append(l.buf, p...) - for { - i := bytes.IndexByte(l.buf, '\n') - if i < 0 { - break - } - l.emit(string(l.buf[:i])) - l.buf = l.buf[i+1:] - } - if len(l.buf) > 64<<10 { // a line with no end: don't grow without bound - l.emit(string(l.buf)) - l.buf = nil - } - return len(p), nil -} - -func (l *lineLogger) flush() { - l.mu.Lock() - defer l.mu.Unlock() - if len(l.buf) > 0 { - l.emit(string(l.buf)) - l.buf = nil - } -} - -func (l *lineLogger) emit(line string) { - if line = strings.TrimRight(line, "\r"); line != "" { - l.log.Warn("store output", "store", l.store, "line", line) - } -} diff --git a/internal/vmsup/supervisor_test.go b/internal/vmsup/supervisor_test.go index 97f8f83..0a91a06 100644 --- a/internal/vmsup/supervisor_test.go +++ b/internal/vmsup/supervisor_test.go @@ -258,8 +258,8 @@ func TestBinaryTamperedBetweenStarts(t *testing.T) { if err != nil { t.Fatal(err) } - f.WriteString("tampered") - f.Close() + _, _ = f.WriteString("tampered") + _ = f.Close() _ = syscall.Kill(hot, syscall.SIGKILL) eventually(t, 5*time.Second, "store_failed on checksum", func() bool { return ev.count(EventStoreFailed, StoreHot) == 1 }) ev.mu.Lock() @@ -291,7 +291,7 @@ func TestExternalStores(t *testing.T) { mkSrv := func() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/health" { - w.Write([]byte("OK")) + _, _ = w.Write([]byte("OK")) return } buf := make([]byte, 4096) diff --git a/profiles/apc-ups.yaml b/profiles/apc-ups.yaml index d7cac53..476f88d 100644 --- a/profiles/apc-ups.yaml +++ b/profiles/apc-ups.yaml @@ -8,6 +8,9 @@ priority: 10 provenance: UPS-MIB (RFC 1628), PowerNet-MIB upsAdv/upsBasic (APC, enterprise 318) match: sysObjectID: 1.3.6.1.4.1.318 +# upsInputVoltage / upsOutputVoltage / upsOutputPercentLoad: UPS-MIB (RFC 1628) makes the +# line-index columns not-accessible, so real devices never return them. Rows are +# labelled by the metric's own column (the row index), as printer does. metrics: - name: upsBatteryStatus oid: 1.3.6.1.2.1.33.1.2.1.0 @@ -17,9 +20,9 @@ metrics: enum: { 1: unknown, 2: batteryNormal, 3: batteryLow, 4: batteryDepleted } - { name: upsEstimatedMinutesRemaining, oid: 1.3.6.1.2.1.33.1.2.3.0, type: gauge, unit: minutes, interval: 5m } - { name: upsEstimatedChargeRemaining, oid: 1.3.6.1.2.1.33.1.2.4.0, type: gauge, unit: percent, interval: 5m } - - { name: upsInputVoltage, oid: 1.3.6.1.2.1.33.1.3.3.1.3, type: gauge, unit: volts, interval: 5m, index_label: { column: upsInputLineIndex, as: component } } - - { name: upsOutputVoltage, oid: 1.3.6.1.2.1.33.1.4.4.1.2, type: gauge, unit: volts, interval: 5m, index_label: { column: upsOutputLineIndex, as: component } } - - { name: upsOutputPercentLoad, oid: 1.3.6.1.2.1.33.1.4.4.1.5, type: gauge, unit: percent, interval: 5m, index_label: { column: upsOutputLineIndex, as: component } } + - { name: upsInputVoltage, oid: 1.3.6.1.2.1.33.1.3.3.1.3, type: gauge, unit: volts, interval: 5m, index_label: { column: upsInputVoltage, as: component } } + - { name: upsOutputVoltage, oid: 1.3.6.1.2.1.33.1.4.4.1.2, type: gauge, unit: volts, interval: 5m, index_label: { column: upsOutputVoltage, as: component } } + - { name: upsOutputPercentLoad, oid: 1.3.6.1.2.1.33.1.4.4.1.5, type: gauge, unit: percent, interval: 5m, index_label: { column: upsOutputPercentLoad, as: component } } - name: upsOutputSource oid: 1.3.6.1.2.1.33.1.4.1.0 type: status