Add support for SNMP over TCP (#5870)

This commit is contained in:
Felix Maurer
2019-11-07 20:56:51 +02:00
committed by Daniel Nelson
parent b4a712969e
commit 378c570c06
5 changed files with 51 additions and 5 deletions

View File

@@ -98,7 +98,7 @@ Resulting output:
### Config parameters
* `agents`: Default: `[]`
List of SNMP agents to connect to in the form of `IP[:PORT]`. If `:PORT` is unspecified, it defaults to `161`.
List of SNMP agents to connect to in the form of `[tcp://]IP[:PORT]`. If `:PORT` is unspecified, it defaults to `161`. When using the optional prefix `tcp://`, SNMP over TCP will be used. Otherwise UDP is used as the transport protocol.
* `version`: Default: `2`
SNMP protocol version to use.

View File

@@ -623,6 +623,10 @@ func (s *Snmp) getConnection(idx int) (snmpConnection, error) {
gs := gosnmpWrapper{&gosnmp.GoSNMP{}}
s.connectionCache[idx] = gs
if strings.HasPrefix(agent, "tcp://") {
agent = strings.TrimPrefix(agent, "tcp://")
gs.Transport = "tcp"
}
host, portStr, err := net.SplitHostPort(agent)
if err != nil {
if err, ok := err.(*net.AddrError); !ok || err.Err != "missing port in address" {

View File

@@ -272,12 +272,46 @@ func TestGetSNMPConnection_v2(t *testing.T) {
assert.EqualValues(t, 567, gs.Port)
assert.Equal(t, gosnmp.Version2c, gs.Version)
assert.Equal(t, "foo", gs.Community)
assert.Equal(t, "udp", gs.Transport)
gsc, err = s.getConnection(1)
require.NoError(t, err)
gs = gsc.(gosnmpWrapper)
assert.Equal(t, "1.2.3.4", gs.Target)
assert.EqualValues(t, 161, gs.Port)
assert.Equal(t, "udp", gs.Transport)
}
func TestGetSNMPConnectionTCP(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
go stubTCPServer(&wg)
wg.Wait()
s := &Snmp{
Agents: []string{"tcp://127.0.0.1:56789"},
}
err := s.init()
require.NoError(t, err)
wg.Add(1)
gsc, err := s.getConnection(0)
require.NoError(t, err)
gs := gsc.(gosnmpWrapper)
assert.Equal(t, "127.0.0.1", gs.Target)
assert.EqualValues(t, 56789, gs.Port)
assert.Equal(t, "tcp", gs.Transport)
wg.Wait()
}
func stubTCPServer(wg *sync.WaitGroup) {
defer wg.Done()
tcpAddr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:56789")
tcpServer, _ := net.ListenTCP("tcp", tcpAddr)
defer tcpServer.Close()
wg.Done()
conn, _ := tcpServer.AcceptTCP()
defer conn.Close()
}
func TestGetSNMPConnection_v3(t *testing.T) {