diff --git a/docs/src/main/asciidoc/README.adoc b/docs/src/main/asciidoc/README.adoc index 04d13871a..41f433d4e 100644 --- a/docs/src/main/asciidoc/README.adoc +++ b/docs/src/main/asciidoc/README.adoc @@ -2,26 +2,7 @@ image::https://api.travis-ci.org/spring-cloud/spring-cloud-sleuth.svg?branch=mas include::intro.adoc[] -== Features - -* Adds trace and span ids to the Slf4J MDC, so you can extract all the logs from a given trace or span in a log aggregator. Example configuration: -+ -[source,yaml] ----- -logging: - pattern: - level: '[trace=%X{X-Trace-Id:-},span=%X{X-Span-Id:-}] %5p' ----- -+ -(notice the `%X` entries from the MDC). - -* Optionally log span data in JSON format for harvesting in a log aggregator (set `spring.sleuth.log.json.enabled=true`). - -* Provides an abstraction over common distributed tracing data models: traces, spans (forming a DAG), annotations, key-value annotations. Loosely based on HTrace, but Zipkin (Dapper) compatible. - -* Instruments common ingress and egress points from Spring applications (servlet filter, rest template, scheduled actions, message channels, zuul filters, feign client). - -* If `spring-cloud-sleuth-zipkin` then the app will generate and collect Zipkin-compatible traces (using Brave). By default it sends them via Thrift to a Zipkin collector service on localhost (port 9410). Configure the location of the service using `spring.zipkin.[host,port]`. +include::features.adoc[] == Running the samples diff --git a/docs/src/main/asciidoc/features.adoc b/docs/src/main/asciidoc/features.adoc new file mode 100644 index 000000000..36d22f711 --- /dev/null +++ b/docs/src/main/asciidoc/features.adoc @@ -0,0 +1,22 @@ +== Features + +* Adds trace and span ids to the Slf4J MDC, so you can extract all the logs from a given trace or span in a log aggregator. Example configuration: ++ +[source,yaml] +---- +logging: + pattern: + level: '[trace=%X{X-Trace-Id:-},span=%X{X-Span-Id:-}] %5p' +---- ++ +(notice the `%X` entries from the MDC). + +* Optionally log span data in JSON format for harvesting in a log aggregator (set `spring.sleuth.log.json.enabled=true`). + +* Provides an abstraction over common distributed tracing data models: traces, spans (forming a DAG), annotations, key-value annotations. Loosely based on HTrace, but Zipkin (Dapper) compatible. + +* Instruments common ingress and egress points from Spring applications (servlet filter, rest template, scheduled actions, message channels, zuul filters, feign client). + +* If `spring-cloud-sleuth-zipkin` then the app will generate and collect Zipkin-compatible traces (using Brave). By default it sends them via Thrift to a Zipkin collector service on localhost (port 9410). Configure the location of the service using `spring.zipkin.[host,port]`. + +* If `spring-cloud-sleuth-stream` then the app will generate and collect traces via Spring Cloud Stream. Your app automatically becomes a producer of tracer messages that are sent over your broker of choice (e.g. RabbitMQ, Apache Kafka, Redis). \ No newline at end of file diff --git a/docs/src/main/asciidoc/spring-cloud-sleuth.adoc b/docs/src/main/asciidoc/spring-cloud-sleuth.adoc index 1659d6484..4773bf6ab 100644 --- a/docs/src/main/asciidoc/spring-cloud-sleuth.adoc +++ b/docs/src/main/asciidoc/spring-cloud-sleuth.adoc @@ -6,5 +6,55 @@ include::intro.adoc[] -== TODO: Document Spring Cloud Sleuth +include::features.adoc[] +== Sampling + +In distributed tracing the data volumes can be very high so sampling +is important (you usually don't need to trace all requests to get a +good picture of what is happening). Spring Cloud Sleuth has a +`Sampler` strategy that you can implement to take control of the +sampling algorithm. By default you get a strategy that continues to +trace if a span is already active, but never starts a new one. If all +your apps run with this sampler you will see no traces, so it's best +to install your own strategy. For testing there is an `AlwaysSampler` +that traces everything, which can be installed just by creating a bean definition: + +[source,java] +---- +@Bean +public Sampler defaultSampler() { + return new AlwaysSampler(); +} +---- + +== Spans as Messages + +You can accumulate and send span data over +http://cloud.spring.io/spring-cloud-stream[Spring Cloud Stream] by +including the `spring-cloud-sleuth-stream` jar as a dependency, and +adding a Channel Binder implementation +(e.g. `spring-cloud-starter-stream-rabbit` for RabbitMQ or +`spring-cloud-starter-stream-kafka` for Kafka). This will +automatically turn your app into a producer of messages with payload +type `Spans`. A consumer can then easily be implemented using +`spring-cloud-sleuth-stream` and binding to the `SleuthSink`. Example: + +[source,java] +---- +@EnableBinding(SleuthSink.class) +@SpringBootApplication(exclude = SleuthStreamAutoConfiguration.class) +@MessageEndpoint +public class Consumer { + + @ServiceActivator(inputChannel = SleuthSink.INPUT) + public void sink(Spans input) throws Exception { + // ... process spans + } +} +---- + +NOTE: the sample consumer application above explicitly excludes +`SleuthStreamAutoConfiguration` so it doesn't send messages to itself, +but this is optional (you might actually want to trace requests into +the consumer app). \ No newline at end of file diff --git a/pom.xml b/pom.xml index 7a88c5980..6978c1a28 100644 --- a/pom.xml +++ b/pom.xml @@ -28,6 +28,7 @@ spring-cloud-sleuth-core spring-cloud-sleuth-zipkin + spring-cloud-sleuth-stream spring-cloud-sleuth-samples spring-cloud-starter-sleuth spring-cloud-starter-zipkin diff --git a/spring-cloud-sleuth-stream/.google b/spring-cloud-sleuth-stream/.google new file mode 100644 index 000000000..e69de29bb diff --git a/spring-cloud-sleuth-stream/.mvn/jvm.config b/spring-cloud-sleuth-stream/.mvn/jvm.config new file mode 100644 index 000000000..0e7dabeff --- /dev/null +++ b/spring-cloud-sleuth-stream/.mvn/jvm.config @@ -0,0 +1 @@ +-Xmx1024m -XX:CICompilerCount=1 -XX:TieredStopAtLevel=1 -Djava.security.egd=file:/dev/./urandom \ No newline at end of file diff --git a/spring-cloud-sleuth-stream/.mvn/maven.config b/spring-cloud-sleuth-stream/.mvn/maven.config new file mode 100644 index 000000000..3b8cf46e1 --- /dev/null +++ b/spring-cloud-sleuth-stream/.mvn/maven.config @@ -0,0 +1 @@ +-DaltSnapshotDeploymentRepository=repo.spring.io::default::https://repo.spring.io/libs-snapshot-local -P spring diff --git a/spring-cloud-sleuth-stream/.mvn/wrapper/maven-wrapper.jar b/spring-cloud-sleuth-stream/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 000000000..5fd4d5023 Binary files /dev/null and b/spring-cloud-sleuth-stream/.mvn/wrapper/maven-wrapper.jar differ diff --git a/spring-cloud-sleuth-stream/.mvn/wrapper/maven-wrapper.properties b/spring-cloud-sleuth-stream/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..eb9194764 --- /dev/null +++ b/spring-cloud-sleuth-stream/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file diff --git a/spring-cloud-sleuth-stream/docker-compose.yml b/spring-cloud-sleuth-stream/docker-compose.yml new file mode 100644 index 000000000..ae9ea8b0d --- /dev/null +++ b/spring-cloud-sleuth-stream/docker-compose.yml @@ -0,0 +1,35 @@ +cassandra: + image: quay.io/openzipkin/zipkin-cassandra:1.9.0 + ports: + - 9042:9042 +collector: + image: quay.io/openzipkin/zipkin-collector:1.9.0 + environment: + - BLOCK_ON_CASSANDRA=true + expose: + - 9410 + ports: + - 9410:9410 + - 9900:9900 + links: + - cassandra:db +query: + image: quay.io/openzipkin/zipkin-query:1.9.0 + environment: + - BLOCK_ON_CASSANDRA=true + expose: + - 9411 + ports: + - 9411:9411 + - 9901:9901 + links: + - cassandra:db + - collector +web: + image: quay.io/openzipkin/zipkin-web:1.9.0 + ports: + - 8080:8080 + - 9990:9990 + links: + - collector + - query diff --git a/spring-cloud-sleuth-stream/mvnw b/spring-cloud-sleuth-stream/mvnw new file mode 100755 index 000000000..e3511489f --- /dev/null +++ b/spring-cloud-sleuth-stream/mvnw @@ -0,0 +1,234 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # + # Look for the Apple JDKs first to preserve the existing behaviour, and then look + # for the new JDKs provided by Oracle. + # + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then + # + # Oracle JDKs + # + export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then + # + # Apple JDKs + # + export JAVA_HOME=`/usr/libexec/java_home` + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + local basedir=$(pwd) + local wdir=$(pwd) + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + wdir=$(cd "$wdir/.."; pwd) + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} "$@" + diff --git a/spring-cloud-sleuth-stream/mvnw.cmd b/spring-cloud-sleuth-stream/mvnw.cmd new file mode 100644 index 000000000..fc8302432 --- /dev/null +++ b/spring-cloud-sleuth-stream/mvnw.cmd @@ -0,0 +1,145 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +set MAVEN_CMD_LINE_ARGS=%* + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/spring-cloud-sleuth-stream/pom.xml b/spring-cloud-sleuth-stream/pom.xml new file mode 100644 index 000000000..29be0ec13 --- /dev/null +++ b/spring-cloud-sleuth-stream/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + spring-cloud-sleuth-stream + jar + Spring Cloud Sleuth Stream + Spring Cloud Sleuth Stream + + + org.springframework.cloud + spring-cloud-sleuth + 1.0.0.BUILD-SNAPSHOT + + + + + org.springframework.cloud + spring-cloud-sleuth-core + + + org.springframework.cloud + spring-cloud-stream + + + org.springframework.cloud + spring-cloud-commons + true + + + org.springframework.boot + spring-boot-actuator + true + + + org.springframework.boot + spring-boot-starter-logging + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + + true + + + org.springframework.cloud + spring-cloud-stream-binder-local + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/DiscoveryClientHostLocator.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/DiscoveryClientHostLocator.java new file mode 100644 index 000000000..04c18558f --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/DiscoveryClientHostLocator.java @@ -0,0 +1,57 @@ +/* + * Copyright 2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import java.net.InetAddress; + +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.sleuth.Span; + +/** + * An {@link HostLocator} that tries to find local service information from a + * {@link DiscoveryClient}. + * + * @author Dave Syer + * + */ +public class DiscoveryClientHostLocator implements HostLocator { + + private DiscoveryClient client; + + public DiscoveryClientHostLocator(DiscoveryClient client) { + this.client = client; + } + + @Override + public Host locate(Span span) { + ServiceInstance instance = this.client.getLocalServiceInstance(); + return new Host(instance.getServiceId(), getIpAddress(instance), + instance.getPort()); + } + + private String getIpAddress(ServiceInstance instance) { + try { + InetAddress address = InetAddress.getByName(instance.getHost()); + return address.getHostAddress(); + } + catch (Exception e) { + return "0.0.0.0"; + } + } + +} diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/Host.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/Host.java new file mode 100644 index 000000000..c6bda4f8b --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/Host.java @@ -0,0 +1,52 @@ +/* + * Copyright 2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; + +import com.fasterxml.jackson.annotation.JsonInclude; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * @author Dave Syer + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@Data +@AllArgsConstructor +public class Host { + + private String serviceName; + private String address; + private Integer port; + + public int getIpv4() { + InetAddress inetAddress = null; + try { + inetAddress = InetAddress.getByName(this.address); + } + catch (final UnknownHostException e) { + throw new IllegalArgumentException(e); + } + return ByteBuffer.wrap(inetAddress.getAddress()).getInt(); + } + +} diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/HostLocator.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/HostLocator.java new file mode 100644 index 000000000..b1402ce31 --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/HostLocator.java @@ -0,0 +1,32 @@ +/* + * Copyright 2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import org.springframework.cloud.sleuth.Span; + +/** + * Strategy for locating a "host" from a Spring Cloud Span (and whatever other + * environment properties might be available). + * + * @author Dave Syer + * + */ +public interface HostLocator { + + Host locate(Span span); + +} diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/ServerPropertiesHostLocator.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/ServerPropertiesHostLocator.java new file mode 100644 index 000000000..bc27c1ddf --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/ServerPropertiesHostLocator.java @@ -0,0 +1,92 @@ +/* + * Copyright 2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent; +import org.springframework.cloud.sleuth.Span; +import org.springframework.context.event.EventListener; + +/** + * @author Dave Syer + * + */ +public class ServerPropertiesHostLocator implements HostLocator { + + @Value("${spring.application.name:application}") + private String appName; + + private ServerProperties serverProperties; + + private Integer port; + + public ServerPropertiesHostLocator(ServerProperties serverProperties) { + this.serverProperties = serverProperties; + } + + @Override + public Host locate(Span span) { + String serviceName = getServiceName(span); + String address = getAddress(); + Integer port = getPort(); + Host ep = new Host(serviceName, address, port); + return ep; + } + + @EventListener(EmbeddedServletContainerInitializedEvent.class) + public void grabPort(EmbeddedServletContainerInitializedEvent event) { + this.port = event.getEmbeddedServletContainer().getPort(); + } + + private Integer getPort() { + if (this.port!=null) { + return this.port; + } + Integer port; + if (this.serverProperties!=null && this.serverProperties.getPort() != null) { + port = this.serverProperties.getPort(); + } + else { + port = 8080; + } + return port; + } + + private String getAddress() { + String address; + if (this.serverProperties!=null && this.serverProperties.getAddress() != null) { + address = this.serverProperties.getAddress().getHostAddress(); + } + else { + address = "127.0.0.1"; + } + return address; + } + + private String getServiceName(Span span) { + String serviceName; + if (span.getProcessId() != null) { + serviceName = span.getProcessId().toLowerCase(); + } + else { + serviceName = this.appName; + } + return serviceName; + } + +} diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthSink.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthSink.java new file mode 100644 index 000000000..0ba2a4a81 --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthSink.java @@ -0,0 +1,32 @@ +/* + * Copyright 2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import org.springframework.cloud.stream.annotation.Input; +import org.springframework.messaging.SubscribableChannel; + +/** + * @author Dave Syer + * + */ +public interface SleuthSink { + + String INPUT = "sleuth"; + + @Input(SleuthSink.INPUT) + SubscribableChannel input(); +} diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthSource.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthSource.java new file mode 100644 index 000000000..ed4bd823e --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthSource.java @@ -0,0 +1,33 @@ +/* + * Copyright 2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import org.springframework.cloud.stream.annotation.Output; +import org.springframework.messaging.MessageChannel; + +/** + * @author Dave Syer + * + */ +public interface SleuthSource { + + String OUTPUT = "sleuth"; + + @Output(SleuthSource.OUTPUT) + MessageChannel output(); + +} \ No newline at end of file diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthStreamAutoConfiguration.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthStreamAutoConfiguration.java new file mode 100644 index 000000000..4d1021459 --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthStreamAutoConfiguration.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013-2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.sleuth.Trace; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.config.ChannelBindingAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.integration.config.GlobalChannelInterceptor; +import org.springframework.integration.support.MessageBuilder; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.support.ChannelInterceptor; +import org.springframework.messaging.support.ChannelInterceptorAdapter; + +/** + * Autoconfiguration for sending Spans over Spring Cloud Stream. This is for the producer + * (via {@link SleuthSource}). A consumer can enable binding to {@link SleuthSink} and + * receive the messages coming from the source (they have the same channel name so there + * is no additional configuration to do by default). + * + * @author Dave Syer + */ +@Configuration +@EnableConfigurationProperties(SleuthStreamProperties.class) +@AutoConfigureBefore(ChannelBindingAutoConfiguration.class) +@EnableBinding(SleuthSource.class) +@ConditionalOnProperty(value = "spring.sleuth.stream.enabled", matchIfMissing = true) +public class SleuthStreamAutoConfiguration { + + @Bean + @GlobalChannelInterceptor(patterns = SleuthSource.OUTPUT, order = Ordered.HIGHEST_PRECEDENCE) + public ChannelInterceptor zipkinChannelInterceptor() { + // don't trace the tracer (suppress spans originating from our own source) + return new ChannelInterceptorAdapter() { + @Override + public Message preSend(Message message, MessageChannel channel) { + return MessageBuilder.fromMessage(message) + .setHeader(Trace.NOT_SAMPLED_NAME, "").build(); + } + }; + } + + @Bean + public StreamSpanListener sleuthTracer(HostLocator endpointLocator) { + return new StreamSpanListener(endpointLocator); + } + + @Configuration + @ConditionalOnMissingClass("org.springframework.cloud.client.discovery.DiscoveryClient") + protected static class DefaultEndpointLocatorConfiguration { + + @Autowired(required = false) + private ServerProperties serverProperties; + + @Bean + public HostLocator zipkinEndpointLocator() { + return new ServerPropertiesHostLocator(this.serverProperties); + } + + } + + @Configuration + @ConditionalOnClass(DiscoveryClient.class) + protected static class DiscoveryClientEndpointLocatorConfiguration { + + @Autowired(required = false) + private ServerProperties serverProperties; + + @Autowired(required = false) + private DiscoveryClient client; + + @Bean + public HostLocator zipkinEndpointLocator() { + if (this.client != null) { + return new DiscoveryClientHostLocator(this.client); + } + return new ServerPropertiesHostLocator(this.serverProperties); + } + + } + +} diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthStreamProperties.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthStreamProperties.java new file mode 100644 index 000000000..3ac65a286 --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/SleuthStreamProperties.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013-2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import lombok.Data; + +/** + * @author Dave Syer + */ +@ConfigurationProperties("spring.sleuth.stream") +@Data +public class SleuthStreamProperties { + private boolean enabled = true; +} diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/Spans.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/Spans.java new file mode 100644 index 000000000..b96c19c36 --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/Spans.java @@ -0,0 +1,43 @@ +/* + * Copyright 2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import java.util.Collections; +import java.util.List; + +import org.springframework.cloud.sleuth.Span; + +import com.fasterxml.jackson.annotation.JsonInclude; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * Data transfer object for a collection of spans from a given host. + * + * @author Dave Syer + * + */ +@JsonInclude(JsonInclude.Include.NON_DEFAULT) +@Data +@AllArgsConstructor +public class Spans { + + private Host host; + private List spans = Collections.emptyList(); + +} diff --git a/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/StreamSpanListener.java b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/StreamSpanListener.java new file mode 100644 index 000000000..6ae531878 --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/java/org/springframework/cloud/sleuth/stream/StreamSpanListener.java @@ -0,0 +1,115 @@ +/* + * Copyright 2013-2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.springframework.cloud.sleuth.Span; +import org.springframework.cloud.sleuth.event.ClientReceivedEvent; +import org.springframework.cloud.sleuth.event.ClientSentEvent; +import org.springframework.cloud.sleuth.event.ServerReceivedEvent; +import org.springframework.cloud.sleuth.event.ServerSentEvent; +import org.springframework.cloud.sleuth.event.SpanAcquiredEvent; +import org.springframework.cloud.sleuth.event.SpanReleasedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.core.annotation.Order; +import org.springframework.integration.annotation.InboundChannelAdapter; +import org.springframework.integration.annotation.MessageEndpoint; + +/** + * A message source for spans. Also handles RPC flavoured annotations. + * + * @author Dave Syer + */ +@MessageEndpoint +public class StreamSpanListener { + + public static final String CLIENT_RECV = "cr"; + public static final String CLIENT_SEND = "cs"; + public static final String SERVER_RECV = "sr"; + public static final String SERVER_SEND = "ss"; + + private List queue = new ArrayList<>(); + private HostLocator endpointLocator; + + public StreamSpanListener(HostLocator endpointLocator) { + this.endpointLocator = endpointLocator; + } + + public void setQueue(List queue) { + this.queue = queue; + } + + @EventListener + @Order(0) + public void start(SpanAcquiredEvent event) { + event.getSpan().addTimelineAnnotation("acquire"); + } + + @EventListener + @Order(0) + public void serverReceived(ServerReceivedEvent event) { + if (event.getParent() != null && event.getParent().isRemote()) { + event.getParent().addTimelineAnnotation(SERVER_RECV); + } + } + + @EventListener + @Order(0) + public void clientSend(ClientSentEvent event) { + event.getSpan().addTimelineAnnotation(CLIENT_SEND); + } + + @EventListener + @Order(0) + public void clientReceive(ClientReceivedEvent event) { + event.getSpan().addTimelineAnnotation(CLIENT_RECV); + } + + @EventListener + @Order(0) + public void serverSend(ServerSentEvent event) { + if (event.getParent() != null && event.getParent().isRemote()) { + event.getParent().addTimelineAnnotation(SERVER_SEND); + this.queue.add(event.getParent()); + } + } + + @EventListener + @Order(0) + public void release(SpanReleasedEvent event) { + event.getSpan().addTimelineAnnotation("release"); + this.queue.add(event.getSpan()); + } + + @InboundChannelAdapter(value = SleuthSource.OUTPUT) + public Spans poll() { + List result = new ArrayList<>(this.queue); + this.queue.clear(); + for (Iterator iterator = result.iterator(); iterator.hasNext();) { + Span span = iterator.next(); + if (span.getName().equals("message/zipkin")) { + iterator.remove(); + } + } + return result.isEmpty() ? null + : new Spans(this.endpointLocator.locate(result.get(0)), result); + } + +} diff --git a/spring-cloud-sleuth-stream/src/main/resources/META-INF/spring.factories b/spring-cloud-sleuth-stream/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..5decfc96e --- /dev/null +++ b/spring-cloud-sleuth-stream/src/main/resources/META-INF/spring.factories @@ -0,0 +1,3 @@ +# Auto Configuration +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +org.springframework.cloud.sleuth.stream.SleuthStreamAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-sleuth-stream/src/test/java/org/springframework/cloud/sleuth/stream/StreamSpanListenerTests.java b/spring-cloud-sleuth-stream/src/test/java/org/springframework/cloud/sleuth/stream/StreamSpanListenerTests.java new file mode 100644 index 000000000..d482be7f8 --- /dev/null +++ b/spring-cloud-sleuth-stream/src/test/java/org/springframework/cloud/sleuth/stream/StreamSpanListenerTests.java @@ -0,0 +1,124 @@ +/* + * Copyright 2015 the original author or 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 org.springframework.cloud.sleuth.stream; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.cloud.sleuth.MilliSpan; +import org.springframework.cloud.sleuth.Sampler; +import org.springframework.cloud.sleuth.Span; +import org.springframework.cloud.sleuth.Trace; +import org.springframework.cloud.sleuth.TraceScope; +import org.springframework.cloud.sleuth.autoconfig.TraceAutoConfiguration; +import org.springframework.cloud.sleuth.event.ClientReceivedEvent; +import org.springframework.cloud.sleuth.event.ClientSentEvent; +import org.springframework.cloud.sleuth.event.ServerReceivedEvent; +import org.springframework.cloud.sleuth.event.ServerSentEvent; +import org.springframework.cloud.sleuth.sampler.AlwaysSampler; +import org.springframework.cloud.sleuth.stream.SleuthStreamAutoConfiguration; +import org.springframework.cloud.sleuth.stream.StreamSpanListener; +import org.springframework.cloud.sleuth.stream.StreamSpanListenerTests.TestConfiguration; +import org.springframework.cloud.stream.binder.local.config.LocalBinderAutoConfiguration; +import org.springframework.cloud.stream.config.ChannelBindingAutoConfiguration; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Dave Syer + * + */ +@SpringApplicationConfiguration(classes = TestConfiguration.class) +@RunWith(SpringJUnit4ClassRunner.class) +public class StreamSpanListenerTests { + + @Autowired + private Trace trace; + + @Autowired + private ApplicationContext application; + + @Autowired + private ZipkinTestConfiguration test; + + @PostConstruct + public void init() { + this.test.spans.clear(); + } + + @Test + public void acquireAndRelease() { + TraceScope context = this.trace.startSpan("foo"); + context.close(); + assertEquals(1, this.test.spans.size()); + } + + @Test + public void rpcAnnotations() { + Span parent = MilliSpan.builder().traceId("xxxx").name("parent").remote(true) + .build(); + TraceScope context = this.trace.startSpan("child", parent); + this.application.publishEvent(new ClientSentEvent(this, context.getSpan())); + this.application + .publishEvent(new ServerReceivedEvent(this, parent, context.getSpan())); + this.application + .publishEvent(new ServerSentEvent(this, parent, context.getSpan())); + this.application.publishEvent(new ClientReceivedEvent(this, context.getSpan())); + context.close(); + assertEquals(2, this.test.spans.size()); + } + + @Configuration + @Import({ ZipkinTestConfiguration.class, SleuthStreamAutoConfiguration.class, + LocalBinderAutoConfiguration.class, ChannelBindingAutoConfiguration.class, + TraceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + protected static class TestConfiguration { + } + + @Configuration + protected static class ZipkinTestConfiguration { + + private List spans = new ArrayList<>(); + + @Autowired + StreamSpanListener listener; + + @Bean + public Sampler defaultSampler() { + return new AlwaysSampler(); + } + + @PostConstruct + public void init() { + this.listener.setQueue(this.spans); + } + + } + +} diff --git a/spring-cloud-sleuth-zipkin/pom.xml b/spring-cloud-sleuth-zipkin/pom.xml index 736da70d3..38e92f145 100644 --- a/spring-cloud-sleuth-zipkin/pom.xml +++ b/spring-cloud-sleuth-zipkin/pom.xml @@ -16,22 +16,6 @@ .. - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.codehaus.gmavenplus - gmavenplus-plugin - - - maven-surefire-plugin - - - - org.springframework.cloud @@ -61,10 +45,6 @@ com.github.kristofa brave-zipkin-spancollector - - com.google.guava - guava - org.projectlombok lombok