Skip to content

Commit

Permalink
fix(impl): Support custom span creation in Processor
Browse files Browse the repository at this point in the history
Probably a very narrow use case.
But it could happen.
Along the way of a [recent PR](#109) by @nreant1A trying to make sure:

1. Baggage is properly propagated
2. Custom span creationg is supported in process method

First added 1 QuarkusTest in impl.

The implementation was:

1. extracting the parent context (but not making it current, by which baggage were lost)
2. creating a "process" span and making that a current span
3. early on reinjecting the new span context ids in the message before it starts being processed, relying on the fact that output message are created by modification of the incoming one: `ping.withValue(...)`

The issue we have: baggage cannot be modified in the processor, and any other context modification in the processor is basically ignored (creating a custom span for instance).

Solution: move the injection of the contextual data (traceparent, tracestate, baggage) at message production by implementing a TracingProducerInterceptor.

The OpenTelemetryExtension for JUnit 5 has bean copy pasted so we can inject the W3CBaggagePropagator.
Indeed the original class is final, with private constructor.
A fix upstream will be done shortly.
  • Loading branch information
edeweerd1A committed Oct 11, 2024
1 parent 50cb5f9 commit a8591ce
Show file tree
Hide file tree
Showing 8 changed files with 689 additions and 82 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*-
* #%L
* Quarkus Kafka Streams Processor
* %%
* Copyright (C) 2024 Amadeus s.a.s.
* %%
* Licensed 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.
* #L%
*/
package io.quarkiverse.kafkastreamsprocessor.api.decorator.producer;

/**
* Priorities of the producer interceptors the framework provides.
*/
public final class ProducerInterceptorPriorities {
/**
* Priority of the interceptor that will inject the tracing headers for propagation.
*/
public static final int TRACING = 100;

private ProducerInterceptorPriorities() {

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
import com.google.protobuf.util.JsonFormat;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.trace.StatusCode;
Expand All @@ -58,7 +57,6 @@
import io.quarkiverse.kafkastreamsprocessor.impl.configuration.TopologyConfigurationImpl;
import io.quarkiverse.kafkastreamsprocessor.impl.protocol.KafkaStreamsProcessorHeaders;
import io.quarkiverse.kafkastreamsprocessor.propagation.KafkaTextMapGetter;
import io.quarkiverse.kafkastreamsprocessor.propagation.KafkaTextMapSetter;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -92,11 +90,6 @@ public class TracingDecorator<KIn, VIn, KOut, VOut> implements Processor<KIn, VI
*/
private final KafkaTextMapGetter textMapGetter;

/**
* Injects Context in the Kafka headers of a message
*/
private final KafkaTextMapSetter textMapSetter;

/**
* The tracer instance to create spans
*/
Expand Down Expand Up @@ -126,19 +119,15 @@ public class TracingDecorator<KIn, VIn, KOut, VOut> implements Processor<KIn, VI
* The {@link OpenTelemetry} configured by Quarkus
* @param textMapGetter
* Extracts Context from the Kafka headers of a message
* @param textMapSetter
* Injects Context in the Kafka headers of a message
* @param tracer
* The tracer instance to create spans
* @param configuration
* The TopologyConfiguration after customization.
*/
@Inject
public TracingDecorator(@Delegate Processor<KIn, VIn, KOut, VOut> delegate, OpenTelemetry openTelemetry,
KafkaTextMapGetter textMapGetter, KafkaTextMapSetter textMapSetter, Tracer tracer,
TopologyConfigurationImpl configuration) {
this(delegate, openTelemetry, textMapGetter, textMapSetter, tracer,
configuration.getProcessorPayloadType().getName(),
KafkaTextMapGetter textMapGetter, Tracer tracer, TopologyConfigurationImpl configuration) {
this(delegate, openTelemetry, textMapGetter, tracer, configuration.getProcessorPayloadType().getName(),
JsonFormat.printer());
}

Expand Down Expand Up @@ -167,52 +156,55 @@ public void init(final ProcessorContext<KOut, VOut> context) {
public void process(Record<KIn, VIn> record) {
SpanBuilder spanBuilder = tracer.spanBuilder(applicationName);
final TextMapPropagator propagator = openTelemetry.getPropagators().getTextMapPropagator();

// going through all propagation field names defined in the OTel configuration
// we look if any of them has been set with a non-null value in the headers of the incoming message
Context extractedContext = null;
if (propagator.fields()
.stream()
.map(record.headers()::lastHeader)
.anyMatch(Objects::nonNull)) {
// if that is the case, let's extract a Context initialized with the parent trace id, span id
// and baggage present as headers in the incoming message
extractedContext = propagator.extract(Context.current(), record.headers(), textMapGetter);
// use the context as parent span for the built span
spanBuilder.setParent(extractedContext);
// we clean the headers to avoid their propagation in any outgoing message (knowing that by
// default Kafka Streams copies all headers of the incoming message into any outgoing message)
propagator.fields().forEach(record.headers()::remove);
}
Span span = spanBuilder.startSpan();
// baggage need to be explicitly set as current otherwise it is not propagated (baggage is independent of span
// in opentelemetry) and actually lost as kafka headers are cleaned
try (Scope ignored = (extractedContext != null) ? Baggage.fromContext(extractedContext).makeCurrent() : Scope.noop();
Scope scope = span.makeCurrent()) {
try {
// now that the context has been set to the new started child span of this microservice, we replace
// the headers in the incoming message so when an outgoing message is produced with the copied
// header values it already has the span id from this new child span
propagator.inject(Context.current(), record.headers(), textMapSetter);
delegate.process(record);
span.setStatus(StatusCode.OK);
} catch (KafkaException e) {
// we got a Kafka exception, we record the exception in the span, log but rethrow the exception
// with the idea that it will be caught by one of the DLQ in error management
span.recordException(e);
span.setStatus(StatusCode.ERROR, e.getMessage());
logInputMessageMetadata(record);
throw e;
} catch (RuntimeException e) { // NOSONAR
// very last resort, even the DLQs are not working, then we still record the exception and
// log the message but do not rethrow the exception otherwise we'd end up in an infinite loop
log.error("Runtime error caught while processing the message", e);
span.recordException(e);
span.setStatus(StatusCode.ERROR, e.getMessage());
logInputMessageMetadata(record);
Scope parentScope = null;

try {
// going through all propagation field names defined in the OTel configuration
// we look if any of them has been set with a non-null value in the headers of the incoming message
if (propagator.fields()
.stream()
.map(record.headers()::lastHeader)
.anyMatch(Objects::nonNull)) {
// if that is the case, let's extract a Context initialized with the parent trace id, span id
// and baggage present as headers in the incoming message
Context extractedContext = propagator.extract(Context.current(), record.headers(), textMapGetter);
// use the context as parent span for the built span
spanBuilder.setParent(extractedContext);
// we clean the headers to avoid their propagation in any outgoing message (knowing that by
// default Kafka Streams copies all headers of the incoming message into any outgoing message)
propagator.fields().forEach(record.headers()::remove);
// we make the parent context current to not loose the baggage
parentScope = extractedContext.makeCurrent();
}
Span span = spanBuilder.startSpan();
// baggage need to be explicitly set as current otherwise it is not propagated (baggage is independent of span
// in opentelemetry) and actually lost as kafka headers are cleaned
try (Scope ignored = span.makeCurrent()) {
try {
delegate.process(record);
span.setStatus(StatusCode.OK);
} catch (KafkaException e) {
// we got a Kafka exception, we record the exception in the span, log but rethrow the exception
// with the idea that it will be caught by one of the DLQ in error management
span.recordException(e);
span.setStatus(StatusCode.ERROR, e.getMessage());
logInputMessageMetadata(record);
throw e;
} catch (RuntimeException e) { // NOSONAR
// very last resort, even the DLQs are not working, then we still record the exception and
// log the message but do not rethrow the exception otherwise we'd end up in an infinite loop
log.error("Runtime error caught while processing the message", e);
span.recordException(e);
span.setStatus(StatusCode.ERROR, e.getMessage());
logInputMessageMetadata(record);
}
} finally {
span.end();
}
} finally {
span.end();
if (parentScope != null) {
parentScope.close();
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*-
* #%L
* Quarkus Kafka Streams Processor
* %%
* Copyright (C) 2024 Amadeus s.a.s.
* %%
* Licensed 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.
* #L%
*/
package io.quarkiverse.kafkastreamsprocessor.impl.decorator.producer;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

import org.apache.kafka.clients.producer.ProducerRecord;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.context.Context;
import io.quarkiverse.kafkastreamsprocessor.api.decorator.producer.ProducerInterceptorPriorities;
import io.quarkiverse.kafkastreamsprocessor.api.decorator.producer.ProducerOnSendInterceptor;
import io.quarkiverse.kafkastreamsprocessor.propagation.KafkaTextMapSetter;

/**
* Producer interceptor that injects the tracing headers for propagation.
*/
@ApplicationScoped
public class TracingProducerInterceptor implements ProducerOnSendInterceptor {
private final OpenTelemetry openTelemetry;

private final KafkaTextMapSetter kafkaTextMapSetter;

@Inject
public TracingProducerInterceptor(OpenTelemetry openTelemetry, KafkaTextMapSetter kafkaTextMapSetter) {
this.openTelemetry = openTelemetry;
this.kafkaTextMapSetter = kafkaTextMapSetter;
}

@Override
public ProducerRecord<byte[], byte[]> onSend(ProducerRecord<byte[], byte[]> record) {
openTelemetry.getPropagators().getTextMapPropagator().fields().forEach(record.headers()::remove);
openTelemetry.getPropagators()
.getTextMapPropagator()
.inject(Context.current(), record.headers(), kafkaTextMapSetter);
return record;
}

@Override
public int priority() {
return ProducerInterceptorPriorities.TRACING;
}
}
Loading

0 comments on commit a8591ce

Please sign in to comment.