forked from kisielk/gostatsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphite.go
50 lines (44 loc) · 1.32 KB
/
graphite.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
package statsd
import (
"bytes"
"fmt"
"net"
"regexp"
"time"
)
// Regular expressions used for bucket name normalization
var (
regSpaces = regexp.MustCompile("\\s+")
regSlashes = regexp.MustCompile("\\/")
regInvalid = regexp.MustCompile("[^a-zA-Z_\\-0-9\\.]")
)
// normalizeBucketName cleans up a bucket name by replacing or translating invalid characters
func normalizeBucketName(name string) string {
nospaces := regSpaces.ReplaceAllString(name, "_")
noslashes := regSlashes.ReplaceAllString(nospaces, "-")
return regInvalid.ReplaceAllString(noslashes, "")
}
// GraphiteClient is an object that is used to send messages to a Graphite server's UDP interface
type GraphiteClient struct {
conn *net.Conn
}
// SendMetrics sends the metrics in a MetricsMap to the Graphite server
func (client *GraphiteClient) SendMetrics(metrics MetricMap) (err error) {
buf := new(bytes.Buffer)
now := time.Now().Unix()
for k, v := range metrics {
nk := normalizeBucketName(k)
fmt.Fprintf(buf, "%s %f %d\n", nk, v, now)
}
_, err = buf.WriteTo(*client.conn)
if err != nil {
return err
}
return nil
}
// NewGraphiteClient constructs a GraphiteClient object by connecting to an address
func NewGraphiteClient(addr string) (client GraphiteClient, err error) {
conn, err := net.Dial("tcp", addr)
client = GraphiteClient{&conn}
return
}