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

Add support for MyBatis framework #10258

Merged
merged 12 commits into from
Feb 12, 2024
1 change: 1 addition & 0 deletions docs/supported-libraries.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ These are the supported libraries and frameworks:
| [Vert.x Web](https://vertx.io/docs/vertx-web/java/) | 3.0+ | N/A | Provides `http.route` [2] |
| [Vibur DBCP](https://www.vibur.org/) | 11.0+ | [opentelemetry-vibur-dbcp-11.0](../instrumentation/vibur-dbcp-11.0/library) | [Database Pool Metrics] |
| [ZIO](https://zio.dev/) | 2.0+ | N/A | Context propagation |
| [MyBatis](https://mybatis.org/mybatis-3/) | 3.2.0+ | N/A | none |
steverao marked this conversation as resolved.
Show resolved Hide resolved

**[1]** Standalone library instrumentation refers to instrumentation that can be used without the Java agent.

Expand Down
26 changes: 26 additions & 0 deletions instrumentation/mybatis/javaagent/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
plugins {
id("otel.javaagent-instrumentation")
}

dependencies {
compileOnly("com.google.auto.value:auto-value-annotations")
annotationProcessor("com.google.auto.value:auto-value")
library("org.mybatis:mybatis:3.2.0")
testImplementation("org.mockito:mockito-core")
testImplementation("org.mockito:mockito-junit-jupiter")
testImplementation("com.h2database:h2:1.4.191")
}

muzzle {
steverao marked this conversation as resolved.
Show resolved Hide resolved
pass {
group.set("org.mybatis")
module.set("mybatis")
versions.set("[3.2.0,)")
steverao marked this conversation as resolved.
Show resolved Hide resolved
}
}

tasks.withType<Test>().configureEach {
// required on jdk17
jvmArgs("--add-opens=java.base/java.lang=ALL-UNNAMED")
jvmArgs("-XX:+IgnoreUnrecognizedVMOptions")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.mybatis;
steverao marked this conversation as resolved.
Show resolved Hide resolved

import com.google.auto.value.AutoValue;

@AutoValue
public abstract class MapperMethodRequest {

public static MapperMethodRequest create(String mapperName) {
return new AutoValue_MapperMethodRequest(mapperName);
}

public abstract String getMapperName();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.mybatis;

import io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.context.Context;
import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor;
import javax.annotation.Nullable;

class MybatisAttributesExtractor implements AttributesExtractor<MapperMethodRequest, Void> {

@Override
public void onStart(
AttributesBuilder attributes,
Context parentContext,
MapperMethodRequest mapperMethodRequest) {
attributes.put("component.name", "mybatis");
steverao marked this conversation as resolved.
Show resolved Hide resolved
}

@Override
public void onEnd(
AttributesBuilder attributes,
Context context,
MapperMethodRequest mapperMethodRequest,
@Nullable Void unused,
@Nullable Throwable error) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.mybatis;

import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static io.opentelemetry.javaagent.instrumentation.mybatis.MybatisSingletons.mapperInstrumenter;
import static net.bytebuddy.matcher.ElementMatchers.named;

import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
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.ibatis.binding.MapperMethod.SqlCommand;

public class MybatisExecuteInstrumentation implements TypeInstrumentation {

@Override
public ElementMatcher<TypeDescription> typeMatcher() {
return named("org.apache.ibatis.binding.MapperMethod");
}

@Override
public void transform(TypeTransformer transformer) {
transformer.applyAdviceToMethod(
named("execute"), MybatisExecuteInstrumentation.class.getName() + "$ExecuteAdvice");
}

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

@Advice.OnMethodEnter(suppress = Throwable.class)
public static void getMapperInfo(
@Advice.FieldValue("command") SqlCommand command,
@Advice.Local("otelRequest") MapperMethodRequest request,
@Advice.Local("otelContext") Context context,
@Advice.Local("otelScope") Scope scope) {
Context parentContext = currentContext();
if (command == null || !mapperInstrumenter().shouldStart(parentContext, request)) {
return;
}
request = MapperMethodRequest.create(command.getName());
context = mapperInstrumenter().start(parentContext, request);
scope = context.makeCurrent();
}

@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class, inline = true)
public static void stopSpan(
@Advice.Thrown Throwable throwable,
@Advice.Local("otelRequest") MapperMethodRequest request,
@Advice.Local("otelContext") Context context,
@Advice.Local("otelScope") Scope scope) {
if (scope != null) {
scope.close();
mapperInstrumenter().end(context, request, null, throwable);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.mybatis;

import com.google.auto.service.AutoService;
import io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import java.util.Arrays;
import java.util.List;

@AutoService(InstrumentationModule.class)
public class MybatisInstrumentationModule extends InstrumentationModule {

public MybatisInstrumentationModule() {
super("mybatis");
steverao marked this conversation as resolved.
Show resolved Hide resolved
}

@Override
public List<TypeInstrumentation> typeInstrumentations() {
return Arrays.asList(new MybatisExecuteInstrumentation());
laurit marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.mybatis;

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter;
import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor;
import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor;

public final class MybatisSingletons {
steverao marked this conversation as resolved.
Show resolved Hide resolved
private static final String INSTRUMENTATION_NAME = "io.opentelemetry.mybatis";
laurit marked this conversation as resolved.
Show resolved Hide resolved

private static final Instrumenter<MapperMethodRequest, Void> MAPPER_INSTRUMENTER;

static {
SpanNameExtractor<MapperMethodRequest> spanNameExtractor = new MybatisSpanNameExtractor();

MAPPER_INSTRUMENTER =
Instrumenter.<MapperMethodRequest, Void>builder(
GlobalOpenTelemetry.get(),
INSTRUMENTATION_NAME,
spanNameExtractor)
.addAttributesExtractor(new MybatisAttributesExtractor())
.buildInstrumenter(SpanKindExtractor.alwaysInternal());
}

public static Instrumenter<MapperMethodRequest, Void> mapperInstrumenter() {
return MAPPER_INSTRUMENTER;
}
private MybatisSingletons() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.mybatis;

import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor;

public class MybatisSpanNameExtractor implements SpanNameExtractor<MapperMethodRequest> {

@Override
public String extract(MapperMethodRequest request) {
return request.getMapperName();
steverao marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.mybatis;

import static org.mockito.Mockito.when;

import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.instrumentation.testing.junit.AgentInstrumentationExtension;
import io.opentelemetry.instrumentation.testing.junit.InstrumentationExtension;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.defaults.DefaultSqlSession;
import org.junit.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mockito;

class MybatisTest {
steverao marked this conversation as resolved.
Show resolved Hide resolved

@RegisterExtension
protected static final InstrumentationExtension testing = AgentInstrumentationExtension.create();

private static final String SPAN_NAME =
"io.opentelemetry.javaagent.instrumentation.mybatis.RecordMapper.updateRecord";
steverao marked this conversation as resolved.
Show resolved Hide resolved

@Test
void mybatis() throws Exception {
DefaultSqlSession sqlSession = Mockito.mock(DefaultSqlSession.class);
Configuration configuration = Mockito.mock(Configuration.class);
DefaultObjectFactory defaultObjectFactory = Mockito.mock(DefaultObjectFactory.class);
when(sqlSession.update(SPAN_NAME, null)).thenReturn(1);
Class<?> mappedStatementClass = Class.forName(MappedStatement.class.getName());
steverao marked this conversation as resolved.
Show resolved Hide resolved
Constructor<?> constructor = mappedStatementClass.getDeclaredConstructor();
constructor.setAccessible(true);
MappedStatement mappedStatement = (MappedStatement) constructor.newInstance();
Field id = mappedStatementClass.getDeclaredField("id");
id.setAccessible(true);
id.set(mappedStatement, SPAN_NAME);
Field sqlCommandType = mappedStatementClass.getDeclaredField("sqlCommandType");
sqlCommandType.setAccessible(true);
sqlCommandType.set(mappedStatement, SqlCommandType.UPDATE);
when(configuration.hasStatement(SPAN_NAME)).thenReturn(true);
when(configuration.getMappedStatement(SPAN_NAME)).thenReturn(mappedStatement);
when(configuration.getObjectFactory()).thenReturn(defaultObjectFactory);
when(defaultObjectFactory.isCollection(Void.class)).thenReturn(false);
Class<?> mapper = Class.forName(RecordMapper.class.getName());
Method method = mapper.getMethod("updateRecord");
MapperMethod mapperMethod = new MapperMethod(mapper, method, configuration);
mapperMethod.execute(sqlSession, null);
span(SPAN_NAME);
}

private void span(String spanName) {
testing.waitAndAssertTracesWithoutScopeVersionVerification(
trace -> {
trace
.hasSize(1)
.hasSpansSatisfyingExactly(
span -> {
span.hasKind(SpanKind.INTERNAL).hasName(spanName);
});
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.mybatis;

import org.apache.ibatis.annotations.Update;

public interface RecordMapper {

@Update("update dummy_record set content = '3131223'")
void updateRecord();
}
1 change: 1 addition & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,7 @@ include(":instrumentation:vibur-dbcp-11.0:library")
include(":instrumentation:vibur-dbcp-11.0:testing")
include(":instrumentation:wicket-8.0:javaagent")
include(":instrumentation:zio:zio-2.0:javaagent")
include(":instrumentation:mybatis:javaagent")
steverao marked this conversation as resolved.
Show resolved Hide resolved
steverao marked this conversation as resolved.
Show resolved Hide resolved

// benchmark
include(":benchmark-overhead-jmh")
Expand Down
Loading