Merge v1.4: port graph ranges and p95, per-device poll interval (300 s default)
Some checks failed
ci / lint (push) Successful in 4m8s
ci / postgres (push) Has been cancelled
ci / openapi (push) Has been cancelled
ci / test (push) Has been cancelled

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017TuKgyKve2XLFtrrXWMi2w
This commit is contained in:
Vibe Coder
2026-10-24 18:56:16 +00:00
50 changed files with 467 additions and 159 deletions

View File

@@ -3,7 +3,7 @@ on: [push, pull_request]
jobs:
lint:
# Hard rule (docs/MAINTAINABILITY.md): any finding fails the build.
runs-on: ubuntu-latest
runs-on: debian-13
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
@@ -13,10 +13,7 @@ jobs:
- run: cd web && npm ci
- run: make lint
test:
strategy:
matrix:
arch: [ubuntu-latest, ubuntu-24.04-arm]
runs-on: ${{ matrix.arch }}
runs-on: debian-13
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
@@ -30,14 +27,14 @@ jobs:
- run: make test-v6only
- run: make build && file nmon | grep -q 'statically linked'
postgres:
runs-on: ubuntu-latest
runs-on: debian-13
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with: { go-version: stable }
- run: make test-pg
openapi:
runs-on: ubuntu-latest
runs-on: debian-13
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }

View File

