Skip to content

Commit

Permalink
[connector/spanmetricsconnector] Added disabling options (#23039)
Browse files Browse the repository at this point in the history
**Description:** <Describe what has changed.>
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.
We've tried to use transform as [it was suggested
here](#20525)
And this helps in part of getting less data. But we consumed too much
memory because of high cardinality labels. So we decided to suggest this
mr to escape metric creation at the very beginning.

**Link to tracking Issue:** 
[GH-16344]

**Testing:** 
Added tests to the repository

**Documentation:**
Readme file updated

---------

Co-authored-by: Antoine Toulme <[email protected]>
  • Loading branch information
LaserPhaser and atoulme authored Jun 30, 2023
1 parent 3c9ddf9 commit 4c817c6
Show file tree
Hide file tree
Showing 6 changed files with 205 additions and 24 deletions.
20 changes: 20 additions & 0 deletions .chloggen/spanmetricsconnector_disable_options.yaml
Original file line number Diff line number Diff line change
@@ -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:
3 changes: 3 additions & 0 deletions connector/spanmetricsconnector/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand All @@ -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`.
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion connector/spanmetricsconnector/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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"`
Expand Down
76 changes: 55 additions & 21 deletions connector/spanmetricsconnector/connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -256,9 +260,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)
}

}
}

Expand Down Expand Up @@ -303,14 +311,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)
Expand All @@ -335,13 +343,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))
Expand All @@ -364,10 +390,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 {
Expand Down
124 changes: 123 additions & 1 deletion connector/spanmetricsconnector/connector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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{
Expand Down
2 changes: 1 addition & 1 deletion connector/spanmetricsconnector/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
}
}

Expand Down

0 comments on commit 4c817c6

Please sign in to comment.