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
71 changes: 71 additions & 0 deletions dd-java-agent/instrumentation/cxf-2.1/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
ext {
minVersionForTests = JavaVersion.VERSION_11
}
muzzle {
pass {
group = "org.apache.cxf"
module = "cxf-api"
versions = "[2.0.6,)"
extraDependency "javax.servlet:servlet-api:2.5"
}
pass {
group = "org.apache.cxf"
module = "cxf-core"
versions = "[3,)"
javaVersion = "11"
extraDependency "jakarta.servlet:jakarta.servlet-api:5.0.0"
}
}

apply from: "${rootDir}/gradle/java.gradle"

addTestSuite('latestDepTest')
addTestSuiteForDir('cxf3LatestDepTest', 'test')

[compileLatestDepTestJava, compileCxf3LatestDepTestJava].each {
it.configure {
setJavaVersion(it, 11)
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}

[compileLatestDepTestGroovy, latestDepTest, compileCxf3LatestDepTestGroovy, cxf3LatestDepTest].each {
it.configure {
javaLauncher = getJavaLauncherFor(11)
}
}

dependencies {
compileOnly group: 'org.apache.cxf', name: 'cxf-api', version: '2.1'
testImplementation(project(':dd-java-agent:testing')) {
exclude group: 'org.eclipse.jetty', module: 'jetty-server'
}
testImplementation group: 'org.apache.cxf', name: 'cxf-rt-frontend-jaxrs', version: '3.0.0'
testImplementation group: 'org.apache.cxf', name:'cxf-rt-transports-http-jetty', version: '3.0.0'
testCompileOnly group: 'javax.ws.rs', name: 'javax.ws.rs-api', version: '2.1'
testRuntimeOnly group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
testRuntimeOnly group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1'
testRuntimeOnly project(':dd-java-agent:instrumentation:jetty-7.0')
testRuntimeOnly project(':dd-java-agent:instrumentation:jetty-7.6')
testRuntimeOnly project(':dd-java-agent:instrumentation:jetty-9')
testRuntimeOnly project(':dd-java-agent:instrumentation:jetty-11')
testRuntimeOnly project(':dd-java-agent:instrumentation:trace-annotation')
testRuntimeOnly project(':dd-java-agent:instrumentation:jax-rs-annotations-2')
testRuntimeOnly project(':dd-java-agent:instrumentation:jakarta-rs-annotations-3')
testRuntimeOnly project(':dd-java-agent:instrumentation:jakarta-rs-annotations-3')

cxf3LatestDepTestImplementation group: 'org.apache.cxf', name: 'cxf-rt-frontend-jaxrs', version: '3.+'
cxf3LatestDepTestImplementation group: 'org.apache.cxf', name:'cxf-rt-transports-http-jetty', version: '3.+'
cxf3LatestDepTestCompileOnly group: 'jakarta.ws.rs', name: 'jakarta.ws.rs-api', version: '2.+'

latestDepTestCompileOnly group: 'jakarta.ws.rs', name: 'jakarta.ws.rs-api', version: '3.+'
latestDepTestImplementation group: 'org.apache.cxf', name: 'cxf-rt-frontend-jaxrs', version: '+'
latestDepTestImplementation group: 'org.apache.cxf', name:'cxf-rt-transports-http-jetty', version: '+'

configurations.findAll {it.name in ['latestDepTestRuntimeClasspath', 'cxf3LatestDepTestRuntimeClasspath'] }.each {
it.resolutionStrategy {
force "org.slf4j:slf4j-api:${versions.slf4j}"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import datadog.trace.agent.test.AgentTestRunner
import datadog.trace.agent.test.utils.OkHttpUtils
import datadog.trace.agent.test.utils.TraceUtils
import datadog.trace.api.DDSpanTypes
import datadog.trace.bootstrap.instrumentation.api.Tags
import okhttp3.Request
import org.apache.cxf.endpoint.Server
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider
import org.apache.cxf.transport.http_jetty.JettyHTTPDestination
import org.apache.cxf.transport.http_jetty.JettyHTTPServerEngine
import spock.lang.Shared

class CxfContextPropagationTest extends AgentTestRunner {

@Shared
Server server

@Shared
int port

@Override
void setupSpec() {
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean()
sf.setResourceClasses(TestResource)
List<Object> providers = [new TestExceptionMapper()]
sf.setProviders(providers)

sf.setResourceProvider(TestResource,
new SingletonResourceProvider(new TestResource(), true))
sf.setAddress("http://localhost:0")

server = sf.create()
server.start()
port = ((JettyHTTPServerEngine)((JettyHTTPDestination)server.getDestination()).getEngine()).getConnector().getLocalPort()
}

@Override
void cleanupSpec() {
server?.stop()
}

def "should propagate context on async request resume"() {
setup:
def client = OkHttpUtils.client()
when:
def response = client.newCall(new Request.Builder()
.url("http://localhost:$port/test")
.get().build()).execute()
then:
assert response.code() == 200
assert response.body().string() == "Failure"

assertTraces(1) {
trace(4) {
sortSpansByStart()
span {
operationName "servlet.request"
resourceName "GET /test"
spanType DDSpanTypes.HTTP_SERVER
errored false
parent()
tags {
"$Tags.COMPONENT" "jakarta-rs"
"$Tags.SPAN_KIND" Tags.SPAN_KIND_SERVER
"$Tags.PEER_HOST_IPV4" "127.0.0.1"
"$Tags.PEER_PORT" Integer
"$Tags.HTTP_URL" "http://localhost:$port/test"
"$Tags.HTTP_HOSTNAME" "localhost"
"$Tags.HTTP_METHOD" "GET"
"$Tags.HTTP_STATUS" 200
"$Tags.HTTP_ROUTE" String
"servlet.path" "/test"
"$Tags.HTTP_USER_AGENT" String
"$Tags.HTTP_CLIENT_IP" "127.0.0.1"
defaultTags()
}
}
span {
operationName "jakarta-rs.request"
resourceName "TestResource.someService"
spanType DDSpanTypes.HTTP_SERVER
errored true
childOfPrevious()
tags {
"$Tags.COMPONENT" "jakarta-rs-controller"
"error.message" { String }
"error.type" { String }
"error.stack" { String }
defaultTags()
}
}
TraceUtils.basicSpan(it, "trace.annotation", "TestResource.doSomething",span(1), null, ["component": "trace"] )
TraceUtils.basicSpan(it, "trace.annotation", "TestExceptionMapper.toResponse",span(0), null, ["component": "trace"] )
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import datadog.trace.api.Trace;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;

public class TestExceptionMapper implements ExceptionMapper<Throwable> {
@Override
@Trace
public Response toResponse(Throwable exception) {
return Response.ok(exception.getMessage()).build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import datadog.trace.api.Trace;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.container.AsyncResponse;
import jakarta.ws.rs.container.Suspended;

@Path("/test")
public class TestResource {
@GET
public void someService(@Suspended final AsyncResponse response) {
doSomething();
response.resume(new RuntimeException("Failure"));
}

@Trace
private void doSomething() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package datadog.trace.instrumentation.cxf;

import com.google.auto.service.AutoService;
import datadog.trace.agent.tooling.Instrumenter;
import datadog.trace.agent.tooling.bytebuddy.matcher.ClassLoaderMatchers;
import datadog.trace.agent.tooling.bytebuddy.matcher.HierarchyMatchers;
import datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers;
import datadog.trace.bootstrap.instrumentation.api.AgentScope;
import datadog.trace.bootstrap.instrumentation.api.AgentSpan;
import datadog.trace.bootstrap.instrumentation.api.AgentTracer;
import datadog.trace.bootstrap.instrumentation.decorator.HttpServerDecorator;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;
import org.apache.cxf.message.Exchange;

@AutoService(Instrumenter.class)
public class InvokerInstrumentation extends Instrumenter.Tracing
implements Instrumenter.ForTypeHierarchy {
public InvokerInstrumentation() {
super("cxf", "cxf-invoker");
}

@Override
public ElementMatcher<ClassLoader> classLoaderMatcher() {
return ClassLoaderMatchers.hasClassNamed("javax.servlet.ServletRequest")
.or(ClassLoaderMatchers.hasClassNamed("jakarta.servlet.ServletRequest"));
}

@Override
public String hierarchyMarkerType() {
return "org.apache.cxf.service.invoker.Invoker";
}

@Override
public ElementMatcher<TypeDescription> hierarchyMatcher() {
return HierarchyMatchers.implementsInterface(NameMatchers.named(hierarchyMarkerType()));
}

@Override
public String[] helperClassNames() {
return new String[] {
packageName + ".ServletHelper",
};
}

@Override
public void adviceTransformations(AdviceTransformation transformation) {
transformation.applyAdvice(
ElementMatchers.isMethod().and(NameMatchers.named("invoke")),
getClass().getName() + "$PropagateSpanAdvice");
}

public static class PropagateSpanAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static AgentScope beforeInvoke(@Advice.Argument(0) final Exchange exchange) {
if (exchange == null || exchange.getInMessage() == null || AgentTracer.activeSpan() != null) {
return null;
}
final Object span =
ServletHelper.getServletRequestAttribute(
exchange.getInMessage().get("HTTP.REQUEST"), HttpServerDecorator.DD_SPAN_ATTRIBUTE);
if (span instanceof AgentSpan) {
return AgentTracer.activateSpan((AgentSpan) span);
}
return null;
}

@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
public static void afterInvoke(@Advice.Enter final AgentScope scope) {
if (scope != null) {
scope.close();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package datadog.trace.instrumentation.cxf;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// Probably one day we should put it in the bootstrap if used in a lot of places

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.

As part of refactoring the build I'd like to make it easier to share utilities based on libraries like the servlet-api. And ideally do this in a way such that the right utility is chosen at advice insertion time, which would reduce the need for method handles.

public class ServletHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(ServletHelper.class);
private static final Class<?> JAVAX_SERVLET_REQUEST_CLASS =
safelyLocateClass("javax.servlet.ServletRequest");
private static final Class<?> JAKARTA_SERVLET_REQUEST_CLASS =
safelyLocateClass("jakarta.servlet.ServletRequest");
private static final MethodHandle JAVAX_ATTRIBUTE_ACCESSOR =
safelyUnreflectServletRequestAttributeGetter(JAVAX_SERVLET_REQUEST_CLASS);
private static final MethodHandle JAKARTA_ATTRIBUTE_ACCESSOR =
safelyUnreflectServletRequestAttributeGetter(JAKARTA_SERVLET_REQUEST_CLASS);

private static Class<?> safelyLocateClass(final String name) {
try {
return Class.forName(name, false, ServletHelper.class.getClassLoader());
} catch (Throwable t) {
// can be expected
}
return null;
}

private static MethodHandle safelyUnreflectServletRequestAttributeGetter(
final Class<?> servletRequestClass) {
if (servletRequestClass != null) {
try {
return MethodHandles.lookup()
.unreflect(servletRequestClass.getMethod("getAttribute", String.class));
} catch (Throwable t) {
if (JAVAX_ATTRIBUTE_ACCESSOR == null) {
LOGGER.debug(
"Unable to lookup getAttribute for servlet request class. The cxf-core instrumentation might not work as expected",
t);
}
}
}
return null;
}

public static Object getServletRequestAttribute(final Object servletRequest, final String name) {
final MethodHandle mh =
JAVAX_SERVLET_REQUEST_CLASS != null
&& JAVAX_SERVLET_REQUEST_CLASS.isInstance(servletRequest)
? JAVAX_ATTRIBUTE_ACCESSOR
: JAKARTA_SERVLET_REQUEST_CLASS != null
&& JAKARTA_SERVLET_REQUEST_CLASS.isInstance(servletRequest)
? JAKARTA_ATTRIBUTE_ACCESSOR
: null;
if (mh != null) {
try {
return mh.invoke(servletRequest, name);
} catch (Throwable e) {
// nothing we can do here. Silently ignore
}
}
return null;
}
}
Loading