@@ -77,7 +77,7 @@ func serve(ctx context.Context, args []string) error {
fs.StringVar(&f.ICMP, "icmp", config.ICMPAuto,
"ICMP probing: auto, or off for hosts where ICMP is not permitted (SNMP alone then decides if a device is down)")
fs.IntVar(&f.MaxInflight, "max-inflight", 512, "most SNMP polls in flight at once")
fs.DurationVar(&f.PollInterval, "poll-interval", 0, "dev: SNMP poll interval (default 60s)")
fs.DurationVar(&f.PollInterval, "poll-interval", 0, "dev: default SNMP poll interval (default 300s); a device's own interval overrides it")
fs.IntVar(&f.SNMPPort, "snmp-port", 0, "dev: UDP port of every device's agent (default 161)")
if err := fs.Parse(args); err != nil {
return flagErr(err)

View File

@@ -53,3 +53,4 @@ conscious, reviewed exception.
| 46 | `bgp_peer_down` summary names the peer, AS and description | The rule's own summary names the device and the peer. The AS, router id and description are appended to the **notification** (Summary, Description and labels) when it is delivered, from the component attributes; the stored alert row keeps the plain summary. | The metric label contract allows only `device` and `component`, and the rule templates see only those; extending the evaluator's template data belongs to the v1.2 rules plumbing. | v1.3 |
| 47 | (not specified) vendor of a MAC | An optional IEEE OUI registry (MA-L, MA-M, MA-S) shows the vendor of each MAC and flags locally administered (`local`, shown "Private / randomised") and multicast addresses. It is fetched weekly through the outbound allow-list (`oui.fetch: false` turns it off; `nmon oui import DIR` loads the CSVs offline), kept as `<data-dir>/oui/registry.gz` (checksummed, written atomically, in `nmon backup`), and looked up at query time by the longest prefix, so a refresh relabels history. Without a registry the vendor is empty, nothing fails, and `/poller/health` carries an `oui_unavailable` note (never an alert). The CSVs are public IEEE data and are not in the repository. | Owner request 2026-10-24: nice to have, never required. | v1.3 |
| 48 | Lookup ranks edge ports "the port with the fewest MACs, then the most recent last_seen" | Within a MAC's locations the order is: edge ports before uplinks, then rows the device's last walk still saw before history, then fewest MACs, then most recent. A port is an uplink above `l2.edge_max_macs` MACs (8), with an LLDP neighbour (the lldpRemTable local port number is taken to be the ifIndex), or as a LAG (ifType 161). A port's MAC count is the MACs on it at or after the row's `last_seen`, so for a current row it is the port's MACs in the last walk. | A host that moved should show its new port first even when the old, now empty, port had fewer MACs. | v1.3 |
| 49 | SNMP interface counters are polled every 60 s; rate windows, rollup gap detection and reachability timers assume it | The default SNMP poll interval is **300 s** (LibreNMS-like; `store.DefaultPollInterval`), and an admin can set a different one per device (`poll_interval_s`, 0 or 30..3600, migration 15; empty = the default). The profile's 1m metrics follow it (halved on a device with unreliable 32-bit counters); 5 m and 15 m groups are unchanged and merge with a 300 s primary. Everything that was tied to the cadence follows the device's effective interval: graph, overview and p95 rate windows are two polls wide (at least 2 min; live rates use two default polls), the rollup's lookback and "thin window" test (a cadence of 5 min or slower predicts at most one sample per window, so a window is never thin, and a window with no sample is skipped as before), the `no_data` warning (silent for max(5 min, two polls)), the "unheard of for three polls is down" fallback, the up-series lookback (11 min), the dependency hold, and the `interface_errors` rule (10 min window). ICMP stays at 15 s. `nmon serve --poll-interval` still overrides the default for dev and tests. | Owner request 2026-10-24: 60 s polling of every port is more load than ISP-size fleets need; a per-device override keeps 1 min where it is wanted. Cost: a rollup window of a device polled slower than 5 min often holds no sample and is left empty, and graphs at the default have one point per 5 min. | post-v1.3 |

View File

@@ -116,7 +116,7 @@ oui:
refresh: 7d
```
All of these apply from the next cycle after a reload (Settings save or SIGHUP) with no restart. The job never runs on the 60 s poll path and yields to the poller the way the rollup job does. A device that does not answer in time is skipped for that cycle and named on the Poller page (`l2` status and an `l2_devices_skipped` note); it never delays the other devices. A Cisco IOS switch keeps one bridge table per VLAN: the `cisco-ios` profile sets `l2.per_vlan_context: true`, which lists the VLANs from CISCO-VTP-MIB and walks each with community `<community>@<vlan>` (v3: context `vlan-<vlan>`). Other devices use Q-BRIDGE-MIB, then BRIDGE-MIB (VLAN unknown).
All of these apply from the next cycle after a reload (Settings save or SIGHUP) with no restart. The job never runs on the poll path and yields to the poller the way the rollup job does. A device that does not answer in time is skipped for that cycle and named on the Poller page (`l2` status and an `l2_devices_skipped` note); it never delays the other devices. A Cisco IOS switch keeps one bridge table per VLAN: the `cisco-ios` profile sets `l2.per_vlan_context: true`, which lists the VLANs from CISCO-VTP-MIB and walks each with community `<community>@<vlan>` (v3: context `vlan-<vlan>`). Other devices use Q-BRIDGE-MIB, then BRIDGE-MIB (VLAN unknown).
API: `GET /api/v1/l2/search?q=`, `GET /api/v1/devices/{slug}/{l2,fdb,arp,l2/ports}`, `GET /api/v1/interfaces/{id}/macs`. On a device, the **L2** tab (MAC table with a VLAN filter, ARP / ND, VLAN list) appears once the job has read it, and the Ports tab shows each port's MAC count linking to that port's MACs.
@@ -131,3 +131,7 @@ The registry is the IEEE's public data: MA-L (`https://standards-oui.ieee.org/ou
Router profiles collect BGP session state, uptime, accepted prefixes per address family and update rates every 5 minutes (see `docs/coverage.md` for which profiles and MIBs). The **BGP** page lists every session on every device, the ones that are down first, filterable by state, AS, family and text; a device's **Routing** tab shows its sessions with click-to-graph on prefixes and updates.
The built-in rule `bgp_peer_down` (critical, state not established for 2 minutes) fires only where a policy binds it, like every rule: use the template "Routers: BGP peer down" under Alerts > Alert policies. Its notification names the peer and, from discovery, the peer's AS and description. A prefix-drop alert is a custom rule (v1.2); an example will be added here once custom rules are in.
## Poll interval
SNMP interface counters are polled every 300 s by default. An admin can set a different interval for one device (Device settings, "Poll interval", 30 to 3600 s; blank returns it to the default) or through `PUT /api/v1/devices/{slug}` with `poll_interval_s`. The poller picks it up at once, no restart. Graph rate windows, reachability fallbacks and the rollup follow the device's own interval (see `docs/DEVIATIONS.md` row 49). ICMP is still probed every 15 s. `nmon serve --poll-interval` changes the default for dev and tests only.

View File

@@ -422,11 +422,11 @@ func hostRules(lab func(...string) []string) []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)`,
Expr: `100 * (rate(ifInErrors[10m]) + rate(ifOutErrors[10m])) / clamp_min(` +
`(rate(ifHCInUcastPkts[10m]) + rate(ifHCOutUcastPkts[10m])) or ` +
`((rate(ifHCInOctets[10m]) + rate(ifHCOutOctets[10m])) / 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}} ` +
Description: `Errors are {{printf "%.2f" .Value}}% of packets over 10 minutes on {{.Iface}} of {{.Device}} ` +
`(threshold {{printf "%.2f" .Threshold}}%).`,
},
{

View File

@@ -82,7 +82,8 @@ type Deps struct {
// group flag, group membership), so the evaluator sees it at once instead of after its cache expires.
OnAlertDownChange func()
// PollInterval is the normal poll cadence; a device unheard of for three of them is down. Default 60 s.
// PollInterval is the default poll cadence (300 s); a device unheard of for three of its own is down.
// A device's poll_interval_s overrides it.
PollInterval time.Duration
// HotRetention, FiveMinuteRetention and LongRetention are the stores' retention periods. They decide where a
@@ -153,7 +154,7 @@ func (d Deps) withDefaults() Deps {
d.Logger = slog.Default()
}
d.DiscoveryTimeout = cmp.Or(d.DiscoveryTimeout, DiscoveryTimeout)
d.PollInterval = cmp.Or(d.PollInterval, time.Minute)
d.PollInterval = cmp.Or(d.PollInterval, store.DefaultPollInterval)
d.HotRetention = cmp.Or(d.HotRetention, 30*day)
d.FiveMinuteRetention = cmp.Or(d.FiveMinuteRetention, 120*day)
d.LongRetention = cmp.Or(d.LongRetention, 2*365*day)

View File

@@ -48,7 +48,7 @@ func TestDeviceDetailLiveRates(t *testing.T) {
rateQueries = append(rateQueries, c.expr)
}
}
if len(rateQueries) != 1 || !strings.Contains(rateQueries[0], "rate(ifHCInOctets{device=") || !strings.Contains(rateQueries[0], "[5m])*8") {
if len(rateQueries) != 1 || !strings.Contains(rateQueries[0], "rate(ifHCInOctets{device=") || !strings.Contains(rateQueries[0], "[600s])*8") {
t.Errorf("want one batched rate query, got %q", rateQueries)
}
if d.Slug != core.Slug || d.HWSerial != "SN1" || d.SysDescr != "JunOS" || d.UptimeSeconds == nil || *d.UptimeSeconds != 86400 ||

View File

@@ -45,12 +45,12 @@ func valueExpr(m profile.Metric, slug, comp string) string {
// graphExprs returns the series expression and, for a metric with a capacity that is not drawn as
// percent, the capacity expression.
func graphExprs(res *profile.Resolved, m profile.Metric, slug, comp string, step time.Duration) (expr, maxExpr string) {
func graphExprs(res *profile.Resolved, m profile.Metric, slug, comp string, step, every time.Duration) (expr, maxExpr string) {
display := m.EffectiveDisplay()
val := valueExpr(m, slug, comp)
counter := m.Type == profile.Counter32 || m.Type == profile.Counter64
if counter && display == "rate" {
val = `rate(` + metricSel(m.Name, slug, comp) + `[` + secs(max(step, minRateWindow)) + `])`
val = `rate(` + metricSel(m.Name, slug, comp) + `[` + secs(max(step, rateWindowFor(every))) + `])`
}
om, hasOf := res.Metric(m.Of)
if !hasOf {
@@ -85,7 +85,7 @@ func (s *server) metricGraph(ctx context.Context, in *metricGraphIn) (*struct{ B
if in.Aggregate != "" && comp == "" {
comp = allComponents
}
expr, maxExpr := graphExprs(res, m, d.Slug, comp, step)
expr, maxExpr := graphExprs(res, m, d.Slug, comp, step, d.PollInterval(s.PollInterval))
if comp == allComponents {
expr, maxExpr = in.Aggregate+`(`+expr+`)`, ""
}

View File

@@ -0,0 +1,30 @@
package api_test
import (
"encoding/json"
"testing"
"github.com/v10networks/nmon/internal/api"
)
func TestPutDeviceSetsAndClearsPollInterval(t *testing.T) {
e := newEnv(t, 0)
d := e.device(t, "A", "yyz", "core")
url := "/api/v1/devices/" + d.Slug
var v api.DeviceView
rec := e.do("PUT", url, `{"poll_interval_s":60}`)
_ = json.Unmarshal(rec.Body.Bytes(), &v)
if rec.Code != 200 || v.PollIntervalS != 60 || v.PollIntervalEffectiveS != 60 {
t.Fatalf("set: %d %+v", rec.Code, v)
}
if e.ref.n.Load() != 1 {
t.Error("poller not refreshed")
}
rec = e.do("PUT", url, `{"poll_interval_s":0}`)
_ = json.Unmarshal(rec.Body.Bytes(), &v)
if rec.Code != 200 || v.PollIntervalS != 0 || v.PollIntervalEffectiveS != 300 {
t.Fatalf("clear: %d %+v", rec.Code, v)
}
isProblem(t, e.do("PUT", url, `{"poll_interval_s":10}`), 422)
isProblem(t, e.do("PUT", url, `{"poll_interval_s":7200}`), 422)
}

View File

@@ -3,6 +3,7 @@ package api
import (
"context"
"errors"
"fmt"
"strings"
"github.com/danielgtaylor/huma/v2"
@@ -13,13 +14,14 @@ import (
// PutDeviceBody is the body of PUT /api/v1/devices/{slug}. Absent fields stay
// as they are; an empty parents list removes every parent.
type PutDeviceBody struct {
Name *string `json:"name,omitempty" minLength:"1" maxLength:"255"`
Site *string `json:"site,omitempty"`
Role *string `json:"role,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
Parents []string `json:"parents,omitempty" doc:"Parent device slugs, replacing the current parents."`
SNMP *SNMPBody `json:"snmp,omitempty" doc:"Replaces the SNMP credential; secrets are write-only."`
Profile *string `json:"profile,omitempty" doc:"A profile name pins it; an empty string returns the device to automatic matching. A change triggers one discovery."` //nolint:lll // struct tag text is the OpenAPI doc; cannot wrap
Name *string `json:"name,omitempty" minLength:"1" maxLength:"255"`
Site *string `json:"site,omitempty"`
Role *string `json:"role,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
Parents []string `json:"parents,omitempty" doc:"Parent device slugs, replacing the current parents."`
SNMP *SNMPBody `json:"snmp,omitempty" doc:"Replaces the SNMP credential; secrets are write-only."`
PollIntervalS *int `json:"poll_interval_s,omitempty" minimum:"0" maximum:"3600" doc:"Poll interval, 30 to 3600 s; 0 = default."`
Profile *string `json:"profile,omitempty" doc:"A profile name pins it; an empty string returns the device to automatic matching. A change triggers one discovery."` //nolint:lll // struct tag text is the OpenAPI doc; cannot wrap
}
func isNotFound(err error) bool { return errors.Is(err, store.ErrNotFound) }
@@ -90,6 +92,9 @@ func (s *server) planEdit(ctx context.Context, dev *store.Device, b PutDeviceBod
p.setParents, p.parents = true, parents
p.change["parents"] = b.Parents
}
if err := planPollInterval(p, b.PollIntervalS); err != nil {
return nil, err
}
if b.Profile != nil {
if err := s.planProfile(p, dev, *b.Profile); err != nil {
return nil, err
@@ -110,6 +115,20 @@ func (s *server) planEdit(ctx context.Context, dev *store.Device, b PutDeviceBod
return p, nil
}
// planPollInterval validates the poll-interval override: 0 clears it, otherwise it must be in bounds.
func planPollInterval(p *editPlan, v *int) error {
if v == nil || *v == p.after.PollIntervalS {
return nil
}
if *v != 0 && (*v < store.MinPollIntervalS || *v > store.MaxPollIntervalS) {
return huma.Error422UnprocessableEntity(fmt.Sprintf("poll_interval_s must be 0 or %d to %d",
store.MinPollIntervalS, store.MaxPollIntervalS))
}
p.after.PollIntervalS = *v
p.change["poll_interval_s"] = *v
return nil
}
// applyEdit writes the plan and its audit row in one transaction. The old
// credential is deleted once nothing uses it.
func (s *server) applyEdit(ctx context.Context, dev *store.Device, p *editPlan) error {

View File

@@ -45,9 +45,9 @@ type InterfaceView struct {
LastDiscovered time.Time `json:"last_discovered"`
Unreliable bool `json:"unreliable" doc:"Counters cannot be trusted (32-bit counters on a fast link); no rate is reported."`
RetiredAt *time.Time `json:"retired_at" nullable:"true"`
InBPS *float64 `json:"in_bps" nullable:"true" doc:"Inbound bits per second over 5 minutes."`
InBPS *float64 `json:"in_bps" nullable:"true" doc:"Inbound bits per second over the live window (two default poll intervals)."`
OutBPS *float64 `json:"out_bps" nullable:"true"`
InErrorsPS *float64 `json:"in_errors_ps" nullable:"true" doc:"Inbound errors per second over 5 minutes."`
InErrorsPS *float64 `json:"in_errors_ps" nullable:"true" doc:"Inbound errors per second over the live window."`
OutErrorsPS *float64 `json:"out_errors_ps" nullable:"true"`
AlertDownState
}
@@ -63,23 +63,27 @@ type DeviceView struct {
ProfilePinned bool `json:"profile_pinned" doc:"An operator chose the profile; discovery keeps it."`
ProfileMatch *ProfileMatchView `json:"profile_match,omitempty"`
Enabled bool `json:"enabled"`
MgmtIP string `json:"mgmt_ip"`
Addresses []string `json:"addresses"`
SNMPVersion string `json:"snmp_version,omitempty"`
SysName string `json:"sys_name"`
SysObjectID string `json:"sys_object_id"`
SysDescr string `json:"sys_descr"`
HWSerial string `json:"hw_serial"`
UptimeSeconds *float64 `json:"uptime_seconds" nullable:"true" doc:"sysUpTime from the hot store; null when unknown."`
Reachability string `json:"reachability" enum:"up,down,warning,unknown,maintenance"`
PollState string `json:"poll_state" enum:"ok,degraded,backoff"`
Warnings []string `json:"warnings"`
LastSeen *time.Time `json:"last_seen" nullable:"true"`
CreatedAt time.Time `json:"created_at"`
RetiredAt *time.Time `json:"retired_at,omitempty" nullable:"true"`
Parents []DeviceRef `json:"parents"`
Groups []GroupView `json:"groups"`
Interfaces []InterfaceView `json:"interfaces"`
// PollIntervalS is the admin's SNMP poll interval override in seconds (0 = the default);
// PollIntervalEffectiveS is the interval in force.
PollIntervalS int `json:"poll_interval_s" doc:"Poll interval override in seconds; 0 means the default."`
PollIntervalEffectiveS int `json:"poll_interval_effective_s" doc:"The SNMP poll interval in force, in seconds."`
MgmtIP string `json:"mgmt_ip"`
Addresses []string `json:"addresses"`
SNMPVersion string `json:"snmp_version,omitempty"`
SysName string `json:"sys_name"`
SysObjectID string `json:"sys_object_id"`
SysDescr string `json:"sys_descr"`
HWSerial string `json:"hw_serial"`
UptimeSeconds *float64 `json:"uptime_seconds" nullable:"true" doc:"sysUpTime from the hot store; null when unknown."`
Reachability string `json:"reachability" enum:"up,down,warning,unknown,maintenance"`
PollState string `json:"poll_state" enum:"ok,degraded,backoff"`
Warnings []string `json:"warnings"`
LastSeen *time.Time `json:"last_seen" nullable:"true"`
CreatedAt time.Time `json:"created_at"`
RetiredAt *time.Time `json:"retired_at,omitempty" nullable:"true"`
Parents []DeviceRef `json:"parents"`
Groups []GroupView `json:"groups"`
Interfaces []InterfaceView `json:"interfaces"`
// M5 additions.
HostedOn *DeviceRef `json:"hosted_on,omitempty" doc:"The host node of a VM or container."`
Guests []DeviceRef `json:"guests" doc:"VMs and containers hosted on this device."`
@@ -123,6 +127,7 @@ func (s *server) view(ctx context.Context, slug string) (*deviceOut, error) {
v := DeviceView{
Slug: d.Slug, Name: d.Name, Kind: d.Kind, Site: d.Site, Role: d.Role, Profile: d.Profile,
ProfilePinned: d.ProfilePinned, ProfileMatch: s.profileMatch(d), Enabled: d.Enabled,
PollIntervalS: d.PollIntervalS, PollIntervalEffectiveS: int(d.PollInterval(s.PollInterval) / time.Second),
MgmtIP: d.MgmtIP, SysName: d.SysName, SysObjectID: d.SysObjectID, SysDescr: d.SysDescr, HWSerial: d.HWSerial,
PollState: pollStateOf(d), Warnings: s.warningsOf(d), LastSeen: utcp(d.LastSeen), CreatedAt: d.CreatedAt.UTC(),
RetiredAt: utcp(d.RetiredAt), Addresses: []string{}, Parents: []DeviceRef{}, Groups: []GroupView{},

View File

@@ -30,7 +30,7 @@ type graphIn struct {
To time.Time `query:"to" doc:"End, RFC 3339. Default now."`
Step int64 `query:"step" minimum:"1" doc:"Step in seconds. Default max(60, range/1000) rounded up to whole minutes."`
Dir string `query:"dir" enum:"in,out" doc:"Only this direction; the other series is empty."`
Max bool `query:"max" doc:"Also return in_max and out_max, the highest one-minute rate within each step."`
Max bool `query:"max" doc:"Also return in_max and out_max, the highest poll-to-poll rate within each step."`
P95 bool `query:"p95" doc:"Also return the 95th percentile: monthly for a whole calendar month, else live over the range."`
Month string `query:"month" pattern:"^\\d{4}-(0[1-9]|1[0-2])$" doc:"YYYY-MM in the site timezone. Replaces from and to with that month's bounds."` //nolint:lll // struct tag text is the OpenAPI doc; cannot wrap
}
@@ -64,7 +64,8 @@ func (s *server) graph(ctx context.Context, in *graphIn) (*struct{ Body GraphRes
resp.Unreliable, resp.UnreliableReason = true, unreliableReason(i)
return &struct{ Body GraphResponse }{resp}, nil
}
if err := s.fillGraph(ctx, &resp, i, plan, in, graphSite{hotStart: hotStart, site: dev.Site}); err != nil {
if err := s.fillGraph(ctx, &resp, i, plan, in, graphSite{hotStart: hotStart, site: dev.Site,
every: dev.PollInterval(s.PollInterval)}); err != nil {
return nil, err
}
return &struct{ Body GraphResponse }{resp}, nil
@@ -97,6 +98,7 @@ func (s *server) graphRange(in *graphIn, site string) (from, to time.Time, err e
type graphSite struct {
hotStart time.Time
site string
every time.Duration // the device's effective poll interval
}
// fillGraph queries the stores the plan names and lays the samples out on the grid.
@@ -110,7 +112,7 @@ func (s *server) fillGraph(
defer release()
qctx, cancel := context.WithTimeout(ctx, QueryTimeout)
defer cancel()
q := &graphQuery{iface: i, dirs: []string{dirIn, dirOut}, withMax: in.Max}
q := &graphQuery{iface: i, dirs: []string{dirIn, dirOut}, withMax: in.Max, every: gs.every}
if in.Dir != "" {
q.dirs = []string{in.Dir}
}

View File

@@ -15,13 +15,21 @@ import (
const (
dirIn = "in"
dirOut = "out"
// minRateWindow keeps the rate window above two poll intervals so a step of
// one minute still sees two samples.
// minRateWindow is the floor of every rate window, for devices polled faster than once a minute.
minRateWindow = 2 * time.Minute
// maxInnerStep is the resolution of the max-over-step subquery.
// maxInnerStep is the finest resolution of the max-over-step subquery.
maxInnerStep = time.Minute
)
// rateWindowFor is the window of a rate() over a device polled every `every`: two polls, so a window always holds
// two samples (VictoriaMetrics also takes the one before the window, which only helps). A zero every means the default.
func rateWindowFor(every time.Duration) time.Duration {
if every <= 0 {
every = store.DefaultPollInterval
}
return max(minRateWindow, 2*every)
}
// graphData holds the samples found, by direction and Unix second.
type graphData struct {
avg map[string]map[int64]float64
@@ -50,6 +58,7 @@ type graphQuery struct {
iface *store.Interface
dirs []string
withMax bool
every time.Duration // the device's effective poll interval; sizes the rate windows
}
// octets is the counter that carries direction dir for the interface.
@@ -70,13 +79,14 @@ func secs(d time.Duration) string { return strconv.FormatInt(int64(d/time.Second
// rawExpr is the average bits per second of dir over the rate window.
func (q *graphQuery) rawExpr(dir string, step time.Duration) string {
sel := q.octets(dir) + `{iface=` + quote(q.iface.ID) + `}`
return `rate(` + sel + `[` + secs(max(step, minRateWindow)) + `])*8`
return `rate(` + sel + `[` + secs(max(step, rateWindowFor(q.every))) + `])*8`
}
// rawMaxExpr is the highest one-minute rate seen within each step.
// rawMaxExpr is the highest poll-to-poll rate seen within each step. irate is the rate between the last two
// samples in its window, which is the poll-to-poll rate whatever the cadence.
func (q *graphQuery) rawMaxExpr(dir string, step time.Duration) string {
sel := q.octets(dir) + `{iface=` + quote(q.iface.ID) + `}`
return `max_over_time((rate(` + sel + `[` + secs(maxInnerStep) + `])*8)[` + secs(step) + `:` + secs(maxInnerStep) + `])`
return `max_over_time((irate(` + sel + `[` + secs(rateWindowFor(q.every)) + `])*8)[` + secs(step) + `:` + secs(maxInnerStep) + `])`
}
// longExpr reads an hourly rollup metric. A re-run of a window writes the next

View File

@@ -61,7 +61,7 @@ func (s *server) livep95(ctx context.Context, q *graphQuery, p *graphPlan, hotSt
coverage := 1.0
for _, dir := range q.dirs {
var vals []float64
expr := `rate(` + q.octets(dir) + `{iface=` + quote(q.iface.ID) + `}[` + secs(p95Slot) + `])*8`
expr := `rate(` + q.octets(dir) + `{iface=` + quote(q.iface.ID) + `}[` + secs(max(p95Slot, rateWindowFor(q.every))) + `])*8`
err := s.fetchOne(ctx, "hot", expr, w, func(_ int64, v float64) { vals = append(vals, v) })
if err != nil {
return nil, err

View File

@@ -100,7 +100,7 @@ func TestGraphRawTierWithinHotRetention(t *testing.T) {
}
qs := e.q.queries()
if len(qs) != 2 || qs[0].store != "hot" || qs[0].step != time.Minute ||
qs[0].expr != `rate(ifHCInOctets{iface="`+i.ID+`"}[120s])*8` || !strings.Contains(qs[1].expr, "ifHCOutOctets") {
qs[0].expr != `rate(ifHCInOctets{iface="`+i.ID+`"}[600s])*8` || !strings.Contains(qs[1].expr, "ifHCOutOctets") {
t.Errorf("queries: %+v", qs)
}
var raw map[string]json.RawMessage
@@ -357,7 +357,7 @@ func TestGraphDirectionFilterAndMax(t *testing.T) {
t.Errorf("dir=out queried the in counter: %s", c.expr)
}
}
if !strings.Contains(qs[1].expr, "max_over_time((rate(ifHCOutOctets{iface=") || !strings.Contains(qs[1].expr, "[60s:60s])") {
if !strings.Contains(qs[1].expr, "max_over_time((irate(ifHCOutOctets{iface=") || !strings.Contains(qs[1].expr, "[60s:60s])") {
t.Errorf("max query: %s", qs[1].expr)
}
isProblem(t, e.do("GET", graphURL(i.ID, t0.Add(-time.Hour), t0, "&dir=sideways"), ""), 422)

View File

@@ -88,7 +88,7 @@ func (s *server) overviewMetrics(ctx context.Context, resp *OverviewResponse, d
if len(hc)+len(soft) == 0 {
break
}
vals, err := s.fetchMetricSeries(ctx, trafficExpr(hc, soft, dir, step), plan)
vals, err := s.fetchMetricSeries(ctx, trafficExpr(hc, soft, dir, step, s.PollInterval), plan)
if err != nil {
resp.Partial = append(resp.Partial, "traffic")
resp.Traffic.In, resp.Traffic.Out = []Point{}, []Point{}
@@ -127,9 +127,9 @@ func countedIfaces(ifs []store.Interface, t *OverviewTraffic) (hc, soft []string
}
// trafficExpr is the summed bits per second of dir; HC counters where a port has them, else the 32-bit ones.
func trafficExpr(hc, soft []string, dir string, step time.Duration) string {
func trafficExpr(hc, soft []string, dir string, step, every time.Duration) string {
names := map[string][2]string{dirIn: {"ifHCInOctets", "ifInOctets"}, dirOut: {"ifHCOutOctets", "ifOutOctets"}}[dir]
win := secs(max(step, minRateWindow))
win := secs(max(step, rateWindowFor(every)))
var parts []string
for n, ids := range [][]string{hc, soft} {
if len(ids) > 0 {

View File

@@ -7,8 +7,9 @@ import (
"github.com/v10networks/nmon/internal/store"
)
// liveWindow is the lookback of the "live" rates on device and search pages.
const liveWindow = "5m"
// liveWindow is the lookback of the "live" rates on device and search pages: two default poll intervals, so a
// device polled at the default always has two samples inside it (never under the five minutes it used to be).
func (s *server) liveWindow() string { return secs(rateWindowFor(s.PollInterval)) }
// ifRates holds the five-minute rates of one interface by the counter they came
// from; pick chooses between the 64-bit and 32-bit counters.
@@ -29,17 +30,17 @@ var rateKinds = []struct {
// ratesExpr is one MetricsQL expression yielding every live rate of the interfaces
// matched by match (label matchers), each series tagged with k. When uptime is set
// it also yields the device's last sysUpTime under k="uptime".
func ratesExpr(match string, uptime bool) string {
func ratesExpr(match string, uptime bool, window string) string {
parts := make([]string, 0, len(rateKinds)+1)
for _, k := range rateKinds {
scale := ""
if k.bits {
scale = "*8"
}
parts = append(parts, `label_set(rate(`+k.metric+`{`+match+`}[`+liveWindow+`])`+scale+`, "k", `+quote(k.k)+`)`)
parts = append(parts, `label_set(rate(`+k.metric+`{`+match+`}[`+window+`])`+scale+`, "k", `+quote(k.k)+`)`)
}
if uptime {
parts = append(parts, `label_set(last_over_time(sysUpTime{`+match+`}[10m]), "k", "uptime")`)
parts = append(parts, `label_set(last_over_time(sysUpTime{`+match+`}[`+window+`]), "k", "uptime")`)
}
return strings.Join(parts, " or ")
}
@@ -54,7 +55,7 @@ func (s *server) liveRates(ctx context.Context, match string, uptime bool) (map[
defer release()
qctx, cancel := context.WithTimeout(ctx, QueryTimeout)
defer cancel()
body, err := s.Querier.Query(qctx, "hot", ratesExpr(match, uptime), s.Clock.Now())
body, err := s.Querier.Query(qctx, "hot", ratesExpr(match, uptime, s.liveWindow()), s.Clock.Now())
if err != nil {
s.Logger.Warn("live rates unavailable", "err", err)
return nil, nil

View File

@@ -34,7 +34,8 @@ type persistedReachability struct {
}
// upLookback is how stale an up series may be and still count.
const upLookback = "5m"
// It must outlast two default SNMP polls, or nmon_snmp_up would drop out between polls.
const upLookback = "11m"
// maxScoped is the most devices a query names explicitly; beyond it all devices are fetched.
const maxScoped = 200
@@ -45,7 +46,7 @@ func (p *persistedReachability) Reachability(ctx context.Context, devs []store.D
out := make(map[string]string, len(devs))
for i := range devs {
d := &devs[i]
out[d.Slug] = reachabilityOf(d, icmp[d.Slug], snmp[d.Slug], now, p.interval)
out[d.Slug] = reachabilityOf(d, icmp[d.Slug], snmp[d.Slug], now, d.PollInterval(p.interval))
}
return out
}

View File

@@ -38,7 +38,7 @@ func (a *App) startRollup(s *settings) error {
origin := a.installTime(context.Background(), clk)
job, err := rollup.New(rollup.Options{
Query: q, Inventory: a.st, State: a.st, Writer: ls, Deleter: ls, Queue: a.hot, Paused: a.guard.PauseRollup, Clock: clk,
Logger: a.log, Origin: origin,
Logger: a.log, Origin: origin, PollInterval: s.PollInterval,
Gauges: profileGauges(a.profiles), Alarms: ruleAlarms{a.alerting.sys, alert.RuleRollupStalled},
HotRetention: s.cfg.Retention.Hot.D(), FiveMinuteRetention: s.cfg.Retention.FiveMinute.D(), LongRetention: s.cfg.Retention.Long.D(),
})

View File

@@ -33,7 +33,7 @@ type Flags struct {
VMLongURL string
MaxInflight int
TrapListen string // UDP address for SNMP traps; empty disables the receiver
PollInterval time.Duration // dev/test override of the 60 s interface interval; 0 = profile default
PollInterval time.Duration // dev/test override of the 300 s default SNMP poll interval; 0 = default. A device's own interval still wins
SNMPPort int // dev/test override of UDP 161 for every device; 0 = 161
ICMP string // ICMPAuto (default) or ICMPOff
GraphiteListen string // TCP address for Graphite plaintext push; empty disables the listener

View File

@@ -103,7 +103,7 @@ func (p *Poller) target(ctx context.Context, d *store.Device) (*target, error) {
}
t.notePolledInterfaces(polled)
b := &planBuilder{t: t, polled: polled, byTable: byTable, tableKey: p.o.TableKey,
interval: p.o.Interval, byBase: map[time.Duration]*groupBuilder{}}
interval: d.PollInterval(p.o.Interval), byBase: map[time.Duration]*groupBuilder{}}
for _, ig := range prof.PollableMetrics() {
b.addIntervalGroup(ig)
}

View File

@@ -35,7 +35,7 @@ import (
// Defaults.
const (
DefaultInterval = 60 * time.Second
DefaultInterval = store.DefaultPollInterval
DefaultMaxInflight = 512
icmpInterval = 15 * time.Second
selfmonInterval = 15 * time.Second
@@ -81,7 +81,7 @@ type Options struct {
Profiles *profile.Set
LoadProfiles func() (*profile.Set, error)
Interval time.Duration // cadence of the profile's 60 s group; default 60 s. Its cycle deadline is half of it
Interval time.Duration // cadence of the profile's 1m group; default 300 s; a device's poll_interval_s wins. Cycle deadline is half
MaxInflight int // global cap on concurrent cycles; default 512
SNMPPort int // override of the device's SNMP port (default 161); 0 = use the device's

View File

@@ -66,7 +66,7 @@ type PollResult struct {
// PollOptions tune Poll.
type PollOptions struct {
Interval time.Duration // cadence of the 60 s group; default 60 s (the cycle deadline is half)
Interval time.Duration // profile 1m group cadence; default 60 s, since expect.yaml budgets are keyed by group name
Timeout time.Duration // overall wait; default 60 s
// Settle, when set, is called with the poller's status each 50 ms until it
// returns true; Poll then returns without waiting for every group (used for
@@ -261,6 +261,9 @@ type pollRun struct {
// startPoll runs a real poller against the Env's store with its metric writer
// and SNMP sessions instrumented, so Poll can count PDUs and type mismatches.
func (e *Env) startPoll(ctx context.Context, prof *profile.Resolved, o PollOptions) *pollRun {
if o.Interval <= 0 {
o.Interval = time.Minute
}
r := &pollRun{col: newCollector(prof), cycleCh: make(chan struct{}, 64), done: make(chan struct{})}
w := metrics.WriterFunc(func(_ context.Context, s []metrics.Sample) error {
r.mu.Lock()

View File

@@ -32,7 +32,7 @@ type Options struct {
Log *slog.Logger
Registry *selfmon.Registry
// PollInterval is the poller's normal cadence; it sets the default DependencyHold. Default 60 s.
// PollInterval is the poller's normal cadence; it sets the default DependencyHold. Default 300 s.
PollInterval time.Duration
// DependencyHold is how long a down device's notice waits while the devices it depends on (or
// shares children with) have failing signals but no verdict. Default 2 x PollInterval plus one
@@ -84,7 +84,7 @@ func (o *Options) defaults() {
set(&o.NoData, DefaultNoData)
set(&o.PushAbsent, DefaultPushAbsent)
if o.PollInterval <= 0 {
o.PollInterval = time.Minute
o.PollInterval = store.DefaultPollInterval
}
if o.DependencyHold <= 0 {
o.DependencyHold = 2*o.PollInterval + o.Interval

View File

@@ -145,7 +145,7 @@ func (e *Evaluator) register(devs []store.Device) {
continue
}
live[d.Slug] = true
info := Info{Slug: d.Slug, Kind: d.Kind}
info := Info{Slug: d.Slug, Kind: d.Kind, PollEvery: d.PollInterval(e.o.PollInterval)}
if e.o.ICMPBlocked != nil {
info.ICMPBlocked = e.o.ICMPBlocked(d)
}

View File

@@ -39,17 +39,18 @@ func (n *fakeN) take() []Transition {
}
type harness struct {
t *testing.T
st store.Store
clk *clock.Fake
n *fakeN
ev *Evaluator
opts Options
slug map[string]string // device name -> store slug
names map[string]string // store slug -> device name
maint func(slug string, at time.Time) bool
icmpOff bool
wants func(rule, slug string) bool // nil: every rule is wanted everywhere
t *testing.T
st store.Store
clk *clock.Fake
n *fakeN
ev *Evaluator
opts Options
pollEvery time.Duration // Options.PollInterval for the next start; zero = the product default
slug map[string]string // device name -> store slug
names map[string]string // store slug -> device name
maint func(slug string, at time.Time) bool
icmpOff bool
wants func(rule, slug string) bool // nil: every rule is wanted everywhere
}
func newHarness(t *testing.T) *harness {
@@ -70,7 +71,7 @@ func newHarness(t *testing.T) *harness {
// start creates a fresh Evaluator over the same database, as a process restart would.
func (h *harness) start() {
h.t.Helper()
h.opts = Options{Store: h.st, Notifier: h.n, Clock: h.clk, Registry: selfmon.New(), ICMPOff: h.icmpOff,
h.opts = Options{Store: h.st, Notifier: h.n, Clock: h.clk, Registry: selfmon.New(), ICMPOff: h.icmpOff, PollInterval: h.pollEvery,
ICMPBlocked: func(d *store.Device) bool { return d.Profile == "icmp_blocked" },
InMaintenance: func(slug string, at time.Time) bool {
return h.maint != nil && h.maint(slug, at)

View File

@@ -29,7 +29,7 @@ func (e *Evaluator) assess(d *device, now time.Time) verdict {
default:
v = e.assessNetwork(d, now)
}
stale := now.Sub(maxTime(d.lastSignal, d.registered)) > e.o.NoData
stale := now.Sub(maxTime(d.lastSignal, d.registered)) > max(e.o.NoData, 2*d.info.PollEvery)
if stale && (v.keep || v.state == Up || v.state == Unknown) {
return warn(ReasonNoData)
}

View File

@@ -199,6 +199,7 @@ func TestCheckOnlyDownAfterConfiguredFailures(t *testing.T) {
func TestNoDataWarningAfterFiveMinutesOfSilence(t *testing.T) {
h := newHarness(t)
h.pollEvery = time.Minute // silence is judged against two polls; 5 min applies to a minute cadence
h.add("sw", store.KindNetwork, "")
h.start()
h.cycle()

View File

@@ -133,4 +133,6 @@ type Info struct {
ICMPBlocked bool
// CheckFails is how many consecutive check failures mean down (0 = default 3).
CheckFails int
// PollEvery is the device's effective SNMP poll interval; silence is "no data" only after two of them.
PollEvery time.Duration
}

View File

@@ -3,6 +3,7 @@ package rollup
import (
"context"
"fmt"
"time"
"github.com/v10networks/nmon/internal/store"
)
@@ -10,6 +11,7 @@ import (
// deviceTarget is one device and the interfaces worth rolling up.
type deviceTarget struct {
slug string
every time.Duration // the device's effective SNMP poll interval
ifaces map[string]store.Interface // by interface ID
}
@@ -34,7 +36,7 @@ func (j *Job) devices(ctx context.Context) ([]deviceTarget, error) {
if err != nil {
return nil, fmt.Errorf("rollup: list interfaces of %s: %w", d.Slug, err)
}
t := deviceTarget{slug: d.Slug, ifaces: map[string]store.Interface{}}
t := deviceTarget{slug: d.Slug, every: d.PollInterval(j.o.PollInterval), ifaces: map[string]store.Interface{}}
for _, i := range ifs {
if !i.Excluded && !i.Unreliable {
t.ifaces[i.ID] = i

View File

@@ -308,7 +308,7 @@ func newRig(t *testing.T, now time.Time, mut func(*Options)) *rig {
r := &rig{vm: newFakeVM(), inv: &fakeInv{}, clk: clock.NewFake(now), q: &fakeQueue{}}
r.st = openState(t, r.clk)
r.state = &crashState{Rollup: r.st}
o := Options{Query: r.vm, Inventory: r.inv, State: r.state, Writer: r.vm, Clock: r.clk, Queue: r.q, Origin: t0}
o := Options{Query: r.vm, Inventory: r.inv, State: r.state, Writer: r.vm, Clock: r.clk, Queue: r.q, Origin: t0, PollInterval: time.Minute}
if mut != nil {
mut(&o)
}

View File

@@ -80,8 +80,10 @@ func (j *Job) collectFiveMinute(ctx context.Context, devs []deviceTarget, ws tim
// poll interval predicts).
func (j *Job) deviceRates(ctx context.Context, d deviceTarget, ws time.Time) (out []metrics.Sample, present, thin int, err error) {
we := ws.Add(FiveMinutes)
// The baseline sample of a window's first increase may be one poll earlier than the window.
back := max(lookback, 2*d.every)
q := fmt.Sprintf(`{__name__=~"ifHCInOctets|ifHCOutOctets|ifInOctets|ifOutOctets",device=%q}[%ds]`,
d.slug, int((FiveMinutes+lookback)/time.Second))
d.slug, int((FiveMinutes+back)/time.Second))
body, err := j.o.Query.Query(ctx, "hot", q, we)
if err != nil {
return nil, 0, 0, fmt.Errorf("hot query for %s: %w", d.slug, err)
@@ -90,7 +92,10 @@ func (j *Job) deviceRates(ctx context.Context, d deviceTarget, ws time.Time) (ou
if err != nil {
return nil, 0, 0, err
}
minInside := int(float64(FiveMinutes/j.o.PollInterval) * 0.8)
// A window is thin when it holds under 80 % of the samples the device's cadence predicts. At a cadence of
// 5 min or slower the prediction is at most one sample, so minInside is 0: a window with no sample at all is
// already skipped (not present), and a window with its one sample is complete, never thin.
minInside := int(float64(FiveMinutes/d.every) * 0.8)
for _, r := range rows {
meta, ok := counterMeta[r.labels["__name__"]]
ifc, known := d.ifaces[r.labels["iface"]]

View File

@@ -68,7 +68,7 @@ type Options struct {
HotRetention time.Duration // 30 d: older windows cannot be computed or repaired
FiveMinuteRetention time.Duration // 4 months (120 d)
LongRetention time.Duration // 2 y; bounds how far back the retention job looks
PollInterval time.Duration // 60 s: expected sample spacing, for gap detection
PollInterval time.Duration // 300 s: expected sample spacing of a device without its own interval, for gap detection
Settle time.Duration // 60 s: a window is final this long after it closes
Redo time.Duration // 2 h re-done every run
MaxWindowsPerRun int // 288: catch-up bound, so a long outage drains over several runs
@@ -95,7 +95,7 @@ func (o *Options) defaults() {
set(&o.HotRetention, 30*day)
set(&o.FiveMinuteRetention, 120*day)
set(&o.LongRetention, 2*365*day)
set(&o.PollInterval, time.Minute)
set(&o.PollInterval, store.DefaultPollInterval)
set(&o.Settle, time.Minute)
set(&o.Redo, 2*time.Hour)
if o.MaxWindowsPerRun <= 0 {

View File

@@ -0,0 +1,19 @@
package store
import (
"context"
"github.com/uptrace/bun"
)
// Migration 15 adds devices.poll_interval_s: the operator's SNMP poll cadence for one device, in seconds.
// 0 (the default, and every device that exists before this migration) means the poller-wide default.
func init() {
Migrations.MustRegister(func(ctx context.Context, db *bun.DB) error {
_, err := db.NewAddColumn().Table("devices").ColumnExpr("poll_interval_s INTEGER NOT NULL DEFAULT 0").Exec(ctx)
return err
}, func(ctx context.Context, db *bun.DB) error {
_, err := db.NewDropColumn().Table("devices").Column("poll_interval_s").Exec(ctx)
return err
})
}

View File

@@ -163,7 +163,7 @@ func (s *bunStore) UpdateDevice(ctx context.Context, d *Device) error {
}
res, err := s.db.NewUpdate().Model(d).
Column("name", "kind", "mgmt_ip", "snmp_credential_id", "profile", "site", "role", "enabled",
"external_id", "sys_name", "sys_object_id", "sys_descr", "hw_serial", "snmp_port", "profile_pinned").
"external_id", "sys_name", "sys_object_id", "sys_descr", "hw_serial", "snmp_port", "profile_pinned", "poll_interval_s").
WherePK().Exec(ctx)
if err != nil {
return mapErr(err)

View File

@@ -72,6 +72,8 @@ type Device struct {
SNMPPort int `bun:"snmp_port,notnull"` // migration 2
// ProfilePinned (migration 10): the operator chose Profile, so discovery does not re-match it.
ProfilePinned bool `bun:"profile_pinned,notnull"`
// PollIntervalS (migration 15) overrides the SNMP poll interval in seconds; 0 = the poller default.
PollIntervalS int `bun:"poll_interval_s,notnull"`
}
// DefaultSNMPPort is used when a device has no explicit port.

View File

@@ -0,0 +1,22 @@
package store
import "time"
// Bounds of a device's poll-interval override, in seconds. Below 30 s a device cannot finish a cycle on a slow link;
// above an hour the rate windows and the "unheard of" timers lose their meaning.
const (
MinPollIntervalS = 30
MaxPollIntervalS = 3600
)
// DefaultPollInterval is the SNMP poll cadence of a device without an override (LibreNMS-like; see DEVIATIONS).
// The poller, reachability, the API's "unheard of" timers and the rollup gap detector all start from it.
const DefaultPollInterval = 300 * time.Second
// PollInterval is how often the device's SNMP primary group is polled: its own override, else def.
func (d *Device) PollInterval(def time.Duration) time.Duration {
if d.PollIntervalS > 0 {
return time.Duration(d.PollIntervalS) * time.Second
}
return def
}

View File

@@ -1423,6 +1423,16 @@
},
"type": "array"
},
"poll_interval_effective_s": {
"description": "The SNMP poll interval in force, in seconds.",
"format": "int64",
"type": "integer"
},
"poll_interval_s": {
"description": "Poll interval override in seconds; 0 means the default.",
"format": "int64",
"type": "integer"
},
"poll_state": {
"enum": [
"ok",
@@ -1508,6 +1518,8 @@
"profile",
"profile_pinned",
"enabled",
"poll_interval_s",
"poll_interval_effective_s",
"mgmt_ip",
"addresses",
"sys_name",
@@ -2485,7 +2497,7 @@
"type": "integer"
},
"in_bps": {
"description": "Inbound bits per second over 5 minutes.",
"description": "Inbound bits per second over the live window (two default poll intervals).",
"format": "double",
"type": [
"number",
@@ -2493,7 +2505,7 @@
]
},
"in_errors_ps": {
"description": "Inbound errors per second over 5 minutes.",
"description": "Inbound errors per second over the live window.",
"format": "double",
"type": [
"number",
@@ -4573,6 +4585,13 @@
},
"type": "array"
},
"poll_interval_s": {
"description": "Poll interval, 30 to 3600 s; 0 = default.",
"format": "int64",
"maximum": 3600,
"minimum": 0,
"type": "integer"
},
"profile": {
"description": "A profile name pins it; an empty string returns the device to automatic matching. A change triggers one discovery.",
"type": "string"
@@ -8873,12 +8892,12 @@
}
},
{
"description": "Also return in_max and out_max, the highest one-minute rate within each step.",
"description": "Also return in_max and out_max, the highest poll-to-poll rate within each step.",
"explode": false,
"in": "query",
"name": "max",
"schema": {
"description": "Also return in_max and out_max, the highest one-minute rate within each step.",
"description": "Also return in_max and out_max, the highest poll-to-poll rate within each step.",
"type": "boolean"
}
},

View File

@@ -222,6 +222,8 @@ function makeView(sp: Spec, di: number, interfaces: InterfaceView[]): DeviceView
role: sp.role,
profile: sp.profile,
profile_pinned: false,
poll_interval_s: 0,
poll_interval_effective_s: 300,
enabled: true,
mgmt_ip: ip6,
addresses: di % 4 === 0 ? [ip6, `10.${10 + (di % 3)}.0.${di + 1}`] : [ip6],

View File

@@ -57,6 +57,7 @@ export class MgmtStore {
if (bad) return problem(422, 'Unprocessable Entity', `parents would create a dependency cycle: ${cur.name} -> ${this.r.base(bad)?.name ?? bad} -> ${cur.name}`)
const parents = (body.parents ?? cur.parents.map((p) => p.slug)).map((s) => ({ slug: s, name: this.r.base(s)?.name ?? s }))
const next: Partial<View> = { name: body.name ?? cur.name, site: body.site ?? cur.site, role: body.role ?? cur.role, enabled: body.enabled ?? cur.enabled, parents }
Object.assign(next, pollIntervalPatch(body.poll_interval_s))
if (body.snmp) next.snmp_version = body.snmp.version
Object.assign(next, applyProfileEdit(cur, this.r.base(slug)?.profile, body.profile))
this.patches.set(slug, { ...this.patches.get(slug), ...next })
@@ -92,6 +93,9 @@ export class MgmtStore {
}
}
/** The device fields a poll_interval_s edit changes; 0 returns to the 300 s default. */
const pollIntervalPatch = (s: number | undefined): Partial<View> => (s === undefined ? {} : { poll_interval_s: s, poll_interval_effective_s: s || 300 })
const REPORT: S['DiscoverView'] = {
profile: 'cisco-ios',
partial: false,

View File

@@ -1688,6 +1688,16 @@ export interface components {
mgmt_ip: string;
name: string;
parents: components["schemas"]["DeviceRef"][];
/**
* Format: int64
* @description The SNMP poll interval in force, in seconds.
*/
poll_interval_effective_s: number;
/**
* Format: int64
* @description Poll interval override in seconds; 0 means the default.
*/
poll_interval_s: number;
/** @enum {string} */
poll_state: "ok" | "degraded" | "backoff";
profile: string;
@@ -2057,12 +2067,12 @@ export interface components {
iftype: number;
/**
* Format: double
* @description Inbound bits per second over 5 minutes.
* @description Inbound bits per second over the live window (two default poll intervals).
*/
in_bps: number | null;
/**
* Format: double
* @description Inbound errors per second over 5 minutes.
* @description Inbound errors per second over the live window.
*/
in_errors_ps: number | null;
/** Format: date-time */
@@ -2762,6 +2772,11 @@ export interface components {
name?: string;
/** @description Parent device slugs, replacing the current parents. */
parents?: string[];
/**
* Format: int64
* @description Poll interval, 30 to 3600 s; 0 = default.
*/
poll_interval_s?: number;
/** @description A profile name pins it; an empty string returns the device to automatic matching. A change triggers one discovery. */
profile?: string;
role?: string;
@@ -5655,7 +5670,7 @@ export interface operations {
step?: number;
/** @description Only this direction; the other series is empty. */
dir?: "in" | "out";
/** @description Also return in_max and out_max, the highest one-minute rate within each step. */
/** @description Also return in_max and out_max, the highest poll-to-poll rate within each step. */
max?: boolean;
/** @description Also return the 95th percentile: monthly for a whole calendar month, else live over the range. */
p95?: boolean;

View File

@@ -2,31 +2,14 @@ import { memo, useEffect, useRef, useState } from 'react'
import { useGraph } from '@/api/hooks'
import type { RangeKey } from '@/lib/range'
import { ErrorBox } from './common'
import { GraphSummary } from './GraphSummary'
import type { GraphVariant } from './graphTypes'
import { TrafficGraph } from './TrafficGraph'
/**
* A TrafficGraph that fetches its own data (one query per interface+range, shared
* through the query cache) and only mounts when scrolled near the viewport, or when
* `forceMount` says the idle back-fill has reached it.
*/
export const GraphCell = memo(function GraphCell({
ifaceId,
range,
variant = 'compact',
height,
forceMount = false,
showP95 = false,
showMax = false,
}: {
ifaceId: string
range: RangeKey
variant?: GraphVariant
height?: number
forceMount?: boolean
showP95?: boolean
showMax?: boolean
}) {
const DEFAULT_HEIGHT: Record<GraphVariant, number> = { spark: 44, compact: 130, full: 380 }
/** Whether the element has come within 400 px of the viewport (latched). */
function useNearViewport() {
const ref = useRef<HTMLDivElement>(null)
const [near, setNear] = useState(false)
useEffect(() => {
@@ -49,25 +32,60 @@ export const GraphCell = memo(function GraphCell({
return () => io.disconnect()
}, [near])
return { ref, near }
}
/**
* A TrafficGraph that fetches its own data (one query per interface+range, shared
* through the query cache) and only mounts when scrolled near the viewport, or when
* `forceMount` says the idle back-fill has reached it.
*/
export const GraphCell = memo(function GraphCell({
ifaceId,
range,
variant = 'compact',
height,
forceMount = false,
showP95 = false,
showMax = false,
summary = false,
}: {
ifaceId: string
range: RangeKey
variant?: GraphVariant
height?: number
forceMount?: boolean
showP95?: boolean
showMax?: boolean
/** A current / avg / p95 line under the graph (compact variants; full has its own legend). */
summary?: boolean
}) {
const { ref, near } = useNearViewport()
const active = near || forceMount
const q = useGraph(ifaceId, { range }, active)
const h = height ?? (variant === 'spark' ? 44 : variant === 'compact' ? 130 : 380)
const h = height ?? DEFAULT_HEIGHT[variant]
return (
<div ref={ref} style={{ minHeight: h }}>
{active && q.error ? (
<ErrorBox error={q.error} />
) : active ? (
<TrafficGraph
data={q.data?.graph}
window={q.data?.window}
loading={q.isPending}
variant={variant}
height={h}
rangeLabel={range}
showP95={showP95}
showMax={showMax}
/>
) : null}
{active && <CellBody ifaceId={ifaceId} range={range} variant={variant} h={h} showP95={showP95} showMax={showMax} summary={summary} />}
</div>
)
})
function CellBody(p: { ifaceId: string; range: RangeKey; variant: GraphVariant; h: number; showP95: boolean; showMax: boolean; summary: boolean }) {
const q = useGraph(p.ifaceId, { range: p.range })
if (q.error) return <ErrorBox error={q.error} />
return (
<>
<TrafficGraph
data={q.data?.graph}
window={q.data?.window}
loading={q.isPending}
variant={p.variant}
height={p.h}
rangeLabel={p.range}
showP95={p.showP95}
showMax={p.showMax}
/>
{p.summary && <GraphSummary data={q.data?.graph} />}
</>
)
}

View File

@@ -0,0 +1,34 @@
import { useMemo } from 'react'
import type { GraphResponse } from '@/api/client'
import { formatBps } from '@/lib/format'
import { deriveGraph, type DirStats } from './graphData'
function Dir({ name, color, s, p95 }: { name: string; color: string; s: DirStats; p95: number | null }) {
return (
<span className="inline-flex items-center gap-1.5" data-testid={`summary-${name.toLowerCase()}`}>
<span className="inline-block size-2 rounded-[2px]" style={{ background: color }} aria-hidden />
<span className="text-muted-foreground">{name}</span>
<b className="num font-medium text-foreground" title="Current">
{formatBps(s.current)}
</b>
<span className="num" title="Average over the range">
avg {formatBps(s.avg)}
</span>
<span className="num" title="95th percentile over the range">
p95 {formatBps(p95)}
</span>
</span>
)
}
/** One line under a small graph: current, average and p95 per direction over the shown range (the API's p95 when it sent one). */
export function GraphSummary({ data }: { data: GraphResponse | undefined }) {
const stats = useMemo(() => deriveGraph(data && !data.unreliable ? data.series : null).stats, [data])
if (!stats) return null
return (
<div className="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground" data-testid="graph-summary">
<Dir name="In" color="var(--chart-in)" s={stats.in} p95={data?.p95?.in_bps ?? stats.in.p95} />
<Dir name="Out" color="var(--chart-out)" s={stats.out} p95={data?.p95?.out_bps ?? stats.out.p95} />
</div>
)
}

View File

@@ -12,6 +12,7 @@ import {
parseAddresses,
reattachCandidates,
validateAdd,
validatePollInterval,
validateSnmp,
} from './deviceForm'
@@ -76,6 +77,15 @@ describe('payloads', () => {
expect(buildEditPayload(e)).toEqual({ name: 'c', site: '', role: 'core', enabled: false, parents: ['a-1'] })
expect(buildEditPayload({ ...e, replaceSnmp: true }).snmp).toEqual({ version: 'v2c', community: 'x' })
})
it('edit sends the poll interval: blank clears it, a number sets it, undefined leaves it out', () => {
const e = { name: 'c', site: '', role: '', enabled: true, parents: [], replaceSnmp: false, snmp: emptySnmp(), profile: null }
expect(buildEditPayload({ ...e, pollInterval: '' }).poll_interval_s).toBe(0)
expect(buildEditPayload({ ...e, pollInterval: ' 60 ' }).poll_interval_s).toBe(60)
expect('poll_interval_s' in buildEditPayload(e)).toBe(false)
expect(validatePollInterval('')).toBeUndefined()
expect(validatePollInterval('30')).toBeUndefined()
for (const bad of ['5', '3601', '1.5', 'x']) expect(validatePollInterval(bad), bad).toBeDefined()
})
it('edit sends the profile choice: a name pins, empty is automatic, null leaves it out', () => {
const e = { name: 'c', site: '', role: '', enabled: true, parents: [], replaceSnmp: false, snmp: emptySnmp() }
expect(buildEditPayload({ ...e, profile: 'vyos' }).profile).toBe('vyos')

View File

@@ -118,6 +118,21 @@ export interface EditForm {
snmp: SnmpForm
/** Profile name to pin, '' for automatic, null when the device has no profile to choose (not a network device). */
profile: string | null
/** Poll interval override in seconds as typed; '' returns the device to the default, undefined leaves it alone. */
pollInterval?: string
}
export const DEFAULT_POLL_INTERVAL_S = 300
export const MIN_POLL_INTERVAL_S = 30
export const MAX_POLL_INTERVAL_S = 3600
/** The message for a bad poll-interval entry, or undefined when it is blank (default) or a whole number of seconds in range. */
export function validatePollInterval(s: string): string | undefined {
const t = s.trim()
if (t === '') return undefined
const n = Number(t)
if (!Number.isInteger(n) || n < MIN_POLL_INTERVAL_S || n > MAX_POLL_INTERVAL_S) return `Enter ${MIN_POLL_INTERVAL_S} to ${MAX_POLL_INTERVAL_S} seconds, or leave blank for ${DEFAULT_POLL_INTERVAL_S}.`
return undefined
}
export function buildEditPayload(f: EditForm): PutDeviceBody {
@@ -128,6 +143,7 @@ export function buildEditPayload(f: EditForm): PutDeviceBody {
enabled: f.enabled,
parents: f.parents,
...(f.profile !== null && { profile: f.profile }),
...(f.pollInterval !== undefined && { poll_interval_s: f.pollInterval.trim() === '' ? 0 : Number(f.pollInterval) }),
...(f.replaceSnmp && { snmp: buildSnmp(f.snmp) }),
}
}

View File

@@ -8,10 +8,11 @@ import { SnmpFields } from '@/components/SnmpFields'
import { toast } from '@/components/toast'
import { Button } from '@/components/ui/button'
import { Dialog } from '@/components/ui/dialog'
import { buildEditPayload, emptySnmp, validateSnmp, type EditForm, type FieldErrors } from '@/lib/deviceForm'
import { buildEditPayload, emptySnmp, validatePollInterval, validateSnmp, type EditForm, type FieldErrors } from '@/lib/deviceForm'
import { cyclePath } from '@/pages/devices/importModel'
import { NameField, SiteRole } from '@/pages/devices/DeviceBasics'
import { ParentsPicker } from './ParentsPicker'
import { PollIntervalField } from './PollIntervalField'
import { initialProfile, ProfileSelect } from './ProfileSelect'
const initial = (d: DeviceView): EditForm => ({
@@ -23,6 +24,7 @@ const initial = (d: DeviceView): EditForm => ({
replaceSnmp: false,
snmp: emptySnmp(),
profile: d.kind === 'network' ? initialProfile(d) : null,
pollInterval: d.kind === 'network' ? (d.poll_interval_s > 0 ? String(d.poll_interval_s) : '') : undefined,
})
/** The 422 about the parents (a dependency cycle, an unknown slug), shown next to the picker instead of at the bottom. */
@@ -47,6 +49,8 @@ function EditFormBody({ d, onClose }: { d: DeviceView; onClose: () => void }) {
const submit = () => {
const v = form.replaceSnmp ? validateSnmp(form.snmp) : {}
if (!form.name.trim()) v.name = 'A name is required.'
const pi = validatePollInterval(form.pollInterval ?? '')
if (pi) v.pollInterval = pi
setErrors(v)
if (Object.keys(v).length) return
edit.mutate(buildEditPayload(form), {
@@ -77,6 +81,7 @@ function EditFormBody({ d, onClose }: { d: DeviceView; onClose: () => void }) {
</FormField>
{err && <CycleError error={err} />}
{form.profile !== null && <ProfileSelect d={d} value={form.profile} onChange={(profile) => set({ profile })} />}
{form.pollInterval !== undefined && <PollIntervalField value={form.pollInterval} onChange={(pollInterval) => set({ pollInterval })} error={errors.pollInterval} />}
{d.kind === 'network' && <SnmpReplace form={form} set={set} errors={errors} />}
</fieldset>
{edit.error && !err && <ErrorBox error={edit.error} />}

View File

@@ -1,28 +1,38 @@
import { memo, useEffect, useState } from 'react'
import { Link } from '@tanstack/react-router'
import type { InterfaceView } from '@/api/client'
import { RangePicker } from '@/components/common'
import { GraphCell } from '@/components/GraphCell'
import { Toggle } from '@/components/ui/toggle'
import { formatBps } from '@/lib/format'
import type { RangeKey } from '@/lib/range'
const GridCard = memo(function GridCard({ i, forceMount }: { i: InterfaceView; forceMount: boolean }) {
/** Ranges the grid offers; 2 y is left to the graph view. */
export const GRID_RANGES: readonly RangeKey[] = ['1h', '24h', '7d', '30d', '1y']
const GridCard = memo(function GridCard({ i, range, showP95, forceMount }: { i: InterfaceView; range: RangeKey; showP95: boolean; forceMount: boolean }) {
return (
<div className="rounded-md border border-border p-2" data-testid="graph-card" data-ifname={i.ifname}>
<div className="mb-1 flex items-baseline justify-between gap-2 text-xs">
<Link to="/graph/$ifaceId" params={{ ifaceId: i.id }} search={{ range: '24h' }} className="mono font-semibold hover:text-primary hover:underline">
<Link to="/graph/$ifaceId" params={{ ifaceId: i.id }} search={{ range }} className="mono font-semibold hover:text-primary hover:underline">
{i.ifname}
</Link>
<span className="min-w-0 truncate text-muted-foreground" title={i.ifalias}>
{i.ifalias}
</span>
<span className="num shrink-0 text-muted-foreground">{i.unreliable ? 'n/a' : `${formatBps(i.in_bps)} / ${formatBps(i.out_bps)}`}</span>
<span className="num shrink-0 text-muted-foreground" title="Live in / out">
{i.unreliable ? 'n/a' : `${formatBps(i.in_bps)} / ${formatBps(i.out_bps)}`}
</span>
</div>
<GraphCell ifaceId={i.id} range="24h" variant="compact" height={120} forceMount={forceMount} />
<GraphCell ifaceId={i.id} range={range} variant="compact" height={120} forceMount={forceMount} showP95={showP95} summary />
</div>
)
})
/** Every interface as a small 24 h graph. Cells near the viewport mount at once; the rest are back-filled in slices. */
/** Every interface as a small graph over one shared range. Cells near the viewport mount at once; the rest are back-filled in slices. */
export function GraphGrid({ rows }: { rows: InterfaceView[] }) {
const [range, setRange] = useState<RangeKey>('24h')
const [showP95, setShowP95] = useState(true)
const [limit, setLimit] = useState(0)
useEffect(() => {
if (limit >= rows.length) return
@@ -30,10 +40,18 @@ export function GraphGrid({ rows }: { rows: InterfaceView[] }) {
return () => clearTimeout(t)
}, [limit, rows.length])
return (
<div className="grid gap-3 p-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4" data-testid="graph-grid">
{rows.map((i, idx) => (
<GridCard key={i.id} i={i} forceMount={idx < limit} />
))}
<div data-testid="graph-grid-wrap">
<div className="flex flex-wrap items-center gap-2 border-b border-border px-3 py-2">
<RangePicker value={range} onChange={setRange} keys={GRID_RANGES} />
<Toggle pressed={showP95} onPressedChange={setShowP95} data-testid="grid-p95">
p95
</Toggle>
</div>
<div className="grid gap-3 p-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4" data-testid="graph-grid" data-range={range}>
{rows.map((i, idx) => (
<GridCard key={i.id} i={i} range={range} showP95={showP95} forceMount={idx < limit} />
))}
</div>
</div>
)
}

View File

@@ -1,15 +1,19 @@
import { Fragment, memo } from 'react'
import { Fragment, memo, useState } from 'react'
import { Link } from '@tanstack/react-router'
import { ChevronDown, ChevronRight, ExternalLink, TriangleAlert } from 'lucide-react'
import type { InterfaceView, L2Port } from '@/api/client'
import { RangePicker } from '@/components/common'
import { GraphCell } from '@/components/GraphCell'
import { IfStatusIcon } from '@/components/Status'
import { Badge } from '@/components/ui/badge'
import { TD, TR } from '@/components/ui/table'
import { Toggle } from '@/components/ui/toggle'
import { Tip } from '@/components/ui/tooltip'
import { formatBps, formatPct, formatPerSec, formatSpeed } from '@/lib/format'
import type { RangeKey } from '@/lib/range'
import { cn } from '@/lib/utils'
import { AlertDownCell } from './AlertDownCell'
import { GRID_RANGES } from './GraphGrid'
import { speedOf, unreliableTip, util } from './ifaceModel'
export function UtilBar({ pct }: { pct: number | null }) {
@@ -75,18 +79,24 @@ function LiveCells({ i, stale }: { i: InterfaceView; stale: boolean }) {
}
function ExpandedGraph({ i }: { i: InterfaceView }) {
const [range, setRange] = useState<RangeKey>('24h')
const [showP95, setShowP95] = useState(true)
return (
<tr className="border-b border-border bg-muted/20">
<td colSpan={13} className="px-4 py-3">
<div className="mb-2 flex items-center justify-between text-xs text-muted-foreground">
<span>
Last 24 h · <span className="mono">{i.ifname}</span>
</span>
<Link to="/graph/$ifaceId" params={{ ifaceId: i.id }} search={{ range: '24h' }} className="inline-flex items-center gap-1 text-primary hover:underline" data-testid="open-graph">
<div className="mb-2 flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<div className="flex flex-wrap items-center gap-2">
<span className="mono">{i.ifname}</span>
<RangePicker value={range} onChange={setRange} keys={GRID_RANGES} />
<Toggle pressed={showP95} onPressedChange={setShowP95} data-testid="row-p95">
p95
</Toggle>
</div>
<Link to="/graph/$ifaceId" params={{ ifaceId: i.id }} search={{ range }} className="inline-flex items-center gap-1 text-primary hover:underline" data-testid="open-graph">
Open graph view <ExternalLink className="size-3" />
</Link>
</div>
<GraphCell ifaceId={i.id} range="24h" variant="full" height={230} forceMount />
<GraphCell ifaceId={i.id} range={range} variant="full" height={230} forceMount showP95={showP95} />
</td>
</tr>
)

View File

@@ -0,0 +1,25 @@
import { FormField } from '@/components/FormField'
import { Input } from '@/components/ui/input'
import { DEFAULT_POLL_INTERVAL_S, MAX_POLL_INTERVAL_S, MIN_POLL_INTERVAL_S } from '@/lib/deviceForm'
/** The per-device SNMP poll interval in seconds; blank means the default. */
export function PollIntervalField({ value, onChange, error }: { value: string; onChange: (v: string) => void; error?: string }) {
return (
<FormField id="edit-poll-interval" label="Poll interval" hint={`(seconds, ${MIN_POLL_INTERVAL_S} to ${MAX_POLL_INTERVAL_S}; blank = default ${DEFAULT_POLL_INTERVAL_S})`}>
<Input
id="edit-poll-interval"
inputMode="numeric"
value={value}
placeholder={String(DEFAULT_POLL_INTERVAL_S)}
onChange={(e) => onChange(e.target.value)}
aria-invalid={error ? true : undefined}
data-testid="edit-poll-interval"
/>
{error && (
<p role="alert" className="mt-1 text-xs text-down" data-testid="edit-poll-interval-error">
{error}
</p>
)}
</FormField>
)
}

View File

@@ -31,6 +31,10 @@ export function SystemPanel({ d }: { d: DeviceView }) {
<Row label="Uptime">
<span className="num">{formatDuration(d.uptime_seconds)}</span>
</Row>
<Row label="Poll interval">
<span className="num">{formatDuration(d.poll_interval_effective_s)}</span>
{d.poll_interval_s > 0 && <span className="text-muted-foreground"> (custom)</span>}
</Row>
<Row label="Mgmt IP">
<span className="mono">{d.mgmt_ip || '—'}</span>
</Row>