diff --git a/pom.xml b/pom.xml index 925d60843..b5a208ead 100644 --- a/pom.xml +++ b/pom.xml @@ -43,7 +43,7 @@ - 0.22.0 + 0.33.0 1.8 1.8 1.9.3 @@ -440,91 +440,91 @@ - - - release - - - - org.sonatype.plugins - nexus-staging-maven-plugin - ${maven.staging.plugin} - true - - ossrh - https://oss.sonatype.org/ - false - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven.gpg.pluign} - - - sign-artifacts - verify - - sign - - - - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - snapshot - - - - org.sonatype.plugins - nexus-staging-maven-plugin - ${maven.staging.plugin} - true - - ossrh - https://oss.sonatype.org/ - false - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven.gpg.pluign} - - - sign-artifacts - verify - - sign - - - - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-2.6.x-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java b/sofa-tracer-plugins/sofa-tracer-dubbo-2.6.x-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java index 28c223f60..f18343175 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-2.6.x-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-2.6.x-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java @@ -186,6 +186,13 @@ private Result doClientFilter(RpcContext rpcContext, Invoker invoker, Invocat //restore parent sofaTraceContext.push(clientSpan.getParentSofaTracerSpan()); } + + + + + + + } } } diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientStatReporter.java b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientStatReporter.java index 50c8518d9..b535fef1d 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientStatReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientStatReporter.java @@ -61,4 +61,5 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { //reserve this.addStat(statKey, values); } + } diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/SofaTracerAsyncHttpInterceptor.java b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/SofaTracerAsyncHttpInterceptor.java index 3d5130d02..3eece35f5 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/SofaTracerAsyncHttpInterceptor.java +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/SofaTracerAsyncHttpInterceptor.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.holder.SofaTraceContextHolder; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tracer.AbstractTracer; +import io.opentracing.Scope; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; @@ -58,17 +59,20 @@ public void process(HttpRequest httpRequest, HttpContext httpContext) throws Htt super.appendHttpClientRequestSpanTags(httpRequest, httpClientSpan); //async handle httpContext.setAttribute(CURRENT_ASYNC_HTTP_SPAN_KEY, httpClientSpan); - SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); - //client span - if (httpClientSpan.getParentSofaTracerSpan() != null) { - //restore parent - sofaTraceContext.push(httpClientSpan.getParentSofaTracerSpan()); - } else { - //pop async span - sofaTraceContext.pop(); - } +// SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); +// //client span +// if (httpClientSpan.getParentSofaTracerSpan() != null) { +// //restore parent +// sofaTraceContext.push(httpClientSpan.getParentSofaTracerSpan()); +// } else { +// //pop async span +// sofaTraceContext.pop(); +// } } + + + @Override public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException { diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/SofaTracerHttpInterceptor.java b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/SofaTracerHttpInterceptor.java index 7433d38b1..5a7c3427a 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/SofaTracerHttpInterceptor.java +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/SofaTracerHttpInterceptor.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.holder.SofaTraceContextHolder; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tracer.AbstractTracer; +import io.opentracing.Scope; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; @@ -61,12 +62,16 @@ public void process(HttpRequest httpRequest, HttpContext httpContext) throws Htt @Override public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException { - SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); - SofaTracerSpan httpClientSpan = sofaTraceContext.getCurrentSpan(); +// SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); +// SofaTracerSpan httpClientSpan = sofaTraceContext.getCurrentSpan(); + SofaTracerSpan httpClientSpan = (SofaTracerSpan) httpClientTracer.getSofaTracer().activeSpan(); //tag append super.appendHttpClientResponseSpanTags(httpResponse, httpClientSpan); //finish int statusCode = httpResponse.getStatusLine().getStatusCode(); httpClientTracer.clientReceive(String.valueOf(statusCode)); } + + + } diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/AsyncHttpClientTracerTest.java b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/AsyncHttpClientTracerTest.java index d5bf47c7a..558d4d223 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/AsyncHttpClientTracerTest.java +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/AsyncHttpClientTracerTest.java @@ -26,6 +26,7 @@ import com.alipay.sofa.tracer.plugins.httpclient.base.AbstractTestBase; import com.alipay.sofa.tracer.plugins.httpclient.base.client.HttpAsyncClientInstance; import com.alipay.sofa.tracer.plugins.httpclient.base.controller.PostBody; +import io.opentracing.Scope; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; @@ -98,26 +99,45 @@ private void testAsyncHttpClientPost(int expectedLength) throws Exception { "HttpClientTracer Baggage").start(); sofaTracerParentSpan.setBaggageItem("key1", "baggage1"); sofaTracerParentSpan.setBaggageItem("key2", "baggage2"); - sofaTraceContext.push(sofaTracerParentSpan); - - String responseStr = new HttpAsyncClientInstance().executePost(httpUrl, + try(Scope scope = sofaTracer.scopeManager().activate(sofaTracerParentSpan)){ + String responseStr = new HttpAsyncClientInstance().executePost(httpUrl, JSON.toJSONString(postBody)); - PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class); - assertEquals(postBody, resultPostBody); + PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class); + assertEquals(postBody, resultPostBody); - assertEquals(sofaTraceContext.getCurrentSpan(), sofaTracerParentSpan); - //wait for async output - List contents = FileUtils + assertEquals(sofaTracer.activeSpan(), sofaTracerParentSpan); + List contents = FileUtils .readLines(customFileLog(HttpClientLogEnum.HTTP_CLIENT_DIGEST.getDefaultLogName())); - assertTrue(contents.size() == expectedLength); - - // stat log print cycle: 1s - Thread.sleep(1000); - - //stat log - List statContents = FileUtils - .readLines(customFileLog(HttpClientLogEnum.HTTP_CLIENT_STAT.getDefaultLogName())); - assertTrue(statContents.size() == expectedLength); + assertTrue(contents.size() == expectedLength); + // stat log print cycle: 1s + Thread.sleep(1000); + + //stat log + List statContents = FileUtils + .readLines(customFileLog(HttpClientLogEnum.HTTP_CLIENT_STAT.getDefaultLogName())); + assertTrue(statContents.size() == expectedLength); + } +// sofaTraceContext.push(sofaTracerParentSpan); +// +// String responseStr = new HttpAsyncClientInstance().executePost(httpUrl, +// JSON.toJSONString(postBody)); +// +// PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class); +// assertEquals(postBody, resultPostBody); +// +// assertEquals(sofaTraceContext.getCurrentSpan(), sofaTracerParentSpan); +// //wait for async output +// List contents = FileUtils +// .readLines(customFileLog(HttpClientLogEnum.HTTP_CLIENT_DIGEST.getDefaultLogName())); +// assertTrue(contents.size() == expectedLength); +// +// // stat log print cycle: 1s +// Thread.sleep(1000); +// +// //stat log +// List statContents = FileUtils +// .readLines(customFileLog(HttpClientLogEnum.HTTP_CLIENT_STAT.getDefaultLogName())); +// assertTrue(statContents.size() == expectedLength); } } diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/interceptor/SofaTracerOkHttpInterceptor.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/interceptor/SofaTracerOkHttpInterceptor.java index 01513df4f..f19af2474 100644 --- a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/interceptor/SofaTracerOkHttpInterceptor.java +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/interceptor/SofaTracerOkHttpInterceptor.java @@ -24,6 +24,7 @@ import com.alipay.common.tracer.core.tracer.AbstractTracer; import com.alipay.common.tracer.core.utils.StringUtils; import com.alipay.sofa.tracer.plugins.okhttp.OkHttpRequestCarrier; +import io.opentracing.Scope; import okhttp3.Headers; import okhttp3.Request; import okhttp3.Response; @@ -53,9 +54,16 @@ public SofaTracerOkHttpInterceptor(AbstractTracer okHttpTracer, String appName, @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); + Response response = null; + SofaTracer sofaTracer = okHttpTracer.getSofaTracer(); SofaTracerSpan sofaTracerSpan = okHttpTracer.clientSend(request.method()); - Response response = chain.proceed(appendOkHttpRequestSpanTags(request, sofaTracerSpan)); - okHttpTracer.clientReceive(String.valueOf(response.code())); + try(Scope scope = sofaTracer.scopeManager().activate(sofaTracerSpan)){ + response = chain.proceed(appendOkHttpRequestSpanTags(request, sofaTracerSpan)); + okHttpTracer.clientReceive(String.valueOf(response.code())); + } finally { + sofaTracerSpan.finish(); + } + return response; } diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerNonJsonTest.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerNonJsonTest.java index f234a7069..ba1ca0d4c 100644 --- a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerNonJsonTest.java +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerNonJsonTest.java @@ -32,6 +32,7 @@ import com.alipay.sofa.tracer.plugins.okhttp.OkHttpTracer; import com.alipay.sofa.tracer.plugins.okhttp.base.client.OkHttpClientInstance; import com.alipay.sofa.tracer.plugins.okhttp.base.controller.PostBody; +import io.opentracing.Scope; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Before; @@ -101,20 +102,36 @@ private void testOkHttpPost() throws Exception { SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); SofaTracerSpan sofaTracerSpan = (SofaTracerSpan) sofaTracer.buildSpan( "HttpClientTracer Baggage").start(); - sofaTracerSpan.setBaggageItem("key1", "baggage1"); - sofaTracerSpan.setBaggageItem("key2", "baggage2"); - sofaTraceContext.push(sofaTracerSpan); - - String responseStr = new OkHttpClientInstance().executePost(httpGetUrl, - JSON.toJSONString(postBody)); - PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class); - assertEquals(postBody, resultPostBody); - - //wait for async output - List contents = FileUtils.readLines(customFileLog(OkHttpLogEnum.OK_HTTP_DIGEST - .getDefaultLogName())); - Assert.assertTrue(contents.size() > 0); - Assert.assertTrue(contents.get(0).split(",")[1].equalsIgnoreCase("test")); + + try(Scope scope = sofaTracer.scopeManager().activate(sofaTracerSpan)){ + sofaTracerSpan.setBaggageItem("key1", "baggage1"); + sofaTracerSpan.setBaggageItem("key2", "baggage2"); + String responseStr = new OkHttpClientInstance().executePost(httpGetUrl, + JSON.toJSONString(postBody)); + PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class); + assertEquals(postBody, resultPostBody); + //wait for async output + List contents = FileUtils.readLines(customFileLog(OkHttpLogEnum.OK_HTTP_DIGEST + .getDefaultLogName())); + Assert.assertTrue(contents.size() > 0); + Assert.assertTrue(contents.get(0).split(",")[1].equalsIgnoreCase("test")); + }finally { + sofaTracerSpan.finish(); + } +// sofaTracerSpan.setBaggageItem("key1", "baggage1"); +// sofaTracerSpan.setBaggageItem("key2", "baggage2"); +// sofaTraceContext.push(sofaTracerSpan); + +// String responseStr = new OkHttpClientInstance().executePost(httpGetUrl, +// JSON.toJSONString(postBody)); +// PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class); +// assertEquals(postBody, resultPostBody); +// +// //wait for async output +// List contents = FileUtils.readLines(customFileLog(OkHttpLogEnum.OK_HTTP_DIGEST +// .getDefaultLogName())); +// Assert.assertTrue(contents.size() > 0); +// Assert.assertTrue(contents.get(0).split(",")[1].equalsIgnoreCase("test")); } protected static File customFileLog(String fileName) { diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerTest.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerTest.java index 24f504d5f..1e4477a85 100644 --- a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerTest.java +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerTest.java @@ -27,6 +27,7 @@ import com.alipay.sofa.tracer.plugins.okhttp.OkHttpTracer; import com.alipay.sofa.tracer.plugins.okhttp.base.client.OkHttpClientInstance; import com.alipay.sofa.tracer.plugins.okhttp.base.controller.PostBody; +import io.opentracing.Scope; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -88,17 +89,29 @@ private void testOkHttpPost() throws Exception { String httpGetUrl = urlHttpPrefix + "/httpclient"; //baggage SofaTracer sofaTracer = OkHttpTracer.getOkHttpTracerSingleton().getSofaTracer(); - SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); + //SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); SofaTracerSpan sofaTracerSpan = (SofaTracerSpan) sofaTracer.buildSpan( "HttpClientTracer Baggage").start(); - sofaTracerSpan.setBaggageItem("key1", "baggage1"); - sofaTracerSpan.setBaggageItem("key2", "baggage2"); - sofaTraceContext.push(sofaTracerSpan); - - String responseStr = new OkHttpClientInstance().executePost(httpGetUrl, - JSON.toJSONString(postBody)); - PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class); - assertEquals(postBody, resultPostBody); + try(Scope scope = sofaTracer.scopeManager().activate(sofaTracerSpan)){ + sofaTracerSpan.setBaggageItem("key1", "baggage1"); + sofaTracerSpan.setBaggageItem("key2", "baggage2"); + String responseStr = new OkHttpClientInstance().executePost(httpGetUrl, + JSON.toJSONString(postBody)); + PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class); + assertEquals(postBody, resultPostBody); + assertEquals(sofaTracer.activeSpan(), sofaTracerSpan); + }finally { + sofaTracerSpan.finish(); + } + + + +// sofaTraceContext.push(sofaTracerSpan); +// +// String responseStr = new OkHttpClientInstance().executePost(httpGetUrl, +// JSON.toJSONString(postBody)); +// PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class); +// assertEquals(postBody, resultPostBody); } private void testOkHttpTracerUnique() { diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcSofaTracerFilter.java b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcSofaTracerFilter.java index a6d43e196..185317017 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcSofaTracerFilter.java +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcSofaTracerFilter.java @@ -24,6 +24,7 @@ import com.alipay.common.tracer.core.span.CommonSpanTags; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.utils.StringUtils; +import io.opentracing.Scope; import io.opentracing.tag.Tags; import javax.servlet.Filter; @@ -68,16 +69,16 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo int httpStatus = -1; Throwable currThrowable = null; boolean errorFlag = false; - try { - HttpServletRequest request = (HttpServletRequest) servletRequest; - HttpServletResponse response = (HttpServletResponse) servletResponse; - SofaTracerSpanContext spanContext = getSpanContextFromRequest(request); - // sr - springMvcSpan = springMvcTracer.serverReceive(spanContext); + HttpServletRequest request = (HttpServletRequest) servletRequest; + HttpServletResponse response = (HttpServletResponse) servletResponse; + SofaTracerSpanContext spanContext = getSpanContextFromRequest(request); + // sr + springMvcSpan = springMvcTracer.serverReceive(spanContext); + try(Scope scope = this.springMvcTracer.getSofaTracer().activateSpan(springMvcSpan)){ if (StringUtils.isBlank(this.appName)) { this.appName = SofaTracerConfiguration - .getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY); + .getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY); } //set service name springMvcSpan.setOperationName(request.getRequestURL().toString()); @@ -93,6 +94,8 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo //filter end httpStatus = responseWrapper.getStatus(); responseSize = responseWrapper.getContentLength(); + + } catch (Throwable t) { httpStatus = 500; errorFlag = true; diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/SofaTracer.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/SofaTracer.java index 68f8cb331..aa5f2b0cd 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/SofaTracer.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/SofaTracer.java @@ -28,16 +28,16 @@ import com.alipay.common.tracer.core.samplers.Sampler; import com.alipay.common.tracer.core.samplers.SamplerFactory; import com.alipay.common.tracer.core.samplers.SamplingStatus; +import com.alipay.common.tracer.core.scope.SofaTracerScope; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.span.SofaTracerSpanReferenceRelationship; import com.alipay.common.tracer.core.utils.AssertUtils; import com.alipay.common.tracer.core.utils.StringUtils; import com.alipay.sofa.common.code.LogCode2Description; -import io.opentracing.References; -import io.opentracing.Span; -import io.opentracing.SpanContext; -import io.opentracing.Tracer; +import io.opentracing.*; import io.opentracing.propagation.Format; +import io.opentracing.tag.Tag; +import io.opentracing.util.ThreadLocalScopeManager; import java.util.ArrayList; import java.util.Collections; @@ -56,6 +56,7 @@ */ public class SofaTracer implements Tracer { + /** * normal root spanId's default value */ @@ -86,22 +87,42 @@ public class SofaTracer implements Tracer { */ private final Sampler sampler; + private final ScopeManager scopeManager; + + protected SofaTracer(String tracerType, Reporter clientReporter, Reporter serverReporter, - Sampler sampler, Map tracerTags) { + Sampler sampler, Map tracerTags, ScopeManager scopeManager) { this.tracerType = tracerType; this.clientReporter = clientReporter; this.serverReporter = serverReporter; this.sampler = sampler; + this.scopeManager = scopeManager; if (tracerTags != null && tracerTags.size() > 0) { this.tracerTags.putAll(tracerTags); } } - protected SofaTracer(String tracerType, Sampler sampler) { + protected SofaTracer(String tracerType, Sampler sampler, ScopeManager scopeManager) { this.tracerType = tracerType; this.clientReporter = null; this.serverReporter = null; this.sampler = sampler; + this.scopeManager = scopeManager; + } + + @Override + public ScopeManager scopeManager() { + return this.scopeManager; + } + + @Override + public Span activeSpan() { + return this.scopeManager.activeSpan(); + } + + @Override + public Scope activateSpan(Span span) { + return this.scopeManager.activate(span); } @Override @@ -156,6 +177,7 @@ public void reportSpan(SofaTracerSpan span) { /** * Shuts down the {@link Reporter} and {@link Sampler} */ + @Override public void close() { if (this.clientReporter != null) { this.clientReporter.close(); @@ -224,6 +246,8 @@ public class SofaTracerSpanBuilder implements io.opentracing.Tracer.SpanBuilder private final Map tags = new HashMap<>(); + private boolean ignoreActiveSpan = false; + public SofaTracerSpanBuilder(String operationName) { this.operationName = operationName; } @@ -268,6 +292,12 @@ public Tracer.SpanBuilder addReference(String referenceType, SpanContext referen return this; } + @Override + public Tracer.SpanBuilder ignoreActiveSpan() { + this.ignoreActiveSpan = true; + return this; + } + @Override public Tracer.SpanBuilder withTag(String key, String value) { this.tags.put(key, value); @@ -286,6 +316,14 @@ public Tracer.SpanBuilder withTag(String key, Number value) { return this; } + @Override + public Tracer.SpanBuilder withTag(Tag tag, T t) { + if(tag != null && tag.getKey() != null){ + this.tags.put(tag.getKey(), t); + } + return this; + } + @Override public Tracer.SpanBuilder withStartTimestamp(long microseconds) { this.startTime = microseconds; @@ -295,6 +333,13 @@ public Tracer.SpanBuilder withStartTimestamp(long microseconds) { @Override public Span start() { SofaTracerSpanContext sofaTracerSpanContext; + //Check if active span should establish a relationship with the previous span + //Artificially specify the relationship between the currently constructed span and the currently active span + //If not specified, defaults to asChldOf + if(this.references.isEmpty() && scopeManager.activeSpan() != null && !this.ignoreActiveSpan){ + asChildOf(scopeManager.activeSpan()); + } + if (this.references != null && this.references.size() > 0) { //Parent context exist sofaTracerSpanContext = this.createChildContext(); @@ -404,6 +449,8 @@ public static final class Builder { private Sampler sampler; + private ScopeManager scopeManager = new ThreadLocalScopeManager(); + public Builder(String tracerType) { AssertUtils.isTrue(StringUtils.isNotBlank(tracerType), "tracerType must be not empty"); this.tracerType = tracerType; @@ -473,7 +520,7 @@ public SofaTracer build() { SelfLog.error(LogCode2Description.convert(SPACE_ID, "01-00002")); } return new SofaTracer(this.tracerType, this.clientReporter, this.serverReporter, - this.sampler, this.tracerTags); + this.sampler, this.tracerTags, this.scopeManager); } } } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/context/span/SofaTracerSpanContext.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/context/span/SofaTracerSpanContext.java index 5b3da3a5b..d4974e131 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/context/span/SofaTracerSpanContext.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/context/span/SofaTracerSpanContext.java @@ -131,6 +131,16 @@ public SofaTracerSpanContext addSysBaggage(Map sysBaggage) { return this; } + @Override + public String toTraceId() { + return this.traceId; + } + + @Override + public String toSpanId() { + return this.spanId; + } + /** * return both system and business baggage * @return Iterable @@ -147,6 +157,7 @@ public Iterable> baggageItems() { return allBaggage.entrySet(); } + /** * return key information string for SofaTracerSpanContext * @return diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/BinaryFormater.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/BinaryFormater.java index 72eb4a526..126703133 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/BinaryFormater.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/BinaryFormater.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; import com.alipay.common.tracer.core.utils.ByteArrayUtils; +import io.opentracing.propagation.Binary; import io.opentracing.propagation.Format; import java.nio.ByteBuffer; @@ -32,7 +33,7 @@ * @author yangguanchao * @since 2017/06/23 */ -public class BinaryFormater implements RegistryExtractorInjector { +public class BinaryFormater implements RegistryExtractorInjector { /** * As the keyword key or header identification information of the cross-process transmission field, @@ -44,16 +45,48 @@ public class BinaryFormater implements RegistryExtractorInjector { .getBytes(SofaTracerConstant.DEFAULT_UTF8_CHARSET); @Override - public Format getFormatType() { + public Format getFormatType() { return Format.Builtin.BINARY; } + + @Override + public void inject(SofaTracerSpanContext spanContext, Binary carrier) { + if (carrier == null || spanContext == null) { + return; + } + + ByteBuffer buf = carrier.injectionBuffer(64); + //head + buf.put(FORMATER_KEY_HEAD_BYTES); + String spanContextInfos = spanContext.serializeSpanContext(); + byte[] value = spanContextInfos.getBytes(SofaTracerConstant.DEFAULT_UTF8_CHARSET); + //length + buf.putInt(value.length); + //data + buf.put(value); +// +// //head +// carrier.put(FORMATER_KEY_HEAD_BYTES); +// String spanContextInfos = spanContext.serializeSpanContext(); +// byte[] value = spanContextInfos.getBytes(SofaTracerConstant.DEFAULT_UTF8_CHARSET); +// //length +// carrier.putInt(value.length); +// //data +// carrier.put(value); + } + + //new @Override - public SofaTracerSpanContext extract(ByteBuffer carrier) { - if (carrier == null || carrier.array().length < FORMATER_KEY_HEAD_BYTES.length) { + public SofaTracerSpanContext extract(Binary carrier) { + if(carrier == null) { + return SofaTracerSpanContext.rootStart(); + } + ByteBuffer buf = carrier.extractionBuffer(); + if (buf == null || buf.array().length < FORMATER_KEY_HEAD_BYTES.length) { return SofaTracerSpanContext.rootStart(); } - byte[] carrierDatas = carrier.array(); + byte[] carrierDatas = buf.array(); //head byte[] formaterKeyHeadBytes = FORMATER_KEY_HEAD_BYTES; int index = ByteArrayUtils.indexOf(carrierDatas, formaterKeyHeadBytes); @@ -62,10 +95,10 @@ public SofaTracerSpanContext extract(ByteBuffer carrier) { } try { //(UTF-8)Put the head from 0 - carrier.position(index + formaterKeyHeadBytes.length); + buf.position(index + formaterKeyHeadBytes.length); //value byte arrays - byte[] contextDataBytes = new byte[carrier.getInt()]; - carrier.get(contextDataBytes); + byte[] contextDataBytes = new byte[buf.getInt()]; + buf.get(contextDataBytes); String spanContextInfos = new String(contextDataBytes, SofaTracerConstant.DEFAULT_UTF8_CHARSET); return SofaTracerSpanContext.deserializeFromString(spanContextInfos); @@ -78,19 +111,8 @@ public SofaTracerSpanContext extract(ByteBuffer carrier) { } } - @Override - public void inject(SofaTracerSpanContext spanContext, ByteBuffer carrier) { - if (carrier == null || spanContext == null) { - return; - } - //head - carrier.put(FORMATER_KEY_HEAD_BYTES); - String spanContextInfos = spanContext.serializeSpanContext(); - byte[] value = spanContextInfos.getBytes(SofaTracerConstant.DEFAULT_UTF8_CHARSET); - //length - carrier.putInt(value.length); - //data - carrier.put(value); - } + + + } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/scope/SofaTracerScope.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/scope/SofaTracerScope.java new file mode 100644 index 000000000..e1b87b2c7 --- /dev/null +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/scope/SofaTracerScope.java @@ -0,0 +1,33 @@ +package com.alipay.common.tracer.core.scope; + +import com.alipay.common.tracer.core.SofaTracer; +import io.opentracing.Scope; +import io.opentracing.ScopeManager; +import io.opentracing.Span; + +public class SofaTracerScope implements Scope { + private final SofaTracerScopeManager scopeManager; + private final Span wrapped; + private final SofaTracerScope toRestore; + + SofaTracerScope(SofaTracerScopeManager scopeManager, Span wrapped) { + this.scopeManager = scopeManager; + this.wrapped = wrapped; + this.toRestore = scopeManager.tlsScope.get(); + scopeManager.tlsScope.set(this); + } + + @Override + public void close() { + if (scopeManager.tlsScope.get() != this) { + // This shouldn't happen if users call methods in the expected order. Bail out. + return; + } + + scopeManager.tlsScope.set(toRestore); + } + + Span span() { + return wrapped; + } +} diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/scope/SofaTracerScopeManager.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/scope/SofaTracerScopeManager.java new file mode 100644 index 000000000..715b13502 --- /dev/null +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/scope/SofaTracerScopeManager.java @@ -0,0 +1,29 @@ +package com.alipay.common.tracer.core.scope; + + +import com.alipay.common.tracer.core.span.SofaTracerSpan; +import io.opentracing.Scope; +import io.opentracing.ScopeManager; +import io.opentracing.Span; +import io.opentracing.util.ThreadLocalScope; + +public class SofaTracerScopeManager implements ScopeManager{ + final ThreadLocal tlsScope = new ThreadLocal(); + + @Override + public SofaTracerScope activate(Span span) { + return new SofaTracerScope(this, span); + } + + @Override + public Span activeSpan() { + SofaTracerScope scope = tlsScope.get(); + return scope == null ? null : scope.span(); + } + + public SofaTracerScope active(){ + return tlsScope.get(); + } +} + + diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/SofaTracerSpan.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/SofaTracerSpan.java index 91d21313d..cce8c71ba 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/SofaTracerSpan.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/SofaTracerSpan.java @@ -29,6 +29,7 @@ import com.alipay.sofa.common.code.LogCode2Description; import io.opentracing.Span; import io.opentracing.SpanContext; +import io.opentracing.tag.Tag; import io.opentracing.tag.Tags; import java.io.PrintWriter; @@ -167,7 +168,7 @@ public void finish(long endTime) { SpanExtensionFactory.logStoppedSpan(this); } - @Override + @Deprecated public void close() { this.finish(); } @@ -176,6 +177,7 @@ public void close() { public Span setTag(String key, String value) { if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) { return this; + } this.tagsWithStr.put(key, value); //to set log type by span kind type @@ -208,6 +210,28 @@ public Span setTag(String key, Number number) { return this; } + @Override + public Span setTag(Tag tag, T t) { + String key = tag.getKey(); + if(t == null){ + return this; + } + if (t instanceof String) { + this.setTag(key, (String) t); + } else if (t instanceof Boolean) { + this.setTag(key, (Boolean) t); + } else if (t instanceof Number) { + this.setTag(key, (Number) t); + } else { + SelfLog.error(String.format( + LogCode2Description.convert(SofaTracerConstant.SPACE_ID, "01-00012"), + t.getClass())); + } + + return this; + + } + @Override public Span log(String eventValue) { //log with current time @@ -242,13 +266,13 @@ public Span log(Map map) { return this.log(System.currentTimeMillis(), map); } - @Override + @Deprecated public Span log(String eventName, /* @Nullable */Object payload) { //key:value return this.log(System.currentTimeMillis(), eventName, payload); } - @Override + @Deprecated public Span log(long currentTime, String eventName, /* @Nullable */Object payload) { //key:value AssertUtils.isTrue(currentTime >= startTime, "current time must greater than start time"); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/tracer/AbstractTracer.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/tracer/AbstractTracer.java index 9bba3052a..febf8a4a3 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/tracer/AbstractTracer.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/tracer/AbstractTracer.java @@ -30,7 +30,10 @@ import com.alipay.common.tracer.core.span.LogData; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.utils.StringUtils; +import com.sun.org.apache.xerces.internal.impl.xs.models.XSCMBinOp; +import io.opentracing.Scope; import io.opentracing.tag.Tags; +import io.opentracing.util.ThreadLocalScope; import java.util.Map; @@ -108,8 +111,7 @@ protected Reporter generateReporter(AbstractSofaTracerStatisticReporter statRepo * @return a new spam */ public SofaTracerSpan clientSend(String operationName) { - SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); - SofaTracerSpan serverSpan = sofaTraceContext.pop(); + SofaTracerSpan serverSpan = (SofaTracerSpan) this.sofaTracer.scopeManager().activeSpan(); SofaTracerSpan clientSpan = null; try { clientSpan = (SofaTracerSpan) this.sofaTracer.buildSpan(operationName) @@ -134,12 +136,44 @@ public SofaTracerSpan clientSend(String operationName) { .getName()); // log clientSpan.log(LogData.CLIENT_SEND_EVENT_VALUE); - // Put into the thread context - sofaTraceContext.push(clientSpan); } } return clientSpan; } +// public SofaTracerSpan clientSend(String operationName) { +// SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); +// SofaTracerSpan serverSpan = sofaTraceContext.pop(); +// SofaTracerSpan clientSpan = null; +// try { +// clientSpan = (SofaTracerSpan) this.sofaTracer.buildSpan(operationName) +// .asChildOf(serverSpan).start(); +// // Need to actively cache your own serverSpan, because: asChildOf is concerned about spanContext +// clientSpan.setParentSofaTracerSpan(serverSpan); +// return clientSpan; +// } catch (Throwable throwable) { +// SelfLog.errorWithTraceId("Client Send Error And Restart by Root Span", throwable); +// SelfLog.flush(); +// Map bizBaggage = null; +// Map sysBaggage = null; +// if (serverSpan != null) { +// bizBaggage = serverSpan.getSofaTracerSpanContext().getBizBaggage(); +// sysBaggage = serverSpan.getSofaTracerSpanContext().getSysBaggage(); +// } +// clientSpan = this.errorRecover(bizBaggage, sysBaggage); +// } finally { +// if (clientSpan != null) { +// clientSpan.setTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); +// clientSpan.setTag(CommonSpanTags.CURRENT_THREAD_NAME, Thread.currentThread() +// .getName()); +// // log +// clientSpan.log(LogData.CLIENT_SEND_EVENT_VALUE); +// // Put into the thread context +// sofaTraceContext.push(clientSpan); +// } +// } +// return clientSpan; +// } + /** * @@ -148,19 +182,31 @@ public SofaTracerSpan clientSend(String operationName) { * @param resultCode resultCode to mark success or fail */ public void clientReceive(String resultCode) { - SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); - SofaTracerSpan clientSpan = sofaTraceContext.pop(); + SofaTracerSpan clientSpan = (SofaTracerSpan) this.sofaTracer.activeSpan(); if (clientSpan == null) { return; } // finish and to report this.clientReceiveTagFinish(clientSpan, resultCode); - // restore parent span - if (clientSpan.getParentSofaTracerSpan() != null) { - sofaTraceContext.push(clientSpan.getParentSofaTracerSpan()); - } + } +// public void clientReceive(String resultCode) { +// SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); +// SofaTracerSpan clientSpan = sofaTraceContext.pop(); +// if (clientSpan == null) { +// return; +// } +// // finish and to report +// this.clientReceiveTagFinish(clientSpan, resultCode); +// // restore parent span +// if (clientSpan.getParentSofaTracerSpan() != null) { +// sofaTraceContext.push(clientSpan.getParentSofaTracerSpan()); +// } +// } + + + /** * Span finished and append tags * @param clientSpan current finished span @@ -173,10 +219,11 @@ public void clientReceiveTagFinish(SofaTracerSpan clientSpan, String resultCode) // set resultCode clientSpan.setTag(CommonSpanTags.RESULT_CODE, resultCode); // finish client span - clientSpan.finish(); + //clientSpan.finish(); } } + /** * Stage SR , This stage will produce a new span. * @@ -196,11 +243,11 @@ public SofaTracerSpan serverReceive() { * @param sofaTracerSpanContext The context to restore * @return SofaTracerSpan */ + public SofaTracerSpan serverReceive(SofaTracerSpanContext sofaTracerSpanContext) { SofaTracerSpan newSpan = null; // pop LogContext - SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); - SofaTracerSpan serverSpan = sofaTraceContext.pop(); + SofaTracerSpan serverSpan = (SofaTracerSpan) this.sofaTracer.activeSpan(); try { if (serverSpan == null) { newSpan = (SofaTracerSpan) this.sofaTracer.buildSpan(StringUtils.EMPTY_STRING) @@ -227,36 +274,92 @@ public SofaTracerSpan serverReceive(SofaTracerSpanContext sofaTracerSpanContext) newSpan.setTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER); newSpan .setTag(CommonSpanTags.CURRENT_THREAD_NAME, Thread.currentThread().getName()); - // push to sofaTraceContext - sofaTraceContext.push(newSpan); } } return newSpan; } + +// public SofaTracerSpan serverReceive(SofaTracerSpanContext sofaTracerSpanContext) { +// SofaTracerSpan newSpan = null; +// // pop LogContext +// SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); +// SofaTracerSpan serverSpan = sofaTraceContext.pop(); +// try { +// if (serverSpan == null) { +// newSpan = (SofaTracerSpan) this.sofaTracer.buildSpan(StringUtils.EMPTY_STRING) +// .asChildOf(sofaTracerSpanContext).start(); +// } else { +// newSpan = (SofaTracerSpan) this.sofaTracer.buildSpan(StringUtils.EMPTY_STRING) +// .asChildOf(serverSpan).start(); +// } +// } catch (Throwable throwable) { +// SelfLog.errorWithTraceId("Middleware server received and restart root span", throwable); +// SelfLog.flush(); +// Map bizBaggage = null; +// Map sysBaggage = null; +// if (serverSpan != null) { +// bizBaggage = serverSpan.getSofaTracerSpanContext().getBizBaggage(); +// sysBaggage = serverSpan.getSofaTracerSpanContext().getSysBaggage(); +// } +// newSpan = this.errorRecover(bizBaggage, sysBaggage); +// } finally { +// if (newSpan != null) { +// // log +// newSpan.log(LogData.SERVER_RECV_EVENT_VALUE); +// // server tags +// newSpan.setTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER); +// newSpan +// .setTag(CommonSpanTags.CURRENT_THREAD_NAME, Thread.currentThread().getName()); +// // push to sofaTraceContext +// sofaTraceContext.push(newSpan); +// } +// } +// return newSpan; +// } + + + + /** * Stage SS, This stage will end a span * * @param resultCode */ public void serverSend(String resultCode) { - try { - SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); - SofaTracerSpan serverSpan = sofaTraceContext.pop(); - if (serverSpan == null) { - return; - } - // log - serverSpan.log(LogData.SERVER_SEND_EVENT_VALUE); - // resultCode - serverSpan.setTag(CommonSpanTags.RESULT_CODE, resultCode); - serverSpan.finish(); - } finally { - // clear TreadLocalContext - this.clearTreadLocalContext(); + SofaTracerSpan serverSpan = (SofaTracerSpan) this.sofaTracer.activeSpan(); + if (serverSpan == null) { + return; } + // log + serverSpan.log(LogData.SERVER_SEND_EVENT_VALUE); + // resultCode + serverSpan.setTag(CommonSpanTags.RESULT_CODE, resultCode); + serverSpan.finish(); } +// public void serverSend(String resultCode) { +// try { +// SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); +// SofaTracerSpan serverSpan = sofaTraceContext.pop(); +// if (serverSpan == null) { +// return; +// } +// // log +// serverSpan.log(LogData.SERVER_SEND_EVENT_VALUE); +// // resultCode +// serverSpan.setTag(CommonSpanTags.RESULT_CODE, resultCode); +// serverSpan.finish(); +// } finally { +// // clear TreadLocalContext +// this.clearTreadLocalContext(); +// } +// } + + + + + protected SofaTracerSpan genSeverSpanInstance(long startTime, String operationName, SofaTracerSpanContext sofaTracerSpanContext, Map tags) { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/context/trace/SofaTracerThreadLocalTraceContextTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/context/trace/SofaTracerThreadLocalTraceContextTest.java index 7dc95f826..6be5c5632 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/context/trace/SofaTracerThreadLocalTraceContextTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/context/trace/SofaTracerThreadLocalTraceContextTest.java @@ -19,6 +19,8 @@ import com.alipay.common.tracer.core.SofaTracer; import com.alipay.common.tracer.core.holder.SofaTraceContextHolder; import com.alipay.common.tracer.core.span.SofaTracerSpan; +import io.opentracing.Scope; +import io.opentracing.util.ThreadLocalScope; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -67,4 +69,16 @@ public void testPushPop() throws Exception { assertTrue(sofaTraceContext.isEmpty()); } + + //new--test + @Test + public void testScopePushPop() throws Exception{ + SofaTracerSpan sofaTracerSpan = (SofaTracerSpan) this.sofaTracer.buildSpan("op").start(); + try(Scope scope = this.sofaTracer.scopeManager().activate(sofaTracerSpan)){ + //assertEquals(sofaTracerSpan.context().toTraceId(), ); + } + } + + + } diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/BinaryCarrierTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/BinaryCarrierTest.java new file mode 100644 index 000000000..c641e248a --- /dev/null +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/BinaryCarrierTest.java @@ -0,0 +1,33 @@ +package com.alipay.common.tracer.core.registry; + +import io.opentracing.propagation.Binary; + +import java.nio.ByteBuffer; + +public class BinaryCarrierTest implements Binary { + + ByteBuffer buffer = null; + + public BinaryCarrierTest(ByteBuffer buffer) { + this.buffer = buffer; + } + + public BinaryCarrierTest(){ + + } + @Override + public ByteBuffer injectionBuffer(int length) { + if (length < 1) { + throw new IllegalArgumentException("length must be greater than zero"); + } + if (buffer == null) { + buffer = ByteBuffer.allocate(length); + } + return buffer; + } + + @Override + public ByteBuffer extractionBuffer() { + return buffer; + } +} diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/BinaryFormaterTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/BinaryFormaterTest.java index 0e7bf3424..86ee54fe4 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/BinaryFormaterTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/BinaryFormaterTest.java @@ -19,6 +19,7 @@ import com.alipay.common.tracer.core.SofaTracer; import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; +import io.opentracing.propagation.Binary; import io.opentracing.propagation.Format; import org.junit.After; import org.junit.Assert; @@ -41,7 +42,7 @@ */ public class BinaryFormaterTest { - private RegistryExtractorInjector registryExtractorInjector; + private RegistryExtractorInjector registryExtractorInjector; @Before public void before() throws Exception { @@ -77,13 +78,15 @@ public void testGetFormatType() throws Exception { */ @Test public void testExtractCarrier() throws Exception { - ByteBuffer carrierNull = null; + //ByteBuffer carrierNull = null; + BinaryCarrierTest carrierNull = new BinaryCarrierTest(); SofaTracerSpanContext extractContext = this.registryExtractorInjector.extract(carrierNull); assertTrue(extractContext.toString(), extractContext.getSpanId().equals(SofaTracer.ROOT_SPAN_ID)); ByteBuffer carrier = ByteBuffer.allocate(4); - SofaTracerSpanContext extractContextAllo = this.registryExtractorInjector.extract(carrier); + BinaryCarrierTest bct = new BinaryCarrierTest(carrier); + SofaTracerSpanContext extractContextAllo = this.registryExtractorInjector.extract(bct); assertEquals(extractContextAllo.toString(), SofaTracer.ROOT_SPAN_ID, extractContextAllo.getSpanId()); } @@ -105,9 +108,10 @@ public void testExtract() throws Exception { //inject //200 bytes ByteBuffer carrier = ByteBuffer.allocate(400); - this.registryExtractorInjector.inject(spanContext, carrier); + BinaryCarrierTest bct = new BinaryCarrierTest(carrier); + this.registryExtractorInjector.inject(spanContext, bct); //extract - SofaTracerSpanContext extractContext = this.registryExtractorInjector.extract(carrier); + SofaTracerSpanContext extractContext = this.registryExtractorInjector.extract(bct); //traceid spanId sampled extractContext.equals(spanContext); assertTrue("Extract baggage : " + extractContext.getBizBaggage(), @@ -137,13 +141,14 @@ public void testExtractInject() throws Exception { //inject //200 bytes ByteBuffer carrier = ByteBuffer.allocate(400); + BinaryCarrierTest bct = new BinaryCarrierTest(carrier); //Put some data in advance to test String header = "index_=testSOFATracerInject"; byte[] headerBytes = header.getBytes(SofaTracerConstant.DEFAULT_UTF8_CHARSET); carrier.put(headerBytes); - this.registryExtractorInjector.inject(spanContext, carrier); + this.registryExtractorInjector.inject(spanContext, bct); //extract - SofaTracerSpanContext extractContext = this.registryExtractorInjector.extract(carrier); + SofaTracerSpanContext extractContext = this.registryExtractorInjector.extract(bct); //traceid spanId sampled extractContext.equals(spanContext); assertTrue("Extract baggage : " + extractContext.getBizBaggage(), @@ -170,11 +175,12 @@ public void testDirectByteBufferExtractInjectException() throws Exception { //inject //200 bytes ByteBuffer carrier = ByteBuffer.allocateDirect(200); - this.registryExtractorInjector.inject(spanContext, carrier); + BinaryCarrierTest bct = new BinaryCarrierTest(carrier); + this.registryExtractorInjector.inject(spanContext, bct); //extract boolean isException = false; try { - this.registryExtractorInjector.extract(carrier); + this.registryExtractorInjector.extract(bct); } catch (UnsupportedOperationException exception) { isException = true; } diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/tracer/AbstractClientTracerTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracer/AbstractClientTracerTest.java index 9e0aedf11..23abd4877 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/tracer/AbstractClientTracerTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracer/AbstractClientTracerTest.java @@ -39,6 +39,7 @@ public void init() { clientTracer = new TestClientTracer("springmvc"); } + @Test public void getServerDigestReporterLogName() { String serverDigestReporterLogName = clientTracer.getServerDigestReporterLogName(); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/tracer/AbstractServerTracerTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracer/AbstractServerTracerTest.java index 03d213477..912e33dea 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/tracer/AbstractServerTracerTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracer/AbstractServerTracerTest.java @@ -21,6 +21,7 @@ import com.alipay.common.tracer.core.holder.SofaTraceContextHolder; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.span.SofaTracerSpan; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -90,6 +91,20 @@ public void testServerReceive_sofaTracerSpanContext() { Assert.assertTrue(sofaTracerSpan.getSofaTracerSpanContext().isSampled()); } + @Test + public void testDec(){ + SofaTracerSpanContext sofaTracerSpanContext1 = new SofaTracerSpanContext("123", "0"); + SofaTracerSpanContext sofaTracerSpanContext2 = new SofaTracerSpanContext("124", "1"); + System.out.println(sofaTracerSpanContext1.equals(sofaTracerSpanContext2)); + } + + @Test + public void simulateClientCommunicationServer(){ + + } + + + @Test public void generateClientStatReporter() { //user super method diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/ScopeTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/ScopeTest.java new file mode 100644 index 000000000..fd723d0d0 --- /dev/null +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/ScopeTest.java @@ -0,0 +1,136 @@ +package com.alipay.common.tracer.core.tracertest; + +import com.alipay.common.tracer.core.SofaTracer; +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.reporter.digest.DiskReporterImpl; +import com.alipay.common.tracer.core.reporter.facade.Reporter; +import com.alipay.common.tracer.core.samplers.Sampler; +import com.alipay.common.tracer.core.samplers.SofaTracerPercentageBasedSampler; +import com.alipay.common.tracer.core.span.CommonSpanTags; +import com.alipay.common.tracer.core.span.LogData; +import com.alipay.common.tracer.core.span.SofaTracerSpan; +import com.alipay.common.tracer.core.tracertest.encoder.ClientSpanEncoder; +import com.alipay.common.tracer.core.tracertest.encoder.ServerSpanEncoder; +import com.alipay.common.tracer.core.tracertest.type.TracerTestLogEnum; +import io.opentracing.References; +import io.opentracing.Scope; +import io.opentracing.Span; +import io.opentracing.tag.Tags; +import org.junit.Before; +import org.junit.Test; + + +import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class ScopeTest { + private final String tracerType = "TracerTestService"; + private final String tracerGlobalTagKey = "tracerkey"; + private final String tracerGlobalTagValue = "tracervalue"; + private SofaTracer sofaTracer; + + @Before + public void beforeInstance(){ + SofaTracerConfiguration.setProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY, + SofaTracerPercentageBasedSampler.TYPE); + SofaTracerConfiguration.setProperty( + SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY, "100"); + + //client + DiskReporterImpl clientReporter = new DiskReporterImpl( + TracerTestLogEnum.RPC_CLIENT.getDefaultLogName(), new ClientSpanEncoder()); + + //server + DiskReporterImpl serverReporter = new DiskReporterImpl( + TracerTestLogEnum.RPC_SERVER.getDefaultLogName(), new ServerSpanEncoder()); + this.sofaTracer = new SofaTracer.Builder(tracerType) + .withClientReporter(clientReporter) + .withServerReporter(serverReporter) + .build(); + } + + @Test + public void testActiveSpan(){ + SofaTracerSpan sofaTracerSpan = (SofaTracerSpan) this.sofaTracer.buildSpan("testActiveSpan").start(); + try(Scope scope = this.sofaTracer.scopeManager().activate(sofaTracerSpan)){ + assertEquals(sofaTracerSpan, this.sofaTracer.activeSpan()); + }finally { + sofaTracerSpan.finish(); + } + } + + @Test + public void testActivateSpan(){ + SofaTracerSpan sofaTracerSpan = (SofaTracerSpan) this.sofaTracer.buildSpan("testActivateSpan").start(); + this.sofaTracer.activateSpan(sofaTracerSpan); + assertEquals(sofaTracerSpan, this.sofaTracer.activeSpan()); + } + + @Test + public void testActiveSpanPropagation(){ + SofaTracerSpan sofaTracerSpan = (SofaTracerSpan) this.sofaTracer.buildSpan("parent").start(); + try(Scope scope = this.sofaTracer.activateSpan(sofaTracerSpan)){ + assertEquals(sofaTracerSpan, this.sofaTracer.scopeManager().activeSpan()); + }finally { + sofaTracerSpan.finish(); + } + } + + + @Test + public void testActiveSpanAutoReference() { + SofaTracerSpan parent = (SofaTracerSpan) this.sofaTracer.buildSpan("parent").start(); + try (Scope scope = this.sofaTracer.activateSpan(parent)) { + SofaTracerSpan child = (SofaTracerSpan) this.sofaTracer.buildSpan("child").start(); + child.finish(); + assertEquals(References.CHILD_OF, child.getSpanReferences().get(0).getReferenceType()); + + } finally { + parent.finish(); + } + + } + + @Test + public void testIgnoreActiveSpan(){ + SofaTracerSpan parentSpan = (SofaTracerSpan) this.sofaTracer.buildSpan("parent") + .start(); + try(Scope scope = this.sofaTracer.activateSpan(parentSpan)){ + assertEquals(this.sofaTracer.activeSpan(), parentSpan); + SofaTracerSpan sonSpan = (SofaTracerSpan) this.sofaTracer.buildSpan("child"). + ignoreActiveSpan().start(); + sonSpan.finish(); + assertEquals(sonSpan.getSpanReferences().size(),0); + SofaTracerSpan daughterSpan = (SofaTracerSpan) this.sofaTracer.buildSpan("child").start(); + daughterSpan.finish(); + assertEquals(daughterSpan.getSpanReferences().size(),1); + }finally { + parentSpan.finish(); + } + } + + + + + @Test + public void testContextScope(){ + SofaTracer tracer = new SofaTracer.Builder(tracerType) + .build(); + SofaTracerSpan sofaTracerSpan = (SofaTracerSpan) tracer.buildSpan("parent").start(); + try(Scope scope = tracer.activateSpan(sofaTracerSpan)){ + assertEquals(sofaTracerSpan, tracer.scopeManager().activeSpan()); + }finally { + sofaTracerSpan.finish(); + } + } + + + + + + + + +} diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/SofaTracerTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/SofaTracerTest.java index f3d4900f9..3784349e8 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/SofaTracerTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/SofaTracerTest.java @@ -331,16 +331,19 @@ public void testAsChildOfMultiParentSpan() { .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).start(); String parentTraceID = spanParent.getSofaTracerSpanContext().getTraceId(); String parentSpanId = spanParent.getSofaTracerSpanContext().getSpanId(); + //follow SofaTracerSpan spanFollow = (SofaTracerSpan) this.sofaTracer.buildSpan("spanFollow") .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).start(); String followTraceId = spanFollow.getSofaTracerSpanContext().getTraceId(); String followSpanId = spanFollow.getSofaTracerSpanContext().getSpanId(); + //parent1 SofaTracerSpan spanParent1 = (SofaTracerSpan) this.sofaTracer.buildSpan("spanParent1") .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).start(); String p1TraceId = spanParent1.getSofaTracerSpanContext().getTraceId(); String p1SpanId = spanParent1.getSofaTracerSpanContext().getSpanId(); + //assert assertTrue("Parent1 --> TraceId : " + p1TraceId + ", spanId : " + p1SpanId, SofaTracer.ROOT_SPAN_ID.equals(parentSpanId) && parentSpanId.equals(followSpanId) @@ -369,6 +372,7 @@ public void testAsChildOfMultiParentSpan() { .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).start(); String grandsonTraceid = grandsonSpan.getSofaTracerSpanContext().getTraceId(); String grandsonSpanId = grandsonSpan.getSofaTracerSpanContext().getSpanId(); + //check traceId assertEquals("Grandson --> TraceId : " + grandsonTraceid + ", Grandson spanId :" + grandsonSpanId, childTraceid, parentTraceID);