/
serializer.go
249 lines (216 loc) · 7.3 KB
/
serializer.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
package opentsdbexporter
import (
"bytes"
"fmt"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.uber.org/zap"
"regexp"
"strings"
)
type Metric struct {
Metric string `json:"metric"`
Timestamp uint64 `json:"timestamp"`
Value interface{} `json:"value"`
Tags map[string]string `json:"tags"`
}
func (m Metric) String() string {
tags := new(bytes.Buffer)
for key, value := range m.Tags {
fmt.Fprintf(tags, "%s='%s' ", key, value)
}
return fmt.Sprintf("[%d] %s = %s { %s }", m.Timestamp, m.Metric, m.Value, tags)
}
type HttpSerializer struct {
logger *zap.Logger
maxTags int
skipTags []string
}
func NewHttpSerializer(logger *zap.Logger, maxTags int, skipTags []string) *HttpSerializer {
return &HttpSerializer{
logger: logger,
maxTags: maxTags,
skipTags: skipTags,
}
}
func (h *HttpSerializer) Marshal(metrics pmetric.Metrics) (sMetrics []*Metric, errs []error) {
h.logger.Debug("HttpSerializer#Marshal", zap.Int("#metrics", metrics.MetricCount()), zap.Int("#datapoints", metrics.DataPointCount()))
rms := metrics.ResourceMetrics()
for i := 0; i < rms.Len(); i++ {
h.logger.Debug("ResourceMetrics", zap.Int("#id", i))
rm := rms.At(i)
resource := rm.Resource()
ilms := rm.ScopeMetrics()
for j := 0; j < ilms.Len(); j++ {
h.logger.Debug("InstrumentationLibraryMetric", zap.Int("#id", j))
ilm := ilms.At(j)
il := ilm.Scope()
h.logger.Debug("InstrumentationLibrary", zap.String("#name", il.Name()), zap.String("#version", il.Version()))
ms := ilm.Metrics()
for k := 0; k < ms.Len(); k++ {
h.logger.Debug("Metric", zap.Int("#id", k))
metric := ms.At(k)
switch metric.Type() {
case pmetric.MetricTypeGauge:
s, sErrs := h.serializeGauge(metric, resource, il)
if sErrs != nil {
errs = append(errs, sErrs...)
}
sMetrics = append(sMetrics, s...)
case pmetric.MetricTypeSum:
s, sErrs := h.serializeSum(metric, resource, il)
if sErrs != nil {
errs = append(errs, sErrs...)
}
sMetrics = append(sMetrics, s...)
default:
errs = append(errs, fmt.Errorf("unhandled DataType: %s", metric.Type()))
}
}
}
}
return sMetrics, errs
}
func (h *HttpSerializer) serializeGauge(metric pmetric.Metric, resource pcommon.Resource, instrumentationLibrary pcommon.InstrumentationScope) (mSlice []*Metric, errs []error) {
dps := metric.Gauge().DataPoints()
for i := 0; i < dps.Len(); i++ {
dp := dps.At(i)
var value interface{}
switch dp.ValueType() {
case pmetric.NumberDataPointValueTypeEmpty:
continue
case pmetric.NumberDataPointValueTypeInt:
value = dp.IntValue()
case pmetric.NumberDataPointValueTypeDouble:
value = dp.DoubleValue()
default:
errs = append(errs, fmt.Errorf("unsupported gauge data point type %d", dp.ValueType()))
}
tags, _ := h.createTags(resource, instrumentationLibrary, dp.Attributes(), metric.Name())
m := &Metric{
Metric: metric.Name(),
Timestamp: uint64(dp.Timestamp()) / 1000000,
Value: value,
Tags: tags,
}
mSlice = append(mSlice, m)
}
return mSlice, errs
}
func (h *HttpSerializer) serializeSum(metric pmetric.Metric, resource pcommon.Resource, instrumentationLibrary pcommon.InstrumentationScope) (mSlice []*Metric, errs []error) {
if metric.Sum().AggregationTemporality() != pmetric.AggregationTemporalityCumulative {
return nil, append(errs, fmt.Errorf("unsupported sum aggregation temporality %q", metric.Sum().AggregationTemporality()))
}
if !metric.Sum().IsMonotonic() {
return nil, append(errs, fmt.Errorf("unsupported non-monotonic sum '%s'", metric.Name()))
}
dps := metric.Sum().DataPoints()
for i := 0; i < dps.Len(); i++ {
dp := dps.At(i)
var value interface{}
switch dp.ValueType() {
case pmetric.NumberDataPointValueTypeEmpty:
continue
case pmetric.NumberDataPointValueTypeInt:
value = dp.IntValue()
case pmetric.NumberDataPointValueTypeDouble:
value = dp.DoubleValue()
default:
errs = append(errs, fmt.Errorf("unsupported sum data point type %d", dp.ValueType()))
}
tags, _ := h.createTags(resource, instrumentationLibrary, dp.Attributes(), metric.Name())
m := &Metric{
Metric: metric.Name(),
Timestamp: uint64(dp.Timestamp()) / 1000000,
Value: value,
Tags: tags,
}
mSlice = append(mSlice, m)
}
return mSlice, errs
}
func (h *HttpSerializer) createTags(resource pcommon.Resource, instrumentationLibrary pcommon.InstrumentationScope, attributes pcommon.Map, metricName string) (map[string]string, map[string]string) {
tags := make(map[string]string)
skipped := make(map[string]string)
attributes.Range(func(key string, value pcommon.Value) bool {
if key != "" {
if h.shouldIncludeTag(key) {
if len(tags) < h.maxTags {
// tags[key] = strings.Replace(value.AsString(), ":", "/", -1)
tags[key] = sanitizeForOpenTSDB(value.AsString())
} else {
skipped[key] = sanitizeForOpenTSDB(value.AsString())
}
}
}
return true
})
tags, skipped = h.resourceToTags(resource, tags, skipped)
tags, skipped = h.instrumentationLibraryToTags(instrumentationLibrary, tags, skipped)
if len(skipped) > 0 {
h.logger.Warn("tags skipped during serialization", zap.String("#name", metricName), zap.Int("#skippedCount", len(skipped)))
if ce := h.logger.Check(zap.DebugLevel, "skipped tags"); ce != nil {
buffer := new(bytes.Buffer)
for key, value := range skipped {
fmt.Fprintf(buffer, "%s=\"%s\" ", key, value)
}
ce.Write(zap.String("tags", strings.Trim(buffer.String(), " ")))
}
}
return tags, skipped
}
func (h *HttpSerializer) resourceToTags(resource pcommon.Resource, tags map[string]string, skipped map[string]string) (map[string]string, map[string]string) {
resource.Attributes().Range(func(key string, value pcommon.Value) bool {
if key != "" {
if h.shouldIncludeTag(key) {
if len(tags) < h.maxTags {
// tags[key] = strings.Replace(value.AsString(), ":", "/", -1)
tags[key] = sanitizeForOpenTSDB(value.AsString())
} else {
skipped[key] = sanitizeForOpenTSDB(value.AsString())
}
}
}
return true
})
return tags, skipped
}
func (h *HttpSerializer) instrumentationLibraryToTags(instrumentationLibrary pcommon.InstrumentationScope, tags map[string]string, skipped map[string]string) (map[string]string, map[string]string) {
if instrumentationLibrary.Name() != "" {
if len(tags) < h.maxTags {
tags["otel.library.name"] = sanitizeForOpenTSDB(instrumentationLibrary.Name())
} else {
skipped["otel.library.name"] = sanitizeForOpenTSDB(instrumentationLibrary.Name())
}
}
if instrumentationLibrary.Version() != "" {
if len(tags) < h.maxTags {
tags["otel.library.version"] = sanitizeForOpenTSDB(instrumentationLibrary.Version())
} else {
skipped["otel.library.version"] = sanitizeForOpenTSDB(instrumentationLibrary.Version())
}
}
return tags, skipped
}
func (h *HttpSerializer) shouldIncludeTag(tag string) bool {
for i := 0; i < len(h.skipTags); i++ {
if strings.EqualFold(tag, h.skipTags[i]) {
return false
}
}
return true
}
func sanitizeForOpenTSDB(value string) string {
if value == "" {
return value
}
// Try to keep some meanings around bucket limits
if value == "+Inf" {
return "pInf"
}
if value == "-Inf" {
return "mInf"
}
reg, _ := regexp.Compile(`[^a-zA-Z0-9\-._/]+`)
return reg.ReplaceAllString(value, "_")
}