forked from prometheus/graphite_exporter
/
main.go
247 lines (226 loc) · 6.45 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
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
// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"math"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/log"
)
var (
listeningAddress = flag.String("web.listen-address", ":9108", "Address on which to expose metrics.")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose Prometheus metrics.")
graphiteAddress = flag.String("graphite.listen-address", ":9109", "TCP and UDP address on which to accept samples.")
mappingConfig = flag.String("graphite.mapping-config", "", "Metric mapping configuration file name.")
sampleExpiry = flag.Duration("graphite.sample-expiry", 5*time.Minute, "How long a sample is valid for.")
strictMatch = flag.Bool("graphite.mapping-strict-match", false, "Only store metrics that match the mapping configuration.")
lastProcessed = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "graphite_last_processed_timestamp_seconds",
Help: "Unix timestamp of the last processed graphite metric.",
},
)
invalidMetricChars = regexp.MustCompile("[^a-zA-Z0-9_:]")
)
type graphiteSample struct {
OriginalName string
Name string
Labels map[string]string
Help string
Value float64
Type prometheus.ValueType
Timestamp time.Time
}
type graphiteCollector struct {
samples map[string]*graphiteSample
mu *sync.Mutex
mapper *metricMapper
ch chan *graphiteSample
}
func newGraphiteCollector() *graphiteCollector {
c := &graphiteCollector{
ch: make(chan *graphiteSample, 0),
mu: &sync.Mutex{},
samples: map[string]*graphiteSample{},
}
go c.processSamples()
return c
}
func (c *graphiteCollector) processReader(reader io.Reader) {
lineScanner := bufio.NewScanner(reader)
for {
if ok := lineScanner.Scan(); !ok {
break
}
c.processLine(lineScanner.Text())
}
}
func (c *graphiteCollector) processLine(line string) {
parts := strings.Split(line, " ")
if len(parts) != 3 {
log.Infof("Invalid part count of %d in line: %s", len(parts), line)
return
}
var name string
labels, present := c.mapper.getMapping(parts[0])
if present {
name = labels["name"]
delete(labels, "name")
} else {
// If graphite.mapping-strict-match flag is set, we will drop this metric.
if *strictMatch {
return
}
name = invalidMetricChars.ReplaceAllString(parts[0], "_")
}
value, err := strconv.ParseFloat(parts[1], 64)
if err != nil {
log.Infof("Invalid value in line: %s", line)
return
}
timestamp, err := strconv.ParseFloat(parts[2], 64)
if err != nil {
log.Infof("Invalid timestamp in line: %s", line)
return
}
sample := graphiteSample{
OriginalName: parts[0],
Name: name,
Value: value,
Labels: labels,
Type: prometheus.GaugeValue,
Help: fmt.Sprintf("Graphite metric %s", parts[0]),
Timestamp: time.Unix(int64(timestamp), int64(math.Mod(timestamp, 1.0)*1e9)),
}
lastProcessed.Set(float64(time.Now().UnixNano()) / 1e9)
c.ch <- &sample
}
func (c *graphiteCollector) processSamples() {
ticker := time.NewTicker(time.Minute).C
for {
select {
case sample := <-c.ch:
c.mu.Lock()
c.samples[sample.OriginalName] = sample
c.mu.Unlock()
case <-ticker:
// Garbage collect expired samples.
ageLimit := time.Now().Add(-*sampleExpiry)
c.mu.Lock()
for k, sample := range c.samples {
if ageLimit.After(sample.Timestamp) {
delete(c.samples, k)
}
}
c.mu.Unlock()
}
}
}
// Collect implements prometheus.Collector.
func (c graphiteCollector) Collect(ch chan<- prometheus.Metric) {
ch <- lastProcessed
c.mu.Lock()
samples := make([]*graphiteSample, 0, len(c.samples))
for _, sample := range c.samples {
samples = append(samples, sample)
}
c.mu.Unlock()
ageLimit := time.Now().Add(-*sampleExpiry)
for _, sample := range samples {
if ageLimit.After(sample.Timestamp) {
continue
}
ch <- prometheus.MustNewConstMetric(
prometheus.NewDesc(sample.Name, sample.Help, []string{}, sample.Labels),
sample.Type,
sample.Value,
)
}
}
// Describe implements prometheus.Collector.
func (c graphiteCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- lastProcessed.Desc()
}
func main() {
flag.Parse()
http.Handle(*metricsPath, prometheus.Handler())
c := newGraphiteCollector()
prometheus.MustRegister(c)
c.mapper = &metricMapper{}
if *mappingConfig != "" {
err := c.mapper.initFromFile(*mappingConfig)
if err != nil {
log.Fatalf("Error loading metric mapping config: %s", err)
}
}
tcpSock, err := net.Listen("tcp", *graphiteAddress)
if err != nil {
log.Fatalf("Error binding to TCP socket: %s", err)
}
go func() {
for {
conn, err := tcpSock.Accept()
if err != nil {
log.Errorf("Error accepting TCP connection: %s", err)
continue
}
go func() {
defer conn.Close()
c.processReader(conn)
}()
}
}()
udpAddress, err := net.ResolveUDPAddr("udp", *graphiteAddress)
if err != nil {
log.Fatalf("Error resolving UDP address: %s", err)
}
udpSock, err := net.ListenUDP("udp", udpAddress)
if err != nil {
log.Fatalf("Error listening to UDP address: %s", err)
}
go func() {
defer udpSock.Close()
for {
buf := make([]byte, 65536)
chars, srcAddress, err := udpSock.ReadFromUDP(buf)
if err != nil {
log.Errorf("Error reading UDP packet from %s: %s", srcAddress, err)
continue
}
go c.processReader(bytes.NewReader(buf[0:chars]))
}
}()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Graphite Exporter</title></head>
<body>
<h1>Graphite Exporter</h1>
<p>Accepting plaintext Graphite samples over TCP and UDP on ` + *graphiteAddress + `</p>
<p><a href="` + *metricsPath + `">Metrics</a></p>
</body>
</html>`))
})
log.Infof("Starting Server: %s", *listeningAddress)
http.ListenAndServe(*listeningAddress, nil)
}