-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathriemann.go
277 lines (252 loc) · 6.09 KB
/
riemann.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Copyright 2015 Jacek Masiulaniec. All rights reserved.
// Use of this source code is governed by a free license that can be
// found in the LICENSE file.
// Package riemann implements a Riemann client.
package riemann
import (
"errors"
"io"
"io/ioutil"
"log"
"net"
"os"
"strings"
"time"
riemann "github.com/masiulaniec/riemann/proto"
"github.com/golang/protobuf/proto"
)
// Client flushes every 100 events or every 1 second, whichever occurs first
const (
frameMaxEvents = 100
frameMaxDelay = 1 * time.Second
)
const (
poolDefaultSize = 1 // how many parallel conns?
poolMaxQueue = 100000 // sender-side safety buffer
)
// errClosed is used internally to signal connection close.
var errClosed = errors.New("client closed")
// Event represents a Riemann event.
type Event struct {
Host string // sending host
Service string // the service the event pertains to
IsFloat bool // value type
Float float64 // value if IsFloat
Int int64 // value if !IsFloat
// Optional
Description string // arbitrary text
Time int64 // creation time (unix epoch)
TTL float32 // time to live (seconds)
State string // associated health state
Tags []string // list of string labels
Attributes []string // list of key, value pairs
}
func (e *Event) validate() error {
if e.Host == "" {
hostname, err := os.Hostname()
if err != nil {
return err
}
e.Host = hostname
}
if e.Time == 0 {
now := time.Now().Unix()
e.Time = now
}
if e.Service == "" {
return errors.New("undefined service")
}
if e.IsFloat && e.Int != 0 {
return errors.New("float event with non-float value")
}
return nil
}
// ClientConfig can be used to override Client settings.
type ClientConfig struct {
// PoolSize defines how many TCP connections to create.
// Default: 1
PoolSize int
}
// Client represents a Riemann client.
type Client struct {
addr string
pool chan *Event
}
// NewClient returns a client for Riemann server listening at
// the given address. If nil config is provided, default settings
// are used.
func NewClient(addr string, config *ClientConfig) *Client {
if config == nil {
config = &ClientConfig{}
}
if config.PoolSize == 0 {
config.PoolSize = poolDefaultSize
}
client := &Client{
addr: addr,
pool: make(chan *Event, poolMaxQueue),
}
for i := 0; i < config.PoolSize; i++ {
go client.conn()
}
return client
}
// Close terminates the client by closing its connection pool.
func (c *Client) Close() error {
close(c.pool)
return nil
}
// Send tries to delivier the given event. Delivery is not guaranteed.
// Send will panic if the given event is invalid.
func (c *Client) Send(event *Event) {
if err := event.validate(); err != nil {
log.Panic(err)
}
select {
case c.pool <- event:
// ok
default:
// Data loss.
}
}
// conn keeps alive a connection to the server.
func (c *Client) conn() {
for {
err := c.conn1()
if err == errClosed {
return
}
log.Printf("riemann: server %s: %v", c.addr, err)
time.Sleep(5 * time.Second)
}
}
func (c *Client) conn1() error {
addr := c.addr
if !strings.HasSuffix(addr, ":5555") {
addr += ":5555"
}
conn, err := net.Dial("tcp", addr)
if err != nil {
return err
}
defer conn.Close()
go c.readLoop(conn)
return c.writeLoop(conn)
}
// writeLoop sends requests to the server.
func (c *Client) writeLoop(w io.Writer) error {
frame := new(frame)
frame.Reset()
timer := time.NewTimer(frameMaxDelay)
defer timer.Stop()
for {
select {
case event, ok := <-c.pool:
if !ok {
return errClosed
}
frame.append(event)
if frame.Len == frameMaxEvents {
if _, err := w.Write(frame.Bytes()); err != nil {
return err
}
frame.Reset()
timer.Reset(frameMaxDelay)
}
case <-timer.C:
if frame.Len > 0 {
if _, err := w.Write(frame.Bytes()); err != nil {
return err
}
frame.Reset()
}
timer.Reset(frameMaxDelay)
}
}
}
// readLoop processes server responses.
func (c *Client) readLoop(r io.Reader) {
// Just discard the acks. We know they are acks and not errors
// because invalid messages are never transmitted. Instead,
// bad data is detected eagerly in (*Client).Send, which helps
// identify faulty call sites.
io.Copy(ioutil.Discard, r)
}
// frame represents a Riemann frame.
type frame struct {
proto.Buffer // holds Riemann header and protobuf body
Len int // number of events buffered
event riemann.Event // helps avoid an allocation
scratch [512]byte // helps avoid an allocation
}
// Reset prepares a new frame.
func (fr *frame) Reset() {
fr.Buffer.Reset()
// Reserve space for Riemann's frame header.
fr.EncodeFixed32(0)
fr.Len = 0
}
// Bytes returns the frame in a ready-to-write form.
func (fr *frame) Bytes() []byte {
var (
header = fr.Buffer.Bytes()[:4]
body = fr.Buffer.Bytes()[4:]
)
bodyLen := uint32(len(body))
header[0] = byte(bodyLen >> 24)
header[1] = byte(bodyLen >> 16)
header[2] = byte(bodyLen >> 8)
header[3] = byte(bodyLen >> 0)
return fr.Buffer.Bytes()
}
// append encodes the given event in the frame.
func (fr *frame) append(event *Event) {
e := &fr.event
// Prepare the event for marshaling.
e.Time = &event.Time
if event.State != "" {
e.State = &event.State
} else {
e.State = nil
}
e.Service = &event.Service
e.Host = &event.Host
if event.Description != "" {
e.Description = &event.Description
} else {
e.Description = nil
}
e.Tags = event.Tags
if event.TTL != 0 {
e.Ttl = &event.TTL
} else {
e.Ttl = nil
}
if event.IsFloat {
e.MetricSint64 = nil
e.MetricD = &event.Float
} else {
e.MetricSint64 = &event.Int
e.MetricD = nil
}
e.Attributes = e.Attributes[:0]
for i := 0; i < len(event.Attributes); i += 2 {
attr := &riemann.Attribute{
Key: &event.Attributes[i],
Value: &event.Attributes[i+1],
}
e.Attributes = append(e.Attributes, attr)
}
// Marshal it.
ebuf := proto.NewBuffer(fr.scratch[:0])
if err := ebuf.Marshal(e); err != nil {
panic(err)
}
if err := fr.EncodeVarint(6<<3 | proto.WireBytes); err != nil {
panic(err)
}
if err := fr.EncodeRawBytes(ebuf.Bytes()); err != nil {
panic(err)
}
fr.Len++
}