Commit 06921718 authored by ale's avatar ale

make the GraphiteClient reconnect on error

parent 1d3ac345
...@@ -2,9 +2,10 @@ package main ...@@ -2,9 +2,10 @@ package main
import ( import (
"flag" "flag"
"github.com/kisielk/gostatsd/statsd"
"log" "log"
"time" "time"
"git.autistici.org/ale/gostatsd/statsd"
) )
const ( const (
......
...@@ -5,6 +5,7 @@ import ( ...@@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"net" "net"
"regexp" "regexp"
"sync"
"time" "time"
) )
...@@ -24,19 +25,38 @@ func normalizeBucketName(name string) string { ...@@ -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 // GraphiteClient is an object that is used to send messages to a Graphite server's UDP interface
type GraphiteClient struct { 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 // SendMetrics sends the metrics in a MetricsMap to the Graphite server
func (client *GraphiteClient) SendMetrics(metrics MetricMap) (err error) { 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) buf := new(bytes.Buffer)
now := time.Now().Unix() now := time.Now().Unix()
for k, v := range metrics { for k, v := range metrics {
nk := normalizeBucketName(k) nk := normalizeBucketName(k)
fmt.Fprintf(buf, "%s %f %d\n", nk, v, now) fmt.Fprintf(buf, "%s %f %d\n", nk, v, now)
} }
_, err = buf.WriteTo(*client.conn) _, err = buf.WriteTo(conn)
if err != nil { if err != nil {
conn.Close()
client.lock.Lock()
if client.conn == conn {
client.conn = nil
}
client.lock.Unlock()
return err return err
} }
return nil return nil
...@@ -44,7 +64,6 @@ func (client *GraphiteClient) SendMetrics(metrics MetricMap) (err error) { ...@@ -44,7 +64,6 @@ func (client *GraphiteClient) SendMetrics(metrics MetricMap) (err error) {
// NewGraphiteClient constructs a GraphiteClient object by connecting to an address // NewGraphiteClient constructs a GraphiteClient object by connecting to an address
func NewGraphiteClient(addr string) (client GraphiteClient, err error) { func NewGraphiteClient(addr string) (client GraphiteClient, err error) {
conn, err := net.Dial("tcp", addr) client = GraphiteClient{addr: addr}
client = GraphiteClient{&conn}
return return
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment