2019-01-24 20:15:10 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
2018-12-11 18:24:31 +00:00
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// GraphiteDest is a MetricDest that sends data with the Graphite TCP wire
|
|
|
|
// protocol
|
|
|
|
type GraphiteDest struct {
|
|
|
|
address string
|
2019-01-01 09:41:27 +00:00
|
|
|
|
|
|
|
mu sync.Mutex
|
2018-12-11 18:24:31 +00:00
|
|
|
conn net.Conn
|
|
|
|
buf *bufio.Writer
|
|
|
|
stopped bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewGraphiteDest creates a GraphiteDest with TCP address address. Because
|
|
|
|
// this function is called in a Lua pipeline domain-specific language, the DSL
|
|
|
|
// wants a graphite destination to be flushing every few seconds, so this
|
|
|
|
// constructor will start that process. Use Close to stop it.
|
|
|
|
func NewGraphiteDest(address string) *GraphiteDest {
|
|
|
|
rv := &GraphiteDest{address: address}
|
|
|
|
go rv.flush()
|
|
|
|
return rv
|
|
|
|
}
|
|
|
|
|
|
|
|
// Metric implements MetricDest
|
2019-01-01 09:41:27 +00:00
|
|
|
func (d *GraphiteDest) Metric(application, instance string, key []byte, val float64, ts time.Time) error {
|
|
|
|
d.mu.Lock()
|
|
|
|
defer d.mu.Unlock()
|
2018-12-11 18:24:31 +00:00
|
|
|
|
|
|
|
if d.conn == nil {
|
|
|
|
conn, err := net.Dial("tcp", d.address)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
d.conn = conn
|
|
|
|
d.buf = bufio.NewWriter(conn)
|
|
|
|
}
|
|
|
|
|
2019-01-01 09:41:27 +00:00
|
|
|
_, err := fmt.Fprintf(d.buf, "%s.%s.%s %v %d\n", application, string(key), instance, val, ts.Unix())
|
2018-12-11 18:24:31 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close stops the flushing goroutine
|
|
|
|
func (d *GraphiteDest) Close() error {
|
2019-01-01 09:41:27 +00:00
|
|
|
d.mu.Lock()
|
2018-12-11 18:24:31 +00:00
|
|
|
d.stopped = true
|
2019-01-01 09:41:27 +00:00
|
|
|
d.mu.Unlock()
|
2018-12-11 18:24:31 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *GraphiteDest) flush() {
|
|
|
|
for {
|
|
|
|
time.Sleep(5 * time.Second)
|
2019-01-01 09:41:27 +00:00
|
|
|
d.mu.Lock()
|
2018-12-11 18:24:31 +00:00
|
|
|
if d.stopped {
|
2019-01-01 09:41:27 +00:00
|
|
|
d.mu.Unlock()
|
2018-12-11 18:24:31 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
var err error
|
|
|
|
if d.buf != nil {
|
|
|
|
err = d.buf.Flush()
|
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
d.mu.Unlock()
|
2018-12-11 18:24:31 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("failed flushing: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|