forked from mackerelio/mackerel-agent-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snmp.go
123 lines (101 loc) · 2.58 KB
/
snmp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"flag"
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/alouca/gosnmp"
mp "github.com/mackerelio/go-mackerel-plugin"
)
// SNMPMetrics metrics
type SNMPMetrics struct {
OID string
Metrics mp.Metrics
}
// SNMPPlugin mackerel plugin for snmp
type SNMPPlugin struct {
GraphName string
GraphUnit string
Host string
Community string
Tempfile string
SNMPMetricsSlice []SNMPMetrics
}
// FetchMetrics interface for mackerelplugin
func (m SNMPPlugin) FetchMetrics() (map[string]float64, error) {
stat := make(map[string]float64)
s, err := gosnmp.NewGoSNMP(m.Host, m.Community, gosnmp.Version2c, 30)
if err != nil {
return nil, err
}
for _, sm := range m.SNMPMetricsSlice {
resp, err := s.Get(sm.OID)
if err != nil {
log.Println("SNMP get failed: ", err)
continue
}
ret, err := strconv.ParseFloat(fmt.Sprint(resp.Variables[0].Value), 64)
if err != nil {
log.Println(err)
continue
}
stat[sm.Metrics.Name] = ret
}
return stat, err
}
// GraphDefinition interface for mackerelplugin
func (m SNMPPlugin) GraphDefinition() map[string](mp.Graphs) {
metrics := []mp.Metrics{}
for _, sm := range m.SNMPMetricsSlice {
metrics = append(metrics, sm.Metrics)
}
return map[string](mp.Graphs){
m.GraphName: mp.Graphs{
Label: m.GraphName,
Unit: m.GraphUnit,
Metrics: metrics,
},
}
}
func main() {
optGraphName := flag.String("name", "snmp", "Graph name")
optGraphUnit := flag.String("unit", "float", "Graph unit")
optHost := flag.String("host", "localhost", "Hostname")
optCommunity := flag.String("community", "public", "SNMP V2c Community")
optTempfile := flag.String("tempfile", "", "Temp file name")
flag.Parse()
var snmp SNMPPlugin
snmp.Host = *optHost
snmp.Community = *optCommunity
snmp.GraphName = *optGraphName
snmp.GraphUnit = *optGraphUnit
sms := []SNMPMetrics{}
for _, arg := range flag.Args() {
vals := strings.Split(arg, ":")
if len(vals) < 2 {
continue
}
mpm := mp.Metrics{Name: vals[1], Label: vals[1]}
if len(vals) >= 3 {
mpm.Diff, _ = strconv.ParseBool(vals[2])
}
if len(vals) >= 4 {
mpm.Stacked, _ = strconv.ParseBool(vals[3])
}
sms = append(sms, SNMPMetrics{OID: vals[0], Metrics: mpm})
}
snmp.SNMPMetricsSlice = sms
helper := mp.NewMackerelPlugin(snmp)
if *optTempfile != "" {
helper.Tempfile = *optTempfile
} else {
helper.Tempfile = fmt.Sprintf("/tmp/mackerel-plugin-snmp-%s-%s", *optHost, *optGraphName)
}
if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
helper.OutputDefinitions()
} else {
helper.OutputValues()
}
}