influxdb/services/udp/service.go

227 lines
5.2 KiB
Go
Raw Normal View History

2016-02-10 18:30:52 +00:00
package udp // import "github.com/influxdata/influxdb/services/udp"
2015-06-03 13:06:36 +00:00
import (
2015-06-04 23:07:34 +00:00
"errors"
2015-09-09 01:47:41 +00:00
"expvar"
2015-06-04 23:07:34 +00:00
"log"
2015-06-03 13:06:36 +00:00
"net"
2015-06-04 23:07:34 +00:00
"os"
2015-09-09 01:47:41 +00:00
"strings"
2015-06-04 23:07:34 +00:00
"sync"
2015-06-03 13:06:36 +00:00
"time"
2015-06-04 23:07:34 +00:00
"github.com/influxdata/influxdb"
"github.com/influxdata/influxdb/cluster"
"github.com/influxdata/influxdb/models"
"github.com/influxdata/influxdb/services/meta"
"github.com/influxdata/influxdb/tsdb"
2015-06-04 23:07:34 +00:00
)
const (
// Arbitrary, testing indicated that this doesn't typically get over 10
parserChanLen = 1000
2015-06-03 13:06:36 +00:00
)
2015-09-09 01:47:41 +00:00
// statistics gathered by the UDP package.
const (
statPointsReceived = "pointsRx"
statBytesReceived = "bytesRx"
statPointsParseFail = "pointsParseFail"
statReadFail = "readFail"
statBatchesTrasmitted = "batchesTx"
statPointsTransmitted = "pointsTx"
statBatchesTransmitFail = "batchesTxFail"
2015-09-09 01:47:41 +00:00
)
2015-06-04 23:07:34 +00:00
//
// Service represents here an UDP service
// that will listen for incoming packets
// formatted with the inline protocol
//
2015-06-03 13:06:36 +00:00
type Service struct {
2015-06-04 23:07:34 +00:00
conn *net.UDPConn
addr *net.UDPAddr
wg sync.WaitGroup
done chan struct{}
2015-06-03 13:06:36 +00:00
parserChan chan []byte
batcher *tsdb.PointBatcher
config Config
2015-06-04 23:07:34 +00:00
PointsWriter interface {
WritePoints(p *cluster.WritePointsRequest) error
}
2015-12-23 15:48:25 +00:00
MetaClient interface {
CreateDatabase(name string) (*meta.DatabaseInfo, error)
}
2015-09-09 01:47:41 +00:00
Logger *log.Logger
statMap *expvar.Map
2015-06-03 13:06:36 +00:00
}
// NewService returns a new instance of Service.
2015-06-03 13:06:36 +00:00
func NewService(c Config) *Service {
2015-09-08 22:25:42 +00:00
d := *c.WithDefaults()
2015-06-03 13:06:36 +00:00
return &Service{
config: d,
done: make(chan struct{}),
parserChan: make(chan []byte, parserChanLen),
batcher: tsdb.NewPointBatcher(d.BatchSize, d.BatchPending, time.Duration(d.BatchTimeout)),
Logger: log.New(os.Stderr, "[udp] ", log.LstdFlags),
2015-06-04 23:07:34 +00:00
}
}
// Open starts the service
2015-06-04 23:07:34 +00:00
func (s *Service) Open() (err error) {
2015-09-09 01:47:41 +00:00
// Configure expvar monitoring. It's OK to do this even if the service fails to open and
// should be done before any data could arrive for the service.
key := strings.Join([]string{"udp", s.config.BindAddress}, ":")
tags := map[string]string{"bind": s.config.BindAddress}
s.statMap = influxdb.NewStatistics(key, "udp", tags)
2015-06-04 23:07:34 +00:00
if s.config.BindAddress == "" {
return errors.New("bind address has to be specified in config")
}
if s.config.Database == "" {
return errors.New("database has to be specified in config")
}
if _, err := s.MetaClient.CreateDatabase(s.config.Database); err != nil {
return errors.New("Failed to ensure target database exists")
}
2015-06-04 23:07:34 +00:00
s.addr, err = net.ResolveUDPAddr("udp", s.config.BindAddress)
if err != nil {
s.Logger.Printf("Failed to resolve UDP address %s: %s", s.config.BindAddress, err)
return err
}
s.conn, err = net.ListenUDP("udp", s.addr)
if err != nil {
s.Logger.Printf("Failed to set up UDP listener at address %s: %s", s.addr, err)
return err
}
if s.config.ReadBuffer != 0 {
err = s.conn.SetReadBuffer(s.config.ReadBuffer)
if err != nil {
s.Logger.Printf("Failed to set UDP read buffer to %d: %s",
s.config.ReadBuffer, err)
return err
}
}
2015-06-04 23:07:34 +00:00
s.Logger.Printf("Started listening on UDP: %s", s.config.BindAddress)
2015-06-04 23:07:34 +00:00
s.wg.Add(3)
2015-06-04 23:07:34 +00:00
go s.serve()
go s.parser()
go s.writer()
2015-06-04 23:07:34 +00:00
return nil
}
func (s *Service) writer() {
2015-06-04 23:07:34 +00:00
defer s.wg.Done()
for {
select {
case batch := <-s.batcher.Out():
2015-09-09 01:47:41 +00:00
if err := s.PointsWriter.WritePoints(&cluster.WritePointsRequest{
2015-06-04 23:07:34 +00:00
Database: s.config.Database,
RetentionPolicy: s.config.RetentionPolicy,
2015-06-04 23:07:34 +00:00
ConsistencyLevel: cluster.ConsistencyLevelOne,
Points: batch,
2015-09-09 01:47:41 +00:00
}); err == nil {
s.statMap.Add(statBatchesTrasmitted, 1)
s.statMap.Add(statPointsTransmitted, int64(len(batch)))
} else {
s.Logger.Printf("failed to write point batch to database %q: %s", s.config.Database, err)
s.statMap.Add(statBatchesTransmitFail, 1)
2015-06-04 23:07:34 +00:00
}
2015-06-04 23:07:34 +00:00
case <-s.done:
return
}
2015-06-03 13:06:36 +00:00
}
}
2015-06-04 23:07:34 +00:00
func (s *Service) serve() {
defer s.wg.Done()
s.batcher.Start()
for {
select {
case <-s.done:
// We closed the connection, time to go.
return
default:
// Keep processing.
buf := make([]byte, s.config.UDPPayloadSize)
n, _, err := s.conn.ReadFromUDP(buf)
if err != nil {
s.statMap.Add(statReadFail, 1)
s.Logger.Printf("Failed to read UDP message: %s", err)
continue
}
s.statMap.Add(statBytesReceived, int64(n))
s.parserChan <- buf[:n]
2015-06-04 23:07:34 +00:00
}
}
}
2015-06-04 23:07:34 +00:00
func (s *Service) parser() {
defer s.wg.Done()
2015-06-04 23:07:34 +00:00
for {
select {
case <-s.done:
return
case buf := <-s.parserChan:
points, err := models.ParsePointsWithPrecision(buf, time.Now().UTC(), s.config.Precision)
if err != nil {
s.statMap.Add(statPointsParseFail, 1)
s.Logger.Printf("Failed to parse points: %s", err)
continue
}
2015-06-04 23:07:34 +00:00
for _, point := range points {
s.batcher.In() <- point
}
s.statMap.Add(statPointsReceived, int64(len(points)))
2015-06-04 23:07:34 +00:00
}
}
2015-06-03 13:06:36 +00:00
}
// Close closes the underlying listener.
2015-06-03 13:06:36 +00:00
func (s *Service) Close() error {
2015-06-04 23:07:34 +00:00
if s.conn == nil {
return errors.New("Service already closed")
}
s.conn.Close()
s.batcher.Flush()
close(s.done)
s.wg.Wait()
// Release all remaining resources.
s.done = nil
s.conn = nil
s.Logger.Print("Service closed")
return nil
2015-06-03 13:06:36 +00:00
}
// SetLogger sets the internal logger to the logger passed in.
func (s *Service) SetLogger(l *log.Logger) {
s.Logger = l
}
// Addr returns the listener's address
2015-06-03 13:06:36 +00:00
func (s *Service) Addr() net.Addr {
2015-06-04 23:07:34 +00:00
return s.addr
2015-06-03 13:06:36 +00:00
}