Files
nmon/internal/snmprec/write.go

93 lines
2.2 KiB
Go

package snmprec
import (
"bufio"
"encoding/hex"
"fmt"
"io"
"strconv"
"strings"
"github.com/gosnmp/gosnmp"
)
var tags = map[gosnmp.Asn1BER]string{
gosnmp.Integer: "2", gosnmp.OctetString: "4", gosnmp.Null: "5", gosnmp.ObjectIdentifier: "6",
gosnmp.IPAddress: "64", gosnmp.Counter32: "65", gosnmp.Gauge32: "66", gosnmp.TimeTicks: "67",
gosnmp.Opaque: "68", gosnmp.Counter64: "70",
}
// Write writes rec in snmpsim .snmprec format, in OID order.
func Write(w io.Writer, rec *Recording) error {
bw := bufio.NewWriter(w)
for _, r := range rec.Records() {
tag, ok := tags[r.Type]
if !ok {
return fmt.Errorf("snmprec: %s: unsupported type %v", r.OID, r.Type)
}
var val string
switch {
case r.Dyn != nil:
tag += ":numeric"
val = numeric(r.Dyn)
default:
var err error
if tag, val, err = format(r, tag); err != nil {
return err
}
}
if _, err := bw.WriteString(r.OID + "|" + tag + "|" + val + "\n"); err != nil {
return err
}
}
return bw.Flush()
}
func numeric(d *Dynamic) string {
s := "rate=" + strconv.FormatFloat(d.Rate, 'f', -1, 64) + ",initial=" + strconv.FormatUint(d.Initial, 10)
if d.Wrap != 0 {
s += ",wrap=" + strconv.FormatUint(d.Wrap, 10)
}
if d.ResetAt > 0 {
s += ",reset_at=" + strconv.FormatFloat(d.ResetAt.Seconds(), 'f', -1, 64)
}
return s
}
func format(r Record, tag string) (string, string, error) {
switch v := r.Value.(type) {
case nil:
return tag, "", nil
case int:
return tag, strconv.Itoa(v), nil
case uint32:
return tag, strconv.FormatUint(uint64(v), 10), nil
case uint64:
return tag, strconv.FormatUint(v, 10), nil
case string:
return tag, v, nil
case []byte:
if r.Type == gosnmp.OctetString && printable(v) {
return tag, string(v), nil
}
return tag + "x", hex.EncodeToString(v), nil
}
return "", "", fmt.Errorf("snmprec: %s: unsupported value %T", r.OID, r.Value)
}
// printable reports whether b survives a text line unchanged.
func printable(b []byte) bool {
if len(b) == 0 {
return true
}
if b[0] == ' ' || b[len(b)-1] == ' ' || strings.ContainsRune(string(b), '|') {
return false
}
for _, c := range b {
if c < 0x20 || c > 0x7e {
return false
}
}
return true
}