snmp

package module
v0.0.0-...-42b81e2 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2019 License: MIT Imports: 14 Imported by: 0

README

snmp

SNMP v1/v2c client library that allows communication with multiple hosts through a single socket

Documentation

Index

Constants

View Source
const (

	// DefaultChanSize represents the default queue size of MessageSender.MC and MessageSender.TC
	DefaultChanSize = 20
	// ErrTimedOut is emitted when the server did not respond in time
	ErrTimedOut = errTimedOut("Timed Out")
	// ErrWalkSingleOid is emitted when a snmpgo.GetBulkRequest PDU type with
	// MessageRequest.DontWant set to false requested, but 0 or more than one
	// OIDS were provided
	ErrWalkSingleOid = errWalkSingleOid("bulkwalk only supports a single OID")
	// ErrCancelViaUpdate is emitted when a TableRequest.Update function callback is
	// non-nil and the invokign it returns true
	ErrCancelViaUpdate = errCancelViaUpdate("cancellation requested by TableRequest.Update(...) returning true")
	// DefaultErrorLogger (which implements ErrorLogger) is used when the error logger
	// passed into NewMessageSender and NewMessageSenderWithConn is nil. It is called
	// when an error occurs, namely the code is unable to marshal or unmarshal a
	// message, or a socket read error occurs), or a validation step failed, this
	// type is called with the error
	DefaultErrorLogger = defaultErrorLogger("I am the default error logger!")
)
View Source
const DefaultMaxRepetitions = 10

Variables

This section is empty.

Functions

This section is empty.

Types

type ErrMalformedResponse

type ErrMalformedResponse struct {
	ExpOIDs int
	GotOIDs int
}

func (*ErrMalformedResponse) Error

func (e *ErrMalformedResponse) Error() string

type ErrorLogger

type ErrorLogger interface {
	Log(err error)
}

ErrorLogger is used when the error logger passed into NewMessageSender and NewMessageSenderWithConn is nil. It is called when an error occurs, namely the code is unable to marshal or unmarshal a message, or a socket read error occurs), or a validation step failed, this type is called with the error

type Message

type Message struct {
	Version   snmpgo.SNMPVersion // SNMP version, only v1 and v2c are supported
	Community []byte             // Host's community string
	Pdu       snmpgo.Pdu         // PDU data, storing the OIDs and in the SNMP Response, associated values
}

Message wraps requests and responses. It is rough copy of snmpgo.message with some minor conveniences, unfortunately it was not exported.

func NewMessageWithOids

func NewMessageWithOids(
	ver snmpgo.SNMPVersion,
	pduType snmpgo.PduType,
	community []byte,
	oids snmpgo.Oids,
) *Message

NewMessageWithOids is used when creating SNMP requests

func NewMessageWithVarBinds

func NewMessageWithVarBinds(ver snmpgo.SNMPVersion,
	pduType snmpgo.PduType,
	community []byte,
	varbinds snmpgo.VarBinds,
) *Message

NewMessageWithVarBinds is used when creating SNMP responses

func (*Message) Marshal

func (msg *Message) Marshal() (b []byte, err error)

func (*Message) String

func (msg *Message) String() string

func (*Message) Unmarshal

func (msg *Message) Unmarshal(b []byte) ([]byte, error)

type MessageRequest

type MessageRequest struct {
	Addr             net.Addr // Destination address. Should be *net.UDPAddr unless testing
	Message          *Message // Source message
	DontRetryOnError bool     // Disable (if true) retry of SNMP v1-type errors

	// Response is called when a response comes in. If not nil, it will be
	// called on the main thread. If it blocks, then the SNMP operations will
	// block (so be fast!).
	Response func(response MessageResponse)

	// C is a channel created by the user. If it is not nil, it messages will be
	// sent to it. If it blocks then SNMP operations will block (so be fast!)
	C chan MessageResponse
	// contains filtered or unexported fields
}

MessageRequest represents a single SNMP request (with some special-case conditions for bulk walks). The response may be sent either to the .Response or .C attributes.

func (*MessageRequest) Retries

func (mr *MessageRequest) Retries(retries int, timeoutAfter time.Duration)

Retries is called when you want to modify the default retry and timeout behavior of individual SNMP requests. If not called, defaults to being called as:

mr.Retries(2, time.Second)

type MessageResponse

type MessageResponse struct {
	Request  *Message // the original request
	Response *Message // full response. If non-nil, then Err is nil
	Err      error    // may be either ErrTimedOut or ErrWalkSingleOid
}

MessageResponse is sent to the MessageRequest.Response or MessageRequest.C attrs. Either Response or Err will be non-nil, not both/neither.

type MessageSender

type MessageSender struct {
	MC chan *MessageRequest
	TC chan *TableRequest

	// Reply that do not match known requests (perhaps the request timed out internally)
	OrphanedReplies uint64
	// a valid RequestID was seen in a reply from host B whereas the request was sent to host A
	IllegalHostReplies uint64
	// contains filtered or unexported fields
}

