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

CAMEL-21648: Provide a way to customize OpenTelemetry Span creation #16904

Merged
merged 1 commit into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ public boolean configure(CamelContext camelContext, Object obj, String name, Obj
case "excludePatterns": target.setExcludePatterns(property(camelContext, java.lang.String.class, value)); return true;
case "instrumentationname":
case "instrumentationName": target.setInstrumentationName(property(camelContext, java.lang.String.class, value)); return true;
case "spancustomizer":
case "spanCustomizer": target.setSpanCustomizer(property(camelContext, org.apache.camel.opentelemetry.SpanCustomizer.class, value)); return true;
case "traceprocessors":
case "traceProcessors": target.setTraceProcessors(property(camelContext, boolean.class, value)); return true;
case "tracer": target.setTracer(property(camelContext, io.opentelemetry.api.trace.Tracer.class, value)); return true;
Expand All @@ -53,6 +55,8 @@ public Class<?> getOptionType(String name, boolean ignoreCase) {
case "excludePatterns": return java.lang.String.class;
case "instrumentationname":
case "instrumentationName": return java.lang.String.class;
case "spancustomizer":
case "spanCustomizer": return org.apache.camel.opentelemetry.SpanCustomizer.class;
case "traceprocessors":
case "traceProcessors": return boolean.class;
case "tracer": return io.opentelemetry.api.trace.Tracer.class;
Expand All @@ -75,6 +79,8 @@ public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
case "excludePatterns": return target.getExcludePatterns();
case "instrumentationname":
case "instrumentationName": return target.getInstrumentationName();
case "spancustomizer":
case "spanCustomizer": return target.getSpanCustomizer();
case "traceprocessors":
case "traceProcessors": return target.isTraceProcessors();
case "tracer": return target.getTracer();
Expand Down
29 changes: 29 additions & 0 deletions components/camel-opentelemetry/src/main/docs/opentelemetry.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,32 @@ Multiple `SpanExporters` can be used at the same time.
== MDC Logging

You can add Mapped Diagnostic Context tracing information (ie, `trace_id` and `span_id`) adding the specific https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/docs/logger-mdc-instrumentation.md[Opentelemetry Logger MDC auto instrumentation]. The configuration depends on the logging framework you're using.

== Customizing OpenTelemetry spans

In _rare_ circumstances, it may be desirable to apply advanced customizations to the OpenTelemetry Span generated by the Camel `OpenTelemetryTracer`.

To do this, you can provide a custom implementation of `SpanCustomizer` and either set it explicitly on the `OpenTelemetryTracer`,
or bind it to the Camel registry, where it will be automatically resolved by the tracer upon initialization.

Note that care should be taken when configuring parents & links to avoid breaking the relationship between spans & traces.

[source,java]
----
public class MySpanCustomizer implements SpanCustomizer {
@Override
public void customize(SpanBuilder spanBuilder, String operationName, Exchange exchange) {
spanBuilder.setAttribute("foo", "bar");
spanBuilder.setParent(myCustomParentContext);
spanBuilder.addLink(linkedSpanContext);
// other customizations...
}

// By default, all spans will have customizations applied. You can restrict this by overriding isEnabled
@Override
public boolean isEnabled(String operationName, Exchange exchange) {
String header = exchange.getMessage().getHeader("foo", String.class);
return operationName.equals("my-message-queue") && header.equals("bar");
}
}
----
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public class OpenTelemetryTracer extends org.apache.camel.tracing.Tracer {
private String instrumentationName = "camel";
private ContextPropagators contextPropagators;
private boolean traceProcessors;
private SpanCustomizer spanCustomizer;

public Tracer getTracer() {
return tracer;
Expand Down Expand Up @@ -94,6 +95,17 @@ public void setContextPropagators(ContextPropagators contextPropagators) {
this.contextPropagators = contextPropagators;
}

public SpanCustomizer getSpanCustomizer() {
return spanCustomizer;
}

/**
* Enables the capability to apply customizations to Spans before they are started.
*/
public void setSpanCustomizer(SpanCustomizer spanCustomizer) {
this.spanCustomizer = spanCustomizer;
}

private SpanKind mapToSpanKind(org.apache.camel.tracing.SpanKind kind) {
switch (kind) {
case SPAN_KIND_CLIENT:
Expand Down Expand Up @@ -124,6 +136,9 @@ protected void initTracer() {
tracingStrategy.setPropagateContext(true);
setTracingStrategy(tracingStrategy);
}
if (spanCustomizer == null) {
spanCustomizer = CamelContextHelper.findSingleByType(getCamelContext(), SpanCustomizer.class);
}
}

@Override
Expand All @@ -149,6 +164,9 @@ protected SpanAdapter startSendingEventSpan(
baggage = oTelSpanWrapper.getBaggage();
builder = builder.setParent(Context.current().with(parentSpan));
}
if (spanCustomizer != null && spanCustomizer.isEnabled(operationName, exchange)) {
spanCustomizer.customize(builder, operationName, exchange);
}
return new OpenTelemetrySpanAdapter(builder.startSpan(), baggage);
}

Expand All @@ -174,7 +192,9 @@ protected SpanAdapter startExchangeBeginSpan(
builder.setSpanKind(mapToSpanKind(sd.getReceiverSpanKind()));
}
}

if (spanCustomizer != null && spanCustomizer.isEnabled(operationName, exchange)) {
spanCustomizer.customize(builder, operationName, exchange);
}
return new OpenTelemetrySpanAdapter(builder.startSpan(), baggage);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.opentelemetry;

import io.opentelemetry.api.trace.SpanBuilder;
import org.apache.camel.Exchange;

/**
* An abstraction to customize the generation of a {@link io.opentelemetry.api.trace.Span} produced by
* {@link OpenTelemetryTracer}.
*/
public interface SpanCustomizer {
/**
* Applies customizations to Spans created by {@link OpenTelemetryTracer}.
*
* @param spanBuilder The {@link SpanBuilder} instance for customizing the span
* @param operationName The name of the tracing operation
* @param exchange The exchange instance
*/
void customize(SpanBuilder spanBuilder, String operationName, Exchange exchange);

/**
* Determines whether customizations to the {@link io.opentelemetry.api.trace.Span} should be applied. For example,
* if the operation name or some properties of the exchange match specific conditions. By default, customizations
* are applied to all spans.
*
* @param operationName The name of the tracing operation
* @param exchange The exchange instance
* @return {@code true} if customizations should be applied a {@link io.opentelemetry.api.trace.Span},
* else {@code false} if they should not be applied.
*/
default boolean isEnabled(String operationName, Exchange exchange) {
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.apache.camel.spi.InterceptStrategy;
import org.apache.camel.spi.ThreadPoolFactory;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.apache.camel.util.ObjectHelper;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
Expand Down Expand Up @@ -226,6 +227,10 @@ protected void verifySpan(int index, SpanTestData[] testdata, List<SpanData> spa

assertEquals(td.getKind(), span.getKind(), td.getLabel());

if (ObjectHelper.isNotEmpty(td.getTraceId())) {
assertEquals(td.getTraceId(), span.getTraceId());
}

if (!td.getLogMessages().isEmpty()) {
assertEquals(td.getLogMessages().size(), span.getEvents().size(), td.getLabel());
for (int i = 0; i < td.getLogMessages().size(); i++) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.opentelemetry;

import java.util.Arrays;

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.TraceFlags;
import io.opentelemetry.api.trace.TraceState;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.trace.IdGenerator;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class SpanCustomizerTest extends CamelOpenTelemetryTestSupport {
private static final SpanTestData[] TEST_DATA = {
new SpanTestData().setOperation("external-parent"),
new SpanTestData().setUri("seda://next").setOperation("next")
.setParentId(2),
new SpanTestData().setUri("seda://next").setOperation("next")
.setKind(SpanKind.CLIENT)
.setParentId(3),
new SpanTestData().setUri("direct://start").setOperation("start"),
};
private static final String CUSTOM_SPAN_ID = IdGenerator.random().generateSpanId();
private String traceId;

SpanCustomizerTest() {
super(TEST_DATA);
}

@Test
void customizeSpan() {
template.requestBody("direct:start", traceId);
verify();
assertEquals(CUSTOM_SPAN_ID, otelExtension.getSpans().get(3).getParentSpanId());
}

@Override
protected void initTracer(CamelContext context) {
context.getRegistry().bind("spanCustomizer", createSpanCustomizer());
super.initTracer(context);

// Simulate a trace being generated from outside of Camel
// We'll use a SpanCustomizer to use it as the parent for our route spans
Span span = tracer.spanBuilder("external-parent").setAttribute("component", "foo").startSpan();
traceId = span.getSpanContext().getTraceId();
span.end();

Arrays.stream(TEST_DATA).forEach(td -> td.setTraceId(traceId));
}

@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").routeId("start")
.to("seda:next");

from("seda:next")
.log("${body}");
}
};
}

private SpanCustomizer createSpanCustomizer() {
return new SpanCustomizer() {
@Override
public void customize(SpanBuilder spanBuilder, String operationName, Exchange exchange) {
if (operationName.equals("start") && exchange.getFromRouteId().equals("start")) {
// Use a custom trace id for propagation to all spans generated from direct:start routing
String traceId = exchange.getMessage().getBody(String.class);
SpanContext spanContext = SpanContext.create(traceId,
CUSTOM_SPAN_ID,
TraceFlags.getSampled(),
TraceState.getDefault());

spanBuilder.setParent(Context.current().with(Span.wrap(spanContext)));
}
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public class SpanTestData {
private String uri;
private String operation;
private SpanKind kind = SpanKind.INTERNAL;
private String traceId;
private int parentId = -1;
private final List<String> logMessages = new ArrayList<>();
private final Map<String, String> tags = new HashMap<>();
Expand Down Expand Up @@ -72,6 +73,15 @@ public SpanTestData setKind(SpanKind kind) {
return this;
}

public String getTraceId() {
return traceId;
}

public SpanTestData setTraceId(String traceId) {
this.traceId = traceId;
return this;
}

public int getParentId() {
return parentId;
}
Expand Down
Loading