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

Add container tags #31642

Merged
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: []
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"`
dineshg13 marked this conversation as resolved.
Show resolved Hide resolved
}

// Validate the configuration for errors. This is required by component.Config.
Expand Down
73 changes: 67 additions & 6 deletions connector/datadogconnector/connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import (
"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 +38,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 @@ -60,14 +65,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))
dineshg13 marked this conversation as resolved.
Show resolved Hide resolved
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(cache.DefaultExpiration, cache.DefaultExpiration),
songy23 marked this conversation as resolved.
Show resolved Hide resolved
exit: make(chan struct{}),
}, nil
}

Expand All @@ -80,6 +93,9 @@ 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{}{}
Copy link

Choose a reason for hiding this comment

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

👍

songy23 marked this conversation as resolved.
Show resolved Hide resolved
}
if v := cfg.TraceBuffer; v > 0 {
acfg.TraceBuffer = v
}
Expand Down Expand Up @@ -112,6 +128,31 @@ func (c *traceToMetricConnector) Capabilities() consumer.Capabilities {
}

func (c *traceToMetricConnector) ConsumeTraces(ctx context.Context, traces ptrace.Traces) error {
if len(c.resourceAttrs) > 0 {
dineshg13 marked this conversation as resolved.
Show resolved Hide resolved
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{}{}
dineshg13 marked this conversation as resolved.
Show resolved Hide resolved
songy23 marked this conversation as resolved.
Show resolved Hide resolved
} else {
cacheVal = make(map[string]struct{})
cacheVal[fmt.Sprintf("%s:%s", attr, val)] = struct{}{}
c.containerTagCache.Set(containerID.AsString(), cacheVal, cache.DefaultExpiration)
}

}
}
}
}
c.agent.Ingest(ctx, traces)
return nil
}
Expand All @@ -128,7 +169,27 @@ func (c *traceToMetricConnector) run() {
}
var mx pmetric.Metrics
var err error
// Enrich the stats with container tags
dineshg13 marked this conversation as resolved.
Show resolved Hide resolved
if len(c.resourceAttrs) > 0 {
for _, stat := range stats.Stats {
if stat.ContainerID != "" {
if tags, ok := c.containerTagCache.Get(stat.ContainerID); ok {
tagList := tags.(map[string]struct{})
// Add unique tags to the stats
for _, tag := range stat.Tags {
songy23 marked this conversation as resolved.
Show resolved Hide resolved
tagList[tag] = struct{}{}
}
stat.Tags = make([]string, 0, len(tagList))
for tag := range tagList {
stat.Tags = append(stat.Tags, tag)
}
}
}
}
}

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