MessageSender is the controller for all SNMP operations. SNMP message requests are sent to

func NewMessageSender

func NewMessageSender(ctx context.Context, opts *MessageSenderOpts) (*MessageSender, error)

NewMessageSender sets up *MessageSender to allow sending and receiving of SNMP messages asynchronously from a socket.

Param ctx will gracefully shut down all goroutines created by this method call. Calling MessageSender.Wait() will will block until all goroutines have exited.

If 'opts' is nil, sensible tunable defaults will be used however internal error messages will be sent using the 'log' interface

func (*MessageSender) Wait

func (ms *MessageSender) Wait()

Wait blocks until all goroutines created by NewMessageSenderWithConn have shut down. That shutdown will happen when the context provided to it closes.

type MessageSenderOpts

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

func NewMessageSenderOpts

func NewMessageSenderOpts() *MessageSenderOpts

func (*MessageSenderOpts) CallbackInline

func (o *MessageSenderOpts) CallbackInline(inline bool) *MessageSenderOpts

CallbackInline controls whether each MessageRequest.Response Callback is called in its own goroutine, or on the main goroutine. If you are leaving the .Response attr nil and only using channels then this is irrelevant.

By default this is false, each callback will run on its goroutine.

func (*MessageSenderOpts) ChanSize

func (o *MessageSenderOpts) ChanSize(sz int) *MessageSenderOpts

ChanSize (which defaults to DefaultChanSize) controls the queue size of MessageSender.MC and MessageSender.TC. Setting this to 0 will cause the queue to become blocking.

func (*MessageSenderOpts) Conn

Conn is the socket on which all UDP packets will be sent. By default, it binds to UDP ':0', which will create a UDP socket on an ephemeral port which will be in the range (on Linux) as per this command:

sysctl net.ipv4.ip_local_port_range

func (*MessageSenderOpts) OnErr

OnErr provides an interface for logging all errors. By default it uses the 'log' package. If you wish to provide a code callback, use OnErrFunc instead

func (*MessageSenderOpts) OnErrFunc

func (o *MessageSenderOpts) OnErrFunc(onErr func(error)) *MessageSenderOpts

OnErrFunc provides an interface for logging all errors. By default it uses the 'log' package. This method allows a func instead of interface

type TableRequest

type TableRequest struct {
	// Context for cancellation. If nil, uses the context of the MessageSender. Cancelling
	// this context will prevent messages being sent using the channel C, but the Response
	// function will be called regardless
	Context context.Context

	Addr      net.Addr    // Destination address. Should be *net.UDPAddr unless testing
	Community []byte      // Host's community string
	SnmpV1    bool        // SNMP version, only v1 and v2c are supported
	Oids      snmpgo.Oids // Table base OIDs to fetch

	TimeoutAfter time.Duration // Timeout for each request
	StopAfter    time.Time     // Stop request resends after this time
	MaxRep       int           // defaults to DefaultMaxRepetitions when using GetBulk
	Slow         bool          // when true, uses GetNext instead of GetBulk

	// Update (when non-nil) will be called after each SNMP request/response,
	// and allow the caller to update MaxRep if requested. This is useful when
	// experimenting with increasing the MaxRep field to decrease roundtrip times, and
	// compensating for that if packets are being dropped
	//
	// In the Update call, you can alter MaxRep and TimeoutAfter and it will take effect in
	// the next SNMP packet. Return true to stop further processing.
	Update func(tr *TableRequest, failure bool, took time.Duration) (stop bool)

	// Response is called when a response comes in. If not nil, it will be
	// called on the main thread. If it blocks, then the SNMP operations will
	// block (so be fast!).
	Response func(response TableResponse)
	// C is a channel created by the user. If it is not nil, it messages will be
	// sent to it. If it blocks then SNMP operations will block (so be fast!)
	C chan TableResponse
}

type TableResponse

type TableResponse struct {
	Request  *TableRequest
	VarBinds []snmpgo.VarBinds // Responses corresponding to the indices of the OIDs in the request
	// Err may be one of the following:
	//    ErrTimedOut
	//    ErrWalkSingleOid
	//    context.Canceled
	//    context.DeadlineExceeded
	//
	// This differs in behavior to MessageResponse.Err in that a new context can be
	// passed into GetTableSlow or GetTable, allowing cancellation or deadlines
	// to occur which will be passed back. This increase in functionality is allowed
	// as this is a higher level API which builds on the MessageRequest primitives
	Err error

	Timeouts      int             // number of sub-requests that timed out
	ResponseTimes []time.Duration // times of responses that did not time out
}

func (*TableResponse) TimedOut

func (tr *TableResponse) TimedOut() bool

Jump to

Keyboard shortcuts

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