-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
collector.go
250 lines (213 loc) · 7.73 KB
/
collector.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
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prometheusexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/prometheusexporter"
import (
"fmt"
"sort"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
conventions "go.opentelemetry.io/collector/semconv/v1.6.1"
"go.uber.org/zap"
)
type collector struct {
accumulator accumulator
logger *zap.Logger
sendTimestamps bool
namespace string
constLabels prometheus.Labels
skipSanitizeLabel bool
}
func newCollector(config *Config, logger *zap.Logger) *collector {
return &collector{
accumulator: newAccumulator(logger, config.MetricExpiration),
logger: logger,
namespace: sanitize(config.Namespace, config.skipSanitizeLabel),
sendTimestamps: config.SendTimestamps,
constLabels: config.ConstLabels,
skipSanitizeLabel: config.skipSanitizeLabel,
}
}
// Describe is a no-op, because the collector dynamically allocates metrics.
// https://github.com/prometheus/client_golang/blob/v1.9.0/prometheus/collector.go#L28-L40
func (c *collector) Describe(_ chan<- *prometheus.Desc) {}
/*
Processing
*/
func (c *collector) processMetrics(rm pmetric.ResourceMetrics) (n int) {
return c.accumulator.Accumulate(rm)
}
var errUnknownMetricType = fmt.Errorf("unknown metric type")
func (c *collector) convertMetric(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
switch metric.DataType() {
case pmetric.MetricDataTypeGauge:
return c.convertGauge(metric, resourceAttrs)
case pmetric.MetricDataTypeSum:
return c.convertSum(metric, resourceAttrs)
case pmetric.MetricDataTypeHistogram:
return c.convertDoubleHistogram(metric, resourceAttrs)
case pmetric.MetricDataTypeSummary:
return c.convertSummary(metric, resourceAttrs)
}
return nil, errUnknownMetricType
}
func (c *collector) metricName(namespace string, metric pmetric.Metric) string {
if namespace != "" {
return namespace + "_" + sanitize(metric.Name(), c.skipSanitizeLabel)
}
return sanitize(metric.Name(), c.skipSanitizeLabel)
}
func (c *collector) getMetricMetadata(metric pmetric.Metric, attributes pcommon.Map, resourceAttrs pcommon.Map) (*prometheus.Desc, []string) {
keys := make([]string, 0, attributes.Len()+2) // +2 for job and instance labels.
values := make([]string, 0, attributes.Len()+2)
attributes.Range(func(k string, v pcommon.Value) bool {
keys = append(keys, sanitize(k, c.skipSanitizeLabel))
values = append(values, v.AsString())
return true
})
// Map service.name + service.namespace to job
if serviceName, ok := resourceAttrs.Get(conventions.AttributeServiceName); ok {
val := serviceName.AsString()
if serviceNamespace, ok := resourceAttrs.Get(conventions.AttributeServiceNamespace); ok {
val = fmt.Sprintf("%s/%s", serviceNamespace.AsString(), val)
}
keys = append(keys, model.JobLabel)
values = append(values, val)
}
// Map service.instance.id to instance
if instance, ok := resourceAttrs.Get(conventions.AttributeServiceInstanceID); ok {
keys = append(keys, model.InstanceLabel)
values = append(values, instance.AsString())
}
return prometheus.NewDesc(
c.metricName(c.namespace, metric),
metric.Description(),
keys,
c.constLabels,
), values
}
func (c *collector) convertGauge(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
ip := metric.Gauge().DataPoints().At(0)
desc, attributes := c.getMetricMetadata(metric, ip.Attributes(), resourceAttrs)
var value float64
switch ip.ValueType() {
case pmetric.NumberDataPointValueTypeInt:
value = float64(ip.IntVal())
case pmetric.NumberDataPointValueTypeDouble:
value = ip.DoubleVal()
}
m, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, value, attributes...)
if err != nil {
return nil, err
}
if c.sendTimestamps {
return prometheus.NewMetricWithTimestamp(ip.Timestamp().AsTime(), m), nil
}
return m, nil
}
func (c *collector) convertSum(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
ip := metric.Sum().DataPoints().At(0)
metricType := prometheus.GaugeValue
if metric.Sum().IsMonotonic() {
metricType = prometheus.CounterValue
}
desc, attributes := c.getMetricMetadata(metric, ip.Attributes(), resourceAttrs)
var value float64
switch ip.ValueType() {
case pmetric.NumberDataPointValueTypeInt:
value = float64(ip.IntVal())
case pmetric.NumberDataPointValueTypeDouble:
value = ip.DoubleVal()
}
m, err := prometheus.NewConstMetric(desc, metricType, value, attributes...)
if err != nil {
return nil, err
}
if c.sendTimestamps {
return prometheus.NewMetricWithTimestamp(ip.Timestamp().AsTime(), m), nil
}
return m, nil
}
func (c *collector) convertSummary(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
// TODO: In the off chance that we have multiple points
// within the same metric, how should we handle them?
point := metric.Summary().DataPoints().At(0)
quantiles := make(map[float64]float64)
qv := point.QuantileValues()
for j := 0; j < qv.Len(); j++ {
qvj := qv.At(j)
// There should be EXACTLY one quantile value lest it is an invalid exposition.
quantiles[qvj.Quantile()] = qvj.Value()
}
desc, attributes := c.getMetricMetadata(metric, point.Attributes(), resourceAttrs)
m, err := prometheus.NewConstSummary(desc, point.Count(), point.Sum(), quantiles, attributes...)
if err != nil {
return nil, err
}
if c.sendTimestamps {
return prometheus.NewMetricWithTimestamp(point.Timestamp().AsTime(), m), nil
}
return m, nil
}
func (c *collector) convertDoubleHistogram(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
ip := metric.Histogram().DataPoints().At(0)
desc, attributes := c.getMetricMetadata(metric, ip.Attributes(), resourceAttrs)
indicesMap := make(map[float64]int)
buckets := make([]float64, 0, len(ip.MBucketCounts()))
for index, bucket := range ip.MExplicitBounds() {
if _, added := indicesMap[bucket]; !added {
indicesMap[bucket] = index
buckets = append(buckets, bucket)
}
}
sort.Float64s(buckets)
cumCount := uint64(0)
points := make(map[float64]uint64)
for _, bucket := range buckets {
index := indicesMap[bucket]
var countPerBucket uint64
if len(ip.MExplicitBounds()) > 0 && index < len(ip.MExplicitBounds()) {
countPerBucket = ip.MBucketCounts()[index]
}
cumCount += countPerBucket
points[bucket] = cumCount
}
m, err := prometheus.NewConstHistogram(desc, ip.Count(), ip.Sum(), points, attributes...)
if err != nil {
return nil, err
}
if c.sendTimestamps {
return prometheus.NewMetricWithTimestamp(ip.Timestamp().AsTime(), m), nil
}
return m, nil
}
/*
Reporting
*/
func (c *collector) Collect(ch chan<- prometheus.Metric) {
c.logger.Debug("collect called")
inMetrics, resourceAttrs := c.accumulator.Collect()
for i := range inMetrics {
pMetric := inMetrics[i]
rAttr := resourceAttrs[i]
m, err := c.convertMetric(pMetric, rAttr)
if err != nil {
c.logger.Error(fmt.Sprintf("failed to convert metric %s: %s", pMetric.Name(), err.Error()))
continue
}
ch <- m
c.logger.Debug(fmt.Sprintf("metric served: %s", m.Desc().String()))
}
}