未验证 提交 382264fd 编写于 作者: ShardingSphere's avatar ShardingSphere 提交者: GitHub

Merge pull request #674 from oracle219/dev

Move sharding-jdbc-opentracing to sharding-jdbc project
......@@ -13,6 +13,7 @@
<module>sharding-jdbc-transaction-parent</module>
<module>sharding-jdbc-orchestration</module>
<module>sharding-jdbc-orchestration-spring</module>
<module>sharding-opentracing</module>
<module>sharding-proxy</module>
<module>sharding-sql-test</module>
</modules>
......@@ -50,6 +51,8 @@
<protobuf.version>3.4.0</protobuf.version>
<guava-retrying.version>2.0.0</guava-retrying.version>
<quartz.version>2.3.0</quartz.version>
<opentracing.version>0.30.0</opentracing.version>
<powermock.version>1.7.1</powermock.version>
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<maven-assembly-plugin.version>3.1.0</maven-assembly-plugin.version>
......@@ -74,6 +77,7 @@
<maven-gpg-plugin.version>1.6</maven-gpg-plugin.version>
<protobuf-maven-plugin.version>0.5.0</protobuf-maven-plugin.version>
<os-maven-plugin.version>1.5.0.Final</os-maven-plugin.version>
<coveralls-maven-plugin.version>4.1.0</coveralls-maven-plugin.version>
<javadocExecutable>${java.home}/../bin/javadoc</javadocExecutable>
</properties>
......
language: java
jdk:
- oraclejdk8
before_script:
- echo "MAVEN_OPTS='-Xmx1024m -XX:MaxPermSize=256m'" > ~/.mavenrc
after_success:
- mvn clean cobertura:cobertura coveralls:report
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingjdbc</groupId>
<artifactId>sharding-jdbc</artifactId>
<version>2.1.0-SNAPSHOT</version>
</parent>
<artifactId>sharding-opentracing</artifactId>
<name>${project.artifactId}</name>
<properties>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>io.opentracing</groupId>
<artifactId>opentracing-util</artifactId>
<version>${opentracing.version}</version>
</dependency>
<dependency>
<groupId>io.shardingjdbc</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>io.opentracing</groupId>
<artifactId>opentracing-mock</artifactId>
<version>${opentracing.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<testSource>${java.version}</testSource>
<testTarget>${java.version}</testTarget>
</configuration>
<version>${maven-compiler-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven-resources-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>${maven-site-plugin.version}</version>
<configuration>
<locales>${project.build.locale}</locales>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>${lifecycle-mapping.version}</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<versionRange>[1.0.0,)</versionRange>
<goals>
<goal>enforce</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<versionRange>[1.0.0,)</versionRange>
<goals>
<goal>descriptor</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<version>${maven-plugin-plugin.version}</version>
<configuration>
<skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
</configuration>
<executions>
<execution>
<id>default-descriptor</id>
<phase>process-classes</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>${maven-source-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<aggregate>true</aggregate>
<charset>${project.build.sourceEncoding}</charset>
<encoding>${project.build.sourceEncoding}</encoding>
<docencoding>${project.build.sourceEncoding}</docencoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>${maven-enforcer-plugin.version}</version>
<executions>
<execution>
<id>enforce-banned-dependencies</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>${maven.version.range}</version>
</requireMavenVersion>
<requireJavaVersion>
<version>${java.version}</version>
</requireJavaVersion>
</rules>
<fail>true</fail>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>${cobertura-maven-plugin.version}</version>
<configuration>
<check>
<branchRate>85</branchRate>
<lineRate>85</lineRate>
<haltOnFailure>true</haltOnFailure>
<totalBranchRate>85</totalBranchRate>
<totalLineRate>85</totalLineRate>
<packageLineRate>85</packageLineRate>
<packageBranchRate>85</packageBranchRate>
</check>
<aggregate>true</aggregate>
<encoding>${project.build.sourceEncoding}</encoding>
<quiet>true</quiet>
<format>xml</format>
<instrumentation>
<ignoreTrivial>true</ignoreTrivial>
<excludes>
<exclude>io/shardingjdbc/**/*Test.class</exclude>
<exclude>io/shardingjdbc/**/Test*.class</exclude>
</excludes>
</instrumentation>
</configuration>
</plugin>
<plugin>
<groupId>org.eluder.coveralls</groupId>
<artifactId>coveralls-maven-plugin</artifactId>
<version>${coveralls-maven-plugin.version}</version>
</plugin>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>${maven-gpg-plugin.version}</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
-->
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>${maven-project-info-reports-plugin.version}</version>
<configuration>
<dependencyLocationsEnabled>false</dependencyLocationsEnabled>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<aggregate>true</aggregate>
<charset>${project.build.sourceEncoding}</charset>
<encoding>${project.build.sourceEncoding}</encoding>
<docencoding>${project.build.sourceEncoding}</docencoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>${maven-jxr-plugin.version}</version>
<reportSets>
<reportSet>
<id>aggregate</id>
<inherited>false</inherited>
<reports>
<report>aggregate</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>${findbugs-maven-plugin.version}</version>
<configuration>
<xmlOutput>true</xmlOutput>
<effort>Max</effort>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${maven-checkstyle-plugin.version}</version>
<configuration>
<configLocation>src/main/resources/dd_checks.xml</configLocation>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>${maven-pmd-plugin.version}</version>
<configuration>
<aggregate>true</aggregate>
<sourceEncoding>${project.build.sourceEncoding}</sourceEncoding>
<targetJdk>${java.version}</targetJdk>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jdepend-maven-plugin</artifactId>
<version>${jdepend-maven-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>taglist-maven-plugin</artifactId>
<version>${taglist-maven-plugin.version}</version>
<configuration>
<aggregate>true</aggregate>
</configuration>
</plugin>
</plugins>
</reporting>
<repositories>
<repository>
<id>alfresco-maven-repo</id>
<url>https://maven.alfresco.com/nexus/content/groups/public/</url>
</repository>
<repository>
<id>java-net</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>terracotta-releases</id>
<url>http://terracotta.org/download/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<url>http://shardingjdbc.io</url>
<description>RDB Sharding</description>
<licenses>
<license>
<name>Apache License 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<scm>
<connection>scm:https://github.com/shardingjdbc/sharding-jdbc-opentracing</connection>
<developerConnection>scm:https://github.com/shardingjdbc/sharding-jdbc-opentracing</developerConnection>
<url>https://github.com/shardingjdbc/sharding-jdbc-opentracing</url>
</scm>
<mailingLists>
<mailingList>
<name>Zhangliang</name>
<post>zhangliang@dangdang.com</post>
</mailingList>
</mailingLists>
<developers>
<developer>
<id>zhangliang</id>
<name>ZhangLiang</name>
<email>zhangliang@dangdang.com</email>
<timezone>8</timezone>
</developer>
</developers>
<distributionManagement>
<snapshotRepository>
<id>sonatype-nexus-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>sonatype-nexus-releases</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
</repository>
</distributionManagement>
</project>
\ No newline at end of file
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import io.opentracing.ActiveSpan;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.tag.Tags;
import io.shardingjdbc.core.exception.ShardingJdbcException;
import io.shardingjdbc.core.executor.event.AbstractSQLExecutionEvent;
import io.shardingjdbc.core.executor.event.DMLExecutionEvent;
import io.shardingjdbc.core.executor.event.DQLExecutionEvent;
import io.shardingjdbc.core.executor.event.OverallExecutionEvent;
import io.shardingjdbc.core.executor.threadlocal.ExecutorDataMap;
import java.util.HashMap;
import java.util.Map;
/**
* Listen to the event of sql execution.
*
* @author gaohongtao
* @author wangkai
*/
public final class ExecuteEventListener {
private static final String SNAPSHOT_DATA_KEY = "OPENTRACING_SNAPSHOT_DATA";
private final ThreadLocal<ActiveSpan> trunkContainer = new ThreadLocal<>();
private final ThreadLocal<Span> branchContainer = new ThreadLocal<>();
private final ThreadLocal<ActiveSpan> trunkInBranchContainer = new ThreadLocal<>();
/**
* listen overall sql execution event.
*
* @param event Overall sql execution event.
*/
@Subscribe
@AllowConcurrentEvents
public void listenOverall(final OverallExecutionEvent event) {
Tracer tracer = ShardingJDBCTracer.get();
ActiveSpan activeSpan;
switch (event.getEventExecutionType()) {
case BEFORE_EXECUTE:
activeSpan = tracer.buildSpan("/SJDBC/TRUNK/" + event.getSqlType().name()).withTag(Tags.COMPONENT.getKey(), "ShardingJDBC")
.startActive();
trunkContainer.set(activeSpan);
if (isParallelExecute(event)) {
ExecutorDataMap.getDataMap().put(SNAPSHOT_DATA_KEY, activeSpan.capture());
}
break;
case EXECUTE_FAILURE:
activeSpan = trunkContainer.get();
activeSpan.setTag(Tags.ERROR.getKey(), true);
if (event.getException().isPresent()) {
activeSpan.log(System.currentTimeMillis(), log(event.getException().get()));
}
deactivate();
break;
case EXECUTE_SUCCESS:
deactivate();
break;
default:
throw new ShardingJdbcException("Unsupported event type");
}
}
private boolean isParallelExecute(final OverallExecutionEvent event) {
return event.getStatementUnitSize() > 1;
}
private void deactivate() {
trunkContainer.get().deactivate();
trunkContainer.remove();
}
/**
* listen DML execution event.
*
* @param event DML execution event.
*/
@Subscribe
@AllowConcurrentEvents
public void listenDML(final DMLExecutionEvent event) {
handle(event, "MODIFY");
}
/**
* listen DQL execution event.
*
* @param event DQL execution event.
*/
@Subscribe
@AllowConcurrentEvents
public void listenDQL(final DQLExecutionEvent event) {
handle(event, "QUERY");
}
private void handle(final AbstractSQLExecutionEvent event, final String operation) {
Tracer tracer = ShardingJDBCTracer.get();
switch (event.getEventExecutionType()) {
case BEFORE_EXECUTE:
if (ExecutorDataMap.getDataMap().containsKey(SNAPSHOT_DATA_KEY) && !isCurrentMainThread()) {
trunkInBranchContainer.set(((ActiveSpan.Continuation) ExecutorDataMap.getDataMap().get(SNAPSHOT_DATA_KEY)).activate());
}
branchContainer.set(tracer.buildSpan("/SJDBC/BRANCH/" + operation).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
.withTag(Tags.PEER_HOSTNAME.getKey(), event.getDataSource()).withTag(Tags.COMPONENT.getKey(), "ShardingJDBC")
.withTag(Tags.DB_INSTANCE.getKey(), event.getDataSource()).withTag(Tags.DB_TYPE.getKey(), "sql")
.withTag(Tags.DB_STATEMENT.getKey(), event.getSql()).startManual());
break;
case EXECUTE_FAILURE:
Span span = branchContainer.get();
span.setTag(Tags.ERROR.getKey(), true);
if (event.getException().isPresent()) {
span.log(System.currentTimeMillis(), log(event.getException().get()));
}
finish();
break;
case EXECUTE_SUCCESS:
finish();
break;
default:
throw new ShardingJdbcException("Unsupported event type");
}
}
private boolean isCurrentMainThread() {
return null != trunkContainer.get();
}
private void finish() {
branchContainer.get().finish();
branchContainer.remove();
if (null == trunkInBranchContainer.get()) {
return;
}
trunkInBranchContainer.get().deactivate();
trunkInBranchContainer.remove();
}
private Map<String, ?> log(final Throwable t) {
Map<String, String> result = new HashMap<>(3);
result.put("event", "error");
result.put("error.kind", t.getClass().getName());
result.put("message", t.getMessage());
return result;
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing;
import io.opentracing.Tracer;
import io.opentracing.util.GlobalTracer;
import io.shardingjdbc.core.exception.ShardingJdbcException;
import io.shardingjdbc.core.util.EventBusInstance;
import io.shardingjdbc.opentracing.config.ConfigLoader;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* A container of tracer object.
*
* @author gaohongtao
* @author wangkai
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ShardingJDBCTracer {
/**
* Initialize tracer.
*/
public static void init() {
if (GlobalTracer.isRegistered()) {
return;
}
String tracerClassName = new ConfigLoader().getTracerClassName();
try {
init((Tracer) Class.forName(tracerClassName).newInstance());
} catch (final InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
throw new ShardingJdbcException("Parse tracer class name", ex);
}
}
/**
* Initialize tracer from another one.
*
* @param tracer that is delegated
*/
public static void init(final Tracer tracer) {
if (GlobalTracer.isRegistered()) {
return;
}
GlobalTracer.register(tracer);
EventBusInstance.getInstance().register(new ExecuteEventListener());
}
/**
* Get the tracer from container.
*
* @return tracer
*/
public static Tracer get() {
if (GlobalTracer.isRegistered()) {
return GlobalTracer.get();
}
init();
return GlobalTracer.get();
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing.config;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import lombok.Getter;
/**
* Config loader.
*
* @author gaohongtao
* @author wangkai
*/
public class ConfigLoader {
private static final ConfigParser[] PARSERS = new ConfigParser[]{new OptsConfigParser()};
@Getter
private final String tracerClassName;
public ConfigLoader() {
String tracerClassName = null;
for (ConfigParser each : PARSERS) {
Optional<String> tracerClassOptional = each.parse("tracer.class");
if (tracerClassOptional.isPresent()) {
tracerClassName = tracerClassOptional.get();
break;
}
}
Preconditions.checkNotNull(tracerClassName);
this.tracerClassName = tracerClassName;
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing.config;
import com.google.common.base.Optional;
/**
* Parse config.
*
* @author gaohongtao
* @author wangkai
*/
interface ConfigParser {
/**
* Parse config item to config value.
*
* @param configItem config item
* @return config value
*/
Optional<String> parse(String configItem);
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing.config;
import com.google.common.base.Optional;
/**
* Parse config from java opts.
*
* @author gaohongtao
* @author wangkai
*/
public class OptsConfigParser implements ConfigParser {
private static final String PREFIX = "shardingjdbc.opentracing";
@Override
public Optional<String> parse(final String configItem) {
return Optional.fromNullable(System.getProperty(PREFIX + "." + configItem));
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing;
import io.shardingjdbc.opentracing.config.ConfigLoaderTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ConfigLoaderTest.class,
ExecuteEventListenerTest.class,
ShardingJDBCTracerTest.class
})
public class AllTests {
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing;
import io.opentracing.mock.MockTracer;
import io.opentracing.util.ThreadLocalActiveSpanSource;
import io.shardingjdbc.core.constant.SQLType;
import io.shardingjdbc.core.executor.BaseStatementUnit;
import io.shardingjdbc.core.executor.ExecuteCallback;
import io.shardingjdbc.core.executor.ExecutorEngine;
import io.shardingjdbc.core.executor.type.statement.StatementUnit;
import io.shardingjdbc.core.routing.SQLExecutionUnit;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
public class ExecuteEventListenerTest {
private static final MockTracer TRACER = new MockTracer(new ThreadLocalActiveSpanSource(),
MockTracer.Propagator.TEXT_MAP);
private final ExecutorEngine executorEngine = new ExecutorEngine(5);
@BeforeClass
public static void init() {
ShardingJDBCTracer.init(TRACER);
}
@Before
public void before() throws NoSuchFieldException, IllegalAccessException {
TRACER.reset();
}
@Test
public void assertSingleStatement() throws Exception {
Statement statement = mock(Statement.class);
when(statement.getConnection()).thenReturn(mock(Connection.class));
executorEngine.executeStatement(SQLType.DML, Collections.singleton(new StatementUnit(new SQLExecutionUnit("ds_0", "insert into ..."), statement)), new ExecuteCallback<Integer>() {
@Override
public Integer execute(final BaseStatementUnit baseStatementUnit) throws Exception {
return 0;
}
});
assertThat(TRACER.finishedSpans().size(), is(2));
}
@Test
public void assertMultiStatement() throws Exception {
List<StatementUnit> statementUnitList = new ArrayList<>(2);
Statement stm1 = mock(Statement.class);
when(stm1.getConnection()).thenReturn(mock(Connection.class));
statementUnitList.add(new StatementUnit(new SQLExecutionUnit("ds_0", "insert into ..."), stm1));
Statement stm2 = mock(Statement.class);
when(stm2.getConnection()).thenReturn(mock(Connection.class));
statementUnitList.add(new StatementUnit(new SQLExecutionUnit("ds_0", "insert into ..."), stm2));
executorEngine.executeStatement(SQLType.DML, statementUnitList, new ExecuteCallback<Integer>() {
@Override
public Integer execute(final BaseStatementUnit baseStatementUnit) throws Exception {
return 0;
}
});
assertThat(TRACER.finishedSpans().size(), is(3));
}
@Test(expected = SQLException.class)
public void assertSQLException() throws Exception {
Statement statement = mock(Statement.class);
when(statement.getConnection()).thenReturn(mock(Connection.class));
executorEngine.executeStatement(SQLType.DQL, Collections.singleton(new StatementUnit(new SQLExecutionUnit("ds_0", "select ..."), statement)), new ExecuteCallback<Integer>() {
@Override
public Integer execute(final BaseStatementUnit baseStatementUnit) throws Exception {
throw new SQLException();
}
});
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing;
import io.opentracing.NoopTracerFactory;
import io.opentracing.Tracer;
import io.opentracing.util.GlobalTracer;
import io.shardingjdbc.core.exception.ShardingJdbcException;
import io.shardingjdbc.opentracing.config.OptsConfigParser;
import org.apache.commons.lang3.builder.ToStringExclude;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest(OptsConfigParser.class)
public class ShardingJDBCTracerTest {
@Before
public void setUp() throws Exception {
mockStatic(System.class);
clearGlobalTracer();
}
@Test
public void assertDuplicatedLoading() {
ShardingJDBCTracer.init(mock(Tracer.class));
Tracer t1 = ShardingJDBCTracer.get();
ShardingJDBCTracer.init();
assertEquals(t1, ShardingJDBCTracer.get());
ShardingJDBCTracer.init(mock(Tracer.class));
assertEquals(t1, ShardingJDBCTracer.get());
}
@Test
public void assertTracer() {
when(System.getProperty("shardingjdbc.opentracing.tracer.class")).thenReturn("io.shardingjdbc.opentracing.fixture.FooTracer");
assertThat((GlobalTracer) ShardingJDBCTracer.get(), Is.isA(GlobalTracer.class));
assertTrue(GlobalTracer.isRegistered());
assertThat(ShardingJDBCTracer.get(), Is.is(ShardingJDBCTracer.get()));
}
@Test(expected = ShardingJdbcException.class)
public void assertTracerClassError() {
when(System.getProperty("shardingjdbc.opentracing.tracer.class")).thenReturn("com.foo.FooTracer");
ShardingJDBCTracer.get();
}
private static void clearGlobalTracer() throws NoSuchFieldException, IllegalAccessException {
Field tracerField = GlobalTracer.class.getDeclaredField("tracer");
tracerField.setAccessible(true);
tracerField.set(GlobalTracer.class, NoopTracerFactory.create());
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing.config;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest(OptsConfigParser.class)
public class ConfigLoaderTest {
@Before
public void setUp() throws Exception {
mockStatic(System.class);
}
@Test
public void assertLoadConfigFromProperty() {
when(System.getProperty("shardingjdbc.opentracing.tracer.class")).thenReturn("com.foo.fooClass");
assertThat(new ConfigLoader().getTracerClassName(), is("com.foo.fooClass"));
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.opentracing.fixture;
import io.opentracing.ActiveSpan;
import io.opentracing.Span;
import io.opentracing.SpanContext;
import io.opentracing.Tracer;
import io.opentracing.propagation.Format;
public class FooTracer implements Tracer {
@Override
public SpanBuilder buildSpan(final String s) {
return null;
}
@Override
public <C> void inject(final SpanContext spanContext, final Format<C> format, final C c) {
}
@Override
public <C> SpanContext extract(final Format<C> format, final C c) {
return null;
}
@Override
public ActiveSpan activeSpan() {
return null;
}
@Override
public ActiveSpan makeActive(final Span span) {
return null;
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册