Skip to content

Commit

Permalink
[connector/datadog] Add container tags (open-telemetry#31642)
Browse files Browse the repository at this point in the history
**Description:** 
Customers can now set container tags on stats payload computed in DD
connector.

sample collector config:
```
  datadog/connector:
    traces:
      resource_attributes_as_container_tags:
        - "k8s.pod.name"
        - "cloud.availability_zone"
```
  • Loading branch information
dineshg13 committed Mar 20, 2024
1 parent 72c6cd0 commit da2043b
Show file tree
Hide file tree
Showing 7 changed files with 261 additions and 27 deletions.
23 changes: 23 additions & 0 deletions .chloggen/dinesh.gurumurthy_add-container-stats.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 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. filelogreceiver)
component: datadogconnector
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add a new option to the Datadog connector to enable container tags on stats Payloads.
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [31642]
# (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: |
This change adds a new option to the Datadog connector to enable container tags on stats Payloads. This is useful for users who want to use container tags as second primary tag for Datadog APM.
# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# 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: []
5 changes: 5 additions & 0 deletions connector/datadogconnector/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,11 @@ connectors:
## https://github.com/DataDog/datadog-agent/blob/505170c4ac8c3cbff1a61cf5f84b28d835c91058/pkg/trace/stats/concentrator.go#L55.
#
# peer_tags: ["tag"]

