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 javaagent instrumentation for ktor2 #9149

Merged
merged 4 commits into from
Aug 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
42 changes: 42 additions & 0 deletions instrumentation/ktor/ktor-2.0/javaagent/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
id("org.jetbrains.kotlin.jvm")
id("otel.javaagent-instrumentation")
}

muzzle {
pass {
group.set("org.jetbrains.kotlinx")
module.set("ktor-server-core")
versions.set("[2.0.0,)")
}
}

val ktorVersion = "2.0.0"

dependencies {
library("io.ktor:ktor-client-core:$ktorVersion")
library("io.ktor:ktor-server-core:$ktorVersion")

implementation(project(":instrumentation:ktor:ktor-2.0:library"))

compileOnly("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

testInstrumentation(project(":instrumentation:netty:netty-4.1:javaagent"))

testImplementation(project(":instrumentation:ktor:ktor-2.0:testing"))
testImplementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("io.opentelemetry:opentelemetry-extension-kotlin")

testLibrary("io.ktor:ktor-server-netty:$ktorVersion")
testLibrary("io.ktor:ktor-client-cio:$ktorVersion")
}

tasks {
withType(KotlinCompile::class).configureEach {
kotlinOptions {
jvmTarget = "1.8"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.ktor.v2_0;

import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
import static net.bytebuddy.matcher.ElementMatchers.takesArguments;

import io.ktor.client.HttpClientConfig;
import io.ktor.client.engine.HttpClientEngineConfig;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.instrumentation.ktor.v2_0.client.KtorClientTracing;
import io.opentelemetry.instrumentation.ktor.v2_0.client.KtorClientTracingBuilder;
import io.opentelemetry.javaagent.bootstrap.internal.CommonConfig;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

public class HttpClientInstrumentation implements TypeInstrumentation {
@Override
public ElementMatcher<TypeDescription> typeMatcher() {
return named("io.ktor.client.HttpClient");
}

@Override
public void transform(TypeTransformer transformer) {
transformer.applyAdviceToMethod(
isConstructor()
.and(takesArguments(2))
.and(takesArgument(1, named("io.ktor.client.HttpClientConfig"))),
this.getClass().getName() + "$ConstructorAdvice");
}

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

@Advice.OnMethodEnter
public static void onEnter(
@Advice.Argument(1) HttpClientConfig<HttpClientEngineConfig> httpClientConfig) {
httpClientConfig.install(KtorClientTracing.Companion, new SetupFunction());
}
}

public static class SetupFunction implements Function1<KtorClientTracingBuilder, Unit> {

@Override
public Unit invoke(KtorClientTracingBuilder builder) {
OpenTelemetry openTelemetry = GlobalOpenTelemetry.get();
builder.setOpenTelemetry(openTelemetry);
builder.setCapturedRequestHeaders(CommonConfig.get().getClientRequestHeaders());
builder.setCapturedResponseHeaders(CommonConfig.get().getClientResponseHeaders());

laurit marked this conversation as resolved.
Show resolved Hide resolved
return kotlin.Unit.INSTANCE;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.ktor.v2_0;

import static java.util.Arrays.asList;

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

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

public KtorInstrumentationModule() {
super("ktor", "ktor-2.0");
}

@Override
public boolean isHelperClass(String className) {
return className.startsWith("io.opentelemetry.extension.kotlin.");
Copy link
Member

Choose a reason for hiding this comment

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

Wouldn't this normally be injected by the coroutine instrumentation module? Do we need that here as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is more about muzzle, if we don't tell it that these are helpers it will fail with Missing class io.opentelemetry.javaagent.shaded.io.opentelemetry.extension.kotlin.ContextExtensionsKt

}

@Override
public List<TypeInstrumentation> typeInstrumentations() {
return asList(new ServerInstrumentation(), new HttpClientInstrumentation());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.ktor.v2_0;

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

import io.ktor.server.application.Application;
import io.ktor.server.application.ApplicationPluginKt;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.instrumentation.ktor.v2_0.server.KtorServerTracing;
import io.opentelemetry.javaagent.bootstrap.internal.CommonConfig;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

public class ServerInstrumentation implements TypeInstrumentation {
@Override
public ElementMatcher<TypeDescription> typeMatcher() {
return named("io.ktor.server.engine.ApplicationEngineEnvironmentReloading");
}

@Override
public void transform(TypeTransformer transformer) {
transformer.applyAdviceToMethod(
isConstructor(), this.getClass().getName() + "$ConstructorAdvice");
}

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

@Advice.OnMethodExit
public static void onExit(@Advice.FieldValue("_applicationInstance") Application application) {
ApplicationPluginKt.install(application, KtorServerTracing.Feature, new SetupFunction());
}
}

public static class SetupFunction
implements Function1<KtorServerTracing.Configuration, kotlin.Unit> {

@Override
public Unit invoke(KtorServerTracing.Configuration configuration) {
OpenTelemetry openTelemetry = GlobalOpenTelemetry.get();
configuration.setOpenTelemetry(openTelemetry);
configuration.setCapturedRequestHeaders(CommonConfig.get().getClientRequestHeaders());
configuration.setCapturedResponseHeaders(CommonConfig.get().getClientResponseHeaders());
laurit marked this conversation as resolved.
Show resolved Hide resolved

return kotlin.Unit.INSTANCE;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.instrumentation.ktor.v2_0.client

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.opentelemetry.instrumentation.testing.junit.http.HttpClientInstrumentationExtension
import kotlinx.coroutines.*
import org.junit.jupiter.api.extension.RegisterExtension

class KtorHttpClientTest : AbstractKtorHttpClientTest() {

companion object {
@JvmStatic
@RegisterExtension
private val TESTING = HttpClientInstrumentationExtension.forAgent()
}

override fun HttpClientConfig<*>.installTracing() {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.instrumentation.ktor.v2_0.server

import io.ktor.server.application.*
import io.opentelemetry.instrumentation.testing.junit.InstrumentationExtension
import io.opentelemetry.instrumentation.testing.junit.http.HttpServerInstrumentationExtension
import io.opentelemetry.instrumentation.testing.junit.http.HttpServerTestOptions
import org.junit.jupiter.api.extension.RegisterExtension

class KtorHttpServerTest : AbstractKtorHttpServerTest() {

companion object {
@JvmStatic
@RegisterExtension
val TESTING: InstrumentationExtension = HttpServerInstrumentationExtension.forAgent()
}

override fun getTesting(): InstrumentationExtension {
return TESTING
}

override fun installOpenTelemetry(application: Application) {
}

override fun configure(options: HttpServerTestOptions) {
super.configure(options)
options.setTestException(false)
}
}
1 change: 1 addition & 0 deletions instrumentation/ktor/ktor-2.0/library/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ dependencies {

compileOnly("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

testImplementation(project(":instrumentation:ktor:ktor-2.0:testing"))
testImplementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

testLibrary("io.ktor:ktor-server-netty:$ktorVersion")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,7 @@ class KtorServerTracing private constructor(
}

pipeline.environment.monitor.subscribe(Routing.RoutingCallStarted) { call ->
val context = call.attributes.getOrNull(contextKey)
if (context != null) {
HttpRouteHolder.updateHttpRoute(context, HttpRouteSource.SERVLET, { _, arg -> arg.route.parent.toString() }, call)
}
HttpRouteHolder.updateHttpRoute(Context.current(), HttpRouteSource.SERVLET, { _, arg -> arg.route.parent.toString() }, call)
}

return feature
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,84 +6,22 @@
package io.opentelemetry.instrumentation.ktor.v2_0.client

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.opentelemetry.context.Context
import io.opentelemetry.extension.kotlin.asContextElement
import io.opentelemetry.instrumentation.testing.junit.http.AbstractHttpClientTest
import io.opentelemetry.instrumentation.testing.junit.http.HttpClientInstrumentationExtension
import io.opentelemetry.instrumentation.testing.junit.http.HttpClientResult
import io.opentelemetry.instrumentation.testing.junit.http.HttpClientTestOptions
import io.opentelemetry.instrumentation.testing.junit.http.HttpClientTestOptions.DEFAULT_HTTP_ATTRIBUTES
import io.opentelemetry.semconv.trace.attributes.SemanticAttributes
import kotlinx.coroutines.*
import org.junit.jupiter.api.extension.RegisterExtension
import java.net.URI

class KtorHttpClientTest : AbstractHttpClientTest<HttpRequestBuilder>() {

override fun buildRequest(requestMethod: String, uri: URI, requestHeaders: MutableMap<String, String>) =
HttpRequestBuilder(uri.toURL()).apply {
method = HttpMethod.parse(requestMethod)

requestHeaders.forEach { (header, value) -> headers.append(header, value) }
}

override fun sendRequest(request: HttpRequestBuilder, method: String, uri: URI, headers: MutableMap<String, String>) = runBlocking {
CLIENT.request(request).status.value
}

override fun sendRequestWithCallback(
request: HttpRequestBuilder,
method: String,
uri: URI,
headers: MutableMap<String, String>,
httpClientResult: HttpClientResult,
) {
CoroutineScope(Dispatchers.Default + Context.current().asContextElement()).launch {
try {
val statusCode = CLIENT.request(request).status.value
httpClientResult.complete(statusCode)
} catch (e: Throwable) {
httpClientResult.complete(e)
}
}
}

override fun configure(optionsBuilder: HttpClientTestOptions.Builder) {
with(optionsBuilder) {
disableTestReadTimeout()
// this instrumentation creates a span per each physical request
// related issue https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/5722
disableTestRedirects()

setHttpAttributes { DEFAULT_HTTP_ATTRIBUTES - setOf(SemanticAttributes.NET_PROTOCOL_NAME, SemanticAttributes.NET_PROTOCOL_VERSION) }

setSingleConnectionFactory { host, port ->
KtorHttpClientSingleConnection(host, port) { installTracing() }
}
}
}
class KtorHttpClientTest : AbstractKtorHttpClientTest() {

companion object {
@JvmStatic
@RegisterExtension
private val TESTING = HttpClientInstrumentationExtension.forLibrary()
}

private val CLIENT = HttpClient(CIO) {
install(HttpRedirect)

installTracing()
}

private fun HttpClientConfig<*>.installTracing() {
install(KtorClientTracing) {
setOpenTelemetry(TESTING.openTelemetry)
setCapturedRequestHeaders(listOf(AbstractHttpClientTest.TEST_REQUEST_HEADER))
setCapturedResponseHeaders(listOf(AbstractHttpClientTest.TEST_RESPONSE_HEADER))
}
override fun HttpClientConfig<*>.installTracing() {
install(KtorClientTracing) {
setOpenTelemetry(TESTING.openTelemetry)
setCapturedRequestHeaders(listOf(TEST_REQUEST_HEADER))
setCapturedResponseHeaders(listOf(TEST_RESPONSE_HEADER))
}
}
}
Loading