| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
// Package internal provides internal functionality for the opencensus package. |
| 5 |
package internal // import "go.opentelemetry.io/otel/bridge/opencensus/internal/ocmetric" |
| 6 |
|
| 7 |
import ( |
| 8 |
"cmp" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"math" |
| 12 |
"reflect" |
| 13 |
"slices" |
| 14 |
"strconv" |
| 15 |
|
| 16 |
ocmetricdata "go.opencensus.io/metric/metricdata" |
| 17 |
octrace "go.opencensus.io/trace" |
| 18 |
|
| 19 |
"go.opentelemetry.io/otel/attribute" |
| 20 |
"go.opentelemetry.io/otel/sdk/metric/metricdata" |
| 21 |
) |
| 22 |
|
| 23 |
var ( |
| 24 |
errAggregationType = errors.New("unsupported OpenCensus aggregation type") |
| 25 |
errMismatchedValueTypes = errors.New("wrong value type for data point") |
| 26 |
errNegativeCount = errors.New("distribution or summary count is negative") |
| 27 |
errNegativeBucketCount = errors.New("distribution bucket count is negative") |
| 28 |
errMismatchedAttributeKeyValues = errors.New("mismatched number of attribute keys and values") |
| 29 |
errInvalidExemplarSpanContext = errors.New( |
| 30 |
"span context exemplar attachment does not contain an OpenCensus SpanContext", |
| 31 |
) |
| 32 |
) |
| 33 |
|
| 34 |
// ConvertMetrics converts metric data from OpenCensus to OpenTelemetry. |
| 35 |
func ConvertMetrics(ocmetrics []*ocmetricdata.Metric) ([]metricdata.Metrics, error) { |
| 36 |
otelMetrics := make([]metricdata.Metrics, 0, len(ocmetrics)) |
| 37 |
var err error |
| 38 |
for _, ocm := range ocmetrics { |
| 39 |
if ocm == nil { |
| 40 |
continue |
| 41 |
} |
| 42 |
agg, aggregationErr := convertAggregation(ocm) |
| 43 |
if aggregationErr != nil { |
| 44 |
err = errors.Join(err, fmt.Errorf("error converting metric %v: %w", ocm.Descriptor.Name, aggregationErr)) |
| 45 |
continue |
| 46 |
} |
| 47 |
otelMetrics = append(otelMetrics, metricdata.Metrics{ |
| 48 |
Name: ocm.Descriptor.Name, |
| 49 |
Description: ocm.Descriptor.Description, |
| 50 |
Unit: string(ocm.Descriptor.Unit), |
| 51 |
Data: agg, |
| 52 |
}) |
| 53 |
} |
| 54 |
if err != nil { |
| 55 |
return otelMetrics, fmt.Errorf("error converting from OpenCensus to OpenTelemetry: %w", err) |
| 56 |
} |
| 57 |
return otelMetrics, nil |
| 58 |
} |
| 59 |
|
| 60 |
// convertAggregation produces an aggregation based on the OpenCensus Metric. |
| 61 |
func convertAggregation(metric *ocmetricdata.Metric) (metricdata.Aggregation, error) { |
| 62 |
labelKeys := metric.Descriptor.LabelKeys |
| 63 |
switch metric.Descriptor.Type { |
| 64 |
case ocmetricdata.TypeGaugeInt64: |
| 65 |
return convertGauge[int64](labelKeys, metric.TimeSeries) |
| 66 |
case ocmetricdata.TypeGaugeFloat64: |
| 67 |
return convertGauge[float64](labelKeys, metric.TimeSeries) |
| 68 |
case ocmetricdata.TypeCumulativeInt64: |
| 69 |
return convertSum[int64](labelKeys, metric.TimeSeries) |
| 70 |
case ocmetricdata.TypeCumulativeFloat64: |
| 71 |
return convertSum[float64](labelKeys, metric.TimeSeries) |
| 72 |
case ocmetricdata.TypeCumulativeDistribution: |
| 73 |
return convertHistogram(labelKeys, metric.TimeSeries) |
| 74 |
case ocmetricdata.TypeSummary: |
| 75 |
return convertSummary(labelKeys, metric.TimeSeries) |
| 76 |
} |
| 77 |
return nil, fmt.Errorf("%w: %q", errAggregationType, metric.Descriptor.Type) |
| 78 |
} |
| 79 |
|
| 80 |
// convertGauge converts an OpenCensus gauge to an OpenTelemetry gauge aggregation. |
| 81 |
func convertGauge[N int64 | float64]( |
| 82 |
labelKeys []ocmetricdata.LabelKey, |
| 83 |
ts []*ocmetricdata.TimeSeries, |
| 84 |
) (metricdata.Gauge[N], error) { |
| 85 |
points, err := convertNumberDataPoints[N](labelKeys, ts) |
| 86 |
return metricdata.Gauge[N]{DataPoints: points}, err |
| 87 |
} |
| 88 |
|
| 89 |
// convertSum converts an OpenCensus cumulative to an OpenTelemetry sum aggregation. |
| 90 |
func convertSum[N int64 | float64]( |
| 91 |
labelKeys []ocmetricdata.LabelKey, |
| 92 |
ts []*ocmetricdata.TimeSeries, |
| 93 |
) (metricdata.Sum[N], error) { |
| 94 |
points, err := convertNumberDataPoints[N](labelKeys, ts) |
| 95 |
// OpenCensus sums are always Cumulative |
| 96 |
return metricdata.Sum[N]{DataPoints: points, Temporality: metricdata.CumulativeTemporality, IsMonotonic: true}, err |
| 97 |
} |
| 98 |
|
| 99 |
// convertNumberDataPoints converts OpenCensus TimeSeries to OpenTelemetry DataPoints. |
| 100 |
func convertNumberDataPoints[N int64 | float64]( |
| 101 |
labelKeys []ocmetricdata.LabelKey, |
| 102 |
ts []*ocmetricdata.TimeSeries, |
| 103 |
) ([]metricdata.DataPoint[N], error) { |
| 104 |
var points []metricdata.DataPoint[N] |
| 105 |
var err error |
| 106 |
for _, t := range ts { |
| 107 |
attrs, attrsErr := convertAttrs(labelKeys, t.LabelValues) |
| 108 |
if attrsErr != nil { |
| 109 |
err = errors.Join(err, attrsErr) |
| 110 |
continue |
| 111 |
} |
| 112 |
for _, p := range t.Points { |
| 113 |
v, ok := p.Value.(N) |
| 114 |
if !ok { |
| 115 |
err = errors.Join(err, fmt.Errorf("%w: %q", errMismatchedValueTypes, p.Value)) |
| 116 |
continue |
| 117 |
} |
| 118 |
points = append(points, metricdata.DataPoint[N]{ |
| 119 |
Attributes: attrs, |
| 120 |
StartTime: t.StartTime, |
| 121 |
Time: p.Time, |
| 122 |
Value: v, |
| 123 |
}) |
| 124 |
} |
| 125 |
} |
| 126 |
return points, err |
| 127 |
} |
| 128 |
|
| 129 |
// convertHistogram converts OpenCensus Distribution timeseries to an |
| 130 |
// OpenTelemetry Histogram aggregation. |
| 131 |
func convertHistogram( |
| 132 |
labelKeys []ocmetricdata.LabelKey, |
| 133 |
ts []*ocmetricdata.TimeSeries, |
| 134 |
) (metricdata.Histogram[float64], error) { |
| 135 |
points := make([]metricdata.HistogramDataPoint[float64], 0, len(ts)) |
| 136 |
var err error |
| 137 |
for _, t := range ts { |
| 138 |
attrs, attrsErr := convertAttrs(labelKeys, t.LabelValues) |
| 139 |
if attrsErr != nil { |
| 140 |
err = errors.Join(err, attrsErr) |
| 141 |
continue |
| 142 |
} |
| 143 |
for _, p := range t.Points { |
| 144 |
dist, ok := p.Value.(*ocmetricdata.Distribution) |
| 145 |
if !ok { |
| 146 |
err = errors.Join(err, fmt.Errorf("%w: %d", errMismatchedValueTypes, p.Value)) |
| 147 |
continue |
| 148 |
} |
| 149 |
bucketCounts, exemplars, bucketErr := convertBuckets(dist.Buckets) |
| 150 |
if bucketErr != nil { |
| 151 |
err = errors.Join(err, bucketErr) |
| 152 |
continue |
| 153 |
} |
| 154 |
if dist.Count < 0 { |
| 155 |
err = errors.Join(err, fmt.Errorf("%w: %d", errNegativeCount, dist.Count)) |
| 156 |
continue |
| 157 |
} |
| 158 |
points = append(points, metricdata.HistogramDataPoint[float64]{ |
| 159 |
Attributes: attrs, |
| 160 |
StartTime: t.StartTime, |
| 161 |
Time: p.Time, |
| 162 |
Count: uint64(max(0, dist.Count)), // nolint:gosec // A count should never be negative. |
| 163 |
Sum: dist.Sum, |
| 164 |
Bounds: dist.BucketOptions.Bounds, |
| 165 |
BucketCounts: bucketCounts, |
| 166 |
Exemplars: exemplars, |
| 167 |
}) |
| 168 |
} |
| 169 |
} |
| 170 |
return metricdata.Histogram[float64]{DataPoints: points, Temporality: metricdata.CumulativeTemporality}, err |
| 171 |
} |
| 172 |
|
| 173 |
// convertBuckets converts from OpenCensus bucket counts to slice of uint64, |
| 174 |
// and converts OpenCensus exemplars to OpenTelemetry exemplars. |
| 175 |
func convertBuckets(buckets []ocmetricdata.Bucket) ([]uint64, []metricdata.Exemplar[float64], error) { |
| 176 |
bucketCounts := make([]uint64, len(buckets)) |
| 177 |
exemplars := []metricdata.Exemplar[float64]{} |
| 178 |
var err error |
| 179 |
for i, bucket := range buckets { |
| 180 |
if bucket.Count < 0 { |
| 181 |
err = errors.Join(err, fmt.Errorf("%w: %q", errNegativeBucketCount, bucket.Count)) |
| 182 |
continue |
| 183 |
} |
| 184 |
bucketCounts[i] = uint64(max(0, bucket.Count)) // nolint:gosec // A count should never be negative. |
| 185 |
|
| 186 |
if bucket.Exemplar != nil { |
| 187 |
exemplar, exemplarErr := convertExemplar(bucket.Exemplar) |
| 188 |
if exemplarErr != nil { |
| 189 |
err = errors.Join(err, exemplarErr) |
| 190 |
continue |
| 191 |
} |
| 192 |
exemplars = append(exemplars, exemplar) |
| 193 |
} |
| 194 |
} |
| 195 |
return bucketCounts, exemplars, err |
| 196 |
} |
| 197 |
|
| 198 |
// convertExemplar converts an OpenCensus exemplar to an OpenTelemetry exemplar. |
| 199 |
func convertExemplar(ocExemplar *ocmetricdata.Exemplar) (metricdata.Exemplar[float64], error) { |
| 200 |
exemplar := metricdata.Exemplar[float64]{ |
| 201 |
Value: ocExemplar.Value, |
| 202 |
Time: ocExemplar.Timestamp, |
| 203 |
} |
| 204 |
var err error |
| 205 |
for k, v := range ocExemplar.Attachments { |
| 206 |
switch k { |
| 207 |
case ocmetricdata.AttachmentKeySpanContext: |
| 208 |
sc, ok := v.(octrace.SpanContext) |
| 209 |
if !ok { |
| 210 |
err = errors.Join(err, fmt.Errorf("%w; type: %v", errInvalidExemplarSpanContext, reflect.TypeOf(v))) |
| 211 |
continue |
| 212 |
} |
| 213 |
exemplar.SpanID = sc.SpanID[:] |
| 214 |
exemplar.TraceID = sc.TraceID[:] |
| 215 |
default: |
| 216 |
exemplar.FilteredAttributes = append(exemplar.FilteredAttributes, convertKV(k, v)) |
| 217 |
} |
| 218 |
} |
| 219 |
slices.SortFunc(exemplar.FilteredAttributes, func(a, b attribute.KeyValue) int { |
| 220 |
return cmp.Compare(a.Key, b.Key) |
| 221 |
}) |
| 222 |
return exemplar, err |
| 223 |
} |
| 224 |
|
| 225 |
// convertKV converts an OpenCensus Attachment to an OpenTelemetry KeyValue. |
| 226 |
func convertKV(key string, value any) attribute.KeyValue { |
| 227 |
switch typedVal := value.(type) { |
| 228 |
case bool: |
| 229 |
return attribute.Bool(key, typedVal) |
| 230 |
case int: |
| 231 |
return attribute.Int(key, typedVal) |
| 232 |
case int8: |
| 233 |
return attribute.Int(key, int(typedVal)) |
| 234 |
case int16: |
| 235 |
return attribute.Int(key, int(typedVal)) |
| 236 |
case int32: |
| 237 |
return attribute.Int(key, int(typedVal)) |
| 238 |
case int64: |
| 239 |
return attribute.Int64(key, typedVal) |
| 240 |
case uint: |
| 241 |
return uintKV(key, typedVal) |
| 242 |
case uint8: |
| 243 |
return uintKV(key, uint(typedVal)) |
| 244 |
case uint16: |
| 245 |
return uintKV(key, uint(typedVal)) |
| 246 |
case uint32: |
| 247 |
return uintKV(key, uint(typedVal)) |
| 248 |
case uintptr: |
| 249 |
return uint64KV(key, uint64(typedVal)) |
| 250 |
case uint64: |
| 251 |
return uint64KV(key, typedVal) |
| 252 |
case float32: |
| 253 |
return attribute.Float64(key, float64(typedVal)) |
| 254 |
case float64: |
| 255 |
return attribute.Float64(key, typedVal) |
| 256 |
case complex64: |
| 257 |
return attribute.String(key, complexToString(typedVal)) |
| 258 |
case complex128: |
| 259 |
return attribute.String(key, complexToString(typedVal)) |
| 260 |
case string: |
| 261 |
return attribute.String(key, typedVal) |
| 262 |
case []bool: |
| 263 |
return attribute.BoolSlice(key, typedVal) |
| 264 |
case []int: |
| 265 |
return attribute.IntSlice(key, typedVal) |
| 266 |
case []int8: |
| 267 |
return intSliceKV(key, typedVal) |
| 268 |
case []int16: |
| 269 |
return intSliceKV(key, typedVal) |
| 270 |
case []int32: |
| 271 |
return intSliceKV(key, typedVal) |
| 272 |
case []int64: |
| 273 |
return attribute.Int64Slice(key, typedVal) |
| 274 |
case []uint: |
| 275 |
return uintSliceKV(key, typedVal) |
| 276 |
case []uint8: |
| 277 |
return uintSliceKV(key, typedVal) |
| 278 |
case []uint16: |
| 279 |
return uintSliceKV(key, typedVal) |
| 280 |
case []uint32: |
| 281 |
return uintSliceKV(key, typedVal) |
| 282 |
case []uintptr: |
| 283 |
return uintSliceKV(key, typedVal) |
| 284 |
case []uint64: |
| 285 |
return uintSliceKV(key, typedVal) |
| 286 |
case []float32: |
| 287 |
floatSlice := make([]float64, len(typedVal)) |
| 288 |
for i := range typedVal { |
| 289 |
floatSlice[i] = float64(typedVal[i]) |
| 290 |
} |
| 291 |
return attribute.Float64Slice(key, floatSlice) |
| 292 |
case []float64: |
| 293 |
return attribute.Float64Slice(key, typedVal) |
| 294 |
case []complex64: |
| 295 |
return complexSliceKV(key, typedVal) |
| 296 |
case []complex128: |
| 297 |
return complexSliceKV(key, typedVal) |
| 298 |
case []string: |
| 299 |
return attribute.StringSlice(key, typedVal) |
| 300 |
case fmt.Stringer: |
| 301 |
return attribute.Stringer(key, typedVal) |
| 302 |
default: |
| 303 |
return attribute.String(key, fmt.Sprintf("unhandled attribute value: %+v", value)) |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
func intSliceKV[N int8 | int16 | int32](key string, val []N) attribute.KeyValue { |
| 308 |
intSlice := make([]int, len(val)) |
| 309 |
for i := range val { |
| 310 |
intSlice[i] = int(val[i]) |
| 311 |
} |
| 312 |
return attribute.IntSlice(key, intSlice) |
| 313 |
} |
| 314 |
|
| 315 |
func uintKV(key string, val uint) attribute.KeyValue { |
| 316 |
if val > uint(math.MaxInt) { |
| 317 |
return attribute.String(key, strconv.FormatUint(uint64(val), 10)) |
| 318 |
} |
| 319 |
return attribute.Int(key, int(val)) // nolint: gosec // Overflow checked above. |
| 320 |
} |
| 321 |
|
| 322 |
func uintSliceKV[N uint | uint8 | uint16 | uint32 | uint64 | uintptr](key string, val []N) attribute.KeyValue { |
| 323 |
strSlice := make([]string, len(val)) |
| 324 |
for i := range val { |
| 325 |
strSlice[i] = strconv.FormatUint(uint64(val[i]), 10) |
| 326 |
} |
| 327 |
return attribute.StringSlice(key, strSlice) |
| 328 |
} |
| 329 |
|
| 330 |
func uint64KV(key string, val uint64) attribute.KeyValue { |
| 331 |
const maxInt64 = ^uint64(0) >> 1 |
| 332 |
if val > maxInt64 { |
| 333 |
return attribute.String(key, strconv.FormatUint(val, 10)) |
| 334 |
} |
| 335 |
return attribute.Int64(key, int64(val)) // nolint: gosec // Overflow checked above. |
| 336 |
} |
| 337 |
|
| 338 |
func complexSliceKV[N complex64 | complex128](key string, val []N) attribute.KeyValue { |
| 339 |
strSlice := make([]string, len(val)) |
| 340 |
for i := range val { |
| 341 |
strSlice[i] = complexToString(val[i]) |
| 342 |
} |
| 343 |
return attribute.StringSlice(key, strSlice) |
| 344 |
} |
| 345 |
|
| 346 |
func complexToString[N complex64 | complex128](val N) string { |
| 347 |
return strconv.FormatComplex(complex128(val), 'f', -1, 64) |
| 348 |
} |
| 349 |
|
| 350 |
// convertSummary converts OpenCensus Summary timeseries to an |
| 351 |
// OpenTelemetry Summary. |
| 352 |
func convertSummary(labelKeys []ocmetricdata.LabelKey, ts []*ocmetricdata.TimeSeries) (metricdata.Summary, error) { |
| 353 |
points := make([]metricdata.SummaryDataPoint, 0, len(ts)) |
| 354 |
var err error |
| 355 |
for _, t := range ts { |
| 356 |
attrs, attrErr := convertAttrs(labelKeys, t.LabelValues) |
| 357 |
if attrErr != nil { |
| 358 |
err = errors.Join(err, attrErr) |
| 359 |
continue |
| 360 |
} |
| 361 |
for _, p := range t.Points { |
| 362 |
summary, ok := p.Value.(*ocmetricdata.Summary) |
| 363 |
if !ok { |
| 364 |
err = errors.Join(err, fmt.Errorf("%w: %d", errMismatchedValueTypes, p.Value)) |
| 365 |
continue |
| 366 |
} |
| 367 |
if summary.Count < 0 { |
| 368 |
err = errors.Join(err, fmt.Errorf("%w: %d", errNegativeCount, summary.Count)) |
| 369 |
continue |
| 370 |
} |
| 371 |
point := metricdata.SummaryDataPoint{ |
| 372 |
Attributes: attrs, |
| 373 |
StartTime: t.StartTime, |
| 374 |
Time: p.Time, |
| 375 |
Count: uint64(max(0, summary.Count)), // nolint:gosec // A count should never be negative. |
| 376 |
QuantileValues: convertQuantiles(summary.Snapshot), |
| 377 |
Sum: summary.Sum, |
| 378 |
} |
| 379 |
points = append(points, point) |
| 380 |
} |
| 381 |
} |
| 382 |
return metricdata.Summary{DataPoints: points}, err |
| 383 |
} |
| 384 |
|
| 385 |
// convertQuantiles converts an OpenCensus summary snapshot to |
| 386 |
// OpenTelemetry quantiles. |
| 387 |
func convertQuantiles(snapshot ocmetricdata.Snapshot) []metricdata.QuantileValue { |
| 388 |
quantileValues := make([]metricdata.QuantileValue, 0, len(snapshot.Percentiles)) |
| 389 |
for quantile, value := range snapshot.Percentiles { |
| 390 |
quantileValues = append(quantileValues, metricdata.QuantileValue{ |
| 391 |
// OpenCensus quantiles are range (0-100.0], but OpenTelemetry |
| 392 |
// quantiles are range [0.0, 1.0]. |
| 393 |
Quantile: quantile / 100.0, |
| 394 |
Value: value, |
| 395 |
}) |
| 396 |
} |
| 397 |
slices.SortFunc(quantileValues, func(a, b metricdata.QuantileValue) int { |
| 398 |
return cmp.Compare(a.Quantile, b.Quantile) |
| 399 |
}) |
| 400 |
return quantileValues |
| 401 |
} |
| 402 |
|
| 403 |
// convertAttrs converts from OpenCensus attribute keys and values to an |
| 404 |
// OpenTelemetry attribute Set. |
| 405 |
func convertAttrs(keys []ocmetricdata.LabelKey, values []ocmetricdata.LabelValue) (attribute.Set, error) { |
| 406 |
if len(keys) != len(values) { |
| 407 |
return attribute.NewSet(), fmt.Errorf( |
| 408 |
"%w: keys(%q) values(%q)", |
| 409 |
errMismatchedAttributeKeyValues, |
| 410 |
len(keys), |
| 411 |
len(values), |
| 412 |
) |
| 413 |
} |
| 414 |
attrs := []attribute.KeyValue{} |
| 415 |
for i, lv := range values { |
| 416 |
if !lv.Present { |
| 417 |
continue |
| 418 |
} |
| 419 |
attrs = append(attrs, attribute.KeyValue{ |
| 420 |
Key: attribute.Key(keys[i].Key), |
| 421 |
Value: attribute.StringValue(lv.Value), |
| 422 |
}) |
| 423 |
} |
| 424 |
return attribute.NewSet(attrs...), nil |
| 425 |
} |