diff --git a/.chloggen/spanmetricsconnector_disable_options.yaml b/.chloggen/spanmetricsconnector_disable_options.yaml new file mode 100755 index 000000000000..15f6f4af1438 --- /dev/null +++ b/.chloggen/spanmetricsconnector_disable_options.yaml @@ -0,0 +1,20 @@ +# Use this changelog template to create an entry for release notes. +# If your change doesn't affect end users, such as a test fix or a tooling change, +# you should instead start your pull request title with [chore] or use the "Skip Changelog" label. + +# 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. filelogreceiver) +component: spanmetricsconnector + +# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). +note: "Added disabling options for histogram metrics and option to exclude default labels from all metrics. In some cases users want to optionally disable part of metrics because they generate too much data or are not needed." + +# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. +issues: [16344] + +# (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: diff --git a/connector/spanmetricsconnector/README.md b/connector/spanmetricsconnector/README.md index dad1bda76942..84c5da08ca49 100644 --- a/connector/spanmetricsconnector/README.md +++ b/connector/spanmetricsconnector/README.md @@ -75,6 +75,7 @@ The following settings can be optionally configured: - `histogram` (default: `explicit`): Use to configure the type of histogram to record calculated from spans duration measurements. Must be either `explicit` or `exponential`. + - `disable` (default: `false`): Disable all histogram metrics. - `unit` (default: `ms`): The time unit for recording duration measurements. calculated from spans duration measurements. One of either: `ms` or `s`. - `explicit`: @@ -90,6 +91,7 @@ The following settings can be optionally configured: If the `name`d attribute is missing in the span, the optional provided `default` is used. If no `default` is provided, this dimension will be **omitted** from the metric. +- `exclude_dimensions`: the list of dimensions to be excluded from the default set of dimensions. Use to exclude unneeded data from metrics. - `dimensions_cache_size` (default: `1000`): the size of cache for storing Dimensions to improve collectors memory usage. Must be a positive number. - `aggregation_temporality` (default: `AGGREGATION_TEMPORALITY_CUMULATIVE`): Defines the aggregation temporality of the generated metrics. One of either `AGGREGATION_TEMPORALITY_CUMULATIVE` or `AGGREGATION_TEMPORALITY_DELTA`. @@ -120,6 +122,7 @@ connectors: - name: http.method default: GET - name: http.status_code + exclude_dimensions: ['status.code'] dimensions_cache_size: 1000 aggregation_temporality: "AGGREGATION_TEMPORALITY_CUMULATIVE" metrics_flush_interval: 15s diff --git a/connector/spanmetricsconnector/config.go b/connector/spanmetricsconnector/config.go index bd03b63847bb..b19edbdef04a 100644 --- a/connector/spanmetricsconnector/config.go +++ b/connector/spanmetricsconnector/config.go @@ -38,7 +38,8 @@ type Config struct { // - status.code // The dimensions will be fetched from the span's attributes. Examples of some conventionally used attributes: // https://github.com/open-telemetry/opentelemetry-collector/blob/main/model/semconv/opentelemetry.go. - Dimensions []Dimension `mapstructure:"dimensions"` + Dimensions []Dimension `mapstructure:"dimensions"` + ExcludeDimensions []string `mapstructure:"exclude_dimensions"` // DimensionsCacheSize defines the size of cache for storing Dimensions, which helps to avoid cache memory growing // indefinitely over the lifetime of the collector. @@ -57,6 +58,7 @@ type Config struct { } type HistogramConfig struct { + Disable bool `mapstructure:"disable"` Unit metrics.Unit `mapstructure:"unit"` Exponential *ExponentialHistogramConfig `mapstructure:"exponential"` Explicit *ExplicitHistogramConfig `mapstructure:"explicit"` diff --git a/connector/spanmetricsconnector/connector.go b/connector/spanmetricsconnector/connector.go index 99f08eaf158f..bef6266a2435 100644 --- a/connector/spanmetricsconnector/connector.go +++ b/connector/spanmetricsconnector/connector.go @@ -117,6 +117,9 @@ func newConnector(logger *zap.Logger, config component.Config, ticker *clock.Tic } func initHistogramMetrics(cfg Config) metrics.HistogramMetrics { + if cfg.Histogram.Disable { + return nil + } if cfg.Histogram.Exponential != nil { maxSize := structure.DefaultMaxSize if cfg.Histogram.Exponential.MaxSize != 0 { @@ -235,12 +238,13 @@ func (p *connectorImp) buildMetrics() pmetric.Metrics { metric := sm.Metrics().AppendEmpty() metric.SetName(buildMetricName(p.config.Namespace, metricNameCalls)) sums.BuildMetrics(metric, p.startTimestamp, p.config.GetAggregationTemporality()) - - histograms := rawMetrics.histograms - metric = sm.Metrics().AppendEmpty() - metric.SetName(buildMetricName(p.config.Namespace, metricNameDuration)) - metric.SetUnit(p.config.Histogram.Unit.String()) - histograms.BuildMetrics(metric, p.startTimestamp, p.config.GetAggregationTemporality()) + if !p.config.Histogram.Disable { + histograms := rawMetrics.histograms + metric = sm.Metrics().AppendEmpty() + metric.SetName(buildMetricName(p.config.Namespace, metricNameDuration)) + metric.SetUnit(p.config.Histogram.Unit.String()) + histograms.BuildMetrics(metric, p.startTimestamp, p.config.GetAggregationTemporality()) + } } return m @@ -255,9 +259,13 @@ func (p *connectorImp) resetState() { p.metricKeyToDimensions.RemoveEvictedItems() // Exemplars are only relevant to this batch of traces, so must be cleared within the lock + if p.config.Histogram.Disable { + return + } for _, m := range p.resourceMetrics { m.histograms.Reset(true) } + } } @@ -302,14 +310,14 @@ func (p *connectorImp) aggregateMetrics(traces ptrace.Traces) { attributes = p.buildAttributes(serviceName, span, resourceAttr) p.metricKeyToDimensions.Add(key, attributes) } - - // aggregate histogram metrics - h := histograms.GetOrCreate(key, attributes) - h.Observe(duration) - if !span.TraceID().IsEmpty() { - h.AddExemplar(span.TraceID(), span.SpanID(), duration) + if !p.config.Histogram.Disable { + // aggregate histogram metrics + h := histograms.GetOrCreate(key, attributes) + h.Observe(duration) + if !span.TraceID().IsEmpty() { + h.AddExemplar(span.TraceID(), span.SpanID(), duration) + } } - // aggregate sums metrics s := sums.GetOrCreate(key, attributes) s.Add(1) @@ -334,13 +342,31 @@ func (p *connectorImp) getOrCreateResourceMetrics(attr pcommon.Map) *resourceMet return v } +// contains checks if string slice contains a string value +func contains(elements []string, value string) bool { + for _, element := range elements { + if value == element { + return true + } + } + return false +} + func (p *connectorImp) buildAttributes(serviceName string, span ptrace.Span, resourceAttrs pcommon.Map) pcommon.Map { attr := pcommon.NewMap() attr.EnsureCapacity(4 + len(p.dimensions)) - attr.PutStr(serviceNameKey, serviceName) - attr.PutStr(spanNameKey, span.Name()) - attr.PutStr(spanKindKey, traceutil.SpanKindStr(span.Kind())) - attr.PutStr(statusCodeKey, traceutil.StatusCodeStr(span.Status().Code())) + if !contains(p.config.ExcludeDimensions, serviceNameKey) { + attr.PutStr(serviceNameKey, serviceName) + } + if !contains(p.config.ExcludeDimensions, spanNameKey) { + attr.PutStr(spanNameKey, span.Name()) + } + if !contains(p.config.ExcludeDimensions, spanKindKey) { + attr.PutStr(spanKindKey, traceutil.SpanKindStr(span.Kind())) + } + if !contains(p.config.ExcludeDimensions, statusCodeKey) { + attr.PutStr(statusCodeKey, traceutil.StatusCodeStr(span.Status().Code())) + } for _, d := range p.dimensions { if v, ok := getDimensionValue(d, span.Attributes(), resourceAttrs); ok { v.CopyTo(attr.PutEmpty(d.name)) @@ -363,10 +389,18 @@ func concatDimensionValue(dest *bytes.Buffer, value string, prefixSep bool) { // The metric key is a simple concatenation of dimension values, delimited by a null character. func (p *connectorImp) buildKey(serviceName string, span ptrace.Span, optionalDims []dimension, resourceAttrs pcommon.Map) metrics.Key { p.keyBuf.Reset() - concatDimensionValue(p.keyBuf, serviceName, false) - concatDimensionValue(p.keyBuf, span.Name(), true) - concatDimensionValue(p.keyBuf, traceutil.SpanKindStr(span.Kind()), true) - concatDimensionValue(p.keyBuf, traceutil.StatusCodeStr(span.Status().Code()), true) + if !contains(p.config.ExcludeDimensions, serviceNameKey) { + concatDimensionValue(p.keyBuf, serviceName, false) + } + if !contains(p.config.ExcludeDimensions, spanNameKey) { + concatDimensionValue(p.keyBuf, span.Name(), true) + } + if !contains(p.config.ExcludeDimensions, spanKindKey) { + concatDimensionValue(p.keyBuf, traceutil.SpanKindStr(span.Kind()), true) + } + if !contains(p.config.ExcludeDimensions, statusCodeKey) { + concatDimensionValue(p.keyBuf, traceutil.StatusCodeStr(span.Status().Code()), true) + } for _, d := range optionalDims { if v, ok := getDimensionValue(d, span.Attributes(), resourceAttrs); ok { diff --git a/connector/spanmetricsconnector/connector_test.go b/connector/spanmetricsconnector/connector_test.go index f4473d290bb6..4146c63aa126 100644 --- a/connector/spanmetricsconnector/connector_test.go +++ b/connector/spanmetricsconnector/connector_test.go @@ -75,6 +75,24 @@ type span struct { spanID [8]byte } +// verifyDisabledHistogram expects that histograms are disabled. +func verifyDisabledHistogram(t testing.TB, input pmetric.Metrics) bool { + for i := 0; i < input.ResourceMetrics().Len(); i++ { + rm := input.ResourceMetrics().At(i) + ism := rm.ScopeMetrics() + // Checking all metrics, naming notice: ismC/mC - C here is for Counter. + for ismC := 0; ismC < ism.Len(); ismC++ { + m := ism.At(ismC).Metrics() + for mC := 0; mC < m.Len(); mC++ { + metric := m.At(mC) + assert.NotEqual(t, pmetric.MetricTypeExponentialHistogram, metric.Type()) + assert.NotEqual(t, pmetric.MetricTypeHistogram, metric.Type()) + } + } + } + return true +} + // verifyConsumeMetricsInputCumulative expects one accumulation of metrics, and marked as cumulative func verifyConsumeMetricsInputCumulative(t testing.TB, input pmetric.Metrics) bool { return verifyConsumeMetricsInput(t, input, pmetric.AggregationTemporalityCumulative, 1) @@ -371,6 +389,13 @@ func exponentialHistogramsConfig() HistogramConfig { } } +func disabledHistogramsConfig() HistogramConfig { + return HistogramConfig{ + Unit: defaultUnit, + Disable: true, + } +} + func TestBuildKeySameServiceNameCharSequence(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig().(*Config) @@ -390,6 +415,32 @@ func TestBuildKeySameServiceNameCharSequence(t *testing.T) { assert.Equal(t, metrics.Key("a\u0000bc\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET"), k1) } +func TestBuildKeyExcludeDimensionsAll(t *testing.T) { + factory := NewFactory() + cfg := factory.CreateDefaultConfig().(*Config) + cfg.ExcludeDimensions = []string{"span.kind", "service.name", "span.name", "status.code"} + c, err := newConnector(zaptest.NewLogger(t), cfg, nil) + require.NoError(t, err) + + span0 := ptrace.NewSpan() + span0.SetName("spanName") + k0 := c.buildKey("serviceName", span0, nil, pcommon.NewMap()) + assert.Equal(t, metrics.Key(""), k0) +} + +func TestBuildKeyExcludeWrongDimensions(t *testing.T) { + factory := NewFactory() + cfg := factory.CreateDefaultConfig().(*Config) + cfg.ExcludeDimensions = []string{"span.kind", "service.name.wrong.name", "span.name", "status.code"} + c, err := newConnector(zaptest.NewLogger(t), cfg, nil) + require.NoError(t, err) + + span0 := ptrace.NewSpan() + span0.SetName("spanName") + k0 := c.buildKey("serviceName", span0, nil, pcommon.NewMap()) + assert.Equal(t, metrics.Key("serviceName"), k0) +} + func TestBuildKeyWithDimensions(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig().(*Config) @@ -601,6 +652,14 @@ func TestConsumeTraces(t *testing.T) { verifier func(t testing.TB, input pmetric.Metrics) bool traces []ptrace.Traces }{ + // disabling histogram + { + name: "Test histogram metrics are disabled", + aggregationTemporality: cumulative, + histogramConfig: disabledHistogramsConfig, + verifier: verifyDisabledHistogram, + traces: []ptrace.Traces{buildSampleTrace()}, + }, // exponential buckets histogram { name: "Test single consumption, three spans (Cumulative), using exp. histogram", @@ -769,10 +828,64 @@ func BenchmarkConnectorConsumeTraces(b *testing.B) { } } -func newConnectorImp(t *testing.T, mcon consumer.Metrics, defaultNullValue *string, histogramConfig func() HistogramConfig, temporality string, logger *zap.Logger, ticker *clock.Ticker) *connectorImp { +func TestExcludeDimensionsConsumeTraces(t *testing.T) { + mcon := &mocks.MetricsConsumer{} + mcon.On("ConsumeMetrics", mock.Anything, mock.Anything).Return(nil) + excludeDimensions := []string{"span.kind", "span.name", "totallyWrongNameDoesNotAffectAnything"} + p := newConnectorImp(t, mcon, stringp("defaultNullValue"), explicitHistogramsConfig, cumulative, zaptest.NewLogger(t), nil, excludeDimensions...) + traces := buildSampleTrace() + + // Test + ctx := metadata.NewIncomingContext(context.Background(), nil) + + err := p.ConsumeTraces(ctx, traces) + require.NoError(t, err) + metrics := p.buildMetrics() + + for i := 0; i < metrics.ResourceMetrics().Len(); i++ { + rm := metrics.ResourceMetrics().At(i) + ism := rm.ScopeMetrics() + // Checking all metrics, naming notice: ilmC/mC - C here is for Counter. + for ilmC := 0; ilmC < ism.Len(); ilmC++ { + m := ism.At(ilmC).Metrics() + for mC := 0; mC < m.Len(); mC++ { + metric := m.At(mC) + // We check only sum and histogram metrics here, because for now only they are present in this module. + + switch metric.Type() { + case pmetric.MetricTypeExponentialHistogram, pmetric.MetricTypeHistogram: + { + dp := metric.Histogram().DataPoints() + for dpi := 0; dpi < dp.Len(); dpi++ { + for attributeKey := range dp.At(dpi).Attributes().AsRaw() { + assert.NotContains(t, excludeDimensions, attributeKey) + } + + } + } + case pmetric.MetricTypeEmpty, pmetric.MetricTypeGauge, pmetric.MetricTypeSum, pmetric.MetricTypeSummary: + { + dp := metric.Sum().DataPoints() + for dpi := 0; dpi < dp.Len(); dpi++ { + for attributeKey := range dp.At(dpi).Attributes().AsRaw() { + assert.NotContains(t, excludeDimensions, attributeKey) + } + } + } + + } + + } + } + } + +} + +func newConnectorImp(t *testing.T, mcon consumer.Metrics, defaultNullValue *string, histogramConfig func() HistogramConfig, temporality string, logger *zap.Logger, ticker *clock.Ticker, excludedDimensions ...string) *connectorImp { cfg := &Config{ AggregationTemporality: temporality, Histogram: histogramConfig(), + ExcludeDimensions: excludedDimensions, DimensionsCacheSize: DimensionsCacheSize, Dimensions: []Dimension{ // Set nil defaults to force a lookup for the attribute in the span. @@ -1000,6 +1113,15 @@ func TestConnector_initHistogramMetrics(t *testing.T) { config: Config{}, want: metrics.NewExplicitHistogramMetrics(defaultHistogramBucketsMs), }, + { + name: "Disable histogram", + config: Config{ + Histogram: HistogramConfig{ + Disable: true, + }, + }, + want: nil, + }, { name: "initialize explicit histogram with default bounds (ms)", config: Config{ diff --git a/connector/spanmetricsconnector/factory.go b/connector/spanmetricsconnector/factory.go index 26ec56ccc671..792b47935b7e 100644 --- a/connector/spanmetricsconnector/factory.go +++ b/connector/spanmetricsconnector/factory.go @@ -31,7 +31,7 @@ func createDefaultConfig() component.Config { AggregationTemporality: "AGGREGATION_TEMPORALITY_CUMULATIVE", DimensionsCacheSize: defaultDimensionsCacheSize, MetricsFlushInterval: 15 * time.Second, - Histogram: HistogramConfig{Unit: defaultUnit}, + Histogram: HistogramConfig{Disable: false, Unit: defaultUnit}, } }