snmp

package
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 28 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package snmp polls devices over SNMP v1, v2c and v3, receives traps and turns both into metrics and logs. OID sets come from YAML manifests (integrations/snmp/, embedded copies in manifests/), hand-written or compiled from vendor MIBs by package mibc (`wtctl mib compile`).

Everything that names a device or holds a credential (address, community, v3 users and passphrases) comes from the agent's own file. None of it is exported, logged or put in an error.

Index

Constants

View Source
const MaxSubnetHosts = 4096

MaxSubnetHosts bounds a discovery sweep.

View Source
const MaxVarbinds = 10000

MaxVarbinds caps the varbinds read from one device in one poll.

Variables

This section is empty.

Functions

func EmitLinks(out sink.Sink, local Device, ns []Neighbor, states map[string]PortState, at time.Time)

EmitLinks is EmitNeighbors plus the local port's state (linkstatus.go): link.oper_status and link.utilization (0..1) when known.

func EmitNeighbors

func EmitNeighbors(out sink.Sink, local Device, ns []Neighbor, at time.Time)

EmitNeighbors sends one `network.neighbor` log record per adjacency; the worker turns them into `entity_links` of kind lldp or cdp between `network_device` entities.

func Manifests

func Manifests(dir string) (map[string]Manifest, error)

Manifests returns the manifests by name: the embedded ones, then any *.yaml in dir (local config only) replacing those of the same name.

func PollNeighbors

func PollNeighbors(ctx context.Context, t Target, out sink.Sink, at time.Time) error

PollNeighbors walks one device and emits its adjacencies. Whatever Walk read before an error is used (a device without CDP still gives its LLDP neighbours); only an empty walk is an error.

func PollTarget

func PollTarget(ctx context.Context, t Target, ms []Manifest, rates *Rates, out sink.Sink, at time.Time) error

PollTarget polls one device once and writes its metrics.

func Run

func Run(ctx context.Context, raw json.RawMessage, out sink.Sink) error

Run polls and listens until ctx ends.

func RunTopology

func RunTopology(ctx context.Context, raw json.RawMessage, out sink.Sink) error

RunTopology is the `topology` agent module: every interval, walk each configured device, each poll under its own deadline.

func SubnetHosts

func SubnetHosts(cidr string) ([]netip.Addr, error)

SubnetHosts lists the host addresses of a CIDR (network and broadcast excluded for IPv4).

func SysInfo

func SysInfo(ctx context.Context, t Target) (objectID, name, descr string, err error)

SysInfo reads sysObjectID.0, sysName.0 and sysDescr.0 of a device (discovery, INF-021).

func TrapName

func TrapName(oid string) string

TrapName returns the symbolic name of a trap OID, or "" when unknown.

func Walk

func Walk(ctx context.Context, t Target, oids []string, max int) ([]gosnmp.SnmpPDU, error)

Walk reads the subtrees under oids from the device, at most max varbinds in all (max <= 0 or above MaxVarbinds means MaxVarbinds). ctx bounds the whole walk. When a subtree fails the varbinds read so far are still returned together with the first error; error text never contains the address or a credential.

Types

type Config

type Config struct {
	Enabled     *bool       `json:"enabled"`
	Interval    string      `json:"interval"`     // default 60s, at least 10s
	PollTimeout string      `json:"poll_timeout"` // deadline for one device's whole poll, default 30s
	ManifestDir string      `json:"manifest_dir"` // extra or replacement manifests
	ProfileDir  string      `json:"profile_dir"`  // extra or replacement vendor profiles
	Targets     []Target    `json:"targets"`
	Trap        *TrapConfig `json:"trap"`
}

Config is the snmp module's config. Remote config may only set Enabled and Interval; targets, credentials, the manifest directory and the trap listener exist only in the agent's file.

type Device

type Device struct {
	ID, Name, Addr string
}

