-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathstatsd_parser.go
439 lines (372 loc) · 11.8 KB
/
statsd_parser.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package protocol // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/statsdreceiver/protocol"
import (
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/lightstep/go-expohisto/structure"
"go.opentelemetry.io/collector/client"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/otel/attribute"
)
var (
errEmptyMetricName = errors.New("empty metric name")
errEmptyMetricValue = errors.New("empty metric value")
)
type (
MetricType string // From the statsd line e.g., "c", "g", "h"
TypeName string // How humans describe the MetricTypes ("counter", "gauge")
ObserverType string // How the server will aggregate histogram and timings ("gauge", "summary")
)
const (
tagMetricType = "metric_type"
CounterType MetricType = "c"
GaugeType MetricType = "g"
HistogramType MetricType = "h"
TimingType MetricType = "ms"
CounterTypeName TypeName = "counter"
GaugeTypeName TypeName = "gauge"
HistogramTypeName TypeName = "histogram"
TimingTypeName TypeName = "timing"
TimingAltTypeName TypeName = "timer"
GaugeObserver ObserverType = "gauge"
SummaryObserver ObserverType = "summary"
HistogramObserver ObserverType = "histogram"
DisableObserver ObserverType = "disabled"
DefaultObserverType = DisableObserver
receiverName = "otelcol/statsdreceiver"
)
type TimerHistogramMapping struct {
StatsdType TypeName `mapstructure:"statsd_type"`
ObserverType ObserverType `mapstructure:"observer_type"`
Histogram HistogramConfig `mapstructure:"histogram"`
}
type HistogramConfig struct {
MaxSize int32 `mapstructure:"max_size"`
}
type ObserverCategory struct {
method ObserverType
histogramConfig structure.Config
}
var defaultObserverCategory = ObserverCategory{
method: DefaultObserverType,
}
// StatsDParser supports the Parse method for parsing StatsD messages with Tags.
type StatsDParser struct {
instrumentsByAddress map[netAddr]*instruments
enableMetricType bool
isMonotonicCounter bool
timerEvents ObserverCategory
histogramEvents ObserverCategory
lastIntervalTime time.Time
BuildInfo component.BuildInfo
}
type instruments struct {
addr net.Addr
gauges map[statsDMetricDescription]pmetric.ScopeMetrics
counters map[statsDMetricDescription]pmetric.ScopeMetrics
summaries map[statsDMetricDescription]summaryMetric
histograms map[statsDMetricDescription]histogramMetric
timersAndDistributions []pmetric.ScopeMetrics
}
func newInstruments(addr net.Addr) *instruments {
return &instruments{
addr: addr,
gauges: make(map[statsDMetricDescription]pmetric.ScopeMetrics),
counters: make(map[statsDMetricDescription]pmetric.ScopeMetrics),
summaries: make(map[statsDMetricDescription]summaryMetric),
histograms: make(map[statsDMetricDescription]histogramMetric),
}
}
type sampleValue struct {
value float64
count float64
}
type summaryMetric struct {
points []float64
weights []float64
}
type histogramStructure = structure.Histogram[float64]
type histogramMetric struct {
agg *histogramStructure
}
type statsDMetric struct {
description statsDMetricDescription
asFloat float64
addition bool
unit string
sampleRate float64
}
type statsDMetricDescription struct {
name string
metricType MetricType
attrs attribute.Set
}
func (t MetricType) FullName() TypeName {
switch t {
case GaugeType:
return GaugeTypeName
case CounterType:
return CounterTypeName
case TimingType:
return TimingTypeName
case HistogramType:
return HistogramTypeName
}
return TypeName(fmt.Sprintf("unknown(%s)", t))
}
func (p *StatsDParser) resetState(when time.Time) {
p.lastIntervalTime = when
p.instrumentsByAddress = make(map[netAddr]*instruments)
}
func (p *StatsDParser) Initialize(enableMetricType bool, isMonotonicCounter bool, sendTimerHistogram []TimerHistogramMapping) error {
p.resetState(timeNowFunc())
p.histogramEvents = defaultObserverCategory
p.timerEvents = defaultObserverCategory
p.enableMetricType = enableMetricType
p.isMonotonicCounter = isMonotonicCounter
// Note: validation occurs in ("../".Config).validate()
for _, eachMap := range sendTimerHistogram {
switch eachMap.StatsdType {
case HistogramTypeName:
p.histogramEvents.method = eachMap.ObserverType
p.histogramEvents.histogramConfig = expoHistogramConfig(eachMap.Histogram)
case TimingTypeName, TimingAltTypeName:
p.timerEvents.method = eachMap.ObserverType
p.timerEvents.histogramConfig = expoHistogramConfig(eachMap.Histogram)
}
}
return nil
}
func expoHistogramConfig(opts HistogramConfig) structure.Config {
var r []structure.Option
if opts.MaxSize >= structure.MinSize {
r = append(r, structure.WithMaxSize(opts.MaxSize))
}
return structure.NewConfig(r...)
}
// GetMetrics gets the metrics preparing for flushing and reset the state.
func (p *StatsDParser) GetMetrics() []BatchMetrics {
batchMetrics := make([]BatchMetrics, 0, len(p.instrumentsByAddress))
now := timeNowFunc()
for _, instrument := range p.instrumentsByAddress {
batch := BatchMetrics{
Info: client.Info{
Addr: instrument.addr,
},
Metrics: pmetric.NewMetrics(),
}
rm := batch.Metrics.ResourceMetrics().AppendEmpty()
for _, metric := range instrument.gauges {
p.copyMetricAndScope(rm, metric)
}
for _, metric := range instrument.timersAndDistributions {
p.copyMetricAndScope(rm, metric)
}
for _, metric := range instrument.counters {
setTimestampsForCounterMetric(metric, p.lastIntervalTime, now)
p.copyMetricAndScope(rm, metric)
}
for desc, summaryMetric := range instrument.summaries {
ilm := rm.ScopeMetrics().AppendEmpty()
p.setVersionAndNameScope(ilm.Scope())
buildSummaryMetric(
desc,
summaryMetric,
p.lastIntervalTime,
now,
statsDDefaultPercentiles,
ilm,
)
}
for desc, histogramMetric := range instrument.histograms {
ilm := rm.ScopeMetrics().AppendEmpty()
p.setVersionAndNameScope(ilm.Scope())
buildHistogramMetric(
desc,
histogramMetric,
p.lastIntervalTime,
now,
ilm,
)
}
batchMetrics = append(batchMetrics, batch)
}
p.resetState(now)
return batchMetrics
}
func (p *StatsDParser) copyMetricAndScope(rm pmetric.ResourceMetrics, metric pmetric.ScopeMetrics) {
ilm := rm.ScopeMetrics().AppendEmpty()
metric.CopyTo(ilm)
p.setVersionAndNameScope(ilm.Scope())
}
func (p *StatsDParser) setVersionAndNameScope(ilm pcommon.InstrumentationScope) {
ilm.SetVersion(p.BuildInfo.Version)
ilm.SetName(receiverName)
}
var timeNowFunc = time.Now
func (p *StatsDParser) observerCategoryFor(t MetricType) ObserverCategory {
switch t {
case HistogramType:
return p.histogramEvents
case TimingType:
return p.timerEvents
}
return defaultObserverCategory
}
// Aggregate for each metric line.
func (p *StatsDParser) Aggregate(line string, addr net.Addr) error {
parsedMetric, err := parseMessageToMetric(line, p.enableMetricType)
if err != nil {
return err
}
addrKey := newNetAddr(addr)
instrument, ok := p.instrumentsByAddress[addrKey]
if !ok {
instrument = newInstruments(addr)
p.instrumentsByAddress[addrKey] = instrument
}
switch parsedMetric.description.metricType {
case GaugeType:
_, ok := instrument.gauges[parsedMetric.description]
if !ok {
instrument.gauges[parsedMetric.description] = buildGaugeMetric(parsedMetric, timeNowFunc())
} else {
if parsedMetric.addition {
point := instrument.gauges[parsedMetric.description].Metrics().At(0).Gauge().DataPoints().At(0)
point.SetDoubleValue(point.DoubleValue() + parsedMetric.gaugeValue())
} else {
instrument.gauges[parsedMetric.description] = buildGaugeMetric(parsedMetric, timeNowFunc())
}
}
case CounterType:
_, ok := instrument.counters[parsedMetric.description]
if !ok {
instrument.counters[parsedMetric.description] = buildCounterMetric(parsedMetric, p.isMonotonicCounter)
} else {
point := instrument.counters[parsedMetric.description].Metrics().At(0).Sum().DataPoints().At(0)
point.SetIntValue(point.IntValue() + parsedMetric.counterValue())
}
case TimingType, HistogramType:
category := p.observerCategoryFor(parsedMetric.description.metricType)
switch category.method {
case GaugeObserver:
instrument.timersAndDistributions = append(instrument.timersAndDistributions, buildGaugeMetric(parsedMetric, timeNowFunc()))
case SummaryObserver:
raw := parsedMetric.sampleValue()
if existing, ok := instrument.summaries[parsedMetric.description]; !ok {
instrument.summaries[parsedMetric.description] = summaryMetric{
points: []float64{raw.value},
weights: []float64{raw.count},
}
} else {
instrument.summaries[parsedMetric.description] = summaryMetric{
points: append(existing.points, raw.value),
weights: append(existing.weights, raw.count),
}
}
case HistogramObserver:
raw := parsedMetric.sampleValue()
var agg *histogramStructure
if existing, ok := instrument.histograms[parsedMetric.description]; ok {
agg = existing.agg
} else {
agg = new(histogramStructure)
agg.Init(category.histogramConfig)
instrument.histograms[parsedMetric.description] = histogramMetric{
agg: agg,
}
}
agg.UpdateByIncr(
raw.value,
uint64(raw.count), // Note! Rounding float64 to uint64 here.
)
case DisableObserver:
// No action.
}
}
return nil
}
func parseMessageToMetric(line string, enableMetricType bool) (statsDMetric, error) {
result := statsDMetric{}
parts := strings.Split(line, "|")
if len(parts) < 2 {
return result, fmt.Errorf("invalid message format: %s", line)
}
separatorIndex := strings.IndexByte(parts[0], ':')
if separatorIndex < 0 {
return result, fmt.Errorf("invalid <name>:<value> format: %s", parts[0])
}
result.description.name = parts[0][0:separatorIndex]
if result.description.name == "" {
return result, errEmptyMetricName
}
valueStr := parts[0][separatorIndex+1:]
if valueStr == "" {
return result, errEmptyMetricValue
}
if strings.HasPrefix(valueStr, "-") || strings.HasPrefix(valueStr, "+") {
result.addition = true
}
inType := MetricType(parts[1])
switch inType {
case CounterType, GaugeType, HistogramType, TimingType:
result.description.metricType = inType
default:
return result, fmt.Errorf("unsupported metric type: %s", inType)
}
additionalParts := parts[2:]
var kvs []attribute.KeyValue
for _, part := range additionalParts {
switch {
case strings.HasPrefix(part, "@"):
sampleRateStr := strings.TrimPrefix(part, "@")
f, err := strconv.ParseFloat(sampleRateStr, 64)
if err != nil {
return result, fmt.Errorf("parse sample rate: %s", sampleRateStr)
}
result.sampleRate = f
case strings.HasPrefix(part, "#"):
tagsStr := strings.TrimPrefix(part, "#")
tagSets := strings.Split(tagsStr, ",")
for _, tagSet := range tagSets {
tagParts := strings.SplitN(tagSet, ":", 2)
if len(tagParts) != 2 {
return result, fmt.Errorf("invalid tag format: %s", tagParts)
}
k := tagParts[0]
v := tagParts[1]
kvs = append(kvs, attribute.String(k, v))
}
default:
return result, fmt.Errorf("unrecognized message part: %s", part)
}
}
var err error
result.asFloat, err = strconv.ParseFloat(valueStr, 64)
if err != nil {
return result, fmt.Errorf("parse metric value string: %s", valueStr)
}
// add metric_type dimension for all metrics
if enableMetricType {
metricType := string(result.description.metricType.FullName())
kvs = append(kvs, attribute.String(tagMetricType, metricType))
}
if len(kvs) != 0 {
result.description.attrs = attribute.NewSet(kvs...)
}
return result, nil
}
type netAddr struct {
Network string
String string
}
func newNetAddr(addr net.Addr) netAddr {
return netAddr{addr.Network(), addr.String()}
}