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