diff --git a/README.md b/README.md index b458774c..76ad5fb4 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ note on [Docs and Samples Migration](https://blog.jetbrains.com/ktor/2020/09/16/ * [postgres](postgres/README.md) - An application for creating, editing and deleting articles that uses Postgres database running on Docker image as a storage. * [mongodb](mongodb/README.md) - An application for creating, editing and deleting articles that uses Mongodb running on Docker image as a storage. * [mvc-web](mvc-web/README.md) - An application for adding and removing wishes to wishlist that uses [FreeMarker](https://ktor.io/docs/freemarker.html) templates and Exposed. +* [opentelemetry](opentelemetry/README.md) - An application that uses Kotlin DSL to work with OpenTelemetry Ktor plugins. ## Server diff --git a/opentelemetry/README.md b/opentelemetry/README.md new file mode 100644 index 00000000..70e0e8ad --- /dev/null +++ b/opentelemetry/README.md @@ -0,0 +1,87 @@ +# OpenTelemetry-Ktor Demo + +[OpenTelemetry](https://opentelemetry.io/) provides support for Ktor with the `KtorClientTracing`and `KtorServerTracing` +plugins for the Ktor client and server respectively. For the source code, see +the [repository on GitHub](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation/ktor). + +This project contains extension functions for plugins that allow you to write code in the Ktor DSL style. + +Take the following code as an example: + +```kotlin +install(KtorServerTracing) { + ... + addAttributeExtractor( + object : AttributesExtractor { + override fun onEnd( + attributes: AttributesBuilder, + context: Context, + request: ApplicationRequest, + response: ApplicationResponse?, + error: Throwable? + ) { + attributes.put("end-time", Instant.now().toEpochMilli()) + } + } + ) + ... +} +``` + +Rewritten in Ktor DSL style, it looks like the following: + +```kotlin +install(KtorServerTracing) { + ... + attributeExtractor { + onEnd { + attributes.put("end-time", Instant.now().toEpochMilli()) + } + } + ... +} +``` + +You can find all extensions for the client plugin `KtorClientTracing` in +the [extractions](./client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/) folder. \ +And you can find all extensions for the server plugin `KtorServerTracing` in +the [extractions](./server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/) folder. + +## Running + +**Note:** You need to have [Docker](https://www.docker.com/) installed and running to run the sample. + +To run this sample, execute the following command from the `opentelemetry` directory:: + +```bash +./gradlew :runWithDocker +``` + +It will start a `Jaeger` in the docker container (`Jaeger UI` available on http://localhost:16686/search) and +then it will start a `server` on http://localhost:8080/ + +Then, to run the client, which will send requests to a server, you can execute the following command in +an `opentelemetry` directory: + +```bash +./gradlew :client:run +``` + +**Note:** In this example, we use +an [Autoconfiguration OpenTelemetry instance](https://opentelemetry.io/docs/languages/java/instrumentation/#automatic-configuration), +we set environment variables `OTEL_METRICS_EXPORTER` and `OTEL_EXPORTER_OTLP_ENDPOINT` +in [build.gradle.kts](./build.gradle.kts) file. +You can find more information about these environment variables +in the [OpenTelemetry documentation](https://opentelemetry.io/docs/languages/sdk-configuration/). + +Let's check what we will see in the `Jaeger UI` after running the server (with Docker) and the client: + +1. We can see two our services that send opentelemetry data: `opentelemetry-ktor-sample-server` + and `opentelemetry-ktor-sample-client`, and service `jaeger-all-in-one`, it's `Jaeger` tracing some of + its components: + ![img.png](images/1.png) +2. If you select `opentelemetry-ktor-sample-server` service and click on **Find traces**, you will see a list of traces: + ![img.png](images/2.png) +3. If you click on one of those traces, you will be navigated to a screen providing detailed information about the + selected trace: + ![img.png](images/3.png) diff --git a/opentelemetry/build.gradle.kts b/opentelemetry/build.gradle.kts new file mode 100644 index 00000000..0b495970 --- /dev/null +++ b/opentelemetry/build.gradle.kts @@ -0,0 +1,32 @@ +description = "OpenTelemetry-Ktor example" + +plugins { + id("com.avast.gradle.docker-compose") version "0.14.0" +} + +subprojects { + group = "opentelemetry.ktor.example" + version = "0.0.1" + + repositories { + mavenCentral() + } +} + +dockerCompose { + useComposeFiles.add("docker/docker-compose.yml") +} + +tasks.register("runWithDocker") { + dependsOn("composeUp", ":server:run") +} + +project(":server").setEnvironmentVariablesForOpenTelemetry() +project(":client").setEnvironmentVariablesForOpenTelemetry() + +fun Project.setEnvironmentVariablesForOpenTelemetry() { + tasks.withType { + environment("OTEL_METRICS_EXPORTER", "none") + environment("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317/") + } +} \ No newline at end of file diff --git a/opentelemetry/client/build.gradle.kts b/opentelemetry/client/build.gradle.kts new file mode 100644 index 00000000..5280155a --- /dev/null +++ b/opentelemetry/client/build.gradle.kts @@ -0,0 +1,28 @@ +val ktor_version: String by project +val logback_version: String by project +val kotlin_version: String by project +val opentelemetry_version: String by project + +plugins { + kotlin("jvm") version "1.9.21" + id("io.ktor.plugin") version "2.3.8" + id("application") +} + +application { + mainClass.set("opentelemetry.ktor.example.ClientKt") + + val isDevelopment: Boolean = project.ext.has("development") + applicationDefaultJvmArgs = listOf("-Dio.ktor.development=$isDevelopment") +} + +dependencies { + implementation(project(":shared")) + + implementation("io.ktor:ktor-client-core-jvm") + implementation("io.ktor:ktor-client-cio-jvm") + implementation("io.ktor:ktor-client-websockets:$ktor_version") + implementation("ch.qos.logback:logback-classic:$logback_version") + + implementation("io.opentelemetry.instrumentation:opentelemetry-ktor-2.0:$opentelemetry_version-alpha") +} \ No newline at end of file diff --git a/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/Client.kt b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/Client.kt new file mode 100644 index 00000000..aeaf0e19 --- /dev/null +++ b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/Client.kt @@ -0,0 +1,21 @@ +package opentelemetry.ktor.example + +import io.ktor.client.* +import io.ktor.client.engine.cio.* +import io.ktor.client.plugins.* +import io.ktor.client.plugins.websocket.* +import opentelemetry.ktor.example.plugins.opentelemetry.setupClientTelemetry + +suspend fun main() { + val client = HttpClient(CIO) { + install(WebSockets) + + defaultRequest { + url("http://$SERVER_HOST:$SERVER_PORT") + } + + setupClientTelemetry() + } + + doRequests(client) +} diff --git a/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/Requests.kt b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/Requests.kt new file mode 100644 index 00000000..97f6d5ae --- /dev/null +++ b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/Requests.kt @@ -0,0 +1,43 @@ +package opentelemetry.ktor.example + +import io.ktor.client.* +import io.ktor.client.plugins.websocket.* +import io.ktor.client.request.* +import io.ktor.websocket.* + + +suspend fun doRequests(client: HttpClient) { + // For this request you can see `CUSTOM` method instead of default `HTTP` in the Jaeger UI + client.request("/known-methods") { + method = CUSTOM_METHOD + } + + // For this request you can't see `CUSTOM_NOT_KNOWN` method, you can see default `HTTP` in the Jaeger UI + client.request("/known-methods") { + method = CUSTOM_METHOD_NOT_KNOWN + } + + // You can see tags `http.request.header.accept` and `http.response.header.content_type` for all requests + // in the Jaeger UI and also `http.response.header.custom_header` for this request + client.get("/captured-headers") + + // For this request you can see tag `error=true` and `Error` icon only for server trace in the Jaeger UI + client.get("/span-status-extractor") + + // For this request you can see tag `span.kind=producer` only for server trace in the Jaeger UI + client.post("/span-kind-extractor") + + // You can see attribute `start-time` and `end-time` in the Jaeger UI for all requests + client.get("/attribute-extractor") + + // For this request you can see several spans and events only for server trace in the Jaeger UI + client.get("/opentelemetry/tracer") + + // For this request you can see several events only for server trace in the Jaeger UI + client.ws("/opentelemetry/websocket") { + send(Frame.Text("Hello, world!")) + repeat(10) { + send(incoming.receive()) + } + } +} \ No newline at end of file diff --git a/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/attributeExtractor.kt b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/attributeExtractor.kt new file mode 100644 index 00000000..6c77363f --- /dev/null +++ b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/attributeExtractor.kt @@ -0,0 +1,69 @@ +package opentelemetry.ktor.example.plugins.opentelemetry.extractions + +import io.ktor.client.request.* +import io.ktor.client.statement.* +import io.opentelemetry.api.common.AttributesBuilder +import io.opentelemetry.context.Context +import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor +import io.opentelemetry.instrumentation.ktor.v2_0.client.KtorClientTracingBuilder + +// addAttributeExtractor +fun KtorClientTracingBuilder.attributeExtractor( + extractorBuilder: ExtractorBuilder.() -> Unit = {} +) { + val builder = ExtractorBuilder().apply(extractorBuilder).build() + addAttributesExtractors( + object : AttributesExtractor { + override fun onStart( + attributes: AttributesBuilder, + parentContext: Context, + request: HttpRequestData + ) { + builder.onStart(OnStartData(attributes, parentContext, request)) + } + + override fun onEnd( + attributes: AttributesBuilder, + context: Context, + request: HttpRequestData, + response: HttpResponse?, + error: Throwable? + ) { + builder.onEnd(OnEndData(attributes, context, request, response, error)) + } + } + ) +} + +class ExtractorBuilder { + private var onStart: OnStartData.() -> Unit = {} + private var onEnd: OnEndData.() -> Unit = {} + + fun onStart(block: OnStartData.() -> Unit) { + onStart = block + } + + fun onEnd(block: OnEndData.() -> Unit) { + onEnd = block + } + + internal fun build(): Extractor { + return Extractor(onStart, onEnd) + } +} + +internal class Extractor(val onStart: OnStartData.() -> Unit, val onEnd: OnEndData.() -> Unit) + +data class OnStartData( + val attributes: AttributesBuilder, + val parentContext: Context, + val request: HttpRequestData +) + +data class OnEndData( + val attributes: AttributesBuilder, + val parentContext: Context, + val request: HttpRequestData, + val response: HttpResponse?, + val error: Throwable? +) \ No newline at end of file diff --git a/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/capturedHeaders.kt b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/capturedHeaders.kt new file mode 100644 index 00000000..de3cdcef --- /dev/null +++ b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/capturedHeaders.kt @@ -0,0 +1,21 @@ +package opentelemetry.ktor.example.plugins.opentelemetry.extractions + +import io.opentelemetry.instrumentation.ktor.v2_0.client.KtorClientTracingBuilder + +// setCapturedRequestHeaders +fun KtorClientTracingBuilder.capturedRequestHeaders(vararg headers: String) { + capturedRequestHeaders(headers.asIterable()) +} + +fun KtorClientTracingBuilder.capturedRequestHeaders(headers: Iterable) { + setCapturedRequestHeaders(headers.toList()) +} + +// setCapturedResponseHeaders +fun KtorClientTracingBuilder.capturedResponseHeaders(vararg headers: String) { + capturedResponseHeaders(headers.asIterable()) +} + +fun KtorClientTracingBuilder.capturedResponseHeaders(headers: Iterable) { + setCapturedResponseHeaders(headers.toList()) +} \ No newline at end of file diff --git a/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/emitExperimentalHttpClientMetrics.kt b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/emitExperimentalHttpClientMetrics.kt new file mode 100644 index 00000000..74743153 --- /dev/null +++ b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/emitExperimentalHttpClientMetrics.kt @@ -0,0 +1,8 @@ +package opentelemetry.ktor.example.plugins.opentelemetry.extractions + +import io.opentelemetry.instrumentation.ktor.v2_0.client.KtorClientTracingBuilder + +// setEmitExperimentalHttpClientMetrics +fun KtorClientTracingBuilder.emitExperimentalHttpClientMetrics() { + setEmitExperimentalHttpClientMetrics(true) +} \ No newline at end of file diff --git a/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/knownMethods.kt b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/knownMethods.kt new file mode 100644 index 00000000..7a86d298 --- /dev/null +++ b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/knownMethods.kt @@ -0,0 +1,13 @@ +package opentelemetry.ktor.example.plugins.opentelemetry.extractions + +import io.ktor.http.* +import io.opentelemetry.instrumentation.ktor.v2_0.client.KtorClientTracingBuilder + +// setKnownMethods +fun KtorClientTracingBuilder.knownMethods(vararg methods: HttpMethod) { + knownMethods(methods.asIterable()) +} + +fun KtorClientTracingBuilder.knownMethods(methods: Iterable) { + setKnownMethods(methods.map { it.value }.toSet()) +} \ No newline at end of file diff --git a/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/setupClientTelemetry.kt b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/setupClientTelemetry.kt new file mode 100644 index 00000000..e41c7792 --- /dev/null +++ b/opentelemetry/client/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/setupClientTelemetry.kt @@ -0,0 +1,36 @@ +package opentelemetry.ktor.example.plugins.opentelemetry + +import io.ktor.client.* +import io.ktor.client.engine.cio.* +import io.ktor.http.* +import io.opentelemetry.instrumentation.ktor.v2_0.client.KtorClientTracing +import opentelemetry.ktor.example.CUSTOM_HEADER +import opentelemetry.ktor.example.CUSTOM_METHOD +import opentelemetry.ktor.example.getOpenTelemetry +import opentelemetry.ktor.example.plugins.opentelemetry.extractions.* + +/** + * Install OpenTelemetry on the client. + * You can see usages of new extension functions for [KtorClientTracing]. + */ +fun HttpClientConfig.setupClientTelemetry() { + val openTelemetry = getOpenTelemetry(serviceName = "opentelemetry-ktor-sample-client") + install(KtorClientTracing) { + setOpenTelemetry(openTelemetry) + + emitExperimentalHttpClientMetrics() + + knownMethods(HttpMethod.DefaultMethods + CUSTOM_METHOD) + capturedRequestHeaders(HttpHeaders.Accept) + capturedResponseHeaders(HttpHeaders.ContentType, CUSTOM_HEADER) + + attributeExtractor { + onStart { + attributes.put("start-time", System.currentTimeMillis()) + } + onEnd { + attributes.put("end-time", System.currentTimeMillis()) + } + } + } +} \ No newline at end of file diff --git a/opentelemetry/docker/docker-compose.yml b/opentelemetry/docker/docker-compose.yml new file mode 100644 index 00000000..db8a5c90 --- /dev/null +++ b/opentelemetry/docker/docker-compose.yml @@ -0,0 +1,8 @@ +# This file is used to start the Jaeger all-in-one container +version: '3.7' +services: + jaeger: + image: jaegertracing/all-in-one:latest + ports: + - "4317:4317" # OTLP gRPC receiver + - "16686:16686" # Jaeger UI \ No newline at end of file diff --git a/opentelemetry/gradle.properties b/opentelemetry/gradle.properties new file mode 100644 index 00000000..4ce0f15c --- /dev/null +++ b/opentelemetry/gradle.properties @@ -0,0 +1,7 @@ +ktor_version=2.3.8 +kotlin_version=1.9.21 +logback_version=1.4.11 +kotlin.code.style=official + +opentelemetry_version=1.32.0 +opentelemetry_semconv_version=1.21.0-alpha \ No newline at end of file diff --git a/opentelemetry/gradle/wrapper/gradle-wrapper.jar b/opentelemetry/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7454180f Binary files /dev/null and b/opentelemetry/gradle/wrapper/gradle-wrapper.jar differ diff --git a/opentelemetry/gradle/wrapper/gradle-wrapper.properties b/opentelemetry/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..e411586a --- /dev/null +++ b/opentelemetry/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/opentelemetry/gradlew b/opentelemetry/gradlew new file mode 100755 index 00000000..1b6c7873 --- /dev/null +++ b/opentelemetry/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/opentelemetry/gradlew.bat b/opentelemetry/gradlew.bat new file mode 100644 index 00000000..107acd32 --- /dev/null +++ b/opentelemetry/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/opentelemetry/images/1.png b/opentelemetry/images/1.png new file mode 100644 index 00000000..f9a3ed8e Binary files /dev/null and b/opentelemetry/images/1.png differ diff --git a/opentelemetry/images/2.png b/opentelemetry/images/2.png new file mode 100644 index 00000000..8e4bf57f Binary files /dev/null and b/opentelemetry/images/2.png differ diff --git a/opentelemetry/images/3.png b/opentelemetry/images/3.png new file mode 100644 index 00000000..ca9235b5 Binary files /dev/null and b/opentelemetry/images/3.png differ diff --git a/opentelemetry/server/build.gradle.kts b/opentelemetry/server/build.gradle.kts new file mode 100644 index 00000000..0fc3242e --- /dev/null +++ b/opentelemetry/server/build.gradle.kts @@ -0,0 +1,27 @@ +val ktor_version: String by project +val kotlin_version: String by project +val opentelemetry_version: String by project +val logback_version: String by project + +plugins { + kotlin("jvm") version "1.9.21" + id("io.ktor.plugin") version "2.3.8" + id("application") +} + +application { + mainClass.set("opentelemetry.ktor.example.ServerKt") + + val isDevelopment: Boolean = project.ext.has("development") + applicationDefaultJvmArgs = listOf("-Dio.ktor.development=$isDevelopment") +} + +dependencies { + implementation(project(":shared")) + + implementation("io.ktor:ktor-server-cio-jvm") + implementation("io.ktor:ktor-server-websockets:$ktor_version") + implementation("ch.qos.logback:logback-classic:$logback_version") + + implementation("io.opentelemetry.instrumentation:opentelemetry-ktor-2.0:$opentelemetry_version-alpha") +} \ No newline at end of file diff --git a/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/Server.kt b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/Server.kt new file mode 100644 index 00000000..498a384a --- /dev/null +++ b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/Server.kt @@ -0,0 +1,15 @@ +package opentelemetry.ktor.example + +import io.ktor.server.application.* +import io.ktor.server.cio.* +import io.ktor.server.engine.* +import opentelemetry.ktor.example.plugins.routing.configureRouting + +fun main() { + embeddedServer(CIO, port = 8080, host = "0.0.0.0", module = Application::module) + .start(wait = true) +} + +fun Application.module() { + configureRouting() +} diff --git a/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/attributeExtractor.kt b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/attributeExtractor.kt new file mode 100644 index 00000000..b17a01f0 --- /dev/null +++ b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/attributeExtractor.kt @@ -0,0 +1,65 @@ +package opentelemetry.ktor.example.plugins.opentelemetry.extractions + +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.opentelemetry.api.common.AttributesBuilder +import io.opentelemetry.context.Context +import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor +import io.opentelemetry.instrumentation.ktor.v2_0.server.KtorServerTracing + +// addAttributeExtractor +fun KtorServerTracing.Configuration.attributeExtractor( + extractorBuilder: ExtractorBuilder.() -> Unit = {} +) { + val builder = ExtractorBuilder().apply(extractorBuilder).build() + addAttributeExtractor( + object : AttributesExtractor { + override fun onStart(attributes: AttributesBuilder, parentContext: Context, request: ApplicationRequest) { + builder.onStart(OnStartData(attributes, parentContext, request)) + } + + override fun onEnd( + attributes: AttributesBuilder, + context: Context, + request: ApplicationRequest, + response: ApplicationResponse?, + error: Throwable? + ) { + builder.onEnd(OnEndData(attributes, context, request, response, error)) + } + } + ) +} + +class ExtractorBuilder { + private var onStart: OnStartData.() -> Unit = {} + private var onEnd: OnEndData.() -> Unit = {} + + fun onStart(block: OnStartData.() -> Unit) { + onStart = block + } + + fun onEnd(block: OnEndData.() -> Unit) { + onEnd = block + } + + internal fun build(): Extractor { + return Extractor(onStart, onEnd) + } +} + +internal class Extractor(val onStart: OnStartData.() -> Unit, val onEnd: OnEndData.() -> Unit) + +data class OnStartData( + val attributes: AttributesBuilder, + val parentContext: Context, + val request: ApplicationRequest +) + +data class OnEndData( + val attributes: AttributesBuilder, + val parentContext: Context, + val request: ApplicationRequest, + val response: ApplicationResponse?, + val error: Throwable? +) \ No newline at end of file diff --git a/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/capturedHeaders.kt b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/capturedHeaders.kt new file mode 100644 index 00000000..523b0d61 --- /dev/null +++ b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/capturedHeaders.kt @@ -0,0 +1,21 @@ +package opentelemetry.ktor.example.plugins.opentelemetry.extractions + +import io.opentelemetry.instrumentation.ktor.v2_0.server.KtorServerTracing + +// setCapturedRequestHeaders +fun KtorServerTracing.Configuration.capturedRequestHeaders(vararg headers: String) { + capturedRequestHeaders(headers.asIterable()) +} + +fun KtorServerTracing.Configuration.capturedRequestHeaders(headers: Iterable) { + setCapturedRequestHeaders(headers.toList()) +} + +// setCapturedResponseHeaders +fun KtorServerTracing.Configuration.capturedResponseHeaders(vararg headers: String) { + capturedResponseHeaders(headers.asIterable()) +} + +fun KtorServerTracing.Configuration.capturedResponseHeaders(headers: Iterable) { + setCapturedResponseHeaders(headers.toList()) +} \ No newline at end of file diff --git a/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/knownMethods.kt b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/knownMethods.kt new file mode 100644 index 00000000..ebae1183 --- /dev/null +++ b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/knownMethods.kt @@ -0,0 +1,13 @@ +package opentelemetry.ktor.example.plugins.opentelemetry.extractions + +import io.ktor.http.* +import io.opentelemetry.instrumentation.ktor.v2_0.server.KtorServerTracing + +// setKnownMethods +fun KtorServerTracing.Configuration.knownMethods(vararg methods: HttpMethod) { + knownMethods(methods.asIterable()) +} + +fun KtorServerTracing.Configuration.knownMethods(methods: Iterable) { + setKnownMethods(methods.map { it.value }.toSet()) +} \ No newline at end of file diff --git a/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/spanKindExtractor.kt b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/spanKindExtractor.kt new file mode 100644 index 00000000..6c5fe63f --- /dev/null +++ b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/spanKindExtractor.kt @@ -0,0 +1,15 @@ +package opentelemetry.ktor.example.plugins.opentelemetry.extractions + +import io.ktor.server.request.* +import io.opentelemetry.api.trace.SpanKind +import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor +import io.opentelemetry.instrumentation.ktor.v2_0.server.KtorServerTracing + +// setSpanKindExtractor +fun KtorServerTracing.Configuration.spanKindExtractor(extract: ApplicationRequest.() -> SpanKind) { + setSpanKindExtractor { + SpanKindExtractor { request: ApplicationRequest -> + extract(request) + } + } +} \ No newline at end of file diff --git a/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/spanStatusExtractor.kt b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/spanStatusExtractor.kt new file mode 100644 index 00000000..92a49001 --- /dev/null +++ b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/extractions/spanStatusExtractor.kt @@ -0,0 +1,26 @@ +package opentelemetry.ktor.example.plugins.opentelemetry.extractions + +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusBuilder +import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor +import io.opentelemetry.instrumentation.ktor.v2_0.server.KtorServerTracing + +// setStatusExtractor +fun KtorServerTracing.Configuration.spanStatusExtractor(extract: SpanStatusData.() -> Unit) { + setStatusExtractor { + SpanStatusExtractor { spanStatusBuilder: SpanStatusBuilder, + request: ApplicationRequest, + response: ApplicationResponse?, + throwable: Throwable? -> + extract(SpanStatusData(spanStatusBuilder, request, response, throwable)) + } + } +} + +data class SpanStatusData( + val spanStatusBuilder: SpanStatusBuilder, + val request: ApplicationRequest, + val response: ApplicationResponse?, + val error: Throwable? +) \ No newline at end of file diff --git a/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/setupServerTelemetry.kt b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/setupServerTelemetry.kt new file mode 100644 index 00000000..b46d5b7d --- /dev/null +++ b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/opentelemetry/setupServerTelemetry.kt @@ -0,0 +1,57 @@ +package opentelemetry.ktor.example.plugins.opentelemetry + +import io.ktor.http.* +import io.ktor.server.application.* +import io.ktor.server.request.* +import io.opentelemetry.api.OpenTelemetry +import io.opentelemetry.api.trace.SpanKind +import io.opentelemetry.api.trace.StatusCode +import io.opentelemetry.instrumentation.ktor.v2_0.server.KtorServerTracing +import opentelemetry.ktor.example.CUSTOM_HEADER +import opentelemetry.ktor.example.CUSTOM_METHOD +import opentelemetry.ktor.example.getOpenTelemetry +import opentelemetry.ktor.example.plugins.opentelemetry.extractions.* +import java.time.Instant + +const val serviceName = "opentelemetry-ktor-sample-server" + +/** + * Install OpenTelemetry on the server. + * You can see usages of new extension functions for [KtorServerTracing]. + */ +fun Application.setupServerTelemetry(): OpenTelemetry { + val openTelemetry = getOpenTelemetry(serviceName) + install(KtorServerTracing) { + setOpenTelemetry(openTelemetry) + + knownMethods(HttpMethod.DefaultMethods + CUSTOM_METHOD) + capturedRequestHeaders(HttpHeaders.UserAgent) + capturedResponseHeaders(HttpHeaders.ContentType, CUSTOM_HEADER) + + spanStatusExtractor { + val path = response?.call?.request?.path() ?: "" + if (path.contains("/span-status-extractor") || error != null) { + spanStatusBuilder.setStatus(StatusCode.ERROR) + } + } + + spanKindExtractor { + if (httpMethod == HttpMethod.Post) { + SpanKind.PRODUCER + } else { + SpanKind.CLIENT + } + } + + attributeExtractor { + onStart { + attributes.put("start-time", System.currentTimeMillis()) + } + onEnd { + attributes.put("end-time", Instant.now().toEpochMilli()) + } + } + } + + return openTelemetry +} diff --git a/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/routing/Routing.kt b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/routing/Routing.kt new file mode 100644 index 00000000..aec46c80 --- /dev/null +++ b/opentelemetry/server/src/main/kotlin/opentelemetry/ktor/example/plugins/routing/Routing.kt @@ -0,0 +1,102 @@ +package opentelemetry.ktor.example.plugins.routing + +import io.ktor.server.application.* +import io.ktor.server.response.* +import io.ktor.server.routing.* +import io.ktor.server.websocket.* +import io.ktor.websocket.* +import io.opentelemetry.api.trace.Span +import kotlinx.coroutines.delay +import opentelemetry.ktor.example.CUSTOM_HEADER +import opentelemetry.ktor.example.CUSTOM_METHOD +import opentelemetry.ktor.example.CUSTOM_METHOD_NOT_KNOWN +import opentelemetry.ktor.example.plugins.opentelemetry.serviceName +import opentelemetry.ktor.example.plugins.opentelemetry.setupServerTelemetry + +fun Application.configureRouting() { + install(WebSockets) + + val openTelemetry = setupServerTelemetry() + + routing { + get("/") { + call.respondText("Hello World!") + } + + route("/known-methods") { + method(CUSTOM_METHOD) { + handle { + call.respondText( + "For this request you can see `CUSTOM` method instead of default `HTTP` in the Jaeger UI" + ) + } + } + + method(CUSTOM_METHOD_NOT_KNOWN) { + handle { + call.respondText( + "For this request you can't see `CUSTOM_NOT_KNOWN` method, " + + "you can see default `HTTP` in the Jaeger UI" + ) + } + } + } + + get("/captured-headers") { + call.response.headers.append(CUSTOM_HEADER, "it's a custom value") + call.respondText( + "You can see tags `http.request.header.user_agent` and `http.response.header.content_type` for " + + "all requests in the Jaeger UI and also `http.response.header.custom_header` for this request" + ) + } + + get("/span-status-extractor") { + call.respond("For this request you can see tag `error=true` and `Error` icon in the Jaeger UI") + } + + post("/span-kind-extractor") { + call.respond("For this request you can see tag `span.kind=producer` in the Jaeger UI") + } + + get("/attribute-extractor") { + call.respondText("For this request you can see attribute `start-time` and `end-time` in the Jaeger UI") + } + + + val tracer = openTelemetry.getTracer(serviceName) + val meter = openTelemetry.getMeter(serviceName) + route("/opentelemetry") { + get("/tracer") { + val span = tracer.spanBuilder("/trace doWork").startSpan() + try { + span.makeCurrent().use { _ -> + Span.current().addEvent("Starting the work") + call.respondText { "For this request you can see several spans and events in the Jaeger UI" } + Span.current().addEvent("Finished working") + } + } finally { + span.end() + } + } + + + webSocket("/websocket") { + val span = tracer.spanBuilder("/websocket-server").startSpan() + val counter = meter.counterBuilder("/websocket-server").build() + try { + repeat(10) { + span.makeCurrent().use { _ -> + Span.current().addEvent("$it") + val frame = incoming.receive() as Frame.Text + counter.add(1) + outgoing.send(frame) + } + } + } finally { + delay(100) + span.end() + } + } + } + } +} \ No newline at end of file diff --git a/opentelemetry/settings.gradle.kts b/opentelemetry/settings.gradle.kts new file mode 100644 index 00000000..dd788336 --- /dev/null +++ b/opentelemetry/settings.gradle.kts @@ -0,0 +1,5 @@ +rootProject.name = "opentelemetry-ktor-sample" + +include(":server") +include(":client") +include(":shared") \ No newline at end of file diff --git a/opentelemetry/shared/build.gradle.kts b/opentelemetry/shared/build.gradle.kts new file mode 100644 index 00000000..26c657b9 --- /dev/null +++ b/opentelemetry/shared/build.gradle.kts @@ -0,0 +1,15 @@ +val opentelemetry_version: String by project +val opentelemetry_semconv_version: String by project + +plugins { + kotlin("jvm") version "1.9.21" + id("io.ktor.plugin") version "2.3.8" +} + +dependencies { + implementation("io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:$opentelemetry_version"); + implementation("io.opentelemetry:opentelemetry-exporter-otlp:$opentelemetry_version"); + implementation("io.opentelemetry.semconv:opentelemetry-semconv:$opentelemetry_semconv_version") + + implementation("io.ktor:ktor-server-core-jvm") +} \ No newline at end of file diff --git a/opentelemetry/shared/src/main/kotlin/opentelemetry/ktor/example/constants.kt b/opentelemetry/shared/src/main/kotlin/opentelemetry/ktor/example/constants.kt new file mode 100644 index 00000000..2c9b8273 --- /dev/null +++ b/opentelemetry/shared/src/main/kotlin/opentelemetry/ktor/example/constants.kt @@ -0,0 +1,13 @@ +package opentelemetry.ktor.example + +import io.ktor.http.* + +const val SERVER_HOST = "0.0.0.0" +const val SERVER_PORT = 8080 + +// Custom HTTP methods +val CUSTOM_METHOD = HttpMethod("CUSTOM") +val CUSTOM_METHOD_NOT_KNOWN = HttpMethod("CUSTOM_NOT_KNOWN") + +// Custom HTTP headers +const val CUSTOM_HEADER = "Custom-Header" diff --git a/opentelemetry/shared/src/main/kotlin/opentelemetry/ktor/example/utils.kt b/opentelemetry/shared/src/main/kotlin/opentelemetry/ktor/example/utils.kt new file mode 100644 index 00000000..a6055a9c --- /dev/null +++ b/opentelemetry/shared/src/main/kotlin/opentelemetry/ktor/example/utils.kt @@ -0,0 +1,14 @@ +package opentelemetry.ktor.example + +import io.opentelemetry.api.OpenTelemetry +import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk +import io.opentelemetry.semconv.ResourceAttributes + +fun getOpenTelemetry(serviceName: String): OpenTelemetry { + return AutoConfiguredOpenTelemetrySdk.builder().addResourceCustomizer { oldResource, _ -> + oldResource.toBuilder() + .putAll(oldResource.attributes) + .put(ResourceAttributes.SERVICE_NAME, serviceName) + .build() + }.build().openTelemetrySdk +} \ No newline at end of file