Files
nmon/internal/snmprec/parse.go

219 lines
6.0 KiB
Go

package snmprec
import (
"bufio"
"encoding/hex"
"fmt"
"io"
"math"
"net/netip"
"os"
"strconv"
"strings"
"time"
"github.com/gosnmp/gosnmp"
)
// Load reads a .snmprec file.
func Load(path string) (*Recording, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() { _ = f.Close() }() // read-only file: a close error cannot lose data
rec, err := Parse(f)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return rec, nil
}
// Parse reads the snmpsim .snmprec format: OID|TAG|VALUE per line.
func Parse(r io.Reader) (*Recording, error) {
rec, _, err := parse(r, false)
return rec, err
}
// LoadLenient reads a recording made by other tools (for example the
// LibreNMS snmpsim collection) and skips what the agent cannot serve instead of
// failing: lines with unknown tags, snmpsim's "e" (evaluated) values and
// unsupported variations. A 32-bit value above 2^32-1 wraps. It returns the
// number of lines skipped.
func LoadLenient(path string) (*Recording, int, error) {
f, err := os.Open(path)
if err != nil {
return nil, 0, err
}
defer func() { _ = f.Close() }() // read-only file: a close error cannot lose data
rec, skipped, err := parse(f, true)
if err != nil {
return nil, 0, fmt.Errorf("%s: %w", path, err)
}
return rec, skipped, nil
}
func parse(r io.Reader, lenient bool) (*Recording, int, error) {
skipped := 0
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 64<<10), 4<<20)
var recs []Record
for n := 1; sc.Scan(); n++ {
line := strings.TrimSuffix(sc.Text(), "\r")
if strings.TrimSpace(line) == "" || strings.HasPrefix(line, "#") {
continue
}
rec, err := parseLine(line, lenient)
if err != nil {
if lenient {
skipped++
continue
}
return nil, 0, fmt.Errorf("line %d: %w", n, err)
}
recs = append(recs, rec)
}
if err := sc.Err(); err != nil {
return nil, 0, err
}
return NewRecording(recs), skipped, nil
}
func parseLine(line string, lenient bool) (Record, error) {
oid, rest, ok := strings.Cut(line, "|")
if !ok {
return Record{}, fmt.Errorf("want OID|TAG|VALUE")
}
tag, val, ok := strings.Cut(rest, "|")
if !ok {
return Record{}, fmt.Errorf("want OID|TAG|VALUE")
}
oid = strings.TrimPrefix(strings.TrimSpace(oid), ".")
if !ValidOID(oid) {
return Record{}, fmt.Errorf("bad OID %q", oid)
}
tag, variation, _ := strings.Cut(tag, ":")
isHex := strings.HasSuffix(tag, "x")
code, err := strconv.Atoi(strings.TrimSuffix(tag, "x"))
if err != nil {
return Record{}, fmt.Errorf("bad tag %q", tag)
}
typ, ok := tagTypes[code]
if !ok {
return Record{}, fmt.Errorf("unsupported tag %q", tag)
}
rec := Record{OID: oid, Type: typ}
if variation != "" {
rec.Dyn, err = parseVariation(typ, code, variation, val)
return rec, err
}
rec.Value, err = parseValue(rec.Type, isHex, val, lenient)
return rec, err
}
// tagTypes maps the snmprec numeric tags to the SNMP types the agent serves.
var tagTypes = map[int]gosnmp.Asn1BER{
2: gosnmp.Integer, 4: gosnmp.OctetString, 5: gosnmp.Null, 6: gosnmp.ObjectIdentifier,
64: gosnmp.IPAddress, 65: gosnmp.Counter32, 66: gosnmp.Gauge32, 67: gosnmp.TimeTicks,
68: gosnmp.Opaque, 70: gosnmp.Counter64,
}
// parseVariation handles the only supported variation, ":numeric", which makes
// a numeric tag count or wander over time.
func parseVariation(typ gosnmp.Asn1BER, code int, variation, val string) (*Dynamic, error) {
if variation != "numeric" {
return nil, fmt.Errorf("unsupported variation %q", variation)
}
switch typ {
case gosnmp.Integer, gosnmp.Counter32, gosnmp.Gauge32, gosnmp.TimeTicks, gosnmp.Counter64:
return parseNumeric(val)
default:
return nil, fmt.Errorf("numeric variation on tag %d", code)
}
}
func parseValue(t gosnmp.Asn1BER, isHex bool, val string, lenient bool) (any, error) {
switch t {
case gosnmp.Integer:
v, err := strconv.ParseInt(val, 10, 32)
return int(v), err
case gosnmp.OctetString, gosnmp.Opaque:
if isHex {
return hex.DecodeString(val)
}
return []byte(val), nil
case gosnmp.Null:
return nil, nil
case gosnmp.ObjectIdentifier:
val = strings.TrimPrefix(strings.TrimSpace(val), ".")
if !ValidOID(val) {
return nil, fmt.Errorf("bad OID value %q", val)
}
return val, nil
case gosnmp.IPAddress:
return parseIPAddress(isHex, val)
case gosnmp.Counter64:
return strconv.ParseUint(val, 10, 64)
default: // Counter32, Gauge32, TimeTicks
return parseUint32(val, lenient)
}
}
func parseIPAddress(isHex bool, val string) (any, error) {
if isHex {
b, err := hex.DecodeString(val)
if err != nil || len(b) != 4 {
return nil, fmt.Errorf("bad IpAddress %q", val)
}
return netip.AddrFrom4([4]byte(b)).String(), nil
}
a, err := netip.ParseAddr(strings.TrimSpace(val))
if err != nil || !a.Is4() {
return nil, fmt.Errorf("bad IpAddress %q", val)
}
return a.String(), nil
}
// parseUint32 parses a 32-bit unsigned value; lenient mode accepts larger
// numbers and wraps them, as other recording tools produce them.
func parseUint32(val string, lenient bool) (any, error) {
if lenient {
v, err := strconv.ParseUint(strings.TrimSpace(val), 10, 64)
return uint32(v), err // wraps
}
v, err := strconv.ParseUint(val, 10, 32)
return uint32(v), err
}
func parseNumeric(s string) (*Dynamic, error) {
d := &Dynamic{}
for _, kv := range strings.Split(s, ",") {
k, v, ok := strings.Cut(strings.TrimSpace(kv), "=")
if !ok {
return nil, fmt.Errorf("bad numeric option %q", kv)
}
var err error
switch k {
case "rate":
d.Rate, err = strconv.ParseFloat(v, 64)
if err == nil && (d.Rate < 0 || math.IsNaN(d.Rate) || math.IsInf(d.Rate, 0)) {
err = fmt.Errorf("must be non-negative")
}
case "initial":
d.Initial, err = strconv.ParseUint(v, 10, 64)
case "wrap":
d.Wrap, err = strconv.ParseUint(v, 10, 64)
case "reset_at":
var sec float64
sec, err = strconv.ParseFloat(v, 64)
d.ResetAt = time.Duration(sec * float64(time.Second))
default:
return nil, fmt.Errorf("unsupported numeric option %q", k)
}
if err != nil {
return nil, fmt.Errorf("numeric option %s: %w", k, err)
}
}
return d, nil
}