-
Notifications
You must be signed in to change notification settings - Fork 32
/
client.go
246 lines (204 loc) · 5.99 KB
/
client.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
package datadog
import (
"bytes"
"io"
"log"
"net"
"os"
"syscall"
"time"
"github.com/segmentio/stats"
)
const (
// DefaultAddress is the default address to which the datadog client tries
// to connect to.
DefaultAddress = "localhost:8125"
// DefaultBufferSize is the default size for batches of metrics sent to
// datadog.
DefaultBufferSize = 1024
// MaxBufferSize is a hard-limit on the max size of the datagram buffer.
MaxBufferSize = 65507
)
// DefaultFilter is the default tag to filter before sending to
// datadog. Using the request path as a tag can overwhelm datadog's
// servers if there are too many unique routes due to unique IDs being a
// part of the path. Only change the default filter if there is a static
// number of routes.
var (
DefaultFilters = []string{"http_req_path"}
)
// The ClientConfig type is used to configure datadog clients.
type ClientConfig struct {
// Address of the datadog database to send metrics to.
Address string
// Maximum size of batch of events sent to datadog.
BufferSize int
// List of tags to filter. If left nil is set to DefaultFilters.
Filters []string
}
// Client represents an datadog client that implements the stats.Handler
// interface.
type Client struct {
serializer
err error
buffer stats.Buffer
}
// NewClient creates and returns a new datadog client publishing metrics to the
// server running at addr.
func NewClient(addr string) *Client {
return NewClientWith(ClientConfig{
Address: addr,
})
}
// NewClientWith creates and returns a new datadog client configured with the
// given config.
func NewClientWith(config ClientConfig) *Client {
if len(config.Address) == 0 {
config.Address = DefaultAddress
}
if config.BufferSize == 0 {
config.BufferSize = DefaultBufferSize
}
if config.Filters == nil {
config.Filters = DefaultFilters
}
// transform filters from array to map
filterMap := make(map[string]struct{})
for _, f := range config.Filters {
filterMap[f] = struct{}{}
}
c := &Client{
serializer: serializer{
filters: filterMap,
},
}
conn, bufferSize, err := dial(config.Address, config.BufferSize)
if err != nil {
log.Printf("stats/datadog: %s", err)
}
c.conn, c.err, c.bufferSize = conn, err, bufferSize
c.buffer.BufferSize = bufferSize
c.buffer.Serializer = &c.serializer
log.Printf("stats/datadog: sending metrics with a buffer of size %d B", bufferSize)
return c
}
// HandleMetric satisfies the stats.Handler interface.
func (c *Client) HandleMeasures(time time.Time, measures ...stats.Measure) {
c.buffer.HandleMeasures(time, measures...)
}
// Flush satisfies the stats.Flusher interface.
func (c *Client) Flush() {
c.buffer.Flush()
}
// Write satisfies the io.Writer interface.
func (c *Client) Write(b []byte) (int, error) {
return c.serializer.Write(b)
}
// Close flushes and closes the client, satisfies the io.Closer interface.
func (c *Client) Close() error {
c.Flush()
c.close()
return c.err
}
type serializer struct {
conn net.Conn
bufferSize int
filters map[string]struct{}
}
func (s *serializer) AppendMeasures(b []byte, _ time.Time, measures ...stats.Measure) []byte {
for _, m := range measures {
b = AppendMeasureFiltered(b, m, s.filters)
}
return b
}
func (s *serializer) Write(b []byte) (int, error) {
if s.conn == nil {
return 0, io.ErrClosedPipe
}
if len(b) <= s.bufferSize {
return s.conn.Write(b)
}
// When the serialized metrics are larger than the configured socket buffer
// size we split them on '\n' characters.
var n int
for len(b) != 0 {
var splitIndex int
for splitIndex != len(b) {
i := bytes.IndexByte(b[splitIndex:], '\n')
if i < 0 {
panic("stats/datadog: metrics are not formatted for the dogstatsd protocol")
}
if (i + splitIndex) >= s.bufferSize {
if splitIndex == 0 {
log.Printf("stats/datadog: metric of length %d B doesn't fit in the socket buffer of size %d B: %s", i+1, s.bufferSize, string(b))
b = b[i+1:]
continue
}
break
}
splitIndex += i + 1
}
c, err := s.conn.Write(b[:splitIndex])
if err != nil {
return n + c, err
}
n += c
b = b[splitIndex:]
}
return n, nil
}
func (s *serializer) close() {
if s.conn != nil {
s.conn.Close()
}
}
func dial(address string, sizehint int) (conn net.Conn, bufsize int, err error) {
var f *os.File
if conn, err = net.Dial("udp", address); err != nil {
return
}
if f, err = conn.(*net.UDPConn).File(); err != nil {
conn.Close()
return
}
defer f.Close()
fd := int(f.Fd())
// The kernel refuses to send UDP datagrams that are larger than the size of
// the size of the socket send buffer. To maximize the number of metrics
// sent in one batch we attempt to attempt to adjust the kernel buffer size
// to accept larger datagrams, or fallback to the default socket buffer size
// if it failed.
if bufsize, err = syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF); err != nil {
conn.Close()
return
}
// The kernel applies a 2x factor on the socket buffer size, only half of it
// is available to write datagrams from user-space, the other half is used
// by the kernel directly.
bufsize /= 2
for sizehint > bufsize && sizehint > 0 {
if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, sizehint); err == nil {
bufsize = sizehint
break
}
sizehint /= 2
}
// Even tho the buffer agrees to support a bigger size it shouldn't be
// possible to send datagrams larger than 65 KB on an IPv4 socket, so let's
// enforce the max size.
if bufsize > MaxBufferSize {
bufsize = MaxBufferSize
}
// Use the size hint as an upper bound, event if the socket buffer is
// larger, this gives control in situations where the receive buffer size
// on the other side is known but cannot be controlled so the client does
// not produce datagrams that are too large for the receiver.
//
// Related issue: https://github.com/DataDog/dd-agent/issues/2638
if bufsize > sizehint {
bufsize = sizehint
}
// Creating the file put the socket in blocking mode, reverting.
syscall.SetNonblock(fd, true)
return
}