|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package io.opentelemetry.javaagent.instrumentation.activejhttp; |
| 7 | + |
| 8 | +import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext; |
| 9 | +import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.hasSuperType; |
| 10 | +import static io.opentelemetry.javaagent.instrumentation.activejhttp.ActiveJHttpServerConnectionSingletons.instrumenter; |
| 11 | +import static net.bytebuddy.matcher.ElementMatchers.isInterface; |
| 12 | +import static net.bytebuddy.matcher.ElementMatchers.isMethod; |
| 13 | +import static net.bytebuddy.matcher.ElementMatchers.named; |
| 14 | +import static net.bytebuddy.matcher.ElementMatchers.not; |
| 15 | +import static net.bytebuddy.matcher.ElementMatchers.takesArgument; |
| 16 | +import static net.bytebuddy.matcher.ElementMatchers.takesArguments; |
| 17 | + |
| 18 | +import io.activej.http.AsyncServlet; |
| 19 | +import io.activej.http.HttpHeaders; |
| 20 | +import io.activej.http.HttpRequest; |
| 21 | +import io.activej.http.HttpResponse; |
| 22 | +import io.activej.promise.Promise; |
| 23 | +import io.opentelemetry.api.trace.Span; |
| 24 | +import io.opentelemetry.context.Context; |
| 25 | +import io.opentelemetry.context.Scope; |
| 26 | +import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation; |
| 27 | +import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer; |
| 28 | +import net.bytebuddy.asm.Advice; |
| 29 | +import net.bytebuddy.description.type.TypeDescription; |
| 30 | +import net.bytebuddy.matcher.ElementMatcher; |
| 31 | + |
| 32 | +/** |
| 33 | + * This class provides instrumentation for ActiveJ HTTP server connections by applying advice to the |
| 34 | + * {@code serve} method of classes that extend {@code io.activej.http.AsyncServlet}. The |
| 35 | + * instrumentation is designed to integrate with OpenTelemetry for distributed tracing, capturing |
| 36 | + * and propagating trace context through HTTP requests and responses. |
| 37 | + * |
| 38 | + * @author Krishna Chaitanya Surapaneni |
| 39 | + */ |
| 40 | +public class ActiveJHttpServerConnectionInstrumentation implements TypeInstrumentation { |
| 41 | + |
| 42 | + /** |
| 43 | + * Matches classes that extend {@code io.activej.http.AsyncServlet} but are not interfaces. |
| 44 | + * |
| 45 | + * @return An {@code ElementMatcher} that identifies target classes for instrumentation. |
| 46 | + */ |
| 47 | + @Override |
| 48 | + public ElementMatcher<TypeDescription> typeMatcher() { |
| 49 | + return hasSuperType(named("io.activej.http.AsyncServlet")).and(not(isInterface())); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Applies advice to the {@code serve} method of the matched classes. The advice captures trace |
| 54 | + * context at the start of the method and propagates it through the response. |
| 55 | + * |
| 56 | + * @param transformer The {@code TypeTransformer} used to apply the advice. |
| 57 | + */ |
| 58 | + @Override |
| 59 | + public void transform(TypeTransformer transformer) { |
| 60 | + transformer.applyAdviceToMethod( |
| 61 | + isMethod() |
| 62 | + .and(named("serve")) |
| 63 | + .and(takesArguments(1).and(takesArgument(0, named("io.activej.http.HttpRequest")))), |
| 64 | + this.getClass().getName() + "$ServeAdvice"); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Inner class containing the advice logic for the {@code serve} method. This class defines two |
| 69 | + * methods: |
| 70 | + * |
| 71 | + * <ul> |
| 72 | + * <li>{@code methodEnter}: Captures the trace context at the start of the method. |
| 73 | + * <li>{@code methodExit}: Propagates the trace context to the response and ends the span. |
| 74 | + * </ul> |
| 75 | + */ |
| 76 | + @SuppressWarnings("unused") |
| 77 | + public static class ServeAdvice { |
| 78 | + |
| 79 | + /** |
| 80 | + * Advice executed at the start of the {@code serve} method. Captures the current trace context |
| 81 | + * and starts a new span if tracing is enabled for the request. |
| 82 | + * |
| 83 | + * @param asyncServlet The {@code AsyncServlet} instance handling the request. |
| 84 | + * @param request The incoming HTTP request. |
| 85 | + * @param context Local variable to store the OpenTelemetry context. |
| 86 | + * @param scope Local variable to store the OpenTelemetry scope. |
| 87 | + * @param httpRequest Local variable to store the HTTP request. |
| 88 | + */ |
| 89 | + @Advice.OnMethodEnter(suppress = Throwable.class) |
| 90 | + public static void methodEnter( |
| 91 | + @Advice.This AsyncServlet asyncServlet, |
| 92 | + @Advice.Argument(0) HttpRequest request, |
| 93 | + @Advice.Local("otelContext") Context context, |
| 94 | + @Advice.Local("otelScope") Scope scope, |
| 95 | + @Advice.Local("httpRequest") HttpRequest httpRequest) { |
| 96 | + Context parentContext = currentContext(); |
| 97 | + httpRequest = request; |
| 98 | + if (!instrumenter().shouldStart(parentContext, request)) { |
| 99 | + return; |
| 100 | + } |
| 101 | + context = instrumenter().start(parentContext, request); |
| 102 | + scope = context.makeCurrent(); |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * Advice executed at the end of the {@code serve} method. Propagates the trace context to the |
| 107 | + * response, handles exceptions, and ends the span. |
| 108 | + * |
| 109 | + * @param asyncServlet The {@code AsyncServlet} instance handling the request. |
| 110 | + * @param responsePromise The promise representing the HTTP response. |
| 111 | + * @param throwable Any exception thrown during the execution of the method. |
| 112 | + * @param context Local variable storing the OpenTelemetry context. |
| 113 | + * @param scope Local variable storing the OpenTelemetry scope. |
| 114 | + * @param httpRequest Local variable storing the HTTP request. |
| 115 | + */ |
| 116 | + @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) |
| 117 | + public static void methodExit( |
| 118 | + @Advice.This AsyncServlet asyncServlet, |
| 119 | + @Advice.Return(readOnly = false) Promise<HttpResponse> responsePromise, |
| 120 | + @Advice.Thrown(readOnly = false) Throwable throwable, |
| 121 | + @Advice.Local("otelContext") Context context, |
| 122 | + @Advice.Local("otelScope") Scope scope, |
| 123 | + @Advice.Local("httpRequest") HttpRequest httpRequest) { |
| 124 | + if (context == null || scope == null || httpRequest == null) { |
| 125 | + return; |
| 126 | + } |
| 127 | + String traceId = Span.fromContext(context).getSpanContext().getTraceId(); |
| 128 | + String spanId = Span.fromContext(context).getSpanContext().getSpanId(); |
| 129 | + String traceFlags = |
| 130 | + Span.fromContext(context).getSpanContext().getTraceFlags().asHex().substring(0, 2); |
| 131 | + String traceparent = String.format("00-%s-%s-%s", traceId, spanId, traceFlags); |
| 132 | + |
| 133 | + scope.close(); |
| 134 | + String traceparentHeader = "traceparent"; |
| 135 | + if (responsePromise != null) { |
| 136 | + HttpResponse httpResponse = responsePromise.getResult(); |
| 137 | + Throwable error = throwable; |
| 138 | + if (responsePromise.isException()) { |
| 139 | + error = responsePromise.getException(); |
| 140 | + } |
| 141 | + httpResponse = ActiveJHttpServerHelper.createResponse(error, traceparent, httpResponse); |
| 142 | + instrumenter().end(context, httpRequest, httpResponse, error); |
| 143 | + responsePromise = Promise.of(httpResponse); |
| 144 | + } else if (throwable != null) { |
| 145 | + HttpResponse httpResponse = |
| 146 | + HttpResponse.builder() |
| 147 | + .withCode(500) |
| 148 | + .withPlainText(throwable.getMessage()) |
| 149 | + .withHeader(HttpHeaders.of(traceparentHeader), traceparent) |
| 150 | + .build(); |
| 151 | + instrumenter().end(context, httpRequest, httpResponse, throwable); |
| 152 | + responsePromise = Promise.of(httpResponse); |
| 153 | + throwable = null; |
| 154 | + } else { |
| 155 | + HttpResponse httpResponse = |
| 156 | + HttpResponse.notFound404() |
| 157 | + .withHeader(HttpHeaders.of(traceparentHeader), traceparent) |
| 158 | + .build(); |
| 159 | + instrumenter().end(context, httpRequest, httpResponse, throwable); |
| 160 | + responsePromise = Promise.of(httpResponse); |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | +} |
0 commit comments