diff --git a/CHANGELOG.md b/CHANGELOG.md index 236007a7b669..5991dd6cc834 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Main (unreleased) +- [ENHANCEMENT] Traces: Improved pod association in PromSD processor (@mapno) + # v0.21.1 (2021-11-18) - [BUGFIX] Fix panic when using postgres_exporter integration (@saputradharma) diff --git a/docs/configuration/traces-config.md b/docs/configuration/traces-config.md index a1851e9b1603..fb26dd90c180 100644 --- a/docs/configuration/traces-config.md +++ b/docs/configuration/traces-config.md @@ -145,6 +145,26 @@ scrape_configs: # `update` only modifies an existing k/v and `insert` only appends if the k/v # is not present. `upsert` does both. [ prom_sd_operation_type: | default = "upsert" ] +# Configures what methods to use to do association between spans and pods. +# PromSD processor matches the IP address of the metadata labels from the k8s API +# with the IP address obtained from the specified pod association method. +# If a match is found then the span is labeled. +# +# Options are `ip`, `net.host.ip`, `k8s.pod.ip`, `hostname` and `connection`. +# - `ip`, `net.host.ip` and `k8s.pod.ip`, `hostname` match spans tags. +# - `connection` inspects the context from the incoming requests (gRPC and HTTP). +# +# Tracing instrumentation is commonly the responsible for tagging spans +# with IP address to the labels mentioned above. +# If running on kubernetes, `k8s.pod.ip` can be automatically attached via the +# downward API. For example, if you're using OTel instrumentation libraries, set +# OTEL_RESOURCE_ATTRIBUTES=k8s.pod.ip=$(POD_IP) to inject spans with the sender +# pod's IP. +# +# By default, all methods are enabled, and evaluated in the order specified above. +# Order of evaluation is honored when multiple methods are enabled. +prom_sd_pod_association: + - [ ... ] # spanmetrics supports aggregating Request, Error and Duration (R.E.D) metrics # from span data. diff --git a/pkg/traces/config.go b/pkg/traces/config.go index ca097c1b3644..dcf6e739ddc4 100644 --- a/pkg/traces/config.go +++ b/pkg/traces/config.go @@ -110,8 +110,9 @@ type InstanceConfig struct { Attributes map[string]interface{} `yaml:"attributes,omitempty"` // prom service discovery config - ScrapeConfigs []interface{} `yaml:"scrape_configs,omitempty"` - OperationType string `yaml:"prom_sd_operation_type,omitempty"` + ScrapeConfigs []interface{} `yaml:"scrape_configs,omitempty"` + OperationType string `yaml:"prom_sd_operation_type,omitempty"` + PodAssociations []string `yaml:"prom_sd_pod_associations,omitempty"` // SpanMetricsProcessor: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/spanmetricsprocessor/README.md SpanMetrics *SpanMetricsConfig `yaml:"spanmetrics,omitempty"` @@ -402,8 +403,9 @@ func (c *InstanceConfig) otelConfig() (*config.Config, error) { } processorNames = append(processorNames, promsdprocessor.TypeStr) processors[promsdprocessor.TypeStr] = map[string]interface{}{ - "scrape_configs": c.ScrapeConfigs, - "operation_type": opType, + "scrape_configs": c.ScrapeConfigs, + "operation_type": opType, + "pod_associations": c.PodAssociations, } } diff --git a/pkg/traces/promsdprocessor/factory.go b/pkg/traces/promsdprocessor/factory.go index 74ab46c9f1ca..5a859bcaaf5d 100644 --- a/pkg/traces/promsdprocessor/factory.go +++ b/pkg/traces/promsdprocessor/factory.go @@ -22,6 +22,12 @@ const ( OperationTypeUpdate = "update" // OperationTypeUpsert does both of above OperationTypeUpsert = "upsert" + + podAssociationIPLabel = "ip" + podAssociationOTelIPLabel = "net.host.ip" + podAssociationk8sIPLabel = "k8s.pod.ip" + podAssociationHostnameLabel = "hostname" + podAssociationConnectionIP = "connection" ) // Config holds the configuration for the Prometheus SD processor. @@ -29,6 +35,7 @@ type Config struct { config.ProcessorSettings `mapstructure:",squash"` ScrapeConfigs []interface{} `mapstructure:"scrape_configs"` OperationType string `mapstructure:"operation_type"` + PodAssociations []string `mapstructure:"pod_associations"` } // NewFactory returns a new factory for the Attributes processor. @@ -65,5 +72,5 @@ func createTraceProcessor( return nil, fmt.Errorf("unable to unmarshal bytes to []*config.ScrapeConfig: %w", err) } - return newTraceProcessor(nextConsumer, oCfg.OperationType, scrapeConfigs) + return newTraceProcessor(nextConsumer, oCfg.OperationType, oCfg.PodAssociations, scrapeConfigs) } diff --git a/pkg/traces/promsdprocessor/prom_sd_processor.go b/pkg/traces/promsdprocessor/prom_sd_processor.go index d60e11784aea..8d0b995b68a9 100644 --- a/pkg/traces/promsdprocessor/prom_sd_processor.go +++ b/pkg/traces/promsdprocessor/prom_sd_processor.go @@ -16,6 +16,7 @@ import ( "github.com/prometheus/prometheus/discovery/targetgroup" "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/pkg/relabel" + "go.opentelemetry.io/collector/client" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/component/componenterror" "go.opentelemetry.io/collector/consumer" @@ -33,12 +34,13 @@ type promServiceDiscoProcessor struct { hostLabels map[string]model.LabelSet mtx sync.Mutex - operationType string + operationType string + podAssociations []string logger log.Logger } -func newTraceProcessor(nextConsumer consumer.Traces, operationType string, scrapeConfigs []*config.ScrapeConfig) (component.TracesProcessor, error) { +func newTraceProcessor(nextConsumer consumer.Traces, operationType string, podAssociations []string, scrapeConfigs []*config.ScrapeConfig) (component.TracesProcessor, error) { ctx, cancel := context.WithCancel(context.Background()) logger := log.With(util.Logger, "component", "traces service disco") @@ -66,6 +68,19 @@ func newTraceProcessor(nextConsumer consumer.Traces, operationType string, scrap return nil, fmt.Errorf("unknown operation type %s", operationType) } + for _, podAssociation := range podAssociations { + switch podAssociation { + case podAssociationIPLabel, podAssociationOTelIPLabel, podAssociationk8sIPLabel, podAssociationHostnameLabel, podAssociationConnectionIP: + default: + cancel() + return nil, fmt.Errorf("unknown pod association %s", podAssociation) + } + } + + if len(podAssociations) == 0 { + podAssociations = []string{podAssociationIPLabel, podAssociationOTelIPLabel, podAssociationk8sIPLabel, podAssociationHostnameLabel, podAssociationConnectionIP} + } + if nextConsumer == nil { cancel() return nil, componenterror.ErrNilNextConsumer @@ -79,6 +94,7 @@ func newTraceProcessor(nextConsumer consumer.Traces, operationType string, scrap hostLabels: make(map[string]model.LabelSet), logger: logger, operationType: operationType, + podAssociations: podAssociations, }, nil } @@ -87,30 +103,53 @@ func (p *promServiceDiscoProcessor) ConsumeTraces(ctx context.Context, td pdata. for i := 0; i < rss.Len(); i++ { rs := rss.At(i) - p.processAttributes(rs.Resource().Attributes()) + p.processAttributes(ctx, rs.Resource().Attributes()) } return p.nextConsumer.ConsumeTraces(ctx, td) } -func (p *promServiceDiscoProcessor) processAttributes(attrs pdata.AttributeMap) { - // find the ip - ipTagNames := []string{ - "ip", // jaeger/opentracing? default - semconv.AttributeNetHostIP, // otel semantics for host ip +func stringAttributeFromMap(attrs pdata.AttributeMap, key string) string { + if attr, ok := attrs.Get(key); ok { + if attr.Type() == pdata.AttributeValueTypeString { + return attr.StringVal() + } } + return "" +} - var ip string - for _, name := range ipTagNames { - val, ok := attrs.Get(name) - if !ok { - continue - } +func getConnectionIP(ctx context.Context) string { + if c, ok := client.FromContext(ctx); ok { + return c.IP + } + return "" +} - ip = val.StringVal() - break +func (p *promServiceDiscoProcessor) getPodIP(ctx context.Context, attrs pdata.AttributeMap) string { + for _, podAssociation := range p.podAssociations { + switch podAssociation { + case podAssociationIPLabel, podAssociationOTelIPLabel, podAssociationk8sIPLabel: + ip := stringAttributeFromMap(attrs, podAssociation) + if ip != "" { + return ip + } + case podAssociationHostnameLabel: + hostname := stringAttributeFromMap(attrs, semconv.AttributeHostName) + if net.ParseIP(hostname) != nil { + return hostname + } + case podAssociationConnectionIP: + ip := getConnectionIP(ctx) + if ip != "" { + return ip + } + } } + return "" +} +func (p *promServiceDiscoProcessor) processAttributes(ctx context.Context, attrs pdata.AttributeMap) { + ip := p.getPodIP(ctx, attrs) // have to have an ip for labels lookup if ip == "" { level.Debug(p.logger).Log("msg", "unable to find ip in span attributes, skipping attribute addition") diff --git a/pkg/traces/promsdprocessor/prom_sd_processor_test.go b/pkg/traces/promsdprocessor/prom_sd_processor_test.go index 40debbebf550..c6aebb0d7c5b 100644 --- a/pkg/traces/promsdprocessor/prom_sd_processor_test.go +++ b/pkg/traces/promsdprocessor/prom_sd_processor_test.go @@ -1,6 +1,9 @@ package promsdprocessor import ( + "context" + "net" + "net/http" "testing" "github.com/go-kit/log" @@ -9,9 +12,11 @@ import ( "github.com/prometheus/prometheus/pkg/relabel" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.opentelemetry.io/collector/client" "go.opentelemetry.io/collector/consumer/consumertest" "go.opentelemetry.io/collector/model/pdata" semconv "go.opentelemetry.io/collector/model/semconv/v1.6.1" + "google.golang.org/grpc/peer" ) func TestSyncGroups(t *testing.T) { @@ -178,7 +183,7 @@ func TestOperationType(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { mockProcessor := new(consumertest.TracesSink) - p, err := newTraceProcessor(mockProcessor, tc.operationType, nil) + p, err := newTraceProcessor(mockProcessor, tc.operationType, nil, nil) require.NoError(t, err) attrValue := pdata.NewAttributeValueString("old-value") @@ -196,10 +201,150 @@ func TestOperationType(t *testing.T) { }, } p.(*promServiceDiscoProcessor).hostLabels = hostLabels - p.(*promServiceDiscoProcessor).processAttributes(attrMap) + p.(*promServiceDiscoProcessor).processAttributes(context.TODO(), attrMap) actualAttrValue, _ := attrMap.Get(attrKey) assert.Equal(t, tc.expectedValue, actualAttrValue.StringVal()) }) } } + +func TestPodAssociation(t *testing.T) { + const ipStr = "1.1.1.1" + + testCases := []struct { + name string + podAssociations []string + ctxFn func(t *testing.T) context.Context + attrMapFn func(t *testing.T) pdata.AttributeMap + expectedIP string + }{ + { + name: "HTTP connection IP", + ctxFn: func(t *testing.T) context.Context { + r := &http.Request{RemoteAddr: ipStr} + c, ok := client.FromHTTP(r) + require.True(t, ok) + return client.NewContext(context.Background(), c) + }, + attrMapFn: func(*testing.T) pdata.AttributeMap { return pdata.NewAttributeMap() }, + expectedIP: ipStr, + }, + { + name: "gRPC connection IP", + ctxFn: func(t *testing.T) context.Context { + grpcCtx := peer.NewContext(context.Background(), &peer.Peer{ + Addr: &net.TCPAddr{ + IP: net.ParseIP(ipStr), + Port: 80, + }, + }) + c, ok := client.FromGRPC(grpcCtx) + require.True(t, ok) + return client.NewContext(context.Background(), c) + }, + attrMapFn: func(*testing.T) pdata.AttributeMap { return pdata.NewAttributeMap() }, + expectedIP: ipStr, + }, + { + name: "ip attribute", + ctxFn: func(t *testing.T) context.Context { return context.Background() }, + attrMapFn: func(*testing.T) pdata.AttributeMap { + attrMap := pdata.NewAttributeMap() + attrMap.Insert("ip", pdata.NewAttributeValueString(ipStr)) + return attrMap + }, + expectedIP: ipStr, + }, + { + name: "net.host.ip attribute", + ctxFn: func(t *testing.T) context.Context { return context.Background() }, + attrMapFn: func(*testing.T) pdata.AttributeMap { + attrMap := pdata.NewAttributeMap() + attrMap.Insert(semconv.AttributeNetHostIP, pdata.NewAttributeValueString(ipStr)) + return attrMap + }, + expectedIP: ipStr, + }, + { + name: "k8s ip attribute", + ctxFn: func(t *testing.T) context.Context { return context.Background() }, + attrMapFn: func(*testing.T) pdata.AttributeMap { + attrMap := pdata.NewAttributeMap() + attrMap.Insert("k8s.pod.ip", pdata.NewAttributeValueString(ipStr)) + return attrMap + }, + expectedIP: ipStr, + }, + { + name: "ip from hostname", + ctxFn: func(t *testing.T) context.Context { return context.Background() }, + attrMapFn: func(*testing.T) pdata.AttributeMap { + attrMap := pdata.NewAttributeMap() + attrMap.Insert(semconv.AttributeHostName, pdata.NewAttributeValueString(ipStr)) + return attrMap + }, + expectedIP: ipStr, + }, + { + name: "uses attr before context (default associations)", + ctxFn: func(t *testing.T) context.Context { + r := &http.Request{RemoteAddr: "2.2.2.2"} + c, ok := client.FromHTTP(r) + require.True(t, ok) + return client.NewContext(context.Background(), c) + }, + attrMapFn: func(*testing.T) pdata.AttributeMap { + attrMap := pdata.NewAttributeMap() + attrMap.Insert(semconv.AttributeNetHostIP, pdata.NewAttributeValueString(ipStr)) + return attrMap + }, + expectedIP: ipStr, + }, + { + name: "uses attr before hostname (default associations)", + ctxFn: func(t *testing.T) context.Context { return context.Background() }, + attrMapFn: func(*testing.T) pdata.AttributeMap { + attrMap := pdata.NewAttributeMap() + attrMap.Insert(semconv.AttributeNetHostIP, pdata.NewAttributeValueString(ipStr)) + attrMap.Insert(semconv.AttributeHostName, pdata.NewAttributeValueString("3.3.3.3")) + return attrMap + }, + expectedIP: ipStr, + }, + { + name: "ip attribute but not as pod association", + podAssociations: []string{podAssociationk8sIPLabel}, + ctxFn: func(t *testing.T) context.Context { return context.Background() }, + attrMapFn: func(*testing.T) pdata.AttributeMap { + attrMap := pdata.NewAttributeMap() + attrMap.Insert("ip", pdata.NewAttributeValueString(ipStr)) + return attrMap + }, + expectedIP: "", + }, + { + name: "uses hostname before attribute (reverse order from default)", + podAssociations: []string{podAssociationHostnameLabel, podAssociationOTelIPLabel}, + ctxFn: func(t *testing.T) context.Context { return context.Background() }, + attrMapFn: func(*testing.T) pdata.AttributeMap { + attrMap := pdata.NewAttributeMap() + attrMap.Insert(semconv.AttributeNetHostIP, pdata.NewAttributeValueString("3.3.3.3")) + attrMap.Insert(semconv.AttributeHostName, pdata.NewAttributeValueString(ipStr)) + return attrMap + }, + expectedIP: ipStr, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + mockProcessor := new(consumertest.TracesSink) + p, err := newTraceProcessor(mockProcessor, "", tc.podAssociations, nil) + require.NoError(t, err) + + ip := p.(*promServiceDiscoProcessor).getPodIP(tc.ctxFn(t), tc.attrMapFn(t)) + assert.Equal(t, tc.expectedIP, ip) + }) + } +}