Debian Codegraph @

storage/remote/otlptranslator/prometheusremotewrite/helper.go

raw
1 // Copyright 2024 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 // Provenance-includes-location: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/95e8f8fdc2a9dc87230406c9a3cf02be4fd68bea/pkg/translator/prometheusremotewrite/helper.go
14 // Provenance-includes-license: Apache-2.0
15 // Provenance-includes-copyright: Copyright The OpenTelemetry Authors.
16
17 package prometheusremotewrite
18
19 import (
20 "encoding/hex"
21 "fmt"
22 "log"
23 "math"
24 "slices"
25 "sort"
26 "strconv"
27 "time"
28 "unicode/utf8"
29
30 "github.com/cespare/xxhash/v2"
31 "github.com/prometheus/common/model"
32 "go.opentelemetry.io/collector/pdata/pcommon"
33 "go.opentelemetry.io/collector/pdata/pmetric"
34 conventions "go.opentelemetry.io/collector/semconv/v1.6.1"
35
36 "github.com/prometheus/prometheus/model/timestamp"
37 "github.com/prometheus/prometheus/model/value"
38 "github.com/prometheus/prometheus/prompb"
39
40 prometheustranslator "github.com/prometheus/prometheus/storage/remote/otlptranslator/prometheus"
41 )
42
43 const (
44 sumStr = "_sum"
45 countStr = "_count"
46 bucketStr = "_bucket"
47 leStr = "le"
48 quantileStr = "quantile"
49 pInfStr = "+Inf"
50 createdSuffix = "_created"
51 // maxExemplarRunes is the maximum number of UTF-8 exemplar characters
52 // according to the prometheus specification
53 // https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#exemplars
54 maxExemplarRunes = 128
55 // Trace and Span id keys are defined as part of the spec:
56 // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification%2Fmetrics%2Fdatamodel.md#exemplars-2
57 traceIDKey = "trace_id"
58 spanIDKey = "span_id"
59 infoType = "info"
60 targetMetricName = "target_info"
61 )
62
63 type bucketBoundsData struct {
64 ts *prompb.TimeSeries
65 bound float64
66 }
67
68 // byBucketBoundsData enables the usage of sort.Sort() with a slice of bucket bounds
69 type byBucketBoundsData []bucketBoundsData
70
71 func (m byBucketBoundsData) Len() int { return len(m) }
72 func (m byBucketBoundsData) Less(i, j int) bool { return m[i].bound < m[j].bound }
73 func (m byBucketBoundsData) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
74
75 // ByLabelName enables the usage of sort.Sort() with a slice of labels
76 type ByLabelName []prompb.Label
77
78 func (a ByLabelName) Len() int { return len(a) }
79 func (a ByLabelName) Less(i, j int) bool { return a[i].Name < a[j].Name }
80 func (a ByLabelName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
81
82 // timeSeriesSignature returns a hashed label set signature.
83 // The label slice should not contain duplicate label names; this method sorts the slice by label name before creating
84 // the signature.
85 // The algorithm is the same as in Prometheus' labels.StableHash function.
86 func timeSeriesSignature(labels []prompb.Label) uint64 {
87 sort.Sort(ByLabelName(labels))
88
89 // Use xxhash.Sum64(b) for fast path as it's faster.
90 b := make([]byte, 0, 1024)
91 for i, v := range labels {
92 if len(b)+len(v.Name)+len(v.Value)+2 >= cap(b) {
93 // If labels entry is 1KB+ do not allocate whole entry.
94 h := xxhash.New()
95 _, _ = h.Write(b)
96 for _, v := range labels[i:] {
97 _, _ = h.WriteString(v.Name)
98 _, _ = h.Write(seps)
99 _, _ = h.WriteString(v.Value)
100 _, _ = h.Write(seps)
101 }
102 return h.Sum64()
103 }
104
105 b = append(b, v.Name...)
106 b = append(b, seps[0])
107 b = append(b, v.Value...)
108 b = append(b, seps[0])
109 }
110 return xxhash.Sum64(b)
111 }
112
113 var seps = []byte{'\xff'}
114
115 // createAttributes creates a slice of Prometheus Labels with OTLP attributes and pairs of string values.
116 // Unpaired string values are ignored. String pairs overwrite OTLP labels if collisions happen and
117 // if logOnOverwrite is true, the overwrite is logged. Resulting label names are sanitized.
118 func createAttributes(resource pcommon.Resource, attributes pcommon.Map, externalLabels map[string]string,
119 ignoreAttrs []string, logOnOverwrite bool, extras ...string) []prompb.Label {
120 resourceAttrs := resource.Attributes()
121 serviceName, haveServiceName := resourceAttrs.Get(conventions.AttributeServiceName)
122 instance, haveInstanceID := resourceAttrs.Get(conventions.AttributeServiceInstanceID)
123
124 // Calculate the maximum possible number of labels we could return so we can preallocate l
125 maxLabelCount := attributes.Len() + len(externalLabels) + len(extras)/2
126
127 if haveServiceName {
128 maxLabelCount++
129 }
130
131 if haveInstanceID {
132 maxLabelCount++
133 }
134
135 // map ensures no duplicate label name
136 l := make(map[string]string, maxLabelCount)
137
138 // Ensure attributes are sorted by key for consistent merging of keys which
139 // collide when sanitized.
140 labels := make([]prompb.Label, 0, maxLabelCount)
141 // XXX: Should we always drop service namespace/service name/service instance ID from the labels
142 // (as they get mapped to other Prometheus labels)?
143 attributes.Range(func(key string, value pcommon.Value) bool {
144 if !slices.Contains(ignoreAttrs, key) {
145 labels = append(labels, prompb.Label{Name: key, Value: value.AsString()})
146 }
147 return true
148 })
149 sort.Stable(ByLabelName(labels))
150
151 for _, label := range labels {
152 var finalKey = prometheustranslator.NormalizeLabel(label.Name)
153 if existingValue, alreadyExists := l[finalKey]; alreadyExists {
154 l[finalKey] = existingValue + ";" + label.Value
155 } else {
156 l[finalKey] = label.Value
157 }
158 }
159
160 // Map service.name + service.namespace to job
161 if haveServiceName {
162 val := serviceName.AsString()
163 if serviceNamespace, ok := resourceAttrs.Get(conventions.AttributeServiceNamespace); ok {
164 val = fmt.Sprintf("%s/%s", serviceNamespace.AsString(), val)
165 }
166 l[model.JobLabel] = val
167 }
168 // Map service.instance.id to instance
169 if haveInstanceID {
170 l[model.InstanceLabel] = instance.AsString()
171 }
172 for key, value := range externalLabels {
173 // External labels have already been sanitized
174 if _, alreadyExists := l[key]; alreadyExists {
175 // Skip external labels if they are overridden by metric attributes
176 continue
177 }
178 l[key] = value
179 }
180
181 for i := 0; i < len(extras); i += 2 {
182 if i+1 >= len(extras) {
183 break
184 }
185 _, found := l[extras[i]]
186 if found && logOnOverwrite {
187 log.Println("label " + extras[i] + " is overwritten. Check if Prometheus reserved labels are used.")
188 }
189 // internal labels should be maintained
190 name := extras[i]
191 if !(len(name) > 4 && name[:2] == "__" && name[len(name)-2:] == "__") {
192 name = prometheustranslator.NormalizeLabel(name)
193 }
194 l[name] = extras[i+1]
195 }
196
197 labels = labels[:0]
198 for k, v := range l {
199 labels = append(labels, prompb.Label{Name: k, Value: v})
200 }
201
202 return labels
203 }
204
205 // isValidAggregationTemporality checks whether an OTel metric has a valid
206 // aggregation temporality for conversion to a Prometheus metric.
207 func isValidAggregationTemporality(metric pmetric.Metric) bool {
208 //exhaustive:enforce
209 switch metric.Type() {
210 case pmetric.MetricTypeGauge, pmetric.MetricTypeSummary:
211 return true
212 case pmetric.MetricTypeSum:
213 return metric.Sum().AggregationTemporality() == pmetric.AggregationTemporalityCumulative
214 case pmetric.MetricTypeHistogram:
215 return metric.Histogram().AggregationTemporality() == pmetric.AggregationTemporalityCumulative
216 case pmetric.MetricTypeExponentialHistogram:
217 return metric.ExponentialHistogram().AggregationTemporality() == pmetric.AggregationTemporalityCumulative
218 }
219 return false
220 }
221
222 func (c *PrometheusConverter) addHistogramDataPoints(dataPoints pmetric.HistogramDataPointSlice,
223 resource pcommon.Resource, settings Settings, baseName string) {
224 for x := 0; x < dataPoints.Len(); x++ {
225 pt := dataPoints.At(x)
226 timestamp := convertTimeStamp(pt.Timestamp())
227 baseLabels := createAttributes(resource, pt.Attributes(), settings.ExternalLabels, nil, false)
228
229 // If the sum is unset, it indicates the _sum metric point should be
230 // omitted
231 if pt.HasSum() {
232 // treat sum as a sample in an individual TimeSeries
233 sum := &prompb.Sample{
234 Value: pt.Sum(),
235 Timestamp: timestamp,
236 }
237 if pt.Flags().NoRecordedValue() {
238 sum.Value = math.Float64frombits(value.StaleNaN)
239 }
240
241 sumlabels := createLabels(baseName+sumStr, baseLabels)
242 c.addSample(sum, sumlabels)
243
244 }
245
246 // treat count as a sample in an individual TimeSeries
247 count := &prompb.Sample{
248 Value: float64(pt.Count()),
249 Timestamp: timestamp,
250 }
251 if pt.Flags().NoRecordedValue() {
252 count.Value = math.Float64frombits(value.StaleNaN)
253 }
254
255 countlabels := createLabels(baseName+countStr, baseLabels)
256 c.addSample(count, countlabels)
257
258 // cumulative count for conversion to cumulative histogram
259 var cumulativeCount uint64
260
261 var bucketBounds []bucketBoundsData
262
263 // process each bound, based on histograms proto definition, # of buckets = # of explicit bounds + 1
264 for i := 0; i < pt.ExplicitBounds().Len() && i < pt.BucketCounts().Len(); i++ {
265 bound := pt.ExplicitBounds().At(i)
266 cumulativeCount += pt.BucketCounts().At(i)
267 bucket := &prompb.Sample{
268 Value: float64(cumulativeCount),
269 Timestamp: timestamp,
270 }
271 if pt.Flags().NoRecordedValue() {
272 bucket.Value = math.Float64frombits(value.StaleNaN)
273 }
274 boundStr := strconv.FormatFloat(bound, 'f', -1, 64)
275 labels := createLabels(baseName+bucketStr, baseLabels, leStr, boundStr)
276 ts := c.addSample(bucket, labels)
277
278 bucketBounds = append(bucketBounds, bucketBoundsData{ts: ts, bound: bound})
279 }
280 // add le=+Inf bucket
281 infBucket := &prompb.Sample{
282 Timestamp: timestamp,
283 }
284 if pt.Flags().NoRecordedValue() {
285 infBucket.Value = math.Float64frombits(value.StaleNaN)
286 } else {
287 infBucket.Value = float64(pt.Count())
288 }
289 infLabels := createLabels(baseName+bucketStr, baseLabels, leStr, pInfStr)
290 ts := c.addSample(infBucket, infLabels)
291
292 bucketBounds = append(bucketBounds, bucketBoundsData{ts: ts, bound: math.Inf(1)})
293 c.addExemplars(pt, bucketBounds)
294
295 startTimestamp := pt.StartTimestamp()
296 if settings.ExportCreatedMetric && startTimestamp != 0 {
297 labels := createLabels(baseName+createdSuffix, baseLabels)
298 c.addTimeSeriesIfNeeded(labels, startTimestamp, pt.Timestamp())
299 }
300 }
301 }
302
303 type exemplarType interface {
304 pmetric.ExponentialHistogramDataPoint | pmetric.HistogramDataPoint | pmetric.NumberDataPoint
305 Exemplars() pmetric.ExemplarSlice
306 }
307
308 func getPromExemplars[T exemplarType](pt T) []prompb.Exemplar {
309 promExemplars := make([]prompb.Exemplar, 0, pt.Exemplars().Len())
310 for i := 0; i < pt.Exemplars().Len(); i++ {
311 exemplar := pt.Exemplars().At(i)
312 exemplarRunes := 0
313
314 promExemplar := prompb.Exemplar{
315 Value: exemplar.DoubleValue(),
316 Timestamp: timestamp.FromTime(exemplar.Timestamp().AsTime()),
317 }
318 if traceID := exemplar.TraceID(); !traceID.IsEmpty() {
319 val := hex.EncodeToString(traceID[:])
320 exemplarRunes += utf8.RuneCountInString(traceIDKey) + utf8.RuneCountInString(val)
321 promLabel := prompb.Label{
322 Name: traceIDKey,
323 Value: val,
324 }
325 promExemplar.Labels = append(promExemplar.Labels, promLabel)
326 }
327 if spanID := exemplar.SpanID(); !spanID.IsEmpty() {
328 val := hex.EncodeToString(spanID[:])
329 exemplarRunes += utf8.RuneCountInString(spanIDKey) + utf8.RuneCountInString(val)
330 promLabel := prompb.Label{
331 Name: spanIDKey,
332 Value: val,
333 }
334 promExemplar.Labels = append(promExemplar.Labels, promLabel)
335 }
336
337 attrs := exemplar.FilteredAttributes()
338 labelsFromAttributes := make([]prompb.Label, 0, attrs.Len())
339 attrs.Range(func(key string, value pcommon.Value) bool {
340 val := value.AsString()
341 exemplarRunes += utf8.RuneCountInString(key) + utf8.RuneCountInString(val)
342 promLabel := prompb.Label{
343 Name: key,
344 Value: val,
345 }
346
347 labelsFromAttributes = append(labelsFromAttributes, promLabel)
348
349 return true
350 })
351 if exemplarRunes <= maxExemplarRunes {
352 // only append filtered attributes if it does not cause exemplar
353 // labels to exceed the max number of runes
354 promExemplar.Labels = append(promExemplar.Labels, labelsFromAttributes...)
355 }
356
357 promExemplars = append(promExemplars, promExemplar)
358 }
359
360 return promExemplars
361 }
362
363 // mostRecentTimestampInMetric returns the latest timestamp in a batch of metrics
364 func mostRecentTimestampInMetric(metric pmetric.Metric) pcommon.Timestamp {
365 var ts pcommon.Timestamp
366 // handle individual metric based on type
367 //exhaustive:enforce
368 switch metric.Type() {
369 case pmetric.MetricTypeGauge:
370 dataPoints := metric.Gauge().DataPoints()
371 for x := 0; x < dataPoints.Len(); x++ {
372 ts = max(ts, dataPoints.At(x).Timestamp())
373 }
374 case pmetric.MetricTypeSum:
375 dataPoints := metric.Sum().DataPoints()
376 for x := 0; x < dataPoints.Len(); x++ {
377 ts = max(ts, dataPoints.At(x).Timestamp())
378 }
379 case pmetric.MetricTypeHistogram:
380 dataPoints := metric.Histogram().DataPoints()
381 for x := 0; x < dataPoints.Len(); x++ {
382 ts = max(ts, dataPoints.At(x).Timestamp())
383 }
384 case pmetric.MetricTypeExponentialHistogram:
385 dataPoints := metric.ExponentialHistogram().DataPoints()
386 for x := 0; x < dataPoints.Len(); x++ {
387 ts = max(ts, dataPoints.At(x).Timestamp())
388 }
389 case pmetric.MetricTypeSummary:
390 dataPoints := metric.Summary().DataPoints()
391 for x := 0; x < dataPoints.Len(); x++ {
392 ts = max(ts, dataPoints.At(x).Timestamp())
393 }
394 }
395 return ts
396 }
397
398 func (c *PrometheusConverter) addSummaryDataPoints(dataPoints pmetric.SummaryDataPointSlice, resource pcommon.Resource,
399 settings Settings, baseName string) {
400 for x := 0; x < dataPoints.Len(); x++ {
401 pt := dataPoints.At(x)
402 timestamp := convertTimeStamp(pt.Timestamp())
403 baseLabels := createAttributes(resource, pt.Attributes(), settings.ExternalLabels, nil, false)
404
405 // treat sum as a sample in an individual TimeSeries
406 sum := &prompb.Sample{
407 Value: pt.Sum(),
408 Timestamp: timestamp,
409 }
410 if pt.Flags().NoRecordedValue() {
411 sum.Value = math.Float64frombits(value.StaleNaN)
412 }
413 // sum and count of the summary should append suffix to baseName
414 sumlabels := createLabels(baseName+sumStr, baseLabels)
415 c.addSample(sum, sumlabels)
416
417 // treat count as a sample in an individual TimeSeries
418 count := &prompb.Sample{
419 Value: float64(pt.Count()),
420 Timestamp: timestamp,
421 }
422 if pt.Flags().NoRecordedValue() {
423 count.Value = math.Float64frombits(value.StaleNaN)
424 }
425 countlabels := createLabels(baseName+countStr, baseLabels)
426 c.addSample(count, countlabels)
427
428 // process each percentile/quantile
429 for i := 0; i < pt.QuantileValues().Len(); i++ {
430 qt := pt.QuantileValues().At(i)
431 quantile := &prompb.Sample{
432 Value: qt.Value(),
433 Timestamp: timestamp,
434 }
435 if pt.Flags().NoRecordedValue() {
436 quantile.Value = math.Float64frombits(value.StaleNaN)
437 }
438 percentileStr := strconv.FormatFloat(qt.Quantile(), 'f', -1, 64)
439 qtlabels := createLabels(baseName, baseLabels, quantileStr, percentileStr)
440 c.addSample(quantile, qtlabels)
441 }
442
443 startTimestamp := pt.StartTimestamp()
444 if settings.ExportCreatedMetric && startTimestamp != 0 {
445 createdLabels := createLabels(baseName+createdSuffix, baseLabels)
446 c.addTimeSeriesIfNeeded(createdLabels, startTimestamp, pt.Timestamp())
447 }
448 }
449 }
450
451 // createLabels returns a copy of baseLabels, adding to it the pair model.MetricNameLabel=name.
452 // If extras are provided, corresponding label pairs are also added to the returned slice.
453 // If extras is uneven length, the last (unpaired) extra will be ignored.
454 func createLabels(name string, baseLabels []prompb.Label, extras ...string) []prompb.Label {
455 extraLabelCount := len(extras) / 2
456 labels := make([]prompb.Label, len(baseLabels), len(baseLabels)+extraLabelCount+1) // +1 for name
457 copy(labels, baseLabels)
458
459 n := len(extras)
460 n -= n % 2
461 for extrasIdx := 0; extrasIdx < n; extrasIdx += 2 {
462 labels = append(labels, prompb.Label{Name: extras[extrasIdx], Value: extras[extrasIdx+1]})
463 }
464
465 labels = append(labels, prompb.Label{Name: model.MetricNameLabel, Value: name})
466 return labels
467 }
468
469 // getOrCreateTimeSeries returns the time series corresponding to the label set if existent, and false.
470 // Otherwise it creates a new one and returns that, and true.
471 func (c *PrometheusConverter) getOrCreateTimeSeries(lbls []prompb.Label) (*prompb.TimeSeries, bool) {
472 h := timeSeriesSignature(lbls)
473 ts := c.unique[h]
474 if ts != nil {
475 if isSameMetric(ts, lbls) {
476 // We already have this metric
477 return ts, false
478 }
479
480 // Look for a matching conflict
481 for _, cTS := range c.conflicts[h] {
482 if isSameMetric(cTS, lbls) {
483 // We already have this metric
484 return cTS, false
485 }
486 }
487
488 // New conflict
489 ts = &prompb.TimeSeries{
490 Labels: lbls,
491 }
492 c.conflicts[h] = append(c.conflicts[h], ts)
493 return ts, true
494 }
495
496 // This metric is new
497 ts = &prompb.TimeSeries{
498 Labels: lbls,
499 }
500 c.unique[h] = ts
501 return ts, true
502 }
503
504 // addTimeSeriesIfNeeded adds a corresponding time series if it doesn't already exist.
505 // If the time series doesn't already exist, it gets added with startTimestamp for its value and timestamp for its timestamp,
506 // both converted to milliseconds.
507 func (c *PrometheusConverter) addTimeSeriesIfNeeded(lbls []prompb.Label, startTimestamp pcommon.Timestamp, timestamp pcommon.Timestamp) {
508 ts, created := c.getOrCreateTimeSeries(lbls)
509 if created {
510 ts.Samples = []prompb.Sample{
511 {
512 // convert ns to ms
513 Value: float64(convertTimeStamp(startTimestamp)),
514 Timestamp: convertTimeStamp(timestamp),
515 },
516 }
517 }
518 }
519
520 // addResourceTargetInfo converts the resource to the target info metric.
521 func addResourceTargetInfo(resource pcommon.Resource, settings Settings, timestamp pcommon.Timestamp, converter *PrometheusConverter) {
522 if settings.DisableTargetInfo || timestamp == 0 {
523 return
524 }
525
526 attributes := resource.Attributes()
527 identifyingAttrs := []string{
528 conventions.AttributeServiceNamespace,
529 conventions.AttributeServiceName,
530 conventions.AttributeServiceInstanceID,
531 }
532 nonIdentifyingAttrsCount := attributes.Len()
533 for _, a := range identifyingAttrs {
534 _, haveAttr := attributes.Get(a)
535 if haveAttr {
536 nonIdentifyingAttrsCount--
537 }
538 }
539 if nonIdentifyingAttrsCount == 0 {
540 // If we only have job + instance, then target_info isn't useful, so don't add it.
541 return
542 }
543
544 name := targetMetricName
545 if len(settings.Namespace) > 0 {
546 name = settings.Namespace + "_" + name
547 }
548
549 labels := createAttributes(resource, attributes, settings.ExternalLabels, identifyingAttrs, false, model.MetricNameLabel, name)
550 haveIdentifier := false
551 for _, l := range labels {
552 if l.Name == model.JobLabel || l.Name == model.InstanceLabel {
553 haveIdentifier = true
554 break
555 }
556 }
557
558 if !haveIdentifier {
559 // We need at least one identifying label to generate target_info.
560 return
561 }
562
563 sample := &prompb.Sample{
564 Value: float64(1),
565 // convert ns to ms
566 Timestamp: convertTimeStamp(timestamp),
567 }
568 converter.addSample(sample, labels)
569 }
570
571 // convertTimeStamp converts OTLP timestamp in ns to timestamp in ms
572 func convertTimeStamp(timestamp pcommon.Timestamp) int64 {
573 return timestamp.AsTime().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
574 }