Additional instrumentation for hibernate 4.3 and 5.x onwards
MODIFY
dd-java-agent/instrumentation/hibernate-4.0/hibernate-4.0.gradle
dd-java-agent/instrumentation/hibernate-4.0/hibernate-4.0.gradle
@@ -46,4 +46,6 @@ dependencies {
latestDepTestCompile group: 'org.hibernate', name: 'hibernate-core', version: '+'
latestDepTestCompile group: 'com.h2database', name: 'h2', version: '1.4.197'
+ // Test that the incremental instrumentation for hibernate 4.3 doesn't cause issues.
+ latestDepTestCompile project(':dd-java-agent:instrumentation:hibernate-4.3')
}

ADD
dd-java-agent/instrumentation/hibernate-4.3/hibernate-4.3.gradle
+// Set properties before any plugins get loaded
+project.ext {
+ // Execute tests on all JVMs, even rare and outdated ones
+ coreJavaInstrumentation = true
+ minJavaVersionForTests = JavaVersion.VERSION_1_7
+}
+
+muzzle {
+ pass {
+ group = "org.hibernate"
+ module = "hibernate-core"
+ versions = "[4.3.0.Final,)"
+ }
+}
+
+apply from: "${rootDir}/gradle/java.gradle"
+
+apply plugin: 'org.unbroken-dome.test-sets'
+
+testSets {
+ latestDepTest {
+ dirName = 'test'
+ }
+}
+
+dependencies {
+ compileOnly group: 'org.hibernate', name: 'hibernate-core', version: '4.3.0.Final'
+
+ compile project(':dd-java-agent:agent-tooling')
+ compile project(':dd-java-agent:instrumentation:hibernate-4.0')
+
+ compile deps.bytebuddy
+ compile deps.opentracing
+ annotationProcessor deps.autoservice
+ implementation deps.autoservice
+
+ testCompile project(':dd-java-agent:testing')
+ testCompile project(':dd-java-agent:instrumentation:jdbc')
+
+ testCompile group: 'org.hibernate', name: 'hibernate-core', version: '4.3.0.Final'
+ testCompile group: 'org.hsqldb', name: 'hsqldb', version: '+'
+
+ latestDepTestCompile group: 'org.hibernate', name: 'hibernate-core', version: '+'
+ latestDepTestCompile group: 'org.hsqldb', name: 'hsqldb', version: '+'
+}

ADD
dd-java-agent/instrumentation/hibernate-4.3/src/main/java/datadog/trace/instrumentation/hibernate/v4_3/ProcedureCallInstrumentation.java
+package datadog.trace.instrumentation.hibernate.v4_3;
+
+import static datadog.trace.agent.tooling.ByteBuddyElementMatchers.safeHasSuperType;
+import static java.util.Collections.singletonMap;
+import static net.bytebuddy.matcher.ElementMatchers.isInterface;
+import static net.bytebuddy.matcher.ElementMatchers.isMethod;
+import static net.bytebuddy.matcher.ElementMatchers.named;
+import static net.bytebuddy.matcher.ElementMatchers.not;
+
+import com.google.auto.service.AutoService;
+import datadog.trace.agent.tooling.Instrumenter;
+import datadog.trace.bootstrap.ContextStore;
+import datadog.trace.bootstrap.InstrumentationContext;
+import datadog.trace.instrumentation.hibernate.v4_0.SessionMethodUtils;
+import datadog.trace.instrumentation.hibernate.v4_0.SessionState;
+import java.util.Map;
+import net.bytebuddy.asm.Advice;
+import net.bytebuddy.description.method.MethodDescription;
+import net.bytebuddy.description.type.TypeDescription;
+import net.bytebuddy.matcher.ElementMatcher;
+import org.hibernate.procedure.ProcedureCall;
+
+@AutoService(Instrumenter.class)
+public class ProcedureCallInstrumentation extends Instrumenter.Default {
+
+ public ProcedureCallInstrumentation() {
+ super("hibernate", "hibernate-core");
+ }
+
+ @Override
+ public Map<String, String> contextStore() {
+ return singletonMap("org.hibernate.procedure.ProcedureCall", SessionState.class.getName());
+ }
+
+ @Override
+ public String[] helperClassNames() {
+ return new String[] {
+ "datadog.trace.instrumentation.hibernate.v4_0.SessionMethodUtils",
+ "datadog.trace.instrumentation.hibernate.v4_0.SessionState",
+ "datadog.trace.agent.decorator.BaseDecorator",
+ "datadog.trace.agent.decorator.ClientDecorator",
+ "datadog.trace.agent.decorator.DatabaseClientDecorator",
+ "datadog.trace.agent.decorator.OrmClientDecorator",
+ "datadog.trace.instrumentation.hibernate.v4_0.HibernateDecorator",
+ };
+ }
+
+ @Override
+ public ElementMatcher<TypeDescription> typeMatcher() {
+ return not(isInterface()).and(safeHasSuperType(named("org.hibernate.procedure.ProcedureCall")));
+ }
+
+ @Override
+ public Map<? extends ElementMatcher<? super MethodDescription>, String> transformers() {
+ return singletonMap(
+ isMethod().and(named("getOutputs")), ProcedureCallMethodAdvice.class.getName());
+ }
+
+ public static class ProcedureCallMethodAdvice {
+
+ @Advice.OnMethodEnter(suppress = Throwable.class)
+ public static SessionState startMethod(
+ @Advice.This final ProcedureCall call, @Advice.Origin("#m") final String name) {
+
+ final ContextStore<ProcedureCall, SessionState> contextStore =
+ InstrumentationContext.get(ProcedureCall.class, SessionState.class);
+
+ final SessionState state =
+ SessionMethodUtils.startScopeFrom(
+ contextStore, call, "hibernate.procedure." + name, call.getProcedureName(), true);
+ return state;
+ }
+
+ @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
+ public static void endMethod(
+ @Advice.Enter final SessionState state, @Advice.Thrown final Throwable throwable) {
+ SessionMethodUtils.closeScope(state, throwable, null);
+ }
+ }
+}

