From 55265698e9a0278129181755b34cba6b4db528e5 Mon Sep 17 00:00:00 2001 From: Vibe Coder Date: Sat, 24 Oct 2026 18:55:43 +0000 Subject: [PATCH 1/3] Add range, p95 and a summary line to the port graph grid and expanded rows The Ports grid only drew a fixed 24 h graph per port, and an expanded row was fixed at 24 h too, so there was no way to look at 1 h, 7 d or 30 d the way LibreNMS allows, and the grid never showed p95. The grid now has one range picker (1 h to 1 y) and a p95 toggle shared by every card, and each card shows current, average and p95 per direction under the graph. An expanded row gets its own range picker and p95 toggle, and "Open graph view" keeps the chosen range. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017TuKgyKve2XLFtrrXWMi2w --- web/src/components/GraphCell.tsx | 94 +++++++++++++++++------------ web/src/components/GraphSummary.tsx | 34 +++++++++++ web/src/pages/device/GraphGrid.tsx | 36 ++++++++--- web/src/pages/device/IfRow.tsx | 24 +++++--- 4 files changed, 134 insertions(+), 54 deletions(-) create mode 100644 web/src/components/GraphSummary.tsx diff --git a/web/src/components/GraphCell.tsx b/web/src/components/GraphCell.tsx index ede0159..a2b924d 100644 --- a/web/src/components/GraphCell.tsx +++ b/web/src/components/GraphCell.tsx @@ -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 = { spark: 44, compact: 130, full: 380 } + +/** Whether the element has come within 400 px of the viewport (latched). */ +function useNearViewport() { const ref = useRef(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 (
- {active && q.error ? ( - - ) : active ? ( - - ) : null} + {active && }
) }) + +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 + return ( + <> + + {p.summary && } + + ) +} diff --git a/web/src/components/GraphSummary.tsx b/web/src/components/GraphSummary.tsx new file mode 100644 index 0000000..84316ac --- /dev/null +++ b/web/src/components/GraphSummary.tsx @@ -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 ( + + + {name} + + {formatBps(s.current)} + + + avg {formatBps(s.avg)} + + + p95 {formatBps(p95)} + + + ) +} + +/** 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 ( +
+ + +
+ ) +} diff --git a/web/src/pages/device/GraphGrid.tsx b/web/src/pages/device/GraphGrid.tsx index 79ed689..8866ccd 100644 --- a/web/src/pages/device/GraphGrid.tsx +++ b/web/src/pages/device/GraphGrid.tsx @@ -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 (
- + {i.ifname} {i.ifalias} - {i.unreliable ? 'n/a' : `${formatBps(i.in_bps)} / ${formatBps(i.out_bps)}`} + + {i.unreliable ? 'n/a' : `${formatBps(i.in_bps)} / ${formatBps(i.out_bps)}`} +
- +
) }) -/** 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('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 ( -
- {rows.map((i, idx) => ( - - ))} +
+
+ + + p95 + +
+
+ {rows.map((i, idx) => ( + + ))} +
) } diff --git a/web/src/pages/device/IfRow.tsx b/web/src/pages/device/IfRow.tsx index f2c4632..cb81da4 100644 --- a/web/src/pages/device/IfRow.tsx +++ b/web/src/pages/device/IfRow.tsx @@ -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('24h') + const [showP95, setShowP95] = useState(true) return ( -
- - Last 24 h · {i.ifname} - - +
+
+ {i.ifname} + + + p95 + +
+ Open graph view
- + ) From 881f0ae3b132772ed95751b17fc321b741bb04e9 Mon Sep 17 00:00:00 2001 From: Vibe Coder Date: Sat, 24 Oct 2026 18:55:43 +0000 Subject: [PATCH 2/3] Poll every 300 s by default, with a per-device poll interval The owner wants LibreNMS-like 5-minute polling by default and the option to poll a given device faster or slower. Devices gain poll_interval_s (new migration; 0 means the default, otherwise 30 to 3600 s), settable in the device edit dialog and through PUT /api/v1/devices/{slug}; the poller picks it up on the next inventory refresh. Everything that assumed one-minute samples now follows the device's interval: graph and p95 rate windows are at least two polls, the max series uses irate, the up-series lookback, the no_data warning, the "unheard of for three polls" fallback and the rollup's thin-window check. interface_errors widens to 10 m. profiletest keeps 60 s because the expect budgets are keyed by the 1m group. Recorded as DEVIATIONS 49. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017TuKgyKve2XLFtrrXWMi2w --- cmd/nmon/serve.go | 2 +- docs/DEVIATIONS.md | 1 + docs/operations.md | 6 ++- internal/alert/rules.go | 8 ++-- internal/api/api.go | 5 ++- internal/api/detail_test.go | 2 +- internal/api/device_metrics_graph.go | 6 +-- internal/api/device_poll_interval_test.go | 30 +++++++++++++ internal/api/device_put.go | 33 +++++++++++--- internal/api/device_view.go | 43 +++++++++++-------- internal/api/graph.go | 8 ++-- internal/api/graph_fetch.go | 22 +++++++--- internal/api/graph_p95.go | 2 +- internal/api/graph_test.go | 4 +- internal/api/overview.go | 6 +-- internal/api/rates.go | 13 +++--- internal/api/reach.go | 5 ++- internal/app/rollup.go | 2 +- internal/config/config.go | 2 +- internal/poller/plan.go | 2 +- internal/poller/poller.go | 4 +- internal/profiletest/poll.go | 5 ++- internal/reach/config.go | 4 +- internal/reach/evaluator.go | 2 +- internal/reach/harness_test.go | 25 +++++------ internal/reach/policy.go | 2 +- internal/reach/policy_test.go | 1 + internal/reach/types.go | 2 + internal/rollup/devices.go | 4 +- internal/rollup/fakes_test.go | 2 +- internal/rollup/fivemin.go | 9 +++- internal/rollup/job.go | 4 +- .../20261024000015_device_poll_interval.go | 19 ++++++++ internal/store/device.go | 2 +- internal/store/models.go | 2 + internal/store/pollinterval.go | 22 ++++++++++ openapi.json | 27 ++++++++++-- web/e2e/fixtures/generate.ts | 2 + web/e2e/mock/mgmt.ts | 4 ++ web/src/api/schema.d.ts | 21 +++++++-- web/src/lib/deviceForm.test.ts | 10 +++++ web/src/lib/deviceForm.ts | 16 +++++++ web/src/pages/device/EditDialog.tsx | 7 ++- web/src/pages/device/PollIntervalField.tsx | 25 +++++++++++ web/src/pages/device/overview/SystemPanel.tsx | 4 ++ 45 files changed, 329 insertions(+), 98 deletions(-) create mode 100644 internal/api/device_poll_interval_test.go create mode 100644 internal/store/20261024000015_device_poll_interval.go create mode 100644 internal/store/pollinterval.go create mode 100644 web/src/pages/device/PollIntervalField.tsx diff --git a/cmd/nmon/serve.go b/cmd/nmon/serve.go index 28a659c..1dfd174 100644 --- a/cmd/nmon/serve.go +++ b/cmd/nmon/serve.go @@ -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) diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index e065c4b..f8856de 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -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 `/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 | diff --git a/docs/operations.md b/docs/operations.md index 6e049b5..d006a84 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -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 `@` (v3: context `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 `@` (v3: context `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. diff --git a/internal/alert/rules.go b/internal/alert/rules.go index 316f011..afb1041 100644 --- a/internal/alert/rules.go +++ b/internal/alert/rules.go @@ -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}}%).`, }, { diff --git a/internal/api/api.go b/internal/api/api.go index e347e7b..a3894b4 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -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) diff --git a/internal/api/detail_test.go b/internal/api/detail_test.go index b4c9315..e2a6fce 100644 --- a/internal/api/detail_test.go +++ b/internal/api/detail_test.go @@ -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 || diff --git a/internal/api/device_metrics_graph.go b/internal/api/device_metrics_graph.go index d1eabcc..2f97fc2 100644 --- a/internal/api/device_metrics_graph.go +++ b/internal/api/device_metrics_graph.go @@ -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+`)`, "" } diff --git a/internal/api/device_poll_interval_test.go b/internal/api/device_poll_interval_test.go new file mode 100644 index 0000000..b502b91 --- /dev/null +++ b/internal/api/device_poll_interval_test.go @@ -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) +} diff --git a/internal/api/device_put.go b/internal/api/device_put.go index c2d2092..a4d60e5 100644 --- a/internal/api/device_put.go +++ b/internal/api/device_put.go @@ -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 { diff --git a/internal/api/device_view.go b/internal/api/device_view.go index e4b4a71..f516125 100644 --- a/internal/api/device_view.go +++ b/internal/api/device_view.go @@ -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{}, diff --git a/internal/api/graph.go b/internal/api/graph.go index 7068966..668426c 100644 --- a/internal/api/graph.go +++ b/internal/api/graph.go @@ -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} } diff --git a/internal/api/graph_fetch.go b/internal/api/graph_fetch.go index 0dcaf95..87eaea5 100644 --- a/internal/api/graph_fetch.go +++ b/internal/api/graph_fetch.go @@ -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 diff --git a/internal/api/graph_p95.go b/internal/api/graph_p95.go index 69144ef..5b558dc 100644 --- a/internal/api/graph_p95.go +++ b/internal/api/graph_p95.go @@ -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 diff --git a/internal/api/graph_test.go b/internal/api/graph_test.go index e216457..4f20d37 100644 --- a/internal/api/graph_test.go +++ b/internal/api/graph_test.go @@ -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) diff --git a/internal/api/overview.go b/internal/api/overview.go index 5236081..e6ef0d4 100644 --- a/internal/api/overview.go +++ b/internal/api/overview.go @@ -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 { diff --git a/internal/api/rates.go b/internal/api/rates.go index 5943f91..1ed129b 100644 --- a/internal/api/rates.go +++ b/internal/api/rates.go @@ -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 diff --git a/internal/api/reach.go b/internal/api/reach.go index 53ba9d9..130ffdb 100644 --- a/internal/api/reach.go +++ b/internal/api/reach.go @@ -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 } diff --git a/internal/app/rollup.go b/internal/app/rollup.go index b49a659..9e09dd6 100644 --- a/internal/app/rollup.go +++ b/internal/app/rollup.go @@ -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(), }) diff --git a/internal/config/config.go b/internal/config/config.go index c3b8ca7..82a10b5 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -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 diff --git a/internal/poller/plan.go b/internal/poller/plan.go index b2d6732..e3fb850 100644 --- a/internal/poller/plan.go +++ b/internal/poller/plan.go @@ -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) } diff --git a/internal/poller/poller.go b/internal/poller/poller.go index 99eb191..1d97e80 100644 --- a/internal/poller/poller.go +++ b/internal/poller/poller.go @@ -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 diff --git a/internal/profiletest/poll.go b/internal/profiletest/poll.go index f57ae16..0a1ed63 100644 --- a/internal/profiletest/poll.go +++ b/internal/profiletest/poll.go @@ -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() diff --git a/internal/reach/config.go b/internal/reach/config.go index 9e0b8f3..d1c57be 100644 --- a/internal/reach/config.go +++ b/internal/reach/config.go @@ -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 diff --git a/internal/reach/evaluator.go b/internal/reach/evaluator.go index 58b071f..67390dd 100644 --- a/internal/reach/evaluator.go +++ b/internal/reach/evaluator.go @@ -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) } diff --git a/internal/reach/harness_test.go b/internal/reach/harness_test.go index 9db6b58..a1bc0fd 100644 --- a/internal/reach/harness_test.go +++ b/internal/reach/harness_test.go @@ -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) diff --git a/internal/reach/policy.go b/internal/reach/policy.go index a9d2dac..59dd033 100644 --- a/internal/reach/policy.go +++ b/internal/reach/policy.go @@ -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) } diff --git a/internal/reach/policy_test.go b/internal/reach/policy_test.go index 3be0d08..fff9540 100644 --- a/internal/reach/policy_test.go +++ b/internal/reach/policy_test.go @@ -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() diff --git a/internal/reach/types.go b/internal/reach/types.go index de04136..1bc8a6d 100644 --- a/internal/reach/types.go +++ b/internal/reach/types.go @@ -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 } diff --git a/internal/rollup/devices.go b/internal/rollup/devices.go index 7f4d107..37c59d6 100644 --- a/internal/rollup/devices.go +++ b/internal/rollup/devices.go @@ -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 diff --git a/internal/rollup/fakes_test.go b/internal/rollup/fakes_test.go index 859a0eb..1ed1c35 100644 --- a/internal/rollup/fakes_test.go +++ b/internal/rollup/fakes_test.go @@ -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) } diff --git a/internal/rollup/fivemin.go b/internal/rollup/fivemin.go index 5ef3d60..93edfbf 100644 --- a/internal/rollup/fivemin.go +++ b/internal/rollup/fivemin.go @@ -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"]] diff --git a/internal/rollup/job.go b/internal/rollup/job.go index 9727a7c..516dbd7 100644 --- a/internal/rollup/job.go +++ b/internal/rollup/job.go @@ -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 { diff --git a/internal/store/20261024000015_device_poll_interval.go b/internal/store/20261024000015_device_poll_interval.go new file mode 100644 index 0000000..00133e8 --- /dev/null +++ b/internal/store/20261024000015_device_poll_interval.go @@ -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 + }) +} diff --git a/internal/store/device.go b/internal/store/device.go index 825d1f2..e3e10ff 100644 --- a/internal/store/device.go +++ b/internal/store/device.go @@ -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) diff --git a/internal/store/models.go b/internal/store/models.go index 4e47794..1548542 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -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. diff --git a/internal/store/pollinterval.go b/internal/store/pollinterval.go new file mode 100644 index 0000000..b74fcd0 --- /dev/null +++ b/internal/store/pollinterval.go @@ -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 +} diff --git a/openapi.json b/openapi.json index 17200cc..d84c55d 100644 --- a/openapi.json +++ b/openapi.json @@ -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" } }, diff --git a/web/e2e/fixtures/generate.ts b/web/e2e/fixtures/generate.ts index 55a6966..135c5b7 100644 --- a/web/e2e/fixtures/generate.ts +++ b/web/e2e/fixtures/generate.ts @@ -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], diff --git a/web/e2e/mock/mgmt.ts b/web/e2e/mock/mgmt.ts index 8a47281..f2953ce 100644 --- a/web/e2e/mock/mgmt.ts +++ b/web/e2e/mock/mgmt.ts @@ -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 = { 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 => (s === undefined ? {} : { poll_interval_s: s, poll_interval_effective_s: s || 300 }) + const REPORT: S['DiscoverView'] = { profile: 'cisco-ios', partial: false, diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index 6e52faf..dea5db3 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -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; diff --git a/web/src/lib/deviceForm.test.ts b/web/src/lib/deviceForm.test.ts index 0930817..eece1c4 100644 --- a/web/src/lib/deviceForm.test.ts +++ b/web/src/lib/deviceForm.test.ts @@ -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') diff --git a/web/src/lib/deviceForm.ts b/web/src/lib/deviceForm.ts index a901674..0d2c027 100644 --- a/web/src/lib/deviceForm.ts +++ b/web/src/lib/deviceForm.ts @@ -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) }), } } diff --git a/web/src/pages/device/EditDialog.tsx b/web/src/pages/device/EditDialog.tsx index 4bd9760..85a612a 100644 --- a/web/src/pages/device/EditDialog.tsx +++ b/web/src/pages/device/EditDialog.tsx @@ -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 }) { {err && } {form.profile !== null && set({ profile })} />} + {form.pollInterval !== undefined && set({ pollInterval })} error={errors.pollInterval} />} {d.kind === 'network' && } {edit.error && !err && } diff --git a/web/src/pages/device/PollIntervalField.tsx b/web/src/pages/device/PollIntervalField.tsx new file mode 100644 index 0000000..6d384c2 --- /dev/null +++ b/web/src/pages/device/PollIntervalField.tsx @@ -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 ( + + onChange(e.target.value)} + aria-invalid={error ? true : undefined} + data-testid="edit-poll-interval" + /> + {error && ( +

+ {error} +

+ )} +
+ ) +} diff --git a/web/src/pages/device/overview/SystemPanel.tsx b/web/src/pages/device/overview/SystemPanel.tsx index cce17b0..d465b46 100644 --- a/web/src/pages/device/overview/SystemPanel.tsx +++ b/web/src/pages/device/overview/SystemPanel.tsx @@ -31,6 +31,10 @@ export function SystemPanel({ d }: { d: DeviceView }) { {formatDuration(d.uptime_seconds)} + + {formatDuration(d.poll_interval_effective_s)} + {d.poll_interval_s > 0 && (custom)} + {d.mgmt_ip || '—'} From 273c6b541bb0db2df59f75f4d56a00680b9adcdc Mon Sep 17 00:00:00 2001 From: Vibe Coder Date: Sat, 24 Oct 2026 18:55:43 +0000 Subject: [PATCH 3/3] Run CI on the Gitea debian-13 runner The remote is a Gitea server whose only runner label is debian-13, so the ubuntu-latest jobs never got picked up. The arm64 test leg is dropped because no arm runner exists there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017TuKgyKve2XLFtrrXWMi2w --- .github/workflows/ci.yml | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a39168c..5fcdc1a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 }