influxdb/services/graphite/graphite_udp.go

98 lines
1.8 KiB
Go
Raw Normal View History

package graphite
import (
"log"
"net"
2015-03-26 00:40:18 +00:00
"os"
"strings"
"sync"
2015-05-22 21:00:51 +00:00
"github.com/influxdb/influxdb/tsdb"
)
const (
udpBufferSize = 65536
)
2015-03-12 19:16:00 +00:00
// UDPServer processes Graphite data received via UDP.
type UDPServer struct {
writer SeriesWriter
parser *Parser
database string
2015-04-16 17:47:00 +00:00
conn *net.UDPConn
addr *net.UDPAddr
wg sync.WaitGroup
Logger *log.Logger
host string
}
// NewUDPServer returns a new instance of a UDPServer
func NewUDPServer(p *Parser, w SeriesWriter, db string) *UDPServer {
u := UDPServer{
parser: p,
writer: w,
database: db,
2015-03-26 00:40:18 +00:00
Logger: log.New(os.Stderr, "[graphite] ", log.LstdFlags),
}
return &u
}
2015-01-07 08:10:46 +00:00
// ListenAndServer instructs the UDPServer to start processing Graphite data
// on the given interface. iface must be in the form host:port.
func (u *UDPServer) ListenAndServe(iface string) error {
if iface == "" { // Make sure we have an address
return ErrBindAddressRequired
}
addr, err := net.ResolveUDPAddr("udp", iface)
if err != nil {
2015-04-03 02:01:19 +00:00
return err
}
2015-04-16 17:47:00 +00:00
u.addr = addr
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return err
}
u.host = u.addr.String()
buf := make([]byte, udpBufferSize)
u.wg.Add(1)
go func() {
defer u.wg.Done()
for {
n, _, err := conn.ReadFromUDP(buf)
if err != nil {
return
}
for _, line := range strings.Split(string(buf[:n]), "\n") {
point, err := u.parser.Parse(line)
if err != nil {
continue
}
// Send the data to the writer.
2015-05-22 21:00:51 +00:00
_, e := u.writer.WriteSeries(u.database, "", []tsdb.Point{point})
if e != nil {
2015-05-30 14:57:27 +00:00
u.Logger.Printf("unable to write data point: %s\n", e)
}
}
}
}()
return nil
}
2015-04-16 17:47:00 +00:00
func (u *UDPServer) Host() string {
return u.host
2015-04-16 17:47:00 +00:00
}
func (u *UDPServer) Close() error {
err := u.Close()
u.wg.Done()
return err
2015-04-16 17:47:00 +00:00
}