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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017TuKgyKve2XLFtrrXWMi2w
187 lines
7.3 KiB
TypeScript
187 lines
7.3 KiB
TypeScript
import type { AddDeviceBody, ApiError, DeviceKind, PutDeviceBody, SnmpBody } from '@/api/client'
|
|
|
|
export type SnmpVersion = 'v1' | 'v2c' | 'v3'
|
|
|
|
/** The SNMP credential as typed into the form; every field is text. */
|
|
export interface SnmpForm {
|
|
version: SnmpVersion
|
|
community: string
|
|
v3User: string
|
|
authProto: string
|
|
authPass: string
|
|
privProto: string
|
|
privPass: string
|
|
context: string
|
|
port: string
|
|
}
|
|
|
|
export const AUTH_PROTOS = ['SHA256', 'SHA', 'SHA224', 'SHA384', 'SHA512', 'MD5']
|
|
export const PRIV_PROTOS = ['AES', 'AES192', 'AES256', 'DES']
|
|
export const KINDS: DeviceKind[] = ['network', 'vm', 'container', 'check_only']
|
|
|
|
export const emptySnmp = (): SnmpForm => ({ version: 'v2c', community: '', v3User: '', authProto: 'SHA256', authPass: '', privProto: 'AES', privPass: '', context: '', port: '' })
|
|
|
|
export interface AddForm {
|
|
name: string
|
|
addresses: string
|
|
kind: DeviceKind
|
|
site: string
|
|
role: string
|
|
snmp: SnmpForm
|
|
}
|
|
|
|
export const emptyAdd = (): AddForm => ({ name: '', addresses: '', kind: 'network', site: '', role: '', snmp: emptySnmp() })
|
|
|
|
/** Field name -> message. `form` holds errors that belong to no single field. */
|
|
export type FieldErrors = Record<string, string>
|
|
|
|
const V4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
|
|
|
|
/** True for a literal IPv4 or IPv6 address (a zone suffix is tolerated; the server drops it). */
|
|
export function isIp(s: string): boolean {
|
|
if (V4.test(s)) return true
|
|
const bare = s.split('%')[0] ?? ''
|
|
if (!bare.includes(':') || !/^[0-9a-fA-F:.]+$/.test(bare)) return false
|
|
try {
|
|
return new URL(`http://[${bare}]/`).hostname !== ''
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
|
|
/** Splits "a, b\nc" into addresses and the entries that are not IPs. Duplicates are dropped. */
|
|
export function parseAddresses(text: string): { addrs: string[]; invalid: string[] } {
|
|
const parts = text
|
|
.split(/[\s,;]+/)
|
|
.map((x) => x.trim())
|
|
.filter(Boolean)
|
|
const uniq = [...new Set(parts)]
|
|
return { addrs: uniq.filter(isIp), invalid: uniq.filter((x) => !isIp(x)) }
|
|
}
|
|
|
|
/** Client-side checks of the SNMP section; mirrors what the server rejects with 422. */
|
|
export function validateSnmp(f: SnmpForm): FieldErrors {
|
|
const e: FieldErrors = {}
|
|
if (f.version === 'v3') {
|
|
if (!f.v3User.trim()) e['snmp.v3_user'] = 'The v3 user name is required.'
|
|
} else if (!f.community) e['snmp.community'] = 'The community is required.'
|
|
if (f.port !== '') {
|
|
const n = Number(f.port)
|
|
if (!Number.isInteger(n) || n < 1 || n > 65535) e['snmp.port'] = 'The port must be 1 to 65535.'
|
|
}
|
|
return e
|
|
}
|
|
|
|
export function validateAdd(f: AddForm): FieldErrors {
|
|
const e: FieldErrors = f.kind === 'network' ? validateSnmp(f.snmp) : {}
|
|
if (!f.name.trim()) e.name = 'A name is required.'
|
|
const { addrs, invalid } = parseAddresses(f.addresses)
|
|
if (invalid.length) e.addresses = `Not an IP address: ${invalid.join(', ')}`
|
|
else if (!addrs.length) e.addresses = 'At least one management address is required.'
|
|
return e
|
|
}
|
|
|
|
/** The SNMP block of a request. Secrets that do not apply to the chosen version are never sent. */
|
|
export function buildSnmp(f: SnmpForm): SnmpBody {
|
|
const port = f.port === '' ? {} : { port: Number(f.port) }
|
|
if (f.version !== 'v3') return { version: f.version, community: f.community, ...port }
|
|
return {
|
|
version: 'v3',
|
|
v3_user: f.v3User.trim(),
|
|
v3_auth_proto: f.authProto,
|
|
v3_auth_pass: f.authPass,
|
|
v3_priv_proto: f.privProto,
|
|
v3_priv_pass: f.privPass,
|
|
...(f.context && { v3_context: f.context }),
|
|
...port,
|
|
}
|
|
}
|
|
|
|
/** A reattach choice from a 409: restore a retired device, or insist on a new one. */
|
|
export type AddChoice = { reattach: string } | { createNew: true } | undefined
|
|
|
|
export function buildAddPayload(f: AddForm, choice?: AddChoice): AddDeviceBody {
|
|
const body: AddDeviceBody = { name: f.name.trim(), addresses: parseAddresses(f.addresses).addrs, kind: f.kind, site: f.site.trim(), role: f.role.trim() }
|
|
if (f.kind === 'network') body.snmp = buildSnmp(f.snmp)
|
|
if (choice && 'reattach' in choice) body.reattach = choice.reattach
|
|
if (choice && 'createNew' in choice) body.create_new = true
|
|
return body
|
|
}
|
|
|
|
export interface EditForm {
|
|
name: string
|
|
site: string
|
|
role: string
|
|
enabled: boolean
|
|
parents: string[]
|
|
replaceSnmp: boolean
|
|
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 {
|
|
return {
|
|
name: f.name.trim(),
|
|
site: f.site.trim(),
|
|
role: f.role.trim(),
|
|
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) }),
|
|
}
|
|
}
|
|
|
|
export interface Candidate {
|
|
slug: string
|
|
name: string
|
|
retired_at: string
|
|
}
|
|
|
|
/** The retired devices a 409 offers, empty when the error is something else. */
|
|
export function reattachCandidates(e: unknown): Candidate[] {
|
|
const b = (e as Partial<ApiError> | null)?.body as { reattach_candidates?: Candidate[] } | undefined
|
|
return (e as Partial<ApiError> | null)?.status === 409 && Array.isArray(b?.reattach_candidates) ? b.reattach_candidates : []
|
|
}
|
|
|
|
export type AddFailure = { kind: 'fields'; fields: FieldErrors } | { kind: 'unreachable'; detail: string } | { kind: 'other' }
|
|
|
|
/** Field name of a problem location such as "body.snmp.community" or "body.addresses[0]". */
|
|
function fieldOf(location: string | undefined): string {
|
|
return (location ?? '').replace(/^body\./, '').replace(/\[\d+\]/g, '')
|
|
}
|
|
|
|
/** Sorts a failed add into field errors (422 validation), an unreachable device (422 snmp / 502) or anything else. */
|
|
export function classifyAddFailure(e: Pick<ApiError, 'status' | 'detail' | 'items'>): AddFailure {
|
|
const detail = e.detail ?? ''
|
|
if (e.status === 502 || (e.status === 422 && detail.startsWith('snmp:'))) return { kind: 'unreachable', detail }
|
|
if (e.status !== 422) return { kind: 'other' }
|
|
const fields: FieldErrors = {}
|
|
for (const it of e.items) fields[fieldOf(it.location) || 'form'] ??= it.message
|
|
const m = /^(snmp\.[a-z0-9_]+) (.*)$/.exec(detail)
|
|
if (m) fields[m[1] as string] = `${m[1]} ${m[2]}`
|
|
else if (detail && !Object.keys(fields).length) fields.form = detail
|
|
return { kind: 'fields', fields }
|
|
}
|
|
|
|
/** "Added core1: 24 interfaces, profile generic". */
|
|
export function addedMessage(name: string, interfaces: number, profile: string): string {
|
|
return `Added ${name}: ${interfaces} ${interfaces === 1 ? 'interface' : 'interfaces'}, profile ${profile}`
|
|
}
|