Fix URL agent address form with udp in snmp input (#6899)

This commit is contained in:
Daniel Nelson 2020-01-14 16:26:44 -08:00 committed by GitHub
parent 0693748c35
commit 8d647c4ebf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 11 deletions

View File

@ -7,6 +7,7 @@ import (
"log" "log"
"math" "math"
"net" "net"
"net/url"
"os/exec" "os/exec"
"strconv" "strconv"
"strings" "strings"
@ -609,20 +610,30 @@ func (s *Snmp) getConnection(idx int) (snmpConnection, error) {
gs := gosnmpWrapper{&gosnmp.GoSNMP{}} gs := gosnmpWrapper{&gosnmp.GoSNMP{}}
s.connectionCache[idx] = gs s.connectionCache[idx] = gs
if strings.HasPrefix(agent, "tcp://") { if !strings.Contains(agent, "://") {
agent = strings.TrimPrefix(agent, "tcp://") agent = "udp://" + agent
gs.Transport = "tcp"
} }
host, portStr, err := net.SplitHostPort(agent)
u, err := url.Parse(agent)
if err != nil { if err != nil {
if err, ok := err.(*net.AddrError); !ok || err.Err != "missing port in address" { return nil, err
return nil, Errorf(err, "parsing host") }
}
host = agent 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 = u.Hostname()
portStr := u.Port()
if portStr == "" {
portStr = "161" portStr = "161"
} }
gs.Target = host
port, err := strconv.ParseUint(portStr, 10, 16) port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil { if err != nil {
return nil, Errorf(err, "parsing port") return nil, Errorf(err, "parsing port")

View File

@ -232,7 +232,7 @@ func TestSnmpInit_noTranslate(t *testing.T) {
func TestGetSNMPConnection_v2(t *testing.T) { func TestGetSNMPConnection_v2(t *testing.T) {
s := &Snmp{ 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}, Timeout: internal.Duration{Duration: 3 * time.Second},
Retries: 4, Retries: 4,
Version: 2, Version: 2,
@ -256,6 +256,13 @@ func TestGetSNMPConnection_v2(t *testing.T) {
assert.Equal(t, "1.2.3.4", gs.Target) assert.Equal(t, "1.2.3.4", gs.Target)
assert.EqualValues(t, 161, gs.Port) assert.EqualValues(t, 161, gs.Port)
assert.Equal(t, "udp", gs.Transport) 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) { func TestGetSNMPConnectionTCP(t *testing.T) {