## @param resource_attributes_as_container_tags - enables the use of resource attributes as container tags - Optional
## A list of resource attributes that should be used as container tags.
#
# resource_attributes_as_container_tags: ["could.availability_zone", "could.region"]
```

**NOTE**: `compute_stats_by_span_kind` and `peer_tags_aggregation` only work when the feature gate `connector.datadogconnector.performance` is enabled. See below for details on this feature gate.
Expand Down
3 changes: 3 additions & 0 deletions connector/datadogconnector/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ type TracesConfig struct {
// TraceBuffer specifies the number of Datadog Agent TracerPayloads to buffer before dropping.
// The default value is 1000.
TraceBuffer int `mapstructure:"trace_buffer"`

// ResourceAttributesAsContainerTags specifies the list of resource attributes to be used as container tags.
ResourceAttributesAsContainerTags []string `mapstructure:"resource_attributes_as_container_tags"`
}

// Validate the configuration for errors. This is required by component.Config.
Expand Down
87 changes: 81 additions & 6 deletions connector/datadogconnector/connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,20 @@ package datadogconnector // import "github.com/open-telemetry/opentelemetry-coll
import (
"context"
"fmt"
"time"

pb "github.com/DataDog/datadog-agent/pkg/proto/pbgo/trace"
traceconfig "github.com/DataDog/datadog-agent/pkg/trace/config"
"github.com/DataDog/datadog-agent/pkg/trace/timing"
"github.com/DataDog/datadog-go/v5/statsd"
"github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/attributes"
"github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/metrics"
"github.com/patrickmn/go-cache"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/collector/pdata/ptrace"
semconv "go.opentelemetry.io/collector/semconv/v1.17.0"
"go.opentelemetry.io/otel/metric/noop"
"go.uber.org/zap"

Expand All @@ -36,6 +39,9 @@ type traceToMetricConnector struct {
// from the agent to OTLP Metrics.
translator *metrics.Translator

resourceAttrs map[string]string
containerTagCache *cache.Cache

// in specifies the channel through which the agent will output Stats Payloads
// resulting from ingested traces.
in chan *pb.StatsPayload
Expand All @@ -49,6 +55,13 @@ type traceToMetricConnector struct {

var _ component.Component = (*traceToMetricConnector)(nil) // testing that the connectorImp properly implements the type Component interface

// cacheExpiration is the time after which a container tag cache entry will expire
// and be removed from the cache.
var cacheExpiration = time.Minute * 5

// cacheCleanupInterval is the time after which the cache will be cleaned up.
var cacheCleanupInterval = time.Minute

// function to create a new connector
func newTraceToMetricConnector(set component.TelemetrySettings, cfg component.Config, metricsConsumer consumer.Metrics, metricsClient statsd.ClientInterface, timingReporter timing.Reporter) (*traceToMetricConnector, error) {
set.Logger.Info("Building datadog connector for traces to metrics")
Expand All @@ -63,14 +76,22 @@ func newTraceToMetricConnector(set component.TelemetrySettings, cfg component.Co
return nil, fmt.Errorf("failed to create metrics translator: %w", err)
}

ctags := make(map[string]string, len(cfg.(*Config).Traces.ResourceAttributesAsContainerTags))
for _, val := range cfg.(*Config).Traces.ResourceAttributesAsContainerTags {
ctags[val] = ""
}
ddtags := attributes.ContainerTagFromAttributes(ctags)

ctx := context.Background()
return &traceToMetricConnector{
logger: set.Logger,
agent: datadog.NewAgentWithConfig(ctx, getTraceAgentCfg(cfg.(*Config).Traces, attributesTranslator), in, metricsClient, timingReporter),
translator: trans,
in: in,
metricsConsumer: metricsConsumer,
exit: make(chan struct{}),
logger: set.Logger,
agent: datadog.NewAgentWithConfig(ctx, getTraceAgentCfg(cfg.(*Config).Traces, attributesTranslator), in, metricsClient, timingReporter),
translator: trans,
in: in,
metricsConsumer: metricsConsumer,
resourceAttrs: ddtags,
containerTagCache: cache.New(cacheExpiration, cacheCleanupInterval),
exit: make(chan struct{}),
}, nil
}

Expand All @@ -83,6 +104,10 @@ func getTraceAgentCfg(cfg TracesConfig, attributesTranslator *attributes.Transla
acfg.ComputeStatsBySpanKind = cfg.ComputeStatsBySpanKind
acfg.PeerTagsAggregation = cfg.PeerTagsAggregation
acfg.PeerTags = cfg.PeerTags
if len(cfg.ResourceAttributesAsContainerTags) > 0 {
acfg.Features["enable_cid_stats"] = struct{}{}
delete(acfg.Features, "disable_cid_stats")
}
if v := cfg.TraceBuffer; v > 0 {
acfg.TraceBuffer = v
}
Expand Down Expand Up @@ -120,11 +145,55 @@ func (c *traceToMetricConnector) Capabilities() consumer.Capabilities {
return consumer.Capabilities{MutatesData: false}
}

func (c *traceToMetricConnector) populateContainerTagsCache(traces ptrace.Traces) {
for i := 0; i < traces.ResourceSpans().Len(); i++ {
rs := traces.ResourceSpans().At(i)
attrs := rs.Resource().Attributes()
containerID, ok := attrs.Get(semconv.AttributeContainerID)
if !ok {
continue
}
ddContainerTags := attributes.ContainerTagsFromResourceAttributes(attrs)
for attr := range c.resourceAttrs {
if val, ok := ddContainerTags[attr]; ok {
var cacheVal map[string]struct{}
if v, ok := c.containerTagCache.Get(containerID.AsString()); ok {
cacheVal = v.(map[string]struct{})
cacheVal[fmt.Sprintf("%s:%s", attr, val)] = struct{}{}
} else {
cacheVal = make(map[string]struct{})
cacheVal[fmt.Sprintf("%s:%s", attr, val)] = struct{}{}
c.containerTagCache.Set(containerID.AsString(), cacheVal, cache.DefaultExpiration)
}

}
}
}
}

func (c *traceToMetricConnector) ConsumeTraces(ctx context.Context, traces ptrace.Traces) error {
c.populateContainerTagsCache(traces)
c.agent.Ingest(ctx, traces)
return nil
}

func (c *traceToMetricConnector) enrichStatsPayload(stats *pb.StatsPayload) {
for _, stat := range stats.Stats {
if stat.ContainerID != "" {
if tags, ok := c.containerTagCache.Get(stat.ContainerID); ok {
tagList := tags.(map[string]struct{})
for _, tag := range stat.Tags {
tagList[tag] = struct{}{}
}
stat.Tags = make([]string, 0, len(tagList))
for tag := range tagList {
stat.Tags = append(stat.Tags, tag)
}
}
}
}
}

// run awaits incoming stats resulting from the agent's ingestion, converts them
// to metrics and flushes them using the configured metrics exporter.
func (c *traceToMetricConnector) run() {
Expand All @@ -137,7 +206,13 @@ func (c *traceToMetricConnector) run() {
}
var mx pmetric.Metrics
var err error
// Enrich the stats with container tags
if len(c.resourceAttrs) > 0 {
c.enrichStatsPayload(stats)
}

c.logger.Debug("Received stats payload", zap.Any("stats", stats))

mx, err = c.translator.StatsToMetrics(stats)
if err != nil {
c.logger.Error("Failed to convert stats to metrics", zap.Error(err))
Expand Down
140 changes: 140 additions & 0 deletions connector/datadogconnector/connector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,22 @@ package datadogconnector
import (
"context"
"testing"
"time"

pb "github.com/DataDog/datadog-agent/pkg/proto/pbgo/trace"
"github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/attributes"
otlpmetrics "github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/metrics"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/component/componenttest"
"go.opentelemetry.io/collector/connector/connectortest"
"go.opentelemetry.io/collector/consumer/consumertest"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/ptrace"
semconv "go.opentelemetry.io/collector/semconv/v1.17.0"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
)

var _ component.Component = (*traceToMetricConnector)(nil) // testing that the connectorImp properly implements the type Component interface
Expand Down Expand Up @@ -41,3 +52,132 @@ func TestTraceToTraceConnector(t *testing.T) {
_, ok := traceToTracesConnector.(*traceToTraceConnector)
assert.True(t, ok) // checks if the created connector implements the connectorImp struct
}

var (
spanStartTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 12, 321, time.UTC))
spanEventTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 123, time.UTC))
spanEndTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC))
)

func generateTrace() ptrace.Traces {
td := ptrace.NewTraces()
res := td.ResourceSpans().AppendEmpty().Resource()
res.Attributes().EnsureCapacity(3)
res.Attributes().PutStr("resource-attr1", "resource-attr-val1")
res.Attributes().PutStr("container.id", "my-container-id")
res.Attributes().PutStr("cloud.availability_zone", "my-zone")
res.Attributes().PutStr("cloud.region", "my-region")

ss := td.ResourceSpans().At(0).ScopeSpans().AppendEmpty().Spans()
ss.EnsureCapacity(1)
fillSpanOne(ss.AppendEmpty())
return td
}

func fillSpanOne(span ptrace.Span) {
span.SetName("operationA")
span.SetStartTimestamp(spanStartTimestamp)
span.SetEndTimestamp(spanEndTimestamp)
span.SetDroppedAttributesCount(1)
span.SetTraceID([16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})
span.SetSpanID([8]byte{0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18})
evs := span.Events()
ev0 := evs.AppendEmpty()
ev0.SetTimestamp(spanEventTimestamp)
ev0.SetName("event-with-attr")
ev0.Attributes().PutStr("span-event-attr", "span-event-attr-val")
ev0.SetDroppedAttributesCount(2)
ev1 := evs.AppendEmpty()
ev1.SetTimestamp(spanEventTimestamp)
ev1.SetName("event")
ev1.SetDroppedAttributesCount(2)
span.SetDroppedEventsCount(1)
status := span.Status()
status.SetCode(ptrace.StatusCodeError)
status.SetMessage("status-cancelled")
}

func TestContainerTags(t *testing.T) {
factory := NewFactory()

creationParams := connectortest.NewNopCreateSettings()
cfg := factory.CreateDefaultConfig().(*Config)
cfg.Traces.ResourceAttributesAsContainerTags = []string{semconv.AttributeCloudAvailabilityZone, semconv.AttributeCloudRegion}
metricsSink := &consumertest.MetricsSink{}

traceToMetricsConnector, err := factory.CreateTracesToMetrics(context.Background(), creationParams, cfg, metricsSink)
assert.NoError(t, err)

connector, ok := traceToMetricsConnector.(*traceToMetricConnector)
err = connector.Start(context.Background(), componenttest.NewNopHost())
if err != nil {
t.Errorf("Error starting connector: %v", err)
return
}
defer func() {
_ = connector.Shutdown(context.Background())
}()

assert.True(t, ok) // checks if the created connector implements the connectorImp struct
trace1 := generateTrace()

err = connector.ConsumeTraces(context.Background(), trace1)
assert.NoError(t, err)

// Send two traces to ensure unique container tags are added to the cache
trace2 := generateTrace()
err = connector.ConsumeTraces(context.Background(), trace2)
assert.NoError(t, err)
// check if the container tags are added to the cache
assert.Equal(t, 1, len(connector.containerTagCache.Items()))
assert.Equal(t, 2, len(connector.containerTagCache.Items()["my-container-id"].Object.(map[string]struct{})))

for {
if len(metricsSink.AllMetrics()) > 0 {
break
}
time.Sleep(100 * time.Millisecond)
}

// check if the container tags are added to the metrics
metrics := metricsSink.AllMetrics()
assert.Equal(t, 1, len(metrics))

ch := make(chan []byte, 100)
tr := newTranslatorWithStatsChannel(t, zap.NewNop(), ch)
_, err = tr.MapMetrics(context.Background(), metrics[0], nil)
require.NoError(t, err)
msg := <-ch
sp := &pb.StatsPayload{}

err = proto.Unmarshal(msg, sp)
require.NoError(t, err)

tags := sp.Stats[0].Tags
assert.Equal(t, 2, len(tags))
assert.ElementsMatch(t, []string{"region:my-region", "zone:my-zone"}, tags)
}

func newTranslatorWithStatsChannel(t *testing.T, logger *zap.Logger, ch chan []byte) *otlpmetrics.Translator {
options := []otlpmetrics.TranslatorOption{
otlpmetrics.WithHistogramMode(otlpmetrics.HistogramModeDistributions),

otlpmetrics.WithNumberMode(otlpmetrics.NumberModeCumulativeToDelta),
otlpmetrics.WithHistogramAggregations(),
otlpmetrics.WithStatsOut(ch),
}

set := componenttest.NewNopTelemetrySettings()
set.Logger = logger

attributesTranslator, err := attributes.NewTranslator(set)
require.NoError(t, err)
tr, err := otlpmetrics.NewTranslator(
set,
attributesTranslator,
options...,
)

require.NoError(t, err)
return tr
}
Loading

0 comments on commit da2043b

Please sign in to comment.