forked from prometheus-junkyard/munin_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
munin_exporter.go
290 lines (258 loc) · 7.2 KB
/
munin_exporter.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
)
const (
proto = "tcp"
retryInterval = 1
)
var (
listeningAddress = flag.String("listeningAddress", ":8080", "Address on which to expose Prometheus metrics.")
muninAddress = flag.String("muninAddress", "localhost:4949", "munin-node address.")
muninScrapeInterval = flag.Int("muninScrapeInterval", 60, "Interval in seconds between scrapes.")
globalConn net.Conn
hostname string
graphs []string
gaugePerMetric map[string]*prometheus.GaugeVec
counterPerMetric map[string]*prometheus.CounterVec
muninBanner *regexp.Regexp
)
func init() {
flag.Parse()
var err error
gaugePerMetric = map[string]*prometheus.GaugeVec{}
counterPerMetric = map[string]*prometheus.CounterVec{}
muninBanner = regexp.MustCompile(`# munin node at (.*)`)
err = connect()
if err != nil {
log.Fatalf("Could not connect to %s: %s", *muninAddress, err)
}
}
func serveStatus() {
http.Handle("/metrics", prometheus.Handler())
http.ListenAndServe(*listeningAddress, nil)
}
func connect() (err error) {
log.Printf("Connecting...")
globalConn, err = net.Dial(proto, *muninAddress)
if err != nil {
return
}
log.Printf("connected!")
reader := bufio.NewReader(globalConn)
head, err := reader.ReadString('\n')
if err != nil {
return
}
matches := muninBanner.FindStringSubmatch(head)
if len(matches) != 2 { // expect: # munin node at <hostname>
return fmt.Errorf("Unexpected line: %s", head)
}
hostname = matches[1]
log.Printf("Found hostname: %s", hostname)
return
}
func muninCommand(cmd string) (reader *bufio.Reader, err error) {
reader = bufio.NewReader(globalConn)
fmt.Fprintf(globalConn, cmd+"\n")
_, err = reader.Peek(1)
switch err {
case io.EOF:
log.Printf("not connected anymore, closing connection")
globalConn.Close()
for {
err = connect()
if err == nil {
break
}
log.Printf("Couldn't reconnect: %s", err)
time.Sleep(retryInterval * time.Second)
}
return muninCommand(cmd)
case nil: //no error
break
default:
log.Fatalf("Unexpected error: %s", err)
}
return
}
func muninList() (items []string, err error) {
munin, err := muninCommand("list")
if err != nil {
log.Printf("couldn't get list")
return
}
response, err := munin.ReadString('\n') // we are only interested in the first line
if err != nil {
log.Printf("couldn't read response")
return
}
if response[0] == '#' { // # not expected here
err = fmt.Errorf("Error getting items: %s", response)
return
}
items = strings.Fields(strings.TrimRight(response, "\n"))
return
}
func muninConfig(name string) (config map[string]map[string]string, graphConfig map[string]string, err error) {
graphConfig = make(map[string]string)
config = make(map[string]map[string]string)
resp, err := muninCommand("config " + name)
if err != nil {
log.Printf("couldn't get config for %s", name)
return
}
for {
line, err := resp.ReadString('\n')
if err == io.EOF {
log.Fatalf("unexpected EOF, retrying")
return muninConfig(name)
}
if err != nil {
return nil, nil, err
}
if line == ".\n" { // munin end marker
break
}
if line[0] == '#' { // here it's just a comment, so ignore it
continue
}
parts := strings.Fields(line)
if len(parts) < 2 {
return nil, nil, fmt.Errorf("Line unexpected: %s", line)
}
key, value := parts[0], strings.TrimRight(strings.Join(parts[1:], " "), "\n")
key_parts := strings.Split(key, ".")
if len(key_parts) > 1 { // it's a metric config (metric.label etc)
if _, ok := config[key_parts[0]]; !ok { //FIXME: is there no better way?
config[key_parts[0]] = make(map[string]string)
}
config[key_parts[0]][key_parts[1]] = value
} else {
graphConfig[key_parts[0]] = value
}
}
return
}
func registerMetrics() (err error) {
items, err := muninList()
if err != nil {
return
}
for _, name := range items {
graphs = append(graphs, name)
configs, graphConfig, err := muninConfig(name)
if err != nil {
return err
}
for metric, config := range configs {
metricName := strings.Replace(name + "_" + metric, "-","_",-1)
//metricName = strings.Replace(name, "-","_",-1)
desc := graphConfig["graph_title"] + ": " + config["label"]
if config["info"] != "" {
desc = desc + ", " + config["info"]
}
muninType := strings.ToLower(config["type"])
// muninType can be empty and defaults to gauge
if muninType == "counter" || muninType == "derive" {
gv := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: metricName,
Help: desc,
ConstLabels: prometheus.Labels{"type":muninType},
},
[]string{"hostname","graphname","muninlabel"},
)
log.Printf("Registered counter %s: %s", metricName, desc)
counterPerMetric[metricName] = gv
prometheus.Register(gv)
} else {
gv := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: metricName,
Help: desc,
ConstLabels: prometheus.Labels{"type":"counter"},
},
[]string{"hostname","graphname","muninlabel"},
)
log.Printf("Registered gauge %s: %s", metricName, desc)
gaugePerMetric[metricName] = gv
prometheus.Register(gv)
}
}
}
return nil
}
func fetchMetrics() (err error) {
for _, graph := range graphs {
munin, err := muninCommand("fetch " + graph)
if err != nil {
return err
}
for {
line, err := munin.ReadString('\n')
line = strings.TrimRight(line, "\n")
if err == io.EOF {
log.Fatalf("unexpected EOF, retrying")
return fetchMetrics()
}
if err != nil {
return err
}
if len(line) == 1 && line[0] == '.' {
log.Printf("End of list")
break
}
parts := strings.Fields(line)
if len(parts) != 2 {
log.Printf("unexpected line: %s", line)
continue
}
key, value_s := strings.Split(parts[0], ".")[0], parts[1]
value, err := strconv.ParseFloat(value_s, 64)
if err != nil {
log.Printf("Couldn't parse value in line %s, malformed?", line)
continue
}
name := strings.Replace(graph + "_" + key, "-","_",-1)
//name = strings.Replace(graph, "-","_",-1)
log.Printf("%s: %f\n", name, value)
_, isGauge := gaugePerMetric[name]
if isGauge {
gaugePerMetric[name].WithLabelValues(hostname, graph, key).Set(value)
} else {
counterPerMetric[name].WithLabelValues(hostname, graph, key).Set(value)
}
}
}
return
}
func main() {
flag.Parse()
err := registerMetrics()
if err != nil {
log.Fatalf("Could not register metrics: %s", err)
}
go serveStatus()
func() {
for {
log.Printf("Scraping")
err := fetchMetrics()
if err != nil {
log.Printf("Error occured when trying to fetch metrics: %s", err)
}
time.Sleep(time.Duration(*muninScrapeInterval) * time.Second)
}
}()
}