From 5bf3376c8c69ee322de40ad1ec540f80469c575b Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 19 Jun 2021 04:33:45 +0800 Subject: [PATCH 01/69] Added jdbc library with ported version of OpenTracing JDBC Instrumentation. --- instrumentation/jdbc/library/NOTICE.txt | 19 + .../jdbc/library/jdbc-library.gradle | 1 + .../instrumentation/jdbc/Classes.java | 161 +++++ .../instrumentation/jdbc/ConnectionInfo.java | 131 ++++ .../instrumentation/jdbc/JdbcTracing.java | 65 ++ .../jdbc/JdbcTracingUtils.java | 182 +++++ .../jdbc/TracingCallableStatement.java | 631 ++++++++++++++++++ .../jdbc/TracingConnection.java | 371 ++++++++++ .../jdbc/TracingDataSource.java | 147 ++++ .../instrumentation/jdbc/TracingDriver.java | 275 ++++++++ .../jdbc/TracingPreparedStatement.java | 343 ++++++++++ .../jdbc/TracingStatement.java | 311 +++++++++ .../instrumentation/jdbc/WrapperProxy.java | 156 +++++ .../jdbc/parser/AS400URLParser.java | 43 ++ .../jdbc/parser/AbstractMatcherURLParser.java | 89 +++ .../jdbc/parser/AbstractURLParser.java | 68 ++ .../jdbc/parser/ConnectionURLParser.java | 29 + .../jdbc/parser/DB2URLParser.java | 44 ++ .../jdbc/parser/H2URLParser.java | 157 +++++ .../jdbc/parser/MariadbURLParser.java | 29 + .../jdbc/parser/MysqlURLParser.java | 116 ++++ .../jdbc/parser/OracleURLParser.java | 172 +++++ .../jdbc/parser/PostgreSQLURLParser.java | 86 +++ .../jdbc/parser/SqlServerURLParser.java | 111 +++ .../jdbc/parser/URLLocation.java | 41 ++ .../jdbc/parser/URLParser.java | 102 +++ .../META-INF/services/java.sql.Driver | 1 + settings.gradle | 1 + 28 files changed, 3882 insertions(+) create mode 100644 instrumentation/jdbc/library/NOTICE.txt create mode 100644 instrumentation/jdbc/library/jdbc-library.gradle create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java create mode 100644 instrumentation/jdbc/library/src/main/resources/META-INF/services/java.sql.Driver diff --git a/instrumentation/jdbc/library/NOTICE.txt b/instrumentation/jdbc/library/NOTICE.txt new file mode 100644 index 000000000000..b46b353fc4b2 --- /dev/null +++ b/instrumentation/jdbc/library/NOTICE.txt @@ -0,0 +1,19 @@ +This product contains a modified part of OpenTracing JDBC Instrumentation: + + * License: + + Copyright 2017-2021 The OpenTracing Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + * Homepage: https://github.com/opentracing-contrib/java-jdbc diff --git a/instrumentation/jdbc/library/jdbc-library.gradle b/instrumentation/jdbc/library/jdbc-library.gradle new file mode 100644 index 000000000000..9233e87a1921 --- /dev/null +++ b/instrumentation/jdbc/library/jdbc-library.gradle @@ -0,0 +1 @@ +apply plugin: "otel.library-instrumentation" diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java new file mode 100644 index 000000000000..8a2224331875 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java @@ -0,0 +1,161 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashSet; + +public final class Classes { + + /** + * Adds all interfaces extended by the specified {@code iface} interface {@link Class}. + * + * @param iface The interface {@link Class}. + * @param set The set into which all extended interfaces are to be added. + * @throws NullPointerException If {@code iface} or {@code set} is null. + */ + private static void recurse(final Class iface, final HashSet> set) { + if (set.contains(iface)) { + return; + } + + set.add(iface); + for (final Class extended : iface.getInterfaces()) { + recurse(extended, set); + } + } + + /** + * Returns all interfaces implemented by the class or interface represented by the specified + * class. This method differentiates itself from {@link Class#getInterfaces()} by returning + * all interfaces (full depth and breadth) instead of just the interfaces directly + * implemented by the class. + * + * @param cls The class. + * @return All interfaces implemented by the class or interface represented by the specified + * class. + * @throws NullPointerException If {@code cls} is null. + */ + public static Class[] getAllInterfaces(final Class cls) { + Class parent = cls; + Class[] ifaces = null; + HashSet> set = null; + do { + ifaces = parent.getInterfaces(); + if (ifaces.length == 0) { + continue; + } + + if (set == null) { + set = new HashSet<>(4); + } + + for (final Class iface : ifaces) { + recurse(iface, set); + } + } + while ((parent = parent.getSuperclass()) != null); + return set == null ? ifaces : set.toArray(new Class[set.size()]); + } + + /** + * Returns a Method object that reflects the specified declared method of the class or interface + * represented by {@code cls} (excluding inherited methods), or {@code null} if the method is not + * found. + *

+ * Declared methods include public, protected, default (package) access, and private visibility. + *

+ * The {@code name} parameter is a String that specifies the simple name of the desired method, + * and the {@code parameterTypes} parameter is an array of Class objects that identify the + * method's formal parameter types, in declared order. If more than one method with the same + * parameter types is declared in a class, and one of these methods has a return type that is more + * specific than any of the others, that method is returned; otherwise one of the methods is + * chosen arbitrarily. If the name is {@code ""} or {@code ""} this method returns + * {@code null}. If this Class object represents an array type, then this method does not find the + * clone() method. + *

+ * This method differentiates itself from {@link Class#getDeclaredMethod(String, Class...)} by + * returning {@code null} when a method is not found, instead of throwing {@link + * NoSuchMethodException}. + * + * @param cls The class in which to find the declared method. + * @param name The simple name of the method. + * @param parameterTypes The parameter array. + * @return A Method object that reflects the specified declared method of the class or interface + * represented by {@code cls} (excluding inherited methods), or {@code null} if the method is not + * found. + * @throws NullPointerException If {@code cls} or {@code name} is null. + */ + public static Method getDeclaredMethod(final Class cls, final String name, + final Class... parameterTypes) { + final Method[] methods = cls.getDeclaredMethods(); + for (final Method method : methods) { + if (name.equals(method.getName()) && Arrays + .equals(method.getParameterTypes(), parameterTypes)) { + return method; + } + } + + return null; + } + + /** + * Returns a Method object that reflects the specified declared method of the class or interface + * represented by {@code cls} (including inherited methods), or {@code null} if the method is not + * found. + *

+ * Declared methods include public, protected, default (package) access, and private visibility. + *

+ * The {@code name} parameter is a String that specifies the simple name of the desired method, + * and the {@code parameterTypes} parameter is an array of Class objects that identify the + * method's formal parameter types, in declared order. If more than one method with the same + * parameter types is declared in a class, and one of these methods has a return type that is more + * specific than any of the others, that method is returned; otherwise one of the methods is + * chosen arbitrarily. If the name is {@code ""} or {@code ""} this method returns + * {@code null}. If this Class object represents an array type, then this method does not find the + * clone() method. + *

+ * This method differentiates itself from {@link Class#getDeclaredMethod(String, Class...)} by + * returning {@code null} when a method is not found, instead of throwing {@link + * NoSuchMethodException}. + * + * @param cls The class in which to find the declared method. + * @param name The simple name of the method. + * @param parameterTypes The parameter array. + * @return A Method object that reflects the specified declared method of the class or interface + * represented by {@code cls} (including inherited methods), or {@code null} if the method is not + * found. + * @throws NullPointerException If {@code cls} or {@code name} is null. + */ + public static Method getDeclaredMethodDeep(Class cls, final String name, + final Class... parameterTypes) { + Method method; + do { + method = getDeclaredMethod(cls, name, parameterTypes); + } + while (method == null && (cls = cls.getSuperclass()) != null); + return method; + } + + private Classes() { + } +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java new file mode 100644 index 000000000000..f2d87ecbd725 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java @@ -0,0 +1,131 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +public class ConnectionInfo { + + public static ConnectionInfo UNKNOWN_CONNECTION_INFO = new Builder("unknown_peer") + .dbType("unknown_type").dbInstance("unknown_instance").build(); + + private final String dbType; + private final String dbUser; + private final String dbInstance; + private final String dbPeer; + private final String dbPeerService; + + private ConnectionInfo(String dbType, String dbUser, String dbInstance, String dbHost, + Integer dbPort) { + this.dbType = dbType; + this.dbUser = dbUser; + this.dbInstance = dbInstance; + if (dbHost != null && dbPort != null) { + this.dbPeer = dbHost + ":" + dbPort; + } else { + this.dbPeer = ""; + } + + this.dbPeerService = makePeerService(); + } + + private ConnectionInfo(String dbType, String dbUser, String dbInstance, String dbPeer) { + this.dbType = dbType; + this.dbUser = dbUser; + this.dbInstance = dbInstance; + this.dbPeer = dbPeer; + + this.dbPeerService = makePeerService(); + } + + /** + * Make a unique serviceName that could be used in dependency diagram. + */ + private String makePeerService() { + if (null != dbInstance && !dbInstance.isEmpty()) { + return dbInstance + "[" + dbType + "(" + dbPeer + ")]"; + } else { + return dbType + "(" + dbPeer + ")"; + } + } + + public String getDbType() { + return dbType; + } + + public String getDbUser() { + return dbUser; + } + + public String getDbInstance() { + return dbInstance; + } + + public String getDbPeer() { + return dbPeer; + } + + public String getPeerService() { + return dbPeerService; + } + + public static class Builder { + + private String dbType; + private String dbUser; + private String dbInstance; + private String dbHost; + private Integer dbPort; + private String dbPeer; + + public Builder(String dbPeer) { + this.dbPeer = dbPeer; + } + + public Builder(String dbHost, Integer dbPort) { + this.dbHost = dbHost; + this.dbPort = dbPort; + } + + public Builder dbType(String dbType) { + this.dbType = dbType; + return this; + } + + public Builder dbUser(String dbUser) { + this.dbUser = dbUser; + return this; + } + + public Builder dbInstance(String dbInstance) { + this.dbInstance = dbInstance; + return this; + } + + public ConnectionInfo build() { + if (this.dbPeer != null && !dbPeer.isEmpty()) { + return new ConnectionInfo(this.dbType, this.dbUser, this.dbInstance, this.dbPeer); + } + return new ConnectionInfo(this.dbType, this.dbUser, this.dbInstance, this.dbHost, + this.dbPort); + } + + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java new file mode 100644 index 000000000000..261f39bf7fc3 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java @@ -0,0 +1,65 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +public class JdbcTracing { + + private static boolean traceEnabled = true; + + /** + * Sets the {@code traceEnabled} property to enable or disable traces. + * + * @param traceEnabled The {@code traceEnabled} value. + */ + public static void setTraceEnabled(boolean traceEnabled) { + JdbcTracing.traceEnabled = traceEnabled; + } + + public static boolean isTraceEnabled() { + return JdbcTracing.traceEnabled; + } + + /** + * can be modified by application code + */ + private static int slowQueryThresholdMs = Integer + .getInteger("io.opentracing.contrib.jdbc.slowQueryThresholdMs", 0); + + public static int getSlowQueryThresholdMs() { + return slowQueryThresholdMs; + } + + public static void setSlowQueryThresholdMs(final int slowQueryThresholdMs) { + JdbcTracing.slowQueryThresholdMs = slowQueryThresholdMs; + } + + private static int excludeFastQueryThresholdMs = Integer + .getInteger("io.opentracing.contrib.jdbc.excludeFastQueryThresholdMs", 0); + + public static int getExcludeFastQueryThresholdMs() { + return excludeFastQueryThresholdMs; + } + + public static void setExcludeFastQueryThresholdMs(final int excludeFastQueryThresholdMs) { + JdbcTracing.excludeFastQueryThresholdMs = excludeFastQueryThresholdMs; + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java new file mode 100644 index 000000000000..31d0a6484cbc --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java @@ -0,0 +1,182 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanBuilder; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.StatusCode; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +class JdbcTracingUtils { + + static final AttributeKey SLOW = AttributeKey.booleanKey("slow"); + + // TODO is it requires for OTEL? + static final AttributeKey SAMPLING_PRIORITY = AttributeKey.longKey("sampling.priority"); + + static Span buildSpan(String operationName, + String sql, + ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, + Set ignoreStatements, + Tracer tracer) { + if (!JdbcTracing.isTraceEnabled() + || (withActiveSpanOnly && Span.fromContextOrNull(Context.current()) == null)) { + // noop span + return Span.getInvalid(); + } else if (ignoreStatements != null && ignoreStatements.contains(sql)) { + // noop span + return Span.getInvalid(); + } + + SpanBuilder spanBuilder = tracer.spanBuilder(operationName) + .setSpanKind(SpanKind.CLIENT); + + Span span = spanBuilder.startSpan(); + decorate(span, sql, connectionInfo); + + return span; + } + + static void execute(String operationName, + CheckedRunnable runnable, + String sql, + ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, + Set ignoreStatements, + Tracer tracer) throws E { + if (!JdbcTracing.isTraceEnabled() + || (withActiveSpanOnly && Span.fromContextOrNull(Context.current()) == null)) { + runnable.run(); + return; + } + + final Span span = buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, + ignoreStatements, tracer); + long startTime = (JdbcTracing.getSlowQueryThresholdMs() > 0 + || JdbcTracing.getExcludeFastQueryThresholdMs() > 0) ? System.nanoTime() : 0; + try (Scope ignored = span.makeCurrent()) { + runnable.run(); + } catch (Exception e) { + JdbcTracingUtils.onError(e, span); + throw e; + } finally { + JdbcTracingUtils.queryThresholdChecks(span, startTime); + span.end(); + } + } + + static T call(String operationName, + CheckedCallable callable, + String sql, + ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, + Set ignoreStatements, + Tracer tracer) throws E { + if (!JdbcTracing.isTraceEnabled() + || (withActiveSpanOnly && Span.fromContextOrNull(Context.current()) == null)) { + return callable.call(); + } + + final Span span = buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, + ignoreStatements, tracer); + long startTime = JdbcTracing.getSlowQueryThresholdMs() > 0 ? System.nanoTime() : 0; + try (Scope ignored = span.makeCurrent()) { + return callable.call(); + } catch (Exception e) { + JdbcTracingUtils.onError(e, span); + throw e; + } finally { + JdbcTracingUtils.queryThresholdChecks(span, startTime); + span.end(); + } + } + + private static boolean isNotEmpty(CharSequence s) { + return s != null && !"".contentEquals(s); + } + + /** + * Add tags to span. Skip empty tags to avoid reported NPE in tracers. + */ + private static void decorate(Span span, String sql, ConnectionInfo connectionInfo) { + if (isNotEmpty(sql)) { + span.setAttribute(SemanticAttributes.DB_STATEMENT, sql); + } + if (isNotEmpty(connectionInfo.getDbType())) { + span.setAttribute(SemanticAttributes.DB_SYSTEM, connectionInfo.getDbType()); + } + if (isNotEmpty(connectionInfo.getDbPeer())) { + span.setAttribute(SemanticAttributes.NET_PEER_IP, connectionInfo.getDbPeer()); + } + if (isNotEmpty(connectionInfo.getDbInstance())) { + span.setAttribute(SemanticAttributes.DB_NAME, connectionInfo.getDbInstance()); + } + if (isNotEmpty(connectionInfo.getDbUser())) { + span.setAttribute(SemanticAttributes.DB_USER, connectionInfo.getDbUser()); + } + if (isNotEmpty(connectionInfo.getPeerService())) { + span.setAttribute(SemanticAttributes.PEER_SERVICE, connectionInfo.getPeerService()); + } + } + + static void onError(Throwable throwable, Span span) { + span.setStatus(StatusCode.ERROR); + + if (throwable != null) { + span.recordException(throwable); + } + } + + private static void queryThresholdChecks(Span span, long startTime) { + long completionTime = System.nanoTime() - startTime; + if (JdbcTracing.getExcludeFastQueryThresholdMs() > 0 && completionTime < TimeUnit.MILLISECONDS + .toNanos(JdbcTracing.getExcludeFastQueryThresholdMs())) { + span.setAttribute(SAMPLING_PRIORITY, 0); + } + if (JdbcTracing.getSlowQueryThresholdMs() > 0 && completionTime > TimeUnit.MILLISECONDS + .toNanos(JdbcTracing.getSlowQueryThresholdMs())) { + span.setAttribute(SLOW, true); + } + } + + @FunctionalInterface + interface CheckedRunnable { + + void run() throws E; + + } + + @FunctionalInterface + interface CheckedCallable { + + T call() throws E; + + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java new file mode 100644 index 000000000000..fb4ab347e4ec --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java @@ -0,0 +1,631 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +import io.opentelemetry.api.trace.Tracer; +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.Date; +import java.sql.NClob; +import java.sql.Ref; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLXML; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Map; +import java.util.Set; + +public class TracingCallableStatement extends TracingPreparedStatement implements + CallableStatement { + + private final CallableStatement statement; + + public TracingCallableStatement(CallableStatement statement, String query, + ConnectionInfo connectionInfo, boolean withActiveSpanOnly, Set ignoreStatements, + Tracer tracer) { + super(statement, query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + this.statement = statement; + } + + @Override + public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { + statement.registerOutParameter(parameterIndex, sqlType); + } + + @Override + public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { + statement.registerOutParameter(parameterIndex, sqlType, scale); + } + + @Override + public boolean wasNull() throws SQLException { + return statement.wasNull(); + } + + @Override + public String getString(int parameterIndex) throws SQLException { + return statement.getString(parameterIndex); + } + + @Override + public boolean getBoolean(int parameterIndex) throws SQLException { + return statement.getBoolean(parameterIndex); + } + + @Override + public byte getByte(int parameterIndex) throws SQLException { + return statement.getByte(parameterIndex); + } + + @Override + public short getShort(int parameterIndex) throws SQLException { + return statement.getShort(parameterIndex); + } + + @Override + public int getInt(int parameterIndex) throws SQLException { + return statement.getInt(parameterIndex); + } + + @Override + public long getLong(int parameterIndex) throws SQLException { + return statement.getLong(parameterIndex); + } + + @Override + public float getFloat(int parameterIndex) throws SQLException { + return statement.getFloat(parameterIndex); + } + + @Override + public double getDouble(int parameterIndex) throws SQLException { + return statement.getDouble(parameterIndex); + } + + @Override + @Deprecated + public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { + return statement.getBigDecimal(parameterIndex, scale); + } + + @Override + public byte[] getBytes(int parameterIndex) throws SQLException { + return statement.getBytes(parameterIndex); + } + + @Override + public Date getDate(int parameterIndex) throws SQLException { + return statement.getDate(parameterIndex); + } + + @Override + public Time getTime(int parameterIndex) throws SQLException { + return statement.getTime(parameterIndex); + } + + @Override + public Timestamp getTimestamp(int parameterIndex) throws SQLException { + return statement.getTimestamp(parameterIndex); + } + + @Override + public Object getObject(int parameterIndex) throws SQLException { + return statement.getObject(parameterIndex); + } + + @Override + public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { + return statement.getBigDecimal(parameterIndex); + } + + @Override + public Object getObject(int parameterIndex, Map> map) throws SQLException { + return statement.getObject(parameterIndex, map); + } + + @Override + public Ref getRef(int parameterIndex) throws SQLException { + return statement.getRef(parameterIndex); + } + + @Override + public Blob getBlob(int parameterIndex) throws SQLException { + return statement.getBlob(parameterIndex); + } + + @Override + public Clob getClob(int parameterIndex) throws SQLException { + return statement.getClob(parameterIndex); + } + + @Override + public Array getArray(int parameterIndex) throws SQLException { + return statement.getArray(parameterIndex); + } + + @Override + public Date getDate(int parameterIndex, Calendar cal) throws SQLException { + return statement.getDate(parameterIndex, cal); + } + + @Override + public Time getTime(int parameterIndex, Calendar cal) throws SQLException { + return statement.getTime(parameterIndex, cal); + } + + @Override + public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { + return statement.getTimestamp(parameterIndex, cal); + } + + @Override + public void registerOutParameter(int parameterIndex, int sqlType, String typeName) + throws SQLException { + statement.registerOutParameter(parameterIndex, sqlType, typeName); + } + + @Override + public void registerOutParameter(String parameterName, int sqlType) throws SQLException { + statement.registerOutParameter(parameterName, sqlType); + } + + @Override + public void registerOutParameter(String parameterName, int sqlType, int scale) + throws SQLException { + statement.registerOutParameter(parameterName, sqlType, scale); + } + + @Override + public void registerOutParameter(String parameterName, int sqlType, String typeName) + throws SQLException { + statement.registerOutParameter(parameterName, sqlType, typeName); + } + + @Override + public URL getURL(int parameterIndex) throws SQLException { + return statement.getURL(parameterIndex); + } + + @Override + public void setURL(String parameterName, URL val) throws SQLException { + statement.setURL(parameterName, val); + } + + @Override + public void setNull(String parameterName, int sqlType) throws SQLException { + statement.setNull(parameterName, sqlType); + } + + @Override + public void setBoolean(String parameterName, boolean x) throws SQLException { + statement.setBoolean(parameterName, x); + } + + @Override + public void setByte(String parameterName, byte x) throws SQLException { + statement.setByte(parameterName, x); + } + + @Override + public void setShort(String parameterName, short x) throws SQLException { + statement.setShort(parameterName, x); + } + + @Override + public void setInt(String parameterName, int x) throws SQLException { + statement.setInt(parameterName, x); + } + + @Override + public void setLong(String parameterName, long x) throws SQLException { + statement.setLong(parameterName, x); + } + + @Override + public void setFloat(String parameterName, float x) throws SQLException { + statement.setFloat(parameterName, x); + } + + @Override + public void setDouble(String parameterName, double x) throws SQLException { + statement.setDouble(parameterName, x); + } + + @Override + public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { + statement.setBigDecimal(parameterName, x); + } + + @Override + public void setString(String parameterName, String x) throws SQLException { + statement.setString(parameterName, x); + } + + @Override + public void setBytes(String parameterName, byte[] x) throws SQLException { + statement.setBytes(parameterName, x); + } + + @Override + public void setDate(String parameterName, Date x) throws SQLException { + statement.setDate(parameterName, x); + } + + @Override + public void setTime(String parameterName, Time x) throws SQLException { + statement.setTime(parameterName, x); + } + + @Override + public void setTimestamp(String parameterName, Timestamp x) throws SQLException { + statement.setTimestamp(parameterName, x); + } + + @Override + public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException { + statement.setAsciiStream(parameterName, x, length); + } + + @Override + public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException { + statement.setBinaryStream(parameterName, x, length); + } + + @Override + public void setObject(String parameterName, Object x, int targetSqlType, int scale) + throws SQLException { + statement.setObject(parameterName, x, targetSqlType, scale); + } + + @Override + public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { + statement.setObject(parameterName, x, targetSqlType); + } + + @Override + public void setObject(String parameterName, Object x) throws SQLException { + statement.setObject(parameterName, x); + } + + @Override + public void setCharacterStream(String parameterName, Reader reader, int length) + throws SQLException { + statement.setCharacterStream(parameterName, reader, length); + } + + @Override + public void setDate(String parameterName, Date x, Calendar cal) throws SQLException { + statement.setDate(parameterName, x, cal); + } + + @Override + public void setTime(String parameterName, Time x, Calendar cal) throws SQLException { + statement.setTime(parameterName, x, cal); + } + + @Override + public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { + statement.setTimestamp(parameterName, x, cal); + } + + @Override + public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { + statement.setNull(parameterName, sqlType, typeName); + } + + @Override + public String getString(String parameterName) throws SQLException { + return statement.getString(parameterName); + } + + @Override + public boolean getBoolean(String parameterName) throws SQLException { + return statement.getBoolean(parameterName); + } + + @Override + public byte getByte(String parameterName) throws SQLException { + return statement.getByte(parameterName); + } + + @Override + public short getShort(String parameterName) throws SQLException { + return statement.getShort(parameterName); + } + + @Override + public int getInt(String parameterName) throws SQLException { + return statement.getInt(parameterName); + } + + @Override + public long getLong(String parameterName) throws SQLException { + return statement.getLong(parameterName); + } + + @Override + public float getFloat(String parameterName) throws SQLException { + return statement.getFloat(parameterName); + } + + @Override + public double getDouble(String parameterName) throws SQLException { + return statement.getDouble(parameterName); + } + + @Override + public byte[] getBytes(String parameterName) throws SQLException { + return statement.getBytes(parameterName); + } + + @Override + public Date getDate(String parameterName) throws SQLException { + return statement.getDate(parameterName); + } + + @Override + public Time getTime(String parameterName) throws SQLException { + return statement.getTime(parameterName); + } + + @Override + public Timestamp getTimestamp(String parameterName) throws SQLException { + return statement.getTimestamp(parameterName); + } + + @Override + public Object getObject(String parameterName) throws SQLException { + return statement.getObject(parameterName); + } + + @Override + public BigDecimal getBigDecimal(String parameterName) throws SQLException { + return statement.getBigDecimal(parameterName); + } + + @Override + public Object getObject(String parameterName, Map> map) throws SQLException { + return statement.getObject(parameterName, map); + } + + @Override + public Ref getRef(String parameterName) throws SQLException { + return statement.getRef(parameterName); + } + + @Override + public Blob getBlob(String parameterName) throws SQLException { + return statement.getBlob(parameterName); + } + + @Override + public Clob getClob(String parameterName) throws SQLException { + return statement.getClob(parameterName); + } + + @Override + public Array getArray(String parameterName) throws SQLException { + return statement.getArray(parameterName); + } + + @Override + public Date getDate(String parameterName, Calendar cal) throws SQLException { + return statement.getDate(parameterName, cal); + } + + @Override + public Time getTime(String parameterName, Calendar cal) throws SQLException { + return statement.getTime(parameterName, cal); + } + + @Override + public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { + return statement.getTimestamp(parameterName, cal); + } + + @Override + public URL getURL(String parameterName) throws SQLException { + return statement.getURL(parameterName); + } + + @Override + public RowId getRowId(int parameterIndex) throws SQLException { + return statement.getRowId(parameterIndex); + } + + @Override + public RowId getRowId(String parameterName) throws SQLException { + return statement.getRowId(parameterName); + } + + @Override + public void setRowId(String parameterName, RowId x) throws SQLException { + statement.setRowId(parameterName, x); + } + + @Override + public void setNString(String parameterName, String value) throws SQLException { + statement.setNString(parameterName, value); + } + + @Override + public void setNCharacterStream(String parameterName, Reader value, long length) + throws SQLException { + statement.setNCharacterStream(parameterName, value, length); + } + + @Override + public void setNClob(String parameterName, NClob value) throws SQLException { + statement.setNClob(parameterName, value); + } + + @Override + public void setClob(String parameterName, Reader reader, long length) throws SQLException { + statement.setClob(parameterName, reader, length); + } + + @Override + public void setBlob(String parameterName, InputStream inputStream, long length) + throws SQLException { + statement.setBlob(parameterName, inputStream, length); + } + + @Override + public void setNClob(String parameterName, Reader reader, long length) throws SQLException { + statement.setNClob(parameterName, reader, length); + } + + @Override + public NClob getNClob(int parameterIndex) throws SQLException { + return statement.getNClob(parameterIndex); + } + + @Override + public NClob getNClob(String parameterName) throws SQLException { + return statement.getNClob(parameterName); + } + + @Override + public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { + statement.setSQLXML(parameterName, xmlObject); + } + + @Override + public SQLXML getSQLXML(int parameterIndex) throws SQLException { + return statement.getSQLXML(parameterIndex); + } + + @Override + public SQLXML getSQLXML(String parameterName) throws SQLException { + return statement.getSQLXML(parameterName); + } + + @Override + public String getNString(int parameterIndex) throws SQLException { + return statement.getNString(parameterIndex); + } + + @Override + public String getNString(String parameterName) throws SQLException { + return statement.getNString(parameterName); + } + + @Override + public Reader getNCharacterStream(int parameterIndex) throws SQLException { + return statement.getNCharacterStream(parameterIndex); + } + + @Override + public Reader getNCharacterStream(String parameterName) throws SQLException { + return statement.getNCharacterStream(parameterName); + } + + @Override + public Reader getCharacterStream(int parameterIndex) throws SQLException { + return statement.getCharacterStream(parameterIndex); + } + + @Override + public Reader getCharacterStream(String parameterName) throws SQLException { + return statement.getCharacterStream(parameterName); + } + + @Override + public void setBlob(String parameterName, Blob x) throws SQLException { + statement.setBlob(parameterName, x); + } + + @Override + public void setClob(String parameterName, Clob x) throws SQLException { + statement.setClob(parameterName, x); + } + + @Override + public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { + statement.setAsciiStream(parameterName, x, length); + } + + @Override + public void setBinaryStream(String parameterName, InputStream x, long length) + throws SQLException { + statement.setBinaryStream(parameterName, x, length); + } + + @Override + public void setCharacterStream(String parameterName, Reader reader, long length) + throws SQLException { + statement.setCharacterStream(parameterName, reader, length); + } + + @Override + public void setAsciiStream(String parameterName, InputStream x) throws SQLException { + statement.setAsciiStream(parameterName, x); + } + + @Override + public void setBinaryStream(String parameterName, InputStream x) throws SQLException { + statement.setBinaryStream(parameterName, x); + } + + @Override + public void setCharacterStream(String parameterName, Reader reader) throws SQLException { + statement.setCharacterStream(parameterName, reader); + } + + @Override + public void setNCharacterStream(String parameterName, Reader value) throws SQLException { + statement.setNCharacterStream(parameterName, value); + } + + @Override + public void setClob(String parameterName, Reader reader) throws SQLException { + statement.setClob(parameterName, reader); + } + + @Override + public void setBlob(String parameterName, InputStream inputStream) throws SQLException { + statement.setBlob(parameterName, inputStream); + } + + @Override + public void setNClob(String parameterName, Reader reader) throws SQLException { + statement.setNClob(parameterName, reader); + } + + @Override + public T getObject(int parameterIndex, Class type) throws SQLException { + return statement.getObject(parameterIndex, type); + } + + @Override + public T getObject(String parameterName, Class type) throws SQLException { + return statement.getObject(parameterName, type); + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java new file mode 100644 index 000000000000..2cd10fafb8f1 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java @@ -0,0 +1,371 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +import io.opentelemetry.api.trace.Tracer; +import java.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.NClob; +import java.sql.PreparedStatement; +import java.sql.SQLClientInfoException; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Savepoint; +import java.sql.Statement; +import java.sql.Struct; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.Executor; + +public class TracingConnection implements Connection { + + private final Connection connection; + private final ConnectionInfo connectionInfo; + private final boolean withActiveSpanOnly; + private final Set ignoreStatements; + private final Tracer tracer; + + public TracingConnection(Connection connection, ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, Set ignoreStatements, Tracer tracer) { + this.connection = connection; + this.connectionInfo = connectionInfo; + this.withActiveSpanOnly = withActiveSpanOnly; + this.ignoreStatements = ignoreStatements; + this.tracer = tracer; + } + + @Override + public Statement createStatement() throws SQLException { + final Statement statement = connection.createStatement(); + return WrapperProxy + .wrap(statement, new TracingStatement(statement, connectionInfo, withActiveSpanOnly, + ignoreStatements, tracer)); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency) + throws SQLException { + final Statement statement = connection.createStatement(resultSetType, resultSetConcurrency); + return WrapperProxy.wrap(statement, new TracingStatement(statement, + connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + final Statement statement = connection + .createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); + return WrapperProxy.wrap(statement, new TracingStatement(statement, + connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public PreparedStatement prepareStatement(String sql) throws SQLException { + final PreparedStatement statement = connection.prepareStatement(sql); + return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, connectionInfo, + withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) + throws SQLException { + final PreparedStatement statement = connection + .prepareStatement(sql, resultSetType, resultSetConcurrency); + return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, connectionInfo, + withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + final PreparedStatement statement = connection + .prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + final PreparedStatement statement = connection.prepareStatement(sql, autoGeneratedKeys); + return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, + connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + final PreparedStatement statement = connection.prepareStatement(sql, columnIndexes); + return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, + connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + final PreparedStatement statement = connection.prepareStatement(sql, columnNames); + return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, connectionInfo, + withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public CallableStatement prepareCall(String sql) throws SQLException { + final CallableStatement statement = connection.prepareCall(sql); + return WrapperProxy.wrap(statement, + new TracingCallableStatement(connection.prepareCall(sql), sql, connectionInfo, + withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) + throws SQLException { + final CallableStatement statement = connection + .prepareCall(sql, resultSetType, resultSetConcurrency); + return WrapperProxy.wrap(statement, new TracingCallableStatement(statement, sql, connectionInfo, + withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + final CallableStatement statement = connection + .prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + return WrapperProxy.wrap(statement, new TracingCallableStatement(statement, sql, + connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + } + + @Override + public void commit() throws SQLException { + JdbcTracingUtils.execute("Commit", connection::commit, null, + connectionInfo, withActiveSpanOnly, null, tracer); + } + + @Override + public void rollback() throws SQLException { + JdbcTracingUtils.execute("Rollback", connection::rollback, null, + connectionInfo, withActiveSpanOnly, null, tracer); + } + + @Override + public void close() throws SQLException { + JdbcTracingUtils.execute("Close", connection::close, null, + connectionInfo, withActiveSpanOnly, null, tracer); + } + + @Override + public String nativeSQL(String sql) throws SQLException { + return connection.nativeSQL(sql); + } + + @Override + public void setAutoCommit(boolean autoCommit) throws SQLException { + connection.setAutoCommit(autoCommit); + } + + @Override + public boolean getAutoCommit() throws SQLException { + return connection.getAutoCommit(); + } + + @Override + public boolean isClosed() throws SQLException { + return connection.isClosed(); + } + + @Override + public DatabaseMetaData getMetaData() throws SQLException { + return connection.getMetaData(); + } + + @Override + public void setReadOnly(boolean readOnly) throws SQLException { + connection.setReadOnly(readOnly); + } + + @Override + public boolean isReadOnly() throws SQLException { + return connection.isReadOnly(); + } + + @Override + public void setCatalog(String catalog) throws SQLException { + connection.setCatalog(catalog); + } + + @Override + public String getCatalog() throws SQLException { + return connection.getCatalog(); + } + + @Override + public void setTransactionIsolation(int level) throws SQLException { + connection.setTransactionIsolation(level); + } + + @Override + public int getTransactionIsolation() throws SQLException { + return connection.getTransactionIsolation(); + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return connection.getWarnings(); + } + + @Override + public void clearWarnings() throws SQLException { + connection.clearWarnings(); + } + + @Override + public Map> getTypeMap() throws SQLException { + return connection.getTypeMap(); + } + + @Override + public void setTypeMap(Map> map) throws SQLException { + connection.setTypeMap(map); + } + + @Override + public void setHoldability(int holdability) throws SQLException { + connection.setHoldability(holdability); + } + + @Override + public int getHoldability() throws SQLException { + return connection.getHoldability(); + } + + @Override + public Savepoint setSavepoint() throws SQLException { + return connection.setSavepoint(); + } + + @Override + public Savepoint setSavepoint(String name) throws SQLException { + return connection.setSavepoint(name); + } + + @Override + public void rollback(Savepoint savepoint) throws SQLException { + connection.rollback(savepoint); + } + + @Override + public void releaseSavepoint(Savepoint savepoint) throws SQLException { + connection.releaseSavepoint(savepoint); + } + + @Override + public Clob createClob() throws SQLException { + return connection.createClob(); + } + + @Override + public Blob createBlob() throws SQLException { + return connection.createBlob(); + } + + @Override + public NClob createNClob() throws SQLException { + return connection.createNClob(); + } + + @Override + public SQLXML createSQLXML() throws SQLException { + return connection.createSQLXML(); + } + + @Override + public boolean isValid(int timeout) throws SQLException { + return connection.isValid(timeout); + } + + @Override + public void setClientInfo(String name, String value) throws SQLClientInfoException { + connection.setClientInfo(name, value); + } + + @Override + public void setClientInfo(Properties properties) throws SQLClientInfoException { + connection.setClientInfo(properties); + } + + @Override + public String getClientInfo(String name) throws SQLException { + return connection.getClientInfo(name); + } + + @Override + public Properties getClientInfo() throws SQLException { + return connection.getClientInfo(); + } + + @Override + public Array createArrayOf(String typeName, Object[] elements) throws SQLException { + return connection.createArrayOf(typeName, elements); + } + + @Override + public Struct createStruct(String typeName, Object[] attributes) throws SQLException { + return connection.createStruct(typeName, attributes); + } + + @Override + public void setSchema(String schema) throws SQLException { + connection.setSchema(schema); + } + + @Override + public String getSchema() throws SQLException { + return connection.getSchema(); + } + + @Override + public void abort(Executor executor) throws SQLException { + connection.abort(executor); + } + + @Override + public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { + connection.setNetworkTimeout(executor, milliseconds); + } + + @Override + public int getNetworkTimeout() throws SQLException { + return connection.getNetworkTimeout(); + } + + @Override + public T unwrap(Class iface) throws SQLException { + return connection.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return connection.isWrapperFor(iface); + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java new file mode 100644 index 000000000000..9ec45c69fa6f --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java @@ -0,0 +1,147 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.instrumentation.jdbc.parser.URLParser; +import java.io.PrintWriter; +import java.lang.reflect.Method; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.util.Collections; +import java.util.Set; +import java.util.logging.Logger; +import javax.sql.DataSource; + +public class TracingDataSource implements DataSource, AutoCloseable { + + private static final boolean DEFAULT_WITH_ACTIVE_SPAN_ONLY = false; + private static final Set DEFAULT_IGNORED_STATEMENTS = Collections.emptySet(); + + private final Tracer tracer; + private final DataSource underlying; + private final ConnectionInfo connectionInfo; + private final boolean withActiveSpanOnly; + private final Set ignoreStatements; + + public TracingDataSource(final Tracer tracer, + final DataSource underlying) { + this(tracer, underlying, null, DEFAULT_WITH_ACTIVE_SPAN_ONLY, + DEFAULT_IGNORED_STATEMENTS); + } + + public TracingDataSource(final Tracer tracer, + final DataSource underlying, + final ConnectionInfo connectionInfo, + final boolean withActiveSpanOnly, + final Set ignoreStatements) { + this.tracer = tracer; + this.underlying = underlying; + ConnectionInfo info = connectionInfo; + if (info == null) { + try { + Method method; + try { + method = underlying.getClass().getMethod("getJdbcUrl"); + } catch (NoSuchMethodException e) { + method = underlying.getClass().getMethod("getUrl"); + } + info = URLParser.parse((String) method.invoke(underlying)); + } catch (Exception ignored) { + info = ConnectionInfo.UNKNOWN_CONNECTION_INFO; + } + } + this.connectionInfo = info; + this.withActiveSpanOnly = withActiveSpanOnly; + this.ignoreStatements = ignoreStatements; + } + + public DataSource getUnderlying() { + return underlying; + } + + @Override + public Connection getConnection() throws SQLException { + final Connection connection = JdbcTracingUtils + .call("AcquireConnection", underlying::getConnection, + null, connectionInfo, withActiveSpanOnly, null, tracer); + + return WrapperProxy + .wrap(connection, new TracingConnection(connection, connectionInfo, withActiveSpanOnly, + ignoreStatements, tracer)); + } + + @Override + public Connection getConnection(final String username, final String password) + throws SQLException { + final Connection connection = JdbcTracingUtils.call("AcquireConnection", () -> + underlying.getConnection(username, password), null, connectionInfo, + withActiveSpanOnly, null, tracer); + + return WrapperProxy + .wrap(connection, new TracingConnection(connection, connectionInfo, withActiveSpanOnly, + ignoreStatements, tracer)); + } + + @Override + public PrintWriter getLogWriter() throws SQLException { + return underlying.getLogWriter(); + } + + @Override + public void setLogWriter(final PrintWriter out) throws SQLException { + underlying.setLogWriter(out); + } + + @Override + public void setLoginTimeout(final int seconds) throws SQLException { + underlying.setLoginTimeout(seconds); + } + + @Override + public int getLoginTimeout() throws SQLException { + return underlying.getLoginTimeout(); + } + + @Override + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + return underlying.getParentLogger(); + } + + @Override + public T unwrap(final Class iface) throws SQLException { + return underlying.unwrap(iface); + } + + @Override + public boolean isWrapperFor(final Class iface) throws SQLException { + return underlying.isWrapperFor(iface); + } + + @Override + public void close() throws Exception { + if (underlying instanceof AutoCloseable) { + ((AutoCloseable) underlying).close(); + } + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java new file mode 100644 index 000000000000..3bc7342eec27 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java @@ -0,0 +1,275 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.instrumentation.jdbc.parser.URLParser; +import java.sql.Connection; +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.DriverPropertyInfo; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class TracingDriver implements Driver { + + private static final Driver INSTANCE = new TracingDriver(); + + protected static final String TRACE_WITH_ACTIVE_SPAN_ONLY = "traceWithActiveSpanOnly"; + + protected static final String WITH_ACTIVE_SPAN_ONLY = TRACE_WITH_ACTIVE_SPAN_ONLY + "=true"; + + public static final String IGNORE_FOR_TRACING_REGEX = "ignoreForTracing=\"((?:\\\\\"|[^\"])*)\"[;]*"; + + protected static final Pattern PATTERN_FOR_IGNORING = Pattern.compile(IGNORE_FOR_TRACING_REGEX); + + static { + try { + DriverManager.registerDriver(INSTANCE); + } catch (SQLException e) { + throw new IllegalStateException("Could not register TracingDriver with DriverManager", e); + } + } + + /** + * @return The singleton instance of the {@code TracingDriver}. + */ + public static Driver load() { + return INSTANCE; + } + + /** + * Ensure {@code TracingDriver} be the first driver of {@link DriverManager} to make sure + * "interceptor mode" works. WARNING: Driver like Oracle JDBC may fail since it's destroyed + * forever after deregistration. + */ + public synchronized static void ensureRegisteredAsTheFirstDriver() { + try { + Enumeration enumeration = DriverManager.getDrivers(); + List drivers = null; + for (int i = 0; enumeration.hasMoreElements(); ++i) { + Driver driver = enumeration.nextElement(); + if (i == 0) { + if (driver == INSTANCE) { + return; + } + drivers = new ArrayList<>(); + } + if (driver != INSTANCE) { + drivers.add(driver); + DriverManager.deregisterDriver(driver); + } + } + for (Driver driver : drivers) { + DriverManager.registerDriver(driver); + } + } catch (SQLException e) { + throw new IllegalStateException("Could not register TracingDriver with DriverManager", e); + } + } + + /** + * Sets the {@code traceEnabled} property to enable or disable traces. + * + * @param traceEnabled The {@code traceEnabled} value. + */ + public static void setTraceEnabled(boolean traceEnabled) { + JdbcTracing.setTraceEnabled(traceEnabled); + } + + public static boolean isTraceEnabled() { + return JdbcTracing.isTraceEnabled(); + } + + private static boolean interceptorMode = false; + + /** + * Turns "interceptor mode" on or off. + * + * @param interceptorMode The {@code interceptorMode} value. + */ + public static void setInterceptorMode(final boolean interceptorMode) { + TracingDriver.interceptorMode = interceptorMode; + } + + private static boolean withActiveSpanOnly; + + /** + * Sets the {@code withActiveSpanOnly} property for "interceptor mode". + * + * @param withActiveSpanOnly The {@code withActiveSpanOnly} value. + */ + public static void setInterceptorProperty(final boolean withActiveSpanOnly) { + TracingDriver.withActiveSpanOnly = withActiveSpanOnly; + } + + private static Set ignoreStatements; + + /** + * Sets the {@code ignoreStatements} property for "interceptor mode". + * + * @param ignoreStatements The {@code ignoreStatements} value. + */ + public static void setInterceptorProperty(final Set ignoreStatements) { + TracingDriver.ignoreStatements = ignoreStatements; + } + + protected Tracer tracer; + + @Override + public Connection connect(String url, Properties info) throws SQLException { + // if there is no url, we have problems + if (url == null) { + throw new SQLException("url is required"); + } + + final Set ignoreStatements; + final boolean withActiveSpanOnly; + if (interceptorMode) { + withActiveSpanOnly = TracingDriver.withActiveSpanOnly; + ignoreStatements = TracingDriver.ignoreStatements; + } else if (acceptsURL(url)) { + withActiveSpanOnly = url.contains(WITH_ACTIVE_SPAN_ONLY); + ignoreStatements = extractIgnoredStatements(url); + } else { + return null; + } + + url = extractRealUrl(url); + + // find the real driver for the URL + final Driver wrappedDriver = findDriver(url); + + final Tracer currentTracer = getTracer(); + final ConnectionInfo connectionInfo = URLParser.parse(url); + final String realUrl = url; + final Connection connection = JdbcTracingUtils.call("AcquireConnection", () -> + wrappedDriver.connect(realUrl, info), null, connectionInfo, withActiveSpanOnly, + null, currentTracer); + + return WrapperProxy + .wrap(connection, new TracingConnection(connection, connectionInfo, withActiveSpanOnly, + ignoreStatements, currentTracer)); + } + + @Override + public boolean acceptsURL(String url) throws SQLException { + return url != null && ( + url.startsWith(getUrlPrefix()) || + (interceptorMode && url.startsWith("jdbc:")) + ); + } + + @Override + public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { + return findDriver(url).getPropertyInfo(url, info); + } + + @Override + public int getMajorVersion() { + // There is no way to get it from wrapped driver + return 1; + } + + @Override + public int getMinorVersion() { + // There is no way to get it from wrapped driver + return 0; + } + + @Override + public boolean jdbcCompliant() { + return true; + } + + @Override + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + // There is no way to get it from wrapped driver + return null; + } + + public void setTracer(Tracer tracer) { + this.tracer = tracer; + } + + protected String getUrlPrefix() { + return "jdbc:tracing:"; + } + + protected Driver findDriver(String realUrl) throws SQLException { + if (realUrl == null || realUrl.trim().length() == 0) { + throw new IllegalArgumentException("url is required"); + } + + for (Driver candidate : Collections.list(DriverManager.getDrivers())) { + try { + if (!(candidate instanceof TracingDriver) && candidate.acceptsURL(realUrl)) { + return candidate; + } + } catch (SQLException ignored) { + // intentionally ignore exception + } + } + + throw new SQLException("Unable to find a driver that accepts url: " + realUrl); + } + + protected String extractRealUrl(String url) { + String extracted = url.startsWith(getUrlPrefix()) ? url.replace(getUrlPrefix(), "jdbc:") : url; + return extracted.replaceAll(TRACE_WITH_ACTIVE_SPAN_ONLY + "=(true|false)[;]*", "") + .replaceAll(IGNORE_FOR_TRACING_REGEX, "") + .replaceAll("\\?$", ""); + } + + protected Set extractIgnoredStatements(String url) { + + final Matcher matcher = PATTERN_FOR_IGNORING.matcher(url); + + Set results = new HashSet<>(8); + + while (matcher.find()) { + String rawValue = matcher.group(1); + String finalValue = rawValue.replace("\\\"", "\""); + results.add(finalValue); + } + + return results; + } + + Tracer getTracer() { + if (tracer == null) { + return GlobalOpenTelemetry.get().getTracer("opentelemetry-jdbc", "0.1.0"); + } + return tracer; + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java new file mode 100644 index 000000000000..01ed7f34927b --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java @@ -0,0 +1,343 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +import io.opentelemetry.api.trace.Tracer; +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Date; +import java.sql.NClob; +import java.sql.ParameterMetaData; +import java.sql.PreparedStatement; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLXML; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Set; + +public class TracingPreparedStatement extends TracingStatement implements PreparedStatement { + + private final PreparedStatement preparedStatement; + private final String query; + + public TracingPreparedStatement(PreparedStatement preparedStatement, String query, + ConnectionInfo connectionInfo, boolean withActiveSpanOnly, Set ignoreStatements, + Tracer tracer) { + super(preparedStatement, query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + this.preparedStatement = preparedStatement; + this.query = query; + } + + @Override + public ResultSet executeQuery() throws SQLException { + return JdbcTracingUtils.call("Query", preparedStatement::executeQuery, + query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public int executeUpdate() throws SQLException { + return JdbcTracingUtils.call("Update", preparedStatement::executeUpdate, + query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public boolean execute() throws SQLException { + return JdbcTracingUtils.call("Execute", preparedStatement::execute, + query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public void setNull(int parameterIndex, int sqlType) throws SQLException { + preparedStatement.setNull(parameterIndex, sqlType); + } + + @Override + public void setBoolean(int parameterIndex, boolean x) throws SQLException { + preparedStatement.setBoolean(parameterIndex, x); + } + + @Override + public void setByte(int parameterIndex, byte x) throws SQLException { + preparedStatement.setByte(parameterIndex, x); + } + + @Override + public void setShort(int parameterIndex, short x) throws SQLException { + preparedStatement.setShort(parameterIndex, x); + } + + @Override + public void setInt(int parameterIndex, int x) throws SQLException { + preparedStatement.setInt(parameterIndex, x); + } + + @Override + public void setLong(int parameterIndex, long x) throws SQLException { + preparedStatement.setLong(parameterIndex, x); + } + + @Override + public void setFloat(int parameterIndex, float x) throws SQLException { + preparedStatement.setFloat(parameterIndex, x); + } + + @Override + public void setDouble(int parameterIndex, double x) throws SQLException { + preparedStatement.setDouble(parameterIndex, x); + } + + @Override + public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { + preparedStatement.setBigDecimal(parameterIndex, x); + } + + @Override + public void setString(int parameterIndex, String x) throws SQLException { + preparedStatement.setString(parameterIndex, x); + } + + @Override + public void setBytes(int parameterIndex, byte[] x) throws SQLException { + preparedStatement.setBytes(parameterIndex, x); + } + + @Override + public void setDate(int parameterIndex, Date x) throws SQLException { + preparedStatement.setDate(parameterIndex, x); + } + + @Override + public void setTime(int parameterIndex, Time x) throws SQLException { + preparedStatement.setTime(parameterIndex, x); + } + + @Override + public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { + preparedStatement.setTimestamp(parameterIndex, x); + } + + @Override + public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { + preparedStatement.setAsciiStream(parameterIndex, x, length); + } + + @Override + @Deprecated + public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { + preparedStatement.setUnicodeStream(parameterIndex, x, length); + } + + @Override + public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { + preparedStatement.setBinaryStream(parameterIndex, x, length); + } + + @Override + public void clearParameters() throws SQLException { + preparedStatement.clearParameters(); + } + + @Override + public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { + preparedStatement.setObject(parameterIndex, x, targetSqlType); + } + + @Override + public void setObject(int parameterIndex, Object x) throws SQLException { + preparedStatement.setObject(parameterIndex, x); + } + + @Override + public void addBatch() throws SQLException { + preparedStatement.addBatch(); + } + + @Override + public void setCharacterStream(int parameterIndex, Reader reader, int length) + throws SQLException { + preparedStatement.setCharacterStream(parameterIndex, reader, length); + } + + @Override + public void setRef(int parameterIndex, Ref x) throws SQLException { + preparedStatement.setRef(parameterIndex, x); + } + + @Override + public void setBlob(int parameterIndex, Blob x) throws SQLException { + preparedStatement.setBlob(parameterIndex, x); + } + + @Override + public void setClob(int parameterIndex, Clob x) throws SQLException { + preparedStatement.setClob(parameterIndex, x); + } + + @Override + public void setArray(int parameterIndex, Array x) throws SQLException { + preparedStatement.setArray(parameterIndex, x); + } + + @Override + public ResultSetMetaData getMetaData() throws SQLException { + return preparedStatement.getMetaData(); + } + + @Override + public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { + preparedStatement.setDate(parameterIndex, x, cal); + } + + @Override + public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { + preparedStatement.setTime(parameterIndex, x, cal); + } + + @Override + public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { + preparedStatement.setTimestamp(parameterIndex, x, cal); + } + + @Override + public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { + preparedStatement.setNull(parameterIndex, sqlType, typeName); + } + + @Override + public void setURL(int parameterIndex, URL x) throws SQLException { + preparedStatement.setURL(parameterIndex, x); + } + + @Override + public ParameterMetaData getParameterMetaData() throws SQLException { + return preparedStatement.getParameterMetaData(); + } + + @Override + public void setRowId(int parameterIndex, RowId x) throws SQLException { + preparedStatement.setRowId(parameterIndex, x); + } + + @Override + public void setNString(int parameterIndex, String value) throws SQLException { + preparedStatement.setNString(parameterIndex, value); + } + + @Override + public void setNCharacterStream(int parameterIndex, Reader value, long length) + throws SQLException { + preparedStatement.setNCharacterStream(parameterIndex, value, length); + } + + @Override + public void setNClob(int parameterIndex, NClob value) throws SQLException { + preparedStatement.setNClob(parameterIndex, value); + } + + @Override + public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { + preparedStatement.setClob(parameterIndex, reader, length); + } + + @Override + public void setBlob(int parameterIndex, InputStream inputStream, long length) + throws SQLException { + preparedStatement.setBlob(parameterIndex, inputStream, length); + } + + @Override + public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { + preparedStatement.setNClob(parameterIndex, reader, length); + } + + @Override + public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { + preparedStatement.setSQLXML(parameterIndex, xmlObject); + } + + @Override + public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) + throws SQLException { + preparedStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength); + } + + @Override + public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { + preparedStatement.setAsciiStream(parameterIndex, x, length); + } + + @Override + public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { + preparedStatement.setBinaryStream(parameterIndex, x, length); + } + + @Override + public void setCharacterStream(int parameterIndex, Reader reader, long length) + throws SQLException { + preparedStatement.setCharacterStream(parameterIndex, reader, length); + } + + @Override + public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { + preparedStatement.setAsciiStream(parameterIndex, x); + } + + @Override + public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { + preparedStatement.setBinaryStream(parameterIndex, x); + } + + @Override + public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { + preparedStatement.setCharacterStream(parameterIndex, reader); + } + + @Override + public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { + preparedStatement.setNCharacterStream(parameterIndex, value); + } + + @Override + public void setClob(int parameterIndex, Reader reader) throws SQLException { + preparedStatement.setClob(parameterIndex, reader); + } + + @Override + public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { + preparedStatement.setBlob(parameterIndex, inputStream); + } + + @Override + public void setNClob(int parameterIndex, Reader reader) throws SQLException { + preparedStatement.setNClob(parameterIndex, reader); + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java new file mode 100644 index 000000000000..954219024520 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java @@ -0,0 +1,311 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +import io.opentelemetry.api.trace.Tracer; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Set; + +public class TracingStatement implements Statement { + + private final Statement statement; + private final String query; + private final ArrayList batchCommands = new ArrayList<>(); + final ConnectionInfo connectionInfo; + final boolean withActiveSpanOnly; + final Set ignoreStatements; + final Tracer tracer; + + TracingStatement(Statement statement, ConnectionInfo connectionInfo, boolean withActiveSpanOnly, + Set ignoreStatements, Tracer tracer) { + this(statement, null, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + TracingStatement(Statement statement, String query, ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, Set ignoreStatements, Tracer tracer) { + this.statement = statement; + this.query = query; + this.connectionInfo = connectionInfo; + this.withActiveSpanOnly = withActiveSpanOnly; + this.ignoreStatements = ignoreStatements; + this.tracer = tracer; + } + + @Override + public ResultSet executeQuery(String sql) throws SQLException { + return JdbcTracingUtils.call("Query", () -> statement.executeQuery(sql), + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public int executeUpdate(String sql) throws SQLException { + return JdbcTracingUtils.call("Update", () -> statement.executeUpdate(sql), + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { + return JdbcTracingUtils.call("Update", () -> statement.executeUpdate(sql, autoGeneratedKeys), + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { + return JdbcTracingUtils.call("Update", () -> statement.executeUpdate(sql, columnIndexes), + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public int executeUpdate(String sql, String[] columnNames) throws SQLException { + return JdbcTracingUtils.call("Update", () -> statement.executeUpdate(sql, columnNames), + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public boolean execute(String sql) throws SQLException { + return JdbcTracingUtils.call("Execute", () -> statement.execute(sql), + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { + return JdbcTracingUtils.call("Execute", () -> statement.execute(sql, autoGeneratedKeys), + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public boolean execute(String sql, int[] columnIndexes) throws SQLException { + return JdbcTracingUtils.call("Execute", () -> statement.execute(sql, columnIndexes), + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public boolean execute(String sql, String[] columnNames) throws SQLException { + return JdbcTracingUtils.call("Execute", () -> statement.execute(sql, columnNames), + sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public int[] executeBatch() throws SQLException { + return JdbcTracingUtils.call("Update", statement::executeBatch, + buildSqlForBatch(), connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + } + + @Override + public void close() throws SQLException { + statement.close(); + } + + @Override + public int getMaxFieldSize() throws SQLException { + return statement.getMaxFieldSize(); + } + + @Override + public void setMaxFieldSize(int max) throws SQLException { + statement.setMaxFieldSize(max); + } + + @Override + public int getMaxRows() throws SQLException { + return statement.getMaxRows(); + } + + @Override + public void setMaxRows(int max) throws SQLException { + statement.setMaxRows(max); + } + + @Override + public void setEscapeProcessing(boolean enable) throws SQLException { + statement.setEscapeProcessing(enable); + } + + @Override + public int getQueryTimeout() throws SQLException { + return statement.getQueryTimeout(); + } + + @Override + public void setQueryTimeout(int seconds) throws SQLException { + statement.setQueryTimeout(seconds); + } + + @Override + public void cancel() throws SQLException { + statement.cancel(); + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return statement.getWarnings(); + } + + @Override + public void clearWarnings() throws SQLException { + statement.clearWarnings(); + } + + @Override + public void setCursorName(String name) throws SQLException { + statement.setCursorName(name); + } + + @Override + public ResultSet getResultSet() throws SQLException { + return statement.getResultSet(); + } + + @Override + public int getUpdateCount() throws SQLException { + return statement.getUpdateCount(); + } + + @Override + public boolean getMoreResults() throws SQLException { + return statement.getMoreResults(); + } + + @Override + public void setFetchDirection(int direction) throws SQLException { + statement.setFetchDirection(direction); + } + + @Override + public int getFetchDirection() throws SQLException { + return statement.getFetchDirection(); + } + + @Override + public void setFetchSize(int rows) throws SQLException { + statement.setFetchSize(rows); + } + + @Override + public int getFetchSize() throws SQLException { + return statement.getFetchSize(); + } + + @Override + public int getResultSetConcurrency() throws SQLException { + return statement.getResultSetConcurrency(); + } + + @Override + public int getResultSetType() throws SQLException { + return statement.getResultSetType(); + } + + @Override + public void addBatch(String sql) throws SQLException { + statement.addBatch(sql); + batchCommands.add(sql); + } + + @Override + public void clearBatch() throws SQLException { + statement.clearBatch(); + batchCommands.clear(); + } + + @Override + public Connection getConnection() throws SQLException { + return statement.getConnection(); + } + + @Override + public boolean getMoreResults(int current) throws SQLException { + return statement.getMoreResults(current); + } + + @Override + public ResultSet getGeneratedKeys() throws SQLException { + return statement.getGeneratedKeys(); + } + + @Override + public int getResultSetHoldability() throws SQLException { + return statement.getResultSetHoldability(); + } + + @Override + public boolean isClosed() throws SQLException { + return statement.isClosed(); + } + + @Override + public void setPoolable(boolean poolable) throws SQLException { + statement.setPoolable(poolable); + } + + @Override + public boolean isPoolable() throws SQLException { + return statement.isPoolable(); + } + + @Override + public void closeOnCompletion() throws SQLException { + statement.closeOnCompletion(); + } + + @Override + public boolean isCloseOnCompletion() throws SQLException { + return statement.isCloseOnCompletion(); + } + + @Override + public T unwrap(Class iface) throws SQLException { + return statement.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return statement.isWrapperFor(iface); + } + + public String getQuery() { + return query; + } + + @Override + public String toString() { + return getQuery(); + } + + private String buildSqlForBatch() { + StringBuilder sqlBuilder = new StringBuilder(); + if (query != null) { + sqlBuilder.append(query); + } + + for (String batchCommand : batchCommands) { + sqlBuilder.append(batchCommand); + } + + return sqlBuilder.toString(); + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java new file mode 100644 index 000000000000..45a3d8d6a97f --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java @@ -0,0 +1,156 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +/** + * Utility class for the creation of wrapper proxies. + */ +public final class WrapperProxy { + + private interface WrapperInvocationHandler extends InvocationHandler { + + T getObject(); + + T getWrapper(); + } + + /** + * Returns a {@linkplain Proxy proxy} with type {@code } of the specified {@code obj} wrapping + * the provided {@code wrapper} instance. Method invocations on the proxy instance will be handled + * as such: + *

    + *
  1. The {@code wrapper} instance will be invoked for methods that + * exist in the {@code wrapper} instance.
  2. + *
  3. The {@code obj} instance will be invoked for methods that do not + * exist in the {@code wrapper} instance.
  4. + *
+ * The type of the returned {@linkplain Proxy proxy} will be the composition + * of all super-interfaces of the runtime type of the specified {@code obj} + * instance. + *

+ * Note: The runtime type of the returned instance will not be + * of a concrete class, but rather a composition of all super-interfaces of + * the concrete class {@code }. It is therefore not possible to cast the + * instance returned by this method to a concrete class, but rather any + * super-interface of the concrete class. + * + * @param The type parameter of the specified arguments. + * @param obj The target object instance to wrap. + * @param wrapper The wrapping object. + * @return a {@linkplain Proxy proxy} with type {@code } of the specified {@code obj} wrapping + * wrapping the provided {@code wrapper} instance, or, {@code wrapper} if {@code obj == wrapper}, + * or if {@code target} or {@code wrapper} is null. + */ + @SuppressWarnings("unchecked") + public static T wrap(final T obj, final T wrapper) { + if (obj == null || wrapper == null || obj == wrapper) { + return wrapper; + } + + final Class objClass = obj.getClass(); + final Class wrapperClass = wrapper.getClass(); + return (T) Proxy.newProxyInstance(objClass.getClassLoader(), Classes.getAllInterfaces(objClass), + new WrapperInvocationHandler() { + @Override + public Object invoke(final Object proxy, final Method method, final Object[] args) + throws Throwable { + try { + try { + if (method.getDeclaringClass().isAssignableFrom(wrapperClass)) { + return method.invoke(wrapper, args); + } + + final Method specific = Classes + .getDeclaredMethodDeep(wrapperClass, method.getName(), + method.getParameterTypes()); + if (specific != null) { + return specific.invoke(wrapper, args); + } + } catch (final IllegalArgumentException e) { + } + + return method.invoke(obj, args); + } catch (final InvocationTargetException e) { + throw e.getCause(); + } catch (final IllegalAccessException e) { + final IllegalAccessError error = new IllegalAccessError(e.getMessage()); + error.setStackTrace(e.getStackTrace()); + throw error; + } + } + + @Override + public T getObject() { + return obj; + } + + @Override + public T getWrapper() { + return wrapper; + } + }); + } + + /** + * Tests whether the specified object is a proxy of a wrapped object. + * + * @param obj The object to test. + * @return Whether the specified object is a proxy of a wrapped object. + * @throws NullPointerException If {@code obj} is null. + */ + public static boolean isWrapper(final Object obj) { + return Proxy.isProxyClass(obj.getClass()) && Proxy + .getInvocationHandler(obj) instanceof WrapperInvocationHandler; + } + + /** + * Tests whether the specified object is a proxy of a wrapped instance type matching the provided + * {@code wrappedClass}. + * + * @param The common type of the proxy and wrapped instance. + * @param obj The object to test. + * @param wrappedClass The type of the instance wrapped by the specified {@code obj}. + * @return Whether the specified object is a proxy of a wrapped instance type matching the + * provided {@code wrappedClass}. + * @throws NullPointerException If {@code obj} or {@code wrappedClass} is null. + */ + public static boolean isWrapper(final T obj, final Class wrappedClass) { + if (!Proxy.isProxyClass(obj.getClass())) { + return false; + } + + final InvocationHandler handler = Proxy.getInvocationHandler(obj); + if (!(handler instanceof WrapperInvocationHandler)) { + return false; + } + + return wrappedClass + .isAssignableFrom(((WrapperInvocationHandler) handler).getWrapper().getClass()); + } + + private WrapperProxy() { + } +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java new file mode 100644 index 000000000000..e80564b87d53 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import java.util.regex.Pattern; + +/** + * Parser for AS400 + * + * @author oburgosm + * @since 0.2.12 + */ +public class AS400URLParser extends AbstractMatcherURLParser { + + private static final Pattern AS400_URL_PATTERN = Pattern + .compile( + "jdbc:as400:\\/\\/(?[^\\/;]+)(\\/(?[^;\\/]*))?\\/?(;(?.*))?"); + + private static final String AS400_TYPE = "as400"; + + public AS400URLParser() { + super(AS400_URL_PATTERN, AS400_TYPE); + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java new file mode 100644 index 000000000000..e594443e7db7 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Parser based on regular expression + * + * @author oburgosm + * @since 0.2.12 + */ +public abstract class AbstractMatcherURLParser implements ConnectionURLParser { + + private final Pattern pattern; + + private final String dbType; + + public AbstractMatcherURLParser(Pattern pattern, String dbType) { + this.pattern = pattern; + this.dbType = dbType; + } + + /** + * Useful to modify ConnectionInfo before build + * + * @param matcher The matcher to apply. Note that the matcher must have a group named host, and + * optionally, a group named port and another named instance + * @return + */ + protected ConnectionInfo.Builder initBuilder(Matcher matcher) { + String host = matcher.group("host"); + String port = null; + try { + port = matcher.group("port"); + } catch (IllegalArgumentException e) { + // The pattern has no instance port + } + ConnectionInfo.Builder builder; + if (port == null || "".equals(port)) { + builder = new ConnectionInfo.Builder(host); + } else { + builder = new ConnectionInfo.Builder(host, Integer.valueOf(port)); + } + String instance = ConnectionInfo.UNKNOWN_CONNECTION_INFO.getDbInstance(); + try { + instance = matcher.group("instance"); + if (instance == null || "".equals(instance)) { + instance = ConnectionInfo.UNKNOWN_CONNECTION_INFO.getDbInstance(); + } + } catch (IllegalArgumentException e) { + // The pattern has no instance group + } + return builder + .dbType(this.dbType) + .dbInstance(instance); + } + + @Override + public ConnectionInfo parse(String url) { + Matcher matcher = this.pattern.matcher(url); + if (matcher.matches()) { + return this.initBuilder(matcher).build(); + } else { + return ConnectionInfo.UNKNOWN_CONNECTION_INFO; + } + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java new file mode 100644 index 000000000000..b5ea59f384dc --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +public abstract class AbstractURLParser implements ConnectionURLParser { + + /** + * Fetch the index range that database host and port from connection url. + * + * @return index range that database hosts. + */ + protected abstract URLLocation fetchDatabaseHostsIndexRange(final String url); + + /** + * Fetch the index range that database name from connection url. + * + * @return index range that database name. + */ + protected abstract URLLocation fetchDatabaseNameIndexRange(final String url); + + /** + * Fetch database host(s) from connection url. + * + * @return database host(s). + */ + protected String fetchDatabaseHostsFromURL(String url) { + URLLocation hostsLocation = fetchDatabaseHostsIndexRange(url); + return url.substring(hostsLocation.startIndex(), hostsLocation.endIndex()); + } + + /** + * Fetch database name from connection url. + * + * @return database name. + */ + protected String fetchDatabaseNameFromURL(String url) { + URLLocation hostsLocation = fetchDatabaseNameIndexRange(url); + return url.substring(hostsLocation.startIndex(), hostsLocation.endIndex()); + } + + /** + * Fetch database name from connection url. + * + * @return database name. + */ + protected String fetchDatabaseNameFromURL(String url, int[] indexRange) { + return url.substring(indexRange[0], indexRange[1]); + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java new file mode 100644 index 000000000000..b5aeeac5a657 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; + +public interface ConnectionURLParser { + + ConnectionInfo parse(final String url); + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java new file mode 100644 index 000000000000..07fec5ed5944 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import java.util.regex.Pattern; + +/** + * Parser for DB2 + * + * @author oburgosm + * @since 0.2.12 + */ +public class DB2URLParser extends AbstractMatcherURLParser { + + + private static final Pattern DB2_URL_PATTERN = Pattern + .compile( + "jdbc:db2:\\/\\/(?[^:\\/]+)(:(?\\d+))?\\/(?[^:]+)(:(?.*))?"); + + private static final String DB2_TYPE = "db2"; + + public DB2URLParser() { + super(DB2_URL_PATTERN, DB2_TYPE); + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java new file mode 100644 index 000000000000..6e7a26289165 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java @@ -0,0 +1,157 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; + +public class H2URLParser extends AbstractURLParser { + + private static final String LOCALHOST = "localhost"; + private static final int DEFAULT_PORT = 8084; + /** + * Flag that H2 running with memory mode. + */ + private static final String MEMORY_MODE_FLAG = "mem"; + /** + * Flag that H2 running with tcp mode. + */ + private static final String TCP_MODE_FLAG = "h2:tcp"; + /** + * Flag that H2 running with file mode. + */ + private static final String FILE_MODE_FLAG = "file"; + /** + * Flag that H2 running with implicit file mode. + */ + private static final String IMPLICIT_FILE_MODE_FLAG = "jdbc:h2"; + private static final String H2_DB_TYPE = "h2"; + + @Override + protected URLLocation fetchDatabaseHostsIndexRange(String url) { + int hostLabelStartIndex = url.indexOf("//"); + int hostLabelEndIndex = url.indexOf("/", hostLabelStartIndex + 2); + return new URLLocation(hostLabelStartIndex + 2, hostLabelEndIndex); + } + + @Override + protected URLLocation fetchDatabaseNameIndexRange(String url) { + int databaseStartTag = url.lastIndexOf("/"); + int databaseEndTag = url.indexOf(";"); + if (databaseEndTag == -1) { + databaseEndTag = url.length(); + } + return new URLLocation(databaseStartTag + 1, databaseEndTag); + } + + @Override + public ConnectionInfo parse(String url) { + int[] databaseNameRangeIndex = fetchDatabaseNameRangeIndexFromURLForH2FileMode(url); + if (databaseNameRangeIndex != null) { + return new ConnectionInfo.Builder(LOCALHOST, -1).dbType(H2_DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)).build(); + } + + databaseNameRangeIndex = fetchDatabaseNameRangeIndexFromURLForH2MemMode(url); + if (databaseNameRangeIndex != null) { + return new ConnectionInfo.Builder(LOCALHOST, -1).dbType(H2_DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)).build(); + } + + databaseNameRangeIndex = fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(url); + if (databaseNameRangeIndex != null) { + return new ConnectionInfo.Builder(LOCALHOST, -1).dbType(H2_DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)).build(); + } + + String[] hostAndPort = fetchDatabaseHostsFromURL(url).split(":"); + if (hostAndPort.length == 1) { + return new ConnectionInfo.Builder(hostAndPort[0], DEFAULT_PORT).dbType(H2_DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url)).build(); + } else { + return new ConnectionInfo.Builder(hostAndPort[0], Integer.valueOf(hostAndPort[1])) + .dbType(H2_DB_TYPE).dbInstance(fetchDatabaseNameFromURL(url)).build(); + } + } + + /** + * Fetch range index that the database name from connection url if H2 database running with file + * mode. + * + * @return range index that the database name. + */ + private int[] fetchDatabaseNameRangeIndexFromURLForH2FileMode(String url) { + int fileLabelIndex = url.indexOf(FILE_MODE_FLAG); + int parameterLabelIndex = url.indexOf(";", fileLabelIndex); + if (parameterLabelIndex == -1) { + parameterLabelIndex = url.length(); + } + + if (fileLabelIndex != -1) { + return new int[]{fileLabelIndex + FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; + } else { + return null; + } + } + + /** + * Fetch range index that the database name from connection url if H2 database running with + * implicit file mode. + * + * @return range index that the database name. + */ + private int[] fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(String url) { + if (url.contains(TCP_MODE_FLAG)) { + return null; + } + int fileLabelIndex = url.indexOf(IMPLICIT_FILE_MODE_FLAG); + int parameterLabelIndex = url.indexOf(";", fileLabelIndex); + if (parameterLabelIndex == -1) { + parameterLabelIndex = url.length(); + } + + if (fileLabelIndex != -1) { + return new int[]{fileLabelIndex + IMPLICIT_FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; + } else { + return null; + } + } + + /** + * Fetch range index that the database name from connection url if H2 database running with memory + * mode. + * + * @return range index that the database name. + */ + private int[] fetchDatabaseNameRangeIndexFromURLForH2MemMode(String url) { + int fileLabelIndex = url.indexOf(MEMORY_MODE_FLAG); + int parameterLabelIndex = url.indexOf(";", fileLabelIndex); + if (parameterLabelIndex == -1) { + parameterLabelIndex = url.length(); + } + + if (fileLabelIndex != -1) { + return new int[]{fileLabelIndex + MEMORY_MODE_FLAG.length() + 1, parameterLabelIndex}; + } else { + return null; + } + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java new file mode 100644 index 000000000000..c734ee8dfd2d --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +public class MariadbURLParser extends MysqlURLParser { + + protected String dbType() { + return "mariadb"; + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java new file mode 100644 index 000000000000..1908c52e21b8 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java @@ -0,0 +1,116 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; + +public class MysqlURLParser extends AbstractURLParser { + + private static final String DEFAULT_HOST = "localhost"; + + private static final int DEFAULT_PORT = 3306; + + protected String dbType() { + return "mysql"; + } + + @Override + protected URLLocation fetchDatabaseHostsIndexRange(String url) { + int hostLabelStartIndex = url.indexOf("//") + 2; + int hostLabelEndIndex = url.indexOf("/", hostLabelStartIndex); + if (hostLabelEndIndex == -1) { + int queryStringStartIndex = url.indexOf("?", hostLabelStartIndex); + if (queryStringStartIndex == -1) { + hostLabelEndIndex = url.length(); + } else { + hostLabelEndIndex = queryStringStartIndex; + } + } + return new URLLocation(hostLabelStartIndex, hostLabelEndIndex); + } + + protected String fetchDatabaseNameFromURL(String url, int startSize) { + URLLocation hostsLocation = fetchDatabaseNameIndexRange(url, startSize); + if (hostsLocation == null) { + return ""; + } + return url.substring(hostsLocation.startIndex(), hostsLocation.endIndex()); + } + + protected URLLocation fetchDatabaseNameIndexRange(String url, int startSize) { + int databaseStartTag = url.indexOf("/", startSize); + if (databaseStartTag == -1) { + return null; + } + int databaseEndTag = url.indexOf("?", databaseStartTag); + if (databaseEndTag == -1) { + databaseEndTag = url.length(); + } + return new URLLocation(databaseStartTag + 1, databaseEndTag); + } + + @Override + protected URLLocation fetchDatabaseNameIndexRange(String url) { + int databaseStartTag = url.lastIndexOf("/"); + int databaseEndTag = url.indexOf("?", databaseStartTag); + if (databaseEndTag == -1) { + databaseEndTag = url.length(); + } + return new URLLocation(databaseStartTag + 1, databaseEndTag); + } + + @Override + public ConnectionInfo parse(String url) { + URLLocation location = fetchDatabaseHostsIndexRange(url); + String hosts = url.substring(location.startIndex(), location.endIndex()); + if (hosts.isEmpty()) { + hosts = DEFAULT_HOST; + } + String[] hostSegment = hosts.split(","); + if (hostSegment.length > 1) { + StringBuilder sb = new StringBuilder(); + for (String host : hostSegment) { + if (host.split(":").length == 1) { + sb.append(host + ":" + DEFAULT_PORT + ","); + } else { + sb.append(host + ","); + } + } + if (',' == sb.charAt(sb.length() - 1)) { + sb.deleteCharAt(sb.length() - 1); + } + return new ConnectionInfo.Builder(sb.toString()).dbType(dbType()) + .dbInstance(fetchDatabaseNameFromURL(url)).build(); + } else { + String[] hostAndPort = hostSegment[0].split(":"); + if (hostAndPort.length != 1) { + return new ConnectionInfo.Builder(hostAndPort[0], Integer.valueOf(hostAndPort[1])) + .dbType(dbType()).dbInstance(fetchDatabaseNameFromURL(url, location.endIndex())) + .build(); + } else { + + return new ConnectionInfo.Builder(hostAndPort[0], DEFAULT_PORT).dbType(dbType()) + .dbInstance(fetchDatabaseNameFromURL(url, location.endIndex())).build(); + } + } + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java new file mode 100644 index 000000000000..6d273d27d4f0 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java @@ -0,0 +1,172 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class OracleURLParser implements ConnectionURLParser { + + public static final String DB_TYPE = "oracle"; + public static final String PREFIX_THIN = "jdbc:oracle:thin:"; + public static final String PREFIX_OCI = "jdbc:oracle:oci:"; + public static final int DEFAULT_PORT = 1521; + private static Pattern EASY_CONNECT_PATTERN = Pattern.compile( + "(?.*)@(?ldap:)?(//)?(?[^:/]+)(?:[0-9]+)?(?[:/][^:/]+)?(?:[^:/]+)?(?/[^:/]+)?"); + + @Override + public ConnectionInfo parse(final String url) { + if (url != null) { + String lowerCaseUrl = url.toLowerCase(); + if ((lowerCaseUrl.startsWith(PREFIX_THIN) || lowerCaseUrl.startsWith(PREFIX_OCI))) { + String trimmedURL; + if (lowerCaseUrl.startsWith(PREFIX_THIN)) { + trimmedURL = url.substring(PREFIX_THIN.length()); + } else { + trimmedURL = url.substring(PREFIX_OCI.length()); + } + OracleConnectionInfo connectionInfo = parseTnsName(trimmedURL); + if (connectionInfo == null) { + connectionInfo = parseEasyConnect(trimmedURL); + } + if (connectionInfo != null) { + return new ConnectionInfo.Builder(connectionInfo.getDbPeer()) // + .dbType(DB_TYPE) // + .dbInstance(connectionInfo.getDbInstance()) // + .build(); + } + } + } + return null; + } + + private OracleConnectionInfo parseTnsName(final String url) { + final String hosts = parseDatabaseHostsFromTnsUrl(url); + if (hosts != null) { + final int idxServiceName = url.indexOf("SERVICE_NAME"); + final int start = url.indexOf('=', idxServiceName) + 1; + final int end = url.indexOf(")", start); + final String serviceName = url.substring(start, end); + return new OracleConnectionInfo() // + .setDbPeer(hosts) // + .setDbInstance(serviceName); + } + return null; + } + + public static String parseDatabaseHostsFromTnsUrl(String url) { + int beginIndex = url.indexOf("DESCRIPTION"); + if (beginIndex == -1) { + return null; + } + List hosts = new ArrayList(); + do { + int hostStartIndex = url.indexOf("HOST", beginIndex); + if (hostStartIndex == -1) { + break; + } + int equalStartIndex = url.indexOf("=", hostStartIndex); + int hostEndIndex = url.indexOf(")", hostStartIndex); + String host = url.substring(equalStartIndex + 1, hostEndIndex); + + int port = DEFAULT_PORT; + int portStartIndex = url.indexOf("PORT", hostEndIndex); + int portEndIndex = url.length(); + if (portStartIndex != -1) { + int portEqualStartIndex = url.indexOf("=", portStartIndex); + portEndIndex = url.indexOf(")", portEqualStartIndex); + port = Integer.parseInt(url.substring(portEqualStartIndex + 1, portEndIndex).trim()); + } + hosts.add(host.trim() + ":" + port); + beginIndex = portEndIndex; + } while (true); + return join(",", hosts); + } + + private static String join(String delimiter, List list) { + if (list == null || list.isEmpty()) { + return ""; + } + StringBuilder builder = new StringBuilder(); + for (int i = 0, len = list.size(); i < len; i++) { + if (i == (len - 1)) { + builder.append(list.get(i)); + } else { + builder.append(list.get(i)).append(delimiter); + } + } + return builder.toString(); + } + + /** + * Implementation according to https://www.oracle.com/technetwork/database/enterprise-edition/oraclenetservices-neteasyconnect-133058.pdf + * + * @param url the url without the oracle jdbc prefix + * @return the oracle connection info if the url could be parsed, or null otherwise. + */ + public static OracleConnectionInfo parseEasyConnect(final String url) { + final Matcher matcher = EASY_CONNECT_PATTERN.matcher(url); + if (matcher.matches()) { + final OracleConnectionInfo result = new OracleConnectionInfo(); + final String host = matcher.group("host"); + final String portGroup = matcher.group("port"); + final int dbPort = + portGroup != null ? Integer.parseInt(portGroup.substring(1)) : DEFAULT_PORT; + result.setDbPeer(host + ":" + dbPort); + final String service = matcher.group("service"); + if (service != null) { + result.setDbInstance(service.substring(1)); + } else { + result.setDbInstance(host); + } + return result; + } + return null; + } + + public static class OracleConnectionInfo { + + private String dbInstance; + private String dbPeer; + + public String getDbInstance() { + return dbInstance; + } + + public OracleConnectionInfo setDbInstance(final String dbInstance) { + this.dbInstance = dbInstance; + return this; + } + + public String getDbPeer() { + return dbPeer; + } + + public OracleConnectionInfo setDbPeer(final String dbPeer) { + this.dbPeer = dbPeer; + return this; + } + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java new file mode 100644 index 000000000000..50b7323b6077 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java @@ -0,0 +1,86 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; +import java.net.URI; +import java.net.URISyntaxException; + +public class PostgreSQLURLParser extends AbstractURLParser { + + private static final int DEFAULT_PORT = 5432; + private static final String DB_TYPE = "postgresql"; + + @Override + protected URLLocation fetchDatabaseHostsIndexRange(String url) { + int hostLabelStartIndex = url.indexOf("//"); + int hostLabelEndIndex = url.indexOf("/", hostLabelStartIndex + 2); + return new URLLocation(hostLabelStartIndex + 2, hostLabelEndIndex); + } + + @Override + protected URLLocation fetchDatabaseNameIndexRange(String url) { + int hostLabelStartIndex = url.indexOf("//"); + int hostLabelEndIndex = url.indexOf("/", hostLabelStartIndex + 2); + int databaseStartTag = url.indexOf("/", hostLabelEndIndex); + int databaseEndTag = url.indexOf("?", databaseStartTag); + if (databaseEndTag == -1) { + databaseEndTag = url.length(); + } + return new URLLocation(databaseStartTag + 1, databaseEndTag); + } + + @Override + public ConnectionInfo parse(String url) { + URLLocation location = fetchDatabaseHostsIndexRange(url); + String hosts = url.substring(location.startIndex(), location.endIndex()); + String[] hostSegment = hosts.split(","); + if (hostSegment.length > 1) { + StringBuilder sb = new StringBuilder(); + for (String host : hostSegment) { + URI uri = parseHost(host); + int port = uri.getPort() == -1 ? DEFAULT_PORT : uri.getPort(); + + sb.append(uri.getHost() + ":" + port + ","); + } + if (',' == sb.charAt(sb.length() - 1)) { + sb.deleteCharAt(sb.length() - 1); + } + return new ConnectionInfo.Builder(sb.toString()).dbType(DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url)).build(); + } else { + URI uri = parseHost(hostSegment[0]); + int port = uri.getPort() == -1 ? DEFAULT_PORT : uri.getPort(); + + return new ConnectionInfo.Builder(uri.getHost(), port) + .dbType(DB_TYPE).dbInstance(fetchDatabaseNameFromURL(url)).build(); + } + } + + private URI parseHost(String host) { + try { + return new URI("proto://" + host); + } catch (URISyntaxException e) { + throw new IllegalArgumentException(e); + } + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java new file mode 100644 index 000000000000..184b5fa47fea --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java @@ -0,0 +1,111 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +public class SqlServerURLParser implements ConnectionURLParser { + + private static final int DEFAULT_PORT = 1433; + + protected String dbType() { + return "sqlserver"; + } + + @Override + public ConnectionInfo parse(String url) { + String serverName = ""; + Integer port = DEFAULT_PORT; + String dbInstance = null; + int hostIndex = url.indexOf("://"); + if (hostIndex <= 0) { + return null; + } + + String[] split = url.split(";", 2); + if (split.length > 1) { + Map props = parseQueryParams(split[1], ";"); + serverName = props.get("serverName"); + dbInstance = props.get("databaseName"); + if (props.containsKey("portNumber")) { + String portNumber = props.get("portNumber"); + try { + port = Integer.parseInt(portNumber); + } catch (NumberFormatException e) { + } + } + } + + String urlServerName = split[0].substring(hostIndex + 3); + if (!urlServerName.isEmpty()) { + serverName = urlServerName; + } + + int portLoc = serverName.indexOf(":"); + if (portLoc > 1) { + port = Integer.parseInt(serverName.substring(portLoc + 1)); + serverName = serverName.substring(0, portLoc); + } + + int instanceLoc = serverName.indexOf("\\"); + if (instanceLoc > 1) { + serverName = serverName.substring(0, instanceLoc); + } + + if (serverName.isEmpty()) { + return null; + } + + return new ConnectionInfo.Builder(serverName, port).dbType(dbType()) + .dbInstance(dbInstance).build(); + } + + private Map parseQueryParams(String query, String separator) { + if (query == null || query.isEmpty()) { + return Collections.emptyMap(); + } + Map queryParams = 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), StandardCharsets.UTF_8.name()) + : pair; + if (!queryParams.containsKey(key)) { + String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder + .decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name()) : null; + queryParams.put(key, value); + } + } catch (UnsupportedEncodingException e) { + // Ignore. + } + } + return queryParams; + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java new file mode 100644 index 000000000000..9a348f67d3fe --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +public class URLLocation { + + private final int startIndex; + private final int endIndex; + + public URLLocation(int startIndex, int endIndex) { + this.startIndex = startIndex; + this.endIndex = endIndex; + } + + public int startIndex() { + return startIndex; + } + + public int endIndex() { + return endIndex; + } + +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java new file mode 100644 index 000000000000..164af400f859 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java @@ -0,0 +1,102 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +/* + * Copyright 2017-2021 The OpenTracing Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package io.opentelemetry.instrumentation.jdbc.parser; + +import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class URLParser { + + private static final Logger log = Logger.getLogger(URLParser.class.getName()); + + private static final String MYSQL_JDBC_URL_PREFIX = "jdbc:mysql"; + private static final String ORACLE_JDBC_URL_PREFIX = "jdbc:oracle"; + private static final String H2_JDBC_URL_PREFIX = "jdbc:h2"; + private static final String POSTGRESQL_JDBC_URL_PREFIX = "jdbc:postgresql"; + private static final String MARIADB_JDBC_URL_PREFIX = "jdbc:mariadb"; + private static final String SQLSERVER_JDBC_URL_PREFIX = "jdbc:sqlserver"; + private static final String DB2_JDBC_URL_PREFIX = "jdbc:db2"; + private static final String AS400_JDBC_URL_PREFIX = "jdbc:as400"; + private static final Map parserRegister = new LinkedHashMap<>(); + + static { + // put mysql parser firstly + parserRegister.put(MYSQL_JDBC_URL_PREFIX, new MysqlURLParser()); + parserRegister.put(ORACLE_JDBC_URL_PREFIX, new OracleURLParser()); + parserRegister.put(H2_JDBC_URL_PREFIX, new H2URLParser()); + parserRegister.put(POSTGRESQL_JDBC_URL_PREFIX, new PostgreSQLURLParser()); + parserRegister.put(MARIADB_JDBC_URL_PREFIX, new MariadbURLParser()); + parserRegister.put(SQLSERVER_JDBC_URL_PREFIX, new SqlServerURLParser()); + parserRegister.put(DB2_JDBC_URL_PREFIX, new DB2URLParser()); + parserRegister.put(AS400_JDBC_URL_PREFIX, new AS400URLParser()); + } + + /** + * parse the url to the ConnectionInfo + */ + public static ConnectionInfo parse(String url) { + if (null == url) { + return ConnectionInfo.UNKNOWN_CONNECTION_INFO; + } + String lowerCaseUrl = url.toLowerCase(); + ConnectionURLParser parser = findURLParser(lowerCaseUrl); + if (parser == null) { + return ConnectionInfo.UNKNOWN_CONNECTION_INFO; + } + try { + return parser.parse(url); + } catch (Exception e) { + log.log(Level.WARNING, "error occurs when parsing jdbc url"); + } + return ConnectionInfo.UNKNOWN_CONNECTION_INFO; + } + + /** + * @deprecated use {@link #parse(String)} instead + */ + @Deprecated + public static ConnectionInfo parser(String url) { + return parse(url); + } + + private static ConnectionURLParser findURLParser(String lowerCaseUrl) { + for (Map.Entry entry : parserRegister.entrySet()) { + if (lowerCaseUrl.startsWith(entry.getKey())) { + return entry.getValue(); + } + } + return null; + } + + /** + * register new ConnectionURLParser. Can override existing parser. + */ + public static void registerConnectionParser(String urlPrefix, ConnectionURLParser parser) { + if (null == urlPrefix || parser == null) { + throw new IllegalArgumentException("urlPrefix and parser can not be null"); + } + parserRegister.put(urlPrefix.toLowerCase(), parser); + } + +} diff --git a/instrumentation/jdbc/library/src/main/resources/META-INF/services/java.sql.Driver b/instrumentation/jdbc/library/src/main/resources/META-INF/services/java.sql.Driver new file mode 100644 index 000000000000..b67485aeacf7 --- /dev/null +++ b/instrumentation/jdbc/library/src/main/resources/META-INF/services/java.sql.Driver @@ -0,0 +1 @@ +io.opentelemetry.instrumentation.jdbc.TracingDriver diff --git a/settings.gradle b/settings.gradle index 7424da25957d..f0dae2600549 100644 --- a/settings.gradle +++ b/settings.gradle @@ -179,6 +179,7 @@ include ':instrumentation:jaxws:jaxws-common:library' include ':instrumentation:jaxws:jws-1.1:javaagent' include ':instrumentation:jdbc:javaagent' include ':instrumentation:jdbc:javaagent-unit-tests' +include ':instrumentation:jdbc:library' include ':instrumentation:jedis:jedis-1.4:javaagent' include ':instrumentation:jedis:jedis-3.0:javaagent' include ':instrumentation:jetty:jetty-8.0:javaagent' From e3df35b0211a9327926d599209144e84f5b3dcef Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 19 Jun 2021 04:37:38 +0800 Subject: [PATCH 02/69] Gradle 7.1. --- gradle/wrapper/gradle-wrapper.properties | 1 - 1 file changed, 1 deletion(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 5c195045889a..69a9715077f4 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip -distributionSha256Sum=2debee19271e1b82c6e41137d78e44e6e841035230a1a169ca47fd3fb09ed87b zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists From af12c2abcc8bcab0bbd344fc529f0ec92ebb61a6 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 19 Jun 2021 04:38:10 +0800 Subject: [PATCH 03/69] Revert "Gradle 7.1." This reverts commit e3df35b0 --- gradle/wrapper/gradle-wrapper.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 69a9715077f4..5c195045889a 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip +distributionSha256Sum=2debee19271e1b82c6e41137d78e44e6e841035230a1a169ca47fd3fb09ed87b zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists From ca929fcb6064c52d170f71e3d5c484de373f0b67 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 19 Jun 2021 05:15:09 +0800 Subject: [PATCH 04/69] Code style fixes. --- .../instrumentation/jdbc/Classes.java | 67 +++++---- .../instrumentation/jdbc/ConnectionInfo.java | 18 +-- .../instrumentation/jdbc/JdbcTracing.java | 13 +- .../jdbc/JdbcTracingUtils.java | 49 ++++--- .../jdbc/TracingCallableStatement.java | 13 +- .../jdbc/TracingConnection.java | 134 +++++++++++------- .../jdbc/TracingDataSource.java | 52 ++++--- .../instrumentation/jdbc/TracingDriver.java | 40 +++--- .../jdbc/TracingPreparedStatement.java | 40 ++++-- .../jdbc/TracingStatement.java | 119 ++++++++++++---- .../instrumentation/jdbc/WrapperProxy.java | 131 ++++++++--------- .../jdbc/parser/AS400URLParser.java | 5 +- .../jdbc/parser/AbstractMatcherURLParser.java | 7 +- .../jdbc/parser/AbstractURLParser.java | 1 - .../jdbc/parser/ConnectionURLParser.java | 1 - .../jdbc/parser/DB2URLParser.java | 6 +- .../jdbc/parser/H2URLParser.java | 52 +++---- .../jdbc/parser/MariadbURLParser.java | 1 - .../jdbc/parser/MysqlURLParser.java | 16 ++- .../jdbc/parser/OracleURLParser.java | 9 +- .../jdbc/parser/PostgreSQLURLParser.java | 11 +- .../jdbc/parser/SqlServerURLParser.java | 16 ++- .../jdbc/parser/URLLocation.java | 1 - .../jdbc/parser/URLParser.java | 13 +- 24 files changed, 475 insertions(+), 340 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java index 8a2224331875..04f8249cebba 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java @@ -30,7 +30,7 @@ public final class Classes { * Adds all interfaces extended by the specified {@code iface} interface {@link Class}. * * @param iface The interface {@link Class}. - * @param set The set into which all extended interfaces are to be added. + * @param set The set into which all extended interfaces are to be added. * @throws NullPointerException If {@code iface} or {@code set} is null. */ private static void recurse(final Class iface, final HashSet> set) { @@ -52,7 +52,7 @@ private static void recurse(final Class iface, final HashSet> set) { * * @param cls The class. * @return All interfaces implemented by the class or interface represented by the specified - * class. + * class. * @throws NullPointerException If {@code cls} is null. */ public static Class[] getAllInterfaces(final Class cls) { @@ -72,8 +72,7 @@ public static Class[] getAllInterfaces(final Class cls) { for (final Class iface : ifaces) { recurse(iface, set); } - } - while ((parent = parent.getSuperclass()) != null); + } while ((parent = parent.getSuperclass()) != null); return set == null ? ifaces : set.toArray(new Class[set.size()]); } @@ -81,10 +80,11 @@ public static Class[] getAllInterfaces(final Class cls) { * Returns a Method object that reflects the specified declared method of the class or interface * represented by {@code cls} (excluding inherited methods), or {@code null} if the method is not * found. - *

- * Declared methods include public, protected, default (package) access, and private visibility. - *

- * The {@code name} parameter is a String that specifies the simple name of the desired method, + * + *

Declared methods include public, protected, default (package) access, and private + * visibility. + * + *

The {@code name} parameter is a String that specifies the simple name of the desired method, * and the {@code parameterTypes} parameter is an array of Class objects that identify the * method's formal parameter types, in declared order. If more than one method with the same * parameter types is declared in a class, and one of these methods has a return type that is more @@ -92,25 +92,25 @@ public static Class[] getAllInterfaces(final Class cls) { * chosen arbitrarily. If the name is {@code ""} or {@code ""} this method returns * {@code null}. If this Class object represents an array type, then this method does not find the * clone() method. - *

- * This method differentiates itself from {@link Class#getDeclaredMethod(String, Class...)} by + * + *

This method differentiates itself from {@link Class#getDeclaredMethod(String, Class...)} by * returning {@code null} when a method is not found, instead of throwing {@link * NoSuchMethodException}. * - * @param cls The class in which to find the declared method. - * @param name The simple name of the method. + * @param cls The class in which to find the declared method. + * @param name The simple name of the method. * @param parameterTypes The parameter array. * @return A Method object that reflects the specified declared method of the class or interface - * represented by {@code cls} (excluding inherited methods), or {@code null} if the method is not - * found. + * represented by {@code cls} (excluding inherited methods), or {@code null} if the method is + * not found. * @throws NullPointerException If {@code cls} or {@code name} is null. */ - public static Method getDeclaredMethod(final Class cls, final String name, - final Class... parameterTypes) { + public static Method getDeclaredMethod( + final Class cls, final String name, final Class... parameterTypes) { final Method[] methods = cls.getDeclaredMethods(); for (final Method method : methods) { - if (name.equals(method.getName()) && Arrays - .equals(method.getParameterTypes(), parameterTypes)) { + if (name.equals(method.getName()) + && Arrays.equals(method.getParameterTypes(), parameterTypes)) { return method; } } @@ -122,10 +122,11 @@ public static Method getDeclaredMethod(final Class cls, final String name, * Returns a Method object that reflects the specified declared method of the class or interface * represented by {@code cls} (including inherited methods), or {@code null} if the method is not * found. - *

- * Declared methods include public, protected, default (package) access, and private visibility. - *

- * The {@code name} parameter is a String that specifies the simple name of the desired method, + * + *

Declared methods include public, protected, default (package) access, and private + * visibility. + * + *

The {@code name} parameter is a String that specifies the simple name of the desired method, * and the {@code parameterTypes} parameter is an array of Class objects that identify the * method's formal parameter types, in declared order. If more than one method with the same * parameter types is declared in a class, and one of these methods has a return type that is more @@ -133,29 +134,27 @@ public static Method getDeclaredMethod(final Class cls, final String name, * chosen arbitrarily. If the name is {@code ""} or {@code ""} this method returns * {@code null}. If this Class object represents an array type, then this method does not find the * clone() method. - *

- * This method differentiates itself from {@link Class#getDeclaredMethod(String, Class...)} by + * + *

This method differentiates itself from {@link Class#getDeclaredMethod(String, Class...)} by * returning {@code null} when a method is not found, instead of throwing {@link * NoSuchMethodException}. * - * @param cls The class in which to find the declared method. - * @param name The simple name of the method. + * @param cls The class in which to find the declared method. + * @param name The simple name of the method. * @param parameterTypes The parameter array. * @return A Method object that reflects the specified declared method of the class or interface - * represented by {@code cls} (including inherited methods), or {@code null} if the method is not - * found. + * represented by {@code cls} (including inherited methods), or {@code null} if the method is + * not found. * @throws NullPointerException If {@code cls} or {@code name} is null. */ - public static Method getDeclaredMethodDeep(Class cls, final String name, - final Class... parameterTypes) { + public static Method getDeclaredMethodDeep( + Class cls, final String name, final Class... parameterTypes) { Method method; do { method = getDeclaredMethod(cls, name, parameterTypes); - } - while (method == null && (cls = cls.getSuperclass()) != null); + } while (method == null && (cls = cls.getSuperclass()) != null); return method; } - private Classes() { - } + private Classes() {} } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java index f2d87ecbd725..59dd5c83bcdd 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java @@ -22,8 +22,8 @@ public class ConnectionInfo { - public static ConnectionInfo UNKNOWN_CONNECTION_INFO = new Builder("unknown_peer") - .dbType("unknown_type").dbInstance("unknown_instance").build(); + public static final ConnectionInfo UNKNOWN_CONNECTION_INFO = + new Builder("unknown_peer").dbType("unknown_type").dbInstance("unknown_instance").build(); private final String dbType; private final String dbUser; @@ -31,8 +31,8 @@ public class ConnectionInfo { private final String dbPeer; private final String dbPeerService; - private ConnectionInfo(String dbType, String dbUser, String dbInstance, String dbHost, - Integer dbPort) { + private ConnectionInfo( + String dbType, String dbUser, String dbInstance, String dbHost, Integer dbPort) { this.dbType = dbType; this.dbUser = dbUser; this.dbInstance = dbInstance; @@ -54,9 +54,7 @@ private ConnectionInfo(String dbType, String dbUser, String dbInstance, String d this.dbPeerService = makePeerService(); } - /** - * Make a unique serviceName that could be used in dependency diagram. - */ + /** Make a unique serviceName that could be used in dependency diagram. */ private String makePeerService() { if (null != dbInstance && !dbInstance.isEmpty()) { return dbInstance + "[" + dbType + "(" + dbPeer + ")]"; @@ -122,10 +120,8 @@ public ConnectionInfo build() { if (this.dbPeer != null && !dbPeer.isEmpty()) { return new ConnectionInfo(this.dbType, this.dbUser, this.dbInstance, this.dbPeer); } - return new ConnectionInfo(this.dbType, this.dbUser, this.dbInstance, this.dbHost, - this.dbPort); + return new ConnectionInfo( + this.dbType, this.dbUser, this.dbInstance, this.dbHost, this.dbPort); } - } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java index 261f39bf7fc3..19e683d75268 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java @@ -37,11 +37,9 @@ public static boolean isTraceEnabled() { return JdbcTracing.traceEnabled; } - /** - * can be modified by application code - */ - private static int slowQueryThresholdMs = Integer - .getInteger("io.opentracing.contrib.jdbc.slowQueryThresholdMs", 0); + /** can be modified by application code */ + private static int slowQueryThresholdMs = + Integer.getInteger("io.opentracing.contrib.jdbc.slowQueryThresholdMs", 0); public static int getSlowQueryThresholdMs() { return slowQueryThresholdMs; @@ -51,8 +49,8 @@ public static void setSlowQueryThresholdMs(final int slowQueryThresholdMs) { JdbcTracing.slowQueryThresholdMs = slowQueryThresholdMs; } - private static int excludeFastQueryThresholdMs = Integer - .getInteger("io.opentracing.contrib.jdbc.excludeFastQueryThresholdMs", 0); + private static int excludeFastQueryThresholdMs = + Integer.getInteger("io.opentracing.contrib.jdbc.excludeFastQueryThresholdMs", 0); public static int getExcludeFastQueryThresholdMs() { return excludeFastQueryThresholdMs; @@ -61,5 +59,4 @@ public static int getExcludeFastQueryThresholdMs() { public static void setExcludeFastQueryThresholdMs(final int excludeFastQueryThresholdMs) { JdbcTracing.excludeFastQueryThresholdMs = excludeFastQueryThresholdMs; } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java index 31d0a6484cbc..ce9db5418ec8 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java @@ -39,7 +39,8 @@ class JdbcTracingUtils { // TODO is it requires for OTEL? static final AttributeKey SAMPLING_PRIORITY = AttributeKey.longKey("sampling.priority"); - static Span buildSpan(String operationName, + static Span buildSpan( + String operationName, String sql, ConnectionInfo connectionInfo, boolean withActiveSpanOnly, @@ -54,8 +55,7 @@ static Span buildSpan(String operationName, return Span.getInvalid(); } - SpanBuilder spanBuilder = tracer.spanBuilder(operationName) - .setSpanKind(SpanKind.CLIENT); + SpanBuilder spanBuilder = tracer.spanBuilder(operationName).setSpanKind(SpanKind.CLIENT); Span span = spanBuilder.startSpan(); decorate(span, sql, connectionInfo); @@ -63,23 +63,28 @@ static Span buildSpan(String operationName, return span; } - static void execute(String operationName, + static void execute( + String operationName, CheckedRunnable runnable, String sql, ConnectionInfo connectionInfo, boolean withActiveSpanOnly, Set ignoreStatements, - Tracer tracer) throws E { + Tracer tracer) + throws E { if (!JdbcTracing.isTraceEnabled() || (withActiveSpanOnly && Span.fromContextOrNull(Context.current()) == null)) { runnable.run(); return; } - final Span span = buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, - ignoreStatements, tracer); - long startTime = (JdbcTracing.getSlowQueryThresholdMs() > 0 - || JdbcTracing.getExcludeFastQueryThresholdMs() > 0) ? System.nanoTime() : 0; + final Span span = + buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + long startTime = + (JdbcTracing.getSlowQueryThresholdMs() > 0 + || JdbcTracing.getExcludeFastQueryThresholdMs() > 0) + ? System.nanoTime() + : 0; try (Scope ignored = span.makeCurrent()) { runnable.run(); } catch (Exception e) { @@ -91,20 +96,22 @@ static void execute(String operationName, } } - static T call(String operationName, + static T call( + String operationName, CheckedCallable callable, String sql, ConnectionInfo connectionInfo, boolean withActiveSpanOnly, Set ignoreStatements, - Tracer tracer) throws E { + Tracer tracer) + throws E { if (!JdbcTracing.isTraceEnabled() || (withActiveSpanOnly && Span.fromContextOrNull(Context.current()) == null)) { return callable.call(); } - final Span span = buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, - ignoreStatements, tracer); + final Span span = + buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); long startTime = JdbcTracing.getSlowQueryThresholdMs() > 0 ? System.nanoTime() : 0; try (Scope ignored = span.makeCurrent()) { return callable.call(); @@ -121,9 +128,7 @@ private static boolean isNotEmpty(CharSequence s) { return s != null && !"".contentEquals(s); } - /** - * Add tags to span. Skip empty tags to avoid reported NPE in tracers. - */ + /** Add tags to span. Skip empty tags to avoid reported NPE in tracers. */ private static void decorate(Span span, String sql, ConnectionInfo connectionInfo) { if (isNotEmpty(sql)) { span.setAttribute(SemanticAttributes.DB_STATEMENT, sql); @@ -155,12 +160,13 @@ static void onError(Throwable throwable, Span span) { private static void queryThresholdChecks(Span span, long startTime) { long completionTime = System.nanoTime() - startTime; - if (JdbcTracing.getExcludeFastQueryThresholdMs() > 0 && completionTime < TimeUnit.MILLISECONDS - .toNanos(JdbcTracing.getExcludeFastQueryThresholdMs())) { + if (JdbcTracing.getExcludeFastQueryThresholdMs() > 0 + && completionTime + < TimeUnit.MILLISECONDS.toNanos(JdbcTracing.getExcludeFastQueryThresholdMs())) { span.setAttribute(SAMPLING_PRIORITY, 0); } - if (JdbcTracing.getSlowQueryThresholdMs() > 0 && completionTime > TimeUnit.MILLISECONDS - .toNanos(JdbcTracing.getSlowQueryThresholdMs())) { + if (JdbcTracing.getSlowQueryThresholdMs() > 0 + && completionTime > TimeUnit.MILLISECONDS.toNanos(JdbcTracing.getSlowQueryThresholdMs())) { span.setAttribute(SLOW, true); } } @@ -169,14 +175,11 @@ private static void queryThresholdChecks(Span span, long startTime) { interface CheckedRunnable { void run() throws E; - } @FunctionalInterface interface CheckedCallable { T call() throws E; - } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java index fb4ab347e4ec..8b5d9d4a75b7 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java @@ -41,13 +41,17 @@ import java.util.Map; import java.util.Set; -public class TracingCallableStatement extends TracingPreparedStatement implements - CallableStatement { +public class TracingCallableStatement extends TracingPreparedStatement + implements CallableStatement { private final CallableStatement statement; - public TracingCallableStatement(CallableStatement statement, String query, - ConnectionInfo connectionInfo, boolean withActiveSpanOnly, Set ignoreStatements, + public TracingCallableStatement( + CallableStatement statement, + String query, + ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, + Set ignoreStatements, Tracer tracer) { super(statement, query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); this.statement = statement; @@ -627,5 +631,4 @@ public T getObject(int parameterIndex, Class type) throws SQLException { public T getObject(String parameterName, Class type) throws SQLException { return statement.getObject(parameterName, type); } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java index 2cd10fafb8f1..152c5d66e72e 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java @@ -49,8 +49,12 @@ public class TracingConnection implements Connection { private final Set ignoreStatements; private final Tracer tracer; - public TracingConnection(Connection connection, ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, Set ignoreStatements, Tracer tracer) { + public TracingConnection( + Connection connection, + ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, + Set ignoreStatements, + Tracer tracer) { this.connection = connection; this.connectionInfo = connectionInfo; this.withActiveSpanOnly = withActiveSpanOnly; @@ -61,116 +65,145 @@ public TracingConnection(Connection connection, ConnectionInfo connectionInfo, @Override public Statement createStatement() throws SQLException { final Statement statement = connection.createStatement(); - return WrapperProxy - .wrap(statement, new TracingStatement(statement, connectionInfo, withActiveSpanOnly, - ignoreStatements, tracer)); + return WrapperProxy.wrap( + statement, + new TracingStatement( + statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { final Statement statement = connection.createStatement(resultSetType, resultSetConcurrency); - return WrapperProxy.wrap(statement, new TracingStatement(statement, - connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return WrapperProxy.wrap( + statement, + new TracingStatement( + statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { - final Statement statement = connection - .createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - return WrapperProxy.wrap(statement, new TracingStatement(statement, - connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + public Statement createStatement( + int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + final Statement statement = + connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); + return WrapperProxy.wrap( + statement, + new TracingStatement( + statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql); - return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, connectionInfo, - withActiveSpanOnly, ignoreStatements, tracer)); + return WrapperProxy.wrap( + statement, + new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - final PreparedStatement statement = connection - .prepareStatement(sql, resultSetType, resultSetConcurrency); - return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, connectionInfo, - withActiveSpanOnly, ignoreStatements, tracer)); + final PreparedStatement statement = + connection.prepareStatement(sql, resultSetType, resultSetConcurrency); + return WrapperProxy.wrap( + statement, + new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { - final PreparedStatement statement = connection - .prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + public PreparedStatement prepareStatement( + String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) + throws SQLException { + final PreparedStatement statement = + connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + return WrapperProxy.wrap( + statement, + new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, autoGeneratedKeys); - return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, - connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return WrapperProxy.wrap( + statement, + new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, columnIndexes); - return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, - connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return WrapperProxy.wrap( + statement, + new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, columnNames); - return WrapperProxy.wrap(statement, new TracingPreparedStatement(statement, sql, connectionInfo, - withActiveSpanOnly, ignoreStatements, tracer)); + return WrapperProxy.wrap( + statement, + new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override public CallableStatement prepareCall(String sql) throws SQLException { final CallableStatement statement = connection.prepareCall(sql); - return WrapperProxy.wrap(statement, - new TracingCallableStatement(connection.prepareCall(sql), sql, connectionInfo, - withActiveSpanOnly, ignoreStatements, tracer)); + return WrapperProxy.wrap( + statement, + new TracingCallableStatement( + connection.prepareCall(sql), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer)); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - final CallableStatement statement = connection - .prepareCall(sql, resultSetType, resultSetConcurrency); - return WrapperProxy.wrap(statement, new TracingCallableStatement(statement, sql, connectionInfo, - withActiveSpanOnly, ignoreStatements, tracer)); + final CallableStatement statement = + connection.prepareCall(sql, resultSetType, resultSetConcurrency); + return WrapperProxy.wrap( + statement, + new TracingCallableStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { - final CallableStatement statement = connection - .prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - return WrapperProxy.wrap(statement, new TracingCallableStatement(statement, sql, - connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + public CallableStatement prepareCall( + String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) + throws SQLException { + final CallableStatement statement = + connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + return WrapperProxy.wrap( + statement, + new TracingCallableStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override public void commit() throws SQLException { - JdbcTracingUtils.execute("Commit", connection::commit, null, - connectionInfo, withActiveSpanOnly, null, tracer); + JdbcTracingUtils.execute( + "Commit", connection::commit, null, connectionInfo, withActiveSpanOnly, null, tracer); } @Override public void rollback() throws SQLException { - JdbcTracingUtils.execute("Rollback", connection::rollback, null, - connectionInfo, withActiveSpanOnly, null, tracer); + JdbcTracingUtils.execute( + "Rollback", connection::rollback, null, connectionInfo, withActiveSpanOnly, null, tracer); } @Override public void close() throws SQLException { - JdbcTracingUtils.execute("Close", connection::close, null, - connectionInfo, withActiveSpanOnly, null, tracer); + JdbcTracingUtils.execute( + "Close", connection::close, null, connectionInfo, withActiveSpanOnly, null, tracer); } @Override @@ -367,5 +400,4 @@ public T unwrap(Class iface) throws SQLException { public boolean isWrapperFor(Class iface) throws SQLException { return connection.isWrapperFor(iface); } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java index 9ec45c69fa6f..dcd39c96fb03 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java @@ -43,13 +43,12 @@ public class TracingDataSource implements DataSource, AutoCloseable { private final boolean withActiveSpanOnly; private final Set ignoreStatements; - public TracingDataSource(final Tracer tracer, - final DataSource underlying) { - this(tracer, underlying, null, DEFAULT_WITH_ACTIVE_SPAN_ONLY, - DEFAULT_IGNORED_STATEMENTS); + public TracingDataSource(final Tracer tracer, final DataSource underlying) { + this(tracer, underlying, null, DEFAULT_WITH_ACTIVE_SPAN_ONLY, DEFAULT_IGNORED_STATEMENTS); } - public TracingDataSource(final Tracer tracer, + public TracingDataSource( + final Tracer tracer, final DataSource underlying, final ConnectionInfo connectionInfo, final boolean withActiveSpanOnly, @@ -81,25 +80,39 @@ public DataSource getUnderlying() { @Override public Connection getConnection() throws SQLException { - final Connection connection = JdbcTracingUtils - .call("AcquireConnection", underlying::getConnection, - null, connectionInfo, withActiveSpanOnly, null, tracer); - - return WrapperProxy - .wrap(connection, new TracingConnection(connection, connectionInfo, withActiveSpanOnly, - ignoreStatements, tracer)); + final Connection connection = + JdbcTracingUtils.call( + "AcquireConnection", + underlying::getConnection, + null, + connectionInfo, + withActiveSpanOnly, + null, + tracer); + + return WrapperProxy.wrap( + connection, + new TracingConnection( + connection, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override public Connection getConnection(final String username, final String password) throws SQLException { - final Connection connection = JdbcTracingUtils.call("AcquireConnection", () -> - underlying.getConnection(username, password), null, connectionInfo, - withActiveSpanOnly, null, tracer); - - return WrapperProxy - .wrap(connection, new TracingConnection(connection, connectionInfo, withActiveSpanOnly, - ignoreStatements, tracer)); + final Connection connection = + JdbcTracingUtils.call( + "AcquireConnection", + () -> underlying.getConnection(username, password), + null, + connectionInfo, + withActiveSpanOnly, + null, + tracer); + + return WrapperProxy.wrap( + connection, + new TracingConnection( + connection, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); } @Override @@ -143,5 +156,4 @@ public void close() throws Exception { ((AutoCloseable) underlying).close(); } } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java index 3bc7342eec27..b13ee49a9bfb 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java @@ -48,7 +48,8 @@ public class TracingDriver implements Driver { protected static final String WITH_ACTIVE_SPAN_ONLY = TRACE_WITH_ACTIVE_SPAN_ONLY + "=true"; - public static final String IGNORE_FOR_TRACING_REGEX = "ignoreForTracing=\"((?:\\\\\"|[^\"])*)\"[;]*"; + public static final String IGNORE_FOR_TRACING_REGEX = + "ignoreForTracing=\"((?:\\\\\"|[^\"])*)\"[;]*"; protected static final Pattern PATTERN_FOR_IGNORING = Pattern.compile(IGNORE_FOR_TRACING_REGEX); @@ -60,9 +61,7 @@ public class TracingDriver implements Driver { } } - /** - * @return The singleton instance of the {@code TracingDriver}. - */ + /** @return The singleton instance of the {@code TracingDriver}. */ public static Driver load() { return INSTANCE; } @@ -72,7 +71,7 @@ public static Driver load() { * "interceptor mode" works. WARNING: Driver like Oracle JDBC may fail since it's destroyed * forever after deregistration. */ - public synchronized static void ensureRegisteredAsTheFirstDriver() { + public static synchronized void ensureRegisteredAsTheFirstDriver() { try { Enumeration enumeration = DriverManager.getDrivers(); List drivers = null; @@ -172,21 +171,26 @@ public Connection connect(String url, Properties info) throws SQLException { final Tracer currentTracer = getTracer(); final ConnectionInfo connectionInfo = URLParser.parse(url); final String realUrl = url; - final Connection connection = JdbcTracingUtils.call("AcquireConnection", () -> - wrappedDriver.connect(realUrl, info), null, connectionInfo, withActiveSpanOnly, - null, currentTracer); - - return WrapperProxy - .wrap(connection, new TracingConnection(connection, connectionInfo, withActiveSpanOnly, - ignoreStatements, currentTracer)); + final Connection connection = + JdbcTracingUtils.call( + "AcquireConnection", + () -> wrappedDriver.connect(realUrl, info), + null, + connectionInfo, + withActiveSpanOnly, + null, + currentTracer); + + return WrapperProxy.wrap( + connection, + new TracingConnection( + connection, connectionInfo, withActiveSpanOnly, ignoreStatements, currentTracer)); } @Override public boolean acceptsURL(String url) throws SQLException { - return url != null && ( - url.startsWith(getUrlPrefix()) || - (interceptorMode && url.startsWith("jdbc:")) - ); + return url != null + && (url.startsWith(getUrlPrefix()) || (interceptorMode && url.startsWith("jdbc:"))); } @Override @@ -245,7 +249,8 @@ protected Driver findDriver(String realUrl) throws SQLException { protected String extractRealUrl(String url) { String extracted = url.startsWith(getUrlPrefix()) ? url.replace(getUrlPrefix(), "jdbc:") : url; - return extracted.replaceAll(TRACE_WITH_ACTIVE_SPAN_ONLY + "=(true|false)[;]*", "") + return extracted + .replaceAll(TRACE_WITH_ACTIVE_SPAN_ONLY + "=(true|false)[;]*", "") .replaceAll(IGNORE_FOR_TRACING_REGEX, "") .replaceAll("\\?$", ""); } @@ -271,5 +276,4 @@ Tracer getTracer() { } return tracer; } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java index 01ed7f34927b..14fcbb0601af 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java @@ -48,8 +48,12 @@ public class TracingPreparedStatement extends TracingStatement implements Prepar private final PreparedStatement preparedStatement; private final String query; - public TracingPreparedStatement(PreparedStatement preparedStatement, String query, - ConnectionInfo connectionInfo, boolean withActiveSpanOnly, Set ignoreStatements, + public TracingPreparedStatement( + PreparedStatement preparedStatement, + String query, + ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, + Set ignoreStatements, Tracer tracer) { super(preparedStatement, query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); this.preparedStatement = preparedStatement; @@ -58,20 +62,38 @@ public TracingPreparedStatement(PreparedStatement preparedStatement, String quer @Override public ResultSet executeQuery() throws SQLException { - return JdbcTracingUtils.call("Query", preparedStatement::executeQuery, - query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Query", + preparedStatement::executeQuery, + query, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public int executeUpdate() throws SQLException { - return JdbcTracingUtils.call("Update", preparedStatement::executeUpdate, - query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Update", + preparedStatement::executeUpdate, + query, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public boolean execute() throws SQLException { - return JdbcTracingUtils.call("Execute", preparedStatement::execute, - query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Execute", + preparedStatement::execute, + query, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override @@ -335,9 +357,9 @@ public void setBlob(int parameterIndex, InputStream inputStream) throws SQLExcep preparedStatement.setBlob(parameterIndex, inputStream); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNClob(int parameterIndex, Reader reader) throws SQLException { preparedStatement.setNClob(parameterIndex, reader); } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java index 954219024520..3accd7a05e79 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java @@ -39,13 +39,22 @@ public class TracingStatement implements Statement { final Set ignoreStatements; final Tracer tracer; - TracingStatement(Statement statement, ConnectionInfo connectionInfo, boolean withActiveSpanOnly, - Set ignoreStatements, Tracer tracer) { + TracingStatement( + Statement statement, + ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, + Set ignoreStatements, + Tracer tracer) { this(statement, null, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } - TracingStatement(Statement statement, String query, ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, Set ignoreStatements, Tracer tracer) { + TracingStatement( + Statement statement, + String query, + ConnectionInfo connectionInfo, + boolean withActiveSpanOnly, + Set ignoreStatements, + Tracer tracer) { this.statement = statement; this.query = query; this.connectionInfo = connectionInfo; @@ -56,62 +65,122 @@ public class TracingStatement implements Statement { @Override public ResultSet executeQuery(String sql) throws SQLException { - return JdbcTracingUtils.call("Query", () -> statement.executeQuery(sql), - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Query", + () -> statement.executeQuery(sql), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public int executeUpdate(String sql) throws SQLException { - return JdbcTracingUtils.call("Update", () -> statement.executeUpdate(sql), - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Update", + () -> statement.executeUpdate(sql), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - return JdbcTracingUtils.call("Update", () -> statement.executeUpdate(sql, autoGeneratedKeys), - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Update", + () -> statement.executeUpdate(sql, autoGeneratedKeys), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - return JdbcTracingUtils.call("Update", () -> statement.executeUpdate(sql, columnIndexes), - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Update", + () -> statement.executeUpdate(sql, columnIndexes), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { - return JdbcTracingUtils.call("Update", () -> statement.executeUpdate(sql, columnNames), - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Update", + () -> statement.executeUpdate(sql, columnNames), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public boolean execute(String sql) throws SQLException { - return JdbcTracingUtils.call("Execute", () -> statement.execute(sql), - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Execute", + () -> statement.execute(sql), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return JdbcTracingUtils.call("Execute", () -> statement.execute(sql, autoGeneratedKeys), - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Execute", + () -> statement.execute(sql, autoGeneratedKeys), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { - return JdbcTracingUtils.call("Execute", () -> statement.execute(sql, columnIndexes), - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Execute", + () -> statement.execute(sql, columnIndexes), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public boolean execute(String sql, String[] columnNames) throws SQLException { - return JdbcTracingUtils.call("Execute", () -> statement.execute(sql, columnNames), - sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Execute", + () -> statement.execute(sql, columnNames), + sql, + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override public int[] executeBatch() throws SQLException { - return JdbcTracingUtils.call("Update", statement::executeBatch, - buildSqlForBatch(), connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return JdbcTracingUtils.call( + "Update", + statement::executeBatch, + buildSqlForBatch(), + connectionInfo, + withActiveSpanOnly, + ignoreStatements, + tracer); } @Override @@ -236,6 +305,7 @@ public Connection getConnection() throws SQLException { return statement.getConnection(); } + @SuppressWarnings("UngroupedOverloads") @Override public boolean getMoreResults(int current) throws SQLException { return statement.getMoreResults(current); @@ -307,5 +377,4 @@ private String buildSqlForBatch() { return sqlBuilder.toString(); } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java index 45a3d8d6a97f..c4c5ece60fbe 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java @@ -25,9 +25,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; -/** - * Utility class for the creation of wrapper proxies. - */ +/** Utility class for the creation of wrapper proxies. */ public final class WrapperProxy { private interface WrapperInvocationHandler extends InvocationHandler { @@ -41,28 +39,28 @@ private interface WrapperInvocationHandler extends InvocationHandler { * Returns a {@linkplain Proxy proxy} with type {@code } of the specified {@code obj} wrapping * the provided {@code wrapper} instance. Method invocations on the proxy instance will be handled * as such: + * *

    - *
  1. The {@code wrapper} instance will be invoked for methods that - * exist in the {@code wrapper} instance.
  2. - *
  3. The {@code obj} instance will be invoked for methods that do not - * exist in the {@code wrapper} instance.
  4. + *
  5. The {@code wrapper} instance will be invoked for methods that exist in the {@code + * wrapper} instance. + *
  6. The {@code obj} instance will be invoked for methods that do not exist in the + * {@code wrapper} instance. *
- * The type of the returned {@linkplain Proxy proxy} will be the composition - * of all super-interfaces of the runtime type of the specified {@code obj} - * instance. - *

- * Note: The runtime type of the returned instance will not be - * of a concrete class, but rather a composition of all super-interfaces of - * the concrete class {@code }. It is therefore not possible to cast the - * instance returned by this method to a concrete class, but rather any - * super-interface of the concrete class. * - * @param The type parameter of the specified arguments. - * @param obj The target object instance to wrap. + * The type of the returned {@linkplain Proxy proxy} will be the composition of all + * super-interfaces of the runtime type of the specified {@code obj} instance. + * + *

Note: The runtime type of the returned instance will not be of a concrete + * class, but rather a composition of all super-interfaces of the concrete class {@code }. It + * is therefore not possible to cast the instance returned by this method to a concrete class, but + * rather any super-interface of the concrete class. + * + * @param The type parameter of the specified arguments. + * @param obj The target object instance to wrap. * @param wrapper The wrapping object. * @return a {@linkplain Proxy proxy} with type {@code } of the specified {@code obj} wrapping - * wrapping the provided {@code wrapper} instance, or, {@code wrapper} if {@code obj == wrapper}, - * or if {@code target} or {@code wrapper} is null. + * wrapping the provided {@code wrapper} instance, or, {@code wrapper} if {@code obj == + * wrapper}, or if {@code target} or {@code wrapper} is null. */ @SuppressWarnings("unchecked") public static T wrap(final T obj, final T wrapper) { @@ -72,46 +70,50 @@ public static T wrap(final T obj, final T wrapper) { final Class objClass = obj.getClass(); final Class wrapperClass = wrapper.getClass(); - return (T) Proxy.newProxyInstance(objClass.getClassLoader(), Classes.getAllInterfaces(objClass), - new WrapperInvocationHandler() { - @Override - public Object invoke(final Object proxy, final Method method, final Object[] args) - throws Throwable { - try { - try { - if (method.getDeclaringClass().isAssignableFrom(wrapperClass)) { - return method.invoke(wrapper, args); + return (T) + Proxy.newProxyInstance( + objClass.getClassLoader(), + Classes.getAllInterfaces(objClass), + new WrapperInvocationHandler() { + @Override + public Object invoke(final Object proxy, final Method method, final Object[] args) + throws Throwable { + try { + try { + if (method.getDeclaringClass().isAssignableFrom(wrapperClass)) { + return method.invoke(wrapper, args); + } + + final Method specific = + Classes.getDeclaredMethodDeep( + wrapperClass, method.getName(), method.getParameterTypes()); + if (specific != null) { + return specific.invoke(wrapper, args); + } + } catch (final IllegalArgumentException ignored) { + // nothing to do, expected exception + } + + return method.invoke(obj, args); + } catch (final InvocationTargetException e) { + throw e.getCause(); + } catch (final IllegalAccessException e) { + final IllegalAccessError error = new IllegalAccessError(e.getMessage()); + error.setStackTrace(e.getStackTrace()); + throw error; } + } - final Method specific = Classes - .getDeclaredMethodDeep(wrapperClass, method.getName(), - method.getParameterTypes()); - if (specific != null) { - return specific.invoke(wrapper, args); - } - } catch (final IllegalArgumentException e) { + @Override + public T getObject() { + return obj; } - return method.invoke(obj, args); - } catch (final InvocationTargetException e) { - throw e.getCause(); - } catch (final IllegalAccessException e) { - final IllegalAccessError error = new IllegalAccessError(e.getMessage()); - error.setStackTrace(e.getStackTrace()); - throw error; - } - } - - @Override - public T getObject() { - return obj; - } - - @Override - public T getWrapper() { - return wrapper; - } - }); + @Override + public T getWrapper() { + return wrapper; + } + }); } /** @@ -122,19 +124,19 @@ public T getWrapper() { * @throws NullPointerException If {@code obj} is null. */ public static boolean isWrapper(final Object obj) { - return Proxy.isProxyClass(obj.getClass()) && Proxy - .getInvocationHandler(obj) instanceof WrapperInvocationHandler; + return Proxy.isProxyClass(obj.getClass()) + && Proxy.getInvocationHandler(obj) instanceof WrapperInvocationHandler; } /** * Tests whether the specified object is a proxy of a wrapped instance type matching the provided * {@code wrappedClass}. * - * @param The common type of the proxy and wrapped instance. - * @param obj The object to test. + * @param The common type of the proxy and wrapped instance. + * @param obj The object to test. * @param wrappedClass The type of the instance wrapped by the specified {@code obj}. * @return Whether the specified object is a proxy of a wrapped instance type matching the - * provided {@code wrappedClass}. + * provided {@code wrappedClass}. * @throws NullPointerException If {@code obj} or {@code wrappedClass} is null. */ public static boolean isWrapper(final T obj, final Class wrappedClass) { @@ -147,10 +149,9 @@ public static boolean isWrapper(final T obj, final Class wrappe return false; } - return wrappedClass - .isAssignableFrom(((WrapperInvocationHandler) handler).getWrapper().getClass()); + return wrappedClass.isAssignableFrom( + ((WrapperInvocationHandler) handler).getWrapper().getClass()); } - private WrapperProxy() { - } + private WrapperProxy() {} } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java index e80564b87d53..9c0d8afb0a58 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java @@ -30,8 +30,8 @@ */ public class AS400URLParser extends AbstractMatcherURLParser { - private static final Pattern AS400_URL_PATTERN = Pattern - .compile( + private static final Pattern AS400_URL_PATTERN = + Pattern.compile( "jdbc:as400:\\/\\/(?[^\\/;]+)(\\/(?[^;\\/]*))?\\/?(;(?.*))?"); private static final String AS400_TYPE = "as400"; @@ -39,5 +39,4 @@ public class AS400URLParser extends AbstractMatcherURLParser { public AS400URLParser() { super(AS400_URL_PATTERN, AS400_TYPE); } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java index e594443e7db7..be72b129a8a5 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java @@ -45,7 +45,7 @@ public AbstractMatcherURLParser(Pattern pattern, String dbType) { * Useful to modify ConnectionInfo before build * * @param matcher The matcher to apply. Note that the matcher must have a group named host, and - * optionally, a group named port and another named instance + * optionally, a group named port and another named instance * @return */ protected ConnectionInfo.Builder initBuilder(Matcher matcher) { @@ -71,9 +71,7 @@ protected ConnectionInfo.Builder initBuilder(Matcher matcher) { } catch (IllegalArgumentException e) { // The pattern has no instance group } - return builder - .dbType(this.dbType) - .dbInstance(instance); + return builder.dbType(this.dbType).dbInstance(instance); } @Override @@ -85,5 +83,4 @@ public ConnectionInfo parse(String url) { return ConnectionInfo.UNKNOWN_CONNECTION_INFO; } } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java index b5ea59f384dc..f0dfad552869 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java @@ -64,5 +64,4 @@ protected String fetchDatabaseNameFromURL(String url) { protected String fetchDatabaseNameFromURL(String url, int[] indexRange) { return url.substring(indexRange[0], indexRange[1]); } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java index b5aeeac5a657..713027879120 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java @@ -25,5 +25,4 @@ public interface ConnectionURLParser { ConnectionInfo parse(final String url); - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java index 07fec5ed5944..69ddadfc2527 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java @@ -30,9 +30,8 @@ */ public class DB2URLParser extends AbstractMatcherURLParser { - - private static final Pattern DB2_URL_PATTERN = Pattern - .compile( + private static final Pattern DB2_URL_PATTERN = + Pattern.compile( "jdbc:db2:\\/\\/(?[^:\\/]+)(:(?\\d+))?\\/(?[^:]+)(:(?.*))?"); private static final String DB2_TYPE = "db2"; @@ -40,5 +39,4 @@ public class DB2URLParser extends AbstractMatcherURLParser { public DB2URLParser() { super(DB2_URL_PATTERN, DB2_TYPE); } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java index 6e7a26289165..e6f1c8cacad4 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java @@ -26,22 +26,15 @@ public class H2URLParser extends AbstractURLParser { private static final String LOCALHOST = "localhost"; private static final int DEFAULT_PORT = 8084; - /** - * Flag that H2 running with memory mode. - */ + /** Flag that H2 running with memory mode. */ private static final String MEMORY_MODE_FLAG = "mem"; - /** - * Flag that H2 running with tcp mode. - */ + /** Flag that H2 running with tcp mode. */ private static final String TCP_MODE_FLAG = "h2:tcp"; - /** - * Flag that H2 running with file mode. - */ + /** Flag that H2 running with file mode. */ private static final String FILE_MODE_FLAG = "file"; - /** - * Flag that H2 running with implicit file mode. - */ + /** Flag that H2 running with implicit file mode. */ private static final String IMPLICIT_FILE_MODE_FLAG = "jdbc:h2"; + private static final String H2_DB_TYPE = "h2"; @Override @@ -65,29 +58,39 @@ protected URLLocation fetchDatabaseNameIndexRange(String url) { public ConnectionInfo parse(String url) { int[] databaseNameRangeIndex = fetchDatabaseNameRangeIndexFromURLForH2FileMode(url); if (databaseNameRangeIndex != null) { - return new ConnectionInfo.Builder(LOCALHOST, -1).dbType(H2_DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)).build(); + return new ConnectionInfo.Builder(LOCALHOST, -1) + .dbType(H2_DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)) + .build(); } databaseNameRangeIndex = fetchDatabaseNameRangeIndexFromURLForH2MemMode(url); if (databaseNameRangeIndex != null) { - return new ConnectionInfo.Builder(LOCALHOST, -1).dbType(H2_DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)).build(); + return new ConnectionInfo.Builder(LOCALHOST, -1) + .dbType(H2_DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)) + .build(); } databaseNameRangeIndex = fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(url); if (databaseNameRangeIndex != null) { - return new ConnectionInfo.Builder(LOCALHOST, -1).dbType(H2_DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)).build(); + return new ConnectionInfo.Builder(LOCALHOST, -1) + .dbType(H2_DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)) + .build(); } String[] hostAndPort = fetchDatabaseHostsFromURL(url).split(":"); if (hostAndPort.length == 1) { - return new ConnectionInfo.Builder(hostAndPort[0], DEFAULT_PORT).dbType(H2_DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url)).build(); + return new ConnectionInfo.Builder(hostAndPort[0], DEFAULT_PORT) + .dbType(H2_DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url)) + .build(); } else { return new ConnectionInfo.Builder(hostAndPort[0], Integer.valueOf(hostAndPort[1])) - .dbType(H2_DB_TYPE).dbInstance(fetchDatabaseNameFromURL(url)).build(); + .dbType(H2_DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url)) + .build(); } } @@ -105,7 +108,7 @@ private int[] fetchDatabaseNameRangeIndexFromURLForH2FileMode(String url) { } if (fileLabelIndex != -1) { - return new int[]{fileLabelIndex + FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; + return new int[] {fileLabelIndex + FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } @@ -128,7 +131,7 @@ private int[] fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(String url } if (fileLabelIndex != -1) { - return new int[]{fileLabelIndex + IMPLICIT_FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; + return new int[] {fileLabelIndex + IMPLICIT_FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } @@ -148,10 +151,9 @@ private int[] fetchDatabaseNameRangeIndexFromURLForH2MemMode(String url) { } if (fileLabelIndex != -1) { - return new int[]{fileLabelIndex + MEMORY_MODE_FLAG.length() + 1, parameterLabelIndex}; + return new int[] {fileLabelIndex + MEMORY_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java index c734ee8dfd2d..d061df14ef54 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java @@ -25,5 +25,4 @@ public class MariadbURLParser extends MysqlURLParser { protected String dbType() { return "mariadb"; } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java index 1908c52e21b8..20bc7a2863ed 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java @@ -97,20 +97,24 @@ public ConnectionInfo parse(String url) { if (',' == sb.charAt(sb.length() - 1)) { sb.deleteCharAt(sb.length() - 1); } - return new ConnectionInfo.Builder(sb.toString()).dbType(dbType()) - .dbInstance(fetchDatabaseNameFromURL(url)).build(); + return new ConnectionInfo.Builder(sb.toString()) + .dbType(dbType()) + .dbInstance(fetchDatabaseNameFromURL(url)) + .build(); } else { String[] hostAndPort = hostSegment[0].split(":"); if (hostAndPort.length != 1) { return new ConnectionInfo.Builder(hostAndPort[0], Integer.valueOf(hostAndPort[1])) - .dbType(dbType()).dbInstance(fetchDatabaseNameFromURL(url, location.endIndex())) + .dbType(dbType()) + .dbInstance(fetchDatabaseNameFromURL(url, location.endIndex())) .build(); } else { - return new ConnectionInfo.Builder(hostAndPort[0], DEFAULT_PORT).dbType(dbType()) - .dbInstance(fetchDatabaseNameFromURL(url, location.endIndex())).build(); + return new ConnectionInfo.Builder(hostAndPort[0], DEFAULT_PORT) + .dbType(dbType()) + .dbInstance(fetchDatabaseNameFromURL(url, location.endIndex())) + .build(); } } } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java index 6d273d27d4f0..63f17b42fbb3 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java @@ -32,8 +32,9 @@ public class OracleURLParser implements ConnectionURLParser { public static final String PREFIX_THIN = "jdbc:oracle:thin:"; public static final String PREFIX_OCI = "jdbc:oracle:oci:"; public static final int DEFAULT_PORT = 1521; - private static Pattern EASY_CONNECT_PATTERN = Pattern.compile( - "(?.*)@(?ldap:)?(//)?(?[^:/]+)(?:[0-9]+)?(?[:/][^:/]+)?(?:[^:/]+)?(?/[^:/]+)?"); + private static Pattern EASY_CONNECT_PATTERN = + Pattern.compile( + "(?.*)@(?ldap:)?(//)?(?[^:/]+)(?:[0-9]+)?(?[:/][^:/]+)?(?:[^:/]+)?(?/[^:/]+)?"); @Override public ConnectionInfo parse(final String url) { @@ -120,7 +121,8 @@ private static String join(String delimiter, List list) { } /** - * Implementation according to https://www.oracle.com/technetwork/database/enterprise-edition/oraclenetservices-neteasyconnect-133058.pdf + * Implementation according to + * https://www.oracle.com/technetwork/database/enterprise-edition/oraclenetservices-neteasyconnect-133058.pdf * * @param url the url without the oracle jdbc prefix * @return the oracle connection info if the url could be parsed, or null otherwise. @@ -168,5 +170,4 @@ public OracleConnectionInfo setDbPeer(final String dbPeer) { return this; } } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java index 50b7323b6077..5b9b6fe04a8f 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java @@ -64,14 +64,18 @@ public ConnectionInfo parse(String url) { if (',' == sb.charAt(sb.length() - 1)) { sb.deleteCharAt(sb.length() - 1); } - return new ConnectionInfo.Builder(sb.toString()).dbType(DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url)).build(); + return new ConnectionInfo.Builder(sb.toString()) + .dbType(DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url)) + .build(); } else { URI uri = parseHost(hostSegment[0]); int port = uri.getPort() == -1 ? DEFAULT_PORT : uri.getPort(); return new ConnectionInfo.Builder(uri.getHost(), port) - .dbType(DB_TYPE).dbInstance(fetchDatabaseNameFromURL(url)).build(); + .dbType(DB_TYPE) + .dbInstance(fetchDatabaseNameFromURL(url)) + .build(); } } @@ -82,5 +86,4 @@ private URI parseHost(String host) { throw new IllegalArgumentException(e); } } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java index 184b5fa47fea..0e56ea7ce80c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java @@ -80,8 +80,10 @@ public ConnectionInfo parse(String url) { return null; } - return new ConnectionInfo.Builder(serverName, port).dbType(dbType()) - .dbInstance(dbInstance).build(); + return new ConnectionInfo.Builder(serverName, port) + .dbType(dbType()) + .dbInstance(dbInstance) + .build(); } private Map parseQueryParams(String query, String separator) { @@ -94,11 +96,14 @@ private Map parseQueryParams(String query, String separator) { try { int idx = pair.indexOf("="); String key = - idx > 0 ? URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name()) + idx > 0 + ? URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name()) : pair; if (!queryParams.containsKey(key)) { - String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder - .decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name()) : null; + String value = + idx > 0 && pair.length() > idx + 1 + ? URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name()) + : null; queryParams.put(key, value); } } catch (UnsupportedEncodingException e) { @@ -107,5 +112,4 @@ private Map parseQueryParams(String query, String separator) { } return queryParams; } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java index 9a348f67d3fe..3226e0e4ebdd 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java @@ -37,5 +37,4 @@ public int startIndex() { public int endIndex() { return endIndex; } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java index 164af400f859..5e8b8d7bd86c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java @@ -52,9 +52,7 @@ public class URLParser { parserRegister.put(AS400_JDBC_URL_PREFIX, new AS400URLParser()); } - /** - * parse the url to the ConnectionInfo - */ + /** parse the url to the ConnectionInfo */ public static ConnectionInfo parse(String url) { if (null == url) { return ConnectionInfo.UNKNOWN_CONNECTION_INFO; @@ -72,9 +70,7 @@ public static ConnectionInfo parse(String url) { return ConnectionInfo.UNKNOWN_CONNECTION_INFO; } - /** - * @deprecated use {@link #parse(String)} instead - */ + /** @deprecated use {@link #parse(String)} instead */ @Deprecated public static ConnectionInfo parser(String url) { return parse(url); @@ -89,14 +85,11 @@ private static ConnectionURLParser findURLParser(String lowerCaseUrl) { return null; } - /** - * register new ConnectionURLParser. Can override existing parser. - */ + /** register new ConnectionURLParser. Can override existing parser. */ public static void registerConnectionParser(String urlPrefix, ConnectionURLParser parser) { if (null == urlPrefix || parser == null) { throw new IllegalArgumentException("urlPrefix and parser can not be null"); } parserRegister.put(urlPrefix.toLowerCase(), parser); } - } From 464cbb7a8c20bb4176a665aa3669afa507b98c65 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 19 Jun 2021 05:34:57 +0800 Subject: [PATCH 05/69] Code style fixes. --- .../jdbc/TracingCallableStatement.java | 79 +++++++++++++++++++ .../jdbc/TracingConnection.java | 2 + .../instrumentation/jdbc/TracingDriver.java | 6 +- .../jdbc/TracingPreparedStatement.java | 23 ++++++ .../jdbc/parser/AbstractMatcherURLParser.java | 5 +- .../jdbc/parser/H2URLParser.java | 28 ++++--- .../jdbc/parser/MariadbURLParser.java | 1 + .../jdbc/parser/OracleURLParser.java | 7 +- .../jdbc/parser/PostgreSQLURLParser.java | 2 +- .../jdbc/parser/SqlServerURLParser.java | 5 +- .../jdbc/parser/URLParser.java | 13 ++- 11 files changed, 147 insertions(+), 24 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java index 8b5d9d4a75b7..8d0ad0734ce2 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java @@ -57,11 +57,13 @@ public TracingCallableStatement( this.statement = statement; } + @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { statement.registerOutParameter(parameterIndex, sqlType); } + @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { statement.registerOutParameter(parameterIndex, sqlType, scale); @@ -72,145 +74,173 @@ public boolean wasNull() throws SQLException { return statement.wasNull(); } + @SuppressWarnings("UngroupedOverloads") @Override public String getString(int parameterIndex) throws SQLException { return statement.getString(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public boolean getBoolean(int parameterIndex) throws SQLException { return statement.getBoolean(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public byte getByte(int parameterIndex) throws SQLException { return statement.getByte(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public short getShort(int parameterIndex) throws SQLException { return statement.getShort(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public int getInt(int parameterIndex) throws SQLException { return statement.getInt(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public long getLong(int parameterIndex) throws SQLException { return statement.getLong(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public float getFloat(int parameterIndex) throws SQLException { return statement.getFloat(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public double getDouble(int parameterIndex) throws SQLException { return statement.getDouble(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { return statement.getBigDecimal(parameterIndex, scale); } + @SuppressWarnings("UngroupedOverloads") @Override public byte[] getBytes(int parameterIndex) throws SQLException { return statement.getBytes(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public Date getDate(int parameterIndex) throws SQLException { return statement.getDate(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public Time getTime(int parameterIndex) throws SQLException { return statement.getTime(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public Timestamp getTimestamp(int parameterIndex) throws SQLException { return statement.getTimestamp(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public Object getObject(int parameterIndex) throws SQLException { return statement.getObject(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { return statement.getBigDecimal(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public Object getObject(int parameterIndex, Map> map) throws SQLException { return statement.getObject(parameterIndex, map); } + @SuppressWarnings("UngroupedOverloads") @Override public Ref getRef(int parameterIndex) throws SQLException { return statement.getRef(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public Blob getBlob(int parameterIndex) throws SQLException { return statement.getBlob(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public Clob getClob(int parameterIndex) throws SQLException { return statement.getClob(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public Array getArray(int parameterIndex) throws SQLException { return statement.getArray(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override public Date getDate(int parameterIndex, Calendar cal) throws SQLException { return statement.getDate(parameterIndex, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public Time getTime(int parameterIndex, Calendar cal) throws SQLException { return statement.getTime(parameterIndex, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { return statement.getTimestamp(parameterIndex, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { statement.registerOutParameter(parameterIndex, sqlType, typeName); } + @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { statement.registerOutParameter(parameterName, sqlType); } + @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { statement.registerOutParameter(parameterName, sqlType, scale); } + @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { statement.registerOutParameter(parameterName, sqlType, typeName); } + @SuppressWarnings("UngroupedOverloads") @Override public URL getURL(int parameterIndex) throws SQLException { return statement.getURL(parameterIndex); @@ -221,6 +251,7 @@ public void setURL(String parameterName, URL val) throws SQLException { statement.setURL(parameterName, val); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNull(String parameterName, int sqlType) throws SQLException { statement.setNull(parameterName, sqlType); @@ -276,6 +307,7 @@ public void setBytes(String parameterName, byte[] x) throws SQLException { statement.setBytes(parameterName, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setDate(String parameterName, Date x) throws SQLException { statement.setDate(parameterName, x); @@ -286,16 +318,19 @@ public void setTime(String parameterName, Time x) throws SQLException { statement.setTime(parameterName, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setTimestamp(String parameterName, Timestamp x) throws SQLException { statement.setTimestamp(parameterName, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException { statement.setAsciiStream(parameterName, x, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException { statement.setBinaryStream(parameterName, x, length); @@ -317,102 +352,122 @@ public void setObject(String parameterName, Object x) throws SQLException { statement.setObject(parameterName, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException { statement.setCharacterStream(parameterName, reader, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setDate(String parameterName, Date x, Calendar cal) throws SQLException { statement.setDate(parameterName, x, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public void setTime(String parameterName, Time x, Calendar cal) throws SQLException { statement.setTime(parameterName, x, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { statement.setTimestamp(parameterName, x, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { statement.setNull(parameterName, sqlType, typeName); } + @SuppressWarnings("UngroupedOverloads") @Override public String getString(String parameterName) throws SQLException { return statement.getString(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public boolean getBoolean(String parameterName) throws SQLException { return statement.getBoolean(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public byte getByte(String parameterName) throws SQLException { return statement.getByte(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public short getShort(String parameterName) throws SQLException { return statement.getShort(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public int getInt(String parameterName) throws SQLException { return statement.getInt(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public long getLong(String parameterName) throws SQLException { return statement.getLong(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public float getFloat(String parameterName) throws SQLException { return statement.getFloat(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public double getDouble(String parameterName) throws SQLException { return statement.getDouble(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public byte[] getBytes(String parameterName) throws SQLException { return statement.getBytes(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public Date getDate(String parameterName) throws SQLException { return statement.getDate(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public Time getTime(String parameterName) throws SQLException { return statement.getTime(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public Timestamp getTimestamp(String parameterName) throws SQLException { return statement.getTimestamp(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public Object getObject(String parameterName) throws SQLException { return statement.getObject(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { return statement.getBigDecimal(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public Object getObject(String parameterName, Map> map) throws SQLException { return statement.getObject(parameterName, map); @@ -433,26 +488,31 @@ public Clob getClob(String parameterName) throws SQLException { return statement.getClob(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public Array getArray(String parameterName) throws SQLException { return statement.getArray(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public Date getDate(String parameterName, Calendar cal) throws SQLException { return statement.getDate(parameterName, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public Time getTime(String parameterName, Calendar cal) throws SQLException { return statement.getTime(parameterName, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { return statement.getTimestamp(parameterName, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public URL getURL(String parameterName) throws SQLException { return statement.getURL(parameterName); @@ -478,28 +538,33 @@ public void setNString(String parameterName, String value) throws SQLException { statement.setNString(parameterName, value); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { statement.setNCharacterStream(parameterName, value, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNClob(String parameterName, NClob value) throws SQLException { statement.setNClob(parameterName, value); } + @SuppressWarnings("UngroupedOverloads") @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { statement.setClob(parameterName, reader, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { statement.setBlob(parameterName, inputStream, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { statement.setNClob(parameterName, reader, length); @@ -560,73 +625,87 @@ public Reader getCharacterStream(String parameterName) throws SQLException { return statement.getCharacterStream(parameterName); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBlob(String parameterName, Blob x) throws SQLException { statement.setBlob(parameterName, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setClob(String parameterName, Clob x) throws SQLException { statement.setClob(parameterName, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { statement.setAsciiStream(parameterName, x, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException { statement.setBinaryStream(parameterName, x, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException { statement.setCharacterStream(parameterName, reader, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(String parameterName, InputStream x) throws SQLException { statement.setAsciiStream(parameterName, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(String parameterName, InputStream x) throws SQLException { statement.setBinaryStream(parameterName, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(String parameterName, Reader reader) throws SQLException { statement.setCharacterStream(parameterName, reader); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { statement.setNCharacterStream(parameterName, value); } + @SuppressWarnings("UngroupedOverloads") @Override public void setClob(String parameterName, Reader reader) throws SQLException { statement.setClob(parameterName, reader); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { statement.setBlob(parameterName, inputStream); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNClob(String parameterName, Reader reader) throws SQLException { statement.setNClob(parameterName, reader); } + @SuppressWarnings("UngroupedOverloads") @Override public T getObject(int parameterIndex, Class type) throws SQLException { return statement.getObject(parameterIndex, type); } + @SuppressWarnings("UngroupedOverloads") @Override public T getObject(String parameterName, Class type) throws SQLException { return statement.getObject(parameterName, type); diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java index 152c5d66e72e..225825145090 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java @@ -194,6 +194,7 @@ public void commit() throws SQLException { "Commit", connection::commit, null, connectionInfo, withActiveSpanOnly, null, tracer); } + @SuppressWarnings("UngroupedOverloads") @Override public void rollback() throws SQLException { JdbcTracingUtils.execute( @@ -301,6 +302,7 @@ public Savepoint setSavepoint(String name) throws SQLException { return connection.setSavepoint(name); } + @SuppressWarnings("UngroupedOverloads") @Override public void rollback(Savepoint savepoint) throws SQLException { connection.rollback(savepoint); diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java index b13ee49a9bfb..689bf60668b5 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java @@ -61,7 +61,9 @@ public class TracingDriver implements Driver { } } - /** @return The singleton instance of the {@code TracingDriver}. */ + /** + * Returns the singleton instance of the {@code TracingDriver}. + */ public static Driver load() { return INSTANCE; } @@ -127,6 +129,7 @@ public static void setInterceptorMode(final boolean interceptorMode) { * * @param withActiveSpanOnly The {@code withActiveSpanOnly} value. */ + @SuppressWarnings("UngroupedOverloads") public static void setInterceptorProperty(final boolean withActiveSpanOnly) { TracingDriver.withActiveSpanOnly = withActiveSpanOnly; } @@ -138,6 +141,7 @@ public static void setInterceptorProperty(final boolean withActiveSpanOnly) { * * @param ignoreStatements The {@code ignoreStatements} value. */ + @SuppressWarnings("UngroupedOverloads") public static void setInterceptorProperty(final Set ignoreStatements) { TracingDriver.ignoreStatements = ignoreStatements; } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java index 14fcbb0601af..143786044528 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java @@ -96,6 +96,7 @@ public boolean execute() throws SQLException { tracer); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNull(int parameterIndex, int sqlType) throws SQLException { preparedStatement.setNull(parameterIndex, sqlType); @@ -151,21 +152,25 @@ public void setBytes(int parameterIndex, byte[] x) throws SQLException { preparedStatement.setBytes(parameterIndex, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setDate(int parameterIndex, Date x) throws SQLException { preparedStatement.setDate(parameterIndex, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setTime(int parameterIndex, Time x) throws SQLException { preparedStatement.setTime(parameterIndex, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { preparedStatement.setTimestamp(parameterIndex, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { preparedStatement.setAsciiStream(parameterIndex, x, length); @@ -177,6 +182,7 @@ public void setUnicodeStream(int parameterIndex, InputStream x, int length) thro preparedStatement.setUnicodeStream(parameterIndex, x, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { preparedStatement.setBinaryStream(parameterIndex, x, length); @@ -187,11 +193,13 @@ public void clearParameters() throws SQLException { preparedStatement.clearParameters(); } + @SuppressWarnings("UngroupedOverloads") @Override public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { preparedStatement.setObject(parameterIndex, x, targetSqlType); } + @SuppressWarnings("UngroupedOverloads") @Override public void setObject(int parameterIndex, Object x) throws SQLException { preparedStatement.setObject(parameterIndex, x); @@ -202,6 +210,7 @@ public void addBatch() throws SQLException { preparedStatement.addBatch(); } + @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { @@ -218,6 +227,7 @@ public void setBlob(int parameterIndex, Blob x) throws SQLException { preparedStatement.setBlob(parameterIndex, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setClob(int parameterIndex, Clob x) throws SQLException { preparedStatement.setClob(parameterIndex, x); @@ -233,6 +243,7 @@ public ResultSetMetaData getMetaData() throws SQLException { return preparedStatement.getMetaData(); } + @SuppressWarnings("UngroupedOverloads") @Override public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { preparedStatement.setDate(parameterIndex, x, cal); @@ -243,11 +254,13 @@ public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLExceptio preparedStatement.setTime(parameterIndex, x, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { preparedStatement.setTimestamp(parameterIndex, x, cal); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { preparedStatement.setNull(parameterIndex, sqlType, typeName); @@ -273,6 +286,7 @@ public void setNString(int parameterIndex, String value) throws SQLException { preparedStatement.setNString(parameterIndex, value); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { @@ -284,6 +298,7 @@ public void setNClob(int parameterIndex, NClob value) throws SQLException { preparedStatement.setNClob(parameterIndex, value); } + @SuppressWarnings("UngroupedOverloads") @Override public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { preparedStatement.setClob(parameterIndex, reader, length); @@ -311,27 +326,32 @@ public void setObject(int parameterIndex, Object x, int targetSqlType, int scale preparedStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength); } + @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { preparedStatement.setAsciiStream(parameterIndex, x, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { preparedStatement.setBinaryStream(parameterIndex, x, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { preparedStatement.setCharacterStream(parameterIndex, reader, length); } + @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { preparedStatement.setAsciiStream(parameterIndex, x); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { preparedStatement.setBinaryStream(parameterIndex, x); @@ -342,16 +362,19 @@ public void setCharacterStream(int parameterIndex, Reader reader) throws SQLExce preparedStatement.setCharacterStream(parameterIndex, reader); } + @SuppressWarnings("UngroupedOverloads") @Override public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { preparedStatement.setNCharacterStream(parameterIndex, value); } + @SuppressWarnings("UngroupedOverloads") @Override public void setClob(int parameterIndex, Reader reader) throws SQLException { preparedStatement.setClob(parameterIndex, reader); } + @SuppressWarnings("UngroupedOverloads") @Override public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { preparedStatement.setBlob(parameterIndex, inputStream); diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java index be72b129a8a5..64e21da5f664 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java @@ -36,7 +36,7 @@ public abstract class AbstractMatcherURLParser implements ConnectionURLParser { private final String dbType; - public AbstractMatcherURLParser(Pattern pattern, String dbType) { + protected AbstractMatcherURLParser(Pattern pattern, String dbType) { this.pattern = pattern; this.dbType = dbType; } @@ -45,8 +45,7 @@ public AbstractMatcherURLParser(Pattern pattern, String dbType) { * Useful to modify ConnectionInfo before build * * @param matcher The matcher to apply. Note that the matcher must have a group named host, and - * optionally, a group named port and another named instance - * @return + * optionally, a group named port and another named instance */ protected ConnectionInfo.Builder initBuilder(Matcher matcher) { String host = matcher.group("host"); diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java index e6f1c8cacad4..1f5f67c14772 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java @@ -26,13 +26,21 @@ public class H2URLParser extends AbstractURLParser { private static final String LOCALHOST = "localhost"; private static final int DEFAULT_PORT = 8084; - /** Flag that H2 running with memory mode. */ + /** + * Flag that H2 running with memory mode. + */ private static final String MEMORY_MODE_FLAG = "mem"; - /** Flag that H2 running with tcp mode. */ + /** + * Flag that H2 running with tcp mode. + */ private static final String TCP_MODE_FLAG = "h2:tcp"; - /** Flag that H2 running with file mode. */ + /** + * Flag that H2 running with file mode. + */ private static final String FILE_MODE_FLAG = "file"; - /** Flag that H2 running with implicit file mode. */ + /** + * Flag that H2 running with implicit file mode. + */ private static final String IMPLICIT_FILE_MODE_FLAG = "jdbc:h2"; private static final String H2_DB_TYPE = "h2"; @@ -100,7 +108,7 @@ public ConnectionInfo parse(String url) { * * @return range index that the database name. */ - private int[] fetchDatabaseNameRangeIndexFromURLForH2FileMode(String url) { + private static int[] fetchDatabaseNameRangeIndexFromURLForH2FileMode(String url) { int fileLabelIndex = url.indexOf(FILE_MODE_FLAG); int parameterLabelIndex = url.indexOf(";", fileLabelIndex); if (parameterLabelIndex == -1) { @@ -108,7 +116,7 @@ private int[] fetchDatabaseNameRangeIndexFromURLForH2FileMode(String url) { } if (fileLabelIndex != -1) { - return new int[] {fileLabelIndex + FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; + return new int[]{fileLabelIndex + FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } @@ -120,7 +128,7 @@ private int[] fetchDatabaseNameRangeIndexFromURLForH2FileMode(String url) { * * @return range index that the database name. */ - private int[] fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(String url) { + private static int[] fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(String url) { if (url.contains(TCP_MODE_FLAG)) { return null; } @@ -131,7 +139,7 @@ private int[] fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(String url } if (fileLabelIndex != -1) { - return new int[] {fileLabelIndex + IMPLICIT_FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; + return new int[]{fileLabelIndex + IMPLICIT_FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } @@ -143,7 +151,7 @@ private int[] fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(String url * * @return range index that the database name. */ - private int[] fetchDatabaseNameRangeIndexFromURLForH2MemMode(String url) { + private static int[] fetchDatabaseNameRangeIndexFromURLForH2MemMode(String url) { int fileLabelIndex = url.indexOf(MEMORY_MODE_FLAG); int parameterLabelIndex = url.indexOf(";", fileLabelIndex); if (parameterLabelIndex == -1) { @@ -151,7 +159,7 @@ private int[] fetchDatabaseNameRangeIndexFromURLForH2MemMode(String url) { } if (fileLabelIndex != -1) { - return new int[] {fileLabelIndex + MEMORY_MODE_FLAG.length() + 1, parameterLabelIndex}; + return new int[]{fileLabelIndex + MEMORY_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java index d061df14ef54..2fffa653e0ec 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java @@ -22,6 +22,7 @@ public class MariadbURLParser extends MysqlURLParser { + @Override protected String dbType() { return "mariadb"; } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java index 63f17b42fbb3..bbf952edd99e 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java @@ -32,7 +32,7 @@ public class OracleURLParser implements ConnectionURLParser { public static final String PREFIX_THIN = "jdbc:oracle:thin:"; public static final String PREFIX_OCI = "jdbc:oracle:oci:"; public static final int DEFAULT_PORT = 1521; - private static Pattern EASY_CONNECT_PATTERN = + private static final Pattern EASY_CONNECT_PATTERN = Pattern.compile( "(?.*)@(?ldap:)?(//)?(?[^:/]+)(?:[0-9]+)?(?[:/][^:/]+)?(?:[^:/]+)?(?/[^:/]+)?"); @@ -62,7 +62,7 @@ public ConnectionInfo parse(final String url) { return null; } - private OracleConnectionInfo parseTnsName(final String url) { + private static OracleConnectionInfo parseTnsName(final String url) { final String hosts = parseDatabaseHostsFromTnsUrl(url); if (hosts != null) { final int idxServiceName = url.indexOf("SERVICE_NAME"); @@ -121,8 +121,7 @@ private static String join(String delimiter, List list) { } /** - * Implementation according to - * https://www.oracle.com/technetwork/database/enterprise-edition/oraclenetservices-neteasyconnect-133058.pdf + * Implementation according to https://www.oracle.com/technetwork/database/enterprise-edition/oraclenetservices-neteasyconnect-133058.pdf * * @param url the url without the oracle jdbc prefix * @return the oracle connection info if the url could be parsed, or null otherwise. diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java index 5b9b6fe04a8f..98f542d54336 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java @@ -79,7 +79,7 @@ public ConnectionInfo parse(String url) { } } - private URI parseHost(String host) { + private static URI parseHost(String host) { try { return new URI("proto://" + host); } catch (URISyntaxException e) { diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java index 0e56ea7ce80c..9de1d54f92cc 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java @@ -55,7 +55,8 @@ public ConnectionInfo parse(String url) { String portNumber = props.get("portNumber"); try { port = Integer.parseInt(portNumber); - } catch (NumberFormatException e) { + } catch (NumberFormatException ignored) { + // nothing to do, expected } } } @@ -86,7 +87,7 @@ public ConnectionInfo parse(String url) { .build(); } - private Map parseQueryParams(String query, String separator) { + private static Map parseQueryParams(String query, String separator) { if (query == null || query.isEmpty()) { return Collections.emptyMap(); } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java index 5e8b8d7bd86c..997ea5739d72 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java @@ -52,7 +52,10 @@ public class URLParser { parserRegister.put(AS400_JDBC_URL_PREFIX, new AS400URLParser()); } - /** parse the url to the ConnectionInfo */ + /** + * parse the url to the ConnectionInfo + */ + @SuppressWarnings("CatchingUnchecked") public static ConnectionInfo parse(String url) { if (null == url) { return ConnectionInfo.UNKNOWN_CONNECTION_INFO; @@ -70,7 +73,9 @@ public static ConnectionInfo parse(String url) { return ConnectionInfo.UNKNOWN_CONNECTION_INFO; } - /** @deprecated use {@link #parse(String)} instead */ + /** + * @deprecated use {@link #parse(String)} instead + */ @Deprecated public static ConnectionInfo parser(String url) { return parse(url); @@ -85,7 +90,9 @@ private static ConnectionURLParser findURLParser(String lowerCaseUrl) { return null; } - /** register new ConnectionURLParser. Can override existing parser. */ + /** + * register new ConnectionURLParser. Can override existing parser. + */ public static void registerConnectionParser(String urlPrefix, ConnectionURLParser parser) { if (null == urlPrefix || parser == null) { throw new IllegalArgumentException("urlPrefix and parser can not be null"); From e4fe822fe3d6548d00026d988fcf4bd2803550af Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 20 Jun 2021 00:54:37 +0800 Subject: [PATCH 06/69] Moved some JDBC utilities classes to the library module. --- instrumentation/jdbc/javaagent/jdbc-javaagent.gradle | 1 + instrumentation/jdbc/library/jdbc-library.gradle | 5 +++++ .../opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java | 0 .../javaagent/instrumentation/jdbc/DbRequest.java | 0 .../instrumentation/jdbc/JdbcConnectionUrlParser.java | 0 .../javaagent/instrumentation/jdbc/JdbcMaps.java | 0 .../javaagent/instrumentation/jdbc/JdbcUtils.java | 0 7 files changed, 6 insertions(+) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java (100%) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbRequest.java (100%) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcConnectionUrlParser.java (100%) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcMaps.java (100%) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcUtils.java (100%) diff --git a/instrumentation/jdbc/javaagent/jdbc-javaagent.gradle b/instrumentation/jdbc/javaagent/jdbc-javaagent.gradle index c0cb82ecb3e0..00d1a017c18e 100644 --- a/instrumentation/jdbc/javaagent/jdbc-javaagent.gradle +++ b/instrumentation/jdbc/javaagent/jdbc-javaagent.gradle @@ -7,6 +7,7 @@ muzzle { } dependencies { + implementation project(':instrumentation:jdbc:library') compileOnly "com.google.auto.value:auto-value-annotations" annotationProcessor "com.google.auto.value:auto-value" diff --git a/instrumentation/jdbc/library/jdbc-library.gradle b/instrumentation/jdbc/library/jdbc-library.gradle index 9233e87a1921..efb7fa8c5d83 100644 --- a/instrumentation/jdbc/library/jdbc-library.gradle +++ b/instrumentation/jdbc/library/jdbc-library.gradle @@ -1 +1,6 @@ apply plugin: "otel.library-instrumentation" + +dependencies { + compileOnly "com.google.auto.value:auto-value-annotations" + annotationProcessor "com.google.auto.value:auto-value" +} diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbRequest.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbRequest.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbRequest.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbRequest.java diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcConnectionUrlParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcConnectionUrlParser.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcConnectionUrlParser.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcConnectionUrlParser.java diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcMaps.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcMaps.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcMaps.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcMaps.java diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcUtils.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcUtils.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcUtils.java From 91e6b9a3b041871e37aa7f28725bc0df1feac8c2 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 20 Jun 2021 00:56:03 +0800 Subject: [PATCH 07/69] javax.annotation.Nullable -> org.checkerframework.checker.nullness.qual.Nullable --- .../io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java index a0aa44019235..43447243de3f 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java @@ -6,7 +6,7 @@ package io.opentelemetry.javaagent.instrumentation.jdbc; import com.google.auto.value.AutoValue; -import javax.annotation.Nullable; +import org.checkerframework.checker.nullness.qual.Nullable; @AutoValue public abstract class DbInfo { From 7c903f3919a5fd8b910170763d3c329750da1ea1 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 20 Jun 2021 03:54:11 +0800 Subject: [PATCH 08/69] Build fix. --- instrumentation/jdbc/library/jdbc-library.gradle | 2 ++ 1 file changed, 2 insertions(+) diff --git a/instrumentation/jdbc/library/jdbc-library.gradle b/instrumentation/jdbc/library/jdbc-library.gradle index efb7fa8c5d83..ff10898c9b51 100644 --- a/instrumentation/jdbc/library/jdbc-library.gradle +++ b/instrumentation/jdbc/library/jdbc-library.gradle @@ -3,4 +3,6 @@ apply plugin: "otel.library-instrumentation" dependencies { compileOnly "com.google.auto.value:auto-value-annotations" annotationProcessor "com.google.auto.value:auto-value" + + implementation "org.slf4j:slf4j-api" } From 573d3ce0c971af87c30ddaed6fdc9a5a6783db4c Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 20 Jun 2021 03:54:38 +0800 Subject: [PATCH 09/69] Spotless fixes. --- .../instrumentation/jdbc/TracingDriver.java | 4 +--- .../jdbc/parser/AbstractMatcherURLParser.java | 2 +- .../jdbc/parser/H2URLParser.java | 22 ++++++------------- .../jdbc/parser/OracleURLParser.java | 3 ++- .../jdbc/parser/URLParser.java | 12 +++------- 5 files changed, 14 insertions(+), 29 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java index 689bf60668b5..063a01c17bc7 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java @@ -61,9 +61,7 @@ public class TracingDriver implements Driver { } } - /** - * Returns the singleton instance of the {@code TracingDriver}. - */ + /** Returns the singleton instance of the {@code TracingDriver}. */ public static Driver load() { return INSTANCE; } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java index 64e21da5f664..e90d40863b61 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java @@ -45,7 +45,7 @@ protected AbstractMatcherURLParser(Pattern pattern, String dbType) { * Useful to modify ConnectionInfo before build * * @param matcher The matcher to apply. Note that the matcher must have a group named host, and - * optionally, a group named port and another named instance + * optionally, a group named port and another named instance */ protected ConnectionInfo.Builder initBuilder(Matcher matcher) { String host = matcher.group("host"); diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java index 1f5f67c14772..97d6232c3eb3 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java @@ -26,21 +26,13 @@ public class H2URLParser extends AbstractURLParser { private static final String LOCALHOST = "localhost"; private static final int DEFAULT_PORT = 8084; - /** - * Flag that H2 running with memory mode. - */ + /** Flag that H2 running with memory mode. */ private static final String MEMORY_MODE_FLAG = "mem"; - /** - * Flag that H2 running with tcp mode. - */ + /** Flag that H2 running with tcp mode. */ private static final String TCP_MODE_FLAG = "h2:tcp"; - /** - * Flag that H2 running with file mode. - */ + /** Flag that H2 running with file mode. */ private static final String FILE_MODE_FLAG = "file"; - /** - * Flag that H2 running with implicit file mode. - */ + /** Flag that H2 running with implicit file mode. */ private static final String IMPLICIT_FILE_MODE_FLAG = "jdbc:h2"; private static final String H2_DB_TYPE = "h2"; @@ -116,7 +108,7 @@ private static int[] fetchDatabaseNameRangeIndexFromURLForH2FileMode(String url) } if (fileLabelIndex != -1) { - return new int[]{fileLabelIndex + FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; + return new int[] {fileLabelIndex + FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } @@ -139,7 +131,7 @@ private static int[] fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(Str } if (fileLabelIndex != -1) { - return new int[]{fileLabelIndex + IMPLICIT_FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; + return new int[] {fileLabelIndex + IMPLICIT_FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } @@ -159,7 +151,7 @@ private static int[] fetchDatabaseNameRangeIndexFromURLForH2MemMode(String url) } if (fileLabelIndex != -1) { - return new int[]{fileLabelIndex + MEMORY_MODE_FLAG.length() + 1, parameterLabelIndex}; + return new int[] {fileLabelIndex + MEMORY_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java index bbf952edd99e..3cd2f9dcafed 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java @@ -121,7 +121,8 @@ private static String join(String delimiter, List list) { } /** - * Implementation according to https://www.oracle.com/technetwork/database/enterprise-edition/oraclenetservices-neteasyconnect-133058.pdf + * Implementation according to + * https://www.oracle.com/technetwork/database/enterprise-edition/oraclenetservices-neteasyconnect-133058.pdf * * @param url the url without the oracle jdbc prefix * @return the oracle connection info if the url could be parsed, or null otherwise. diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java index 997ea5739d72..41c030402025 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java @@ -52,9 +52,7 @@ public class URLParser { parserRegister.put(AS400_JDBC_URL_PREFIX, new AS400URLParser()); } - /** - * parse the url to the ConnectionInfo - */ + /** parse the url to the ConnectionInfo */ @SuppressWarnings("CatchingUnchecked") public static ConnectionInfo parse(String url) { if (null == url) { @@ -73,9 +71,7 @@ public static ConnectionInfo parse(String url) { return ConnectionInfo.UNKNOWN_CONNECTION_INFO; } - /** - * @deprecated use {@link #parse(String)} instead - */ + /** @deprecated use {@link #parse(String)} instead */ @Deprecated public static ConnectionInfo parser(String url) { return parse(url); @@ -90,9 +86,7 @@ private static ConnectionURLParser findURLParser(String lowerCaseUrl) { return null; } - /** - * register new ConnectionURLParser. Can override existing parser. - */ + /** register new ConnectionURLParser. Can override existing parser. */ public static void registerConnectionParser(String urlPrefix, ConnectionURLParser parser) { if (null == urlPrefix || parser == null) { throw new IllegalArgumentException("urlPrefix and parser can not be null"); From c357a573c36ec22492107e6e2b536eaadbd50bc3 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 20 Jun 2021 04:07:03 +0800 Subject: [PATCH 10/69] Cache prepared statements. --- .../instrumentation/jdbc/TracingConnection.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java index 225825145090..c5e4490ed5d0 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java @@ -21,6 +21,7 @@ package io.opentelemetry.instrumentation.jdbc; import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcMaps; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; @@ -95,6 +96,7 @@ public Statement createStatement( @Override public PreparedStatement prepareStatement(String sql) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql); + JdbcMaps.preparedStatements.put(statement, sql); return WrapperProxy.wrap( statement, new TracingPreparedStatement( @@ -106,6 +108,7 @@ public PreparedStatement prepareStatement(String sql, int resultSetType, int res throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, resultSetType, resultSetConcurrency); + JdbcMaps.preparedStatements.put(statement, sql); return WrapperProxy.wrap( statement, new TracingPreparedStatement( @@ -118,6 +121,7 @@ public PreparedStatement prepareStatement( throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + JdbcMaps.preparedStatements.put(statement, sql); return WrapperProxy.wrap( statement, new TracingPreparedStatement( @@ -127,6 +131,7 @@ public PreparedStatement prepareStatement( @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, autoGeneratedKeys); + JdbcMaps.preparedStatements.put(statement, sql); return WrapperProxy.wrap( statement, new TracingPreparedStatement( @@ -136,6 +141,7 @@ public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) thr @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, columnIndexes); + JdbcMaps.preparedStatements.put(statement, sql); return WrapperProxy.wrap( statement, new TracingPreparedStatement( @@ -145,6 +151,7 @@ public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throw @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, columnNames); + JdbcMaps.preparedStatements.put(statement, sql); return WrapperProxy.wrap( statement, new TracingPreparedStatement( From 1229c5f668cad2ae27ae02889f19414617863316 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 20 Jun 2021 04:12:21 +0800 Subject: [PATCH 11/69] Cache connection info. --- .../opentelemetry/instrumentation/jdbc/TracingDriver.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java index 063a01c17bc7..cb0c3a69dabe 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java @@ -23,6 +23,9 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.instrumentation.jdbc.parser.URLParser; +import io.opentelemetry.javaagent.instrumentation.jdbc.DbInfo; +import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcConnectionUrlParser; +import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcMaps; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; @@ -183,6 +186,9 @@ public Connection connect(String url, Properties info) throws SQLException { null, currentTracer); + DbInfo dbInfo = JdbcConnectionUrlParser.parse(url, info); + JdbcMaps.connectionInfo.put(connection, dbInfo); + return WrapperProxy.wrap( connection, new TracingConnection( From d163b428acd7122268430ab3a6f7cbc8ae284f91 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 20 Jun 2021 05:08:53 +0800 Subject: [PATCH 12/69] Tracing for JDBC statement and prepared statement. --- docs/standalone-library-instrumentation.md | 1 + .../jdbc/library/jdbc-library.gradle | 19 ++++ .../jdbc/JdbcTracingUtils.java | 68 +++++++++++++ .../jdbc/TracingPreparedStatement.java | 31 +----- .../jdbc/TracingStatement.java | 97 ++++--------------- .../jdbc/JdbcAttributesExtractor.java | 0 .../jdbc/JdbcNetAttributesExtractor.java | 0 .../instrumentation/jdbc/JdbcSingletons.java | 0 8 files changed, 110 insertions(+), 106 deletions(-) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcAttributesExtractor.java (100%) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcNetAttributesExtractor.java (100%) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java (100%) diff --git a/docs/standalone-library-instrumentation.md b/docs/standalone-library-instrumentation.md index d170510202da..d24fe8bc23b7 100644 --- a/docs/standalone-library-instrumentation.md +++ b/docs/standalone-library-instrumentation.md @@ -10,6 +10,7 @@ that can be used if you prefer that over using the Java agent: * [AWS SDK 2.2+](../instrumentation/aws-sdk/aws-sdk-2.2/library) * [gRPC](../instrumentation/grpc-1.6/library) * [Guava](../instrumentation/guava-10.0/library) +* [JDBC](../instrumentation/jdbc/library) * [Lettuce](../instrumentation/lettuce/lettuce-5.1/library) * [Log4j](../instrumentation/log4j/log4j-2.13.2/library) * [Logback](../instrumentation/logback-1.0/library) diff --git a/instrumentation/jdbc/library/jdbc-library.gradle b/instrumentation/jdbc/library/jdbc-library.gradle index ff10898c9b51..2f58bf104266 100644 --- a/instrumentation/jdbc/library/jdbc-library.gradle +++ b/instrumentation/jdbc/library/jdbc-library.gradle @@ -1,6 +1,25 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + apply plugin: "otel.library-instrumentation" dependencies { + compileOnly project(':instrumentation-api') + compileOnly project(':javaagent-api') + compileOnly "com.google.auto.value:auto-value-annotations" annotationProcessor "com.google.auto.value:auto-value" diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java index ce9db5418ec8..aed9ce0c6a0d 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java @@ -20,6 +20,8 @@ package io.opentelemetry.instrumentation.jdbc; +import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; + import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanBuilder; @@ -28,7 +30,11 @@ import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; +import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; +import io.opentelemetry.javaagent.instrumentation.jdbc.DbRequest; import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; +import java.sql.PreparedStatement; +import java.sql.Statement; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -124,6 +130,68 @@ static T call( } } + static T executePreparedStatement( + PreparedStatement preparedStatement, CheckedCallable callable) throws E { + // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info + // this happens before the DB CLIENT span is started (and put in the current context), so this + // instrumentation runs again and the shouldStartSpan() check always returns true - and so on + // until we get a StackOverflowError + // using CallDepth prevents this, because this check happens before Connection#getMetadata() + // is called - the first recursive Statement call is just skipped and we do not create a span + // for it + if (CallDepthThreadLocalMap.getCallDepth(Statement.class).getAndIncrement() > 0) { + return callable.call(); + } + + Context parentContext = Context.current(); + DbRequest request = DbRequest.create(preparedStatement); + + if (request == null || !instrumenter().shouldStart(parentContext, request)) { + return callable.call(); + } + + Context context = instrumenter().start(parentContext, request); + try (Scope ignored = context.makeCurrent()) { + return callable.call(); + } catch (Throwable throwable) { + instrumenter().end(context, request, null, throwable); + throw throwable; + } finally { + CallDepthThreadLocalMap.reset(Statement.class); + } + } + + static T executeStatement( + Statement statement, String sql, CheckedCallable callable) throws E { + // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info + // this happens before the DB CLIENT span is started (and put in the current context), so this + // instrumentation runs again and the shouldStartSpan() check always returns true - and so on + // until we get a StackOverflowError + // using CallDepth prevents this, because this check happens before Connection#getMetadata() + // is called - the first recursive Statement call is just skipped and we do not create a span + // for it + if (CallDepthThreadLocalMap.getCallDepth(Statement.class).getAndIncrement() > 0) { + return callable.call(); + } + + Context parentContext = Context.current(); + DbRequest request = DbRequest.create(statement, sql); + + if (request == null || !instrumenter().shouldStart(parentContext, request)) { + return callable.call(); + } + + Context context = instrumenter().start(parentContext, request); + try (Scope ignored = context.makeCurrent()) { + return callable.call(); + } catch (Throwable throwable) { + instrumenter().end(context, request, null, throwable); + throw throwable; + } finally { + CallDepthThreadLocalMap.reset(Statement.class); + } + } + private static boolean isNotEmpty(CharSequence s) { return s != null && !"".contentEquals(s); } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java index 143786044528..c85b345838b0 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java @@ -46,7 +46,6 @@ public class TracingPreparedStatement extends TracingStatement implements PreparedStatement { private final PreparedStatement preparedStatement; - private final String query; public TracingPreparedStatement( PreparedStatement preparedStatement, @@ -57,43 +56,23 @@ public TracingPreparedStatement( Tracer tracer) { super(preparedStatement, query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); this.preparedStatement = preparedStatement; - this.query = query; } @Override public ResultSet executeQuery() throws SQLException { - return JdbcTracingUtils.call( - "Query", - preparedStatement::executeQuery, - query, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executePreparedStatement( + preparedStatement, preparedStatement::executeQuery); } @Override public int executeUpdate() throws SQLException { - return JdbcTracingUtils.call( - "Update", - preparedStatement::executeUpdate, - query, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executePreparedStatement( + preparedStatement, preparedStatement::executeUpdate); } @Override public boolean execute() throws SQLException { - return JdbcTracingUtils.call( - "Execute", - preparedStatement::execute, - query, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executePreparedStatement(preparedStatement, preparedStatement::execute); } @SuppressWarnings("UngroupedOverloads") diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java index 3accd7a05e79..caf809d0ce2c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java @@ -65,122 +65,59 @@ public class TracingStatement implements Statement { @Override public ResultSet executeQuery(String sql) throws SQLException { - return JdbcTracingUtils.call( - "Query", - () -> statement.executeQuery(sql), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement(statement, sql, () -> statement.executeQuery(sql)); } @Override public int executeUpdate(String sql) throws SQLException { - return JdbcTracingUtils.call( - "Update", - () -> statement.executeUpdate(sql), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement(statement, sql, () -> statement.executeUpdate(sql)); } @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - return JdbcTracingUtils.call( - "Update", - () -> statement.executeUpdate(sql, autoGeneratedKeys), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement( + statement, sql, () -> statement.executeUpdate(sql, autoGeneratedKeys)); } @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - return JdbcTracingUtils.call( - "Update", - () -> statement.executeUpdate(sql, columnIndexes), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement( + statement, sql, () -> statement.executeUpdate(sql, columnIndexes)); } @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { - return JdbcTracingUtils.call( - "Update", - () -> statement.executeUpdate(sql, columnNames), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement( + statement, sql, () -> statement.executeUpdate(sql, columnNames)); } @Override public boolean execute(String sql) throws SQLException { - return JdbcTracingUtils.call( - "Execute", - () -> statement.execute(sql), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement(statement, sql, () -> statement.execute(sql)); } @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return JdbcTracingUtils.call( - "Execute", - () -> statement.execute(sql, autoGeneratedKeys), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement( + statement, sql, () -> statement.execute(sql, autoGeneratedKeys)); } @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { - return JdbcTracingUtils.call( - "Execute", - () -> statement.execute(sql, columnIndexes), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement( + statement, sql, () -> statement.execute(sql, columnIndexes)); } @Override public boolean execute(String sql, String[] columnNames) throws SQLException { - return JdbcTracingUtils.call( - "Execute", - () -> statement.execute(sql, columnNames), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement( + statement, sql, () -> statement.execute(sql, columnNames)); } @Override public int[] executeBatch() throws SQLException { - return JdbcTracingUtils.call( - "Update", - statement::executeBatch, - buildSqlForBatch(), - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer); + return JdbcTracingUtils.executeStatement( + statement, buildSqlForBatch(), statement::executeBatch); } @Override diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcAttributesExtractor.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcAttributesExtractor.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcAttributesExtractor.java diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcNetAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcNetAttributesExtractor.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcNetAttributesExtractor.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcNetAttributesExtractor.java diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java From 8afb87dba7f6fa07c7e60f896ebf878f2fdc1f67 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 20 Jun 2021 05:28:14 +0800 Subject: [PATCH 13/69] Added some API dependencies. --- instrumentation/jdbc/library/jdbc-library.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/instrumentation/jdbc/library/jdbc-library.gradle b/instrumentation/jdbc/library/jdbc-library.gradle index 2f58bf104266..863ed534ea6d 100644 --- a/instrumentation/jdbc/library/jdbc-library.gradle +++ b/instrumentation/jdbc/library/jdbc-library.gradle @@ -17,8 +17,8 @@ apply plugin: "otel.library-instrumentation" dependencies { - compileOnly project(':instrumentation-api') - compileOnly project(':javaagent-api') + implementation project(':instrumentation-api') + implementation project(':javaagent-api') compileOnly "com.google.auto.value:auto-value-annotations" annotationProcessor "com.google.auto.value:auto-value" From 034b5378a9b7b628997f32d47dd64aa053f3bd55 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 20 Jun 2021 05:51:04 +0800 Subject: [PATCH 14/69] Fixed ending the span. --- .../jdbc/JdbcTracingUtils.java | 70 +++++++++++-------- 1 file changed, 41 insertions(+), 29 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java index aed9ce0c6a0d..f5a0b6a321a8 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java @@ -88,7 +88,7 @@ static void execute( buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); long startTime = (JdbcTracing.getSlowQueryThresholdMs() > 0 - || JdbcTracing.getExcludeFastQueryThresholdMs() > 0) + || JdbcTracing.getExcludeFastQueryThresholdMs() > 0) ? System.nanoTime() : 0; try (Scope ignored = span.makeCurrent()) { @@ -143,19 +143,24 @@ static T executePreparedStatement( return callable.call(); } - Context parentContext = Context.current(); - DbRequest request = DbRequest.create(preparedStatement); - - if (request == null || !instrumenter().shouldStart(parentContext, request)) { - return callable.call(); - } - - Context context = instrumenter().start(parentContext, request); - try (Scope ignored = context.makeCurrent()) { - return callable.call(); - } catch (Throwable throwable) { - instrumenter().end(context, request, null, throwable); - throw throwable; + try { + Context parentContext = Context.current(); + DbRequest request = DbRequest.create(preparedStatement); + + if (request == null || !instrumenter().shouldStart(parentContext, request)) { + return callable.call(); + } + + Context context = instrumenter().start(parentContext, request); + T result; + try (Scope ignored = context.makeCurrent()) { + result = callable.call(); + } catch (Throwable t) { + instrumenter().end(context, request, null, t); + throw t; + } + instrumenter().end(context, request, null, null); + return result; } finally { CallDepthThreadLocalMap.reset(Statement.class); } @@ -174,19 +179,24 @@ static T executeStatement( return callable.call(); } - Context parentContext = Context.current(); - DbRequest request = DbRequest.create(statement, sql); - - if (request == null || !instrumenter().shouldStart(parentContext, request)) { - return callable.call(); - } - - Context context = instrumenter().start(parentContext, request); - try (Scope ignored = context.makeCurrent()) { - return callable.call(); - } catch (Throwable throwable) { - instrumenter().end(context, request, null, throwable); - throw throwable; + try { + Context parentContext = Context.current(); + DbRequest request = DbRequest.create(statement, sql); + + if (request == null || !instrumenter().shouldStart(parentContext, request)) { + return callable.call(); + } + + Context context = instrumenter().start(parentContext, request); + T result; + try (Scope ignored = context.makeCurrent()) { + result = callable.call(); + } catch (Throwable t) { + instrumenter().end(context, request, null, t); + throw t; + } + instrumenter().end(context, request, null, null); + return result; } finally { CallDepthThreadLocalMap.reset(Statement.class); } @@ -196,7 +206,9 @@ private static boolean isNotEmpty(CharSequence s) { return s != null && !"".contentEquals(s); } - /** Add tags to span. Skip empty tags to avoid reported NPE in tracers. */ + /** + * Add tags to span. Skip empty tags to avoid reported NPE in tracers. + */ private static void decorate(Span span, String sql, ConnectionInfo connectionInfo) { if (isNotEmpty(sql)) { span.setAttribute(SemanticAttributes.DB_STATEMENT, sql); @@ -230,7 +242,7 @@ private static void queryThresholdChecks(Span span, long startTime) { long completionTime = System.nanoTime() - startTime; if (JdbcTracing.getExcludeFastQueryThresholdMs() > 0 && completionTime - < TimeUnit.MILLISECONDS.toNanos(JdbcTracing.getExcludeFastQueryThresholdMs())) { + < TimeUnit.MILLISECONDS.toNanos(JdbcTracing.getExcludeFastQueryThresholdMs())) { span.setAttribute(SAMPLING_PRIORITY, 0); } if (JdbcTracing.getSlowQueryThresholdMs() > 0 From f45f3f97385b173782196d647a4724e8fa7f05f9 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 21 Jun 2021 12:14:01 +0800 Subject: [PATCH 15/69] Removed proxy usage. --- .../instrumentation/jdbc/Classes.java | 160 ------------------ .../jdbc/JdbcTracingUtils.java | 8 +- .../jdbc/TracingConnection.java | 86 +++------- .../jdbc/TracingDataSource.java | 12 +- .../instrumentation/jdbc/TracingDriver.java | 8 +- .../instrumentation/jdbc/WrapperProxy.java | 157 ----------------- 6 files changed, 37 insertions(+), 394 deletions(-) delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java deleted file mode 100644 index 04f8249cebba..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/Classes.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashSet; - -public final class Classes { - - /** - * Adds all interfaces extended by the specified {@code iface} interface {@link Class}. - * - * @param iface The interface {@link Class}. - * @param set The set into which all extended interfaces are to be added. - * @throws NullPointerException If {@code iface} or {@code set} is null. - */ - private static void recurse(final Class iface, final HashSet> set) { - if (set.contains(iface)) { - return; - } - - set.add(iface); - for (final Class extended : iface.getInterfaces()) { - recurse(extended, set); - } - } - - /** - * Returns all interfaces implemented by the class or interface represented by the specified - * class. This method differentiates itself from {@link Class#getInterfaces()} by returning - * all interfaces (full depth and breadth) instead of just the interfaces directly - * implemented by the class. - * - * @param cls The class. - * @return All interfaces implemented by the class or interface represented by the specified - * class. - * @throws NullPointerException If {@code cls} is null. - */ - public static Class[] getAllInterfaces(final Class cls) { - Class parent = cls; - Class[] ifaces = null; - HashSet> set = null; - do { - ifaces = parent.getInterfaces(); - if (ifaces.length == 0) { - continue; - } - - if (set == null) { - set = new HashSet<>(4); - } - - for (final Class iface : ifaces) { - recurse(iface, set); - } - } while ((parent = parent.getSuperclass()) != null); - return set == null ? ifaces : set.toArray(new Class[set.size()]); - } - - /** - * Returns a Method object that reflects the specified declared method of the class or interface - * represented by {@code cls} (excluding inherited methods), or {@code null} if the method is not - * found. - * - *

Declared methods include public, protected, default (package) access, and private - * visibility. - * - *

The {@code name} parameter is a String that specifies the simple name of the desired method, - * and the {@code parameterTypes} parameter is an array of Class objects that identify the - * method's formal parameter types, in declared order. If more than one method with the same - * parameter types is declared in a class, and one of these methods has a return type that is more - * specific than any of the others, that method is returned; otherwise one of the methods is - * chosen arbitrarily. If the name is {@code ""} or {@code ""} this method returns - * {@code null}. If this Class object represents an array type, then this method does not find the - * clone() method. - * - *

This method differentiates itself from {@link Class#getDeclaredMethod(String, Class...)} by - * returning {@code null} when a method is not found, instead of throwing {@link - * NoSuchMethodException}. - * - * @param cls The class in which to find the declared method. - * @param name The simple name of the method. - * @param parameterTypes The parameter array. - * @return A Method object that reflects the specified declared method of the class or interface - * represented by {@code cls} (excluding inherited methods), or {@code null} if the method is - * not found. - * @throws NullPointerException If {@code cls} or {@code name} is null. - */ - public static Method getDeclaredMethod( - final Class cls, final String name, final Class... parameterTypes) { - final Method[] methods = cls.getDeclaredMethods(); - for (final Method method : methods) { - if (name.equals(method.getName()) - && Arrays.equals(method.getParameterTypes(), parameterTypes)) { - return method; - } - } - - return null; - } - - /** - * Returns a Method object that reflects the specified declared method of the class or interface - * represented by {@code cls} (including inherited methods), or {@code null} if the method is not - * found. - * - *

Declared methods include public, protected, default (package) access, and private - * visibility. - * - *

The {@code name} parameter is a String that specifies the simple name of the desired method, - * and the {@code parameterTypes} parameter is an array of Class objects that identify the - * method's formal parameter types, in declared order. If more than one method with the same - * parameter types is declared in a class, and one of these methods has a return type that is more - * specific than any of the others, that method is returned; otherwise one of the methods is - * chosen arbitrarily. If the name is {@code ""} or {@code ""} this method returns - * {@code null}. If this Class object represents an array type, then this method does not find the - * clone() method. - * - *

This method differentiates itself from {@link Class#getDeclaredMethod(String, Class...)} by - * returning {@code null} when a method is not found, instead of throwing {@link - * NoSuchMethodException}. - * - * @param cls The class in which to find the declared method. - * @param name The simple name of the method. - * @param parameterTypes The parameter array. - * @return A Method object that reflects the specified declared method of the class or interface - * represented by {@code cls} (including inherited methods), or {@code null} if the method is - * not found. - * @throws NullPointerException If {@code cls} or {@code name} is null. - */ - public static Method getDeclaredMethodDeep( - Class cls, final String name, final Class... parameterTypes) { - Method method; - do { - method = getDeclaredMethod(cls, name, parameterTypes); - } while (method == null && (cls = cls.getSuperclass()) != null); - return method; - } - - private Classes() {} -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java index f5a0b6a321a8..4b8853013f41 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java @@ -88,7 +88,7 @@ static void execute( buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); long startTime = (JdbcTracing.getSlowQueryThresholdMs() > 0 - || JdbcTracing.getExcludeFastQueryThresholdMs() > 0) + || JdbcTracing.getExcludeFastQueryThresholdMs() > 0) ? System.nanoTime() : 0; try (Scope ignored = span.makeCurrent()) { @@ -206,9 +206,7 @@ private static boolean isNotEmpty(CharSequence s) { return s != null && !"".contentEquals(s); } - /** - * Add tags to span. Skip empty tags to avoid reported NPE in tracers. - */ + /** Add tags to span. Skip empty tags to avoid reported NPE in tracers. */ private static void decorate(Span span, String sql, ConnectionInfo connectionInfo) { if (isNotEmpty(sql)) { span.setAttribute(SemanticAttributes.DB_STATEMENT, sql); @@ -242,7 +240,7 @@ private static void queryThresholdChecks(Span span, long startTime) { long completionTime = System.nanoTime() - startTime; if (JdbcTracing.getExcludeFastQueryThresholdMs() > 0 && completionTime - < TimeUnit.MILLISECONDS.toNanos(JdbcTracing.getExcludeFastQueryThresholdMs())) { + < TimeUnit.MILLISECONDS.toNanos(JdbcTracing.getExcludeFastQueryThresholdMs())) { span.setAttribute(SAMPLING_PRIORITY, 0); } if (JdbcTracing.getSlowQueryThresholdMs() > 0 diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java index c5e4490ed5d0..f28c86739f8d 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java @@ -66,20 +66,16 @@ public TracingConnection( @Override public Statement createStatement() throws SQLException { final Statement statement = connection.createStatement(); - return WrapperProxy.wrap( - statement, - new TracingStatement( - statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingStatement( + statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { final Statement statement = connection.createStatement(resultSetType, resultSetConcurrency); - return WrapperProxy.wrap( - statement, - new TracingStatement( - statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingStatement( + statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override @@ -87,20 +83,16 @@ public Statement createStatement( int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { final Statement statement = connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - return WrapperProxy.wrap( - statement, - new TracingStatement( - statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingStatement( + statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql); JdbcMaps.preparedStatements.put(statement, sql); - return WrapperProxy.wrap( - statement, - new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override @@ -109,10 +101,8 @@ public PreparedStatement prepareStatement(String sql, int resultSetType, int res final PreparedStatement statement = connection.prepareStatement(sql, resultSetType, resultSetConcurrency); JdbcMaps.preparedStatements.put(statement, sql); - return WrapperProxy.wrap( - statement, - new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override @@ -122,54 +112,39 @@ public PreparedStatement prepareStatement( final PreparedStatement statement = connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); JdbcMaps.preparedStatements.put(statement, sql); - return WrapperProxy.wrap( - statement, - new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, autoGeneratedKeys); JdbcMaps.preparedStatements.put(statement, sql); - return WrapperProxy.wrap( - statement, - new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, columnIndexes); JdbcMaps.preparedStatements.put(statement, sql); - return WrapperProxy.wrap( - statement, - new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { final PreparedStatement statement = connection.prepareStatement(sql, columnNames); JdbcMaps.preparedStatements.put(statement, sql); - return WrapperProxy.wrap( - statement, - new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingPreparedStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override public CallableStatement prepareCall(String sql) throws SQLException { final CallableStatement statement = connection.prepareCall(sql); - return WrapperProxy.wrap( - statement, - new TracingCallableStatement( - connection.prepareCall(sql), - sql, - connectionInfo, - withActiveSpanOnly, - ignoreStatements, - tracer)); + return new TracingCallableStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override @@ -177,10 +152,8 @@ public CallableStatement prepareCall(String sql, int resultSetType, int resultSe throws SQLException { final CallableStatement statement = connection.prepareCall(sql, resultSetType, resultSetConcurrency); - return WrapperProxy.wrap( - statement, - new TracingCallableStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingCallableStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override @@ -189,29 +162,24 @@ public CallableStatement prepareCall( throws SQLException { final CallableStatement statement = connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - return WrapperProxy.wrap( - statement, - new TracingCallableStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingCallableStatement( + statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override public void commit() throws SQLException { - JdbcTracingUtils.execute( - "Commit", connection::commit, null, connectionInfo, withActiveSpanOnly, null, tracer); + connection.commit(); } @SuppressWarnings("UngroupedOverloads") @Override public void rollback() throws SQLException { - JdbcTracingUtils.execute( - "Rollback", connection::rollback, null, connectionInfo, withActiveSpanOnly, null, tracer); + connection.rollback(); } @Override public void close() throws SQLException { - JdbcTracingUtils.execute( - "Close", connection::close, null, connectionInfo, withActiveSpanOnly, null, tracer); + connection.close(); } @Override diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java index dcd39c96fb03..b7614bc1ebee 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java @@ -90,10 +90,8 @@ public Connection getConnection() throws SQLException { null, tracer); - return WrapperProxy.wrap( - connection, - new TracingConnection( - connection, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingConnection( + connection, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override @@ -109,10 +107,8 @@ public Connection getConnection(final String username, final String password) null, tracer); - return WrapperProxy.wrap( - connection, - new TracingConnection( - connection, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer)); + return new TracingConnection( + connection, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); } @Override diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java index cb0c3a69dabe..e6ab6187a588 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java @@ -189,14 +189,12 @@ public Connection connect(String url, Properties info) throws SQLException { DbInfo dbInfo = JdbcConnectionUrlParser.parse(url, info); JdbcMaps.connectionInfo.put(connection, dbInfo); - return WrapperProxy.wrap( - connection, - new TracingConnection( - connection, connectionInfo, withActiveSpanOnly, ignoreStatements, currentTracer)); + return new TracingConnection( + connection, connectionInfo, withActiveSpanOnly, ignoreStatements, currentTracer); } @Override - public boolean acceptsURL(String url) throws SQLException { + public boolean acceptsURL(String url) { return url != null && (url.startsWith(getUrlPrefix()) || (interceptorMode && url.startsWith("jdbc:"))); } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java deleted file mode 100644 index c4c5ece60fbe..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/WrapperProxy.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** Utility class for the creation of wrapper proxies. */ -public final class WrapperProxy { - - private interface WrapperInvocationHandler extends InvocationHandler { - - T getObject(); - - T getWrapper(); - } - - /** - * Returns a {@linkplain Proxy proxy} with type {@code } of the specified {@code obj} wrapping - * the provided {@code wrapper} instance. Method invocations on the proxy instance will be handled - * as such: - * - *

    - *
  1. The {@code wrapper} instance will be invoked for methods that exist in the {@code - * wrapper} instance. - *
  2. The {@code obj} instance will be invoked for methods that do not exist in the - * {@code wrapper} instance. - *
- * - * The type of the returned {@linkplain Proxy proxy} will be the composition of all - * super-interfaces of the runtime type of the specified {@code obj} instance. - * - *

Note: The runtime type of the returned instance will not be of a concrete - * class, but rather a composition of all super-interfaces of the concrete class {@code }. It - * is therefore not possible to cast the instance returned by this method to a concrete class, but - * rather any super-interface of the concrete class. - * - * @param The type parameter of the specified arguments. - * @param obj The target object instance to wrap. - * @param wrapper The wrapping object. - * @return a {@linkplain Proxy proxy} with type {@code } of the specified {@code obj} wrapping - * wrapping the provided {@code wrapper} instance, or, {@code wrapper} if {@code obj == - * wrapper}, or if {@code target} or {@code wrapper} is null. - */ - @SuppressWarnings("unchecked") - public static T wrap(final T obj, final T wrapper) { - if (obj == null || wrapper == null || obj == wrapper) { - return wrapper; - } - - final Class objClass = obj.getClass(); - final Class wrapperClass = wrapper.getClass(); - return (T) - Proxy.newProxyInstance( - objClass.getClassLoader(), - Classes.getAllInterfaces(objClass), - new WrapperInvocationHandler() { - @Override - public Object invoke(final Object proxy, final Method method, final Object[] args) - throws Throwable { - try { - try { - if (method.getDeclaringClass().isAssignableFrom(wrapperClass)) { - return method.invoke(wrapper, args); - } - - final Method specific = - Classes.getDeclaredMethodDeep( - wrapperClass, method.getName(), method.getParameterTypes()); - if (specific != null) { - return specific.invoke(wrapper, args); - } - } catch (final IllegalArgumentException ignored) { - // nothing to do, expected exception - } - - return method.invoke(obj, args); - } catch (final InvocationTargetException e) { - throw e.getCause(); - } catch (final IllegalAccessException e) { - final IllegalAccessError error = new IllegalAccessError(e.getMessage()); - error.setStackTrace(e.getStackTrace()); - throw error; - } - } - - @Override - public T getObject() { - return obj; - } - - @Override - public T getWrapper() { - return wrapper; - } - }); - } - - /** - * Tests whether the specified object is a proxy of a wrapped object. - * - * @param obj The object to test. - * @return Whether the specified object is a proxy of a wrapped object. - * @throws NullPointerException If {@code obj} is null. - */ - public static boolean isWrapper(final Object obj) { - return Proxy.isProxyClass(obj.getClass()) - && Proxy.getInvocationHandler(obj) instanceof WrapperInvocationHandler; - } - - /** - * Tests whether the specified object is a proxy of a wrapped instance type matching the provided - * {@code wrappedClass}. - * - * @param The common type of the proxy and wrapped instance. - * @param obj The object to test. - * @param wrappedClass The type of the instance wrapped by the specified {@code obj}. - * @return Whether the specified object is a proxy of a wrapped instance type matching the - * provided {@code wrappedClass}. - * @throws NullPointerException If {@code obj} or {@code wrappedClass} is null. - */ - public static boolean isWrapper(final T obj, final Class wrappedClass) { - if (!Proxy.isProxyClass(obj.getClass())) { - return false; - } - - final InvocationHandler handler = Proxy.getInvocationHandler(obj); - if (!(handler instanceof WrapperInvocationHandler)) { - return false; - } - - return wrappedClass.isAssignableFrom( - ((WrapperInvocationHandler) handler).getWrapper().getClass()); - } - - private WrapperProxy() {} -} From 343643a4096e53bb932ed8c25eff88f33f430497 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 21 Jun 2021 14:04:58 +0800 Subject: [PATCH 16/69] Cleanup. --- .../instrumentation/jdbc/CheckedCallable.java | 12 + .../instrumentation/jdbc/ConnectionInfo.java | 127 --------- .../instrumentation/jdbc/JdbcTracing.java | 62 ----- .../jdbc/JdbcTracingUtils.java | 263 ------------------ .../jdbc/TracingCallableStatement.java | 243 ++++++++-------- .../jdbc/TracingConnection.java | 197 ++++++------- .../jdbc/TracingDataSource.java | 99 ++----- .../instrumentation/jdbc/TracingDriver.java | 245 ++++++---------- .../jdbc/TracingPreparedStatement.java | 175 +++++++----- .../jdbc/TracingStatement.java | 198 ++++++------- .../jdbc/parser/AS400URLParser.java | 42 --- .../jdbc/parser/AbstractMatcherURLParser.java | 85 ------ .../jdbc/parser/AbstractURLParser.java | 67 ----- .../jdbc/parser/ConnectionURLParser.java | 28 -- .../jdbc/parser/DB2URLParser.java | 42 --- .../jdbc/parser/H2URLParser.java | 159 ----------- .../jdbc/parser/MariadbURLParser.java | 29 -- .../jdbc/parser/MysqlURLParser.java | 120 -------- .../jdbc/parser/OracleURLParser.java | 173 ------------ .../jdbc/parser/PostgreSQLURLParser.java | 89 ------ .../jdbc/parser/SqlServerURLParser.java | 116 -------- .../jdbc/parser/URLLocation.java | 40 --- .../jdbc/parser/URLParser.java | 96 ------- 23 files changed, 528 insertions(+), 2179 deletions(-) create mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java delete mode 100644 instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java new file mode 100644 index 000000000000..745f939dce5f --- /dev/null +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java @@ -0,0 +1,12 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc; + +@FunctionalInterface +interface CheckedCallable { + + T call() throws E; +} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java deleted file mode 100644 index 59dd5c83bcdd..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/ConnectionInfo.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc; - -public class ConnectionInfo { - - public static final ConnectionInfo UNKNOWN_CONNECTION_INFO = - new Builder("unknown_peer").dbType("unknown_type").dbInstance("unknown_instance").build(); - - private final String dbType; - private final String dbUser; - private final String dbInstance; - private final String dbPeer; - private final String dbPeerService; - - private ConnectionInfo( - String dbType, String dbUser, String dbInstance, String dbHost, Integer dbPort) { - this.dbType = dbType; - this.dbUser = dbUser; - this.dbInstance = dbInstance; - if (dbHost != null && dbPort != null) { - this.dbPeer = dbHost + ":" + dbPort; - } else { - this.dbPeer = ""; - } - - this.dbPeerService = makePeerService(); - } - - private ConnectionInfo(String dbType, String dbUser, String dbInstance, String dbPeer) { - this.dbType = dbType; - this.dbUser = dbUser; - this.dbInstance = dbInstance; - this.dbPeer = dbPeer; - - this.dbPeerService = makePeerService(); - } - - /** Make a unique serviceName that could be used in dependency diagram. */ - private String makePeerService() { - if (null != dbInstance && !dbInstance.isEmpty()) { - return dbInstance + "[" + dbType + "(" + dbPeer + ")]"; - } else { - return dbType + "(" + dbPeer + ")"; - } - } - - public String getDbType() { - return dbType; - } - - public String getDbUser() { - return dbUser; - } - - public String getDbInstance() { - return dbInstance; - } - - public String getDbPeer() { - return dbPeer; - } - - public String getPeerService() { - return dbPeerService; - } - - public static class Builder { - - private String dbType; - private String dbUser; - private String dbInstance; - private String dbHost; - private Integer dbPort; - private String dbPeer; - - public Builder(String dbPeer) { - this.dbPeer = dbPeer; - } - - public Builder(String dbHost, Integer dbPort) { - this.dbHost = dbHost; - this.dbPort = dbPort; - } - - public Builder dbType(String dbType) { - this.dbType = dbType; - return this; - } - - public Builder dbUser(String dbUser) { - this.dbUser = dbUser; - return this; - } - - public Builder dbInstance(String dbInstance) { - this.dbInstance = dbInstance; - return this; - } - - public ConnectionInfo build() { - if (this.dbPeer != null && !dbPeer.isEmpty()) { - return new ConnectionInfo(this.dbType, this.dbUser, this.dbInstance, this.dbPeer); - } - return new ConnectionInfo( - this.dbType, this.dbUser, this.dbInstance, this.dbHost, this.dbPort); - } - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java deleted file mode 100644 index 19e683d75268..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracing.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc; - -public class JdbcTracing { - - private static boolean traceEnabled = true; - - /** - * Sets the {@code traceEnabled} property to enable or disable traces. - * - * @param traceEnabled The {@code traceEnabled} value. - */ - public static void setTraceEnabled(boolean traceEnabled) { - JdbcTracing.traceEnabled = traceEnabled; - } - - public static boolean isTraceEnabled() { - return JdbcTracing.traceEnabled; - } - - /** can be modified by application code */ - private static int slowQueryThresholdMs = - Integer.getInteger("io.opentracing.contrib.jdbc.slowQueryThresholdMs", 0); - - public static int getSlowQueryThresholdMs() { - return slowQueryThresholdMs; - } - - public static void setSlowQueryThresholdMs(final int slowQueryThresholdMs) { - JdbcTracing.slowQueryThresholdMs = slowQueryThresholdMs; - } - - private static int excludeFastQueryThresholdMs = - Integer.getInteger("io.opentracing.contrib.jdbc.excludeFastQueryThresholdMs", 0); - - public static int getExcludeFastQueryThresholdMs() { - return excludeFastQueryThresholdMs; - } - - public static void setExcludeFastQueryThresholdMs(final int excludeFastQueryThresholdMs) { - JdbcTracing.excludeFastQueryThresholdMs = excludeFastQueryThresholdMs; - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java deleted file mode 100644 index 4b8853013f41..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/JdbcTracingUtils.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc; - -import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanBuilder; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.context.Context; -import io.opentelemetry.context.Scope; -import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; -import io.opentelemetry.javaagent.instrumentation.jdbc.DbRequest; -import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -class JdbcTracingUtils { - - static final AttributeKey SLOW = AttributeKey.booleanKey("slow"); - - // TODO is it requires for OTEL? - static final AttributeKey SAMPLING_PRIORITY = AttributeKey.longKey("sampling.priority"); - - static Span buildSpan( - String operationName, - String sql, - ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, - Set ignoreStatements, - Tracer tracer) { - if (!JdbcTracing.isTraceEnabled() - || (withActiveSpanOnly && Span.fromContextOrNull(Context.current()) == null)) { - // noop span - return Span.getInvalid(); - } else if (ignoreStatements != null && ignoreStatements.contains(sql)) { - // noop span - return Span.getInvalid(); - } - - SpanBuilder spanBuilder = tracer.spanBuilder(operationName).setSpanKind(SpanKind.CLIENT); - - Span span = spanBuilder.startSpan(); - decorate(span, sql, connectionInfo); - - return span; - } - - static void execute( - String operationName, - CheckedRunnable runnable, - String sql, - ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, - Set ignoreStatements, - Tracer tracer) - throws E { - if (!JdbcTracing.isTraceEnabled() - || (withActiveSpanOnly && Span.fromContextOrNull(Context.current()) == null)) { - runnable.run(); - return; - } - - final Span span = - buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); - long startTime = - (JdbcTracing.getSlowQueryThresholdMs() > 0 - || JdbcTracing.getExcludeFastQueryThresholdMs() > 0) - ? System.nanoTime() - : 0; - try (Scope ignored = span.makeCurrent()) { - runnable.run(); - } catch (Exception e) { - JdbcTracingUtils.onError(e, span); - throw e; - } finally { - JdbcTracingUtils.queryThresholdChecks(span, startTime); - span.end(); - } - } - - static T call( - String operationName, - CheckedCallable callable, - String sql, - ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, - Set ignoreStatements, - Tracer tracer) - throws E { - if (!JdbcTracing.isTraceEnabled() - || (withActiveSpanOnly && Span.fromContextOrNull(Context.current()) == null)) { - return callable.call(); - } - - final Span span = - buildSpan(operationName, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); - long startTime = JdbcTracing.getSlowQueryThresholdMs() > 0 ? System.nanoTime() : 0; - try (Scope ignored = span.makeCurrent()) { - return callable.call(); - } catch (Exception e) { - JdbcTracingUtils.onError(e, span); - throw e; - } finally { - JdbcTracingUtils.queryThresholdChecks(span, startTime); - span.end(); - } - } - - static T executePreparedStatement( - PreparedStatement preparedStatement, CheckedCallable callable) throws E { - // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info - // this happens before the DB CLIENT span is started (and put in the current context), so this - // instrumentation runs again and the shouldStartSpan() check always returns true - and so on - // until we get a StackOverflowError - // using CallDepth prevents this, because this check happens before Connection#getMetadata() - // is called - the first recursive Statement call is just skipped and we do not create a span - // for it - if (CallDepthThreadLocalMap.getCallDepth(Statement.class).getAndIncrement() > 0) { - return callable.call(); - } - - try { - Context parentContext = Context.current(); - DbRequest request = DbRequest.create(preparedStatement); - - if (request == null || !instrumenter().shouldStart(parentContext, request)) { - return callable.call(); - } - - Context context = instrumenter().start(parentContext, request); - T result; - try (Scope ignored = context.makeCurrent()) { - result = callable.call(); - } catch (Throwable t) { - instrumenter().end(context, request, null, t); - throw t; - } - instrumenter().end(context, request, null, null); - return result; - } finally { - CallDepthThreadLocalMap.reset(Statement.class); - } - } - - static T executeStatement( - Statement statement, String sql, CheckedCallable callable) throws E { - // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info - // this happens before the DB CLIENT span is started (and put in the current context), so this - // instrumentation runs again and the shouldStartSpan() check always returns true - and so on - // until we get a StackOverflowError - // using CallDepth prevents this, because this check happens before Connection#getMetadata() - // is called - the first recursive Statement call is just skipped and we do not create a span - // for it - if (CallDepthThreadLocalMap.getCallDepth(Statement.class).getAndIncrement() > 0) { - return callable.call(); - } - - try { - Context parentContext = Context.current(); - DbRequest request = DbRequest.create(statement, sql); - - if (request == null || !instrumenter().shouldStart(parentContext, request)) { - return callable.call(); - } - - Context context = instrumenter().start(parentContext, request); - T result; - try (Scope ignored = context.makeCurrent()) { - result = callable.call(); - } catch (Throwable t) { - instrumenter().end(context, request, null, t); - throw t; - } - instrumenter().end(context, request, null, null); - return result; - } finally { - CallDepthThreadLocalMap.reset(Statement.class); - } - } - - private static boolean isNotEmpty(CharSequence s) { - return s != null && !"".contentEquals(s); - } - - /** Add tags to span. Skip empty tags to avoid reported NPE in tracers. */ - private static void decorate(Span span, String sql, ConnectionInfo connectionInfo) { - if (isNotEmpty(sql)) { - span.setAttribute(SemanticAttributes.DB_STATEMENT, sql); - } - if (isNotEmpty(connectionInfo.getDbType())) { - span.setAttribute(SemanticAttributes.DB_SYSTEM, connectionInfo.getDbType()); - } - if (isNotEmpty(connectionInfo.getDbPeer())) { - span.setAttribute(SemanticAttributes.NET_PEER_IP, connectionInfo.getDbPeer()); - } - if (isNotEmpty(connectionInfo.getDbInstance())) { - span.setAttribute(SemanticAttributes.DB_NAME, connectionInfo.getDbInstance()); - } - if (isNotEmpty(connectionInfo.getDbUser())) { - span.setAttribute(SemanticAttributes.DB_USER, connectionInfo.getDbUser()); - } - if (isNotEmpty(connectionInfo.getPeerService())) { - span.setAttribute(SemanticAttributes.PEER_SERVICE, connectionInfo.getPeerService()); - } - } - - static void onError(Throwable throwable, Span span) { - span.setStatus(StatusCode.ERROR); - - if (throwable != null) { - span.recordException(throwable); - } - } - - private static void queryThresholdChecks(Span span, long startTime) { - long completionTime = System.nanoTime() - startTime; - if (JdbcTracing.getExcludeFastQueryThresholdMs() > 0 - && completionTime - < TimeUnit.MILLISECONDS.toNanos(JdbcTracing.getExcludeFastQueryThresholdMs())) { - span.setAttribute(SAMPLING_PRIORITY, 0); - } - if (JdbcTracing.getSlowQueryThresholdMs() > 0 - && completionTime > TimeUnit.MILLISECONDS.toNanos(JdbcTracing.getSlowQueryThresholdMs())) { - span.setAttribute(SLOW, true); - } - } - - @FunctionalInterface - interface CheckedRunnable { - - void run() throws E; - } - - @FunctionalInterface - interface CheckedCallable { - - T call() throws E; - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java index 8d0ad0734ce2..90050443f00a 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java @@ -20,7 +20,6 @@ package io.opentelemetry.instrumentation.jdbc; -import io.opentelemetry.api.trace.Tracer; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; @@ -39,675 +38,665 @@ import java.sql.Timestamp; import java.util.Calendar; import java.util.Map; -import java.util.Set; -public class TracingCallableStatement extends TracingPreparedStatement +class TracingCallableStatement extends TracingPreparedStatement implements CallableStatement { - private final CallableStatement statement; - - public TracingCallableStatement( - CallableStatement statement, - String query, - ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, - Set ignoreStatements, - Tracer tracer) { - super(statement, query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); - this.statement = statement; + public TracingCallableStatement(S callableStatement, String query) { + super(callableStatement, query); } @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { - statement.registerOutParameter(parameterIndex, sqlType); + delegate.registerOutParameter(parameterIndex, sqlType); } @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { - statement.registerOutParameter(parameterIndex, sqlType, scale); + delegate.registerOutParameter(parameterIndex, sqlType, scale); } @Override public boolean wasNull() throws SQLException { - return statement.wasNull(); + return delegate.wasNull(); } @SuppressWarnings("UngroupedOverloads") @Override public String getString(int parameterIndex) throws SQLException { - return statement.getString(parameterIndex); + return delegate.getString(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public boolean getBoolean(int parameterIndex) throws SQLException { - return statement.getBoolean(parameterIndex); + return delegate.getBoolean(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public byte getByte(int parameterIndex) throws SQLException { - return statement.getByte(parameterIndex); + return delegate.getByte(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public short getShort(int parameterIndex) throws SQLException { - return statement.getShort(parameterIndex); + return delegate.getShort(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public int getInt(int parameterIndex) throws SQLException { - return statement.getInt(parameterIndex); + return delegate.getInt(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public long getLong(int parameterIndex) throws SQLException { - return statement.getLong(parameterIndex); + return delegate.getLong(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public float getFloat(int parameterIndex) throws SQLException { - return statement.getFloat(parameterIndex); + return delegate.getFloat(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public double getDouble(int parameterIndex) throws SQLException { - return statement.getDouble(parameterIndex); + return delegate.getDouble(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { - return statement.getBigDecimal(parameterIndex, scale); + return delegate.getBigDecimal(parameterIndex, scale); } @SuppressWarnings("UngroupedOverloads") @Override public byte[] getBytes(int parameterIndex) throws SQLException { - return statement.getBytes(parameterIndex); + return delegate.getBytes(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public Date getDate(int parameterIndex) throws SQLException { - return statement.getDate(parameterIndex); + return delegate.getDate(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public Time getTime(int parameterIndex) throws SQLException { - return statement.getTime(parameterIndex); + return delegate.getTime(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public Timestamp getTimestamp(int parameterIndex) throws SQLException { - return statement.getTimestamp(parameterIndex); + return delegate.getTimestamp(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public Object getObject(int parameterIndex) throws SQLException { - return statement.getObject(parameterIndex); + return delegate.getObject(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { - return statement.getBigDecimal(parameterIndex); + return delegate.getBigDecimal(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public Object getObject(int parameterIndex, Map> map) throws SQLException { - return statement.getObject(parameterIndex, map); + return delegate.getObject(parameterIndex, map); } @SuppressWarnings("UngroupedOverloads") @Override public Ref getRef(int parameterIndex) throws SQLException { - return statement.getRef(parameterIndex); + return delegate.getRef(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public Blob getBlob(int parameterIndex) throws SQLException { - return statement.getBlob(parameterIndex); + return delegate.getBlob(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public Clob getClob(int parameterIndex) throws SQLException { - return statement.getClob(parameterIndex); + return delegate.getClob(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public Array getArray(int parameterIndex) throws SQLException { - return statement.getArray(parameterIndex); + return delegate.getArray(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override public Date getDate(int parameterIndex, Calendar cal) throws SQLException { - return statement.getDate(parameterIndex, cal); + return delegate.getDate(parameterIndex, cal); } @SuppressWarnings("UngroupedOverloads") @Override public Time getTime(int parameterIndex, Calendar cal) throws SQLException { - return statement.getTime(parameterIndex, cal); + return delegate.getTime(parameterIndex, cal); } @SuppressWarnings("UngroupedOverloads") @Override public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { - return statement.getTimestamp(parameterIndex, cal); + return delegate.getTimestamp(parameterIndex, cal); } @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { - statement.registerOutParameter(parameterIndex, sqlType, typeName); + delegate.registerOutParameter(parameterIndex, sqlType, typeName); } @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { - statement.registerOutParameter(parameterName, sqlType); + delegate.registerOutParameter(parameterName, sqlType); } @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { - statement.registerOutParameter(parameterName, sqlType, scale); + delegate.registerOutParameter(parameterName, sqlType, scale); } @SuppressWarnings("UngroupedOverloads") @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { - statement.registerOutParameter(parameterName, sqlType, typeName); + delegate.registerOutParameter(parameterName, sqlType, typeName); } @SuppressWarnings("UngroupedOverloads") @Override public URL getURL(int parameterIndex) throws SQLException { - return statement.getURL(parameterIndex); + return delegate.getURL(parameterIndex); } @Override public void setURL(String parameterName, URL val) throws SQLException { - statement.setURL(parameterName, val); + delegate.setURL(parameterName, val); } @SuppressWarnings("UngroupedOverloads") @Override public void setNull(String parameterName, int sqlType) throws SQLException { - statement.setNull(parameterName, sqlType); + delegate.setNull(parameterName, sqlType); } @Override public void setBoolean(String parameterName, boolean x) throws SQLException { - statement.setBoolean(parameterName, x); + delegate.setBoolean(parameterName, x); } @Override public void setByte(String parameterName, byte x) throws SQLException { - statement.setByte(parameterName, x); + delegate.setByte(parameterName, x); } @Override public void setShort(String parameterName, short x) throws SQLException { - statement.setShort(parameterName, x); + delegate.setShort(parameterName, x); } @Override public void setInt(String parameterName, int x) throws SQLException { - statement.setInt(parameterName, x); + delegate.setInt(parameterName, x); } @Override public void setLong(String parameterName, long x) throws SQLException { - statement.setLong(parameterName, x); + delegate.setLong(parameterName, x); } @Override public void setFloat(String parameterName, float x) throws SQLException { - statement.setFloat(parameterName, x); + delegate.setFloat(parameterName, x); } @Override public void setDouble(String parameterName, double x) throws SQLException { - statement.setDouble(parameterName, x); + delegate.setDouble(parameterName, x); } @Override public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { - statement.setBigDecimal(parameterName, x); + delegate.setBigDecimal(parameterName, x); } @Override public void setString(String parameterName, String x) throws SQLException { - statement.setString(parameterName, x); + delegate.setString(parameterName, x); } @Override public void setBytes(String parameterName, byte[] x) throws SQLException { - statement.setBytes(parameterName, x); + delegate.setBytes(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setDate(String parameterName, Date x) throws SQLException { - statement.setDate(parameterName, x); + delegate.setDate(parameterName, x); } @Override public void setTime(String parameterName, Time x) throws SQLException { - statement.setTime(parameterName, x); + delegate.setTime(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setTimestamp(String parameterName, Timestamp x) throws SQLException { - statement.setTimestamp(parameterName, x); + delegate.setTimestamp(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException { - statement.setAsciiStream(parameterName, x, length); + delegate.setAsciiStream(parameterName, x, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException { - statement.setBinaryStream(parameterName, x, length); + delegate.setBinaryStream(parameterName, x, length); } @Override public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { - statement.setObject(parameterName, x, targetSqlType, scale); + delegate.setObject(parameterName, x, targetSqlType, scale); } @Override public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { - statement.setObject(parameterName, x, targetSqlType); + delegate.setObject(parameterName, x, targetSqlType); } @Override public void setObject(String parameterName, Object x) throws SQLException { - statement.setObject(parameterName, x); + delegate.setObject(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException { - statement.setCharacterStream(parameterName, reader, length); + delegate.setCharacterStream(parameterName, reader, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setDate(String parameterName, Date x, Calendar cal) throws SQLException { - statement.setDate(parameterName, x, cal); + delegate.setDate(parameterName, x, cal); } @SuppressWarnings("UngroupedOverloads") @Override public void setTime(String parameterName, Time x, Calendar cal) throws SQLException { - statement.setTime(parameterName, x, cal); + delegate.setTime(parameterName, x, cal); } @SuppressWarnings("UngroupedOverloads") @Override public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { - statement.setTimestamp(parameterName, x, cal); + delegate.setTimestamp(parameterName, x, cal); } @SuppressWarnings("UngroupedOverloads") @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { - statement.setNull(parameterName, sqlType, typeName); + delegate.setNull(parameterName, sqlType, typeName); } @SuppressWarnings("UngroupedOverloads") @Override public String getString(String parameterName) throws SQLException { - return statement.getString(parameterName); + return delegate.getString(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public boolean getBoolean(String parameterName) throws SQLException { - return statement.getBoolean(parameterName); + return delegate.getBoolean(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public byte getByte(String parameterName) throws SQLException { - return statement.getByte(parameterName); + return delegate.getByte(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public short getShort(String parameterName) throws SQLException { - return statement.getShort(parameterName); + return delegate.getShort(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public int getInt(String parameterName) throws SQLException { - return statement.getInt(parameterName); + return delegate.getInt(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public long getLong(String parameterName) throws SQLException { - return statement.getLong(parameterName); + return delegate.getLong(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public float getFloat(String parameterName) throws SQLException { - return statement.getFloat(parameterName); + return delegate.getFloat(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public double getDouble(String parameterName) throws SQLException { - return statement.getDouble(parameterName); + return delegate.getDouble(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public byte[] getBytes(String parameterName) throws SQLException { - return statement.getBytes(parameterName); + return delegate.getBytes(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public Date getDate(String parameterName) throws SQLException { - return statement.getDate(parameterName); + return delegate.getDate(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public Time getTime(String parameterName) throws SQLException { - return statement.getTime(parameterName); + return delegate.getTime(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public Timestamp getTimestamp(String parameterName) throws SQLException { - return statement.getTimestamp(parameterName); + return delegate.getTimestamp(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public Object getObject(String parameterName) throws SQLException { - return statement.getObject(parameterName); + return delegate.getObject(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { - return statement.getBigDecimal(parameterName); + return delegate.getBigDecimal(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public Object getObject(String parameterName, Map> map) throws SQLException { - return statement.getObject(parameterName, map); + return delegate.getObject(parameterName, map); } @Override public Ref getRef(String parameterName) throws SQLException { - return statement.getRef(parameterName); + return delegate.getRef(parameterName); } @Override public Blob getBlob(String parameterName) throws SQLException { - return statement.getBlob(parameterName); + return delegate.getBlob(parameterName); } @Override public Clob getClob(String parameterName) throws SQLException { - return statement.getClob(parameterName); + return delegate.getClob(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public Array getArray(String parameterName) throws SQLException { - return statement.getArray(parameterName); + return delegate.getArray(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public Date getDate(String parameterName, Calendar cal) throws SQLException { - return statement.getDate(parameterName, cal); + return delegate.getDate(parameterName, cal); } @SuppressWarnings("UngroupedOverloads") @Override public Time getTime(String parameterName, Calendar cal) throws SQLException { - return statement.getTime(parameterName, cal); + return delegate.getTime(parameterName, cal); } @SuppressWarnings("UngroupedOverloads") @Override public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { - return statement.getTimestamp(parameterName, cal); + return delegate.getTimestamp(parameterName, cal); } @SuppressWarnings("UngroupedOverloads") @Override public URL getURL(String parameterName) throws SQLException { - return statement.getURL(parameterName); + return delegate.getURL(parameterName); } @Override public RowId getRowId(int parameterIndex) throws SQLException { - return statement.getRowId(parameterIndex); + return delegate.getRowId(parameterIndex); } @Override public RowId getRowId(String parameterName) throws SQLException { - return statement.getRowId(parameterName); + return delegate.getRowId(parameterName); } @Override public void setRowId(String parameterName, RowId x) throws SQLException { - statement.setRowId(parameterName, x); + delegate.setRowId(parameterName, x); } @Override public void setNString(String parameterName, String value) throws SQLException { - statement.setNString(parameterName, value); + delegate.setNString(parameterName, value); } @SuppressWarnings("UngroupedOverloads") @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { - statement.setNCharacterStream(parameterName, value, length); + delegate.setNCharacterStream(parameterName, value, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setNClob(String parameterName, NClob value) throws SQLException { - statement.setNClob(parameterName, value); + delegate.setNClob(parameterName, value); } @SuppressWarnings("UngroupedOverloads") @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { - statement.setClob(parameterName, reader, length); + delegate.setClob(parameterName, reader, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { - statement.setBlob(parameterName, inputStream, length); + delegate.setBlob(parameterName, inputStream, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { - statement.setNClob(parameterName, reader, length); + delegate.setNClob(parameterName, reader, length); } @Override public NClob getNClob(int parameterIndex) throws SQLException { - return statement.getNClob(parameterIndex); + return delegate.getNClob(parameterIndex); } @Override public NClob getNClob(String parameterName) throws SQLException { - return statement.getNClob(parameterName); + return delegate.getNClob(parameterName); } @Override public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { - statement.setSQLXML(parameterName, xmlObject); + delegate.setSQLXML(parameterName, xmlObject); } @Override public SQLXML getSQLXML(int parameterIndex) throws SQLException { - return statement.getSQLXML(parameterIndex); + return delegate.getSQLXML(parameterIndex); } @Override public SQLXML getSQLXML(String parameterName) throws SQLException { - return statement.getSQLXML(parameterName); + return delegate.getSQLXML(parameterName); } @Override public String getNString(int parameterIndex) throws SQLException { - return statement.getNString(parameterIndex); + return delegate.getNString(parameterIndex); } @Override public String getNString(String parameterName) throws SQLException { - return statement.getNString(parameterName); + return delegate.getNString(parameterName); } @Override public Reader getNCharacterStream(int parameterIndex) throws SQLException { - return statement.getNCharacterStream(parameterIndex); + return delegate.getNCharacterStream(parameterIndex); } @Override public Reader getNCharacterStream(String parameterName) throws SQLException { - return statement.getNCharacterStream(parameterName); + return delegate.getNCharacterStream(parameterName); } @Override public Reader getCharacterStream(int parameterIndex) throws SQLException { - return statement.getCharacterStream(parameterIndex); + return delegate.getCharacterStream(parameterIndex); } @Override public Reader getCharacterStream(String parameterName) throws SQLException { - return statement.getCharacterStream(parameterName); + return delegate.getCharacterStream(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override public void setBlob(String parameterName, Blob x) throws SQLException { - statement.setBlob(parameterName, x); + delegate.setBlob(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setClob(String parameterName, Clob x) throws SQLException { - statement.setClob(parameterName, x); + delegate.setClob(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { - statement.setAsciiStream(parameterName, x, length); + delegate.setAsciiStream(parameterName, x, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException { - statement.setBinaryStream(parameterName, x, length); + delegate.setBinaryStream(parameterName, x, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException { - statement.setCharacterStream(parameterName, reader, length); + delegate.setCharacterStream(parameterName, reader, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(String parameterName, InputStream x) throws SQLException { - statement.setAsciiStream(parameterName, x); + delegate.setAsciiStream(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(String parameterName, InputStream x) throws SQLException { - statement.setBinaryStream(parameterName, x); + delegate.setBinaryStream(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(String parameterName, Reader reader) throws SQLException { - statement.setCharacterStream(parameterName, reader); + delegate.setCharacterStream(parameterName, reader); } @SuppressWarnings("UngroupedOverloads") @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { - statement.setNCharacterStream(parameterName, value); + delegate.setNCharacterStream(parameterName, value); } @SuppressWarnings("UngroupedOverloads") @Override public void setClob(String parameterName, Reader reader) throws SQLException { - statement.setClob(parameterName, reader); + delegate.setClob(parameterName, reader); } @SuppressWarnings("UngroupedOverloads") @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { - statement.setBlob(parameterName, inputStream); + delegate.setBlob(parameterName, inputStream); } @SuppressWarnings("UngroupedOverloads") @Override public void setNClob(String parameterName, Reader reader) throws SQLException { - statement.setNClob(parameterName, reader); + delegate.setNClob(parameterName, reader); } @SuppressWarnings("UngroupedOverloads") @Override public T getObject(int parameterIndex, Class type) throws SQLException { - return statement.getObject(parameterIndex, type); + return delegate.getObject(parameterIndex, type); } @SuppressWarnings("UngroupedOverloads") @Override public T getObject(String parameterName, Class type) throws SQLException { - return statement.getObject(parameterName, type); + return delegate.getObject(parameterName, type); } } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java index f28c86739f8d..f61b205f06e6 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java @@ -20,7 +20,6 @@ package io.opentelemetry.instrumentation.jdbc; -import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcMaps; import java.sql.Array; import java.sql.Blob; @@ -39,70 +38,51 @@ import java.sql.Struct; import java.util.Map; import java.util.Properties; -import java.util.Set; import java.util.concurrent.Executor; public class TracingConnection implements Connection { - private final Connection connection; - private final ConnectionInfo connectionInfo; - private final boolean withActiveSpanOnly; - private final Set ignoreStatements; - private final Tracer tracer; + private final Connection delegate; - public TracingConnection( - Connection connection, - ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, - Set ignoreStatements, - Tracer tracer) { - this.connection = connection; - this.connectionInfo = connectionInfo; - this.withActiveSpanOnly = withActiveSpanOnly; - this.ignoreStatements = ignoreStatements; - this.tracer = tracer; + public TracingConnection(Connection delegate) { + this.delegate = delegate; } @Override public Statement createStatement() throws SQLException { - final Statement statement = connection.createStatement(); - return new TracingStatement( - statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + final Statement statement = delegate.createStatement(); + return new TracingStatement<>(statement); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - final Statement statement = connection.createStatement(resultSetType, resultSetConcurrency); - return new TracingStatement( - statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + final Statement statement = delegate.createStatement(resultSetType, resultSetConcurrency); + return new TracingStatement<>(statement); } @Override public Statement createStatement( int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { final Statement statement = - connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - return new TracingStatement( - statement, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); + return new TracingStatement<>(statement); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { - final PreparedStatement statement = connection.prepareStatement(sql); + final PreparedStatement statement = delegate.prepareStatement(sql); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return new TracingPreparedStatement<>(statement, sql); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { final PreparedStatement statement = - connection.prepareStatement(sql, resultSetType, resultSetConcurrency); + delegate.prepareStatement(sql, resultSetType, resultSetConcurrency); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return new TracingPreparedStatement<>(statement, sql); } @Override @@ -110,50 +90,44 @@ public PreparedStatement prepareStatement( String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { final PreparedStatement statement = - connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return new TracingPreparedStatement<>(statement, sql); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - final PreparedStatement statement = connection.prepareStatement(sql, autoGeneratedKeys); + final PreparedStatement statement = delegate.prepareStatement(sql, autoGeneratedKeys); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return new TracingPreparedStatement<>(statement, sql); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - final PreparedStatement statement = connection.prepareStatement(sql, columnIndexes); + final PreparedStatement statement = delegate.prepareStatement(sql, columnIndexes); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return new TracingPreparedStatement<>(statement, sql); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - final PreparedStatement statement = connection.prepareStatement(sql, columnNames); + final PreparedStatement statement = delegate.prepareStatement(sql, columnNames); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + return new TracingPreparedStatement<>(statement, sql); } @Override public CallableStatement prepareCall(String sql) throws SQLException { - final CallableStatement statement = connection.prepareCall(sql); - return new TracingCallableStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + final CallableStatement statement = delegate.prepareCall(sql); + return new TracingCallableStatement<>(statement, sql); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { final CallableStatement statement = - connection.prepareCall(sql, resultSetType, resultSetConcurrency); - return new TracingCallableStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + delegate.prepareCall(sql, resultSetType, resultSetConcurrency); + return new TracingCallableStatement<>(statement, sql); } @Override @@ -161,220 +135,221 @@ public CallableStatement prepareCall( String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { final CallableStatement statement = - connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - return new TracingCallableStatement( - statement, sql, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + return new TracingCallableStatement(statement, sql); } @Override public void commit() throws SQLException { - connection.commit(); + delegate.commit(); } @SuppressWarnings("UngroupedOverloads") @Override public void rollback() throws SQLException { - connection.rollback(); + delegate.rollback(); } @Override public void close() throws SQLException { - connection.close(); + delegate.close(); } @Override public String nativeSQL(String sql) throws SQLException { - return connection.nativeSQL(sql); + return delegate.nativeSQL(sql); } @Override - public void setAutoCommit(boolean autoCommit) throws SQLException { - connection.setAutoCommit(autoCommit); + public boolean getAutoCommit() throws SQLException { + return delegate.getAutoCommit(); } @Override - public boolean getAutoCommit() throws SQLException { - return connection.getAutoCommit(); + public void setAutoCommit(boolean autoCommit) throws SQLException { + delegate.setAutoCommit(autoCommit); } @Override public boolean isClosed() throws SQLException { - return connection.isClosed(); + return delegate.isClosed(); } @Override public DatabaseMetaData getMetaData() throws SQLException { - return connection.getMetaData(); - } - - @Override - public void setReadOnly(boolean readOnly) throws SQLException { - connection.setReadOnly(readOnly); + return delegate.getMetaData(); } @Override public boolean isReadOnly() throws SQLException { - return connection.isReadOnly(); + return delegate.isReadOnly(); } @Override - public void setCatalog(String catalog) throws SQLException { - connection.setCatalog(catalog); + public void setReadOnly(boolean readOnly) throws SQLException { + delegate.setReadOnly(readOnly); } @Override public String getCatalog() throws SQLException { - return connection.getCatalog(); + return delegate.getCatalog(); } @Override - public void setTransactionIsolation(int level) throws SQLException { - connection.setTransactionIsolation(level); + public void setCatalog(String catalog) throws SQLException { + delegate.setCatalog(catalog); } @Override public int getTransactionIsolation() throws SQLException { - return connection.getTransactionIsolation(); + return delegate.getTransactionIsolation(); + } + + @Override + public void setTransactionIsolation(int level) throws SQLException { + delegate.setTransactionIsolation(level); } @Override public SQLWarning getWarnings() throws SQLException { - return connection.getWarnings(); + return delegate.getWarnings(); } @Override public void clearWarnings() throws SQLException { - connection.clearWarnings(); + delegate.clearWarnings(); } @Override public Map> getTypeMap() throws SQLException { - return connection.getTypeMap(); + return delegate.getTypeMap(); } @Override public void setTypeMap(Map> map) throws SQLException { - connection.setTypeMap(map); + delegate.setTypeMap(map); } @Override - public void setHoldability(int holdability) throws SQLException { - connection.setHoldability(holdability); + public int getHoldability() throws SQLException { + return delegate.getHoldability(); } @Override - public int getHoldability() throws SQLException { - return connection.getHoldability(); + public void setHoldability(int holdability) throws SQLException { + delegate.setHoldability(holdability); } @Override public Savepoint setSavepoint() throws SQLException { - return connection.setSavepoint(); + return delegate.setSavepoint(); } @Override public Savepoint setSavepoint(String name) throws SQLException { - return connection.setSavepoint(name); + return delegate.setSavepoint(name); } @SuppressWarnings("UngroupedOverloads") @Override public void rollback(Savepoint savepoint) throws SQLException { - connection.rollback(savepoint); + delegate.rollback(savepoint); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { - connection.releaseSavepoint(savepoint); + delegate.releaseSavepoint(savepoint); } @Override public Clob createClob() throws SQLException { - return connection.createClob(); + return delegate.createClob(); } @Override public Blob createBlob() throws SQLException { - return connection.createBlob(); + return delegate.createBlob(); } @Override public NClob createNClob() throws SQLException { - return connection.createNClob(); + return delegate.createNClob(); } @Override public SQLXML createSQLXML() throws SQLException { - return connection.createSQLXML(); + return delegate.createSQLXML(); } @Override public boolean isValid(int timeout) throws SQLException { - return connection.isValid(timeout); + return delegate.isValid(timeout); } + @SuppressWarnings("UngroupedOverloads") @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { - connection.setClientInfo(name, value); + delegate.setClientInfo(name, value); } @Override - public void setClientInfo(Properties properties) throws SQLClientInfoException { - connection.setClientInfo(properties); + public String getClientInfo(String name) throws SQLException { + return delegate.getClientInfo(name); } @Override - public String getClientInfo(String name) throws SQLException { - return connection.getClientInfo(name); + public Properties getClientInfo() throws SQLException { + return delegate.getClientInfo(); } + @SuppressWarnings("UngroupedOverloads") @Override - public Properties getClientInfo() throws SQLException { - return connection.getClientInfo(); + public void setClientInfo(Properties properties) throws SQLClientInfoException { + delegate.setClientInfo(properties); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { - return connection.createArrayOf(typeName, elements); + return delegate.createArrayOf(typeName, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { - return connection.createStruct(typeName, attributes); + return delegate.createStruct(typeName, attributes); } @Override - public void setSchema(String schema) throws SQLException { - connection.setSchema(schema); + public String getSchema() throws SQLException { + return delegate.getSchema(); } @Override - public String getSchema() throws SQLException { - return connection.getSchema(); + public void setSchema(String schema) throws SQLException { + delegate.setSchema(schema); } @Override public void abort(Executor executor) throws SQLException { - connection.abort(executor); + delegate.abort(executor); } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { - connection.setNetworkTimeout(executor, milliseconds); + delegate.setNetworkTimeout(executor, milliseconds); } @Override public int getNetworkTimeout() throws SQLException { - return connection.getNetworkTimeout(); + return delegate.getNetworkTimeout(); } @Override public T unwrap(Class iface) throws SQLException { - return connection.unwrap(iface); + return delegate.unwrap(iface); } @Override public boolean isWrapperFor(Class iface) throws SQLException { - return connection.isWrapperFor(iface); + return delegate.isWrapperFor(iface); } } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java index b7614bc1ebee..27a97acbbb8c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java @@ -20,136 +20,73 @@ package io.opentelemetry.instrumentation.jdbc; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.instrumentation.jdbc.parser.URLParser; import java.io.PrintWriter; -import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; -import java.util.Collections; -import java.util.Set; import java.util.logging.Logger; import javax.sql.DataSource; public class TracingDataSource implements DataSource, AutoCloseable { - private static final boolean DEFAULT_WITH_ACTIVE_SPAN_ONLY = false; - private static final Set DEFAULT_IGNORED_STATEMENTS = Collections.emptySet(); + private final DataSource delegate; - private final Tracer tracer; - private final DataSource underlying; - private final ConnectionInfo connectionInfo; - private final boolean withActiveSpanOnly; - private final Set ignoreStatements; - - public TracingDataSource(final Tracer tracer, final DataSource underlying) { - this(tracer, underlying, null, DEFAULT_WITH_ACTIVE_SPAN_ONLY, DEFAULT_IGNORED_STATEMENTS); - } - - public TracingDataSource( - final Tracer tracer, - final DataSource underlying, - final ConnectionInfo connectionInfo, - final boolean withActiveSpanOnly, - final Set ignoreStatements) { - this.tracer = tracer; - this.underlying = underlying; - ConnectionInfo info = connectionInfo; - if (info == null) { - try { - Method method; - try { - method = underlying.getClass().getMethod("getJdbcUrl"); - } catch (NoSuchMethodException e) { - method = underlying.getClass().getMethod("getUrl"); - } - info = URLParser.parse((String) method.invoke(underlying)); - } catch (Exception ignored) { - info = ConnectionInfo.UNKNOWN_CONNECTION_INFO; - } - } - this.connectionInfo = info; - this.withActiveSpanOnly = withActiveSpanOnly; - this.ignoreStatements = ignoreStatements; - } - - public DataSource getUnderlying() { - return underlying; + public TracingDataSource(DataSource delegate) { + this.delegate = delegate; } @Override public Connection getConnection() throws SQLException { - final Connection connection = - JdbcTracingUtils.call( - "AcquireConnection", - underlying::getConnection, - null, - connectionInfo, - withActiveSpanOnly, - null, - tracer); - - return new TracingConnection( - connection, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + final Connection connection = delegate.getConnection(); + return new TracingConnection(connection); } @Override public Connection getConnection(final String username, final String password) throws SQLException { - final Connection connection = - JdbcTracingUtils.call( - "AcquireConnection", - () -> underlying.getConnection(username, password), - null, - connectionInfo, - withActiveSpanOnly, - null, - tracer); - - return new TracingConnection( - connection, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); + final Connection connection = delegate.getConnection(username, password); + return new TracingConnection(connection); } @Override public PrintWriter getLogWriter() throws SQLException { - return underlying.getLogWriter(); + return delegate.getLogWriter(); } @Override public void setLogWriter(final PrintWriter out) throws SQLException { - underlying.setLogWriter(out); + delegate.setLogWriter(out); } @Override - public void setLoginTimeout(final int seconds) throws SQLException { - underlying.setLoginTimeout(seconds); + public int getLoginTimeout() throws SQLException { + return delegate.getLoginTimeout(); } @Override - public int getLoginTimeout() throws SQLException { - return underlying.getLoginTimeout(); + public void setLoginTimeout(final int seconds) throws SQLException { + delegate.setLoginTimeout(seconds); } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { - return underlying.getParentLogger(); + return delegate.getParentLogger(); } @Override public T unwrap(final Class iface) throws SQLException { - return underlying.unwrap(iface); + return delegate.unwrap(iface); } @Override public boolean isWrapperFor(final Class iface) throws SQLException { - return underlying.isWrapperFor(iface); + return delegate.isWrapperFor(iface); } @Override public void close() throws Exception { - if (underlying instanceof AutoCloseable) { - ((AutoCloseable) underlying).close(); + if (delegate instanceof AutoCloseable) { + ((AutoCloseable) delegate).close(); } } } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java index e6ab6187a588..9d75802524c6 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java @@ -20,9 +20,6 @@ package io.opentelemetry.instrumentation.jdbc; -import io.opentelemetry.api.GlobalOpenTelemetry; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.instrumentation.jdbc.parser.URLParser; import io.opentelemetry.javaagent.instrumentation.jdbc.DbInfo; import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcConnectionUrlParser; import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcMaps; @@ -31,44 +28,31 @@ import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; -import java.util.HashSet; import java.util.List; import java.util.Properties; -import java.util.Set; import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import org.checkerframework.checker.nullness.qual.Nullable; public class TracingDriver implements Driver { - private static final Driver INSTANCE = new TracingDriver(); + private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; - protected static final String TRACE_WITH_ACTIVE_SPAN_ONLY = "traceWithActiveSpanOnly"; + private static final TracingDriver INSTANCE = new TracingDriver(); - protected static final String WITH_ACTIVE_SPAN_ONLY = TRACE_WITH_ACTIVE_SPAN_ONLY + "=true"; - - public static final String IGNORE_FOR_TRACING_REGEX = - "ignoreForTracing=\"((?:\\\\\"|[^\"])*)\"[;]*"; - - protected static final Pattern PATTERN_FOR_IGNORING = Pattern.compile(IGNORE_FOR_TRACING_REGEX); + private static boolean registered = false; + private static boolean interceptorMode = false; static { try { - DriverManager.registerDriver(INSTANCE); + register(); } catch (SQLException e) { - throw new IllegalStateException("Could not register TracingDriver with DriverManager", e); + throw new ExceptionInInitializerError(e); } } - /** Returns the singleton instance of the {@code TracingDriver}. */ - public static Driver load() { - return INSTANCE; - } - /** * Ensure {@code TracingDriver} be the first driver of {@link DriverManager} to make sure * "interceptor mode" works. WARNING: Driver like Oracle JDBC may fail since it's destroyed @@ -77,43 +61,31 @@ public static Driver load() { public static synchronized void ensureRegisteredAsTheFirstDriver() { try { Enumeration enumeration = DriverManager.getDrivers(); - List drivers = null; + List drivers = new ArrayList<>(); for (int i = 0; enumeration.hasMoreElements(); ++i) { Driver driver = enumeration.nextElement(); - if (i == 0) { - if (driver == INSTANCE) { - return; - } - drivers = new ArrayList<>(); + if (i == 0 && driver == INSTANCE) { + // the first driver is the tracing driver, skip all this verification + return; } - if (driver != INSTANCE) { + if (driver instanceof TracingDriver) { drivers.add(driver); - DriverManager.deregisterDriver(driver); } + DriverManager.deregisterDriver(driver); } + + // register tracing driver first + register(); + + // register other drivers for (Driver driver : drivers) { DriverManager.registerDriver(driver); } } catch (SQLException e) { - throw new IllegalStateException("Could not register TracingDriver with DriverManager", e); + throw new ExceptionInInitializerError(e); } } - /** - * Sets the {@code traceEnabled} property to enable or disable traces. - * - * @param traceEnabled The {@code traceEnabled} value. - */ - public static void setTraceEnabled(boolean traceEnabled) { - JdbcTracing.setTraceEnabled(traceEnabled); - } - - public static boolean isTraceEnabled() { - return JdbcTracing.isTraceEnabled(); - } - - private static boolean interceptorMode = false; - /** * Turns "interceptor mode" on or off. * @@ -123,32 +95,70 @@ public static void setInterceptorMode(final boolean interceptorMode) { TracingDriver.interceptorMode = interceptorMode; } - private static boolean withActiveSpanOnly; - /** - * Sets the {@code withActiveSpanOnly} property for "interceptor mode". + * Register the driver against {@link DriverManager}. This is done automatically when the class is + * loaded. Dropping the driver from DriverManager's list is possible using {@link #deregister()} + * method. * - * @param withActiveSpanOnly The {@code withActiveSpanOnly} value. + * @throws IllegalStateException if the driver is already registered + * @throws SQLException if registering the driver fails */ - @SuppressWarnings("UngroupedOverloads") - public static void setInterceptorProperty(final boolean withActiveSpanOnly) { - TracingDriver.withActiveSpanOnly = withActiveSpanOnly; + public static void register() throws SQLException { + if (isRegistered()) { + throw new IllegalStateException( + "Driver is already registered. It can only be registered once."); + } + DriverManager.registerDriver(INSTANCE); + TracingDriver.registered = true; } - private static Set ignoreStatements; - /** - * Sets the {@code ignoreStatements} property for "interceptor mode". + * According to JDBC specification, this driver is registered against {@link DriverManager} when + * the class is loaded. To avoid leaks, this method allow unregistering the driver so that the + * class can be gc'ed if necessary. * - * @param ignoreStatements The {@code ignoreStatements} value. + * @throws IllegalStateException if the driver is not registered + * @throws SQLException if deregistering the driver fails */ - @SuppressWarnings("UngroupedOverloads") - public static void setInterceptorProperty(final Set ignoreStatements) { - TracingDriver.ignoreStatements = ignoreStatements; + public static void deregister() throws SQLException { + if (!registered) { + throw new IllegalStateException( + "Driver is not registered (or it has not been registered using Driver.register() method)"); + } + DriverManager.deregisterDriver(INSTANCE); + registered = false; + } + + /** Returns {@code true} if the driver is registered against {@link DriverManager} */ + public static boolean isRegistered() { + return registered; + } + + private static Driver findDriver(String realUrl) throws SQLException { + if (realUrl == null || realUrl.trim().length() == 0) { + throw new IllegalArgumentException("url is required"); + } + + for (Driver candidate : Collections.list(DriverManager.getDrivers())) { + try { + if (!(candidate instanceof TracingDriver) && candidate.acceptsURL(realUrl)) { + return candidate; + } + } catch (SQLException ignored) { + // intentionally ignore exception + } + } + + throw new SQLException("Unable to find a driver that accepts url: " + realUrl); } - protected Tracer tracer; + private static String extractRealUrl(String url) { + return url.startsWith(INTERCEPTOR_MODE_URL_PREFIX) + ? url.replace(INTERCEPTOR_MODE_URL_PREFIX, "jdbc:") + : url; + } + @Nullable @Override public Connection connect(String url, Properties info) throws SQLException { // if there is no url, we have problems @@ -156,47 +166,32 @@ public Connection connect(String url, Properties info) throws SQLException { throw new SQLException("url is required"); } - final Set ignoreStatements; - final boolean withActiveSpanOnly; - if (interceptorMode) { - withActiveSpanOnly = TracingDriver.withActiveSpanOnly; - ignoreStatements = TracingDriver.ignoreStatements; - } else if (acceptsURL(url)) { - withActiveSpanOnly = url.contains(WITH_ACTIVE_SPAN_ONLY); - ignoreStatements = extractIgnoredStatements(url); - } else { + if (!acceptsURL(url)) { return null; } - url = extractRealUrl(url); + final String realUrl = extractRealUrl(url); // find the real driver for the URL - final Driver wrappedDriver = findDriver(url); - - final Tracer currentTracer = getTracer(); - final ConnectionInfo connectionInfo = URLParser.parse(url); - final String realUrl = url; - final Connection connection = - JdbcTracingUtils.call( - "AcquireConnection", - () -> wrappedDriver.connect(realUrl, info), - null, - connectionInfo, - withActiveSpanOnly, - null, - currentTracer); - - DbInfo dbInfo = JdbcConnectionUrlParser.parse(url, info); + final Driver wrappedDriver = findDriver(realUrl); + + final Connection connection = wrappedDriver.connect(realUrl, info); + + final DbInfo dbInfo = JdbcConnectionUrlParser.parse(realUrl, info); JdbcMaps.connectionInfo.put(connection, dbInfo); - return new TracingConnection( - connection, connectionInfo, withActiveSpanOnly, ignoreStatements, currentTracer); + return new TracingConnection(connection); } @Override public boolean acceptsURL(String url) { - return url != null - && (url.startsWith(getUrlPrefix()) || (interceptorMode && url.startsWith("jdbc:"))); + if (url == null) { + return false; + } + if (url.startsWith(INTERCEPTOR_MODE_URL_PREFIX)) { + return true; + } + return interceptorMode && url.startsWith("jdbc:"); } @Override @@ -206,80 +201,22 @@ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws @Override public int getMajorVersion() { - // There is no way to get it from wrapped driver return 1; } @Override public int getMinorVersion() { - // There is no way to get it from wrapped driver - return 0; + return 4; } + /** Returns {@literal false} because not all delegated drivers are JDBC compliant. */ @Override public boolean jdbcCompliant() { - return true; + return false; } @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - // There is no way to get it from wrapped driver + public Logger getParentLogger() { return null; } - - public void setTracer(Tracer tracer) { - this.tracer = tracer; - } - - protected String getUrlPrefix() { - return "jdbc:tracing:"; - } - - protected Driver findDriver(String realUrl) throws SQLException { - if (realUrl == null || realUrl.trim().length() == 0) { - throw new IllegalArgumentException("url is required"); - } - - for (Driver candidate : Collections.list(DriverManager.getDrivers())) { - try { - if (!(candidate instanceof TracingDriver) && candidate.acceptsURL(realUrl)) { - return candidate; - } - } catch (SQLException ignored) { - // intentionally ignore exception - } - } - - throw new SQLException("Unable to find a driver that accepts url: " + realUrl); - } - - protected String extractRealUrl(String url) { - String extracted = url.startsWith(getUrlPrefix()) ? url.replace(getUrlPrefix(), "jdbc:") : url; - return extracted - .replaceAll(TRACE_WITH_ACTIVE_SPAN_ONLY + "=(true|false)[;]*", "") - .replaceAll(IGNORE_FOR_TRACING_REGEX, "") - .replaceAll("\\?$", ""); - } - - protected Set extractIgnoredStatements(String url) { - - final Matcher matcher = PATTERN_FOR_IGNORING.matcher(url); - - Set results = new HashSet<>(8); - - while (matcher.find()) { - String rawValue = matcher.group(1); - String finalValue = rawValue.replace("\\\"", "\""); - results.add(finalValue); - } - - return results; - } - - Tracer getTracer() { - if (tracer == null) { - return GlobalOpenTelemetry.get().getTracer("opentelemetry-jdbc", "0.1.0"); - } - return tracer; - } } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java index c85b345838b0..4dd5b780a85b 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java @@ -20,7 +20,12 @@ package io.opentelemetry.instrumentation.jdbc; -import io.opentelemetry.api.trace.Tracer; +import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; + +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; +import io.opentelemetry.javaagent.instrumentation.jdbc.DbRequest; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; @@ -38,330 +43,356 @@ import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLXML; +import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; -import java.util.Set; - -public class TracingPreparedStatement extends TracingStatement implements PreparedStatement { - - private final PreparedStatement preparedStatement; - public TracingPreparedStatement( - PreparedStatement preparedStatement, - String query, - ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, - Set ignoreStatements, - Tracer tracer) { - super(preparedStatement, query, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); - this.preparedStatement = preparedStatement; +class TracingPreparedStatement extends TracingStatement + implements PreparedStatement { + + public TracingPreparedStatement(S preparedStatement, String query) { + super(preparedStatement, query); + } + + private static T executePreparedStatement( + PreparedStatement preparedStatement, CheckedCallable callable) throws E { + // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info + // this happens before the DB CLIENT span is started (and put in the current context), so this + // instrumentation runs again and the shouldStartSpan() check always returns true - and so on + // until we get a StackOverflowError + // using CallDepth prevents this, because this check happens before Connection#getMetadata() + // is called - the first recursive Statement call is just skipped and we do not create a span + // for it + if (CallDepthThreadLocalMap.getCallDepth(Statement.class).getAndIncrement() > 0) { + return callable.call(); + } + + try { + Context parentContext = Context.current(); + DbRequest request = DbRequest.create(preparedStatement); + + if (request == null || !instrumenter().shouldStart(parentContext, request)) { + return callable.call(); + } + + Context context = instrumenter().start(parentContext, request); + T result; + try (Scope ignored = context.makeCurrent()) { + result = callable.call(); + } catch (Throwable t) { + instrumenter().end(context, request, null, t); + throw t; + } + instrumenter().end(context, request, null, null); + return result; + } finally { + CallDepthThreadLocalMap.reset(Statement.class); + } } @Override public ResultSet executeQuery() throws SQLException { - return JdbcTracingUtils.executePreparedStatement( - preparedStatement, preparedStatement::executeQuery); + return executePreparedStatement(delegate, delegate::executeQuery); } @Override public int executeUpdate() throws SQLException { - return JdbcTracingUtils.executePreparedStatement( - preparedStatement, preparedStatement::executeUpdate); + return executePreparedStatement(delegate, delegate::executeUpdate); } @Override public boolean execute() throws SQLException { - return JdbcTracingUtils.executePreparedStatement(preparedStatement, preparedStatement::execute); + return executePreparedStatement(delegate, delegate::execute); } @SuppressWarnings("UngroupedOverloads") @Override public void setNull(int parameterIndex, int sqlType) throws SQLException { - preparedStatement.setNull(parameterIndex, sqlType); + delegate.setNull(parameterIndex, sqlType); } @Override public void setBoolean(int parameterIndex, boolean x) throws SQLException { - preparedStatement.setBoolean(parameterIndex, x); + delegate.setBoolean(parameterIndex, x); } @Override public void setByte(int parameterIndex, byte x) throws SQLException { - preparedStatement.setByte(parameterIndex, x); + delegate.setByte(parameterIndex, x); } @Override public void setShort(int parameterIndex, short x) throws SQLException { - preparedStatement.setShort(parameterIndex, x); + delegate.setShort(parameterIndex, x); } @Override public void setInt(int parameterIndex, int x) throws SQLException { - preparedStatement.setInt(parameterIndex, x); + delegate.setInt(parameterIndex, x); } @Override public void setLong(int parameterIndex, long x) throws SQLException { - preparedStatement.setLong(parameterIndex, x); + delegate.setLong(parameterIndex, x); } @Override public void setFloat(int parameterIndex, float x) throws SQLException { - preparedStatement.setFloat(parameterIndex, x); + delegate.setFloat(parameterIndex, x); } @Override public void setDouble(int parameterIndex, double x) throws SQLException { - preparedStatement.setDouble(parameterIndex, x); + delegate.setDouble(parameterIndex, x); } @Override public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { - preparedStatement.setBigDecimal(parameterIndex, x); + delegate.setBigDecimal(parameterIndex, x); } @Override public void setString(int parameterIndex, String x) throws SQLException { - preparedStatement.setString(parameterIndex, x); + delegate.setString(parameterIndex, x); } @Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { - preparedStatement.setBytes(parameterIndex, x); + delegate.setBytes(parameterIndex, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setDate(int parameterIndex, Date x) throws SQLException { - preparedStatement.setDate(parameterIndex, x); + delegate.setDate(parameterIndex, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setTime(int parameterIndex, Time x) throws SQLException { - preparedStatement.setTime(parameterIndex, x); + delegate.setTime(parameterIndex, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { - preparedStatement.setTimestamp(parameterIndex, x); + delegate.setTimestamp(parameterIndex, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { - preparedStatement.setAsciiStream(parameterIndex, x, length); + delegate.setAsciiStream(parameterIndex, x, length); } @Override @Deprecated public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { - preparedStatement.setUnicodeStream(parameterIndex, x, length); + delegate.setUnicodeStream(parameterIndex, x, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { - preparedStatement.setBinaryStream(parameterIndex, x, length); + delegate.setBinaryStream(parameterIndex, x, length); } @Override public void clearParameters() throws SQLException { - preparedStatement.clearParameters(); + delegate.clearParameters(); } @SuppressWarnings("UngroupedOverloads") @Override public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { - preparedStatement.setObject(parameterIndex, x, targetSqlType); + delegate.setObject(parameterIndex, x, targetSqlType); } @SuppressWarnings("UngroupedOverloads") @Override public void setObject(int parameterIndex, Object x) throws SQLException { - preparedStatement.setObject(parameterIndex, x); + delegate.setObject(parameterIndex, x); } @Override public void addBatch() throws SQLException { - preparedStatement.addBatch(); + delegate.addBatch(); } @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { - preparedStatement.setCharacterStream(parameterIndex, reader, length); + delegate.setCharacterStream(parameterIndex, reader, length); } @Override public void setRef(int parameterIndex, Ref x) throws SQLException { - preparedStatement.setRef(parameterIndex, x); + delegate.setRef(parameterIndex, x); } @Override public void setBlob(int parameterIndex, Blob x) throws SQLException { - preparedStatement.setBlob(parameterIndex, x); + delegate.setBlob(parameterIndex, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setClob(int parameterIndex, Clob x) throws SQLException { - preparedStatement.setClob(parameterIndex, x); + delegate.setClob(parameterIndex, x); } @Override public void setArray(int parameterIndex, Array x) throws SQLException { - preparedStatement.setArray(parameterIndex, x); + delegate.setArray(parameterIndex, x); } @Override public ResultSetMetaData getMetaData() throws SQLException { - return preparedStatement.getMetaData(); + return delegate.getMetaData(); } @SuppressWarnings("UngroupedOverloads") @Override public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { - preparedStatement.setDate(parameterIndex, x, cal); + delegate.setDate(parameterIndex, x, cal); } @Override public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { - preparedStatement.setTime(parameterIndex, x, cal); + delegate.setTime(parameterIndex, x, cal); } @SuppressWarnings("UngroupedOverloads") @Override public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { - preparedStatement.setTimestamp(parameterIndex, x, cal); + delegate.setTimestamp(parameterIndex, x, cal); } @SuppressWarnings("UngroupedOverloads") @Override public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { - preparedStatement.setNull(parameterIndex, sqlType, typeName); + delegate.setNull(parameterIndex, sqlType, typeName); } @Override public void setURL(int parameterIndex, URL x) throws SQLException { - preparedStatement.setURL(parameterIndex, x); + delegate.setURL(parameterIndex, x); } @Override public ParameterMetaData getParameterMetaData() throws SQLException { - return preparedStatement.getParameterMetaData(); + return delegate.getParameterMetaData(); } @Override public void setRowId(int parameterIndex, RowId x) throws SQLException { - preparedStatement.setRowId(parameterIndex, x); + delegate.setRowId(parameterIndex, x); } @Override public void setNString(int parameterIndex, String value) throws SQLException { - preparedStatement.setNString(parameterIndex, value); + delegate.setNString(parameterIndex, value); } @SuppressWarnings("UngroupedOverloads") @Override public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { - preparedStatement.setNCharacterStream(parameterIndex, value, length); + delegate.setNCharacterStream(parameterIndex, value, length); } @Override public void setNClob(int parameterIndex, NClob value) throws SQLException { - preparedStatement.setNClob(parameterIndex, value); + delegate.setNClob(parameterIndex, value); } @SuppressWarnings("UngroupedOverloads") @Override public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { - preparedStatement.setClob(parameterIndex, reader, length); + delegate.setClob(parameterIndex, reader, length); } @Override public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { - preparedStatement.setBlob(parameterIndex, inputStream, length); + delegate.setBlob(parameterIndex, inputStream, length); } @Override public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { - preparedStatement.setNClob(parameterIndex, reader, length); + delegate.setNClob(parameterIndex, reader, length); } @Override public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { - preparedStatement.setSQLXML(parameterIndex, xmlObject); + delegate.setSQLXML(parameterIndex, xmlObject); } @Override public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { - preparedStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength); + delegate.setObject(parameterIndex, x, targetSqlType, scaleOrLength); } @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { - preparedStatement.setAsciiStream(parameterIndex, x, length); + delegate.setAsciiStream(parameterIndex, x, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { - preparedStatement.setBinaryStream(parameterIndex, x, length); + delegate.setBinaryStream(parameterIndex, x, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { - preparedStatement.setCharacterStream(parameterIndex, reader, length); + delegate.setCharacterStream(parameterIndex, reader, length); } @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { - preparedStatement.setAsciiStream(parameterIndex, x); + delegate.setAsciiStream(parameterIndex, x); } @SuppressWarnings("UngroupedOverloads") @Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { - preparedStatement.setBinaryStream(parameterIndex, x); + delegate.setBinaryStream(parameterIndex, x); } @Override public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { - preparedStatement.setCharacterStream(parameterIndex, reader); + delegate.setCharacterStream(parameterIndex, reader); } @SuppressWarnings("UngroupedOverloads") @Override public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { - preparedStatement.setNCharacterStream(parameterIndex, value); + delegate.setNCharacterStream(parameterIndex, value); } @SuppressWarnings("UngroupedOverloads") @Override public void setClob(int parameterIndex, Reader reader) throws SQLException { - preparedStatement.setClob(parameterIndex, reader); + delegate.setClob(parameterIndex, reader); } @SuppressWarnings("UngroupedOverloads") @Override public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { - preparedStatement.setBlob(parameterIndex, inputStream); + delegate.setBlob(parameterIndex, inputStream); } @SuppressWarnings("UngroupedOverloads") @Override public void setNClob(int parameterIndex, Reader reader) throws SQLException { - preparedStatement.setNClob(parameterIndex, reader); + delegate.setNClob(parameterIndex, reader); } } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java index caf809d0ce2c..8fa978c91483 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java @@ -20,286 +20,292 @@ package io.opentelemetry.instrumentation.jdbc; -import io.opentelemetry.api.trace.Tracer; +import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; + +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; +import io.opentelemetry.javaagent.instrumentation.jdbc.DbRequest; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; import java.util.ArrayList; -import java.util.Set; -public class TracingStatement implements Statement { +class TracingStatement implements Statement { - private final Statement statement; + protected final S delegate; private final String query; + private final ArrayList batchCommands = new ArrayList<>(); - final ConnectionInfo connectionInfo; - final boolean withActiveSpanOnly; - final Set ignoreStatements; - final Tracer tracer; - - TracingStatement( - Statement statement, - ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, - Set ignoreStatements, - Tracer tracer) { - this(statement, null, connectionInfo, withActiveSpanOnly, ignoreStatements, tracer); - } - - TracingStatement( - Statement statement, - String query, - ConnectionInfo connectionInfo, - boolean withActiveSpanOnly, - Set ignoreStatements, - Tracer tracer) { - this.statement = statement; + + TracingStatement(S delegate) { + this(delegate, null); + } + + TracingStatement(S delegate, String query) { + this.delegate = delegate; this.query = query; - this.connectionInfo = connectionInfo; - this.withActiveSpanOnly = withActiveSpanOnly; - this.ignoreStatements = ignoreStatements; - this.tracer = tracer; + } + + private static T executeStatement( + Statement statement, String sql, CheckedCallable callable) throws E { + // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info + // this happens before the DB CLIENT span is started (and put in the current context), so this + // instrumentation runs again and the shouldStartSpan() check always returns true - and so on + // until we get a StackOverflowError + // using CallDepth prevents this, because this check happens before Connection#getMetadata() + // is called - the first recursive Statement call is just skipped and we do not create a span + // for it + if (CallDepthThreadLocalMap.getCallDepth(Statement.class).getAndIncrement() > 0) { + return callable.call(); + } + + try { + Context parentContext = Context.current(); + DbRequest request = DbRequest.create(statement, sql); + + if (request == null || !instrumenter().shouldStart(parentContext, request)) { + return callable.call(); + } + + Context context = instrumenter().start(parentContext, request); + T result; + try (Scope ignored = context.makeCurrent()) { + result = callable.call(); + } catch (Throwable t) { + instrumenter().end(context, request, null, t); + throw t; + } + instrumenter().end(context, request, null, null); + return result; + } finally { + CallDepthThreadLocalMap.reset(Statement.class); + } } @Override public ResultSet executeQuery(String sql) throws SQLException { - return JdbcTracingUtils.executeStatement(statement, sql, () -> statement.executeQuery(sql)); + return executeStatement(delegate, sql, () -> delegate.executeQuery(sql)); } @Override public int executeUpdate(String sql) throws SQLException { - return JdbcTracingUtils.executeStatement(statement, sql, () -> statement.executeUpdate(sql)); + return executeStatement(delegate, sql, () -> delegate.executeUpdate(sql)); } @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - return JdbcTracingUtils.executeStatement( - statement, sql, () -> statement.executeUpdate(sql, autoGeneratedKeys)); + return executeStatement(delegate, sql, () -> delegate.executeUpdate(sql, autoGeneratedKeys)); } @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - return JdbcTracingUtils.executeStatement( - statement, sql, () -> statement.executeUpdate(sql, columnIndexes)); + return executeStatement(delegate, sql, () -> delegate.executeUpdate(sql, columnIndexes)); } @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { - return JdbcTracingUtils.executeStatement( - statement, sql, () -> statement.executeUpdate(sql, columnNames)); + return executeStatement(delegate, sql, () -> delegate.executeUpdate(sql, columnNames)); } @Override public boolean execute(String sql) throws SQLException { - return JdbcTracingUtils.executeStatement(statement, sql, () -> statement.execute(sql)); + return executeStatement(delegate, sql, () -> delegate.execute(sql)); } @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return JdbcTracingUtils.executeStatement( - statement, sql, () -> statement.execute(sql, autoGeneratedKeys)); + return executeStatement(delegate, sql, () -> delegate.execute(sql, autoGeneratedKeys)); } @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { - return JdbcTracingUtils.executeStatement( - statement, sql, () -> statement.execute(sql, columnIndexes)); + return executeStatement(delegate, sql, () -> delegate.execute(sql, columnIndexes)); } @Override public boolean execute(String sql, String[] columnNames) throws SQLException { - return JdbcTracingUtils.executeStatement( - statement, sql, () -> statement.execute(sql, columnNames)); + return executeStatement(delegate, sql, () -> delegate.execute(sql, columnNames)); } @Override public int[] executeBatch() throws SQLException { - return JdbcTracingUtils.executeStatement( - statement, buildSqlForBatch(), statement::executeBatch); + return executeStatement(delegate, buildSqlForBatch(), delegate::executeBatch); } @Override public void close() throws SQLException { - statement.close(); + delegate.close(); } @Override public int getMaxFieldSize() throws SQLException { - return statement.getMaxFieldSize(); + return delegate.getMaxFieldSize(); } @Override public void setMaxFieldSize(int max) throws SQLException { - statement.setMaxFieldSize(max); + delegate.setMaxFieldSize(max); } @Override public int getMaxRows() throws SQLException { - return statement.getMaxRows(); + return delegate.getMaxRows(); } @Override public void setMaxRows(int max) throws SQLException { - statement.setMaxRows(max); + delegate.setMaxRows(max); } @Override public void setEscapeProcessing(boolean enable) throws SQLException { - statement.setEscapeProcessing(enable); + delegate.setEscapeProcessing(enable); } @Override public int getQueryTimeout() throws SQLException { - return statement.getQueryTimeout(); + return delegate.getQueryTimeout(); } @Override public void setQueryTimeout(int seconds) throws SQLException { - statement.setQueryTimeout(seconds); + delegate.setQueryTimeout(seconds); } @Override public void cancel() throws SQLException { - statement.cancel(); + delegate.cancel(); } @Override public SQLWarning getWarnings() throws SQLException { - return statement.getWarnings(); + return delegate.getWarnings(); } @Override public void clearWarnings() throws SQLException { - statement.clearWarnings(); + delegate.clearWarnings(); } @Override public void setCursorName(String name) throws SQLException { - statement.setCursorName(name); + delegate.setCursorName(name); } @Override public ResultSet getResultSet() throws SQLException { - return statement.getResultSet(); + return delegate.getResultSet(); } @Override public int getUpdateCount() throws SQLException { - return statement.getUpdateCount(); + return delegate.getUpdateCount(); } @Override public boolean getMoreResults() throws SQLException { - return statement.getMoreResults(); + return delegate.getMoreResults(); } @Override - public void setFetchDirection(int direction) throws SQLException { - statement.setFetchDirection(direction); + public int getFetchDirection() throws SQLException { + return delegate.getFetchDirection(); } @Override - public int getFetchDirection() throws SQLException { - return statement.getFetchDirection(); + public void setFetchDirection(int direction) throws SQLException { + delegate.setFetchDirection(direction); } @Override - public void setFetchSize(int rows) throws SQLException { - statement.setFetchSize(rows); + public int getFetchSize() throws SQLException { + return delegate.getFetchSize(); } @Override - public int getFetchSize() throws SQLException { - return statement.getFetchSize(); + public void setFetchSize(int rows) throws SQLException { + delegate.setFetchSize(rows); } @Override public int getResultSetConcurrency() throws SQLException { - return statement.getResultSetConcurrency(); + return delegate.getResultSetConcurrency(); } @Override public int getResultSetType() throws SQLException { - return statement.getResultSetType(); + return delegate.getResultSetType(); } @Override public void addBatch(String sql) throws SQLException { - statement.addBatch(sql); + delegate.addBatch(sql); batchCommands.add(sql); } @Override public void clearBatch() throws SQLException { - statement.clearBatch(); + delegate.clearBatch(); batchCommands.clear(); } @Override public Connection getConnection() throws SQLException { - return statement.getConnection(); + return delegate.getConnection(); } @SuppressWarnings("UngroupedOverloads") @Override public boolean getMoreResults(int current) throws SQLException { - return statement.getMoreResults(current); + return delegate.getMoreResults(current); } @Override public ResultSet getGeneratedKeys() throws SQLException { - return statement.getGeneratedKeys(); + return delegate.getGeneratedKeys(); } @Override public int getResultSetHoldability() throws SQLException { - return statement.getResultSetHoldability(); + return delegate.getResultSetHoldability(); } @Override public boolean isClosed() throws SQLException { - return statement.isClosed(); + return delegate.isClosed(); } @Override - public void setPoolable(boolean poolable) throws SQLException { - statement.setPoolable(poolable); + public boolean isPoolable() throws SQLException { + return delegate.isPoolable(); } @Override - public boolean isPoolable() throws SQLException { - return statement.isPoolable(); + public void setPoolable(boolean poolable) throws SQLException { + delegate.setPoolable(poolable); } @Override public void closeOnCompletion() throws SQLException { - statement.closeOnCompletion(); + delegate.closeOnCompletion(); } @Override public boolean isCloseOnCompletion() throws SQLException { - return statement.isCloseOnCompletion(); + return delegate.isCloseOnCompletion(); } @Override public T unwrap(Class iface) throws SQLException { - return statement.unwrap(iface); + return delegate.unwrap(iface); } @Override public boolean isWrapperFor(Class iface) throws SQLException { - return statement.isWrapperFor(iface); - } - - public String getQuery() { - return query; - } - - @Override - public String toString() { - return getQuery(); + return delegate.isWrapperFor(iface); } private String buildSqlForBatch() { diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java deleted file mode 100644 index 9c0d8afb0a58..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AS400URLParser.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import java.util.regex.Pattern; - -/** - * Parser for AS400 - * - * @author oburgosm - * @since 0.2.12 - */ -public class AS400URLParser extends AbstractMatcherURLParser { - - private static final Pattern AS400_URL_PATTERN = - Pattern.compile( - "jdbc:as400:\\/\\/(?[^\\/;]+)(\\/(?[^;\\/]*))?\\/?(;(?.*))?"); - - private static final String AS400_TYPE = "as400"; - - public AS400URLParser() { - super(AS400_URL_PATTERN, AS400_TYPE); - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java deleted file mode 100644 index e90d40863b61..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractMatcherURLParser.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Parser based on regular expression - * - * @author oburgosm - * @since 0.2.12 - */ -public abstract class AbstractMatcherURLParser implements ConnectionURLParser { - - private final Pattern pattern; - - private final String dbType; - - protected AbstractMatcherURLParser(Pattern pattern, String dbType) { - this.pattern = pattern; - this.dbType = dbType; - } - - /** - * Useful to modify ConnectionInfo before build - * - * @param matcher The matcher to apply. Note that the matcher must have a group named host, and - * optionally, a group named port and another named instance - */ - protected ConnectionInfo.Builder initBuilder(Matcher matcher) { - String host = matcher.group("host"); - String port = null; - try { - port = matcher.group("port"); - } catch (IllegalArgumentException e) { - // The pattern has no instance port - } - ConnectionInfo.Builder builder; - if (port == null || "".equals(port)) { - builder = new ConnectionInfo.Builder(host); - } else { - builder = new ConnectionInfo.Builder(host, Integer.valueOf(port)); - } - String instance = ConnectionInfo.UNKNOWN_CONNECTION_INFO.getDbInstance(); - try { - instance = matcher.group("instance"); - if (instance == null || "".equals(instance)) { - instance = ConnectionInfo.UNKNOWN_CONNECTION_INFO.getDbInstance(); - } - } catch (IllegalArgumentException e) { - // The pattern has no instance group - } - return builder.dbType(this.dbType).dbInstance(instance); - } - - @Override - public ConnectionInfo parse(String url) { - Matcher matcher = this.pattern.matcher(url); - if (matcher.matches()) { - return this.initBuilder(matcher).build(); - } else { - return ConnectionInfo.UNKNOWN_CONNECTION_INFO; - } - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java deleted file mode 100644 index f0dfad552869..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/AbstractURLParser.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -public abstract class AbstractURLParser implements ConnectionURLParser { - - /** - * Fetch the index range that database host and port from connection url. - * - * @return index range that database hosts. - */ - protected abstract URLLocation fetchDatabaseHostsIndexRange(final String url); - - /** - * Fetch the index range that database name from connection url. - * - * @return index range that database name. - */ - protected abstract URLLocation fetchDatabaseNameIndexRange(final String url); - - /** - * Fetch database host(s) from connection url. - * - * @return database host(s). - */ - protected String fetchDatabaseHostsFromURL(String url) { - URLLocation hostsLocation = fetchDatabaseHostsIndexRange(url); - return url.substring(hostsLocation.startIndex(), hostsLocation.endIndex()); - } - - /** - * Fetch database name from connection url. - * - * @return database name. - */ - protected String fetchDatabaseNameFromURL(String url) { - URLLocation hostsLocation = fetchDatabaseNameIndexRange(url); - return url.substring(hostsLocation.startIndex(), hostsLocation.endIndex()); - } - - /** - * Fetch database name from connection url. - * - * @return database name. - */ - protected String fetchDatabaseNameFromURL(String url, int[] indexRange) { - return url.substring(indexRange[0], indexRange[1]); - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java deleted file mode 100644 index 713027879120..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/ConnectionURLParser.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; - -public interface ConnectionURLParser { - - ConnectionInfo parse(final String url); -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java deleted file mode 100644 index 69ddadfc2527..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/DB2URLParser.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import java.util.regex.Pattern; - -/** - * Parser for DB2 - * - * @author oburgosm - * @since 0.2.12 - */ -public class DB2URLParser extends AbstractMatcherURLParser { - - private static final Pattern DB2_URL_PATTERN = - Pattern.compile( - "jdbc:db2:\\/\\/(?[^:\\/]+)(:(?\\d+))?\\/(?[^:]+)(:(?.*))?"); - - private static final String DB2_TYPE = "db2"; - - public DB2URLParser() { - super(DB2_URL_PATTERN, DB2_TYPE); - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java deleted file mode 100644 index 97d6232c3eb3..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/H2URLParser.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; - -public class H2URLParser extends AbstractURLParser { - - private static final String LOCALHOST = "localhost"; - private static final int DEFAULT_PORT = 8084; - /** Flag that H2 running with memory mode. */ - private static final String MEMORY_MODE_FLAG = "mem"; - /** Flag that H2 running with tcp mode. */ - private static final String TCP_MODE_FLAG = "h2:tcp"; - /** Flag that H2 running with file mode. */ - private static final String FILE_MODE_FLAG = "file"; - /** Flag that H2 running with implicit file mode. */ - private static final String IMPLICIT_FILE_MODE_FLAG = "jdbc:h2"; - - private static final String H2_DB_TYPE = "h2"; - - @Override - protected URLLocation fetchDatabaseHostsIndexRange(String url) { - int hostLabelStartIndex = url.indexOf("//"); - int hostLabelEndIndex = url.indexOf("/", hostLabelStartIndex + 2); - return new URLLocation(hostLabelStartIndex + 2, hostLabelEndIndex); - } - - @Override - protected URLLocation fetchDatabaseNameIndexRange(String url) { - int databaseStartTag = url.lastIndexOf("/"); - int databaseEndTag = url.indexOf(";"); - if (databaseEndTag == -1) { - databaseEndTag = url.length(); - } - return new URLLocation(databaseStartTag + 1, databaseEndTag); - } - - @Override - public ConnectionInfo parse(String url) { - int[] databaseNameRangeIndex = fetchDatabaseNameRangeIndexFromURLForH2FileMode(url); - if (databaseNameRangeIndex != null) { - return new ConnectionInfo.Builder(LOCALHOST, -1) - .dbType(H2_DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)) - .build(); - } - - databaseNameRangeIndex = fetchDatabaseNameRangeIndexFromURLForH2MemMode(url); - if (databaseNameRangeIndex != null) { - return new ConnectionInfo.Builder(LOCALHOST, -1) - .dbType(H2_DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)) - .build(); - } - - databaseNameRangeIndex = fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(url); - if (databaseNameRangeIndex != null) { - return new ConnectionInfo.Builder(LOCALHOST, -1) - .dbType(H2_DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url, databaseNameRangeIndex)) - .build(); - } - - String[] hostAndPort = fetchDatabaseHostsFromURL(url).split(":"); - if (hostAndPort.length == 1) { - return new ConnectionInfo.Builder(hostAndPort[0], DEFAULT_PORT) - .dbType(H2_DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url)) - .build(); - } else { - return new ConnectionInfo.Builder(hostAndPort[0], Integer.valueOf(hostAndPort[1])) - .dbType(H2_DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url)) - .build(); - } - } - - /** - * Fetch range index that the database name from connection url if H2 database running with file - * mode. - * - * @return range index that the database name. - */ - private static int[] fetchDatabaseNameRangeIndexFromURLForH2FileMode(String url) { - int fileLabelIndex = url.indexOf(FILE_MODE_FLAG); - int parameterLabelIndex = url.indexOf(";", fileLabelIndex); - if (parameterLabelIndex == -1) { - parameterLabelIndex = url.length(); - } - - if (fileLabelIndex != -1) { - return new int[] {fileLabelIndex + FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; - } else { - return null; - } - } - - /** - * Fetch range index that the database name from connection url if H2 database running with - * implicit file mode. - * - * @return range index that the database name. - */ - private static int[] fetchDatabaseNameRangeIndexFromURLForH2ImplicitFileMode(String url) { - if (url.contains(TCP_MODE_FLAG)) { - return null; - } - int fileLabelIndex = url.indexOf(IMPLICIT_FILE_MODE_FLAG); - int parameterLabelIndex = url.indexOf(";", fileLabelIndex); - if (parameterLabelIndex == -1) { - parameterLabelIndex = url.length(); - } - - if (fileLabelIndex != -1) { - return new int[] {fileLabelIndex + IMPLICIT_FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; - } else { - return null; - } - } - - /** - * Fetch range index that the database name from connection url if H2 database running with memory - * mode. - * - * @return range index that the database name. - */ - private static int[] fetchDatabaseNameRangeIndexFromURLForH2MemMode(String url) { - int fileLabelIndex = url.indexOf(MEMORY_MODE_FLAG); - int parameterLabelIndex = url.indexOf(";", fileLabelIndex); - if (parameterLabelIndex == -1) { - parameterLabelIndex = url.length(); - } - - if (fileLabelIndex != -1) { - return new int[] {fileLabelIndex + MEMORY_MODE_FLAG.length() + 1, parameterLabelIndex}; - } else { - return null; - } - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java deleted file mode 100644 index 2fffa653e0ec..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MariadbURLParser.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -public class MariadbURLParser extends MysqlURLParser { - - @Override - protected String dbType() { - return "mariadb"; - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java deleted file mode 100644 index 20bc7a2863ed..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/MysqlURLParser.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; - -public class MysqlURLParser extends AbstractURLParser { - - private static final String DEFAULT_HOST = "localhost"; - - private static final int DEFAULT_PORT = 3306; - - protected String dbType() { - return "mysql"; - } - - @Override - protected URLLocation fetchDatabaseHostsIndexRange(String url) { - int hostLabelStartIndex = url.indexOf("//") + 2; - int hostLabelEndIndex = url.indexOf("/", hostLabelStartIndex); - if (hostLabelEndIndex == -1) { - int queryStringStartIndex = url.indexOf("?", hostLabelStartIndex); - if (queryStringStartIndex == -1) { - hostLabelEndIndex = url.length(); - } else { - hostLabelEndIndex = queryStringStartIndex; - } - } - return new URLLocation(hostLabelStartIndex, hostLabelEndIndex); - } - - protected String fetchDatabaseNameFromURL(String url, int startSize) { - URLLocation hostsLocation = fetchDatabaseNameIndexRange(url, startSize); - if (hostsLocation == null) { - return ""; - } - return url.substring(hostsLocation.startIndex(), hostsLocation.endIndex()); - } - - protected URLLocation fetchDatabaseNameIndexRange(String url, int startSize) { - int databaseStartTag = url.indexOf("/", startSize); - if (databaseStartTag == -1) { - return null; - } - int databaseEndTag = url.indexOf("?", databaseStartTag); - if (databaseEndTag == -1) { - databaseEndTag = url.length(); - } - return new URLLocation(databaseStartTag + 1, databaseEndTag); - } - - @Override - protected URLLocation fetchDatabaseNameIndexRange(String url) { - int databaseStartTag = url.lastIndexOf("/"); - int databaseEndTag = url.indexOf("?", databaseStartTag); - if (databaseEndTag == -1) { - databaseEndTag = url.length(); - } - return new URLLocation(databaseStartTag + 1, databaseEndTag); - } - - @Override - public ConnectionInfo parse(String url) { - URLLocation location = fetchDatabaseHostsIndexRange(url); - String hosts = url.substring(location.startIndex(), location.endIndex()); - if (hosts.isEmpty()) { - hosts = DEFAULT_HOST; - } - String[] hostSegment = hosts.split(","); - if (hostSegment.length > 1) { - StringBuilder sb = new StringBuilder(); - for (String host : hostSegment) { - if (host.split(":").length == 1) { - sb.append(host + ":" + DEFAULT_PORT + ","); - } else { - sb.append(host + ","); - } - } - if (',' == sb.charAt(sb.length() - 1)) { - sb.deleteCharAt(sb.length() - 1); - } - return new ConnectionInfo.Builder(sb.toString()) - .dbType(dbType()) - .dbInstance(fetchDatabaseNameFromURL(url)) - .build(); - } else { - String[] hostAndPort = hostSegment[0].split(":"); - if (hostAndPort.length != 1) { - return new ConnectionInfo.Builder(hostAndPort[0], Integer.valueOf(hostAndPort[1])) - .dbType(dbType()) - .dbInstance(fetchDatabaseNameFromURL(url, location.endIndex())) - .build(); - } else { - - return new ConnectionInfo.Builder(hostAndPort[0], DEFAULT_PORT) - .dbType(dbType()) - .dbInstance(fetchDatabaseNameFromURL(url, location.endIndex())) - .build(); - } - } - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java deleted file mode 100644 index 3cd2f9dcafed..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/OracleURLParser.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class OracleURLParser implements ConnectionURLParser { - - public static final String DB_TYPE = "oracle"; - public static final String PREFIX_THIN = "jdbc:oracle:thin:"; - public static final String PREFIX_OCI = "jdbc:oracle:oci:"; - public static final int DEFAULT_PORT = 1521; - private static final Pattern EASY_CONNECT_PATTERN = - Pattern.compile( - "(?.*)@(?ldap:)?(//)?(?[^:/]+)(?:[0-9]+)?(?[:/][^:/]+)?(?:[^:/]+)?(?/[^:/]+)?"); - - @Override - public ConnectionInfo parse(final String url) { - if (url != null) { - String lowerCaseUrl = url.toLowerCase(); - if ((lowerCaseUrl.startsWith(PREFIX_THIN) || lowerCaseUrl.startsWith(PREFIX_OCI))) { - String trimmedURL; - if (lowerCaseUrl.startsWith(PREFIX_THIN)) { - trimmedURL = url.substring(PREFIX_THIN.length()); - } else { - trimmedURL = url.substring(PREFIX_OCI.length()); - } - OracleConnectionInfo connectionInfo = parseTnsName(trimmedURL); - if (connectionInfo == null) { - connectionInfo = parseEasyConnect(trimmedURL); - } - if (connectionInfo != null) { - return new ConnectionInfo.Builder(connectionInfo.getDbPeer()) // - .dbType(DB_TYPE) // - .dbInstance(connectionInfo.getDbInstance()) // - .build(); - } - } - } - return null; - } - - private static OracleConnectionInfo parseTnsName(final String url) { - final String hosts = parseDatabaseHostsFromTnsUrl(url); - if (hosts != null) { - final int idxServiceName = url.indexOf("SERVICE_NAME"); - final int start = url.indexOf('=', idxServiceName) + 1; - final int end = url.indexOf(")", start); - final String serviceName = url.substring(start, end); - return new OracleConnectionInfo() // - .setDbPeer(hosts) // - .setDbInstance(serviceName); - } - return null; - } - - public static String parseDatabaseHostsFromTnsUrl(String url) { - int beginIndex = url.indexOf("DESCRIPTION"); - if (beginIndex == -1) { - return null; - } - List hosts = new ArrayList(); - do { - int hostStartIndex = url.indexOf("HOST", beginIndex); - if (hostStartIndex == -1) { - break; - } - int equalStartIndex = url.indexOf("=", hostStartIndex); - int hostEndIndex = url.indexOf(")", hostStartIndex); - String host = url.substring(equalStartIndex + 1, hostEndIndex); - - int port = DEFAULT_PORT; - int portStartIndex = url.indexOf("PORT", hostEndIndex); - int portEndIndex = url.length(); - if (portStartIndex != -1) { - int portEqualStartIndex = url.indexOf("=", portStartIndex); - portEndIndex = url.indexOf(")", portEqualStartIndex); - port = Integer.parseInt(url.substring(portEqualStartIndex + 1, portEndIndex).trim()); - } - hosts.add(host.trim() + ":" + port); - beginIndex = portEndIndex; - } while (true); - return join(",", hosts); - } - - private static String join(String delimiter, List list) { - if (list == null || list.isEmpty()) { - return ""; - } - StringBuilder builder = new StringBuilder(); - for (int i = 0, len = list.size(); i < len; i++) { - if (i == (len - 1)) { - builder.append(list.get(i)); - } else { - builder.append(list.get(i)).append(delimiter); - } - } - return builder.toString(); - } - - /** - * Implementation according to - * https://www.oracle.com/technetwork/database/enterprise-edition/oraclenetservices-neteasyconnect-133058.pdf - * - * @param url the url without the oracle jdbc prefix - * @return the oracle connection info if the url could be parsed, or null otherwise. - */ - public static OracleConnectionInfo parseEasyConnect(final String url) { - final Matcher matcher = EASY_CONNECT_PATTERN.matcher(url); - if (matcher.matches()) { - final OracleConnectionInfo result = new OracleConnectionInfo(); - final String host = matcher.group("host"); - final String portGroup = matcher.group("port"); - final int dbPort = - portGroup != null ? Integer.parseInt(portGroup.substring(1)) : DEFAULT_PORT; - result.setDbPeer(host + ":" + dbPort); - final String service = matcher.group("service"); - if (service != null) { - result.setDbInstance(service.substring(1)); - } else { - result.setDbInstance(host); - } - return result; - } - return null; - } - - public static class OracleConnectionInfo { - - private String dbInstance; - private String dbPeer; - - public String getDbInstance() { - return dbInstance; - } - - public OracleConnectionInfo setDbInstance(final String dbInstance) { - this.dbInstance = dbInstance; - return this; - } - - public String getDbPeer() { - return dbPeer; - } - - public OracleConnectionInfo setDbPeer(final String dbPeer) { - this.dbPeer = dbPeer; - return this; - } - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java deleted file mode 100644 index 98f542d54336..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/PostgreSQLURLParser.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; -import java.net.URI; -import java.net.URISyntaxException; - -public class PostgreSQLURLParser extends AbstractURLParser { - - private static final int DEFAULT_PORT = 5432; - private static final String DB_TYPE = "postgresql"; - - @Override - protected URLLocation fetchDatabaseHostsIndexRange(String url) { - int hostLabelStartIndex = url.indexOf("//"); - int hostLabelEndIndex = url.indexOf("/", hostLabelStartIndex + 2); - return new URLLocation(hostLabelStartIndex + 2, hostLabelEndIndex); - } - - @Override - protected URLLocation fetchDatabaseNameIndexRange(String url) { - int hostLabelStartIndex = url.indexOf("//"); - int hostLabelEndIndex = url.indexOf("/", hostLabelStartIndex + 2); - int databaseStartTag = url.indexOf("/", hostLabelEndIndex); - int databaseEndTag = url.indexOf("?", databaseStartTag); - if (databaseEndTag == -1) { - databaseEndTag = url.length(); - } - return new URLLocation(databaseStartTag + 1, databaseEndTag); - } - - @Override - public ConnectionInfo parse(String url) { - URLLocation location = fetchDatabaseHostsIndexRange(url); - String hosts = url.substring(location.startIndex(), location.endIndex()); - String[] hostSegment = hosts.split(","); - if (hostSegment.length > 1) { - StringBuilder sb = new StringBuilder(); - for (String host : hostSegment) { - URI uri = parseHost(host); - int port = uri.getPort() == -1 ? DEFAULT_PORT : uri.getPort(); - - sb.append(uri.getHost() + ":" + port + ","); - } - if (',' == sb.charAt(sb.length() - 1)) { - sb.deleteCharAt(sb.length() - 1); - } - return new ConnectionInfo.Builder(sb.toString()) - .dbType(DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url)) - .build(); - } else { - URI uri = parseHost(hostSegment[0]); - int port = uri.getPort() == -1 ? DEFAULT_PORT : uri.getPort(); - - return new ConnectionInfo.Builder(uri.getHost(), port) - .dbType(DB_TYPE) - .dbInstance(fetchDatabaseNameFromURL(url)) - .build(); - } - } - - private static URI parseHost(String host) { - try { - return new URI("proto://" + host); - } catch (URISyntaxException e) { - throw new IllegalArgumentException(e); - } - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java deleted file mode 100644 index 9de1d54f92cc..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/SqlServerURLParser.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -public class SqlServerURLParser implements ConnectionURLParser { - - private static final int DEFAULT_PORT = 1433; - - protected String dbType() { - return "sqlserver"; - } - - @Override - public ConnectionInfo parse(String url) { - String serverName = ""; - Integer port = DEFAULT_PORT; - String dbInstance = null; - int hostIndex = url.indexOf("://"); - if (hostIndex <= 0) { - return null; - } - - String[] split = url.split(";", 2); - if (split.length > 1) { - Map props = parseQueryParams(split[1], ";"); - serverName = props.get("serverName"); - dbInstance = props.get("databaseName"); - if (props.containsKey("portNumber")) { - String portNumber = props.get("portNumber"); - try { - port = Integer.parseInt(portNumber); - } catch (NumberFormatException ignored) { - // nothing to do, expected - } - } - } - - String urlServerName = split[0].substring(hostIndex + 3); - if (!urlServerName.isEmpty()) { - serverName = urlServerName; - } - - int portLoc = serverName.indexOf(":"); - if (portLoc > 1) { - port = Integer.parseInt(serverName.substring(portLoc + 1)); - serverName = serverName.substring(0, portLoc); - } - - int instanceLoc = serverName.indexOf("\\"); - if (instanceLoc > 1) { - serverName = serverName.substring(0, instanceLoc); - } - - if (serverName.isEmpty()) { - return null; - } - - return new ConnectionInfo.Builder(serverName, port) - .dbType(dbType()) - .dbInstance(dbInstance) - .build(); - } - - private static Map parseQueryParams(String query, String separator) { - if (query == null || query.isEmpty()) { - return Collections.emptyMap(); - } - Map queryParams = 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), StandardCharsets.UTF_8.name()) - : pair; - if (!queryParams.containsKey(key)) { - String value = - idx > 0 && pair.length() > idx + 1 - ? URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name()) - : null; - queryParams.put(key, value); - } - } catch (UnsupportedEncodingException e) { - // Ignore. - } - } - return queryParams; - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java deleted file mode 100644 index 3226e0e4ebdd..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLLocation.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -public class URLLocation { - - private final int startIndex; - private final int endIndex; - - public URLLocation(int startIndex, int endIndex) { - this.startIndex = startIndex; - this.endIndex = endIndex; - } - - public int startIndex() { - return startIndex; - } - - public int endIndex() { - return endIndex; - } -} diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java deleted file mode 100644 index 41c030402025..000000000000 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/parser/URLParser.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2017-2021 The OpenTracing Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package io.opentelemetry.instrumentation.jdbc.parser; - -import io.opentelemetry.instrumentation.jdbc.ConnectionInfo; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class URLParser { - - private static final Logger log = Logger.getLogger(URLParser.class.getName()); - - private static final String MYSQL_JDBC_URL_PREFIX = "jdbc:mysql"; - private static final String ORACLE_JDBC_URL_PREFIX = "jdbc:oracle"; - private static final String H2_JDBC_URL_PREFIX = "jdbc:h2"; - private static final String POSTGRESQL_JDBC_URL_PREFIX = "jdbc:postgresql"; - private static final String MARIADB_JDBC_URL_PREFIX = "jdbc:mariadb"; - private static final String SQLSERVER_JDBC_URL_PREFIX = "jdbc:sqlserver"; - private static final String DB2_JDBC_URL_PREFIX = "jdbc:db2"; - private static final String AS400_JDBC_URL_PREFIX = "jdbc:as400"; - private static final Map parserRegister = new LinkedHashMap<>(); - - static { - // put mysql parser firstly - parserRegister.put(MYSQL_JDBC_URL_PREFIX, new MysqlURLParser()); - parserRegister.put(ORACLE_JDBC_URL_PREFIX, new OracleURLParser()); - parserRegister.put(H2_JDBC_URL_PREFIX, new H2URLParser()); - parserRegister.put(POSTGRESQL_JDBC_URL_PREFIX, new PostgreSQLURLParser()); - parserRegister.put(MARIADB_JDBC_URL_PREFIX, new MariadbURLParser()); - parserRegister.put(SQLSERVER_JDBC_URL_PREFIX, new SqlServerURLParser()); - parserRegister.put(DB2_JDBC_URL_PREFIX, new DB2URLParser()); - parserRegister.put(AS400_JDBC_URL_PREFIX, new AS400URLParser()); - } - - /** parse the url to the ConnectionInfo */ - @SuppressWarnings("CatchingUnchecked") - public static ConnectionInfo parse(String url) { - if (null == url) { - return ConnectionInfo.UNKNOWN_CONNECTION_INFO; - } - String lowerCaseUrl = url.toLowerCase(); - ConnectionURLParser parser = findURLParser(lowerCaseUrl); - if (parser == null) { - return ConnectionInfo.UNKNOWN_CONNECTION_INFO; - } - try { - return parser.parse(url); - } catch (Exception e) { - log.log(Level.WARNING, "error occurs when parsing jdbc url"); - } - return ConnectionInfo.UNKNOWN_CONNECTION_INFO; - } - - /** @deprecated use {@link #parse(String)} instead */ - @Deprecated - public static ConnectionInfo parser(String url) { - return parse(url); - } - - private static ConnectionURLParser findURLParser(String lowerCaseUrl) { - for (Map.Entry entry : parserRegister.entrySet()) { - if (lowerCaseUrl.startsWith(entry.getKey())) { - return entry.getValue(); - } - } - return null; - } - - /** register new ConnectionURLParser. Can override existing parser. */ - public static void registerConnectionParser(String urlPrefix, ConnectionURLParser parser) { - if (null == urlPrefix || parser == null) { - throw new IllegalArgumentException("urlPrefix and parser can not be null"); - } - parserRegister.put(urlPrefix.toLowerCase(), parser); - } -} From 95bfe7bebc9b881e0160e278148e1c89f4630f40 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 21 Jun 2021 14:22:05 +0800 Subject: [PATCH 17/69] Implemented datasource with tracing support. --- .../instrumentation/jdbc/CheckedCallable.java | 2 +- .../jdbc/TracingPreparedStatement.java | 8 ++--- .../jdbc/TracingStatement.java | 22 ++++++------ .../{ => datasource}/TracingDataSource.java | 36 +++++++++++++++++-- .../DataSourceCodeAttributesExtractor.java | 0 .../jdbc/datasource/DataSourceSingletons.java | 0 6 files changed, 49 insertions(+), 19 deletions(-) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{ => datasource}/TracingDataSource.java (63%) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceCodeAttributesExtractor.java (100%) rename instrumentation/jdbc/{javaagent => library}/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceSingletons.java (100%) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java index 745f939dce5f..651a39953803 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java @@ -6,7 +6,7 @@ package io.opentelemetry.instrumentation.jdbc; @FunctionalInterface -interface CheckedCallable { +public interface CheckedCallable { T call() throws E; } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java index 4dd5b780a85b..ae6dbb5b230f 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java @@ -55,7 +55,7 @@ public TracingPreparedStatement(S preparedStatement, String query) { super(preparedStatement, query); } - private static T executePreparedStatement( + private static T wrapCall( PreparedStatement preparedStatement, CheckedCallable callable) throws E { // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info // this happens before the DB CLIENT span is started (and put in the current context), so this @@ -93,17 +93,17 @@ private static T executePreparedStatement( @Override public ResultSet executeQuery() throws SQLException { - return executePreparedStatement(delegate, delegate::executeQuery); + return wrapCall(delegate, delegate::executeQuery); } @Override public int executeUpdate() throws SQLException { - return executePreparedStatement(delegate, delegate::executeUpdate); + return wrapCall(delegate, delegate::executeUpdate); } @Override public boolean execute() throws SQLException { - return executePreparedStatement(delegate, delegate::execute); + return wrapCall(delegate, delegate::execute); } @SuppressWarnings("UngroupedOverloads") diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java index 8fa978c91483..01c33446d3f9 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java @@ -49,7 +49,7 @@ class TracingStatement implements Statement { this.query = query; } - private static T executeStatement( + private static T wrapCall( Statement statement, String sql, CheckedCallable callable) throws E { // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info // this happens before the DB CLIENT span is started (and put in the current context), so this @@ -87,52 +87,52 @@ private static T executeStatement( @Override public ResultSet executeQuery(String sql) throws SQLException { - return executeStatement(delegate, sql, () -> delegate.executeQuery(sql)); + return wrapCall(delegate, sql, () -> delegate.executeQuery(sql)); } @Override public int executeUpdate(String sql) throws SQLException { - return executeStatement(delegate, sql, () -> delegate.executeUpdate(sql)); + return wrapCall(delegate, sql, () -> delegate.executeUpdate(sql)); } @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - return executeStatement(delegate, sql, () -> delegate.executeUpdate(sql, autoGeneratedKeys)); + return wrapCall(delegate, sql, () -> delegate.executeUpdate(sql, autoGeneratedKeys)); } @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - return executeStatement(delegate, sql, () -> delegate.executeUpdate(sql, columnIndexes)); + return wrapCall(delegate, sql, () -> delegate.executeUpdate(sql, columnIndexes)); } @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { - return executeStatement(delegate, sql, () -> delegate.executeUpdate(sql, columnNames)); + return wrapCall(delegate, sql, () -> delegate.executeUpdate(sql, columnNames)); } @Override public boolean execute(String sql) throws SQLException { - return executeStatement(delegate, sql, () -> delegate.execute(sql)); + return wrapCall(delegate, sql, () -> delegate.execute(sql)); } @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return executeStatement(delegate, sql, () -> delegate.execute(sql, autoGeneratedKeys)); + return wrapCall(delegate, sql, () -> delegate.execute(sql, autoGeneratedKeys)); } @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { - return executeStatement(delegate, sql, () -> delegate.execute(sql, columnIndexes)); + return wrapCall(delegate, sql, () -> delegate.execute(sql, columnIndexes)); } @Override public boolean execute(String sql, String[] columnNames) throws SQLException { - return executeStatement(delegate, sql, () -> delegate.execute(sql, columnNames)); + return wrapCall(delegate, sql, () -> delegate.execute(sql, columnNames)); } @Override public int[] executeBatch() throws SQLException { - return executeStatement(delegate, buildSqlForBatch(), delegate::executeBatch); + return wrapCall(delegate, buildSqlForBatch(), delegate::executeBatch); } @Override diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/TracingDataSource.java similarity index 63% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/TracingDataSource.java index 27a97acbbb8c..7bdb88fce26c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/TracingDataSource.java @@ -18,8 +18,15 @@ * the License. */ -package io.opentelemetry.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.datasource; +import static io.opentelemetry.javaagent.instrumentation.jdbc.datasource.DataSourceSingletons.instrumenter; + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.instrumentation.jdbc.CheckedCallable; +import io.opentelemetry.instrumentation.jdbc.TracingConnection; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; @@ -35,16 +42,39 @@ public TracingDataSource(DataSource delegate) { this.delegate = delegate; } + private static T wrapCall(DataSource ds, + CheckedCallable callable) throws E { + Context parentContext = Context.current(); + + if (!Span.fromContext(parentContext).getSpanContext().isValid()) { + // this instrumentation is already very noisy, and calls to getConnection outside of an + // existing trace do not tend to be very interesting + return callable.call(); + } + + Context context = instrumenter().start(parentContext, ds); + T result; + try (Scope ignored = context.makeCurrent()) { + result = callable.call(); + } catch (Throwable t) { + instrumenter().end(context, ds, null, t); + throw t; + } + instrumenter().end(context, ds, null, null); + return result; + } + @Override public Connection getConnection() throws SQLException { - final Connection connection = delegate.getConnection(); + Connection connection = wrapCall(delegate, delegate::getConnection); return new TracingConnection(connection); } @Override public Connection getConnection(final String username, final String password) throws SQLException { - final Connection connection = delegate.getConnection(username, password); + Connection connection = wrapCall(delegate, + () -> delegate.getConnection(username, password)); return new TracingConnection(connection); } diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceCodeAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceCodeAttributesExtractor.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceCodeAttributesExtractor.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceCodeAttributesExtractor.java diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceSingletons.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceSingletons.java similarity index 100% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceSingletons.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceSingletons.java From 375b7acc052dfa173d3bd9f86559fadf07d99ac1 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 21 Jun 2021 14:25:47 +0800 Subject: [PATCH 18/69] Renamed Tracing prefix with OpenTelemetry. --- ...CallableStatement.java => OpenTelemetryCallableStatement.java} | 0 .../jdbc/{TracingConnection.java => OpenTelemetryConnection.java} | 0 .../jdbc/{TracingDriver.java => OpenTelemetryDriver.java} | 0 ...PreparedStatement.java => OpenTelemetryPreparedStatement.java} | 0 .../jdbc/{TracingStatement.java => OpenTelemetryStatement.java} | 0 .../{TracingDataSource.java => OpenTelemetryDataSource.java} | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{TracingCallableStatement.java => OpenTelemetryCallableStatement.java} (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{TracingConnection.java => OpenTelemetryConnection.java} (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{TracingDriver.java => OpenTelemetryDriver.java} (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{TracingPreparedStatement.java => OpenTelemetryPreparedStatement.java} (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{TracingStatement.java => OpenTelemetryStatement.java} (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/{TracingDataSource.java => OpenTelemetryDataSource.java} (100%) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryCallableStatement.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingCallableStatement.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryCallableStatement.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnection.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingConnection.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnection.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingDriver.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryPreparedStatement.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingPreparedStatement.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryPreparedStatement.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryStatement.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/TracingStatement.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryStatement.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/TracingDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/TracingDataSource.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java From a124016760a3eb55e830e89b6ebb94f6d1873fc8 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 21 Jun 2021 14:25:54 +0800 Subject: [PATCH 19/69] Renamed Tracing prefix with OpenTelemetry. --- .../jdbc/OpenTelemetryCallableStatement.java | 5 ++-- .../jdbc/OpenTelemetryConnection.java | 28 +++++++++---------- .../jdbc/OpenTelemetryDriver.java | 14 +++++----- .../jdbc/OpenTelemetryPreparedStatement.java | 4 +-- .../jdbc/OpenTelemetryStatement.java | 6 ++-- .../datasource/OpenTelemetryDataSource.java | 10 +++---- .../META-INF/services/java.sql.Driver | 2 +- 7 files changed, 35 insertions(+), 34 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryCallableStatement.java index 90050443f00a..34829f2b19d5 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryCallableStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryCallableStatement.java @@ -39,10 +39,11 @@ import java.util.Calendar; import java.util.Map; -class TracingCallableStatement extends TracingPreparedStatement +class OpenTelemetryCallableStatement extends + OpenTelemetryPreparedStatement implements CallableStatement { - public TracingCallableStatement(S callableStatement, String query) { + public OpenTelemetryCallableStatement(S callableStatement, String query) { super(callableStatement, query); } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnection.java index f61b205f06e6..34b3d58616d5 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnection.java @@ -40,25 +40,25 @@ import java.util.Properties; import java.util.concurrent.Executor; -public class TracingConnection implements Connection { +public class OpenTelemetryConnection implements Connection { private final Connection delegate; - public TracingConnection(Connection delegate) { + public OpenTelemetryConnection(Connection delegate) { this.delegate = delegate; } @Override public Statement createStatement() throws SQLException { final Statement statement = delegate.createStatement(); - return new TracingStatement<>(statement); + return new OpenTelemetryStatement<>(statement); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { final Statement statement = delegate.createStatement(resultSetType, resultSetConcurrency); - return new TracingStatement<>(statement); + return new OpenTelemetryStatement<>(statement); } @Override @@ -66,14 +66,14 @@ public Statement createStatement( int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { final Statement statement = delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - return new TracingStatement<>(statement); + return new OpenTelemetryStatement<>(statement); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, sql); } @Override @@ -82,7 +82,7 @@ public PreparedStatement prepareStatement(String sql, int resultSetType, int res final PreparedStatement statement = delegate.prepareStatement(sql, resultSetType, resultSetConcurrency); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, sql); } @Override @@ -92,34 +92,34 @@ public PreparedStatement prepareStatement( final PreparedStatement statement = delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, sql); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql, autoGeneratedKeys); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, sql); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql, columnIndexes); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, sql); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql, columnNames); JdbcMaps.preparedStatements.put(statement, sql); - return new TracingPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, sql); } @Override public CallableStatement prepareCall(String sql) throws SQLException { final CallableStatement statement = delegate.prepareCall(sql); - return new TracingCallableStatement<>(statement, sql); + return new OpenTelemetryCallableStatement<>(statement, sql); } @Override @@ -127,7 +127,7 @@ public CallableStatement prepareCall(String sql, int resultSetType, int resultSe throws SQLException { final CallableStatement statement = delegate.prepareCall(sql, resultSetType, resultSetConcurrency); - return new TracingCallableStatement<>(statement, sql); + return new OpenTelemetryCallableStatement<>(statement, sql); } @Override @@ -136,7 +136,7 @@ public CallableStatement prepareCall( throws SQLException { final CallableStatement statement = delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - return new TracingCallableStatement(statement, sql); + return new OpenTelemetryCallableStatement(statement, sql); } @Override diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 9d75802524c6..b1952fccc328 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -36,11 +36,11 @@ import java.util.logging.Logger; import org.checkerframework.checker.nullness.qual.Nullable; -public class TracingDriver implements Driver { +public class OpenTelemetryDriver implements Driver { private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; - private static final TracingDriver INSTANCE = new TracingDriver(); + private static final OpenTelemetryDriver INSTANCE = new OpenTelemetryDriver(); private static boolean registered = false; private static boolean interceptorMode = false; @@ -68,7 +68,7 @@ public static synchronized void ensureRegisteredAsTheFirstDriver() { // the first driver is the tracing driver, skip all this verification return; } - if (driver instanceof TracingDriver) { + if (driver instanceof OpenTelemetryDriver) { drivers.add(driver); } DriverManager.deregisterDriver(driver); @@ -92,7 +92,7 @@ public static synchronized void ensureRegisteredAsTheFirstDriver() { * @param interceptorMode The {@code interceptorMode} value. */ public static void setInterceptorMode(final boolean interceptorMode) { - TracingDriver.interceptorMode = interceptorMode; + OpenTelemetryDriver.interceptorMode = interceptorMode; } /** @@ -109,7 +109,7 @@ public static void register() throws SQLException { "Driver is already registered. It can only be registered once."); } DriverManager.registerDriver(INSTANCE); - TracingDriver.registered = true; + OpenTelemetryDriver.registered = true; } /** @@ -141,7 +141,7 @@ private static Driver findDriver(String realUrl) throws SQLException { for (Driver candidate : Collections.list(DriverManager.getDrivers())) { try { - if (!(candidate instanceof TracingDriver) && candidate.acceptsURL(realUrl)) { + if (!(candidate instanceof OpenTelemetryDriver) && candidate.acceptsURL(realUrl)) { return candidate; } } catch (SQLException ignored) { @@ -180,7 +180,7 @@ public Connection connect(String url, Properties info) throws SQLException { final DbInfo dbInfo = JdbcConnectionUrlParser.parse(realUrl, info); JdbcMaps.connectionInfo.put(connection, dbInfo); - return new TracingConnection(connection); + return new OpenTelemetryConnection(connection); } @Override diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryPreparedStatement.java index ae6dbb5b230f..14089bf8482d 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryPreparedStatement.java @@ -48,10 +48,10 @@ import java.sql.Timestamp; import java.util.Calendar; -class TracingPreparedStatement extends TracingStatement +class OpenTelemetryPreparedStatement extends OpenTelemetryStatement implements PreparedStatement { - public TracingPreparedStatement(S preparedStatement, String query) { + public OpenTelemetryPreparedStatement(S preparedStatement, String query) { super(preparedStatement, query); } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryStatement.java index 01c33446d3f9..bca9a5d1d80c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryStatement.java @@ -33,18 +33,18 @@ import java.sql.Statement; import java.util.ArrayList; -class TracingStatement implements Statement { +class OpenTelemetryStatement implements Statement { protected final S delegate; private final String query; private final ArrayList batchCommands = new ArrayList<>(); - TracingStatement(S delegate) { + OpenTelemetryStatement(S delegate) { this(delegate, null); } - TracingStatement(S delegate, String query) { + OpenTelemetryStatement(S delegate, String query) { this.delegate = delegate; this.query = query; } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java index 7bdb88fce26c..e518fadd373b 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java @@ -26,7 +26,7 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; import io.opentelemetry.instrumentation.jdbc.CheckedCallable; -import io.opentelemetry.instrumentation.jdbc.TracingConnection; +import io.opentelemetry.instrumentation.jdbc.OpenTelemetryConnection; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; @@ -34,11 +34,11 @@ import java.util.logging.Logger; import javax.sql.DataSource; -public class TracingDataSource implements DataSource, AutoCloseable { +public class OpenTelemetryDataSource implements DataSource, AutoCloseable { private final DataSource delegate; - public TracingDataSource(DataSource delegate) { + public OpenTelemetryDataSource(DataSource delegate) { this.delegate = delegate; } @@ -67,7 +67,7 @@ private static T wrapCall(DataSource ds, @Override public Connection getConnection() throws SQLException { Connection connection = wrapCall(delegate, delegate::getConnection); - return new TracingConnection(connection); + return new OpenTelemetryConnection(connection); } @Override @@ -75,7 +75,7 @@ public Connection getConnection(final String username, final String password) throws SQLException { Connection connection = wrapCall(delegate, () -> delegate.getConnection(username, password)); - return new TracingConnection(connection); + return new OpenTelemetryConnection(connection); } @Override diff --git a/instrumentation/jdbc/library/src/main/resources/META-INF/services/java.sql.Driver b/instrumentation/jdbc/library/src/main/resources/META-INF/services/java.sql.Driver index b67485aeacf7..39bfb3d82f9d 100644 --- a/instrumentation/jdbc/library/src/main/resources/META-INF/services/java.sql.Driver +++ b/instrumentation/jdbc/library/src/main/resources/META-INF/services/java.sql.Driver @@ -1 +1 @@ -io.opentelemetry.instrumentation.jdbc.TracingDriver +io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver From 397bc4b75fcace7396c3658411f4c22b913f220d Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 21 Jun 2021 18:53:49 +0800 Subject: [PATCH 20/69] Moved utilities classes to io.opentelemetry.instrumentation.jdbc.internal subpackage. --- .../instrumentation/jdbc/{ => internal}/CheckedCallable.java | 0 .../jdbc/internal}/DataSourceCodeAttributesExtractor.java | 0 .../jdbc/internal}/DataSourceSingletons.java | 2 +- .../jdbc => instrumentation/jdbc/internal}/DbInfo.java | 0 .../jdbc => instrumentation/jdbc/internal}/DbRequest.java | 0 .../jdbc/internal}/JdbcAttributesExtractor.java | 0 .../jdbc/internal}/JdbcConnectionUrlParser.java | 0 .../jdbc => instrumentation/jdbc/internal}/JdbcMaps.java | 0 .../jdbc/internal}/JdbcNetAttributesExtractor.java | 0 .../jdbc => instrumentation/jdbc/internal}/JdbcSingletons.java | 2 +- .../jdbc => instrumentation/jdbc/internal}/JdbcUtils.java | 0 .../jdbc/{ => internal}/OpenTelemetryCallableStatement.java | 0 .../jdbc/{ => internal}/OpenTelemetryConnection.java | 0 .../jdbc/{ => internal}/OpenTelemetryPreparedStatement.java | 1 + .../jdbc/{ => internal}/OpenTelemetryStatement.java | 1 + 15 files changed, 4 insertions(+), 2 deletions(-) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{ => internal}/CheckedCallable.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc/datasource => instrumentation/jdbc/internal}/DataSourceCodeAttributesExtractor.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc/datasource => instrumentation/jdbc/internal}/DataSourceSingletons.java (98%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc => instrumentation/jdbc/internal}/DbInfo.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc => instrumentation/jdbc/internal}/DbRequest.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc => instrumentation/jdbc/internal}/JdbcAttributesExtractor.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc => instrumentation/jdbc/internal}/JdbcConnectionUrlParser.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc => instrumentation/jdbc/internal}/JdbcMaps.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc => instrumentation/jdbc/internal}/JdbcNetAttributesExtractor.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc => instrumentation/jdbc/internal}/JdbcSingletons.java (98%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/{javaagent/instrumentation/jdbc => instrumentation/jdbc/internal}/JdbcUtils.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{ => internal}/OpenTelemetryCallableStatement.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{ => internal}/OpenTelemetryConnection.java (100%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{ => internal}/OpenTelemetryPreparedStatement.java (99%) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/{ => internal}/OpenTelemetryStatement.java (99%) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/CheckedCallable.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/CheckedCallable.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/CheckedCallable.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceCodeAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceCodeAttributesExtractor.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceCodeAttributesExtractor.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceCodeAttributesExtractor.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceSingletons.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceSingletons.java similarity index 98% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceSingletons.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceSingletons.java index 48f751e33f2f..1338b80fa024 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceSingletons.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceSingletons.java @@ -13,7 +13,7 @@ import javax.sql.DataSource; public final class DataSourceSingletons { - private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jdbc"; + private static final String INSTRUMENTATION_NAME = "io.opentelemetry.jdbc"; private static final Instrumenter INSTRUMENTER; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbInfo.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbRequest.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DbRequest.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcAttributesExtractor.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcConnectionUrlParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParser.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcConnectionUrlParser.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParser.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcMaps.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcMaps.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcMaps.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcMaps.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcNetAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcNetAttributesExtractor.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java similarity index 98% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java index 58c3accf7a4a..1c8c935ce4e2 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java @@ -14,7 +14,7 @@ import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class JdbcSingletons { - private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jdbc"; + private static final String INSTRUMENTATION_NAME = "io.opentelemetry.jdbc"; private static final Instrumenter INSTRUMENTER; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcUtils.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryCallableStatement.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java similarity index 100% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnection.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java similarity index 99% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryPreparedStatement.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java index 14089bf8482d..2ce32c69d25f 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java @@ -24,6 +24,7 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; +import io.opentelemetry.instrumentation.jdbc.internal.CheckedCallable; import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; import io.opentelemetry.javaagent.instrumentation.jdbc.DbRequest; import java.io.InputStream; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java similarity index 99% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryStatement.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java index bca9a5d1d80c..924a9ceecfc9 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java @@ -24,6 +24,7 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; +import io.opentelemetry.instrumentation.jdbc.internal.CheckedCallable; import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; import io.opentelemetry.javaagent.instrumentation.jdbc.DbRequest; import java.sql.Connection; From 09ce33f651da2d37c450ed0a1bb725030b44d984 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 21 Jun 2021 18:59:41 +0800 Subject: [PATCH 21/69] Build fix. --- .../test/groovy/JdbcConnectionUrlParserTest.groovy | 4 ++-- .../jdbc/ConnectionInstrumentation.java | 1 + .../instrumentation/jdbc/DriverInstrumentation.java | 3 +++ .../jdbc/PreparedStatementInstrumentation.java | 3 ++- .../jdbc/StatementInstrumentation.java | 3 ++- .../jdbc/datasource/DataSourceInstrumentation.java | 2 +- .../instrumentation/jdbc/OpenTelemetryDriver.java | 7 ++++--- .../jdbc/datasource/OpenTelemetryDataSource.java | 13 ++++++------- .../jdbc/internal/CheckedCallable.java | 2 +- .../internal/DataSourceCodeAttributesExtractor.java | 2 +- .../jdbc/internal/DataSourceSingletons.java | 2 +- .../instrumentation/jdbc/internal/DbInfo.java | 3 ++- .../instrumentation/jdbc/internal/DbRequest.java | 7 ++++--- .../jdbc/internal/JdbcAttributesExtractor.java | 2 +- .../jdbc/internal/JdbcConnectionUrlParser.java | 4 ++-- .../instrumentation/jdbc/internal/JdbcMaps.java | 2 +- .../jdbc/internal/JdbcNetAttributesExtractor.java | 2 +- .../jdbc/internal/JdbcSingletons.java | 2 +- .../instrumentation/jdbc/internal/JdbcUtils.java | 2 +- .../internal/OpenTelemetryCallableStatement.java | 7 +++---- .../jdbc/internal/OpenTelemetryConnection.java | 3 +-- .../internal/OpenTelemetryPreparedStatement.java | 6 ++---- .../jdbc/internal/OpenTelemetryStatement.java | 6 ++---- 23 files changed, 45 insertions(+), 43 deletions(-) diff --git a/instrumentation/jdbc/javaagent-unit-tests/src/test/groovy/JdbcConnectionUrlParserTest.groovy b/instrumentation/jdbc/javaagent-unit-tests/src/test/groovy/JdbcConnectionUrlParserTest.groovy index d4c1f29e79e3..ed80a249d8c5 100644 --- a/instrumentation/jdbc/javaagent-unit-tests/src/test/groovy/JdbcConnectionUrlParserTest.groovy +++ b/instrumentation/jdbc/javaagent-unit-tests/src/test/groovy/JdbcConnectionUrlParserTest.groovy @@ -3,9 +3,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcConnectionUrlParser.parse +import static io.opentelemetry.instrumentation.jdbc.internal.JdbcConnectionUrlParser.parse -import io.opentelemetry.javaagent.instrumentation.jdbc.DbInfo +import io.opentelemetry.instrumentation.jdbc.internal.DbInfo import spock.lang.Shared import spock.lang.Specification diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/ConnectionInstrumentation.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/ConnectionInstrumentation.java index b3a899937ad5..4f3a9dd5a740 100644 --- a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/ConnectionInstrumentation.java +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/ConnectionInstrumentation.java @@ -12,6 +12,7 @@ import static net.bytebuddy.matcher.ElementMatchers.returns; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; +import io.opentelemetry.instrumentation.jdbc.internal.JdbcMaps; import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation; import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer; import java.sql.PreparedStatement; diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DriverInstrumentation.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DriverInstrumentation.java index 2bc70288036d..d6607e42f91c 100644 --- a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DriverInstrumentation.java +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/DriverInstrumentation.java @@ -12,6 +12,9 @@ import static net.bytebuddy.matcher.ElementMatchers.returns; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; +import io.opentelemetry.instrumentation.jdbc.internal.DbInfo; +import io.opentelemetry.instrumentation.jdbc.internal.JdbcConnectionUrlParser; +import io.opentelemetry.instrumentation.jdbc.internal.JdbcMaps; import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation; import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer; import java.sql.Connection; diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java index 9a704ce0e353..85d025e76273 100644 --- a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java @@ -5,10 +5,10 @@ package io.opentelemetry.javaagent.instrumentation.jdbc; +import static io.opentelemetry.instrumentation.jdbc.internal.JdbcSingletons.instrumenter; import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.implementsInterface; import static io.opentelemetry.javaagent.extension.matcher.ClassLoaderMatcher.hasClassesNamed; import static io.opentelemetry.javaagent.instrumentation.api.Java8BytecodeBridge.currentContext; -import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; import static net.bytebuddy.matcher.ElementMatchers.isPublic; import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith; import static net.bytebuddy.matcher.ElementMatchers.named; @@ -16,6 +16,7 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; +import io.opentelemetry.instrumentation.jdbc.internal.DbRequest; import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation; import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer; import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/StatementInstrumentation.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/StatementInstrumentation.java index 06047d33ba02..1d665596c48f 100644 --- a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/StatementInstrumentation.java +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/StatementInstrumentation.java @@ -5,10 +5,10 @@ package io.opentelemetry.javaagent.instrumentation.jdbc; +import static io.opentelemetry.instrumentation.jdbc.internal.JdbcSingletons.instrumenter; import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.implementsInterface; import static io.opentelemetry.javaagent.extension.matcher.ClassLoaderMatcher.hasClassesNamed; import static io.opentelemetry.javaagent.instrumentation.api.Java8BytecodeBridge.currentContext; -import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; import static net.bytebuddy.matcher.ElementMatchers.isPublic; import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith; import static net.bytebuddy.matcher.ElementMatchers.named; @@ -16,6 +16,7 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; +import io.opentelemetry.instrumentation.jdbc.internal.DbRequest; import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation; import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer; import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceInstrumentation.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceInstrumentation.java index e82eb1cb5cf7..bc5305bdfd61 100644 --- a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceInstrumentation.java +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/datasource/DataSourceInstrumentation.java @@ -5,8 +5,8 @@ package io.opentelemetry.javaagent.instrumentation.jdbc.datasource; +import static io.opentelemetry.instrumentation.jdbc.internal.DataSourceSingletons.instrumenter; import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.implementsInterface; -import static io.opentelemetry.javaagent.instrumentation.jdbc.datasource.DataSourceSingletons.instrumenter; import static net.bytebuddy.matcher.ElementMatchers.named; import io.opentelemetry.context.Context; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index b1952fccc328..0a23eed93a95 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -20,9 +20,10 @@ package io.opentelemetry.instrumentation.jdbc; -import io.opentelemetry.javaagent.instrumentation.jdbc.DbInfo; -import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcConnectionUrlParser; -import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcMaps; +import io.opentelemetry.instrumentation.jdbc.internal.DbInfo; +import io.opentelemetry.instrumentation.jdbc.internal.JdbcConnectionUrlParser; +import io.opentelemetry.instrumentation.jdbc.internal.JdbcMaps; +import io.opentelemetry.instrumentation.jdbc.internal.OpenTelemetryConnection; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java index e518fadd373b..b03589f48344 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java @@ -20,13 +20,13 @@ package io.opentelemetry.instrumentation.jdbc.datasource; -import static io.opentelemetry.javaagent.instrumentation.jdbc.datasource.DataSourceSingletons.instrumenter; +import static io.opentelemetry.instrumentation.jdbc.internal.DataSourceSingletons.instrumenter; import io.opentelemetry.api.trace.Span; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; -import io.opentelemetry.instrumentation.jdbc.CheckedCallable; -import io.opentelemetry.instrumentation.jdbc.OpenTelemetryConnection; +import io.opentelemetry.instrumentation.jdbc.internal.CheckedCallable; +import io.opentelemetry.instrumentation.jdbc.internal.OpenTelemetryConnection; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; @@ -42,8 +42,8 @@ public OpenTelemetryDataSource(DataSource delegate) { this.delegate = delegate; } - private static T wrapCall(DataSource ds, - CheckedCallable callable) throws E { + private static T wrapCall( + DataSource ds, CheckedCallable callable) throws E { Context parentContext = Context.current(); if (!Span.fromContext(parentContext).getSpanContext().isValid()) { @@ -73,8 +73,7 @@ public Connection getConnection() throws SQLException { @Override public Connection getConnection(final String username, final String password) throws SQLException { - Connection connection = wrapCall(delegate, - () -> delegate.getConnection(username, password)); + Connection connection = wrapCall(delegate, () -> delegate.getConnection(username, password)); return new OpenTelemetryConnection(connection); } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/CheckedCallable.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/CheckedCallable.java index 651a39953803..41b4f221a576 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/CheckedCallable.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/CheckedCallable.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; @FunctionalInterface public interface CheckedCallable { diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceCodeAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceCodeAttributesExtractor.java index a4a96fe1f0cb..5792a245c2d1 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceCodeAttributesExtractor.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceCodeAttributesExtractor.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc.datasource; +package io.opentelemetry.instrumentation.jdbc.internal; import io.opentelemetry.instrumentation.api.instrumenter.code.CodeAttributesExtractor; import javax.sql.DataSource; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceSingletons.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceSingletons.java index 1338b80fa024..c66d86de294d 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceSingletons.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DataSourceSingletons.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc.datasource; +package io.opentelemetry.instrumentation.jdbc.internal; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java index 43447243de3f..c89c2bcf87eb 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java @@ -3,9 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; import com.google.auto.value.AutoValue; +import io.opentelemetry.javaagent.instrumentation.jdbc.AutoValue_DbInfo; import org.checkerframework.checker.nullness.qual.Nullable; @AutoValue diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java index 94d24aa1bb12..57a344152e12 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java @@ -3,12 +3,13 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; -import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcUtils.connectionFromStatement; -import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcUtils.extractDbInfo; +import static io.opentelemetry.instrumentation.jdbc.internal.JdbcUtils.connectionFromStatement; +import static io.opentelemetry.instrumentation.jdbc.internal.JdbcUtils.extractDbInfo; import com.google.auto.value.AutoValue; +import io.opentelemetry.javaagent.instrumentation.jdbc.AutoValue_DbRequest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java index 8647eea54b00..8ebb68b1bf3c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.instrumentation.api.instrumenter.db.SqlAttributesExtractor; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParser.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParser.java index 1e1a03bf944b..5566f384ba63 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParser.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParser.java @@ -3,9 +3,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; -import static io.opentelemetry.javaagent.instrumentation.jdbc.DbInfo.DEFAULT; +import static io.opentelemetry.instrumentation.jdbc.internal.DbInfo.DEFAULT; import static java.util.regex.Pattern.CASE_INSENSITIVE; import io.opentelemetry.semconv.trace.attributes.SemanticAttributes.DbSystemValues; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcMaps.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcMaps.java index 9e2f472e0dc7..5be37d687e65 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcMaps.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcMaps.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; import io.opentelemetry.instrumentation.api.caching.Cache; import java.sql.Connection; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java index f4efad618ca3..72e9f19c1af8 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; import io.opentelemetry.instrumentation.api.instrumenter.net.NetAttributesExtractor; import org.checkerframework.checker.nullness.qual.Nullable; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java index 1c8c935ce4e2..290167fd332f 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java index a4337faff4a4..7b883695f75c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; import java.lang.reflect.Field; import java.sql.Connection; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java index 34829f2b19d5..204e6270ea59 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java @@ -18,7 +18,7 @@ * the License. */ -package io.opentelemetry.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; import java.io.InputStream; import java.io.Reader; @@ -39,9 +39,8 @@ import java.util.Calendar; import java.util.Map; -class OpenTelemetryCallableStatement extends - OpenTelemetryPreparedStatement - implements CallableStatement { +class OpenTelemetryCallableStatement + extends OpenTelemetryPreparedStatement implements CallableStatement { public OpenTelemetryCallableStatement(S callableStatement, String query) { super(callableStatement, query); diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java index 34b3d58616d5..a2a3105c545b 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java @@ -18,9 +18,8 @@ * the License. */ -package io.opentelemetry.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; -import io.opentelemetry.javaagent.instrumentation.jdbc.JdbcMaps; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java index 2ce32c69d25f..321ce792d710 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java @@ -18,15 +18,13 @@ * the License. */ -package io.opentelemetry.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; -import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; +import static io.opentelemetry.instrumentation.jdbc.internal.JdbcSingletons.instrumenter; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; -import io.opentelemetry.instrumentation.jdbc.internal.CheckedCallable; import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; -import io.opentelemetry.javaagent.instrumentation.jdbc.DbRequest; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java index 924a9ceecfc9..4a6cbf33d73e 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java @@ -18,15 +18,13 @@ * the License. */ -package io.opentelemetry.instrumentation.jdbc; +package io.opentelemetry.instrumentation.jdbc.internal; -import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; +import static io.opentelemetry.instrumentation.jdbc.internal.JdbcSingletons.instrumenter; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; -import io.opentelemetry.instrumentation.jdbc.internal.CheckedCallable; import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; -import io.opentelemetry.javaagent.instrumentation.jdbc.DbRequest; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; From 2a9ce6c79398dc436bd427f8d6e27f402597d333 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 21 Jun 2021 18:59:49 +0800 Subject: [PATCH 22/69] Build fix. --- .../io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java | 2 +- .../opentelemetry/instrumentation/jdbc/internal/DbRequest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java index c89c2bcf87eb..b666ad412c08 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java @@ -6,7 +6,7 @@ package io.opentelemetry.instrumentation.jdbc.internal; import com.google.auto.value.AutoValue; -import io.opentelemetry.javaagent.instrumentation.jdbc.AutoValue_DbInfo; +import io.opentelemetry.instrumentation.jdbc.internal.AutoValue_DbInfo; import org.checkerframework.checker.nullness.qual.Nullable; @AutoValue diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java index 57a344152e12..62c0edf39f79 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java @@ -9,7 +9,7 @@ import static io.opentelemetry.instrumentation.jdbc.internal.JdbcUtils.extractDbInfo; import com.google.auto.value.AutoValue; -import io.opentelemetry.javaagent.instrumentation.jdbc.AutoValue_DbRequest; +import io.opentelemetry.instrumentation.jdbc.internal.AutoValue_DbRequest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; From 751ddb463fd4cbb459359f5040a575f09bf73313 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 21 Jun 2021 19:27:21 +0800 Subject: [PATCH 23/69] Cleanup. --- instrumentation/jdbc/library/jdbc-library.gradle | 13 +------------ .../instrumentation/jdbc/OpenTelemetryDriver.java | 4 ++-- .../instrumentation/jdbc/internal/DbInfo.java | 1 - .../instrumentation/jdbc/internal/DbRequest.java | 1 - 4 files changed, 3 insertions(+), 16 deletions(-) diff --git a/instrumentation/jdbc/library/jdbc-library.gradle b/instrumentation/jdbc/library/jdbc-library.gradle index 863ed534ea6d..ceecb39c82ce 100644 --- a/instrumentation/jdbc/library/jdbc-library.gradle +++ b/instrumentation/jdbc/library/jdbc-library.gradle @@ -1,17 +1,6 @@ /* * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * SPDX-License-Identifier: Apache-2.0 */ apply plugin: "otel.library-instrumentation" diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 0a23eed93a95..6b268340ad22 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -66,7 +66,7 @@ public static synchronized void ensureRegisteredAsTheFirstDriver() { for (int i = 0; enumeration.hasMoreElements(); ++i) { Driver driver = enumeration.nextElement(); if (i == 0 && driver == INSTANCE) { - // the first driver is the tracing driver, skip all this verification + // the first driver is OTEL driver, skip all this verification return; } if (driver instanceof OpenTelemetryDriver) { @@ -75,7 +75,7 @@ public static synchronized void ensureRegisteredAsTheFirstDriver() { DriverManager.deregisterDriver(driver); } - // register tracing driver first + // register OTEL driver first register(); // register other drivers diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java index b666ad412c08..c704b1a1baaf 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbInfo.java @@ -6,7 +6,6 @@ package io.opentelemetry.instrumentation.jdbc.internal; import com.google.auto.value.AutoValue; -import io.opentelemetry.instrumentation.jdbc.internal.AutoValue_DbInfo; import org.checkerframework.checker.nullness.qual.Nullable; @AutoValue diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java index 62c0edf39f79..829d24b4e5fe 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/DbRequest.java @@ -9,7 +9,6 @@ import static io.opentelemetry.instrumentation.jdbc.internal.JdbcUtils.extractDbInfo; import com.google.auto.value.AutoValue; -import io.opentelemetry.instrumentation.jdbc.internal.AutoValue_DbRequest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; From a2ae147d864b7adbdf55fe4daacd25ab0b4a01a9 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Tue, 22 Jun 2021 17:35:19 +0800 Subject: [PATCH 24/69] Moved some shared classes to instrumentation-api module. --- .../api/instrumenter/PeerServiceAttributesExtractor.java | 0 .../ReflectionPeerServiceAttributesExtractorFactory.java | 0 .../api/instrumenter/PeerServiceAttributesExtractorTest.java | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {javaagent-api/src/main/java/io/opentelemetry/javaagent => instrumentation-api/src/main/java/io/opentelemetry}/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java (100%) rename {javaagent-api/src/main/java/io/opentelemetry/javaagent => instrumentation-api/src/main/java/io/opentelemetry}/instrumentation/api/instrumenter/ReflectionPeerServiceAttributesExtractorFactory.java (100%) rename {javaagent-api/src/test/java/io/opentelemetry/javaagent => instrumentation-api/src/test/java/io/opentelemetry}/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java (100%) diff --git a/javaagent-api/src/main/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java b/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java similarity index 100% rename from javaagent-api/src/main/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java rename to instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java diff --git a/javaagent-api/src/main/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/ReflectionPeerServiceAttributesExtractorFactory.java b/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/ReflectionPeerServiceAttributesExtractorFactory.java similarity index 100% rename from javaagent-api/src/main/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/ReflectionPeerServiceAttributesExtractorFactory.java rename to instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/ReflectionPeerServiceAttributesExtractorFactory.java diff --git a/javaagent-api/src/test/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java b/instrumentation-api/src/test/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java similarity index 100% rename from javaagent-api/src/test/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java rename to instrumentation-api/src/test/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java From 2212831d8682a753efc74ed9839a25bb21a43c25 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Tue, 22 Jun 2021 17:35:36 +0800 Subject: [PATCH 25/69] Code review fixes. --- .../PeerServiceAttributesExtractor.java | 3 +- ...PeerServiceAttributesExtractorFactory.java | 2 +- .../PeerServiceAttributesExtractorTest.java | 2 +- .../v2_0/ApacheHttpClientSingletons.java | 2 +- .../v4_0/ApacheHttpClientSingletons.java | 2 +- .../v5_0/ApacheHttpClientSingletons.java | 2 +- .../armeria/v1_3/ArmeriaSingletons.java | 2 +- .../v2_0/AsyncHttpClientSingletons.java | 2 +- .../jdbc/OpenTelemetryDriver.java | 17 ++-- .../datasource/OpenTelemetryDataSource.java | 56 ++++++------ .../jdbc/internal/JdbcSingletons.java | 2 +- .../jdbc/internal/JdbcUtils.java | 2 +- .../OpenTelemetryCallableStatement.java | 4 +- .../internal/OpenTelemetryConnection.java | 34 ++++--- .../OpenTelemetryPreparedStatement.java | 52 ++--------- .../jdbc/internal/OpenTelemetryStatement.java | 88 ++++++++----------- .../jedis/v1_4/JedisSingletons.java | 2 +- .../jedis/v3_0/JedisSingletons.java | 2 +- .../lettuce/v4_0/LettuceSingletons.java | 2 +- .../lettuce/v5_0/LettuceSingletons.java | 2 +- 20 files changed, 111 insertions(+), 169 deletions(-) diff --git a/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java b/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java index be1e67aca8f4..3e8a49b3b216 100644 --- a/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java +++ b/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java @@ -3,11 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.api.instrumenter; +package io.opentelemetry.instrumentation.api.instrumenter; import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.instrumentation.api.config.Config; -import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.net.NetAttributesExtractor; import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; import java.util.Map; diff --git a/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/ReflectionPeerServiceAttributesExtractorFactory.java b/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/ReflectionPeerServiceAttributesExtractorFactory.java index 5bdcf2e19dea..e5f00aa6dffa 100644 --- a/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/ReflectionPeerServiceAttributesExtractorFactory.java +++ b/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/ReflectionPeerServiceAttributesExtractorFactory.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.api.instrumenter; +package io.opentelemetry.instrumentation.api.instrumenter; import io.opentelemetry.instrumentation.api.instrumenter.net.NetAttributesExtractor; import java.lang.reflect.Constructor; diff --git a/instrumentation-api/src/test/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java b/instrumentation-api/src/test/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java index 300f9a7e28cd..ecb452bb32db 100644 --- a/instrumentation-api/src/test/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java +++ b/instrumentation-api/src/test/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.javaagent.instrumentation.api.instrumenter; +package io.opentelemetry.instrumentation.api.instrumenter; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static java.util.Collections.singletonMap; diff --git a/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java b/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java index 7594393cd72f..ca1730528bdb 100644 --- a/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java +++ b/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java @@ -12,7 +12,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.apache.commons.httpclient.HttpMethod; public final class ApacheHttpClientSingletons { diff --git a/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java b/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java index b4a014e70822..031294c902f5 100644 --- a/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java +++ b/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java @@ -12,7 +12,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; diff --git a/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java b/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java index 53fe88bfa6d2..ff7237a13d40 100644 --- a/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java +++ b/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java @@ -12,7 +12,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.HttpResponse; diff --git a/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java b/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java index 227ad16d4ee4..9a4d0e2c3967 100644 --- a/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java +++ b/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java @@ -13,7 +13,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor; import io.opentelemetry.instrumentation.armeria.v1_3.ArmeriaTracing; import io.opentelemetry.instrumentation.armeria.v1_3.ArmeriaTracingBuilder; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import java.util.function.Function; // Holds singleton references to decorators to match against during suppression. diff --git a/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java b/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java index 29c62ecacafd..ec7bc9a4ab4f 100644 --- a/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java +++ b/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java @@ -12,7 +12,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.asynchttpclient.Request; import org.asynchttpclient.Response; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 6b268340ad22..ed78259c43cb 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -22,7 +22,6 @@ import io.opentelemetry.instrumentation.jdbc.internal.DbInfo; import io.opentelemetry.instrumentation.jdbc.internal.JdbcConnectionUrlParser; -import io.opentelemetry.instrumentation.jdbc.internal.JdbcMaps; import io.opentelemetry.instrumentation.jdbc.internal.OpenTelemetryConnection; import java.sql.Connection; import java.sql.Driver; @@ -34,6 +33,7 @@ import java.util.Enumeration; import java.util.List; import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; import org.checkerframework.checker.nullness.qual.Nullable; @@ -42,8 +42,8 @@ public class OpenTelemetryDriver implements Driver { private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; private static final OpenTelemetryDriver INSTANCE = new OpenTelemetryDriver(); + private static final AtomicBoolean REGISTERED = new AtomicBoolean(); - private static boolean registered = false; private static boolean interceptorMode = false; static { @@ -69,7 +69,7 @@ public static synchronized void ensureRegisteredAsTheFirstDriver() { // the first driver is OTEL driver, skip all this verification return; } - if (driver instanceof OpenTelemetryDriver) { + if (!(driver instanceof OpenTelemetryDriver)) { drivers.add(driver); } DriverManager.deregisterDriver(driver); @@ -110,7 +110,7 @@ public static void register() throws SQLException { "Driver is already registered. It can only be registered once."); } DriverManager.registerDriver(INSTANCE); - OpenTelemetryDriver.registered = true; + REGISTERED.set(true); } /** @@ -122,17 +122,17 @@ public static void register() throws SQLException { * @throws SQLException if deregistering the driver fails */ public static void deregister() throws SQLException { - if (!registered) { + if (!REGISTERED.get()) { throw new IllegalStateException( "Driver is not registered (or it has not been registered using Driver.register() method)"); } DriverManager.deregisterDriver(INSTANCE); - registered = false; + REGISTERED.set(false); } /** Returns {@code true} if the driver is registered against {@link DriverManager} */ public static boolean isRegistered() { - return registered; + return REGISTERED.get(); } private static Driver findDriver(String realUrl) throws SQLException { @@ -179,9 +179,8 @@ public Connection connect(String url, Properties info) throws SQLException { final Connection connection = wrappedDriver.connect(realUrl, info); final DbInfo dbInfo = JdbcConnectionUrlParser.parse(realUrl, info); - JdbcMaps.connectionInfo.put(connection, dbInfo); - return new OpenTelemetryConnection(connection); + return new OpenTelemetryConnection(connection, dbInfo); } @Override diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java index b03589f48344..24efbbc3554e 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java @@ -21,11 +21,13 @@ package io.opentelemetry.instrumentation.jdbc.datasource; import static io.opentelemetry.instrumentation.jdbc.internal.DataSourceSingletons.instrumenter; +import static io.opentelemetry.instrumentation.jdbc.internal.JdbcUtils.computeDbInfo; import io.opentelemetry.api.trace.Span; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; import io.opentelemetry.instrumentation.jdbc.internal.CheckedCallable; +import io.opentelemetry.instrumentation.jdbc.internal.DbInfo; import io.opentelemetry.instrumentation.jdbc.internal.OpenTelemetryConnection; import java.io.PrintWriter; import java.sql.Connection; @@ -42,39 +44,19 @@ public OpenTelemetryDataSource(DataSource delegate) { this.delegate = delegate; } - private static T wrapCall( - DataSource ds, CheckedCallable callable) throws E { - Context parentContext = Context.current(); - - if (!Span.fromContext(parentContext).getSpanContext().isValid()) { - // this instrumentation is already very noisy, and calls to getConnection outside of an - // existing trace do not tend to be very interesting - return callable.call(); - } - - Context context = instrumenter().start(parentContext, ds); - T result; - try (Scope ignored = context.makeCurrent()) { - result = callable.call(); - } catch (Throwable t) { - instrumenter().end(context, ds, null, t); - throw t; - } - instrumenter().end(context, ds, null, null); - return result; - } - @Override public Connection getConnection() throws SQLException { - Connection connection = wrapCall(delegate, delegate::getConnection); - return new OpenTelemetryConnection(connection); + Connection connection = wrapCall(delegate::getConnection); + DbInfo dbInfo = computeDbInfo(connection); + return new OpenTelemetryConnection(connection, dbInfo); } @Override public Connection getConnection(final String username, final String password) throws SQLException { - Connection connection = wrapCall(delegate, () -> delegate.getConnection(username, password)); - return new OpenTelemetryConnection(connection); + Connection connection = wrapCall(() -> delegate.getConnection(username, password)); + DbInfo dbInfo = computeDbInfo(connection); + return new OpenTelemetryConnection(connection, dbInfo); } @Override @@ -118,4 +100,26 @@ public void close() throws Exception { ((AutoCloseable) delegate).close(); } } + + private T wrapCall(CheckedCallable callable) throws E { + Context parentContext = Context.current(); + + if (!Span.fromContext(parentContext).getSpanContext().isValid()) { + // this instrumentation is already very noisy, and calls to getConnection outside of an + // existing trace do not tend to be very interesting + return callable.call(); + } + + Context context = instrumenter().start(parentContext, delegate); + T result; + try (Scope ignored = context.makeCurrent()) { + result = callable.call(); + } catch (Throwable t) { + instrumenter().end(context, delegate, null, t); + throw t; + } + instrumenter().end(context, delegate, null, null); + return result; + } + } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java index 290167fd332f..ca39fedc7937 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java @@ -11,7 +11,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class JdbcSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.jdbc"; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java index 7b883695f75c..e3e089fdc0b9 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcUtils.java @@ -68,7 +68,7 @@ public static DbInfo extractDbInfo(Connection connection) { return JdbcMaps.connectionInfo.computeIfAbsent(connection, JdbcUtils::computeDbInfo); } - private static DbInfo computeDbInfo(Connection connection) { + public static DbInfo computeDbInfo(Connection 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 diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java index 204e6270ea59..3abaa29b78b3 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java @@ -42,8 +42,8 @@ class OpenTelemetryCallableStatement extends OpenTelemetryPreparedStatement implements CallableStatement { - public OpenTelemetryCallableStatement(S callableStatement, String query) { - super(callableStatement, query); + public OpenTelemetryCallableStatement(S delegate, DbInfo dbInfo, String query) { + super(delegate, dbInfo, query); } @SuppressWarnings("UngroupedOverloads") diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java index a2a3105c545b..973bdbc050fe 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java @@ -42,22 +42,24 @@ public class OpenTelemetryConnection implements Connection { private final Connection delegate; + private final DbInfo dbInfo; - public OpenTelemetryConnection(Connection delegate) { + public OpenTelemetryConnection(Connection delegate, DbInfo dbInfo) { this.delegate = delegate; + this.dbInfo = dbInfo; } @Override public Statement createStatement() throws SQLException { final Statement statement = delegate.createStatement(); - return new OpenTelemetryStatement<>(statement); + return new OpenTelemetryStatement<>(statement, dbInfo); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { final Statement statement = delegate.createStatement(resultSetType, resultSetConcurrency); - return new OpenTelemetryStatement<>(statement); + return new OpenTelemetryStatement<>(statement, dbInfo); } @Override @@ -65,14 +67,13 @@ public Statement createStatement( int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { final Statement statement = delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - return new OpenTelemetryStatement<>(statement); + return new OpenTelemetryStatement<>(statement, dbInfo); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql); - JdbcMaps.preparedStatements.put(statement, sql); - return new OpenTelemetryPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, dbInfo, sql); } @Override @@ -80,8 +81,7 @@ public PreparedStatement prepareStatement(String sql, int resultSetType, int res throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql, resultSetType, resultSetConcurrency); - JdbcMaps.preparedStatements.put(statement, sql); - return new OpenTelemetryPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, dbInfo, sql); } @Override @@ -90,35 +90,31 @@ public PreparedStatement prepareStatement( throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - JdbcMaps.preparedStatements.put(statement, sql); - return new OpenTelemetryPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, dbInfo, sql); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql, autoGeneratedKeys); - JdbcMaps.preparedStatements.put(statement, sql); - return new OpenTelemetryPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, dbInfo, sql); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql, columnIndexes); - JdbcMaps.preparedStatements.put(statement, sql); - return new OpenTelemetryPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, dbInfo, sql); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { final PreparedStatement statement = delegate.prepareStatement(sql, columnNames); - JdbcMaps.preparedStatements.put(statement, sql); - return new OpenTelemetryPreparedStatement<>(statement, sql); + return new OpenTelemetryPreparedStatement<>(statement, dbInfo, sql); } @Override public CallableStatement prepareCall(String sql) throws SQLException { final CallableStatement statement = delegate.prepareCall(sql); - return new OpenTelemetryCallableStatement<>(statement, sql); + return new OpenTelemetryCallableStatement<>(statement, dbInfo, sql); } @Override @@ -126,7 +122,7 @@ public CallableStatement prepareCall(String sql, int resultSetType, int resultSe throws SQLException { final CallableStatement statement = delegate.prepareCall(sql, resultSetType, resultSetConcurrency); - return new OpenTelemetryCallableStatement<>(statement, sql); + return new OpenTelemetryCallableStatement<>(statement, dbInfo, sql); } @Override @@ -135,7 +131,7 @@ public CallableStatement prepareCall( throws SQLException { final CallableStatement statement = delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - return new OpenTelemetryCallableStatement(statement, sql); + return new OpenTelemetryCallableStatement(statement, dbInfo, sql); } @Override diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java index 321ce792d710..292075f2dce7 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java @@ -20,11 +20,6 @@ package io.opentelemetry.instrumentation.jdbc.internal; -import static io.opentelemetry.instrumentation.jdbc.internal.JdbcSingletons.instrumenter; - -import io.opentelemetry.context.Context; -import io.opentelemetry.context.Scope; -import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; @@ -42,7 +37,6 @@ import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLXML; -import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; @@ -50,59 +44,23 @@ class OpenTelemetryPreparedStatement extends OpenTelemetryStatement implements PreparedStatement { - public OpenTelemetryPreparedStatement(S preparedStatement, String query) { - super(preparedStatement, query); - } - - private static T wrapCall( - PreparedStatement preparedStatement, CheckedCallable callable) throws E { - // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info - // this happens before the DB CLIENT span is started (and put in the current context), so this - // instrumentation runs again and the shouldStartSpan() check always returns true - and so on - // until we get a StackOverflowError - // using CallDepth prevents this, because this check happens before Connection#getMetadata() - // is called - the first recursive Statement call is just skipped and we do not create a span - // for it - if (CallDepthThreadLocalMap.getCallDepth(Statement.class).getAndIncrement() > 0) { - return callable.call(); - } - - try { - Context parentContext = Context.current(); - DbRequest request = DbRequest.create(preparedStatement); - - if (request == null || !instrumenter().shouldStart(parentContext, request)) { - return callable.call(); - } - - Context context = instrumenter().start(parentContext, request); - T result; - try (Scope ignored = context.makeCurrent()) { - result = callable.call(); - } catch (Throwable t) { - instrumenter().end(context, request, null, t); - throw t; - } - instrumenter().end(context, request, null, null); - return result; - } finally { - CallDepthThreadLocalMap.reset(Statement.class); - } + public OpenTelemetryPreparedStatement(S delegate, DbInfo dbInfo, String query) { + super(delegate, dbInfo, query); } @Override public ResultSet executeQuery() throws SQLException { - return wrapCall(delegate, delegate::executeQuery); + return wrapCall(query, delegate::executeQuery); } @Override public int executeUpdate() throws SQLException { - return wrapCall(delegate, delegate::executeUpdate); + return wrapCall(query, delegate::executeUpdate); } @Override public boolean execute() throws SQLException { - return wrapCall(delegate, delegate::execute); + return wrapCall(query, delegate::execute); } @SuppressWarnings("UngroupedOverloads") diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java index 4a6cbf33d73e..ba1f3ed899f8 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java @@ -24,7 +24,6 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; -import io.opentelemetry.javaagent.instrumentation.api.CallDepthThreadLocalMap; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -35,103 +34,69 @@ class OpenTelemetryStatement implements Statement { protected final S delegate; - private final String query; + protected final DbInfo dbInfo; + protected final String query; private final ArrayList batchCommands = new ArrayList<>(); - OpenTelemetryStatement(S delegate) { - this(delegate, null); + OpenTelemetryStatement(S delegate, DbInfo dbInfo) { + this(delegate, dbInfo, null); } - OpenTelemetryStatement(S delegate, String query) { + OpenTelemetryStatement(S delegate, DbInfo dbInfo, String query) { this.delegate = delegate; + this.dbInfo = dbInfo; this.query = query; } - private static T wrapCall( - Statement statement, String sql, CheckedCallable callable) throws E { - // Connection#getMetaData() may execute a Statement or PreparedStatement to retrieve DB info - // this happens before the DB CLIENT span is started (and put in the current context), so this - // instrumentation runs again and the shouldStartSpan() check always returns true - and so on - // until we get a StackOverflowError - // using CallDepth prevents this, because this check happens before Connection#getMetadata() - // is called - the first recursive Statement call is just skipped and we do not create a span - // for it - if (CallDepthThreadLocalMap.getCallDepth(Statement.class).getAndIncrement() > 0) { - return callable.call(); - } - - try { - Context parentContext = Context.current(); - DbRequest request = DbRequest.create(statement, sql); - - if (request == null || !instrumenter().shouldStart(parentContext, request)) { - return callable.call(); - } - - Context context = instrumenter().start(parentContext, request); - T result; - try (Scope ignored = context.makeCurrent()) { - result = callable.call(); - } catch (Throwable t) { - instrumenter().end(context, request, null, t); - throw t; - } - instrumenter().end(context, request, null, null); - return result; - } finally { - CallDepthThreadLocalMap.reset(Statement.class); - } - } - @Override public ResultSet executeQuery(String sql) throws SQLException { - return wrapCall(delegate, sql, () -> delegate.executeQuery(sql)); + return wrapCall(sql, () -> delegate.executeQuery(sql)); } @Override public int executeUpdate(String sql) throws SQLException { - return wrapCall(delegate, sql, () -> delegate.executeUpdate(sql)); + return wrapCall(sql, () -> delegate.executeUpdate(sql)); } @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - return wrapCall(delegate, sql, () -> delegate.executeUpdate(sql, autoGeneratedKeys)); + return wrapCall(sql, () -> delegate.executeUpdate(sql, autoGeneratedKeys)); } @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - return wrapCall(delegate, sql, () -> delegate.executeUpdate(sql, columnIndexes)); + return wrapCall(sql, () -> delegate.executeUpdate(sql, columnIndexes)); } @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { - return wrapCall(delegate, sql, () -> delegate.executeUpdate(sql, columnNames)); + return wrapCall(sql, () -> delegate.executeUpdate(sql, columnNames)); } @Override public boolean execute(String sql) throws SQLException { - return wrapCall(delegate, sql, () -> delegate.execute(sql)); + return wrapCall(sql, () -> delegate.execute(sql)); } @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return wrapCall(delegate, sql, () -> delegate.execute(sql, autoGeneratedKeys)); + return wrapCall(sql, () -> delegate.execute(sql, autoGeneratedKeys)); } @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { - return wrapCall(delegate, sql, () -> delegate.execute(sql, columnIndexes)); + return wrapCall(sql, () -> delegate.execute(sql, columnIndexes)); } @Override public boolean execute(String sql, String[] columnNames) throws SQLException { - return wrapCall(delegate, sql, () -> delegate.execute(sql, columnNames)); + return wrapCall(sql, () -> delegate.execute(sql, columnNames)); } @Override public int[] executeBatch() throws SQLException { - return wrapCall(delegate, buildSqlForBatch(), delegate::executeBatch); + return wrapCall(buildSqlForBatch(), delegate::executeBatch); } @Override @@ -307,6 +272,27 @@ public boolean isWrapperFor(Class iface) throws SQLException { return delegate.isWrapperFor(iface); } + protected T wrapCall(String sql, CheckedCallable callable) + throws E { + Context parentContext = Context.current(); + DbRequest request = DbRequest.create(dbInfo, sql); + + if (!instrumenter().shouldStart(parentContext, request)) { + return callable.call(); + } + + Context context = instrumenter().start(parentContext, request); + T result; + try (Scope ignored = context.makeCurrent()) { + result = callable.call(); + } catch (Throwable t) { + instrumenter().end(context, request, null, t); + throw t; + } + instrumenter().end(context, request, null, null); + return result; + } + private String buildSqlForBatch() { StringBuilder sqlBuilder = new StringBuilder(); if (query != null) { diff --git a/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java b/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java index f31dcba7cbca..7a1e0ee67d69 100644 --- a/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java +++ b/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java @@ -11,7 +11,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class JedisSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-1.4"; diff --git a/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java b/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java index b0b75559ee1f..db1e14c09d87 100644 --- a/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java +++ b/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java @@ -11,7 +11,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class JedisSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-3.0"; diff --git a/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java b/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java index 825d45c6c387..adc9be08dbf9 100644 --- a/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java +++ b/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java @@ -13,7 +13,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class LettuceSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-1.4"; diff --git a/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java b/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java index 016b71894e96..f74ef03fc3ac 100644 --- a/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java +++ b/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java @@ -13,7 +13,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class LettuceSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-5.0"; From a8f1553af259bfab1751c682046e828e300e5d32 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Tue, 22 Jun 2021 17:41:33 +0800 Subject: [PATCH 26/69] Make OpenTelemetryDriver final. --- .../opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index ed78259c43cb..55c4169f3d2c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -37,7 +37,7 @@ import java.util.logging.Logger; import org.checkerframework.checker.nullness.qual.Nullable; -public class OpenTelemetryDriver implements Driver { +public final class OpenTelemetryDriver implements Driver { private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; From 5699f89df85aa5fb32cfb8611eb0b25839e4a3b9 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Tue, 22 Jun 2021 17:52:04 +0800 Subject: [PATCH 27/69] Spotless fixes. --- .../apachehttpclient/v2_0/ApacheHttpClientSingletons.java | 2 +- .../apachehttpclient/v4_0/ApacheHttpClientSingletons.java | 2 +- .../apachehttpclient/v5_0/ApacheHttpClientSingletons.java | 2 +- .../instrumentation/armeria/v1_3/ArmeriaSingletons.java | 2 +- .../asynchttpclient/v2_0/AsyncHttpClientSingletons.java | 2 +- .../jdbc/datasource/OpenTelemetryDataSource.java | 1 - .../instrumentation/jdbc/internal/JdbcSingletons.java | 2 +- .../javaagent/instrumentation/jedis/v1_4/JedisSingletons.java | 2 +- .../javaagent/instrumentation/jedis/v3_0/JedisSingletons.java | 2 +- .../instrumentation/lettuce/v4_0/LettuceSingletons.java | 2 +- .../instrumentation/lettuce/v5_0/LettuceSingletons.java | 2 +- 11 files changed, 10 insertions(+), 11 deletions(-) diff --git a/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java b/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java index ca1730528bdb..da0270f07e38 100644 --- a/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java +++ b/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java @@ -7,12 +7,12 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.apache.commons.httpclient.HttpMethod; public final class ApacheHttpClientSingletons { diff --git a/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java b/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java index 031294c902f5..491416fcdfc1 100644 --- a/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java +++ b/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java @@ -7,12 +7,12 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; diff --git a/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java b/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java index ff7237a13d40..7961e3f87f49 100644 --- a/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java +++ b/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java @@ -7,12 +7,12 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.HttpResponse; diff --git a/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java b/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java index 9a4d0e2c3967..a8f2631e279d 100644 --- a/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java +++ b/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java @@ -11,9 +11,9 @@ import com.linecorp.armeria.server.HttpService; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.armeria.v1_3.ArmeriaTracing; import io.opentelemetry.instrumentation.armeria.v1_3.ArmeriaTracingBuilder; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import java.util.function.Function; // Holds singleton references to decorators to match against during suppression. diff --git a/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java b/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java index ec7bc9a4ab4f..2e8918a0dfbc 100644 --- a/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java +++ b/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java @@ -7,12 +7,12 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.asynchttpclient.Request; import org.asynchttpclient.Response; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java index 24efbbc3554e..a6ba59bccc4c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java @@ -121,5 +121,4 @@ private T wrapCall(CheckedCallable callable) t instrumenter().end(context, delegate, null, null); return result; } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java index ca39fedc7937..986053769628 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java @@ -7,11 +7,11 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class JdbcSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.jdbc"; diff --git a/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java b/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java index 7a1e0ee67d69..3549a92652ec 100644 --- a/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java +++ b/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java @@ -7,11 +7,11 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class JedisSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-1.4"; diff --git a/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java b/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java index db1e14c09d87..8bb99035d4a5 100644 --- a/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java +++ b/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java @@ -7,11 +7,11 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class JedisSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-3.0"; diff --git a/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java b/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java index adc9be08dbf9..d2a0990036f8 100644 --- a/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java +++ b/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java @@ -9,11 +9,11 @@ import com.lambdaworks.redis.protocol.RedisCommand; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class LettuceSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-1.4"; diff --git a/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java b/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java index f74ef03fc3ac..81a2430f1a6f 100644 --- a/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java +++ b/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java @@ -9,11 +9,11 @@ import io.lettuce.core.protocol.RedisCommand; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class LettuceSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-5.0"; From 60f6f239328ff80e32a3854da529694fe00eb9d7 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Wed, 23 Jun 2021 15:21:08 +0800 Subject: [PATCH 28/69] Moved test classes from javaagent-unit-tests module to library module. --- .../jdbc/internal}/JdbcConnectionUrlParserTest.groovy | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename instrumentation/jdbc/{javaagent-unit-tests/src/test/groovy => library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/internal}/JdbcConnectionUrlParserTest.groovy (100%) diff --git a/instrumentation/jdbc/javaagent-unit-tests/src/test/groovy/JdbcConnectionUrlParserTest.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParserTest.groovy similarity index 100% rename from instrumentation/jdbc/javaagent-unit-tests/src/test/groovy/JdbcConnectionUrlParserTest.groovy rename to instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParserTest.groovy From 6997669ed4fda96e3ab8d7ecd0a495fedc3cdfd7 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Wed, 23 Jun 2021 15:21:45 +0800 Subject: [PATCH 29/69] Removed javaagent-unit-tests module. --- .../jdbc/internal/JdbcConnectionUrlParserTest.groovy | 3 ++- settings.gradle | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParserTest.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParserTest.groovy index ed80a249d8c5..60488e4eab7d 100644 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParserTest.groovy +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/internal/JdbcConnectionUrlParserTest.groovy @@ -3,9 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 */ +package io.opentelemetry.instrumentation.jdbc.internal + import static io.opentelemetry.instrumentation.jdbc.internal.JdbcConnectionUrlParser.parse -import io.opentelemetry.instrumentation.jdbc.internal.DbInfo import spock.lang.Shared import spock.lang.Specification diff --git a/settings.gradle b/settings.gradle index f0dae2600549..527884514f81 100644 --- a/settings.gradle +++ b/settings.gradle @@ -178,7 +178,6 @@ include ':instrumentation:jaxws:jaxws-2.0-testing' include ':instrumentation:jaxws:jaxws-common:library' include ':instrumentation:jaxws:jws-1.1:javaagent' include ':instrumentation:jdbc:javaagent' -include ':instrumentation:jdbc:javaagent-unit-tests' include ':instrumentation:jdbc:library' include ':instrumentation:jedis:jedis-1.4:javaagent' include ':instrumentation:jedis:jedis-3.0:javaagent' From a89ffc5a29326c68b9e692e0ee914cb979d1269d Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Wed, 23 Jun 2021 16:41:49 +0800 Subject: [PATCH 30/69] Covered OpenTelemetryDriver with tests. --- .../jdbc/OpenTelemetryDriver.java | 23 +- .../jdbc/AnotherTestDriver.groovy | 46 +++ .../jdbc/OpenTelemetryDriverTest.groovy | 217 ++++++++++++++ .../jdbc/TestConnection.groovy | 281 ++++++++++++++++++ .../instrumentation/jdbc/TestDriver.groovy | 46 +++ 5 files changed, 604 insertions(+), 9 deletions(-) create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/AnotherTestDriver.groovy create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 55c4169f3d2c..330fdd994a36 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -39,9 +39,9 @@ public final class OpenTelemetryDriver implements Driver { - private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; + public static final OpenTelemetryDriver INSTANCE = new OpenTelemetryDriver(); - private static final OpenTelemetryDriver INSTANCE = new OpenTelemetryDriver(); + private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; private static final AtomicBoolean REGISTERED = new AtomicBoolean(); private static boolean interceptorMode = false; @@ -135,7 +135,7 @@ public static boolean isRegistered() { return REGISTERED.get(); } - private static Driver findDriver(String realUrl) throws SQLException { + private static Driver findDriver(String realUrl) { if (realUrl == null || realUrl.trim().length() == 0) { throw new IllegalArgumentException("url is required"); } @@ -150,7 +150,7 @@ private static Driver findDriver(String realUrl) throws SQLException { } } - throw new SQLException("Unable to find a driver that accepts url: " + realUrl); + throw new IllegalStateException("Unable to find a driver that accepts url: " + realUrl); } private static String extractRealUrl(String url) { @@ -162,9 +162,8 @@ private static String extractRealUrl(String url) { @Nullable @Override public Connection connect(String url, Properties info) throws SQLException { - // if there is no url, we have problems - if (url == null) { - throw new SQLException("url is required"); + if (url == null || url.trim().length() == 0) { + throw new IllegalArgumentException("url is required"); } if (!acceptsURL(url)) { @@ -191,12 +190,18 @@ public boolean acceptsURL(String url) { if (url.startsWith(INTERCEPTOR_MODE_URL_PREFIX)) { return true; } - return interceptorMode && url.startsWith("jdbc:"); + return interceptorMode && url.startsWith("jdbc:") && url.length() > 5; } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { - return findDriver(url).getPropertyInfo(url, info); + if (url == null || url.trim().length() == 0) { + throw new IllegalArgumentException("url is required"); + } + + final String realUrl = extractRealUrl(url); + final Driver wrappedDriver = findDriver(realUrl); + return wrappedDriver.getPropertyInfo(realUrl, info); } @Override diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/AnotherTestDriver.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/AnotherTestDriver.groovy new file mode 100644 index 000000000000..3590fc801e66 --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/AnotherTestDriver.groovy @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc + +import java.sql.* +import java.util.logging.Logger + +class AnotherTestDriver implements Driver { + @Override + Connection connect(String url, Properties info) throws SQLException { + return null + } + + @Override + boolean acceptsURL(String url) throws SQLException { + return false + } + + @Override + DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { + return new DriverPropertyInfo[0] + } + + @Override + int getMajorVersion() { + return 0 + } + + @Override + int getMinorVersion() { + return 0 + } + + @Override + boolean jdbcCompliant() { + return false + } + + @Override + Logger getParentLogger() throws SQLFeatureNotSupportedException { + return null + } +} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy new file mode 100644 index 000000000000..452996d34620 --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy @@ -0,0 +1,217 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc + +import io.opentelemetry.instrumentation.jdbc.internal.OpenTelemetryConnection +import spock.lang.Specification + +import java.sql.DriverManager + +class OpenTelemetryDriverTest extends Specification { + + def cleanup() { + OpenTelemetryDriver.setInterceptorMode(false) + if (!OpenTelemetryDriver.registered) { + OpenTelemetryDriver.register() + } + } + + def "verify driver auto registered"() { + when: + Class driverClass = Class.forName("io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver") + def drivers = DriverManager.drivers + + then: + driverClass != null + OpenTelemetryDriver.registered + drivers.any { driver -> + driver instanceof OpenTelemetryDriver && driver == OpenTelemetryDriver.INSTANCE + } + } + + def "verify standard properties"() { + expect: + !OpenTelemetryDriver.INSTANCE.jdbcCompliant() + OpenTelemetryDriver.INSTANCE.parentLogger == null + OpenTelemetryDriver.INSTANCE.majorVersion == 1 + OpenTelemetryDriver.INSTANCE.minorVersion == 4 + } + + def "verify driver registered as a first driver"() { + given: + DriverManager.drivers.each { driver -> + if (driver instanceof OpenTelemetryDriver) { + OpenTelemetryDriver.deregister() + } else { + DriverManager.deregisterDriver(driver) + } + } + DriverManager.registerDriver(new TestDriver()) + DriverManager.registerDriver(new AnotherTestDriver()) + OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver() + + when: + def firstDriver = DriverManager.drivers.nextElement() + + then: + OpenTelemetryDriver.registered + firstDriver != null + firstDriver instanceof OpenTelemetryDriver + } + + def "verify accepted urls"() { + expect: + def driver = OpenTelemetryDriver.INSTANCE + OpenTelemetryDriver.setInterceptorMode(interceptorMode) + driver.acceptsURL(url) == expected + + where: + url | interceptorMode | expected + null | false | false + "" | false | false + "jdbc:" | false | false + "jdbc::" | false | false + "bogus:string" | false | false + "jdbc:postgresql://127.0.0.1:5432/dbname" | false | false + "jdbc:otel:postgresql://127.0.0.1:5432/dbname" | false | true + null | true | false + "" | true | false + "jdbc:" | true | false + "jdbc::" | true | true + "bogus:string" | true | false + "jdbc:postgresql://127.0.0.1:5432/dbname" | true | true + "jdbc:otel:postgresql://127.0.0.1:5432/dbname" | true | true + } + + def "verify deregister"() { + when: + if (OpenTelemetryDriver.registered) { + OpenTelemetryDriver.deregister() + } + + then: + !OpenTelemetryDriver.registered + DriverManager.drivers.every { driver -> + !(driver instanceof OpenTelemetryDriver) + } + } + + def "verify register"() { + when: + if (OpenTelemetryDriver.registered) { + OpenTelemetryDriver.deregister() + } + OpenTelemetryDriver.register() + + then: + OpenTelemetryDriver.registered + DriverManager.drivers.any { driver -> + driver instanceof OpenTelemetryDriver && driver == OpenTelemetryDriver.INSTANCE + } + } + + def "verify connection with null url"() { + when: + OpenTelemetryDriver.INSTANCE.connect(null, null) + + then: + def e = thrown(IllegalArgumentException) + e.message == "url is required" + } + + def "verify connection with empty url"() { + when: + OpenTelemetryDriver.INSTANCE.connect(" ", null) + + then: + def e = thrown(IllegalArgumentException) + e.message == "url is required" + } + + def "verify connection with not accepted url"() { + when: + def connection = OpenTelemetryDriver.INSTANCE.connect("abc:xyz", null) + + then: + connection == null + } + + def "verify connection with disabled interceptor mode"() { + when: + OpenTelemetryDriver.interceptorMode = false + def connection = OpenTelemetryDriver.INSTANCE.connect("jdbc:test:", null) + + then: + connection == null + + when: + registerTestDriver() + OpenTelemetryDriver.interceptorMode = false + connection = OpenTelemetryDriver.INSTANCE.connect("jdbc:otel:test:", null) + + then: + connection != null + connection instanceof OpenTelemetryConnection + } + + def "verify connection with enabled interceptor mode"() { + when: + registerTestDriver() + OpenTelemetryDriver.interceptorMode = true + def connection = OpenTelemetryDriver.INSTANCE.connect("jdbc:test:", null) + + then: + connection != null + connection instanceof OpenTelemetryConnection + } + + def "verify get property info with null url"() { + when: + OpenTelemetryDriver.INSTANCE.getPropertyInfo(null, null) + + then: + def e = thrown(IllegalArgumentException) + e.message == "url is required" + } + + def "verify get property info with empty url"() { + when: + OpenTelemetryDriver.INSTANCE.getPropertyInfo(" ", null) + + then: + def e = thrown(IllegalArgumentException) + e.message == "url is required" + } + + def "verify get property info with unknown driver url"() { + when: + def realUrl = "jdbc:unknown" + OpenTelemetryDriver.INSTANCE.getPropertyInfo(realUrl, null) + + then: + def e = thrown(IllegalStateException) + e.message == "Unable to find a driver that accepts url: ${realUrl}" + } + + def "verify get property info with test driver url"() { + when: + registerTestDriver() + def realUrl = "jdbc:otel:test:" + def propertyInfos = OpenTelemetryDriver.INSTANCE.getPropertyInfo(realUrl, null) + + then: + propertyInfos.size() == 1 + propertyInfos[0].name == "test" + propertyInfos[0].value == "test" + } + + private static void registerTestDriver() { + if (!(DriverManager.drivers.any { it instanceof TestDriver })) { + DriverManager.registerDriver(new TestDriver()) + } + } + +} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy new file mode 100644 index 000000000000..5a339f923161 --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy @@ -0,0 +1,281 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc + +import java.sql.* +import java.util.concurrent.Executor + +class TestConnection implements Connection { + @Override + Statement createStatement() throws SQLException { + return null + } + + @Override + PreparedStatement prepareStatement(String sql) throws SQLException { + return null + } + + @Override + CallableStatement prepareCall(String sql) throws SQLException { + return null + } + + @Override + String nativeSQL(String sql) throws SQLException { + return null + } + + @Override + void setAutoCommit(boolean autoCommit) throws SQLException { + + } + + @Override + boolean getAutoCommit() throws SQLException { + return false + } + + @Override + void commit() throws SQLException { + + } + + @Override + void rollback() throws SQLException { + + } + + @Override + void close() throws SQLException { + + } + + @Override + boolean isClosed() throws SQLException { + return false + } + + @Override + DatabaseMetaData getMetaData() throws SQLException { + return null + } + + @Override + void setReadOnly(boolean readOnly) throws SQLException { + + } + + @Override + boolean isReadOnly() throws SQLException { + return false + } + + @Override + void setCatalog(String catalog) throws SQLException { + + } + + @Override + String getCatalog() throws SQLException { + return null + } + + @Override + void setTransactionIsolation(int level) throws SQLException { + + } + + @Override + int getTransactionIsolation() throws SQLException { + return 0 + } + + @Override + SQLWarning getWarnings() throws SQLException { + return null + } + + @Override + void clearWarnings() throws SQLException { + + } + + @Override + Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + return null + } + + @Override + PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return null + } + + @Override + CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return null + } + + @Override + Map> getTypeMap() throws SQLException { + return null + } + + @Override + void setTypeMap(Map> map) throws SQLException { + + } + + @Override + void setHoldability(int holdability) throws SQLException { + + } + + @Override + int getHoldability() throws SQLException { + return 0 + } + + @Override + Savepoint setSavepoint() throws SQLException { + return null + } + + @Override + Savepoint setSavepoint(String name) throws SQLException { + return null + } + + @Override + void rollback(Savepoint savepoint) throws SQLException { + + } + + @Override + void releaseSavepoint(Savepoint savepoint) throws SQLException { + + } + + @Override + Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return null + } + + @Override + PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return null + } + + @Override + CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return null + } + + @Override + PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return null + } + + @Override + PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return null + } + + @Override + PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return null + } + + @Override + Clob createClob() throws SQLException { + return null + } + + @Override + Blob createBlob() throws SQLException { + return null + } + + @Override + NClob createNClob() throws SQLException { + return null + } + + @Override + SQLXML createSQLXML() throws SQLException { + return null + } + + @Override + boolean isValid(int timeout) throws SQLException { + return false + } + + @Override + void setClientInfo(String name, String value) throws SQLClientInfoException { + + } + + @Override + void setClientInfo(Properties properties) throws SQLClientInfoException { + + } + + @Override + String getClientInfo(String name) throws SQLException { + return null + } + + @Override + Properties getClientInfo() throws SQLException { + return null + } + + @Override + Array createArrayOf(String typeName, Object[] elements) throws SQLException { + return null + } + + @Override + Struct createStruct(String typeName, Object[] attributes) throws SQLException { + return null + } + + @Override + void setSchema(String schema) throws SQLException { + + } + + @Override + String getSchema() throws SQLException { + return null + } + + @Override + void abort(Executor executor) throws SQLException { + + } + + @Override + void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { + + } + + @Override + int getNetworkTimeout() throws SQLException { + return 0 + } + + @Override + def T unwrap(Class iface) throws SQLException { + return null + } + + @Override + boolean isWrapperFor(Class iface) throws SQLException { + return false + } +} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy new file mode 100644 index 000000000000..db93d28ed82f --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc + +import java.sql.* +import java.util.logging.Logger + +class TestDriver implements Driver { + @Override + Connection connect(String url, Properties info) throws SQLException { + return new TestConnection() + } + + @Override + boolean acceptsURL(String url) throws SQLException { + return url?.startsWith("jdbc:test:") + } + + @Override + DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { + return [new DriverPropertyInfo("test", "test")] + } + + @Override + int getMajorVersion() { + return 0 + } + + @Override + int getMinorVersion() { + return 0 + } + + @Override + boolean jdbcCompliant() { + return false + } + + @Override + Logger getParentLogger() throws SQLFeatureNotSupportedException { + return null + } +} From fb14f111400df158c7f0a3a8a5f43bfaee57fba3 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Wed, 23 Jun 2021 16:42:20 +0800 Subject: [PATCH 31/69] Cleanup. --- .../javaagent-unit-tests/jdbc-javaagent-unit-tests.gradle | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 instrumentation/jdbc/javaagent-unit-tests/jdbc-javaagent-unit-tests.gradle diff --git a/instrumentation/jdbc/javaagent-unit-tests/jdbc-javaagent-unit-tests.gradle b/instrumentation/jdbc/javaagent-unit-tests/jdbc-javaagent-unit-tests.gradle deleted file mode 100644 index a3436089d9ad..000000000000 --- a/instrumentation/jdbc/javaagent-unit-tests/jdbc-javaagent-unit-tests.gradle +++ /dev/null @@ -1,5 +0,0 @@ -apply plugin: "otel.java-conventions" - -dependencies { - testImplementation project(':instrumentation:jdbc:javaagent') -} From 0ef50c7ebc53df0e8dffe46b348b633a9fc39535 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Thu, 24 Jun 2021 17:30:46 +0800 Subject: [PATCH 32/69] Covered OpenTelemetryDataSource with tests. --- .../internal/OpenTelemetryConnection.java | 5 + .../jdbc/TestConnection.groovy | 2 +- .../jdbc/TestDatabaseMetaData.groovy | 890 ++++++++++++++++++ .../OpenTelemetryDataSourceTest.groovy | 59 ++ .../jdbc/datasource/TestDataSource.groovy | 64 ++ 5 files changed, 1019 insertions(+), 1 deletion(-) create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSourceTest.groovy create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/datasource/TestDataSource.groovy diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java index 973bdbc050fe..cb39a6cdc30d 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java @@ -347,4 +347,9 @@ public T unwrap(Class iface) throws SQLException { public boolean isWrapperFor(Class iface) throws SQLException { return delegate.isWrapperFor(iface); } + + // visible for testing + public DbInfo getDbInfo() { + return dbInfo; + } } diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy index 5a339f923161..333467cf74c3 100644 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy @@ -61,7 +61,7 @@ class TestConnection implements Connection { @Override DatabaseMetaData getMetaData() throws SQLException { - return null + return new TestDatabaseMetaData() } @Override diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy new file mode 100644 index 000000000000..7b5370c9f11a --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy @@ -0,0 +1,890 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc + +import java.sql.* + +class TestDatabaseMetaData implements DatabaseMetaData { + @Override + boolean allProceduresAreCallable() throws SQLException { + return false + } + + @Override + boolean allTablesAreSelectable() throws SQLException { + return false + } + + @Override + String getURL() throws SQLException { + return "jdbc:postgresql://127.0.0.1:5432/dbname" + } + + @Override + String getUserName() throws SQLException { + return null + } + + @Override + boolean isReadOnly() throws SQLException { + return false + } + + @Override + boolean nullsAreSortedHigh() throws SQLException { + return false + } + + @Override + boolean nullsAreSortedLow() throws SQLException { + return false + } + + @Override + boolean nullsAreSortedAtStart() throws SQLException { + return false + } + + @Override + boolean nullsAreSortedAtEnd() throws SQLException { + return false + } + + @Override + String getDatabaseProductName() throws SQLException { + return null + } + + @Override + String getDatabaseProductVersion() throws SQLException { + return null + } + + @Override + String getDriverName() throws SQLException { + return null + } + + @Override + String getDriverVersion() throws SQLException { + return null + } + + @Override + int getDriverMajorVersion() { + return 0 + } + + @Override + int getDriverMinorVersion() { + return 0 + } + + @Override + boolean usesLocalFiles() throws SQLException { + return false + } + + @Override + boolean usesLocalFilePerTable() throws SQLException { + return false + } + + @Override + boolean supportsMixedCaseIdentifiers() throws SQLException { + return false + } + + @Override + boolean storesUpperCaseIdentifiers() throws SQLException { + return false + } + + @Override + boolean storesLowerCaseIdentifiers() throws SQLException { + return false + } + + @Override + boolean storesMixedCaseIdentifiers() throws SQLException { + return false + } + + @Override + boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { + return false + } + + @Override + boolean storesUpperCaseQuotedIdentifiers() throws SQLException { + return false + } + + @Override + boolean storesLowerCaseQuotedIdentifiers() throws SQLException { + return false + } + + @Override + boolean storesMixedCaseQuotedIdentifiers() throws SQLException { + return false + } + + @Override + String getIdentifierQuoteString() throws SQLException { + return null + } + + @Override + String getSQLKeywords() throws SQLException { + return null + } + + @Override + String getNumericFunctions() throws SQLException { + return null + } + + @Override + String getStringFunctions() throws SQLException { + return null + } + + @Override + String getSystemFunctions() throws SQLException { + return null + } + + @Override + String getTimeDateFunctions() throws SQLException { + return null + } + + @Override + String getSearchStringEscape() throws SQLException { + return null + } + + @Override + String getExtraNameCharacters() throws SQLException { + return null + } + + @Override + boolean supportsAlterTableWithAddColumn() throws SQLException { + return false + } + + @Override + boolean supportsAlterTableWithDropColumn() throws SQLException { + return false + } + + @Override + boolean supportsColumnAliasing() throws SQLException { + return false + } + + @Override + boolean nullPlusNonNullIsNull() throws SQLException { + return false + } + + @Override + boolean supportsConvert() throws SQLException { + return false + } + + @Override + boolean supportsConvert(int fromType, int toType) throws SQLException { + return false + } + + @Override + boolean supportsTableCorrelationNames() throws SQLException { + return false + } + + @Override + boolean supportsDifferentTableCorrelationNames() throws SQLException { + return false + } + + @Override + boolean supportsExpressionsInOrderBy() throws SQLException { + return false + } + + @Override + boolean supportsOrderByUnrelated() throws SQLException { + return false + } + + @Override + boolean supportsGroupBy() throws SQLException { + return false + } + + @Override + boolean supportsGroupByUnrelated() throws SQLException { + return false + } + + @Override + boolean supportsGroupByBeyondSelect() throws SQLException { + return false + } + + @Override + boolean supportsLikeEscapeClause() throws SQLException { + return false + } + + @Override + boolean supportsMultipleResultSets() throws SQLException { + return false + } + + @Override + boolean supportsMultipleTransactions() throws SQLException { + return false + } + + @Override + boolean supportsNonNullableColumns() throws SQLException { + return false + } + + @Override + boolean supportsMinimumSQLGrammar() throws SQLException { + return false + } + + @Override + boolean supportsCoreSQLGrammar() throws SQLException { + return false + } + + @Override + boolean supportsExtendedSQLGrammar() throws SQLException { + return false + } + + @Override + boolean supportsANSI92EntryLevelSQL() throws SQLException { + return false + } + + @Override + boolean supportsANSI92IntermediateSQL() throws SQLException { + return false + } + + @Override + boolean supportsANSI92FullSQL() throws SQLException { + return false + } + + @Override + boolean supportsIntegrityEnhancementFacility() throws SQLException { + return false + } + + @Override + boolean supportsOuterJoins() throws SQLException { + return false + } + + @Override + boolean supportsFullOuterJoins() throws SQLException { + return false + } + + @Override + boolean supportsLimitedOuterJoins() throws SQLException { + return false + } + + @Override + String getSchemaTerm() throws SQLException { + return null + } + + @Override + String getProcedureTerm() throws SQLException { + return null + } + + @Override + String getCatalogTerm() throws SQLException { + return null + } + + @Override + boolean isCatalogAtStart() throws SQLException { + return false + } + + @Override + String getCatalogSeparator() throws SQLException { + return null + } + + @Override + boolean supportsSchemasInDataManipulation() throws SQLException { + return false + } + + @Override + boolean supportsSchemasInProcedureCalls() throws SQLException { + return false + } + + @Override + boolean supportsSchemasInTableDefinitions() throws SQLException { + return false + } + + @Override + boolean supportsSchemasInIndexDefinitions() throws SQLException { + return false + } + + @Override + boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { + return false + } + + @Override + boolean supportsCatalogsInDataManipulation() throws SQLException { + return false + } + + @Override + boolean supportsCatalogsInProcedureCalls() throws SQLException { + return false + } + + @Override + boolean supportsCatalogsInTableDefinitions() throws SQLException { + return false + } + + @Override + boolean supportsCatalogsInIndexDefinitions() throws SQLException { + return false + } + + @Override + boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { + return false + } + + @Override + boolean supportsPositionedDelete() throws SQLException { + return false + } + + @Override + boolean supportsPositionedUpdate() throws SQLException { + return false + } + + @Override + boolean supportsSelectForUpdate() throws SQLException { + return false + } + + @Override + boolean supportsStoredProcedures() throws SQLException { + return false + } + + @Override + boolean supportsSubqueriesInComparisons() throws SQLException { + return false + } + + @Override + boolean supportsSubqueriesInExists() throws SQLException { + return false + } + + @Override + boolean supportsSubqueriesInIns() throws SQLException { + return false + } + + @Override + boolean supportsSubqueriesInQuantifieds() throws SQLException { + return false + } + + @Override + boolean supportsCorrelatedSubqueries() throws SQLException { + return false + } + + @Override + boolean supportsUnion() throws SQLException { + return false + } + + @Override + boolean supportsUnionAll() throws SQLException { + return false + } + + @Override + boolean supportsOpenCursorsAcrossCommit() throws SQLException { + return false + } + + @Override + boolean supportsOpenCursorsAcrossRollback() throws SQLException { + return false + } + + @Override + boolean supportsOpenStatementsAcrossCommit() throws SQLException { + return false + } + + @Override + boolean supportsOpenStatementsAcrossRollback() throws SQLException { + return false + } + + @Override + int getMaxBinaryLiteralLength() throws SQLException { + return 0 + } + + @Override + int getMaxCharLiteralLength() throws SQLException { + return 0 + } + + @Override + int getMaxColumnNameLength() throws SQLException { + return 0 + } + + @Override + int getMaxColumnsInGroupBy() throws SQLException { + return 0 + } + + @Override + int getMaxColumnsInIndex() throws SQLException { + return 0 + } + + @Override + int getMaxColumnsInOrderBy() throws SQLException { + return 0 + } + + @Override + int getMaxColumnsInSelect() throws SQLException { + return 0 + } + + @Override + int getMaxColumnsInTable() throws SQLException { + return 0 + } + + @Override + int getMaxConnections() throws SQLException { + return 0 + } + + @Override + int getMaxCursorNameLength() throws SQLException { + return 0 + } + + @Override + int getMaxIndexLength() throws SQLException { + return 0 + } + + @Override + int getMaxSchemaNameLength() throws SQLException { + return 0 + } + + @Override + int getMaxProcedureNameLength() throws SQLException { + return 0 + } + + @Override + int getMaxCatalogNameLength() throws SQLException { + return 0 + } + + @Override + int getMaxRowSize() throws SQLException { + return 0 + } + + @Override + boolean doesMaxRowSizeIncludeBlobs() throws SQLException { + return false + } + + @Override + int getMaxStatementLength() throws SQLException { + return 0 + } + + @Override + int getMaxStatements() throws SQLException { + return 0 + } + + @Override + int getMaxTableNameLength() throws SQLException { + return 0 + } + + @Override + int getMaxTablesInSelect() throws SQLException { + return 0 + } + + @Override + int getMaxUserNameLength() throws SQLException { + return 0 + } + + @Override + int getDefaultTransactionIsolation() throws SQLException { + return 0 + } + + @Override + boolean supportsTransactions() throws SQLException { + return false + } + + @Override + boolean supportsTransactionIsolationLevel(int level) throws SQLException { + return false + } + + @Override + boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { + return false + } + + @Override + boolean supportsDataManipulationTransactionsOnly() throws SQLException { + return false + } + + @Override + boolean dataDefinitionCausesTransactionCommit() throws SQLException { + return false + } + + @Override + boolean dataDefinitionIgnoredInTransactions() throws SQLException { + return false + } + + @Override + ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { + return null + } + + @Override + ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { + return null + } + + @Override + ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { + return null + } + + @Override + ResultSet getSchemas() throws SQLException { + return null + } + + @Override + ResultSet getCatalogs() throws SQLException { + return null + } + + @Override + ResultSet getTableTypes() throws SQLException { + return null + } + + @Override + ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { + return null + } + + @Override + ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { + return null + } + + @Override + ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { + return null + } + + @Override + ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { + return null + } + + @Override + ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { + return null + } + + @Override + ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { + return null + } + + @Override + ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { + return null + } + + @Override + ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { + return null + } + + @Override + ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { + return null + } + + @Override + ResultSet getTypeInfo() throws SQLException { + return null + } + + @Override + ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { + return null + } + + @Override + boolean supportsResultSetType(int type) throws SQLException { + return false + } + + @Override + boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { + return false + } + + @Override + boolean ownUpdatesAreVisible(int type) throws SQLException { + return false + } + + @Override + boolean ownDeletesAreVisible(int type) throws SQLException { + return false + } + + @Override + boolean ownInsertsAreVisible(int type) throws SQLException { + return false + } + + @Override + boolean othersUpdatesAreVisible(int type) throws SQLException { + return false + } + + @Override + boolean othersDeletesAreVisible(int type) throws SQLException { + return false + } + + @Override + boolean othersInsertsAreVisible(int type) throws SQLException { + return false + } + + @Override + boolean updatesAreDetected(int type) throws SQLException { + return false + } + + @Override + boolean deletesAreDetected(int type) throws SQLException { + return false + } + + @Override + boolean insertsAreDetected(int type) throws SQLException { + return false + } + + @Override + boolean supportsBatchUpdates() throws SQLException { + return false + } + + @Override + ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { + return null + } + + @Override + Connection getConnection() throws SQLException { + return null + } + + @Override + boolean supportsSavepoints() throws SQLException { + return false + } + + @Override + boolean supportsNamedParameters() throws SQLException { + return false + } + + @Override + boolean supportsMultipleOpenResults() throws SQLException { + return false + } + + @Override + boolean supportsGetGeneratedKeys() throws SQLException { + return false + } + + @Override + ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { + return null + } + + @Override + ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { + return null + } + + @Override + ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { + return null + } + + @Override + boolean supportsResultSetHoldability(int holdability) throws SQLException { + return false + } + + @Override + int getResultSetHoldability() throws SQLException { + return 0 + } + + @Override + int getDatabaseMajorVersion() throws SQLException { + return 0 + } + + @Override + int getDatabaseMinorVersion() throws SQLException { + return 0 + } + + @Override + int getJDBCMajorVersion() throws SQLException { + return 0 + } + + @Override + int getJDBCMinorVersion() throws SQLException { + return 0 + } + + @Override + int getSQLStateType() throws SQLException { + return 0 + } + + @Override + boolean locatorsUpdateCopy() throws SQLException { + return false + } + + @Override + boolean supportsStatementPooling() throws SQLException { + return false + } + + @Override + RowIdLifetime getRowIdLifetime() throws SQLException { + return null + } + + @Override + ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { + return null + } + + @Override + boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { + return false + } + + @Override + boolean autoCommitFailureClosesAllResultSets() throws SQLException { + return false + } + + @Override + ResultSet getClientInfoProperties() throws SQLException { + return null + } + + @Override + ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException { + return null + } + + @Override + ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException { + return null + } + + @Override + ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { + return null + } + + @Override + boolean generatedKeyAlwaysReturned() throws SQLException { + return false + } + + @Override + def T unwrap(Class iface) throws SQLException { + return null + } + + @Override + boolean isWrapperFor(Class iface) throws SQLException { + return false + } +} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSourceTest.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSourceTest.groovy new file mode 100644 index 000000000000..7e8e92fdaa74 --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSourceTest.groovy @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc.datasource + +import io.opentelemetry.instrumentation.jdbc.internal.OpenTelemetryConnection +import spock.lang.Specification + +class OpenTelemetryDataSourceTest extends Specification { + + def "verify get connection"() { + when: + def dataSource = new OpenTelemetryDataSource(new TestDataSource()) + def connection = dataSource.getConnection() + + then: + connection != null + connection instanceof OpenTelemetryConnection + + when: + def dbInfo = ((OpenTelemetryConnection) connection).dbInfo + + then: + dbInfo.system == "postgresql" + dbInfo.subtype == null + dbInfo.shortUrl == "postgresql://127.0.0.1:5432" + dbInfo.user == null + dbInfo.name == null + dbInfo.db == "dbname" + dbInfo.host == "127.0.0.1" + dbInfo.port == 5432 + } + + def "verify get connection with username and password"() { + when: + def dataSource = new OpenTelemetryDataSource(new TestDataSource()) + def connection = dataSource.getConnection(null, null) + + then: + connection != null + connection instanceof OpenTelemetryConnection + + when: + def dbInfo = ((OpenTelemetryConnection) connection).dbInfo + + then: + dbInfo.system == "postgresql" + dbInfo.subtype == null + dbInfo.shortUrl == "postgresql://127.0.0.1:5432" + dbInfo.user == null + dbInfo.name == null + dbInfo.db == "dbname" + dbInfo.host == "127.0.0.1" + dbInfo.port == 5432 + } + +} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/datasource/TestDataSource.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/datasource/TestDataSource.groovy new file mode 100644 index 000000000000..78e2d6366fc5 --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/datasource/TestDataSource.groovy @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc.datasource + +import io.opentelemetry.instrumentation.jdbc.TestConnection + +import javax.sql.DataSource +import java.sql.Connection +import java.sql.SQLException +import java.sql.SQLFeatureNotSupportedException +import java.util.logging.Logger + +class TestDataSource implements DataSource { + + @Override + Connection getConnection() throws SQLException { + return new TestConnection() + } + + @Override + Connection getConnection(String username, String password) throws SQLException { + return new TestConnection() + } + + @Override + PrintWriter getLogWriter() throws SQLException { + return null + } + + @Override + void setLogWriter(PrintWriter out) throws SQLException { + + } + + @Override + void setLoginTimeout(int seconds) throws SQLException { + + } + + @Override + int getLoginTimeout() throws SQLException { + return 0 + } + + @Override + Logger getParentLogger() throws SQLFeatureNotSupportedException { + return null + } + + @Override + def T unwrap(Class iface) throws SQLException { + return null + } + + @Override + boolean isWrapperFor(Class iface) throws SQLException { + return false + } + +} + From 07e1ab729184541d71457e791288d31b68a688cd Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Thu, 24 Jun 2021 19:49:42 +0800 Subject: [PATCH 33/69] Covered OpenTelemetryConnection with tests. --- .../groovy/test/TestPreparedStatement.groovy | 17 +- .../OpenTelemetryCallableStatement.java | 2 +- .../OpenTelemetryPreparedStatement.java | 4 +- .../jdbc/internal/OpenTelemetryStatement.java | 2 +- .../jdbc/OpenTelemetryConnectionTest.groovy | 182 ++++++ .../jdbc/TestCallableStatement.groovy | 575 ++++++++++++++++++ .../jdbc/TestConnection.groovy | 96 +-- .../jdbc/TestPreparedStatement.groovy | 285 +++++++++ .../instrumentation/jdbc/TestStatement.groovy | 230 +++++++ 9 files changed, 1325 insertions(+), 68 deletions(-) create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnectionTest.groovy create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestCallableStatement.groovy create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy create mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy diff --git a/instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy b/instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy index 5f2b4f1a02da..b0fad08781cf 100644 --- a/instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy +++ b/instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy @@ -5,22 +5,7 @@ package test -import java.sql.Array -import java.sql.Blob -import java.sql.Clob -import java.sql.Connection -import java.sql.Date -import java.sql.NClob -import java.sql.ParameterMetaData -import java.sql.PreparedStatement -import java.sql.Ref -import java.sql.ResultSet -import java.sql.ResultSetMetaData -import java.sql.RowId -import java.sql.SQLException -import java.sql.SQLXML -import java.sql.Time -import java.sql.Timestamp +import java.sql.* class TestPreparedStatement extends TestStatement implements PreparedStatement { TestPreparedStatement(Connection connection) { diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java index 3abaa29b78b3..97bcb226e4ce 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java @@ -39,7 +39,7 @@ import java.util.Calendar; import java.util.Map; -class OpenTelemetryCallableStatement +public class OpenTelemetryCallableStatement extends OpenTelemetryPreparedStatement implements CallableStatement { public OpenTelemetryCallableStatement(S delegate, DbInfo dbInfo, String query) { diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java index 292075f2dce7..d40cfdf8682a 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java @@ -41,8 +41,8 @@ import java.sql.Timestamp; import java.util.Calendar; -class OpenTelemetryPreparedStatement extends OpenTelemetryStatement - implements PreparedStatement { +public class OpenTelemetryPreparedStatement + extends OpenTelemetryStatement implements PreparedStatement { public OpenTelemetryPreparedStatement(S delegate, DbInfo dbInfo, String query) { super(delegate, dbInfo, query); diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java index ba1f3ed899f8..c75d64713522 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java @@ -31,7 +31,7 @@ import java.sql.Statement; import java.util.ArrayList; -class OpenTelemetryStatement implements Statement { +public class OpenTelemetryStatement implements Statement { protected final S delegate; protected final DbInfo dbInfo; diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnectionTest.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnectionTest.groovy new file mode 100644 index 000000000000..3e155360135e --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnectionTest.groovy @@ -0,0 +1,182 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc + +import io.opentelemetry.instrumentation.jdbc.internal.* +import io.opentelemetry.instrumentation.test.InstrumentationSpecification +import io.opentelemetry.instrumentation.test.LibraryTestTrait +import io.opentelemetry.semconv.trace.attributes.SemanticAttributes + +import static io.opentelemetry.api.trace.SpanKind.CLIENT +import static io.opentelemetry.instrumentation.test.utils.TraceUtils.basicSpan +import static io.opentelemetry.instrumentation.test.utils.TraceUtils.runUnderTrace + +class OpenTelemetryConnectionTest extends InstrumentationSpecification implements LibraryTestTrait { + + def "verify create statement"() { + setup: + def dbInfo = getDbInfo() + def connection = new OpenTelemetryConnection(new TestConnection(), dbInfo) + String query = "SELECT * FROM users" + def statement = connection.createStatement() + runUnderTrace("parent") { + assert statement.execute(query) + } + + expect: + assertTraces(1) { + trace(0, 2) { + basicSpan(it, 0, "parent") + span(1) { + name "SELECT my_name.users" + kind CLIENT + childOf span(0) + attributes { + "$SemanticAttributes.DB_SYSTEM.key" dbInfo.system + "$SemanticAttributes.DB_NAME.key" dbInfo.name + "$SemanticAttributes.DB_USER.key" dbInfo.user + "$SemanticAttributes.DB_CONNECTION_STRING.key" dbInfo.shortUrl + "$SemanticAttributes.NET_PEER_NAME.key" dbInfo.host + "$SemanticAttributes.NET_PEER_PORT.key" dbInfo.port + "$SemanticAttributes.NET_PEER_IP.key" null + "$SemanticAttributes.DB_STATEMENT.key" query + "$SemanticAttributes.DB_OPERATION.key" "SELECT" + "$SemanticAttributes.DB_SQL_TABLE.key" "users" + } + } + } + } + + cleanup: + statement.close() + connection.close() + } + + def "verify create statement returns otel wrapper"() { + when: + def connection = new OpenTelemetryConnection(new TestConnection(), DbInfo.DEFAULT) + + then: + connection.createStatement().class == OpenTelemetryStatement + connection.createStatement(0, 0).class == OpenTelemetryStatement + connection.createStatement(0, 0, 0).class == OpenTelemetryStatement + } + + def "verify prepare statement"() { + setup: + def dbInfo = getDbInfo() + def connection = new OpenTelemetryConnection(new TestConnection(), dbInfo) + String query = "SELECT * FROM users" + def statement = connection.prepareStatement(query) + runUnderTrace("parent") { + assert statement.execute() + } + + expect: + assertTraces(1) { + trace(0, 2) { + basicSpan(it, 0, "parent") + span(1) { + name "SELECT my_name.users" + kind CLIENT + childOf span(0) + attributes { + "$SemanticAttributes.DB_SYSTEM.key" dbInfo.system + "$SemanticAttributes.DB_NAME.key" dbInfo.name + "$SemanticAttributes.DB_USER.key" dbInfo.user + "$SemanticAttributes.DB_CONNECTION_STRING.key" dbInfo.shortUrl + "$SemanticAttributes.NET_PEER_NAME.key" dbInfo.host + "$SemanticAttributes.NET_PEER_PORT.key" dbInfo.port + "$SemanticAttributes.NET_PEER_IP.key" null + "$SemanticAttributes.DB_STATEMENT.key" query + "$SemanticAttributes.DB_OPERATION.key" "SELECT" + "$SemanticAttributes.DB_SQL_TABLE.key" "users" + } + } + } + } + + cleanup: + statement.close() + connection.close() + } + + def "verify prepare statement returns otel wrapper"() { + when: + def connection = new OpenTelemetryConnection(new TestConnection(), DbInfo.DEFAULT) + + then: + connection.prepareStatement("SELECT * FROM users").class == OpenTelemetryPreparedStatement + connection.prepareStatement("SELECT * FROM users", [0] as int[]).class == OpenTelemetryPreparedStatement + connection.prepareStatement("SELECT * FROM users", ["id"] as String[]).class == OpenTelemetryPreparedStatement + connection.prepareStatement("SELECT * FROM users", 0).class == OpenTelemetryPreparedStatement + connection.prepareStatement("SELECT * FROM users", 0, 0).class == OpenTelemetryPreparedStatement + connection.prepareStatement("SELECT * FROM users", 0, 0, 0).class == OpenTelemetryPreparedStatement + } + + def "verify prepare call"() { + setup: + def dbInfo = getDbInfo() + def connection = new OpenTelemetryConnection(new TestConnection(), dbInfo) + String query = "SELECT * FROM users" + def statement = connection.prepareCall(query) + runUnderTrace("parent") { + assert statement.execute() + } + + expect: + assertTraces(1) { + trace(0, 2) { + basicSpan(it, 0, "parent") + span(1) { + name "SELECT my_name.users" + kind CLIENT + childOf span(0) + attributes { + "$SemanticAttributes.DB_SYSTEM.key" dbInfo.system + "$SemanticAttributes.DB_NAME.key" dbInfo.name + "$SemanticAttributes.DB_USER.key" dbInfo.user + "$SemanticAttributes.DB_CONNECTION_STRING.key" dbInfo.shortUrl + "$SemanticAttributes.NET_PEER_NAME.key" dbInfo.host + "$SemanticAttributes.NET_PEER_PORT.key" dbInfo.port + "$SemanticAttributes.NET_PEER_IP.key" null + "$SemanticAttributes.DB_STATEMENT.key" query + "$SemanticAttributes.DB_OPERATION.key" "SELECT" + "$SemanticAttributes.DB_SQL_TABLE.key" "users" + } + } + } + } + + cleanup: + statement.close() + connection.close() + } + + def "verify prepare call returns otel wrapper"() { + when: + def connection = new OpenTelemetryConnection(new TestConnection(), DbInfo.DEFAULT) + + then: + connection.prepareCall("SELECT * FROM users").class == OpenTelemetryCallableStatement + connection.prepareCall("SELECT * FROM users", 0, 0).class == OpenTelemetryCallableStatement + connection.prepareCall("SELECT * FROM users", 0, 0, 0).class == OpenTelemetryCallableStatement + } + + private DbInfo getDbInfo() { + DbInfo.builder() + .system("my_system") + .subtype("my_sub_type") + .shortUrl("my_connection_string") + .user("my_user") + .name("my_name") + .db("my_db") + .host("my_host") + .port(1234) + .build() + } + +} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestCallableStatement.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestCallableStatement.groovy new file mode 100644 index 000000000000..b7980fee699e --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestCallableStatement.groovy @@ -0,0 +1,575 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc + +import java.sql.* + +class TestCallableStatement extends TestPreparedStatement implements CallableStatement { + @Override + void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { + + } + + @Override + void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { + + } + + @Override + boolean wasNull() throws SQLException { + return false + } + + @Override + String getString(int parameterIndex) throws SQLException { + return null + } + + @Override + boolean getBoolean(int parameterIndex) throws SQLException { + return false + } + + @Override + byte getByte(int parameterIndex) throws SQLException { + return 0 + } + + @Override + short getShort(int parameterIndex) throws SQLException { + return 0 + } + + @Override + int getInt(int parameterIndex) throws SQLException { + return 0 + } + + @Override + long getLong(int parameterIndex) throws SQLException { + return 0 + } + + @Override + float getFloat(int parameterIndex) throws SQLException { + return 0 + } + + @Override + double getDouble(int parameterIndex) throws SQLException { + return 0 + } + + @Override + BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { + return null + } + + @Override + byte[] getBytes(int parameterIndex) throws SQLException { + return new byte[0] + } + + @Override + Date getDate(int parameterIndex) throws SQLException { + return null + } + + @Override + Time getTime(int parameterIndex) throws SQLException { + return null + } + + @Override + Timestamp getTimestamp(int parameterIndex) throws SQLException { + return null + } + + @Override + Object getObject(int parameterIndex) throws SQLException { + return null + } + + @Override + BigDecimal getBigDecimal(int parameterIndex) throws SQLException { + return null + } + + @Override + Object getObject(int parameterIndex, Map> map) throws SQLException { + return null + } + + @Override + Ref getRef(int parameterIndex) throws SQLException { + return null + } + + @Override + Blob getBlob(int parameterIndex) throws SQLException { + return null + } + + @Override + Clob getClob(int parameterIndex) throws SQLException { + return null + } + + @Override + Array getArray(int parameterIndex) throws SQLException { + return null + } + + @Override + Date getDate(int parameterIndex, Calendar cal) throws SQLException { + return null + } + + @Override + Time getTime(int parameterIndex, Calendar cal) throws SQLException { + return null + } + + @Override + Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { + return null + } + + @Override + void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { + + } + + @Override + void registerOutParameter(String parameterName, int sqlType) throws SQLException { + + } + + @Override + void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { + + } + + @Override + void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { + + } + + @Override + URL getURL(int parameterIndex) throws SQLException { + return null + } + + @Override + void setURL(String parameterName, URL val) throws SQLException { + + } + + @Override + void setNull(String parameterName, int sqlType) throws SQLException { + + } + + @Override + void setBoolean(String parameterName, boolean x) throws SQLException { + + } + + @Override + void setByte(String parameterName, byte x) throws SQLException { + + } + + @Override + void setShort(String parameterName, short x) throws SQLException { + + } + + @Override + void setInt(String parameterName, int x) throws SQLException { + + } + + @Override + void setLong(String parameterName, long x) throws SQLException { + + } + + @Override + void setFloat(String parameterName, float x) throws SQLException { + + } + + @Override + void setDouble(String parameterName, double x) throws SQLException { + + } + + @Override + void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { + + } + + @Override + void setString(String parameterName, String x) throws SQLException { + + } + + @Override + void setBytes(String parameterName, byte[] x) throws SQLException { + + } + + @Override + void setDate(String parameterName, Date x) throws SQLException { + + } + + @Override + void setTime(String parameterName, Time x) throws SQLException { + + } + + @Override + void setTimestamp(String parameterName, Timestamp x) throws SQLException { + + } + + @Override + void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException { + + } + + @Override + void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException { + + } + + @Override + void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { + + } + + @Override + void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { + + } + + @Override + void setObject(String parameterName, Object x) throws SQLException { + + } + + @Override + void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException { + + } + + @Override + void setDate(String parameterName, Date x, Calendar cal) throws SQLException { + + } + + @Override + void setTime(String parameterName, Time x, Calendar cal) throws SQLException { + + } + + @Override + void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { + + } + + @Override + void setNull(String parameterName, int sqlType, String typeName) throws SQLException { + + } + + @Override + String getString(String parameterName) throws SQLException { + return null + } + + @Override + boolean getBoolean(String parameterName) throws SQLException { + return false + } + + @Override + byte getByte(String parameterName) throws SQLException { + return 0 + } + + @Override + short getShort(String parameterName) throws SQLException { + return 0 + } + + @Override + int getInt(String parameterName) throws SQLException { + return 0 + } + + @Override + long getLong(String parameterName) throws SQLException { + return 0 + } + + @Override + float getFloat(String parameterName) throws SQLException { + return 0 + } + + @Override + double getDouble(String parameterName) throws SQLException { + return 0 + } + + @Override + byte[] getBytes(String parameterName) throws SQLException { + return new byte[0] + } + + @Override + Date getDate(String parameterName) throws SQLException { + return null + } + + @Override + Time getTime(String parameterName) throws SQLException { + return null + } + + @Override + Timestamp getTimestamp(String parameterName) throws SQLException { + return null + } + + @Override + Object getObject(String parameterName) throws SQLException { + return null + } + + @Override + BigDecimal getBigDecimal(String parameterName) throws SQLException { + return null + } + + @Override + Object getObject(String parameterName, Map> map) throws SQLException { + return null + } + + @Override + Ref getRef(String parameterName) throws SQLException { + return null + } + + @Override + Blob getBlob(String parameterName) throws SQLException { + return null + } + + @Override + Clob getClob(String parameterName) throws SQLException { + return null + } + + @Override + Array getArray(String parameterName) throws SQLException { + return null + } + + @Override + Date getDate(String parameterName, Calendar cal) throws SQLException { + return null + } + + @Override + Time getTime(String parameterName, Calendar cal) throws SQLException { + return null + } + + @Override + Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { + return null + } + + @Override + URL getURL(String parameterName) throws SQLException { + return null + } + + @Override + RowId getRowId(int parameterIndex) throws SQLException { + return null + } + + @Override + RowId getRowId(String parameterName) throws SQLException { + return null + } + + @Override + void setRowId(String parameterName, RowId x) throws SQLException { + + } + + @Override + void setNString(String parameterName, String value) throws SQLException { + + } + + @Override + void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { + + } + + @Override + void setNClob(String parameterName, NClob value) throws SQLException { + + } + + @Override + void setClob(String parameterName, Reader reader, long length) throws SQLException { + + } + + @Override + void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { + + } + + @Override + void setNClob(String parameterName, Reader reader, long length) throws SQLException { + + } + + @Override + NClob getNClob(int parameterIndex) throws SQLException { + return null + } + + @Override + NClob getNClob(String parameterName) throws SQLException { + return null + } + + @Override + void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { + + } + + @Override + SQLXML getSQLXML(int parameterIndex) throws SQLException { + return null + } + + @Override + SQLXML getSQLXML(String parameterName) throws SQLException { + return null + } + + @Override + String getNString(int parameterIndex) throws SQLException { + return null + } + + @Override + String getNString(String parameterName) throws SQLException { + return null + } + + @Override + Reader getNCharacterStream(int parameterIndex) throws SQLException { + return null + } + + @Override + Reader getNCharacterStream(String parameterName) throws SQLException { + return null + } + + @Override + Reader getCharacterStream(int parameterIndex) throws SQLException { + return null + } + + @Override + Reader getCharacterStream(String parameterName) throws SQLException { + return null + } + + @Override + void setBlob(String parameterName, Blob x) throws SQLException { + + } + + @Override + void setClob(String parameterName, Clob x) throws SQLException { + + } + + @Override + void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { + + } + + @Override + void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException { + + } + + @Override + void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException { + + } + + @Override + void setAsciiStream(String parameterName, InputStream x) throws SQLException { + + } + + @Override + void setBinaryStream(String parameterName, InputStream x) throws SQLException { + + } + + @Override + void setCharacterStream(String parameterName, Reader reader) throws SQLException { + + } + + @Override + void setNCharacterStream(String parameterName, Reader value) throws SQLException { + + } + + @Override + void setClob(String parameterName, Reader reader) throws SQLException { + + } + + @Override + void setBlob(String parameterName, InputStream inputStream) throws SQLException { + + } + + @Override + void setNClob(String parameterName, Reader reader) throws SQLException { + + } + + @Override + def T getObject(int parameterIndex, Class type) throws SQLException { + return null + } + + @Override + def T getObject(String parameterName, Class type) throws SQLException { + return null + } +} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy index 333467cf74c3..9f0d549e07c3 100644 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy @@ -11,17 +11,62 @@ import java.util.concurrent.Executor class TestConnection implements Connection { @Override Statement createStatement() throws SQLException { - return null + return new TestStatement() + } + + @Override + Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + return new TestStatement() + } + + @Override + Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return new TestStatement() } @Override PreparedStatement prepareStatement(String sql) throws SQLException { - return null + return new TestPreparedStatement() + } + + @Override + PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return new TestPreparedStatement() + } + + @Override + PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return new TestPreparedStatement() + } + + @Override + PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return new TestPreparedStatement() + } + + @Override + PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return new TestPreparedStatement() + } + + @Override + PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return new TestPreparedStatement() } @Override CallableStatement prepareCall(String sql) throws SQLException { - return null + return new TestCallableStatement() + } + + @Override + CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return new TestCallableStatement() + } + + @Override + CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return new TestCallableStatement() } @Override @@ -104,21 +149,6 @@ class TestConnection implements Connection { } - @Override - Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return null - } - - @Override - CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return null - } - @Override Map> getTypeMap() throws SQLException { return null @@ -159,36 +189,6 @@ class TestConnection implements Connection { } - @Override - Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return null - } - - @Override - CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - return null - } - @Override Clob createClob() throws SQLException { return null diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy new file mode 100644 index 000000000000..083755c715f0 --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy @@ -0,0 +1,285 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc + +import java.sql.* + +class TestPreparedStatement extends TestStatement implements PreparedStatement { + @Override + boolean execute() throws SQLException { + return true + } + + @Override + ResultSet executeQuery() throws SQLException { + return null + } + + @Override + int executeUpdate() throws SQLException { + return 0 + } + + @Override + void setNull(int parameterIndex, int sqlType) throws SQLException { + + } + + @Override + void setBoolean(int parameterIndex, boolean x) throws SQLException { + + } + + @Override + void setByte(int parameterIndex, byte x) throws SQLException { + + } + + @Override + void setShort(int parameterIndex, short x) throws SQLException { + + } + + @Override + void setInt(int parameterIndex, int x) throws SQLException { + + } + + @Override + void setLong(int parameterIndex, long x) throws SQLException { + + } + + @Override + void setFloat(int parameterIndex, float x) throws SQLException { + + } + + @Override + void setDouble(int parameterIndex, double x) throws SQLException { + + } + + @Override + void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { + + } + + @Override + void setString(int parameterIndex, String x) throws SQLException { + + } + + @Override + void setBytes(int parameterIndex, byte[] x) throws SQLException { + + } + + @Override + void setDate(int parameterIndex, Date x) throws SQLException { + + } + + @Override + void setTime(int parameterIndex, Time x) throws SQLException { + + } + + @Override + void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { + + } + + @Override + void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { + + } + + @Override + void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { + + } + + @Override + void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { + + } + + @Override + void clearParameters() throws SQLException { + + } + + @Override + void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { + + } + + @Override + void setObject(int parameterIndex, Object x) throws SQLException { + + } + + @Override + void addBatch() throws SQLException { + + } + + @Override + void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { + + } + + @Override + void setRef(int parameterIndex, Ref x) throws SQLException { + + } + + @Override + void setBlob(int parameterIndex, Blob x) throws SQLException { + + } + + @Override + void setClob(int parameterIndex, Clob x) throws SQLException { + + } + + @Override + void setArray(int parameterIndex, Array x) throws SQLException { + + } + + @Override + ResultSetMetaData getMetaData() throws SQLException { + return null + } + + @Override + void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { + + } + + @Override + void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { + + } + + @Override + void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { + + } + + @Override + void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { + + } + + @Override + void setURL(int parameterIndex, URL x) throws SQLException { + + } + + @Override + ParameterMetaData getParameterMetaData() throws SQLException { + return null + } + + @Override + void setRowId(int parameterIndex, RowId x) throws SQLException { + + } + + @Override + void setNString(int parameterIndex, String value) throws SQLException { + + } + + @Override + void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { + + } + + @Override + void setNClob(int parameterIndex, NClob value) throws SQLException { + + } + + @Override + void setClob(int parameterIndex, Reader reader, long length) throws SQLException { + + } + + @Override + void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { + + } + + @Override + void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { + + } + + @Override + void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { + + } + + @Override + void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { + + } + + @Override + void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { + + } + + @Override + void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { + + } + + @Override + void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { + + } + + @Override + void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { + + } + + @Override + void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { + + } + + @Override + void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { + + } + + @Override + void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { + + } + + @Override + void setClob(int parameterIndex, Reader reader) throws SQLException { + + } + + @Override + void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { + + } + + @Override + void setNClob(int parameterIndex, Reader reader) throws SQLException { + + } +} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy new file mode 100644 index 000000000000..fd9f4dc3af20 --- /dev/null +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy @@ -0,0 +1,230 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.instrumentation.jdbc + +import java.sql.* + +class TestStatement implements Statement { + @Override + boolean execute(String sql) throws SQLException { + return true + } + + @Override + boolean execute(String sql, int autoGeneratedKeys) throws SQLException { + return true + } + + @Override + boolean execute(String sql, int[] columnIndexes) throws SQLException { + return true + } + + @Override + boolean execute(String sql, String[] columnNames) throws SQLException { + return true + } + + @Override + ResultSet executeQuery(String sql) throws SQLException { + return null + } + + @Override + int executeUpdate(String sql) throws SQLException { + return 0 + } + + @Override + int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { + return 0 + } + + @Override + int executeUpdate(String sql, int[] columnIndexes) throws SQLException { + return 0 + } + + @Override + int executeUpdate(String sql, String[] columnNames) throws SQLException { + return 0 + } + + @Override + void close() throws SQLException { + + } + + @Override + int getMaxFieldSize() throws SQLException { + return 0 + } + + @Override + void setMaxFieldSize(int max) throws SQLException { + + } + + @Override + int getMaxRows() throws SQLException { + return 0 + } + + @Override + void setMaxRows(int max) throws SQLException { + + } + + @Override + void setEscapeProcessing(boolean enable) throws SQLException { + + } + + @Override + int getQueryTimeout() throws SQLException { + return 0 + } + + @Override + void setQueryTimeout(int seconds) throws SQLException { + + } + + @Override + void cancel() throws SQLException { + + } + + @Override + SQLWarning getWarnings() throws SQLException { + return null + } + + @Override + void clearWarnings() throws SQLException { + + } + + @Override + void setCursorName(String name) throws SQLException { + + } + + @Override + ResultSet getResultSet() throws SQLException { + return null + } + + @Override + int getUpdateCount() throws SQLException { + return 0 + } + + @Override + boolean getMoreResults() throws SQLException { + return false + } + + @Override + void setFetchDirection(int direction) throws SQLException { + + } + + @Override + int getFetchDirection() throws SQLException { + return 0 + } + + @Override + void setFetchSize(int rows) throws SQLException { + + } + + @Override + int getFetchSize() throws SQLException { + return 0 + } + + @Override + int getResultSetConcurrency() throws SQLException { + return 0 + } + + @Override + int getResultSetType() throws SQLException { + return 0 + } + + @Override + void addBatch(String sql) throws SQLException { + + } + + @Override + void clearBatch() throws SQLException { + + } + + @Override + int[] executeBatch() throws SQLException { + return new int[0] + } + + @Override + Connection getConnection() throws SQLException { + return null + } + + @Override + boolean getMoreResults(int current) throws SQLException { + return false + } + + @Override + ResultSet getGeneratedKeys() throws SQLException { + return null + } + + @Override + int getResultSetHoldability() throws SQLException { + return 0 + } + + @Override + boolean isClosed() throws SQLException { + return false + } + + @Override + void setPoolable(boolean poolable) throws SQLException { + + } + + @Override + boolean isPoolable() throws SQLException { + return false + } + + @Override + void closeOnCompletion() throws SQLException { + + } + + @Override + boolean isCloseOnCompletion() throws SQLException { + return false + } + + @Override + def T unwrap(Class iface) throws SQLException { + return null + } + + @Override + boolean isWrapperFor(Class iface) throws SQLException { + return false + } +} From 4112488132280814976b730983e1f07c439ca480 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Thu, 24 Jun 2021 20:54:48 +0800 Subject: [PATCH 34/69] Revert TestPreparedStatement. --- .../groovy/test/TestPreparedStatement.groovy | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy b/instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy index b0fad08781cf..5f2b4f1a02da 100644 --- a/instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy +++ b/instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy @@ -5,7 +5,22 @@ package test -import java.sql.* +import java.sql.Array +import java.sql.Blob +import java.sql.Clob +import java.sql.Connection +import java.sql.Date +import java.sql.NClob +import java.sql.ParameterMetaData +import java.sql.PreparedStatement +import java.sql.Ref +import java.sql.ResultSet +import java.sql.ResultSetMetaData +import java.sql.RowId +import java.sql.SQLException +import java.sql.SQLXML +import java.sql.Time +import java.sql.Timestamp class TestPreparedStatement extends TestStatement implements PreparedStatement { TestPreparedStatement(Connection connection) { From fa9c60ce1b531cf58a5fe9655b813a2782d966bc Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Thu, 24 Jun 2021 22:43:47 +0800 Subject: [PATCH 35/69] Added README. --- instrumentation/jdbc/library/README.md | 88 ++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 instrumentation/jdbc/library/README.md diff --git a/instrumentation/jdbc/library/README.md b/instrumentation/jdbc/library/README.md new file mode 100644 index 000000000000..44e33b599db9 --- /dev/null +++ b/instrumentation/jdbc/library/README.md @@ -0,0 +1,88 @@ +# Manual Instrumentation for JDBC + +Provides OpenTelemetry instrumentation for [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/). + +## Quickstart + +### Add these dependencies to your project. + +Replace `OPENTELEMETRY_VERSION` with the latest stable [release](https://mvnrepository.com/artifact/io.opentelemetry). +`Minimum version: 1.4.0` + +For Maven add to your `pom.xml`: + +```xml + + + io.opentelemetry.instrumentation + opentelemetry-jdbc + OPENTELEMETRY_VERSION + + +``` + +For Gradle add to your dependencies: + +```groovy +implementation("io.opentelemetry.instrumentation:opentelemetry-jdbc:OPENTELEMETRY_VERSION") +``` + +##### Usage + +There two possible modes to activate OpenTelemetry tracing with JDBC. The first one is requires +to change the connection URL and switch to use a special OpenTelemetry driver, when another way +is requires minimal changes in your application without the needs to change the connection URL but +requires to remove explicit driver selection. + +### Non-interceptor mode + +1. Activate tracing for JDBC connections by setting `jdbc:otel:` prefix to the JDBC URL: + +``` +jdbc:otel:h2:mem:test +``` + +2. Set the driver class to `io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver` and + initialize the driver with: + +```java +Class.forName("io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver"); +``` + +### Interceptor mode + +This mode can be useful for activating tracing for all JDBC connections without modifying the URL. + +In "interceptor mode", the `OpenTelemetryDriver` will intercept calls to +`DriverManager.getConnection(url,...)` for all URLs. The `OpenTelemetryDriver` provides connections +to the `DriverManager` that are instrumented. Please note that the `OpenTelemetryDriver` must be +registered before the underlying driver, It's recommended to turn on "interceptor mode" in the first place. + +For most applications: + +```java +public static void main(String[] args) { + io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver.setInterceptorMode(true); + + // ... +} + +``` + +For web applications based on Servlet API: + +```java +public void contextInitialized(ServletContextEvent event) { + io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver.setInterceptorMode(true); + + // ... +} +``` + +Sometimes it's also required to register the OpenTelemetry driver as a first driver in the +DriverManager list, otherwise another driver can be selected at the time of initialization. + +To fix this problem it requires to call `OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver()` +method along with `setInterceptorMode(true)`. + +Please note drivers like Oracle JDBC may fail since it's destroyed forever after deregistration. From 02b73a483cf36b95bec4e18fa4c7c11ad24c00b3 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Thu, 24 Jun 2021 22:51:55 +0800 Subject: [PATCH 36/69] Build fix. --- .../javaagent/instrumentation/grpc/v1_6/GrpcSingletons.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/grpc-1.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/grpc/v1_6/GrpcSingletons.java b/instrumentation/grpc-1.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/grpc/v1_6/GrpcSingletons.java index fc58694f08ff..1ed18f48a5ed 100644 --- a/instrumentation/grpc-1.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/grpc/v1_6/GrpcSingletons.java +++ b/instrumentation/grpc-1.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/grpc/v1_6/GrpcSingletons.java @@ -11,11 +11,11 @@ import io.grpc.Status; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.config.Config; +import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.grpc.v1_6.GrpcRequest; import io.opentelemetry.instrumentation.grpc.v1_6.GrpcTracing; import io.opentelemetry.instrumentation.grpc.v1_6.internal.ContextStorageBridge; import io.opentelemetry.instrumentation.grpc.v1_6.internal.GrpcNetAttributesExtractor; -import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; // Holds singleton references. public final class GrpcSingletons { From 53151f53c149e4cbca8bcc682a80ac8d0350357d Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 01:20:57 +0800 Subject: [PATCH 37/69] Checkstyle fixes. --- .../jdbc/OpenTelemetryDriver.java | 12 +- .../OpenTelemetryCallableStatement.java | 453 +++++++++--------- .../internal/OpenTelemetryConnection.java | 24 +- .../OpenTelemetryPreparedStatement.java | 177 +++---- .../jdbc/internal/OpenTelemetryStatement.java | 12 +- 5 files changed, 342 insertions(+), 336 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 330fdd994a36..a2acfcaa3a0e 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -102,7 +102,7 @@ public static void setInterceptorMode(final boolean interceptorMode) { * method. * * @throws IllegalStateException if the driver is already registered - * @throws SQLException if registering the driver fails + * @throws SQLException if registering the driver fails */ public static void register() throws SQLException { if (isRegistered()) { @@ -119,7 +119,7 @@ public static void register() throws SQLException { * class can be gc'ed if necessary. * * @throws IllegalStateException if the driver is not registered - * @throws SQLException if deregistering the driver fails + * @throws SQLException if deregistering the driver fails */ public static void deregister() throws SQLException { if (!REGISTERED.get()) { @@ -130,7 +130,9 @@ public static void deregister() throws SQLException { REGISTERED.set(false); } - /** Returns {@code true} if the driver is registered against {@link DriverManager} */ + /** + * Returns {@code true} if the driver is registered against {@link DriverManager}. + */ public static boolean isRegistered() { return REGISTERED.get(); } @@ -214,7 +216,9 @@ public int getMinorVersion() { return 4; } - /** Returns {@literal false} because not all delegated drivers are JDBC compliant. */ + /** + * Returns {@literal false} because not all delegated drivers are JDBC compliant. + */ @Override public boolean jdbcCompliant() { return false; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java index 97bcb226e4ce..b8884090b8bf 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java @@ -46,33 +46,33 @@ public OpenTelemetryCallableStatement(S delegate, DbInfo dbInfo, String query) { super(delegate, dbInfo, query); } - @SuppressWarnings("UngroupedOverloads") @Override - public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { - delegate.registerOutParameter(parameterIndex, sqlType); + public boolean wasNull() throws SQLException { + return delegate.wasNull(); } @SuppressWarnings("UngroupedOverloads") @Override - public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { - delegate.registerOutParameter(parameterIndex, sqlType, scale); + public String getString(int parameterIndex) throws SQLException { + return delegate.getString(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override - public boolean wasNull() throws SQLException { - return delegate.wasNull(); + public String getString(String parameterName) throws SQLException { + return delegate.getString(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override - public String getString(int parameterIndex) throws SQLException { - return delegate.getString(parameterIndex); + public boolean getBoolean(int parameterIndex) throws SQLException { + return delegate.getBoolean(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override - public boolean getBoolean(int parameterIndex) throws SQLException { - return delegate.getBoolean(parameterIndex); + public boolean getBoolean(String parameterName) throws SQLException { + return delegate.getBoolean(parameterName); } @SuppressWarnings("UngroupedOverloads") @@ -81,30 +81,60 @@ public byte getByte(int parameterIndex) throws SQLException { return delegate.getByte(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") + @Override + public byte getByte(String parameterName) throws SQLException { + return delegate.getByte(parameterName); + } + @SuppressWarnings("UngroupedOverloads") @Override public short getShort(int parameterIndex) throws SQLException { return delegate.getShort(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") + @Override + public short getShort(String parameterName) throws SQLException { + return delegate.getShort(parameterName); + } + @SuppressWarnings("UngroupedOverloads") @Override public int getInt(int parameterIndex) throws SQLException { return delegate.getInt(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") + @Override + public int getInt(String parameterName) throws SQLException { + return delegate.getInt(parameterName); + } + @SuppressWarnings("UngroupedOverloads") @Override public long getLong(int parameterIndex) throws SQLException { return delegate.getLong(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") + @Override + public long getLong(String parameterName) throws SQLException { + return delegate.getLong(parameterName); + } + @SuppressWarnings("UngroupedOverloads") @Override public float getFloat(int parameterIndex) throws SQLException { return delegate.getFloat(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") + @Override + public float getFloat(String parameterName) throws SQLException { + return delegate.getFloat(parameterName); + } + @SuppressWarnings("UngroupedOverloads") @Override public double getDouble(int parameterIndex) throws SQLException { @@ -113,9 +143,8 @@ public double getDouble(int parameterIndex) throws SQLException { @SuppressWarnings("UngroupedOverloads") @Override - @Deprecated - public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { - return delegate.getBigDecimal(parameterIndex, scale); + public double getDouble(String parameterName) throws SQLException { + return delegate.getDouble(parameterName); } @SuppressWarnings("UngroupedOverloads") @@ -126,8 +155,8 @@ public byte[] getBytes(int parameterIndex) throws SQLException { @SuppressWarnings("UngroupedOverloads") @Override - public Date getDate(int parameterIndex) throws SQLException { - return delegate.getDate(parameterIndex); + public byte[] getBytes(String parameterName) throws SQLException { + return delegate.getBytes(parameterName); } @SuppressWarnings("UngroupedOverloads") @@ -136,6 +165,24 @@ public Time getTime(int parameterIndex) throws SQLException { return delegate.getTime(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") + @Override + public Time getTime(String parameterName, Calendar cal) throws SQLException { + return delegate.getTime(parameterName, cal); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public Time getTime(int parameterIndex, Calendar cal) throws SQLException { + return delegate.getTime(parameterIndex, cal); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public Time getTime(String parameterName) throws SQLException { + return delegate.getTime(parameterName); + } + @SuppressWarnings("UngroupedOverloads") @Override public Timestamp getTimestamp(int parameterIndex) throws SQLException { @@ -144,14 +191,26 @@ public Timestamp getTimestamp(int parameterIndex) throws SQLException { @SuppressWarnings("UngroupedOverloads") @Override - public Object getObject(int parameterIndex) throws SQLException { - return delegate.getObject(parameterIndex); + public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { + return delegate.getTimestamp(parameterName, cal); } @SuppressWarnings("UngroupedOverloads") @Override - public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { - return delegate.getBigDecimal(parameterIndex); + public Timestamp getTimestamp(String parameterName) throws SQLException { + return delegate.getTimestamp(parameterName); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { + return delegate.getTimestamp(parameterIndex, cal); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public Object getObject(int parameterIndex) throws SQLException { + return delegate.getObject(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @@ -160,46 +219,73 @@ public Object getObject(int parameterIndex, Map> map) throws SQ return delegate.getObject(parameterIndex, map); } + @SuppressWarnings("UngroupedOverloads") + @Override + public Object getObject(String parameterName) throws SQLException { + return delegate.getObject(parameterName); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public T getObject(int parameterIndex, Class type) throws SQLException { + return delegate.getObject(parameterIndex, type); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public T getObject(String parameterName, Class type) throws SQLException { + return delegate.getObject(parameterName, type); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public Object getObject(String parameterName, Map> map) throws SQLException { + return delegate.getObject(parameterName, map); + } + @SuppressWarnings("UngroupedOverloads") @Override public Ref getRef(int parameterIndex) throws SQLException { return delegate.getRef(parameterIndex); } + @Override + public Ref getRef(String parameterName) throws SQLException { + return delegate.getRef(parameterName); + } + @SuppressWarnings("UngroupedOverloads") @Override public Blob getBlob(int parameterIndex) throws SQLException { return delegate.getBlob(parameterIndex); } - @SuppressWarnings("UngroupedOverloads") @Override - public Clob getClob(int parameterIndex) throws SQLException { - return delegate.getClob(parameterIndex); + public Blob getBlob(String parameterName) throws SQLException { + return delegate.getBlob(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override - public Array getArray(int parameterIndex) throws SQLException { - return delegate.getArray(parameterIndex); + public Clob getClob(int parameterIndex) throws SQLException { + return delegate.getClob(parameterIndex); } - @SuppressWarnings("UngroupedOverloads") @Override - public Date getDate(int parameterIndex, Calendar cal) throws SQLException { - return delegate.getDate(parameterIndex, cal); + public Clob getClob(String parameterName) throws SQLException { + return delegate.getClob(parameterName); } @SuppressWarnings("UngroupedOverloads") @Override - public Time getTime(int parameterIndex, Calendar cal) throws SQLException { - return delegate.getTime(parameterIndex, cal); + public Array getArray(int parameterIndex) throws SQLException { + return delegate.getArray(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override - public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { - return delegate.getTimestamp(parameterIndex, cal); + public Array getArray(String parameterName) throws SQLException { + return delegate.getArray(parameterName); } @SuppressWarnings("UngroupedOverloads") @@ -229,12 +315,30 @@ public void registerOutParameter(String parameterName, int sqlType, String typeN delegate.registerOutParameter(parameterName, sqlType, typeName); } + @SuppressWarnings("UngroupedOverloads") + @Override + public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { + delegate.registerOutParameter(parameterIndex, sqlType); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { + delegate.registerOutParameter(parameterIndex, sqlType, scale); + } + @SuppressWarnings("UngroupedOverloads") @Override public URL getURL(int parameterIndex) throws SQLException { return delegate.getURL(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") + @Override + public URL getURL(String parameterName) throws SQLException { + return delegate.getURL(parameterName); + } + @Override public void setURL(String parameterName, URL val) throws SQLException { delegate.setURL(parameterName, val); @@ -246,6 +350,12 @@ public void setNull(String parameterName, int sqlType) throws SQLException { delegate.setNull(parameterName, sqlType); } + @SuppressWarnings("UngroupedOverloads") + @Override + public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { + delegate.setNull(parameterName, sqlType, typeName); + } + @Override public void setBoolean(String parameterName, boolean x) throws SQLException { delegate.setBoolean(parameterName, x); @@ -302,128 +412,106 @@ public void setDate(String parameterName, Date x) throws SQLException { delegate.setDate(parameterName, x); } - @Override - public void setTime(String parameterName, Time x) throws SQLException { - delegate.setTime(parameterName, x); - } - @SuppressWarnings("UngroupedOverloads") @Override - public void setTimestamp(String parameterName, Timestamp x) throws SQLException { - delegate.setTimestamp(parameterName, x); + public void setDate(String parameterName, Date x, Calendar cal) throws SQLException { + delegate.setDate(parameterName, x, cal); } - @SuppressWarnings("UngroupedOverloads") @Override - public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException { - delegate.setAsciiStream(parameterName, x, length); + public void setTime(String parameterName, Time x) throws SQLException { + delegate.setTime(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override - public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException { - delegate.setBinaryStream(parameterName, x, length); - } - - @Override - public void setObject(String parameterName, Object x, int targetSqlType, int scale) - throws SQLException { - delegate.setObject(parameterName, x, targetSqlType, scale); - } - - @Override - public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { - delegate.setObject(parameterName, x, targetSqlType); - } - - @Override - public void setObject(String parameterName, Object x) throws SQLException { - delegate.setObject(parameterName, x); + public void setTime(String parameterName, Time x, Calendar cal) throws SQLException { + delegate.setTime(parameterName, x, cal); } @SuppressWarnings("UngroupedOverloads") @Override - public void setCharacterStream(String parameterName, Reader reader, int length) - throws SQLException { - delegate.setCharacterStream(parameterName, reader, length); + public void setTimestamp(String parameterName, Timestamp x) throws SQLException { + delegate.setTimestamp(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override - public void setDate(String parameterName, Date x, Calendar cal) throws SQLException { - delegate.setDate(parameterName, x, cal); + public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { + delegate.setTimestamp(parameterName, x, cal); } @SuppressWarnings("UngroupedOverloads") @Override - public void setTime(String parameterName, Time x, Calendar cal) throws SQLException { - delegate.setTime(parameterName, x, cal); + public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException { + delegate.setAsciiStream(parameterName, x, length); } @SuppressWarnings("UngroupedOverloads") @Override - public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { - delegate.setTimestamp(parameterName, x, cal); + public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { + delegate.setAsciiStream(parameterName, x, length); } @SuppressWarnings("UngroupedOverloads") @Override - public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { - delegate.setNull(parameterName, sqlType, typeName); + public void setAsciiStream(String parameterName, InputStream x) throws SQLException { + delegate.setAsciiStream(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override - public String getString(String parameterName) throws SQLException { - return delegate.getString(parameterName); + public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException { + delegate.setBinaryStream(parameterName, x, length); } @SuppressWarnings("UngroupedOverloads") @Override - public boolean getBoolean(String parameterName) throws SQLException { - return delegate.getBoolean(parameterName); + public void setBinaryStream(String parameterName, InputStream x, long length) + throws SQLException { + delegate.setBinaryStream(parameterName, x, length); } @SuppressWarnings("UngroupedOverloads") @Override - public byte getByte(String parameterName) throws SQLException { - return delegate.getByte(parameterName); + public void setBinaryStream(String parameterName, InputStream x) throws SQLException { + delegate.setBinaryStream(parameterName, x); } - @SuppressWarnings("UngroupedOverloads") @Override - public short getShort(String parameterName) throws SQLException { - return delegate.getShort(parameterName); + public void setObject(String parameterName, Object x, int targetSqlType, int scale) + throws SQLException { + delegate.setObject(parameterName, x, targetSqlType, scale); } - @SuppressWarnings("UngroupedOverloads") @Override - public int getInt(String parameterName) throws SQLException { - return delegate.getInt(parameterName); + public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { + delegate.setObject(parameterName, x, targetSqlType); } - @SuppressWarnings("UngroupedOverloads") @Override - public long getLong(String parameterName) throws SQLException { - return delegate.getLong(parameterName); + public void setObject(String parameterName, Object x) throws SQLException { + delegate.setObject(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @Override - public float getFloat(String parameterName) throws SQLException { - return delegate.getFloat(parameterName); + public void setCharacterStream(String parameterName, Reader reader, int length) + throws SQLException { + delegate.setCharacterStream(parameterName, reader, length); } @SuppressWarnings("UngroupedOverloads") @Override - public double getDouble(String parameterName) throws SQLException { - return delegate.getDouble(parameterName); + public void setCharacterStream(String parameterName, Reader reader, long length) + throws SQLException { + delegate.setCharacterStream(parameterName, reader, length); } @SuppressWarnings("UngroupedOverloads") @Override - public byte[] getBytes(String parameterName) throws SQLException { - return delegate.getBytes(parameterName); + public void setCharacterStream(String parameterName, Reader reader) throws SQLException { + delegate.setCharacterStream(parameterName, reader); } @SuppressWarnings("UngroupedOverloads") @@ -434,20 +522,20 @@ public Date getDate(String parameterName) throws SQLException { @SuppressWarnings("UngroupedOverloads") @Override - public Time getTime(String parameterName) throws SQLException { - return delegate.getTime(parameterName); + public Date getDate(int parameterIndex, Calendar cal) throws SQLException { + return delegate.getDate(parameterIndex, cal); } @SuppressWarnings("UngroupedOverloads") @Override - public Timestamp getTimestamp(String parameterName) throws SQLException { - return delegate.getTimestamp(parameterName); + public Date getDate(int parameterIndex) throws SQLException { + return delegate.getDate(parameterIndex); } @SuppressWarnings("UngroupedOverloads") @Override - public Object getObject(String parameterName) throws SQLException { - return delegate.getObject(parameterName); + public Date getDate(String parameterName, Calendar cal) throws SQLException { + return delegate.getDate(parameterName, cal); } @SuppressWarnings("UngroupedOverloads") @@ -458,92 +546,84 @@ public BigDecimal getBigDecimal(String parameterName) throws SQLException { @SuppressWarnings("UngroupedOverloads") @Override - public Object getObject(String parameterName, Map> map) throws SQLException { - return delegate.getObject(parameterName, map); + public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { + return delegate.getBigDecimal(parameterIndex); } + @SuppressWarnings("UngroupedOverloads") @Override - public Ref getRef(String parameterName) throws SQLException { - return delegate.getRef(parameterName); + @Deprecated + public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { + return delegate.getBigDecimal(parameterIndex, scale); } @Override - public Blob getBlob(String parameterName) throws SQLException { - return delegate.getBlob(parameterName); + public RowId getRowId(int parameterIndex) throws SQLException { + return delegate.getRowId(parameterIndex); } @Override - public Clob getClob(String parameterName) throws SQLException { - return delegate.getClob(parameterName); + public RowId getRowId(String parameterName) throws SQLException { + return delegate.getRowId(parameterName); } - @SuppressWarnings("UngroupedOverloads") @Override - public Array getArray(String parameterName) throws SQLException { - return delegate.getArray(parameterName); + public void setRowId(String parameterName, RowId x) throws SQLException { + delegate.setRowId(parameterName, x); } - @SuppressWarnings("UngroupedOverloads") @Override - public Date getDate(String parameterName, Calendar cal) throws SQLException { - return delegate.getDate(parameterName, cal); + public void setNString(String parameterName, String value) throws SQLException { + delegate.setNString(parameterName, value); } @SuppressWarnings("UngroupedOverloads") @Override - public Time getTime(String parameterName, Calendar cal) throws SQLException { - return delegate.getTime(parameterName, cal); + public void setNCharacterStream(String parameterName, Reader value, long length) + throws SQLException { + delegate.setNCharacterStream(parameterName, value, length); } @SuppressWarnings("UngroupedOverloads") @Override - public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { - return delegate.getTimestamp(parameterName, cal); + public void setNCharacterStream(String parameterName, Reader value) throws SQLException { + delegate.setNCharacterStream(parameterName, value); } @SuppressWarnings("UngroupedOverloads") @Override - public URL getURL(String parameterName) throws SQLException { - return delegate.getURL(parameterName); - } - - @Override - public RowId getRowId(int parameterIndex) throws SQLException { - return delegate.getRowId(parameterIndex); - } - - @Override - public RowId getRowId(String parameterName) throws SQLException { - return delegate.getRowId(parameterName); + public void setNClob(String parameterName, NClob value) throws SQLException { + delegate.setNClob(parameterName, value); } + @SuppressWarnings("UngroupedOverloads") @Override - public void setRowId(String parameterName, RowId x) throws SQLException { - delegate.setRowId(parameterName, x); + public void setNClob(String parameterName, Reader reader) throws SQLException { + delegate.setNClob(parameterName, reader); } + @SuppressWarnings("UngroupedOverloads") @Override - public void setNString(String parameterName, String value) throws SQLException { - delegate.setNString(parameterName, value); + public void setNClob(String parameterName, Reader reader, long length) throws SQLException { + delegate.setNClob(parameterName, reader, length); } @SuppressWarnings("UngroupedOverloads") @Override - public void setNCharacterStream(String parameterName, Reader value, long length) - throws SQLException { - delegate.setNCharacterStream(parameterName, value, length); + public void setClob(String parameterName, Reader reader, long length) throws SQLException { + delegate.setClob(parameterName, reader, length); } @SuppressWarnings("UngroupedOverloads") @Override - public void setNClob(String parameterName, NClob value) throws SQLException { - delegate.setNClob(parameterName, value); + public void setClob(String parameterName, Reader reader) throws SQLException { + delegate.setClob(parameterName, reader); } @SuppressWarnings("UngroupedOverloads") @Override - public void setClob(String parameterName, Reader reader, long length) throws SQLException { - delegate.setClob(parameterName, reader, length); + public void setClob(String parameterName, Clob x) throws SQLException { + delegate.setClob(parameterName, x); } @SuppressWarnings("UngroupedOverloads") @@ -555,8 +635,14 @@ public void setBlob(String parameterName, InputStream inputStream, long length) @SuppressWarnings("UngroupedOverloads") @Override - public void setNClob(String parameterName, Reader reader, long length) throws SQLException { - delegate.setNClob(parameterName, reader, length); + public void setBlob(String parameterName, InputStream inputStream) throws SQLException { + delegate.setBlob(parameterName, inputStream); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public void setBlob(String parameterName, Blob x) throws SQLException { + delegate.setBlob(parameterName, x); } @Override @@ -614,89 +700,4 @@ public Reader getCharacterStream(String parameterName) throws SQLException { return delegate.getCharacterStream(parameterName); } - @SuppressWarnings("UngroupedOverloads") - @Override - public void setBlob(String parameterName, Blob x) throws SQLException { - delegate.setBlob(parameterName, x); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setClob(String parameterName, Clob x) throws SQLException { - delegate.setClob(parameterName, x); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { - delegate.setAsciiStream(parameterName, x, length); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setBinaryStream(String parameterName, InputStream x, long length) - throws SQLException { - delegate.setBinaryStream(parameterName, x, length); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setCharacterStream(String parameterName, Reader reader, long length) - throws SQLException { - delegate.setCharacterStream(parameterName, reader, length); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setAsciiStream(String parameterName, InputStream x) throws SQLException { - delegate.setAsciiStream(parameterName, x); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setBinaryStream(String parameterName, InputStream x) throws SQLException { - delegate.setBinaryStream(parameterName, x); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setCharacterStream(String parameterName, Reader reader) throws SQLException { - delegate.setCharacterStream(parameterName, reader); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setNCharacterStream(String parameterName, Reader value) throws SQLException { - delegate.setNCharacterStream(parameterName, value); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setClob(String parameterName, Reader reader) throws SQLException { - delegate.setClob(parameterName, reader); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setBlob(String parameterName, InputStream inputStream) throws SQLException { - delegate.setBlob(parameterName, inputStream); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setNClob(String parameterName, Reader reader) throws SQLException { - delegate.setNClob(parameterName, reader); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public T getObject(int parameterIndex, Class type) throws SQLException { - return delegate.getObject(parameterIndex, type); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public T getObject(String parameterName, Class type) throws SQLException { - return delegate.getObject(parameterName, type); - } } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java index cb39a6cdc30d..298b8302ba4e 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryConnection.java @@ -139,12 +139,6 @@ public void commit() throws SQLException { delegate.commit(); } - @SuppressWarnings("UngroupedOverloads") - @Override - public void rollback() throws SQLException { - delegate.rollback(); - } - @Override public void close() throws SQLException { delegate.close(); @@ -245,6 +239,12 @@ public Savepoint setSavepoint(String name) throws SQLException { return delegate.setSavepoint(name); } + @SuppressWarnings("UngroupedOverloads") + @Override + public void rollback() throws SQLException { + delegate.rollback(); + } + @SuppressWarnings("UngroupedOverloads") @Override public void rollback(Savepoint savepoint) throws SQLException { @@ -287,6 +287,12 @@ public void setClientInfo(String name, String value) throws SQLClientInfoExcepti delegate.setClientInfo(name, value); } + @SuppressWarnings("UngroupedOverloads") + @Override + public void setClientInfo(Properties properties) throws SQLClientInfoException { + delegate.setClientInfo(properties); + } + @Override public String getClientInfo(String name) throws SQLException { return delegate.getClientInfo(name); @@ -297,12 +303,6 @@ public Properties getClientInfo() throws SQLException { return delegate.getClientInfo(); } - @SuppressWarnings("UngroupedOverloads") - @Override - public void setClientInfo(Properties properties) throws SQLClientInfoException { - delegate.setClientInfo(properties); - } - @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return delegate.createArrayOf(typeName, elements); diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java index d40cfdf8682a..76d9a511eddc 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java @@ -69,6 +69,12 @@ public void setNull(int parameterIndex, int sqlType) throws SQLException { delegate.setNull(parameterIndex, sqlType); } + @SuppressWarnings("UngroupedOverloads") + @Override + public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { + delegate.setNull(parameterIndex, sqlType, typeName); + } + @Override public void setBoolean(int parameterIndex, boolean x) throws SQLException { delegate.setBoolean(parameterIndex, x); @@ -125,24 +131,53 @@ public void setDate(int parameterIndex, Date x) throws SQLException { delegate.setDate(parameterIndex, x); } + @SuppressWarnings("UngroupedOverloads") + @Override + public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { + delegate.setDate(parameterIndex, x, cal); + } + @SuppressWarnings("UngroupedOverloads") @Override public void setTime(int parameterIndex, Time x) throws SQLException { delegate.setTime(parameterIndex, x); } + @Override + public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { + delegate.setTime(parameterIndex, x, cal); + } + @SuppressWarnings("UngroupedOverloads") @Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { delegate.setTimestamp(parameterIndex, x); } + @SuppressWarnings("UngroupedOverloads") + @Override + public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { + delegate.setTimestamp(parameterIndex, x, cal); + } + @SuppressWarnings("UngroupedOverloads") @Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { delegate.setAsciiStream(parameterIndex, x, length); } + @SuppressWarnings("UngroupedOverloads") + @Override + public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { + delegate.setAsciiStream(parameterIndex, x); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { + delegate.setAsciiStream(parameterIndex, x, length); + } + @Override @Deprecated public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { @@ -155,9 +190,16 @@ public void setBinaryStream(int parameterIndex, InputStream x, int length) throw delegate.setBinaryStream(parameterIndex, x, length); } + @SuppressWarnings("UngroupedOverloads") @Override - public void clearParameters() throws SQLException { - delegate.clearParameters(); + public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { + delegate.setBinaryStream(parameterIndex, x, length); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { + delegate.setBinaryStream(parameterIndex, x); } @SuppressWarnings("UngroupedOverloads") @@ -172,6 +214,12 @@ public void setObject(int parameterIndex, Object x) throws SQLException { delegate.setObject(parameterIndex, x); } + @Override + public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) + throws SQLException { + delegate.setObject(parameterIndex, x, targetSqlType, scaleOrLength); + } + @Override public void addBatch() throws SQLException { delegate.addBatch(); @@ -184,6 +232,18 @@ public void setCharacterStream(int parameterIndex, Reader reader, int length) delegate.setCharacterStream(parameterIndex, reader, length); } + @Override + public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { + delegate.setCharacterStream(parameterIndex, reader); + } + + @SuppressWarnings("UngroupedOverloads") + @Override + public void setCharacterStream(int parameterIndex, Reader reader, long length) + throws SQLException { + delegate.setCharacterStream(parameterIndex, reader, length); + } + @Override public void setRef(int parameterIndex, Ref x) throws SQLException { delegate.setRef(parameterIndex, x); @@ -196,41 +256,42 @@ public void setBlob(int parameterIndex, Blob x) throws SQLException { @SuppressWarnings("UngroupedOverloads") @Override - public void setClob(int parameterIndex, Clob x) throws SQLException { - delegate.setClob(parameterIndex, x); + public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { + delegate.setBlob(parameterIndex, inputStream); } @Override - public void setArray(int parameterIndex, Array x) throws SQLException { - delegate.setArray(parameterIndex, x); + public void setBlob(int parameterIndex, InputStream inputStream, long length) + throws SQLException { + delegate.setBlob(parameterIndex, inputStream, length); } + @SuppressWarnings("UngroupedOverloads") @Override - public ResultSetMetaData getMetaData() throws SQLException { - return delegate.getMetaData(); + public void setClob(int parameterIndex, Clob x) throws SQLException { + delegate.setClob(parameterIndex, x); } @SuppressWarnings("UngroupedOverloads") @Override - public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { - delegate.setDate(parameterIndex, x, cal); + public void setClob(int parameterIndex, Reader reader) throws SQLException { + delegate.setClob(parameterIndex, reader); } + @SuppressWarnings("UngroupedOverloads") @Override - public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { - delegate.setTime(parameterIndex, x, cal); + public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { + delegate.setClob(parameterIndex, reader, length); } - @SuppressWarnings("UngroupedOverloads") @Override - public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { - delegate.setTimestamp(parameterIndex, x, cal); + public void setArray(int parameterIndex, Array x) throws SQLException { + delegate.setArray(parameterIndex, x); } - @SuppressWarnings("UngroupedOverloads") @Override - public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { - delegate.setNull(parameterIndex, sqlType, typeName); + public ResultSetMetaData getMetaData() throws SQLException { + return delegate.getMetaData(); } @Override @@ -260,21 +321,15 @@ public void setNCharacterStream(int parameterIndex, Reader value, long length) delegate.setNCharacterStream(parameterIndex, value, length); } - @Override - public void setNClob(int parameterIndex, NClob value) throws SQLException { - delegate.setNClob(parameterIndex, value); - } - @SuppressWarnings("UngroupedOverloads") @Override - public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { - delegate.setClob(parameterIndex, reader, length); + public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { + delegate.setNCharacterStream(parameterIndex, value); } @Override - public void setBlob(int parameterIndex, InputStream inputStream, long length) - throws SQLException { - delegate.setBlob(parameterIndex, inputStream, length); + public void setNClob(int parameterIndex, NClob value) throws SQLException { + delegate.setNClob(parameterIndex, value); } @Override @@ -282,74 +337,20 @@ public void setNClob(int parameterIndex, Reader reader, long length) throws SQLE delegate.setNClob(parameterIndex, reader, length); } - @Override - public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { - delegate.setSQLXML(parameterIndex, xmlObject); - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) - throws SQLException { - delegate.setObject(parameterIndex, x, targetSqlType, scaleOrLength); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { - delegate.setAsciiStream(parameterIndex, x, length); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { - delegate.setBinaryStream(parameterIndex, x, length); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setCharacterStream(int parameterIndex, Reader reader, long length) - throws SQLException { - delegate.setCharacterStream(parameterIndex, reader, length); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { - delegate.setAsciiStream(parameterIndex, x); - } - - @SuppressWarnings("UngroupedOverloads") - @Override - public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { - delegate.setBinaryStream(parameterIndex, x); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { - delegate.setCharacterStream(parameterIndex, reader); - } - @SuppressWarnings("UngroupedOverloads") @Override - public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { - delegate.setNCharacterStream(parameterIndex, value); + public void setNClob(int parameterIndex, Reader reader) throws SQLException { + delegate.setNClob(parameterIndex, reader); } - @SuppressWarnings("UngroupedOverloads") @Override - public void setClob(int parameterIndex, Reader reader) throws SQLException { - delegate.setClob(parameterIndex, reader); + public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { + delegate.setSQLXML(parameterIndex, xmlObject); } - @SuppressWarnings("UngroupedOverloads") @Override - public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { - delegate.setBlob(parameterIndex, inputStream); + public void clearParameters() throws SQLException { + delegate.clearParameters(); } - @SuppressWarnings("UngroupedOverloads") - @Override - public void setNClob(int parameterIndex, Reader reader) throws SQLException { - delegate.setNClob(parameterIndex, reader); - } } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java index c75d64713522..db829da9e6a0 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java @@ -174,6 +174,12 @@ public boolean getMoreResults() throws SQLException { return delegate.getMoreResults(); } + @SuppressWarnings("UngroupedOverloads") + @Override + public boolean getMoreResults(int current) throws SQLException { + return delegate.getMoreResults(current); + } + @Override public int getFetchDirection() throws SQLException { return delegate.getFetchDirection(); @@ -221,12 +227,6 @@ public Connection getConnection() throws SQLException { return delegate.getConnection(); } - @SuppressWarnings("UngroupedOverloads") - @Override - public boolean getMoreResults(int current) throws SQLException { - return delegate.getMoreResults(current); - } - @Override public ResultSet getGeneratedKeys() throws SQLException { return delegate.getGeneratedKeys(); From edcb7f9f0e749acd7c545f3b18bafa2cf0fd1b84 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 01:22:19 +0800 Subject: [PATCH 38/69] Spotless fixes. --- .../instrumentation/jdbc/OpenTelemetryDriver.java | 12 ++++-------- .../internal/OpenTelemetryCallableStatement.java | 1 - .../internal/OpenTelemetryPreparedStatement.java | 1 - 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index a2acfcaa3a0e..38b4f0dfa1cf 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -102,7 +102,7 @@ public static void setInterceptorMode(final boolean interceptorMode) { * method. * * @throws IllegalStateException if the driver is already registered - * @throws SQLException if registering the driver fails + * @throws SQLException if registering the driver fails */ public static void register() throws SQLException { if (isRegistered()) { @@ -119,7 +119,7 @@ public static void register() throws SQLException { * class can be gc'ed if necessary. * * @throws IllegalStateException if the driver is not registered - * @throws SQLException if deregistering the driver fails + * @throws SQLException if deregistering the driver fails */ public static void deregister() throws SQLException { if (!REGISTERED.get()) { @@ -130,9 +130,7 @@ public static void deregister() throws SQLException { REGISTERED.set(false); } - /** - * Returns {@code true} if the driver is registered against {@link DriverManager}. - */ + /** Returns {@code true} if the driver is registered against {@link DriverManager}. */ public static boolean isRegistered() { return REGISTERED.get(); } @@ -216,9 +214,7 @@ public int getMinorVersion() { return 4; } - /** - * Returns {@literal false} because not all delegated drivers are JDBC compliant. - */ + /** Returns {@literal false} because not all delegated drivers are JDBC compliant. */ @Override public boolean jdbcCompliant() { return false; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java index b8884090b8bf..e92366a39b27 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryCallableStatement.java @@ -699,5 +699,4 @@ public Reader getCharacterStream(int parameterIndex) throws SQLException { public Reader getCharacterStream(String parameterName) throws SQLException { return delegate.getCharacterStream(parameterName); } - } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java index 76d9a511eddc..0e127aa57e87 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryPreparedStatement.java @@ -352,5 +352,4 @@ public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException public void clearParameters() throws SQLException { delegate.clearParameters(); } - } From 3acc14a0f7c5900629ba987a48d451aa3621e378 Mon Sep 17 00:00:00 2001 From: Anuraag Agrawal Date: Fri, 25 Jun 2021 16:27:49 +0900 Subject: [PATCH 39/69] Rename to build.gradle --- instrumentation/jdbc/library/build.gradle | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 instrumentation/jdbc/library/build.gradle diff --git a/instrumentation/jdbc/library/build.gradle b/instrumentation/jdbc/library/build.gradle new file mode 100644 index 000000000000..ceecb39c82ce --- /dev/null +++ b/instrumentation/jdbc/library/build.gradle @@ -0,0 +1,16 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +apply plugin: "otel.library-instrumentation" + +dependencies { + implementation project(':instrumentation-api') + implementation project(':javaagent-api') + + compileOnly "com.google.auto.value:auto-value-annotations" + annotationProcessor "com.google.auto.value:auto-value" + + implementation "org.slf4j:slf4j-api" +} From df40e8094fab89d04f0f6f1e7fe983361bde1689 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 16:27:03 +0800 Subject: [PATCH 40/69] Fix build.gradle format. --- instrumentation/jdbc/library/build.gradle | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/instrumentation/jdbc/library/build.gradle b/instrumentation/jdbc/library/build.gradle index ceecb39c82ce..103fbe5d2f81 100644 --- a/instrumentation/jdbc/library/build.gradle +++ b/instrumentation/jdbc/library/build.gradle @@ -3,7 +3,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -apply plugin: "otel.library-instrumentation" +plugins { + id("otel.library-instrumentation") +} dependencies { implementation project(':instrumentation-api') From 141bece529bae4bbec6dbb8136637dffc97fd5c1 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 16:33:47 +0800 Subject: [PATCH 41/69] INSTANCE package scope. --- .../instrumentation/jdbc/OpenTelemetryDriver.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 38b4f0dfa1cf..9883fa257dbc 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -39,7 +39,8 @@ public final class OpenTelemetryDriver implements Driver { - public static final OpenTelemetryDriver INSTANCE = new OpenTelemetryDriver(); + // visible for testing + static final OpenTelemetryDriver INSTANCE = new OpenTelemetryDriver(); private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; private static final AtomicBoolean REGISTERED = new AtomicBoolean(); From f51900e0db9cc7a4a814b4ded21fdc2b466a1f5c Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 17:10:16 +0800 Subject: [PATCH 42/69] Documented OpenTelemetryDataSource usage. --- instrumentation/jdbc/library/README.md | 61 ++++++++++++++----- .../jdbc/OpenTelemetryDriver.java | 12 +++- .../datasource/OpenTelemetryDataSource.java | 7 +++ .../jdbc/OpenTelemetryDriverTest.groovy | 11 +++- 4 files changed, 74 insertions(+), 17 deletions(-) diff --git a/instrumentation/jdbc/library/README.md b/instrumentation/jdbc/library/README.md index 44e33b599db9..3a287a9841bc 100644 --- a/instrumentation/jdbc/library/README.md +++ b/instrumentation/jdbc/library/README.md @@ -1,13 +1,14 @@ # Manual Instrumentation for JDBC -Provides OpenTelemetry instrumentation for [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/). +Provides OpenTelemetry instrumentation for +[Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/). ## Quickstart ### Add these dependencies to your project. -Replace `OPENTELEMETRY_VERSION` with the latest stable [release](https://mvnrepository.com/artifact/io.opentelemetry). -`Minimum version: 1.4.0` +Replace `OPENTELEMETRY_VERSION` with the latest stable +[release](https://mvnrepository.com/artifact/io.opentelemetry). `Minimum version: 1.4.0` For Maven add to your `pom.xml`: @@ -29,12 +30,13 @@ implementation("io.opentelemetry.instrumentation:opentelemetry-jdbc:OPENTELEMETR ##### Usage -There two possible modes to activate OpenTelemetry tracing with JDBC. The first one is requires -to change the connection URL and switch to use a special OpenTelemetry driver, when another way +There are three possible ways to activate OpenTelemetry tracing with JDBC. The first one is requires +to change the connection URL and switch to use a special OpenTelemetry driver. When the second way is requires minimal changes in your application without the needs to change the connection URL but -requires to remove explicit driver selection. +requires removing explicit driver selection. And the third way is more preferable for DI frameworks +which uses connection pool, it requires only wrap DataSource with special OpenTelemetry wrapper. -### Non-interceptor mode +### Driver: non-interceptor mode. 1. Activate tracing for JDBC connections by setting `jdbc:otel:` prefix to the JDBC URL: @@ -49,22 +51,23 @@ jdbc:otel:h2:mem:test Class.forName("io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver"); ``` -### Interceptor mode +### Driver: interceptor mode. This mode can be useful for activating tracing for all JDBC connections without modifying the URL. In "interceptor mode", the `OpenTelemetryDriver` will intercept calls to `DriverManager.getConnection(url,...)` for all URLs. The `OpenTelemetryDriver` provides connections to the `DriverManager` that are instrumented. Please note that the `OpenTelemetryDriver` must be -registered before the underlying driver, It's recommended to turn on "interceptor mode" in the first place. +registered before the underlying driver, It's recommended to turn on "interceptor mode" in the first +place. For most applications: ```java public static void main(String[] args) { - io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver.setInterceptorMode(true); + io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver.setInterceptorMode(true); - // ... + // ... } ``` @@ -73,16 +76,46 @@ For web applications based on Servlet API: ```java public void contextInitialized(ServletContextEvent event) { - io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver.setInterceptorMode(true); + io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver.setInterceptorMode(true); - // ... + // ... } ``` Sometimes it's also required to register the OpenTelemetry driver as a first driver in the DriverManager list, otherwise another driver can be selected at the time of initialization. -To fix this problem it requires to call `OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver()` +To fix this problem it requires calling `OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver()` method along with `setInterceptorMode(true)`. Please note drivers like Oracle JDBC may fail since it's destroyed forever after deregistration. + +### Datasource way + +If your application uses a DataSource, simply wrap your current DataSource object with +`OpenTelemetryDataSource`. `OpenTelemetryDataSource` has a constructor method that accepts the +`DataSource` to wrap. This is by far the simplest method especially if you use a dependency +injection (DI) frameworks such as [Spring Framework](https://spring.io/projects/spring-framework), +[Micronaut](https://micronaut.io), [Quarkus](https://quarkus.io), or +[Guice](https://github.com/google/guice). + +```java +import org.apache.commons.dbcp2.BasicDataSource; +import org.springframework.context.annotation.Configuration; +import io.opentelemetry.instrumentation.jdbc.datasource.OpenTelemetryDataSource; + +@Configuration +public class DataSourceConfig { + + @Bean + public DataSource dataSource() { + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl("jdbc:postgresql://127.0.0.1:5432/example"); + dataSource.setUsername("postgres"); + dataSource.setPassword("root"); + return new OpenTelemetryDataSource(dataSource); + } + +} +``` diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 9883fa257dbc..6da5b7037708 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -28,6 +28,7 @@ import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; @@ -37,6 +38,7 @@ import java.util.logging.Logger; import org.checkerframework.checker.nullness.qual.Nullable; +/** JDBC driver for OpenTelemetry. */ public final class OpenTelemetryDriver implements Driver { // visible for testing @@ -154,6 +156,12 @@ private static Driver findDriver(String realUrl) { throw new IllegalStateException("Unable to find a driver that accepts url: " + realUrl); } + /** + * Parses out the real JDBC connection URL by removing "otel:" prefix. + * + * @param url the connection URL + * @return the parsed URL + */ private static String extractRealUrl(String url) { return url.startsWith(INTERCEPTOR_MODE_URL_PREFIX) ? url.replace(INTERCEPTOR_MODE_URL_PREFIX, "jdbc:") @@ -222,7 +230,7 @@ public boolean jdbcCompliant() { } @Override - public Logger getParentLogger() { - return null; + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + throw new SQLFeatureNotSupportedException("Feature not supported"); } } diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java index a6ba59bccc4c..c0403373fbe5 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java @@ -36,10 +36,17 @@ import java.util.logging.Logger; import javax.sql.DataSource; +/** OpenTelemetry {@link DataSource} implementation. */ public class OpenTelemetryDataSource implements DataSource, AutoCloseable { private final DataSource delegate; + /** + * Create a OpenTelemetry DataSource wrapping another DataSource. This constructor is primarily + * used by dependency injection frameworks. + * + * @param delegate the DataSource to wrap + */ public OpenTelemetryDataSource(DataSource delegate) { this.delegate = delegate; } diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy index 452996d34620..f7d6deafd380 100644 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy @@ -9,6 +9,7 @@ import io.opentelemetry.instrumentation.jdbc.internal.OpenTelemetryConnection import spock.lang.Specification import java.sql.DriverManager +import java.sql.SQLFeatureNotSupportedException class OpenTelemetryDriverTest extends Specification { @@ -35,11 +36,19 @@ class OpenTelemetryDriverTest extends Specification { def "verify standard properties"() { expect: !OpenTelemetryDriver.INSTANCE.jdbcCompliant() - OpenTelemetryDriver.INSTANCE.parentLogger == null OpenTelemetryDriver.INSTANCE.majorVersion == 1 OpenTelemetryDriver.INSTANCE.minorVersion == 4 } + def "verify parent logger thrown an exception"() { + when: + OpenTelemetryDriver.INSTANCE.parentLogger + + then: + def e = thrown(SQLFeatureNotSupportedException) + e.message == "Feature not supported" + } + def "verify driver registered as a first driver"() { given: DriverManager.drivers.each { driver -> From f25ba7308a02a77e0834382db3d17bedf60f7bfb Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 17:14:19 +0800 Subject: [PATCH 43/69] Renamed CheckedCallable to ThrowingSupplier. --- .../jdbc/datasource/OpenTelemetryDataSource.java | 4 ++-- .../instrumentation/jdbc/internal/OpenTelemetryStatement.java | 2 +- .../internal/{CheckedCallable.java => ThrowingSupplier.java} | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) rename instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/{CheckedCallable.java => ThrowingSupplier.java} (75%) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java index c0403373fbe5..398e70ff5f37 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/datasource/OpenTelemetryDataSource.java @@ -26,9 +26,9 @@ import io.opentelemetry.api.trace.Span; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; -import io.opentelemetry.instrumentation.jdbc.internal.CheckedCallable; import io.opentelemetry.instrumentation.jdbc.internal.DbInfo; import io.opentelemetry.instrumentation.jdbc.internal.OpenTelemetryConnection; +import io.opentelemetry.instrumentation.jdbc.internal.ThrowingSupplier; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; @@ -108,7 +108,7 @@ public void close() throws Exception { } } - private T wrapCall(CheckedCallable callable) throws E { + private T wrapCall(ThrowingSupplier callable) throws E { Context parentContext = Context.current(); if (!Span.fromContext(parentContext).getSpanContext().isValid()) { diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java index db829da9e6a0..08fbcdded199 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/OpenTelemetryStatement.java @@ -272,7 +272,7 @@ public boolean isWrapperFor(Class iface) throws SQLException { return delegate.isWrapperFor(iface); } - protected T wrapCall(String sql, CheckedCallable callable) + protected T wrapCall(String sql, ThrowingSupplier callable) throws E { Context parentContext = Context.current(); DbRequest request = DbRequest.create(dbInfo, sql); diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/CheckedCallable.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/ThrowingSupplier.java similarity index 75% rename from instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/CheckedCallable.java rename to instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/ThrowingSupplier.java index 41b4f221a576..9fed1175ac8e 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/CheckedCallable.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/ThrowingSupplier.java @@ -6,7 +6,7 @@ package io.opentelemetry.instrumentation.jdbc.internal; @FunctionalInterface -public interface CheckedCallable { +public interface ThrowingSupplier { T call() throws E; } From f189b5f70020c7b53eb3f1886fc1e04eeb295e02 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 19:29:12 +0800 Subject: [PATCH 44/69] Update instrumentation/jdbc/library/README.md Co-authored-by: Mateusz Rzeszutek --- instrumentation/jdbc/library/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/instrumentation/jdbc/library/README.md b/instrumentation/jdbc/library/README.md index 3a287a9841bc..7880c0df68c0 100644 --- a/instrumentation/jdbc/library/README.md +++ b/instrumentation/jdbc/library/README.md @@ -30,11 +30,11 @@ implementation("io.opentelemetry.instrumentation:opentelemetry-jdbc:OPENTELEMETR ##### Usage -There are three possible ways to activate OpenTelemetry tracing with JDBC. The first one is requires -to change the connection URL and switch to use a special OpenTelemetry driver. When the second way -is requires minimal changes in your application without the needs to change the connection URL but -requires removing explicit driver selection. And the third way is more preferable for DI frameworks -which uses connection pool, it requires only wrap DataSource with special OpenTelemetry wrapper. +There are three possible ways to activate the OpenTelemetry JDBC instrumentation. The first one requires +to change the connection URL and switch to use a special OpenTelemetry driver. The second method +only requires minimal changes in your application without needing to change the connection URL, but +it's necessary to remove the explicit driver selection. And the third way is more preferable for DI frameworks +which uses connection pools, as it wraps a `DataSource` with a special OpenTelemetry wrapper. ### Driver: non-interceptor mode. From 66d34aa5de2170208d9b8ca7c881e39cb9073133 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 19:38:19 +0800 Subject: [PATCH 45/69] Update instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java Co-authored-by: Mateusz Rzeszutek --- .../opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 6da5b7037708..659a61316ad4 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -47,7 +47,7 @@ public final class OpenTelemetryDriver implements Driver { private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; private static final AtomicBoolean REGISTERED = new AtomicBoolean(); - private static boolean interceptorMode = false; + private static volatile boolean interceptorMode = false; static { try { From 97b8b7131db578600238be1d1fe0e61c2ce772a8 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 19:42:16 +0800 Subject: [PATCH 46/69] Update instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java Co-authored-by: Mateusz Rzeszutek --- .../instrumentation/jdbc/OpenTelemetryDriver.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 659a61316ad4..1240a94976a7 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -108,12 +108,11 @@ public static void setInterceptorMode(final boolean interceptorMode) { * @throws SQLException if registering the driver fails */ public static void register() throws SQLException { - if (isRegistered()) { + if (!REGISTERED.compareAndSet(false, true)) { throw new IllegalStateException( "Driver is already registered. It can only be registered once."); } DriverManager.registerDriver(INSTANCE); - REGISTERED.set(true); } /** From dc769756678aa509f64c94d5fcdeebf8b7d4e11b Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 19:43:03 +0800 Subject: [PATCH 47/69] Update instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java Co-authored-by: Mateusz Rzeszutek --- .../instrumentation/jdbc/OpenTelemetryDriver.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 1240a94976a7..e56747091c31 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -124,12 +124,11 @@ public static void register() throws SQLException { * @throws SQLException if deregistering the driver fails */ public static void deregister() throws SQLException { - if (!REGISTERED.get()) { + if (!REGISTERED.compareAndSet(true, false)) { throw new IllegalStateException( "Driver is not registered (or it has not been registered using Driver.register() method)"); } DriverManager.deregisterDriver(INSTANCE); - REGISTERED.set(false); } /** Returns {@code true} if the driver is registered against {@link DriverManager}. */ From b15f9c9fdbfc3fd7a4db312a429339ab825cfdd7 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 19:43:13 +0800 Subject: [PATCH 48/69] Update instrumentation/jdbc/library/README.md Co-authored-by: Mateusz Rzeszutek --- instrumentation/jdbc/library/README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/instrumentation/jdbc/library/README.md b/instrumentation/jdbc/library/README.md index 7880c0df68c0..1df1d053b64f 100644 --- a/instrumentation/jdbc/library/README.md +++ b/instrumentation/jdbc/library/README.md @@ -55,11 +55,10 @@ Class.forName("io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver"); This mode can be useful for activating tracing for all JDBC connections without modifying the URL. -In "interceptor mode", the `OpenTelemetryDriver` will intercept calls to -`DriverManager.getConnection(url,...)` for all URLs. The `OpenTelemetryDriver` provides connections -to the `DriverManager` that are instrumented. Please note that the `OpenTelemetryDriver` must be -registered before the underlying driver, It's recommended to turn on "interceptor mode" in the first -place. +In the "interceptor mode", the `OpenTelemetryDriver` will intercept calls to +`DriverManager.getConnection(url,...)` for all URLs. The `OpenTelemetryDriver` will return instrumented +connections that will delegate calls to the actual DB driver. Please note that the `OpenTelemetryDriver` must be +registered before the underlying driver - it's recommended to turn on the "interceptor mode" as early as possible. For most applications: From 0dd11788e5964200f63dcf8d23c1c2b41986af20 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 19:43:27 +0800 Subject: [PATCH 49/69] Update instrumentation/jdbc/library/README.md Co-authored-by: Mateusz Rzeszutek --- instrumentation/jdbc/library/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/instrumentation/jdbc/library/README.md b/instrumentation/jdbc/library/README.md index 1df1d053b64f..bda8e9a7e3ba 100644 --- a/instrumentation/jdbc/library/README.md +++ b/instrumentation/jdbc/library/README.md @@ -84,8 +84,8 @@ public void contextInitialized(ServletContextEvent event) { Sometimes it's also required to register the OpenTelemetry driver as a first driver in the DriverManager list, otherwise another driver can be selected at the time of initialization. -To fix this problem it requires calling `OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver()` -method along with `setInterceptorMode(true)`. +Calling `OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver()` method along with +`setInterceptorMode(true)` will fix that problem. Please note drivers like Oracle JDBC may fail since it's destroyed forever after deregistration. From 41e956196bc1ec4c502fc755964793f38fd019ab Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Fri, 25 Jun 2021 19:43:41 +0800 Subject: [PATCH 50/69] Update instrumentation/jdbc/library/README.md Co-authored-by: Mateusz Rzeszutek --- instrumentation/jdbc/library/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/jdbc/library/README.md b/instrumentation/jdbc/library/README.md index bda8e9a7e3ba..e7287bdf8e3d 100644 --- a/instrumentation/jdbc/library/README.md +++ b/instrumentation/jdbc/library/README.md @@ -87,7 +87,7 @@ DriverManager list, otherwise another driver can be selected at the time of init Calling `OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver()` method along with `setInterceptorMode(true)` will fix that problem. -Please note drivers like Oracle JDBC may fail since it's destroyed forever after deregistration. +Please note drivers like Oracle JDBC may fail since they're destroyed forever after deregistration. ### Datasource way From 18beecec63a434a8b1f8a41e4c68fd5c0e576a41 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 26 Jun 2021 00:24:44 +0800 Subject: [PATCH 51/69] Removed javaagent-api module usage. --- instrumentation/jdbc/library/build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/instrumentation/jdbc/library/build.gradle b/instrumentation/jdbc/library/build.gradle index 103fbe5d2f81..adeabfad9c95 100644 --- a/instrumentation/jdbc/library/build.gradle +++ b/instrumentation/jdbc/library/build.gradle @@ -9,7 +9,6 @@ plugins { dependencies { implementation project(':instrumentation-api') - implementation project(':javaagent-api') compileOnly "com.google.auto.value:auto-value-annotations" annotationProcessor "com.google.auto.value:auto-value" From 327d26f7c1472c3b9b56bba0e1e4cfb1596378e5 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 26 Jun 2021 03:07:49 +0800 Subject: [PATCH 52/69] Removed useless checking. --- .../instrumentation/jdbc/OpenTelemetryDriver.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index e56747091c31..5d902428a74e 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -137,10 +137,6 @@ public static boolean isRegistered() { } private static Driver findDriver(String realUrl) { - if (realUrl == null || realUrl.trim().length() == 0) { - throw new IllegalArgumentException("url is required"); - } - for (Driver candidate : Collections.list(DriverManager.getDrivers())) { try { if (!(candidate instanceof OpenTelemetryDriver) && candidate.acceptsURL(realUrl)) { From e6b7925c50835a20140719d41c8a3ec9ad745530 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 26 Jun 2021 04:07:32 +0800 Subject: [PATCH 53/69] Moved javaagent test classes to testing module. --- .../jdbc/TestConnection.groovy | 281 ------ .../jdbc/TestDatabaseMetaData.groovy | 890 ------------------ .../instrumentation/jdbc/TestDriver.groovy | 46 - .../jdbc/TestPreparedStatement.groovy | 285 ------ .../instrumentation/jdbc/TestStatement.groovy | 230 ----- instrumentation/jdbc/testing/build.gradle | 17 + .../jdbc/AnotherTestDriver.groovy | 0 .../jdbc/TestCallableStatement.groovy | 0 .../jdbc}/TestConnection.groovy | 0 .../jdbc}/TestDatabaseMetaData.groovy | 0 .../instrumentation/jdbc}/TestDriver.groovy | 0 .../jdbc}/TestPreparedStatement.groovy | 0 .../jdbc}/TestStatement.groovy | 0 13 files changed, 17 insertions(+), 1732 deletions(-) delete mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy delete mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy delete mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy delete mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy delete mode 100644 instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy create mode 100644 instrumentation/jdbc/testing/build.gradle rename instrumentation/jdbc/{library/src/test => testing/src/main}/groovy/io/opentelemetry/instrumentation/jdbc/AnotherTestDriver.groovy (100%) rename instrumentation/jdbc/{library/src/test => testing/src/main}/groovy/io/opentelemetry/instrumentation/jdbc/TestCallableStatement.groovy (100%) rename instrumentation/jdbc/{javaagent/src/test/groovy/test => testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc}/TestConnection.groovy (100%) rename instrumentation/jdbc/{javaagent/src/test/groovy/test => testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc}/TestDatabaseMetaData.groovy (100%) rename instrumentation/jdbc/{javaagent/src/test/groovy/test => testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc}/TestDriver.groovy (100%) rename instrumentation/jdbc/{javaagent/src/test/groovy/test => testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc}/TestPreparedStatement.groovy (100%) rename instrumentation/jdbc/{javaagent/src/test/groovy/test => testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc}/TestStatement.groovy (100%) diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy deleted file mode 100644 index 9f0d549e07c3..000000000000 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.instrumentation.jdbc - -import java.sql.* -import java.util.concurrent.Executor - -class TestConnection implements Connection { - @Override - Statement createStatement() throws SQLException { - return new TestStatement() - } - - @Override - Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - return new TestStatement() - } - - @Override - Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return new TestStatement() - } - - @Override - PreparedStatement prepareStatement(String sql) throws SQLException { - return new TestPreparedStatement() - } - - @Override - PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return new TestPreparedStatement() - } - - @Override - PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return new TestPreparedStatement() - } - - @Override - PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - return new TestPreparedStatement() - } - - @Override - PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - return new TestPreparedStatement() - } - - @Override - PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - return new TestPreparedStatement() - } - - @Override - CallableStatement prepareCall(String sql) throws SQLException { - return new TestCallableStatement() - } - - @Override - CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return new TestCallableStatement() - } - - @Override - CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return new TestCallableStatement() - } - - @Override - String nativeSQL(String sql) throws SQLException { - return null - } - - @Override - void setAutoCommit(boolean autoCommit) throws SQLException { - - } - - @Override - boolean getAutoCommit() throws SQLException { - return false - } - - @Override - void commit() throws SQLException { - - } - - @Override - void rollback() throws SQLException { - - } - - @Override - void close() throws SQLException { - - } - - @Override - boolean isClosed() throws SQLException { - return false - } - - @Override - DatabaseMetaData getMetaData() throws SQLException { - return new TestDatabaseMetaData() - } - - @Override - void setReadOnly(boolean readOnly) throws SQLException { - - } - - @Override - boolean isReadOnly() throws SQLException { - return false - } - - @Override - void setCatalog(String catalog) throws SQLException { - - } - - @Override - String getCatalog() throws SQLException { - return null - } - - @Override - void setTransactionIsolation(int level) throws SQLException { - - } - - @Override - int getTransactionIsolation() throws SQLException { - return 0 - } - - @Override - SQLWarning getWarnings() throws SQLException { - return null - } - - @Override - void clearWarnings() throws SQLException { - - } - - @Override - Map> getTypeMap() throws SQLException { - return null - } - - @Override - void setTypeMap(Map> map) throws SQLException { - - } - - @Override - void setHoldability(int holdability) throws SQLException { - - } - - @Override - int getHoldability() throws SQLException { - return 0 - } - - @Override - Savepoint setSavepoint() throws SQLException { - return null - } - - @Override - Savepoint setSavepoint(String name) throws SQLException { - return null - } - - @Override - void rollback(Savepoint savepoint) throws SQLException { - - } - - @Override - void releaseSavepoint(Savepoint savepoint) throws SQLException { - - } - - @Override - Clob createClob() throws SQLException { - return null - } - - @Override - Blob createBlob() throws SQLException { - return null - } - - @Override - NClob createNClob() throws SQLException { - return null - } - - @Override - SQLXML createSQLXML() throws SQLException { - return null - } - - @Override - boolean isValid(int timeout) throws SQLException { - return false - } - - @Override - void setClientInfo(String name, String value) throws SQLClientInfoException { - - } - - @Override - void setClientInfo(Properties properties) throws SQLClientInfoException { - - } - - @Override - String getClientInfo(String name) throws SQLException { - return null - } - - @Override - Properties getClientInfo() throws SQLException { - return null - } - - @Override - Array createArrayOf(String typeName, Object[] elements) throws SQLException { - return null - } - - @Override - Struct createStruct(String typeName, Object[] attributes) throws SQLException { - return null - } - - @Override - void setSchema(String schema) throws SQLException { - - } - - @Override - String getSchema() throws SQLException { - return null - } - - @Override - void abort(Executor executor) throws SQLException { - - } - - @Override - void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { - - } - - @Override - int getNetworkTimeout() throws SQLException { - return 0 - } - - @Override - def T unwrap(Class iface) throws SQLException { - return null - } - - @Override - boolean isWrapperFor(Class iface) throws SQLException { - return false - } -} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy deleted file mode 100644 index 7b5370c9f11a..000000000000 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy +++ /dev/null @@ -1,890 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.instrumentation.jdbc - -import java.sql.* - -class TestDatabaseMetaData implements DatabaseMetaData { - @Override - boolean allProceduresAreCallable() throws SQLException { - return false - } - - @Override - boolean allTablesAreSelectable() throws SQLException { - return false - } - - @Override - String getURL() throws SQLException { - return "jdbc:postgresql://127.0.0.1:5432/dbname" - } - - @Override - String getUserName() throws SQLException { - return null - } - - @Override - boolean isReadOnly() throws SQLException { - return false - } - - @Override - boolean nullsAreSortedHigh() throws SQLException { - return false - } - - @Override - boolean nullsAreSortedLow() throws SQLException { - return false - } - - @Override - boolean nullsAreSortedAtStart() throws SQLException { - return false - } - - @Override - boolean nullsAreSortedAtEnd() throws SQLException { - return false - } - - @Override - String getDatabaseProductName() throws SQLException { - return null - } - - @Override - String getDatabaseProductVersion() throws SQLException { - return null - } - - @Override - String getDriverName() throws SQLException { - return null - } - - @Override - String getDriverVersion() throws SQLException { - return null - } - - @Override - int getDriverMajorVersion() { - return 0 - } - - @Override - int getDriverMinorVersion() { - return 0 - } - - @Override - boolean usesLocalFiles() throws SQLException { - return false - } - - @Override - boolean usesLocalFilePerTable() throws SQLException { - return false - } - - @Override - boolean supportsMixedCaseIdentifiers() throws SQLException { - return false - } - - @Override - boolean storesUpperCaseIdentifiers() throws SQLException { - return false - } - - @Override - boolean storesLowerCaseIdentifiers() throws SQLException { - return false - } - - @Override - boolean storesMixedCaseIdentifiers() throws SQLException { - return false - } - - @Override - boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { - return false - } - - @Override - boolean storesUpperCaseQuotedIdentifiers() throws SQLException { - return false - } - - @Override - boolean storesLowerCaseQuotedIdentifiers() throws SQLException { - return false - } - - @Override - boolean storesMixedCaseQuotedIdentifiers() throws SQLException { - return false - } - - @Override - String getIdentifierQuoteString() throws SQLException { - return null - } - - @Override - String getSQLKeywords() throws SQLException { - return null - } - - @Override - String getNumericFunctions() throws SQLException { - return null - } - - @Override - String getStringFunctions() throws SQLException { - return null - } - - @Override - String getSystemFunctions() throws SQLException { - return null - } - - @Override - String getTimeDateFunctions() throws SQLException { - return null - } - - @Override - String getSearchStringEscape() throws SQLException { - return null - } - - @Override - String getExtraNameCharacters() throws SQLException { - return null - } - - @Override - boolean supportsAlterTableWithAddColumn() throws SQLException { - return false - } - - @Override - boolean supportsAlterTableWithDropColumn() throws SQLException { - return false - } - - @Override - boolean supportsColumnAliasing() throws SQLException { - return false - } - - @Override - boolean nullPlusNonNullIsNull() throws SQLException { - return false - } - - @Override - boolean supportsConvert() throws SQLException { - return false - } - - @Override - boolean supportsConvert(int fromType, int toType) throws SQLException { - return false - } - - @Override - boolean supportsTableCorrelationNames() throws SQLException { - return false - } - - @Override - boolean supportsDifferentTableCorrelationNames() throws SQLException { - return false - } - - @Override - boolean supportsExpressionsInOrderBy() throws SQLException { - return false - } - - @Override - boolean supportsOrderByUnrelated() throws SQLException { - return false - } - - @Override - boolean supportsGroupBy() throws SQLException { - return false - } - - @Override - boolean supportsGroupByUnrelated() throws SQLException { - return false - } - - @Override - boolean supportsGroupByBeyondSelect() throws SQLException { - return false - } - - @Override - boolean supportsLikeEscapeClause() throws SQLException { - return false - } - - @Override - boolean supportsMultipleResultSets() throws SQLException { - return false - } - - @Override - boolean supportsMultipleTransactions() throws SQLException { - return false - } - - @Override - boolean supportsNonNullableColumns() throws SQLException { - return false - } - - @Override - boolean supportsMinimumSQLGrammar() throws SQLException { - return false - } - - @Override - boolean supportsCoreSQLGrammar() throws SQLException { - return false - } - - @Override - boolean supportsExtendedSQLGrammar() throws SQLException { - return false - } - - @Override - boolean supportsANSI92EntryLevelSQL() throws SQLException { - return false - } - - @Override - boolean supportsANSI92IntermediateSQL() throws SQLException { - return false - } - - @Override - boolean supportsANSI92FullSQL() throws SQLException { - return false - } - - @Override - boolean supportsIntegrityEnhancementFacility() throws SQLException { - return false - } - - @Override - boolean supportsOuterJoins() throws SQLException { - return false - } - - @Override - boolean supportsFullOuterJoins() throws SQLException { - return false - } - - @Override - boolean supportsLimitedOuterJoins() throws SQLException { - return false - } - - @Override - String getSchemaTerm() throws SQLException { - return null - } - - @Override - String getProcedureTerm() throws SQLException { - return null - } - - @Override - String getCatalogTerm() throws SQLException { - return null - } - - @Override - boolean isCatalogAtStart() throws SQLException { - return false - } - - @Override - String getCatalogSeparator() throws SQLException { - return null - } - - @Override - boolean supportsSchemasInDataManipulation() throws SQLException { - return false - } - - @Override - boolean supportsSchemasInProcedureCalls() throws SQLException { - return false - } - - @Override - boolean supportsSchemasInTableDefinitions() throws SQLException { - return false - } - - @Override - boolean supportsSchemasInIndexDefinitions() throws SQLException { - return false - } - - @Override - boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { - return false - } - - @Override - boolean supportsCatalogsInDataManipulation() throws SQLException { - return false - } - - @Override - boolean supportsCatalogsInProcedureCalls() throws SQLException { - return false - } - - @Override - boolean supportsCatalogsInTableDefinitions() throws SQLException { - return false - } - - @Override - boolean supportsCatalogsInIndexDefinitions() throws SQLException { - return false - } - - @Override - boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { - return false - } - - @Override - boolean supportsPositionedDelete() throws SQLException { - return false - } - - @Override - boolean supportsPositionedUpdate() throws SQLException { - return false - } - - @Override - boolean supportsSelectForUpdate() throws SQLException { - return false - } - - @Override - boolean supportsStoredProcedures() throws SQLException { - return false - } - - @Override - boolean supportsSubqueriesInComparisons() throws SQLException { - return false - } - - @Override - boolean supportsSubqueriesInExists() throws SQLException { - return false - } - - @Override - boolean supportsSubqueriesInIns() throws SQLException { - return false - } - - @Override - boolean supportsSubqueriesInQuantifieds() throws SQLException { - return false - } - - @Override - boolean supportsCorrelatedSubqueries() throws SQLException { - return false - } - - @Override - boolean supportsUnion() throws SQLException { - return false - } - - @Override - boolean supportsUnionAll() throws SQLException { - return false - } - - @Override - boolean supportsOpenCursorsAcrossCommit() throws SQLException { - return false - } - - @Override - boolean supportsOpenCursorsAcrossRollback() throws SQLException { - return false - } - - @Override - boolean supportsOpenStatementsAcrossCommit() throws SQLException { - return false - } - - @Override - boolean supportsOpenStatementsAcrossRollback() throws SQLException { - return false - } - - @Override - int getMaxBinaryLiteralLength() throws SQLException { - return 0 - } - - @Override - int getMaxCharLiteralLength() throws SQLException { - return 0 - } - - @Override - int getMaxColumnNameLength() throws SQLException { - return 0 - } - - @Override - int getMaxColumnsInGroupBy() throws SQLException { - return 0 - } - - @Override - int getMaxColumnsInIndex() throws SQLException { - return 0 - } - - @Override - int getMaxColumnsInOrderBy() throws SQLException { - return 0 - } - - @Override - int getMaxColumnsInSelect() throws SQLException { - return 0 - } - - @Override - int getMaxColumnsInTable() throws SQLException { - return 0 - } - - @Override - int getMaxConnections() throws SQLException { - return 0 - } - - @Override - int getMaxCursorNameLength() throws SQLException { - return 0 - } - - @Override - int getMaxIndexLength() throws SQLException { - return 0 - } - - @Override - int getMaxSchemaNameLength() throws SQLException { - return 0 - } - - @Override - int getMaxProcedureNameLength() throws SQLException { - return 0 - } - - @Override - int getMaxCatalogNameLength() throws SQLException { - return 0 - } - - @Override - int getMaxRowSize() throws SQLException { - return 0 - } - - @Override - boolean doesMaxRowSizeIncludeBlobs() throws SQLException { - return false - } - - @Override - int getMaxStatementLength() throws SQLException { - return 0 - } - - @Override - int getMaxStatements() throws SQLException { - return 0 - } - - @Override - int getMaxTableNameLength() throws SQLException { - return 0 - } - - @Override - int getMaxTablesInSelect() throws SQLException { - return 0 - } - - @Override - int getMaxUserNameLength() throws SQLException { - return 0 - } - - @Override - int getDefaultTransactionIsolation() throws SQLException { - return 0 - } - - @Override - boolean supportsTransactions() throws SQLException { - return false - } - - @Override - boolean supportsTransactionIsolationLevel(int level) throws SQLException { - return false - } - - @Override - boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { - return false - } - - @Override - boolean supportsDataManipulationTransactionsOnly() throws SQLException { - return false - } - - @Override - boolean dataDefinitionCausesTransactionCommit() throws SQLException { - return false - } - - @Override - boolean dataDefinitionIgnoredInTransactions() throws SQLException { - return false - } - - @Override - ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { - return null - } - - @Override - ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { - return null - } - - @Override - ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { - return null - } - - @Override - ResultSet getSchemas() throws SQLException { - return null - } - - @Override - ResultSet getCatalogs() throws SQLException { - return null - } - - @Override - ResultSet getTableTypes() throws SQLException { - return null - } - - @Override - ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { - return null - } - - @Override - ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { - return null - } - - @Override - ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { - return null - } - - @Override - ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { - return null - } - - @Override - ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { - return null - } - - @Override - ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { - return null - } - - @Override - ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { - return null - } - - @Override - ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { - return null - } - - @Override - ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { - return null - } - - @Override - ResultSet getTypeInfo() throws SQLException { - return null - } - - @Override - ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { - return null - } - - @Override - boolean supportsResultSetType(int type) throws SQLException { - return false - } - - @Override - boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { - return false - } - - @Override - boolean ownUpdatesAreVisible(int type) throws SQLException { - return false - } - - @Override - boolean ownDeletesAreVisible(int type) throws SQLException { - return false - } - - @Override - boolean ownInsertsAreVisible(int type) throws SQLException { - return false - } - - @Override - boolean othersUpdatesAreVisible(int type) throws SQLException { - return false - } - - @Override - boolean othersDeletesAreVisible(int type) throws SQLException { - return false - } - - @Override - boolean othersInsertsAreVisible(int type) throws SQLException { - return false - } - - @Override - boolean updatesAreDetected(int type) throws SQLException { - return false - } - - @Override - boolean deletesAreDetected(int type) throws SQLException { - return false - } - - @Override - boolean insertsAreDetected(int type) throws SQLException { - return false - } - - @Override - boolean supportsBatchUpdates() throws SQLException { - return false - } - - @Override - ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { - return null - } - - @Override - Connection getConnection() throws SQLException { - return null - } - - @Override - boolean supportsSavepoints() throws SQLException { - return false - } - - @Override - boolean supportsNamedParameters() throws SQLException { - return false - } - - @Override - boolean supportsMultipleOpenResults() throws SQLException { - return false - } - - @Override - boolean supportsGetGeneratedKeys() throws SQLException { - return false - } - - @Override - ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { - return null - } - - @Override - ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { - return null - } - - @Override - ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { - return null - } - - @Override - boolean supportsResultSetHoldability(int holdability) throws SQLException { - return false - } - - @Override - int getResultSetHoldability() throws SQLException { - return 0 - } - - @Override - int getDatabaseMajorVersion() throws SQLException { - return 0 - } - - @Override - int getDatabaseMinorVersion() throws SQLException { - return 0 - } - - @Override - int getJDBCMajorVersion() throws SQLException { - return 0 - } - - @Override - int getJDBCMinorVersion() throws SQLException { - return 0 - } - - @Override - int getSQLStateType() throws SQLException { - return 0 - } - - @Override - boolean locatorsUpdateCopy() throws SQLException { - return false - } - - @Override - boolean supportsStatementPooling() throws SQLException { - return false - } - - @Override - RowIdLifetime getRowIdLifetime() throws SQLException { - return null - } - - @Override - ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { - return null - } - - @Override - boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { - return false - } - - @Override - boolean autoCommitFailureClosesAllResultSets() throws SQLException { - return false - } - - @Override - ResultSet getClientInfoProperties() throws SQLException { - return null - } - - @Override - ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException { - return null - } - - @Override - ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException { - return null - } - - @Override - ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { - return null - } - - @Override - boolean generatedKeyAlwaysReturned() throws SQLException { - return false - } - - @Override - def T unwrap(Class iface) throws SQLException { - return null - } - - @Override - boolean isWrapperFor(Class iface) throws SQLException { - return false - } -} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy deleted file mode 100644 index db93d28ed82f..000000000000 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.instrumentation.jdbc - -import java.sql.* -import java.util.logging.Logger - -class TestDriver implements Driver { - @Override - Connection connect(String url, Properties info) throws SQLException { - return new TestConnection() - } - - @Override - boolean acceptsURL(String url) throws SQLException { - return url?.startsWith("jdbc:test:") - } - - @Override - DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { - return [new DriverPropertyInfo("test", "test")] - } - - @Override - int getMajorVersion() { - return 0 - } - - @Override - int getMinorVersion() { - return 0 - } - - @Override - boolean jdbcCompliant() { - return false - } - - @Override - Logger getParentLogger() throws SQLFeatureNotSupportedException { - return null - } -} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy deleted file mode 100644 index 083755c715f0..000000000000 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.instrumentation.jdbc - -import java.sql.* - -class TestPreparedStatement extends TestStatement implements PreparedStatement { - @Override - boolean execute() throws SQLException { - return true - } - - @Override - ResultSet executeQuery() throws SQLException { - return null - } - - @Override - int executeUpdate() throws SQLException { - return 0 - } - - @Override - void setNull(int parameterIndex, int sqlType) throws SQLException { - - } - - @Override - void setBoolean(int parameterIndex, boolean x) throws SQLException { - - } - - @Override - void setByte(int parameterIndex, byte x) throws SQLException { - - } - - @Override - void setShort(int parameterIndex, short x) throws SQLException { - - } - - @Override - void setInt(int parameterIndex, int x) throws SQLException { - - } - - @Override - void setLong(int parameterIndex, long x) throws SQLException { - - } - - @Override - void setFloat(int parameterIndex, float x) throws SQLException { - - } - - @Override - void setDouble(int parameterIndex, double x) throws SQLException { - - } - - @Override - void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { - - } - - @Override - void setString(int parameterIndex, String x) throws SQLException { - - } - - @Override - void setBytes(int parameterIndex, byte[] x) throws SQLException { - - } - - @Override - void setDate(int parameterIndex, Date x) throws SQLException { - - } - - @Override - void setTime(int parameterIndex, Time x) throws SQLException { - - } - - @Override - void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { - - } - - @Override - void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { - - } - - @Override - void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { - - } - - @Override - void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { - - } - - @Override - void clearParameters() throws SQLException { - - } - - @Override - void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { - - } - - @Override - void setObject(int parameterIndex, Object x) throws SQLException { - - } - - @Override - void addBatch() throws SQLException { - - } - - @Override - void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { - - } - - @Override - void setRef(int parameterIndex, Ref x) throws SQLException { - - } - - @Override - void setBlob(int parameterIndex, Blob x) throws SQLException { - - } - - @Override - void setClob(int parameterIndex, Clob x) throws SQLException { - - } - - @Override - void setArray(int parameterIndex, Array x) throws SQLException { - - } - - @Override - ResultSetMetaData getMetaData() throws SQLException { - return null - } - - @Override - void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { - - } - - @Override - void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { - - } - - @Override - void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { - - } - - @Override - void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { - - } - - @Override - void setURL(int parameterIndex, URL x) throws SQLException { - - } - - @Override - ParameterMetaData getParameterMetaData() throws SQLException { - return null - } - - @Override - void setRowId(int parameterIndex, RowId x) throws SQLException { - - } - - @Override - void setNString(int parameterIndex, String value) throws SQLException { - - } - - @Override - void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { - - } - - @Override - void setNClob(int parameterIndex, NClob value) throws SQLException { - - } - - @Override - void setClob(int parameterIndex, Reader reader, long length) throws SQLException { - - } - - @Override - void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { - - } - - @Override - void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { - - } - - @Override - void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { - - } - - @Override - void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { - - } - - @Override - void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { - - } - - @Override - void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { - - } - - @Override - void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { - - } - - @Override - void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { - - } - - @Override - void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { - - } - - @Override - void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { - - } - - @Override - void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { - - } - - @Override - void setClob(int parameterIndex, Reader reader) throws SQLException { - - } - - @Override - void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { - - } - - @Override - void setNClob(int parameterIndex, Reader reader) throws SQLException { - - } -} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy deleted file mode 100644 index fd9f4dc3af20..000000000000 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.instrumentation.jdbc - -import java.sql.* - -class TestStatement implements Statement { - @Override - boolean execute(String sql) throws SQLException { - return true - } - - @Override - boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return true - } - - @Override - boolean execute(String sql, int[] columnIndexes) throws SQLException { - return true - } - - @Override - boolean execute(String sql, String[] columnNames) throws SQLException { - return true - } - - @Override - ResultSet executeQuery(String sql) throws SQLException { - return null - } - - @Override - int executeUpdate(String sql) throws SQLException { - return 0 - } - - @Override - int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - return 0 - } - - @Override - int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - return 0 - } - - @Override - int executeUpdate(String sql, String[] columnNames) throws SQLException { - return 0 - } - - @Override - void close() throws SQLException { - - } - - @Override - int getMaxFieldSize() throws SQLException { - return 0 - } - - @Override - void setMaxFieldSize(int max) throws SQLException { - - } - - @Override - int getMaxRows() throws SQLException { - return 0 - } - - @Override - void setMaxRows(int max) throws SQLException { - - } - - @Override - void setEscapeProcessing(boolean enable) throws SQLException { - - } - - @Override - int getQueryTimeout() throws SQLException { - return 0 - } - - @Override - void setQueryTimeout(int seconds) throws SQLException { - - } - - @Override - void cancel() throws SQLException { - - } - - @Override - SQLWarning getWarnings() throws SQLException { - return null - } - - @Override - void clearWarnings() throws SQLException { - - } - - @Override - void setCursorName(String name) throws SQLException { - - } - - @Override - ResultSet getResultSet() throws SQLException { - return null - } - - @Override - int getUpdateCount() throws SQLException { - return 0 - } - - @Override - boolean getMoreResults() throws SQLException { - return false - } - - @Override - void setFetchDirection(int direction) throws SQLException { - - } - - @Override - int getFetchDirection() throws SQLException { - return 0 - } - - @Override - void setFetchSize(int rows) throws SQLException { - - } - - @Override - int getFetchSize() throws SQLException { - return 0 - } - - @Override - int getResultSetConcurrency() throws SQLException { - return 0 - } - - @Override - int getResultSetType() throws SQLException { - return 0 - } - - @Override - void addBatch(String sql) throws SQLException { - - } - - @Override - void clearBatch() throws SQLException { - - } - - @Override - int[] executeBatch() throws SQLException { - return new int[0] - } - - @Override - Connection getConnection() throws SQLException { - return null - } - - @Override - boolean getMoreResults(int current) throws SQLException { - return false - } - - @Override - ResultSet getGeneratedKeys() throws SQLException { - return null - } - - @Override - int getResultSetHoldability() throws SQLException { - return 0 - } - - @Override - boolean isClosed() throws SQLException { - return false - } - - @Override - void setPoolable(boolean poolable) throws SQLException { - - } - - @Override - boolean isPoolable() throws SQLException { - return false - } - - @Override - void closeOnCompletion() throws SQLException { - - } - - @Override - boolean isCloseOnCompletion() throws SQLException { - return false - } - - @Override - def T unwrap(Class iface) throws SQLException { - return null - } - - @Override - boolean isWrapperFor(Class iface) throws SQLException { - return false - } -} diff --git a/instrumentation/jdbc/testing/build.gradle b/instrumentation/jdbc/testing/build.gradle new file mode 100644 index 000000000000..adeabfad9c95 --- /dev/null +++ b/instrumentation/jdbc/testing/build.gradle @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +plugins { + id("otel.library-instrumentation") +} + +dependencies { + implementation project(':instrumentation-api') + + compileOnly "com.google.auto.value:auto-value-annotations" + annotationProcessor "com.google.auto.value:auto-value" + + implementation "org.slf4j:slf4j-api" +} diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/AnotherTestDriver.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/AnotherTestDriver.groovy similarity index 100% rename from instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/AnotherTestDriver.groovy rename to instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/AnotherTestDriver.groovy diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestCallableStatement.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestCallableStatement.groovy similarity index 100% rename from instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/TestCallableStatement.groovy rename to instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestCallableStatement.groovy diff --git a/instrumentation/jdbc/javaagent/src/test/groovy/test/TestConnection.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy similarity index 100% rename from instrumentation/jdbc/javaagent/src/test/groovy/test/TestConnection.groovy rename to instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy diff --git a/instrumentation/jdbc/javaagent/src/test/groovy/test/TestDatabaseMetaData.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy similarity index 100% rename from instrumentation/jdbc/javaagent/src/test/groovy/test/TestDatabaseMetaData.groovy rename to instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy diff --git a/instrumentation/jdbc/javaagent/src/test/groovy/test/TestDriver.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy similarity index 100% rename from instrumentation/jdbc/javaagent/src/test/groovy/test/TestDriver.groovy rename to instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy diff --git a/instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy similarity index 100% rename from instrumentation/jdbc/javaagent/src/test/groovy/test/TestPreparedStatement.groovy rename to instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy diff --git a/instrumentation/jdbc/javaagent/src/test/groovy/test/TestStatement.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy similarity index 100% rename from instrumentation/jdbc/javaagent/src/test/groovy/test/TestStatement.groovy rename to instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy From e14ac6a3b030256864915e4eebce5d6d9b903226 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 26 Jun 2021 04:11:38 +0800 Subject: [PATCH 54/69] Move common JDBC test classes to testing module. --- instrumentation/jdbc/javaagent/build.gradle | 2 + .../groovy/JdbcInstrumentationTest.groovy | 9 +- instrumentation/jdbc/library/build.gradle | 2 + instrumentation/jdbc/testing/build.gradle | 9 +- .../jdbc/TestConnection.groovy | 130 +++++++++--------- .../jdbc/TestDatabaseMetaData.groovy | 20 ++- .../instrumentation/jdbc/TestDriver.groovy | 14 +- .../jdbc/TestPreparedStatement.groovy | 36 ++--- .../instrumentation/jdbc/TestStatement.groovy | 20 +-- settings.gradle | 1 + 10 files changed, 119 insertions(+), 124 deletions(-) diff --git a/instrumentation/jdbc/javaagent/build.gradle b/instrumentation/jdbc/javaagent/build.gradle index cd781c19bd76..ae7e0d8e1a6c 100644 --- a/instrumentation/jdbc/javaagent/build.gradle +++ b/instrumentation/jdbc/javaagent/build.gradle @@ -27,6 +27,8 @@ dependencies { testLibrary "com.mchange:c3p0:0.9.5" latestDepTestLibrary "org.apache.derby:derby:10.14.+" + + testImplementation project(':instrumentation:jdbc:testing') } tasks.withType(Test).configureEach { diff --git a/instrumentation/jdbc/javaagent/src/test/groovy/JdbcInstrumentationTest.groovy b/instrumentation/jdbc/javaagent/src/test/groovy/JdbcInstrumentationTest.groovy index 2cde833052ed..4dd9c5a6a162 100644 --- a/instrumentation/jdbc/javaagent/src/test/groovy/JdbcInstrumentationTest.groovy +++ b/instrumentation/jdbc/javaagent/src/test/groovy/JdbcInstrumentationTest.groovy @@ -3,6 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 */ + +import io.opentelemetry.instrumentation.jdbc.TestConnection +import io.opentelemetry.instrumentation.jdbc.TestDriver + import static io.opentelemetry.api.trace.SpanKind.CLIENT import static io.opentelemetry.api.trace.SpanKind.INTERNAL import static io.opentelemetry.instrumentation.test.utils.TraceUtils.basicSpan @@ -28,8 +32,6 @@ import org.h2.jdbcx.JdbcDataSource import org.hsqldb.jdbc.JDBCDriver import spock.lang.Shared import spock.lang.Unroll -import test.TestConnection -import test.TestDriver @Unroll class JdbcInstrumentationTest extends AgentInstrumentationSpecification { @@ -466,6 +468,7 @@ class JdbcInstrumentationTest extends AgentInstrumentationSpecification { when: try { connection = new TestConnection(true) + connection.url = "jdbc:testdb://localhost" } catch (Exception ignored) { connection = driver.connect(jdbcUrl, null) } @@ -580,6 +583,7 @@ class JdbcInstrumentationTest extends AgentInstrumentationSpecification { def "test getClientInfo exception"() { setup: Connection connection = new TestConnection(false) + connection.url = "jdbc:testdb://localhost" when: Statement statement = null @@ -720,6 +724,7 @@ class JdbcInstrumentationTest extends AgentInstrumentationSpecification { def "should handle recursive Statements inside Connection.getMetaData(): #desc"() { given: def connection = new DbCallingConnection(usePreparedStatementInConnection) + connection.url = "jdbc:testdb://localhost" when: runUnderTrace("parent") { diff --git a/instrumentation/jdbc/library/build.gradle b/instrumentation/jdbc/library/build.gradle index adeabfad9c95..520c2d7e6683 100644 --- a/instrumentation/jdbc/library/build.gradle +++ b/instrumentation/jdbc/library/build.gradle @@ -14,4 +14,6 @@ dependencies { annotationProcessor "com.google.auto.value:auto-value" implementation "org.slf4j:slf4j-api" + + testImplementation project(':instrumentation:jdbc:testing') } diff --git a/instrumentation/jdbc/testing/build.gradle b/instrumentation/jdbc/testing/build.gradle index adeabfad9c95..e2e8e71be169 100644 --- a/instrumentation/jdbc/testing/build.gradle +++ b/instrumentation/jdbc/testing/build.gradle @@ -4,14 +4,9 @@ */ plugins { - id("otel.library-instrumentation") + id("otel.java-conventions") } dependencies { - implementation project(':instrumentation-api') - - compileOnly "com.google.auto.value:auto-value-annotations" - annotationProcessor "com.google.auto.value:auto-value" - - implementation "org.slf4j:slf4j-api" + implementation "org.codehaus.groovy:groovy-all" } diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy index 9eca7a13a2f4..f0644d8b4a2d 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy @@ -3,50 +3,85 @@ * SPDX-License-Identifier: Apache-2.0 */ -package test - -import java.sql.Array -import java.sql.Blob -import java.sql.CallableStatement -import java.sql.Clob -import java.sql.Connection -import java.sql.DatabaseMetaData -import java.sql.NClob -import java.sql.PreparedStatement -import java.sql.SQLClientInfoException -import java.sql.SQLException -import java.sql.SQLWarning -import java.sql.SQLXML -import java.sql.Savepoint -import java.sql.Statement -import java.sql.Struct -import java.util.concurrent.Executor +package io.opentelemetry.instrumentation.jdbc +import java.sql.* +import java.util.concurrent.Executor /** * A JDBC connection class that optionally throws an exception in the constructor, used to test */ class TestConnection implements Connection { + private String url + + TestConnection() { + this(false) + } + TestConnection(boolean throwException) { if (throwException) { throw new IllegalStateException("connection exception") } } - @Override Statement createStatement() throws SQLException { return new TestStatement(this) } + @Override + Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + return new TestStatement(this) + } + + @Override + Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return new TestStatement(this) + } + @Override PreparedStatement prepareStatement(String sql) throws SQLException { return new TestPreparedStatement(this) } + @Override + PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return new TestPreparedStatement(this) + } + + @Override + PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return new TestPreparedStatement(this) + } + + @Override + PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return new TestPreparedStatement(this) + } + + @Override + PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return new TestPreparedStatement(this) + } + + @Override + PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return new TestPreparedStatement(this) + } + @Override CallableStatement prepareCall(String sql) throws SQLException { - return null + return new TestCallableStatement() + } + + @Override + CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return new TestCallableStatement() + } + + @Override + CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return new TestCallableStatement() } @Override @@ -86,7 +121,11 @@ class TestConnection implements Connection { @Override DatabaseMetaData getMetaData() throws SQLException { - return new TestDatabaseMetaData() + if (url) { + return new TestDatabaseMetaData(url) + } else { + return new TestDatabaseMetaData() + } } @Override @@ -129,21 +168,6 @@ class TestConnection implements Connection { } - @Override - Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return null - } - - @Override - CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return null - } - @Override Map> getTypeMap() throws SQLException { return null @@ -184,36 +208,6 @@ class TestConnection implements Connection { } - @Override - Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return null - } - - @Override - CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - return null - } - - @Override - PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - return null - } - @Override Clob createClob() throws SQLException { return null @@ -303,4 +297,8 @@ class TestConnection implements Connection { boolean isWrapperFor(Class iface) throws SQLException { return false } + + void setUrl(String url) { + this.url = url + } } diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy index 757b43a2dff5..598570be48e5 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy @@ -3,15 +3,21 @@ * SPDX-License-Identifier: Apache-2.0 */ -package test +package io.opentelemetry.instrumentation.jdbc -import java.sql.Connection -import java.sql.DatabaseMetaData -import java.sql.ResultSet -import java.sql.RowIdLifetime -import java.sql.SQLException +import java.sql.* class TestDatabaseMetaData implements DatabaseMetaData { + final String url + + TestDatabaseMetaData() { + this("jdbc:postgresql://127.0.0.1:5432/dbname") + } + + TestDatabaseMetaData(String url) { + this.url = url + } + @Override boolean allProceduresAreCallable() throws SQLException { return false @@ -24,7 +30,7 @@ class TestDatabaseMetaData implements DatabaseMetaData { @Override String getURL() throws SQLException { - return "jdbc:testdb://localhost" + return url } @Override diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy index 60b2368bac57..db93d28ed82f 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDriver.groovy @@ -3,29 +3,25 @@ * SPDX-License-Identifier: Apache-2.0 */ -package test +package io.opentelemetry.instrumentation.jdbc -import java.sql.Connection -import java.sql.Driver -import java.sql.DriverPropertyInfo -import java.sql.SQLException -import java.sql.SQLFeatureNotSupportedException +import java.sql.* import java.util.logging.Logger class TestDriver implements Driver { @Override Connection connect(String url, Properties info) throws SQLException { - return new TestConnection("connectException=true" == url) + return new TestConnection() } @Override boolean acceptsURL(String url) throws SQLException { - return false + return url?.startsWith("jdbc:test:") } @Override DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { - return new DriverPropertyInfo[0] + return [new DriverPropertyInfo("test", "test")] } @Override diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy index 5f2b4f1a02da..d9f9a04c0d0e 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy @@ -3,30 +3,25 @@ * SPDX-License-Identifier: Apache-2.0 */ -package test - -import java.sql.Array -import java.sql.Blob -import java.sql.Clob -import java.sql.Connection -import java.sql.Date -import java.sql.NClob -import java.sql.ParameterMetaData -import java.sql.PreparedStatement -import java.sql.Ref -import java.sql.ResultSet -import java.sql.ResultSetMetaData -import java.sql.RowId -import java.sql.SQLException -import java.sql.SQLXML -import java.sql.Time -import java.sql.Timestamp +package io.opentelemetry.instrumentation.jdbc + +import java.sql.* class TestPreparedStatement extends TestStatement implements PreparedStatement { + + TestPreparedStatement() { + super() + } + TestPreparedStatement(Connection connection) { super(connection) } + @Override + boolean execute() throws SQLException { + return true + } + @Override ResultSet executeQuery() throws SQLException { return null @@ -137,11 +132,6 @@ class TestPreparedStatement extends TestStatement implements PreparedStatement { } - @Override - boolean execute() throws SQLException { - return false - } - @Override void addBatch() throws SQLException { diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy index 3a2605c353e7..4d70e07553aa 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy @@ -3,17 +3,17 @@ * SPDX-License-Identifier: Apache-2.0 */ -package test +package io.opentelemetry.instrumentation.jdbc -import java.sql.Connection -import java.sql.ResultSet -import java.sql.SQLException -import java.sql.SQLWarning -import java.sql.Statement +import java.sql.* class TestStatement implements Statement { final Connection connection + TestStatement() { + this.connection = null + } + TestStatement(Connection connection) { this.connection = connection } @@ -90,7 +90,7 @@ class TestStatement implements Statement { @Override boolean execute(String sql) throws SQLException { - return false + return true } @Override @@ -185,17 +185,17 @@ class TestStatement implements Statement { @Override boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return false + return true } @Override boolean execute(String sql, int[] columnIndexes) throws SQLException { - return false + return true } @Override boolean execute(String sql, String[] columnNames) throws SQLException { - return false + return true } @Override diff --git a/settings.gradle b/settings.gradle index 10d932a1c562..a9466931599e 100644 --- a/settings.gradle +++ b/settings.gradle @@ -180,6 +180,7 @@ include ':instrumentation:jaxws:jaxws-common:library' include ':instrumentation:jaxws:jws-1.1:javaagent' include ':instrumentation:jdbc:javaagent' include ':instrumentation:jdbc:library' +include ':instrumentation:jdbc:testing' include ':instrumentation:jedis:jedis-1.4:javaagent' include ':instrumentation:jedis:jedis-3.0:javaagent' include ':instrumentation:jetty:jetty-8.0:javaagent' From bbbef33c839a9ad4ec7c90432f706ef5aee0483a Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 26 Jun 2021 04:15:41 +0800 Subject: [PATCH 55/69] Spotless fixes. --- .../javaagent/src/test/groovy/JdbcInstrumentationTest.groovy | 1 - 1 file changed, 1 deletion(-) diff --git a/instrumentation/jdbc/javaagent/src/test/groovy/JdbcInstrumentationTest.groovy b/instrumentation/jdbc/javaagent/src/test/groovy/JdbcInstrumentationTest.groovy index 4dd9c5a6a162..045d4b706c96 100644 --- a/instrumentation/jdbc/javaagent/src/test/groovy/JdbcInstrumentationTest.groovy +++ b/instrumentation/jdbc/javaagent/src/test/groovy/JdbcInstrumentationTest.groovy @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - import io.opentelemetry.instrumentation.jdbc.TestConnection import io.opentelemetry.instrumentation.jdbc.TestDriver From b35f6bbe302565d51405ffb5b0d6c700420abdb8 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 26 Jun 2021 04:20:33 +0800 Subject: [PATCH 56/69] Code format. --- .../instrumentation/jdbc/TestConnection.groovy | 16 +++++++++++++++- .../jdbc/TestDatabaseMetaData.groovy | 6 +++++- .../jdbc/TestPreparedStatement.groovy | 17 ++++++++++++++++- .../instrumentation/jdbc/TestStatement.groovy | 6 +++++- 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy index f0644d8b4a2d..724eccd3e49d 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy @@ -5,7 +5,21 @@ package io.opentelemetry.instrumentation.jdbc -import java.sql.* +import java.sql.Array +import java.sql.Blob +import java.sql.CallableStatement +import java.sql.Clob +import java.sql.Connection +import java.sql.DatabaseMetaData +import java.sql.NClob +import java.sql.PreparedStatement +import java.sql.SQLClientInfoException +import java.sql.SQLException +import java.sql.SQLWarning +import java.sql.SQLXML +import java.sql.Savepoint +import java.sql.Statement +import java.sql.Struct import java.util.concurrent.Executor /** diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy index 598570be48e5..a65835f08a9c 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestDatabaseMetaData.groovy @@ -5,7 +5,11 @@ package io.opentelemetry.instrumentation.jdbc -import java.sql.* +import java.sql.Connection +import java.sql.DatabaseMetaData +import java.sql.ResultSet +import java.sql.RowIdLifetime +import java.sql.SQLException class TestDatabaseMetaData implements DatabaseMetaData { final String url diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy index d9f9a04c0d0e..c8f21d061beb 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestPreparedStatement.groovy @@ -5,7 +5,22 @@ package io.opentelemetry.instrumentation.jdbc -import java.sql.* +import java.sql.Array +import java.sql.Blob +import java.sql.Clob +import java.sql.Connection +import java.sql.Date +import java.sql.NClob +import java.sql.ParameterMetaData +import java.sql.PreparedStatement +import java.sql.Ref +import java.sql.ResultSet +import java.sql.ResultSetMetaData +import java.sql.RowId +import java.sql.SQLException +import java.sql.SQLXML +import java.sql.Time +import java.sql.Timestamp class TestPreparedStatement extends TestStatement implements PreparedStatement { diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy index 4d70e07553aa..4c833c93358c 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestStatement.groovy @@ -5,7 +5,11 @@ package io.opentelemetry.instrumentation.jdbc -import java.sql.* +import java.sql.Connection +import java.sql.ResultSet +import java.sql.SQLException +import java.sql.SQLWarning +import java.sql.Statement class TestStatement implements Statement { final Connection connection From 402637b48bb1ca61040777c12a57f2bd8c2bd21f Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 26 Jun 2021 04:34:29 +0800 Subject: [PATCH 57/69] Moved PeerServiceAttributesExtractor back to javaagent-api module. --- .../v2_0/ApacheHttpClientSingletons.java | 2 +- .../v4_0/ApacheHttpClientSingletons.java | 2 +- .../v5_0/ApacheHttpClientSingletons.java | 2 +- .../armeria/v1_3/ArmeriaSingletons.java | 2 +- .../v2_0/AsyncHttpClientSingletons.java | 2 +- .../grpc/v1_6/GrpcSingletons.java | 2 +- .../jdbc/JavaAgentJdbcSingletons.java | 43 +++++++++++++++++++ .../PreparedStatementInstrumentation.java | 2 +- .../internal/JdbcAttributesExtractor.java | 2 +- .../internal/JdbcNetAttributesExtractor.java | 2 +- .../jdbc/internal/JdbcSingletons.java | 2 - .../jedis/v1_4/JedisSingletons.java | 2 +- .../jedis/v3_0/JedisSingletons.java | 2 +- .../lettuce/v4_0/LettuceSingletons.java | 2 +- .../lettuce/v5_0/LettuceSingletons.java | 2 +- .../PeerServiceAttributesExtractor.java | 3 +- .../PeerServiceAttributesExtractorTest.java | 2 +- 17 files changed, 59 insertions(+), 17 deletions(-) create mode 100644 instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JavaAgentJdbcSingletons.java rename {instrumentation-api/src/main/java/io/opentelemetry => javaagent-api/src/main/java/io/opentelemetry/javaagent}/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java (95%) rename {instrumentation-api/src/test/java/io/opentelemetry => javaagent-api/src/test/java/io/opentelemetry/javaagent}/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java (98%) diff --git a/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java b/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java index da0270f07e38..7594393cd72f 100644 --- a/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java +++ b/instrumentation/apache-httpclient/apache-httpclient-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v2_0/ApacheHttpClientSingletons.java @@ -7,12 +7,12 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.apache.commons.httpclient.HttpMethod; public final class ApacheHttpClientSingletons { diff --git a/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java b/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java index 491416fcdfc1..b4a014e70822 100644 --- a/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java +++ b/instrumentation/apache-httpclient/apache-httpclient-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v4_0/ApacheHttpClientSingletons.java @@ -7,12 +7,12 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; diff --git a/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java b/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java index 7961e3f87f49..53fe88bfa6d2 100644 --- a/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java +++ b/instrumentation/apache-httpclient/apache-httpclient-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/apachehttpclient/v5_0/ApacheHttpClientSingletons.java @@ -7,12 +7,12 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.HttpResponse; diff --git a/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java b/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java index 8bb0397f4d60..c83960cad4d9 100644 --- a/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java +++ b/instrumentation/armeria-1.3/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/armeria/v1_3/ArmeriaSingletons.java @@ -10,9 +10,9 @@ import com.linecorp.armeria.common.logging.RequestLog; import com.linecorp.armeria.server.HttpService; import io.opentelemetry.api.GlobalOpenTelemetry; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.armeria.v1_3.ArmeriaTracing; import io.opentelemetry.instrumentation.armeria.v1_3.internal.ArmeriaNetAttributesExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import java.util.function.Function; // Holds singleton references to decorators to match against during suppression. diff --git a/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java b/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java index 2e8918a0dfbc..29c62ecacafd 100644 --- a/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java +++ b/instrumentation/async-http-client/async-http-client-2.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/asynchttpclient/v2_0/AsyncHttpClientSingletons.java @@ -7,12 +7,12 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanStatusExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.http.HttpSpanStatusExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import org.asynchttpclient.Request; import org.asynchttpclient.Response; diff --git a/instrumentation/grpc-1.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/grpc/v1_6/GrpcSingletons.java b/instrumentation/grpc-1.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/grpc/v1_6/GrpcSingletons.java index 1ed18f48a5ed..fc58694f08ff 100644 --- a/instrumentation/grpc-1.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/grpc/v1_6/GrpcSingletons.java +++ b/instrumentation/grpc-1.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/grpc/v1_6/GrpcSingletons.java @@ -11,11 +11,11 @@ import io.grpc.Status; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.config.Config; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.grpc.v1_6.GrpcRequest; import io.opentelemetry.instrumentation.grpc.v1_6.GrpcTracing; import io.opentelemetry.instrumentation.grpc.v1_6.internal.ContextStorageBridge; import io.opentelemetry.instrumentation.grpc.v1_6.internal.GrpcNetAttributesExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; // Holds singleton references. public final class GrpcSingletons { diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JavaAgentJdbcSingletons.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JavaAgentJdbcSingletons.java new file mode 100644 index 000000000000..6becc16ae9bd --- /dev/null +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JavaAgentJdbcSingletons.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.javaagent.instrumentation.jdbc; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; +import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; +import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; +import io.opentelemetry.instrumentation.jdbc.internal.DbRequest; +import io.opentelemetry.instrumentation.jdbc.internal.JdbcAttributesExtractor; +import io.opentelemetry.instrumentation.jdbc.internal.JdbcNetAttributesExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; + +public final class JavaAgentJdbcSingletons { + private static final String INSTRUMENTATION_NAME = "io.opentelemetry.jdbc"; + + private static final Instrumenter INSTRUMENTER; + + static { + DbAttributesExtractor dbAttributesExtractor = new JdbcAttributesExtractor(); + SpanNameExtractor spanName = DbSpanNameExtractor.create(dbAttributesExtractor); + JdbcNetAttributesExtractor netAttributesExtractor = new JdbcNetAttributesExtractor(); + + INSTRUMENTER = + Instrumenter.newBuilder( + GlobalOpenTelemetry.get(), INSTRUMENTATION_NAME, spanName) + .addAttributesExtractor(dbAttributesExtractor) + .addAttributesExtractor(netAttributesExtractor) + .addAttributesExtractor(PeerServiceAttributesExtractor.create(netAttributesExtractor)) + .newInstrumenter(SpanKindExtractor.alwaysClient()); + } + + public static Instrumenter instrumenter() { + return INSTRUMENTER; + } + + private JavaAgentJdbcSingletons() {} +} diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java index 85d025e76273..3ac5eaa33c02 100644 --- a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java @@ -5,10 +5,10 @@ package io.opentelemetry.javaagent.instrumentation.jdbc; -import static io.opentelemetry.instrumentation.jdbc.internal.JdbcSingletons.instrumenter; import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.implementsInterface; import static io.opentelemetry.javaagent.extension.matcher.ClassLoaderMatcher.hasClassesNamed; import static io.opentelemetry.javaagent.instrumentation.api.Java8BytecodeBridge.currentContext; +import static io.opentelemetry.javaagent.instrumentation.jdbc.JavaAgentJdbcSingletons.instrumenter; import static net.bytebuddy.matcher.ElementMatchers.isPublic; import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith; import static net.bytebuddy.matcher.ElementMatchers.named; diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java index 8ebb68b1bf3c..38831e01bfdc 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcAttributesExtractor.java @@ -10,7 +10,7 @@ import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; import org.checkerframework.checker.nullness.qual.Nullable; -final class JdbcAttributesExtractor extends SqlAttributesExtractor { +public final class JdbcAttributesExtractor extends SqlAttributesExtractor { @Nullable @Override protected String system(DbRequest request) { diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java index 72e9f19c1af8..c0b9bd67525c 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcNetAttributesExtractor.java @@ -8,7 +8,7 @@ import io.opentelemetry.instrumentation.api.instrumenter.net.NetAttributesExtractor; import org.checkerframework.checker.nullness.qual.Nullable; -final class JdbcNetAttributesExtractor extends NetAttributesExtractor { +public final class JdbcNetAttributesExtractor extends NetAttributesExtractor { @Nullable @Override diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java index 986053769628..8a16ae4b2c32 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/internal/JdbcSingletons.java @@ -7,7 +7,6 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; @@ -28,7 +27,6 @@ public final class JdbcSingletons { GlobalOpenTelemetry.get(), INSTRUMENTATION_NAME, spanName) .addAttributesExtractor(dbAttributesExtractor) .addAttributesExtractor(netAttributesExtractor) - .addAttributesExtractor(PeerServiceAttributesExtractor.create(netAttributesExtractor)) .newInstrumenter(SpanKindExtractor.alwaysClient()); } diff --git a/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java b/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java index 3549a92652ec..f31dcba7cbca 100644 --- a/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java +++ b/instrumentation/jedis/jedis-1.4/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v1_4/JedisSingletons.java @@ -7,11 +7,11 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class JedisSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-1.4"; diff --git a/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java b/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java index 8bb99035d4a5..b0b75559ee1f 100644 --- a/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java +++ b/instrumentation/jedis/jedis-3.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jedis/v3_0/JedisSingletons.java @@ -7,11 +7,11 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class JedisSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-3.0"; diff --git a/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java b/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java index d2a0990036f8..825d45c6c387 100644 --- a/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java +++ b/instrumentation/lettuce/lettuce-4.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v4_0/LettuceSingletons.java @@ -9,11 +9,11 @@ import com.lambdaworks.redis.protocol.RedisCommand; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class LettuceSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-1.4"; diff --git a/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java b/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java index 81a2430f1a6f..016b71894e96 100644 --- a/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java +++ b/instrumentation/lettuce/lettuce-5.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_0/LettuceSingletons.java @@ -9,11 +9,11 @@ import io.lettuce.core.protocol.RedisCommand; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; -import io.opentelemetry.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanKindExtractor; import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbAttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.db.DbSpanNameExtractor; +import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; public final class LettuceSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.javaagent.jedis-5.0"; diff --git a/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java b/javaagent-api/src/main/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java similarity index 95% rename from instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java rename to javaagent-api/src/main/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java index 82e104b182d8..adbdad14ffdd 100644 --- a/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java +++ b/javaagent-api/src/main/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractor.java @@ -3,10 +3,11 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.instrumentation.api.instrumenter; +package io.opentelemetry.javaagent.instrumentation.api.instrumenter; import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.instrumentation.api.config.Config; +import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor; import io.opentelemetry.instrumentation.api.instrumenter.net.NetAttributesExtractor; import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; import java.util.Map; diff --git a/instrumentation-api/src/test/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java b/javaagent-api/src/test/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java similarity index 98% rename from instrumentation-api/src/test/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java rename to javaagent-api/src/test/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java index ecb452bb32db..300f9a7e28cd 100644 --- a/instrumentation-api/src/test/java/io/opentelemetry/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java +++ b/javaagent-api/src/test/java/io/opentelemetry/javaagent/instrumentation/api/instrumenter/PeerServiceAttributesExtractorTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.instrumentation.api.instrumenter; +package io.opentelemetry.javaagent.instrumentation.api.instrumenter; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static java.util.Collections.singletonMap; From d0266d3ffa9a3d44c69db792ff19985090a349a5 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 26 Jun 2021 04:38:54 +0800 Subject: [PATCH 58/69] Rename JavaAgentJdbcSingletons to JdbcSingletons. --- .../{JavaAgentJdbcSingletons.java => JdbcSingletons.java} | 4 ++-- .../jdbc/PreparedStatementInstrumentation.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/{JavaAgentJdbcSingletons.java => JdbcSingletons.java} (95%) diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JavaAgentJdbcSingletons.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java similarity index 95% rename from instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JavaAgentJdbcSingletons.java rename to instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java index 6becc16ae9bd..6ce589beb462 100644 --- a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JavaAgentJdbcSingletons.java +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/JdbcSingletons.java @@ -16,7 +16,7 @@ import io.opentelemetry.instrumentation.jdbc.internal.JdbcNetAttributesExtractor; import io.opentelemetry.javaagent.instrumentation.api.instrumenter.PeerServiceAttributesExtractor; -public final class JavaAgentJdbcSingletons { +public final class JdbcSingletons { private static final String INSTRUMENTATION_NAME = "io.opentelemetry.jdbc"; private static final Instrumenter INSTRUMENTER; @@ -39,5 +39,5 @@ public static Instrumenter instrumenter() { return INSTRUMENTER; } - private JavaAgentJdbcSingletons() {} + private JdbcSingletons() {} } diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java index 3ac5eaa33c02..a198ecc5cb8a 100644 --- a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/PreparedStatementInstrumentation.java @@ -8,7 +8,7 @@ import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.implementsInterface; import static io.opentelemetry.javaagent.extension.matcher.ClassLoaderMatcher.hasClassesNamed; import static io.opentelemetry.javaagent.instrumentation.api.Java8BytecodeBridge.currentContext; -import static io.opentelemetry.javaagent.instrumentation.jdbc.JavaAgentJdbcSingletons.instrumenter; +import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; import static net.bytebuddy.matcher.ElementMatchers.isPublic; import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith; import static net.bytebuddy.matcher.ElementMatchers.named; From 7e86a5a36cbc9ffcf1e5ce35a5980a0ea5e6f47b Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sat, 26 Jun 2021 04:41:02 +0800 Subject: [PATCH 59/69] Fixed JdbcSingletons import. --- .../instrumentation/jdbc/StatementInstrumentation.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/StatementInstrumentation.java b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/StatementInstrumentation.java index 1d665596c48f..3cbbcf857ddc 100644 --- a/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/StatementInstrumentation.java +++ b/instrumentation/jdbc/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/jdbc/StatementInstrumentation.java @@ -5,10 +5,10 @@ package io.opentelemetry.javaagent.instrumentation.jdbc; -import static io.opentelemetry.instrumentation.jdbc.internal.JdbcSingletons.instrumenter; import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.implementsInterface; import static io.opentelemetry.javaagent.extension.matcher.ClassLoaderMatcher.hasClassesNamed; import static io.opentelemetry.javaagent.instrumentation.api.Java8BytecodeBridge.currentContext; +import static io.opentelemetry.javaagent.instrumentation.jdbc.JdbcSingletons.instrumenter; import static net.bytebuddy.matcher.ElementMatchers.isPublic; import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith; import static net.bytebuddy.matcher.ElementMatchers.named; From 1720575a0bc3203c06a41a73ff641f89850918cf Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Sun, 27 Jun 2021 13:07:37 +0800 Subject: [PATCH 60/69] Cleanup. --- .../instrumentation/jdbc/OpenTelemetryConnectionTest.groovy | 3 --- 1 file changed, 3 deletions(-) diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnectionTest.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnectionTest.groovy index 3e155360135e..ab9c21414d29 100644 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnectionTest.groovy +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryConnectionTest.groovy @@ -41,7 +41,6 @@ class OpenTelemetryConnectionTest extends InstrumentationSpecification implement "$SemanticAttributes.DB_CONNECTION_STRING.key" dbInfo.shortUrl "$SemanticAttributes.NET_PEER_NAME.key" dbInfo.host "$SemanticAttributes.NET_PEER_PORT.key" dbInfo.port - "$SemanticAttributes.NET_PEER_IP.key" null "$SemanticAttributes.DB_STATEMENT.key" query "$SemanticAttributes.DB_OPERATION.key" "SELECT" "$SemanticAttributes.DB_SQL_TABLE.key" "users" @@ -90,7 +89,6 @@ class OpenTelemetryConnectionTest extends InstrumentationSpecification implement "$SemanticAttributes.DB_CONNECTION_STRING.key" dbInfo.shortUrl "$SemanticAttributes.NET_PEER_NAME.key" dbInfo.host "$SemanticAttributes.NET_PEER_PORT.key" dbInfo.port - "$SemanticAttributes.NET_PEER_IP.key" null "$SemanticAttributes.DB_STATEMENT.key" query "$SemanticAttributes.DB_OPERATION.key" "SELECT" "$SemanticAttributes.DB_SQL_TABLE.key" "users" @@ -142,7 +140,6 @@ class OpenTelemetryConnectionTest extends InstrumentationSpecification implement "$SemanticAttributes.DB_CONNECTION_STRING.key" dbInfo.shortUrl "$SemanticAttributes.NET_PEER_NAME.key" dbInfo.host "$SemanticAttributes.NET_PEER_PORT.key" dbInfo.port - "$SemanticAttributes.NET_PEER_IP.key" null "$SemanticAttributes.DB_STATEMENT.key" query "$SemanticAttributes.DB_OPERATION.key" "SELECT" "$SemanticAttributes.DB_SQL_TABLE.key" "users" From d178c34b3ec911116d62d46c61a546a4fc7be0ae Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 28 Jun 2021 03:45:12 +0800 Subject: [PATCH 61/69] Codenarc fixes. --- .../opentelemetry/instrumentation/jdbc/TestConnection.groovy | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy index 724eccd3e49d..abee3ad6b9e9 100644 --- a/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy +++ b/instrumentation/jdbc/testing/src/main/groovy/io/opentelemetry/instrumentation/jdbc/TestConnection.groovy @@ -137,9 +137,8 @@ class TestConnection implements Connection { DatabaseMetaData getMetaData() throws SQLException { if (url) { return new TestDatabaseMetaData(url) - } else { - return new TestDatabaseMetaData() } + return new TestDatabaseMetaData() } @Override From 09851dc2e4de490d0a21fc163fe46e789c42bae9 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 28 Jun 2021 13:24:57 +0800 Subject: [PATCH 62/69] Update instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java Co-authored-by: Anuraag Agrawal --- .../opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 5d902428a74e..4fa64ebfca6b 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -198,7 +198,7 @@ public boolean acceptsURL(String url) { @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { - if (url == null || url.trim().length() == 0) { + if (url == null || url.trim().isEmpty()) { throw new IllegalArgumentException("url is required"); } From 3f894637383fff2828d301fe0bd8e568dc16a39e Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 28 Jun 2021 13:25:10 +0800 Subject: [PATCH 63/69] Update instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java Co-authored-by: Anuraag Agrawal --- .../opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 4fa64ebfca6b..e6ba59b6586d 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -165,7 +165,7 @@ private static String extractRealUrl(String url) { @Nullable @Override public Connection connect(String url, Properties info) throws SQLException { - if (url == null || url.trim().length() == 0) { + if (url == null || url.trim().isEmpty()) { throw new IllegalArgumentException("url is required"); } From fc5299d115ef040381472867de90ffd86ceeaadd Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 28 Jun 2021 13:37:22 +0800 Subject: [PATCH 64/69] Parse InstrumentationVersion.VERSION. --- .../jdbc/OpenTelemetryDriver.java | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index e6ba59b6586d..af054de546c1 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -20,6 +20,7 @@ package io.opentelemetry.instrumentation.jdbc; +import io.opentelemetry.instrumentation.api.InstrumentationVersion; import io.opentelemetry.instrumentation.jdbc.internal.DbInfo; import io.opentelemetry.instrumentation.jdbc.internal.JdbcConnectionUrlParser; import io.opentelemetry.instrumentation.jdbc.internal.OpenTelemetryConnection; @@ -162,6 +163,22 @@ private static String extractRealUrl(String url) { : url; } + private static int[] parseInstrumentationVersion() { + String[] parts = InstrumentationVersion.VERSION.split("\\."); + if (parts.length >= 2) { + try { + int majorVersion = Integer.parseInt(parts[0]); + int minorVersion = Integer.parseInt(parts[1]); + + return new int[] {majorVersion, minorVersion}; + } catch (NumberFormatException ignored) { + // ignore incorrect version + } + } + // return 0.0 as a fallback + return new int[] {0, 0}; + } + @Nullable @Override public Connection connect(String url, Properties info) throws SQLException { @@ -209,12 +226,12 @@ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws @Override public int getMajorVersion() { - return 1; + return parseInstrumentationVersion()[0]; } @Override public int getMinorVersion() { - return 4; + return parseInstrumentationVersion()[1]; } /** Returns {@literal false} because not all delegated drivers are JDBC compliant. */ From de70de16637aef7cbd91d51d63c71300421f448e Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Mon, 28 Jun 2021 13:43:52 +0800 Subject: [PATCH 65/69] Store major and minor version in private static fields. --- .../instrumentation/jdbc/OpenTelemetryDriver.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index af054de546c1..7fc4b91a0a7a 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -45,6 +45,9 @@ public final class OpenTelemetryDriver implements Driver { // visible for testing static final OpenTelemetryDriver INSTANCE = new OpenTelemetryDriver(); + private static final int MAJOR_VERSION; + private static final int MINOR_VERSION; + private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; private static final AtomicBoolean REGISTERED = new AtomicBoolean(); @@ -52,6 +55,10 @@ public final class OpenTelemetryDriver implements Driver { static { try { + int[] version = parseInstrumentationVersion(); + MAJOR_VERSION = version[0]; + MINOR_VERSION = version[1]; + register(); } catch (SQLException e) { throw new ExceptionInInitializerError(e); @@ -226,12 +233,12 @@ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws @Override public int getMajorVersion() { - return parseInstrumentationVersion()[0]; + return MAJOR_VERSION; } @Override public int getMinorVersion() { - return parseInstrumentationVersion()[1]; + return MINOR_VERSION; } /** Returns {@literal false} because not all delegated drivers are JDBC compliant. */ From 286f48ddcfeb8e5581c860f62822be915b854bd6 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Thu, 1 Jul 2021 14:57:43 +0800 Subject: [PATCH 66/69] Make the datasource way a preferred way. --- instrumentation/jdbc/library/README.md | 70 +++++++++++++------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/instrumentation/jdbc/library/README.md b/instrumentation/jdbc/library/README.md index e7287bdf8e3d..7fc922d64365 100644 --- a/instrumentation/jdbc/library/README.md +++ b/instrumentation/jdbc/library/README.md @@ -30,11 +30,41 @@ implementation("io.opentelemetry.instrumentation:opentelemetry-jdbc:OPENTELEMETR ##### Usage -There are three possible ways to activate the OpenTelemetry JDBC instrumentation. The first one requires -to change the connection URL and switch to use a special OpenTelemetry driver. The second method -only requires minimal changes in your application without needing to change the connection URL, but -it's necessary to remove the explicit driver selection. And the third way is more preferable for DI frameworks -which uses connection pools, as it wraps a `DataSource` with a special OpenTelemetry wrapper. +There are three possible ways to activate the OpenTelemetry JDBC instrumentation. The first way is more preferable +for DI frameworks which uses connection pools, as it wraps a `DataSource` with a special OpenTelemetry wrapper. The +second one requires to change the connection URL and switch to use a special OpenTelemetry driver. And the third method +only requires minimal changes in your application without needing to change the connection URL, but it's necessary to +remove the explicit driver selection. + +### Datasource way + +If your application uses a DataSource, simply wrap your current DataSource object with +`OpenTelemetryDataSource`. `OpenTelemetryDataSource` has a constructor method that accepts the +`DataSource` to wrap. This is by far the simplest method especially if you use a dependency +injection (DI) frameworks such as [Spring Framework](https://spring.io/projects/spring-framework), +[Micronaut](https://micronaut.io), [Quarkus](https://quarkus.io), or +[Guice](https://github.com/google/guice). + +```java +import org.apache.commons.dbcp2.BasicDataSource; +import org.springframework.context.annotation.Configuration; +import io.opentelemetry.instrumentation.jdbc.datasource.OpenTelemetryDataSource; + +@Configuration +public class DataSourceConfig { + + @Bean + public DataSource dataSource() { + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl("jdbc:postgresql://127.0.0.1:5432/example"); + dataSource.setUsername("postgres"); + dataSource.setPassword("root"); + return new OpenTelemetryDataSource(dataSource); + } + +} +``` ### Driver: non-interceptor mode. @@ -88,33 +118,3 @@ Calling `OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver()` method along wi `setInterceptorMode(true)` will fix that problem. Please note drivers like Oracle JDBC may fail since they're destroyed forever after deregistration. - -### Datasource way - -If your application uses a DataSource, simply wrap your current DataSource object with -`OpenTelemetryDataSource`. `OpenTelemetryDataSource` has a constructor method that accepts the -`DataSource` to wrap. This is by far the simplest method especially if you use a dependency -injection (DI) frameworks such as [Spring Framework](https://spring.io/projects/spring-framework), -[Micronaut](https://micronaut.io), [Quarkus](https://quarkus.io), or -[Guice](https://github.com/google/guice). - -```java -import org.apache.commons.dbcp2.BasicDataSource; -import org.springframework.context.annotation.Configuration; -import io.opentelemetry.instrumentation.jdbc.datasource.OpenTelemetryDataSource; - -@Configuration -public class DataSourceConfig { - - @Bean - public DataSource dataSource() { - BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - dataSource.setUrl("jdbc:postgresql://127.0.0.1:5432/example"); - dataSource.setUsername("postgres"); - dataSource.setPassword("root"); - return new OpenTelemetryDataSource(dataSource); - } - -} -``` From 7e7ce1fe7be8612778691607da20702e0415a5e6 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Thu, 1 Jul 2021 15:22:12 +0800 Subject: [PATCH 67/69] Removed interceptor mode. --- instrumentation/jdbc/library/README.md | 62 +++------------- .../jdbc/OpenTelemetryDriver.java | 58 +-------------- .../jdbc/OpenTelemetryDriverTest.groovy | 71 +++---------------- 3 files changed, 24 insertions(+), 167 deletions(-) diff --git a/instrumentation/jdbc/library/README.md b/instrumentation/jdbc/library/README.md index 7fc922d64365..e4f5a56a06af 100644 --- a/instrumentation/jdbc/library/README.md +++ b/instrumentation/jdbc/library/README.md @@ -30,20 +30,17 @@ implementation("io.opentelemetry.instrumentation:opentelemetry-jdbc:OPENTELEMETR ##### Usage -There are three possible ways to activate the OpenTelemetry JDBC instrumentation. The first way is more preferable -for DI frameworks which uses connection pools, as it wraps a `DataSource` with a special OpenTelemetry wrapper. The -second one requires to change the connection URL and switch to use a special OpenTelemetry driver. And the third method -only requires minimal changes in your application without needing to change the connection URL, but it's necessary to -remove the explicit driver selection. +There are three possible ways to activate the OpenTelemetry JDBC instrumentation. The first way is more preferable for +DI frameworks which uses connection pools, as it wraps a `DataSource` with a special OpenTelemetry wrapper. The second +one requires to change the connection URL and switch to use a special OpenTelemetry driver. ### Datasource way -If your application uses a DataSource, simply wrap your current DataSource object with -`OpenTelemetryDataSource`. `OpenTelemetryDataSource` has a constructor method that accepts the -`DataSource` to wrap. This is by far the simplest method especially if you use a dependency -injection (DI) frameworks such as [Spring Framework](https://spring.io/projects/spring-framework), -[Micronaut](https://micronaut.io), [Quarkus](https://quarkus.io), or -[Guice](https://github.com/google/guice). +If your application uses a DataSource, simply wrap your current DataSource object with `OpenTelemetryDataSource`. +`OpenTelemetryDataSource` has a constructor method that accepts the `DataSource` to wrap. This is by far the simplest +method especially if you use a dependency injection (DI) frameworks such as +[Spring Framework](https://spring.io/projects/spring-framework), [Micronaut](https://micronaut.io), +[Quarkus](https://quarkus.io), or [Guice](https://github.com/google/guice). ```java import org.apache.commons.dbcp2.BasicDataSource; @@ -66,7 +63,7 @@ public class DataSourceConfig { } ``` -### Driver: non-interceptor mode. +### Driver way 1. Activate tracing for JDBC connections by setting `jdbc:otel:` prefix to the JDBC URL: @@ -74,47 +71,8 @@ public class DataSourceConfig { jdbc:otel:h2:mem:test ``` -2. Set the driver class to `io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver` and - initialize the driver with: +2. Set the driver class to `io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver` and initialize the driver with: ```java Class.forName("io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver"); ``` - -### Driver: interceptor mode. - -This mode can be useful for activating tracing for all JDBC connections without modifying the URL. - -In the "interceptor mode", the `OpenTelemetryDriver` will intercept calls to -`DriverManager.getConnection(url,...)` for all URLs. The `OpenTelemetryDriver` will return instrumented -connections that will delegate calls to the actual DB driver. Please note that the `OpenTelemetryDriver` must be -registered before the underlying driver - it's recommended to turn on the "interceptor mode" as early as possible. - -For most applications: - -```java -public static void main(String[] args) { - io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver.setInterceptorMode(true); - - // ... -} - -``` - -For web applications based on Servlet API: - -```java -public void contextInitialized(ServletContextEvent event) { - io.opentelemetry.instrumentation.jdbc.OpenTelemetryDriver.setInterceptorMode(true); - - // ... -} -``` - -Sometimes it's also required to register the OpenTelemetry driver as a first driver in the -DriverManager list, otherwise another driver can be selected at the time of initialization. - -Calling `OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver()` method along with -`setInterceptorMode(true)` will fix that problem. - -Please note drivers like Oracle JDBC may fail since they're destroyed forever after deregistration. diff --git a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java index 7fc4b91a0a7a..ac492c860213 100644 --- a/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java +++ b/instrumentation/jdbc/library/src/main/java/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriver.java @@ -30,10 +30,7 @@ import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; -import java.util.ArrayList; import java.util.Collections; -import java.util.Enumeration; -import java.util.List; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; @@ -48,11 +45,9 @@ public final class OpenTelemetryDriver implements Driver { private static final int MAJOR_VERSION; private static final int MINOR_VERSION; - private static final String INTERCEPTOR_MODE_URL_PREFIX = "jdbc:otel:"; + private static final String URL_PREFIX = "jdbc:otel:"; private static final AtomicBoolean REGISTERED = new AtomicBoolean(); - private static volatile boolean interceptorMode = false; - static { try { int[] version = parseInstrumentationVersion(); @@ -65,48 +60,6 @@ public final class OpenTelemetryDriver implements Driver { } } - /** - * Ensure {@code TracingDriver} be the first driver of {@link DriverManager} to make sure - * "interceptor mode" works. WARNING: Driver like Oracle JDBC may fail since it's destroyed - * forever after deregistration. - */ - public static synchronized void ensureRegisteredAsTheFirstDriver() { - try { - Enumeration enumeration = DriverManager.getDrivers(); - List drivers = new ArrayList<>(); - for (int i = 0; enumeration.hasMoreElements(); ++i) { - Driver driver = enumeration.nextElement(); - if (i == 0 && driver == INSTANCE) { - // the first driver is OTEL driver, skip all this verification - return; - } - if (!(driver instanceof OpenTelemetryDriver)) { - drivers.add(driver); - } - DriverManager.deregisterDriver(driver); - } - - // register OTEL driver first - register(); - - // register other drivers - for (Driver driver : drivers) { - DriverManager.registerDriver(driver); - } - } catch (SQLException e) { - throw new ExceptionInInitializerError(e); - } - } - - /** - * Turns "interceptor mode" on or off. - * - * @param interceptorMode The {@code interceptorMode} value. - */ - public static void setInterceptorMode(final boolean interceptorMode) { - OpenTelemetryDriver.interceptorMode = interceptorMode; - } - /** * Register the driver against {@link DriverManager}. This is done automatically when the class is * loaded. Dropping the driver from DriverManager's list is possible using {@link #deregister()} @@ -165,9 +118,7 @@ private static Driver findDriver(String realUrl) { * @return the parsed URL */ private static String extractRealUrl(String url) { - return url.startsWith(INTERCEPTOR_MODE_URL_PREFIX) - ? url.replace(INTERCEPTOR_MODE_URL_PREFIX, "jdbc:") - : url; + return url.startsWith(URL_PREFIX) ? url.replace(URL_PREFIX, "jdbc:") : url; } private static int[] parseInstrumentationVersion() { @@ -214,10 +165,7 @@ public boolean acceptsURL(String url) { if (url == null) { return false; } - if (url.startsWith(INTERCEPTOR_MODE_URL_PREFIX)) { - return true; - } - return interceptorMode && url.startsWith("jdbc:") && url.length() > 5; + return url.startsWith(URL_PREFIX) && url.length() > URL_PREFIX.length(); } @Override diff --git a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy index f7d6deafd380..e4d43f826b66 100644 --- a/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy +++ b/instrumentation/jdbc/library/src/test/groovy/io/opentelemetry/instrumentation/jdbc/OpenTelemetryDriverTest.groovy @@ -14,7 +14,6 @@ import java.sql.SQLFeatureNotSupportedException class OpenTelemetryDriverTest extends Specification { def cleanup() { - OpenTelemetryDriver.setInterceptorMode(false) if (!OpenTelemetryDriver.registered) { OpenTelemetryDriver.register() } @@ -36,6 +35,7 @@ class OpenTelemetryDriverTest extends Specification { def "verify standard properties"() { expect: !OpenTelemetryDriver.INSTANCE.jdbcCompliant() + // replace with actual version of instrumentation library OpenTelemetryDriver.INSTANCE.majorVersion == 1 OpenTelemetryDriver.INSTANCE.minorVersion == 4 } @@ -49,50 +49,20 @@ class OpenTelemetryDriverTest extends Specification { e.message == "Feature not supported" } - def "verify driver registered as a first driver"() { - given: - DriverManager.drivers.each { driver -> - if (driver instanceof OpenTelemetryDriver) { - OpenTelemetryDriver.deregister() - } else { - DriverManager.deregisterDriver(driver) - } - } - DriverManager.registerDriver(new TestDriver()) - DriverManager.registerDriver(new AnotherTestDriver()) - OpenTelemetryDriver.ensureRegisteredAsTheFirstDriver() - - when: - def firstDriver = DriverManager.drivers.nextElement() - - then: - OpenTelemetryDriver.registered - firstDriver != null - firstDriver instanceof OpenTelemetryDriver - } - def "verify accepted urls"() { expect: def driver = OpenTelemetryDriver.INSTANCE - OpenTelemetryDriver.setInterceptorMode(interceptorMode) driver.acceptsURL(url) == expected where: - url | interceptorMode | expected - null | false | false - "" | false | false - "jdbc:" | false | false - "jdbc::" | false | false - "bogus:string" | false | false - "jdbc:postgresql://127.0.0.1:5432/dbname" | false | false - "jdbc:otel:postgresql://127.0.0.1:5432/dbname" | false | true - null | true | false - "" | true | false - "jdbc:" | true | false - "jdbc::" | true | true - "bogus:string" | true | false - "jdbc:postgresql://127.0.0.1:5432/dbname" | true | true - "jdbc:otel:postgresql://127.0.0.1:5432/dbname" | true | true + url | expected + null | false + "" | false + "jdbc:" | false + "jdbc::" | false + "bogus:string" | false + "jdbc:postgresql://127.0.0.1:5432/dbname" | false + "jdbc:otel:postgresql://127.0.0.1:5432/dbname" | true } def "verify deregister"() { @@ -148,29 +118,10 @@ class OpenTelemetryDriverTest extends Specification { connection == null } - def "verify connection with disabled interceptor mode"() { - when: - OpenTelemetryDriver.interceptorMode = false - def connection = OpenTelemetryDriver.INSTANCE.connect("jdbc:test:", null) - - then: - connection == null - - when: - registerTestDriver() - OpenTelemetryDriver.interceptorMode = false - connection = OpenTelemetryDriver.INSTANCE.connect("jdbc:otel:test:", null) - - then: - connection != null - connection instanceof OpenTelemetryConnection - } - - def "verify connection with enabled interceptor mode"() { + def "verify connection with accepted url"() { when: registerTestDriver() - OpenTelemetryDriver.interceptorMode = true - def connection = OpenTelemetryDriver.INSTANCE.connect("jdbc:test:", null) + def connection = OpenTelemetryDriver.INSTANCE.connect("jdbc:otel:test:", null) then: connection != null From 4473948b5cb30762748fa1260a1bdef4235540db Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Thu, 1 Jul 2021 16:01:30 +0800 Subject: [PATCH 68/69] Rename build.gradle -> build.gradle.kts. --- instrumentation/jdbc/library/{build.gradle => build.gradle.kts} | 0 instrumentation/jdbc/testing/{build.gradle => build.gradle.kts} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename instrumentation/jdbc/library/{build.gradle => build.gradle.kts} (100%) rename instrumentation/jdbc/testing/{build.gradle => build.gradle.kts} (100%) diff --git a/instrumentation/jdbc/library/build.gradle b/instrumentation/jdbc/library/build.gradle.kts similarity index 100% rename from instrumentation/jdbc/library/build.gradle rename to instrumentation/jdbc/library/build.gradle.kts diff --git a/instrumentation/jdbc/testing/build.gradle b/instrumentation/jdbc/testing/build.gradle.kts similarity index 100% rename from instrumentation/jdbc/testing/build.gradle rename to instrumentation/jdbc/testing/build.gradle.kts From df12ddc791dcd38f56b32b1921c9bd73a6bb20b7 Mon Sep 17 00:00:00 2001 From: Alexey Zhokhov Date: Thu, 1 Jul 2021 16:05:47 +0800 Subject: [PATCH 69/69] Switch to Gradle Kotlin DSL. --- instrumentation/jdbc/library/build.gradle.kts | 10 +++++----- instrumentation/jdbc/testing/build.gradle.kts | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/instrumentation/jdbc/library/build.gradle.kts b/instrumentation/jdbc/library/build.gradle.kts index 520c2d7e6683..e3689fbbfd01 100644 --- a/instrumentation/jdbc/library/build.gradle.kts +++ b/instrumentation/jdbc/library/build.gradle.kts @@ -8,12 +8,12 @@ plugins { } dependencies { - implementation project(':instrumentation-api') + implementation(project(":instrumentation-api")) - compileOnly "com.google.auto.value:auto-value-annotations" - annotationProcessor "com.google.auto.value:auto-value" + compileOnly("com.google.auto.value:auto-value-annotations") + annotationProcessor("com.google.auto.value:auto-value") - implementation "org.slf4j:slf4j-api" + implementation("org.slf4j:slf4j-api") - testImplementation project(':instrumentation:jdbc:testing') + testImplementation(project(":instrumentation:jdbc:testing")) } diff --git a/instrumentation/jdbc/testing/build.gradle.kts b/instrumentation/jdbc/testing/build.gradle.kts index e2e8e71be169..b1a174dfe0d3 100644 --- a/instrumentation/jdbc/testing/build.gradle.kts +++ b/instrumentation/jdbc/testing/build.gradle.kts @@ -8,5 +8,5 @@ plugins { } dependencies { - implementation "org.codehaus.groovy:groovy-all" + implementation("org.codehaus.groovy:groovy-all") }