-
Notifications
You must be signed in to change notification settings - Fork 306
/
dogstatsd.js
259 lines (210 loc) · 5.93 KB
/
dogstatsd.js
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
'use strict'
const lookup = require('dns').lookup // cache to avoid instrumentation
const request = require('./exporters/common/request')
const dgram = require('dgram')
const isIP = require('net').isIP
const log = require('./log')
const { URL, format } = require('url')
const MAX_BUFFER_SIZE = 1024 // limit from the agent
const TYPE_COUNTER = 'c'
const TYPE_GAUGE = 'g'
const TYPE_DISTRIBUTION = 'd'
class DogStatsDClient {
constructor (options = {}) {
if (options.metricsProxyUrl) {
this._httpOptions = {
url: options.metricsProxyUrl.toString(),
path: '/dogstatsd/v2/proxy'
}
}
this._host = options.host || 'localhost'
this._family = isIP(this._host)
this._port = options.port || 8125
this._prefix = options.prefix || ''
this._tags = options.tags || []
this._queue = []
this._buffer = ''
this._offset = 0
this._udp4 = this._socket('udp4')
this._udp6 = this._socket('udp6')
}
increment (stat, value, tags) {
this._add(stat, value, TYPE_COUNTER, tags)
}
gauge (stat, value, tags) {
this._add(stat, value, TYPE_GAUGE, tags)
}
distribution (stat, value, tags) {
this._add(stat, value, TYPE_DISTRIBUTION, tags)
}
flush () {
const queue = this._enqueue()
log.debug(`Flushing ${queue.length} metrics via ${this._httpOptions ? 'HTTP' : 'UDP'}`)
if (this._queue.length === 0) return
this._queue = []
if (this._httpOptions) {
this._sendHttp(queue)
} else {
this._sendUdp(queue)
}
}
_sendHttp (queue) {
const buffer = Buffer.concat(queue)
request(buffer, this._httpOptions, (err) => {
if (err) {
log.error('HTTP error from agent: ' + err.stack)
if (err.status) {
// Inside this if-block, we have connectivity to the agent, but
// we're not getting a 200 from the proxy endpoint. If it's a 404,
// then we know we'll never have the endpoint, so just clear out the
// options. Either way, we can give UDP a try.
if (err.status === 404) {
this._httpOptions = null
}
this._sendUdp(queue)
}
}
})
}
_sendUdp (queue) {
if (this._family !== 0) {
this._sendUdpFromQueue(queue, this._host, this._family)
} else {
lookup(this._host, (err, address, family) => {
if (err) return log.error(err)
this._sendUdpFromQueue(queue, address, family)
})
}
}
_sendUdpFromQueue (queue, address, family) {
const socket = family === 6 ? this._udp6 : this._udp4
queue.forEach((buffer) => {
log.debug(`Sending to DogStatsD: ${buffer}`)
socket.send(buffer, 0, buffer.length, this._port, address)
})
}
_add (stat, value, type, tags) {
const message = `${this._prefix + stat}:${value}|${type}`
tags = tags ? this._tags.concat(tags) : this._tags
if (tags.length > 0) {
this._write(`${message}|#${tags.join(',')}\n`)
} else {
this._write(`${message}\n`)
}
}
_write (message) {
const offset = Buffer.byteLength(message)
if (this._offset + offset > MAX_BUFFER_SIZE) {
this._enqueue()
}
this._offset += offset
this._buffer += message
}
_enqueue () {
if (this._offset > 0) {
this._queue.push(Buffer.from(this._buffer))
this._buffer = ''
this._offset = 0
}
return this._queue
}
_socket (type) {
const socket = dgram.createSocket(type)
socket.on('error', () => {})
socket.unref()
return socket
}
static generateClientConfig (config = {}) {
const tags = []
if (config.tags) {
Object.keys(config.tags)
.filter(key => typeof config.tags[key] === 'string')
.filter(key => {
// Skip runtime-id unless enabled as cardinality may be too high
if (key !== 'runtime-id') return true
return (config.experimental && config.experimental.runtimeId)
})
.forEach(key => {
// https://docs.datadoghq.com/tagging/#defining-tags
const value = config.tags[key].replace(/[^a-z0-9_:./-]/ig, '_')
tags.push(`${key}:${value}`)
})
}
const clientConfig = {
host: config.dogstatsd.hostname,
port: config.dogstatsd.port,
tags
}
if (config.url) {
clientConfig.metricsProxyUrl = config.url
} else if (config.port) {
clientConfig.metricsProxyUrl = new URL(format({
protocol: 'http:',
hostname: config.hostname || 'localhost',
port: config.port
}))
}
return clientConfig
}
}
class NoopDogStatsDClient {
gauge () { }
increment () { }
distribution () { }
flush () { }
}
// This is a simplified user-facing proxy to the underlying DogStatsDClient instance
class CustomMetrics {
constructor (config) {
const clientConfig = DogStatsDClient.generateClientConfig(config)
this.dogstatsd = new DogStatsDClient(clientConfig)
}
increment (stat, value = 1, tags) {
return this.dogstatsd.increment(
stat,
value,
CustomMetrics.tagTranslator(tags)
)
}
decrement (stat, value = 1, tags) {
return this.dogstatsd.increment(
stat,
value * -1,
CustomMetrics.tagTranslator(tags)
)
}
gauge (stat, value, tags) {
return this.dogstatsd.gauge(
stat,
value,
CustomMetrics.tagTranslator(tags)
)
}
distribution (stat, value, tags) {
return this.dogstatsd.distribution(
stat,
value,
CustomMetrics.tagTranslator(tags)
)
}
flush () {
return this.dogstatsd.flush()
}
/**
* Exposing { tagName: 'tagValue' } to the end user
* These are translated into [ 'tagName:tagValue' ] for internal use
*/
static tagTranslator (objTags) {
const arrTags = []
if (!objTags) return arrTags
for (const [key, value] of Object.entries(objTags)) {
arrTags.push(`${key}:${value}`)
}
return arrTags
}
}
module.exports = {
DogStatsDClient,
NoopDogStatsDClient,
CustomMetrics
}