Enable checkstyle for google style guide (#1641)

This commit is contained in:
Trask Stalnaker 2020-11-16 18:46:59 -08:00 committed by GitHub
parent 6e9ccfc39d
commit 6d5ec329d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
204 changed files with 1158 additions and 1361 deletions

View File

@ -16,16 +16,16 @@ public class Worker {
private static final Tracer tracer = OpenTelemetry.getGlobalTracer("io.opentelemetry.auto");
/** Simulate work for the give number of milliseconds. */
public static void doWork(long workTimeMS) {
public static void doWork(long workTimeMillis) {
Span span = tracer.spanBuilder("work").startSpan();
try (Scope scope = span.makeCurrent()) {
if (span != null) {
span.setAttribute("work-time", workTimeMS);
span.setAttribute("work-time", workTimeMillis);
span.setAttribute("info", "interesting stuff");
span.setAttribute("additionalInfo", "interesting stuff");
}
long doneTimestamp = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(workTimeMS);
long doneTimestamp = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(workTimeMillis);
while (System.nanoTime() < doneTimestamp) {
// busy-wait to simulate work
}

View File

@ -55,25 +55,25 @@ public class JettyPerftest {
if (request.getParameter("error") != null) {
throw new RuntimeException("some sync error");
}
String workVal = request.getParameter("workTimeMS");
long workTimeMS = 0l;
String workVal = request.getParameter("workTimeMillis");
long workTimeMillis = 0L;
if (null != workVal) {
workTimeMS = Long.parseLong(workVal);
workTimeMillis = Long.parseLong(workVal);
}
scheduleWork(workTimeMS);
response.getWriter().print("Did " + workTimeMS + "ms of work.");
scheduleWork(workTimeMillis);
response.getWriter().print("Did " + workTimeMillis + "ms of work.");
}
private void scheduleWork(long workTimeMS) {
private void scheduleWork(long workTimeMillis) {
Span span = tracer.spanBuilder("work").startSpan();
try (Scope scope = span.makeCurrent()) {
if (span != null) {
span.setAttribute("work-time", workTimeMS);
span.setAttribute("work-time", workTimeMillis);
span.setAttribute("info", "interesting stuff");
span.setAttribute("additionalInfo", "interesting stuff");
}
if (workTimeMS > 0) {
Worker.doWork(workTimeMS);
if (workTimeMillis > 0) {
Worker.doWork(workTimeMillis);
}
span.end();
}

View File

@ -10,8 +10,8 @@ test_num_threads=5
# endpoionts to test
declare -A endpoints
endpoints['<1MS']='http://localhost:8080/work'
endpoints['1MS']='http://localhost:8080/work?workTimeMS=1'
endpoints['2MS']='http://localhost:8080/work?workTimeMS=2'
endpoints['5MS']='http://localhost:8080/work?workTimeMS=5'
endpoints['10MS']='http://localhost:8080/work?workTimeMS=10'
endpoints['1MS']='http://localhost:8080/work?workTimeMillis=1'
endpoints['2MS']='http://localhost:8080/work?workTimeMillis=2'
endpoints['5MS']='http://localhost:8080/work?workTimeMillis=5'
endpoints['10MS']='http://localhost:8080/work?workTimeMillis=10'
test_order=( '<1MS' '1MS' '2MS' '5MS' '10MS' )

View File

@ -23,23 +23,23 @@ import javax.inject.Inject
import play.api.mvc._
/**
* This controller creates an `Action` to handle HTTP requests to the
* application's work page which does busy wait to simulate some work
*/
* This controller creates an `Action` to handle HTTP requests to the
* application's work page which does busy wait to simulate some work
*/
class HomeController @Inject()(cc: ControllerComponents)
extends AbstractController(cc) {
extends AbstractController(cc) {
val TRACER: Tracer =
OpenTelemetry.getTracerProvider.get("io.opentelemetry.auto")
/**
* Create an Action to perform busy wait
*/
def doGet(workTimeMS: Option[Long], error: Option[String]) = Action {
* Create an Action to perform busy wait
*/
def doGet(workTimeMillis: Option[Long], error: Option[String]) = Action {
implicit request: Request[AnyContent] =>
error match {
case Some(x) => throw new RuntimeException("some sync error")
case None => {
var workTime = workTimeMS.getOrElse(0L)
var workTime = workTimeMillis.getOrElse(0L)
scheduleWork(workTime)
Ok("Did " + workTime + "ms of work.")
}
@ -47,17 +47,17 @@ class HomeController @Inject()(cc: ControllerComponents)
}
private def scheduleWork(workTimeMS: Long) {
private def scheduleWork(workTimeMillis: Long) {
val span = tracer().spanBuilder("work").startSpan()
val scope = tracer().withSpan(span)
try {
if (span != null) {
span.setAttribute("work-time", workTimeMS)
span.setAttribute("work-time", workTimeMillis)
span.setAttribute("info", "interesting stuff")
span.setAttribute("additionalInfo", "interesting stuff")
}
if (workTimeMS > 0) {
Worker.doWork(workTimeMS)
if (workTimeMillis > 0) {
Worker.doWork(workTimeMillis)
}
} finally {
span.end()

View File

@ -24,19 +24,19 @@ object Worker {
val TRACER: Tracer =
OpenTelemetry.getTracerProvider.get("io.opentelemetry.auto")
def doWork(workTimeMS: Long) = {
def doWork(workTimeMillis: Long) = {
val span = tracer().spanBuilder("work").startSpan()
val scope = tracer().withSpan(span)
try {
if (span != null) {
span.setAttribute("work-time", workTimeMS)
span.setAttribute("work-time", workTimeMillis)
span.setAttribute("info", "interesting stuff")
span.setAttribute("additionalInfo", "interesting stuff")
}
val doneTimestamp = System.nanoTime + TimeUnit.MILLISECONDS.toNanos(
workTimeMS
workTimeMillis
)
while ({
while ( {
System.nanoTime < doneTimestamp
}) {
// busy-wait to simulate work

View File

@ -4,4 +4,4 @@
# ~~~~
# An example controller showing a sample home page
GET /work controllers.HomeController.doGet(workTimeMS: Option[Long], error: Option[String])
GET /work controllers.HomeController.doGet(workTimeMillis: Option[Long], error: Option[String])

View File

@ -11,7 +11,6 @@ import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import java.net.InetSocketAddress;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -20,8 +19,8 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class HttpClass {
private String contextPath = "/path";
private Integer port = 18888;
private final String contextPath = "/path";
private final Integer port = 18888;
public Server buildJettyServer() {
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
@ -38,11 +37,11 @@ public class HttpClass {
@WebServlet
public static class HttpClassServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
Thread.sleep(10);
} catch (Exception e) {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
resp.setContentType("application/json");
resp.setStatus(HttpServletResponse.SC_OK);
@ -50,7 +49,7 @@ public class HttpClass {
}
}
private HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
private final HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
public void executeRequest() throws IOException {
String url = "http://localhost:" + port + contextPath;

View File

@ -1,7 +1,10 @@
### Style guideline
## Style guideline
We follow the [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html).
Our build will fail if source code is not formatted according to that style.
### Auto-formatting
The build will fail if the source code is not formatted according to the google java style.
The main goal is to avoid extensive reformatting caused by different IDEs having different opinion
about how things should be formatted by establishing.
@ -38,3 +41,14 @@ As additional convenience for IntelliJ users, we provide `.editorconfig`
file. IntelliJ will automatically use it to adjust its code formatting settings.
It does not support all required rules, so you still have to run
`spotlessApply` from time to time.
### Additional checks
The build uses checkstyle to verify some parts of the Google Java Style Guide that cannot be handled
by auto-formatting.
To run these checks locally:
```
./gradlew checkstyleMain checkstyleTest
```

8
gradle/checkstyle.gradle Normal file
View File

@ -0,0 +1,8 @@
apply plugin: "checkstyle"
checkstyle {
configFile = rootProject.file('gradle/enforcement/checkstyle.xml')
// this version should match the version of google_checks.xml used as basis for above configuration
toolVersion = "8.37"
maxWarnings = 0
}

View File

@ -0,0 +1,396 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<!--
Checkstyle configuration that checks the Google coding conventions from Google Java Style
that can be found at https://google.github.io/styleguide/javaguide.html
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.org (or in your downloaded distribution).
To completely disable a check, just comment it out or delete it from the file.
To suppress certain violations please review suppression filters.
Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov.
-->
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml"/>
<!-- Excludes all 'module-info.java' files -->
<!-- See https://checkstyle.org/config_filefilters.html -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- https://checkstyle.org/config_filters.html#SuppressionFilter -->
<module name="SuppressionFilter">
<property name="file" value="${org.checkstyle.google.suppressionfilter.config}"
default="checkstyle-suppressions.xml"/>
<property name="optional" value="true"/>
</module>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.org/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<!--
<module name="LineLength">
<property name="fileExtensions" value="java"/>
<property name="max" value="100"/>
<property name="ignorePattern"
value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
-->
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format"
value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message"
value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap">
<property name="tokens" value="PACKAGE_DEF, IMPORT, STATIC_IMPORT"/>
</module>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces">
<property name="tokens"
value="LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE"/>
</module>
<module name="LeftCurly">
<property name="tokens"
value="ANNOTATION_DEF, CLASS_DEF, CTOR_DEF, ENUM_CONSTANT_DEF, ENUM_DEF,
INTERFACE_DEF, LAMBDA, LITERAL_CASE, LITERAL_CATCH, LITERAL_DEFAULT,
LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF,
LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, METHOD_DEF,
OBJBLOCK, STATIC_INIT, RECORD_DEF, COMPACT_CTOR_DEF"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE,
LITERAL_DO"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens"
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, STATIC_INIT,
INSTANCE_INIT, ANNOTATION_DEF, ENUM_DEF, INTERFACE_DEF, RECORD_DEF,
COMPACT_CTOR_DEF"/>
</module>
<module name="SuppressionXpathSingleFilter">
<!-- suppresion is required till https://github.com/checkstyle/checkstyle/issues/7541 -->
<property name="id" value="RightCurlyAlone"/>
<property name="query" value="//RCURLY[parent::SLIST[count(./*)=1]
or preceding-sibling::*[last()][self::LCURLY]]"/>
</module>
<module name="WhitespaceAfter">
<property name="tokens"
value="COMMA, SEMI, TYPECAST, LITERAL_IF, LITERAL_ELSE,
LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, DO_WHILE"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyLambdas" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<property name="ignoreEnhancedForColon" value="false"/>
<property name="tokens"
value="ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR,
BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, DO_WHILE, EQUAL, GE, GT, LAMBDA, LAND,
LCURLY, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY,
LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SWITCH, LITERAL_SYNCHRONIZED,
LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN,
NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR,
SR_ASSIGN, STAR, STAR_ASSIGN, LITERAL_ASSERT, TYPE_EXTENSION_AND"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="EmptyLineSeparator">
<property name="tokens"
value="PACKAGE_DEF, IMPORT, STATIC_IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF,
STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF, RECORD_DEF,
COMPACT_CTOR_DEF"/>
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapDot"/>
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapComma"/>
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ELLIPSIS is EOL until https://github.com/google/styleguide/issues/258 -->
<property name="id" value="SeparatorWrapEllipsis"/>
<property name="tokens" value="ELLIPSIS"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ARRAY_DECLARATOR is EOL until https://github.com/google/styleguide/issues/259 -->
<property name="id" value="SeparatorWrapArrayDeclarator"/>
<property name="tokens" value="ARRAY_DECLARATOR"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapMethodRef"/>
<property name="tokens" value="METHOD_REF"/>
<property name="option" value="nl"/>
</module>
<module name="PackageName">
<!-- modified from default to support packages like
io.opentelemetry.javaagent.instrumentation.log4j.v2_13_2 and
io.opentelemetry.javaagent.instrumentation.netty.v4_1.client -->
<property name="format"
value="^[a-z]+(\.[a-z][a-z0-9]*)*(\.v[0-9]+_[0-9]+(_[0-9]+)?)?(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF,
ANNOTATION_DEF, RECORD_DEF"/>
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LambdaParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="PatternVariableName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Pattern variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<!--
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
-->
<module name="RecordTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Record type name ''{0}'' must match pattern ''{1}''."/>
</module>
<!--
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
-->
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<!-- this doesn't seem to be compatible with google auto-format
<module name="Indentation">
<property name="basicOffset" value="2"/>
<property name="braceAdjustment" value="2"/>
<property name="caseIndent" value="2"/>
<property name="throwsIndent" value="4"/>
<property name="lineWrappingIndentation" value="4"/>
<property name="arrayInitIndent" value="2"/>
</module>
-->
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<!-- modified from default to support KHttp -->
<property name="allowedAbbreviationLength" value="1"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, ANNOTATION_DEF, ANNOTATION_FIELD_DEF,
PARAMETER_DEF, VARIABLE_DEF, METHOD_DEF, PATTERN_VARIABLE_DEF, RECORD_DEF,
RECORD_COMPONENT_DEF"/>
</module>
<!--
<module name="OverloadMethodsDeclarationOrder"/>
-->
<!-- there are only a few violations of this, and they all appear to be for good reasons
<module name="VariableDeclarationUsageDistance"/>
-->
<module name="CustomImportOrder">
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="separateLineBetweenGroups" value="true"/>
<property name="customImportOrderRules" value="STATIC###THIRD_PARTY_PACKAGE"/>
<property name="tokens" value="IMPORT, STATIC_IMPORT, PACKAGE_DEF"/>
</module>
<module name="MethodParamPad">
<property name="tokens"
value="CTOR_DEF, LITERAL_NEW, METHOD_CALL, METHOD_DEF,
SUPER_CTOR_CALL, ENUM_CONSTANT_DEF, RECORD_DEF"/>
</module>
<module name="NoWhitespaceBefore">
<property name="tokens"
value="COMMA, SEMI, POST_INC, POST_DEC, DOT,
LABELED_STAT, METHOD_REF"/>
<property name="allowLineBreaks" value="true"/>
</module>
<module name="ParenPad">
<property name="tokens"
value="ANNOTATION, ANNOTATION_FIELD_DEF, CTOR_CALL, CTOR_DEF, DOT, ENUM_CONSTANT_DEF,
EXPR, LITERAL_CATCH, LITERAL_DO, LITERAL_FOR, LITERAL_IF, LITERAL_NEW,
LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_WHILE, METHOD_CALL,
METHOD_DEF, QUESTION, RESOURCE_SPECIFICATION, SUPER_CTOR_CALL, LAMBDA,
RECORD_DEF"/>
</module>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens"
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR,
LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF "/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationMostCases"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF,
RECORD_DEF, COMPACT_CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationVariables"/>
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="InvalidJavadocPosition"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments"
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="RequireEmptyLineBeforeBlockTagGroup"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<module name="JavadocMethod">
<property name="scope" value="public"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="tokens" value="METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF, COMPACT_CTOR_DEF"/>
</module>
<!--
<module name="MissingJavadocMethod">
<property name="scope" value="public"/>
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="tokens" value="METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF,
COMPACT_CTOR_DEF"/>
</module>
-->
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<!-- this doesn't seem to be compatible with google auto-format
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
-->
<module name="EmptyCatchBlock">
<!-- modified from "expected" to "ignored" to match Intellij -->
<property name="exceptionVariableName" value="ignored"/>
</module>
<module name="CommentsIndentation">
<property name="tokens" value="SINGLE_LINE_COMMENT, BLOCK_COMMENT_BEGIN"/>
</module>
<!-- https://checkstyle.org/config_filters.html#SuppressionXpathFilter -->
<module name="SuppressionXpathFilter">
<property name="file" value="${org.checkstyle.google.suppressionxpathfilter.config}"
default="checkstyle-xpath-suppressions.xml"/>
<property name="optional" value="true"/>
</module>
<!-- this enables @SuppressWarnings("checkstyle:...") annotations -->
<module name="SuppressWarningsHolder"/>
</module>
<!-- this enables @SuppressWarnings("checkstyle:...") annotations -->
<module name="SuppressWarningsFilter"/>
<!-- skip javacc generated files -->
<module name="SuppressionSingleFilter">
<property name="checks" value=".*"/>
<property name="files" value="javaagent-api[/\\]build[/\\]generated[/\\]javacc"/>
</module>
<module name="SuppressionSingleFilter">
<property name="checks" value="MethodName"/>
<property name="files" value="bytebuddy[/\\]matcher[/\\]testclasses"/>
</module>
<module name="SuppressionSingleFilter">
<property name="checks" value="MethodName"/>
<property name="files" value="benchmark[/\\]src[/\\]jmh"/>
</module>
<module name="SuppressionSingleFilter">
<property name="checks" value=".*"/>
<property name="files" value="instrumentation[/\\]api[/\\]typedspan"/>
</module>
</module>

View File

@ -7,6 +7,7 @@ apply plugin: 'org.gradle.test-retry'
apply from: "$rootDir/gradle/spotless.gradle"
apply from: "$rootDir/gradle/codenarc.gradle"
apply from: "$rootDir/gradle/spotbugs.gradle"
apply from: "$rootDir/gradle/checkstyle.gradle"
afterEvaluate {
if (findProperty('mavenGroupId') == 'io.opentelemetry.javaagent.instrumentation') {

View File

@ -1,51 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
<Match>
<Bug pattern="RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT" /> <!-- Fluent APIs trigger this -->
<!-- Fluent APIs trigger this -->
<Bug pattern="RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT"/>
</Match>
<Match>
<!-- ignore default encoding for auto-genned class -->
<Class name="io.opentelemetry.javaagent.instrumentation.api.db.normalizer.SimpleCharStream"/>
<Bug pattern="DM_DEFAULT_ENCODING"/> <!-- ignore default encoding for auto-genned class -->
<Bug pattern="DM_DEFAULT_ENCODING"/>
</Match>
<Match>
<Class name="io.opentelemetry.instrumentation.util.gc.GCUtils"/>
<Bug pattern="DM_GC"/> <!-- forced GC only used in testing -->
<!-- forced GC only used in testing -->
<Class name="io.opentelemetry.instrumentation.util.gc.GcUtils"/>
<Bug pattern="DM_GC"/>
</Match>
<Match>
<Source name="~.*\.kt" /> <!-- https://github.com/spotbugs/spotbugs/issues/573 kotlin is not well supported (yet) -->
<!-- https://github.com/spotbugs/spotbugs/issues/573 kotlin is not well supported (yet) -->
<Source name="~.*\.kt"/>
</Match>
<Match>
<!-- final field warnings can be ignored for this test class -->
<Class name="~muzzle\.TestClasses.*"/>
<Bug
pattern="MS_SHOULD_BE_FINAL"/> <!-- final field warnings can be ignored for this test class -->
<Bug pattern="MS_SHOULD_BE_FINAL"/>
</Match>
<Match>
<!-- inner class serialization warning can be ignored for testing purposes -->
<Class name="~HttpServletResponseTest\$.*"/>
<Bug
pattern="SE_BAD_FIELD_INNER_CLASS"/> <!-- inner class serialization warning can be ignored for testing purposes -->
<Bug pattern="SE_BAD_FIELD_INNER_CLASS"/>
</Match>
<Match>
<!-- inner class serialization warning can be ignored for testing purposes -->
<Class name="~HttpServletTest\$.*"/>
<Bug
pattern="SE_BAD_FIELD_INNER_CLASS"/> <!-- inner class serialization warning can be ignored for testing purposes -->
<Bug pattern="SE_BAD_FIELD_INNER_CLASS"/>
</Match>
<Match>
<!-- inner class serialization warning can be ignored for testing purposes -->
<Class name="~SpymemcachedTest\$.*"/>
<Bug
pattern="SE_BAD_FIELD_INNER_CLASS"/> <!-- inner class serialization warning can be ignored for testing purposes -->
<Bug pattern="SE_BAD_FIELD_INNER_CLASS"/>
</Match>
<Match>
<Class name="io.opentelemetry.instrumentation.api.tracer.utils.NetPeerUtils"/>
<Method name="setNetPeer"
params="io.opentelemetry.api.trace.Span,java.lang.String,java.lang.String,int" returns="void"/>
params="io.opentelemetry.api.trace.Span,java.lang.String,java.lang.String,int"
returns="void"/>
<Bug pattern="UC_USELESS_VOID_METHOD"/>
</Match>

View File

@ -53,7 +53,8 @@ public abstract class Config {
abstract Map<String, String> getAllProperties();
/**
* @return A string property value or null if a property with name {@code name} did not exist.
* Returns a string property value or null if a property with name {@code name} did not exist.
*
* @see #getProperty(String, String)
*/
@Nullable
@ -80,8 +81,9 @@ public abstract class Config {
}
/**
* @return A boolean property value or {@code defaultValue} if a property with name {@code name}
* did not exist.
* Returns a boolean property value or {@code defaultValue} if a property with name {@code name}
* did not exist.
*
* @see #getProperty(String, String)
*/
public boolean getBooleanProperty(String name, boolean defaultValue) {
@ -89,8 +91,9 @@ public abstract class Config {
}
/**
* @return A list-of-strings property value or empty list if a property with name {@code name} did
* not exist.
* Returns a list-of-strings property value or empty list if a property with name {@code name} did
* not exist.
*
* @see #getProperty(String, String)
*/
public List<String> getListProperty(String name) {
@ -98,8 +101,9 @@ public abstract class Config {
}
/**
* @return A list-of-strings property value or {@code defaultValue} if a property with name {@code
* name} did not exist.
* Returns a list-of-strings property value or {@code defaultValue} if a property with name {@code
* name} did not exist.
*
* @see #getProperty(String, String)
*/
public List<String> getListProperty(String name, List<String> defaultValue) {
@ -107,8 +111,9 @@ public abstract class Config {
}
/**
* @return A map-of-strings property value or empty map if a property with name {@code name} did
* not exist.
* Returns a map-of-strings property value or empty map if a property with name {@code name} did
* not exist.
*
* @see #getProperty(String, String)
*/
public Map<String, String> getMapProperty(String name) {

View File

@ -48,9 +48,9 @@ class CamelTracer extends BaseTracer {
String component = "";
String uri = endpoint.getEndpointUri();
String splitURI[] = StringHelper.splitOnCharacter(uri, ":", 2);
if (splitURI[1] != null) {
component = splitURI[0];
String[] splitUri = StringHelper.splitOnCharacter(uri, ":", 2);
if (splitUri[1] != null) {
component = splitUri[0];
}
return registry.forComponent(component);
}

View File

@ -39,8 +39,7 @@ public interface SpanDecorator {
boolean shouldStartNewSpan();
/**
* This method returns the operation name to use with the Span representing this exchange and
* endpoint.
* Returns the operation name to use with the Span representing this exchange and endpoint.
*
* @param exchange The exchange
* @param endpoint The endpoint
@ -68,19 +67,9 @@ public interface SpanDecorator {
*/
void post(Span span, Exchange exchange, Endpoint endpoint);
/**
* This method returns the 'span.kind' value for use when the component is initiating a
* communication.
*
* @return The kind
*/
/** Returns the 'span.kind' value for use when the component is initiating a communication. */
Span.Kind getInitiatorSpanKind();
/**
* This method returns the 'span.kind' value for use when the component is receiving a
* communication.
*
* @return The kind
*/
/** Returns the 'span.kind' value for use when the component is receiving a communication. */
Span.Kind getReceiverSpanKind();
}

View File

@ -86,8 +86,8 @@ class BaseSpanDecorator implements SpanDecorator {
@Override
public String getOperationName(
Exchange exchange, Endpoint endpoint, CamelDirection camelDirection) {
String[] splitURI = StringHelper.splitOnCharacter(endpoint.getEndpointUri(), ":", 2);
return (splitURI.length > 0 ? splitURI[0] : DEFAULT_OPERATION_NAME);
String[] splitUri = StringHelper.splitOnCharacter(endpoint.getEndpointUri(), ":", 2);
return (splitUri.length > 0 ? splitUri[0] : DEFAULT_OPERATION_NAME);
}
@Override

View File

@ -48,77 +48,69 @@ class DbSpanDecorator extends BaseSpanDecorator {
switch (component) {
case "mongodb":
case "elasticsearch":
{
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
if (queryParameters.containsKey("operation")) {
return queryParameters.get("operation");
}
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
if (queryParameters.containsKey("operation")) {
return queryParameters.get("operation");
}
return super.getOperationName(exchange, endpoint, camelDirection);
default:
return super.getOperationName(exchange, endpoint, camelDirection);
}
return super.getOperationName(exchange, endpoint, camelDirection);
}
private String getStatement(Exchange exchange, Endpoint endpoint) {
switch (component) {
case "mongodb":
{
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
return queryParameters.toString();
}
Map<String, String> mongoParameters = toQueryParameters(endpoint.getEndpointUri());
return mongoParameters.toString();
case "cql":
{
Object cql = exchange.getIn().getHeader("CamelCqlQuery");
if (cql != null) {
return cql.toString();
} else {
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
if (queryParameters.containsKey("cql")) {
return queryParameters.get("cql");
}
}
Object cqlObj = exchange.getIn().getHeader("CamelCqlQuery");
if (cqlObj != null) {
return cqlObj.toString();
}
Map<String, String> cqlParameters = toQueryParameters(endpoint.getEndpointUri());
if (cqlParameters.containsKey("cql")) {
return cqlParameters.get("cql");
}
return null;
case "jdbc":
{
Object body = exchange.getIn().getBody();
if (body instanceof String) {
return (String) body;
}
Object body = exchange.getIn().getBody();
if (body instanceof String) {
return (String) body;
}
return null;
case "sql":
{
Object sqlquery = exchange.getIn().getHeader("CamelSqlQuery");
if (sqlquery instanceof String) {
return (String) sqlquery;
}
Object sqlquery = exchange.getIn().getHeader("CamelSqlQuery");
if (sqlquery instanceof String) {
return (String) sqlquery;
}
return null;
default:
return null;
}
return null;
}
private String getDbName(Endpoint endpoint) {
switch (component) {
case "mongodb":
{
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
return queryParameters.get("database");
}
Map<String, String> mongoParameters = toQueryParameters(endpoint.getEndpointUri());
return mongoParameters.get("database");
case "cql":
{
URI uri = URI.create(endpoint.getEndpointUri());
if (uri.getPath() != null && uri.getPath().length() > 0) {
// Strip leading '/' from path
return uri.getPath().substring(1);
}
URI uri = URI.create(endpoint.getEndpointUri());
if (uri.getPath() != null && uri.getPath().length() > 0) {
// Strip leading '/' from path
return uri.getPath().substring(1);
}
return null;
case "elasticsearch":
{
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
if (queryParameters.containsKey("indexName")) {
return queryParameters.get("indexName");
}
Map<String, String> elasticsearchParameters = toQueryParameters(endpoint.getEndpointUri());
if (elasticsearchParameters.containsKey("indexName")) {
return elasticsearchParameters.get("indexName");
}
return null;
default:
return null;
}
return null;
}
@Override

View File

@ -80,7 +80,7 @@ class HttpSpanDecorator extends BaseSpanDecorator {
public void pre(Span span, Exchange exchange, Endpoint endpoint, CamelDirection camelDirection) {
super.pre(span, exchange, endpoint, camelDirection);
String httpUrl = getHttpURL(exchange, endpoint);
String httpUrl = getHttpUrl(exchange, endpoint);
if (httpUrl != null) {
span.setAttribute(SemanticAttributes.HTTP_URL, httpUrl);
}
@ -100,7 +100,7 @@ class HttpSpanDecorator extends BaseSpanDecorator {
@Nullable
protected String getPath(Exchange exchange, Endpoint endpoint) {
String httpUrl = getHttpURL(exchange, endpoint);
String httpUrl = getHttpUrl(exchange, endpoint);
try {
URL url = new URL(httpUrl);
return url.getPath();
@ -120,7 +120,7 @@ class HttpSpanDecorator extends BaseSpanDecorator {
}
}
protected String getHttpURL(Exchange exchange, Endpoint endpoint) {
protected String getHttpUrl(Exchange exchange, Endpoint endpoint) {
Object url = exchange.getIn().getHeader(Exchange.HTTP_URL);
if (url instanceof String) {
return (String) url;

View File

@ -81,12 +81,11 @@ class KafkaSpanDecorator extends MessagingSpanDecorator {
}
/**
* Extracts header value from the exchange for given header
* Extracts header value from the exchange for given header.
*
* @param exchange the {@link Exchange}
* @param header the header name
* @param type the class type of the exchange header
* @return
*/
private <T> String getValue(final Exchange exchange, final String header, Class<T> type) {
T value = exchange.getIn().getHeader(header, type);

View File

@ -44,9 +44,8 @@ class MessagingSpanDecorator extends BaseSpanDecorator {
public String getOperationName(
Exchange exchange, Endpoint endpoint, CamelDirection camelDirection) {
switch (component) {
case "mqtt":
return stripSchemeAndOptions(endpoint);
if ("mqtt".equals(component)) {
return stripSchemeAndOptions(endpoint);
}
return getDestination(exchange, endpoint);
}
@ -78,22 +77,19 @@ class MessagingSpanDecorator extends BaseSpanDecorator {
case "rabbitmq":
return (String) exchange.getIn().getHeader("rabbitmq.EXCHANGE_NAME");
case "stomp":
{
String destination = stripSchemeAndOptions(endpoint);
if (destination.startsWith("queue:")) {
destination = destination.substring("queue:".length());
}
return destination;
String destination = stripSchemeAndOptions(endpoint);
if (destination.startsWith("queue:")) {
destination = destination.substring("queue:".length());
}
return destination;
case "mqtt":
{
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
return (queryParameters.containsKey("subscribeTopicNames")
? queryParameters.get("subscribeTopicNames")
: queryParameters.get("publishTopicName"));
}
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
return (queryParameters.containsKey("subscribeTopicNames")
? queryParameters.get("subscribeTopicNames")
: queryParameters.get("publishTopicName"));
default:
return stripSchemeAndOptions(endpoint);
}
return stripSchemeAndOptions(endpoint);
}
@Override
@ -121,7 +117,8 @@ class MessagingSpanDecorator extends BaseSpanDecorator {
return (String) exchange.getIn().getHeader("CamelIronMQMessageId");
case "jms":
return (String) exchange.getIn().getHeader("JMSMessageID");
default:
return null;
}
return null;
}
}

View File

@ -14,13 +14,13 @@ import org.apache.http.RequestLine;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.AbstractHttpMessage;
/** Wraps HttpHost and HttpRequest into a HttpUriRequest for decorators and injectors */
/** Wraps HttpHost and HttpRequest into a HttpUriRequest for decorators and injectors. */
public class HostAndRequestAsHttpUriRequest extends AbstractHttpMessage implements HttpUriRequest {
private final String method;
private final RequestLine requestLine;
private final ProtocolVersion protocolVersion;
private final java.net.URI URI;
private final java.net.URI uri;
private final HttpRequest actualRequest;
@ -30,13 +30,13 @@ public class HostAndRequestAsHttpUriRequest extends AbstractHttpMessage implemen
requestLine = httpRequest.getRequestLine();
protocolVersion = requestLine.getProtocolVersion();
URI calculatedURI;
URI calculatedUri;
try {
calculatedURI = new URI(httpHost.toURI() + httpRequest.getRequestLine().getUri());
calculatedUri = new URI(httpHost.toURI() + httpRequest.getRequestLine().getUri());
} catch (URISyntaxException e) {
calculatedURI = null;
calculatedUri = null;
}
URI = calculatedURI;
uri = calculatedUri;
actualRequest = httpRequest;
}
@ -72,7 +72,7 @@ public class HostAndRequestAsHttpUriRequest extends AbstractHttpMessage implemen
@Override
public java.net.URI getURI() {
return URI;
return uri;
}
public HttpRequest getActualRequest() {

View File

@ -95,8 +95,9 @@ public class OpenTelemetryService extends SimpleDecoratingHttpService {
return paths.get(paths.size() - 1);
case REGEX_WITH_PREFIX:
return paths.get(1) + paths.get(0);
default:
return null;
}
return null;
}
private static class Decorator implements Function<HttpService, OpenTelemetryService> {

View File

@ -20,10 +20,10 @@ abstract class ApiGatewayProxyRequest {
private static boolean noHttpPropagationNeeded() {
List<String> fields = OpenTelemetry.getGlobalPropagators().getTextMapPropagator().fields();
return (fields.isEmpty() || xRayPropagationFieldsOnly(fields));
return (fields.isEmpty() || xrayPropagationFieldsOnly(fields));
}
private static boolean xRayPropagationFieldsOnly(List<String> fields) {
private static boolean xrayPropagationFieldsOnly(List<String> fields) {
// ugly but faster than typical convert-to-set-and-check-contains-only
return (fields.size() == 1)
&& (ParentContextExtractor.AWS_TRACE_HEADER_PROPAGATOR_KEY.equals(fields.get(0)));

View File

@ -68,6 +68,7 @@ public class AwsLambdaMessageTracer extends BaseTracer {
return span.startSpan();
}
@Override
public Scope startScope(Span span) {
return span.makeCurrent();
}
@ -76,7 +77,7 @@ public class AwsLambdaMessageTracer extends BaseTracer {
String parentHeader = message.getAttributes().get(AWS_TRACE_HEADER_SQS_ATTRIBUTE_KEY);
if (parentHeader != null) {
SpanContext parentCtx =
Span.fromContext(ParentContextExtractor.fromXRayHeader(parentHeader)).getSpanContext();
Span.fromContext(ParentContextExtractor.fromXrayHeader(parentHeader)).getSpanContext();
if (parentCtx.isValid()) {
span.addLink(parentCtx);
}

View File

@ -40,7 +40,7 @@ public class AwsLambdaTracer extends BaseTracer {
io.opentelemetry.context.Context parentContext = null;
String parentTraceHeader = System.getenv(AWS_TRACE_HEADER_ENV_KEY);
if (parentTraceHeader != null) {
parentContext = ParentContextExtractor.fromXRayHeader(parentTraceHeader);
parentContext = ParentContextExtractor.fromXrayHeader(parentTraceHeader);
}
if (!isValid(parentContext) && (headers != null)) {
// try http
@ -69,6 +69,7 @@ public class AwsLambdaTracer extends BaseTracer {
}
/** Creates new scoped context with the given span. */
@Override
public Scope startScope(Span span) {
// TODO we could do this in one go, but TracingContextUtils.CONTEXT_SPAN_KEY is private
io.opentelemetry.context.Context newContext =

View File

@ -38,7 +38,7 @@ public class ParentContextExtractor {
static final String AWS_TRACE_HEADER_PROPAGATOR_KEY = "X-Amzn-Trace-Id";
static Context fromXRayHeader(String parentHeader) {
static Context fromXrayHeader(String parentHeader) {
return OpenTelemetry.getGlobalPropagators()
.getTextMapPropagator()
.extract(

View File

@ -13,19 +13,19 @@ import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import java.util.concurrent.TimeUnit;
public abstract class TracingSQSEventHandler extends TracingRequestHandler<SQSEvent, Void> {
public abstract class TracingSqsEventHandler extends TracingRequestHandler<SQSEvent, Void> {
private final AwsLambdaMessageTracer tracer;
/** Creates a new {@link TracingRequestHandler} which traces using the default {@link Tracer}. */
protected TracingSQSEventHandler() {
protected TracingSqsEventHandler() {
this.tracer = new AwsLambdaMessageTracer();
}
/**
* Creates a new {@link TracingRequestHandler} which traces using the specified {@link Tracer}.
*/
protected TracingSQSEventHandler(Tracer tracer) {
protected TracingSqsEventHandler(Tracer tracer) {
super(tracer);
this.tracer = new AwsLambdaMessageTracer(tracer);
}
@ -34,7 +34,7 @@ public abstract class TracingSQSEventHandler extends TracingRequestHandler<SQSEv
* Creates a new {@link TracingRequestHandler} which traces using the specified {@link
* AwsLambdaMessageTracer}.
*/
protected TracingSQSEventHandler(AwsLambdaMessageTracer tracer) {
protected TracingSqsEventHandler(AwsLambdaMessageTracer tracer) {
this.tracer = tracer;
}

View File

@ -12,17 +12,17 @@ import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
public abstract class TracingSQSMessageHandler extends TracingSQSEventHandler {
public abstract class TracingSqsMessageHandler extends TracingSqsEventHandler {
/** Creates a new {@link TracingRequestHandler} which traces using the default {@link Tracer}. */
protected TracingSQSMessageHandler() {
protected TracingSqsMessageHandler() {
super(new AwsLambdaMessageTracer());
}
/**
* Creates a new {@link TracingRequestHandler} which traces using the specified {@link Tracer}.
*/
protected TracingSQSMessageHandler(Tracer tracer) {
protected TracingSqsMessageHandler(Tracer tracer) {
super(new AwsLambdaMessageTracer(tracer));
}
@ -30,10 +30,11 @@ public abstract class TracingSQSMessageHandler extends TracingSQSEventHandler {
* Creates a new {@link TracingRequestHandler} which traces using the specified {@link
* AwsLambdaMessageTracer}.
*/
protected TracingSQSMessageHandler(AwsLambdaMessageTracer tracer) {
protected TracingSqsMessageHandler(AwsLambdaMessageTracer tracer) {
super(tracer);
}
@Override
protected final void handleEvent(SQSEvent event, Context context) {
for (SQSMessage message : event.getRecords()) {
Span span = getTracer().startSpan(message);

View File

@ -26,8 +26,6 @@ class WrappedLambda {
/**
* Creates new lambda wrapper out of configuration. Supported env properties: - {@value
* OTEL_LAMBDA_HANDLER_ENV_KEY} - lambda handler in format: package.ClassName::methodName
*
* @return
*/
static WrappedLambda fromConfiguration() {

View File

@ -12,7 +12,7 @@ import io.opentelemetry.instrumentation.test.InstrumentationTestTrait
class AwsLambdaSqsHandlerTest extends AbstractAwsLambdaSqsHandlerTest implements InstrumentationTestTrait {
class TestHandler extends TracingSQSEventHandler {
class TestHandler extends TracingSqsEventHandler {
@Override
protected void handleEvent(SQSEvent event, Context context) {
}

View File

@ -11,12 +11,12 @@ import static io.opentelemetry.api.trace.Span.Kind.SERVER
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.events.SQSEvent
import io.opentelemetry.api.OpenTelemetry
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import io.opentelemetry.api.trace.propagation.HttpTraceContext
import io.opentelemetry.context.propagation.DefaultContextPropagators
import io.opentelemetry.extension.trace.propagation.AwsXRayPropagator
import io.opentelemetry.instrumentation.test.InstrumentationSpecification
import io.opentelemetry.instrumentation.test.InstrumentationTestTrait
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import io.opentelemetry.api.trace.propagation.HttpTraceContext
class AwsLambdaSqsMessageHandlerTest extends InstrumentationSpecification implements InstrumentationTestTrait {
@ -32,7 +32,7 @@ class AwsLambdaSqsMessageHandlerTest extends InstrumentationSpecification implem
private static final String AWS_TRACE_HEADER1 = "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1"
private static final String AWS_TRACE_HEADER2 = "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad9;Sampled=1"
class TestHandler extends TracingSQSMessageHandler {
class TestHandler extends TracingSqsMessageHandler {
@Override
protected void handleMessage(SQSEvent.SQSMessage event, Context context) {
}

View File

@ -36,10 +36,10 @@ final class AwsClientInstrumentation implements TypeInstrumentation {
@Override
public Map<? extends ElementMatcher<? super MethodDescription>, String> transformers() {
return singletonMap(
isConstructor(), AwsClientInstrumentation.class.getName() + "$AWSClientAdvice");
isConstructor(), AwsClientInstrumentation.class.getName() + "$AwsClientAdvice");
}
public static class AWSClientAdvice {
public static class AwsClientAdvice {
// Since we're instrumenting the constructor, we can't add onThrowable.
@Advice.OnMethodExit(suppress = Throwable.class)
public static void addHandler(

View File

@ -17,7 +17,7 @@ import io.opentelemetry.context.Scope;
import io.opentelemetry.javaagent.instrumentation.api.ContextStore;
import io.opentelemetry.javaagent.instrumentation.api.SpanWithScope;
/** Tracing Request Handler */
/** Tracing Request Handler. */
public class TracingRequestHandler extends RequestHandler2 {
private final ContextStore<AmazonWebServiceRequest, RequestMeta> contextStore;

View File

@ -3,9 +3,9 @@
* SPDX-License-Identifier: Apache-2.0
*/
import static io.opentelemetry.api.trace.Span.Kind.CLIENT
import static io.opentelemetry.instrumentation.test.server.http.TestHttpServer.httpServer
import static io.opentelemetry.instrumentation.test.utils.PortUtils.UNUSABLE_PORT
import static io.opentelemetry.api.trace.Span.Kind.CLIENT
import com.amazonaws.AmazonClientException
import com.amazonaws.AmazonWebServiceClient
@ -37,15 +37,15 @@ import com.amazonaws.services.s3.AmazonS3ClientBuilder
import com.amazonaws.services.sqs.AmazonSQSClientBuilder
import com.amazonaws.services.sqs.model.CreateQueueRequest
import com.amazonaws.services.sqs.model.SendMessageRequest
import io.opentelemetry.instrumentation.api.tracer.HttpClientTracer
import io.opentelemetry.instrumentation.test.AgentTestRunner
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import io.opentelemetry.instrumentation.api.tracer.HttpClientTracer
import io.opentelemetry.instrumentation.test.AgentTestRunner
import java.util.concurrent.atomic.AtomicReference
import spock.lang.AutoCleanup
import spock.lang.Shared
class AWS1ClientTest extends AgentTestRunner {
class Aws1ClientTest extends AgentTestRunner {
private static final CREDENTIALS_PROVIDER_CHAIN = new AWSCredentialsProviderChain(
new EnvironmentVariableCredentialsProvider(),

View File

@ -3,9 +3,9 @@
* SPDX-License-Identifier: Apache-2.0
*/
import static io.opentelemetry.api.trace.Span.Kind.CLIENT
import static io.opentelemetry.instrumentation.test.server.http.TestHttpServer.httpServer
import static io.opentelemetry.instrumentation.test.utils.PortUtils.UNUSABLE_PORT
import static io.opentelemetry.api.trace.Span.Kind.CLIENT
import com.amazonaws.AmazonClientException
import com.amazonaws.ClientConfiguration
@ -24,15 +24,15 @@ import com.amazonaws.services.rds.AmazonRDSClient
import com.amazonaws.services.rds.model.DeleteOptionGroupRequest
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.S3ClientOptions
import io.opentelemetry.instrumentation.api.tracer.HttpClientTracer
import io.opentelemetry.instrumentation.test.AgentTestRunner
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import io.opentelemetry.instrumentation.api.tracer.HttpClientTracer
import io.opentelemetry.instrumentation.test.AgentTestRunner
import java.util.concurrent.atomic.AtomicReference
import spock.lang.AutoCleanup
import spock.lang.Shared
class AWS0ClientTest extends AgentTestRunner {
class Aws0ClientTest extends AgentTestRunner {
private static final CREDENTIALS_PROVIDER_CHAIN = new AWSCredentialsProviderChain(
new EnvironmentVariableCredentialsProvider(),

View File

@ -24,7 +24,7 @@ import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
/** AWS request execution interceptor */
/** AWS request execution interceptor. */
final class TracingExecutionInterceptor implements ExecutionInterceptor {
static final ExecutionAttribute<io.opentelemetry.context.Context> CONTEXT_ATTRIBUTE =

View File

@ -68,7 +68,6 @@ public class CassandraClientInstrumentationModule extends InstrumentationModule
* contribution is a simple wrapper, so we just have to wrap the new session.
*
* @param session The fresh session to patch. This session is replaced with new session
* @throws Exception
*/
@Advice.OnMethodExit(suppress = Throwable.class)
public static void injectTracingSession(@Advice.Return(readOnly = false) Session session) {

View File

@ -33,13 +33,13 @@ class TraceAnnotationsTest extends AgentTestRunner {
def "test complex case annotations"() {
when:
// Test new trace with 2 children spans
SayTracedHello.sayHELLOsayHA()
SayTracedHello.sayHelloSayHa()
then:
assertTraces(1) {
trace(0, 3) {
span(0) {
name "SayTracedHello.sayHELLOsayHA"
name "SayTracedHello.sayHelloSayHa"
hasNoParent()
errored false
attributes {
@ -70,7 +70,7 @@ class TraceAnnotationsTest extends AgentTestRunner {
setup:
Throwable error = null
try {
SayTracedHello.sayERROR()
SayTracedHello.sayError()
} catch (final Throwable ex) {
error = ex
}
@ -79,7 +79,7 @@ class TraceAnnotationsTest extends AgentTestRunner {
assertTraces(1) {
trace(0, 1) {
span(0) {
name "SayTracedHello.sayERROR"
name "SayTracedHello.sayError"
errored true
errorEvent(error.class)
}

View File

@ -75,13 +75,13 @@ public class SayTracedHello {
}
@io.opentracing.contrib.dropwizard.Trace
public static String sayHELLOsayHA() {
public static String sayHelloSayHa() {
Span.current().setAttribute("myattr", "test2");
return sayHello() + sayHello();
}
@io.opentracing.contrib.dropwizard.Trace
public static String sayERROR() {
public static String sayError() {
throw new RuntimeException();
}

View File

@ -38,8 +38,8 @@ public class HttpUrlConnectionTracer
}
@Override
protected String requestHeader(HttpURLConnection httpURLConnection, String name) {
return httpURLConnection.getRequestProperty(name);
protected String requestHeader(HttpURLConnection httpUrlConnection, String name) {
return httpUrlConnection.getRequestProperty(name);
}
@Override

View File

@ -88,7 +88,7 @@ final class ClassLoaderInstrumentation implements TypeInstrumentation {
if (name.startsWith(prefix)) {
try {
return Class.forName(name, false, null);
} catch (ClassNotFoundException e) {
} catch (ClassNotFoundException ignored) {
}
}
}

View File

@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import static io.opentelemetry.instrumentation.util.gc.GCUtils.awaitGC
import static io.opentelemetry.instrumentation.util.gc.GcUtils.awaitGc
import io.opentelemetry.instrumentation.test.AgentTestRunner
import io.opentelemetry.javaagent.tooling.HelperInjector
@ -40,7 +40,7 @@ class ResourceInjectionTest extends AgentTestRunner {
def ref = new WeakReference(emptyLoader.get())
emptyLoader.set(null)
awaitGC(ref)
awaitGc(ref)
then: "HelperInjector doesn't prevent it from being collected"
null == ref.get()

View File

@ -26,27 +26,30 @@ abstract class AbstractExecutorInstrumentation implements TypeInstrumentation {
private static final Logger log = LoggerFactory.getLogger(AbstractExecutorInstrumentation.class);
private static final String TRACE_EXECUTORS_CONFIG = "otel.trace.executors";
private final boolean TRACE_ALL_EXECUTORS =
// hopefully these configuration properties can be static after
// https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/1345
private final boolean traceAllExecutors =
Config.get().getBooleanProperty("otel.trace.executors.all", false);
/**
* Only apply executor instrumentation to allowed executors. To apply to all executors, use
* override setting above.
*/
private final Collection<String> ALLOWED_EXECUTORS;
private final Collection<String> allowedExecutors;
/**
* Some frameworks have their executors defined as anon classes inside other classes. Referencing
* anon classes by name would be fragile, so instead we will use list of class prefix names. Since
* checking this list is more expensive (O(n)) we should try to keep it short.
*/
private final Collection<String> ALLOWED_EXECUTORS_PREFIXES;
private final Collection<String> allowedExecutorsPrefixes;
AbstractExecutorInstrumentation() {
if (TRACE_ALL_EXECUTORS) {
if (traceAllExecutors) {
log.info("Tracing all executors enabled.");
ALLOWED_EXECUTORS = Collections.emptyList();
ALLOWED_EXECUTORS_PREFIXES = Collections.emptyList();
allowedExecutors = Collections.emptyList();
allowedExecutorsPrefixes = Collections.emptyList();
} else {
String[] allowed = {
"akka.actor.ActorSystemImpl$$anon$1",
@ -94,11 +97,10 @@ abstract class AbstractExecutorInstrumentation implements TypeInstrumentation {
Set<String> executors = new HashSet<>(Config.get().getListProperty(TRACE_EXECUTORS_CONFIG));
executors.addAll(Arrays.asList(allowed));
ALLOWED_EXECUTORS = Collections.unmodifiableSet(executors);
allowedExecutors = Collections.unmodifiableSet(executors);
String[] allowedPrefixes = {"slick.util.AsyncExecutor$"};
ALLOWED_EXECUTORS_PREFIXES =
Collections.unmodifiableCollection(Arrays.asList(allowedPrefixes));
allowedExecutorsPrefixes = Collections.unmodifiableCollection(Arrays.asList(allowedPrefixes));
}
}
@ -107,17 +109,17 @@ abstract class AbstractExecutorInstrumentation implements TypeInstrumentation {
ElementMatcher.Junction<TypeDescription> matcher = any();
final ElementMatcher.Junction<TypeDescription> hasExecutorInterfaceMatcher =
implementsInterface(named(Executor.class.getName()));
if (!TRACE_ALL_EXECUTORS) {
if (!traceAllExecutors) {
matcher =
matcher.and(
new ElementMatcher<TypeDescription>() {
@Override
public boolean matches(TypeDescription target) {
boolean allowed = ALLOWED_EXECUTORS.contains(target.getName());
boolean allowed = allowedExecutors.contains(target.getName());
// Check for possible prefixes match only if not allowed already
if (!allowed) {
for (String name : ALLOWED_EXECUTORS_PREFIXES) {
for (String name : allowedExecutorsPrefixes) {
if (target.getName().startsWith(name)) {
allowed = true;
break;

View File

@ -43,7 +43,8 @@ public final class NonStandardExecutorsInstrumentationModule extends Instrumenta
public Map<? extends ElementMatcher<? super MethodDescription>, String> transformers() {
Map<ElementMatcher<? super MethodDescription>, String> transformers = new HashMap<>();
transformers.put( // org.eclipse.jetty.util.thread.QueuedThreadPool
transformers.put(
// org.eclipse.jetty.util.thread.QueuedThreadPool
named("dispatch").and(takesArguments(1)).and(takesArgument(0, Runnable.class)),
JavaExecutorInstrumentation.class.getName() + "$SetExecuteRunnableStateAdvice");
return transformers;

View File

@ -8,7 +8,7 @@ package io.opentelemetry.javaagent.instrumentation.httpclient;
import io.opentelemetry.context.propagation.TextMapPropagator;
import java.net.http.HttpRequest;
/** Context propagation is implemented via {@link HttpHeadersInstrumentation} */
/** Context propagation is implemented via {@link HttpHeadersInstrumentation}. */
public class HttpHeadersInjectAdapter implements TextMapPropagator.Setter<HttpRequest> {
public static final HttpHeadersInjectAdapter SETTER = new HttpHeadersInjectAdapter();

View File

@ -47,11 +47,11 @@ final class ConnectionInstrumentation implements TypeInstrumentation {
public static class ConnectionPrepareAdvice {
@Advice.OnMethodExit(suppress = Throwable.class)
public static void addDBInfo(
public static void addDbInfo(
@Advice.Argument(0) String sql, @Advice.Return PreparedStatement statement) {
SqlStatementInfo normalizedSql = JDBCUtils.normalizeAndExtractInfo(sql);
SqlStatementInfo normalizedSql = JdbcUtils.normalizeAndExtractInfo(sql);
if (normalizedSql != null) {
JDBCMaps.preparedStatements.put(statement, normalizedSql);
JdbcMaps.preparedStatements.put(statement, normalizedSql);
}
}
}

View File

@ -7,9 +7,9 @@ package io.opentelemetry.javaagent.instrumentation.jdbc;
import java.util.Objects;
public class DBInfo {
public class DbInfo {
public static final DBInfo DEFAULT = new Builder().build();
public static final DbInfo DEFAULT = new Builder().build();
private final String system;
private final String subtype;
@ -20,7 +20,7 @@ public class DBInfo {
private final String host;
private final Integer port;
public DBInfo(
public DbInfo(
String system,
String subtype,
String shortUrl,
@ -88,10 +88,10 @@ public class DBInfo {
if (this == o) {
return true;
}
if (!(o instanceof DBInfo)) {
if (!(o instanceof DbInfo)) {
return false;
}
DBInfo dbInfo = (DBInfo) o;
DbInfo dbInfo = (DbInfo) o;
return Objects.equals(system, dbInfo.system)
&& Objects.equals(subtype, dbInfo.subtype)
&& Objects.equals(shortUrl, dbInfo.shortUrl)
@ -157,8 +157,8 @@ public class DBInfo {
return this;
}
public DBInfo build() {
return new DBInfo(system, subtype, shortUrl, user, name, db, host, port);
public DbInfo build() {
return new DbInfo(system, subtype, shortUrl, user, name, db, host, port);
}
}
}

View File

@ -46,7 +46,7 @@ final class DriverInstrumentation implements TypeInstrumentation {
public static class DriverAdvice {
@Advice.OnMethodExit(suppress = Throwable.class)
public static void addDBInfo(
public static void addDbInfo(
@Advice.Argument(0) String url,
@Advice.Argument(1) Properties props,
@Advice.Return Connection connection) {
@ -54,8 +54,8 @@ final class DriverInstrumentation implements TypeInstrumentation {
// Exception was probably thrown.
return;
}
DBInfo dbInfo = JDBCConnectionUrlParser.parse(url, props);
JDBCMaps.connectionInfo.put(connection, dbInfo);
DbInfo dbInfo = JdbcConnectionUrlParser.parse(url, props);
JdbcMaps.connectionInfo.put(connection, dbInfo);
}
}
}

View File

@ -5,7 +5,7 @@
package io.opentelemetry.javaagent.instrumentation.jdbc;
import static io.opentelemetry.javaagent.instrumentation.jdbc.DBInfo.DEFAULT;
import static io.opentelemetry.javaagent.instrumentation.jdbc.DbInfo.DEFAULT;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import io.opentelemetry.javaagent.instrumentation.api.db.DbSystem;
@ -26,10 +26,10 @@ import org.slf4j.LoggerFactory;
* Structured as an enum instead of a class hierarchy to allow iterating through the parsers
* automatically without having to maintain a separate list of parsers.
*/
public enum JDBCConnectionUrlParser {
public enum JdbcConnectionUrlParser {
GENERIC_URL_LIKE() {
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
try {
// Attempt generic parsing
URI uri = new URI(jdbcUrl);
@ -64,13 +64,10 @@ public enum JDBCConnectionUrlParser {
}
},
/**
* http://jtds.sourceforge.net/faq.html#urlFormat
* jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
*/
// see http://jtds.sourceforge.net/faq.html#urlFormat
JTDS_URL_LIKE() {
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
String serverName = "";
Integer port = null;
@ -116,7 +113,7 @@ public enum JDBCConnectionUrlParser {
MODIFIED_URL_LIKE() {
// Source: Regular Expressions Cookbook 2nd edition - 8.17.
// Matches Standard, Mixed or Compressed notation in a wider body of text
private final Pattern IPv6 =
private final Pattern ipv6 =
Pattern.compile(
// Non Compressed
"(?:(?:(?:[A-F0-9]{1,4}:){6}"
@ -143,7 +140,7 @@ public enum JDBCConnectionUrlParser {
CASE_INSENSITIVE);
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
String type;
String serverName = "";
Integer port = null;
@ -188,7 +185,7 @@ public enum JDBCConnectionUrlParser {
serverName = serverName.substring(0, instanceLoc);
}
Matcher ipv6Matcher = IPv6.matcher(serverName);
Matcher ipv6Matcher = ipv6.matcher(serverName);
boolean isIpv6 = ipv6Matcher.find();
int portLoc = -1;
@ -239,8 +236,8 @@ public enum JDBCConnectionUrlParser {
private static final int DEFAULT_PORT = 5432;
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DBInfo dbInfo = builder.build();
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
DbInfo dbInfo = builder.build();
if (dbInfo.getHost() == null) {
builder.host(DEFAULT_HOST);
}
@ -256,8 +253,8 @@ public enum JDBCConnectionUrlParser {
private static final int DEFAULT_PORT = 3306;
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DBInfo dbInfo = builder.build();
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
DbInfo dbInfo = builder.build();
if (dbInfo.getHost() == null) {
builder.host(DEFAULT_HOST);
}
@ -293,6 +290,7 @@ public enum JDBCConnectionUrlParser {
try {
builder.port(Integer.parseInt(jdbcUrl.substring(portLoc + 1, dbLoc)));
} catch (NumberFormatException e) {
log.debug(e.getMessage(), e);
}
} else {
hostEndLoc = dbLoc;
@ -306,7 +304,7 @@ public enum JDBCConnectionUrlParser {
MARIA_SUBPROTO() {
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
int hostEndLoc;
int clusterSepLoc = jdbcUrl.indexOf(",");
int ipv6End = jdbcUrl.startsWith("[") ? jdbcUrl.indexOf("]") : -1;
@ -333,6 +331,7 @@ public enum JDBCConnectionUrlParser {
try {
builder.port(Integer.parseInt(jdbcUrl.substring(portLoc + 1, portEndLoc)));
} catch (NumberFormatException e) {
log.debug(e.getMessage(), e);
}
} else {
hostEndLoc = clusterSepLoc > 0 ? clusterSepLoc : dbLoc;
@ -348,27 +347,27 @@ public enum JDBCConnectionUrlParser {
},
MARIA_ADDRESS() {
private final Pattern HOST_REGEX = Pattern.compile("\\(\\s*host\\s*=\\s*([^ )]+)\\s*\\)");
private final Pattern PORT_REGEX = Pattern.compile("\\(\\s*port\\s*=\\s*([\\d]+)\\s*\\)");
private final Pattern USER_REGEX = Pattern.compile("\\(\\s*user\\s*=\\s*([^ )]+)\\s*\\)");
private final Pattern hostPattern = Pattern.compile("\\(\\s*host\\s*=\\s*([^ )]+)\\s*\\)");
private final Pattern portPattern = Pattern.compile("\\(\\s*port\\s*=\\s*([\\d]+)\\s*\\)");
private final Pattern userPattern = Pattern.compile("\\(\\s*user\\s*=\\s*([^ )]+)\\s*\\)");
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
int addressEnd = jdbcUrl.indexOf(",address=");
if (addressEnd > 0) {
jdbcUrl = jdbcUrl.substring(0, addressEnd);
}
Matcher hostMatcher = HOST_REGEX.matcher(jdbcUrl);
Matcher hostMatcher = hostPattern.matcher(jdbcUrl);
if (hostMatcher.find()) {
builder.host(hostMatcher.group(1));
}
Matcher portMatcher = PORT_REGEX.matcher(jdbcUrl);
Matcher portMatcher = portPattern.matcher(jdbcUrl);
if (portMatcher.find()) {
builder.port(Integer.parseInt(portMatcher.group(1)));
}
Matcher userMatcher = USER_REGEX.matcher(jdbcUrl);
Matcher userMatcher = userPattern.matcher(jdbcUrl);
if (userMatcher.find()) {
builder.user(userMatcher.group(1));
}
@ -381,8 +380,8 @@ public enum JDBCConnectionUrlParser {
private static final String DEFAULT_HOST = "localhost";
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DBInfo dbInfo = builder.build();
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
DbInfo dbInfo = builder.build();
if (dbInfo.getHost() == null) {
builder.host(DEFAULT_HOST);
}
@ -395,8 +394,8 @@ public enum JDBCConnectionUrlParser {
private static final int DEFAULT_PORT = 1433;
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DBInfo dbInfo = builder.build();
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
DbInfo dbInfo = builder.build();
if (dbInfo.getHost() == null) {
builder.host(DEFAULT_HOST);
}
@ -423,8 +422,8 @@ public enum JDBCConnectionUrlParser {
private static final int DEFAULT_PORT = 50000;
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DBInfo dbInfo = builder.build();
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
DbInfo dbInfo = builder.build();
if (dbInfo.getPort() == null) {
builder.port(DEFAULT_PORT);
}
@ -436,13 +435,13 @@ public enum JDBCConnectionUrlParser {
private static final int DEFAULT_PORT = 1521;
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
int typeEndIndex = jdbcUrl.indexOf(":", "oracle:".length());
String subtype = jdbcUrl.substring("oracle:".length(), typeEndIndex);
jdbcUrl = jdbcUrl.substring(typeEndIndex + 1);
builder.subtype(subtype);
DBInfo dbInfo = builder.build();
DbInfo dbInfo = builder.build();
if (dbInfo.getPort() == null) {
builder.port(DEFAULT_PORT);
}
@ -457,7 +456,7 @@ public enum JDBCConnectionUrlParser {
ORACLE_CONNECT_INFO() {
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
String host;
Integer port;
@ -481,6 +480,7 @@ public enum JDBCConnectionUrlParser {
try {
parsedPort = Integer.parseInt(portOrInstance);
} catch (NumberFormatException e) {
log.debug(e.getMessage(), e);
}
if (parsedPort == null) {
port = null;
@ -518,7 +518,7 @@ public enum JDBCConnectionUrlParser {
ORACLE_AT() {
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
if (jdbcUrl.contains("@(description")) {
return ORACLE_AT_DESCRIPTION.doParse(jdbcUrl, builder);
}
@ -554,13 +554,13 @@ public enum JDBCConnectionUrlParser {
* defined in the first block. (It would locate data from subsequent address blocks.
*/
ORACLE_AT_DESCRIPTION() {
private final Pattern HOST_REGEX = Pattern.compile("\\(\\s*host\\s*=\\s*([^ )]+)\\s*\\)");
private final Pattern PORT_REGEX = Pattern.compile("\\(\\s*port\\s*=\\s*([\\d]+)\\s*\\)");
private final Pattern INSTANCE_REGEX =
private final Pattern hostPattern = Pattern.compile("\\(\\s*host\\s*=\\s*([^ )]+)\\s*\\)");
private final Pattern portPattern = Pattern.compile("\\(\\s*port\\s*=\\s*([\\d]+)\\s*\\)");
private final Pattern instancePattern =
Pattern.compile("\\(\\s*service_name\\s*=\\s*([^ )]+)\\s*\\)");
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
String[] atSplit = jdbcUrl.split("@", 2);
int userInfoLoc = atSplit[0].indexOf("/");
@ -568,17 +568,17 @@ public enum JDBCConnectionUrlParser {
builder.user(atSplit[0].substring(0, userInfoLoc));
}
Matcher hostMatcher = HOST_REGEX.matcher(atSplit[1]);
Matcher hostMatcher = hostPattern.matcher(atSplit[1]);
if (hostMatcher.find()) {
builder.host(hostMatcher.group(1));
}
Matcher portMatcher = PORT_REGEX.matcher(atSplit[1]);
Matcher portMatcher = portPattern.matcher(atSplit[1]);
if (portMatcher.find()) {
builder.port(Integer.parseInt(portMatcher.group(1)));
}
Matcher instanceMatcher = INSTANCE_REGEX.matcher(atSplit[1]);
Matcher instanceMatcher = instancePattern.matcher(atSplit[1]);
if (instanceMatcher.find()) {
builder.name(instanceMatcher.group(1));
}
@ -591,7 +591,7 @@ public enum JDBCConnectionUrlParser {
private static final int DEFAULT_PORT = 8082;
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
String instance;
String h2Url = jdbcUrl.substring("h2:".length());
@ -620,13 +620,13 @@ public enum JDBCConnectionUrlParser {
instance = h2Url.substring("zip:".length());
}
} else if (h2Url.startsWith("tcp:")) {
DBInfo dbInfo = builder.build();
DbInfo dbInfo = builder.build();
if (dbInfo.getPort() == null) {
builder.port(DEFAULT_PORT);
}
return MODIFIED_URL_LIKE.doParse(jdbcUrl, builder).system(DbSystem.H2).subtype("tcp");
} else if (h2Url.startsWith("ssl:")) {
DBInfo dbInfo = builder.build();
DbInfo dbInfo = builder.build();
if (dbInfo.getPort() == null) {
builder.port(DEFAULT_PORT);
}
@ -652,9 +652,9 @@ public enum JDBCConnectionUrlParser {
private static final int DEFAULT_PORT = 9001;
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
String instance = null;
DBInfo dbInfo = builder.build();
DbInfo dbInfo = builder.build();
if (dbInfo.getUser() == null) {
builder.user(DEFAULT_USER);
}
@ -710,11 +710,11 @@ public enum JDBCConnectionUrlParser {
private static final int DEFAULT_PORT = 1527;
@Override
DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder) {
DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder) {
String instance = null;
String host = null;
DBInfo dbInfo = builder.build();
DbInfo dbInfo = builder.build();
if (dbInfo.getUser() == null) {
builder.user(DEFAULT_USER);
}
@ -788,12 +788,12 @@ public enum JDBCConnectionUrlParser {
}
};
private static final Logger log = LoggerFactory.getLogger(JDBCConnectionUrlParser.class);
private static final Logger log = LoggerFactory.getLogger(JdbcConnectionUrlParser.class);
private static final Map<String, JDBCConnectionUrlParser> typeParsers = new HashMap<>();
private static final Map<String, JdbcConnectionUrlParser> typeParsers = new HashMap<>();
static {
for (JDBCConnectionUrlParser parser : JDBCConnectionUrlParser.values()) {
for (JdbcConnectionUrlParser parser : JdbcConnectionUrlParser.values()) {
for (String key : parser.typeKeys) {
typeParsers.put(key, parser);
}
@ -802,13 +802,13 @@ public enum JDBCConnectionUrlParser {
private final String[] typeKeys;
JDBCConnectionUrlParser(String... typeKeys) {
JdbcConnectionUrlParser(String... typeKeys) {
this.typeKeys = typeKeys;
}
abstract DBInfo.Builder doParse(String jdbcUrl, DBInfo.Builder builder);
abstract DbInfo.Builder doParse(String jdbcUrl, DbInfo.Builder builder);
public static DBInfo parse(String connectionUrl, Properties props) {
public static DbInfo parse(String connectionUrl, Properties props) {
if (connectionUrl == null) {
return DEFAULT;
}
@ -829,7 +829,7 @@ public enum JDBCConnectionUrlParser {
String type = jdbcUrl.substring(0, typeLoc);
String system = toDbSystem(type);
DBInfo.Builder parsedProps = DEFAULT.toBuilder().system(system);
DbInfo.Builder parsedProps = DEFAULT.toBuilder().system(system);
populateStandardProperties(parsedProps, props);
try {
@ -844,8 +844,8 @@ public enum JDBCConnectionUrlParser {
}
}
private static DBInfo withUrl(DBInfo.Builder builder, String type) {
DBInfo info = builder.build();
private static DbInfo withUrl(DbInfo.Builder builder, String type) {
DbInfo info = builder.build();
StringBuilder url = new StringBuilder();
url.append(type);
url.append(':');
@ -872,28 +872,28 @@ public enum JDBCConnectionUrlParser {
if (query == null || query.isEmpty()) {
return Collections.emptyMap();
}
Map<String, String> query_pairs = new LinkedHashMap<>();
Map<String, String> queryPairs = new LinkedHashMap<>();
String[] pairs = query.split(separator);
for (String pair : pairs) {
try {
int idx = pair.indexOf("=");
String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
if (!query_pairs.containsKey(key)) {
if (!queryPairs.containsKey(key)) {
String value =
idx > 0 && pair.length() > idx + 1
? URLDecoder.decode(pair.substring(idx + 1), "UTF-8")
: null;
query_pairs.put(key, value);
queryPairs.put(key, value);
}
} catch (UnsupportedEncodingException e) {
// Ignore.
}
}
return query_pairs;
return queryPairs;
}
private static void populateStandardProperties(
DBInfo.Builder builder, Map<? extends Object, ? extends Object> props) {
DbInfo.Builder builder, Map<? extends Object, ? extends Object> props) {
if (props != null && !props.isEmpty()) {
if (props.containsKey("user")) {
builder.user((String) props.get("user"));
@ -933,10 +933,8 @@ public enum JDBCConnectionUrlParser {
}
}
/**
* see {@link <a
* href="https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/database.md">specification</a>}
*/
// see
// https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/database.md
private static String toDbSystem(String type) {
switch (type) {
case "as400": // IBM AS400 Database

View File

@ -36,28 +36,28 @@ public final class JdbcDataSourceInstrumentationModule extends InstrumentationMo
public String[] helperClassNames() {
return new String[] {
packageName + ".DataSourceTracer",
packageName + ".DBInfo",
packageName + ".DBInfo$Builder",
packageName + ".JDBCConnectionUrlParser",
packageName + ".JDBCConnectionUrlParser$1",
packageName + ".JDBCConnectionUrlParser$2",
packageName + ".JDBCConnectionUrlParser$3",
packageName + ".JDBCConnectionUrlParser$4",
packageName + ".JDBCConnectionUrlParser$5",
packageName + ".JDBCConnectionUrlParser$6",
packageName + ".JDBCConnectionUrlParser$7",
packageName + ".JDBCConnectionUrlParser$8",
packageName + ".JDBCConnectionUrlParser$9",
packageName + ".JDBCConnectionUrlParser$10",
packageName + ".JDBCConnectionUrlParser$11",
packageName + ".JDBCConnectionUrlParser$12",
packageName + ".JDBCConnectionUrlParser$13",
packageName + ".JDBCConnectionUrlParser$14",
packageName + ".JDBCConnectionUrlParser$15",
packageName + ".JDBCConnectionUrlParser$16",
packageName + ".JDBCConnectionUrlParser$17",
packageName + ".JDBCMaps",
packageName + ".JDBCUtils",
packageName + ".DbInfo",
packageName + ".DbInfo$Builder",
packageName + ".JdbcConnectionUrlParser",
packageName + ".JdbcConnectionUrlParser$1",
packageName + ".JdbcConnectionUrlParser$2",
packageName + ".JdbcConnectionUrlParser$3",
packageName + ".JdbcConnectionUrlParser$4",
packageName + ".JdbcConnectionUrlParser$5",
packageName + ".JdbcConnectionUrlParser$6",
packageName + ".JdbcConnectionUrlParser$7",
packageName + ".JdbcConnectionUrlParser$8",
packageName + ".JdbcConnectionUrlParser$9",
packageName + ".JdbcConnectionUrlParser$10",
packageName + ".JdbcConnectionUrlParser$11",
packageName + ".JdbcConnectionUrlParser$12",
packageName + ".JdbcConnectionUrlParser$13",
packageName + ".JdbcConnectionUrlParser$14",
packageName + ".JdbcConnectionUrlParser$15",
packageName + ".JdbcConnectionUrlParser$16",
packageName + ".JdbcConnectionUrlParser$17",
packageName + ".JdbcMaps",
packageName + ".JdbcUtils",
};
}

View File

@ -21,29 +21,29 @@ public class JdbcInstrumentationModule extends InstrumentationModule {
@Override
public String[] helperClassNames() {
return new String[] {
packageName + ".DBInfo",
packageName + ".DBInfo$Builder",
packageName + ".JDBCConnectionUrlParser",
packageName + ".JDBCConnectionUrlParser$1",
packageName + ".JDBCConnectionUrlParser$2",
packageName + ".JDBCConnectionUrlParser$3",
packageName + ".JDBCConnectionUrlParser$4",
packageName + ".JDBCConnectionUrlParser$5",
packageName + ".JDBCConnectionUrlParser$6",
packageName + ".JDBCConnectionUrlParser$7",
packageName + ".JDBCConnectionUrlParser$8",
packageName + ".JDBCConnectionUrlParser$9",
packageName + ".JDBCConnectionUrlParser$10",
packageName + ".JDBCConnectionUrlParser$11",
packageName + ".JDBCConnectionUrlParser$12",
packageName + ".JDBCConnectionUrlParser$13",
packageName + ".JDBCConnectionUrlParser$14",
packageName + ".JDBCConnectionUrlParser$15",
packageName + ".JDBCConnectionUrlParser$16",
packageName + ".JDBCConnectionUrlParser$17",
packageName + ".JDBCMaps",
packageName + ".DbInfo",
packageName + ".DbInfo$Builder",
packageName + ".JdbcConnectionUrlParser",
packageName + ".JdbcConnectionUrlParser$1",
packageName + ".JdbcConnectionUrlParser$2",
packageName + ".JdbcConnectionUrlParser$3",
packageName + ".JdbcConnectionUrlParser$4",
packageName + ".JdbcConnectionUrlParser$5",
packageName + ".JdbcConnectionUrlParser$6",
packageName + ".JdbcConnectionUrlParser$7",
packageName + ".JdbcConnectionUrlParser$8",
packageName + ".JdbcConnectionUrlParser$9",
packageName + ".JdbcConnectionUrlParser$10",
packageName + ".JdbcConnectionUrlParser$11",
packageName + ".JdbcConnectionUrlParser$12",
packageName + ".JdbcConnectionUrlParser$13",
packageName + ".JdbcConnectionUrlParser$14",
packageName + ".JdbcConnectionUrlParser$15",
packageName + ".JdbcConnectionUrlParser$16",
packageName + ".JdbcConnectionUrlParser$17",
packageName + ".JdbcMaps",
packageName + ".JdbcTracer",
packageName + ".JDBCUtils",
packageName + ".JdbcUtils",
};
}

View File

@ -17,8 +17,8 @@ import java.sql.PreparedStatement;
*
* <p>Should be injected into the bootstrap classpath.
*/
public class JDBCMaps {
public static final WeakMap<Connection, DBInfo> connectionInfo = newWeakMap();
public class JdbcMaps {
public static final WeakMap<Connection, DbInfo> connectionInfo = newWeakMap();
public static final WeakMap<PreparedStatement, SqlStatementInfo> preparedStatements =
newWeakMap();
}

View File

@ -5,8 +5,8 @@
package io.opentelemetry.javaagent.instrumentation.jdbc;
import static io.opentelemetry.javaagent.instrumentation.jdbc.JDBCUtils.connectionFromStatement;
import static io.opentelemetry.javaagent.instrumentation.jdbc.JDBCUtils.normalizeAndExtractInfo;
import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcUtils.connectionFromStatement;
import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcUtils.normalizeAndExtractInfo;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.instrumentation.api.tracer.DatabaseClientTracer;
@ -20,7 +20,7 @@ import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTracer extends DatabaseClientTracer<DBInfo, SqlStatementInfo> {
public class JdbcTracer extends DatabaseClientTracer<DbInfo, SqlStatementInfo> {
private static final JdbcTracer TRACER = new JdbcTracer();
public static JdbcTracer tracer() {
@ -33,17 +33,17 @@ public class JdbcTracer extends DatabaseClientTracer<DBInfo, SqlStatementInfo> {
}
@Override
protected String dbSystem(DBInfo info) {
protected String dbSystem(DbInfo info) {
return info.getSystem();
}
@Override
protected String dbUser(DBInfo info) {
protected String dbUser(DbInfo info) {
return info.getUser();
}
@Override
protected String dbName(DBInfo info) {
protected String dbName(DbInfo info) {
if (info.getName() != null) {
return info.getName();
} else {
@ -53,12 +53,12 @@ public class JdbcTracer extends DatabaseClientTracer<DBInfo, SqlStatementInfo> {
// TODO find a way to implement
@Override
protected InetSocketAddress peerAddress(DBInfo dbInfo) {
protected InetSocketAddress peerAddress(DbInfo dbInfo) {
return null;
}
@Override
protected String dbConnectionString(DBInfo info) {
protected String dbConnectionString(DbInfo info) {
return info.getShortUrl();
}
@ -67,7 +67,7 @@ public class JdbcTracer extends DatabaseClientTracer<DBInfo, SqlStatementInfo> {
}
public Span startSpan(PreparedStatement statement) {
return startSpan(statement, JDBCMaps.preparedStatements.get(statement));
return startSpan(statement, JdbcMaps.preparedStatements.get(statement));
}
public Span startSpan(Statement statement, String query) {
@ -80,7 +80,7 @@ public class JdbcTracer extends DatabaseClientTracer<DBInfo, SqlStatementInfo> {
return null;
}
DBInfo dbInfo = extractDbInfo(connection);
DbInfo dbInfo = extractDbInfo(connection);
return startSpan(dbInfo, queryInfo);
}
@ -91,7 +91,7 @@ public class JdbcTracer extends DatabaseClientTracer<DBInfo, SqlStatementInfo> {
}
@Override
protected String spanName(DBInfo connection, SqlStatementInfo query, String normalizedQuery) {
protected String spanName(DbInfo connection, SqlStatementInfo query, String normalizedQuery) {
String dbName = dbName(connection);
if (query.getOperation() == null) {
return dbName == null ? DB_QUERY : dbName;
@ -111,8 +111,8 @@ public class JdbcTracer extends DatabaseClientTracer<DBInfo, SqlStatementInfo> {
return name.toString();
}
private DBInfo extractDbInfo(Connection connection) {
DBInfo dbInfo = JDBCMaps.connectionInfo.get(connection);
private DbInfo extractDbInfo(Connection connection) {
DbInfo dbInfo = JdbcMaps.connectionInfo.get(connection);
/*
* Logic to get the DBInfo from a JDBC Connection, if the connection was not created via
* Driver.connect, or it has never seen before, the connectionInfo map will return null and will
@ -127,18 +127,18 @@ public class JdbcTracer extends DatabaseClientTracer<DBInfo, SqlStatementInfo> {
String url = metaData.getURL();
if (url != null) {
try {
dbInfo = JDBCConnectionUrlParser.parse(url, connection.getClientInfo());
dbInfo = JdbcConnectionUrlParser.parse(url, connection.getClientInfo());
} catch (Throwable ex) {
// getClientInfo is likely not allowed.
dbInfo = JDBCConnectionUrlParser.parse(url, null);
dbInfo = JdbcConnectionUrlParser.parse(url, null);
}
} else {
dbInfo = DBInfo.DEFAULT;
dbInfo = DbInfo.DEFAULT;
}
} catch (SQLException se) {
dbInfo = DBInfo.DEFAULT;
dbInfo = DbInfo.DEFAULT;
}
JDBCMaps.connectionInfo.put(connection, dbInfo);
JdbcMaps.connectionInfo.put(connection, dbInfo);
}
}
return dbInfo;

View File

@ -17,18 +17,15 @@ import java.sql.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class JDBCUtils {
public abstract class JdbcUtils {
private static final Logger log = LoggerFactory.getLogger(JDBCUtils.class);
private static final Logger log = LoggerFactory.getLogger(JdbcUtils.class);
private static final boolean NORMALIZATION_ENABLED = isQueryNormalizationEnabled("jdbc");
private static Field c3poField = null;
/**
* @param statement
* @return the unwrapped connection or null if exception was thrown.
*/
/** Returns the unwrapped connection or null if exception was thrown. */
public static Connection connectionFromStatement(Statement statement) {
Connection connection;
try {
@ -72,7 +69,7 @@ public abstract class JDBCUtils {
return connection;
}
/** @return null if the sql could not be normalized for any reason */
/** Returns null if the sql could not be normalized for any reason. */
public static String normalizeSql(String sql) {
if (!NORMALIZATION_ENABLED) {
return sql;

View File

@ -3,13 +3,13 @@
* SPDX-License-Identifier: Apache-2.0
*/
import static io.opentelemetry.javaagent.instrumentation.jdbc.JDBCConnectionUrlParser.parse
import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcConnectionUrlParser.parse
import io.opentelemetry.javaagent.instrumentation.jdbc.DBInfo
import io.opentelemetry.javaagent.instrumentation.jdbc.DbInfo
import spock.lang.Shared
import spock.lang.Specification
class JDBCConnectionUrlParserTest extends Specification {
class JdbcConnectionUrlParserTest extends Specification {
@Shared
def stdProps = {
@ -29,7 +29,7 @@ class JDBCConnectionUrlParserTest extends Specification {
def "invalid url returns default"() {
expect:
parse(url, null) == DBInfo.DEFAULT
parse(url, null) == DbInfo.DEFAULT
where:
url | _
@ -200,6 +200,6 @@ class JDBCConnectionUrlParserTest extends Specification {
"jdbc:derby:jar:/derbydb;user=derbyuser;password=pw" | null | "derby:jar:" | "derby" | "jar" | "derbyuser" | null | null | "/derbydb" | null
"jdbc:derby:jar:(~/path/to/db.jar)/other/derbydb;user=derbyuser;password=pw" | null | "derby:jar:" | "derby" | "jar" | "derbyuser" | null | null | "(~/path/to/db.jar)/other/derbydb" | null
expected = new DBInfo.Builder().system(system).subtype(subtype).user(user).name(name).db(db).host(host).port(port).shortUrl(shortUrl).build()
expected = new DbInfo.Builder().system(system).subtype(subtype).user(user).name(name).db(db).host(host).port(port).shortUrl(shortUrl).build()
}
}

View File

@ -13,7 +13,7 @@ import com.zaxxer.hikari.HikariDataSource
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import io.opentelemetry.instrumentation.test.AgentTestRunner
import io.opentelemetry.instrumentation.test.utils.ConfigUtils
import io.opentelemetry.javaagent.instrumentation.jdbc.JDBCUtils
import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcUtils
import java.sql.CallableStatement
import java.sql.Connection
import java.sql.PreparedStatement
@ -30,7 +30,7 @@ import spock.lang.Unroll
import test.TestConnection
import test.TestDriver
class JDBCInstrumentationTest extends AgentTestRunner {
class JdbcInstrumentationTest extends AgentTestRunner {
static final PREVIOUS_CONFIG = ConfigUtils.updateConfigAndResetInstrumentation {
it.setProperty("otel.instrumentation.jdbc-datasource.enabled", "true")
}
@ -194,7 +194,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
if (username != null) {
"$SemanticAttributes.DB_USER.key" username
}
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" url
}
}
@ -250,7 +250,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
if (username != null) {
"$SemanticAttributes.DB_USER.key" username
}
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" url
}
}
@ -298,7 +298,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
if (username != null) {
"$SemanticAttributes.DB_USER.key" username
}
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" url
}
}
@ -346,7 +346,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
if (username != null) {
"$SemanticAttributes.DB_USER.key" username
}
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" url
}
}
@ -394,7 +394,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
if (username != null) {
"$SemanticAttributes.DB_USER.key" username
}
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" url
}
}
@ -445,7 +445,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
if (username != null) {
"$SemanticAttributes.DB_USER.key" username
}
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" url
}
}
@ -507,7 +507,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
if (username != null) {
"$SemanticAttributes.DB_USER.key" username
}
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" url
}
}
@ -602,7 +602,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
errored false
attributes {
"$SemanticAttributes.DB_SYSTEM.key" "testdb"
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" "testdb://localhost"
}
}
@ -641,7 +641,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
attributes {
"$SemanticAttributes.DB_SYSTEM.key" "testdb"
"$SemanticAttributes.DB_NAME.key" databaseName
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" "testdb://localhost"
}
}
@ -698,7 +698,7 @@ class JDBCInstrumentationTest extends AgentTestRunner {
"$SemanticAttributes.DB_SYSTEM.key" "hsqldb"
"$SemanticAttributes.DB_NAME.key" dbNameLower
"$SemanticAttributes.DB_USER.key" "SA"
"$SemanticAttributes.DB_STATEMENT.key" JDBCUtils.normalizeSql(query)
"$SemanticAttributes.DB_STATEMENT.key" JdbcUtils.normalizeSql(query)
"$SemanticAttributes.DB_CONNECTION_STRING.key" "hsqldb:mem:"
}
}

View File

@ -7,11 +7,11 @@ import static io.opentelemetry.api.trace.Span.Kind.CONSUMER
import static io.opentelemetry.api.trace.Span.Kind.PRODUCER
import com.google.common.io.Files
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import io.opentelemetry.instrumentation.test.AgentTestRunner
import io.opentelemetry.instrumentation.test.asserts.TraceAssert
import io.opentelemetry.javaagent.instrumentation.jms.JMSTracer
import io.opentelemetry.javaagent.instrumentation.jms.JmsTracer
import io.opentelemetry.sdk.trace.data.SpanData
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicReference
import javax.jms.Message
@ -32,7 +32,7 @@ import org.hornetq.core.server.HornetQServers
import org.hornetq.jms.client.HornetQTextMessage
import spock.lang.Shared
class JMS2Test extends AgentTestRunner {
class Jms2Test extends AgentTestRunner {
@Shared
HornetQServer server
@Shared
@ -110,8 +110,8 @@ class JMS2Test extends AgentTestRunner {
destination | destinationType | destinationName
session.createQueue("someQueue") | "queue" | "someQueue"
session.createTopic("someTopic") | "topic" | "someTopic"
session.createTemporaryQueue() | "queue" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryQueue() | "queue" | JmsTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JmsTracer.TEMP_DESTINATION_NAME
}
def "sending to a MessageListener on #destinationName #destinationType generates a span"() {
@ -149,8 +149,8 @@ class JMS2Test extends AgentTestRunner {
destination | destinationType | destinationName
session.createQueue("someQueue") | "queue" | "someQueue"
session.createTopic("someTopic") | "topic" | "someTopic"
session.createTemporaryQueue() | "queue" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryQueue() | "queue" | JmsTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JmsTracer.TEMP_DESTINATION_NAME
}
def "failing to receive message with receiveNoWait on #destinationName #destinationType works"() {
@ -234,7 +234,7 @@ class JMS2Test extends AgentTestRunner {
"${SemanticAttributes.MESSAGING_SYSTEM.key}" "jms"
"${SemanticAttributes.MESSAGING_DESTINATION.key}" destinationName
"${SemanticAttributes.MESSAGING_DESTINATION_KIND.key}" destinationType
if (destinationName == JMSTracer.TEMP_DESTINATION_NAME) {
if (destinationName == JmsTracer.TEMP_DESTINATION_NAME) {
"${SemanticAttributes.MESSAGING_TEMP_DESTINATION.key}" true
}
}
@ -263,7 +263,7 @@ class JMS2Test extends AgentTestRunner {
//In some tests we don't know exact messageId, so we pass "" and verify just the existence of the attribute
"${SemanticAttributes.MESSAGING_MESSAGE_ID.key}" { it == messageId || messageId == "" }
}
if (destinationName == JMSTracer.TEMP_DESTINATION_NAME) {
if (destinationName == JmsTracer.TEMP_DESTINATION_NAME) {
"${SemanticAttributes.MESSAGING_TEMP_DESTINATION.key}" true
}
}

View File

@ -3,8 +3,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
import static JMS2Test.consumerSpan
import static JMS2Test.producerSpan
import static Jms2Test.consumerSpan
import static Jms2Test.producerSpan
import io.opentelemetry.instrumentation.test.AgentTestRunner
import javax.jms.ConnectionFactory
@ -12,22 +12,22 @@ import listener.Config
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.jms.core.JmsTemplate
class SpringListenerJMS2Test extends AgentTestRunner {
class SpringListenerJms2Test extends AgentTestRunner {
def "receiving message in spring listener generates spans"() {
setup:
def context = new AnnotationConfigApplicationContext(Config)
def factory = context.getBean(ConnectionFactory)
def template = new JmsTemplate(factory)
template.convertAndSend("SpringListenerJMS2", "a message")
template.convertAndSend("SpringListenerJms2", "a message")
expect:
assertTraces(2) {
trace(0, 2) {
producerSpan(it, 0, "queue", "SpringListenerJMS2")
consumerSpan(it, 1, "queue", "SpringListenerJMS2", "", span(0), "process")
producerSpan(it, 0, "queue", "SpringListenerJms2")
consumerSpan(it, 1, "queue", "SpringListenerJms2", "", span(0), "process")
}
trace(1, 1) {
consumerSpan(it, 0, "queue", "SpringListenerJMS2", "", null, "receive")
consumerSpan(it, 0, "queue", "SpringListenerJms2", "", null, "receive")
}
}

View File

@ -3,8 +3,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
import static JMS2Test.consumerSpan
import static JMS2Test.producerSpan
import static Jms2Test.consumerSpan
import static Jms2Test.producerSpan
import com.google.common.io.Files
import io.opentelemetry.instrumentation.test.AgentTestRunner
@ -26,7 +26,7 @@ import org.hornetq.core.server.HornetQServers
import org.springframework.jms.core.JmsTemplate
import spock.lang.Shared
class SpringTemplateJMS2Test extends AgentTestRunner {
class SpringTemplateJms2Test extends AgentTestRunner {
@Shared
HornetQServer server
@Shared
@ -56,7 +56,7 @@ class SpringTemplateJMS2Test extends AgentTestRunner {
def serverLocator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(InVMConnectorFactory.name))
def sf = serverLocator.createSessionFactory()
def clientSession = sf.createSession(false, false, false)
clientSession.createQueue("jms.queue.SpringTemplateJMS2", "jms.queue.SpringTemplateJMS2", true)
clientSession.createQueue("jms.queue.SpringTemplateJms2", "jms.queue.SpringTemplateJms2", true)
clientSession.close()
sf.close()
serverLocator.close()
@ -95,7 +95,7 @@ class SpringTemplateJMS2Test extends AgentTestRunner {
where:
destination | destinationType | destinationName
session.createQueue("SpringTemplateJMS2") | "queue" | "SpringTemplateJMS2"
session.createQueue("SpringTemplateJms2") | "queue" | "SpringTemplateJms2"
}
def "send and receive message generates spans"() {
@ -134,6 +134,6 @@ class SpringTemplateJMS2Test extends AgentTestRunner {
where:
destination | destinationType | destinationName
session.createQueue("SpringTemplateJMS2") | "queue" | "SpringTemplateJMS2"
session.createQueue("SpringTemplateJms2") | "queue" | "SpringTemplateJms2"
}
}

View File

@ -53,7 +53,7 @@ class Config {
def serverLocator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(InVMConnectorFactory.name))
def sf = serverLocator.createSessionFactory()
def clientSession = sf.createSession(false, false, false)
clientSession.createQueue("jms.queue.SpringListenerJMS2", "jms.queue.SpringListenerJMS2", true)
clientSession.createQueue("jms.queue.SpringListenerJms2", "jms.queue.SpringListenerJms2", true)
clientSession.close()
sf.close()
serverLocator.close()

View File

@ -11,7 +11,7 @@ import org.springframework.stereotype.Component
@Component
class TestListener {
@JmsListener(destination = "SpringListenerJMS2", containerFactory = "containerFactory")
@JmsListener(destination = "SpringListenerJms2", containerFactory = "containerFactory")
void receiveMessage(String message) {
println "received: " + message
}

View File

@ -24,7 +24,7 @@ public class JmsInstrumentationModule extends InstrumentationModule {
public String[] helperClassNames() {
return new String[] {
packageName + ".MessageDestination",
packageName + ".JMSTracer",
packageName + ".JmsTracer",
packageName + ".MessageExtractAdapter",
packageName + ".MessageInjectAdapter"
};
@ -33,10 +33,10 @@ public class JmsInstrumentationModule extends InstrumentationModule {
@Override
public List<TypeInstrumentation> typeInstrumentations() {
return asList(
new JMSMessageConsumerInstrumentation(),
new JMSMessageListenerInstrumentation(),
new JMSMessageProducerInstrumentation(),
new JMSSessionInstrumentation());
new JmsMessageConsumerInstrumentation(),
new JmsMessageListenerInstrumentation(),
new JmsMessageProducerInstrumentation(),
new JmsSessionInstrumentation());
}
@Override

View File

@ -5,7 +5,7 @@
package io.opentelemetry.javaagent.instrumentation.jms;
import static io.opentelemetry.javaagent.instrumentation.jms.JMSTracer.tracer;
import static io.opentelemetry.javaagent.instrumentation.jms.JmsTracer.tracer;
import static io.opentelemetry.javaagent.tooling.ClassLoaderMatcher.hasClassesNamed;
import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.AgentElementMatchers.implementsInterface;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
@ -24,7 +24,7 @@ import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
final class JMSMessageConsumerInstrumentation implements TypeInstrumentation {
final class JmsMessageConsumerInstrumentation implements TypeInstrumentation {
@Override
public ElementMatcher<ClassLoader> classLoaderMatcher() {
@ -42,10 +42,10 @@ final class JMSMessageConsumerInstrumentation implements TypeInstrumentation {
Map<ElementMatcher<? super MethodDescription>, String> transformers = new HashMap<>();
transformers.put(
named("receive").and(takesArguments(0).or(takesArguments(1))).and(isPublic()),
JMSMessageConsumerInstrumentation.class.getName() + "$ConsumerAdvice");
JmsMessageConsumerInstrumentation.class.getName() + "$ConsumerAdvice");
transformers.put(
named("receiveNoWait").and(takesArguments(0)).and(isPublic()),
JMSMessageConsumerInstrumentation.class.getName() + "$ConsumerAdvice");
JmsMessageConsumerInstrumentation.class.getName() + "$ConsumerAdvice");
return transformers;
}

View File

@ -5,7 +5,7 @@
package io.opentelemetry.javaagent.instrumentation.jms;
import static io.opentelemetry.javaagent.instrumentation.jms.JMSTracer.tracer;
import static io.opentelemetry.javaagent.instrumentation.jms.JmsTracer.tracer;
import static io.opentelemetry.javaagent.tooling.ClassLoaderMatcher.hasClassesNamed;
import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.AgentElementMatchers.implementsInterface;
import static java.util.Collections.singletonMap;
@ -23,7 +23,7 @@ import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
final class JMSMessageListenerInstrumentation implements TypeInstrumentation {
final class JmsMessageListenerInstrumentation implements TypeInstrumentation {
@Override
public ElementMatcher<ClassLoader> classLoaderMatcher() {
@ -40,7 +40,7 @@ final class JMSMessageListenerInstrumentation implements TypeInstrumentation {
public Map<? extends ElementMatcher<? super MethodDescription>, String> transformers() {
return singletonMap(
named("onMessage").and(takesArgument(0, named("javax.jms.Message"))).and(isPublic()),
JMSMessageListenerInstrumentation.class.getName() + "$MessageListenerAdvice");
JmsMessageListenerInstrumentation.class.getName() + "$MessageListenerAdvice");
}
public static class MessageListenerAdvice {

View File

@ -5,7 +5,7 @@
package io.opentelemetry.javaagent.instrumentation.jms;
import static io.opentelemetry.javaagent.instrumentation.jms.JMSTracer.tracer;
import static io.opentelemetry.javaagent.instrumentation.jms.JmsTracer.tracer;
import static io.opentelemetry.javaagent.tooling.ClassLoaderMatcher.hasClassesNamed;
import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.AgentElementMatchers.implementsInterface;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
@ -27,7 +27,7 @@ import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
final class JMSMessageProducerInstrumentation implements TypeInstrumentation {
final class JmsMessageProducerInstrumentation implements TypeInstrumentation {
@Override
public ElementMatcher<ClassLoader> classLoaderMatcher() {
@ -45,13 +45,13 @@ final class JMSMessageProducerInstrumentation implements TypeInstrumentation {
Map<ElementMatcher<? super MethodDescription>, String> transformers = new HashMap<>();
transformers.put(
named("send").and(takesArgument(0, named("javax.jms.Message"))).and(isPublic()),
JMSMessageProducerInstrumentation.class.getName() + "$ProducerAdvice");
JmsMessageProducerInstrumentation.class.getName() + "$ProducerAdvice");
transformers.put(
named("send")
.and(takesArgument(0, named("javax.jms.Destination")))
.and(takesArgument(1, named("javax.jms.Message")))
.and(isPublic()),
JMSMessageProducerInstrumentation.class.getName() + "$ProducerWithDestinationAdvice");
JmsMessageProducerInstrumentation.class.getName() + "$ProducerWithDestinationAdvice");
return transformers;
}

View File

@ -22,7 +22,7 @@ import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
final class JMSSessionInstrumentation implements TypeInstrumentation {
final class JmsSessionInstrumentation implements TypeInstrumentation {
@Override
public ElementMatcher<ClassLoader> classLoaderMatcher() {
@ -41,7 +41,7 @@ final class JMSSessionInstrumentation implements TypeInstrumentation {
named("createConsumer")
.and(takesArgument(0, named("javax.jms.Destination")))
.and(isPublic()),
JMSSessionInstrumentation.class.getName() + "$ConsumerAdvice");
JmsSessionInstrumentation.class.getName() + "$ConsumerAdvice");
}
public static class ConsumerAdvice {
@ -49,7 +49,7 @@ final class JMSSessionInstrumentation implements TypeInstrumentation {
@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void onExit(
@Advice.Argument(0) Destination destination, @Advice.Return MessageConsumer consumer) {
MessageDestination messageDestination = JMSTracer.extractMessageDestination(destination);
MessageDestination messageDestination = JmsTracer.extractMessageDestination(destination);
InstrumentationContext.get(MessageConsumer.class, MessageDestination.class)
.put(consumer, messageDestination);
}

View File

@ -29,15 +29,15 @@ import javax.jms.Topic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JMSTracer extends BaseTracer {
private static final Logger log = LoggerFactory.getLogger(JMSTracer.class);
public class JmsTracer extends BaseTracer {
private static final Logger log = LoggerFactory.getLogger(JmsTracer.class);
// From the spec
public static final String TEMP_DESTINATION_NAME = "(temporary)";
private static final JMSTracer TRACER = new JMSTracer();
private static final JmsTracer TRACER = new JmsTracer();
public static JMSTracer tracer() {
public static JmsTracer tracer() {
return TRACER;
}
@ -143,18 +143,18 @@ public class JMSTracer extends BaseTracer {
if (message != null) {
try {
String messageID = message.getJMSMessageID();
if (messageID != null) {
span.setAttribute(SemanticAttributes.MESSAGING_MESSAGE_ID, messageID);
String messageId = message.getJMSMessageID();
if (messageId != null) {
span.setAttribute(SemanticAttributes.MESSAGING_MESSAGE_ID, messageId);
}
} catch (Exception e) {
log.debug("Failure getting JMS message id", e);
}
try {
String correlationID = message.getJMSCorrelationID();
if (correlationID != null) {
span.setAttribute(SemanticAttributes.MESSAGING_CONVERSATION_ID, correlationID);
String correlationId = message.getJMSCorrelationID();
if (correlationId != null) {
span.setAttribute(SemanticAttributes.MESSAGING_CONVERSATION_ID, correlationId);
}
} catch (Exception e) {
log.debug("Failure getting JMS correlation id", e);

View File

@ -6,11 +6,11 @@
import static io.opentelemetry.api.trace.Span.Kind.CONSUMER
import static io.opentelemetry.api.trace.Span.Kind.PRODUCER
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import io.opentelemetry.instrumentation.test.AgentTestRunner
import io.opentelemetry.instrumentation.test.asserts.TraceAssert
import io.opentelemetry.javaagent.instrumentation.jms.JMSTracer
import io.opentelemetry.javaagent.instrumentation.jms.JmsTracer
import io.opentelemetry.sdk.trace.data.SpanData
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicReference
import javax.jms.Connection
@ -28,9 +28,9 @@ import spock.lang.Requires
import spock.lang.Shared
@Requires({ "true" != System.getenv("CIRCLECI") })
class JMS1Test extends AgentTestRunner {
class Jms1Test extends AgentTestRunner {
private static final Logger logger = LoggerFactory.getLogger(JMS1Test)
private static final Logger logger = LoggerFactory.getLogger(Jms1Test)
private static final GenericContainer broker = new GenericContainer("rmohr/activemq")
.withExposedPorts(61616, 8161)
@ -85,8 +85,8 @@ class JMS1Test extends AgentTestRunner {
destination | destinationType | destinationName
session.createQueue("someQueue") | "queue" | "someQueue"
session.createTopic("someTopic") | "topic" | "someTopic"
session.createTemporaryQueue() | "queue" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryQueue() | "queue" | JmsTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JmsTracer.TEMP_DESTINATION_NAME
}
def "sending to a MessageListener on #destinationName #destinationType generates a span"() {
@ -124,8 +124,8 @@ class JMS1Test extends AgentTestRunner {
destination | destinationType | destinationName
session.createQueue("someQueue") | "queue" | "someQueue"
session.createTopic("someTopic") | "topic" | "someTopic"
session.createTemporaryQueue() | "queue" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryQueue() | "queue" | JmsTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JmsTracer.TEMP_DESTINATION_NAME
}
def "failing to receive message with receiveNoWait on #destinationName #destinationType works"() {
@ -235,7 +235,7 @@ class JMS1Test extends AgentTestRunner {
"${SemanticAttributes.MESSAGING_DESTINATION_KIND.key}" destinationType
"${SemanticAttributes.MESSAGING_MESSAGE_ID.key}" receivedMessage.getJMSMessageID()
"${SemanticAttributes.MESSAGING_OPERATION.key}" "receive"
if (destinationName == JMSTracer.TEMP_DESTINATION_NAME) {
if (destinationName == JmsTracer.TEMP_DESTINATION_NAME) {
"${SemanticAttributes.MESSAGING_TEMP_DESTINATION.key}" true
}
}
@ -251,8 +251,8 @@ class JMS1Test extends AgentTestRunner {
destination | destinationType | destinationName
session.createQueue("someQueue") | "queue" | "someQueue"
session.createTopic("someTopic") | "topic" | "someTopic"
session.createTemporaryQueue() | "queue" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JMSTracer.TEMP_DESTINATION_NAME
session.createTemporaryQueue() | "queue" | JmsTracer.TEMP_DESTINATION_NAME
session.createTemporaryTopic() | "topic" | JmsTracer.TEMP_DESTINATION_NAME
}
static producerSpan(TraceAssert trace, int index, String destinationType, String destinationName) {
@ -265,7 +265,7 @@ class JMS1Test extends AgentTestRunner {
"${SemanticAttributes.MESSAGING_SYSTEM.key}" "jms"
"${SemanticAttributes.MESSAGING_DESTINATION.key}" destinationName
"${SemanticAttributes.MESSAGING_DESTINATION_KIND.key}" destinationType
if (destinationName == JMSTracer.TEMP_DESTINATION_NAME) {
if (destinationName == JmsTracer.TEMP_DESTINATION_NAME) {
"${SemanticAttributes.MESSAGING_TEMP_DESTINATION.key}" true
}
}
@ -294,7 +294,7 @@ class JMS1Test extends AgentTestRunner {
//In some tests we don't know exact messageId, so we pass "" and verify just the existence of the attribute
"${SemanticAttributes.MESSAGING_MESSAGE_ID.key}" { it == messageId || messageId == "" }
}
if (destinationName == JMSTracer.TEMP_DESTINATION_NAME) {
if (destinationName == JmsTracer.TEMP_DESTINATION_NAME) {
"${SemanticAttributes.MESSAGING_TEMP_DESTINATION.key}" true
}
}

View File

@ -3,8 +3,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
import static JMS1Test.consumerSpan
import static JMS1Test.producerSpan
import static Jms1Test.consumerSpan
import static Jms1Test.producerSpan
import io.opentelemetry.instrumentation.test.AgentTestRunner
import javax.jms.ConnectionFactory
@ -14,23 +14,23 @@ import org.springframework.jms.core.JmsTemplate
import spock.lang.Requires
@Requires({ "true" != System.getenv("CIRCLECI") })
class SpringListenerJMS1Test extends AgentTestRunner {
class SpringListenerJms1Test extends AgentTestRunner {
def "receiving message in spring listener generates spans"() {
setup:
def context = new AnnotationConfigApplicationContext(Config)
def factory = context.getBean(ConnectionFactory)
def template = new JmsTemplate(factory)
template.convertAndSend("SpringListenerJMS1", "a message")
template.convertAndSend("SpringListenerJms1", "a message")
expect:
assertTraces(2) {
trace(0, 2) {
producerSpan(it, 0, "queue", "SpringListenerJMS1")
consumerSpan(it, 1, "queue", "SpringListenerJMS1", "", span(0), "process")
producerSpan(it, 0, "queue", "SpringListenerJms1")
consumerSpan(it, 1, "queue", "SpringListenerJms1", "", span(0), "process")
}
trace(1, 1) {
consumerSpan(it, 0, "queue", "SpringListenerJMS1", "", null, "receive")
consumerSpan(it, 0, "queue", "SpringListenerJms1", "", null, "receive")
}
}

View File

@ -3,12 +3,12 @@
* SPDX-License-Identifier: Apache-2.0
*/
import static JMS1Test.consumerSpan
import static JMS1Test.producerSpan
import static Jms1Test.consumerSpan
import static Jms1Test.producerSpan
import com.google.common.base.Stopwatch
import io.opentelemetry.instrumentation.test.AgentTestRunner
import io.opentelemetry.javaagent.instrumentation.jms.JMSTracer
import io.opentelemetry.javaagent.instrumentation.jms.JmsTracer
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import javax.jms.Connection
@ -24,8 +24,8 @@ import spock.lang.Requires
import spock.lang.Shared
@Requires({ "true" != System.getenv("CIRCLECI") })
class SpringTemplateJMS1Test extends AgentTestRunner {
private static final Logger logger = LoggerFactory.getLogger(SpringTemplateJMS1Test)
class SpringTemplateJms1Test extends AgentTestRunner {
private static final Logger logger = LoggerFactory.getLogger(SpringTemplateJms1Test)
private static final GenericContainer broker = new GenericContainer("rmohr/activemq")
.withExposedPorts(61616, 8161)
@ -73,7 +73,7 @@ class SpringTemplateJMS1Test extends AgentTestRunner {
where:
destination | destinationType | destinationName
session.createQueue("SpringTemplateJMS1") | "queue" | "SpringTemplateJMS1"
session.createQueue("SpringTemplateJms1") | "queue" | "SpringTemplateJms1"
}
def "send and receive message generates spans"() {
@ -108,15 +108,15 @@ class SpringTemplateJMS1Test extends AgentTestRunner {
}
trace(2, 1) {
// receive doesn't propagate the trace, so this is a root
producerSpan(it, 0, "queue", JMSTracer.TEMP_DESTINATION_NAME)
producerSpan(it, 0, "queue", JmsTracer.TEMP_DESTINATION_NAME)
}
trace(3, 1) {
consumerSpan(it, 0, "queue", JMSTracer.TEMP_DESTINATION_NAME, receivedMessage.getJMSMessageID(), null, "receive")
consumerSpan(it, 0, "queue", JmsTracer.TEMP_DESTINATION_NAME, receivedMessage.getJMSMessageID(), null, "receive")
}
}
where:
destination | destinationType | destinationName
session.createQueue("SpringTemplateJMS1") | "queue" | "SpringTemplateJMS1"
session.createQueue("SpringTemplateJms1") | "queue" | "SpringTemplateJms1"
}
}

View File

@ -11,7 +11,7 @@ import org.springframework.stereotype.Component
@Component
class TestListener {
@JmsListener(destination = "SpringListenerJMS1", containerFactory = "containerFactory")
@JmsListener(destination = "SpringListenerJms1", containerFactory = "containerFactory")
void receiveMessage(String message) {
println "received: " + message
}

View File

@ -5,7 +5,7 @@
package io.opentelemetry.javaagent.instrumentation.jsp;
import static io.opentelemetry.javaagent.instrumentation.jsp.JSPTracer.tracer;
import static io.opentelemetry.javaagent.instrumentation.jsp.JspTracer.tracer;
import static io.opentelemetry.javaagent.tooling.ClassLoaderMatcher.hasClassesNamed;
import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.AgentElementMatchers.implementsInterface;
import static java.util.Collections.singletonMap;

View File

@ -5,7 +5,7 @@
package io.opentelemetry.javaagent.instrumentation.jsp;
import static io.opentelemetry.javaagent.instrumentation.jsp.JSPTracer.tracer;
import static io.opentelemetry.javaagent.instrumentation.jsp.JspTracer.tracer;
import static java.util.Collections.singletonMap;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
import static net.bytebuddy.matcher.ElementMatchers.named;

View File

@ -21,7 +21,7 @@ public class JspInstrumentationModule extends InstrumentationModule {
@Override
public String[] helperClassNames() {
return new String[] {
packageName + ".JSPTracer",
packageName + ".JspTracer",
};
}

View File

@ -17,10 +17,10 @@ import org.apache.jasper.JspCompilationContext;
import org.apache.jasper.compiler.Compiler;
import org.slf4j.LoggerFactory;
public class JSPTracer extends BaseTracer {
private static final JSPTracer TRACER = new JSPTracer();
public class JspTracer extends BaseTracer {
private static final JspTracer TRACER = new JspTracer();
public static JSPTracer tracer() {
public static JspTracer tracer() {
return TRACER;
}
@ -68,9 +68,9 @@ public class JSPTracer extends BaseTracer {
try {
span.setAttribute(
"jsp.requestURL", (new URI(req.getRequestURL().toString())).normalize().toString());
} catch (URISyntaxException uriSE) {
} catch (URISyntaxException e) {
LoggerFactory.getLogger(HttpJspPage.class)
.warn("Failed to get and normalize request URL: " + uriSE.getMessage());
.warn("Failed to get and normalize request URL: " + e.getMessage());
}
}

View File

@ -6,10 +6,10 @@
import static io.opentelemetry.api.trace.Span.Kind.SERVER
import com.google.common.io.Files
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import io.opentelemetry.instrumentation.test.AgentTestRunner
import io.opentelemetry.instrumentation.test.utils.OkHttpUtils
import io.opentelemetry.instrumentation.test.utils.PortUtils
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
@ -22,7 +22,7 @@ import spock.lang.Shared
import spock.lang.Unroll
//TODO should this be HttpServerTest?
class JSPInstrumentationBasicTests extends AgentTestRunner {
class JspInstrumentationBasicTests extends AgentTestRunner {
static {
// skip jar scanning using environment variables:
@ -68,7 +68,7 @@ class JSPInstrumentationBasicTests extends AgentTestRunner {
baseUrl = "http://localhost:$port/$jspWebappContext"
appContext = tomcatServer.addWebapp("/$jspWebappContext",
JSPInstrumentationBasicTests.getResource("/webapps/jsptest").getPath())
JspInstrumentationBasicTests.getResource("/webapps/jsptest").getPath())
tomcatServer.start()
System.out.println(

View File

@ -6,10 +6,10 @@
import static io.opentelemetry.api.trace.Span.Kind.SERVER
import com.google.common.io.Files
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import io.opentelemetry.instrumentation.test.AgentTestRunner
import io.opentelemetry.instrumentation.test.utils.OkHttpUtils
import io.opentelemetry.instrumentation.test.utils.PortUtils
import io.opentelemetry.api.trace.attributes.SemanticAttributes
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
@ -19,7 +19,7 @@ import org.apache.jasper.JasperException
import spock.lang.Shared
import spock.lang.Unroll
class JSPInstrumentationForwardTests extends AgentTestRunner {
class JspInstrumentationForwardTests extends AgentTestRunner {
static {
// skip jar scanning using environment variables:
@ -66,7 +66,7 @@ class JSPInstrumentationForwardTests extends AgentTestRunner {
baseUrl = "http://localhost:$port/$jspWebappContext"
appContext = tomcatServer.addWebapp("/$jspWebappContext",
JSPInstrumentationForwardTests.getResource("/webapps/jsptest").getPath())
JspInstrumentationForwardTests.getResource("/webapps/jsptest").getPath())
tomcatServer.start()
System.out.println(

View File

@ -43,8 +43,9 @@ public enum KubernetesVerb {
return DELETE_COLLECTION;
}
return DELETE;
default:
throw new IllegalArgumentException("invalid HTTP verb for kubernetes client");
}
throw new IllegalArgumentException("invalid HTTP verb for kubernetes client");
}
public String value() {

View File

@ -57,8 +57,8 @@ public final class InstrumentationPoints {
spanWithScope.closeScope();
}
public static SpanWithScope beforeConnect(RedisURI redisURI) {
Span span = LettuceConnectionDatabaseClientTracer.tracer().startSpan(redisURI, "CONNECT");
public static SpanWithScope beforeConnect(RedisURI redisUri) {
Span span = LettuceConnectionDatabaseClientTracer.tracer().startSpan(redisUri, "CONNECT");
return new SpanWithScope(span, LettuceConnectionDatabaseClientTracer.tracer().startScope(span));
}
@ -75,7 +75,7 @@ public final class InstrumentationPoints {
/**
* Determines whether a redis command should finish its relevant span early (as soon as tags are
* added and the command is executed) because these commands have no return values/call backs, so
* we must close the span early in order to provide info for the users
* we must close the span early in order to provide info for the users.
*
* @return false if the span should finish early (the command will not have a return value)
*/

View File

@ -21,8 +21,8 @@ public abstract class LettuceAbstractDatabaseClientTracer<QUERY>
}
@Override
protected InetSocketAddress peerAddress(RedisURI redisURI) {
return new InetSocketAddress(redisURI.getHost(), redisURI.getPort());
protected InetSocketAddress peerAddress(RedisURI redisUri) {
return new InetSocketAddress(redisUri.getHost(), redisUri.getPort());
}
@Override

View File

@ -12,8 +12,8 @@ import net.bytebuddy.asm.Advice;
public class RedisConnectionAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static SpanWithScope onEnter(@Advice.Argument(1) RedisURI redisURI) {
return InstrumentationPoints.beforeConnect(redisURI);
public static SpanWithScope onEnter(@Advice.Argument(1) RedisURI redisUri) {
return InstrumentationPoints.beforeConnect(redisUri);
}
@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)

View File

@ -17,10 +17,10 @@ public class ConnectionFutureAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static void onEnter(
@Advice.Argument(1) RedisURI redisURI,
@Advice.Argument(1) RedisURI redisUri,
@Advice.Local("otelSpan") Span span,
@Advice.Local("otelScope") Scope scope) {
span = tracer().startSpan(redisURI, "CONNECT");
span = tracer().startSpan(redisUri, "CONNECT");
scope = tracer().startScope(span);
}

View File

@ -25,8 +25,8 @@ public abstract class LettuceAbstractDatabaseClientTracer<QUERY>
}
@Override
protected InetSocketAddress peerAddress(RedisURI redisURI) {
return new InetSocketAddress(redisURI.getHost(), redisURI.getPort());
protected InetSocketAddress peerAddress(RedisURI redisUri) {
return new InetSocketAddress(redisUri.getHost(), redisUri.getPort());
}
@Override

View File

@ -13,7 +13,7 @@ import java.util.function.BiFunction;
/**
* Callback class to close the span on an error or a success in the RedisFuture returned by the
* lettuce async API
* lettuce async API.
*
* @param <T> the normal completion result
* @param <U> the error

View File

@ -21,9 +21,8 @@ public class LettuceInstrumentationUtil {
/**
* Determines whether a redis command should finish its relevant span early (as soon as tags are
* added and the command is executed) because these commands have no return values/call backs, so
* we must close the span early in order to provide info for the users
* we must close the span early in order to provide info for the users.
*
* @param command
* @return false if the span should finish early (the command will not have a return value)
*/
public static boolean expectsResponse(RedisCommand<?, ?, ?> command) {
@ -32,7 +31,7 @@ public class LettuceInstrumentationUtil {
}
/**
* Retrieves the actual redis command name from a RedisCommand object
* Retrieves the actual redis command name from a RedisCommand object.
*
* @param command the lettuce RedisCommand object
* @return the redis command as a string

View File

@ -81,6 +81,8 @@ final class LoggingEventInstrumentation implements TypeInstrumentation {
case SAMPLED:
value = Boolean.toString(spanContext.isSampled());
break;
default:
// do nothing
}
}
}

View File

@ -9,11 +9,11 @@ muzzle {
}
dependencies {
implementation project(':instrumentation:logback:logback-1.0.0:library')
implementation project(':instrumentation:logback:logback-1.0:library')
library group: 'ch.qos.logback', name: 'logback-classic', version: '1.0.0'
testImplementation project(':instrumentation:logback:logback-1.0.0:testing')
testImplementation project(':instrumentation:logback:logback-1.0:testing')
// 1.3+ contains breaking changes, check back after it stabilizes.
latestDepTestLibrary group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.+'

View File

@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.logback.v1_0_0;
package io.opentelemetry.javaagent.instrumentation.logback.v1_0;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonMap;
@ -24,9 +24,9 @@ public class LogbackInstrumentationModule extends InstrumentationModule {
@Override
public String[] helperClassNames() {
return new String[] {
"io.opentelemetry.instrumentation.logback.v1_0_0.internal.UnionMap",
"io.opentelemetry.instrumentation.logback.v1_0_0.internal.UnionMap$ConcatenatedSet",
"io.opentelemetry.instrumentation.logback.v1_0_0.internal.UnionMap$ConcatenatedSet$ConcatenatedSetIterator"
"io.opentelemetry.instrumentation.logback.v1_0.internal.UnionMap",
"io.opentelemetry.instrumentation.logback.v1_0.internal.UnionMap$ConcatenatedSet",
"io.opentelemetry.instrumentation.logback.v1_0.internal.UnionMap$ConcatenatedSet$ConcatenatedSetIterator"
};
}

View File

@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.logback.v1_0_0;
package io.opentelemetry.javaagent.instrumentation.logback.v1_0;
import static java.util.Collections.singletonMap;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;

View File

@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.logback.v1_0_0;
package io.opentelemetry.javaagent.instrumentation.logback.v1_0;
import static io.opentelemetry.instrumentation.api.log.LoggingContextConstants.SAMPLED;
import static io.opentelemetry.instrumentation.api.log.LoggingContextConstants.SPAN_ID;
@ -18,7 +18,7 @@ import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
import ch.qos.logback.classic.spi.ILoggingEvent;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.instrumentation.logback.v1_0_0.internal.UnionMap;
import io.opentelemetry.instrumentation.logback.v1_0.internal.UnionMap;
import io.opentelemetry.javaagent.instrumentation.api.InstrumentationContext;
import io.opentelemetry.javaagent.tooling.TypeInstrumentation;
import java.util.HashMap;

View File

@ -3,9 +3,9 @@
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.logback.v1_0_0
package io.opentelemetry.javaagent.instrumentation.logback.v1_0
import io.opentelemetry.instrumentation.logback.v1_0_0.AbstractLogbackTest
import io.opentelemetry.instrumentation.logback.v1_0.AbstractLogbackTest
import io.opentelemetry.instrumentation.test.AgentTestTrait
class LogbackTest extends AbstractLogbackTest implements AgentTestTrait {

View File

@ -23,7 +23,7 @@ To use it, add the module to your application's runtime classpath and add the ap
```kotlin
dependencies {
runtimeOnly("io.opentelemetry.instrumentation:opentelemetry-logback-1.0.0:0.8.0-SNAPSHOT")
runtimeOnly("io.opentelemetry.instrumentation:opentelemetry-logback-1.0:0.8.0-SNAPSHOT")
}
```
@ -39,7 +39,7 @@ dependencies {
</appender>
<!-- Just wrap your logging appender, for example ConsoleAppender, with OpenTelemetryAppender -->
<appender name="OTEL" class="io.opentelemetry.instrumentation.logback.v1_0_0.OpenTelemetryAppender">
<appender name="OTEL" class="io.opentelemetry.instrumentation.logback.v1_0.OpenTelemetryAppender">
<appender-ref ref="CONSOLE" />
</appender>
...

View File

@ -3,7 +3,7 @@ apply from: "$rootDir/gradle/instrumentation-library.gradle"
dependencies {
library group: 'ch.qos.logback', name: 'logback-classic', version: '1.0.0'
testImplementation project(':instrumentation:logback:logback-1.0.0:testing')
testImplementation project(':instrumentation:logback:logback-1.0:testing')
// 1.3+ contains breaking changes, check back after it stabilizes.
latestDepTestLibrary group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.+'

View File

@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.logback.v1_0_0;
package io.opentelemetry.instrumentation.logback.v1_0;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;

View File

@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.logback.v1_0_0;
package io.opentelemetry.instrumentation.logback.v1_0;
import static io.opentelemetry.instrumentation.api.log.LoggingContextConstants.SAMPLED;
import static io.opentelemetry.instrumentation.api.log.LoggingContextConstants.SPAN_ID;
@ -16,7 +16,7 @@ import ch.qos.logback.core.spi.AppenderAttachable;
import ch.qos.logback.core.spi.AppenderAttachableImpl;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.instrumentation.logback.v1_0_0.internal.UnionMap;
import io.opentelemetry.instrumentation.logback.v1_0.internal.UnionMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

View File

@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.logback.v1_0_0.internal;
package io.opentelemetry.instrumentation.logback.v1_0.internal;
import java.util.AbstractMap;
import java.util.AbstractSet;

View File

@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.logback.v1_0_0
package io.opentelemetry.instrumentation.logback.v1_0
import io.opentelemetry.instrumentation.test.InstrumentationTestTrait

View File

@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.logback.v1_0_0.internal
package io.opentelemetry.instrumentation.logback.v1_0.internal
import spock.lang.Specification

Some files were not shown because too many files have changed in this diff Show More