Device is one end of an adjacency. ID is the stable key (LLDP chassis id, CDP device id, or the operator's target name for the polled device); Addr is the management address a neighbour announced, if any. The polled device's own address is never part of it.

func LocalDevice

func LocalDevice(pdus []gosnmp.SnmpPDU, targetName string) Device

LocalDevice is the polled device: keyed by its LLDP chassis id, else by the operator's target name; named by its system name, else by the target name.

type Extra

type Extra struct {
	OID  string `yaml:"oid,omitempty"` // the column OID, e.g. ifName 1.3.6.1.2.1.31.1.1.1.1
	Attr string `yaml:"attr,omitempty"`
}

Extra is a descriptive attribute read from a column of another table with the same row index.

type Found

type Found struct {
	Addr    netip.Addr
	Profile Profile
}

Found is one discovered device.

func Discover

func Discover(ctx context.Context, ps Profiles, hosts []netip.Addr, conc int,
	probe func(context.Context, netip.Addr) (string, error)) ([]Found, error)

Discover asks every host for its sysObjectID (probe) with at most conc probes at once and returns the hosts whose vendor has a profile, in address order.

type Item

type Item struct {
	OID    string            `yaml:"oid,omitempty"`     // scalars: the full instance OID
	Col    string            `yaml:"col,omitempty"`     // table items: the column sub-identifier
	MulCol string            `yaml:"mul_col,omitempty"` // table items: multiply by this column of the same row
	Metric string            `yaml:"metric,omitempty"`
	Unit   string            `yaml:"unit,omitempty"`
	Kind   string            `yaml:"kind,omitempty"`  // gauge (default) or counter (reported as a rate)
	Scale  float64           `yaml:"scale,omitempty"` // 0 means 1
	Attrs  map[string]string `yaml:"attrs,omitempty"`
	// SpeedLimit marks a byte counter whose rate cannot exceed the interface speed (the table's
	// SpeedCol); a bigger rate is a counter reset, not traffic.
	SpeedLimit bool `yaml:"speed_limit,omitempty"`
}

Item is one metric: a scalar OID, or a column of a table.

type LinkRates

type LinkRates struct {
	// contains filtered or unexported fields
}

LinkRates keeps the previous octet counters per device and port, to turn them into rates.

func (*LinkRates) States

func (lr *LinkRates) States(device string, pdus []gosnmp.SnmpPDU, at time.Time) map[string]PortState

States reads the port columns of one walk and returns the state per ifIndex and per LLDP local port number (both as text keys).

type Listener

type Listener struct {
	// contains filtered or unexported fields
}

Listener receives traps over UDP and writes each as an OTLP log record.

func NewListener

func NewListener(c TrapConfig, out sink.Sink) (*Listener, error)

NewListener validates the config. Call Listen, then Serve.

func (*Listener) Addr

func (l *Listener) Addr() net.Addr

Addr is the bound address (after Listen).

func (*Listener) Dropped

func (l *Listener) Dropped(reason string) int64

Dropped counts the traps rejected for a reason: "community", "decode" (unknown v3 user, bad authentication or a malformed packet) or "size".

func (*Listener) Listen

func (l *Listener) Listen() error

Listen binds the UDP socket.

func (*Listener) Report

func (l *Listener) Report(at time.Time)

Report writes the receiver's cumulative counters.

func (*Listener) Serve

func (l *Listener) Serve(ctx context.Context) error

Serve reads traps until ctx ends.

type Manifest

type Manifest struct {
	Name    string   `yaml:"name"`
	Tables  []Table  `yaml:"tables,omitempty"`
	Scalars []Item   `yaml:"scalars,omitempty"`
	Walk    []string `yaml:"walk,omitempty"` // subtrees for other modules (LLDP); not polled here
}

Manifest is one MIB's worth of OIDs.

type Neighbor

type Neighbor struct {
	Kind       string // lldp or cdp
	LocalPort  string
	Remote     Device
	RemotePort string
}

Neighbor is one adjacency seen from the polled device.

func ParseNeighbors

func ParseNeighbors(pdus []gosnmp.SnmpPDU) []Neighbor

ParseNeighbors reads LLDP-MIB lldpRemTable and CISCO-CDP-MIB cdpCacheTable rows. A remote is keyed by its chassis id (LLDP) or device id (CDP), else by its system name. Rows come out sorted so a poll is reproducible.

type PortState

type PortState struct {
	Oper    string // up, down, testing, dormant, notPresent, lowerLayerDown, unknown
	Util    float64
	HasUtil bool
}

PortState is what the map shows for one local port.

type Profile

type Profile struct {
	Enterprise int    `yaml:"enterprise"`
	Vendor     string `yaml:"vendor"`
	Class      string `yaml:"class"`
	// VendorManifests lists the vendor's own manifests (CPU, memory, environment), polled on top of the
	// class set.
	VendorManifests []string `yaml:"manifests,omitempty"`
}

Profile maps a vendor (the enterprise number of sysObjectID) to a device class.

func (Profile) Manifests

func (p Profile) Manifests() []string

Manifests returns the manifest names the profile polls: the class set plus the vendor's own.

type Profiles

type Profiles map[int]Profile

Profiles is a set of vendor profiles keyed by enterprise number.

func LoadProfiles

func LoadProfiles(dir string) (Profiles, error)

LoadProfiles reads the embedded vendor profiles, then *.yaml in dir (local config) which replace entries with the same enterprise number.

func (Profiles) Match

func (ps Profiles) Match(sysObjectID string) (Profile, bool)

Match finds the profile of a sysObjectID such as 1.3.6.1.4.1.9.1.516.

type Rates

type Rates struct {
	// contains filtered or unexported fields
}

Rates turns cumulative counters into per-second rates and keeps the other per-device state that lives across polls (sysUpTime, truncation counts). A counter series not seen within seriesTTL is dropped, so interface churn (subinterfaces, tunnels) does not grow state forever.

func (*Rates) Forget

func (r *Rates) Forget(dev string)

Forget drops the counter baselines of one device, so its next samples only re-baseline.

func (*Rates) Truncated

func (r *Rates) Truncated(dev, table string, at time.Time) (float64, bool)

Truncated counts one cut-off walk of dev's table and returns the running total and whether it should be logged now (once per device and table per hour).

func (*Rates) Update

func (r *Rates) Update(key string, v uint64, bits int, at time.Time) (float64, bool)

Update records v for the series key and returns the rate since the last call. bits is 32 or 64. A 32-bit counter that went down is taken to have wrapped once (emit checks the result against the interface speed and sysUpTime, which catch resets); a 64-bit one that went down was reset, so that interval yields no rate.

func (*Rates) WentBack

func (r *Rates) WentBack(dev string, ticks uint64) bool

WentBack records the device's sysUpTime (hundredths of a second) and reports whether it is lower than at the last poll: the device restarted, so every counter of it starts over.

type Table

type Table struct {
	Name      string `yaml:"name"`
	OID       string `yaml:"oid,omitempty"`
	LabelCol  string `yaml:"label_col,omitempty"`  // column holding the row's name; the row index otherwise
	LabelAttr string `yaml:"label_attr,omitempty"` // attribute that carries the label
	Items     []Item `yaml:"items,omitempty"`
	Sensor    bool   `yaml:"sensor,omitempty"`   // an ENTITY-SENSOR-MIB table (type, scale, precision, value)
	NameOID   string `yaml:"name_oid,omitempty"` // sensor rows are named from this column
	// Priority orders the walks of one poll, highest first, so that when the varbind cap is hit
	// the low-value tables are the ones cut.
	Priority   int     `yaml:"priority,omitempty"`
	Extra      []Extra `yaml:"extra,omitempty"`
	SpeedCol   string  `yaml:"speed_col,omitempty"`   // column with the interface speed
	SpeedScale float64 `yaml:"speed_scale,omitempty"` // multiplier to bit/s (ifHighSpeed is in Mbit/s); 0 means 1
}

Table is a conceptual table walked from OID.

type Target

type Target struct {
	Name      string   `json:"name"`      // shown as snmp.device; the address is never exported
	Address   string   `json:"address"`   // host or host:port (default port 161)
	Version   string   `json:"version"`   // "1", "2c" (default) or "3"
	Community string   `json:"community"` // v1 and v2c
	V3        *V3      `json:"v3"`
	Timeout   string   `json:"timeout"` // per request, default 3s
	Retries   int      `json:"retries"` // default 1
	Manifests []string `json:"manifests"`
}

Target is one polled device. It is read from the agent's own file only.

func (Target) Validate

func (t Target) Validate() error

Validate checks the target without touching the network.

type TrapConfig

type TrapConfig struct {
	Listen      string            `json:"listen"`      // default 0.0.0.0:162
	Communities []string          `json:"communities"` // accepted for v1 and v2c; others are dropped
	V3          []V3              `json:"v3"`          // accepted v3 users; others are dropped
	Sources     map[string]string `json:"sources"`     // sender IP -> device name (snmp.device)
	MaxPacket   int               `json:"max_packet"`  // bytes; larger datagrams are dropped (default 4096)
	// RatePerSource is the most traps per second accepted from one sender IP (default 100);
	// the excess is dropped and counted as "rate".
	RatePerSource int `json:"rate_per_source"`
	// ProfileDir holds extra per-vendor trap profiles (*.yaml, e.g. from `wtctl mib compile`).
	ProfileDir string `json:"profile_dir"`
}

TrapConfig configures the trap receiver. Communities and users are local-file only.

type TrapDef

type TrapDef struct {
	OID         string        `yaml:"oid"`
	Name        string        `yaml:"name"`
	Severity    string        `yaml:"severity,omitempty"` // INFO, WARN, ERROR; default WARN
	Description string        `yaml:"description,omitempty"`
	Varbinds    []TrapVarbind `yaml:"varbinds,omitempty"`
}

TrapDef is one notification.

type TrapEntry

type TrapEntry struct {
	TrapDef
	Vendor string
}

TrapEntry is a resolved trap: its definition and the vendor that defines it.

type TrapProfileFile

type TrapProfileFile struct {
	Vendor string    `yaml:"vendor"`
	Traps  []TrapDef `yaml:"traps"`
}

TrapProfileFile is one vendor's (or one MIB's) file.

