Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[mdatagen] Generate wrapper for OTel calls as a first step towards configurable attributes #10911

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .chloggen/codeboten_wrap-otel-api-mdatagen.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver)
component: mdatagen

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Generate wrapper for OTel calls as a first step towards configurable attributes

# One or more tracking issues or pull requests related to the change
issues: [10911]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: []
2 changes: 1 addition & 1 deletion cmd/mdatagen/internal/samplereceiver/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func createMetrics(ctx context.Context, set receiver.Settings, _ component.Confi
if err != nil {
return nil, err
}
telemetryBuilder.BatchSizeTriggerSend.Add(ctx, 1)
telemetryBuilder.RecordBatchSizeTriggerSend(ctx, 1)
return nopReceiver{telemetryBuilder: telemetryBuilder}, nil
}

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

127 changes: 127 additions & 0 deletions cmd/mdatagen/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/stretchr/testify/require"

"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pmetric"
)

func TestRunContents(t *testing.T) {
Expand Down Expand Up @@ -620,6 +621,132 @@ func LeveledMeter(settings component.TelemetrySettings, level configtelemetry.Le
func Tracer(settings component.TelemetrySettings) trace.Tracer {
return settings.TracerProvider.Tracer("")
}
`,
},
{
name: "foo component with internal telemetry",
md: metadata{
Type: "foo",
Status: &Status{
Stability: map[component.StabilityLevel][]string{
component.StabilityLevelAlpha: {"metrics"},
},
Distributions: []string{"contrib"},
Class: "receiver",
},
Telemetry: telemetry{
Metrics: map[metricName]metric{
"metric1": {
Enabled: true,
Sum: &sum{
Async: false,
Mono: Mono{true},
MetricValueType: MetricValueType{ValueType: pmetric.NumberDataPointValueTypeInt},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add another case where the type is Histogram, since that's the other special case in the generated code?

},
},
"metric2": {
Enabled: true,
Sum: &sum{
Async: true,
Mono: Mono{false},
MetricValueType: MetricValueType{ValueType: pmetric.NumberDataPointValueTypeDouble},
},
},
},
},
},
expected: `// Code generated by mdatagen. DO NOT EDIT.

package metadata

import (
"context"
"errors"

"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/metric/noop"
"go.opentelemetry.io/otel/trace"

"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/config/configtelemetry"
)

// Deprecated: [v0.108.0] use LeveledMeter instead.
func Meter(settings component.TelemetrySettings) metric.Meter {
return settings.MeterProvider.Meter("")
}

func LeveledMeter(settings component.TelemetrySettings, level configtelemetry.Level) metric.Meter {
return settings.LeveledMeterProvider(level).Meter("")
}

func Tracer(settings component.TelemetrySettings) trace.Tracer {
return settings.TracerProvider.Tracer("")
}

// TelemetryBuilder provides an interface for components to report telemetry
// as defined in metadata and user config.
type TelemetryBuilder struct {
meter metric.Meter
Metric1 metric.Int64Counter
Metric2 metric.Float64ObservableUpDownCounter
observeMetric2 func(context.Context, metric.Observer) error
level configtelemetry.Level
}

// telemetryBuilderOption applies changes to default builder.
type telemetryBuilderOption func(*TelemetryBuilder)

// WithLevel sets the current telemetry level for the component.
func WithLevel(lvl configtelemetry.Level) telemetryBuilderOption {
return func(builder *TelemetryBuilder) {
builder.level = lvl
}
}

// WithMetric2Callback sets callback for observable Metric2 metric.
func WithMetric2Callback(cb func() float64, opts ...metric.ObserveOption) telemetryBuilderOption {
return func(builder *TelemetryBuilder) {
builder.observeMetric2 = func(_ context.Context, o metric.Observer) error {
o.ObserveFloat64(builder.Metric2, cb(), opts...)
return nil
}
}
}

// NewTelemetryBuilder provides a struct with methods to update all internal telemetry
// for a component
func NewTelemetryBuilder(settings component.TelemetrySettings, options ...telemetryBuilderOption) (*TelemetryBuilder, error) {
builder := TelemetryBuilder{level: configtelemetry.LevelBasic}
for _, op := range options {
op(&builder)
}
var err, errs error
if builder.level >= configtelemetry.LevelBasic {
builder.meter = Meter(settings)
} else {
builder.meter = noop.Meter{}
}
builder.Metric1, err = builder.meter.Int64Counter(
"otelcol_metric1",
metric.WithDescription(""),
metric.WithUnit("<nil>"),
)
errs = errors.Join(errs, err)
builder.Metric2, err = builder.meter.Float64ObservableUpDownCounter(
"otelcol_metric2",
metric.WithDescription(""),
metric.WithUnit("<nil>"),
)
errs = errors.Join(errs, err)
_, err = builder.meter.RegisterCallback(builder.observeMetric2, builder.Metric2)
errs = errors.Join(errs, err)
return &builder, errs
}

func (b *TelemetryBuilder) RecordMetric1(ctx context.Context, val int64, opts ...metric.AddOption) {
b.Metric1.Add(ctx, val, opts...)
}
`,
},
}
Expand Down
10 changes: 10 additions & 0 deletions cmd/mdatagen/templates/telemetry.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,14 @@ func NewTelemetryBuilder(settings component.TelemetrySettings, options ...teleme
return &builder, errs
}

{{- range $name, $metric := .Telemetry.Metrics }}
{{- if not $metric.Data.Async }}

func (b *TelemetryBuilder) Record{{ $name.Render }}(ctx context.Context, val {{ $metric.Data.BasicType }}, opts ...metric.{{- if eq $metric.Data.Type "Histogram" -}}Record{{- else -}}Add{{- end -}}Option) {
b.{{ $name.Render }}.{{- if eq $metric.Data.Type "Histogram" -}}Record{{- else -}}Add{{- end -}}(ctx, val, opts...)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe we also need Record for gauge metrics.

I found that the Int64Gauge metric type has Record, not Add as rendered here. (Same goes for Float64Gauge) This is hit if you do:

telemetry:
  metrics:
    fake_metric:
      enabled: true
      description: Description of metric
      unit: "{x}"
      gauge:
        value_type: int

}

{{- end }}
{{- end }}

{{- end }}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 9 additions & 16 deletions exporter/exporterhelper/obsexporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,21 +116,17 @@ func (or *obsReport) recordMetrics(ctx context.Context, dataType component.DataT
if or.level == configtelemetry.LevelNone {
return
}
var sentMeasure, failedMeasure metric.Int64Counter
switch dataType {
case component.DataTypeTraces:
sentMeasure = or.telemetryBuilder.ExporterSentSpans
failedMeasure = or.telemetryBuilder.ExporterSendFailedSpans
or.telemetryBuilder.RecordExporterSentSpans(ctx, sent, metric.WithAttributes(or.otelAttrs...))
or.telemetryBuilder.RecordExporterSendFailedSpans(ctx, failed, metric.WithAttributes(or.otelAttrs...))
case component.DataTypeMetrics:
sentMeasure = or.telemetryBuilder.ExporterSentMetricPoints
failedMeasure = or.telemetryBuilder.ExporterSendFailedMetricPoints
or.telemetryBuilder.RecordExporterSentMetricPoints(ctx, sent, metric.WithAttributes(or.otelAttrs...))
or.telemetryBuilder.RecordExporterSendFailedMetricPoints(ctx, failed, metric.WithAttributes(or.otelAttrs...))
case component.DataTypeLogs:
sentMeasure = or.telemetryBuilder.ExporterSentLogRecords
failedMeasure = or.telemetryBuilder.ExporterSendFailedLogRecords
or.telemetryBuilder.RecordExporterSentLogRecords(ctx, sent, metric.WithAttributes(or.otelAttrs...))
or.telemetryBuilder.RecordExporterSendFailedLogRecords(ctx, failed, metric.WithAttributes(or.otelAttrs...))
}

sentMeasure.Add(ctx, sent, metric.WithAttributes(or.otelAttrs...))
failedMeasure.Add(ctx, failed, metric.WithAttributes(or.otelAttrs...))
}

func endSpan(ctx context.Context, err error, numSent, numFailedToSend int64, sentItemsKey, failedToSendItemsKey string) {
Expand All @@ -156,15 +152,12 @@ func toNumItems(numExportedItems int, err error) (int64, int64) {
}

func (or *obsReport) recordEnqueueFailure(ctx context.Context, dataType component.DataType, failed int64) {
var enqueueFailedMeasure metric.Int64Counter
switch dataType {
case component.DataTypeTraces:
enqueueFailedMeasure = or.telemetryBuilder.ExporterEnqueueFailedSpans
or.telemetryBuilder.RecordExporterEnqueueFailedSpans(ctx, failed, metric.WithAttributes(or.otelAttrs...))
case component.DataTypeMetrics:
enqueueFailedMeasure = or.telemetryBuilder.ExporterEnqueueFailedMetricPoints
or.telemetryBuilder.RecordExporterEnqueueFailedMetricPoints(ctx, failed, metric.WithAttributes(or.otelAttrs...))
case component.DataTypeLogs:
enqueueFailedMeasure = or.telemetryBuilder.ExporterEnqueueFailedLogRecords
or.telemetryBuilder.RecordExporterEnqueueFailedLogRecords(ctx, failed, metric.WithAttributes(or.otelAttrs...))
}

enqueueFailedMeasure.Add(ctx, failed, metric.WithAttributes(or.otelAttrs...))
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions processor/batchprocessor/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ func newBatchProcessorTelemetry(set processor.Settings, currentMetadataCardinali
func (bpt *batchProcessorTelemetry) record(trigger trigger, sent, bytes int64) {
switch trigger {
case triggerBatchSize:
bpt.telemetryBuilder.ProcessorBatchBatchSizeTriggerSend.Add(bpt.exportCtx, 1, metric.WithAttributeSet(bpt.processorAttr))
bpt.telemetryBuilder.RecordProcessorBatchBatchSizeTriggerSend(bpt.exportCtx, 1, metric.WithAttributeSet(bpt.processorAttr))
case triggerTimeout:
bpt.telemetryBuilder.ProcessorBatchTimeoutTriggerSend.Add(bpt.exportCtx, 1, metric.WithAttributeSet(bpt.processorAttr))
bpt.telemetryBuilder.RecordProcessorBatchTimeoutTriggerSend(bpt.exportCtx, 1, metric.WithAttributeSet(bpt.processorAttr))
}

bpt.telemetryBuilder.ProcessorBatchBatchSendSize.Record(bpt.exportCtx, sent, metric.WithAttributeSet(bpt.processorAttr))
bpt.telemetryBuilder.RecordProcessorBatchBatchSendSize(bpt.exportCtx, sent, metric.WithAttributeSet(bpt.processorAttr))
if bpt.detailed {
bpt.telemetryBuilder.ProcessorBatchBatchSendSizeBytes.Record(bpt.exportCtx, bytes, metric.WithAttributeSet(bpt.processorAttr))
bpt.telemetryBuilder.RecordProcessorBatchBatchSendSizeBytes(bpt.exportCtx, bytes, metric.WithAttributeSet(bpt.processorAttr))
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading