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

fix(impl): Support custom span creation in Processor #124

Open
wants to merge 1 commit into
base: quarkus-3.8
Choose a base branch
from
Open
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
@@ -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 @@ -59,7 +58,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.extern.slf4j.Slf4j;

/**
Expand All @@ -85,11 +83,6 @@ public class TracingDecorator extends AbstractProcessorDecorator {
*/
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 @@ -117,27 +110,22 @@ public class TracingDecorator extends AbstractProcessorDecorator {
* 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(OpenTelemetry openTelemetry,
KafkaTextMapGetter textMapGetter, KafkaTextMapSetter textMapSetter, Tracer tracer,
public TracingDecorator(OpenTelemetry openTelemetry, KafkaTextMapGetter textMapGetter, Tracer tracer,
TopologyConfigurationImpl configuration) {
this(openTelemetry, textMapGetter, textMapSetter, tracer,
configuration.getProcessorPayloadType().getName(),
this(openTelemetry, textMapGetter, tracer, configuration.getProcessorPayloadType().getName(),
JsonFormat.printer());
}

public TracingDecorator(OpenTelemetry openTelemetry, KafkaTextMapGetter textMapGetter, KafkaTextMapSetter textMapSetter,
public TracingDecorator(OpenTelemetry openTelemetry, KafkaTextMapGetter textMapGetter,
Tracer tracer, String applicationName, JsonFormat.Printer jsonPrinter) {
this.openTelemetry = openTelemetry;
this.textMapGetter = textMapGetter;
this.textMapSetter = textMapSetter;
this.tracer = tracer;
this.applicationName = applicationName;
this.jsonPrinter = jsonPrinter;
Expand Down Expand Up @@ -168,52 +156,55 @@ public void init(final ProcessorContext context) {
public void process(Record 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);
getDelegate().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 {
getDelegate().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
Loading