-
Notifications
You must be signed in to change notification settings - Fork 98
/
extra_metrics.go
382 lines (354 loc) · 13.5 KB
/
extra_metrics.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
// Copyright 2023 Google LLC
//
// 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
//
// https://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 googlemanagedprometheus
import (
"time"
"github.com/prometheus/common/model"
"go.opentelemetry.io/collector/featuregate"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
semconv "go.opentelemetry.io/collector/semconv/v1.18.0"
)
var intToDoubleFeatureGate = featuregate.GlobalRegistry().MustRegister(
"exporter.googlemanagedpromethues.intToDouble",
featuregate.StageAlpha,
featuregate.WithRegisterFromVersion("v0.100.0"),
featuregate.WithRegisterDescription("Convert all int metrics to double metrics to avoid incompatible value types."),
featuregate.WithRegisterReferenceURL("https://github.com/GoogleCloudPlatform/opentelemetry-operations-go/issues/798"))
const prometheusMetricMetadataTypeKey = "prometheus.type"
func (c Config) ExtraMetrics(m pmetric.Metrics) {
addUntypedMetrics(m)
c.addTargetInfoMetric(m)
c.addScopeInfoMetric(m)
convertIntToDouble(m)
}
// convertIntToDouble converts all counter and gauge int values to double.
func convertIntToDouble(m pmetric.Metrics) {
if !intToDoubleFeatureGate.IsEnabled() {
return
}
rms := m.ResourceMetrics()
for i := 0; i < rms.Len(); i++ {
rm := rms.At(i)
for j := 0; j < rm.ScopeMetrics().Len(); j++ {
sm := rm.ScopeMetrics().At(j)
for k := 0; k < sm.Metrics().Len(); k++ {
metric := sm.Metrics().At(k)
var points pmetric.NumberDataPointSlice
switch metric.Type() {
case pmetric.MetricTypeSum:
points = metric.Sum().DataPoints()
case pmetric.MetricTypeGauge:
points = metric.Gauge().DataPoints()
default:
continue
}
for x := 0; x < points.Len(); x++ {
point := points.At(x)
if point.ValueType() == pmetric.NumberDataPointValueTypeInt {
point.SetDoubleValue(float64(point.IntValue()))
}
}
}
}
}
}
// addUntypedMetrics looks for any Gauge data point with the special Ops Agent untyped metric
// attribute and duplicates that data point to a matching Sum.
func addUntypedMetrics(m pmetric.Metrics) {
rms := m.ResourceMetrics()
for i := 0; i < rms.Len(); i++ {
rm := rms.At(i)
sms := rm.ScopeMetrics()
for j := 0; j < sms.Len(); j++ {
sm := sms.At(j)
mes := sm.Metrics()
// only iterate up to the current length. new untyped sum metrics
// will be added to this slice inline.
mLen := mes.Len()
for k := 0; k < mLen; k++ {
metric := mes.At(k)
// only applies to gauges
if metric.Type() != pmetric.MetricTypeGauge {
continue
}
if !isUnknown(metric) {
continue
}
// attribute is set on the data point
gauge := metric.Gauge()
points := gauge.DataPoints()
for l := 0; l < points.Len(); l++ {
// Add the new Sum metric and copy values over from this Gauge
point := points.At(l)
newMetric := mes.AppendEmpty()
newMetric.SetName(metric.Name())
newMetric.SetDescription(metric.Description())
newMetric.SetUnit(metric.Unit())
newMetric.Metadata().PutStr(prometheusMetricMetadataTypeKey, string(model.MetricTypeUnknown))
newSum := newMetric.SetEmptySum()
newSum.SetIsMonotonic(true)
newSum.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
newDataPoint := newSum.DataPoints().AppendEmpty()
point.Attributes().CopyTo(newDataPoint.Attributes())
if point.ValueType() == pmetric.NumberDataPointValueTypeInt {
newDataPoint.SetIntValue(point.IntValue())
} else if point.ValueType() == pmetric.NumberDataPointValueTypeDouble {
newDataPoint.SetDoubleValue(point.DoubleValue())
}
newDataPoint.SetFlags(point.Flags())
newDataPoint.SetTimestamp(point.Timestamp())
newDataPoint.SetStartTimestamp(point.StartTimestamp())
}
}
}
}
}
func isUnknown(metric pmetric.Metric) bool {
originalType, ok := metric.Metadata().Get(prometheusMetricMetadataTypeKey)
return ok && originalType.Str() == string(model.MetricTypeUnknown)
}
// resourceID identifies a resource. We only send one target info for each
// resourceID.
type resourceID struct {
serviceName, serviceInstanceID, serviceNamespace string
}
// addTargetInfoMetric inserts target_info for each resource.
// First, it extracts the target_info metric from each ResourceMetric associated with the input pmetric.Metrics
// and inserts it into a new ScopeMetric for that resource, as specified in
// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.16.0/specification/compatibility/prometheus_and_openmetrics.md#resource-attributes-1
func (c Config) addTargetInfoMetric(m pmetric.Metrics) {
if !c.ExtraMetricsConfig.EnableTargetInfo {
return
}
ids := make(map[resourceID]struct{})
rms := m.ResourceMetrics()
// loop over input (original) resource metrics
for i := 0; i < rms.Len(); i++ {
rm := rms.At(i)
getResourceAttr := func(attr string) string {
if v, ok := rm.Resource().Attributes().Get(attr); ok {
return v.AsString()
}
return ""
}
// Keep track of the most recent time in this resource's metrics
// Use that time for the timestamp of the new metric
latestTime := time.Time{}
for j := 0; j < rm.ScopeMetrics().Len(); j++ {
for k := 0; k < rm.ScopeMetrics().At(j).Metrics().Len(); k++ {
metric := rm.ScopeMetrics().At(j).Metrics().At(k)
switch metric.Type() {
case pmetric.MetricTypeSum:
sum := metric.Sum()
points := sum.DataPoints()
for x := 0; x < points.Len(); x++ {
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
case pmetric.MetricTypeGauge:
gauge := metric.Gauge()
points := gauge.DataPoints()
for x := 0; x < points.Len(); x++ {
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
case pmetric.MetricTypeSummary:
summary := metric.Summary()
points := summary.DataPoints()
for x := 0; x < points.Len(); x++ {
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
case pmetric.MetricTypeHistogram:
hist := metric.Histogram()
points := hist.DataPoints()
for x := 0; x < points.Len(); x++ {
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
case pmetric.MetricTypeExponentialHistogram:
eh := metric.ExponentialHistogram()
points := eh.DataPoints()
for x := 0; x < points.Len(); x++ {
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
}
}
}
id := resourceID{
serviceName: getResourceAttr(semconv.AttributeServiceName),
serviceNamespace: getResourceAttr(semconv.AttributeServiceNamespace),
serviceInstanceID: getResourceAttr(semconv.AttributeServiceInstanceID),
}
if _, ok := ids[id]; ok {
// We've already added a resource with the same ID before, so skip this one.
continue
}
ids[id] = struct{}{}
// create the target_info metric as a Gauge with value 1
targetInfoMetric := rm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()
targetInfoMetric.SetName("target_info")
dataPoint := targetInfoMetric.SetEmptyGauge().DataPoints().AppendEmpty()
dataPoint.SetIntValue(1)
dataPoint.SetTimestamp(pcommon.NewTimestampFromTime(latestTime))
// copy Resource attributes to the metric except for service.name, service.namespace, and service.instance.id
// because those three attributes (if present) will be copied to resource attributes.
// See https://opentelemetry.io/docs/specs/otel/compatibility/prometheus_and_openmetrics/#resource-attributes-1
// Also drop reserved GMP labels (location, cluster, namespace, job, service_namespace, instance).
// Other "fallback" attributes which could become `job` or `instance` in the absence of those three
// (such as k8s.pod.name or faas.name) will be duplicated as a resource attribute and metric label.
rm.Resource().Attributes().Range(func(k string, v pcommon.Value) bool {
if k != semconv.AttributeServiceName &&
k != semconv.AttributeServiceNamespace &&
k != semconv.AttributeServiceInstanceID &&
k != locationLabel &&
k != clusterLabel &&
k != namespaceLabel &&
k != jobLabel &&
k != serviceNamespaceLabel &&
k != instanceLabel {
dataPoint.Attributes().PutStr(k, v.AsString())
}
return true
})
}
}
// scopeID identifies a scope. We only send one scope info for each scopeID within a unique resource.
type scopeID struct {
resource resourceID
name, version string
}
// addScopeInfoMetric adds the otel_scope_info metric to a Metrics slice as specified in
// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.16.0/specification/compatibility/prometheus_and_openmetrics.md#instrumentation-scope-1
// It also updates all other metrics with the corresponding scope_name and scope_version attributes, if they are present.
func (c Config) addScopeInfoMetric(m pmetric.Metrics) {
if !c.ExtraMetricsConfig.EnableScopeInfo {
return
}
ids := make(map[scopeID]struct{})
rms := m.ResourceMetrics()
for i := 0; i < rms.Len(); i++ {
rm := rms.At(i)
getResourceAttr := func(attr string) string {
if v, ok := rm.Resource().Attributes().Get(attr); ok {
return v.AsString()
}
return ""
}
sms := rm.ScopeMetrics()
for j := 0; j < sms.Len(); j++ {
sm := sms.At(j)
// If not present, skip this scope
if len(sm.Scope().Name()) == 0 && len(sm.Scope().Version()) == 0 {
continue
}
// Keep track of the most recent time in this scope's metrics
// Use that time for the timestamp of the new metric
latestTime := time.Time{}
for k := 0; k < sm.Metrics().Len(); k++ {
metric := sm.Metrics().At(k)
switch metric.Type() {
case pmetric.MetricTypeSum:
sum := metric.Sum()
points := sum.DataPoints()
for x := 0; x < points.Len(); x++ {
point := points.At(x)
point.Attributes().PutStr("otel_scope_name", sm.Scope().Name())
point.Attributes().PutStr("otel_scope_version", sm.Scope().Version())
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
case pmetric.MetricTypeGauge:
gauge := metric.Gauge()
points := gauge.DataPoints()
for x := 0; x < points.Len(); x++ {
point := points.At(x)
point.Attributes().PutStr("otel_scope_name", sm.Scope().Name())
point.Attributes().PutStr("otel_scope_version", sm.Scope().Version())
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
case pmetric.MetricTypeSummary:
summary := metric.Summary()
points := summary.DataPoints()
for x := 0; x < points.Len(); x++ {
point := points.At(x)
point.Attributes().PutStr("otel_scope_name", sm.Scope().Name())
point.Attributes().PutStr("otel_scope_version", sm.Scope().Version())
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
case pmetric.MetricTypeHistogram:
hist := metric.Histogram()
points := hist.DataPoints()
for x := 0; x < points.Len(); x++ {
point := points.At(x)
point.Attributes().PutStr("otel_scope_name", sm.Scope().Name())
point.Attributes().PutStr("otel_scope_version", sm.Scope().Version())
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
case pmetric.MetricTypeExponentialHistogram:
eh := metric.ExponentialHistogram()
points := eh.DataPoints()
for x := 0; x < points.Len(); x++ {
point := points.At(x)
point.Attributes().PutStr("otel_scope_name", sm.Scope().Name())
point.Attributes().PutStr("otel_scope_version", sm.Scope().Version())
if latestTime.Before(points.At(x).Timestamp().AsTime()) {
latestTime = points.At(x).Timestamp().AsTime()
}
}
}
}
id := scopeID{
resource: resourceID{
serviceName: getResourceAttr(semconv.AttributeServiceName),
serviceNamespace: getResourceAttr(semconv.AttributeServiceNamespace),
serviceInstanceID: getResourceAttr(semconv.AttributeServiceInstanceID),
},
name: sm.Scope().Name(),
version: sm.Scope().Version(),
}
if _, ok := ids[id]; ok {
// We've already added a scope with the same ID before, so skip this one.
continue
}
ids[id] = struct{}{}
// Add otel_scope_info metric
scopeInfoMetric := sm.Metrics().AppendEmpty()
scopeInfoMetric.SetName("otel_scope_info")
dataPoint := scopeInfoMetric.SetEmptyGauge().DataPoints().AppendEmpty()
dataPoint.SetIntValue(1)
sm.Scope().Attributes().Range(func(k string, v pcommon.Value) bool {
dataPoint.Attributes().PutStr(k, v.AsString())
return true
})
dataPoint.Attributes().PutStr("otel_scope_name", sm.Scope().Name())
dataPoint.Attributes().PutStr("otel_scope_version", sm.Scope().Version())
dataPoint.SetTimestamp(pcommon.NewTimestampFromTime(latestTime))
}
}
}