Skip to content
This repository was archived by the owner on Jul 28, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Main (unreleased)

- [ENHANCEMENT] Traces: Improved pod association in PromSD processor (@mapno)
Comment thread
mapno marked this conversation as resolved.
Resolved

# v0.21.1 (2021-11-18)

- [BUGFIX] Fix panic when using postgres_exporter integration (@saputradharma)
Expand Down
20 changes: 20 additions & 0 deletions docs/configuration/traces-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <string> | 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`.
Comment thread
annanay25 marked this conversation as resolved.
Resolved
# - `ip`, `net.host.ip` and `k8s.pod.ip`, `hostname` match spans tags.
# - `connection` inspects the context from the incoming requests (gRPC and HTTP).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The connection association can be elaborated a bit in the docs. Its not obvious that it will look at the RemoteAddr in the requests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It also uses a different method to inspect the IP in gRPC. Is it worth mentioning? It's something that is done automatically. The user won't have access to this code.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yeah its fine to just mention.

#
# 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't k8s.pod.ip have precedence over ip?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Maybe? I don't know.k8s.pod.ip is a new tag for us, so I'm not familiar with it.

The current order is based on the previous implementation. I thought it'd be better to make it a non-op if relabelling was already working for someone with ip or net.host.ip.

I'm happy to change the ordering to whatever is more common and useful to users though (if that's k8s.pod.ip).

# Order of evaluation is honored when multiple methods are enabled.
prom_sd_pod_association:
- [ <string>... ]

# spanmetrics supports aggregating Request, Error and Duration (R.E.D) metrics
# from span data.
Expand Down
10 changes: 6 additions & 4 deletions pkg/traces/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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,
}
}

Expand Down
9 changes: 8 additions & 1 deletion pkg/traces/promsdprocessor/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,20 @@ 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.
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.
Expand Down Expand Up @@ -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)
}
76 changes: 60 additions & 16 deletions pkg/traces/promsdprocessor/prom_sd_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,19 @@ 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"
"go.opentelemetry.io/collector/model/pdata"
semconv "go.opentelemetry.io/collector/model/semconv/v1.6.1"
)

const (
ipTagName = "ip"
k8sIPTagName = "k8s.pod.ip"
)
Comment thread
mapno marked this conversation as resolved.
Resolved

type promServiceDiscoProcessor struct {
nextConsumer consumer.Traces
discoveryMgr *discovery.Manager
Expand All @@ -33,12 +39,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")
Expand Down Expand Up @@ -66,6 +73,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
Expand All @@ -79,6 +99,7 @@ func newTraceProcessor(nextConsumer consumer.Traces, operationType string, scrap
hostLabels: make(map[string]model.LabelSet),
logger: logger,
operationType: operationType,
podAssociations: podAssociations,
}, nil
}

Expand All @@ -87,30 +108,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")
Expand Down
Loading