| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package metric // import "go.opentelemetry.io/otel/sdk/metric" |
| 5 |
|
| 6 |
import ( |
| 7 |
"container/list" |
| 8 |
"context" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"sync" |
| 12 |
"sync/atomic" |
| 13 |
|
| 14 |
"go.opentelemetry.io/otel/internal/global" |
| 15 |
"go.opentelemetry.io/otel/metric/embedded" |
| 16 |
"go.opentelemetry.io/otel/sdk/instrumentation" |
| 17 |
"go.opentelemetry.io/otel/sdk/metric/exemplar" |
| 18 |
"go.opentelemetry.io/otel/sdk/metric/internal" |
| 19 |
"go.opentelemetry.io/otel/sdk/metric/internal/aggregate" |
| 20 |
"go.opentelemetry.io/otel/sdk/metric/metricdata" |
| 21 |
"go.opentelemetry.io/otel/sdk/resource" |
| 22 |
) |
| 23 |
|
| 24 |
var ( |
| 25 |
errCreatingAggregators = errors.New("could not create all aggregators") |
| 26 |
errIncompatibleAggregation = errors.New("incompatible aggregation") |
| 27 |
errUnknownAggregation = errors.New("unrecognized aggregation") |
| 28 |
) |
| 29 |
|
| 30 |
// instrumentSync is a synchronization point between a pipeline and an |
| 31 |
// instrument's aggregate function. |
| 32 |
type instrumentSync struct { |
| 33 |
name string |
| 34 |
description string |
| 35 |
unit string |
| 36 |
compAgg aggregate.ComputeAggregation |
| 37 |
} |
| 38 |
|
| 39 |
func newPipeline( |
| 40 |
res *resource.Resource, |
| 41 |
reader Reader, |
| 42 |
views []View, |
| 43 |
exemplarFilter exemplar.Filter, |
| 44 |
cardinalityLimit int, |
| 45 |
) *pipeline { |
| 46 |
if res == nil { |
| 47 |
res = resource.Empty() |
| 48 |
} |
| 49 |
return &pipeline{ |
| 50 |
resource: res, |
| 51 |
reader: reader, |
| 52 |
views: views, |
| 53 |
int64Measures: map[observableID[int64]][]aggregate.Measure[int64]{}, |
| 54 |
float64Measures: map[observableID[float64]][]aggregate.Measure[float64]{}, |
| 55 |
exemplarFilter: exemplarFilter, |
| 56 |
cardinalityLimit: cardinalityLimit, |
| 57 |
// aggregations is lazy allocated when needed. |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
// pipeline connects all of the instruments created by a meter provider to a Reader. |
| 62 |
// This is the object that will be `Reader.register()` when a meter provider is created. |
| 63 |
// |
| 64 |
// As instruments are created the instrument should be checked if it exists in |
| 65 |
// the views of a the Reader, and if so each aggregate function should be added |
| 66 |
// to the pipeline. |
| 67 |
type pipeline struct { |
| 68 |
resource *resource.Resource |
| 69 |
|
| 70 |
reader Reader |
| 71 |
views []View |
| 72 |
|
| 73 |
sync.Mutex |
| 74 |
int64Measures map[observableID[int64]][]aggregate.Measure[int64] |
| 75 |
float64Measures map[observableID[float64]][]aggregate.Measure[float64] |
| 76 |
aggregations map[instrumentation.Scope][]instrumentSync |
| 77 |
callbacks []func(context.Context) error |
| 78 |
multiCallbacks list.List |
| 79 |
exemplarFilter exemplar.Filter |
| 80 |
cardinalityLimit int |
| 81 |
} |
| 82 |
|
| 83 |
// addInt64Measure adds a new int64 measure to the pipeline for each observer. |
| 84 |
func (p *pipeline) addInt64Measure(id observableID[int64], m []aggregate.Measure[int64]) { |
| 85 |
p.Lock() |
| 86 |
defer p.Unlock() |
| 87 |
p.int64Measures[id] = m |
| 88 |
} |
| 89 |
|
| 90 |
// addFloat64Measure adds a new float64 measure to the pipeline for each observer. |
| 91 |
func (p *pipeline) addFloat64Measure(id observableID[float64], m []aggregate.Measure[float64]) { |
| 92 |
p.Lock() |
| 93 |
defer p.Unlock() |
| 94 |
p.float64Measures[id] = m |
| 95 |
} |
| 96 |
|
| 97 |
// addSync adds the instrumentSync to pipeline p with scope. This method is not |
| 98 |
// idempotent. Duplicate calls will result in duplicate additions, it is the |
| 99 |
// callers responsibility to ensure this is called with unique values. |
| 100 |
func (p *pipeline) addSync(scope instrumentation.Scope, iSync instrumentSync) { |
| 101 |
p.Lock() |
| 102 |
defer p.Unlock() |
| 103 |
if p.aggregations == nil { |
| 104 |
p.aggregations = map[instrumentation.Scope][]instrumentSync{ |
| 105 |
scope: {iSync}, |
| 106 |
} |
| 107 |
return |
| 108 |
} |
| 109 |
p.aggregations[scope] = append(p.aggregations[scope], iSync) |
| 110 |
} |
| 111 |
|
| 112 |
type multiCallback func(context.Context) error |
| 113 |
|
| 114 |
// addMultiCallback registers a multi-instrument callback to be run when |
| 115 |
// `produce()` is called. |
| 116 |
func (p *pipeline) addMultiCallback(c multiCallback) (unregister func()) { |
| 117 |
p.Lock() |
| 118 |
defer p.Unlock() |
| 119 |
e := p.multiCallbacks.PushBack(c) |
| 120 |
return func() { |
| 121 |
p.Lock() |
| 122 |
p.multiCallbacks.Remove(e) |
| 123 |
p.Unlock() |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
// produce returns aggregated metrics from a single collection. |
| 128 |
// |
| 129 |
// This method is safe to call concurrently. |
| 130 |
func (p *pipeline) produce(ctx context.Context, rm *metricdata.ResourceMetrics) error { |
| 131 |
// Only check if context is already cancelled before starting, not inside or after callback loops. |
| 132 |
// If this method returns after executing some callbacks but before running all aggregations, |
| 133 |
// internal aggregation state can be corrupted and result in incorrect data returned |
| 134 |
// by future produce calls. |
| 135 |
if err := ctx.Err(); err != nil { |
| 136 |
return err |
| 137 |
} |
| 138 |
|
| 139 |
p.Lock() |
| 140 |
defer p.Unlock() |
| 141 |
|
| 142 |
var err error |
| 143 |
for _, c := range p.callbacks { |
| 144 |
// TODO make the callbacks parallel. ( #3034 ) |
| 145 |
if e := c(ctx); e != nil { |
| 146 |
err = errors.Join(err, e) |
| 147 |
} |
| 148 |
} |
| 149 |
for e := p.multiCallbacks.Front(); e != nil; e = e.Next() { |
| 150 |
// TODO make the callbacks parallel. ( #3034 ) |
| 151 |
f := e.Value.(multiCallback) |
| 152 |
if e := f(ctx); e != nil { |
| 153 |
err = errors.Join(err, e) |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
rm.Resource = p.resource |
| 158 |
rm.ScopeMetrics = internal.ReuseSlice(rm.ScopeMetrics, len(p.aggregations)) |
| 159 |
|
| 160 |
i := 0 |
| 161 |
for scope, instruments := range p.aggregations { |
| 162 |
rm.ScopeMetrics[i].Metrics = internal.ReuseSlice(rm.ScopeMetrics[i].Metrics, len(instruments)) |
| 163 |
j := 0 |
| 164 |
for _, inst := range instruments { |
| 165 |
data := rm.ScopeMetrics[i].Metrics[j].Data |
| 166 |
if n := inst.compAgg(&data); n > 0 { |
| 167 |
rm.ScopeMetrics[i].Metrics[j].Name = inst.name |
| 168 |
rm.ScopeMetrics[i].Metrics[j].Description = inst.description |
| 169 |
rm.ScopeMetrics[i].Metrics[j].Unit = inst.unit |
| 170 |
rm.ScopeMetrics[i].Metrics[j].Data = data |
| 171 |
j++ |
| 172 |
} |
| 173 |
} |
| 174 |
rm.ScopeMetrics[i].Metrics = rm.ScopeMetrics[i].Metrics[:j] |
| 175 |
if len(rm.ScopeMetrics[i].Metrics) > 0 { |
| 176 |
rm.ScopeMetrics[i].Scope = scope |
| 177 |
i++ |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
rm.ScopeMetrics = rm.ScopeMetrics[:i] |
| 182 |
|
| 183 |
return err |
| 184 |
} |
| 185 |
|
| 186 |
// inserter facilitates inserting of new instruments from a single scope into a |
| 187 |
// pipeline. |
| 188 |
type inserter[N int64 | float64] struct { |
| 189 |
// aggregators is a cache that holds aggregate function inputs whose |
| 190 |
// outputs have been inserted into the underlying reader pipeline. This |
| 191 |
// cache ensures no duplicate aggregate functions are inserted into the |
| 192 |
// reader pipeline and if a new request during an instrument creation asks |
| 193 |
// for the same aggregate function input the same instance is returned. |
| 194 |
aggregators *cache[instID, aggVal[N]] |
| 195 |
|
| 196 |
// views is a cache that holds instrument identifiers for all the |
| 197 |
// instruments a Meter has created, it is provided from the Meter that owns |
| 198 |
// this inserter. This cache ensures during the creation of instruments |
| 199 |
// with the same name but different options (e.g. description, unit) a |
| 200 |
// warning message is logged. |
| 201 |
views *cache[string, instID] |
| 202 |
|
| 203 |
pipeline *pipeline |
| 204 |
} |
| 205 |
|
| 206 |
func newInserter[N int64 | float64](p *pipeline, vc *cache[string, instID]) *inserter[N] { |
| 207 |
if vc == nil { |
| 208 |
vc = &cache[string, instID]{} |
| 209 |
} |
| 210 |
return &inserter[N]{ |
| 211 |
aggregators: &cache[instID, aggVal[N]]{}, |
| 212 |
views: vc, |
| 213 |
pipeline: p, |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
// Instrument inserts the instrument inst with instUnit into a pipeline. All |
| 218 |
// views the pipeline contains are matched against, and any matching view that |
| 219 |
// creates a unique aggregate function will have its output inserted into the |
| 220 |
// pipeline and its input included in the returned slice. |
| 221 |
// |
| 222 |
// The returned aggregate function inputs are ensured to be deduplicated and |
| 223 |
// unique. If another view in another pipeline that is cached by this |
| 224 |
// inserter's cache has already inserted the same aggregate function for the |
| 225 |
// same instrument, that functions input instance is returned. |
| 226 |
// |
| 227 |
// If another instrument has already been inserted by this inserter, or any |
| 228 |
// other using the same cache, and it conflicts with the instrument being |
| 229 |
// inserted in this call, an aggregate function input matching the arguments |
| 230 |
// will still be returned but an Info level log message will also be logged to |
| 231 |
// the OTel global logger. |
| 232 |
// |
| 233 |
// If the passed instrument would result in an incompatible aggregate function, |
| 234 |
// an error is returned and that aggregate function output is not inserted nor |
| 235 |
// is its input returned. |
| 236 |
// |
| 237 |
// If an instrument is determined to use a Drop aggregation, that instrument is |
| 238 |
// not inserted nor returned. |
| 239 |
func (i *inserter[N]) Instrument(inst Instrument, readerAggregation Aggregation) ([]aggregate.Measure[N], error) { |
| 240 |
var ( |
| 241 |
matched bool |
| 242 |
measures []aggregate.Measure[N] |
| 243 |
) |
| 244 |
|
| 245 |
var err error |
| 246 |
seen := make(map[uint64]struct{}) |
| 247 |
for _, v := range i.pipeline.views { |
| 248 |
stream, match := v(inst) |
| 249 |
if !match { |
| 250 |
continue |
| 251 |
} |
| 252 |
matched = true |
| 253 |
in, id, e := i.cachedAggregator(inst.Scope, inst.Kind, stream, readerAggregation) |
| 254 |
if e != nil { |
| 255 |
err = errors.Join(err, e) |
| 256 |
} |
| 257 |
if in == nil { // Drop aggregation. |
| 258 |
continue |
| 259 |
} |
| 260 |
if _, ok := seen[id]; ok { |
| 261 |
// This aggregate function has already been added. |
| 262 |
continue |
| 263 |
} |
| 264 |
seen[id] = struct{}{} |
| 265 |
measures = append(measures, in) |
| 266 |
} |
| 267 |
|
| 268 |
if err != nil { |
| 269 |
err = errors.Join(errCreatingAggregators, err) |
| 270 |
} |
| 271 |
|
| 272 |
if matched { |
| 273 |
return measures, err |
| 274 |
} |
| 275 |
|
| 276 |
// Apply implicit default view if no explicit matched. |
| 277 |
stream := Stream{ |
| 278 |
Name: inst.Name, |
| 279 |
Description: inst.Description, |
| 280 |
Unit: inst.Unit, |
| 281 |
} |
| 282 |
in, _, e := i.cachedAggregator(inst.Scope, inst.Kind, stream, readerAggregation) |
| 283 |
if e != nil { |
| 284 |
if err == nil { |
| 285 |
err = errCreatingAggregators |
| 286 |
} |
| 287 |
err = errors.Join(err, e) |
| 288 |
} |
| 289 |
if in != nil { |
| 290 |
// Ensured to have not seen given matched was false. |
| 291 |
measures = append(measures, in) |
| 292 |
} |
| 293 |
return measures, err |
| 294 |
} |
| 295 |
|
| 296 |
// addCallback registers a single instrument callback to be run when |
| 297 |
// `produce()` is called. |
| 298 |
func (i *inserter[N]) addCallback(cback func(context.Context) error) { |
| 299 |
i.pipeline.Lock() |
| 300 |
defer i.pipeline.Unlock() |
| 301 |
i.pipeline.callbacks = append(i.pipeline.callbacks, cback) |
| 302 |
} |
| 303 |
|
| 304 |
var aggIDCount atomic.Uint64 |
| 305 |
|
| 306 |
// aggVal is the cached value in an aggregators cache. |
| 307 |
type aggVal[N int64 | float64] struct { |
| 308 |
ID uint64 |
| 309 |
Measure aggregate.Measure[N] |
| 310 |
Err error |
| 311 |
} |
| 312 |
|
| 313 |
// readerDefaultAggregation returns the default aggregation for the instrument |
| 314 |
// kind based on the reader's aggregation preferences. This is used unless the |
| 315 |
// aggregation is overridden with a view. |
| 316 |
func (i *inserter[N]) readerDefaultAggregation(kind InstrumentKind) Aggregation { |
| 317 |
aggregation := i.pipeline.reader.aggregation(kind) |
| 318 |
switch aggregation.(type) { |
| 319 |
case nil, AggregationDefault: |
| 320 |
// If the reader returns default or nil use the default selector. |
| 321 |
aggregation = DefaultAggregationSelector(kind) |
| 322 |
default: |
| 323 |
// Deep copy and validate before using. |
| 324 |
aggregation = aggregation.copy() |
| 325 |
if err := aggregation.err(); err != nil { |
| 326 |
orig := aggregation |
| 327 |
aggregation = DefaultAggregationSelector(kind) |
| 328 |
global.Error( |
| 329 |
err, "using default aggregation instead", |
| 330 |
"aggregation", orig, |
| 331 |
"replacement", aggregation, |
| 332 |
) |
| 333 |
} |
| 334 |
} |
| 335 |
return aggregation |
| 336 |
} |
| 337 |
|
| 338 |
// cachedAggregator returns the appropriate aggregate input and output |
| 339 |
// functions for an instrument configuration. If the exact instrument has been |
| 340 |
// created within the inst.Scope, those aggregate function instances will be |
| 341 |
// returned. Otherwise, new computed aggregate functions will be cached and |
| 342 |
// returned. |
| 343 |
// |
| 344 |
// If the instrument configuration conflicts with an instrument that has |
| 345 |
// already been created (e.g. description, unit, data type) a warning will be |
| 346 |
// logged at the "Info" level with the global OTel logger. Valid new aggregate |
| 347 |
// functions for the instrument configuration will still be returned without an |
| 348 |
// error. |
| 349 |
// |
| 350 |
// If the instrument defines an unknown or incompatible aggregation, an error |
| 351 |
// is returned. |
| 352 |
func (i *inserter[N]) cachedAggregator( |
| 353 |
scope instrumentation.Scope, |
| 354 |
kind InstrumentKind, |
| 355 |
stream Stream, |
| 356 |
readerAggregation Aggregation, |
| 357 |
) (meas aggregate.Measure[N], aggID uint64, err error) { |
| 358 |
switch stream.Aggregation.(type) { |
| 359 |
case nil: |
| 360 |
// The aggregation was not overridden with a view. Use the aggregation |
| 361 |
// provided by the reader. |
| 362 |
stream.Aggregation = readerAggregation |
| 363 |
case AggregationDefault: |
| 364 |
// The view explicitly requested the default aggregation. |
| 365 |
stream.Aggregation = DefaultAggregationSelector(kind) |
| 366 |
} |
| 367 |
if stream.ExemplarReservoirProviderSelector == nil { |
| 368 |
stream.ExemplarReservoirProviderSelector = DefaultExemplarReservoirProviderSelector |
| 369 |
} |
| 370 |
|
| 371 |
if err := isAggregatorCompatible(kind, stream.Aggregation); err != nil { |
| 372 |
return nil, 0, fmt.Errorf( |
| 373 |
"creating aggregator with instrumentKind: %d, aggregation %v: %w", |
| 374 |
kind, stream.Aggregation, err, |
| 375 |
) |
| 376 |
} |
| 377 |
|
| 378 |
id := i.instID(kind, stream) |
| 379 |
// If there is a conflict, the specification says the view should |
| 380 |
// still be applied and a warning should be logged. |
| 381 |
i.logConflict(id) |
| 382 |
|
| 383 |
// If there are requests for the same instrument with different name |
| 384 |
// casing, the first-seen needs to be returned. Use a normalize ID for the |
| 385 |
// cache lookup to ensure the correct comparison. |
| 386 |
normID := id.normalize() |
| 387 |
cv := i.aggregators.Lookup(normID, func() aggVal[N] { |
| 388 |
b := aggregate.Builder[N]{ |
| 389 |
Temporality: i.pipeline.reader.temporality(kind), |
| 390 |
ReservoirFunc: reservoirFunc[N]( |
| 391 |
stream.ExemplarReservoirProviderSelector(stream.Aggregation), |
| 392 |
i.pipeline.exemplarFilter, |
| 393 |
), |
| 394 |
} |
| 395 |
b.Filter = stream.AttributeFilter |
| 396 |
// A value less than or equal to zero will disable the aggregation |
| 397 |
// limits for the builder (an all the created aggregates). |
| 398 |
b.AggregationLimit = i.getCardinalityLimit(kind) |
| 399 |
in, out, err := i.aggregateFunc(b, stream.Aggregation, kind) |
| 400 |
if err != nil { |
| 401 |
return aggVal[N]{0, nil, err} |
| 402 |
} |
| 403 |
if in == nil { // Drop aggregator. |
| 404 |
return aggVal[N]{0, nil, nil} |
| 405 |
} |
| 406 |
i.pipeline.addSync(scope, instrumentSync{ |
| 407 |
// Use the first-seen name casing for this and all subsequent |
| 408 |
// requests of this instrument. |
| 409 |
name: stream.Name, |
| 410 |
description: stream.Description, |
| 411 |
unit: stream.Unit, |
| 412 |
compAgg: out, |
| 413 |
}) |
| 414 |
id := aggIDCount.Add(1) |
| 415 |
return aggVal[N]{id, in, err} |
| 416 |
}) |
| 417 |
return cv.Measure, cv.ID, cv.Err |
| 418 |
} |
| 419 |
|
| 420 |
// getCardinalityLimit returns the cardinality limit for the given instrument kind. |
| 421 |
// When the reader's selector returns fallback = true, the pipeline's global |
| 422 |
// limit is used, then the default if global is unset. When fallback is false, |
| 423 |
// the selector's limit is used (0 or less means unlimited). |
| 424 |
func (i *inserter[N]) getCardinalityLimit(kind InstrumentKind) int { |
| 425 |
limit, fallback := i.pipeline.reader.cardinalityLimit(kind) |
| 426 |
if fallback { |
| 427 |
return i.pipeline.cardinalityLimit |
| 428 |
} |
| 429 |
return limit |
| 430 |
} |
| 431 |
|
| 432 |
// logConflict validates if an instrument with the same case-insensitive name |
| 433 |
// as id has already been created. If that instrument conflicts with id, a |
| 434 |
// warning is logged. |
| 435 |
func (i *inserter[N]) logConflict(id instID) { |
| 436 |
// The API specification defines names as case-insensitive. If there is a |
| 437 |
// different casing of a name it needs to be a conflict. |
| 438 |
name := id.normalize().Name |
| 439 |
existing := i.views.Lookup(name, func() instID { return id }) |
| 440 |
if id == existing { |
| 441 |
return |
| 442 |
} |
| 443 |
|
| 444 |
const msg = "duplicate metric stream definitions" |
| 445 |
args := []any{ |
| 446 |
"names", fmt.Sprintf("%q, %q", existing.Name, id.Name), |
| 447 |
"descriptions", fmt.Sprintf("%q, %q", existing.Description, id.Description), |
| 448 |
"kinds", fmt.Sprintf("%s, %s", existing.Kind, id.Kind), |
| 449 |
"units", fmt.Sprintf("%s, %s", existing.Unit, id.Unit), |
| 450 |
"numbers", fmt.Sprintf("%s, %s", existing.Number, id.Number), |
| 451 |
} |
| 452 |
|
| 453 |
// The specification recommends logging a suggested view to resolve |
| 454 |
// conflicts if possible. |
| 455 |
// |
| 456 |
// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.21.0/specification/metrics/sdk.md#duplicate-instrument-registration |
| 457 |
if id.Unit != existing.Unit || id.Number != existing.Number { |
| 458 |
// There is no view resolution for these, don't make a suggestion. |
| 459 |
global.Warn(msg, args...) |
| 460 |
return |
| 461 |
} |
| 462 |
|
| 463 |
var stream string |
| 464 |
if id.Name != existing.Name || id.Kind != existing.Kind { |
| 465 |
stream = `Stream{Name: "{{NEW_NAME}}"}` |
| 466 |
} else if id.Description != existing.Description { |
| 467 |
stream = fmt.Sprintf("Stream{Description: %q}", existing.Description) |
| 468 |
} |
| 469 |
|
| 470 |
inst := fmt.Sprintf( |
| 471 |
"Instrument{Name: %q, Description: %q, Kind: %q, Unit: %q}", |
| 472 |
id.Name, id.Description, "InstrumentKind"+id.Kind.String(), id.Unit, |
| 473 |
) |
| 474 |
args = append(args, "suggested.view", fmt.Sprintf("NewView(%s, %s)", inst, stream)) |
| 475 |
|
| 476 |
global.Warn(msg, args...) |
| 477 |
} |
| 478 |
|
| 479 |
func (*inserter[N]) instID(kind InstrumentKind, stream Stream) instID { |
| 480 |
var zero N |
| 481 |
return instID{ |
| 482 |
Name: stream.Name, |
| 483 |
Description: stream.Description, |
| 484 |
Unit: stream.Unit, |
| 485 |
Kind: kind, |
| 486 |
Number: fmt.Sprintf("%T", zero), |
| 487 |
} |
| 488 |
} |
| 489 |
|
| 490 |
// aggregateFunc returns new aggregate functions matching agg, kind, and |
| 491 |
// monotonic. If the agg is unknown or temporality is invalid, an error is |
| 492 |
// returned. |
| 493 |
func (i *inserter[N]) aggregateFunc( |
| 494 |
b aggregate.Builder[N], |
| 495 |
agg Aggregation, |
| 496 |
kind InstrumentKind, |
| 497 |
) (meas aggregate.Measure[N], comp aggregate.ComputeAggregation, err error) { |
| 498 |
switch a := agg.(type) { |
| 499 |
case AggregationDefault: |
| 500 |
return i.aggregateFunc(b, DefaultAggregationSelector(kind), kind) |
| 501 |
case AggregationDrop: |
| 502 |
// Return nil in and out to signify the drop aggregator. |
| 503 |
case AggregationLastValue: |
| 504 |
switch kind { |
| 505 |
case InstrumentKindGauge: |
| 506 |
meas, comp = b.LastValue() |
| 507 |
case InstrumentKindObservableGauge: |
| 508 |
meas, comp = b.PrecomputedLastValue() |
| 509 |
} |
| 510 |
case AggregationSum: |
| 511 |
switch kind { |
| 512 |
case InstrumentKindObservableCounter: |
| 513 |
meas, comp = b.PrecomputedSum(true) |
| 514 |
case InstrumentKindObservableUpDownCounter: |
| 515 |
meas, comp = b.PrecomputedSum(false) |
| 516 |
case InstrumentKindCounter, InstrumentKindHistogram: |
| 517 |
meas, comp = b.Sum(true) |
| 518 |
default: |
| 519 |
// InstrumentKindUpDownCounter, InstrumentKindObservableGauge, and |
| 520 |
// instrumentKindUndefined or other invalid instrument kinds. |
| 521 |
meas, comp = b.Sum(false) |
| 522 |
} |
| 523 |
case AggregationExplicitBucketHistogram: |
| 524 |
var noSum bool |
| 525 |
switch kind { |
| 526 |
case InstrumentKindUpDownCounter, |
| 527 |
InstrumentKindObservableUpDownCounter, |
| 528 |
InstrumentKindObservableGauge, |
| 529 |
InstrumentKindGauge: |
| 530 |
// The sum should not be collected for any instrument that can make |
| 531 |
// negative measurements: |
| 532 |
// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.21.0/specification/metrics/sdk.md#histogram-aggregations |
| 533 |
noSum = true |
| 534 |
} |
| 535 |
meas, comp = b.ExplicitBucketHistogram(a.Boundaries, a.NoMinMax, noSum) |
| 536 |
case AggregationBase2ExponentialHistogram: |
| 537 |
var noSum bool |
| 538 |
switch kind { |
| 539 |
case InstrumentKindUpDownCounter, |
| 540 |
InstrumentKindObservableUpDownCounter, |
| 541 |
InstrumentKindObservableGauge, |
| 542 |
InstrumentKindGauge: |
| 543 |
// The sum should not be collected for any instrument that can make |
| 544 |
// negative measurements: |
| 545 |
// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.21.0/specification/metrics/sdk.md#histogram-aggregations |
| 546 |
noSum = true |
| 547 |
} |
| 548 |
meas, comp = b.ExponentialBucketHistogram(a.MaxSize, a.MaxScale, a.NoMinMax, noSum) |
| 549 |
|
| 550 |
default: |
| 551 |
err = errUnknownAggregation |
| 552 |
} |
| 553 |
|
| 554 |
return meas, comp, err |
| 555 |
} |
| 556 |
|
| 557 |
// isAggregatorCompatible checks if the aggregation can be used by the instrument. |
| 558 |
// Current compatibility: |
| 559 |
// |
| 560 |
// | Instrument Kind | Drop | LastValue | Sum | Histogram | Exponential Histogram | |
| 561 |
// |--------------------------|------|-----------|-----|-----------|-----------------------| |
| 562 |
// | Counter | ✓ | | ✓ | ✓ | ✓ | |
| 563 |
// | UpDownCounter | ✓ | | ✓ | ✓ | ✓ | |
| 564 |
// | Histogram | ✓ | | ✓ | ✓ | ✓ | |
| 565 |
// | Gauge | ✓ | ✓ | | ✓ | ✓ | |
| 566 |
// | Observable Counter | ✓ | | ✓ | ✓ | ✓ | |
| 567 |
// | Observable UpDownCounter | ✓ | | ✓ | ✓ | ✓ | |
| 568 |
// | Observable Gauge | ✓ | ✓ | | ✓ | ✓ |. |
| 569 |
func isAggregatorCompatible(kind InstrumentKind, agg Aggregation) error { |
| 570 |
switch agg.(type) { |
| 571 |
case AggregationDefault: |
| 572 |
return nil |
| 573 |
case AggregationExplicitBucketHistogram, AggregationBase2ExponentialHistogram: |
| 574 |
switch kind { |
| 575 |
case InstrumentKindCounter, |
| 576 |
InstrumentKindUpDownCounter, |
| 577 |
InstrumentKindHistogram, |
| 578 |
InstrumentKindGauge, |
| 579 |
InstrumentKindObservableCounter, |
| 580 |
InstrumentKindObservableUpDownCounter, |
| 581 |
InstrumentKindObservableGauge: |
| 582 |
return nil |
| 583 |
default: |
| 584 |
return errIncompatibleAggregation |
| 585 |
} |
| 586 |
case AggregationSum: |
| 587 |
switch kind { |
| 588 |
case InstrumentKindObservableCounter, |
| 589 |
InstrumentKindObservableUpDownCounter, |
| 590 |
InstrumentKindCounter, |
| 591 |
InstrumentKindHistogram, |
| 592 |
InstrumentKindUpDownCounter: |
| 593 |
return nil |
| 594 |
default: |
| 595 |
// TODO: review need for aggregation check after |
| 596 |
// https://github.com/open-telemetry/opentelemetry-specification/issues/2710 |
| 597 |
return errIncompatibleAggregation |
| 598 |
} |
| 599 |
case AggregationLastValue: |
| 600 |
switch kind { |
| 601 |
case InstrumentKindObservableGauge, InstrumentKindGauge: |
| 602 |
return nil |
| 603 |
} |
| 604 |
// TODO: review need for aggregation check after |
| 605 |
// https://github.com/open-telemetry/opentelemetry-specification/issues/2710 |
| 606 |
return errIncompatibleAggregation |
| 607 |
case AggregationDrop: |
| 608 |
return nil |
| 609 |
default: |
| 610 |
// This is used passed checking for default, it should be an error at this point. |
| 611 |
return fmt.Errorf("%w: %v", errUnknownAggregation, agg) |
| 612 |
} |
| 613 |
} |
| 614 |
|
| 615 |
// pipelines is the group of pipelines connecting Readers with instrument |
| 616 |
// measurement. |
| 617 |
type pipelines []*pipeline |
| 618 |
|
| 619 |
func newPipelines( |
| 620 |
res *resource.Resource, |
| 621 |
readers []Reader, |
| 622 |
views []View, |
| 623 |
exemplarFilter exemplar.Filter, |
| 624 |
cardinalityLimit int, |
| 625 |
) pipelines { |
| 626 |
pipes := make([]*pipeline, 0, len(readers)) |
| 627 |
for _, r := range readers { |
| 628 |
p := newPipeline(res, r, views, exemplarFilter, cardinalityLimit) |
| 629 |
r.register(p) |
| 630 |
pipes = append(pipes, p) |
| 631 |
} |
| 632 |
return pipes |
| 633 |
} |
| 634 |
|
| 635 |
type unregisterFuncs struct { |
| 636 |
embedded.Registration |
| 637 |
f []func() |
| 638 |
} |
| 639 |
|
| 640 |
func (u unregisterFuncs) Unregister() error { |
| 641 |
for _, f := range u.f { |
| 642 |
f() |
| 643 |
} |
| 644 |
return nil |
| 645 |
} |
| 646 |
|
| 647 |
// resolver facilitates resolving aggregate functions an instrument calls to |
| 648 |
// aggregate measurements with while updating all pipelines that need to pull |
| 649 |
// from those aggregations. |
| 650 |
type resolver[N int64 | float64] struct { |
| 651 |
inserters []*inserter[N] |
| 652 |
} |
| 653 |
|
| 654 |
func newResolver[N int64 | float64](p pipelines, vc *cache[string, instID]) resolver[N] { |
| 655 |
in := make([]*inserter[N], len(p)) |
| 656 |
for i := range in { |
| 657 |
in[i] = newInserter[N](p[i], vc) |
| 658 |
} |
| 659 |
return resolver[N]{in} |
| 660 |
} |
| 661 |
|
| 662 |
// Aggregators returns the Aggregators that must be updated by the instrument |
| 663 |
// defined by key. |
| 664 |
func (r resolver[N]) Aggregators(id Instrument) ([]aggregate.Measure[N], error) { |
| 665 |
var measures []aggregate.Measure[N] |
| 666 |
|
| 667 |
var err error |
| 668 |
for _, i := range r.inserters { |
| 669 |
in, e := i.Instrument(id, i.readerDefaultAggregation(id.Kind)) |
| 670 |
if e != nil { |
| 671 |
err = errors.Join(err, e) |
| 672 |
} |
| 673 |
measures = append(measures, in...) |
| 674 |
} |
| 675 |
return measures, err |
| 676 |
} |
| 677 |
|
| 678 |
// HistogramAggregators returns the histogram Aggregators that must be updated by the instrument |
| 679 |
// defined by key. If boundaries were provided on instrument instantiation, those take precedence |
| 680 |
// over boundaries provided by the reader. |
| 681 |
func (r resolver[N]) HistogramAggregators(id Instrument, boundaries []float64) ([]aggregate.Measure[N], error) { |
| 682 |
var measures []aggregate.Measure[N] |
| 683 |
|
| 684 |
var err error |
| 685 |
for _, i := range r.inserters { |
| 686 |
agg := i.readerDefaultAggregation(id.Kind) |
| 687 |
if histAgg, ok := agg.(AggregationExplicitBucketHistogram); ok && len(boundaries) > 0 { |
| 688 |
histAgg.Boundaries = boundaries |
| 689 |
agg = histAgg |
| 690 |
} |
| 691 |
in, e := i.Instrument(id, agg) |
| 692 |
if e != nil { |
| 693 |
err = errors.Join(err, e) |
| 694 |
} |
| 695 |
measures = append(measures, in...) |
| 696 |
} |
| 697 |
return measures, err |
| 698 |
} |