Skip to content

Commit

Permalink
feat(inputs.snmp): Convert uneven bytes to int (influxdata#16027)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hipska authored Oct 18, 2024
1 parent c4bce2d commit 3951d89
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 20 deletions.
45 changes: 25 additions & 20 deletions internal/snmp/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,33 +253,38 @@ func (f *Field) Convert(ent gosnmp.SnmpPDU) (interface{}, error) {
return v, nil
}

var b []byte
switch bit {
case "uint64":
b = make([]byte, 8)
case "uint32":
b = make([]byte, 4)
case "uint16":
b = make([]byte, 2)
default:
return nil, fmt.Errorf("invalid bit value (%s) for hex to int conversion", bit)
}
copy(b, bv)

var byteOrder binary.ByteOrder
switch endian {
case "LittleEndian":
switch bit {
case "uint64":
v = binary.LittleEndian.Uint64(bv)
case "uint32":
v = binary.LittleEndian.Uint32(bv)
case "uint16":
v = binary.LittleEndian.Uint16(bv)
default:
return nil, fmt.Errorf("invalid bit value (%s) for hex to int conversion", bit)
}
byteOrder = binary.LittleEndian
case "BigEndian":
switch bit {
case "uint64":
v = binary.BigEndian.Uint64(bv)
case "uint32":
v = binary.BigEndian.Uint32(bv)
case "uint16":
v = binary.BigEndian.Uint16(bv)
default:
return nil, fmt.Errorf("invalid bit value (%s) for hex to int conversion", bit)
}
byteOrder = binary.BigEndian
default:
return nil, fmt.Errorf("invalid Endian value (%s) for hex to int conversion", endian)
}

switch bit {
case "uint64":
v = byteOrder.Uint64(b)
case "uint32":
v = byteOrder.Uint32(b)
case "uint16":
v = byteOrder.Uint16(b)
}

return v, nil
}

Expand Down
9 changes: 9 additions & 0 deletions internal/snmp/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,15 @@ func TestConvertHextoint(t *testing.T) {
},
expected: uint16(0xc884),
},
{
name: "little endian single byte",
conversion: "hextoint:LittleEndian:uint16",
ent: gosnmp.SnmpPDU{
Type: gosnmp.OctetString,
Value: []byte{0x84},
},
expected: uint16(0x84),
},
{
name: "little endian invalid",
conversion: "hextoint:LittleEndian:invalid",
Expand Down

0 comments on commit 3951d89

Please sign in to comment.