ADD
dd-java-agent/instrumentation/hibernate-4.3/src/main/java/datadog/trace/instrumentation/hibernate/v4_3/SessionInstrumentation.java
+package datadog.trace.instrumentation.hibernate.v4_3;
+
+import static datadog.trace.agent.tooling.ByteBuddyElementMatchers.safeHasSuperType;
+import static net.bytebuddy.matcher.ElementMatchers.isInterface;
+import static net.bytebuddy.matcher.ElementMatchers.isMethod;
+import static net.bytebuddy.matcher.ElementMatchers.named;
+import static net.bytebuddy.matcher.ElementMatchers.not;
+import static net.bytebuddy.matcher.ElementMatchers.returns;
+
+import com.google.auto.service.AutoService;
+import datadog.trace.agent.tooling.Instrumenter;
+import datadog.trace.bootstrap.ContextStore;
+import datadog.trace.bootstrap.InstrumentationContext;
+import datadog.trace.instrumentation.hibernate.v4_0.SessionMethodUtils;
+import datadog.trace.instrumentation.hibernate.v4_0.SessionState;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import net.bytebuddy.asm.Advice;
+import net.bytebuddy.description.method.MethodDescription;
+import net.bytebuddy.description.type.TypeDescription;
+import net.bytebuddy.matcher.ElementMatcher;
+import org.hibernate.SharedSessionContract;
+import org.hibernate.procedure.ProcedureCall;
+
+@AutoService(Instrumenter.class)
+public class SessionInstrumentation extends Instrumenter.Default {
+
+ public SessionInstrumentation() {
+ super("hibernate", "hibernate-core");
+ }
+
+ @Override
+ public Map<String, String> contextStore() {
+ final Map<String, String> map = new HashMap<>();
+ map.put("org.hibernate.SharedSessionContract", SessionState.class.getName());
+ map.put("org.hibernate.procedure.ProcedureCall", SessionState.class.getName());
+ return Collections.unmodifiableMap(map);
+ }
+
+ @Override
+ public String[] helperClassNames() {
+ return new String[] {
+ "datadog.trace.instrumentation.hibernate.v4_0.SessionMethodUtils",
+ "datadog.trace.instrumentation.hibernate.v4_0.SessionState",
+ "datadog.trace.agent.decorator.BaseDecorator",
+ "datadog.trace.agent.decorator.ClientDecorator",
+ "datadog.trace.agent.decorator.DatabaseClientDecorator",
+ "datadog.trace.agent.decorator.OrmClientDecorator",
+ "datadog.trace.instrumentation.hibernate.v4_0.HibernateDecorator",
+ };
+ }
+
+ @Override
+ public ElementMatcher<TypeDescription> typeMatcher() {
+ return not(isInterface()).and(safeHasSuperType(named("org.hibernate.SharedSessionContract")));
+ }
+
+ @Override
+ public Map<? extends ElementMatcher<? super MethodDescription>, String> transformers() {
+ final Map<ElementMatcher<? super MethodDescription>, String> transformers = new HashMap<>();
+
+ transformers.put(
+ isMethod().and(returns(safeHasSuperType(named("org.hibernate.procedure.ProcedureCall")))),
+ GetProcedureCallAdvice.class.getName());
+
+ return transformers;
+ }
+
+ public static class GetProcedureCallAdvice {
+
+ @Advice.OnMethodExit(suppress = Throwable.class)
+ public static void getProcedureCall(
+ @Advice.This final SharedSessionContract session,
+ @Advice.Return final ProcedureCall returned) {
+
+ final ContextStore<SharedSessionContract, SessionState> sessionContextStore =
+ InstrumentationContext.get(SharedSessionContract.class, SessionState.class);
+ final ContextStore<ProcedureCall, SessionState> returnedContextStore =
+ InstrumentationContext.get(ProcedureCall.class, SessionState.class);
+
+ SessionMethodUtils.attachSpanFromStore(
+ sessionContextStore, session, returnedContextStore, returned);
+ }
+ }
+}

