Skip to content
Snippets Groups Projects
Commit 06921718 authored by ale's avatar ale
Browse files

make the GraphiteClient reconnect on error

parent 1d3ac345
No related branches found
No related tags found
No related merge requests found
......@@ -2,9 +2,10 @@ package main
import (
"flag"
"github.com/kisielk/gostatsd/statsd"
"log"
"time"
"git.autistici.org/ale/gostatsd/statsd"
)
const (
......
......@@ -5,6 +5,7 @@ import (
"fmt"
"net"
"regexp"
"sync"
"time"
)
......@@ -24,19 +25,38 @@ func normalizeBucketName(name string) string {
// GraphiteClient is an object that is used to send messages to a Graphite server's UDP interface
type GraphiteClient struct {
conn *net.Conn
addr string
conn net.Conn
lock sync.Mutex
}
// SendMetrics sends the metrics in a MetricsMap to the Graphite server
func (client *GraphiteClient) SendMetrics(metrics MetricMap) (err error) {
// Connect opportunistically.
client.lock.Lock()
if client.conn == nil {
client.conn, err = net.Dial("tcp", client.addr)
}
conn := client.conn
client.lock.Unlock()
if err != nil {
return err
}
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)
_, err = buf.WriteTo(conn)
if err != nil {
conn.Close()
client.lock.Lock()
if client.conn == conn {
client.conn = nil
}
client.lock.Unlock()
return err
}
return nil
......@@ -44,7 +64,6 @@ func (client *GraphiteClient) SendMetrics(metrics MetricMap) (err error) {
// 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}
client = GraphiteClient{addr: addr}
return
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment