forked from prometheus/snmp_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
207 lines (187 loc) · 5.5 KB
/
main.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"sync"
"syscall"
"time"
"gopkg.in/alecthomas/kingpin.v2"
yaml "gopkg.in/yaml.v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
"github.com/prometheus/common/version"
"github.com/prometheus/snmp_exporter/config"
)
var (
configFile = kingpin.Flag("config.file", "Path to configuration file.").Default("snmp.yml").String()
listenAddress = kingpin.Flag("web.listen-address", "Address to listen on for web interface and telemetry.").Default(":9116").String()
// Metrics about the SNMP exporter itself.
snmpDuration = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "snmp_collection_duration_seconds",
Help: "Duration of collections by the SNMP exporter",
},
[]string{"module"},
)
snmpRequestErrors = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "snmp_request_errors_total",
Help: "Errors in requests to the SNMP exporter",
},
)
sc = &SafeConfig{
C: &config.Config{},
}
reloadCh chan chan error
)
func init() {
prometheus.MustRegister(snmpDuration)
prometheus.MustRegister(snmpRequestErrors)
prometheus.MustRegister(version.NewCollector("snmp_exporter"))
}
func handler(w http.ResponseWriter, r *http.Request) {
target := r.URL.Query().Get("target")
if target == "" {
http.Error(w, "'target' parameter must be specified", 400)
snmpRequestErrors.Inc()
return
}
moduleName := r.URL.Query().Get("module")
if moduleName == "" {
moduleName = "if_mib"
}
sc.RLock()
module, ok := (*(sc.C))[moduleName]
sc.RUnlock()
if !ok {
http.Error(w, fmt.Sprintf("Unkown module '%s'", moduleName), 400)
snmpRequestErrors.Inc()
return
}
log.Debugf("Scraping target '%s' with module '%s'", target, moduleName)
start := time.Now()
registry := prometheus.NewRegistry()
collector := collector{target: target, module: module}
registry.MustRegister(collector)
// Delegate http serving to Promethues client library, which will call collector.Collect.
h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
h.ServeHTTP(w, r)
duration := float64(time.Since(start).Seconds())
snmpDuration.WithLabelValues(moduleName).Observe(duration)
log.Debugf("Scrape of target '%s' with module '%s' took %f seconds", target, moduleName, duration)
}
func updateConfiguration(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
rc := make(chan error)
reloadCh <- rc
if err := <-rc; err != nil {
http.Error(w, fmt.Sprintf("failed to reload config: %s", err), http.StatusInternalServerError)
}
default:
log.Errorf("POST method expected")
http.Error(w, "POST method expected", 400)
}
}
type SafeConfig struct {
sync.RWMutex
C *config.Config
}
func (sc *SafeConfig) ReloadConfig(configFile string) (err error) {
conf, err := config.LoadFile(configFile)
if err != nil {
log.Errorf("Error parsing config file: %s", err)
return err
}
sc.Lock()
sc.C = conf
sc.Unlock()
log.Infoln("Loaded config file")
return nil
}
func main() {
log.AddFlags(kingpin.CommandLine)
kingpin.Version(version.Print("snmp_exporter"))
kingpin.HelpFlag.Short('h')
kingpin.Parse()
log.Infoln("Starting snmp exporter", version.Info())
log.Infoln("Build context", version.BuildContext())
// Bail early if the config is bad.
var err error
sc.C, err = config.LoadFile(*configFile)
if err != nil {
log.Fatalf("Error parsing config file: %s", err)
}
// Initilise metrics.
for module, _ := range *sc.C {
snmpDuration.WithLabelValues(module)
}
hup := make(chan os.Signal)
reloadCh = make(chan chan error)
signal.Notify(hup, syscall.SIGHUP)
go func() {
for {
select {
case <-hup:
if err := sc.ReloadConfig(*configFile); err != nil {
log.Errorf("Error reloading config: %s", err)
}
case rc := <-reloadCh:
if err := sc.ReloadConfig(*configFile); err != nil {
log.Errorf("Error reloading config: %s", err)
rc <- err
} else {
rc <- nil
}
}
}
}()
http.Handle("/metrics", promhttp.Handler()) // Normal metrics endpoint for SNMP exporter itself.
http.HandleFunc("/snmp", handler) // Endpoint to do SNMP scrapes.
http.HandleFunc("/-/reload", updateConfiguration) // Endpoint to reload configuration.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head>
<title>SNMP Exporter</title>
<style>
label{
display:inline-block;
width:75px;
}
form label {
margin: 10px;
}
form input {
margin: 10px;
}
</style>
</head>
<body>
<h1>SNMP Exporter</h1>
<form action="/snmp">
<label>Target:</label> <input type="text" name="target" placeholder="X.X.X.X" value="1.2.3.4"><br>
<label>Module:</label> <input type="text" name="module" placeholder="module" value="if_mib"><br>
<input type="submit" value="Submit">
</form>
<p><a href="/config">Config</a></p>
</body>
</html>`))
})
http.HandleFunc("/config", func(w http.ResponseWriter, r *http.Request) {
sc.RLock()
c, err := yaml.Marshal(sc.C)
sc.RUnlock()
if err != nil {
log.Warnf("Error marshalling configuration: %v", err)
http.Error(w, err.Error(), 500)
return
}
w.Write(c)
})
log.Infof("Listening on %s", *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}