ADD
dd-java-agent/instrumentation/hibernate-4.3/src/test/groovy/ProcedureCallTest.groovy
+import datadog.trace.agent.test.AgentTestRunner
+import datadog.trace.api.DDSpanTypes
+import io.opentracing.tag.Tags
+import org.hibernate.Session
+import org.hibernate.SessionFactory
+import org.hibernate.cfg.Configuration
+import org.hibernate.exception.SQLGrammarException
+import org.hibernate.procedure.ProcedureCall
+import spock.lang.Shared
+
+import javax.persistence.ParameterMode
+import java.sql.Connection
+import java.sql.DriverManager
+import java.sql.Statement
+
+class ProcedureCallTest extends AgentTestRunner {
+
+
+ @Shared
+ protected SessionFactory sessionFactory
+
+ @Shared
+ protected List<Value> prepopulated
+
+ def setupSpec() {
+ sessionFactory = new Configuration().configure().buildSessionFactory()
+ // Pre-populate the DB, so delete/update can be tested.
+ Session writer = sessionFactory.openSession()
+ writer.beginTransaction()
+ prepopulated = new ArrayList<>()
+ for (int i = 0; i < 2; i++) {
+ prepopulated.add(new Value("Hello :) " + i))
+ writer.save(prepopulated.get(i))
+ }
+ writer.getTransaction().commit()
+ writer.close()
+
+ // Create a stored procedure.
+ Connection conn = DriverManager.getConnection("jdbc:hsqldb:mem:test", "sa", "1")
+ Statement stmt = conn.createStatement()
+ stmt.execute("CREATE PROCEDURE TEST_PROC() MODIFIES SQL DATA BEGIN ATOMIC INSERT INTO Value VALUES (420, 'fred'); END")
+ stmt.close()
+ conn.close()
+ }
+
+ def cleanupSpec() {
+ if (sessionFactory != null) {
+ sessionFactory.close()
+ }
+ }
+
+ def "test ProcedureCall"() {
+ setup:
+
+ Session session = sessionFactory.openSession()
+ session.beginTransaction()
+
+ ProcedureCall call = session.createStoredProcedureCall("TEST_PROC")
+ call.getOutputs()
+
+ session.getTransaction().commit()
+ session.close()
+
+ expect:
+ assertTraces(1) {
+ trace(0, 4) {
+ span(0) {
+ serviceName "hibernate"
+ resourceName "hibernate.session"
+ operationName "hibernate.session"
+ spanType DDSpanTypes.HIBERNATE
+ parent()
+ tags {
+ "$Tags.COMPONENT.key" "java-hibernate"
+ "$Tags.SPAN_KIND.key" Tags.SPAN_KIND_CLIENT
+ defaultTags()
+ }
+ }
+ span(1) {
+ serviceName "hibernate"
+ resourceName "hibernate.transaction.commit"
+ operationName "hibernate.transaction.commit"
+ spanType DDSpanTypes.HIBERNATE
+ childOf span(0)
+ tags {
+ "$Tags.COMPONENT.key" "java-hibernate"
+ "$Tags.SPAN_KIND.key" Tags.SPAN_KIND_CLIENT
+ defaultTags()
+ }
+ }
+ span(2) {
+ serviceName "hibernate"
+ resourceName "TEST_PROC"
+ operationName "hibernate.procedure.getOutputs"
+ spanType DDSpanTypes.HIBERNATE
+ childOf span(0)
+ tags {
+ "$Tags.COMPONENT.key" "java-hibernate"
+ "$Tags.SPAN_KIND.key" Tags.SPAN_KIND_CLIENT
+ defaultTags()
+ }
+ }
+ span(3) {
+ serviceName "hsqldb"
+ spanType "sql"
+ childOf span(2)
+ }
+ }
+ }
+ }
+
+ def "test failing ProcedureCall"() {
+ setup:
+
+ Session session = sessionFactory.openSession()
+ session.beginTransaction()
+
+ ProcedureCall call = session.createStoredProcedureCall("TEST_PROC")
+ call.registerParameter("nonexistent", Long.class, ParameterMode.IN)
+ call.getParameterRegistration("nonexistent").bindValue(420)
+ try {
+ call.getOutputs()
+ } catch (Exception e) {
+ // We expected this.
+ }
+
+ session.getTransaction().commit()
+ session.close()
+
+ expect:
+ assertTraces(1) {
+ trace(0, 3) {
+ span(0) {
+ serviceName "hibernate"
+ resourceName "hibernate.session"
+ operationName "hibernate.session"
+ spanType DDSpanTypes.HIBERNATE
+ parent()
+ tags {
+ "$Tags.COMPONENT.key" "java-hibernate"
+ "$Tags.SPAN_KIND.key" Tags.SPAN_KIND_CLIENT
+ defaultTags()
+ }
+ }
+ span(1) {
+ serviceName "hibernate"
+ resourceName "hibernate.transaction.commit"
+ operationName "hibernate.transaction.commit"
+ spanType DDSpanTypes.HIBERNATE
+ childOf span(0)
+ tags {
+ "$Tags.COMPONENT.key" "java-hibernate"
+ "$Tags.SPAN_KIND.key" Tags.SPAN_KIND_CLIENT
+ defaultTags()
+ }
+ }
+ span(2) {
+ serviceName "hibernate"
+ resourceName "TEST_PROC"
+ operationName "hibernate.procedure.getOutputs"
+ spanType DDSpanTypes.HIBERNATE
+ childOf span(0)
+ errored(true)
+ tags {
+ errorTags(SQLGrammarException, "could not prepare statement")
+ "$Tags.COMPONENT.key" "java-hibernate"
+ "$Tags.SPAN_KIND.key" Tags.SPAN_KIND_CLIENT
+ defaultTags()
+ }
+ }
+ }
+ }
+ }
+}
+

