forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
188 lines (156 loc) · 4.16 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package udp
import (
"errors"
"expvar"
"log"
"net"
"strings"
"sync"
"github.com/influxdb/influxdb"
"github.com/influxdb/influxdb/cluster"
"github.com/influxdb/influxdb/models"
)
const (
UDPPacketSize = 65536
)
// statistics gathered by the UDP package.
const (
statPointsReceived = "points_rx"
statBytesReceived = "bytes_rx"
statPointsParseFail = "points_parse_fail"
statReadFail = "read_fail"
statPointsTransmitted = "points_tx"
statTransmitFail = "tx_fail"
)
//
// Service represents here an UDP service
// that will listen for incoming packets
// formatted with the inline protocol
//
type Service struct {
conn *net.UDPConn
addr *net.UDPAddr
wg sync.WaitGroup
done chan struct{}
packets chan []byte
config Config
PointsWriter interface {
WritePoints(p *cluster.WritePointsRequest) error
}
Logger *log.Logger
statMap *expvar.Map
}
func NewService(c Config, l *log.Logger) *Service {
d := *c.WithDefaults()
return &Service{
config: d,
done: make(chan struct{}),
Logger: l,
}
}
func (s *Service) Open() (err error) {
// 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)
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")
}
s.addr, err = net.ResolveUDPAddr("udp", s.config.BindAddress)
if err != nil {
s.Logger.Printf("E! 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("E! 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("E! Failed to set UDP read buffer to %d: %s", s.config.ReadBuffer, err)
return err
}
}
//save fully resolved and bound addr. Useful if port given was '0'.
s.addr = s.conn.LocalAddr().(*net.UDPAddr)
s.Logger.Printf("I! Started listening on UDP: %s", s.addr.String())
// Start reading and processing packets
s.packets = make(chan []byte, s.config.Buffer)
s.wg.Add(1)
go s.serve()
s.wg.Add(1)
go s.processPackets()
return nil
}
func (s *Service) serve() {
defer s.wg.Done()
defer close(s.packets)
buf := make([]byte, UDPPacketSize)
for {
select {
case <-s.done:
// We closed the connection, time to go.
return
default:
// Keep processing.
}
n, _, err := s.conn.ReadFromUDP(buf)
if err != nil {
if !strings.Contains(err.Error(), "use of closed network connection") {
s.statMap.Add(statReadFail, 1)
s.Logger.Printf("E! Failed to read UDP message: %s", err)
}
continue
}
s.statMap.Add(statBytesReceived, int64(n))
p := make([]byte, n)
copy(p, buf[:n])
s.packets <- p
}
}
func (s *Service) processPackets() {
defer s.wg.Done()
for p := range s.packets {
points, err := models.ParsePoints(p)
if err != nil {
s.statMap.Add(statPointsParseFail, 1)
s.Logger.Printf("E! Failed to parse points: %s", err)
continue
}
if err := s.PointsWriter.WritePoints(&cluster.WritePointsRequest{
Database: s.config.Database,
RetentionPolicy: s.config.RetentionPolicy,
ConsistencyLevel: cluster.ConsistencyLevelOne,
Points: points,
}); err == nil {
s.statMap.Add(statPointsTransmitted, int64(len(points)))
} else {
s.Logger.Printf("E! failed to write points to database %q: %s", s.config.Database, err)
s.statMap.Add(statTransmitFail, 1)
}
s.statMap.Add(statPointsReceived, int64(len(points)))
}
}
func (s *Service) Close() error {
if s.conn == nil {
return errors.New("Service already closed")
}
close(s.done)
s.conn.Close()
s.wg.Wait()
// Release all remaining resources.
s.done = nil
s.conn = nil
s.packets = nil
s.Logger.Print("I! Service closed")
return nil
}
func (s *Service) Addr() net.Addr {
return s.addr
}