bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/snmp/get.go (about) 1 package snmp 2 3 import ( 4 "fmt" 5 6 "bosun.org/snmp/mib" 7 ) 8 9 // Get is a wrapper for SNMP.Get. 10 func Get(host, community string, nameval ...interface{}) error { 11 s, err := New(host, community) 12 if err != nil { 13 return err 14 } 15 return s.Get(nameval...) 16 } 17 18 // Get retrieves an object by its name. Nameval is a pair of: object name or OID 19 // (string), and the corresponding target value (pointer to int, string, etc.). 20 // To retrieve multiple objects in a single transaction, provide multiple name, 21 // value pairs. 22 func (s *SNMP) Get(nameval ...interface{}) error { 23 switch n := len(nameval); { 24 case n == 0: 25 return nil 26 case n%2 == 1: 27 panic("snmp.Get: odd-sized nameval") 28 } 29 bindings, err := fromPairs(nameval) 30 if err != nil { 31 return err 32 } 33 req := &request{ 34 Type: "Get", 35 Bindings: bindings, 36 ID: <-nextID, 37 } 38 resp, err := s.do(req) 39 if err != nil { 40 return err 41 } 42 if err := check(resp, req); err != nil { 43 return err 44 } 45 for i, b := range resp.Bindings { 46 if have, want := b.Name, req.Bindings[i].Name; !have.Equal(want) { 47 return fmt.Errorf("snmp: get %v: invalid response: name mismatch", want) 48 } 49 v := nameval[2*i+1] 50 if err := b.unmarshal(v); err != nil { 51 return err 52 } 53 } 54 return nil 55 } 56 57 // fromPairs creates bindings from the (name, value) pairs. 58 func fromPairs(nameval []interface{}) ([]binding, error) { 59 var bindings []binding 60 for i := 0; i < len(nameval); i += 2 { 61 s, ok := nameval[i].(string) 62 if !ok { 63 panic("pair name not a string") 64 } 65 oid, err := mib.Lookup(s) 66 if err != nil { 67 return nil, err 68 } 69 bindings = append(bindings, binding{Name: oid}) 70 } 71 return bindings, nil 72 }