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"`
}

// Validate the configuration for errors. This is required by component.Config.
Expand Down
82 changes: 76 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 @@ -46,6 +52,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 @@ -60,14 +73,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 @@ -80,6 +101,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{}{}
Copy link

Choose a reason for hiding this comment

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

👍

delete(acfg.Features, "disable_cid_stats")
}
if v := cfg.TraceBuffer; v > 0 {
acfg.TraceBuffer = v
}
Expand Down Expand Up @@ -112,6 +137,31 @@ func (c *traceToMetricConnector) Capabilities() consumer.Capabilities {
}

func (c *traceToMetricConnector) ConsumeTraces(ctx context.Context, traces ptrace.Traces) error {
if len(c.resourceAttrs) > 0 {
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)
}

}
}
}
}
c.agent.Ingest(ctx, traces)
return nil
}
Expand All @@ -128,7 +178,27 @@ func (c *traceToMetricConnector) run() {
}
var mx pmetric.Metrics
var err error
// Enrich the stats with container tags
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 {
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
}
6 changes: 3 additions & 3 deletions connector/datadogconnector/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter v0.96.0
github.com/open-telemetry/opentelemetry-collector-contrib/internal/datadog v0.96.0
github.com/open-telemetry/opentelemetry-collector-contrib/processor/tailsamplingprocessor v0.96.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/stretchr/testify v1.9.0
go.opentelemetry.io/collector/component v0.96.1-0.20240315172937-3b5aee0c7a16
go.opentelemetry.io/collector/connector v0.96.1-0.20240315172937-3b5aee0c7a16
Expand All @@ -23,9 +24,11 @@ require (
go.opentelemetry.io/collector/processor/batchprocessor v0.96.1-0.20240315172937-3b5aee0c7a16
go.opentelemetry.io/collector/receiver v0.96.1-0.20240315172937-3b5aee0c7a16
go.opentelemetry.io/collector/receiver/otlpreceiver v0.96.1-0.20240315172937-3b5aee0c7a16
go.opentelemetry.io/collector/semconv v0.96.1-0.20240315172937-3b5aee0c7a16
go.opentelemetry.io/otel/metric v1.24.0
go.opentelemetry.io/otel/trace v1.24.0
go.uber.org/zap v1.27.0
google.golang.org/protobuf v1.33.0
)

require (
Expand Down Expand Up @@ -116,7 +119,6 @@ require (
github.com/openshift/api v3.9.0+incompatible // indirect
github.com/openshift/client-go v0.0.0-20210521082421-73d9475a9142 // indirect
github.com/outcaste-io/ristretto v0.2.1 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/philhofer/fwd v1.1.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
Expand Down Expand Up @@ -158,7 +160,6 @@ require (
go.opentelemetry.io/collector/extension v0.96.1-0.20240315172937-3b5aee0c7a16 // indirect
go.opentelemetry.io/collector/extension/auth v0.96.1-0.20240315172937-3b5aee0c7a16 // indirect
go.opentelemetry.io/collector/featuregate v1.3.1-0.20240315172937-3b5aee0c7a16 // indirect
go.opentelemetry.io/collector/semconv v0.96.1-0.20240315172937-3b5aee0c7a16 // indirect
go.opentelemetry.io/collector/service v0.96.1-0.20240315172937-3b5aee0c7a16 // indirect
go.opentelemetry.io/contrib/config v0.4.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 // indirect
Expand Down Expand Up @@ -193,7 +194,6 @@ require (
google.golang.org/genproto/googleapis/api v0.0.0-20240123012728-ef4313101c80 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240123012728-ef4313101c80 // indirect
google.golang.org/grpc v1.62.1 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down