graphite.go 1.32 KB
Newer Older
1 2 3 4 5 6
package statsd

import (
	"bytes"
	"fmt"
	"net"
Kamil Kisiel's avatar
Kamil Kisiel committed
7
	"regexp"
8 9 10
	"time"
)

Kamil Kisiel's avatar
Kamil Kisiel committed
11 12 13 14 15 16 17
// Regular expressions used for bucket name normalization
var (
	regSpaces  = regexp.MustCompile("\\s+")
	regSlashes = regexp.MustCompile("\\/")
	regInvalid = regexp.MustCompile("[^a-zA-Z_\\-0-9\\.]")
)

Kamil Kisiel's avatar
Kamil Kisiel committed
18
// normalizeBucketName cleans up a bucket name by replacing or translating invalid characters
19 20 21 22 23 24
func normalizeBucketName(name string) string {
	nospaces := regSpaces.ReplaceAllString(name, "_")
	noslashes := regSlashes.ReplaceAllString(nospaces, "-")
	return regInvalid.ReplaceAllString(noslashes, "")
}

Kamil Kisiel's avatar
Kamil Kisiel committed
25
// GraphiteClient is an object that is used to send messages to a Graphite server's UDP interface
26 27 28 29
type GraphiteClient struct {
	conn *net.Conn
}

Kamil Kisiel's avatar
Kamil Kisiel committed
30
// SendMetrics sends the metrics in a MetricsMap to the Graphite server
31 32 33 34 35 36 37 38 39 40 41 42 43
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
}
Kamil Kisiel's avatar
Kamil Kisiel committed
44 45 46 47 48 49 50

// 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
}