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 servlet 2.2 instrumentation #376

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public interface Filter {
/**
* Evaluate the execution.
*
* @param span span
* @param headers are used for blocking evaluation.
* @return filter result
*/
Expand Down
1 change: 1 addition & 0 deletions instrumentation/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ plugins {

dependencies{
implementation(project(":instrumentation:servlet:servlet-rw"))
implementation(project(":instrumentation:servlet:servlet-2.2"))
implementation(project(":instrumentation:servlet:servlet-3.0"))
implementation(project(":instrumentation:spark-2.3"))
implementation(project(":instrumentation:grpc-1.6"))
Expand Down
48 changes: 48 additions & 0 deletions instrumentation/servlet/servlet-2.2/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
plugins {
`java-library`
id("net.bytebuddy.byte-buddy")
id("io.opentelemetry.instrumentation.auto-instrumentation")
muzzle
}

muzzle {
kaushal02 marked this conversation as resolved.
Show resolved Hide resolved
pass {
group = "javax.servlet"
module = "servlet-api"
versions = "[2.2, 3.0)"
assertInverse = true
}

fail {
group = "javax.servlet"
module = "javax.servlet-api"
versions = "(,)"
}
}

afterEvaluate{
io.opentelemetry.instrumentation.gradle.bytebuddy.ByteBuddyPluginConfigurator(
project,
sourceSets.main.get(),
io.opentelemetry.javaagent.tooling.muzzle.generation.MuzzleCodeGenerationPlugin::class.java.name,
project(":javaagent-tooling").configurations["instrumentationMuzzle"] + configurations.runtimeClasspath
).configure()
}

val versions: Map<String, String> by extra

dependencies {
implementation("io.opentelemetry.javaagent.instrumentation:opentelemetry-javaagent-servlet-common:${versions["opentelemetry_java_agent"]}")
compileOnly("io.opentelemetry.javaagent:opentelemetry-javaagent-bootstrap:${versions["opentelemetry_java_agent"]}")
testRuntimeOnly("io.opentelemetry.javaagent.instrumentation:opentelemetry-javaagent-servlet-common-bootstrap:${versions["opentelemetry_java_agent"]}")
muzzleBootstrap("io.opentelemetry.javaagent.instrumentation:opentelemetry-javaagent-servlet-common-bootstrap:${versions["opentelemetry_java_agent"]}")
compileOnly("javax.servlet:servlet-api:2.2")

// testInstrumentation(project(":instrumentation:servlet:servlet-3.0:javaagent"))
kaushal02 marked this conversation as resolved.
Show resolved Hide resolved
//
// testLibrary("org.eclipse.jetty:jetty-server:7.0.0.v20091005")
// testLibrary("org.eclipse.jetty:jetty-servlet:7.0.0.v20091005")
//
// latestDepTestLibrary("org.eclipse.jetty:jetty-server:7.+") // see servlet-3.0 module
// latestDepTestLibrary("org.eclipse.jetty:jetty-servlet:7.+") // see servlet-3.0 module
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/*
* Copyright The Hypertrace 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
*
* http://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.
*/

package io.opentelemetry.javaagent.instrumentation.hypertrace.servlet.v2_2.nowrapping;

import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.hasClassesNamed;
import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.hasSuperType;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.namedOneOf;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;

import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.instrumentation.api.field.VirtualField;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.instrumentation.api.Java8BytecodeBridge;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.hypertrace.agent.core.config.InstrumentationConfig;
import org.hypertrace.agent.core.instrumentation.HypertraceCallDepthThreadLocalMap;
import org.hypertrace.agent.core.instrumentation.HypertraceEvaluationException;
import org.hypertrace.agent.core.instrumentation.HypertraceSemanticAttributes;
import org.hypertrace.agent.core.instrumentation.SpanAndObjectPair;
import org.hypertrace.agent.core.instrumentation.buffer.*;
import org.hypertrace.agent.core.instrumentation.utils.ContentTypeUtils;
import org.hypertrace.agent.filter.FilterRegistry;

public class Servlet2AndFilterInstrumentation implements TypeInstrumentation {
@Override
public ElementMatcher<ClassLoader> classLoaderOptimization() {
return hasClassesNamed("javax.servlet.Servlet");
}

@Override
public ElementMatcher<TypeDescription> typeMatcher() {
return hasSuperType(namedOneOf("javax.servlet.Filter", "javax.servlet.Servlet"));
}

@Override
public void transform(TypeTransformer transformer) {
// print version with Implmentation Version
kaushal02 marked this conversation as resolved.
Show resolved Hide resolved
transformer.applyAdviceToMethod(
namedOneOf("doFilter", "service")
.and(takesArgument(0, named("javax.servlet.ServletRequest")))
.and(takesArgument(1, named("javax.servlet.ServletResponse")))
.and(isPublic()),
Servlet2AndFilterInstrumentation.class.getName() + "$ServletAdvice");
}

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

@Advice.OnMethodEnter(suppress = Throwable.class, skipOn = Advice.OnNonDefaultValue.class)
public static boolean start(
kaushal02 marked this conversation as resolved.
Show resolved Hide resolved
@Advice.Argument(value = 0) ServletRequest request,
@Advice.Argument(value = 1) ServletResponse response,
@Advice.Local("currentSpan") Span currentSpan) {
int callDepth =
HypertraceCallDepthThreadLocalMap.incrementCallDepth(Servlet2InstrumentationName.class);
if (callDepth > 0) {
return false;
}
if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
return false;
}

HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
currentSpan = Java8BytecodeBridge.currentSpan();

InstrumentationConfig instrumentationConfig = InstrumentationConfig.ConfigProvider.get();

Utils.addSessionId(currentSpan, httpRequest);

// set request headers
Enumeration<?> headerNames = httpRequest.getHeaderNames();
Map<String, String> headers = new HashMap<>();
while (headerNames.hasMoreElements()) {
String headerName;
try {
headerName = (String) headerNames.nextElement();
} catch (Exception e) {
continue;
}
String headerValue = httpRequest.getHeader(headerName);
AttributeKey<String> attributeKey =
HypertraceSemanticAttributes.httpRequestHeader(headerName);

if (instrumentationConfig.httpHeaders().request()) {
currentSpan.setAttribute(attributeKey, headerValue);
}
headers.put(attributeKey.getKey(), headerValue);
}

if (FilterRegistry.getFilter().evaluateRequestHeaders(currentSpan, headers)) {
httpResponse.setStatus(403);
// skip execution of the user code
return true;
}

if (instrumentationConfig.httpBody().request()
&& ContentTypeUtils.shouldCapture(httpRequest.getContentType())) {
// The HttpServletRequest instrumentation uses this to
// enable the instrumentation
VirtualField.find(HttpServletRequest.class, SpanAndObjectPair.class)
.set(
httpRequest,
new SpanAndObjectPair(currentSpan, Collections.unmodifiableMap(headers)));
}
return false;
}

@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void exit(
@Advice.Argument(0) ServletRequest request,
@Advice.Argument(1) ServletResponse response,
@Advice.Thrown(readOnly = false) Throwable throwable,
@Advice.Local("currentSpan") Span currentSpan) {
int callDepth =
HypertraceCallDepthThreadLocalMap.decrementCallDepth(Servlet2InstrumentationName.class);
if (callDepth > 0) {
return;
}
// we are in the most outermost level of Servlet instrumentation

if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
return;
}

HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpServletRequest httpRequest = (HttpServletRequest) request;
InstrumentationConfig instrumentationConfig = InstrumentationConfig.ConfigProvider.get();

try {
// response context to capture body and clear the context
VirtualField<HttpServletResponse, SpanAndObjectPair> responseContextStore =
VirtualField.find(HttpServletResponse.class, SpanAndObjectPair.class);
VirtualField<ServletOutputStream, BoundedByteArrayOutputStream> outputStreamContextStore =
VirtualField.find(ServletOutputStream.class, BoundedByteArrayOutputStream.class);
VirtualField<PrintWriter, BoundedCharArrayWriter> writerContextStore =
VirtualField.find(PrintWriter.class, BoundedCharArrayWriter.class);

// request context to clear body buffer
VirtualField<HttpServletRequest, SpanAndObjectPair> requestContextStore =
VirtualField.find(HttpServletRequest.class, SpanAndObjectPair.class);
VirtualField<ServletInputStream, ByteBufferSpanPair> inputStreamContextStore =
VirtualField.find(ServletInputStream.class, ByteBufferSpanPair.class);
VirtualField<BufferedReader, CharBufferSpanPair> readerContextStore =
VirtualField.find(BufferedReader.class, CharBufferSpanPair.class);
VirtualField<HttpServletRequest, StringMapSpanPair> urlEncodedMapContextStore =
VirtualField.find(HttpServletRequest.class, StringMapSpanPair.class);

// capture response body
// TODO: capture response headers
// FIXME: capture body based on response content type
if (instrumentationConfig.httpBody().response()) {
Utils.captureResponseBody(
currentSpan,
httpResponse,
responseContextStore,
outputStreamContextStore,
writerContextStore);
}

// remove request body buffers from context stores, otherwise they might get reused
if (instrumentationConfig.httpBody().request()
&& ContentTypeUtils.shouldCapture(httpRequest.getContentType())) {
Utils.resetRequestBodyBuffers(
httpRequest,
requestContextStore,
inputStreamContextStore,
readerContextStore,
urlEncodedMapContextStore);
}
} finally {
Throwable tmp = throwable;
while (tmp != null) { // loop in case our exception is nested (eg. springframework)
if (tmp instanceof HypertraceEvaluationException) {
httpResponse.setStatus(403);
// bytebuddy treats the reassignment of this variable to null as an instruction to
// suppress this exception, which is what we want
throwable = null;
break;
}
tmp = tmp.getCause();
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright The Hypertrace 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
*
* http://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.
*/

package io.opentelemetry.javaagent.instrumentation.hypertrace.servlet.v2_2.nowrapping;

import com.google.auto.service.AutoService;
import io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.instrumentation.hypertrace.servlet.v2_2.nowrapping.request.ServletInputStreamInstrumentation;
import io.opentelemetry.javaagent.instrumentation.hypertrace.servlet.v2_2.nowrapping.request.ServletRequestInstrumentation;
import io.opentelemetry.javaagent.instrumentation.hypertrace.servlet.v2_2.nowrapping.response.ServletOutputStreamInstrumentation;
import io.opentelemetry.javaagent.instrumentation.hypertrace.servlet.v2_2.nowrapping.response.ServletResponseInstrumentation;
import java.util.Arrays;
import java.util.List;

@SuppressWarnings("unused")
@AutoService(InstrumentationModule.class)
public class Servlet2InstrumentationModule extends InstrumentationModule {

public Servlet2InstrumentationModule() {
super(Servlet2InstrumentationName.PRIMARY, Servlet2InstrumentationName.OTHER);
}

@Override
public int order() {
return 1;
}

@Override
public List<TypeInstrumentation> typeInstrumentations() {
return Arrays.asList(
new Servlet2AndFilterInstrumentation(),
new ServletRequestInstrumentation(),
new ServletInputStreamInstrumentation(),
new ServletResponseInstrumentation(),
new ServletOutputStreamInstrumentation());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright The Hypertrace 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
*
* http://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.
*/

package io.opentelemetry.javaagent.instrumentation.hypertrace.servlet.v2_2.nowrapping;

public class Servlet2InstrumentationName {
public static final String PRIMARY = "servlet";
public static final String[] OTHER = {
"servlet-2", "ht", "servlet-ht", "servlet-2-ht", "servlet-2-no-wrapping", "servlet-no-wrapping"
};
}
Loading