Skip to content

Commit

Permalink
Fix URL agent address form with udp in snmp input (#6899)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielnelson authored Jan 15, 2020
1 parent 0693748 commit 8d647c4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
31 changes: 21 additions & 10 deletions plugins/inputs/snmp/snmp.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"log"
"math"
"net"
"net/url"
"os/exec"
"strconv"
"strings"
Expand Down Expand Up @@ -609,20 +610,30 @@ 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"
if !strings.Contains(agent, "://") {
agent = "udp://" + agent
}
host, portStr, err := net.SplitHostPort(agent)

u, err := url.Parse(agent)
if err != nil {
if err, ok := err.(*net.AddrError); !ok || err.Err != "missing port in address" {
return nil, Errorf(err, "parsing host")
}
host = agent
portStr = "161"
return nil, err
}

switch u.Scheme {
case "tcp":
gs.Transport = "tcp"
case "", "udp":
gs.Transport = "udp"
default:
return nil, fmt.Errorf("unsupported scheme: %v", u.Scheme)
}
gs.Target = host

gs.Target = u.Hostname()

portStr := u.Port()
if portStr == "" {
portStr = "161"
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, Errorf(err, "parsing port")
Expand Down
9 changes: 8 additions & 1 deletion plugins/inputs/snmp/snmp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ func TestSnmpInit_noTranslate(t *testing.T) {

func TestGetSNMPConnection_v2(t *testing.T) {
s := &Snmp{
Agents: []string{"1.2.3.4:567", "1.2.3.4"},
Agents: []string{"1.2.3.4:567", "1.2.3.4", "udp://127.0.0.1"},
Timeout: internal.Duration{Duration: 3 * time.Second},
Retries: 4,
Version: 2,
Expand All @@ -256,6 +256,13 @@ func TestGetSNMPConnection_v2(t *testing.T) {
assert.Equal(t, "1.2.3.4", gs.Target)
assert.EqualValues(t, 161, gs.Port)
assert.Equal(t, "udp", gs.Transport)

gsc, err = s.getConnection(2)
require.NoError(t, err)
gs = gsc.(gosnmpWrapper)
assert.Equal(t, "127.0.0.1", gs.Target)
assert.EqualValues(t, 161, gs.Port)
assert.Equal(t, "udp", gs.Transport)
}

func TestGetSNMPConnectionTCP(t *testing.T) {
Expand Down

0 comments on commit 8d647c4

Please sign in to comment.