ADD
dd-java-agent/instrumentation/hibernate-4.3/src/test/java/Value.java
+import datadog.trace.api.Trace;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import org.hibernate.annotations.GenericGenerator;
+import org.hibernate.annotations.NamedQuery;
+
+@Entity
+@Table
+@NamedQuery(name = "TestNamedQuery", query = "from Value")
+public class Value {
+
+ private Long id;
+ private String name;
+
+ public Value() {}
+
+ public Value(final String name) {
+ this.name = name;
+ }
+
+ @Id
+ @GeneratedValue(generator = "increment")
+ @GenericGenerator(name = "increment", strategy = "increment")
+ public Long getId() {
+ return id;
+ }
+
+ private void setId(final Long id) {
+ this.id = id;
+ }
+
+ @Trace
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String title) {
+ this.name = title;
+ }
+}

ADD
dd-java-agent/instrumentation/hibernate-4.3/src/test/resources/hibernate.cfg.xml
+<?xml version='1.0' encoding='utf-8'?>
+<!DOCTYPE hibernate-configuration PUBLIC
+ "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
+ "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
+
+<hibernate-configuration>
+
+ <session-factory>
+
+ <!--&lt;!&ndash; Use in-memory DB for testing &ndash;&gt;-->
+ <!--<property name="connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>-->
+ <!--<property name="connection.url">jdbc:derby:test;create=true</property>-->
+ <!--<property name="connection.username">root</property>-->
+ <!--<property name="connection.password">root</property>-->
+ <!--<property name="dialect">org.hibernate.dialect.DerbyTenSevenDialect</property>-->
+
+ <!--<property name="connection.pool_size">3</property>-->
+ <!--<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>-->
+ <!--<property name="show_sql">true</property>-->
+
+ <!--&lt;!&ndash; Reset the DB each test &ndash;&gt;-->
+ <!--<property name="hbm2ddl.auto">create</property>-->
+
+ <property name="hibernate.archive.autodetection">class,hbm</property>
+ <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
+ <property name="hibernate.show_sql">true</property>
+ <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
+ <property name="hibernate.connection.username">sa</property>
+ <property name="hibernate.connection.password">1</property>
+ <property name="hibernate.connection.url">jdbc:hsqldb:mem:test</property>
+ <property name="hibernate.hbm2ddl.auto">create</property>
+
+ <!-- Objects -->
+ <mapping class="Value"/>
+
+ </session-factory>
+
+</hibernate-configuration>

MODIFY
settings.gradle
settings.gradle
@@ -41,6 +41,7 @@ include ':dd-java-agent:instrumentation:elasticsearch:transport-5.3'
include ':dd-java-agent:instrumentation:elasticsearch:transport-6'
include ':dd-java-agent:instrumentation:grpc-1.5'
include ':dd-java-agent:instrumentation:hibernate-4.0'
+include ':dd-java-agent:instrumentation:hibernate-4.3'
include ':dd-java-agent:instrumentation:http-url-connection'
include ':dd-java-agent:instrumentation:hystrix-1.4'
include ':dd-java-agent:instrumentation:jax-rs-annotations'

Additional instrumentation for hibernate 4.3 and 5.x onwards