Skip to content
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 @@ -47,8 +47,6 @@ tasks {
jvmArgs("--add-exports=java.base/sun.security.util=ALL-UNNAMED")
jvmArgs("-XX:+IgnoreUnrecognizedVMOptions")

jvmArgs("-Dio.opentelemetry.javaagent.shaded.io.opentelemetry.context.enableStrictContext=false")

systemProperty("testLatestDeps", findProperty("testLatestDeps") as Boolean)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static class PushAdvice {
public static Scope onEnter(@Advice.Argument(0) GraphInterpreter.Connection connection) {
// processPush is called when execution passes to application or server. Here we propagate the
// context to the application code.
Context context = PekkoFlowWrapper.getContext(connection.outHandler());
Context context = PekkoFlowWrapper.getAndRemoveContext(connection.outHandler());
if (context != null) {
return context.makeCurrent();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.pekkohttp.v1_0.server;

import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.returns;

import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.apache.pekko.http.scaladsl.model.HttpRequest;
import org.apache.pekko.http.scaladsl.model.HttpResponse;
import org.apache.pekko.stream.scaladsl.BidiFlow;

public class HttpServerBluePrintInstrumentation implements TypeInstrumentation {
@Override
public ElementMatcher<TypeDescription> typeMatcher() {
return named("org.apache.pekko.http.impl.engine.server.HttpServerBluePrint$");
}

@Override
public void transform(TypeTransformer transformer) {
transformer.applyAdviceToMethod(
named("requestPreparation")
.and(returns(named("org.apache.pekko.stream.scaladsl.BidiFlow"))),
this.getClass().getName() + "$PekkoBindAndHandleAdvice");
}

@SuppressWarnings("unused")
public static class PekkoBindAndHandleAdvice {

@Advice.AssignReturned.ToReturned
@Advice.OnMethodExit(suppress = Throwable.class)
public static BidiFlow<HttpResponse, ?, ?, HttpRequest, ?> wrapHandler(
@Advice.Return BidiFlow<HttpResponse, ?, ?, HttpRequest, ?> handler) {

return PekkoHttpServerTracer.wrap(handler);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,9 @@

package io.opentelemetry.javaagent.instrumentation.pekkohttp.v1_0.server;

import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;

import io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.bootstrap.http.HttpServerResponseCustomizerHolder;
import io.opentelemetry.javaagent.instrumentation.pekkohttp.v1_0.server.route.PekkoRouteHolder;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import org.apache.pekko.http.javadsl.model.HttpHeader;
import java.util.Queue;
import org.apache.pekko.http.scaladsl.model.HttpRequest;
import org.apache.pekko.http.scaladsl.model.HttpResponse;
import org.apache.pekko.stream.Attributes;
Expand Down Expand Up @@ -42,14 +36,12 @@ public class PekkoFlowWrapper
return handler.join(new PekkoFlowWrapper());
}

public static Context getContext(OutHandler outHandler) {
public static Context getAndRemoveContext(OutHandler outHandler) {
if (outHandler instanceof TracingLogic.ApplicationOutHandler) {
// We have multiple requests here only when requests are pipelined on the same connection.
// It appears that these requests are processed one by one so processing next request won't
// be started before the first one has returned a response, because of this the first request
// in the queue is always the one that is currently being processed.
TracingRequest request =
((TracingLogic.ApplicationOutHandler) outHandler).getRequests().peek();
// We remove the context off of the queue so that the next request can get its context.
PekkoTracingRequest request =
((TracingLogic.ApplicationOutHandler) outHandler).getRequests().poll();
if (request != null) {
return request.context;
}
Expand All @@ -69,7 +61,7 @@ public GraphStageLogic createLogic(Attributes attributes) {
}

private class TracingLogic extends GraphStageLogic {
private final Deque<TracingRequest> requests = new ArrayDeque<>();
private final Queue<PekkoTracingRequest> requests = new ArrayDeque<>();
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Both here and in PekkoHttpServerTracer I'm using a queue (LIFO) because that's what the approach taken in Pekko by the request-timeout stage here.

The previous approach used the Deque as FIFO. Changing it here for consistency.

Copy link
Contributor

Choose a reason for hiding this comment

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

I think the previous usage was a bug since pipelined requests should complete in the oder they are received. Currently with our tests it seems that pekko does not have multiple requests in this queue, probably some extra configuration is needed. If we could figure out how to actually enable pipelining we could consider improving the test.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've enabled the http-pipelining test for the async tests, and managed to get it to work (see the comment on how). Nevertheless switching both deques from LIFO to FIFO has no effect - the tests pass in both cases.

Copy link
Contributor

@laurit laurit Mar 6, 2025

Choose a reason for hiding this comment

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

Thanks for looking at this. If it doesn't break then I'd guess that perhaps there isn't more than 1 request in the queue at the same time. Maybe the requests are processed too fast, idk. I think if there is interest we can tackle this in a follow up PR.
Looking at https://github.com/open-telemetry/opentelemetry-java-instrumentation/pull/13435/files#diff-dc7412c25079c85f7462b02768d4445cda72f0934517132253e0b9140f7d69dcR147-R153 this really isn't a good idea. The scope from makeCurrent must be closed. Leaving the scope open is almost never the best solution as not closing a scope will prevent closing all other scopes that were open for that thread, it could lead to a memory leak or the thread ending in a state where all subsequent spans are added to one trace. If this is just for pipelining I'd suggest you to revert this part for now.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fair enough, I can revert it. This PR didn't break it so yeah a follow up should look into it.

A thought - how bad would it be to use the Context.root() as the parent context when creating the server span? i.e. change this to:

Context parentContext = Context.root();

The tests pass if I do that and remove the tracingRequest.parentContext.makeCurrent() bit, since the previous request's context is ignored when handling the next request.

Copy link
Contributor

Choose a reason for hiding this comment

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

Usually it is better to reset the scope where the unwanted context propagation happens. We usually fail the tests when there are leaked scopes but this is disabled in

jvmArgs("-Dio.opentelemetry.javaagent.shaded.io.opentelemetry.context.enableStrictContext=false")
I think this could be removed as it is carried over from akka instrumentation where we used to leak the scopes, but since we rewrote the instrumentation we don't rely on leaking scopes any more.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That makes sense. I've removed my dodgy workarounds - we can consider better solutions for http-pipelining in another issue.

I've also removed that system property and the tests still pass 👍


public TracingLogic() {
super(shape);
Expand Down Expand Up @@ -112,18 +104,17 @@ public void onDownstreamFinish(Throwable cause) {
@Override
public void onPush() {
HttpRequest request = grab(requestIn);

TracingRequest tracingRequest = TracingRequest.EMPTY;
Context parentContext = currentContext();
if (PekkoHttpServerSingletons.instrumenter().shouldStart(parentContext, request)) {
Context context =
PekkoHttpServerSingletons.instrumenter().start(parentContext, request);
context = PekkoRouteHolder.init(context);
tracingRequest = new TracingRequest(context, request);
PekkoTracingRequest tracingRequest =
request
.getAttribute(PekkoTracingRequest.ATTR_KEY)
.orElse(PekkoTracingRequest.EMPTY);
if (tracingRequest != PekkoTracingRequest.EMPTY) {
// Remove HttpRequest attribute before passing it to user code
request = (HttpRequest) request.removeAttribute(PekkoTracingRequest.ATTR_KEY);
}
// event if span wasn't started we need to push TracingRequest to match response
// with request
requests.push(tracingRequest);
requests.add(tracingRequest);

push(requestOut, request);
}
Expand All @@ -146,40 +137,11 @@ public void onUpstreamFailure(Throwable exception) {
@Override
public void onPush() {
HttpResponse response = grab(responseIn);

TracingRequest tracingRequest = requests.poll();
if (tracingRequest != null && tracingRequest != TracingRequest.EMPTY) {
// pekko response is immutable so the customizer just captures the added headers
PekkoHttpResponseMutator responseMutator = new PekkoHttpResponseMutator();
HttpServerResponseCustomizerHolder.getCustomizer()
.customize(tracingRequest.context, response, responseMutator);
// build a new response with the added headers
List<HttpHeader> headers = responseMutator.getHeaders();
if (!headers.isEmpty()) {
response = (HttpResponse) response.addHeaders(headers);
}

PekkoHttpServerSingletons.instrumenter()
.end(tracingRequest.context, tracingRequest.request, response, null);
}
push(responseOut, response);
}

@Override
public void onUpstreamFailure(Throwable exception) {
TracingRequest tracingRequest;
while ((tracingRequest = requests.poll()) != null) {
if (tracingRequest == TracingRequest.EMPTY) {
continue;
}
PekkoHttpServerSingletons.instrumenter()
.end(
tracingRequest.context,
tracingRequest.request,
PekkoHttpServerSingletons.errorResponse(),
exception);
}

fail(responseOut, exception);
}

Expand All @@ -191,20 +153,9 @@ public void onUpstreamFinish() {
}

abstract class ApplicationOutHandler extends AbstractOutHandler {
Deque<TracingRequest> getRequests() {
Queue<PekkoTracingRequest> getRequests() {
return requests;
}
}
}

private static class TracingRequest {
static final TracingRequest EMPTY = new TracingRequest(null, null);
final Context context;
final HttpRequest request;

TracingRequest(Context context, HttpRequest request) {
this.context = context;
this.request = request;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public String getModuleGroup() {
public List<TypeInstrumentation> typeInstrumentations() {
return asList(
new HttpExtServerInstrumentation(),
new HttpServerBluePrintInstrumentation(),
new GraphInterpreterInstrumentation(),
new PekkoHttpServerSourceInstrumentation());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.pekkohttp.v1_0.server;

import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static io.opentelemetry.javaagent.instrumentation.pekkohttp.v1_0.server.PekkoHttpServerSingletons.instrumenter;

import io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.bootstrap.http.HttpServerResponseCustomizerHolder;
import io.opentelemetry.javaagent.instrumentation.pekkohttp.v1_0.server.route.PekkoRouteHolder;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
import org.apache.pekko.http.javadsl.model.HttpHeader;
import org.apache.pekko.http.scaladsl.model.HttpRequest;
import org.apache.pekko.http.scaladsl.model.HttpResponse;
import org.apache.pekko.stream.Attributes;
import org.apache.pekko.stream.BidiShape;
import org.apache.pekko.stream.Inlet;
import org.apache.pekko.stream.Outlet;
import org.apache.pekko.stream.scaladsl.BidiFlow;
import org.apache.pekko.stream.stage.AbstractInHandler;
import org.apache.pekko.stream.stage.AbstractOutHandler;
import org.apache.pekko.stream.stage.GraphStage;
import org.apache.pekko.stream.stage.GraphStageLogic;

public class PekkoHttpServerTracer
extends GraphStage<BidiShape<HttpResponse, HttpResponse, HttpRequest, HttpRequest>> {
private final Inlet<HttpRequest> requestIn = Inlet.create("otel.requestIn");
private final Outlet<HttpRequest> requestOut = Outlet.create("otel.requestOut");
private final Inlet<HttpResponse> responseIn = Inlet.create("otel.responseIn");
private final Outlet<HttpResponse> responseOut = Outlet.create("otel.responseOut");

private final BidiShape<HttpResponse, HttpResponse, HttpRequest, HttpRequest> shape =
BidiShape.of(responseIn, responseOut, requestIn, requestOut);

public static BidiFlow<HttpResponse, ?, ?, HttpRequest, ?> wrap(
BidiFlow<HttpResponse, ?, ?, HttpRequest, ?> handler) {
return BidiFlow.fromGraph(new PekkoHttpServerTracer()).atopMat(handler, (a, b) -> b);
}

@Override
public BidiShape<HttpResponse, HttpResponse, HttpRequest, HttpRequest> shape() {
return shape;
}

@Override
public GraphStageLogic createLogic(Attributes attributes) {
return new TracingLogic();
}

private class TracingLogic extends GraphStageLogic {
private final Queue<PekkoTracingRequest> requests = new ArrayDeque<>();

public TracingLogic() {
super(shape);

// server pulls response, pass response from user code to server
setHandler(
responseOut,
new AbstractOutHandler() {
@Override
public void onPull() {
pull(responseIn);
}

@Override
public void onDownstreamFinish(Throwable cause) {
cancel(responseIn);
}
});

// user code pulls request, pass request from server to user code
setHandler(
requestOut,
new AbstractOutHandler() {
@Override
public void onPull() {
pull(requestIn);
}

@Override
public void onDownstreamFinish(Throwable cause) {
// Invoked on errors. Don't complete this stage to allow error-capturing
cancel(requestIn);
}
});

// new request from server
setHandler(
requestIn,
new AbstractInHandler() {
@Override
public void onPush() {
HttpRequest request = grab(requestIn);
PekkoTracingRequest tracingRequest = PekkoTracingRequest.EMPTY;
Context parentContext = currentContext();
if (instrumenter().shouldStart(parentContext, request)) {
Context context = instrumenter().start(parentContext, request);
context = PekkoRouteHolder.init(context);
tracingRequest = new PekkoTracingRequest(context, request);
request =
(HttpRequest)
request.addAttribute(PekkoTracingRequest.ATTR_KEY, tracingRequest);
}
// event if span wasn't started we need to push TracingRequest to match response
// with request
requests.add(tracingRequest);

push(requestOut, request);
}

@Override
public void onUpstreamFinish() {
complete(requestOut);
}

@Override
public void onUpstreamFailure(Throwable exception) {
fail(requestOut, exception);
}
});

// response from user code
setHandler(
responseIn,
new AbstractInHandler() {
@Override
public void onPush() {
HttpResponse response = grab(responseIn);

PekkoTracingRequest tracingRequest = requests.poll();
if (tracingRequest != null && tracingRequest != PekkoTracingRequest.EMPTY) {
// pekko response is immutable so the customizer just captures the added headers
PekkoHttpResponseMutator responseMutator = new PekkoHttpResponseMutator();
HttpServerResponseCustomizerHolder.getCustomizer()
.customize(tracingRequest.context, response, responseMutator);
// build a new response with the added headers
List<HttpHeader> headers = responseMutator.getHeaders();
if (!headers.isEmpty()) {
response = (HttpResponse) response.addHeaders(headers);
}

instrumenter().end(tracingRequest.context, tracingRequest.request, response, null);
}
push(responseOut, response);
}

@Override
public void onUpstreamFailure(Throwable exception) {
// End the span for the request that failed
PekkoTracingRequest tracingRequest = requests.poll();
if (tracingRequest != null && tracingRequest != PekkoTracingRequest.EMPTY) {
instrumenter()
.end(
tracingRequest.context,
tracingRequest.request,
PekkoHttpServerSingletons.errorResponse(),
exception);
}

fail(responseOut, exception);
}

@Override
public void onUpstreamFinish() {
// End any ongoing spans, though there should be none.
PekkoTracingRequest tracingRequest;
while ((tracingRequest = requests.poll()) != null) {
if (tracingRequest == PekkoTracingRequest.EMPTY) {
continue;
}
instrumenter()
.end(
tracingRequest.context,
tracingRequest.request,
PekkoHttpServerSingletons.errorResponse(),
null);
}
completeStage();
}
});
}
}
}
Loading
Loading