type TrapProfiles

type TrapProfiles map[string]TrapEntry

TrapProfiles maps a trap OID (no leading dot) to its definition.

func LoadTrapProfiles

func LoadTrapProfiles(dir string) (TrapProfiles, error)

LoadTrapProfiles reads the embedded profiles, then *.yaml in dir (local config only), whose entries replace built-in ones with the same OID.

type TrapVarbind

type TrapVarbind struct {
	OID  string            `yaml:"oid"`
	Name string            `yaml:"name"`
	Enum map[string]string `yaml:"enum,omitempty"` // integer value -> label
}

TrapVarbind names one varbind column (the instance suffix is ignored when matching).

func (TrapVarbind) Label

func (v TrapVarbind) Label(val string) string

Label renders a varbind value, with its enum label when the profile has one.

type V3

type V3 struct {
	// EngineID is the sender's snmpEngineID in hex. Trap users need it (the sender is the
	// authoritative engine, so keys are localized with it); polling finds it by discovery.
	EngineID  string `json:"engine_id"`
	User      string `json:"user"`
	AuthProto string `json:"auth_protocol"` // sha, sha224, sha256, sha384, sha512
	AuthPass  string `json:"auth_passphrase"`
	PrivProto string `json:"priv_protocol"` // aes, aes192, aes256, aes192c, aes256c
	PrivPass  string `json:"priv_passphrase"`
}

V3 is one SNMPv3 user. Used for polling a device and, in the trap config, for the users whose traps are accepted.

Directories

Path Synopsis
Package mibc compiles SMIv1/SMIv2 MIB modules into the agent's SNMP manifests and trap profiles (INF-014, INF-015, gap G-20), so a vendor MIB can be polled and its traps named without hand-written YAML.
Package mibc compiles SMIv1/SMIv2 MIB modules into the agent's SNMP manifests and trap profiles (INF-014, INF-015, gap G-20), so a vendor MIB can be polled and its traps named without hand-written YAML.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL