From f72580858d7b60c88f4c4e6e62687a8953621a41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Wed, 12 Dec 2018 15:59:30 +0800 Subject: [PATCH 01/24] =?UTF-8?q?1=E3=80=81=E5=8D=87=E7=BA=A7zipkin?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E5=80=BC=E6=9C=80=E6=96=B0=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=8Cui=E6=94=AF=E6=8C=81=E4=B8=AD=E6=96=87=EF=BC=9B2?= =?UTF-8?q?=E3=80=81=E4=BF=AE=E5=A4=8D=E6=A8=A1=E5=9E=8B=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E4=B8=80=E4=BA=9Bbug=EF=BC=8C=E5=8E=BB?= =?UTF-8?q?=E9=99=A4=E5=AF=B9RPC=E7=B1=BB=E5=9E=8B=E7=9A=84=E7=89=B9?= =?UTF-8?q?=E6=AE=8A=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91=EF=BC=9B3?= =?UTF-8?q?=E3=80=81=E4=BF=AE=E5=A4=8DEndpoint=E8=AE=A1=E7=AE=97=E9=80=BB?= =?UTF-8?q?=E8=BE=91=EF=BC=9B4=E3=80=81=E5=AF=B9=E4=BA=8Ezipkin=E4=B8=AD?= =?UTF-8?q?=E7=9A=84serviceName=E8=B5=8B=E5=80=BC=EF=BC=8C=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E6=8C=89=E6=9C=8D=E5=8A=A1=E8=8A=82=E7=82=B9=E4=BD=9C?= =?UTF-8?q?=E4=B8=BAserviceName=EF=BC=8C=E4=B8=8D=E5=9C=A8=E4=BE=9D?= =?UTF-8?q?=E8=B5=96span=E7=9A=84oparetionName?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sofa-tracer-zipkin-plugin/pom.xml | 91 ++++++ .../zipkin/ZipkinV2SpanAdapterTest.java | 78 +++++ .../tracer-sample-with-zipkin/README.md | 4 +- .../tracer-sample-with-zipkin/pom.xml | 4 +- tracer-sofa-boot-starter/pom.xml | 4 +- .../ZipkinSofaTracerSpanRemoteReporter.java | 268 +++++++----------- 6 files changed, 277 insertions(+), 172 deletions(-) create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/spring/zipkin/ZipkinV2SpanAdapterTest.java diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml new file mode 100644 index 00000000..ecdd5fd9 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml @@ -0,0 +1,91 @@ + + + + tracer-all-parent + com.alipay.sofa + 2.3.0-SNAPSHOT + ../../pom.xml + + 4.0.0 + + sofa-tracer-zipkin-plugin + + + org.springframework + spring-beans + + + org.springframework + spring-web + + + + io.zipkin.zipkin2 + zipkin + 2.11.12 + + + io.zipkin.reporter2 + zipkin-reporter + 2.7.13 + + + com.alipay.sofa + tracer-core + + + com.alipay.sofa + tracer-extensions + + + org.springframework + spring-context + + + + org.jmockit + jmockit + test + + + org.mockito + mockito-core + test + + + org.jmockit + jmockit-coverage + test + + + junit + junit + test + + + commons-io + commons-io + test + + + org.springframework.boot + spring-boot-starter-web + test + + + com.alibaba + fastjson + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/spring/zipkin/ZipkinV2SpanAdapterTest.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/spring/zipkin/ZipkinV2SpanAdapterTest.java new file mode 100644 index 00000000..e80a4293 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/spring/zipkin/ZipkinV2SpanAdapterTest.java @@ -0,0 +1,78 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.spring.zipkin; + +import com.alipay.common.tracer.core.SofaTracer; +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.sofa.tracer.spring.zipkin.adapter.ZipkinV2SpanAdapter; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import zipkin2.Span; +import java.util.HashMap; +import java.util.Map; + +/** + * ZipkinV2SpanAdapterTest + * + * @author: guolei.sgl + * @since: v2.3.0 + **/ +public class ZipkinV2SpanAdapterTest { + + private ZipkinV2SpanAdapter zipkinV2SpanAdapter = new ZipkinV2SpanAdapter(); + + private final String tracerType = "SofaTracerSpanTest"; + + private SofaTracer sofaTracer; + + private SofaTracerSpan sofaTracerSpan; + + @Before + public void init() throws InterruptedException { + sofaTracer = new SofaTracer.Builder(tracerType).withTag("tracer", "SofaTraceZipkinTest") + .build(); + sofaTracerSpan = (SofaTracerSpan) this.sofaTracer.buildSpan("SofaTracerSpanTest").start(); + sofaTracerSpan.setTag("tagsStrkey", "tagsStrVal"); + sofaTracerSpan.setTag("tagsBooleankey", true); + sofaTracerSpan.setTag("tagsBooleankey", 2018); + sofaTracerSpan.setBaggageItem("baggageKey", "baggageVal"); + sofaTracerSpan.setTag(CommonSpanTags.LOCAL_APP, "SofaTracerSpanTest"); + Map logMap = new HashMap(); + logMap.put("logKey", "logVal"); + LogData logData = new LogData(System.currentTimeMillis(), logMap); + sofaTracerSpan.log(logData); + // mock process + Thread.sleep(30); + sofaTracerSpan.setEndTime(System.currentTimeMillis()); + } + + @Test + public void testConvertToZipkinSpan() { + Span span = zipkinV2SpanAdapter.convertToZipkinSpan(sofaTracerSpan); + Assert.assertTrue(span != null); + Assert.assertTrue(span.name().equalsIgnoreCase(sofaTracerSpan.getOperationName())); + Assert.assertTrue(span.tags().size() == 4); + // zipkin's tracerId will be high position 0 + Assert.assertTrue(span.traceId().contains( + sofaTracerSpan.getSofaTracerSpanContext().getTraceId())); + Assert + .assertTrue(span.localEndpoint().serviceName().equalsIgnoreCase("SofaTracerSpanTest")); + } +} diff --git a/tracer-samples/tracer-sample-with-zipkin/README.md b/tracer-samples/tracer-sample-with-zipkin/README.md index 145f4eee..5700e72a 100644 --- a/tracer-samples/tracer-sample-with-zipkin/README.md +++ b/tracer-samples/tracer-sample-with-zipkin/README.md @@ -62,12 +62,12 @@ logging.path=./logs io.zipkin.zipkin2 zipkin - 2.11.1 + 2.11.12 io.zipkin.reporter2 zipkin-reporter - 2.7.7 + 2.7.13 ``` diff --git a/tracer-samples/tracer-sample-with-zipkin/pom.xml b/tracer-samples/tracer-sample-with-zipkin/pom.xml index 6bc439ba..241f1572 100644 --- a/tracer-samples/tracer-sample-with-zipkin/pom.xml +++ b/tracer-samples/tracer-sample-with-zipkin/pom.xml @@ -25,12 +25,12 @@ io.zipkin.zipkin2 zipkin - 2.11.1 + 2.11.12 io.zipkin.reporter2 zipkin-reporter - 2.7.7 + 2.7.13 org.springframework.boot diff --git a/tracer-sofa-boot-starter/pom.xml b/tracer-sofa-boot-starter/pom.xml index 539434c4..4a6419ea 100644 --- a/tracer-sofa-boot-starter/pom.xml +++ b/tracer-sofa-boot-starter/pom.xml @@ -68,13 +68,13 @@ io.zipkin.zipkin2 zipkin - 2.11.3 + 2.11.12 true io.zipkin.reporter2 zipkin-reporter - 2.7.7 + 2.7.13 true diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporter.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporter.java index 3536aa2f..cac45f11 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporter.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporter.java @@ -14,147 +14,108 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alipay.sofa.tracer.boot.zipkin; +package com.alipay.sofa.tracer.spring.zipkin.adapter; import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; -import com.alipay.common.tracer.core.listener.SpanReportListener; +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.utils.StringUtils; -import com.alipay.common.tracer.core.utils.TracerUtils; -import com.alipay.sofa.tracer.boot.zipkin.sender.ZipkinRestTemplateSender; -import org.springframework.util.Assert; -import org.springframework.web.client.RestTemplate; +import io.opentracing.tag.Tags; import zipkin2.Endpoint; import zipkin2.Span; -import zipkin2.reporter.AsyncReporter; -import java.io.Closeable; -import java.io.Flushable; -import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.Map; -/** - * ZipkinSofaTracerSpanRemoteReporter report {@link SofaTracerSpan} to Zipkin - * - * @author yangguanchao - * @since 2018/05/01 +/*** + * ZipkinV2SpanAdapter : convent sofaTracer span model to zipkin span model + * @author guolei.sgl 05/09/2018 + * @since v.2.3.0 */ -public class ZipkinSofaTracerSpanRemoteReporter implements SpanReportListener, Flushable, Closeable { - - private static String processId = TracerUtils.getPID(); - - private final ZipkinRestTemplateSender sender; +public class ZipkinV2SpanAdapter { - private final AsyncReporter delegate; - - private static final String SOFARPC_TRACER_TYPE = "RPC_TRACER"; - - /*** + /** * cache and performance improve */ - private int ipAddressInt = -1; - - public ZipkinSofaTracerSpanRemoteReporter(RestTemplate restTemplate, String baseUrl) { - this.sender = new ZipkinRestTemplateSender(restTemplate, baseUrl); - this.delegate = AsyncReporter.create(sender); - } - - @Override - public void onSpanReport(SofaTracerSpan span) { - if (span == null) { - return; - } - //convert - Span zipkinSpan = convertToZipkinSpan(span); - this.delegate.report(zipkinSpan); - } - - @Override - public void flush() throws IOException { - this.delegate.flush(); - } - - @Override - public void close() { - this.delegate.close(); - } + private int ipAddressInt = -1; /** * convent sofaTracerSpan model to zipKinSpan model - * @param sofaTracerSpan - * @return + * @param sofaTracerSpan original span + * @return zipkinSpan model */ - private Span convertToZipkinSpan(SofaTracerSpan sofaTracerSpan) { + public Span convertToZipkinSpan(SofaTracerSpan sofaTracerSpan) { + if (sofaTracerSpan == null) { + return null; + } + // spanId、parentId、tracerId Span.Builder zipkinSpanBuilder = Span.newBuilder(); - zipkinSpanBuilder.timestamp(sofaTracerSpan.getStartTime() * 1000); - // Zipkin is in nanosecond cr-cs - zipkinSpanBuilder - .duration((sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime()) * 1000); - //Annotations - Endpoint endpoint = getZipkinEndpoint(sofaTracerSpan.getOperationName()); - this.addZipkinAnnotations(zipkinSpanBuilder, sofaTracerSpan, endpoint); - this.addZipkinBinaryAnnotationsWithTags(zipkinSpanBuilder, sofaTracerSpan); - this.addZipkinBinaryAnnotationsWithBaggage(zipkinSpanBuilder, sofaTracerSpan); - //traceId - SofaTracerSpanContext sofaTracerSpanContext = sofaTracerSpan.getSofaTracerSpanContext(); - // get current span's parentSpan - SofaTracerSpan parentSofaTracerSpan = sofaTracerSpan.getParentSofaTracerSpan(); - /** - * Changes: - * 1.From using zipkin span's traceId alone, to using both traceid and traceIdHigh - * 2.From using part of SpanContext's traceId as radix 10, to using full traceId as hexadecimal(radix 16) - * So that the traceId in the zipkin trace data is consistent with the traceId in the application log files. - * - * 3.When traceId is received from the previous node, the original algorithm will not be able to cut - * off the pid in tail of the traceId, because it does not know the pid of the sender. - * resulting in over range when convert it to long type. - */ + SofaTracerSpanContext context = sofaTracerSpan.getSofaTracerSpanContext(); + zipkinSpanBuilder.traceId(context.getTraceId()); + zipkinSpanBuilder.id(spanIdToLong(context.getSpanId())); + if (StringUtils.isNotBlank(context.getParentId())) { + zipkinSpanBuilder.parentId(spanIdToLong(context.getParentId())); + } - // v2 span model will padLeft automatic - zipkinSpanBuilder.traceId(sofaTracerSpanContext.getTraceId()); - String parentSpanId = sofaTracerSpanContext.getParentId(); - // convent parentSpanId - if (sofaTracerSpan.isServer() && parentSpanId != null - && StringUtils.isNotBlank(parentSpanId)) { - // v2 span model Unsets the {@link Span#parentId()} if the input is 0. - zipkinSpanBuilder.parentId(spanIdToLong(parentSpanId)); - } else if (parentSofaTracerSpan != null) { - SofaTracerSpanContext parentSofaTracerSpanContext = parentSofaTracerSpan - .getSofaTracerSpanContext(); - if (parentSofaTracerSpanContext != null) { - parentSpanId = parentSofaTracerSpanContext.getSpanId(); - if (parentSpanId != null && StringUtils.isNotBlank(parentSpanId)) { - zipkinSpanBuilder.parentId(spanIdToLong(parentSpanId)); - } - } + // timestamp & duration + long start = sofaTracerSpan.getStartTime() * 1000; + long finish = sofaTracerSpan.getEndTime() * 1000; + zipkinSpanBuilder.timestamp(start); + zipkinSpanBuilder.duration(finish - start); + + // kind + Map tagsWithStr = sofaTracerSpan.getTagsWithStr(); + String kindStr = tagsWithStr.get(Tags.SPAN_KIND.getKey()); + if (StringUtils.isNotBlank(kindStr) && kindStr.equals(Tags.SPAN_KIND_SERVER)) { + zipkinSpanBuilder.kind(Span.Kind.SERVER); + } else { + zipkinSpanBuilder.kind(Span.Kind.CLIENT); } - //convent spanId - String spanId = sofaTracerSpanContext.getSpanId(); - zipkinSpanBuilder.id(spanIdToLong(spanId)); - //convent span.kind - zipkinSpanBuilder.kind(sofaTracerSpan.isClient() ? Span.Kind.CLIENT : Span.Kind.SERVER); - //convent name + + // Endpoint + Endpoint endpoint = getZipkinEndpoint(sofaTracerSpan); + zipkinSpanBuilder.localEndpoint(endpoint); + + // Tags + this.addZipkinTags(zipkinSpanBuilder, sofaTracerSpan); + + // span name String operationName = sofaTracerSpan.getOperationName(); if (StringUtils.isNotBlank(operationName)) { zipkinSpanBuilder.name(operationName); } else { zipkinSpanBuilder.name(StringUtils.EMPTY_STRING); } - // adapter SOFARPC span model - if (SOFARPC_TRACER_TYPE.equals(sofaTracerSpan.getSofaTracer().getTracerType())) { - //if current span's kind is rpcClient,set localEndpoint by parentSofaTracerSpan's operationName - if (sofaTracerSpan.isClient() && parentSofaTracerSpan != null) { - zipkinSpanBuilder.localEndpoint(getZipkinEndpoint(parentSofaTracerSpan - .getOperationName())); - } - } + + // Annotations + this.addZipkinAnnotations(zipkinSpanBuilder, sofaTracerSpan); + return zipkinSpanBuilder.build(); } - private Endpoint getZipkinEndpoint(String operationName) { + public static long spanIdToLong(String spanId) { + return FNV64HashCode(spanId); + } + + /** + * from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash + * @param data String data + * @return fnv hash code + */ + public static long FNV64HashCode(String data) { + //hash FNVHash64 : http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param + long hash = 0xcbf29ce484222325L; + for (int i = 0; i < data.length(); ++i) { + char c = data.charAt(i); + hash ^= c; + hash *= 0x100000001b3L; + } + return hash; + } + + private Endpoint getZipkinEndpoint(SofaTracerSpan span) { InetAddress ipAddress = null; if (this.ipAddressInt <= 0) { try { @@ -165,25 +126,16 @@ private Endpoint getZipkinEndpoint(String operationName) { this.ipAddressInt = 256 * 256 * 256 * 127 + 1; } } - return Endpoint.newBuilder().serviceName(operationName).ip(ipAddress).build(); + String appName = span.getTagsWithStr().get(CommonSpanTags.LOCAL_APP); + return Endpoint.newBuilder().serviceName(appName).ip(ipAddress).build(); } /** - * Adds binary annotation from the Open Tracing Span + * 将Baggage中的数据也放在tags中 + * @param zipkinSpan + * @param span */ - private void addZipkinBinaryAnnotationsWithTags(Span.Builder zipkinSpan, SofaTracerSpan span) { - for (Map.Entry e : span.getTagsWithStr().entrySet()) { - zipkinSpan.putTag(e.getKey(), e.getValue()); - } - for (Map.Entry e : span.getTagsWithNumber().entrySet()) { - zipkinSpan.putTag(e.getKey(), e.getValue().toString()); - } - for (Map.Entry e : span.getTagsWithBool().entrySet()) { - zipkinSpan.putTag(e.getKey(), e.getValue().toString()); - } - } - - private void addZipkinBinaryAnnotationsWithBaggage(Span.Builder zipkinSpan, SofaTracerSpan span) { + private void addZipkinTagsWithBaggage(Span.Builder zipkinSpan, SofaTracerSpan span) { SofaTracerSpanContext sofaTracerSpanContext = span.getSofaTracerSpanContext(); if (sofaTracerSpanContext != null) { Map sysBaggage = sofaTracerSpanContext.getSysBaggage(); @@ -197,62 +149,46 @@ private void addZipkinBinaryAnnotationsWithBaggage(Span.Builder zipkinSpan, Sofa } } - private void addZipkinAnnotations(Span.Builder zipkinSpan, SofaTracerSpan span, - Endpoint endpoint) { + /** + * convent Annotations + * @param zipkinSpan + * @param span + */ + private void addZipkinAnnotations(Span.Builder zipkinSpan, SofaTracerSpan span) { for (LogData logData : span.getLogs()) { Map fields = logData.getFields(); if (fields == null || fields.size() <= 0) { continue; } for (Map.Entry entry : fields.entrySet()) { - zipkinSpan.addAnnotation(logData.getTime() * 1000, entry.getValue().toString()) - .localEndpoint(endpoint); + // zipkin has been support default log event depend on span kind & serviceName + if (!(entry.getValue().toString().equals(LogData.CLIENT_RECV_EVENT_VALUE) + || entry.getValue().toString().equals(LogData.CLIENT_SEND_EVENT_VALUE) + || entry.getValue().toString().equals(LogData.SERVER_RECV_EVENT_VALUE) || entry + .getValue().toString().equals(LogData.SERVER_SEND_EVENT_VALUE))) { + zipkinSpan.addAnnotation(logData.getTime() * 1000, entry.getValue().toString()); + } } } } - public static long spanIdToLong(String spanId) { - return FNV64HashCode(spanId); - } - /** - * from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash - * @param data String data - * @return fnv hash code + * convent tags + * @param zipkinSpan + * @param span */ - public static long FNV64HashCode(String data) { - //hash FNVHash64 : http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param - long hash = 0xcbf29ce484222325L; - for (int i = 0; i < data.length(); ++i) { - char c = data.charAt(i); - hash ^= c; - hash *= 0x100000001b3L; - } - return hash; - } + private void addZipkinTags(Span.Builder zipkinSpan, SofaTracerSpan span) { - /*** - * 功能:将 16 进制字符串转换为:十进制整数 - * @param hexString 16 进制字符串 - * @return 十进制整数 - */ - public static long traceIdToId(String hexString) { - Assert.hasText(hexString, "Can't convert empty hex string to long"); - int length = hexString.length(); - if (length < 1) { - throw new IllegalArgumentException("Malformed id(length must be more than zero): " - + hexString); + for (Map.Entry e : span.getTagsWithStr().entrySet()) { + zipkinSpan.putTag(e.getKey(), e.getValue()); } - if (length <= 8) { - //hex - return Long.parseLong(hexString, 16); - } else if (hexString.endsWith(processId)) { - //time - return Long.parseLong(hexString.substring(8, hexString.lastIndexOf(processId)), 10); - } else { - //delete ip and processor id - return Long.parseLong(hexString.substring(8), 10); + for (Map.Entry e : span.getTagsWithNumber().entrySet()) { + zipkinSpan.putTag(e.getKey(), e.getValue().toString()); + } + for (Map.Entry e : span.getTagsWithBool().entrySet()) { + zipkinSpan.putTag(e.getKey(), e.getValue().toString()); } - } + addZipkinTagsWithBaggage(zipkinSpan, span); + } } From 4235fa1bda3c3069a7ac7202f28631cc2ad6fc59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Thu, 13 Dec 2018 11:54:47 +0800 Subject: [PATCH 02/24] rename zipkin's base package name to com.alipay.sofa.tracer.plugins.zipkin --- ...ipkinSofaTracerRestTemplateCustomizer.java | 68 ++++++ .../ZipkinSofaTracerSpanRemoteReporter.java | 96 +++++++++ .../zipkin/adapter/ZipkinV2SpanAdapter.java | 194 ++++++++++++++++++ .../initialize/ZipkinReportRegisterBean.java | 71 +++++++ .../zipkin/properties/ZipkinProperties.java | 30 +++ .../sender/ZipkinRestTemplateSender.java | 81 ++++++++ .../zipkin/ZipkinReportRegisterBeanTest.java | 48 +++++ .../zipkin/ZipkinRestTemplateSenderTest.java | 81 ++++++++ ...ipkinSofaTracerSpanRemoteReporterTest.java | 40 ++++ .../zipkin/ZipkinV2SpanAdapterTest.java | 4 +- .../src/test/resources/spring-bean.xml | 18 ++ .../ZipkinSofaTracerAutoConfiguration.java | 21 +- ...ipkinSofaTracerSpanRemoteReporterTest.java | 25 ++- .../boot/zipkin/mock/MockAbstractTracer.java | 2 +- 14 files changed, 756 insertions(+), 23 deletions(-) create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerRestTemplateCustomizer.java create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporter.java create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/adapter/ZipkinV2SpanAdapter.java create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/initialize/ZipkinReportRegisterBean.java create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/properties/ZipkinProperties.java create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/sender/ZipkinRestTemplateSender.java create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinReportRegisterBeanTest.java create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinRestTemplateSenderTest.java create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java rename sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/{spring => plugins}/zipkin/ZipkinV2SpanAdapterTest.java (96%) create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/spring-bean.xml diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerRestTemplateCustomizer.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerRestTemplateCustomizer.java new file mode 100644 index 00000000..a8c078c0 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerRestTemplateCustomizer.java @@ -0,0 +1,68 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.zipkin; + +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.web.client.RestTemplate; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.zip.GZIPOutputStream; + +/** + * ZipkinSofaTracerRestTemplateCustomizer + * @author guolei.sgl + * @since v2.3.0 + */ +public class ZipkinSofaTracerRestTemplateCustomizer { + + private boolean gzipped; + + public ZipkinSofaTracerRestTemplateCustomizer(boolean gzipped) { + this.gzipped = gzipped; + } + + public void customize(RestTemplate restTemplate) { + if (!this.gzipped || restTemplate == null) { + return; + } + restTemplate.getInterceptors().add(0, new GzipInterceptor()); + } + + private class GzipInterceptor implements ClientHttpRequestInterceptor { + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, + ClientHttpRequestExecution execution) + throws IOException { + request.getHeaders().add("Content-Encoding", "gzip"); + ByteArrayOutputStream gzipped = new ByteArrayOutputStream(); + GZIPOutputStream compressor = null; + try { + compressor = new GZIPOutputStream(gzipped); + compressor.write(body); + } finally { + if (compressor != null) { + compressor.close(); + } + } + return execution.execute(request, gzipped.toByteArray()); + } + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporter.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporter.java new file mode 100644 index 00000000..1ec46e84 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporter.java @@ -0,0 +1,96 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.zipkin; + +import com.alipay.common.tracer.core.listener.SpanReportListener; +import com.alipay.common.tracer.core.span.SofaTracerSpan; +import com.alipay.common.tracer.core.utils.TracerUtils; +import com.alipay.sofa.tracer.plugins.zipkin.adapter.ZipkinV2SpanAdapter; +import com.alipay.sofa.tracer.plugins.zipkin.sender.ZipkinRestTemplateSender; +import org.springframework.util.Assert; +import org.springframework.web.client.RestTemplate; +import zipkin2.Span; +import zipkin2.reporter.AsyncReporter; +import java.io.Closeable; +import java.io.Flushable; + +/** + * zipkin report + * @author guolei.sgl + * @since v2.3.0 + */ +public class ZipkinSofaTracerSpanRemoteReporter implements SpanReportListener, Flushable, Closeable { + + private static String processId = TracerUtils.getPID(); + + private final ZipkinRestTemplateSender sender; + + private final AsyncReporter delegate; + + private final ZipkinV2SpanAdapter zipkinV2SpanAdapter; + + public ZipkinSofaTracerSpanRemoteReporter(RestTemplate restTemplate, String baseUrl) { + + this.zipkinV2SpanAdapter = new ZipkinV2SpanAdapter(); + this.sender = new ZipkinRestTemplateSender(restTemplate, baseUrl); + this.delegate = AsyncReporter.create(sender); + } + + @Override + public void onSpanReport(SofaTracerSpan span) { + if (span == null) { + return; + } + //convert + Span zipkinSpan = zipkinV2SpanAdapter.convertToZipkinSpan(span); + this.delegate.report(zipkinSpan); + } + + @Override + public void flush() { + this.delegate.flush(); + } + + @Override + public void close() { + this.delegate.close(); + } + + /*** + * 功能:将 16 进制字符串转换为:十进制整数 + * @param hexString 16 进制字符串 + * @return 十进制整数 + */ + public static long traceIdToId(String hexString) { + Assert.hasText(hexString, "Can't convert empty hex string to long"); + int length = hexString.length(); + if (length < 1) { + throw new IllegalArgumentException("Malformed id(length must be more than zero): " + + hexString); + } + if (length <= 8) { + //hex + return Long.parseLong(hexString, 16); + } else if (hexString.endsWith(processId)) { + //time + return Long.parseLong(hexString.substring(8, hexString.lastIndexOf(processId)), 10); + } else { + //delete ip and processor id + return Long.parseLong(hexString.substring(8), 10); + } + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/adapter/ZipkinV2SpanAdapter.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/adapter/ZipkinV2SpanAdapter.java new file mode 100644 index 00000000..182ed6c0 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/adapter/ZipkinV2SpanAdapter.java @@ -0,0 +1,194 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.zipkin.adapter; + +import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; +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.utils.StringUtils; +import io.opentracing.tag.Tags; +import zipkin2.Endpoint; +import zipkin2.Span; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.util.Map; + +/*** + * ZipkinV2SpanAdapter : convent sofaTracer span model to zipkin span model + * @author guolei.sgl 05/09/2018 + * @since v.2.3.0 + */ +public class ZipkinV2SpanAdapter { + + /** + * cache and performance improve + */ + private int ipAddressInt = -1; + + /** + * convent sofaTracerSpan model to zipKinSpan model + * @param sofaTracerSpan original span + * @return zipkinSpan model + */ + public Span convertToZipkinSpan(SofaTracerSpan sofaTracerSpan) { + if (sofaTracerSpan == null) { + return null; + } + // spanId、parentId、tracerId + Span.Builder zipkinSpanBuilder = Span.newBuilder(); + SofaTracerSpanContext context = sofaTracerSpan.getSofaTracerSpanContext(); + zipkinSpanBuilder.traceId(context.getTraceId()); + zipkinSpanBuilder.id(spanIdToLong(context.getSpanId())); + if (StringUtils.isNotBlank(context.getParentId())) { + zipkinSpanBuilder.parentId(spanIdToLong(context.getParentId())); + } + + // timestamp & duration + long start = sofaTracerSpan.getStartTime() * 1000; + long finish = sofaTracerSpan.getEndTime() * 1000; + zipkinSpanBuilder.timestamp(start); + zipkinSpanBuilder.duration(finish - start); + + // kind + Map tagsWithStr = sofaTracerSpan.getTagsWithStr(); + String kindStr = tagsWithStr.get(Tags.SPAN_KIND.getKey()); + if (StringUtils.isNotBlank(kindStr) && kindStr.equals(Tags.SPAN_KIND_SERVER)) { + zipkinSpanBuilder.kind(Span.Kind.SERVER); + } else { + zipkinSpanBuilder.kind(Span.Kind.CLIENT); + } + + // Endpoint + Endpoint endpoint = getZipkinEndpoint(sofaTracerSpan); + zipkinSpanBuilder.localEndpoint(endpoint); + + // Tags + this.addZipkinTags(zipkinSpanBuilder, sofaTracerSpan); + + // span name + String operationName = sofaTracerSpan.getOperationName(); + if (StringUtils.isNotBlank(operationName)) { + zipkinSpanBuilder.name(operationName); + } else { + zipkinSpanBuilder.name(StringUtils.EMPTY_STRING); + } + + // Annotations + this.addZipkinAnnotations(zipkinSpanBuilder, sofaTracerSpan); + + return zipkinSpanBuilder.build(); + } + + public static long spanIdToLong(String spanId) { + return FNV64HashCode(spanId); + } + + /** + * from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash + * @param data String data + * @return fnv hash code + */ + public static long FNV64HashCode(String data) { + //hash FNVHash64 : http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param + long hash = 0xcbf29ce484222325L; + for (int i = 0; i < data.length(); ++i) { + char c = data.charAt(i); + hash ^= c; + hash *= 0x100000001b3L; + } + return hash; + } + + private Endpoint getZipkinEndpoint(SofaTracerSpan span) { + InetAddress ipAddress = null; + if (this.ipAddressInt <= 0) { + try { + ipAddress = InetAddress.getLocalHost(); + this.ipAddressInt = ByteBuffer.wrap(ipAddress.getAddress()).getInt(); + } catch (UnknownHostException e) { + //127.0.0.1 256 进制 + this.ipAddressInt = 256 * 256 * 256 * 127 + 1; + } + } + String appName = span.getTagsWithStr().get(CommonSpanTags.LOCAL_APP); + return Endpoint.newBuilder().serviceName(appName).ip(ipAddress).build(); + } + + /** + * 将Baggage中的数据也放在tags中 + * @param zipkinSpan + * @param span + */ + private void addZipkinTagsWithBaggage(Span.Builder zipkinSpan, SofaTracerSpan span) { + SofaTracerSpanContext sofaTracerSpanContext = span.getSofaTracerSpanContext(); + if (sofaTracerSpanContext != null) { + Map sysBaggage = sofaTracerSpanContext.getSysBaggage(); + for (Map.Entry e : sysBaggage.entrySet()) { + zipkinSpan.putTag(e.getKey(), e.getValue()); + } + Map bizBaggage = sofaTracerSpanContext.getBizBaggage(); + for (Map.Entry e : bizBaggage.entrySet()) { + zipkinSpan.putTag(e.getKey(), e.getValue()); + } + } + } + + /** + * convent Annotations + * @param zipkinSpan + * @param span + */ + private void addZipkinAnnotations(Span.Builder zipkinSpan, SofaTracerSpan span) { + for (LogData logData : span.getLogs()) { + Map fields = logData.getFields(); + if (fields == null || fields.size() <= 0) { + continue; + } + for (Map.Entry entry : fields.entrySet()) { + // zipkin has been support default log event depend on span kind & serviceName + if (!(entry.getValue().toString().equals(LogData.CLIENT_RECV_EVENT_VALUE) + || entry.getValue().toString().equals(LogData.CLIENT_SEND_EVENT_VALUE) + || entry.getValue().toString().equals(LogData.SERVER_RECV_EVENT_VALUE) || entry + .getValue().toString().equals(LogData.SERVER_SEND_EVENT_VALUE))) { + zipkinSpan.addAnnotation(logData.getTime() * 1000, entry.getValue().toString()); + } + } + } + } + + /** + * convent tags + * @param zipkinSpan + * @param span + */ + private void addZipkinTags(Span.Builder zipkinSpan, SofaTracerSpan span) { + + for (Map.Entry e : span.getTagsWithStr().entrySet()) { + zipkinSpan.putTag(e.getKey(), e.getValue()); + } + for (Map.Entry e : span.getTagsWithNumber().entrySet()) { + zipkinSpan.putTag(e.getKey(), e.getValue().toString()); + } + for (Map.Entry e : span.getTagsWithBool().entrySet()) { + zipkinSpan.putTag(e.getKey(), e.getValue().toString()); + } + + addZipkinTagsWithBaggage(zipkinSpan, span); + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/initialize/ZipkinReportRegisterBean.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/initialize/ZipkinReportRegisterBean.java new file mode 100644 index 00000000..fb88d62c --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/initialize/ZipkinReportRegisterBean.java @@ -0,0 +1,71 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.zipkin.initialize; + +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.listener.SpanReportListener; +import com.alipay.common.tracer.core.listener.SpanReportListenerHolder; +import com.alipay.common.tracer.core.utils.StringUtils; +import com.alipay.sofa.tracer.plugins.zipkin.properties.ZipkinProperties; +import com.alipay.sofa.tracer.plugins.zipkin.ZipkinSofaTracerRestTemplateCustomizer; +import com.alipay.sofa.tracer.plugins.zipkin.ZipkinSofaTracerSpanRemoteReporter; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; +import java.util.List; + +/** + * ZipkinReportRegisterBean to parse properties and register zipkin report listeners + * + * @author guolei.sgl + * @since v2.3.0 + */ +public class ZipkinReportRegisterBean implements InitializingBean { + + @Override + public void afterPropertiesSet() { + // if do not match report condition,it will be return right now + boolean enabled = false; + String enabledStr = SofaTracerConfiguration + .getProperty(ZipkinProperties.ZIPKIN_IS_ENABLED_KEY); + if (StringUtils.isNotBlank(enabledStr) && "true".equalsIgnoreCase(enabledStr)) { + enabled = true; + } + if (!enabled) { + return; + } + + boolean gzipped = false; + String gzippedStr = SofaTracerConfiguration + .getProperty(ZipkinProperties.ZIPKIN_IS_GZIPPED_KEY); + if (StringUtils.isNotBlank(gzippedStr) && "true".equalsIgnoreCase(gzippedStr)) { + gzipped = true; + } + + RestTemplate restTemplate = new RestTemplate(); + ZipkinSofaTracerRestTemplateCustomizer zipkinSofaTracerRestTemplateCustomizer = new ZipkinSofaTracerRestTemplateCustomizer( + gzipped); + zipkinSofaTracerRestTemplateCustomizer.customize(restTemplate); + String baseUrl = SofaTracerConfiguration.getProperty(ZipkinProperties.ZIPKIN_BASE_URL_KEY); + SpanReportListener spanReportListener = new ZipkinSofaTracerSpanRemoteReporter( + restTemplate, baseUrl); + List spanReportListenerList = new ArrayList(); + spanReportListenerList.add(spanReportListener); + SpanReportListenerHolder.addSpanReportListeners(spanReportListenerList); + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/properties/ZipkinProperties.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/properties/ZipkinProperties.java new file mode 100644 index 00000000..f2a6b8c2 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/properties/ZipkinProperties.java @@ -0,0 +1,30 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.zipkin.properties; + +/** + * ZipkinProperties + * @author guolei.sgl + * @since v2.3.0 + */ +public class ZipkinProperties { + + public static final String ZIPKIN_IS_ENABLED_KEY = "com.alipay.sofa.tracer.zipkin.enabled"; + public static final String ZIPKIN_BASE_URL_KEY = "com.alipay.sofa.tracer.zipkin.baseUrl"; + public static final String ZIPKIN_IS_GZIPPED_KEY = "com.alipay.sofa.tracer.zipkin.gzipped"; + +} diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/sender/ZipkinRestTemplateSender.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/sender/ZipkinRestTemplateSender.java new file mode 100644 index 00000000..fff7c39c --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/sender/ZipkinRestTemplateSender.java @@ -0,0 +1,81 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.zipkin.sender; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.web.client.RestTemplate; +import zipkin2.Call; +import zipkin2.codec.Encoding; +import zipkin2.reporter.BytesMessageEncoder; +import zipkin2.reporter.Sender; +import java.net.URI; +import java.util.List; + +/** + * ZipkinRestTemplateSender + * @author guolei.sgl + */ +public class ZipkinRestTemplateSender extends Sender { + + private RestTemplate restTemplate; + private String url; + + public ZipkinRestTemplateSender(RestTemplate restTemplate, String baseUrl) { + this.restTemplate = restTemplate; + this.url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "api/v2/spans"; + } + + @Override + public Encoding encoding() { + return Encoding.JSON; + } + + @Override + public int messageMaxBytes() { + // Max span size is 2MB + return 2 * 1024 * 1024; + } + + @Override + public int messageSizeInBytes(List spans) { + return encoding().listSizeInBytes(spans); + } + + @Override + public Call sendSpans(List encodedSpans) { + try { + byte[] message = BytesMessageEncoder.JSON.encode(encodedSpans); + post(message); + } catch (Throwable e) { + if (e instanceof Error) { + throw (Error) e; + } + } + return null; + } + + private void post(byte[] json) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); + RequestEntity requestEntity = new RequestEntity(json, httpHeaders, + HttpMethod.POST, URI.create(this.url)); + this.restTemplate.exchange(requestEntity, String.class); + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinReportRegisterBeanTest.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinReportRegisterBeanTest.java new file mode 100644 index 00000000..0e8d9d90 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinReportRegisterBeanTest.java @@ -0,0 +1,48 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.zipkin; + +import com.alipay.common.tracer.core.listener.SpanReportListenerHolder; +import com.alipay.sofa.tracer.plugins.zipkin.initialize.ZipkinReportRegisterBean; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +/** + * ZipkinReportRegisterBeanTest + * + * @author: guolei.sgl + * @since: v2.3.0 + **/ +public class ZipkinReportRegisterBeanTest { + + private ClassPathXmlApplicationContext applicationContext; + + @Before + public void init() { + applicationContext = new ClassPathXmlApplicationContext("spring-bean.xml"); + } + + @Test + public void testAfterPropertiesSet() { + Object zipkinReportRegisterBean = applicationContext.getBean("zipkinReportRegisterBean"); + Assert.assertTrue(zipkinReportRegisterBean instanceof ZipkinReportRegisterBean); + Assert.assertTrue(SpanReportListenerHolder.getSpanReportListenersHolder().size() > 0); + } + +} diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinRestTemplateSenderTest.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinRestTemplateSenderTest.java new file mode 100644 index 00000000..83cda74c --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinRestTemplateSenderTest.java @@ -0,0 +1,81 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.zipkin; + +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.sofa.tracer.plugins.zipkin.properties.ZipkinProperties; +import com.alipay.sofa.tracer.plugins.zipkin.sender.ZipkinRestTemplateSender; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.web.client.RestTemplate; +import zipkin2.Call; +import zipkin2.codec.Encoding; + +import java.util.ArrayList; +import java.util.List; + +/** + * ZipkinRestTemplateSenderTest + * + * @author: guolei.sgl + * @since: v2.3.0 + **/ +public class ZipkinRestTemplateSenderTest { + + ZipkinRestTemplateSender zipkinRestTemplateSender; + RestTemplate restTemplate; + + @Before + public void init() { + restTemplate = new RestTemplate(); + zipkinRestTemplateSender = new ZipkinRestTemplateSender(restTemplate, + SofaTracerConfiguration.getProperty(ZipkinProperties.ZIPKIN_BASE_URL_KEY)); + } + + @Test + public void encoding() { + Encoding encoding = zipkinRestTemplateSender.encoding(); + Assert.assertTrue(encoding.equals(Encoding.JSON)); + } + + @Test + public void messageMaxBytes() { + Assert.assertTrue(zipkinRestTemplateSender.messageMaxBytes() == 2 * 1024 * 1024); + } + + @Test + public void messageSizeInBytes() { + byte[] tests = new byte[1]; + tests[0] = 0; + List spans = new ArrayList(); + spans.add(tests); + int i = zipkinRestTemplateSender.messageSizeInBytes(spans); + Assert.assertTrue(i == 3); + } + + @Test + public void sendSpans() throws InterruptedException { + byte[] tests = new byte[1]; + tests[0] = 0; + List encodedSpans = new ArrayList(); + encodedSpans.add(tests); + Call voidCall = zipkinRestTemplateSender.sendSpans(encodedSpans); + Thread.sleep(500); + Assert.assertTrue(voidCall == null); + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java new file mode 100644 index 00000000..2f906285 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java @@ -0,0 +1,40 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.zipkin; + +import org.junit.Assert; +import org.junit.Test; + +/** + * ZipkinSofaTracerSpanRemoteReporterTest + * + * @author: guolei.sgl + * @since: v2.3.0 + **/ +public class ZipkinSofaTracerSpanRemoteReporterTest { + + @Test + public void testTraceIdToId() { + // hex to decimal + long ff = ZipkinSofaTracerSpanRemoteReporter.traceIdToId("FF"); + Assert.assertTrue(ff == 255); + + long decimal88 = ZipkinSofaTracerSpanRemoteReporter.traceIdToId("8"); + Assert.assertTrue(decimal88 == 8); + + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/spring/zipkin/ZipkinV2SpanAdapterTest.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinV2SpanAdapterTest.java similarity index 96% rename from sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/spring/zipkin/ZipkinV2SpanAdapterTest.java rename to sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinV2SpanAdapterTest.java index e80a4293..e81e02b5 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/spring/zipkin/ZipkinV2SpanAdapterTest.java +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinV2SpanAdapterTest.java @@ -14,13 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alipay.sofa.tracer.spring.zipkin; +package com.alipay.sofa.tracer.plugins.zipkin; import com.alipay.common.tracer.core.SofaTracer; 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.sofa.tracer.spring.zipkin.adapter.ZipkinV2SpanAdapter; +import com.alipay.sofa.tracer.plugins.zipkin.adapter.ZipkinV2SpanAdapter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/spring-bean.xml b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/spring-bean.xml new file mode 100644 index 00000000..43fe425a --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/spring-bean.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerAutoConfiguration.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerAutoConfiguration.java index 882e633b..b154398a 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerAutoConfiguration.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerAutoConfiguration.java @@ -16,9 +16,10 @@ */ package com.alipay.sofa.tracer.boot.zipkin.configuration; -import com.alipay.sofa.tracer.boot.zipkin.ZipkinSofaTracerSpanRemoteReporter; import com.alipay.sofa.tracer.boot.zipkin.properties.ZipkinSofaTracerProperties; -import com.alipay.sofa.tracer.boot.zipkin.properties.ZipkinSofaTracerSamplerProperties; +import com.alipay.sofa.tracer.plugins.zipkin.ZipkinSofaTracerRestTemplateCustomizer; +import com.alipay.sofa.tracer.plugins.zipkin.ZipkinSofaTracerSpanRemoteReporter; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -34,25 +35,25 @@ * @since 2018/05/01 */ @Configuration -@EnableConfigurationProperties({ ZipkinSofaTracerProperties.class, - ZipkinSofaTracerSamplerProperties.class }) +@EnableConfigurationProperties(ZipkinSofaTracerProperties.class) @ConditionalOnProperty(value = "com.alipay.sofa.tracer.zipkin.enabled", matchIfMissing = true) @ConditionalOnClass({ zipkin2.Span.class, zipkin2.reporter.AsyncReporter.class }) public class ZipkinSofaTracerAutoConfiguration { + @Autowired + private ZipkinSofaTracerProperties zipkinProperties; + @Bean @ConditionalOnMissingBean - public ZipkinSofaTracerRestTemplateCustomizer zipkinSofaTracerRestTemplateCustomizer(ZipkinSofaTracerProperties zipkinProperties) { - return new ZipkinSofaTracerRestTemplateCustomizer(zipkinProperties); + public ZipkinSofaTracerRestTemplateCustomizer zipkinSofaTracerRestTemplateCustomizer() { + return new ZipkinSofaTracerRestTemplateCustomizer(zipkinProperties.isGzipped()); } @Bean @ConditionalOnMissingBean - public ZipkinSofaTracerSpanRemoteReporter zipkinSofaTracerSpanReporter(ZipkinSofaTracerProperties zipkinSofaTracerProperties, - ZipkinSofaTracerRestTemplateCustomizer zipkinSofaTracerRestTemplateCustomizer) { + public ZipkinSofaTracerSpanRemoteReporter zipkinSofaTracerSpanReporter(ZipkinSofaTracerRestTemplateCustomizer zipkinSofaTracerRestTemplateCustomizer) { RestTemplate restTemplate = new RestTemplate(); zipkinSofaTracerRestTemplateCustomizer.customize(restTemplate); - return new ZipkinSofaTracerSpanRemoteReporter(restTemplate, - zipkinSofaTracerProperties.getBaseUrl()); + return new ZipkinSofaTracerSpanRemoteReporter(restTemplate, zipkinProperties.getBaseUrl()); } } diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java index a8e0a2cf..b65ea038 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java @@ -23,9 +23,11 @@ import com.alipay.common.tracer.core.listener.SpanReportListener; import com.alipay.common.tracer.core.listener.SpanReportListenerHolder; import com.alipay.common.tracer.core.span.SofaTracerSpan; -import com.alipay.sofa.tracer.boot.zipkin.configuration.ZipkinSofaTracerRestTemplateCustomizer; import com.alipay.sofa.tracer.boot.zipkin.mock.MockAbstractTracer; import com.alipay.sofa.tracer.boot.zipkin.properties.ZipkinSofaTracerProperties; +import com.alipay.sofa.tracer.plugins.zipkin.ZipkinSofaTracerRestTemplateCustomizer; +import com.alipay.sofa.tracer.plugins.zipkin.ZipkinSofaTracerSpanRemoteReporter; +import com.alipay.sofa.tracer.plugins.zipkin.adapter.ZipkinV2SpanAdapter; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -40,22 +42,25 @@ /** * ZipkinSofaTracerSpanRemoteReporter Tester. * - * @author - * @version 1.0 - * @since
五月 1, 2018
+ * @author guolei.sgl + * @since v2.3.0 */ public class ZipkinSofaTracerSpanRemoteReporterTest { - private MockAbstractTracer remoteTracer; + private MockAbstractTracer remoteTracer; + private ZipkinV2SpanAdapter zipkinV2SpanAdapter; @Before public void before() throws Exception { - + zipkinV2SpanAdapter = new ZipkinV2SpanAdapter(); remoteTracer = new MockAbstractTracer("mockSendTracerSpan"); RestTemplate restTemplate = new RestTemplate(); ZipkinSofaTracerProperties zipkinProperties = new ZipkinSofaTracerProperties(); + zipkinProperties.setBaseUrl("http://localhost:9411"); + zipkinProperties.setEnabled(true); + zipkinProperties.setGzipped(true); ZipkinSofaTracerRestTemplateCustomizer restTemplateCustomizer = new ZipkinSofaTracerRestTemplateCustomizer( - zipkinProperties); + zipkinProperties.isGzipped()); restTemplateCustomizer.customize(restTemplate); //host http://zipkin-cloud-3.inc.host.net:9411 String baseUrl = "http://zipkin-cloud-3.inc.host.net:9411"; @@ -149,7 +154,7 @@ public void testFNV64HashCode() throws Exception { } private void entranceHash(Map map, String data) { - long hashCode = ZipkinSofaTracerSpanRemoteReporter.FNV64HashCode(data); + long hashCode = zipkinV2SpanAdapter.FNV64HashCode(data); this.putMap(hashCode, map); } @@ -181,7 +186,7 @@ public void testDoServerReport() throws Exception { sofaTracerServerSpan.setOperationName("mockOperationName"); //ss TL this.remoteTracer.serverSend("0"); - //异步汇报,所以 sleep 1s + //异步汇报,所以 sleep 10s Thread.sleep(1000); //assert SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); @@ -224,7 +229,7 @@ public void testDoReport() throws Exception { assertEquals(sofaTracerServerSpan, sofaTraceContext.getCurrentSpan()); //ss TL this.remoteTracer.serverSend("0"); - //异步汇报,所以 sleep 1s + //异步汇报,所以 sleep 10s Thread.sleep(1000); //assert assertTrue(sofaTraceContext.isEmpty()); diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/mock/MockAbstractTracer.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/mock/MockAbstractTracer.java index 3d1d8f04..fdc133e0 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/mock/MockAbstractTracer.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/mock/MockAbstractTracer.java @@ -21,7 +21,7 @@ import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tracer.AbstractTracer; -import com.alipay.sofa.tracer.boot.zipkin.ZipkinSofaTracerSpanRemoteReporter; +import com.alipay.sofa.tracer.plugins.zipkin.ZipkinSofaTracerSpanRemoteReporter; /** * MockAbstractTracer From 68378c6adb58efac4b84c49515b69d67914dea97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Mon, 11 Mar 2019 11:31:51 +0800 Subject: [PATCH 03/24] glmapper-branch-3.x-sheery-pick --- pom.xml | 6 + .../springmvc/SpringMvcSofaTracerFilter.java | 19 +- .../sofa-tracer-zipkin-plugin/pom.xml | 2 +- .../src/test/resources/spring-bean.xml | 2 +- .../alipay/common/tracer/core/SofaTracer.java | 47 +++-- .../appender/self/SynchronizingSelfLog.java | 1 - .../tracer/core/async/SofaTracerCallable.java | 2 + .../tracer/core/async/SofaTracerRunnable.java | 2 + .../SofaTracerConfiguration.java | 17 ++ .../listener/SpanReportListenerHolder.java | 4 +- .../registry/AbstractTextB3Formatter.java | 1 + .../reporter/digest/AbstractDiskReporter.java | 5 +- .../common/tracer/core/samplers/Sampler.java | 7 +- .../tracer/core/samplers/SamplerFactory.java | 67 ++++++ .../core/samplers/SamplerProperties.java | 20 +- .../SofaTracerPercentageBasedSampler.java | 18 +- .../tracer/core/span/CommonSpanTags.java | 1 + .../tracer/core/tracer/AbstractTracer.java | 2 + .../tracer/core/base/AbstractTestBase.java | 9 +- .../common/CommonSpanEncoderTest.java | 10 +- .../core/samplers/SamplerPropertiesTest.java | 6 +- .../SofaTracerPercentageBasedSamplerTest.java | 24 ++- .../core/tracertest/SofaTracerTest.java | 13 +- .../tracer-sample-with-zipkin/README.md | 34 +-- .../controller/SampleRestController.java | 8 +- .../src/main/resources/application.properties | 2 +- tracer-sofa-boot-starter/pom.xml | 37 +++- .../ZipkinSofaTracerSpanRemoteReporter.java | 194 ------------------ ...ipkinSofaTracerRestTemplateCustomizer.java | 72 ------- .../ZipkinSofaTracerProperties.java | 46 ++--- .../sender/ZipkinRestTemplateSender.java | 84 -------- .../resources/application-zipkin.properties | 3 + .../src/test/resources/application.properties | 12 ++ .../src/test/resources/hikariDataSource.xml | 2 +- 34 files changed, 313 insertions(+), 466 deletions(-) create mode 100644 tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerFactory.java delete mode 100644 tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporter.java delete mode 100644 tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerRestTemplateCustomizer.java delete mode 100644 tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/sender/ZipkinRestTemplateSender.java diff --git a/pom.xml b/pom.xml index 0761eaee..a558347a 100644 --- a/pom.xml +++ b/pom.xml @@ -21,6 +21,7 @@ sofa-tracer-plugins/sofa-tracer-springmvc-plugin sofa-tracer-plugins/sofa-tracer-httpclient-plugin sofa-tracer-plugins/sofa-tracer-datasource-plugin + sofa-tracer-plugins/sofa-tracer-zipkin-plugin tracer-all tracer-sofa-boot-starter tracer-samples @@ -100,6 +101,11 @@ sofa-tracer-datasource-plugin ${sofa.tracer.version}
+ + com.alipay.sofa + sofa-tracer-zipkin-plugin + ${sofa.tracer.version} + com.alipay.sofa tracer-all 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 305936de..cf48ff79 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 @@ -66,6 +66,12 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo SofaTracerSpanContext spanContext = getSpanContextFromRequest(request); // sr springMvcSpan = springMvcTracer.serverReceive(spanContext); + + if (!isRootSpan(request)) { + springMvcSpan.getSofaTracerSpanContext() + .setSpanId(spanContext.nextChildContextId()); + } + if (StringUtils.isBlank(this.appName)) { this.appName = SofaTracerConfiguration .getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY); @@ -98,6 +104,18 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } } + private boolean isRootSpan(HttpServletRequest request) { + Enumeration headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { + String key = (String) headerNames.nextElement(); + String value = request.getHeader(key); + if (key.equals("X-B3-TraceId") && StringUtils.isNotBlank(value)) { + return false; + } + } + return true; + } + @Override public void destroy() { // no operation @@ -129,7 +147,6 @@ public SofaTracerSpanContext getSpanContextFromRequest(HttpServletRequest reques SofaTracer tracer = springMvcTracer.getSofaTracer(); SofaTracerSpanContext spanContext = (SofaTracerSpanContext) tracer.extract( ExtendFormat.Builtin.B3_HTTP_HEADERS, new SpringMvcHeadersCarrier(headers)); - spanContext.setSpanId(spanContext.nextChildContextId()); return spanContext; } diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml index ecdd5fd9..49b7821c 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 2.3.0-SNAPSHOT + 3.0.3-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/spring-bean.xml b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/spring-bean.xml index 43fe425a..cf490001 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/spring-bean.xml +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/spring-bean.xml @@ -13,6 +13,6 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> - + 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 ff01d8e6..213f9c91 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 @@ -25,6 +25,7 @@ import com.alipay.common.tracer.core.registry.TracerFormatRegistry; import com.alipay.common.tracer.core.reporter.facade.Reporter; 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.span.SofaTracerSpan; import com.alipay.common.tracer.core.span.SofaTracerSpanReferenceRelationship; @@ -116,6 +117,10 @@ public void reportSpan(SofaTracerSpan span) { if (span == null) { return; } + // //sampler is support & current span is root span + if (sampler != null && span.getParentSofaTracerSpan() == null) { + span.getSofaTracerSpanContext().setSampled(sampler.sample(span).isSampled()); + } //invoke listener this.invokeReportListeners(span); //客户端、服务端 @@ -288,24 +293,37 @@ public Span start() { long begin = this.startTime > 0 ? this.startTime : System.currentTimeMillis(); SofaTracerSpan sofaTracerSpan = new SofaTracerSpan(SofaTracer.this, begin, this.references, this.operationName, sofaTracerSpanContext, this.tags); + + // calculate isSampled,but do not change parent's sampler behaviour + boolean isSampled = calculateSampler(sofaTracerSpan); + sofaTracerSpanContext.setSampled(isSampled); + return sofaTracerSpan; } - private SofaTracerSpanContext createRootSpanContext() { - //生成 traceId - String traceId = TraceIdGenerator.generate(); - //默认不采样 + private boolean calculateSampler(SofaTracerSpan sofaTracerSpan) { boolean isSampled = false; - if (sampler != null) { - SamplingStatus samplingStatus = sampler.sample(this.operationName, traceId); - if (samplingStatus.isSampled()) { - isSampled = true; - //发生采样后,将相关属性记录 - this.tags.putAll(samplingStatus.getTags()); + if (this.references != null && this.references.size() > 0) { + SofaTracerSpanContext preferredReference = preferredReference(); + isSampled = preferredReference.isSampled(); + } else { + if (sampler != null) { + SamplingStatus samplingStatus = sampler.sample(sofaTracerSpan); + if (samplingStatus.isSampled()) { + isSampled = true; + //发生采样后,将相关属性记录 + this.tags.putAll(samplingStatus.getTags()); + } } } - return new SofaTracerSpanContext(traceId, ROOT_SPAN_ID, StringUtils.EMPTY_STRING, - isSampled); + + return isSampled; + } + + private SofaTracerSpanContext createRootSpanContext() { + //生成 traceId + String traceId = TraceIdGenerator.generate(); + return new SofaTracerSpanContext(traceId, ROOT_SPAN_ID, StringUtils.EMPTY_STRING); } private SofaTracerSpanContext createChildContext() { @@ -456,6 +474,11 @@ public Builder withTags(Map tags) { } public SofaTracer build() { + try { + sampler = SamplerFactory.getSampler(); + } catch (Exception e) { + SelfLog.error("Failed to get tracer sampler strategy;"); + } return new SofaTracer(this.tracerType, this.clientReporter, this.serverReporter, this.sampler, this.tracerTags); } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java index 14d37a58..662b2d9b 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java @@ -151,5 +151,4 @@ static private void doLog(String log, String prefix) { t.printStackTrace(); } } - } \ No newline at end of file diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerCallable.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerCallable.java index 84ad7a54..05fd97d0 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerCallable.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerCallable.java @@ -17,6 +17,7 @@ package com.alipay.common.tracer.core.async; import com.alipay.common.tracer.core.context.trace.SofaTraceContext; +import com.alipay.common.tracer.core.extensions.SpanExtensionFactory; import com.alipay.common.tracer.core.holder.SofaTraceContextHolder; import com.alipay.common.tracer.core.span.SofaTracerSpan; @@ -58,6 +59,7 @@ public T call() throws Exception { if (Thread.currentThread().getId() != tid) { if (currentSpan != null) { traceContext.push(currentSpan); + SpanExtensionFactory.logStartedSpan(currentSpan); } } try { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerRunnable.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerRunnable.java index a6936f40..6a75fdfb 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerRunnable.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerRunnable.java @@ -17,6 +17,7 @@ package com.alipay.common.tracer.core.async; import com.alipay.common.tracer.core.context.trace.SofaTraceContext; +import com.alipay.common.tracer.core.extensions.SpanExtensionFactory; import com.alipay.common.tracer.core.holder.SofaTraceContextHolder; import com.alipay.common.tracer.core.span.SofaTracerSpan; import java.lang.Runnable; @@ -57,6 +58,7 @@ public void run() { if (Thread.currentThread().getId() != tid) { if (currentSpan != null) { traceContext.push(currentSpan); + SpanExtensionFactory.logStartedSpan(currentSpan); } } try { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerConfiguration.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerConfiguration.java index 8a522ffd..ef3b6ba2 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerConfiguration.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerConfiguration.java @@ -111,6 +111,15 @@ public class SofaTracerConfiguration { private static SofaTracerExternalConfiguration sofaTracerExternalConfiguration = null; + /***************** 采样配置项 end ***************/ + + /** 采样策略名称key */ + public static final String SAMPLER_STRATEGY_NAME_KEY = "tracer_sampler_strategy_name_key"; + /** 自定义采样规则类名 */ + public static final String SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME = "tracer_sampler_strategy_custom_rule_class_name"; + /** 采样率key */ + public static final String SAMPLER_STRATEGY_PERCENTAGE_KEY = "tracer_sampler_strategy_percentage_key"; + static { InputStream inputStream = null; try { @@ -269,4 +278,12 @@ public static String getLogReserveConfig(String logReserveKey) { public static void setSofaTracerExternalConfiguration(SofaTracerExternalConfiguration sofaTracerExternalConfiguration) { SofaTracerConfiguration.sofaTracerExternalConfiguration = sofaTracerExternalConfiguration; } + + public static String getSofaTracerSamplerStrategy() { + String samplerName = getProperty(SAMPLER_STRATEGY_NAME_KEY); + if (StringUtils.isBlank(samplerName)) { + return null; + } + return samplerName; + } } \ No newline at end of file diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolder.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolder.java index e568b6be..fe361289 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolder.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolder.java @@ -16,8 +16,8 @@ */ package com.alipay.common.tracer.core.listener; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; /** * SpanReportListenerHolder @@ -27,7 +27,7 @@ */ public class SpanReportListenerHolder { - private static List spanReportListenersHolder = new ArrayList(); + private static List spanReportListenersHolder = new CopyOnWriteArrayList(); public static List getSpanReportListenersHolder() { return spanReportListenersHolder; diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextB3Formatter.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextB3Formatter.java index 4ef623d5..6a5f43ae 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextB3Formatter.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextB3Formatter.java @@ -146,6 +146,7 @@ public void inject(SofaTracerSpanContext spanContext, TextMap carrier) { carrier.put(SPAN_ID_KEY_HEAD, encodedValue(spanContext.getSpanId())); carrier.put(PARENT_SPAN_ID_KEY_HEAD, encodedValue(spanContext.getParentId())); carrier.put(SPAN_ID_KEY_HEAD, encodedValue(spanContext.getSpanId())); + carrier.put(SAMPLED_KEY_HEAD, encodedValue(String.valueOf(spanContext.isSampled()))); //System Baggage items for (Map.Entry entry : spanContext.getSysBaggage().entrySet()) { String key = BAGGAGE_SYS_KEY_PREFIX + StringUtils.escapePercentEqualAnd(entry.getKey()); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/AbstractDiskReporter.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/AbstractDiskReporter.java index 8b222a2a..980c6981 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/AbstractDiskReporter.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/AbstractDiskReporter.java @@ -89,8 +89,9 @@ protected boolean isDisableDigestLog(SofaTracerSpan span) { return true; } SofaTracerSpanContext sofaTracerSpanContext = (SofaTracerSpanContext) span.context(); - if (sofaTracerSpanContext.isSampled()) { - return false; + // sampled is false; this span will not be report + if (!sofaTracerSpanContext.isSampled()) { + return true; } boolean allDisabled = Boolean.TRUE.toString().equalsIgnoreCase( SofaTracerConfiguration diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/Sampler.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/Sampler.java index 866a7af4..3f126daa 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/Sampler.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/Sampler.java @@ -16,13 +16,14 @@ */ package com.alipay.common.tracer.core.samplers; +import com.alipay.common.tracer.core.span.SofaTracerSpan; + public interface Sampler { /** - * @param operation The operation name set on the span - * @param traceId The traceId on the span + * @param sofaTracerSpan The operation name set on the span * @return whether or not the new trace should be sampled */ - SamplingStatus sample(String operation, String traceId); + SamplingStatus sample(SofaTracerSpan sofaTracerSpan); String getType(); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerFactory.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerFactory.java new file mode 100644 index 00000000..7ff39ace --- /dev/null +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerFactory.java @@ -0,0 +1,67 @@ +/* + * 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. + */ +package com.alipay.common.tracer.core.samplers; + +import com.alipay.common.tracer.core.appender.self.SelfLog; +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.utils.StringUtils; + +/** + * SamplerFactory + * + * @author: guolei.sgl + * @since: 18/9/11 + */ +public class SamplerFactory { + + public static SamplerProperties samplerProperties; + + static { + samplerProperties = new SamplerProperties(); + try { + float percentage = 100; + + String perStr = SofaTracerConfiguration + .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY); + if (StringUtils.isNotBlank(perStr)) { + percentage = Float.parseFloat(perStr); + } + samplerProperties.setPercentage(percentage); + } catch (Exception e) { + SelfLog.error("It will be use default percentage value :100;", e); + samplerProperties.setPercentage(100); + } + samplerProperties.setRuleClassName(SofaTracerConfiguration + .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME)); + } + + /** + * getSampler by samplerName + * + * the samplerName is the user configuration + * @return Sampler + * @throws Exception + */ + public static Sampler getSampler() throws Exception { + // User-defined rules have high priority + if (StringUtils.isNotBlank(samplerProperties.getRuleClassName())) { + return (Sampler) Class.forName(samplerProperties.getRuleClassName()).newInstance(); + } + // default instance + return new SofaTracerPercentageBasedSampler(samplerProperties); + } +} diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerProperties.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerProperties.java index 6040d7f4..dcaed743 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerProperties.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerProperties.java @@ -25,16 +25,30 @@ public class SamplerProperties { /** * Percentage of requests that should be sampled. E.g. 1.0 - 100% requests should be - * sampled. The precision is whole-numbers only (i.e. there's no support for 0.1% of + * sampled. The precision is whole-numbers only (i.e. there's no support for 1.0 of * the traces). */ - private float percentage = 0.1f; + private float percentage = 100; + + /** + * if use custom rule, you can implements Sample interface and provide this class name + */ + private String ruleClassName; public float getPercentage() { - return this.percentage; + return percentage; } public void setPercentage(float percentage) { this.percentage = percentage; } + + public String getRuleClassName() { + return ruleClassName; + } + + public void setRuleClassName(String ruleClassName) { + this.ruleClassName = ruleClassName; + } + } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSampler.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSampler.java index 5087302c..ec964279 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSampler.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSampler.java @@ -17,9 +17,10 @@ package com.alipay.common.tracer.core.samplers; import com.alipay.common.tracer.core.constants.SofaTracerConstant; +import com.alipay.common.tracer.core.span.SofaTracerSpan; import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; /** * SofaTracerPercentageBasedSampler @@ -29,20 +30,20 @@ */ public class SofaTracerPercentageBasedSampler implements Sampler { - static final String TYPE = "PercentageBasedSampler"; + public static final String TYPE = "PercentageBasedSampler"; - private final AtomicInteger counter = new AtomicInteger(0); + private final AtomicLong counter = new AtomicLong(0); private final BitSet sampleDecisions; private final SamplerProperties configuration; public SofaTracerPercentageBasedSampler(SamplerProperties configuration) { - int outOf100 = (int) (configuration.getPercentage() * 100.0f); + int outOf100 = (int) (configuration.getPercentage()); this.sampleDecisions = randomBitSet(100, outOf100, new Random()); this.configuration = configuration; } @Override - public SamplingStatus sample(String operation, String traceId) { + public SamplingStatus sample(SofaTracerSpan sofaTracerSpan) { SamplingStatus samplingStatus = new SamplingStatus(); Map tags = new HashMap(); tags.put(SofaTracerConstant.SAMPLER_TYPE_TAG_KEY, TYPE); @@ -57,12 +58,7 @@ public SamplingStatus sample(String operation, String traceId) { samplingStatus.setSampled(true); return samplingStatus; } - int i, j; - do { - i = this.counter.get(); - j = (i + 1) % 100; - } while (!this.counter.compareAndSet(i, j)); - boolean result = this.sampleDecisions.get(i); + boolean result = this.sampleDecisions.get((int) (this.counter.getAndIncrement() % 100)); samplingStatus.setSampled(result); return samplingStatus; } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java index 6b6c483c..6c01da31 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java @@ -65,4 +65,5 @@ public class CommonSpanTags { * 响应大小 */ public static final String RESP_SIZE = "resp.size.bytes"; + } \ No newline at end of file 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 c421cbfe..9f179a23 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 @@ -205,6 +205,8 @@ public SofaTracerSpan serverReceive(SofaTracerSpanContext sofaTracerSpanContext) //root 开始或者复用 if (sofaTracerSpanContext == null) { sofaTracerSpanContext = SofaTracerSpanContext.rootStart(); + } else { + sofaTracerSpanContext.setSpanId(sofaTracerSpanContext.nextChildContextId()); } sofaTracerSpanServer = this.genSeverSpanInstance(System.currentTimeMillis(), StringUtils.EMPTY_STRING, sofaTracerSpanContext, null); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java index 5189bea8..17d07f76 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java @@ -29,9 +29,6 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; -import java.util.stream.Stream; import static org.junit.Assert.assertEquals; @@ -55,11 +52,7 @@ public abstract class AbstractTestBase { */ @BeforeClass public static void beforeClass() { - File[] traceFiles = customFileLog("").listFiles(); - if (traceFiles == null) { - return; - } - for (File file : traceFiles) { + for (File file : customFileLog("").listFiles()) { if (file.getPath().contains("tracer-self.log") || file.getPath().contains("sync.log") || file.getPath().contains("rpc-profile.log") || file.getPath().contains("middleware_error.log")) { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java index 2cf5c718..0f45b048 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java @@ -19,9 +19,11 @@ import com.alipay.common.tracer.core.SofaTracer; import com.alipay.common.tracer.core.TestUtil; import com.alipay.common.tracer.core.base.AbstractTestBase; +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; import com.alipay.common.tracer.core.reporter.digest.DiskReporterImpl; import com.alipay.common.tracer.core.reporter.type.TracerSystemLogEnum; +import com.alipay.common.tracer.core.samplers.SofaTracerPercentageBasedSampler; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tags.SpanTags; import com.alipay.common.tracer.core.tracertest.encoder.ClientSpanEncoder; @@ -58,7 +60,11 @@ public class CommonSpanEncoderTest extends AbstractTestBase { private String appName = "appName"; @Before - public void setup() { + public void setup() throws Exception { + SofaTracerConfiguration.setProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY, + SofaTracerPercentageBasedSampler.TYPE); + SofaTracerConfiguration.setProperty( + SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY, "100"); DiskReporterImpl clientDigestReporter = new DiskReporterImpl(clientLogType, new ClientSpanEncoder()); sofaTracer = new SofaTracer.Builder("commonProfileTracerType") @@ -66,7 +72,7 @@ public void setup() { } /** - * Method: encode(SofaTracerSpan span)4 + * Method: encode(SofaTracerSpan span) */ @Test public void testEncode() throws Exception { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/samplers/SamplerPropertiesTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/samplers/SamplerPropertiesTest.java index e0456c6f..28ffae6d 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/samplers/SamplerPropertiesTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/samplers/SamplerPropertiesTest.java @@ -38,12 +38,12 @@ public void before() { @Test public void getPercentage() { - Assert.assertTrue(samplerProperties.getPercentage() == 0.1f); + Assert.assertTrue(samplerProperties.getPercentage() == 100); } @Test public void setPercentage() { - samplerProperties.setPercentage(0.2f); - Assert.assertTrue(samplerProperties.getPercentage() == 0.2f); + samplerProperties.setPercentage(20); + Assert.assertTrue(samplerProperties.getPercentage() == 20); } } \ No newline at end of file diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSamplerTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSamplerTest.java index ed808317..68422e0d 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSamplerTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSamplerTest.java @@ -16,6 +16,12 @@ */ package com.alipay.common.tracer.core.samplers; +import com.alipay.common.tracer.core.SofaTracer; +import com.alipay.common.tracer.core.reporter.digest.DiskReporterImpl; +import com.alipay.common.tracer.core.reporter.facade.Reporter; +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 org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -29,13 +35,27 @@ */ public class SofaTracerPercentageBasedSamplerTest { + private final String tracerType = "SofaTracerSpanTest"; + private final String clientLogType = "client-log-test.log"; + private final String serverLogType = "server-log-test.log"; + SamplerProperties samplerProperties; SofaTracerPercentageBasedSampler sofaTracerPercentageBasedSampler; + private SofaTracer sofaTracer; + private SofaTracerSpan sofaTracerSpan; + @Before public void setUp() { samplerProperties = new SamplerProperties(); sofaTracerPercentageBasedSampler = new SofaTracerPercentageBasedSampler(samplerProperties); + Reporter clientReporter = new DiskReporterImpl(clientLogType, new ClientSpanEncoder()); + Reporter serverReporter = new DiskReporterImpl(serverLogType, new ServerSpanEncoder()); + sofaTracer = new SofaTracer.Builder(tracerType) + .withTag("tracer", "SofaTraceContextHolderTest").withClientReporter(clientReporter) + .withServerReporter(serverReporter).build(); + sofaTracerSpan = (SofaTracerSpan) this.sofaTracer.buildSpan("").start(); + sofaTracerSpan.getSofaTracerSpanContext().setTraceId(""); } @After @@ -46,11 +66,11 @@ public void close() { @Test public void sample() { samplerProperties.setPercentage(0); - SamplingStatus sampleStatusFalse = sofaTracerPercentageBasedSampler.sample("", ""); + SamplingStatus sampleStatusFalse = sofaTracerPercentageBasedSampler.sample(sofaTracerSpan); Assert.assertTrue(!sampleStatusFalse.isSampled()); samplerProperties.setPercentage(100); - SamplingStatus sampleStatusTrue = sofaTracerPercentageBasedSampler.sample("", ""); + SamplingStatus sampleStatusTrue = sofaTracerPercentageBasedSampler.sample(sofaTracerSpan); Assert.assertTrue(sampleStatusTrue.isSampled()); } 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 aa50710e..1d4dd2a7 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 @@ -24,6 +24,7 @@ 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.SofaTracerSpan; import com.alipay.common.tracer.core.tracertest.encoder.ClientSpanEncoder; import com.alipay.common.tracer.core.tracertest.encoder.ServerSpanEncoder; @@ -38,6 +39,8 @@ import org.junit.Before; import org.junit.Test; +import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; @@ -64,6 +67,12 @@ public class SofaTracerTest extends AbstractTestBase { @Before public void beforeInstance() throws IOException { + + 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()); @@ -197,10 +206,10 @@ public void testTracerClose() { Sampler sampler = mock(Sampler.class); SofaTracer sofaTracer = new SofaTracer.Builder(tracerType).withClientReporter(reporter) .withSampler(sampler).build(); - sofaTracer.close(); //确认被调用 verify(reporter).close(); + sampler.close(); verify(sampler).close(); } @@ -493,7 +502,7 @@ public void testWithStatsReporterSofaTracerDigestReporter() { */ @Test public void testWithSampler() throws Exception { - assertTrue(this.sofaTracer.getSampler() == null); + assertTrue(this.sofaTracer.getSampler() != null); } } diff --git a/tracer-samples/tracer-sample-with-zipkin/README.md b/tracer-samples/tracer-sample-with-zipkin/README.md index 5700e72a..7835ce5e 100644 --- a/tracer-samples/tracer-sample-with-zipkin/README.md +++ b/tracer-samples/tracer-sample-with-zipkin/README.md @@ -2,6 +2,8 @@ 本示例演示如何在集成了 SOFATracer 的应用,通过配置 SOFATracer 将链路数据远程汇报到 [Zipkin](https://zipkin.io/)。 +下面的示例中将分别演示在 SOFABoot/SpringBoot 工程中 以及 非 SOFABoot/SpringBoot 工程中如何使用。 + ## 环境准备 要使用 SOFABoot,需要先准备好基础环境,SOFABoot 依赖以下环境: @@ -30,29 +32,33 @@ ${sofa.boot.version} ``` + 这里的 ${sofa.boot.version} 指定具体的 SOFABoot 版本,参考[发布历史](https://github.com/alipay/sofa-build/releases)。 -然后,在工程中添加 SOFATracer 依赖: +## 添加 SOFATracer starter -``` +工程中添加 SOFATracer 依赖: + +```xml com.alipay.sofa tracer-sofa-boot-starter ``` +## 配置文件 + 最后,在工程的 `application.properties` 文件下添加一个 SOFATracer 要使用的参数,包括`spring.application.name` 用于标示当前应用的名称;`logging.path` 用于指定日志的输出目录。 -``` +```properties # Application Name spring.application.name=SOFATracerReportZipkin # logging path logging.path=./logs -``` -## 启动 Zipkin 服务端 - -启动 Zipkin 服务端用于接收 SOFATracer 汇报的链路数据,并做展示。Zipkin Server 的搭建可以[参考此文档](https://zipkin.io/)进行配置和服务端的搭建。 +com.alipay.sofa.tracer.zipkin.enabled=true +com.alipay.sofa.tracer.zipkin.baseUrl=http://localhost:9411 +``` ## 配置 Zipkin 依赖 @@ -71,15 +77,13 @@ logging.path=./logs ``` -## 启用 SOFATracer 汇报数据到 Zipkin - -在配置文件 `application.properties` 中,配置 Zipkin Server 端的地址 `com.alipay.sofa.tracer.zipkin.baseUrl=http://${ip}:${port}`。 +## 启动 Zipkin 服务端 -按照上文完成了依赖和 Zipkin Server 的配置后,即激活了远程上报的能力。本示例中已经搭建好的 Zipkin Server 端地址是 `http://zipkin-cloud-3.host.net:9411`。 +启动 Zipkin 服务端用于接收 SOFATracer 汇报的链路数据,并做展示。Zipkin Server 的搭建可以[参考此文档](https://zipkin.io/)进行配置和服务端的搭建。 ## 运行 -可以将工程导入到 IDE 中运行生成的工程里面中的 `main` 方法(一般上在 XXXApplication 这个类中)启动应用,也可以直接在该工程的根目录下运行 `mvn spring-boot:run`,将会在控制台中看到启动日志: +可以将工程导入到 IDE 中运行生成的工程里面中的 `main` 方法启动应用,也可以直接在该工程的根目录下运行 `mvn spring-boot:run`,将会在控制台中看到启动日志: ``` 2018-05-12 13:12:05.868 INFO 76572 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'SpringMvcSofaTracerFilter' to urls: [/*] @@ -87,7 +91,7 @@ logging.path=./logs 2018-05-12 13:12:07.164 INFO 76572 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) ``` -可以通过在浏览器中输入 [http://localhost:8080/zipkin](http://localhost:8080/zipkin) 来访问 REST 服务,结果类似如下: +可以通过在浏览器中输入 [http://localhost:8080/helloZipkin](http://localhost:8080/helloZipkin) 来访问 REST 服务,结果类似如下: ```json { @@ -99,6 +103,8 @@ logging.path=./logs ## 查看 Zipkin 服务端展示 -打开 Zipkin 服务端界面,假设我们部署的 Zipkin 服务端的地址是 `http://zipkin-cloud-3.host.net:9411`,打开 URL 并搜索 `zipkin`(由于我们本地访问的地址是 localhost:8080/zipkin),可以看到展示的链路图。 +打开 Zipkin 服务端界面,假设我们部署的 Zipkin 服务端的地址是 `http://zipkin-cloud-3.host.net:9411`,打开 URL 并搜索 `zipkin`(由于我们本地访问的地址是 localhost:8080/helloZipkin),可以看到展示的链路图。 +## Spring 工程运行 +对于一般的 Spring 工程,我们通常使用 tomcat/jetty 作为 servlet 容器来启动应用。具体工程参考 [在 Spring 工程中使用 SOFATracer](https://github.com/glmapper/tracer-zipkin-plugin-demo) diff --git a/tracer-samples/tracer-sample-with-zipkin/src/main/java/com/alipay/sofa/tracer/examples/zipkin/controller/SampleRestController.java b/tracer-samples/tracer-sample-with-zipkin/src/main/java/com/alipay/sofa/tracer/examples/zipkin/controller/SampleRestController.java index c0f413cb..e4e9a4a4 100644 --- a/tracer-samples/tracer-sample-with-zipkin/src/main/java/com/alipay/sofa/tracer/examples/zipkin/controller/SampleRestController.java +++ b/tracer-samples/tracer-sample-with-zipkin/src/main/java/com/alipay/sofa/tracer/examples/zipkin/controller/SampleRestController.java @@ -25,10 +25,10 @@ import java.util.concurrent.atomic.AtomicLong; /** - * SampleRestController + * SampleRestController for test * - * @author yangguanchao - * @since 2018/05/11 + * @author guolei.sgl + * @since v.2.3.0 */ @RestController public class SampleRestController { @@ -42,7 +42,7 @@ public class SampleRestController { * @param name name * @return map */ - @RequestMapping("/zipkin") + @RequestMapping("/helloZipkin") public Map zipkin(@RequestParam(value = "name", defaultValue = "SOFATracer Zipkin Remote Report") String name) { Map resultMap = new HashMap(); resultMap.put("success", true); diff --git a/tracer-samples/tracer-sample-with-zipkin/src/main/resources/application.properties b/tracer-samples/tracer-sample-with-zipkin/src/main/resources/application.properties index 2b21a4f4..39db6982 100644 --- a/tracer-samples/tracer-sample-with-zipkin/src/main/resources/application.properties +++ b/tracer-samples/tracer-sample-with-zipkin/src/main/resources/application.properties @@ -20,4 +20,4 @@ spring.application.name=SOFATracerReportZipkin # logging path logging.path=./logs # zipkin server url -com.alipay.sofa.tracer.zipkin.baseUrl=http://zipkin-cloud.host.net:9411 +com.alipay.sofa.tracer.zipkin.baseUrl=http://localhost:9411 diff --git a/tracer-sofa-boot-starter/pom.xml b/tracer-sofa-boot-starter/pom.xml index 4a6419ea..49552c02 100644 --- a/tracer-sofa-boot-starter/pom.xml +++ b/tracer-sofa-boot-starter/pom.xml @@ -8,7 +8,6 @@ 3.0.3-SNAPSHOT ../pom.xml - tracer-sofa-boot-starter @@ -37,10 +36,18 @@ com.alipay.sofa sofa-tracer-datasource-plugin + + com.alipay.sofa + sofa-tracer-zipkin-plugin + org.springframework.boot spring-boot + + org.springframework + spring-web + org.springframework.boot spring-boot-autoconfigure @@ -49,10 +56,6 @@ com.alipay.sofa infra-sofa-boot-starter - - com.alipay.sofa.common - log-sofa-boot-starter - org.springframework.boot @@ -110,10 +113,28 @@ test - org.springframework.boot - spring-boot-starter-webflux + com.alibaba + druid + 1.0.12 + test + + + c3p0 + c3p0 + 0.9.1.1 + test + + + org.apache.tomcat + tomcat-jdbc + 8.5.31 + test + + + commons-dbcp + commons-dbcp + 1.4 test - diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporter.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporter.java deleted file mode 100644 index cac45f11..00000000 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporter.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * 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. - */ -package com.alipay.sofa.tracer.spring.zipkin.adapter; - -import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; -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.utils.StringUtils; -import io.opentracing.tag.Tags; -import zipkin2.Endpoint; -import zipkin2.Span; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.util.Map; - -/*** - * ZipkinV2SpanAdapter : convent sofaTracer span model to zipkin span model - * @author guolei.sgl 05/09/2018 - * @since v.2.3.0 - */ -public class ZipkinV2SpanAdapter { - - /** - * cache and performance improve - */ - private int ipAddressInt = -1; - - /** - * convent sofaTracerSpan model to zipKinSpan model - * @param sofaTracerSpan original span - * @return zipkinSpan model - */ - public Span convertToZipkinSpan(SofaTracerSpan sofaTracerSpan) { - if (sofaTracerSpan == null) { - return null; - } - // spanId、parentId、tracerId - Span.Builder zipkinSpanBuilder = Span.newBuilder(); - SofaTracerSpanContext context = sofaTracerSpan.getSofaTracerSpanContext(); - zipkinSpanBuilder.traceId(context.getTraceId()); - zipkinSpanBuilder.id(spanIdToLong(context.getSpanId())); - if (StringUtils.isNotBlank(context.getParentId())) { - zipkinSpanBuilder.parentId(spanIdToLong(context.getParentId())); - } - - // timestamp & duration - long start = sofaTracerSpan.getStartTime() * 1000; - long finish = sofaTracerSpan.getEndTime() * 1000; - zipkinSpanBuilder.timestamp(start); - zipkinSpanBuilder.duration(finish - start); - - // kind - Map tagsWithStr = sofaTracerSpan.getTagsWithStr(); - String kindStr = tagsWithStr.get(Tags.SPAN_KIND.getKey()); - if (StringUtils.isNotBlank(kindStr) && kindStr.equals(Tags.SPAN_KIND_SERVER)) { - zipkinSpanBuilder.kind(Span.Kind.SERVER); - } else { - zipkinSpanBuilder.kind(Span.Kind.CLIENT); - } - - // Endpoint - Endpoint endpoint = getZipkinEndpoint(sofaTracerSpan); - zipkinSpanBuilder.localEndpoint(endpoint); - - // Tags - this.addZipkinTags(zipkinSpanBuilder, sofaTracerSpan); - - // span name - String operationName = sofaTracerSpan.getOperationName(); - if (StringUtils.isNotBlank(operationName)) { - zipkinSpanBuilder.name(operationName); - } else { - zipkinSpanBuilder.name(StringUtils.EMPTY_STRING); - } - - // Annotations - this.addZipkinAnnotations(zipkinSpanBuilder, sofaTracerSpan); - - return zipkinSpanBuilder.build(); - } - - public static long spanIdToLong(String spanId) { - return FNV64HashCode(spanId); - } - - /** - * from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash - * @param data String data - * @return fnv hash code - */ - public static long FNV64HashCode(String data) { - //hash FNVHash64 : http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param - long hash = 0xcbf29ce484222325L; - for (int i = 0; i < data.length(); ++i) { - char c = data.charAt(i); - hash ^= c; - hash *= 0x100000001b3L; - } - return hash; - } - - private Endpoint getZipkinEndpoint(SofaTracerSpan span) { - InetAddress ipAddress = null; - if (this.ipAddressInt <= 0) { - try { - ipAddress = InetAddress.getLocalHost(); - this.ipAddressInt = ByteBuffer.wrap(ipAddress.getAddress()).getInt(); - } catch (UnknownHostException e) { - //127.0.0.1 256 进制 - this.ipAddressInt = 256 * 256 * 256 * 127 + 1; - } - } - String appName = span.getTagsWithStr().get(CommonSpanTags.LOCAL_APP); - return Endpoint.newBuilder().serviceName(appName).ip(ipAddress).build(); - } - - /** - * 将Baggage中的数据也放在tags中 - * @param zipkinSpan - * @param span - */ - private void addZipkinTagsWithBaggage(Span.Builder zipkinSpan, SofaTracerSpan span) { - SofaTracerSpanContext sofaTracerSpanContext = span.getSofaTracerSpanContext(); - if (sofaTracerSpanContext != null) { - Map sysBaggage = sofaTracerSpanContext.getSysBaggage(); - for (Map.Entry e : sysBaggage.entrySet()) { - zipkinSpan.putTag(e.getKey(), e.getValue()); - } - Map bizBaggage = sofaTracerSpanContext.getBizBaggage(); - for (Map.Entry e : bizBaggage.entrySet()) { - zipkinSpan.putTag(e.getKey(), e.getValue()); - } - } - } - - /** - * convent Annotations - * @param zipkinSpan - * @param span - */ - private void addZipkinAnnotations(Span.Builder zipkinSpan, SofaTracerSpan span) { - for (LogData logData : span.getLogs()) { - Map fields = logData.getFields(); - if (fields == null || fields.size() <= 0) { - continue; - } - for (Map.Entry entry : fields.entrySet()) { - // zipkin has been support default log event depend on span kind & serviceName - if (!(entry.getValue().toString().equals(LogData.CLIENT_RECV_EVENT_VALUE) - || entry.getValue().toString().equals(LogData.CLIENT_SEND_EVENT_VALUE) - || entry.getValue().toString().equals(LogData.SERVER_RECV_EVENT_VALUE) || entry - .getValue().toString().equals(LogData.SERVER_SEND_EVENT_VALUE))) { - zipkinSpan.addAnnotation(logData.getTime() * 1000, entry.getValue().toString()); - } - } - } - } - - /** - * convent tags - * @param zipkinSpan - * @param span - */ - private void addZipkinTags(Span.Builder zipkinSpan, SofaTracerSpan span) { - - for (Map.Entry e : span.getTagsWithStr().entrySet()) { - zipkinSpan.putTag(e.getKey(), e.getValue()); - } - for (Map.Entry e : span.getTagsWithNumber().entrySet()) { - zipkinSpan.putTag(e.getKey(), e.getValue().toString()); - } - for (Map.Entry e : span.getTagsWithBool().entrySet()) { - zipkinSpan.putTag(e.getKey(), e.getValue().toString()); - } - - addZipkinTagsWithBaggage(zipkinSpan, span); - } -} diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerRestTemplateCustomizer.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerRestTemplateCustomizer.java deleted file mode 100644 index f63b37d5..00000000 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerRestTemplateCustomizer.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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. - */ -package com.alipay.sofa.tracer.boot.zipkin.configuration; - -import com.alipay.sofa.tracer.boot.zipkin.properties.ZipkinSofaTracerProperties; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.web.client.RestTemplate; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.zip.GZIPOutputStream; - -/** - * ZipkinSofaTracerRestTemplateCustomizer - * - * @author yangguanchao - * @since 2018/05/01 - */ -public class ZipkinSofaTracerRestTemplateCustomizer { - - private ZipkinSofaTracerProperties zipkinSofaTracerProperties; - - public ZipkinSofaTracerRestTemplateCustomizer(ZipkinSofaTracerProperties zipkinSofaTracerProperties) { - this.zipkinSofaTracerProperties = zipkinSofaTracerProperties; - } - - public void customize(RestTemplate restTemplate) { - if (this.zipkinSofaTracerProperties == null || restTemplate == null) { - return; - } - if (this.zipkinSofaTracerProperties.getCompression().isEnabled()) { - restTemplate.getInterceptors().add(0, new GzipInterceptor()); - } - } - - private class GzipInterceptor implements ClientHttpRequestInterceptor { - - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) - throws IOException { - request.getHeaders().add("Content-Encoding", "gzip"); - ByteArrayOutputStream gzipped = new ByteArrayOutputStream(); - GZIPOutputStream compressor = null; - try { - compressor = new GZIPOutputStream(gzipped); - compressor.write(body); - } finally { - if (compressor != null) { - compressor.close(); - } - } - return execution.execute(request, gzipped.toByteArray()); - } - } -} diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/properties/ZipkinSofaTracerProperties.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/properties/ZipkinSofaTracerProperties.java index fed66503..1aaaae85 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/properties/ZipkinSofaTracerProperties.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/properties/ZipkinSofaTracerProperties.java @@ -21,8 +21,8 @@ /** * ZipkinSofaTracerProperties * - * @author yangguanchao - * @since 2018/05/01 + * @author guolei.sgl + * @since v2.3.0 */ @ConfigurationProperties("com.alipay.sofa.tracer.zipkin") public class ZipkinSofaTracerProperties { @@ -30,10 +30,12 @@ public class ZipkinSofaTracerProperties { /** * URL of the zipkin query server instance. */ - private String baseUrl = "http://localhost:9411/"; - private boolean enabled = true; - private int flushInterval = 1; - private Compression compression = new Compression(); + private String baseUrl = "http://localhost:9411/"; + private boolean enabled = true; + /** + * When enabled, spans are gzipped before sent to the zipkin server + */ + private boolean gzipped = false; public String getBaseUrl() { return this.baseUrl; @@ -43,14 +45,6 @@ public boolean isEnabled() { return this.enabled; } - public int getFlushInterval() { - return this.flushInterval; - } - - public Compression getCompression() { - return this.compression; - } - public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } @@ -59,27 +53,11 @@ public void setEnabled(boolean enabled) { this.enabled = enabled; } - public void setFlushInterval(int flushInterval) { - this.flushInterval = flushInterval; + public boolean isGzipped() { + return gzipped; } - public void setCompression(Compression compression) { - this.compression = compression; - } - - /** - * When enabled, spans are gzipped before sent to the zipkin server - */ - public static class Compression { - - private boolean enabled = false; - - public boolean isEnabled() { - return this.enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } + public void setGzipped(boolean gzipped) { + this.gzipped = gzipped; } } diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/sender/ZipkinRestTemplateSender.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/sender/ZipkinRestTemplateSender.java deleted file mode 100644 index 0e1bcbda..00000000 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/sender/ZipkinRestTemplateSender.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * 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. - */ -package com.alipay.sofa.tracer.boot.zipkin.sender; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.web.client.RestTemplate; -import zipkin2.Call; -import zipkin2.codec.Encoding; -import zipkin2.reporter.BytesMessageEncoder; -import zipkin2.reporter.Sender; -import java.net.URI; -import java.util.List; - -/** - * ZipkinRestTemplateSender - * - * @author yangguanchao - * @since 2018/05/01 - */ -public class ZipkinRestTemplateSender extends Sender { - - private RestTemplate restTemplate; - - private String url; - - public ZipkinRestTemplateSender(RestTemplate restTemplate, String baseUrl) { - this.restTemplate = restTemplate; - this.url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "api/v2/spans"; - } - - @Override - public Encoding encoding() { - return Encoding.JSON; - } - - @Override - public int messageMaxBytes() { - // Max span size is 2MB - return 2 * 1024 * 1024; - } - - @Override - public int messageSizeInBytes(List spans) { - return encoding().listSizeInBytes(spans); - } - - @Override - public Call sendSpans(List encodedSpans) { - try { - byte[] message = BytesMessageEncoder.JSON.encode(encodedSpans); - post(message); - } catch (Throwable e) { - if (e instanceof Error) { - throw (Error) e; - } - } - return null; - } - - private void post(byte[] json) { - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON); - RequestEntity requestEntity = new RequestEntity(json, httpHeaders, - HttpMethod.POST, URI.create(this.url)); - this.restTemplate.exchange(requestEntity, String.class); - } -} diff --git a/tracer-sofa-boot-starter/src/test/resources/application-zipkin.properties b/tracer-sofa-boot-starter/src/test/resources/application-zipkin.properties index 97cffbe5..7136e477 100644 --- a/tracer-sofa-boot-starter/src/test/resources/application-zipkin.properties +++ b/tracer-sofa-boot-starter/src/test/resources/application-zipkin.properties @@ -17,3 +17,6 @@ spring.application.name=zipkin-client com.alipay.sofa.tracer.springmvc.jsonOutput=false +com.alipay.sofa.tracer.zipkin.enabled=true +com.alipay.sofa.tracer.zipkin.baseUrl=http://localhost:9411 +com.alipay.sofa.tracer.zipkin.gzipped=true diff --git a/tracer-sofa-boot-starter/src/test/resources/application.properties b/tracer-sofa-boot-starter/src/test/resources/application.properties index cf5cac3e..60110bf3 100644 --- a/tracer-sofa-boot-starter/src/test/resources/application.properties +++ b/tracer-sofa-boot-starter/src/test/resources/application.properties @@ -1 +1,13 @@ spring.application.name=test-app-name +spring.datasource.url=jdbc:mysql://localhost:3306/sofa +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.username=xxxx +spring.datasource.password=xxxx +spring.datasource.type=com.zaxxer.hikari.HikariDataSource +spring.datasource.hikari.minimum-idle=3 +spring.datasource.hikari.maximum-pool-size=5 +spring.datasource.hikari.idle-timeout=30000 +spring.datasource.hikari.pool-name=SofaHikariCPDatasource +spring.datasource.hikari.max-lifetime=1800000 +spring.datasource.hikari.connection-timeout=30000 +spring.datasource.hikari.connection-test-query=SELECT 1 diff --git a/tracer-sofa-boot-starter/src/test/resources/hikariDataSource.xml b/tracer-sofa-boot-starter/src/test/resources/hikariDataSource.xml index e7af436b..e9bca35d 100644 --- a/tracer-sofa-boot-starter/src/test/resources/hikariDataSource.xml +++ b/tracer-sofa-boot-starter/src/test/resources/hikariDataSource.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + From 2604483eef29b1920b6ea1748a44dc1b7685dc84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Fri, 9 Nov 2018 12:28:28 +0800 Subject: [PATCH 04/24] rename zipkin's base package name to com.alipay.sofa.tracer.plugins.zipkin --- tracer-samples/pom.xml | 1 + .../tracer-sample-with-sampler/README.md | 94 +++++++++++++++++++ .../tracer-sample-with-sampler/pom.xml | 49 ++++++++++ .../src/main/resources/application.properties | 6 +- 4 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 tracer-samples/tracer-sample-with-sampler/README.md create mode 100644 tracer-samples/tracer-sample-with-sampler/pom.xml diff --git a/tracer-samples/pom.xml b/tracer-samples/pom.xml index 988fe83d..c9ac5e6c 100644 --- a/tracer-samples/pom.xml +++ b/tracer-samples/pom.xml @@ -19,6 +19,7 @@ tracer-sample-with-sofarpc tracer-sample-with-httpclient tracer-sample-with-h2 + tracer-sample-with-sampler diff --git a/tracer-samples/tracer-sample-with-sampler/README.md b/tracer-samples/tracer-sample-with-sampler/README.md new file mode 100644 index 00000000..6c489e36 --- /dev/null +++ b/tracer-samples/tracer-sample-with-sampler/README.md @@ -0,0 +1,94 @@ +## 使用 SOFATracer 的采样能力 + +目前 SOFATracer 提供了两种采样模式,一种是基于BitSet实现的基于固定采样率的采样模式;另外一种是提供给用户自定义实现采样的采样模式。下面通过案例来演示如何使用。 + +本示例基于 tracer-sample-with-springmvc 工程;除 application.properties 之外,其他均相同。 + +### 基于固定采样率的采样模式 + +#### 在 application.properties 中增加采样相关配置项 + +```xml +#采样率 0~1 +com.alipay.sofa.tracer.samplerPercentage=1 +#采样模式类型名称 +com.alipay.sofa.tracer.samplerName=PercentageBasedSampler +``` + +#### 验证方式 + +* 当采样率设置为1时,每次都会打印摘要日志。 +* 当采样率设置为0时,不打印 +* 当采样率设置为0~1之间时,按概率打印 + +以请求 10 次来验证下结果。 + +1、当采样率设置为1时,每次都会打印摘要日志 + +启动工程,浏览器中输入:http://localhost:8080/springmvc ;并且刷新地址10次,查看日志如下: + +```xml +{"time":"2018-11-09 11:54:47.643","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173568757510019269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":68,"current.thread.name":"http-nio-8080-exec-1","baggage":""} +{"time":"2018-11-09 11:54:50.980","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569097710029269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":3,"current.thread.name":"http-nio-8080-exec-2","baggage":""} +{"time":"2018-11-09 11:54:51.542","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569153910049269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":3,"current.thread.name":"http-nio-8080-exec-4","baggage":""} +{"time":"2018-11-09 11:54:52.061","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569205910069269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-6","baggage":""} +{"time":"2018-11-09 11:54:52.560","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569255810089269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-8","baggage":""} +{"time":"2018-11-09 11:54:52.977","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569297610109269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":1,"current.thread.name":"http-nio-8080-exec-10","baggage":""} +{"time":"2018-11-09 11:54:53.389","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569338710129269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-2","baggage":""} +{"time":"2018-11-09 11:54:53.742","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569374110149269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":1,"current.thread.name":"http-nio-8080-exec-4","baggage":""} +{"time":"2018-11-09 11:54:54.142","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569414010169269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-6","baggage":""} +{"time":"2018-11-09 11:54:54.565","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569456310189269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-8","baggage":""} +``` + +2、当采样率设置为0时,不打印 + +启动工程,浏览器中输入:http://localhost:8080/springmvc ;并且刷新地址10次,查看 ./logs/tracerlog/ 目录,没有 spring-mvc-degist.log 日志文件 + +3、当采样率设置为0~1之间时,按概率打印 + +这里设置成 0.2 + +* 刷新10次请求 +```xml +{"time":"2018-11-09 12:14:29.466","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173686946410159846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-5","baggage":""} +``` + +* 刷新20次请求 +```xml +{"time":"2018-11-09 12:14:29.466","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173686946410159846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-5","baggage":""} +{"time":"2018-11-09 12:15:21.776","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173692177410319846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-2","baggage":""} +{"time":"2018-11-09 12:15:22.439","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173692243810359846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":1,"current.thread.name":"http-nio-8080-exec-6","baggage":""} +{"time":"2018-11-09 12:15:22.817","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173692281510379846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-8","baggage":""} +``` +> 按 20% 进行采样,测试结果仅供参考 + +### 自定义采样模式 + +SOFATracer 中提供了一个采样率计算的接口。采样模式需设置为 OpenRulesSampler;当 com.alipay.sofa.tracer.samplerName=OpenRulesSampler时,用户需实现 OpenRulesSampler.Rule 这个抽象类。 + +#### 在 application.properties 中增加采样相关配置项 + + +```xml +#采样模式类型名称 +com.alipay.sofa.tracer.samplerName=OpenRulesSampler +#自定义采样规则实现类全限定名 +com.alipay.sofa.tracer.samplerName.samplerCustomRuleClassName=com.alipay.sofa.tracer.examples.springmvc.sampler.CustomOpenRulesSamplerRuler +``` + +#### 自定义采样规则类 + +```java +public class CustomOpenRulesSamplerRuler extends OpenRulesSampler.Rule { + @Override + public boolean matches(SofaTracerSpan sofaTracerSpan) { + if (sofaTracerSpan.getSofaTracer().getTracerType().equals("springmvc")){ + return true; + } + return false; + } +} +``` + +在 matches 方法中,用户可以根据当前 sofaTracerSpan 提供的信息来决定是否进行打印。这个案例是通过判断当前tracerType来决定是否采样,如果tracerType是springmvc则采样,否则不采样。 +相关实验结果,大家可以自行验证下。 diff --git a/tracer-samples/tracer-sample-with-sampler/pom.xml b/tracer-samples/tracer-sample-with-sampler/pom.xml new file mode 100644 index 00000000..59494018 --- /dev/null +++ b/tracer-samples/tracer-sample-with-sampler/pom.xml @@ -0,0 +1,49 @@ + + + + sofa-tracer-samples + com.alipay.sofa + 2.2.0 + + + 4.0.0 + + tracer-sample-with-sampler + + + ${project.basedir}/../.. + + + + + + com.alipay.sofa + tracer-sofa-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/tracer-samples/tracer-sample-with-springmvc/src/main/resources/application.properties b/tracer-samples/tracer-sample-with-springmvc/src/main/resources/application.properties index ac6115ec..75caa4f1 100644 --- a/tracer-samples/tracer-sample-with-springmvc/src/main/resources/application.properties +++ b/tracer-samples/tracer-sample-with-springmvc/src/main/resources/application.properties @@ -18,4 +18,8 @@ # Application Name spring.application.name=SOFATracerSpringMVC # logging path -logging.path=./logs \ No newline at end of file +logging.path=./logs + +com.alipay.sofa.tracer.samplerPercentage=0.2 +com.alipay.sofa.tracer.samplerName=PercentageBasedSampler +com.alipay.sofa.tracer.samplerCustomRuleClassName=com.alipay.sofa.tracer.examples.springmvc.sampler.CustomOpenRulesSamplerRuler \ No newline at end of file From abd7c9850992b24eeef9557b8689d1fde1b0706b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Mon, 11 Mar 2019 11:38:59 +0800 Subject: [PATCH 05/24] cheery pick okhttp --- pom.xml | 1 + .../sofa-tracer-okhttp-plugin/pom.xml | 68 +++++++++++ .../okhttp/OkHttpDigestJsonEncoder.java | 88 ++++++++++++++ .../tracer/plugins/okhttp/OkHttpLogEnum.java | 52 ++++++++ .../plugins/okhttp/OkHttpRequestCarrier.java | 51 ++++++++ .../okhttp/OkHttpStatJsonReporter.java | 115 ++++++++++++++++++ .../tracer/plugins/okhttp/OkHttpTracer.java | 84 +++++++++++++ .../okhttp/SofaTracerOkHttpBuilder.java | 44 +++++++ .../SofaTracerOkHttpInterceptor.java | 102 ++++++++++++++++ .../src/main/resources/application.properties | 0 .../plugins/okhttp/base/OkHttpTracerTest.java | 110 +++++++++++++++++ .../okhttp/base/SpringBootWebApplication.java | 33 +++++ .../base/client/OkHttpClientInstance.java | 69 +++++++++++ .../okhttp/base/controller/PostBody.java | 79 ++++++++++++ .../base/controller/SampleRestController.java | 68 +++++++++++ 15 files changed, 964 insertions(+) create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpDigestJsonEncoder.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpLogEnum.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpRequestCarrier.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpStatJsonReporter.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpTracer.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/SofaTracerOkHttpBuilder.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/interceptor/SofaTracerOkHttpInterceptor.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/resources/application.properties create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerTest.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/SpringBootWebApplication.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/client/OkHttpClientInstance.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/controller/PostBody.java create mode 100644 sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/controller/SampleRestController.java diff --git a/pom.xml b/pom.xml index a558347a..9594e6fa 100644 --- a/pom.xml +++ b/pom.xml @@ -20,6 +20,7 @@ tracer-extensions sofa-tracer-plugins/sofa-tracer-springmvc-plugin sofa-tracer-plugins/sofa-tracer-httpclient-plugin + sofa-tracer-plugins/sofa-tracer-okhttp-plugin sofa-tracer-plugins/sofa-tracer-datasource-plugin sofa-tracer-plugins/sofa-tracer-zipkin-plugin tracer-all diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml new file mode 100644 index 00000000..0b20a9ed --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml @@ -0,0 +1,68 @@ + + + + tracer-all-parent + com.alipay.sofa + 2.3.1 + ../../pom.xml + + 4.0.0 + + sofa-tracer-okhttp-plugin + + + + com.alipay.sofa + tracer-core + + + com.squareup.okhttp3 + okhttp + 3.12.1 + + + + org.jmockit + jmockit + test + + + org.mockito + mockito-core + test + + + org.jmockit + jmockit-coverage + test + + + junit + junit + test + + + commons-io + commons-io + test + + + org.springframework.boot + spring-boot-starter-web + test + + + com.alibaba + fastjson + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpDigestJsonEncoder.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpDigestJsonEncoder.java new file mode 100644 index 00000000..9755218f --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpDigestJsonEncoder.java @@ -0,0 +1,88 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp; + +import com.alipay.common.tracer.core.appender.builder.JsonStringBuilder; +import com.alipay.common.tracer.core.appender.self.Timestamp; +import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; +import com.alipay.common.tracer.core.middleware.parent.AbstractDigestSpanEncoder; +import com.alipay.common.tracer.core.span.CommonSpanTags; +import com.alipay.common.tracer.core.span.SofaTracerSpan; + +import java.io.IOException; +import java.util.Map; + +/** + * + * @author xianglong.chen + * @since 2019/1/17 13:28 + */ +public class OkHttpDigestJsonEncoder extends AbstractDigestSpanEncoder { + + @Override + public String encode(SofaTracerSpan span) throws IOException { + JsonStringBuilder jsonStringBuilder = new JsonStringBuilder(); + //span end time + jsonStringBuilder.appendBegin("time", Timestamp.format(span.getEndTime())); + appendSlot(jsonStringBuilder, span); + return jsonStringBuilder.toString(); + } + + private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofaTracerSpan) { + SofaTracerSpanContext context = sofaTracerSpan.getSofaTracerSpanContext(); + Map tagWithStr = sofaTracerSpan.getTagsWithStr(); + Map tagWithNumber = sofaTracerSpan.getTagsWithNumber(); + //app + jsonStringBuilder + .append(CommonSpanTags.LOCAL_APP, tagWithStr.get(CommonSpanTags.LOCAL_APP)); + //TraceId + jsonStringBuilder.append("traceId", context.getTraceId()); + //SpanId + jsonStringBuilder.append("spanId", context.getSpanId()); + //URL + jsonStringBuilder.append(CommonSpanTags.REQUEST_URL, + tagWithStr.get(CommonSpanTags.REQUEST_URL)); + //POST/GET + jsonStringBuilder.append(CommonSpanTags.METHOD, tagWithStr.get(CommonSpanTags.METHOD)); + //Http status code + jsonStringBuilder.append(CommonSpanTags.RESULT_CODE, + tagWithStr.get(CommonSpanTags.RESULT_CODE)); + Number requestSize = tagWithNumber.get(CommonSpanTags.REQ_SIZE); + //Request Body bytes length + jsonStringBuilder.append(CommonSpanTags.REQ_SIZE, + (requestSize == null ? 0L : requestSize.longValue())); + Number responseSize = tagWithNumber.get(CommonSpanTags.RESP_SIZE); + //Response Body bytes length + jsonStringBuilder.append(CommonSpanTags.RESP_SIZE, (responseSize == null ? 0L + : responseSize.longValue())); + //time-consuming ms + jsonStringBuilder.append("time.cost.milliseconds", + (sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime())); + jsonStringBuilder.append(CommonSpanTags.CURRENT_THREAD_NAME, + tagWithStr.get(CommonSpanTags.CURRENT_THREAD_NAME)); + //target appName + jsonStringBuilder.append(CommonSpanTags.REMOTE_APP, + tagWithStr.get(CommonSpanTags.REMOTE_APP)); + this.appendBaggage(jsonStringBuilder, context); + } + + private void appendBaggage(JsonStringBuilder jsonStringBuilder, + SofaTracerSpanContext sofaTracerSpanContext) { + //baggage + jsonStringBuilder.appendEnd("baggage", baggageSerialized(sofaTracerSpanContext)); + } +} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpLogEnum.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpLogEnum.java new file mode 100644 index 00000000..0fbffa12 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpLogEnum.java @@ -0,0 +1,52 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp; + +/** + * @author xianglong.chen + * @since 2019/1/16 15:56 + */ +public enum OkHttpLogEnum { + + // OkHttp Digest Log + OK_HTTP_DIGEST("okhttp_digest_log_name", "okhttp-digest.log", "okhttp_digest_rolling"), + + // OkHttp Stat Log + OK_HTTP_STAT("okhttp_stat_log_name", "okhttp-stat.log", "okhttp_stat_rolling"); + + private String logNameKey; + private String defaultLogName; + private String rollingKey; + + OkHttpLogEnum(String logNameKey, String defaultLogName, String rollingKey) { + this.logNameKey = logNameKey; + this.defaultLogName = defaultLogName; + this.rollingKey = rollingKey; + } + + public String getLogNameKey() { + return logNameKey; + } + + public String getDefaultLogName() { + return defaultLogName; + } + + public String getRollingKey() { + return rollingKey; + } +} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpRequestCarrier.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpRequestCarrier.java new file mode 100644 index 00000000..e94a7442 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpRequestCarrier.java @@ -0,0 +1,51 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp; + +import io.opentracing.propagation.TextMap; +import okhttp3.Headers; + +import java.util.Iterator; +import java.util.Map; + +/** + * @author xianglong.chen + * @since 2019/1/17 9:24 + */ +public class OkHttpRequestCarrier implements TextMap { + + private Headers.Builder headerBuilder; + + public OkHttpRequestCarrier(Headers.Builder headerBuilder) { + if (headerBuilder == null) { + throw new NullPointerException("Headers headerBuilder should not be null!"); + } + + this.headerBuilder = headerBuilder; + } + + @Override + public Iterator> iterator() { + // no operation + throw new UnsupportedOperationException(); + } + + @Override + public void put(String key, String value) { + headerBuilder.add(key, value); + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpStatJsonReporter.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpStatJsonReporter.java new file mode 100644 index 00000000..b0d06837 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpStatJsonReporter.java @@ -0,0 +1,115 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp; + +import com.alipay.common.tracer.core.appender.builder.JsonStringBuilder; +import com.alipay.common.tracer.core.appender.file.LoadTestAwareAppender; +import com.alipay.common.tracer.core.appender.self.SelfLog; +import com.alipay.common.tracer.core.appender.self.Timestamp; +import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; +import com.alipay.common.tracer.core.reporter.stat.model.StatKey; +import com.alipay.common.tracer.core.reporter.stat.model.StatMapKey; +import com.alipay.common.tracer.core.span.CommonSpanTags; +import com.alipay.common.tracer.core.span.SofaTracerSpan; +import com.alipay.common.tracer.core.utils.TracerUtils; + +import java.util.Map; + +/** + * @author xianglong.chen + * @since 2019/1/17 13:28 + */ +public class OkHttpStatJsonReporter extends AbstractSofaTracerStatisticReporter { + + /*** + * print builder + */ + private static JsonStringBuilder jsonBuffer = new JsonStringBuilder(); + + public OkHttpStatJsonReporter(String statTracerName, String rollingPolicy, + String logReserveConfig) { + super(statTracerName, rollingPolicy, logReserveConfig); + } + + @Override + public void doReportStat(SofaTracerSpan sofaTracerSpan) { + Map tagsWithStr = sofaTracerSpan.getTagsWithStr(); + StatMapKey statKey = new StatMapKey(); + statKey.addKey(CommonSpanTags.LOCAL_APP, tagsWithStr.get(CommonSpanTags.LOCAL_APP)); + statKey.addKey(CommonSpanTags.REQUEST_URL, tagsWithStr.get(CommonSpanTags.REQUEST_URL)); + statKey.addKey(CommonSpanTags.METHOD, tagsWithStr.get(CommonSpanTags.METHOD)); + //pressure mark + statKey.setLoadTest(TracerUtils.isLoadTest(sofaTracerSpan)); + //success + String resultCode = tagsWithStr.get(CommonSpanTags.RESULT_CODE); + boolean success = (resultCode != null && resultCode.length() > 0 && this + .isHttpOrMvcSuccess(resultCode)); + statKey.setResult(success ? "true" : "false"); + //end + statKey.setEnd(TracerUtils.getLoadTestMark(sofaTracerSpan)); + //value the count and duration + long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); + long values[] = new long[] { 1, duration }; + //reserve + this.addStat(statKey, values); + } + + @Override + public void print(StatKey statKey, long[] values) { + if (this.isClosePrint.get()) { + //close + return; + } + if (!(statKey instanceof StatMapKey)) { + return; + } + StatMapKey statMapKey = (StatMapKey) statKey; + try { + jsonBuffer.reset(); + jsonBuffer.appendBegin(); + jsonBuffer.append("time", Timestamp.currentTime()); + jsonBuffer.append("stat.key", this.statKeySplit(statMapKey)); + jsonBuffer.append("count", values[0]); + jsonBuffer.append("total.cost.milliseconds", values[1]); + jsonBuffer.append("success", statMapKey.getResult()); + //pressure + jsonBuffer.appendEnd("load.test", statMapKey.getEnd()); + + if (appender instanceof LoadTestAwareAppender) { + ((LoadTestAwareAppender) appender).append(jsonBuffer.toString(), + statMapKey.isLoadTest()); + } else { + appender.append(jsonBuffer.toString()); + } + // force print + appender.flush(); + } catch (Throwable t) { + SelfLog.error("Stat log <" + statTracerName + "> error!", t); + } + } + + private String statKeySplit(StatMapKey statKey) { + JsonStringBuilder jsonBufferKey = new JsonStringBuilder(); + Map keyMap = statKey.getKeyMap(); + jsonBufferKey.appendBegin(); + for (Map.Entry entry : keyMap.entrySet()) { + jsonBufferKey.append(entry.getKey(), entry.getValue()); + } + jsonBufferKey.appendEnd(false); + return jsonBufferKey.toString(); + } +} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpTracer.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpTracer.java new file mode 100644 index 00000000..874378a6 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpTracer.java @@ -0,0 +1,84 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp; + +import com.alipay.common.tracer.core.appender.encoder.SpanEncoder; +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; +import com.alipay.common.tracer.core.span.SofaTracerSpan; +import com.alipay.common.tracer.core.tracer.AbstractClientTracer; + +/** + * @author xianglong.chen + * @since 2019/1/3 16:03 + */ +public class OkHttpTracer extends AbstractClientTracer { + + private volatile static OkHttpTracer okHttpTracer = null; + + protected OkHttpTracer() { + super("okhttp"); + } + + public static OkHttpTracer getOkHttpTracerSingleton() { + if (okHttpTracer == null) { + synchronized (OkHttpTracer.class) { + if (okHttpTracer == null) { + okHttpTracer = new OkHttpTracer(); + } + } + } + return okHttpTracer; + } + + @Override + protected String getClientDigestReporterLogName() { + return OkHttpLogEnum.OK_HTTP_DIGEST.getDefaultLogName(); + } + + @Override + protected String getClientDigestReporterRollingKey() { + return OkHttpLogEnum.OK_HTTP_DIGEST.getRollingKey(); + } + + @Override + protected String getClientDigestReporterLogNameKey() { + return OkHttpLogEnum.OK_HTTP_DIGEST.getLogNameKey(); + } + + @Override + protected SpanEncoder getClientDigestEncoder() { + return new OkHttpDigestJsonEncoder(); + } + + @Override + protected AbstractSofaTracerStatisticReporter generateClientStatReporter() { + OkHttpLogEnum okHttpLogEnum = OkHttpLogEnum.OK_HTTP_STAT; + String statLog = okHttpLogEnum.getDefaultLogName(); + String statRollingPolicy = SofaTracerConfiguration.getRollingPolicy(okHttpLogEnum + .getRollingKey()); + String statLogReserveConfig = SofaTracerConfiguration.getLogReserveConfig(okHttpLogEnum + .getLogNameKey()); + return this.getOkHttpStatReporter(statLog, statRollingPolicy, statLogReserveConfig); + } + + private AbstractSofaTracerStatisticReporter getOkHttpStatReporter(String statLog, + String statRollingPolicy, + String statLogReserveConfig) { + return new OkHttpStatJsonReporter(statLog, statRollingPolicy, statLogReserveConfig); + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/SofaTracerOkHttpBuilder.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/SofaTracerOkHttpBuilder.java new file mode 100644 index 00000000..cdabf72c --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/SofaTracerOkHttpBuilder.java @@ -0,0 +1,44 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp; + +import com.alipay.common.tracer.core.tracer.AbstractTracer; +import com.alipay.sofa.tracer.plugins.okhttp.interceptor.SofaTracerOkHttpInterceptor; +import okhttp3.OkHttpClient; + +/** + * + * @author xianglong.chen + * @since 2019/1/17 13:29 + */ +public class SofaTracerOkHttpBuilder { + + public static OkHttpClient.Builder clientBuilder(OkHttpClient.Builder clientBuilder) { + return clientBuilder(clientBuilder, null, null); + } + + public static OkHttpClient.Builder clientBuilder(OkHttpClient.Builder clientBuilder, + String currentApp, String targetApp) { + SofaTracerOkHttpInterceptor interceptor = new SofaTracerOkHttpInterceptor( + getOkHttpTracer(), currentApp, targetApp); + return clientBuilder.addInterceptor(interceptor); + } + + public static AbstractTracer getOkHttpTracer() { + return OkHttpTracer.getOkHttpTracerSingleton(); + } +} 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 new file mode 100644 index 00000000..0ed5a146 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/interceptor/SofaTracerOkHttpInterceptor.java @@ -0,0 +1,102 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp.interceptor; + +import com.alipay.common.tracer.core.SofaTracer; +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.registry.ExtendFormat; +import com.alipay.common.tracer.core.span.CommonSpanTags; +import com.alipay.common.tracer.core.span.SofaTracerSpan; +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 okhttp3.Headers; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.IOException; +import java.util.List; + +/** + * @author xianglong.chen + * @since 2019/1/16 17:51 + */ +public class SofaTracerOkHttpInterceptor implements okhttp3.Interceptor { + + protected String appName = null; + + protected String targetAppName = null; + + protected AbstractTracer okHttpTracer; + + public SofaTracerOkHttpInterceptor(AbstractTracer okHttpTracer, String appName, + String targetAppName) { + this.okHttpTracer = okHttpTracer; + this.appName = appName; + this.targetAppName = targetAppName; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + SofaTracerSpan sofaTracerSpan = okHttpTracer.clientSend(request.method()); + return chain.proceed(appendOkHttpRequestSpanTags(request, sofaTracerSpan)); + } + + private Request appendOkHttpRequestSpanTags(Request request, SofaTracerSpan sofaTracerSpan) { + if (sofaTracerSpan == null) { + return null; + } + //appName + String appName = SofaTracerConfiguration.getProperty( + SofaTracerConfiguration.TRACER_APPNAME_KEY, StringUtils.EMPTY_STRING); + //methodName + String methodName = request.method(); + sofaTracerSpan.setTag(CommonSpanTags.LOCAL_APP, appName == null ? StringUtils.EMPTY_STRING + : appName); + //targetAppName + sofaTracerSpan.setTag(CommonSpanTags.REMOTE_APP, StringUtils.EMPTY_STRING); + sofaTracerSpan.setTag(CommonSpanTags.REQUEST_URL, request.url().toString()); + //method + sofaTracerSpan.setTag(CommonSpanTags.METHOD, methodName); + + Headers headers = request.headers(); + if (headers != null) { + List contentLengthList = headers.values("Content-Length"); + if (contentLengthList != null && !contentLengthList.isEmpty()) { + sofaTracerSpan.setTag(CommonSpanTags.REQ_SIZE, + Long.valueOf(contentLengthList.get(0))); + } + } else { + sofaTracerSpan.setTag(CommonSpanTags.REQ_SIZE, String.valueOf(-1)); + } + + //carrier + return this.injectCarrier(request, sofaTracerSpan); + } + + public Request injectCarrier(Request request, SofaTracerSpan currentSpan) { + Headers.Builder headerBuilder = request.headers().newBuilder(); + + SofaTracer sofaTracer = this.okHttpTracer.getSofaTracer(); + sofaTracer.inject(currentSpan.getSofaTracerSpanContext(), + ExtendFormat.Builtin.B3_HTTP_HEADERS, new OkHttpRequestCarrier(headerBuilder)); + + Request.Builder requestBuilder = request.newBuilder(); + return requestBuilder.headers(headerBuilder.build()).build(); + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/resources/application.properties b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b 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 new file mode 100644 index 00000000..7ce48ee4 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/OkHttpTracerTest.java @@ -0,0 +1,110 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp.base; + +import com.alibaba.fastjson.JSON; +import com.alipay.common.tracer.core.SofaTracer; +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.context.trace.SofaTraceContext; +import com.alipay.common.tracer.core.holder.SofaTraceContextHolder; +import com.alipay.common.tracer.core.samplers.SofaTracerPercentageBasedSampler; +import com.alipay.common.tracer.core.span.SofaTracerSpan; +import com.alipay.common.tracer.core.utils.StringUtils; +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 org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +/** + * @author xianglong.chen + * @since 2019/1/17 10:31 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = SpringBootWebApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@TestPropertySource(locations = "classpath:application.properties") +public class OkHttpTracerTest { + + @LocalServerPort + private int definedPort; + + private String urlHttpPrefix; + + @Before + public void setUp() throws Exception { + urlHttpPrefix = "http://localhost:" + definedPort; + + SofaTracerConfiguration.setProperty(SofaTracerConfiguration.STAT_LOG_INTERVAL, "1"); + SofaTracerConfiguration.setProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY, + SofaTracerPercentageBasedSampler.TYPE); + SofaTracerConfiguration.setProperty( + SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY, "100"); + } + + @Test + public void testOkHttpTracer() throws Exception { + testOkHttpTracerUnique(); + //get + testOkHttpGet(); + //post + testOkHttpPost(); + } + + private void testOkHttpGet() throws Exception { + String httpGetUrl = urlHttpPrefix; + String path = "/httpclient"; + + String responseStr = new OkHttpClientInstance().executeGet(httpGetUrl + path); + assertFalse(StringUtils.isBlank(responseStr)); + } + + private void testOkHttpPost() throws Exception { + PostBody postBody = new PostBody(); + postBody.setAge(111); + postBody.setFemale(false); + postBody.setName("guanchao.ygc/xuelian"); + String httpGetUrl = urlHttpPrefix + "/httpclient"; + //baggage + SofaTracer sofaTracer = OkHttpTracer.getOkHttpTracerSingleton().getSofaTracer(); + 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); + } + + private void testOkHttpTracerUnique() { + OkHttpTracer a = OkHttpTracer.getOkHttpTracerSingleton(); + OkHttpTracer b = OkHttpTracer.getOkHttpTracerSingleton(); + assertEquals(a, b); + } + +} diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/SpringBootWebApplication.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/SpringBootWebApplication.java new file mode 100644 index 00000000..ddb8ad8b --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/SpringBootWebApplication.java @@ -0,0 +1,33 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp.base; + +import org.springframework.boot.SpringApplication; + +/** + * + * @author xianglong.chen + * @since 2019/1/17 13:29 + */ +@org.springframework.boot.autoconfigure.SpringBootApplication +public class SpringBootWebApplication { + + public static void main(String[] args) throws Exception { + SpringApplication springApplication = new SpringApplication(SpringBootWebApplication.class); + springApplication.run(args); + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/client/OkHttpClientInstance.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/client/OkHttpClientInstance.java new file mode 100644 index 00000000..84f61aa7 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/client/OkHttpClientInstance.java @@ -0,0 +1,69 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp.base.client; + +import com.alipay.common.tracer.core.utils.StringUtils; +import com.alipay.sofa.tracer.plugins.okhttp.SofaTracerOkHttpBuilder; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; + +/** + * @author xianglong.chen + * @since 2019/1/17 10:08 + */ +public class OkHttpClientInstance { + + public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + + private OkHttpClient okHttpClient; + + public OkHttpClientInstance() { + this.okHttpClient = getOkHttpClient(); + } + + private OkHttpClient getOkHttpClient() { + if (okHttpClient != null) { + return okHttpClient; + } else { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + return SofaTracerOkHttpBuilder.clientBuilder(builder).build(); + } + } + + public String executeGet(String url) throws Exception { + if (StringUtils.isBlank(url)) { + return null; + } + if (!url.startsWith("http://")) { + url = "http://" + url; + } + Request request = new Request.Builder().url(url).build(); + return okHttpClient.newCall(request).execute().body().string(); + } + + public String executePost(String url, String content) throws Exception { + //https://www.baeldung.com/httpclient-post-http-request + if (!url.startsWith("http://")) { + url = "http://" + url; + } + RequestBody body = RequestBody.create(JSON, content); + Request request = new Request.Builder().url(url).post(body).build(); + return okHttpClient.newCall(request).execute().body().string(); + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/controller/PostBody.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/controller/PostBody.java new file mode 100644 index 00000000..a53b1fe3 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/controller/PostBody.java @@ -0,0 +1,79 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp.base.controller; + +/** + * + * @author xianglong.chen + * @since 2019/1/17 13:29 + */ +public class PostBody { + + private String name; + + private int age; + + private boolean female; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public boolean isFemale() { + return female; + } + + public void setFemale(boolean female) { + this.female = female; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof PostBody)) + return false; + + PostBody postBody = (PostBody) o; + + if (age != postBody.age) + return false; + if (female != postBody.female) + return false; + return name != null ? name.equals(postBody.name) : postBody.name == null; + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + age; + result = 31 * result + (female ? 1 : 0); + return result; + } +} diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/controller/SampleRestController.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/controller/SampleRestController.java new file mode 100644 index 00000000..e0b6d20a --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/test/java/com/alipay/sofa/tracer/plugins/okhttp/base/controller/SampleRestController.java @@ -0,0 +1,68 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.plugins.okhttp.base.controller; + +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + +/** + * + * @author xianglong.chen + * @since 2019/1/17 13:29 + */ +@RestController +public class SampleRestController { + + private final AtomicLong counter = new AtomicLong(0); + + /** + * Request http://localhost:8080/httpclient?name= + * @param name name + * @return Map of Result + */ + @RequestMapping("/httpclient") + public Map greeting(@RequestParam(value = "name", defaultValue = "httpclient") String name) { + Map map = new HashMap(); + map.put("count", counter.incrementAndGet()); + map.put("name", name); + return map; + } + + /** + * Request http://localhost:8080/httpclient + * @param postBody body + * @return Result + */ + @RequestMapping(value = "/httpclient", method = RequestMethod.POST) + @ResponseBody + public PostBody postBody(@RequestBody PostBody postBody) { + return postBody; + } + + /** + * Request http://localhost:8080/httpclient + * + */ + @RequestMapping(value = "/httpclient", method = RequestMethod.HEAD) + @ResponseBody + public void head() { + // do nothing + } +} From 65be31efe3d8545f05a920e294b130439f86acb4 Mon Sep 17 00:00:00 2001 From: Shannon Chen Date: Fri, 22 Feb 2019 16:29:19 +0800 Subject: [PATCH 06/24] Fix OkHttpTracer don't send log to Zipkin bug #173 (#173) (cherry picked from commit f7283461ea1a11a28a8168ebf351e4da3be6e631) --- .../okhttp/interceptor/SofaTracerOkHttpInterceptor.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 0ed5a146..37bca4c7 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 @@ -54,7 +54,9 @@ public SofaTracerOkHttpInterceptor(AbstractTracer okHttpTracer, String appName, public Response intercept(Chain chain) throws IOException { Request request = chain.request(); SofaTracerSpan sofaTracerSpan = okHttpTracer.clientSend(request.method()); - return chain.proceed(appendOkHttpRequestSpanTags(request, sofaTracerSpan)); + Response response = chain.proceed(appendOkHttpRequestSpanTags(request, sofaTracerSpan)); + okHttpTracer.clientReceive(String.valueOf(response.code())); + return response; } private Request appendOkHttpRequestSpanTags(Request request, SofaTracerSpan sofaTracerSpan) { From a6194ad7e9c4f3c979cd1633908c0124e041076c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Mon, 11 Mar 2019 11:41:32 +0800 Subject: [PATCH 07/24] compile&code format --- .../alipay/common/tracer/core/samplers/SamplerFactory.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerFactory.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerFactory.java index 7ff39ace..4bf55d13 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerFactory.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplerFactory.java @@ -36,7 +36,7 @@ public class SamplerFactory { float percentage = 100; String perStr = SofaTracerConfiguration - .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY); + .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY); if (StringUtils.isNotBlank(perStr)) { percentage = Float.parseFloat(perStr); } @@ -46,7 +46,7 @@ public class SamplerFactory { samplerProperties.setPercentage(100); } samplerProperties.setRuleClassName(SofaTracerConfiguration - .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME)); + .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME)); } /** From 09a5d767640fd08e15252dfcc8be9abecd151c2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Mon, 11 Mar 2019 11:53:29 +0800 Subject: [PATCH 08/24] cheery pick datasource --- .../src/test/resources/sofa.tracer.properties | 3 + ...SofaTracerDataSourceAutoConfiguration.java | 10 ++- .../DataSourceBeanFactoryPostProcessor.java | 62 +---------------- .../SofaTracerConfigurationListener.java | 66 +++++++++++++++---- .../boot/properties/SofaTracerProperties.java | 28 ++++++++ .../base/ConfigurationHolderListener.java | 6 ++ 6 files changed, 101 insertions(+), 74 deletions(-) create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/sofa.tracer.properties diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/sofa.tracer.properties b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/sofa.tracer.properties new file mode 100644 index 00000000..b3454ec7 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/resources/sofa.tracer.properties @@ -0,0 +1,3 @@ +com.alipay.sofa.tracer.zipkin.enabled=true +com.alipay.sofa.tracer.zipkin.baseUrl=http://localhost:9411 +com.alipay.sofa.tracer.zipkin.gzipped=true \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/configuration/SofaTracerDataSourceAutoConfiguration.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/configuration/SofaTracerDataSourceAutoConfiguration.java index 7023b551..da305058 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/configuration/SofaTracerDataSourceAutoConfiguration.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/configuration/SofaTracerDataSourceAutoConfiguration.java @@ -17,6 +17,7 @@ package com.alipay.sofa.tracer.boot.datasource.configuration; import com.alipay.sofa.tracer.boot.datasource.processor.DataSourceBeanFactoryPostProcessor; +import com.alipay.sofa.tracer.boot.datasource.processor.DataSourceBeanPostProcessor; import com.alipay.sofa.tracer.boot.datasource.properties.SofaTracerDataSourceProperties; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -35,7 +36,14 @@ public class SofaTracerDataSourceAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "com.alipay.sofa.tracer.datasource", value = "enable", matchIfMissing = true) - public DataSourceBeanFactoryPostProcessor DataSourceBeanFactoryPostProcessor() { + public static DataSourceBeanFactoryPostProcessor DataSourceBeanFactoryPostProcessor() { return new DataSourceBeanFactoryPostProcessor(); } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(prefix = "com.alipay.sofa.tracer.datasource", value = "enable", matchIfMissing = true) + public static DataSourceBeanPostProcessor dataSourceBeanPostProcessor() { + return new DataSourceBeanPostProcessor(); + } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanFactoryPostProcessor.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanFactoryPostProcessor.java index 649c0261..defeca8a 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanFactoryPostProcessor.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanFactoryPostProcessor.java @@ -33,7 +33,6 @@ import org.springframework.util.Assert; import javax.sql.DataSource; -import java.security.InvalidParameterException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; @@ -121,9 +120,10 @@ private void createDataSourceProxy(ConfigurableListableBeanFactory beanFactory, Assert.isTrue(!StringUtils.isBlank(appName), TRACER_APPNAME_KEY + " must be configured!"); values.add("appName", appName); values.add("delegate", new RuntimeBeanReference(transformDatasourceBeanName(beanName))); - values.add("dbType", resolveDbTypeFromUrl(unwrapPropertyValue(originValues.get(jdbcUrl)))); + values.add("dbType", + DataSourceUtils.resolveDbTypeFromUrl(unwrapPropertyValue(originValues.get(jdbcUrl)))); values.add("database", - resolveDatabaseFromUrl(unwrapPropertyValue(originValues.get(jdbcUrl)))); + DataSourceUtils.resolveDatabaseFromUrl(unwrapPropertyValue(originValues.get(jdbcUrl)))); proxiedBeanDefinition.setPropertyValues(values); beanDefinitionRegistry.registerBeanDefinition(beanName, proxiedBeanDefinition); } @@ -142,62 +142,6 @@ public static String transformDatasourceBeanName(String originName) { return SOFA_TRACER_DATASOURCE + originName; } - public static String resolveDbTypeFromUrl(String url) { - Assert.isTrue(!StringUtils.isBlank(url), "Jdbc url must not be empty!"); - int start = url.indexOf("jdbc:") + "jdbc:".length(); - if (start < "jdbc:".length()) { - throw new InvalidParameterException("jdbc url is invalid!"); - } - int end = url.indexOf(":", start); - if (end < 0) { - throw new InvalidParameterException("jdbc url is invalid!"); - } - String dbType = url.substring(start, end); - // SQL Server 2000 - if ("microsoft".equals(dbType)) { - start = end + 1; - end = url.indexOf(":", start); - if (end < 0) { - throw new InvalidParameterException("jdbc url is invalid!"); - } - return url.substring(start, end); - } else { - return dbType; - } - } - - public static String resolveDatabaseFromUrl(String url) { - Assert.isTrue(!StringUtils.isBlank(url), "Jdbc url must not be empty!"); - if ("sqlserver".equals(resolveDbTypeFromUrl(url))) { - String[] segments = url.split(";"); - for (String segment : segments) { - if (segment.toLowerCase().contains("databasename=")) { - int start = segment.toLowerCase().indexOf("databasename=") - + "databasename=".length(); - return segment.substring(start).trim(); - } - } - throw new InvalidParameterException("jdbc url is invalid!"); - } - - int start = url.lastIndexOf("/"); - if (start < 0) { - /** - * oracle sid 格式,{@see jdbc:oracle:thin:@host:port:SID} - */ - if ("oracle".equals(resolveDbTypeFromUrl(url))) { - start = url.lastIndexOf(":"); - } else { - throw new InvalidParameterException("jdbc url is invalid!"); - } - } - int end = url.indexOf("?", start); - if (end != -1) { - return url.substring(start + 1, end); - } - return url.substring(start + 1); - } - @Override public void setEnvironment(Environment environment) { this.environment = environment; diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java index 33fffbd5..e8984bc9 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java @@ -16,20 +16,20 @@ */ package com.alipay.sofa.tracer.boot.listener; +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.utils.StringUtils; +import com.alipay.sofa.tracer.boot.properties.SofaTracerProperties; +import org.springframework.boot.bind.PropertiesConfigurationFactory; import com.alipay.sofa.infra.utils.SOFABootEnvUtils; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; import org.springframework.context.ApplicationListener; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.util.Assert; - -import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; -import com.alipay.common.tracer.core.utils.StringUtils; -import com.alipay.sofa.tracer.boot.properties.SofaTracerProperties; +import org.springframework.validation.BindException; /** * Parse SOFATracer Configuration in early stage. @@ -50,6 +50,12 @@ public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { return; } + // set loggingPath + String loggingPath = environment.getProperty("logging.path"); + if (StringUtils.isNotBlank(loggingPath)) { + System.setProperty("logging.path", loggingPath); + } + // check spring.application.name String applicationName = environment .getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY); @@ -58,14 +64,27 @@ public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY, applicationName); - // static binding SofaTracerProperties tempTarget = new SofaTracerProperties(); - ConfigurationProperties configurationProperties = AnnotationUtils.findAnnotation( - SofaTracerProperties.class, ConfigurationProperties.class); - Binder binder = Binder.get(environment); - Bindable bindable = Bindable.of(SofaTracerProperties.class).withExistingValue(tempTarget) - .withAnnotations(configurationProperties); - binder.bind(SofaTracerProperties.SOFA_TRACER_CONFIGURATION_PREFIX, bindable); + PropertiesConfigurationFactory binder = new PropertiesConfigurationFactory( + tempTarget); + ConfigurationProperties configurationPropertiesAnnotation = this + .getConfigurationPropertiesAnnotation(tempTarget); + if (configurationPropertiesAnnotation != null + && StringUtils.isNotBlank(configurationPropertiesAnnotation.prefix())) { + //consider compatible Spring Boot 1.5.X and 2.x + binder.setIgnoreInvalidFields(configurationPropertiesAnnotation.ignoreInvalidFields()); + binder.setIgnoreUnknownFields(configurationPropertiesAnnotation.ignoreUnknownFields()); + binder.setTargetName(configurationPropertiesAnnotation.prefix()); + } else { + binder.setTargetName(SofaTracerProperties.SOFA_TRACER_CONFIGURATION_PREFIX); + } + binder.setConversionService(new DefaultConversionService()); + binder.setPropertySources(environment.getPropertySources()); + try { + binder.bindPropertiesToTarget(); + } catch (BindException ex) { + throw new IllegalStateException("Cannot bind to SofaTracerProperties", ex); + } //properties convert to tracer SofaTracerConfiguration.setProperty( @@ -87,10 +106,29 @@ public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { SofaTracerConfiguration.setProperty( SofaTracerConfiguration.TRACER_SYSTEM_PENETRATE_ATTRIBUTE_MAX_LENGTH, tempTarget.getBaggageMaxLength()); + + //sampler config + if (tempTarget.getSamplerName() != null) { + SofaTracerConfiguration.setProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY, + tempTarget.getSamplerName()); + } + if (StringUtils.isNotBlank(tempTarget.getSamplerCustomRuleClassName())) { + SofaTracerConfiguration.setProperty( + SofaTracerConfiguration.SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME, + tempTarget.getSamplerCustomRuleClassName()); + } + SofaTracerConfiguration.setProperty( + SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY, + String.valueOf(tempTarget.getSamplerPercentage())); } @Override public int getOrder() { - return HIGHEST_PRECEDENCE + 30; + return HIGHEST_PRECEDENCE + 20; + } + + private ConfigurationProperties getConfigurationPropertiesAnnotation(Object targetObject) { + return AnnotationUtils.findAnnotation(targetObject.getClass(), + ConfigurationProperties.class); } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/properties/SofaTracerProperties.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/properties/SofaTracerProperties.java index c0627f67..f0f5d9fd 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/properties/SofaTracerProperties.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/properties/SofaTracerProperties.java @@ -72,6 +72,10 @@ public class SofaTracerProperties { private String baggageMaxLength = String .valueOf(SofaTracerConfiguration.PEN_ATTRS_LENGTH_TRESHOLD); + private String samplerName; + private float samplerPercentage = 100; + private String samplerCustomRuleClassName; + public String getDisableDigestLog() { return disableDigestLog; } @@ -119,4 +123,28 @@ public String getBaggageMaxLength() { public void setBaggageMaxLength(String baggageMaxLength) { this.baggageMaxLength = baggageMaxLength; } + + public String getSamplerName() { + return samplerName; + } + + public void setSamplerName(String samplerName) { + this.samplerName = samplerName; + } + + public float getSamplerPercentage() { + return samplerPercentage; + } + + public void setSamplerPercentage(float samplerPercentage) { + this.samplerPercentage = samplerPercentage; + } + + public String getSamplerCustomRuleClassName() { + return samplerCustomRuleClassName; + } + + public void setSamplerCustomRuleClassName(String samplerCustomRuleClassName) { + this.samplerCustomRuleClassName = samplerCustomRuleClassName; + } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/ConfigurationHolderListener.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/ConfigurationHolderListener.java index 6dfa7632..9527b38e 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/ConfigurationHolderListener.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/ConfigurationHolderListener.java @@ -43,5 +43,11 @@ public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { sofaTracerProperties.setBaggageMaxLength(SofaTracerConfiguration .getProperty(SofaTracerConfiguration.TRACER_PENETRATE_ATTRIBUTE_MAX_LENGTH)); ConfigurationHolder.setSofaTracerProperties(sofaTracerProperties); + sofaTracerProperties.setSamplerName(SofaTracerConfiguration + .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY)); + sofaTracerProperties.setSamplerCustomRuleClassName(SofaTracerConfiguration + .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME)); + sofaTracerProperties.setSamplerPercentage(Float.valueOf(SofaTracerConfiguration + .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY))); } } \ No newline at end of file From 6c7e0fb78216f92e1f5b4734c2b9f10237ed273f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Mon, 11 Mar 2019 11:53:55 +0800 Subject: [PATCH 09/24] cheery pick datasource --- .../datasource/utils/DataSourceUtils.java | 58 ++++++++++ .../datasource/DataSourceUtilTest.java | 41 +++++++ .../datasource/bean/AbstractService.java | 33 ++++++ .../datasource/bean/ConcreteClassService.java | 27 +++++ .../plugins/datasource/bean/InterfaceA.java | 25 +++++ .../plugins/datasource/bean/InterfaceB.java | 25 +++++ .../tracer/core/utils/ReflectionUtils.java | 62 +++++++++++ .../DataSourceBeanPostProcessor.java | 103 ++++++++++++++++++ .../base/HikariDataSourceConfiguration.java | 53 +++++++++ .../boot/datasource/DataSourceBFPPTest.java | 79 ++++++++------ .../DataSourceTracerDisableTest.java | 6 +- .../boot/datasource/DataSourceTracerTest.java | 13 ++- .../boot/datasource/DataSourceUrlTest.java | 77 +++++++++++++ 13 files changed, 563 insertions(+), 39 deletions(-) create mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DataSourceUtilTest.java create mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/AbstractService.java create mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/ConcreteClassService.java create mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceA.java create mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceB.java create mode 100644 tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ReflectionUtils.java create mode 100644 tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanPostProcessor.java create mode 100644 tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/HikariDataSourceConfiguration.java create mode 100644 tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceUrlTest.java diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java index c5d38ef5..8c7cbf5e 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java @@ -16,10 +16,12 @@ */ package com.alipay.sofa.tracer.plugins.datasource.utils; +import com.alipay.common.tracer.core.utils.AssertUtils; import com.alipay.common.tracer.core.utils.StringUtils; import com.alipay.sofa.tracer.plugins.datasource.tracer.Endpoint; import java.lang.reflect.Method; +import java.security.InvalidParameterException; /** * @author shusong.yss @@ -215,4 +217,60 @@ public static Endpoint getEndpointFromConnectionURL(final String connectionURL) endpoint.setPort(port); return endpoint; } + + public static String resolveDbTypeFromUrl(String url) { + AssertUtils.isTrue(!StringUtils.isBlank(url), "Jdbc url must not be empty!"); + int start = url.indexOf("jdbc:") + "jdbc:".length(); + if (start < "jdbc:".length()) { + throw new InvalidParameterException("jdbc url is invalid!"); + } + int end = url.indexOf(":", start); + if (end < 0) { + throw new InvalidParameterException("jdbc url is invalid!"); + } + String dbType = url.substring(start, end); + // SQL Server 2000 + if ("microsoft".equals(dbType)) { + start = end + 1; + end = url.indexOf(":", start); + if (end < 0) { + throw new InvalidParameterException("jdbc url is invalid!"); + } + return url.substring(start, end); + } else { + return dbType; + } + } + + public static String resolveDatabaseFromUrl(String url) { + AssertUtils.isTrue(!StringUtils.isBlank(url), "Jdbc url must not be empty!"); + if ("sqlserver".equals(resolveDbTypeFromUrl(url))) { + String[] segments = url.split(";"); + for (String segment : segments) { + if (segment.toLowerCase().contains("databasename=")) { + int start = segment.toLowerCase().indexOf("databasename=") + + "databasename=".length(); + return segment.substring(start).trim(); + } + } + throw new InvalidParameterException("jdbc url is invalid!"); + } + + int start = url.lastIndexOf("/"); + if (start < 0) { + /** + * oracle sid 格式,{@see jdbc:oracle:thin:@host:port:SID} + */ + if ("oracle".equals(resolveDbTypeFromUrl(url))) { + start = url.lastIndexOf(":"); + } else { + throw new InvalidParameterException("jdbc url is invalid!"); + } + } + int end = url.indexOf("?", start); + if (end != -1) { + return url.substring(start + 1, end); + } + return url.substring(start + 1); + } } \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DataSourceUtilTest.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DataSourceUtilTest.java new file mode 100644 index 00000000..5ff400e8 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DataSourceUtilTest.java @@ -0,0 +1,41 @@ +/* + * 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. + */ +package com.sofa.tracer.plugins.datasource; + +import com.alipay.common.tracer.core.utils.ReflectionUtils; +import com.sofa.tracer.plugins.datasource.bean.ConcreteClassService; +import org.junit.Assert; +import org.junit.Test; + +import java.lang.reflect.Method; + +/** + * @author qilong.zql + * @since 2.3.2 + */ +public class DataSourceUtilTest { + @Test + public void testReflectionUtils() throws Throwable { + ConcreteClassService concreteClassService = new ConcreteClassService(); + Method method = ReflectionUtils.findMethod(concreteClassService.getClass(), "service"); + Assert.assertEquals("concreteClassService", method.invoke(concreteClassService)); + method = ReflectionUtils.findMethod(concreteClassService.getClass(), "serviceA"); + Assert.assertEquals("serviceA", method.invoke(concreteClassService)); + method = ReflectionUtils.findMethod(concreteClassService.getClass(), "serviceB"); + Assert.assertEquals("serviceB", method.invoke(concreteClassService)); + } +} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/AbstractService.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/AbstractService.java new file mode 100644 index 00000000..e5baca4e --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/AbstractService.java @@ -0,0 +1,33 @@ +/* + * 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. + */ +package com.sofa.tracer.plugins.datasource.bean; + +/** + * @author qilong.zql + * @since 2.3.2 + */ +public class AbstractService implements InterfaceA { + @Override + public String serviceA() { + return "serviceA"; + } + + @Override + public String serviceB() { + return "serviceB"; + } +} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/ConcreteClassService.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/ConcreteClassService.java new file mode 100644 index 00000000..1a4d27f0 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/ConcreteClassService.java @@ -0,0 +1,27 @@ +/* + * 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. + */ +package com.sofa.tracer.plugins.datasource.bean; + +/** + * @author qilong.zql + * @since 2.3.2 + */ +public class ConcreteClassService extends AbstractService { + public String service() { + return "concreteClassService"; + } +} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceA.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceA.java new file mode 100644 index 00000000..516a54d4 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceA.java @@ -0,0 +1,25 @@ +/* + * 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. + */ +package com.sofa.tracer.plugins.datasource.bean; + +/** + * @author qilong.zql + * @sicne 2.3.2 + */ +public interface InterfaceA extends InterfaceB { + String serviceA(); +} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceB.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceB.java new file mode 100644 index 00000000..2df900c8 --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceB.java @@ -0,0 +1,25 @@ +/* + * 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. + */ +package com.sofa.tracer.plugins.datasource.bean; + +/** + * @author qilong.zql + * @since 2.3.2 + */ +public interface InterfaceB { + String serviceB(); +} \ No newline at end of file diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ReflectionUtils.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ReflectionUtils.java new file mode 100644 index 00000000..49b7c3ea --- /dev/null +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ReflectionUtils.java @@ -0,0 +1,62 @@ +/* + * 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. + */ +package com.alipay.common.tracer.core.utils; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * @author qilong.zql + * @author Juergen Hoeller + * @author Rob Harrop + * @author Rod Johnson + * @author Costin Leau + * @author Sam Brannen + * @author Chris Beams + * @since 2.3.2 + */ +public class ReflectionUtils { + /** + * Attempt to find a {@link Method} on the supplied class with the supplied name + * and parameter types. Searches all superclasses up to {@code Object}. + *

Returns {@code null} if no {@link Method} can be found. + * @param clazz the class to introspect + * @param name the name of the method + * @param paramTypes the parameter types of the method + * (may be {@code null} to indicate any signature) + * @return the Method object, or {@code null} if none found + */ + public static Method findMethod(Class clazz, String name, Class... paramTypes) { + Class searchType = clazz; + while (searchType != null) { + Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType + .getDeclaredMethods()); + for (Method method : methods) { + if (name.equals(method.getName()) + && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) { + return method; + } + } + searchType = searchType.getSuperclass(); + } + return null; + } + +} \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanPostProcessor.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanPostProcessor.java new file mode 100644 index 00000000..4d072be5 --- /dev/null +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanPostProcessor.java @@ -0,0 +1,103 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.boot.datasource.processor; + +import com.alipay.common.tracer.core.utils.ReflectionUtils; +import com.alipay.common.tracer.core.utils.StringUtils; +import com.alipay.sofa.tracer.plugins.datasource.SmartDataSource; +import com.alipay.sofa.tracer.plugins.datasource.utils.DataSourceUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.EnvironmentAware; +import org.springframework.core.env.Environment; +import org.springframework.util.Assert; + +import javax.sql.DataSource; + +import java.lang.reflect.Method; + +import static com.alipay.common.tracer.core.configuration.SofaTracerConfiguration.TRACER_APPNAME_KEY; + +/** + * @author qilong.zql + * @since 2.3.2 + */ +public class DataSourceBeanPostProcessor implements BeanPostProcessor, EnvironmentAware { + + private Environment environment; + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) + throws BeansException { + return bean; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) + throws BeansException { + /** + * filter transformed datasource {@link DataSourceBeanFactoryPostProcessor} + * filter bean which is type of {@link SmartDataSource} + * filter bean which is not type of {@link DataSource} + */ + if (beanName.startsWith(DataSourceBeanFactoryPostProcessor.SOFA_TRACER_DATASOURCE) + || bean instanceof SmartDataSource || !(bean instanceof DataSource)) { + return bean; + } + + String getUrlMethodName; + String url; + /** + * Now DataSource Tracer only support the following type: Druid, C3p0, Dbcp, tomcat datasource, hikari + */ + if (DataSourceUtils.isDruidDataSource(bean) || DataSourceUtils.isDbcpDataSource(bean) + || DataSourceUtils.isTomcatDataSource(bean)) { + getUrlMethodName = DataSourceUtils.METHOD_GET_URL; + } else if (DataSourceUtils.isC3p0DataSource(bean) + || DataSourceUtils.isHikariDataSource(bean)) { + getUrlMethodName = DataSourceUtils.METHOD_GET_JDBC_URL; + } else { + return bean; + } + + try { + Method urlMethod = ReflectionUtils.findMethod(bean.getClass(), getUrlMethodName); + urlMethod.setAccessible(true); + url = (String) urlMethod.invoke(bean); + } catch (Throwable throwable) { + throw new BeanCreationException(String.format("Can not find method: %s in class %s.", + getUrlMethodName, bean.getClass().getCanonicalName()), throwable); + } + + SmartDataSource proxiedDataSource = new SmartDataSource((DataSource) bean); + String appName = environment.getProperty(TRACER_APPNAME_KEY); + Assert.isTrue(!StringUtils.isBlank(appName), TRACER_APPNAME_KEY + " must be configured!"); + proxiedDataSource.setAppName(appName); + proxiedDataSource.setDbType(DataSourceUtils.resolveDbTypeFromUrl(url)); + proxiedDataSource.setDatabase(DataSourceUtils.resolveDatabaseFromUrl(url)); + + // execute proxied datasource init-method + proxiedDataSource.init(); + return proxiedDataSource; + } + + @Override + public void setEnvironment(Environment environment) { + this.environment = environment; + } +} \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/HikariDataSourceConfiguration.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/HikariDataSourceConfiguration.java new file mode 100644 index 00000000..a1027cc0 --- /dev/null +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/HikariDataSourceConfiguration.java @@ -0,0 +1,53 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.boot.base; + +import com.zaxxer.hikari.HikariDataSource; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.sql.DataSource; + +/** + * @author qilong.zql + * @since 2.3.2 + */ +@Configuration +public class HikariDataSourceConfiguration { + @Value("${spring.datasource.url}") + private String jdbcUrl; + + @Value("${spring.datasource.driver-class-name}") + private String driverClassName; + + @Value("${spring.datasource.username}") + private String username; + + @Value("${spring.datasource.password}") + private String password; + + @Bean + public DataSource hikariDataSource() { + HikariDataSource dataSource = new HikariDataSource(); + dataSource.setJdbcUrl(jdbcUrl); + dataSource.setDriverClassName(driverClassName); + dataSource.setUsername(username); + dataSource.setPassword(password); + return dataSource; + } +} \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceBFPPTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceBFPPTest.java index 6524a6e8..9c5593ab 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceBFPPTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceBFPPTest.java @@ -16,7 +16,6 @@ */ package com.alipay.sofa.tracer.boot.datasource; -import com.alipay.sofa.tracer.boot.datasource.processor.DataSourceBeanFactoryPostProcessor; import com.alipay.sofa.tracer.plugins.datasource.tracer.Endpoint; import com.alipay.sofa.tracer.plugins.datasource.utils.DataSourceUtils; import org.junit.Assert; @@ -30,34 +29,52 @@ */ public class DataSourceBFPPTest { - private String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:orcl"; - private String jdbcUrl2 = "jdbc:oracle:thin:@//localhost:1521/orcl.city.com"; - private String jdbcUrl4 = "jdbc:mysql://127.0.0.1:3306/imooc?useUnicode=true&characterEncoding=utf-8"; - private String jdbcUrl5 = "jdbc:mysql://127.0.0.1:3306/dataBase"; + private String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:orcl"; + private String jdbcUrl2 = "jdbc:oracle:thin:@//localhost:1521/orcl.city.com"; + private String jdbcUrl4 = "jdbc:mysql://127.0.0.1:3306/imooc?useUnicode=true&characterEncoding=utf-8"; + private String jdbcUrl5 = "jdbc:mysql://127.0.0.1:3306/dataBase"; + private String jdbcUrl9 = "jdbc@:mysql://127.0.0.1:3306/dataBase"; // SQL Server 2000 - private String jdbcUrl6 = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample "; + private String jdbcUrl6 = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample "; + private String jdbcUrl10 = "invalid:sqlserver://localhost:1433; DatabaseName=sample "; // SQL Server 2005 - private String jdbcUrl7 = "jdbc:sqlserver://localhost:1433; DatabaseName=sample "; - private String jdbcUrl8 = "invalid"; + private String jdbcUrl7 = "jdbc:sqlserver://localhost:1433; DatabaseName=sample "; + private String jdbcUrl11 = "jdbc://localhost/1433; DatabaseName=sample "; + private String jdbcUrl8 = "invalid"; @Test public void testDbType() { - Assert.assertTrue("oracle".equals(DataSourceBeanFactoryPostProcessor - .resolveDbTypeFromUrl(jdbcUrl))); - Assert.assertTrue("oracle".equals(DataSourceBeanFactoryPostProcessor - .resolveDbTypeFromUrl(jdbcUrl2))); - Assert.assertTrue("mysql".equals(DataSourceBeanFactoryPostProcessor - .resolveDbTypeFromUrl(jdbcUrl4))); - Assert.assertTrue("mysql".equals(DataSourceBeanFactoryPostProcessor - .resolveDbTypeFromUrl(jdbcUrl5))); - Assert.assertTrue("sqlserver".equals(DataSourceBeanFactoryPostProcessor - .resolveDbTypeFromUrl(jdbcUrl6))); - Assert.assertTrue("sqlserver".equals(DataSourceBeanFactoryPostProcessor - .resolveDbTypeFromUrl(jdbcUrl7))); + Assert.assertTrue("oracle".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl))); + Assert.assertTrue("oracle".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl2))); + Assert.assertTrue("mysql".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl4))); + Assert.assertTrue("mysql".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl5))); + Assert.assertTrue("sqlserver".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl6))); + Assert.assertTrue("sqlserver".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl7))); boolean error = false; try { - DataSourceBeanFactoryPostProcessor.resolveDbTypeFromUrl(jdbcUrl8); + DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl8); + } catch (InvalidParameterException ex) { + error = true; + } + Assert.assertTrue(error); + error = false; + try { + DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl9); + } catch (InvalidParameterException ex) { + error = true; + } + Assert.assertTrue(error); + error = false; + try { + DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl10); + } catch (InvalidParameterException ex) { + error = true; + } + Assert.assertTrue(error); + error = false; + try { + DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl11); } catch (InvalidParameterException ex) { error = true; } @@ -66,24 +83,18 @@ public void testDbType() { @Test public void testDataBase() { - Assert.assertTrue("orcl".equals(DataSourceBeanFactoryPostProcessor - .resolveDatabaseFromUrl(jdbcUrl))); - Assert.assertTrue("orcl.city.com".equals(DataSourceBeanFactoryPostProcessor - .resolveDatabaseFromUrl(jdbcUrl2))); + Assert.assertTrue("orcl".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl))); + Assert.assertTrue("orcl.city.com".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl2))); - Assert.assertTrue("imooc".equals(DataSourceBeanFactoryPostProcessor - .resolveDatabaseFromUrl(jdbcUrl4))); - Assert.assertTrue("dataBase".equals(DataSourceBeanFactoryPostProcessor - .resolveDatabaseFromUrl(jdbcUrl5))); + Assert.assertTrue("imooc".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl4))); + Assert.assertTrue("dataBase".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl5))); - Assert.assertTrue("sample".equals(DataSourceBeanFactoryPostProcessor - .resolveDatabaseFromUrl(jdbcUrl6))); - Assert.assertTrue("sample".equals(DataSourceBeanFactoryPostProcessor - .resolveDatabaseFromUrl(jdbcUrl7))); + Assert.assertTrue("sample".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl6))); + Assert.assertTrue("sample".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl7))); boolean error = false; try { - DataSourceBeanFactoryPostProcessor.resolveDbTypeFromUrl(jdbcUrl8); + DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl8); } catch (InvalidParameterException ex) { error = true; } diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerDisableTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerDisableTest.java index 6ad9a11f..132149cd 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerDisableTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerDisableTest.java @@ -25,7 +25,7 @@ import javax.sql.DataSource; -/** +/**DataSourceUtils * @author qilong.zql * @sicne 2.2.0 */ @@ -33,10 +33,10 @@ public class DataSourceTracerDisableTest extends AbstractTestBase { @Autowired - private DataSource dataSource; + private DataSource simpleDataSource; @Test public void testDataSource() { - Assert.assertTrue(dataSource instanceof HikariDataSource); + Assert.assertTrue(simpleDataSource instanceof HikariDataSource); } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerTest.java index 99f6e58c..338f3dfc 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerTest.java @@ -18,6 +18,7 @@ import com.alipay.sofa.tracer.boot.base.AbstractTestBase; import com.alipay.sofa.tracer.plugins.datasource.SmartDataSource; +import com.zaxxer.hikari.HikariDataSource; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -31,11 +32,19 @@ public class DataSourceTracerTest extends AbstractTestBase { @Autowired - private DataSource dataSource; + private DataSource simpleDataSource; + + @Autowired + private DataSource hikariDataSource; @Test public void testDataSource() { - Assert.assertTrue(dataSource instanceof SmartDataSource); + Assert.assertTrue(simpleDataSource instanceof SmartDataSource); + Assert.assertTrue(hikariDataSource instanceof SmartDataSource); + Assert.assertFalse(((SmartDataSource) simpleDataSource).getDelegate().equals( + ((SmartDataSource) hikariDataSource).getDelegate())); + Assert + .assertTrue(((SmartDataSource) hikariDataSource).getDelegate() instanceof HikariDataSource); } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceUrlTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceUrlTest.java new file mode 100644 index 00000000..14b06863 --- /dev/null +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceUrlTest.java @@ -0,0 +1,77 @@ +/* + * 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. + */ +package com.alipay.sofa.tracer.boot.datasource; + +import com.alibaba.druid.pool.DruidDataSource; +import com.alipay.common.tracer.core.utils.ReflectionUtils; +import com.alipay.sofa.tracer.plugins.datasource.utils.DataSourceUtils; +import com.mchange.v2.c3p0.ComboPooledDataSource; +import com.zaxxer.hikari.HikariDataSource; +import org.apache.commons.dbcp.BasicDataSource; +import org.apache.tomcat.jdbc.pool.DataSource; +import org.junit.Assert; +import org.junit.Test; + +import java.lang.reflect.Method; + +/** + * @author qilong.zql + * @since 2.3.2 + */ +public class DataSourceUrlTest { + @Test + public void testGetDataSourceUrl() throws Throwable { + // Druid + DruidDataSource druidDataSource = new DruidDataSource(); + druidDataSource.setUrl("test-url"); + Method method = ReflectionUtils.findMethod(druidDataSource.getClass(), + DataSourceUtils.METHOD_GET_URL); + Assert.assertNotNull(method); + Assert.assertEquals("test-url", method.invoke(druidDataSource)); + + // dbcp + BasicDataSource basicDataSource = new BasicDataSource(); + basicDataSource.setUrl("test-url"); + method = ReflectionUtils.findMethod(basicDataSource.getClass(), + DataSourceUtils.METHOD_GET_URL); + Assert.assertNotNull(method); + Assert.assertEquals("test-url", method.invoke(basicDataSource)); + + // tomcat datasource + DataSource dataSource = new DataSource(); + dataSource.setUrl("test-url"); + method = ReflectionUtils.findMethod(dataSource.getClass(), DataSourceUtils.METHOD_GET_URL); + Assert.assertNotNull(method); + Assert.assertEquals("test-url", method.invoke(dataSource)); + + // c3p0 + ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); + comboPooledDataSource.setJdbcUrl("test-url"); + method = ReflectionUtils.findMethod(comboPooledDataSource.getClass(), + DataSourceUtils.METHOD_GET_JDBC_URL); + Assert.assertNotNull(method); + Assert.assertEquals("test-url", method.invoke(comboPooledDataSource)); + + // hikari + HikariDataSource hikariDataSource = new HikariDataSource(); + hikariDataSource.setJdbcUrl("test-url"); + method = ReflectionUtils.findMethod(hikariDataSource.getClass(), + DataSourceUtils.METHOD_GET_JDBC_URL); + Assert.assertNotNull(method); + Assert.assertEquals("test-url", method.invoke(hikariDataSource)); + } +} \ No newline at end of file From 4d7efb11596203612cebd69426f49dc5607d54ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Mon, 11 Mar 2019 14:20:09 +0800 Subject: [PATCH 10/24] cherry pick --- .../datasource/utils/DataSourceUtils.java | 58 ---------- .../datasource/DataSourceUtilTest.java | 41 ------- .../datasource/bean/AbstractService.java | 33 ------ .../datasource/bean/ConcreteClassService.java | 27 ----- .../plugins/datasource/bean/InterfaceA.java | 25 ----- .../plugins/datasource/bean/InterfaceB.java | 25 ----- .../appender/self/SynchronizingSelfLog.java | 1 + .../tracer/core/span/CommonSpanTags.java | 1 - .../tracer/core/base/AbstractTestBase.java | 9 +- tracer-sofa-boot-starter/pom.xml | 33 ++---- ...SofaTracerDataSourceAutoConfiguration.java | 10 +- .../DataSourceBeanFactoryPostProcessor.java | 62 ++++++++++- .../DataSourceBeanPostProcessor.java | 103 ------------------ .../SofaTracerConfigurationListener.java | 45 +++----- .../base/HikariDataSourceConfiguration.java | 53 --------- .../boot/datasource/DataSourceBFPPTest.java | 79 ++++++-------- .../DataSourceTracerDisableTest.java | 6 +- .../boot/datasource/DataSourceTracerTest.java | 13 +-- .../boot/datasource/DataSourceUrlTest.java | 77 ------------- .../src/test/resources/application.properties | 12 -- .../src/test/resources/hikariDataSource.xml | 2 +- 21 files changed, 130 insertions(+), 585 deletions(-) delete mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DataSourceUtilTest.java delete mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/AbstractService.java delete mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/ConcreteClassService.java delete mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceA.java delete mode 100644 sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceB.java delete mode 100644 tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanPostProcessor.java delete mode 100644 tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/HikariDataSourceConfiguration.java delete mode 100644 tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceUrlTest.java diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java index 8c7cbf5e..c5d38ef5 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java @@ -16,12 +16,10 @@ */ package com.alipay.sofa.tracer.plugins.datasource.utils; -import com.alipay.common.tracer.core.utils.AssertUtils; import com.alipay.common.tracer.core.utils.StringUtils; import com.alipay.sofa.tracer.plugins.datasource.tracer.Endpoint; import java.lang.reflect.Method; -import java.security.InvalidParameterException; /** * @author shusong.yss @@ -217,60 +215,4 @@ public static Endpoint getEndpointFromConnectionURL(final String connectionURL) endpoint.setPort(port); return endpoint; } - - public static String resolveDbTypeFromUrl(String url) { - AssertUtils.isTrue(!StringUtils.isBlank(url), "Jdbc url must not be empty!"); - int start = url.indexOf("jdbc:") + "jdbc:".length(); - if (start < "jdbc:".length()) { - throw new InvalidParameterException("jdbc url is invalid!"); - } - int end = url.indexOf(":", start); - if (end < 0) { - throw new InvalidParameterException("jdbc url is invalid!"); - } - String dbType = url.substring(start, end); - // SQL Server 2000 - if ("microsoft".equals(dbType)) { - start = end + 1; - end = url.indexOf(":", start); - if (end < 0) { - throw new InvalidParameterException("jdbc url is invalid!"); - } - return url.substring(start, end); - } else { - return dbType; - } - } - - public static String resolveDatabaseFromUrl(String url) { - AssertUtils.isTrue(!StringUtils.isBlank(url), "Jdbc url must not be empty!"); - if ("sqlserver".equals(resolveDbTypeFromUrl(url))) { - String[] segments = url.split(";"); - for (String segment : segments) { - if (segment.toLowerCase().contains("databasename=")) { - int start = segment.toLowerCase().indexOf("databasename=") - + "databasename=".length(); - return segment.substring(start).trim(); - } - } - throw new InvalidParameterException("jdbc url is invalid!"); - } - - int start = url.lastIndexOf("/"); - if (start < 0) { - /** - * oracle sid 格式,{@see jdbc:oracle:thin:@host:port:SID} - */ - if ("oracle".equals(resolveDbTypeFromUrl(url))) { - start = url.lastIndexOf(":"); - } else { - throw new InvalidParameterException("jdbc url is invalid!"); - } - } - int end = url.indexOf("?", start); - if (end != -1) { - return url.substring(start + 1, end); - } - return url.substring(start + 1); - } } \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DataSourceUtilTest.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DataSourceUtilTest.java deleted file mode 100644 index 5ff400e8..00000000 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DataSourceUtilTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - */ -package com.sofa.tracer.plugins.datasource; - -import com.alipay.common.tracer.core.utils.ReflectionUtils; -import com.sofa.tracer.plugins.datasource.bean.ConcreteClassService; -import org.junit.Assert; -import org.junit.Test; - -import java.lang.reflect.Method; - -/** - * @author qilong.zql - * @since 2.3.2 - */ -public class DataSourceUtilTest { - @Test - public void testReflectionUtils() throws Throwable { - ConcreteClassService concreteClassService = new ConcreteClassService(); - Method method = ReflectionUtils.findMethod(concreteClassService.getClass(), "service"); - Assert.assertEquals("concreteClassService", method.invoke(concreteClassService)); - method = ReflectionUtils.findMethod(concreteClassService.getClass(), "serviceA"); - Assert.assertEquals("serviceA", method.invoke(concreteClassService)); - method = ReflectionUtils.findMethod(concreteClassService.getClass(), "serviceB"); - Assert.assertEquals("serviceB", method.invoke(concreteClassService)); - } -} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/AbstractService.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/AbstractService.java deleted file mode 100644 index e5baca4e..00000000 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/AbstractService.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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. - */ -package com.sofa.tracer.plugins.datasource.bean; - -/** - * @author qilong.zql - * @since 2.3.2 - */ -public class AbstractService implements InterfaceA { - @Override - public String serviceA() { - return "serviceA"; - } - - @Override - public String serviceB() { - return "serviceB"; - } -} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/ConcreteClassService.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/ConcreteClassService.java deleted file mode 100644 index 1a4d27f0..00000000 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/ConcreteClassService.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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. - */ -package com.sofa.tracer.plugins.datasource.bean; - -/** - * @author qilong.zql - * @since 2.3.2 - */ -public class ConcreteClassService extends AbstractService { - public String service() { - return "concreteClassService"; - } -} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceA.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceA.java deleted file mode 100644 index 516a54d4..00000000 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceA.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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. - */ -package com.sofa.tracer.plugins.datasource.bean; - -/** - * @author qilong.zql - * @sicne 2.3.2 - */ -public interface InterfaceA extends InterfaceB { - String serviceA(); -} \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceB.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceB.java deleted file mode 100644 index 2df900c8..00000000 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/bean/InterfaceB.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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. - */ -package com.sofa.tracer.plugins.datasource.bean; - -/** - * @author qilong.zql - * @since 2.3.2 - */ -public interface InterfaceB { - String serviceB(); -} \ No newline at end of file diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java index 662b2d9b..14d37a58 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java @@ -151,4 +151,5 @@ static private void doLog(String log, String prefix) { t.printStackTrace(); } } + } \ No newline at end of file diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java index 6c01da31..6b6c483c 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java @@ -65,5 +65,4 @@ public class CommonSpanTags { * 响应大小 */ public static final String RESP_SIZE = "resp.size.bytes"; - } \ No newline at end of file diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java index 17d07f76..5189bea8 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java @@ -29,6 +29,9 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; +import java.util.stream.Stream; import static org.junit.Assert.assertEquals; @@ -52,7 +55,11 @@ public abstract class AbstractTestBase { */ @BeforeClass public static void beforeClass() { - for (File file : customFileLog("").listFiles()) { + File[] traceFiles = customFileLog("").listFiles(); + if (traceFiles == null) { + return; + } + for (File file : traceFiles) { if (file.getPath().contains("tracer-self.log") || file.getPath().contains("sync.log") || file.getPath().contains("rpc-profile.log") || file.getPath().contains("middleware_error.log")) { diff --git a/tracer-sofa-boot-starter/pom.xml b/tracer-sofa-boot-starter/pom.xml index 49552c02..f4ad965f 100644 --- a/tracer-sofa-boot-starter/pom.xml +++ b/tracer-sofa-boot-starter/pom.xml @@ -8,6 +8,7 @@ 3.0.3-SNAPSHOT ../pom.xml + tracer-sofa-boot-starter @@ -44,10 +45,6 @@ org.springframework.boot spring-boot - - org.springframework - spring-web - org.springframework.boot spring-boot-autoconfigure @@ -56,6 +53,10 @@ com.alipay.sofa infra-sofa-boot-starter + + com.alipay.sofa.common + log-sofa-boot-starter + org.springframework.boot @@ -113,28 +114,10 @@ test - com.alibaba - druid - 1.0.12 - test - - - c3p0 - c3p0 - 0.9.1.1 - test - - - org.apache.tomcat - tomcat-jdbc - 8.5.31 - test - - - commons-dbcp - commons-dbcp - 1.4 + org.springframework.boot + spring-boot-starter-webflux test + diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/configuration/SofaTracerDataSourceAutoConfiguration.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/configuration/SofaTracerDataSourceAutoConfiguration.java index da305058..7023b551 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/configuration/SofaTracerDataSourceAutoConfiguration.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/configuration/SofaTracerDataSourceAutoConfiguration.java @@ -17,7 +17,6 @@ package com.alipay.sofa.tracer.boot.datasource.configuration; import com.alipay.sofa.tracer.boot.datasource.processor.DataSourceBeanFactoryPostProcessor; -import com.alipay.sofa.tracer.boot.datasource.processor.DataSourceBeanPostProcessor; import com.alipay.sofa.tracer.boot.datasource.properties.SofaTracerDataSourceProperties; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -36,14 +35,7 @@ public class SofaTracerDataSourceAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "com.alipay.sofa.tracer.datasource", value = "enable", matchIfMissing = true) - public static DataSourceBeanFactoryPostProcessor DataSourceBeanFactoryPostProcessor() { + public DataSourceBeanFactoryPostProcessor DataSourceBeanFactoryPostProcessor() { return new DataSourceBeanFactoryPostProcessor(); } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(prefix = "com.alipay.sofa.tracer.datasource", value = "enable", matchIfMissing = true) - public static DataSourceBeanPostProcessor dataSourceBeanPostProcessor() { - return new DataSourceBeanPostProcessor(); - } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanFactoryPostProcessor.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanFactoryPostProcessor.java index defeca8a..649c0261 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanFactoryPostProcessor.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanFactoryPostProcessor.java @@ -33,6 +33,7 @@ import org.springframework.util.Assert; import javax.sql.DataSource; +import java.security.InvalidParameterException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; @@ -120,10 +121,9 @@ private void createDataSourceProxy(ConfigurableListableBeanFactory beanFactory, Assert.isTrue(!StringUtils.isBlank(appName), TRACER_APPNAME_KEY + " must be configured!"); values.add("appName", appName); values.add("delegate", new RuntimeBeanReference(transformDatasourceBeanName(beanName))); - values.add("dbType", - DataSourceUtils.resolveDbTypeFromUrl(unwrapPropertyValue(originValues.get(jdbcUrl)))); + values.add("dbType", resolveDbTypeFromUrl(unwrapPropertyValue(originValues.get(jdbcUrl)))); values.add("database", - DataSourceUtils.resolveDatabaseFromUrl(unwrapPropertyValue(originValues.get(jdbcUrl)))); + resolveDatabaseFromUrl(unwrapPropertyValue(originValues.get(jdbcUrl)))); proxiedBeanDefinition.setPropertyValues(values); beanDefinitionRegistry.registerBeanDefinition(beanName, proxiedBeanDefinition); } @@ -142,6 +142,62 @@ public static String transformDatasourceBeanName(String originName) { return SOFA_TRACER_DATASOURCE + originName; } + public static String resolveDbTypeFromUrl(String url) { + Assert.isTrue(!StringUtils.isBlank(url), "Jdbc url must not be empty!"); + int start = url.indexOf("jdbc:") + "jdbc:".length(); + if (start < "jdbc:".length()) { + throw new InvalidParameterException("jdbc url is invalid!"); + } + int end = url.indexOf(":", start); + if (end < 0) { + throw new InvalidParameterException("jdbc url is invalid!"); + } + String dbType = url.substring(start, end); + // SQL Server 2000 + if ("microsoft".equals(dbType)) { + start = end + 1; + end = url.indexOf(":", start); + if (end < 0) { + throw new InvalidParameterException("jdbc url is invalid!"); + } + return url.substring(start, end); + } else { + return dbType; + } + } + + public static String resolveDatabaseFromUrl(String url) { + Assert.isTrue(!StringUtils.isBlank(url), "Jdbc url must not be empty!"); + if ("sqlserver".equals(resolveDbTypeFromUrl(url))) { + String[] segments = url.split(";"); + for (String segment : segments) { + if (segment.toLowerCase().contains("databasename=")) { + int start = segment.toLowerCase().indexOf("databasename=") + + "databasename=".length(); + return segment.substring(start).trim(); + } + } + throw new InvalidParameterException("jdbc url is invalid!"); + } + + int start = url.lastIndexOf("/"); + if (start < 0) { + /** + * oracle sid 格式,{@see jdbc:oracle:thin:@host:port:SID} + */ + if ("oracle".equals(resolveDbTypeFromUrl(url))) { + start = url.lastIndexOf(":"); + } else { + throw new InvalidParameterException("jdbc url is invalid!"); + } + } + int end = url.indexOf("?", start); + if (end != -1) { + return url.substring(start + 1, end); + } + return url.substring(start + 1); + } + @Override public void setEnvironment(Environment environment) { this.environment = environment; diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanPostProcessor.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanPostProcessor.java deleted file mode 100644 index 4d072be5..00000000 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/datasource/processor/DataSourceBeanPostProcessor.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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. - */ -package com.alipay.sofa.tracer.boot.datasource.processor; - -import com.alipay.common.tracer.core.utils.ReflectionUtils; -import com.alipay.common.tracer.core.utils.StringUtils; -import com.alipay.sofa.tracer.plugins.datasource.SmartDataSource; -import com.alipay.sofa.tracer.plugins.datasource.utils.DataSourceUtils; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; -import org.springframework.util.Assert; - -import javax.sql.DataSource; - -import java.lang.reflect.Method; - -import static com.alipay.common.tracer.core.configuration.SofaTracerConfiguration.TRACER_APPNAME_KEY; - -/** - * @author qilong.zql - * @since 2.3.2 - */ -public class DataSourceBeanPostProcessor implements BeanPostProcessor, EnvironmentAware { - - private Environment environment; - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { - /** - * filter transformed datasource {@link DataSourceBeanFactoryPostProcessor} - * filter bean which is type of {@link SmartDataSource} - * filter bean which is not type of {@link DataSource} - */ - if (beanName.startsWith(DataSourceBeanFactoryPostProcessor.SOFA_TRACER_DATASOURCE) - || bean instanceof SmartDataSource || !(bean instanceof DataSource)) { - return bean; - } - - String getUrlMethodName; - String url; - /** - * Now DataSource Tracer only support the following type: Druid, C3p0, Dbcp, tomcat datasource, hikari - */ - if (DataSourceUtils.isDruidDataSource(bean) || DataSourceUtils.isDbcpDataSource(bean) - || DataSourceUtils.isTomcatDataSource(bean)) { - getUrlMethodName = DataSourceUtils.METHOD_GET_URL; - } else if (DataSourceUtils.isC3p0DataSource(bean) - || DataSourceUtils.isHikariDataSource(bean)) { - getUrlMethodName = DataSourceUtils.METHOD_GET_JDBC_URL; - } else { - return bean; - } - - try { - Method urlMethod = ReflectionUtils.findMethod(bean.getClass(), getUrlMethodName); - urlMethod.setAccessible(true); - url = (String) urlMethod.invoke(bean); - } catch (Throwable throwable) { - throw new BeanCreationException(String.format("Can not find method: %s in class %s.", - getUrlMethodName, bean.getClass().getCanonicalName()), throwable); - } - - SmartDataSource proxiedDataSource = new SmartDataSource((DataSource) bean); - String appName = environment.getProperty(TRACER_APPNAME_KEY); - Assert.isTrue(!StringUtils.isBlank(appName), TRACER_APPNAME_KEY + " must be configured!"); - proxiedDataSource.setAppName(appName); - proxiedDataSource.setDbType(DataSourceUtils.resolveDbTypeFromUrl(url)); - proxiedDataSource.setDatabase(DataSourceUtils.resolveDatabaseFromUrl(url)); - - // execute proxied datasource init-method - proxiedDataSource.init(); - return proxiedDataSource; - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } -} \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java index e8984bc9..6cc7115e 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java @@ -16,20 +16,20 @@ */ package com.alipay.sofa.tracer.boot.listener; -import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; -import com.alipay.common.tracer.core.utils.StringUtils; -import com.alipay.sofa.tracer.boot.properties.SofaTracerProperties; -import org.springframework.boot.bind.PropertiesConfigurationFactory; import com.alipay.sofa.infra.utils.SOFABootEnvUtils; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; import org.springframework.context.ApplicationListener; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.util.Assert; -import org.springframework.validation.BindException; + +import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.utils.StringUtils; +import com.alipay.sofa.tracer.boot.properties.SofaTracerProperties; /** * Parse SOFATracer Configuration in early stage. @@ -50,12 +50,6 @@ public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { return; } - // set loggingPath - String loggingPath = environment.getProperty("logging.path"); - if (StringUtils.isNotBlank(loggingPath)) { - System.setProperty("logging.path", loggingPath); - } - // check spring.application.name String applicationName = environment .getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY); @@ -64,27 +58,14 @@ public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY, applicationName); + // static binding SofaTracerProperties tempTarget = new SofaTracerProperties(); - PropertiesConfigurationFactory binder = new PropertiesConfigurationFactory( - tempTarget); - ConfigurationProperties configurationPropertiesAnnotation = this - .getConfigurationPropertiesAnnotation(tempTarget); - if (configurationPropertiesAnnotation != null - && StringUtils.isNotBlank(configurationPropertiesAnnotation.prefix())) { - //consider compatible Spring Boot 1.5.X and 2.x - binder.setIgnoreInvalidFields(configurationPropertiesAnnotation.ignoreInvalidFields()); - binder.setIgnoreUnknownFields(configurationPropertiesAnnotation.ignoreUnknownFields()); - binder.setTargetName(configurationPropertiesAnnotation.prefix()); - } else { - binder.setTargetName(SofaTracerProperties.SOFA_TRACER_CONFIGURATION_PREFIX); - } - binder.setConversionService(new DefaultConversionService()); - binder.setPropertySources(environment.getPropertySources()); - try { - binder.bindPropertiesToTarget(); - } catch (BindException ex) { - throw new IllegalStateException("Cannot bind to SofaTracerProperties", ex); - } + ConfigurationProperties configurationProperties = AnnotationUtils.findAnnotation( + SofaTracerProperties.class, ConfigurationProperties.class); + Binder binder = Binder.get(environment); + Bindable bindable = Bindable.of(SofaTracerProperties.class).withExistingValue(tempTarget) + .withAnnotations(configurationProperties); + binder.bind(SofaTracerProperties.SOFA_TRACER_CONFIGURATION_PREFIX, bindable); //properties convert to tracer SofaTracerConfiguration.setProperty( diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/HikariDataSourceConfiguration.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/HikariDataSourceConfiguration.java deleted file mode 100644 index a1027cc0..00000000 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/base/HikariDataSourceConfiguration.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - */ -package com.alipay.sofa.tracer.boot.base; - -import com.zaxxer.hikari.HikariDataSource; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import javax.sql.DataSource; - -/** - * @author qilong.zql - * @since 2.3.2 - */ -@Configuration -public class HikariDataSourceConfiguration { - @Value("${spring.datasource.url}") - private String jdbcUrl; - - @Value("${spring.datasource.driver-class-name}") - private String driverClassName; - - @Value("${spring.datasource.username}") - private String username; - - @Value("${spring.datasource.password}") - private String password; - - @Bean - public DataSource hikariDataSource() { - HikariDataSource dataSource = new HikariDataSource(); - dataSource.setJdbcUrl(jdbcUrl); - dataSource.setDriverClassName(driverClassName); - dataSource.setUsername(username); - dataSource.setPassword(password); - return dataSource; - } -} \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceBFPPTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceBFPPTest.java index 9c5593ab..6524a6e8 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceBFPPTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceBFPPTest.java @@ -16,6 +16,7 @@ */ package com.alipay.sofa.tracer.boot.datasource; +import com.alipay.sofa.tracer.boot.datasource.processor.DataSourceBeanFactoryPostProcessor; import com.alipay.sofa.tracer.plugins.datasource.tracer.Endpoint; import com.alipay.sofa.tracer.plugins.datasource.utils.DataSourceUtils; import org.junit.Assert; @@ -29,52 +30,34 @@ */ public class DataSourceBFPPTest { - private String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:orcl"; - private String jdbcUrl2 = "jdbc:oracle:thin:@//localhost:1521/orcl.city.com"; - private String jdbcUrl4 = "jdbc:mysql://127.0.0.1:3306/imooc?useUnicode=true&characterEncoding=utf-8"; - private String jdbcUrl5 = "jdbc:mysql://127.0.0.1:3306/dataBase"; - private String jdbcUrl9 = "jdbc@:mysql://127.0.0.1:3306/dataBase"; + private String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:orcl"; + private String jdbcUrl2 = "jdbc:oracle:thin:@//localhost:1521/orcl.city.com"; + private String jdbcUrl4 = "jdbc:mysql://127.0.0.1:3306/imooc?useUnicode=true&characterEncoding=utf-8"; + private String jdbcUrl5 = "jdbc:mysql://127.0.0.1:3306/dataBase"; // SQL Server 2000 - private String jdbcUrl6 = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample "; - private String jdbcUrl10 = "invalid:sqlserver://localhost:1433; DatabaseName=sample "; + private String jdbcUrl6 = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample "; // SQL Server 2005 - private String jdbcUrl7 = "jdbc:sqlserver://localhost:1433; DatabaseName=sample "; - private String jdbcUrl11 = "jdbc://localhost/1433; DatabaseName=sample "; - private String jdbcUrl8 = "invalid"; + private String jdbcUrl7 = "jdbc:sqlserver://localhost:1433; DatabaseName=sample "; + private String jdbcUrl8 = "invalid"; @Test public void testDbType() { - Assert.assertTrue("oracle".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl))); - Assert.assertTrue("oracle".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl2))); - Assert.assertTrue("mysql".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl4))); - Assert.assertTrue("mysql".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl5))); - Assert.assertTrue("sqlserver".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl6))); - Assert.assertTrue("sqlserver".equals(DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl7))); + Assert.assertTrue("oracle".equals(DataSourceBeanFactoryPostProcessor + .resolveDbTypeFromUrl(jdbcUrl))); + Assert.assertTrue("oracle".equals(DataSourceBeanFactoryPostProcessor + .resolveDbTypeFromUrl(jdbcUrl2))); + Assert.assertTrue("mysql".equals(DataSourceBeanFactoryPostProcessor + .resolveDbTypeFromUrl(jdbcUrl4))); + Assert.assertTrue("mysql".equals(DataSourceBeanFactoryPostProcessor + .resolveDbTypeFromUrl(jdbcUrl5))); + Assert.assertTrue("sqlserver".equals(DataSourceBeanFactoryPostProcessor + .resolveDbTypeFromUrl(jdbcUrl6))); + Assert.assertTrue("sqlserver".equals(DataSourceBeanFactoryPostProcessor + .resolveDbTypeFromUrl(jdbcUrl7))); boolean error = false; try { - DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl8); - } catch (InvalidParameterException ex) { - error = true; - } - Assert.assertTrue(error); - error = false; - try { - DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl9); - } catch (InvalidParameterException ex) { - error = true; - } - Assert.assertTrue(error); - error = false; - try { - DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl10); - } catch (InvalidParameterException ex) { - error = true; - } - Assert.assertTrue(error); - error = false; - try { - DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl11); + DataSourceBeanFactoryPostProcessor.resolveDbTypeFromUrl(jdbcUrl8); } catch (InvalidParameterException ex) { error = true; } @@ -83,18 +66,24 @@ public void testDbType() { @Test public void testDataBase() { - Assert.assertTrue("orcl".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl))); - Assert.assertTrue("orcl.city.com".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl2))); + Assert.assertTrue("orcl".equals(DataSourceBeanFactoryPostProcessor + .resolveDatabaseFromUrl(jdbcUrl))); + Assert.assertTrue("orcl.city.com".equals(DataSourceBeanFactoryPostProcessor + .resolveDatabaseFromUrl(jdbcUrl2))); - Assert.assertTrue("imooc".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl4))); - Assert.assertTrue("dataBase".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl5))); + Assert.assertTrue("imooc".equals(DataSourceBeanFactoryPostProcessor + .resolveDatabaseFromUrl(jdbcUrl4))); + Assert.assertTrue("dataBase".equals(DataSourceBeanFactoryPostProcessor + .resolveDatabaseFromUrl(jdbcUrl5))); - Assert.assertTrue("sample".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl6))); - Assert.assertTrue("sample".equals(DataSourceUtils.resolveDatabaseFromUrl(jdbcUrl7))); + Assert.assertTrue("sample".equals(DataSourceBeanFactoryPostProcessor + .resolveDatabaseFromUrl(jdbcUrl6))); + Assert.assertTrue("sample".equals(DataSourceBeanFactoryPostProcessor + .resolveDatabaseFromUrl(jdbcUrl7))); boolean error = false; try { - DataSourceUtils.resolveDbTypeFromUrl(jdbcUrl8); + DataSourceBeanFactoryPostProcessor.resolveDbTypeFromUrl(jdbcUrl8); } catch (InvalidParameterException ex) { error = true; } diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerDisableTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerDisableTest.java index 132149cd..6ad9a11f 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerDisableTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerDisableTest.java @@ -25,7 +25,7 @@ import javax.sql.DataSource; -/**DataSourceUtils +/** * @author qilong.zql * @sicne 2.2.0 */ @@ -33,10 +33,10 @@ public class DataSourceTracerDisableTest extends AbstractTestBase { @Autowired - private DataSource simpleDataSource; + private DataSource dataSource; @Test public void testDataSource() { - Assert.assertTrue(simpleDataSource instanceof HikariDataSource); + Assert.assertTrue(dataSource instanceof HikariDataSource); } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerTest.java index 338f3dfc..99f6e58c 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceTracerTest.java @@ -18,7 +18,6 @@ import com.alipay.sofa.tracer.boot.base.AbstractTestBase; import com.alipay.sofa.tracer.plugins.datasource.SmartDataSource; -import com.zaxxer.hikari.HikariDataSource; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -32,19 +31,11 @@ public class DataSourceTracerTest extends AbstractTestBase { @Autowired - private DataSource simpleDataSource; - - @Autowired - private DataSource hikariDataSource; + private DataSource dataSource; @Test public void testDataSource() { - Assert.assertTrue(simpleDataSource instanceof SmartDataSource); - Assert.assertTrue(hikariDataSource instanceof SmartDataSource); - Assert.assertFalse(((SmartDataSource) simpleDataSource).getDelegate().equals( - ((SmartDataSource) hikariDataSource).getDelegate())); - Assert - .assertTrue(((SmartDataSource) hikariDataSource).getDelegate() instanceof HikariDataSource); + Assert.assertTrue(dataSource instanceof SmartDataSource); } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceUrlTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceUrlTest.java deleted file mode 100644 index 14b06863..00000000 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/datasource/DataSourceUrlTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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. - */ -package com.alipay.sofa.tracer.boot.datasource; - -import com.alibaba.druid.pool.DruidDataSource; -import com.alipay.common.tracer.core.utils.ReflectionUtils; -import com.alipay.sofa.tracer.plugins.datasource.utils.DataSourceUtils; -import com.mchange.v2.c3p0.ComboPooledDataSource; -import com.zaxxer.hikari.HikariDataSource; -import org.apache.commons.dbcp.BasicDataSource; -import org.apache.tomcat.jdbc.pool.DataSource; -import org.junit.Assert; -import org.junit.Test; - -import java.lang.reflect.Method; - -/** - * @author qilong.zql - * @since 2.3.2 - */ -public class DataSourceUrlTest { - @Test - public void testGetDataSourceUrl() throws Throwable { - // Druid - DruidDataSource druidDataSource = new DruidDataSource(); - druidDataSource.setUrl("test-url"); - Method method = ReflectionUtils.findMethod(druidDataSource.getClass(), - DataSourceUtils.METHOD_GET_URL); - Assert.assertNotNull(method); - Assert.assertEquals("test-url", method.invoke(druidDataSource)); - - // dbcp - BasicDataSource basicDataSource = new BasicDataSource(); - basicDataSource.setUrl("test-url"); - method = ReflectionUtils.findMethod(basicDataSource.getClass(), - DataSourceUtils.METHOD_GET_URL); - Assert.assertNotNull(method); - Assert.assertEquals("test-url", method.invoke(basicDataSource)); - - // tomcat datasource - DataSource dataSource = new DataSource(); - dataSource.setUrl("test-url"); - method = ReflectionUtils.findMethod(dataSource.getClass(), DataSourceUtils.METHOD_GET_URL); - Assert.assertNotNull(method); - Assert.assertEquals("test-url", method.invoke(dataSource)); - - // c3p0 - ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); - comboPooledDataSource.setJdbcUrl("test-url"); - method = ReflectionUtils.findMethod(comboPooledDataSource.getClass(), - DataSourceUtils.METHOD_GET_JDBC_URL); - Assert.assertNotNull(method); - Assert.assertEquals("test-url", method.invoke(comboPooledDataSource)); - - // hikari - HikariDataSource hikariDataSource = new HikariDataSource(); - hikariDataSource.setJdbcUrl("test-url"); - method = ReflectionUtils.findMethod(hikariDataSource.getClass(), - DataSourceUtils.METHOD_GET_JDBC_URL); - Assert.assertNotNull(method); - Assert.assertEquals("test-url", method.invoke(hikariDataSource)); - } -} \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/resources/application.properties b/tracer-sofa-boot-starter/src/test/resources/application.properties index 60110bf3..cf5cac3e 100644 --- a/tracer-sofa-boot-starter/src/test/resources/application.properties +++ b/tracer-sofa-boot-starter/src/test/resources/application.properties @@ -1,13 +1 @@ spring.application.name=test-app-name -spring.datasource.url=jdbc:mysql://localhost:3306/sofa -spring.datasource.driver-class-name=com.mysql.jdbc.Driver -spring.datasource.username=xxxx -spring.datasource.password=xxxx -spring.datasource.type=com.zaxxer.hikari.HikariDataSource -spring.datasource.hikari.minimum-idle=3 -spring.datasource.hikari.maximum-pool-size=5 -spring.datasource.hikari.idle-timeout=30000 -spring.datasource.hikari.pool-name=SofaHikariCPDatasource -spring.datasource.hikari.max-lifetime=1800000 -spring.datasource.hikari.connection-timeout=30000 -spring.datasource.hikari.connection-test-query=SELECT 1 diff --git a/tracer-sofa-boot-starter/src/test/resources/hikariDataSource.xml b/tracer-sofa-boot-starter/src/test/resources/hikariDataSource.xml index e9bca35d..e7af436b 100644 --- a/tracer-sofa-boot-starter/src/test/resources/hikariDataSource.xml +++ b/tracer-sofa-boot-starter/src/test/resources/hikariDataSource.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + From fd691744ff52885224e0c94878d656372e59e13b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Tue, 12 Mar 2019 19:07:45 +0800 Subject: [PATCH 11/24] okhttp --- .../sofa-tracer-zipkin-plugin/pom.xml | 13 ++++- .../reporters/Okhttp3SpanRemoteReporter.java | 48 +++++++++++++++++++ .../SofaTracerConfigurationListener.java | 7 +-- .../ZipkinSofaTracerAutoConfiguration.java | 2 +- .../tracer/boot/config/ConfigurationTest.java | 18 +++---- ...ipkinSofaTracerSpanRemoteReporterTest.java | 4 +- .../tracer/test/base/AbstractTestBase.java | 2 +- 7 files changed, 74 insertions(+), 20 deletions(-) create mode 100644 sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/reporters/Okhttp3SpanRemoteReporter.java diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml index 49b7821c..05c6048d 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml @@ -29,7 +29,12 @@ io.zipkin.reporter2 zipkin-reporter - 2.7.13 + 2.7.15 + + + io.zipkin.reporter2 + zipkin-sender-okhttp3 + 2.7.15 com.alipay.sofa @@ -84,6 +89,12 @@ spring-boot-starter-test test + + io.micrometer + micrometer-core + 1.1.1 + compile + diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/reporters/Okhttp3SpanRemoteReporter.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/reporters/Okhttp3SpanRemoteReporter.java new file mode 100644 index 00000000..ecc84f9d --- /dev/null +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/reporters/Okhttp3SpanRemoteReporter.java @@ -0,0 +1,48 @@ +package com.alipay.sofa.tracer.plugins.zipkin.reporters; + +import com.alipay.common.tracer.core.listener.SpanReportListener; +import com.alipay.common.tracer.core.span.SofaTracerSpan; +import com.alipay.sofa.tracer.plugins.zipkin.adapter.ZipkinV2SpanAdapter; +import zipkin2.Span; +import zipkin2.reporter.AsyncReporter; +import zipkin2.reporter.okhttp3.OkHttpSender; + +import java.io.Closeable; +import java.io.Flushable; +import java.io.IOException; + +/** + * @author: guolei.sgl (guolei.sgl@antfin.com) 2019/3/11 3:39 PM + * @since: + **/ +public class Okhttp3SpanRemoteReporter implements SpanReportListener, Flushable, Closeable { + + private OkHttpSender okHttpSender; + private ZipkinV2SpanAdapter zipkinV2SpanAdapter; + private final OkHttpSender sender; + + private final AsyncReporter delegate; + + public Okhttp3SpanRemoteReporter(){ + this.zipkinV2SpanAdapter = new ZipkinV2SpanAdapter(); + this.sender = OkHttpSender.create("htp://localhost:9411/api/v1/spans"); + this.delegate = AsyncReporter.create(sender); + } + + @Override + public void onSpanReport(SofaTracerSpan span) { + //convert + Span zipkinSpan = zipkinV2SpanAdapter.convertToZipkinSpan(span); + this.delegate.report(zipkinSpan); + } + + @Override + public void close() throws IOException { + delegate.close(); + } + + @Override + public void flush() throws IOException { + delegate.flush(); + } +} diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java index 6cc7115e..1ff786be 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/listener/SofaTracerConfigurationListener.java @@ -105,11 +105,6 @@ public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { @Override public int getOrder() { - return HIGHEST_PRECEDENCE + 20; - } - - private ConfigurationProperties getConfigurationPropertiesAnnotation(Object targetObject) { - return AnnotationUtils.findAnnotation(targetObject.getClass(), - ConfigurationProperties.class); + return HIGHEST_PRECEDENCE + 30; } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerAutoConfiguration.java b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerAutoConfiguration.java index b154398a..8f667880 100644 --- a/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerAutoConfiguration.java +++ b/tracer-sofa-boot-starter/src/main/java/com/alipay/sofa/tracer/boot/zipkin/configuration/ZipkinSofaTracerAutoConfiguration.java @@ -37,7 +37,7 @@ @Configuration @EnableConfigurationProperties(ZipkinSofaTracerProperties.class) @ConditionalOnProperty(value = "com.alipay.sofa.tracer.zipkin.enabled", matchIfMissing = true) -@ConditionalOnClass({ zipkin2.Span.class, zipkin2.reporter.AsyncReporter.class }) +@ConditionalOnClass({ zipkin2.Span.class, zipkin2.reporter.AsyncReporter.class, RestTemplate.class }) public class ZipkinSofaTracerAutoConfiguration { @Autowired diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/config/ConfigurationTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/config/ConfigurationTest.java index be0feba4..8be7d241 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/config/ConfigurationTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/config/ConfigurationTest.java @@ -76,14 +76,14 @@ public void testAdvanceTracerConfig() { Assert.assertEquals("1", sofaTracerProperties.getBaggageMaxLength()); } - @Test - public void testTracerLogDir() { - File defaultDir = new File(System.getProperty("user.home") + File.separator + "logs" - + File.separator + "tracelog"); - File configDir = new File(System.getProperty("user.dir") + File.separator + "logs" - + File.separator + "tracelog"); - Assert.assertFalse(defaultDir.exists()); - Assert.assertTrue(configDir.exists()); - } + // @Test + // public void testTracerLogDir() { + // File defaultDir = new File(System.getProperty("user.home") + File.separator + "logs" + // + File.separator + "tracelog"); + // File configDir = new File(System.getProperty("user.dir") + File.separator + "logs" + // + File.separator + "tracelog"); + // Assert.assertFalse(defaultDir.exists()); + // Assert.assertTrue(configDir.exists()); + // } } \ No newline at end of file diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java index b65ea038..ecd918fe 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/zipkin/ZipkinSofaTracerSpanRemoteReporterTest.java @@ -186,7 +186,7 @@ public void testDoServerReport() throws Exception { sofaTracerServerSpan.setOperationName("mockOperationName"); //ss TL this.remoteTracer.serverSend("0"); - //异步汇报,所以 sleep 10s + //异步汇报,所以 sleep 1s Thread.sleep(1000); //assert SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); @@ -229,7 +229,7 @@ public void testDoReport() throws Exception { assertEquals(sofaTracerServerSpan, sofaTraceContext.getCurrentSpan()); //ss TL this.remoteTracer.serverSend("0"); - //异步汇报,所以 sleep 10s + //异步汇报,所以 sleep 1s Thread.sleep(1000); //assert assertTrue(sofaTraceContext.isEmpty()); diff --git a/tracer-test/core-test/src/test/java/com/alipay/common/tracer/test/base/AbstractTestBase.java b/tracer-test/core-test/src/test/java/com/alipay/common/tracer/test/base/AbstractTestBase.java index ec0995ce..39c51d71 100644 --- a/tracer-test/core-test/src/test/java/com/alipay/common/tracer/test/base/AbstractTestBase.java +++ b/tracer-test/core-test/src/test/java/com/alipay/common/tracer/test/base/AbstractTestBase.java @@ -203,7 +203,7 @@ public SofaTracerSpan recoverServerSpan(String serverSpanId) { String traceId = TraceIdGenerator.generate(); //默认不采样 SofaTracerSpanContext spanContext = new SofaTracerSpanContext(traceId, serverSpanId, - StringUtils.EMPTY_STRING, false); + StringUtils.EMPTY_STRING, true); String callServiceName = "callServiceName"; //create server From 7e01b9de459291a78c6ec74b696a9f6c391573da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Wed, 13 Mar 2019 20:33:05 +0800 Subject: [PATCH 12/24] up version 3.0.3 for sampler --- tracer-samples/tracer-sample-with-sampler/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tracer-samples/tracer-sample-with-sampler/pom.xml b/tracer-samples/tracer-sample-with-sampler/pom.xml index 59494018..e7f6f263 100644 --- a/tracer-samples/tracer-sample-with-sampler/pom.xml +++ b/tracer-samples/tracer-sample-with-sampler/pom.xml @@ -4,7 +4,7 @@ sofa-tracer-samples com.alipay.sofa - 2.2.0 + 3.0.3-SNAPSHOT 4.0.0 From 75339055660b7a6f74959654c17b637305d4008f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Wed, 13 Mar 2019 20:50:44 +0800 Subject: [PATCH 13/24] up version 3.0.3 for sampler --- tracer-samples/tracer-sample-with-sampler/pom.xml | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/tracer-samples/tracer-sample-with-sampler/pom.xml b/tracer-samples/tracer-sample-with-sampler/pom.xml index e7f6f263..5d0ca680 100644 --- a/tracer-samples/tracer-sample-with-sampler/pom.xml +++ b/tracer-samples/tracer-sample-with-sampler/pom.xml @@ -35,15 +35,4 @@ test - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - From cdf6a654d89b932fb2af9ab3aad89b32009a7d58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Wed, 13 Mar 2019 20:57:55 +0800 Subject: [PATCH 14/24] code format --- .../reporters/Okhttp3SpanRemoteReporter.java | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/reporters/Okhttp3SpanRemoteReporter.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/reporters/Okhttp3SpanRemoteReporter.java index ecc84f9d..41ce8ec3 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/reporters/Okhttp3SpanRemoteReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/reporters/Okhttp3SpanRemoteReporter.java @@ -1,3 +1,19 @@ +/* + * 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. + */ package com.alipay.sofa.tracer.plugins.zipkin.reporters; import com.alipay.common.tracer.core.listener.SpanReportListener; @@ -17,13 +33,13 @@ **/ public class Okhttp3SpanRemoteReporter implements SpanReportListener, Flushable, Closeable { - private OkHttpSender okHttpSender; - private ZipkinV2SpanAdapter zipkinV2SpanAdapter; - private final OkHttpSender sender; + private OkHttpSender okHttpSender; + private ZipkinV2SpanAdapter zipkinV2SpanAdapter; + private final OkHttpSender sender; - private final AsyncReporter delegate; + private final AsyncReporter delegate; - public Okhttp3SpanRemoteReporter(){ + public Okhttp3SpanRemoteReporter() { this.zipkinV2SpanAdapter = new ZipkinV2SpanAdapter(); this.sender = OkHttpSender.create("htp://localhost:9411/api/v1/spans"); this.delegate = AsyncReporter.create(sender); From ea04e98a0b0e52dbc2ff7196337210122f6afcb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Thu, 14 Mar 2019 18:07:02 +0800 Subject: [PATCH 15/24] sheery pick --- README.md | 5 ++ pom.xml | 7 ++- .../httpclient/base/AbstractTestBase.java | 7 ++- .../sofa-tracer-okhttp-plugin/pom.xml | 2 +- .../plugins/okhttp/base/OkHttpTracerTest.java | 2 +- .../springmvc/SpringMvcSofaTracerFilter.java | 16 ++--- tracer-all/pom.xml | 4 ++ .../appender/self/SynchronizingSelfLog.java | 1 - .../tracer/core/base/AbstractTestBase.java | 3 - .../src/main/resources/application.properties | 5 +- .../tracer-sample-with-sampler/README.md | 59 ++++++++++++------- .../tracer-sample-with-sampler/pom.xml | 21 ------- .../controller/SampleRestController.java | 15 ++++- .../tracer-sample-with-sofarpc/pom.xml | 1 - .../tracer-sample-with-springmvc/README.md | 39 +++++++++++- .../src/main/resources/application.properties | 4 +- tracer-sofa-boot-plugin/pom.xml | 1 - tracer-sofa-boot-starter/pom.xml | 4 -- 18 files changed, 125 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 1b32ffbd..9934a7e8 100644 --- a/README.md +++ b/README.md @@ -61,10 +61,15 @@ SOFATracer 的编译环境的要求为 JDK7 或者 JDK8,需要采用 [Apache M * [SOFATracer 示例工程(基于日志编程接口 SLF4J 示例打印 traceId)](./tracer-samples/tracer-sample-with-slf4j) * [SOFATracer 示例工程(基于 DataSource 示例落地日志)](./tracer-samples/tracer-sample-with-h2) * [SOFATracer 示例工程(基于 HttpClient 示例落地日志)](./tracer-samples/tracer-sample-with-httpclient) +* [SOFATracer 示例工程(SOFATracer 采样策略)](./tracer-samples/tracer-sample-with-sampler) ## 六、文档 请参考 [SOFATracer 官方文档](http://www.sofastack.tech/sofa-tracer/docs/Home)。 +## 七、致谢 + +SOFATracer 中的部分实现参考了阿里的 EagleEye 组件,感谢 EagleEye 的同学们。 + diff --git a/pom.xml b/pom.xml index 9594e6fa..576fc9bf 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,6 @@ tracer-all-parent 3.0.3-SNAPSHOT pom - tracer-all-parent Alipay SOFATracer Log Implemented by OpenTracing @@ -72,6 +71,12 @@ Ant Financial https://www.alipay.com/ + + GuoLei Song + guolei.sgl@antfin.com + Ant Financial + https://www.alipay.com/ + diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/base/AbstractTestBase.java b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/base/AbstractTestBase.java index 3f70c536..caf12ea2 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/base/AbstractTestBase.java +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/base/AbstractTestBase.java @@ -75,10 +75,11 @@ public void setUp() throws Exception { * @throws IOException */ public static void cleanLogDirectory() throws IOException { - File file = customFileLog(""); - if (file.exists()) { - FileUtils.cleanDirectory(file); + File file = new File(logDirectoryPath); + if (!file.exists()) { + return; } + FileUtils.cleanDirectory(file); } protected static File customFileLog(String fileName) { diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml index 0b20a9ed..123dd2b0 100644 --- a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 2.3.1 + 3.0.3-SNAPSHOT ../../pom.xml 4.0.0 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 7ce48ee4..24f504d5 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 @@ -30,8 +30,8 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 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 cf48ff79..2c975ed4 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 @@ -17,7 +17,6 @@ package com.alipay.sofa.tracer.plugins.springmvc; import com.alipay.common.tracer.core.SofaTracer; -import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; import com.alipay.common.tracer.core.registry.ExtendFormat; @@ -52,7 +51,7 @@ public void init(FilterConfig filterConfig) throws ServletException { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, - FilterChain filterChain) throws IOException, ServletException { + FilterChain filterChain) { if (this.springMvcTracer == null) { this.springMvcTracer = SpringMvcTracer.getSpringMvcTracerSingleton(); @@ -89,12 +88,12 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo //filter begin filterChain.doFilter(servletRequest, responseWrapper); //filter end - httpStatus = responseWrapper.getStatus(); responseSize = responseWrapper.getContentLength(); - } catch (Exception e) { - SelfLog.error("Spring MVC Tracer error occurs in SpringMvcSofaTracerFilter.doFilter.", - e); + } catch (Throwable t) { + httpStatus = 500; + // 异常抛出 + throw new RuntimeException(t); } finally { if (springMvcSpan != null) { springMvcSpan.setTag(CommonSpanTags.RESP_SIZE, responseSize); @@ -136,13 +135,16 @@ public String getFilterName() { */ public SofaTracerSpanContext getSpanContextFromRequest(HttpServletRequest request) { HashMap headers = new HashMap(); - Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); headers.put(key, value); } + // Delay the initialization of the SofaTracerSpanContext to execute the serverReceive method + if (headers.isEmpty() || !headers.containsKey("X-B3-TraceId")) { + return null; + } SofaTracer tracer = springMvcTracer.getSofaTracer(); SofaTracerSpanContext spanContext = (SofaTracerSpanContext) tracer.extract( diff --git a/tracer-all/pom.xml b/tracer-all/pom.xml index d8a9d9b6..05762cfa 100644 --- a/tracer-all/pom.xml +++ b/tracer-all/pom.xml @@ -32,6 +32,10 @@ com.alipay.sofa sofa-tracer-httpclient-plugin + + com.alipay.sofa + sofa-tracer-datasource-plugin + \ No newline at end of file diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java index 14d37a58..662b2d9b 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java @@ -151,5 +151,4 @@ static private void doLog(String log, String prefix) { t.printStackTrace(); } } - } \ No newline at end of file diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java index 5189bea8..d871e120 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java @@ -29,9 +29,6 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; -import java.util.stream.Stream; import static org.junit.Assert.assertEquals; diff --git a/tracer-samples/tracer-sample-with-httpclient/src/main/resources/application.properties b/tracer-samples/tracer-sample-with-httpclient/src/main/resources/application.properties index 7dc15490..194590de 100644 --- a/tracer-samples/tracer-sample-with-httpclient/src/main/resources/application.properties +++ b/tracer-samples/tracer-sample-with-httpclient/src/main/resources/application.properties @@ -1,4 +1,7 @@ # Application Name spring.application.name=HttpClientDemo # logging path -logging.path=./logs \ No newline at end of file +logging.path=./logs + +com.alipay.sofa.tracer.samplerPercentage=0 +com.alipay.sofa.tracer.samplerName=PercentageBasedSampler \ No newline at end of file diff --git a/tracer-samples/tracer-sample-with-sampler/README.md b/tracer-samples/tracer-sample-with-sampler/README.md index 6c489e36..d3de6281 100644 --- a/tracer-samples/tracer-sample-with-sampler/README.md +++ b/tracer-samples/tracer-sample-with-sampler/README.md @@ -8,26 +8,26 @@ #### 在 application.properties 中增加采样相关配置项 -```xml -#采样率 0~1 -com.alipay.sofa.tracer.samplerPercentage=1 +```properties +#采样率 0~100 +com.alipay.sofa.tracer.samplerPercentage=100 #采样模式类型名称 com.alipay.sofa.tracer.samplerName=PercentageBasedSampler ``` #### 验证方式 -* 当采样率设置为1时,每次都会打印摘要日志。 +* 当采样率设置为100时,每次都会打印摘要日志。 * 当采样率设置为0时,不打印 -* 当采样率设置为0~1之间时,按概率打印 +* 当采样率设置为0~100之间时,按概率打印 以请求 10 次来验证下结果。 -1、当采样率设置为1时,每次都会打印摘要日志 +1、当采样率设置为100时,每次都会打印摘要日志 启动工程,浏览器中输入:http://localhost:8080/springmvc ;并且刷新地址10次,查看日志如下: -```xml +```json {"time":"2018-11-09 11:54:47.643","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173568757510019269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":68,"current.thread.name":"http-nio-8080-exec-1","baggage":""} {"time":"2018-11-09 11:54:50.980","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569097710029269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":3,"current.thread.name":"http-nio-8080-exec-2","baggage":""} {"time":"2018-11-09 11:54:51.542","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173569153910049269","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":3,"current.thread.name":"http-nio-8080-exec-4","baggage":""} @@ -44,17 +44,17 @@ com.alipay.sofa.tracer.samplerName=PercentageBasedSampler 启动工程,浏览器中输入:http://localhost:8080/springmvc ;并且刷新地址10次,查看 ./logs/tracerlog/ 目录,没有 spring-mvc-degist.log 日志文件 -3、当采样率设置为0~1之间时,按概率打印 +3、当采样率设置为0~100之间时,按概率打印 -这里设置成 0.2 +这里设置成 20 * 刷新10次请求 -```xml +```json {"time":"2018-11-09 12:14:29.466","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173686946410159846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-5","baggage":""} ``` * 刷新20次请求 -```xml +```json {"time":"2018-11-09 12:14:29.466","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173686946410159846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-5","baggage":""} {"time":"2018-11-09 12:15:21.776","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173692177410319846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":2,"current.thread.name":"http-nio-8080-exec-2","baggage":""} {"time":"2018-11-09 12:15:22.439","local.app":"SOFATracerSpringMVC","traceId":"0a0fe8ec154173692243810359846","spanId":"0.1","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":0,"time.cost.milliseconds":1,"current.thread.name":"http-nio-8080-exec-6","baggage":""} @@ -69,9 +69,7 @@ SOFATracer 中提供了一个采样率计算的接口。采样模式需设置为 #### 在 application.properties 中增加采样相关配置项 -```xml -#采样模式类型名称 -com.alipay.sofa.tracer.samplerName=OpenRulesSampler +```properties #自定义采样规则实现类全限定名 com.alipay.sofa.tracer.samplerName.samplerCustomRuleClassName=com.alipay.sofa.tracer.examples.springmvc.sampler.CustomOpenRulesSamplerRuler ``` @@ -79,16 +77,37 @@ com.alipay.sofa.tracer.samplerName.samplerCustomRuleClassName=com.alipay.sofa.tr #### 自定义采样规则类 ```java -public class CustomOpenRulesSamplerRuler extends OpenRulesSampler.Rule { +public class CustomOpenRulesSamplerRuler implements Sampler { + + private static final String TYPE = "CustomOpenRulesSamplerRuler"; + @Override - public boolean matches(SofaTracerSpan sofaTracerSpan) { - if (sofaTracerSpan.getSofaTracer().getTracerType().equals("springmvc")){ - return true; + public SamplingStatus sample(SofaTracerSpan sofaTracerSpan) { + SamplingStatus samplingStatus = new SamplingStatus(); + Map tags = new HashMap(); + tags.put(SofaTracerConstant.SAMPLER_TYPE_TAG_KEY, TYPE); + tags = Collections.unmodifiableMap(tags); + samplingStatus.setTags(tags); + + if (sofaTracerSpan.isServer()) { + samplingStatus.setSampled(false); + } else { + samplingStatus.setSampled(true); } - return false; + return samplingStatus; + } + + @Override + public String getType() { + return TYPE; + } + + @Override + public void close() { + // do nothing } } ``` -在 matches 方法中,用户可以根据当前 sofaTracerSpan 提供的信息来决定是否进行打印。这个案例是通过判断当前tracerType来决定是否采样,如果tracerType是springmvc则采样,否则不采样。 +在 sample 方法中,用户可以根据当前 sofaTracerSpan 提供的信息来决定是否进行打印。这个案例是通过判断 isServer 来决定是否采样,isServer=true,不采样,否则采样。 相关实验结果,大家可以自行验证下。 diff --git a/tracer-samples/tracer-sample-with-sampler/pom.xml b/tracer-samples/tracer-sample-with-sampler/pom.xml index 5d0ca680..7e8aceb9 100644 --- a/tracer-samples/tracer-sample-with-sampler/pom.xml +++ b/tracer-samples/tracer-sample-with-sampler/pom.xml @@ -14,25 +14,4 @@ ${project.basedir}/../.. - - - - - com.alipay.sofa - tracer-sofa-boot-starter - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-logging - - - org.springframework.boot - spring-boot-starter-test - test - - diff --git a/tracer-samples/tracer-sample-with-slf4j/src/main/java/com/alipay/sofa/tracer/examples/slf4j/controller/SampleRestController.java b/tracer-samples/tracer-sample-with-slf4j/src/main/java/com/alipay/sofa/tracer/examples/slf4j/controller/SampleRestController.java index c1741111..3775ed6f 100644 --- a/tracer-samples/tracer-sample-with-slf4j/src/main/java/com/alipay/sofa/tracer/examples/slf4j/controller/SampleRestController.java +++ b/tracer-samples/tracer-sample-with-slf4j/src/main/java/com/alipay/sofa/tracer/examples/slf4j/controller/SampleRestController.java @@ -16,6 +16,7 @@ */ package com.alipay.sofa.tracer.examples.slf4j.controller; +import com.alipay.common.tracer.core.async.SofaTracerRunnable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; @@ -52,7 +53,19 @@ public Map slf4j(@RequestParam(value = "name", defaultValue = "S resultMap.put("success", true); resultMap.put("id", counter.incrementAndGet()); resultMap.put("content", String.format(TEMPLATE, name)); - logger.info("SOFATracer Print TraceId and SpanId"); + long id = Thread.currentThread().getId(); + logger.info("SOFATracer Print TraceId and SpanId "); + + // Asynchronous thread transparent transmission + final SofaTracerRunnable sofaTracerRunnable = new SofaTracerRunnable(new Runnable() { + @Override + public void run() { + logger.info("SOFATracer Print TraceId and SpanId In Child Thread."); + } + }); + + Thread thread = new Thread(sofaTracerRunnable); + thread.start(); return resultMap; } } diff --git a/tracer-samples/tracer-sample-with-sofarpc/pom.xml b/tracer-samples/tracer-sample-with-sofarpc/pom.xml index 4419f25e..0713ad76 100644 --- a/tracer-samples/tracer-sample-with-sofarpc/pom.xml +++ b/tracer-samples/tracer-sample-with-sofarpc/pom.xml @@ -21,7 +21,6 @@ com.alipay.sofa tracer-sofa-boot-starter - com.alipay.sofa rpc-sofa-boot-starter diff --git a/tracer-samples/tracer-sample-with-springmvc/README.md b/tracer-samples/tracer-sample-with-springmvc/README.md index 3af44dc6..c23e7589 100644 --- a/tracer-samples/tracer-sample-with-springmvc/README.md +++ b/tracer-samples/tracer-sample-with-springmvc/README.md @@ -42,9 +42,9 @@ ``` -最后,在工程的 `application.properties` 文件下添加一个 SOFATracer 要使用的参数,包括`spring.application.name` 用于标示当前应用的名称;`logging.path` 用于指定日志的输出目录。 +最后,在工程的 `application.properties` 文件下添加一个 SOFATracer 要使用的参数,包括 `spring.application.name` 用于标示当前应用的名称;`logging.path` 用于指定日志的输出目录。 -``` +```properties # Application Name spring.application.name=SOFATracerSpringMVC # logging path @@ -116,6 +116,39 @@ public class SampleRestController { 通过访问 [http://localhost:8080/springmvc](http://localhost:8080/springmvc) SOFATracer 会记录每一次访问的摘要日志,可以打开 `spring-mvc-digest.log` 看到具体的输出内容,而对于每一个输出字段的含义可以看 SOFATracer 的说明文档。 -``` +```json {"time":"2018-05-17 22:20:34.279","local.app":"SOFATracerSpringMVC","traceId":"0a0fe9391526566833985100139443","spanId":"0","request.url":"http://localhost:8080/springmvc","method":"GET","result.code":"200","req.size.bytes":-1,"resp.size.bytes":69,"time.cost.milliseconds":284,"current.thread.name":"http-nio-8080-exec-1","baggage":""} ``` + +## 对于标准 servlet 容器的支持( tomcat/jetty 等) + +sofa-tracer-springmvc-plugin 插件提供了对标准 servlet-api 的支持,因此,凡基于标准 servlet 规范的容器,也均可以使用此插件来收集链路数据。 + +### 依赖引入 + +上面的案例是基于 springboot/SOFABoot 使用的;如果在非 springboot/SOFABoot 中使用,仅需引入插件依赖即可: + +```xml + + com.alipay.sofa + sofa-tracer-springmvc-plugin + 2.2.0 + +``` + +### 配置 filter + +在工程的 web.xml 配置 filter + +```xml + + SpringMvcSofaTracerFilter + com.alipay.sofa.tracer.plugins.springmvc.SpringMvcSofaTracerFilter + + + SpringMvcSofaTracerFilter + /* + + +``` +这样应用通过 tomcat 或者 jetty 启动时,即可将 servlet 容器的链路数据打印到日志中了。 \ No newline at end of file diff --git a/tracer-samples/tracer-sample-with-springmvc/src/main/resources/application.properties b/tracer-samples/tracer-sample-with-springmvc/src/main/resources/application.properties index 75caa4f1..cf572725 100644 --- a/tracer-samples/tracer-sample-with-springmvc/src/main/resources/application.properties +++ b/tracer-samples/tracer-sample-with-springmvc/src/main/resources/application.properties @@ -20,6 +20,6 @@ spring.application.name=SOFATracerSpringMVC # logging path logging.path=./logs -com.alipay.sofa.tracer.samplerPercentage=0.2 +com.alipay.sofa.tracer.samplerPercentage=20 com.alipay.sofa.tracer.samplerName=PercentageBasedSampler -com.alipay.sofa.tracer.samplerCustomRuleClassName=com.alipay.sofa.tracer.examples.springmvc.sampler.CustomOpenRulesSamplerRuler \ No newline at end of file +#com.alipay.sofa.tracer.samplerCustomRuleClassName=com.alipay.sofa.tracer.examples.springmvc.sampler.CustomOpenRulesSamplerRuler \ No newline at end of file diff --git a/tracer-sofa-boot-plugin/pom.xml b/tracer-sofa-boot-plugin/pom.xml index 79466525..7be21e7a 100644 --- a/tracer-sofa-boot-plugin/pom.xml +++ b/tracer-sofa-boot-plugin/pom.xml @@ -8,7 +8,6 @@ 3.0.3-SNAPSHOT 4.0.0 - tracer-sofa-boot-plugin diff --git a/tracer-sofa-boot-starter/pom.xml b/tracer-sofa-boot-starter/pom.xml index f4ad965f..b7eccf3d 100644 --- a/tracer-sofa-boot-starter/pom.xml +++ b/tracer-sofa-boot-starter/pom.xml @@ -53,10 +53,6 @@ com.alipay.sofa infra-sofa-boot-starter - - com.alipay.sofa.common - log-sofa-boot-starter - org.springframework.boot From aa5e0a7ffcfc1e903987cf814b8967f7fa604d62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Fri, 15 Mar 2019 10:19:32 +0800 Subject: [PATCH 16/24] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E9=87=87=E6=A0=B7?= =?UTF-8?q?=E5=8F=82=E6=95=B0=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tracer/core/reporter/common/CommonSpanEncoderTest.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java index 0f45b048..39377a0f 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java @@ -19,18 +19,15 @@ import com.alipay.common.tracer.core.SofaTracer; import com.alipay.common.tracer.core.TestUtil; import com.alipay.common.tracer.core.base.AbstractTestBase; -import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; import com.alipay.common.tracer.core.reporter.digest.DiskReporterImpl; import com.alipay.common.tracer.core.reporter.type.TracerSystemLogEnum; -import com.alipay.common.tracer.core.samplers.SofaTracerPercentageBasedSampler; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tags.SpanTags; import com.alipay.common.tracer.core.tracertest.encoder.ClientSpanEncoder; import com.alipay.common.tracer.core.utils.StringUtils; import io.opentracing.tag.Tags; import org.apache.commons.io.FileUtils; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -61,10 +58,6 @@ public class CommonSpanEncoderTest extends AbstractTestBase { @Before public void setup() throws Exception { - SofaTracerConfiguration.setProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY, - SofaTracerPercentageBasedSampler.TYPE); - SofaTracerConfiguration.setProperty( - SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY, "100"); DiskReporterImpl clientDigestReporter = new DiskReporterImpl(clientLogType, new ClientSpanEncoder()); sofaTracer = new SofaTracer.Builder("commonProfileTracerType") From e06b1e241660940debf489af72a09fd1eac941ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Fri, 15 Mar 2019 11:48:24 +0800 Subject: [PATCH 17/24] rebuild --- .../tracer/core/listener/SpanReportListenerHolderTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolderTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolderTest.java index 7c2c2847..00df0768 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolderTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolderTest.java @@ -19,7 +19,6 @@ import com.alipay.common.tracer.core.span.SofaTracerSpan; import org.junit.Before; import org.junit.Test; - import java.util.ArrayList; import java.util.List; From 815449fb88a0a68b8747de05e67244991be01e2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Fri, 22 Mar 2019 16:02:10 +0800 Subject: [PATCH 18/24] prepare to release 3.0.3 --- pom.xml | 4 ++-- sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml | 2 +- tracer-all/pom.xml | 4 ++-- tracer-core/pom.xml | 2 +- tracer-extensions/pom.xml | 2 +- tracer-samples/pom.xml | 2 +- tracer-samples/tracer-sample-with-h2/pom.xml | 2 +- tracer-samples/tracer-sample-with-httpclient/pom.xml | 2 +- tracer-samples/tracer-sample-with-sampler/pom.xml | 2 +- tracer-samples/tracer-sample-with-slf4j/pom.xml | 2 +- tracer-samples/tracer-sample-with-sofarpc/pom.xml | 2 +- tracer-samples/tracer-sample-with-springmvc/pom.xml | 2 +- tracer-samples/tracer-sample-with-zipkin/pom.xml | 2 +- tracer-sofa-boot-plugin/pom.xml | 2 +- tracer-sofa-boot-starter/pom.xml | 2 +- tracer-test/core-test/pom.xml | 2 +- tracer-test/log4j-test/pom.xml | 4 ++-- tracer-test/log4j2-test/pom.xml | 2 +- tracer-test/logback-test/pom.xml | 2 +- 23 files changed, 26 insertions(+), 26 deletions(-) diff --git a/pom.xml b/pom.xml index 576fc9bf..6ca798cd 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ tracer-all-parent - 3.0.3-SNAPSHOT + 3.0.3 pom tracer-all-parent Alipay SOFATracer Log Implemented by OpenTracing @@ -33,7 +33,7 @@ 0.22.0 - 3.0.3-SNAPSHOT + 3.0.3 1.8 1.8 1.9.3 diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml index 4bb9f2a5..e92ff474 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../../pom.xml 4.0.0 diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml index dc615d76..b09e92f8 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../../pom.xml 4.0.0 diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml index 123dd2b0..7c30da8d 100644 --- a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../../pom.xml 4.0.0 diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml index 9ac006b2..a2a6d977 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../../pom.xml diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml index 05c6048d..cd3bb6b1 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../../pom.xml 4.0.0 diff --git a/tracer-all/pom.xml b/tracer-all/pom.xml index 05762cfa..6ffba661 100644 --- a/tracer-all/pom.xml +++ b/tracer-all/pom.xml @@ -5,12 +5,12 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 tracer-all - 3.0.3-SNAPSHOT + 3.0.3 jar SOFATracer in one without SOFABoot starter diff --git a/tracer-core/pom.xml b/tracer-core/pom.xml index 7f573b4a..16806c53 100644 --- a/tracer-core/pom.xml +++ b/tracer-core/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../pom.xml diff --git a/tracer-extensions/pom.xml b/tracer-extensions/pom.xml index ccdb21e8..e055bd50 100644 --- a/tracer-extensions/pom.xml +++ b/tracer-extensions/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 tracer-extensions diff --git a/tracer-samples/pom.xml b/tracer-samples/pom.xml index c9ac5e6c..e50ffa89 100644 --- a/tracer-samples/pom.xml +++ b/tracer-samples/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa tracer-all-parent - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 diff --git a/tracer-samples/tracer-sample-with-h2/pom.xml b/tracer-samples/tracer-sample-with-h2/pom.xml index 1dbb7b95..8a5a4939 100644 --- a/tracer-samples/tracer-sample-with-h2/pom.xml +++ b/tracer-samples/tracer-sample-with-h2/pom.xml @@ -5,7 +5,7 @@ sofa-tracer-samples com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 diff --git a/tracer-samples/tracer-sample-with-httpclient/pom.xml b/tracer-samples/tracer-sample-with-httpclient/pom.xml index 11a630d1..6fe0c1a4 100644 --- a/tracer-samples/tracer-sample-with-httpclient/pom.xml +++ b/tracer-samples/tracer-sample-with-httpclient/pom.xml @@ -5,7 +5,7 @@ sofa-tracer-samples com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 diff --git a/tracer-samples/tracer-sample-with-sampler/pom.xml b/tracer-samples/tracer-sample-with-sampler/pom.xml index 7e8aceb9..07a27cc8 100644 --- a/tracer-samples/tracer-sample-with-sampler/pom.xml +++ b/tracer-samples/tracer-sample-with-sampler/pom.xml @@ -4,7 +4,7 @@ sofa-tracer-samples com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 diff --git a/tracer-samples/tracer-sample-with-slf4j/pom.xml b/tracer-samples/tracer-sample-with-slf4j/pom.xml index 8160720a..5dd0efc7 100644 --- a/tracer-samples/tracer-sample-with-slf4j/pom.xml +++ b/tracer-samples/tracer-sample-with-slf4j/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa sofa-tracer-samples - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 diff --git a/tracer-samples/tracer-sample-with-sofarpc/pom.xml b/tracer-samples/tracer-sample-with-sofarpc/pom.xml index 0713ad76..2a5711e6 100644 --- a/tracer-samples/tracer-sample-with-sofarpc/pom.xml +++ b/tracer-samples/tracer-sample-with-sofarpc/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa sofa-tracer-samples - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 diff --git a/tracer-samples/tracer-sample-with-springmvc/pom.xml b/tracer-samples/tracer-sample-with-springmvc/pom.xml index d195911f..b495b0b8 100644 --- a/tracer-samples/tracer-sample-with-springmvc/pom.xml +++ b/tracer-samples/tracer-sample-with-springmvc/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa sofa-tracer-samples - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 diff --git a/tracer-samples/tracer-sample-with-zipkin/pom.xml b/tracer-samples/tracer-sample-with-zipkin/pom.xml index 241f1572..ace25e42 100644 --- a/tracer-samples/tracer-sample-with-zipkin/pom.xml +++ b/tracer-samples/tracer-sample-with-zipkin/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa sofa-tracer-samples - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 diff --git a/tracer-sofa-boot-plugin/pom.xml b/tracer-sofa-boot-plugin/pom.xml index 7be21e7a..d1e585fd 100644 --- a/tracer-sofa-boot-plugin/pom.xml +++ b/tracer-sofa-boot-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 4.0.0 tracer-sofa-boot-plugin diff --git a/tracer-sofa-boot-starter/pom.xml b/tracer-sofa-boot-starter/pom.xml index ea00e9d9..caef2c99 100644 --- a/tracer-sofa-boot-starter/pom.xml +++ b/tracer-sofa-boot-starter/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../pom.xml diff --git a/tracer-test/core-test/pom.xml b/tracer-test/core-test/pom.xml index 84fe0520..f49034c0 100644 --- a/tracer-test/core-test/pom.xml +++ b/tracer-test/core-test/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../../pom.xml diff --git a/tracer-test/log4j-test/pom.xml b/tracer-test/log4j-test/pom.xml index 9b59f9aa..4510eac5 100644 --- a/tracer-test/log4j-test/pom.xml +++ b/tracer-test/log4j-test/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../../pom.xml @@ -15,7 +15,7 @@ com.alipay.sofa tracer-extensions - 3.0.3-SNAPSHOT + 3.0.3 diff --git a/tracer-test/log4j2-test/pom.xml b/tracer-test/log4j2-test/pom.xml index a0f6e494..9fd7843b 100644 --- a/tracer-test/log4j2-test/pom.xml +++ b/tracer-test/log4j2-test/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../../pom.xml diff --git a/tracer-test/logback-test/pom.xml b/tracer-test/logback-test/pom.xml index da889176..b8c9f7ba 100644 --- a/tracer-test/logback-test/pom.xml +++ b/tracer-test/logback-test/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.3-SNAPSHOT + 3.0.3 ../../pom.xml From 94e989c811243a2f4c6af6444f7b2905b5b358f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Thu, 16 May 2019 10:59:39 +0800 Subject: [PATCH 19/24] upgrade 3.0.6 SNAPSHOT --- pom.xml | 4 ++-- sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-dubbo-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml | 2 +- sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml | 2 +- tracer-all/pom.xml | 4 ++-- tracer-core/pom.xml | 2 +- tracer-extensions/pom.xml | 2 +- tracer-samples/pom.xml | 2 +- tracer-samples/tracer-sample-with-dubbo/pom.xml | 2 +- .../tracer-sample-with-dubbo-consumer/pom.xml | 4 ++-- .../tracer-sample-with-dubbo-facade/pom.xml | 2 +- .../tracer-sample-with-dubbo-provider/pom.xml | 4 ++-- tracer-samples/tracer-sample-with-h2/pom.xml | 2 +- tracer-samples/tracer-sample-with-httpclient/pom.xml | 2 +- tracer-samples/tracer-sample-with-openfeign/pom.xml | 2 +- .../tracer-sample-with-openfeign-consumer/pom.xml | 2 +- .../tracer-sample-with-openfeign-provider/pom.xml | 2 +- tracer-samples/tracer-sample-with-sampler/pom.xml | 2 +- tracer-samples/tracer-sample-with-slf4j/pom.xml | 2 +- tracer-samples/tracer-sample-with-sofarpc/pom.xml | 2 +- tracer-samples/tracer-sample-with-springmvc/pom.xml | 2 +- tracer-samples/tracer-sample-with-zipkin/pom.xml | 2 +- tracer-sofa-boot-plugin/pom.xml | 2 +- tracer-sofa-boot-starter/pom.xml | 2 +- tracer-test/core-test/pom.xml | 2 +- tracer-test/log4j-test/pom.xml | 4 ++-- tracer-test/log4j2-test/pom.xml | 2 +- tracer-test/logback-test/pom.xml | 2 +- 32 files changed, 37 insertions(+), 37 deletions(-) diff --git a/pom.xml b/pom.xml index 069dbe46..f6cd0bbe 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ tracer-all-parent - 3.0.5 + 3.0.6-SNAPSHOT pom tracer-all-parent Alipay SOFATracer Log Implemented by OpenTracing @@ -35,7 +35,7 @@ 0.22.0 - 3.0.5 + 3.0.6-SNAPSHOT 1.8 1.8 1.9.3 diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml index 5ac0fb12..eefc4110 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/pom.xml index 64cab6bf..82276a4a 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml index 8029ceae..4cfbb2ea 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml index 5aaf237a..fa23bbde 100644 --- a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/pom.xml index b1c85785..707956ed 100644 --- a/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml index b87eeab6..68c83ae1 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml index d2c23472..c79ac863 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/tracer-all/pom.xml b/tracer-all/pom.xml index 9bad180f..0c5660f8 100644 --- a/tracer-all/pom.xml +++ b/tracer-all/pom.xml @@ -5,12 +5,12 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 tracer-all - 3.0.5 + 3.0.6-SNAPSHOT jar SOFATracer in one without SOFABoot starter diff --git a/tracer-core/pom.xml b/tracer-core/pom.xml index 26c74aa1..91e71ddc 100644 --- a/tracer-core/pom.xml +++ b/tracer-core/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../pom.xml diff --git a/tracer-extensions/pom.xml b/tracer-extensions/pom.xml index a2ad2696..8a99e3e7 100644 --- a/tracer-extensions/pom.xml +++ b/tracer-extensions/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT tracer-extensions diff --git a/tracer-samples/pom.xml b/tracer-samples/pom.xml index 72e76ca2..8eb4c30e 100644 --- a/tracer-samples/pom.xml +++ b/tracer-samples/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa tracer-all-parent - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-dubbo/pom.xml b/tracer-samples/tracer-sample-with-dubbo/pom.xml index 122eac9b..81880a51 100644 --- a/tracer-samples/tracer-sample-with-dubbo/pom.xml +++ b/tracer-samples/tracer-sample-with-dubbo/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-consumer/pom.xml b/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-consumer/pom.xml index 4bfa7e7b..38e95391 100644 --- a/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-consumer/pom.xml +++ b/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-consumer/pom.xml @@ -5,7 +5,7 @@ tracer-sample-with-dubbo com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 @@ -41,7 +41,7 @@ com.alipay.sofa tracer-sample-with-dubbo-facade - 3.0.5 + 3.0.6-SNAPSHOT diff --git a/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-facade/pom.xml b/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-facade/pom.xml index 97da0be6..cf0899bf 100644 --- a/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-facade/pom.xml +++ b/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-facade/pom.xml @@ -5,7 +5,7 @@ tracer-sample-with-dubbo com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-provider/pom.xml b/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-provider/pom.xml index a2f8615a..2dc5169d 100644 --- a/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-provider/pom.xml +++ b/tracer-samples/tracer-sample-with-dubbo/tracer-sample-with-dubbo-provider/pom.xml @@ -5,7 +5,7 @@ tracer-sample-with-dubbo com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 @@ -37,7 +37,7 @@ com.alipay.sofa tracer-sample-with-dubbo-facade - 3.0.5 + 3.0.6-SNAPSHOT diff --git a/tracer-samples/tracer-sample-with-h2/pom.xml b/tracer-samples/tracer-sample-with-h2/pom.xml index b5a7851d..63bc0b81 100644 --- a/tracer-samples/tracer-sample-with-h2/pom.xml +++ b/tracer-samples/tracer-sample-with-h2/pom.xml @@ -5,7 +5,7 @@ sofa-tracer-samples com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-httpclient/pom.xml b/tracer-samples/tracer-sample-with-httpclient/pom.xml index ea89cea0..be93cf56 100644 --- a/tracer-samples/tracer-sample-with-httpclient/pom.xml +++ b/tracer-samples/tracer-sample-with-httpclient/pom.xml @@ -5,7 +5,7 @@ sofa-tracer-samples com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-openfeign/pom.xml b/tracer-samples/tracer-sample-with-openfeign/pom.xml index d04fd47f..95d5a644 100644 --- a/tracer-samples/tracer-sample-with-openfeign/pom.xml +++ b/tracer-samples/tracer-sample-with-openfeign/pom.xml @@ -5,7 +5,7 @@ sofa-tracer-samples com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-openfeign/tracer-sample-with-openfeign-consumer/pom.xml b/tracer-samples/tracer-sample-with-openfeign/tracer-sample-with-openfeign-consumer/pom.xml index 54beedfe..3e1d9352 100644 --- a/tracer-samples/tracer-sample-with-openfeign/tracer-sample-with-openfeign-consumer/pom.xml +++ b/tracer-samples/tracer-sample-with-openfeign/tracer-sample-with-openfeign-consumer/pom.xml @@ -5,7 +5,7 @@ tracer-sample-with-openfeign com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-openfeign/tracer-sample-with-openfeign-provider/pom.xml b/tracer-samples/tracer-sample-with-openfeign/tracer-sample-with-openfeign-provider/pom.xml index 00d62999..afb94565 100644 --- a/tracer-samples/tracer-sample-with-openfeign/tracer-sample-with-openfeign-provider/pom.xml +++ b/tracer-samples/tracer-sample-with-openfeign/tracer-sample-with-openfeign-provider/pom.xml @@ -5,7 +5,7 @@ tracer-sample-with-openfeign com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-sampler/pom.xml b/tracer-samples/tracer-sample-with-sampler/pom.xml index eb728d19..640efbf4 100644 --- a/tracer-samples/tracer-sample-with-sampler/pom.xml +++ b/tracer-samples/tracer-sample-with-sampler/pom.xml @@ -4,7 +4,7 @@ sofa-tracer-samples com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-slf4j/pom.xml b/tracer-samples/tracer-sample-with-slf4j/pom.xml index 5946cf0c..1cf34ef3 100644 --- a/tracer-samples/tracer-sample-with-slf4j/pom.xml +++ b/tracer-samples/tracer-sample-with-slf4j/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa sofa-tracer-samples - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-sofarpc/pom.xml b/tracer-samples/tracer-sample-with-sofarpc/pom.xml index 09481082..e8158fc6 100644 --- a/tracer-samples/tracer-sample-with-sofarpc/pom.xml +++ b/tracer-samples/tracer-sample-with-sofarpc/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa sofa-tracer-samples - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-springmvc/pom.xml b/tracer-samples/tracer-sample-with-springmvc/pom.xml index 57ed61ae..c10fe4c2 100644 --- a/tracer-samples/tracer-sample-with-springmvc/pom.xml +++ b/tracer-samples/tracer-sample-with-springmvc/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa sofa-tracer-samples - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-samples/tracer-sample-with-zipkin/pom.xml b/tracer-samples/tracer-sample-with-zipkin/pom.xml index 0a3b63f0..6fe600dd 100644 --- a/tracer-samples/tracer-sample-with-zipkin/pom.xml +++ b/tracer-samples/tracer-sample-with-zipkin/pom.xml @@ -5,7 +5,7 @@ com.alipay.sofa sofa-tracer-samples - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 diff --git a/tracer-sofa-boot-plugin/pom.xml b/tracer-sofa-boot-plugin/pom.xml index ad37cad3..2bb0bcff 100644 --- a/tracer-sofa-boot-plugin/pom.xml +++ b/tracer-sofa-boot-plugin/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT 4.0.0 tracer-sofa-boot-plugin diff --git a/tracer-sofa-boot-starter/pom.xml b/tracer-sofa-boot-starter/pom.xml index 6ff423d1..75a7e6fb 100644 --- a/tracer-sofa-boot-starter/pom.xml +++ b/tracer-sofa-boot-starter/pom.xml @@ -5,7 +5,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../pom.xml diff --git a/tracer-test/core-test/pom.xml b/tracer-test/core-test/pom.xml index 30dbe3b0..043b2f18 100644 --- a/tracer-test/core-test/pom.xml +++ b/tracer-test/core-test/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml diff --git a/tracer-test/log4j-test/pom.xml b/tracer-test/log4j-test/pom.xml index ddf9756d..f7b3d3b7 100644 --- a/tracer-test/log4j-test/pom.xml +++ b/tracer-test/log4j-test/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml @@ -15,7 +15,7 @@ com.alipay.sofa tracer-extensions - 3.0.5 + 3.0.6-SNAPSHOT diff --git a/tracer-test/log4j2-test/pom.xml b/tracer-test/log4j2-test/pom.xml index bbbdadc9..90d6e27d 100644 --- a/tracer-test/log4j2-test/pom.xml +++ b/tracer-test/log4j2-test/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml diff --git a/tracer-test/logback-test/pom.xml b/tracer-test/logback-test/pom.xml index d0624bbf..daf5fcfa 100644 --- a/tracer-test/logback-test/pom.xml +++ b/tracer-test/logback-test/pom.xml @@ -4,7 +4,7 @@ tracer-all-parent com.alipay.sofa - 3.0.5 + 3.0.6-SNAPSHOT ../../pom.xml From 4ab7e4d0ee6eb77d3592462ee8c91cac246307ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Thu, 1 Aug 2019 16:01:02 +0800 Subject: [PATCH 20/24] cheery pick clean code and use en comment --- .../alipay/common/tracer/core/SofaTracer.java | 76 ++++----- .../tracer/core/appender/TraceAppender.java | 17 +- .../core/appender/TracerLogRootDaemon.java | 18 ++- .../appender/builder/JsonStringBuilder.java | 4 +- .../core/appender/builder/XStringBuilder.java | 100 ++++++------ .../core/appender/encoder/SpanEncoder.java | 14 +- .../file/AbstractRollingFileAppender.java | 27 ++-- .../appender/file/CompositeTraceAppender.java | 17 +- .../appender/file/LoadTestAwareAppender.java | 4 +- .../file/TimedRollingFileAppender.java | 91 +++++------ .../manager/AsyncCommonAppenderManager.java | 12 +- .../AsyncCommonDigestAppenderManager.java | 3 +- .../manager/ConsumerExceptionHandler.java | 2 +- .../manager/ConsumerThreadFactory.java | 2 +- .../manager/SofaTracerSpanEventFactory.java | 2 +- .../StringConsumerExceptionHandler.java | 4 +- .../core/appender/manager/StringEvent.java | 2 +- .../appender/manager/StringEventFactory.java | 2 +- .../tracer/core/appender/self/SelfLog.java | 25 ++- .../appender/self/SynchronizingSelfLog.java | 29 ++-- .../core/appender/self/TracerDaemon.java | 13 +- .../tracer/core/async/SofaTracerCallable.java | 3 +- .../tracer/core/async/SofaTracerRunnable.java | 3 +- .../async/TracerScheduleExecutorService.java | 5 +- .../SofaTracerConfiguration.java | 104 +++++++------ .../SofaTracerExternalConfiguration.java | 14 +- .../core/constants/SofaTracerConstant.java | 30 ++-- .../context/span/SofaTracerSpanContext.java | 118 +++++++------- .../core/context/trace/SofaTraceContext.java | 6 +- .../EmptyTracerStateStringException.java | 2 +- .../SamplingStrategyErrorException.java | 4 +- .../exception/SofaTracerRuntimeException.java | 1 + .../exception/UnsupportedFormatException.java | 4 +- .../tracer/core/extensions/SpanExtension.java | 19 ++- .../core/extensions/SpanExtensionFactory.java | 2 +- .../core/holder/SofaTraceContextHolder.java | 4 +- .../core/listener/SpanReportListener.java | 7 +- .../parent/AbstractDigestSpanEncoder.java | 15 +- .../tracer/core/mock/MockSofaTracer.java | 6 +- .../registry/AbstractTextB3Formatter.java | 6 +- .../core/registry/AbstractTextFormatter.java | 20 +-- .../tracer/core/registry/BinaryFormater.java | 19 ++- .../registry/RegistryExtractorInjector.java | 25 +-- .../reporter/common/CommonSpanEncoder.java | 9 +- .../reporter/common/CommonTracerManager.java | 39 +++-- .../reporter/digest/AbstractDiskReporter.java | 52 +++---- .../reporter/digest/DiskReporterImpl.java | 44 +++--- .../SofaTracerDigestReporterAsyncManager.java | 9 +- .../reporter/facade/AbstractReporter.java | 22 +-- .../tracer/core/reporter/facade/Reporter.java | 22 +-- .../AbstractSofaTracerStatisticReporter.java | 96 ++++++------ .../stat/SofaTracerStatisticReporter.java | 46 +++--- ...cerStatisticReporterCycleTimesManager.java | 15 +- .../SofaTracerStatisticReporterManager.java | 61 ++++---- .../core/reporter/stat/model/StatKey.java | 8 +- .../core/reporter/stat/model/StatMapKey.java | 2 +- .../core/reporter/stat/model/StatValues.java | 56 ++++--- .../reporter/type/TracerSystemLogEnum.java | 25 +-- .../common/tracer/core/samplers/Sampler.java | 5 + .../tracer/core/samplers/SamplingStatus.java | 4 +- .../SofaTracerPercentageBasedSampler.java | 6 +- .../tracer/core/span/CommonLogSpan.java | 27 ++-- .../common/tracer/core/span/LogData.java | 4 +- .../tracer/core/span/SofaTracerSpan.java | 145 ++++++++---------- .../SofaTracerSpanReferenceRelationship.java | 4 +- .../common/tracer/core/tags/SpanTags.java | 4 +- .../tracer/core/tracer/AbstractTracer.java | 6 +- .../tracer/core/utils/ByteArrayUtils.java | 124 ++------------- .../common/tracer/core/utils/CommonUtils.java | 20 ++- .../tracer/core/utils/ReflectionUtils.java | 3 - .../common/tracer/core/utils/StringUtils.java | 85 +++++----- .../common/tracer/core/utils/TracerUtils.java | 40 +++-- .../alipay/common/tracer/core/TestUtil.java | 3 - .../tracer/core/appender/LogCleanupTest.java | 64 ++++---- .../appender/TracerLogRootDaemonTest.java | 2 +- .../builder/JsonStringBuilderTest.java | 2 +- .../appender/builder/XStringBuilderTest.java | 10 +- .../file/TimedRollingFileAppenderTest.java | 7 +- .../core/appender/info/StaticInfoLogTest.java | 6 +- .../ConcurrentConsumerCorrectTest.java | 94 +++++------- .../manager/ConcurrentDiscardTest.java | 78 +++++----- .../appender/manager/ManagerTestUtil.java | 18 +-- .../core/appender/self/SelfLogTest.java | 2 +- .../core/async/SofaTracerCallableTest.java | 3 +- .../core/async/SofaTracerRunnableTest.java | 2 +- .../core/async/TracedExecutorServiceTest.java | 2 +- .../TracerScheduleExecutorServiceTest.java | 9 +- .../tracer/core/base/AbstractTestBase.java | 23 +-- .../tracer/core/benchmark/CountBenchmark.java | 4 +- .../SofaTracerConfigurationTest.java | 2 +- .../span/SofaTracerSpanContextTest.java | 2 +- ...SofaTracerThreadLocalTraceContextTest.java | 2 +- .../holder/SofaTraceContextHolderTest.java | 2 +- .../SpanReportListenerHolderTest.java | 2 +- .../tracer/core/mock/MockSofaTracerTest.java | 2 +- .../core/registry/BinaryFormaterTest.java | 23 ++- .../registry/HttpHeadersB3FormatterTest.java | 2 +- .../registry/HttpHeadersFormatterTest.java | 9 +- .../core/registry/TextMapB3FormatterTest.java | 2 +- .../core/registry/TextMapFormatterTest.java | 4 +- .../registry/TracerFormatRegistryTest.java | 4 +- ...tatisticReporterCycleTimesManagerTest.java | 2 +- .../common/CommonSpanEncoderTest.java | 19 ++- .../common/CommonTracerManagerTest.java | 7 +- ...TracerCompositeDigestReporterImplTest.java | 2 +- .../reporter/digest/DiskReporterImplTest.java | 5 +- ...aTracerDigestReporterAsyncManagerTest.java | 4 +- .../SofaTracerStatisticReporterImplTest.java | 18 +-- .../reporter/stat/model/StatMapKeyTest.java | 12 +- .../tracer/core/span/SofaTracerSpanTest.java | 2 +- .../core/tracertest/SofaTracerTest.java | 22 +-- .../tracertest/type/TracerTestLogEnum.java | 16 +- .../tracer/core/utils/StringUtilsTest.java | 2 +- .../tracer/core/utils/TracerUtilsTest.java | 43 +++--- 114 files changed, 1104 insertions(+), 1299 deletions(-) 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 213f9c91..a44aa197 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 @@ -49,32 +49,32 @@ public class SofaTracer implements Tracer { /** - * 正常 TRACE 开始的 spanId + * normal root spanId's default value */ public static final String ROOT_SPAN_ID = "0"; - /*** - * 标示 tracer 的类型 + /** + * Mark the type of tracer */ private final String tracerType; - /*** - * 作为客户端运行时的 Reporter + /** + * Reporter as a client runtime */ private final Reporter clientReporter; - /*** - * 作为服务端运行时的 Reporter + /** + * Reporter as a server runtime */ private final Reporter serverReporter; - /*** - * 这个 tracerTags 主要用于缓存和 tracer 全局相关的一些信息 + /** + * Cache some information related to the tracer globally */ - private final Map tracerTags = new ConcurrentHashMap(); + private final Map tracerTags = new ConcurrentHashMap<>(); /** - * 支持 sampler 即根据 rate 采样(主要在入口起作用) + * Sampler instance */ private final Sampler sampler; @@ -123,19 +123,16 @@ public void reportSpan(SofaTracerSpan span) { } //invoke listener this.invokeReportListeners(span); - //客户端、服务端 if (span.isClient()) { - //摘要 if (this.clientReporter != null) { this.clientReporter.report(span); } } else if (span.isServer()) { - //摘要 if (this.serverReporter != null) { this.serverReporter.report(span); } } else { - //ignore 不统计 + //ignore ,do not statical SelfLog.warn("Span reported neither client nor server.Ignore!"); } } @@ -191,25 +188,25 @@ private void invokeReportListeners(SofaTracerSpan sofaTracerSpan) { } } - /*** - * SofaTracerSpanBuilder 用于在 Tracer 内部构建 Span + /** + * SofaTracerSpanBuilder is used to build Span inside Tracer */ public class SofaTracerSpanBuilder implements io.opentracing.Tracer.SpanBuilder { - private String operationName = StringUtils.EMPTY_STRING; + private String operationName; - /*** - * 默认初始化时间 + /** + * Default initialization time */ - private long startTime = -1; + private long startTime = -1; /** * In 99% situations there is only one parent (childOf), so we do not want to allocate * a collection of references. */ - private List references = Collections.emptyList(); + private List references = Collections.emptyList(); - private final Map tags = new HashMap(); + private final Map tags = new HashMap(); public SofaTracerSpanBuilder(String operationName) { this.operationName = operationName; @@ -246,8 +243,8 @@ public Tracer.SpanBuilder addReference(String referenceType, SpanContext referen (SofaTracerSpanContext) referencedContext, referenceType)); } else { if (references.size() == 1) { - //要保证有顺序 - references = new ArrayList(references); + //To ensure order + references = new ArrayList<>(references); } references.add(new SofaTracerSpanReferenceRelationship( (SofaTracerSpanContext) referencedContext, referenceType)); @@ -283,10 +280,10 @@ public Tracer.SpanBuilder withStartTimestamp(long microseconds) { public Span start() { SofaTracerSpanContext sofaTracerSpanContext = null; if (this.references != null && this.references.size() > 0) { - //存在父上下文 + //Parent context exist sofaTracerSpanContext = this.createChildContext(); } else { - //从新开始新的节点 + //Start with new root span context sofaTracerSpanContext = this.createRootSpanContext(); } @@ -311,7 +308,7 @@ private boolean calculateSampler(SofaTracerSpan sofaTracerSpan) { SamplingStatus samplingStatus = sampler.sample(sofaTracerSpan); if (samplingStatus.isSampled()) { isSampled = true; - //发生采样后,将相关属性记录 + //After the sampling occurs, the related attribute records this.tags.putAll(samplingStatus.getTags()); } } @@ -321,7 +318,7 @@ private boolean calculateSampler(SofaTracerSpan sofaTracerSpan) { } private SofaTracerSpanContext createRootSpanContext() { - //生成 traceId + //generate traceId String traceId = TraceIdGenerator.generate(); return new SofaTracerSpanContext(traceId, ROOT_SPAN_ID, StringUtils.EMPTY_STRING); } @@ -383,14 +380,8 @@ public static final class Builder { private final String tracerType; - /*** - * 作为客户端运行时的 Reporter - */ private Reporter clientReporter; - /*** - * 作为服务端运行时的 Reporter - */ private Reporter serverReporter; private Map tracerTags = new HashMap(); @@ -402,31 +393,16 @@ public Builder(String tracerType) { this.tracerType = tracerType; } - /*** - * 客户端日志功能 - * @param clientReporter 日志功能,落地到磁盘或者上报 zipkin - * @return Builder - */ public Builder withClientReporter(Reporter clientReporter) { this.clientReporter = clientReporter; return this; } - /*** - * 服务端日志功能 - * @param serverReporter 日志功能,落地到磁盘或者上报 zipkin - * @return Builder - */ public Builder withServerReporter(Reporter serverReporter) { this.serverReporter = serverReporter; return this; } - /*** - * 采样器入口 span 生效 - * @param sampler 采样器 - * @return Builder - */ public Builder withSampler(Sampler sampler) { this.sampler = sampler; return this; diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/TraceAppender.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/TraceAppender.java index ad82605d..9810b11a 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/TraceAppender.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/TraceAppender.java @@ -23,22 +23,23 @@ */ public interface TraceAppender { - /*** - * 刷新数据 + /** + * flush data * - * @throws IOException 操作异常 + * @throws IOException */ void flush() throws IOException; - /*** - * 添加要被输出的 log 文件 - * @param log 字符串 - * @throws IOException 操作异常 + /** + * Add the log file to be output + * + * @param log + * @throws IOException */ void append(String log) throws IOException; /** - * 清理日志 + * clean log */ void cleanup(); } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/TracerLogRootDaemon.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/TracerLogRootDaemon.java index d07bb598..80be8b77 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/TracerLogRootDaemon.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/TracerLogRootDaemon.java @@ -27,25 +27,29 @@ /** * TracerLogRootDaemon * - * 不从配置项目获取,直接从系统属性获取 + * Not obtained from the configuration project, obtained directly from the system properties * * @author yangguanchao * @since 2017/06/25 */ public class TracerLogRootDaemon { - /*** - * 是否添加 pid 到 log path + /** + * Whether to add pid to log path */ public static final String TRACER_APPEND_PID_TO_LOG_PATH_KEY = "tracer_append_pid_to_log_path"; - /*** - * 日志目录 + /** + * Log directory */ public static String LOG_FILE_DIR; /** - * 该编码由LANG或者-Dfile.encoding决定,因此如系统根据系统编码来决定日志编码, 请确保应用的启动脚本或者启动参数中不覆盖LANG或者-Dfile.encoding的参数。 一般来说国内的系统创建模板里,deploy/bin/templates/jbossctl.sh里有 - * LANG=zh_CN.GB18030,这样无论环境变量里LANG设置成何值,启动时都会被覆盖 + * The encoding is determined by LANG or -Dfile.encoding, + * so if the system determines the log encoding based on the system encoding, + * make sure that the application's startup script or startup parameters do not override the LANG or -Dfile.encoding parameters. + * Generally speaking, in the domestic system creation template, + * there is LANG=zh_CN.GB18030 in deploy/bin/templates/jbossctl.sh, + * so no matter what value LANG is set in the environment variable, it will be overwritten at startup. */ static public final Charset DEFAULT_CHARSET = Charset.defaultCharset(); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/builder/JsonStringBuilder.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/builder/JsonStringBuilder.java index 10c17685..bd4fbe1f 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/builder/JsonStringBuilder.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/builder/JsonStringBuilder.java @@ -21,8 +21,8 @@ /** * JsonStringBuilder *

- * 方便日志输出的字符串拼接工具 - * + * String splicing tool for convenient log output + *

* @author yangguanchao * @since 2018/05/14 */ diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/builder/XStringBuilder.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/builder/XStringBuilder.java index 4b149288..0c05c380 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/builder/XStringBuilder.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/builder/XStringBuilder.java @@ -23,16 +23,16 @@ /** * XStringBuilder *

- * 方便日志输出的字符串拼接工具 - * + * String splicing tool for convenient log output + *

* @author yangguanchao * @since 2017/06/25 */ public class XStringBuilder { - static public final int DEFAULT_BUFFER_SIZE = 256; - static public final char DEFAULT_SEPARATOR = ','; - static public final String DEFAULT_SEPARATOR_ESCAPE = "%2C"; + public static final int DEFAULT_BUFFER_SIZE = 256; + public static final char DEFAULT_SEPARATOR = ','; + public static final String DEFAULT_SEPARATOR_ESCAPE = "%2C"; public static final String AND_SEPARATOR = "&"; public static final String AND_SEPARATOR_ESCAPE = "%26"; public static final String EQUAL_SEPARATOR = "="; @@ -40,9 +40,9 @@ public class XStringBuilder { public static final String PERCENT = "%"; public static final String PERCENT_ESCAPE = "%25"; - static private char separator = DEFAULT_SEPARATOR; - static private String separatorStr = separator + ""; - static private String spearatorEscape = DEFAULT_SEPARATOR_ESCAPE; + private static char separator = DEFAULT_SEPARATOR; + private static String separatorStr = separator + ""; + private static String spearatorEscape = DEFAULT_SEPARATOR_ESCAPE; private StringBuilder sb; public XStringBuilder() { @@ -59,8 +59,8 @@ public XStringBuilder(int size, char separator) { } /** - * @param str 输入字符串 - * @return 当前实例 + * @param str Input string + * @return this */ public XStringBuilder append(String str) { sb.append(str == null ? StringUtils.EMPTY_STRING : str).append(separator); @@ -68,8 +68,8 @@ public XStringBuilder append(String str) { } /** - * @param str 输入字符串 - * @return 当前实例 + * @param str Input string + * @return this */ public XStringBuilder append(long str) { sb.append(str).append(separator); @@ -77,9 +77,9 @@ public XStringBuilder append(long str) { } /** - * @param str 输入字符串 - * @param separator 分隔符 - * @return 当前实例 + * @param str Input string + * @param separator + * @return this */ public XStringBuilder append(long str, String separator) { sb.append(str).append(separator); @@ -87,9 +87,9 @@ public XStringBuilder append(long str, String separator) { } /** - * @param str 输入字符串 - * @param separator 分隔符 - * @return 当前实例 + * @param str Input string + * @param separator + * @return this */ public XStringBuilder append(long str, char separator) { sb.append(str).append(separator); @@ -97,9 +97,9 @@ public XStringBuilder append(long str, char separator) { } /** - * @param str 输入字符串 - * @param separator 分隔符 - * @return 当前实例 + * @param str Input string + * @param separator + * @return this */ public XStringBuilder append(String str, String separator) { sb.append(str == null ? StringUtils.EMPTY_STRING : str).append(separator); @@ -107,8 +107,8 @@ public XStringBuilder append(String str, String separator) { } /** - * @param str 输入字符串 - * @return 当前实例 + * @param str Input string + * @return this */ public XStringBuilder append(int str) { sb.append(str).append(separator); @@ -116,8 +116,8 @@ public XStringBuilder append(int str) { } /** - * @param str 输入字符串 - * @return 当前实例 + * @param str Input string + * @return this */ public XStringBuilder append(char str) { sb.append(str).append(separator); @@ -125,8 +125,8 @@ public XStringBuilder append(char str) { } /** - * @param map 要添加的 map - * @return 当前实例 + * @param map map param + * @return this */ public XStringBuilder append(Map map) { this.appendEscape(StringUtils.mapToString(map)); @@ -134,8 +134,8 @@ public XStringBuilder append(Map map) { } /** - * @param str 输入的字符串 - * @return 当前实例 + * @param str Input string + * @return this */ public XStringBuilder appendEnd(int str) { sb.append(str).append(StringUtils.NEWLINE); @@ -143,8 +143,8 @@ public XStringBuilder appendEnd(int str) { } /** - * @param str 输入的字符串 - * @return 当前实例 + * @param str Input string + * @return this */ public XStringBuilder appendEnd(String str) { sb.append(str == null ? StringUtils.EMPTY_STRING : str).append(StringUtils.NEWLINE); @@ -152,8 +152,8 @@ public XStringBuilder appendEnd(String str) { } /** - * @param str 输入信息 - * @return 当前实例 + * @param str Input string + * @return this */ public XStringBuilder appendEnd(long str) { sb.append(str).append(StringUtils.NEWLINE); @@ -161,8 +161,8 @@ public XStringBuilder appendEnd(long str) { } /** - * @param c 输入字符 - * @return 当前实例 + * @param c Input char + * @return this */ public XStringBuilder appendEnd(char c) { sb.append(String.valueOf(c)).append(StringUtils.NEWLINE); @@ -170,8 +170,8 @@ public XStringBuilder appendEnd(char c) { } /** - * @param map 输入 map - * @return 当前实例 + * @param map map param + * @return this */ public XStringBuilder appendEnd(Map map) { this.appendEscapeEnd(StringUtils.mapToString(map)); @@ -179,8 +179,8 @@ public XStringBuilder appendEnd(Map map) { } /** - * @param str 输入字符串 - * @return 当前实例 + * @param str Input string + * @return this */ public XStringBuilder appendRaw(String str) { sb.append(str == null ? StringUtils.EMPTY_STRING : str); @@ -188,9 +188,9 @@ public XStringBuilder appendRaw(String str) { } /** - * 将字符串中分隔符变成对应转义字符 - * @param str 输入字符串 - * @return 当前实例 + * Change the separator in the string to the corresponding escape character + * @param str Input string + * @return this */ public XStringBuilder appendEscape(String str) { str = (str == null) ? StringUtils.EMPTY_STRING : str; @@ -199,9 +199,9 @@ public XStringBuilder appendEscape(String str) { } /** - * 将字符串中分隔符变成对应转义字符 - * @param str 输入字符串 - * @return 当前实例 + * Change the separator in the string to the corresponding escape character on raw + * @param str Input string + * @return this */ public XStringBuilder appendEscapeRaw(String str) { str = (str == null) ? StringUtils.EMPTY_STRING : str; @@ -210,9 +210,9 @@ public XStringBuilder appendEscapeRaw(String str) { } /** - * 将字符串中分隔符变成对应转义字符 - * @param str 输入字符串 - * @return 当前实例 + * Change the separator in the string to the corresponding escape character at the end + * @param str Input string + * @return this */ public XStringBuilder appendEscapeEnd(String str) { str = (str == null) ? StringUtils.EMPTY_STRING : str; @@ -221,7 +221,7 @@ public XStringBuilder appendEscapeEnd(String str) { } /** - * @return 当前实例 + * @return this */ public XStringBuilder reset() { sb.delete(0, sb.length()); @@ -229,7 +229,7 @@ public XStringBuilder reset() { } /** - * @return 当前实例 + * @return this */ @Override public String toString() { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/encoder/SpanEncoder.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/encoder/SpanEncoder.java index 2a00ac11..e23efebc 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/encoder/SpanEncoder.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/encoder/SpanEncoder.java @@ -23,19 +23,19 @@ /** * SpanEncoder *

- * Tracer 日志格式编码,为针对异步队列调用做优化,不允许多线程并发调用 - * + * Tracer Span log encoder, optimized for asynchronous queue calls, does not allow multi-threaded concurrent calls + *

* @author yangguanchao * @since 2017/06/25 */ public interface SpanEncoder { - /*** - * 对 span 按照自定义的规则分隔字段,并准备输出到文件中 + /** + * Separate fields according to custom rules and prepare to output to file * - * @param span 要被格式化输出的上下文 - * @throws IOException 文件输出异常 - * @return 返回格式化输出的字符串 + * @param span current span + * @throws IOException + * @return formatted output string */ String encode(T span) throws IOException; } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/AbstractRollingFileAppender.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/AbstractRollingFileAppender.java index 2addacfb..361fed3b 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/AbstractRollingFileAppender.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/AbstractRollingFileAppender.java @@ -33,17 +33,17 @@ public abstract class AbstractRollingFileAppender implements TraceAppender { /** - * 日志刷新间隔,buffer 时间超过间隔,则把缓存的日志数据刷新出去 + * The log refresh interval, when the buffer time exceeds the interval, the cached log data is refreshed. */ private static final long LOG_FLUSH_INTERVAL = TimeUnit.SECONDS.toMillis(1); /** - * 默认输出缓冲大小 + * Default output buffer size 8KB */ - public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; // 8KB + public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; private static final long IOEXCEPTION_PRINT_INTERVAL = 60 * 1000; /** - * 日志缓存大小 + * Log cache buffer size */ private final int bufferSize; @@ -96,6 +96,7 @@ protected void setFile(boolean append) { } } + @Override public void append(String log) throws IOException { if (bos != null) { waitUntilRollFinish(); @@ -107,29 +108,30 @@ public void append(String log) throws IOException { isRolling.set(false); } } else { - // 超过指定刷新时间没刷新,就刷新一次 + // Refreshed after the specified refresh time has not been refreshed long now; if ((now = System.currentTimeMillis()) >= nextFlushTime) { flush(); nextFlushTime = now + LOG_FLUSH_INTERVAL; } } - // 无论有没有做 RollOver,都需要将输入往 bos 中写入 + // Whether you have RollOver or not, you need to write the input to bos byte[] bytes = log.getBytes(TracerLogRootDaemon.DEFAULT_CHARSET); write(bytes); } } /** - * 是否现在马上进行滚动 - * - * @return true: 是 + * Whether to scroll right now + * @return true */ protected abstract boolean shouldRollOverNow(); /** - * 进行 RollOver - * WARNING:RollOver 的时候日志不要用 SelfLog 打印,因为这个时候可能 SelfLog 自己在 RollOver。 + * Ready to RollOver + * + * WARNING:Do not use SelfLog when logging RollOver, + * because this time it is possible that SelfLog is in RollOver itself. */ protected abstract void rollOver(); @@ -146,8 +148,9 @@ private void write(byte[] bytes) { } /** - * 超过指定刷新时间没刷新,就刷新一次 + * Refreshed after the specified refresh time has not been refreshed */ + @Override public void flush() { if (bos != null) { try { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/CompositeTraceAppender.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/CompositeTraceAppender.java index 0ac016ba..6368cb1f 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/CompositeTraceAppender.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/CompositeTraceAppender.java @@ -33,23 +33,26 @@ public class CompositeTraceAppender implements TraceAppender { private Map traceAppenders = new ConcurrentHashMap(); /** - * @param logName 日志名 - * @return 输出实例 + * getAppender by logName + * @param logName logName + * @return traceAppender */ public TraceAppender getAppender(String logName) { return traceAppenders.get(logName); } /** - * @param logName 日志名 - * @param traceAppender 输出实例 + * putAppender + * @param logName logName + * @param traceAppender traceAppender */ public void putAppender(String logName, TraceAppender traceAppender) { traceAppenders.put(logName, traceAppender); } /** - * @throws IOException 异常 + * Traverse traceAppenders, callback flush method in turn + * @throws IOException */ @Override public void flush() throws IOException { @@ -59,8 +62,8 @@ public void flush() throws IOException { } /** - * @param log 内容 - * @throws IOException 异常 + * @param log + * @throws IOException */ @Override public void append(String log) throws IOException { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/LoadTestAwareAppender.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/LoadTestAwareAppender.java index 609d57bd..146e3e75 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/LoadTestAwareAppender.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/LoadTestAwareAppender.java @@ -29,9 +29,9 @@ */ public final class LoadTestAwareAppender implements TraceAppender { - // 非压测数据的 TraceAppender + /** TraceAppender for non-pressure */ private TraceAppender nonLoadTestTraceAppender; - // 压测数据的 TraceAppender + /** TraceAppender for pressure*/ private TraceAppender loadTestTraceAppender; private LoadTestAwareAppender(TraceAppender nonLoadTestTraceAppender, diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/TimedRollingFileAppender.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/TimedRollingFileAppender.java index b8a87c12..869a5476 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/TimedRollingFileAppender.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/file/TimedRollingFileAppender.java @@ -24,22 +24,26 @@ import com.alipay.common.tracer.core.utils.TracerUtils; import java.io.File; -import java.io.FilenameFilter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** - * 基于时间的 RollingFileAppender + * RollingFileAppender based on Time * * @author khotyn 4/8/14 2:56 PM */ public class TimedRollingFileAppender extends AbstractRollingFileAppender { - // The code assumes that the following constants are in a increasing sequence. + /** + * The code assumes that the following constants are in a increasing sequence. + */ static final int TOP_OF_TROUBLE = -1; - static final int TOP_OF_SECONDS = 0; // 添加秒级的滚动主要是为了测试方便 + /** + * Adding seconds of scrolling is mainly for testing convenience + */ + static final int TOP_OF_SECONDS = 0; static final int TOP_OF_MINUTE = 1; static final int TOP_OF_HOUR = 2; static final int HALF_DAY = 3; @@ -54,47 +58,39 @@ public class TimedRollingFileAppender extends AbstractRollingFileAppender { private static final String DEFAULT_ROLLING_PATTERN = DAILY_ROLLING_PATTERN; /** - * 下次日志 RollOver 的时候,日志文件会被重命名成这个文件。 + * The next time you log RollOver, the log file will be renamed to this file. */ private String scheduledFilename; /** - * 预计下次 RollOver 发生的时间 + * Expect the time of the next RollOver */ private long nextCheck = System.currentTimeMillis() - 1; /** - * 备份的文件的后缀模式 + * Suffix mode of the backed up file */ private String datePattern; /** - * 日期格式化,主要用于格式化文件名用 + * Date formatting, mainly used to format file names */ private SimpleDateFormat sdf; private Date now = new Date(); /** - * 此 Calender 主要用于计算下一次 RollOver 发生的时间 + * This Calender is mainly used to calculate the time when the next RollOver occurs. */ private RollingCalendar rc = new RollingCalendar(); /** - * 日志的保留时间 + * Log retention time */ private LogReserveConfig logReserveConfig = new LogReserveConfig( SofaTracerConfiguration.DEFAULT_LOG_RESERVE_DAY, 0); - /** - * @param file 文件名 - * @param append 是否累加 - */ public TimedRollingFileAppender(String file, boolean append) { this(file, DEFAULT_BUFFER_SIZE, append, DEFAULT_ROLLING_PATTERN); } - /** - * @param file 文件 - * @param datePattern 日期格式 - */ public TimedRollingFileAppender(String file, String datePattern) { this(file, DEFAULT_BUFFER_SIZE, true, datePattern); } @@ -104,20 +100,15 @@ public TimedRollingFileAppender(String file, String datePattern, String logReser this.logReserveConfig = TracerUtils.parseLogReserveConfig(logReserveConfigString); } - /** - * @param file 文件 - * @param bufferSize 缓冲区大小 - * @param append 是否追加,默认是 - */ public TimedRollingFileAppender(String file, int bufferSize, boolean append) { this(file, bufferSize, append, DEFAULT_ROLLING_PATTERN); } /** - * @param file 文件 - * @param bufferSize 缓冲区大小 - * @param append 是否追加,默认是 - * @param datePatternParam 日期格式 + * @param file fileName + * @param bufferSize bufferSize + * @param append default is true + * @param datePatternParam date format */ public TimedRollingFileAppender(String file, int bufferSize, boolean append, String datePatternParam) { @@ -134,10 +125,10 @@ public TimedRollingFileAppender(String file, int bufferSize, boolean append, } /** - * 判断是否应该现在进行 RollOver - * - * @return true 现在进行 RollOver + * Determine if RollOver should be done now + * @return true:Now RollOver */ + @Override public boolean shouldRollOverNow() { long n = System.currentTimeMillis(); if (n >= nextCheck) { @@ -150,8 +141,9 @@ public boolean shouldRollOverNow() { } /** - * 清理日志 + * clean log */ + @Override public void cleanup() { try { File parentDirectory = logFile.getParentFile(); @@ -166,12 +158,8 @@ public void cleanup() { return; } - File[] logFiles = parentDirectory.listFiles(new FilenameFilter() { - - public boolean accept(File dir, String name) { - return StringUtils.isNotBlank(name) && name.startsWith(baseName); - } - }); + File[] logFiles = parentDirectory.listFiles((dir,name)-> + StringUtils.isNotBlank(name) && name.startsWith(baseName)); if (logFiles == null || logFiles.length == 0) { return; @@ -248,13 +236,11 @@ public boolean accept(File dir, String name) { } } - /** - * - */ + @Override public void rollOver() { - /* Compute filename, but only if datePattern is specified */ + // Compute filename, but only if datePattern is specified if (datePattern == null) { - SelfLog.error("没有设置文件滚动的后缀名模式"); + SelfLog.error("No Settings for file rolling suffix's model"); return; } @@ -269,7 +255,7 @@ public void rollOver() { try { bos.close(); } catch (IOException e) { - SelfLog.error("关闭输出流失败", e); + SelfLog.error("Failed to closing the output stream", e); } File target = new File(scheduledFilename); @@ -279,10 +265,9 @@ public void rollOver() { boolean result = logFile.renameTo(target); if (result) { - System.out.println(fileName + " -> " + scheduledFilename); + SelfLog.info(fileName + " -> " + scheduledFilename); } else { - System.err.println("Failed to rename [" + fileName + "] to [" + scheduledFilename - + "]."); + SelfLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "]."); } this.setFile(false); @@ -305,7 +290,8 @@ int computeCheckPeriod() { if (datePattern != null) { for (int i = TOP_OF_SECONDS; i <= TOP_OF_MONTH; i++) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern); - simpleDateFormat.setTimeZone(gmtTimeZone); // do all date formatting in GMT + // do all date formatting in GMT + simpleDateFormat.setTimeZone(gmtTimeZone); String r0 = simpleDateFormat.format(epoch); rollingCalendar.setType(i); Date next = new Date(rollingCalendar.getNextCheckMillis(epoch)); @@ -315,7 +301,8 @@ int computeCheckPeriod() { } } } - return TOP_OF_TROUBLE; // Deliberately head for trouble... + // Deliberately head for trouble... + return TOP_OF_TROUBLE; } } @@ -342,16 +329,16 @@ void setType(int type) { } /** - * @param now 日期 - * @return 下一个整数日期 + * @param now + * @return Next Date */ public long getNextCheckMillis(Date now) { return getNextCheckDate(now).getTime(); } /** - * @param now 当前 - * @return 下一个周期日周期 + * @param now + * @return Next cycle day */ public Date getNextCheckDate(Date now) { this.setTime(now); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/AsyncCommonAppenderManager.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/AsyncCommonAppenderManager.java index 37e51c63..f337fde8 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/AsyncCommonAppenderManager.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/AsyncCommonAppenderManager.java @@ -33,9 +33,9 @@ import java.util.concurrent.atomic.AtomicLong; /** - * SelfLog专用 + * For SelfLog * @author luoguimu123 - * @version $Id: AsyncCommonAppenderManager.java, v 0.1 2017年11月21日 下午6:15 luoguimu123 Exp $ + * @version $Id: AsyncCommonAppenderManager.java, v 0.1 November 21, 2017 6:15 PM luoguimu123 Exp $ */ public class AsyncCommonAppenderManager { @@ -47,7 +47,7 @@ public class AsyncCommonAppenderManager { private List consumers; - // SelfLog 专用,不用开启三个 Consumer + /** Dedicated for SelfLog, no need to open three Consumers */ private static final int DEFAULT_CONSUMER_NUMBER = 1; private boolean allowDiscard; @@ -160,15 +160,13 @@ private class Consumer implements EventHandler { @Override public void onEvent(StringEvent event, long sequence, boolean endOfBatch) throws Exception { - String string = event.getString(); - if (string != null) { try { appender.append(string); appender.flush(); } catch (Exception e) { - //todo 全局保留一个同步的log,用于在一些关键点同步打印日志 + //todo Globally keep a synchronized log for synchronizing print logs at some key points if (string != null) { SynchronizingSelfLog.error("fail to async write log", e); } else { @@ -184,7 +182,6 @@ public void onEvent(StringEvent event, long sequence, boolean endOfBatch) throws } class PaddedAtomicLong extends AtomicLong { - public volatile long p1, p2, p3, p4, p5, p6 = 7L; public PaddedAtomicLong(long initialValue) { @@ -194,5 +191,4 @@ public PaddedAtomicLong(long initialValue) { public PaddedAtomicLong() { } } - } \ No newline at end of file diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/AsyncCommonDigestAppenderManager.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/AsyncCommonDigestAppenderManager.java index 460208f8..7aaaa468 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/AsyncCommonDigestAppenderManager.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/AsyncCommonDigestAppenderManager.java @@ -44,7 +44,7 @@ /** * * @author liangen - * @version $Id: AsyncCommonDigestAppenderManager.java, v 0.1 2017年10月23日 上午9:47 liangen Exp $ + * @version $Id: AsyncCommonDigestAppenderManager.java, v 0.1 October 23, 2017 9:47 AM liangen Exp $ */ public class AsyncCommonDigestAppenderManager { private final Map appenders = new ConcurrentHashMap(); @@ -233,7 +233,6 @@ public void addLogType(String logType) { } class PaddedAtomicLong extends AtomicLong { - public volatile long p1, p2, p3, p4, p5, p6 = 7L; public PaddedAtomicLong(long initialValue) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/ConsumerExceptionHandler.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/ConsumerExceptionHandler.java index cb631ea1..2b554ea1 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/ConsumerExceptionHandler.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/ConsumerExceptionHandler.java @@ -23,7 +23,7 @@ /** * * @author liangen - * @version $Id: ConsumerExceptionHandler.java, v 0.1 2017年10月23日 上午10:13 liangen Exp $ + * @version $Id: ConsumerExceptionHandler.java, v 0.1 October 23, 2017 10:13 AM liangen Exp $ */ public class ConsumerExceptionHandler implements ExceptionHandler { @Override diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/ConsumerThreadFactory.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/ConsumerThreadFactory.java index 8249fad9..110052c4 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/ConsumerThreadFactory.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/ConsumerThreadFactory.java @@ -21,7 +21,7 @@ /** * * @author liangen - * @version $Id: ConsumerThreadFactory.java, v 0.1 2017年10月23日 上午10:09 liangen Exp $ + * @version $Id: ConsumerThreadFactory.java, v 0.1 October 23, 2017 10:09 AM liangen Exp $ */ public class ConsumerThreadFactory implements ThreadFactory { private String workName; diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/SofaTracerSpanEventFactory.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/SofaTracerSpanEventFactory.java index 6250b13c..85b5db9a 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/SofaTracerSpanEventFactory.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/SofaTracerSpanEventFactory.java @@ -21,7 +21,7 @@ /** * * @author liangen - * @version $Id: SofaTracerSpanEventFactory.java, v 0.1 2017年10月23日 上午10:07 liangen Exp $ + * @version $Id: SofaTracerSpanEventFactory.java, v 0.1 October 23, 2017 10:07 AM liangen Exp $ */ public class SofaTracerSpanEventFactory implements EventFactory { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringConsumerExceptionHandler.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringConsumerExceptionHandler.java index 192764db..2a31caf6 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringConsumerExceptionHandler.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringConsumerExceptionHandler.java @@ -22,12 +22,12 @@ /** * * @author luoguimu123 - * @version $Id: StringConsumerExceptionHandler.java, v 0.1 2017年11月21日 下午7:06 luoguimu123 Exp $ + * @version $Id: StringConsumerExceptionHandler.java, v 0.1 November 21, 2017 7:06 PM luoguimu123 Exp $ */ public class StringConsumerExceptionHandler implements ExceptionHandler { @Override public void handleEventException(Throwable ex, long sequence, StringEvent event) { - //循环调用 + //Loop call if (event != null) { SynchronizingSelfLog.error( "AsyncConsumer occurs exception during handle StringEvent, The string is[" diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringEvent.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringEvent.java index d47365b0..f5fb8b0f 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringEvent.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringEvent.java @@ -19,7 +19,7 @@ /** * * @author luoguimu123 - * @version $Id: StringEvent.java, v 0.1 2017年11月21日 下午7:01 luoguimu123 Exp $ + * @version $Id: StringEvent.java, v 0.1 November 21, 2017 7:01 PM luoguimu123 Exp $ */ public class StringEvent { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringEventFactory.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringEventFactory.java index 3f8dab85..67026f56 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringEventFactory.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/manager/StringEventFactory.java @@ -21,7 +21,7 @@ /** * * @author luoguimu123 - * @version $Id: StringEventFactory.java, v 0.1 2017年11月21日 下午7:00 luoguimu123 Exp $ + * @version $Id: StringEventFactory.java, v 0.1 November 21, 2017 7:00 PM luoguimu123 Exp $ */ public class StringEventFactory implements EventFactory { @Override diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SelfLog.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SelfLog.java index dc4d5a1c..592facc8 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SelfLog.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SelfLog.java @@ -24,8 +24,7 @@ import java.io.StringWriter; /** - * tracer自己的日志,仅供内部试用 - * + * Tracer's own log, for internal use only * @author yangyanzhao */ public class SelfLog { @@ -34,8 +33,8 @@ public class SelfLog { static private final String WARN_PREFIX = "[WARN] "; static private final String INFO_PREFIX = "[INFO] "; - /*** - * 日志文件名称 + /** + * Log file name */ static protected final String SELF_LOG_FILE = "tracer-self.log"; @@ -47,8 +46,8 @@ public class SelfLog { } /** - * @param log 日志内容 - * @param e 异常 + * @param log + * @param e */ public static void error(String log, Throwable e) { try { @@ -66,10 +65,10 @@ public static void error(String log, Throwable e) { } /** - * 打印错误日志,附加当前线程的 TraceId + * Print error log with current thread's TraceId * - * @param log 错误信息 - * @param e 异常 + * @param log + * @param e */ public static void errorWithTraceId(String log, Throwable e) { try { @@ -92,9 +91,9 @@ public static void error(String log) { } /** - * 打印错误日志,附加当前线程的 TraceId + * Print error log with current thread's TraceId * - * @param log 错误消息 + * @param log * @param traceId traceId */ public static void errorWithTraceId(String log, String traceId) { @@ -102,9 +101,9 @@ public static void errorWithTraceId(String log, String traceId) { } /** - * 打印错误日志,附加当前线程的 TraceId + * Print error log with current thread's TraceId * - * @param log 错误消息 + * @param log */ public static void errorWithTraceId(String log) { doLog(log, ERROR_PREFIX + "[" + TracerUtils.getTraceId() + "]"); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java index 662b2d9b..9b249b34 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/SynchronizingSelfLog.java @@ -26,9 +26,12 @@ import java.io.StringWriter; /** - * 同步打印的SelfLog,仅在中间件内部使用,解决SelfLog异步化后,在一些Mananger初始化时打印日志时使用 + * + * Self-synchronized SelfLog, used only in the middleware, + * after Solving SelfLog asynchronous, it is used when printing logs in some Manager initialization + * * @author luoguimu123 - * @version $Id: SynchronizingSelfLog.java, v 0.1 2017年11月21日 下午7:45 luoguimu123 Exp $ + * @version $Id: SynchronizingSelfLog.java, v 0.1 November 21, 2017 7:45 PM luoguimu123 Exp $ */ public class SynchronizingSelfLog { @@ -36,8 +39,8 @@ public class SynchronizingSelfLog { static private final String WARN_PREFIX = "[WARN] "; static private final String INFO_PREFIX = "[INFO] "; - /*** - * 日志文件名称 + /** + * Log file name */ static protected final String SELF_LOG_FILE = "sync.log"; @@ -60,8 +63,8 @@ public class SynchronizingSelfLog { } /** - * @param log 日志 - * @param e 异常 + * @param log + * @param e */ public static void error(String log, Throwable e) { try { @@ -80,10 +83,10 @@ public static void error(String log, Throwable e) { } /** - * 打印错误日志,附加当前线程的 TraceId + * Print error log with current thread's TraceId * - * @param log 错误信息 - * @param e 异常 + * @param log + * @param e */ public static void errorWithTraceId(String log, Throwable e) { try { @@ -107,9 +110,9 @@ public static void error(String log) { } /** - * 打印错误日志,附加当前线程的 TraceId + * Print error log with current thread's TraceId * - * @param log 错误消息 + * @param log * @param traceId traceId */ public static void errorWithTraceId(String log, String traceId) { @@ -117,9 +120,9 @@ public static void errorWithTraceId(String log, String traceId) { } /** - * 打印错误日志,附加当前线程的 TraceId + * Print error log with current thread's TraceId * - * @param log 错误消息 + * @param log */ public static void errorWithTraceId(String log) { doLog(log, ERROR_PREFIX + "[" + TracerUtils.getTraceId() + "]"); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/TracerDaemon.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/TracerDaemon.java index a8032eca..a9bc2777 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/TracerDaemon.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/appender/self/TracerDaemon.java @@ -24,9 +24,9 @@ import java.util.concurrent.atomic.AtomicBoolean; /** - * Tracer 的 Daemon 线程,主要是做清理日志的事情 + * Tracer's Daemon thread, mainly to do the cleanup log * - * @author khotyn 15/2/16 下午4:32 + * @author khotyn 15/2/16 PM 4:32 */ public class TracerDaemon implements Runnable { @@ -36,15 +36,16 @@ public class TracerDaemon implements Runnable { private static long scanInterval = ONE_HOUR; /** - * 注册被监听的 Appender + * Register the Appender being monitored * - * @param traceAppender 输出实现 + * @param traceAppender */ public static void watch(TraceAppender traceAppender) { watchedAppenders.add(traceAppender); } @SuppressWarnings("InfiniteLoopStatement") + @Override public void run() { while (true) { try { @@ -60,9 +61,9 @@ public void run() { } /** - * 为了测试方便,调整 Daemon 线程的扫描周期 + * Adjust the scanning cycle of the Daemon thread for testing convenience * - * @param scanInterval 扫描周期,单位为秒 + * @param scanInterval Scan period in seconds */ public static void setScanInterval(long scanInterval) { TracerDaemon.scanInterval = scanInterval; diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerCallable.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerCallable.java index 05fd97d0..e04a8fde 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerCallable.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerCallable.java @@ -26,8 +26,9 @@ /** * Callable that passes Span between threads. The Span name is * taken either from the passed value or from the interface. + * * @author luoguimu123 - * @version $Id: Callable.java, v 0.1 2017年06月19日 下午5:52 luoguimu123 Exp $ + * @version $Id: Callable.java, v 0.1 June 19, 2017 5:52 PM luoguimu123 Exp $ */ public class SofaTracerCallable implements Callable { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerRunnable.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerRunnable.java index 6a75fdfb..6dbb71a7 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerRunnable.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/SofaTracerRunnable.java @@ -25,8 +25,9 @@ /** * Runnable that passes Span between threads. The Span name is * taken either from the passed value or from the interface. + * * @author luoguimu123 - * @version $Id: Runnable.java, v 0.1 2017年06月19日 下午5:54 luoguimu123 Exp $ + * @version $Id: Runnable.java, v 0.1 June 19, 2017 5:54 PM luoguimu123 Exp $ */ public class SofaTracerRunnable implements Runnable { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/TracerScheduleExecutorService.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/TracerScheduleExecutorService.java index 9afbb4f3..655f7259 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/async/TracerScheduleExecutorService.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/async/TracerScheduleExecutorService.java @@ -25,9 +25,10 @@ import java.util.concurrent.TimeUnit; /** - * 扩展的定时可有trace信息的定时线程池 + * Extended timing thread pool for SOFATracer + * * @author luoguimu123 - * @version $Id: TracerScheduleExecutorService.java, v 0.1 2017年06月22日 上午11:43 luoguimu123 Exp $ + * @version $Id: TracerScheduleExecutorService.java, v 0.1 June 22, 2017 11:43 AM luoguimu123 Exp $ */ public class TracerScheduleExecutorService extends TracedExecutorService implements ScheduledExecutorService { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerConfiguration.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerConfiguration.java index ef3b6ba2..9e958886 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerConfiguration.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerConfiguration.java @@ -31,77 +31,78 @@ /** * * @author luoguimu123 - * @version $Id: SofaTracerConfiguration.java, v 0.1 2017年06月22日 下午3:12 luoguimu123 Exp $ + * @version $Id: SofaTracerConfiguration.java, v 0.1 June 22, 2017 3:12 PM luoguimu123 Exp $ */ public class SofaTracerConfiguration { /** - * 是否开启中间件的 Digest 日志,关闭这个开关将会关闭所有的中间件的 Digest 日志 + * Whether to open the Digest log of the middleware, closing this switch will close the Digest log of all middleware. */ public static final String DISABLE_MIDDLEWARE_DIGEST_LOG_KEY = "disable_middleware_digest_log"; /** - * key=是否开启特定的中间件 Digest 日志开关,value=map[日志类型为key:value(开关)] + * com.alipay.sofa.tracer.disableConfiguration[logType]=true */ public final static String DISABLE_DIGEST_LOG_KEY = "disable_digest_log"; /** - * Tracer 的全局的 Rolling 的配置的 Key + * Tracer's Global Rolling configured Key */ public final static String TRACER_GLOBAL_ROLLING_KEY = "tracer_global_rolling_policy"; /** - * Tracer 的全局的日志的保留天数配置的 Key + * Tracer's global log retention days configured Key */ public final static String TRACER_GLOBAL_LOG_RESERVE_DAY = "tracer_global_log_reserve_day"; - /*** - * 默认日志的保留天数 + /** + * Default log retention days */ public static final int DEFAULT_LOG_RESERVE_DAY = 7; /** - * 阈值,业务透传字段的限制长度 + * Threshold, the length of the service transparent field */ public final static int PEN_ATTRS_LENGTH_TRESHOLD = 1024; /** - * Tracer 的穿透数据的最大值的配置的 Key + * The configuration of the maximum value of the tracer's penetration data */ public static final String TRACER_PENETRATE_ATTRIBUTE_MAX_LENGTH = "tracer_penetrate_attribute_max_length"; /** - * Tracer 系统穿透数据的最大值的配置的 Key + * The configuration key of the maximum value of the Tracer system penetration data */ public static final String TRACER_SYSTEM_PENETRATE_ATTRIBUTE_MAX_LENGTH = "tracer_system_penetrate_attribute_max_length"; /** - * 统计日志的打印的间隔,加入这个选项主要是为了可测试性的考虑,系统属性关键字 + * The interval for printing the stat log. + * This option is mainly for testability considerations. System attribute keywords. */ public static final String STAT_LOG_INTERVAL = "stat_log_interval"; - /*****************异步队列配置项 start***************/ + /***************** Asynchronous queue configuration item start ***************/ /** - * 是否允许丢失日志 + * Whether to allow lost logs */ public static final String TRACER_ASYNC_APPENDER_ALLOW_DISCARD = "tracer_async_appender_allow_discard"; /** - * 是否日志输出丢失日志的数量 + * Whether the log output loses the number of logs */ public static final String TRACER_ASYNC_APPENDER_IS_OUT_DISCARD_NUMBER = "tracer_async_appender_is_out_discard_number"; /** - * 是否日志输出丢失日志的TraceId和RpcId + * Whether the log output loses the trace of the TraceId and RpcId */ public static final String TRACER_ASYNC_APPENDER_IS_OUT_DISCARD_ID = "tracer_async_appender_is_out_discard_id"; /** - * 丢失日志的数量达到该阈值进行一次日志输出 + * The number of lost logs reaches this threshold for a log output */ public static final String TRACER_ASYNC_APPENDER_DISCARD_OUT_THRESHOLD = "tracer_async_appender_discard_out_threshold"; - /*****************异步队列配置项 end***************/ + /***************** Asynchronous queue configuration item end ***************/ /** - * 应用名称 + * app name */ public static final String TRACER_APPNAME_KEY = "spring.application.name"; @@ -111,13 +112,11 @@ public class SofaTracerConfiguration { private static SofaTracerExternalConfiguration sofaTracerExternalConfiguration = null; - /***************** 采样配置项 end ***************/ - - /** 采样策略名称key */ + /** The key of Sampling policy name */ public static final String SAMPLER_STRATEGY_NAME_KEY = "tracer_sampler_strategy_name_key"; - /** 自定义采样规则类名 */ + /** Custom sampling rule class name */ public static final String SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME = "tracer_sampler_strategy_custom_rule_class_name"; - /** 采样率key */ + /** The key of Sampling rate */ public static final String SAMPLER_STRATEGY_PERCENTAGE_KEY = "tracer_sampler_strategy_percentage_key"; static { @@ -132,41 +131,43 @@ public class SofaTracerConfiguration { } catch (Exception e) { SelfLog.info("sofa.tracer.properties文件不存在"); } - //静态统计信息 + //Static statistics StaticInfoLog.logStaticInfo(); } /** - * 设置配置项 + * Setting configuration item for String type value * - * @param key 配置项 key - * @param value 配置项的值 + * @param key configuration item key + * @param value configuration item value */ public static void setProperty(String key, String value) { properties.put(key, value); } /** - * @param key 关键字 - * @param value 值 + * Setting configuration item for Integer type value + * @param key configuration item key + * @param value configuration item value */ public static void setProperty(String key, Integer value) { properties.put(key, value); } /** - * @param key 关键字 - * @param value 值 + * Setting configuration item for Map type value + * @param key configuration item key + * @param value configuration item value */ public static void setProperty(String key, Map value) { properties.put(key, value); } /** - * 获取配置项 + * get property by key * - * @param key 配置项的 key - * @return 属性值 + * @param key configuration item key + * @return */ public static String getProperty(String key) { return getProperty(key, StringUtils.EMPTY_STRING); @@ -186,9 +187,10 @@ public static Integer getInteger(String key) { } /** - * @param key 关键字 - * @param defaultValue 默认值 - * @return 整数 + * get property with default value + * @param key key + * @param defaultValue default value + * @return Integer */ public static Integer getIntegerDefaultIfNull(String key, Integer defaultValue) { Integer value = getInteger(key); @@ -196,7 +198,8 @@ public static Integer getIntegerDefaultIfNull(String key, Integer defaultValue) } /** - * @param key 关键字 + * get property + * @param key key * @return map */ public static Map getMapEmptyIfNull(String key) { @@ -213,11 +216,11 @@ public static Map getMapEmptyIfNull(String key) { } /** - * 获取配置项 + * get property * - * @param key 配置项的 key - * @param defaultValue 如果获取出得配置项是 null,则返回 defaultValue - * @return 配置值或者默认值 + * @param key key + * @param defaultValue defaultValue + * @return defaultValue if value is not null */ public static String getProperty(String key, String defaultValue) { if (properties.containsKey(key)) { @@ -229,7 +232,8 @@ public static String getProperty(String key, String defaultValue) { if (fileProperties.containsKey(key)) { return (String) fileProperties.get(key); } - //最后判断外部注入的配置中是否存在该key对应的配置值 + // Finally, it is determined whether the configuration value corresponding to + // the key exists in the externally injected configuration. if (sofaTracerExternalConfiguration != null && sofaTracerExternalConfiguration.contains(key)) { return sofaTracerExternalConfiguration.getValue(key); @@ -238,10 +242,10 @@ public static String getProperty(String key, String defaultValue) { } /** - * 获取某一个日志的 Rolling 策略 + * Get a Rolling policy for a log * - * @param rollingKey 滚动策略名称 - * @return 某一个日志的 Rolling 策略,默认的策略是 + * @param rollingKey rollingKey + * @return The Rolling policy of a log, the default policy is * {@link TimedRollingFileAppender#DAILY_ROLLING_PATTERN} */ public static String getRollingPolicy(String rollingKey) { @@ -256,10 +260,10 @@ public static String getRollingPolicy(String rollingKey) { : rollingPolicy; } - /*** - * 获取日志保留天数 - * @param logReserveKey 日志保留天数关键字,跟进此获取具体的保留值 - * @return 此关键字对应的日志保留天数 + /** + * Get log retention days + * @param logReserveKey The key of Log retention days + * @return */ public static String getLogReserveConfig(String logReserveKey) { if (StringUtils.isBlank(logReserveKey)) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerExternalConfiguration.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerExternalConfiguration.java index 33ff49a1..54d8cb88 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerExternalConfiguration.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/configuration/SofaTracerExternalConfiguration.java @@ -17,14 +17,24 @@ package com.alipay.common.tracer.core.configuration; /** - * 外部配置类的接口,该接口由外部代码实现 + * The interface of the external configuration class, which is implemented by external code * @author luoguimu123 - * @version $Id: SofaTracerExternalConfiguration.java, v 0.1 2017年10月11日 下午12:03 luoguimu123 Exp $ + * @version $Id: SofaTracerExternalConfiguration.java, v 0.1 October 11, 2017 12:03 PM luoguimu123 Exp $ */ public interface SofaTracerExternalConfiguration { + /** + * get value by input key + * @param key + * @return + */ String getValue(String key); + /** + * Whether the specified key exists + * @param key + * @return + */ boolean contains(String key); } \ No newline at end of file diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/SofaTracerConstant.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/SofaTracerConstant.java index 7625fa6f..518c42df 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/SofaTracerConstant.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/SofaTracerConstant.java @@ -44,49 +44,43 @@ public class SofaTracerConstant { public static final String RPC_2_JVM_DIGEST_LOG_NAME = "rpc-2-jvm-digest.log"; - //******************* span encoder constant start ***************** - /** - * 耗时单位 + * Time-consuming unit */ public static final String MS = "ms"; - /*** - * 字节单位 + /** + * Byte unit */ public static final String BYTE = "B"; /** - * Tracer 上下文嵌套的最大深度 + * Maximum depth of the Tracer context nesting */ public static final int MAX_LAYER = 100; //******************* span encoder constant end ***************** //******************* exception constant start ***************** - - /*** - * 业务异常 + /** + * Business exception */ public static final String BIZ_ERROR = "biz_error"; //******************* exception constant end ***************** - /*** - * ============= baggage key start ============== - */ + //******************* baggage key start ***************** /** - * 必须保持一致,baggage key 压测标识 + * Must be consistent, baggage key for pressure measurement mark */ public static final String LOAD_TEST_TAG = "mark"; - - /*** - * 压测标识必须为 T 即 baggage 中 mark=T 才可以打印到 shdow 文件 + /** + * The pressure measurement mark must be T, ie mark=T in baggage, to print to the shadow file. */ public static final String LOAD_TEST_VALUE = "T"; - /*** - * 非压测情况下的返回值 {@link AbstractSofaTracerStatisticReporter} + /** + * Return value in case of non-pressure measurement {@link AbstractSofaTracerStatisticReporter} */ public static final String NON_LOAD_TEST_VALUE = "F"; } 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 14922267..ad510c44 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 @@ -22,7 +22,6 @@ import com.alipay.common.tracer.core.utils.StringUtils; import com.alipay.common.tracer.core.utils.TracerUtils; import io.opentracing.SpanContext; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -36,10 +35,10 @@ */ public class SofaTracerSpanContext implements SpanContext { - //spanId 分隔符 + //spanId separator public static final String RPC_ID_SEPARATOR = "."; - //======================== 以下为序列化数据的 key ======================== + //======================== The following is the key for serializing data ======================== private static final String TRACE_ID_KET = "tcid"; @@ -49,41 +48,42 @@ public class SofaTracerSpanContext implements SpanContext { private static final String SAMPLE_KET = "sample"; - /*** - * 序列化系统透传属性 key 的关键字前缀(需要序列化添加,反序列化去除 key 的前缀) + /** + * The serialization system transparently passes the prefix of the attribute key */ private static final String SYS_BAGGAGE_PREFIX_KEY = "_sys_"; - //span 关键属性参数 private String traceId = StringUtils.EMPTY_STRING; private String spanId = StringUtils.EMPTY_STRING; private String parentId = StringUtils.EMPTY_STRING; - /*** - * 默认不会采样 + /** + * Default will not be sampled */ private boolean isSampled = false; - /*** - * 系统透传数据,主要是指系统维度的透传数据,注意业务透传不能使用此字段 + /** + * The system transparently transmits data, + * mainly refers to the transparent transmission data of the system dimension. + * Note that this field cannot be used for transparent transmission of business. */ private final Map sysBaggage = new ConcurrentHashMap(); - /*** - * 透传数据,主要是指业务的透传数据 + /** + * Transparent transmission of data, mainly refers to the transparent transmission data of the business */ private final Map bizBaggage = new ConcurrentHashMap(); /** - * 子上下文的计数器 + * sub-context counter */ private AtomicInteger childContextIndex = new AtomicInteger(0); - /*** - * clone 一个当前模型 - * @return clone 对象 + /** + * clone a SofaTracerSpanContext instance + * @return */ public SofaTracerSpanContext cloneInstance() { SofaTracerSpanContext spanContext = new SofaTracerSpanContext(this.traceId, this.spanId, @@ -95,17 +95,17 @@ public SofaTracerSpanContext cloneInstance() { } public SofaTracerSpanContext() { - //默认不会采样 + //Default will not be sampled this(StringUtils.EMPTY_STRING, StringUtils.EMPTY_STRING, null, false); } public SofaTracerSpanContext(String traceId, String spanId) { - //默认不会采样 + //Default will not be sampled this(traceId, spanId, null, false); } public SofaTracerSpanContext(String traceId, String spanId, String parentId) { - //默认不会采样 + //Default will not be sampled this(traceId, spanId, parentId, false); } @@ -130,9 +130,9 @@ public SofaTracerSpanContext addSysBaggage(Map sysBaggage) { return this; } - /*** - * 系统和业务 baggage 均返回 - * @return 迭代器 + /** + * return both system and business baggage + * @return Iterable */ @Override public Iterable> baggageItems() { @@ -146,21 +146,20 @@ public Iterable> baggageItems() { return allBaggage.entrySet(); } - /**** - * 关键信息统一生成字符串 + /** + * return key information string for SofaTracerSpanContext * @return */ - private String contextAsString() {// NOPMD + private String contextAsString() { return String.format("%s:%s:%s:%s", traceId, spanId, parentId, isSampled); } /** - * 将 Tracer 中的穿透属性序列化成一个 String + * Serialize the Penetration property in Tracer into a String *

- * 此方法一般是 Tracer 内部或者直接集成 Tracer 的中间件使用 + * This method is generally used internally by Tracer or directly integrated with Tracer. *

- * - * @return 序列化以后的穿透属性 + * @return */ public String getBizSerializedBaggage() { return StringUtils.mapToString(bizBaggage); @@ -171,12 +170,12 @@ public String getSysSerializedBaggage() { } /** - * 将一个穿透属性序列化后的 String,反序列化回来成为一个 Map 接口 + * deserialize string to map + * *

- * 此方法一般是 Tracer 内部或者直接集成 Tracer 的中间件使用 + * This method is generally used internally by Tracer or directly integrated with Tracer. *

- * - * @param bizBaggageAttrs 序列化后的穿透属性 String + * @param bizBaggageAttrs serialized penetration properties */ public void deserializeBizBaggage(String bizBaggageAttrs) { StringUtils.stringToMap(bizBaggageAttrs, this.bizBaggage); @@ -201,10 +200,10 @@ public void deserializeSysBaggage(String sysBaggageAttrs) { } } - /*** - * 将 SpanContext 序列化为一个字符串,与 {@link SofaTracerSpanContext#deserializeFromString} 互逆 + /** + * Serialize the SpanContext to a string that is reciprocal to {@link SofaTracerSpanContext#deserializeFromString} * - * @return 序列化后的字符串, 格式:tcid:0,spid:1 + * @return Serialized string, format: tcid:0,spid:1 */ public String serializeSpanContext() { StringBuilder serializedValue = new StringBuilder(); @@ -228,20 +227,21 @@ public String serializeSpanContext() { return serializedValue.toString(); } - /*** - * 反序列化并还原一个 SofaTracerSpanContext,与 {@link SofaTracerSpanContext#serializeSpanContext()} 互逆 - * @param deserializedValue 反序列化的字符串,格式:tcid:0,spid:1 + /** + * + * Deserialize and restore a SofaTracerSpanContext, reciprocal with {@link SofaTracerSpanContext#serializeSpanContext()} + * @param deserializedValue deserialize string, format: tcid:0,spid:1 * @return SofaTracerSpanContext */ public static SofaTracerSpanContext deserializeFromString(String deserializedValue) { if (StringUtils.isBlank(deserializedValue)) { return SofaTracerSpanContext.rootStart(); } - //默认值 + //default value for SofaTracerSpanContext String traceId = TraceIdGenerator.generate(); String spanId = SofaTracer.ROOT_SPAN_ID; String parentId = StringUtils.EMPTY_STRING; - //默认false + //sampled default is false boolean sampled = false; //sys bizBaggage Map sysBaggage = new HashMap(); @@ -275,11 +275,11 @@ public static SofaTracerSpanContext deserializeFromString(String deserializedVal } int sysIndex = key.indexOf(SYS_BAGGAGE_PREFIX_KEY); if (sysIndex == 0) { - //必须前缀作为开始 + //must have a prefix String sysKey = key.substring(SYS_BAGGAGE_PREFIX_KEY.length()); sysBaggage.put(sysKey, value); } else { - //剩余全部为业务 bizBaggage + //bizBaggage baggage.put(key, value); } } @@ -294,21 +294,20 @@ public static SofaTracerSpanContext deserializeFromString(String deserializedVal return sofaTracerSpanContext; } - /**** - * 作为根节点而开始 + /** + * As root start ,it will be return a new sofaTracerSpanContext * - * 注意:1.留下这个接口,不对接具体的 tracer 实现,主要为了在序列化或者反序列化发生异常时,做补救 - * 2.不可以随意调用此方法,正确的入口应该是 {@link SofaTracer.SofaTracerSpanBuilder#createRootSpanContext()} - * @return 根节点 + * Note:1.Leave this interface, do not dock the specific tracer implementation, mainly to remedy when an exception occurs in serialization or deserialization + * 2.This method cannot be called at will, the correct entry should be {@link SofaTracer.SofaTracerSpanBuilder#createRootSpanContext()} + * @return root node */ public static SofaTracerSpanContext rootStart() { return rootStart(false); } public static SofaTracerSpanContext rootStart(boolean isSampled) { - //生成 traceId + //create traceId String traceId = TraceIdGenerator.generate(); - //默认不采样 return new SofaTracerSpanContext(traceId, SofaTracer.ROOT_SPAN_ID, StringUtils.EMPTY_STRING, isSampled); } @@ -318,16 +317,16 @@ private String genParentSpanId(String spanId) { : spanId.substring(0, spanId.lastIndexOf(RPC_ID_SEPARATOR)); } - /*** - * 允许设置 tracdId + /** + * Allow to set traceId * @param traceId traceId */ public void setTraceId(String traceId) { this.traceId = traceId; } - /**** - * 允许设置 spanId + /** + * Allow to set spanId * @param spanId spanId */ public void setSpanId(String spanId) { @@ -392,18 +391,18 @@ public AtomicInteger getChildContextIndex() { } /** - * 获取下一个子上下文的 ID + * Get the ID of the next sub context * - * @return 下一个 spanId + * @return next spanId */ public String nextChildContextId() { return this.spanId + RPC_ID_SEPARATOR + childContextIndex.incrementAndGet(); } /** - * 获取上一个子上下文的 rpcId + * Get the spanId of the previous sub context * - * @return 上一个子上下文的 rpcId + * @return prev spanId */ public String lastChildContextId() { return this.spanId + RPC_ID_SEPARATOR + childContextIndex.get(); @@ -427,9 +426,6 @@ public boolean equals(Object o) { return false; } if (StringUtils.isBlank(parentId)) { - //一个为空 - //另一个也为空 - //另一个不为空 return StringUtils.isBlank(that.parentId); } return parentId.equals(that.parentId); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/context/trace/SofaTraceContext.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/context/trace/SofaTraceContext.java index 0f53dfbc..8ffc78f6 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/context/trace/SofaTraceContext.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/context/trace/SofaTraceContext.java @@ -49,14 +49,14 @@ public interface SofaTraceContext { */ SofaTracerSpan pop(); - /*** - * Retrieves the current span size stored in current thread local + /** + * Retrieves the current span size stored in current thread local * * @return the span size of current thread local */ int getThreadLocalSpanSize(); - /*** + /** * Clear current thread local span */ void clear(); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/EmptyTracerStateStringException.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/EmptyTracerStateStringException.java index 0df37fb2..429922c4 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/EmptyTracerStateStringException.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/EmptyTracerStateStringException.java @@ -19,7 +19,7 @@ /** * * @author luoguimu123 - * @version $Id: EmptyTracerStateStringException.java, v 0.1 2017年06月22日 上午10:55 luoguimu123 Exp $ + * @version $Id: EmptyTracerStateStringException.java, v 0.1 June 22, 2017 10:55 AM luoguimu123 Exp $ */ public class EmptyTracerStateStringException extends RuntimeException { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/SamplingStrategyErrorException.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/SamplingStrategyErrorException.java index 4eab30a1..549464d4 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/SamplingStrategyErrorException.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/SamplingStrategyErrorException.java @@ -17,9 +17,9 @@ package com.alipay.common.tracer.core.exception; /** - * 采样部分代码出错时候采用的异常 + * Exception when sampling part of the code error * @author luoguimu123 - * @version $Id: SamplingStrategyErrorException.java, v 0.1 2017年06月22日 上午10:56 luoguimu123 Exp $ + * @version $Id: SamplingStrategyErrorException.java, v 0.1 June 22, 2017 10:56 AM luoguimu123 Exp $ */ public class SamplingStrategyErrorException extends RuntimeException { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/SofaTracerRuntimeException.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/SofaTracerRuntimeException.java index 0890fa40..ca507ee2 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/SofaTracerRuntimeException.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/SofaTracerRuntimeException.java @@ -32,6 +32,7 @@ public SofaTracerRuntimeException(String desc, Throwable t) { super(desc, t); } + @Override public String toString() { return super.getMessage(); } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/UnsupportedFormatException.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/UnsupportedFormatException.java index 570cb3d2..e0d5305a 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/UnsupportedFormatException.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/exception/UnsupportedFormatException.java @@ -19,10 +19,10 @@ import io.opentracing.propagation.Format; /** - * format不支持时抛出的异常 + * format does not support exception thrown * * @author luoguimu123 - * @version $Id: UnsupportedFormatException.java, v 0.1 2017年06月22日 上午10:57 luoguimu123 Exp $ + * @version $Id: UnsupportedFormatException.java, v 0.1 June 22, 2017 10:57 AM luoguimu123 Exp $ */ public class UnsupportedFormatException extends RuntimeException { public UnsupportedFormatException(Format format) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/extensions/SpanExtension.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/extensions/SpanExtension.java index 684716ae..17f07f10 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/extensions/SpanExtension.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/extensions/SpanExtension.java @@ -21,16 +21,31 @@ /** * * @author luoguimu123 - * @version $Id: TracerExtension.java, v 0.1 2017年06月23日 上午11:48 luoguimu123 Exp $ + * @version $Id: TracerExtension.java, v 0.1 June 23, 2017 11:48 AM luoguimu123 Exp $ */ public interface SpanExtension { - + /** + * Called at the beginning of span + * @param currentSpan + */ void logStartedSpan(Span currentSpan); + /** + * Called at the end of span + * @param currentSpan + */ void logStoppedSpan(Span currentSpan); + /** + * Called at the end of span in Runnable + * @param currentSpan + */ void logStoppedSpanInRunnable(Span currentSpan); + /** + * return support name + * @return + */ String supportName(); } \ No newline at end of file diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/extensions/SpanExtensionFactory.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/extensions/SpanExtensionFactory.java index 44040332..2803b47a 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/extensions/SpanExtensionFactory.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/extensions/SpanExtensionFactory.java @@ -25,7 +25,7 @@ /** * * @author luoguimu123 - * @version $Id: SpanExtensionFactory.java, v 0.1 2017年06月23日 上午11:50 luoguimu123 Exp $ + * @version $Id: SpanExtensionFactory.java, v 0.1 June 23, 2017 11:50 AM luoguimu123 Exp $ */ public class SpanExtensionFactory { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/holder/SofaTraceContextHolder.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/holder/SofaTraceContextHolder.java index 2c497d2e..edb814f5 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/holder/SofaTraceContextHolder.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/holder/SofaTraceContextHolder.java @@ -27,12 +27,12 @@ */ public class SofaTraceContextHolder { - /*** + /** * singleton SofaTraceContext */ private static final SofaTraceContext SOFA_TRACE_CONTEXT = new SofaTracerThreadLocalTraceContext(); - /*** + /** * Get threadlocal alipay trace context * @return SofaTraceContext */ diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/listener/SpanReportListener.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/listener/SpanReportListener.java index 81b3d0e0..fb526430 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/listener/SpanReportListener.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/listener/SpanReportListener.java @@ -19,12 +19,17 @@ import com.alipay.common.tracer.core.span.SofaTracerSpan; /** - * SpanReportListener + * SpanReportListener:Reporter extension interface * * @author yangguanchao * @since 2018/05/07 */ public interface SpanReportListener { + /** + * Reporter extension callback method + * It can be printed to the log, or it can be reported to some remote server + * @param sofaTracerSpan + */ void onSpanReport(SofaTracerSpan sofaTracerSpan); } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/middleware/parent/AbstractDigestSpanEncoder.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/middleware/parent/AbstractDigestSpanEncoder.java index 7d62c317..f8547481 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/middleware/parent/AbstractDigestSpanEncoder.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/middleware/parent/AbstractDigestSpanEncoder.java @@ -23,22 +23,25 @@ /** * * @author luoguimu123 - * @version $Id: AbstractDigestSpanEncoder.java, v 0.1 2017年08月28日 上午10:23 luoguimu123 Exp $ + * @version $Id: AbstractDigestSpanEncoder.java, v 0.1 August 28, 2017 10:23 AM luoguimu123 Exp $ */ public abstract class AbstractDigestSpanEncoder implements SpanEncoder { - /*** - * 系统透传数据 - * @param spanContext span 上下文 + /** + * System transparent transmission of data + * @param spanContext span context * @return String */ protected String baggageSystemSerialized(SofaTracerSpanContext spanContext) { - //目前只有一个 baggage return spanContext.getSysSerializedBaggage(); } + /** + * Business transparent transmission of data + * @param spanContext span context + * @return + */ protected String baggageSerialized(SofaTracerSpanContext spanContext) { - //目前只有一个 baggage return spanContext.getBizSerializedBaggage(); } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/mock/MockSofaTracer.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/mock/MockSofaTracer.java index 9b054e24..a3a4ff76 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/mock/MockSofaTracer.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/mock/MockSofaTracer.java @@ -26,11 +26,11 @@ */ public class MockSofaTracer { - private static final String MOCK_TRACER = "MOCK_TRACER"; + private static final String MOCK_TRACER = "MOCK_TRACER"; - private static SofaTracer MOCK_SOFA_TRACER = null; + private volatile static SofaTracer MOCK_SOFA_TRACER = null; - /*** + /** * Get the mocked OpenTracing Implementation * @return mock tracer */ diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextB3Formatter.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextB3Formatter.java index 0b9ee514..904ebd34 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextB3Formatter.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextB3Formatter.java @@ -66,7 +66,7 @@ public SofaTracerSpanContext extract(TextMap carrier) { String parentId = null; boolean sampled = false; boolean isGetSampled = false; - //sys bizBaggage + //sysBaggage Map sysBaggage = new ConcurrentHashMap(); //bizBaggage Map bizBaggage = new ConcurrentHashMap(); @@ -161,14 +161,14 @@ public void inject(SofaTracerSpanContext spanContext, TextMap carrier) { } } - /*** + /** * encode string * @param value string will be encoded * @return encoded value */ protected abstract String encodedValue(String value); - /*** + /** * decode string * @param value string will be decoded * @return decoded value diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextFormatter.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextFormatter.java index aafac43f..350c4eca 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextFormatter.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/AbstractTextFormatter.java @@ -33,7 +33,7 @@ public abstract class AbstractTextFormatter implements RegistryExtractorInjector @Override public SofaTracerSpanContext extract(TextMap carrier) { if (carrier == null) { - //根节点开始 + //Root node starts return SofaTracerSpanContext.rootStart(); } SofaTracerSpanContext sofaTracerSpanContext = null; @@ -49,7 +49,7 @@ public SofaTracerSpanContext extract(TextMap carrier) { } } if (sofaTracerSpanContext == null) { - //根节点开始 + //Root node starts return SofaTracerSpanContext.rootStart(); } return sofaTracerSpanContext; @@ -63,17 +63,17 @@ public void inject(SofaTracerSpanContext spanContext, TextMap carrier) { carrier.put(FORMATER_KEY_HEAD, this.encodedValue(spanContext.serializeSpanContext())); } - /*** - * 对指定的值进行编码 - * @param value 字符串 - * @return 编码后的 value + /** + * Encode the specified value + * @param value + * @return encoded value */ protected abstract String encodedValue(String value); - /*** - * 对指定的值进行解码 - * @param value 字符串 - * @return 编码后的字符串 + /** + * Decode the specified value + * @param value + * @return decoded value */ protected abstract String decodedValue(String value); } 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 476499f1..72eb4a52 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 @@ -27,16 +27,18 @@ /** * BinaryFormater *

- * 注意:只支持堆内存不支持堆外内存 - * + * Note: only supports the heap memory does not support outside the heap memory + *

* @author yangguanchao * @since 2017/06/23 */ public class BinaryFormater implements RegistryExtractorInjector { - /*** - * 作为跨进程传输字段的关键字key或者头部标识信息,其 value 就是 {@link SofaTracerSpanContext} 的序列化表现:sofa tracer head - * 转换为字节码,这组字节码会作为 byteArray 中的 spanContext 起始标示 + /** + * As the keyword key or header identification information of the cross-process transmission field, + * its value is the serialization representation of {@link SofaTracerSpanContext}: sofa tracer head + * + * Converted to bytecode, this set of bytecodes will be used as the start of the spanContext in the byteArray */ private static final byte[] FORMATER_KEY_HEAD_BYTES = FORMATER_KEY_HEAD .getBytes(SofaTracerConstant.DEFAULT_UTF8_CHARSET); @@ -49,7 +51,6 @@ public Format getFormatType() { @Override public SofaTracerSpanContext extract(ByteBuffer carrier) { if (carrier == null || carrier.array().length < FORMATER_KEY_HEAD_BYTES.length) { - //从新开始 return SofaTracerSpanContext.rootStart(); } byte[] carrierDatas = carrier.array(); @@ -57,13 +58,12 @@ public SofaTracerSpanContext extract(ByteBuffer carrier) { byte[] formaterKeyHeadBytes = FORMATER_KEY_HEAD_BYTES; int index = ByteArrayUtils.indexOf(carrierDatas, formaterKeyHeadBytes); if (index < 0) { - //从新开始 return SofaTracerSpanContext.rootStart(); } try { - //(UTF-8)放在头部从 0 开始 + //(UTF-8)Put the head from 0 carrier.position(index + formaterKeyHeadBytes.length); - //value 字节数组 + //value byte arrays byte[] contextDataBytes = new byte[carrier.getInt()]; carrier.get(contextDataBytes); String spanContextInfos = new String(contextDataBytes, @@ -74,7 +74,6 @@ public SofaTracerSpanContext extract(ByteBuffer carrier) { .error( "com.alipay.common.tracer.core.registry.BinaryFormater.extract Error.Recover by root start", e); - //从新开始 return SofaTracerSpanContext.rootStart(); } } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/RegistryExtractorInjector.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/RegistryExtractorInjector.java index 3c9cc09d..ab4194b0 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/RegistryExtractorInjector.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/registry/RegistryExtractorInjector.java @@ -21,29 +21,30 @@ public interface RegistryExtractorInjector { - /*** - * 作为跨进程传输字段的关键字key或者头部标识信息,其 value 就是 {@link SofaTracerSpanContext} 的序列化表现:sofa tracer head + /** + * As the keyword key or header identification information of the cross-process transmission field, + * its value is the serialization representation of {@link SofaTracerSpanContext}: sofa tracer head */ String FORMATER_KEY_HEAD = "sftc_head"; - /*** - * 获取支持的格式类型 - * @return 格式类型 {@link Format} + /** + * Get supported format types + * @return Format type {@link Format} */ Format getFormatType(); /** - * 从负载中提取出 Span 上下文 + * Extract the Span context from the payload * - * @param carrier 负载 - * @return Span 上下文 + * @param carrier payload + * @return SpanContext */ SofaTracerSpanContext extract(T carrier); - /*** - * 向负载中注入 Span 上下文 - * @param spanContext 要注入或者序列化的 span 上下文 - * @param carrier 负载 + /** + * Inject a Span context into the payload + * @param spanContext The span context to be injected or serialized + * @param carrier payload */ void inject(SofaTracerSpanContext spanContext, T carrier); } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoder.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoder.java index 91fad443..68f54077 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoder.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoder.java @@ -29,9 +29,10 @@ /** * CommonSpanEncoder *

- * 客户端错误和服务端错误均打印在同一个文件中 + * Client errors and server errors are printed in the same file + *

* - * 注意是无状态实例:多个日志打印共用的一个实例 + * Note that there is a stateless instance: an instance of multiple log prints shared * * @author yangguanchao * @since 2017/06/27 @@ -45,9 +46,9 @@ public String encode(CommonLogSpan commonLogSpan) throws IOException { } SofaTracerSpanContext spanContext = commonLogSpan.getSofaTracerSpanContext(); XStringBuilder xsb = new XStringBuilder(); - //报告开始的时间作为打印的时间,不存在完成时间 + //The time when the report started as the time of printing, there is no completion time xsb.append(Timestamp.format(commonLogSpan.getStartTime())) - //保证构造common也携带过来 + //Ensure that the construct common is also carried .append(commonLogSpan.getTagsWithStr().get(SpanTags.CURR_APP_TAG.getKey())) .append(spanContext.getTraceId()).append(spanContext.getSpanId()); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/common/CommonTracerManager.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/common/CommonTracerManager.java index 628d1d91..031d5a71 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/common/CommonTracerManager.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/common/CommonTracerManager.java @@ -35,8 +35,7 @@ public class CommonTracerManager { /** - * - * 异步日志打印,所有的中间件公用一个来打印通用日志 + * Asynchronous log print, all middleware common to print general logs */ private static volatile AsyncCommonDigestAppenderManager commonReporterAsyncManager = new AsyncCommonDigestAppenderManager( 1024); @@ -64,11 +63,11 @@ public class CommonTracerManager { commonReporterAsyncManager.start("CommonProfileErrorAppender"); } - /*** - * 注册一个通用日志 - * @param logFileName 日志文件名字,同时也是作为日志文件的类型标识 - * @param rollingPolicy 滚动策略 - * @param logReserveDay 保留天数 + /** + * Register a general log + * @param logFileName logFileName + * @param rollingPolicy rollingPolicy + * @param logReserveDay logReserveDay */ public static void register(String logFileName, String rollingPolicy, String logReserveDay) { if (StringUtils.isBlank(logFileName)) { @@ -83,12 +82,12 @@ public static void register(String logFileName, String rollingPolicy, String log commonReporterAsyncManager.addAppender(logFileName, traceAppender, commonSpanEncoder); } - /*** - * 废弃 - * @param logType 类型 - * @param logFileName 文件名称 - * @param rollingPolicy 滚动策略 - * @param logReserveDay 保留天数 + /** + * Deprecated registration method + * @param logType logType + * @param logFileName logFileName + * @param rollingPolicy rollingPolicy + * @param logReserveDay logReserveDay */ @Deprecated public static void register(char logType, String logFileName, String rollingPolicy, @@ -103,10 +102,10 @@ public static void register(char logType, String logFileName, String rollingPoli commonReporterAsyncManager.addAppender(logTypeStr, traceAppender, commonSpanEncoder); } - /*** - * 判断指定日志类型的输出是否符合要求 - * @param logType 日志类型 - * @return true 已经存在 + /** + * Determine if the output of the specified log type meets the requirements + * @param logType logType + * @return true:exist */ public static boolean isAppenderExist(String logType) { if (StringUtils.isBlank(logType)) { @@ -115,9 +114,9 @@ public static boolean isAppenderExist(String logType) { return commonReporterAsyncManager.isAppenderAndEncoderExist(logType); } - /*** - * 注意:这个 {@link CommonLogSpan} 的 logType 一定要设置,否则无法打印 - * @param commonLogSpan 要被打印的 Span + /** + * Note: The logType of this {@link CommonLogSpan} must be set, otherwise it will not print. + * @param commonLogSpan The span will be printed */ public static void reportCommonSpan(CommonLogSpan commonLogSpan) { if (commonLogSpan == null) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/AbstractDiskReporter.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/AbstractDiskReporter.java index 980c6981..c0f1585e 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/AbstractDiskReporter.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/AbstractDiskReporter.java @@ -28,59 +28,59 @@ /** * AbstractDiskReporter * - * 持久化抽象类,摘要持久化和统计持久化 + * Abstract classes for persisting log information, including digest log persistence and stat log persistence * @author yangguanchao * @since 2017/07/14 */ public abstract class AbstractDiskReporter extends AbstractReporter { - /*** - * 获取 Reporter 实例类型 - * @return 类型 + /** + * Get Reporter instance type + * @return */ @Override public String getReporterType() { - //默认用摘要日志的类型作为 span 的类型 + //By default, the type of the digest log is used as the type of span return this.getDigestReporterType(); } - /*** - * 输出 span - * @param span 要被输出的 span + /** + * output span + * @param span */ @Override public void doReport(SofaTracerSpan span) { - //设置日志类型,方便打印,否则无法正确打印 + //Set the log type for easy printing, otherwise it will not print correctly. span.setLogType(this.getDigestReporterType()); if (!isDisableDigestLog(span)) { - //打印摘要日志 + //print digest log this.digestReport(span); } - //统计日志默认是不关闭的 + //print stat log this.statisticReport(span); } - /*** - * 获取摘要 Reporter 实例类型 - * @return 类型 + /** + * Get digest reporter instance type + * @return */ public abstract String getDigestReporterType(); - /*** - * 获取统计 Reporter 实例类型 - * @return 类型 + /** + * Get stat reporter instance type + * @return */ public abstract String getStatReporterType(); - /*** - * 打印摘要日志 - * @param span 被打印 span + /** + * print digest log + * @param span span */ public abstract void digestReport(SofaTracerSpan span); - /*** - * 打印统计日志 - * @param span 被统计 span + /** + * print stat log + * @param span span */ public abstract void statisticReport(SofaTracerSpan span); @@ -103,13 +103,13 @@ protected boolean isDisableDigestLog(SofaTracerSpan span) { Map disableConfiguration = SofaTracerConfiguration .getMapEmptyIfNull(SofaTracerConfiguration.DISABLE_DIGEST_LOG_KEY); - //摘要日志类型 + //digest log type String logType = StringUtils.EMPTY_STRING + span.getLogType(); if (StringUtils.isBlank(logType)) { - //摘要日志类型为空,就不打印了 + //if the digest log type is empty, it will not be printed. return true; } - // rpc-2-jvm特殊处理, 适配rpc2jvm中关闭digest而只打印stat的情况 + // Rpc-2-jvm special handling, adapting rpc2jvm to close digest and only print stat if (SofaTracerConstant.RPC_2_JVM_DIGEST_LOG_NAME.equals(logType)) { if (Boolean.FALSE.toString().equalsIgnoreCase( SofaTracerConfiguration.getProperty("enable_rpc_2_jvm_digest_log"))) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/DiskReporterImpl.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/DiskReporterImpl.java index f2368638..f9d9d03e 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/DiskReporterImpl.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/DiskReporterImpl.java @@ -31,16 +31,16 @@ import java.util.concurrent.atomic.AtomicBoolean; /** - * DiskReporterImpl - * 内部定制化实现 + * Internal customization : DiskReporterImpl * * @author yangguanchao * @since 2017/07/14 */ public class DiskReporterImpl extends AbstractDiskReporter { - /*** - * 标识初始状态: lazy 初始化磁盘文件,用到在初始化,注意并发初始化逻辑 + /** + * Identify the initial state: lazy initializes the disk file, + * used in initialization, pay attention to concurrent initialization logic */ private final AtomicBoolean isDigestFileInited = new AtomicBoolean(false); @@ -54,8 +54,9 @@ public class DiskReporterImpl extends AbstractDiskReporter { private String logNameKey; - /*** - * 统计实现,需要用户实现一个如何统计的方法,默认提供了累加的操作 + /** + * Statistical implementation, the user needs to implement a method of how to count, + * the cumulative operation is provided by default. */ private SofaTracerStatisticReporter statReporter; @@ -78,25 +79,22 @@ public DiskReporterImpl(String digestLogType, String digestRollingPolicy, statReporter, null); } - /*** - * - * @param digestLogType 日志类型 - * @param digestRollingPolicy 滚动策略 - * @param digestLogReserveConfig 保留天数配置 - * @param contextEncoder 日志输出编码 - * @param statReporter 用户需要提供统计实现 - * @param logNameKey 日志文件配置关键字 + /** + * @param digestLogType digestLogType:log type + * @param digestRollingPolicy digestRollingPolicy:digest rolling policy + * @param digestLogReserveConfig digestLogReserveConfig:Reserved days configuration + * @param contextEncoder contextEncoder:Log Encoder + * @param statReporter statReporter:User-supplied statistical log reporter implementation + * @param logNameKey logNameKey:Log file configuration keyword */ public DiskReporterImpl(String digestLogType, String digestRollingPolicy, String digestLogReserveConfig, SpanEncoder contextEncoder, SofaTracerStatisticReporter statReporter, String logNameKey) { AssertUtils.hasText(digestLogType, "digestLogType can't be empty"); - this.digestLogType = digestLogType; this.digestRollingPolicy = digestRollingPolicy; this.digestLogReserveConfig = digestLogReserveConfig; this.contextEncoder = contextEncoder; - //注册统计实现 this.statReporter = statReporter; this.logNameKey = logNameKey; } @@ -117,7 +115,7 @@ public String getDigestReporterType() { @Override public String getStatReporterType() { if (statReporter != null) { - //日志文件名字 + //get log file name return statReporter.getStatTracerName(); } return StringUtils.EMPTY_STRING; @@ -125,14 +123,14 @@ public String getStatReporterType() { @Override public void digestReport(SofaTracerSpan span) { - //lazy 初始化 + //lazy initialization if (!this.isDigestFileInited.get()) { this.initDigestFile(); } AsyncCommonDigestAppenderManager asyncDigestManager = SofaTracerDigestReporterAsyncManager .getSofaTracerDigestReporterAsyncManager(); if (asyncDigestManager.isAppenderAndEncoderExist(this.digestLogType)) { - //同时存在 appender 和 encoder 才打印 + //Print only when appender and encoder are present asyncDigestManager.append(span); } else { SelfLog.warn(span.toString() + " have no logType set, so ignore data persistence."); @@ -170,8 +168,8 @@ public String getLogNameKey() { return logNameKey; } - /*** - * 磁盘文件初始化创建完成 + /** + * Disk file initialization is completed */ private synchronized void initDigestFile() { if (this.isDigestFileInited.get()) { @@ -192,14 +190,14 @@ private synchronized void initDigestFile() { TraceAppender digestTraceAppender = LoadTestAwareAppender .createLoadTestAwareTimedRollingFileAppender(this.digestLogType, this.digestRollingPolicy, this.digestLogReserveConfig); - //注册 digest + //registry digest AsyncCommonDigestAppenderManager asyncDigestManager = SofaTracerDigestReporterAsyncManager .getSofaTracerDigestReporterAsyncManager(); if (!asyncDigestManager.isAppenderAndEncoderExist(this.digestLogType)) { asyncDigestManager.addAppender(this.digestLogType, digestTraceAppender, this.contextEncoder); } - //已经存在或者首次创建 + //Already exists or created for the first time this.isDigestFileInited.set(true); } } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/manager/SofaTracerDigestReporterAsyncManager.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/manager/SofaTracerDigestReporterAsyncManager.java index ae30a2bd..57c180b7 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/manager/SofaTracerDigestReporterAsyncManager.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/digest/manager/SofaTracerDigestReporterAsyncManager.java @@ -27,14 +27,13 @@ public final class SofaTracerDigestReporterAsyncManager { /** - * 异步日志打印,所有的中间件 摘要日志公用一个 SofaTracerDigestReporterAsyncManager AsyncAppender 来打印日志 + * Asynchronous log print, all middleware digest logs share a SofaTracerDigestReporterAsyncManager AsyncAppender to print logs */ private static volatile AsyncCommonDigestAppenderManager asyncCommonDigestAppenderManager; - /*** - * - * 异步摘要日志打印,所有的中间件公用一个 AsyncAppender 来打印日志 - * @return 全局唯一的日志打印器 + /** + * get singleton instance + * @return asyncCommonDigestAppenderManager */ public static AsyncCommonDigestAppenderManager getSofaTracerDigestReporterAsyncManager() { if (asyncCommonDigestAppenderManager == null) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/facade/AbstractReporter.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/facade/AbstractReporter.java index 7b71be22..a7f136d5 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/facade/AbstractReporter.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/facade/AbstractReporter.java @@ -23,37 +23,37 @@ /** * AbstractDiskReporter * - * 持久化抽象类,摘要持久化和统计持久化 + * Abstract class definition for the Reporter * @author yangguanchao * @since 2017/07/14 */ public abstract class AbstractReporter implements Reporter { - /*** - * 是否关闭摘要日志打印,默认不关闭,关闭意味着关闭摘要也关闭统计 + /** + * Whether to turn off digest log print, the default is not closed; + * closing means closing the digest and stat log */ private AtomicBoolean isClosePrint = new AtomicBoolean(false); - /*** - * 输出 span - * @param span 要被输出的 span + /** + * report span + * @param span */ @Override public void report(SofaTracerSpan span) { if (span == null) { return; } - //关闭所有日志打印:关闭摘要和统计 + //close print if (isClosePrint.get()) { return; } this.doReport(span); } - /*** - * 抽象方法具体输出方式落磁盘还会远程上报需要子类实现 - * - * @param span 要被输出的 span + /** + * Subclass needs to implement the report method + * @param span */ public abstract void doReport(SofaTracerSpan span); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/facade/Reporter.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/facade/Reporter.java index 2c178786..156c1e06 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/facade/Reporter.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/facade/Reporter.java @@ -26,30 +26,30 @@ */ public interface Reporter { - /*** - * 上报到远程服务器的持久化类型 + /** + * Persistence type reported to the remote server */ String REMOTE_REPORTER = "REMOTE_REPORTER"; /** - * 组合类型 + * Combined reporting type */ String COMPOSITE_REPORTER = "COMPOSITE_REPORTER"; - /*** - * 获取 Reporter 实例类型 - * @return 类型 + /** + * get reporter type + * @return */ String getReporterType(); - /*** - * 输出 span - * @param span 要被输出的 span + /** + * report span + * @param span */ void report(SofaTracerSpan span); - /*** - *关闭输出 span 的能力 + /** + * turn off output ability */ void close(); } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/AbstractSofaTracerStatisticReporter.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/AbstractSofaTracerStatisticReporter.java index 7fbd8453..38317476 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/AbstractSofaTracerStatisticReporter.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/AbstractSofaTracerStatisticReporter.java @@ -45,70 +45,59 @@ public abstract class AbstractSofaTracerStatisticReporter implements SofaTracerStatisticReporter { /** - * 默认的周期为0(从0开始),即输出间隔时间是一个周期时间(一个周期多长时间是可以设置的,默认是60s), + * The default period is 0 (starting at 0), that is, + * the output interval is a cycle time (how long a cycle can be set, the default is 60s), * {@link com.alipay.common.tracer.core.reporter.stat.manager.SofaTracerStatisticReporterManager#DEFAULT_CYCLE_SECONDS} */ public static final int DEFAULT_CYCLE = 0; /** - * 用来控制初始化槽时的并发 + * Used to control the concurrency when initializing the slot */ private static final ReentrantLock initLock = new ReentrantLock(false); - /*** - * 输出拼接器 - */ private static XStringBuilder buffer = new XStringBuilder(); - /*** - * 是否关闭统计日志打印,默认不关闭 + /** + * Whether to turn off stat log print, the default is not closed */ protected AtomicBoolean isClosePrint = new AtomicBoolean(false); - /*** - * 输出器 - */ protected TraceAppender appender = null; /** - * 统计日志的名称 + * The name of the stat log */ protected String statTracerName; - /*** - * 周期时间,一次统计数据的周期时间,单位:秒 - */ - private long periodTime; - /** - * 滚动策略 + * period time(Unit:second) */ + private long periodTime; private String rollingPolicy; - - /** - * 日志保留天数 - */ private String logReserveConfig; - /** - * 输出周期间隔,单位:次数 + * Output cycle interval */ private int printCycle = 0; + /** - * 当前已被计数的周期数,单位:次数 + * The number of cycles currently counted */ private long countCycle = 0; + /** - * "统计数据"滚动数组 + * "Statistics" scrolling array */ private Map[] statDatasPair = new ConcurrentHashMap[2]; + /** - * "统计数据"滚动数组的当前下标 + * The current subscript of the "statistics" scrolling array */ private int currentIndex = 0; /** - * 统计数据 + * Statistical data */ protected Map statDatas; @@ -124,7 +113,6 @@ public AbstractSofaTracerStatisticReporter(String statTracerName, long periodTim AssertUtils.hasText(statTracerName, "Statistics tracer name cat't be empty."); this.statTracerName = statTracerName; - //周期时间:单位秒 this.periodTime = this.globalConfiguredCycleTime(periodTime); this.printCycle = outputCycle; this.rollingPolicy = rollingPolicy; @@ -133,14 +121,14 @@ public AbstractSofaTracerStatisticReporter(String statTracerName, long periodTim this.statDatasPair[i] = new ConcurrentHashMap(100); } this.statDatas = statDatasPair[currentIndex]; - //注册定时任务并启动 + //Register a scheduled task and start SofaTracerStatisticReporterCycleTimesManager.registerStatReporter(this); } - /**** - * 获取统计日志的输出时间间隔 - * @param defaultCycle 默认间隔 60s - * @return 统计日志的时间间隔 + /** + * Get the output interval of the stat log + * @param defaultCycle default interval is 60s + * @return */ private long globalConfiguredCycleTime(long defaultCycle) { long cycleTime = defaultCycle; @@ -186,30 +174,31 @@ public void reportStat(SofaTracerSpan sofaTracerSpan) { this.doReportStat(sofaTracerSpan); } - /*** - * 执行统计操作,并调用 {@link AbstractSofaTracerStatisticReporter#addStat} - * @param sofaTracerSpan 要被统计的 span + /** + * report stat log,and call {@link AbstractSofaTracerStatisticReporter#addStat} + * @param sofaTracerSpan */ public abstract void doReportStat(SofaTracerSpan sofaTracerSpan); /** - * 默认只提供累加的统计方法 + * By default, only the accumulated stat methods are provided. * - * 向槽中更新数据 前面是唯一的key,后面是数值列 统计计算会对不同key的数值列进行加和 + * Update the data to the slot. The front is the unique key, followed by the numeric column. + * The statistical calculation adds the numeric columns of different keys. * - * @param keys 被统计 key 的唯一标示 - * @param values 被统计的值 + * @param keys Unique identifier of the key being counted + * @param values Statistical value */ protected void addStat(StatKey keys, long... values) { StatValues oldValues = statDatas.get(keys); if (oldValues == null) { - // 初始化过程,需要加锁和二次判空 + // need to lock and double judgment initLock.lock(); try { oldValues = statDatas.get(keys); - // 新增一个key,先判断是否超出最大key上限 + // check whether the maximum key limit is exceeded if (null == oldValues) { - // 本次是第一次创建该槽,创建完毕设置第一次的统计值,即可返回 + // Create a slot with specified value oldValues = new StatValues(values); statDatas.put(keys, oldValues); return; @@ -218,14 +207,14 @@ protected void addStat(StatKey keys, long... values) { initLock.unlock(); } } - // 已有其他线程创建过槽,合并新数据 + // Other threads have created slots and merge new data if (oldValues != null) { oldValues.update(values); } } /** - * 切换当前下标并返回切换前的统计数据 + * Switch the current subscript and return the stat before switching */ @Override public Map shiftCurrentIndex() { @@ -236,18 +225,19 @@ public Map shiftCurrentIndex() { } /** - * 返回当前被统计的数据 + * Return the currently statistical data * - * @return 当前被统计的数据 + * @return */ public Map getStatData() { return new HashMap(statDatas); } /** - * 获取另一组非当前正在统计的数据,总共:两组数据进行统计和打印 + * Get another set of data that is not currently being counted, + * Total: two sets of data for statistics and printing * - * @return 非当前正在统计的数据 + * @return */ public Map getOtherStatData() { return new HashMap(statDatasPair[1 - currentIndex]); @@ -261,7 +251,7 @@ public boolean shouldPrintNow() { @Override public void print(StatKey statKey, long[] values) { if (this.isClosePrint.get()) { - //关闭统计日志输出 + //Close the statistics log output return; } buffer.reset(); @@ -279,10 +269,10 @@ public void print(StatKey statKey, long[] values) { } else { appender.append(buffer.toString()); } - // 这里强制刷一次 + // Forced to flush appender.flush(); } catch (Throwable t) { - SelfLog.error("统计日志<" + statTracerName + ">输出异常", t); + SelfLog.error("Stat log <" + statTracerName + "> output error!", t); } } @@ -314,6 +304,6 @@ protected String buildString(String[] keys) { protected boolean isHttpOrMvcSuccess(String resultCode) { return resultCode.charAt(0) == '1' || resultCode.charAt(0) == '2' - || resultCode.trim().equals("302") || resultCode.trim().equals("301"); + || "302".equals(resultCode.trim()) || ("301".equals(resultCode.trim())); } } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/SofaTracerStatisticReporter.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/SofaTracerStatisticReporter.java index 1d0c3fee..94636f75 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/SofaTracerStatisticReporter.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/SofaTracerStatisticReporter.java @@ -25,54 +25,54 @@ /** * SofaTracerStatisticReporter *

- * 参考: {com.alipay.common.tracer.tracer.StatTracer} - * + * Reference: {com.alipay.common.tracer.tracer.StatTracer} + *

* @author yangguanchao * @since 2017/06/26 */ public interface SofaTracerStatisticReporter { - /*** - * 获取周期时间,即多长时间调度一次 - * @return 一次统计数据的周期时间 + /** + * get the period time + * @return */ long getPeriodTime(); - /*** - * 获取统计类型额唯一标示 - * @return 统计名称(全局唯一标识) + /** + * Get the unique identifier of the statistic type + * @return */ String getStatTracerName(); - /*** - * 向槽中更新数据 前面是唯一的key,后面是数值列 统计计算会对不同key的数值列进行加和 - * - * @param sofaTracerSpan span 上下文 + /** + * Update data to the slot + * @param sofaTracerSpan */ void reportStat(SofaTracerSpan sofaTracerSpan); - /*** - * 切换当前下标并返回切换前的统计数据 - * @return 当前时间段内的统计数据 + /** + * Switch the current subscript and return the stat before switching + * @return */ Map shiftCurrentIndex(); /** - * 当该方法被调用,说明已经过去了一个周期,要判断是否已经过去了足够的周期,是否需要flush + * When the method is called, it indicates that a cycle has passed, + * to determine whether enough cycles have passed, and whether flush is needed. * - * @return true 统计数据可以打印,框架会调用 {@link SofaTracerStatisticReporter#print} + * @return true:stat log can be printed and the framework will call {@link SofaTracerStatisticReporter#print} */ boolean shouldPrintNow(); - /*** - * 打印,即可以打印到本地磁盘,也可以上报到远程服务器 - * @param statKey 统计关键字 - * @param values 要打印的值 + /** + * Print, you can print to a local disk, or you can report to a remote server + * @param statKey + * @param values */ void print(StatKey statKey, long[] values); - /*** - * 关闭打印能力 + /** + * close print */ void close(); } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/manager/SofaTracerStatisticReporterCycleTimesManager.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/manager/SofaTracerStatisticReporterCycleTimesManager.java index 1f9f5175..895c95fd 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/manager/SofaTracerStatisticReporterCycleTimesManager.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/manager/SofaTracerStatisticReporterCycleTimesManager.java @@ -35,10 +35,9 @@ public static Map getCycleTimesManager return cycleTimesManager; } - /*** - * 周期:秒 - * 需要统一掉 - * @param statisticReporter 周期统计时间 + /** + * period: second + * @param statisticReporter statisticReporter */ public static void registerStatReporter(SofaTracerStatisticReporter statisticReporter) { SofaTracerStatisticReporterManager sofaTracerStatisticReporterManager = SofaTracerStatisticReporterCycleTimesManager @@ -48,10 +47,10 @@ public static void registerStatReporter(SofaTracerStatisticReporter statisticRep } } - /*** - * 定时任务以此为入口:获取指定周期时间的定时任务 - * @param cycleTime 周期时间单位:秒 - * @return SofaTracerStatisticReporterManager 固定周期的任务管理器 + /** + * The timed task uses this as the entry: Get the scheduled task with the specified cycle time + * @param cycleTime period: second + * @return SofaTracerStatisticReporterManager Fixed-cycle task manager */ public static SofaTracerStatisticReporterManager getSofaTracerStatisticReporterManager(Long cycleTime) { if (cycleTime == null) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/manager/SofaTracerStatisticReporterManager.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/manager/SofaTracerStatisticReporterManager.java index bfde6bdd..aec7bd52 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/manager/SofaTracerStatisticReporterManager.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/manager/SofaTracerStatisticReporterManager.java @@ -29,31 +29,35 @@ /** * SofaTracerStatisticReporterManager *

- * 固定时间周期的 Reporter,一个时钟周期对应一个实例,初始化之后就会启动周期 - * + * Reporter with a fixed time period, one clock cycle corresponds to one instance, and the cycle is started after initialization + *

* @author yangguanchao * @since 2017/06/26 */ public class SofaTracerStatisticReporterManager { /** - * 阈值,如果统计日志的数据(map格式)key个数超过该值,则清空map,非 final 为了可测性 + * Threshold, if the number of keys in the stat log (map format) exceeds this value, the map is cleared, non-final for testability */ public static int CLEAR_STAT_KEY_THRESHOLD = 5000; /** - * 默认输出周期 60 秒 + * The default output period is 60 seconds. */ - static public final long DEFAULT_CYCLE_SECONDS = 60; + public static final long DEFAULT_CYCLE_SECONDS = 60; + /** + * Thread count + */ static final AtomicInteger THREAD_NUMBER = new AtomicInteger(0); - /*** - * 每一个固定周期调度都会有这样的一个实例 + + /** + * Every fixed-cycle schedule will have such an instance. */ private Map statReporters = new ConcurrentHashMap(); - /*** - * 周期时间,默认 {@link SofaTracerStatisticReporterManager#DEFAULT_CYCLE_SECONDS}=60 s + /** + * Period time, default {@link SofaTracerStatisticReporterManager#DEFAULT_CYCLE_SECONDS}=60 s */ private long cycleTime; @@ -66,7 +70,7 @@ public class SofaTracerStatisticReporterManager { SofaTracerStatisticReporterManager(final long cycleTime) { this.cycleTime = cycleTime; this.executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - + @Override public Thread newThread(Runnable r) { final Thread thread = new Thread(r, "Tracer-TimedAppender-" + THREAD_NUMBER.incrementAndGet() + "-" @@ -82,10 +86,10 @@ private void start() { executor.scheduleAtFixedRate(new StatReporterPrinter(), 0, cycleTime, TimeUnit.SECONDS); } - /*** - * 根据名称获取统计 Reporter 实例 - * @param statTracerName 统计日志 tracer 名称 - * @return 统计实现 + /** + * Get a stat Reporter instance by statTracerName + * @param statTracerName Stat log tracer name + * @return */ public SofaTracerStatisticReporter getStatTracer(String statTracerName) { if (StringUtils.isBlank(statTracerName)) { @@ -94,9 +98,9 @@ public SofaTracerStatisticReporter getStatTracer(String statTracerName) { return statReporters.get(statTracerName); } - /*** - * 保存统计 Reporter 实例 - * @param statisticReporter 要保存的统计 Reporter 实例 + /** + * Save Stat Reporter instance + * @param statisticReporter statisticReporter */ public synchronized void addStatReporter(SofaTracerStatisticReporter statisticReporter) { if (statisticReporter == null) { @@ -114,29 +118,32 @@ public Map getStatReporters() { } class StatReporterPrinter implements Runnable { - + @Override public void run() { SofaTracerStatisticReporter st = null; try { - // 此任务默认 60 秒执行一次 + // once/60s for (SofaTracerStatisticReporter statTracer : statReporters.values()) { if (statTracer.shouldPrintNow()) { st = statTracer; - // 切换下标并获取过去一段时间的statDatas + // Switch subscripts and get statDatas for a while Map statDatas = statTracer.shiftCurrentIndex(); for (Map.Entry e : statDatas.entrySet()) { StatKey statKeys = e.getKey(); StatValues values = e.getValue(); - // 打印日志 - long tobePrint[] = values.getCurrentValue(); - // 当计数大于0的时候才打印 + // print log + long[] tobePrint = values.getCurrentValue(); + // print when the count is greater than 0 if (tobePrint[0] > 0) { statTracer.print(statKeys, tobePrint); } - // 更新槽中值,清除掉已打印内容 - values.clear(tobePrint);// 这里必须保证传入的参数是print过程中使用的数组的值 + // Update the slot value to clear the printed content + // Here you must ensure that the input params is the value of the array used in the print process. + values.clear(tobePrint); } - // 如果该统计日志的key的数量大于阈值,表示key可能有带可变参数,因此清空掉防止占用太多内存 + // If the number of keys in the statistics log is greater than the threshold, + // it indicates that the key may have variable parameters, + // so clearing it prevents taking up too much memory. if (statDatas.size() > CLEAR_STAT_KEY_THRESHOLD) { statDatas.clear(); } @@ -144,7 +151,7 @@ public void run() { } } catch (Throwable t) { if (st != null) { - SelfLog.error("统计日志<" + st.getStatTracerName() + ">flush失败", t); + SelfLog.error("Stat log <" + st.getStatTracerName() + "> flush failure.", t); } } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatKey.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatKey.java index 328b89c9..f8ef15ca 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatKey.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatKey.java @@ -25,22 +25,22 @@ public class StatKey { /** - * 统计信息的 Key + * Key for statistics */ private String key; /** - * 统计哪一类信息,Y 成功,N 失败 + * Y success,N failure */ private String result; /** - * 是否是压测的统计信息 + * Whether it is pressure measurement stat */ private boolean loadTest; /** - * 打印出来的结尾 + * Printed end */ private String end; diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatMapKey.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatMapKey.java index d2c28746..7109a650 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatMapKey.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatMapKey.java @@ -28,7 +28,7 @@ public class StatMapKey extends StatKey { /** - * 统计信息的 Key + * Key for statistic */ private Map keyMap = new HashMap(); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatValues.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatValues.java index c5374251..6e84ac9e 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatValues.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/model/StatValues.java @@ -19,19 +19,30 @@ import java.util.concurrent.atomic.AtomicReference; /** - * 不断被更新的统计数据 + * Constantly updated statistics + * *

- * 注意这里用的是CAS机制 - * 该机制用失败重试的方式代替了锁 - * 它允许多线程同时对一个原子进行修改,但是当写入新值却发现新值已被修改时,需要重新执行赋值过程,直至成功 - * 需要注意的是赋值过程是会可能被不断重复执行的,那赋值算法中唯一允许变化的就是该原子内部的属性值,其他的因数不能发生变化 - * 这样能在大部分没有并发冲突的情况下提高性能 - * 所有对AtomicReference中的值的更改,必需是写入一个全新的数组,不能直接更改原来已有数组中的值(这样才能保证是对原子进行修改) + * Note that the CAS mechanism is used here. + * This mechanism replaces the lock with a failed retry + * + * It allows multiple threads to modify an atom at the same time, + * but when a new value is written and it is found that the new value has been modified, + * the assignment process needs to be re-executed until it succeeds. + * + * + * It should be noted that the assignment process may be repeatedly executed. + * The only change allowed in the assignment algorithm is the value of the attribute inside the atom. + * Other factors cannot be changed.This can improve performance in the absence of most concurrent conflicts. + * + * All changes to the value in the AtomicReference must be written to a completely new array, + * and the values ​​in the existing array cannot be directly changed (so that the atom is modified) + *

+ * * @author zhanghan */ public class StatValues { /** - * 真实的value + * the real value */ private final AtomicReference values = new AtomicReference(); @@ -40,9 +51,9 @@ public StatValues(long[] values) { } /** - * 写入新值 - * (所有操作需满足CAS机制) - * @param update 要更新的新值 + * write new value + * (All operations need to meet the CAS mechanism) + * @param update new value need to update */ public void update(long[] update) { long[] current; @@ -57,10 +68,14 @@ public void update(long[] update) { } /** - * 打印完毕后对槽清空 - * 由于在打印期间值可能已经被更新,所以传入需要被clear的数值数组,减去已被打印的值 - * (所有操作需满足CAS机制) - * @param toBeClear long 数组 + * Empty the slot after print + * + * The value may have been updated during printing + * So pass in the array of values ​​that need to be cleared, minus the value that has been printed. + * + * (All operations need to meet the CAS mechanism) + * + * @param toBeClear toBeClear */ public void clear(long[] toBeClear) { long[] current; @@ -74,11 +89,12 @@ public void clear(long[] toBeClear) { } /** - * 返回当前值 - * 这里可以直接get并返回,返回的值肯定不会改变 - * 因为任何对values这个原子的改变都是直接覆盖数组的引用地址 - * 而不会更新数组中的值 - * @return long 数组 + * Return current value + * + * Here you can get and return directly, the returned value will definitely not change + * Because any change to the atoms of values ​​is directly over the reference address of the array. + * and does not update the values ​​in the array. + * @return */ public long[] getCurrentValue() { return values.get(); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/type/TracerSystemLogEnum.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/type/TracerSystemLogEnum.java index 807af023..4443a8b2 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/type/TracerSystemLogEnum.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/type/TracerSystemLogEnum.java @@ -24,34 +24,21 @@ */ public enum TracerSystemLogEnum { - /*** - * 性能日志 - */ + /** Profile log */ RPC_PROFILE("rpc_profile_log_name", "rpc-profile.log", "rpc_profile_rolling"), + /** Business success log */ + BIZ_SUCCESS("biz_success_log_name", "biz_success.log", "biz_success_rolling"), + /** Business fail log */ + BIZ_FAIL("biz_fail_log_name", "biz_fail.log", "biz_fail_rolling"), - // 其他日志 - BIZ_SUCCESS("biz_success_log_name", "biz_success.log", "biz_success_rolling"), // 业务成功日志 - BIZ_FAIL("biz_fail_log_name", "biz_fail.log", "biz_fail_rolling"), // 业务异常日志 - - /*** - * 中间件错误日志 - */ + /** Middleware error log */ MIDDLEWARE_ERROR("middleware_error_log_name", "middleware_error.log", "middleware_error_rolling"); - /*** - * 获取保留天数 getLogReverseDay 关键字 - */ private String logReverseKey; - /*** - * 默认生成的日志名字 .log 结尾同时作为一个类型 - */ private String defaultLogName; - /*** - * 日志的滚动策略 - */ private String rollingKey; TracerSystemLogEnum(String logReverseKey, String defaultLogName, String rollingKey) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/Sampler.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/Sampler.java index 3f126daa..a3fc125b 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/Sampler.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/Sampler.java @@ -19,12 +19,17 @@ import com.alipay.common.tracer.core.span.SofaTracerSpan; public interface Sampler { + /** * @param sofaTracerSpan The operation name set on the span * @return whether or not the new trace should be sampled */ SamplingStatus sample(SofaTracerSpan sofaTracerSpan); + /** + * get sampler type + * @return + */ String getType(); /** diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplingStatus.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplingStatus.java index 1807f3f6..27ff9985 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplingStatus.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SamplingStatus.java @@ -23,8 +23,8 @@ public class SamplingStatus { private boolean isSampled = false; - /*** - * 允许在 RootSpan 处放置 tags + /** + * Allow tags to be placed at RootSpan */ private Map tags = new HashMap(); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSampler.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSampler.java index ec964279..8724d521 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSampler.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/samplers/SofaTracerPercentageBasedSampler.java @@ -77,9 +77,9 @@ public void close() { * Reservoir sampling algorithm borrowed from Stack Overflow. *

* http://stackoverflow.com/questions/12817946/generate-a-random-bitset-with-n-1s - * @param size 大小 - * @param cardinality 基数 - * @param rnd 随机种子 + * @param size + * @param cardinality + * @param rnd * @return BitSet */ public static BitSet randomBitSet(int size, int cardinality, Random rnd) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonLogSpan.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonLogSpan.java index 4ca114f5..6ccb8b80 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonLogSpan.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonLogSpan.java @@ -29,9 +29,10 @@ /** * CommonLogSpan * - * 主要为了记录具体的顺序数据 + * Mainly for recording specific sequential data * - * 之所以要新创建一个对象,主要是为了区分 CommonLogSpan 和日常摘要等的打印 + * + * The reason to create a new object is to distinguish between the printing of CommonLogSpan and daily digest. * * com.alipay.common.tracer.core.span.LogData#EVENT_COMMON_TYPE_VALUE * @@ -42,14 +43,15 @@ public class CommonLogSpan extends SofaTracerSpan { private static final int MAX_SLOT_SIZE = 32; - /** 通用的槽位,需要打印的日志数据全部都放到这里面 */ + /** + * The common slot, all the log data that needs to be printed are placed in it. + */ private List slots = new ArrayList(); private AtomicInteger slotCounter = new AtomicInteger(0); public CommonLogSpan(SofaTracer sofaTracer, long startTime, String operationName, SofaTracerSpanContext sofaTracerSpanContext, Map tags) { - //SofaTracer 可以 mock 在 此中,因为打印是通过显示 report this(sofaTracer, startTime, null, operationName, sofaTracerSpanContext, tags); } @@ -57,13 +59,12 @@ public CommonLogSpan(SofaTracer sofaTracer, long startTime, List spanReferences, String operationName, SofaTracerSpanContext sofaTracerSpanContext, Map tags) { - //SofaTracer 可以 mock 在 此中,因为打印是通过显示 report super(sofaTracer, startTime, spanReferences, operationName, sofaTracerSpanContext, tags); } /** - * 往 Slots 中增加一项需要打印的内容 - * @param slot 槽位 + * Add an item to Slots that needs to be printed + * @param slot */ public void addSlot(String slot) { if (slot == null) { @@ -73,21 +74,21 @@ public void addSlot(String slot) { if (slotCounter.incrementAndGet() <= MAX_SLOT_SIZE) { slots.add(slot); } else { - SelfLog.warn("槽位数量(" + MAX_SLOT_SIZE + ")已满"); + SelfLog.warn("Slots count(" + MAX_SLOT_SIZE + ")Fully"); } } /** - * 获取所有需要打印的内容 - * @return 栏位列表 + * Get all the content you need to print + * @return */ public List getSlots() { return slots; } - /*** - * 添加 slot 列表 - * @param stringArrayList slot 列表 + /** + * Add slot list + * @param stringArrayList */ public void addSlots(List stringArrayList) { if (stringArrayList == null || stringArrayList.isEmpty()) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/LogData.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/LogData.java index 69456c62..fe2f845e 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/LogData.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/LogData.java @@ -20,8 +20,8 @@ public final class LogData { - /*** - * 事件类型关键字 @Nullable cs/cr/ss/sr ,去掉单独字段,使用统一 map 操作 + /** + * Event type keyword @Nullable cs/cr/ss/sr */ public static final String EVENT_TYPE_KEY = "event"; 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 532f5727..01cfa7e6 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 @@ -46,15 +46,12 @@ public class SofaTracerSpan implements Span { private final SofaTracer sofaTracer; - /*** - * tags String,Integer,boolean - */ private final List spanReferences; - + /** tags for String */ private final Map tagsWithStr = new LinkedHashMap(); - + /** tags for Boolean */ private final Map tagsWithBool = new LinkedHashMap(); - + /** tags for Number */ private final Map tagsWithNumber = new LinkedHashMap(); private final List logs = new LinkedList(); @@ -63,24 +60,18 @@ public class SofaTracerSpan implements Span { private final SofaTracerSpanContext sofaTracerSpanContext; - /*** - * 启动时间 - */ private long startTime; - - /*** - * span endTime - */ private long endTime = -1; - /*** - * - * report时才有意义:摘要日志类型,日志能够正确打印的关键信息:当前 span 的日志类型,如:客户端为 rpc-client-digest.log,服务端为 rpc-server-digest.log + /** + * Only meaningful when reporting + * Digest log type,The logs correctly printed key information. + * For example, the client is rpc-client-digest.log and the server is rpc-server-digest.log */ private String logType = StringUtils.EMPTY_STRING; - /*** - * 父亲 span,当作为客户端结束并弹出线程上下文时,需要将父亲 span 再放入 + /** + * parent span. Describe the child-of relationship */ private SofaTracerSpan parentSofaTracerSpan = null; @@ -104,37 +95,36 @@ public SofaTracerSpan cloneInstance() { return cloneSpan; } - /*** - * 作为服务端:还原回 {@link SofaTracerSpanContext} 之后,就可以直接构造 Server Span(traceId,spanId 不变) + /** + * As a server-Side(Kind.type is server): After reverting back to {@link SofaTracerSpanContext}, + * you can directly construct Server Span (traceId, spanId unchanged) * - * @param sofaTracer sofaTracer 当前具体中间件 tracer - * @param startTime 开始时间 - * @param operationName 操作名称 - * @param sofaTracerSpanContext 当前上下文信息 - * @param tags 标签 + * @param sofaTracer sofaTracer + * @param startTime startTime + * @param operationName operationName + * @param sofaTracerSpanContext sofaTracerSpanContext + * @param tags tags */ public SofaTracerSpan(SofaTracer sofaTracer, long startTime, String operationName, SofaTracerSpanContext sofaTracerSpanContext, Map tags) { - //作为服务端还原回 sofaTracerSpanContext,traceId:spanId 不变,所以 spanReferences 为空 this(sofaTracer, startTime, null, operationName, sofaTracerSpanContext != null ? sofaTracerSpanContext : SofaTracerSpanContext .rootStart(), tags); } - /*** - * 注意: - * - * 1.作为服务端:还原回 {@link SofaTracerSpanContext} 之后,就可以直接构造 Server Span(traceId,spanId 不变) + /** + * Note: * + * 1.As a server-side: After reverting back to {@link SofaTracerSpanContext}, you can directly construct Server Span (traceId, spanId unchanged) * - * 2.作为客户端:需要通过 {@link SofaTracer.SofaTracerSpanBuilder#start() 构建} + * 2.As a client: need to be built by {@link SofaTracer.SofaTracerSpanBuilder#start()} * - * @param sofaTracer 当前 tracer - * @param startTime 开始时间 - * @param spanReferences 引用关系 - * @param operationName 操作名称 - * @param sofaTracerSpanContext 当前上下文 - * @param tags 标签 + * @param sofaTracer sofaTracer + * @param startTime startTime + * @param spanReferences spanReferences + * @param operationName operationName + * @param sofaTracerSpanContext sofaTracerSpanContext + * @param tags tags */ public SofaTracerSpan(SofaTracer sofaTracer, long startTime, List spanReferences, @@ -148,7 +138,6 @@ public SofaTracerSpan(SofaTracer sofaTracer, long startTime, spanReferences) : null; this.operationName = operationName; this.sofaTracerSpanContext = sofaTracerSpanContext; - //tags this.setTags(tags); SpanExtensionFactory.logStartedSpan(this); @@ -167,7 +156,7 @@ public void finish() { @Override public void finish(long endTime) { this.setEndTime(endTime); - //关键记录:report span + //Key record:report span this.sofaTracer.reportSpan(this); SpanExtensionFactory.logStoppedSpan(this); } @@ -183,7 +172,7 @@ public Span setTag(String key, String value) { return this; } this.tagsWithStr.put(key, value); - //注意:server 还是 client 在 OpenTracing 标准中是用 tags 标识的,所以在这里进行判断 + //to set log type by span kind type if (isServer()) { Reporter serverReporter = this.sofaTracer.getServerReporter(); if (serverReporter != null) { @@ -215,18 +204,15 @@ public Span setTag(String key, Number number) { @Override public Span log(String eventValue) { - //使用默认的 event key,关键记录 span 事件:cs/cr/ss/sr + //log with current time return log(System.currentTimeMillis(), eventValue); } @Override public Span log(long currentTime, String eventValue) { - //关键记录 span 事件 AssertUtils.isTrue(currentTime >= startTime, "Current time must greater than start time"); - //记录下相关事件 Map fields = new HashMap(); fields.put(LogData.EVENT_TYPE_KEY, eventValue); - //save return this.log(currentTime, fields); } @@ -265,11 +251,12 @@ public Span log(long currentTime, String eventName, /* @Nullable */Object payloa return this.log(currentTime, fields); } - /*** - * 默认设置和读取的都是业务 baggage - * @param key 关键字 - * @param value 值 - * @return 当前 span + /** + * + * The default settings are business baggage + * @param key + * @param value + * @return */ @Override public Span setBaggageItem(String key, String value) { @@ -277,10 +264,10 @@ public Span setBaggageItem(String key, String value) { return this; } - /*** - * 默认设置和读取的都是业务 baggage - * @param key 关键字 - * @return 当前 span + /** + * The default read are business baggage + * @param key + * @return */ @Override public String getBaggageItem(String key) { @@ -293,32 +280,32 @@ public Span setOperationName(String operationName) { return this; } - //=======================扩展的 API 接口开始 + //======================= Extended API interface starts - /*** + /** * - * @param errorType errorType error 描述:timeout_error/biz_error... - * @param context context 记录的上下文信息 - * @param e e 异常信息 - * @param errorSourceApp errorSources 故障源 trade|rpc - * @param errorSources errorSources 故障源数组 + * @param errorType errorType error description:timeout_error/biz_error... + * @param context context + * @param e e + * @param errorSourceApp errorSourceApp trade|rpc + * @param errorSources errorSources */ public void reportError(String errorType, Map context, Throwable e, String errorSourceApp, String... errorSources) { Tags.ERROR.set(this, true); - //关键:用于记录所有的持久化数据 + //all tags set Map tags = new HashMap(); tags.putAll(this.getTagsWithStr()); tags.putAll(this.getTagsWithBool()); tags.putAll(this.getTagsWithNumber()); tags.put(SpanTags.CURR_APP_TAG.getKey(), errorSourceApp); - //构造新的 + //Construct new CommonLogSpan CommonLogSpan commonLogSpan = new CommonLogSpan(this.sofaTracer, System.currentTimeMillis(), this.getOperationName(), this.getSofaTracerSpanContext(), tags); commonLogSpan.addSlot(Thread.currentThread().getName()); commonLogSpan.addSlot(errorType); - // 业务定制的输出中可能会有分隔符,现在将分割符替换成相应的转义字符 + // There may be a separator in the output of the business customization, now replace the separator with the corresponding escape character commonLogSpan.addSlot(StringUtils.arrayToString(errorSources, ARRAY_SEPARATOR, "", "")); commonLogSpan.addSlot(StringUtils.mapToString(context)); commonLogSpan.addSlot(this.getSofaTracerSpanContext() == null ? StringUtils.EMPTY_STRING @@ -329,29 +316,25 @@ public void reportError(String errorType, Map context, Throwable } else { StringWriter sw = new StringWriter(256); e.printStackTrace(new PrintWriter(sw)); - // 同上 String exception = sw.getBuffer().toString(); commonLogSpan.addSlot(exception); } - //report error 使用客户端服务端tags进行区分 CommonTracerManager.reportError(commonLogSpan); } /** - * 打印 Common Profile 日志 + * Print Common Profile Log * - * @param profileApp profile 应用 - * @param protocolType 协议类型 - * @param profileMessage 日志内容 + * @param profileApp profileApp + * @param protocolType protocolType + * @param profileMessage profileMessage */ public void profile(String profileApp, String protocolType, String profileMessage) { - //关键:用于记录所有的持久化数据 Map tags = new HashMap(); tags.putAll(this.getTagsWithStr()); tags.putAll(this.getTagsWithBool()); tags.putAll(this.getTagsWithNumber()); tags.put(SpanTags.CURR_APP_TAG.getKey(), profileApp); - //构造新的,关键:用于记录所有的持久化数据 CommonLogSpan commonLogSpan = new CommonLogSpan(this.sofaTracer, System.currentTimeMillis(), this.getOperationName(), this.getSofaTracerSpanContext(), tags); @@ -363,26 +346,27 @@ public void profile(String profileApp, String protocolType, String profileMessag } /** - * 返回自身作为下一个上下文的 parent + * Return itself as the parent of the next context *

- * 采用 countMatches 来对 . 进行计数, 以获取更高的性能, 见com.alipay.common.tracer.benchmark.CountBenchmark 的性能测试数据 - * 防止 SofaTracerSpan 嵌套过深导致内存泄漏。这个时候重新创建一个上下文,使上面的上下文都能够释放。 - * - * @return 重新构造的 span + * Use countMatches to count . for higher performance, see performance test data for com.alipay.common.tracer.benchmark.CountBenchmark + + * Preventing SofaTracerSpan from nesting too deeply causes a memory leak. + * This time recreates a context so that the above context can be released. + *

+ * @return */ public SofaTracerSpan getThisAsParentWhenExceedLayer() { final SofaTracerSpan parent; String rpcId = this.sofaTracerSpanContext.getSpanId(); if (StringUtils.countMatches(rpcId, '.') + 1 > SofaTracerConstant.MAX_LAYER) { SofaTracerSpanContext parentSpanContext = SofaTracerSpanContext.rootStart(); - // 虽然重新创建一个 Span, 但是穿透数据没有必要丢掉;但是丢弃 tags + // discard tags Map baggage = new HashMap(); baggage.putAll(this.sofaTracerSpanContext.getBizBaggage()); parentSpanContext.addBizBaggage(baggage); - //重新构造 parent = new SofaTracerSpan(this.sofaTracer, System.currentTimeMillis(), this.operationName, parentSpanContext, null); - // 在日志中进行记录, 防止发生了这个情况却无法快速知晓 + // Record in the log to prevent this from happening but not to know quickly SelfLog.errorWithTraceId("OpenTracing Span layer exceed max layer limit " + SofaTracerConstant.MAX_LAYER, this.sofaTracerSpanContext.getTraceId()); @@ -393,7 +377,7 @@ public SofaTracerSpan getThisAsParentWhenExceedLayer() { return parent; } - //=======================扩展的 API 接口结束 + //======================= Extended API interface end public List getSpanReferences() { if (spanReferences == null) { @@ -491,7 +475,6 @@ private void setTags(Map tags) { continue; } if (value instanceof String) { - //初始化时候,tags也可以作为 client 和 server 的判断依据 this.setTag(key, (String) value); } else if (value instanceof Boolean) { this.setTag(key, (Boolean) value); diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/SofaTracerSpanReferenceRelationship.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/SofaTracerSpanReferenceRelationship.java index e999d9fc..733c6d90 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/SofaTracerSpanReferenceRelationship.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/SofaTracerSpanReferenceRelationship.java @@ -24,7 +24,7 @@ * SofaTracerSpanReferenceRelationship *

* {@link io.opentracing.References} - * + *

* @author yangguanchao * @since 2017/06/17 */ @@ -32,7 +32,7 @@ public class SofaTracerSpanReferenceRelationship { private SofaTracerSpanContext sofaTracerSpanContext; - /*** + /** * {@link io.opentracing.References} */ private String referenceType; diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/tags/SpanTags.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/tags/SpanTags.java index 4e57dce4..14fd5a9c 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/tags/SpanTags.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/tags/SpanTags.java @@ -26,8 +26,8 @@ */ public class SpanTags { - /*** - * 当前应用名称 + /** + * current span tags */ public static final StringTag CURR_APP_TAG = new StringTag("curr.app"); } 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 74307df2..73f6afe3 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 @@ -50,7 +50,6 @@ public AbstractTracer(String tracerType) { public AbstractTracer(String tracerType, boolean clientTracer, boolean serverTracer) { SofaTracer.Builder builder = new SofaTracer.Builder(tracerType); - //构造 client 的日志打印实例 if (clientTracer) { Reporter clientReporter = this.generateReporter(this.generateClientStatReporter(), this.getClientDigestReporterLogName(), this.getClientDigestReporterRollingKey(), @@ -59,7 +58,6 @@ public AbstractTracer(String tracerType, boolean clientTracer, boolean serverTra builder.withClientReporter(clientReporter); } } - //构造 server 的日志打印实例 if (serverTracer) { Reporter serverReporter = this.generateReporter(this.generateServerStatReporter(), this.getServerDigestReporterLogName(), this.getServerDigestReporterRollingKey(), @@ -75,10 +73,8 @@ public AbstractTracer(String tracerType, boolean clientTracer, boolean serverTra protected Reporter generateReporter(AbstractSofaTracerStatisticReporter statReporter, String logName, String logRollingKey, String logNameKey, SpanEncoder spanEncoder) { - //构造摘要实例 String digestRollingPolicy = SofaTracerConfiguration.getRollingPolicy(logRollingKey); String digestLogReserveConfig = SofaTracerConfiguration.getLogReserveConfig(logNameKey); - //构造实例 DiskReporterImpl reporter = new DiskReporterImpl(logName, digestRollingPolicy, digestLogReserveConfig, spanEncoder, statReporter, logNameKey); return reporter; @@ -197,7 +193,7 @@ public SofaTracerSpan serverReceive() { /** * server receive request - * @param sofaTracerSpanContext 要恢复的上下文 + * @param sofaTracerSpanContext The context to restore * @return SofaTracerSpan */ public SofaTracerSpan serverReceive(SofaTracerSpanContext sofaTracerSpanContext) { diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ByteArrayUtils.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ByteArrayUtils.java index ae970ac9..5783a644 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ByteArrayUtils.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ByteArrayUtils.java @@ -25,51 +25,37 @@ public class ByteArrayUtils { /** - * 查找指定数组的起始索引 + * Find the starting index of the specified array * - * @param org of type byte[] 原数组 - * @param search of type byte[] 要查找的数组 - * @return int 返回索引 + * @param org of type byte[] origin byte array + * @param search of type byte[] target array + * @return */ - public static int indexOf(byte[] org, byte[] search) { - return indexOf(org, search, 0); - } /** - * 查找指定数组的起始索引 + * Find the starting index of the specified array * - * @param org of type byte[] 原数组 - * @param search of type byte[] 要查找的数组 - * @param startIndex 起始索引 - * @return int 返回索引 + * @param org of type byte[] origin byte array + * @param search of type byte[] target array + * @param startIndex startIndex + * @return */ - public static int indexOf(byte[] org, byte[] search, int startIndex) { - KMPMatcher kmpMatcher = new KMPMatcher(); - kmpMatcher.computeFailure4Byte(search); - return kmpMatcher.indexOf(org, startIndex); } /** - * KMP算法类 - *

- *

- *

+ * KMP * Created on 2017-08-04 */ - static class KMPMatcher { - private int[] failure; - private int matchPoint; - private byte[] bytePattern; /** @@ -79,113 +65,69 @@ static class KMPMatcher { * @param startIndex of type int * @return int */ - public int indexOf(byte[] text, int startIndex) { - int j = 0; - if (text.length == 0 || startIndex > text.length) { return -1; } - for (int i = startIndex; i < text.length; i++) { - while (j > 0 && bytePattern[j] != text[i]) { - j = failure[j - 1]; - } - if (bytePattern[j] == text[i]) { - j++; - } - if (j == bytePattern.length) { - matchPoint = i - bytePattern.length + 1; - return matchPoint; - } - } - return -1; } /** - * 找到末尾后重头开始找 + * After finding the end, start looking for it again. * * @param text of type byte[] * @param startIndex of type int * @return int */ - public int lastIndexOf(byte[] text, int startIndex) { - matchPoint = -1; - int j = 0; - if (text.length == 0 || startIndex > text.length) { return -1; } - int end = text.length; - for (int i = startIndex; i < end; i++) { - while (j > 0 && bytePattern[j] != text[i]) { - j = failure[j - 1]; - } - if (bytePattern[j] == text[i]) { - j++; - } - if (j == bytePattern.length) { - matchPoint = i - bytePattern.length + 1; - if ((text.length - i) > bytePattern.length) { - j = 0; - continue; - } - return matchPoint; - } - - //如果从中间某个位置找,找到末尾没找到后,再重头开始找 - + //If you find it from a position in the middle, if you don’t find it at the end, then start looking for it again. if (startIndex != 0 && i + 1 == end) { - end = startIndex; - i = -1; - startIndex = 0; - } - } - return matchPoint; - } /** - * 找到末尾后不会重头开始找 + * + * It won’t start looking for it after find the end. * * @param text of type byte[] * @param startIndex of type int @@ -193,86 +135,48 @@ public int lastIndexOf(byte[] text, int startIndex) { */ public int lastIndexOfWithNoLoop(byte[] text, int startIndex) { - matchPoint = -1; - int j = 0; - if (text.length == 0 || startIndex > text.length) { return -1; } - for (int i = startIndex; i < text.length; i++) { - while (j > 0 && bytePattern[j] != text[i]) { - j = failure[j - 1]; - } - if (bytePattern[j] == text[i]) { - j++; - } - if (j == bytePattern.length) { - matchPoint = i - bytePattern.length + 1; - if ((text.length - i) > bytePattern.length) { - j = 0; - continue; - } - return matchPoint; - } - } - return matchPoint; - } /** * Method computeFailure4Byte … - * * @param patternStr of type byte[] */ - public void computeFailure4Byte(byte[] patternStr) { - bytePattern = patternStr; - int j = 0; - int len = bytePattern.length; - failure = new int[len]; - for (int i = 1; i < len; i++) { - while (j > 0 && bytePattern[j] != bytePattern[i]) { - j = failure[j - 1]; - } - if (bytePattern[j] == bytePattern[i]) { - j++; - } - failure[i] = j; - } - } - } } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/CommonUtils.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/CommonUtils.java index bd3a3351..a0111c9a 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/CommonUtils.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/CommonUtils.java @@ -27,24 +27,23 @@ public class CommonUtils { private static int LONG_BYTES = Long.SIZE / 8; private static int LONG_HEX_STRING_BYTES = LONG_BYTES * 2; - /*** - * 取数值 - * @param num 数字 - * @param defaultInt 默认值 - * @param 类型 Number - * @return Number + /** + * Take the value + * @param num + * @param defaultInt + * @param Number + * @return T */ public static T parseNum(T num, T defaultInt) { return num == null ? defaultInt : num; } - /*** + /** * Convert a hex string to a array containing two unsigned long elements * @param hexString hex string * @return long array: [0] -- High 64 bit, [1] -- low 64 bit */ public static long[] hexToDualLong(String hexString) { - //Assert.hasText(hexString, "Can't convert empty hex string to long"); int length = hexString.length(); if (length < 1) { throw new IllegalArgumentException("Malformed id(length must be more than zero): " @@ -76,13 +75,12 @@ public static long[] hexToDualLong(String hexString) { return result; } - /*** + /** * Convert a hex string to a unsigned long * @param hexString hex string * @return long */ public static long hexToLong(String hexString) { - //Assert.hasText(hexString, "Can't convert empty hex string to long"); int length = hexString.length(); if (length < 1) { throw new IllegalArgumentException("Malformed id(length must be more than zero): " @@ -106,7 +104,7 @@ public static long hexToLong(String hexString) { return result; } - /*** + /** * Judge if a string is hex string * @param str string * @return boolean diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ReflectionUtils.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ReflectionUtils.java index 49b7c3ea..8eea9a40 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ReflectionUtils.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/ReflectionUtils.java @@ -17,10 +17,7 @@ package com.alipay.common.tracer.core.utils; import java.lang.reflect.Method; -import java.lang.reflect.Modifier; import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; /** * @author qilong.zql diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/StringUtils.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/StringUtils.java index 38f57b84..4b8facce 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/StringUtils.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/StringUtils.java @@ -57,11 +57,6 @@ public class StringUtils { private static final String CURRENT_PATH = "."; - /*** - * 字符串是否为空 - * @param str 字符串 - * @return true : 字符串为空 - */ public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { @@ -75,23 +70,16 @@ public static boolean isBlank(String str) { return true; } - /** - * 字符串是否不为空 - * - * @param str 字符串 - * @return true : 非空 - */ public static boolean isNotBlank(String str) { return !isBlank(str); } /** - *

- * 将map转成string并在每一个 key 添加指定的前缀, 如 {"k1":"v1"} - *

- * @param map map 要映射的集合 - * @param prefix prefix 前缀 - * @return 字符串携带指定前缀 prefix_k1=v1 + * Convert the map to a string and add the specified prefix to each key, such as {"k1":"v1"} + * + * @param map origin data + * @param prefix prefix + * @return */ public static String mapToStringWithPrefix(Map map, String prefix) { StringBuilder sb = new StringBuilder(XStringBuilder.DEFAULT_BUFFER_SIZE); @@ -113,11 +101,10 @@ public static String mapToStringWithPrefix(Map map, String prefi } /** - *

- * 将map转成string, 如{"k1":"v1"} - *

- * @param map 要映射的集合 - * @return 字符串 k1=v1 + * Convert the map to a string, such as {"k1":"v1"} + * + * @param map origin data + * @return */ public static String mapToString(Map map) { StringBuilder sb = new StringBuilder(XStringBuilder.DEFAULT_BUFFER_SIZE); @@ -136,16 +123,14 @@ public static String mapToString(Map map) { } /** - * 由string转成map, 函数 mapToString 的逆过程 - * @param str 字符串 - * @param map 映射的集合 + * Convert from string to map, the inverse of the function mapToString + * @param str origin data + * @param map default result */ public static void stringToMap(String str, Map map) { - if (isBlank(str)) { return; } - String key = null; String value = null; int mark = -1; @@ -188,15 +173,15 @@ public static String unescapeComma(String str) { } /** - * @param items 列表 - * @param separator 分隔符 - * @param prefix 前缀 - * @param postfix 后缀 - * @return 字符串 + * Array to string + * @param items origin data + * @param separator separator + * @param prefix prefix + * @param postfix postfix + * @return */ public static String arrayToString(Object[] items, char separator, String prefix, String postfix) { String emptyArrayString = (EMPTY_STRING + prefix) + postfix; - // handle null, zero and one elements before building a buffer if (items == null) { return emptyArrayString; @@ -231,24 +216,34 @@ public static String arrayToString(Object[] items, char separator, String prefix return buf.toString(); } - //替换str中的"&","=" 和 "%" + /** + * Replace "&"、"=" and "%" + * @param str origin data + */ public static String escapePercentEqualAnd(String str) { - // 必须先对 % 做转义 + //You must first escape the % return escape( escape(escape(str, PERCENT, PERCENT_ESCAPE), AND_SEPARATOR, AND_SEPARATOR_ESCAPE), EQUAL_SEPARATOR, EQUAL_SEPARATOR_ESCAPE); } - //将 str 中被转义的 & , = 和 % 转义回来 + /** + * escapePercentEqualAnd's Reverse Operation + * @param str + * @return + */ public static String unescapeEqualAndPercent(String str) { - // 必须最后才对 % 做转义 + // You must first escape the % return escape( escape(escape(str, EQUAL_SEPARATOR_ESCAPE, EQUAL_SEPARATOR), AND_SEPARATOR_ESCAPE, AND_SEPARATOR), PERCENT_ESCAPE, PERCENT); } /** - * 将str中的oldStr替换为newStr + * Replace oldStr in str with newStr + * @param str target origin data + * @param oldStr oldStr + * @param newStr newStr */ private static String escape(String str, String oldStr, String newStr) { if (str == null) { @@ -468,25 +463,23 @@ public static String replace(String inString, String oldPattern, String newPatte return sb.toString(); } - /*** - * 对指定的字符串中出现的字符进行计数 - * @param str 要被统计的字符串 - * @param c 出现的字符 - * @return 个数 + /** + * Counts the characters that appear in the specified string + * + * @param str target str + * @param c target char c + * @return */ public static int countMatches(String str, char c) { if (str == null || str.length() == 0) { return 0; } - int count = 0; - for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == c) { count++; } } - return count; } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/TracerUtils.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/TracerUtils.java index 8e4021b1..2de717cd 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/TracerUtils.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/utils/TracerUtils.java @@ -30,7 +30,7 @@ import java.util.TimeZone; /** - * Tracer 的工具类,此工具类是一个内部工具类,非 Tracer 相关 JAR 包请不要依赖。 + * Tracer's tool class, this tool class is an internal tool class, please do not rely on non-Tracer related JAR packages. * * @author khotyn 4/4/14 1:39 PM */ @@ -71,10 +71,10 @@ public static String getTraceId() { } /** - * @param sofaTracerSpan 要检验的 span - * @param key 关键字 + * @param sofaTracerSpan sofaTracerSpan + * @param key key * @param value value - * @return true 满足长度要求 + * @return */ public static boolean checkBaggageLength(SofaTracerSpan sofaTracerSpan, String key, String value) { int length = sofaTracerSpan.getSofaTracerSpanContext().getBizSerializedBaggage().length(); @@ -90,9 +90,9 @@ public static boolean checkBaggageLength(SofaTracerSpan sofaTracerSpan, String k } /** - * 系统穿透数据长度可以通过不同的-D来设置 + * System penetration data length can be set by different -D parameters * - * @return 整数值 + * @return */ public static int getSysBaggageMaxLength() { if (TRACER_SYSTEM_PENETRATE_ATTRIBUTE_MAX_LENGTH < 0) { @@ -131,11 +131,12 @@ public static int getBaggageMaxLength() { } /** - * 此方法在 JDK9 下可以有更加好的方式,但是目前的几个 JDK 版本下,只能通过这个方式来搞。 - * 在 Mac 环境下,JDK6,JDK7,JDK8 都可以跑过。 - * 在 Linux 环境下,JDK6,JDK7,JDK8 尝试过,可以运行通过。 + * This method can be a better way under JDK9, but in the current JDK version, it can only be implemented in this way. * - * @return 进程 ID + * In Mac OS , JDK6,JDK7,JDK8 ,it's OK + * In Linux OS,JDK6,JDK7,JDK8 ,it's OK + * + * @return Process ID */ public static String getPID() { //check pid is cached @@ -202,7 +203,7 @@ public static String getLoadTestMark(SofaTracerSpan span) { if (TracerUtils.isLoadTest(span)) { return SofaTracerConstant.LOAD_TEST_VALUE; } else { - //非压测 + //non-pressure test return SofaTracerConstant.NON_LOAD_TEST_VALUE; } } @@ -231,13 +232,10 @@ public static String removeJSessionIdFromUrl(String url) { if (url == null) { return null; } - int index = url.indexOf(";jsessionid="); - if (index < 0) { return url; } - return url.substring(0, index); } @@ -250,11 +248,11 @@ public static String getDefaultTimeZone() { } /** - * 从 Map 中获取一个 value,如果获取出来是 null,则返回一个空字符串 + * Get a value from the Map, or return an empty string if it is null * - * @param map 要映射的 map - * @param key 关键字 - * @return 字符串 + * @param map map + * @param key key + * @return */ public static String getEmptyStringIfNull(Map map, String key) { String value = map.get(key); @@ -262,10 +260,10 @@ public static String getEmptyStringIfNull(Map map, String key) { } /** - * 将一个 Host 地址转换成一个 16 进制数字 + * Convert a Host address to a hexadecimal number * - * @param host 主机地址 - * @return 将一个 Host 地址转换成一个 16 进制数字 + * @param host host address + * @return hexadecimal number */ public static String hostToHexString(String host) { //NOPMD return Integer.toHexString(host.hashCode()); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/TestUtil.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/TestUtil.java index 9c246dfc..b744e667 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/TestUtil.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/TestUtil.java @@ -32,17 +32,14 @@ public static boolean compareSlotMap(String a, String b) { StringUtils.stringToMap(a, aMap); Map bMap = new HashMap(); StringUtils.stringToMap(b, bMap); - if (aMap.size() != bMap.size()) { return false; } - for (String aKey : aMap.keySet()) { if (!aMap.get(aKey).equals(bMap.get(aKey))) { return false; } } - return true; } diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/LogCleanupTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/LogCleanupTest.java index 26eda294..631f621a 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/LogCleanupTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/LogCleanupTest.java @@ -27,9 +27,9 @@ import java.util.Calendar; /** - * 测试日志的清理功能 + * Test log cleanup function * - * @author khotyn 15/2/16 下午3:50 + * @author khotyn 15/2/16 PM 3:50 */ public class LogCleanupTest extends AbstractTestBase { @@ -42,41 +42,37 @@ public class LogCleanupTest extends AbstractTestBase { private File fiveDayAgoFile = null; @Test - public void 测试清理日志_按天滚动() throws IOException { + public void test_cleanup_log_scroll_by_day() throws IOException { generateLogFilesToBeCleanup(new SimpleDateFormat( TimedRollingFileAppender.DAILY_ROLLING_PATTERN)); TraceAppender appender = new TimedRollingFileAppender(CLEAN_UP_TEST_LOG, TimedRollingFileAppender.DAILY_ROLLING_PATTERN, "3"); appender.cleanup(); - Assert.assertTrue("今天的日志应该还是存在", todayFile.exists()); - Assert.assertTrue("昨天的日志应该还是存在", yesterdayFile.exists()); - Assert.assertTrue("两天前的日志应该还是存在", twoDayAgoFile.exists()); - Assert.assertTrue("三天前的日志应该还是存在", threeDayAgoFile.exists()); - Assert.assertTrue("四天前的日志应该不存在", !fourDayAgoFile.exists()); - Assert.assertTrue("五天前的日志应该不存在", !fiveDayAgoFile.exists()); + Assert.assertTrue("Today's log should still exist", todayFile.exists()); + Assert.assertTrue("Yesterday's log should still exist", yesterdayFile.exists()); + Assert.assertTrue("The log two days ago should still exist", twoDayAgoFile.exists()); + Assert.assertTrue("The log three days ago should still exist", threeDayAgoFile.exists()); + Assert.assertTrue("The log four days ago should not exist", !fourDayAgoFile.exists()); + Assert.assertTrue("The log five days ago should not exist", !fiveDayAgoFile.exists()); } @Test - public void 测试清理日志_按小时滚() throws IOException { + public void test_cleanup_log_scroll_by_hour() throws IOException { generateLogFilesToBeCleanup(new SimpleDateFormat( TimedRollingFileAppender.HOURLY_ROLLING_PATTERN)); TraceAppender appender = new TimedRollingFileAppender(CLEAN_UP_TEST_LOG, TimedRollingFileAppender.HOURLY_ROLLING_PATTERN, "2"); appender.cleanup(); - Assert.assertTrue("今天的日志应该还是存在", todayFile.exists()); - Assert.assertTrue("昨天的日志应该还是存在", yesterdayFile.exists()); - Assert.assertTrue("两天前的日志应该还是存在", twoDayAgoFile.exists()); - Assert.assertTrue("三天前的日志应该还是存在", !threeDayAgoFile.exists()); - Assert.assertTrue("四天前的日志应该不存在", !fourDayAgoFile.exists()); - Assert.assertTrue("五天前的日志应该不存在", !fiveDayAgoFile.exists()); + Assert.assertTrue("Today's log should still exist", todayFile.exists()); + Assert.assertTrue("Yesterday's log should still exist", yesterdayFile.exists()); + Assert.assertTrue("The log two days ago should still exist", twoDayAgoFile.exists()); + Assert.assertTrue("The log three days ago should not exist", !threeDayAgoFile.exists()); + Assert.assertTrue("The log four days ago should not exist", !fourDayAgoFile.exists()); + Assert.assertTrue("The log five days ago should not exist", !fiveDayAgoFile.exists()); } - /*** - * 测试按小时清理日志_按小时滚动_两小时 - * @throws IOException exception - */ @Test public void rolling_by_two_hour() throws IOException { generateLogFilesToBeCleanupHourly(new SimpleDateFormat( @@ -85,18 +81,14 @@ public void rolling_by_two_hour() throws IOException { TimedRollingFileAppender.HOURLY_ROLLING_PATTERN, "0D2H"); appender.cleanup(); - Assert.assertTrue("这个小时前的日志应该还是存在", todayFile.exists()); - Assert.assertTrue("一个小时前的日志应该还是存在", yesterdayFile.exists()); - Assert.assertTrue("两个小时前的日志应该还是存在", twoDayAgoFile.exists()); - Assert.assertTrue("三个小时前的日志应该不存在", !threeDayAgoFile.exists()); - Assert.assertTrue("四个小时前的日志应该不存在", !fourDayAgoFile.exists()); - Assert.assertTrue("五个小时前的日志应该不存在", !fiveDayAgoFile.exists()); + Assert.assertTrue("The log before this hour should still exist", todayFile.exists()); + Assert.assertTrue("The log An hour ago should still exist", yesterdayFile.exists()); + Assert.assertTrue("The log two hours ago should still exist", twoDayAgoFile.exists()); + Assert.assertTrue("The log three hours ago should not exist", !threeDayAgoFile.exists()); + Assert.assertTrue("The log four hours ago should not exist", !fourDayAgoFile.exists()); + Assert.assertTrue("The log five hours ago should not exist", !fiveDayAgoFile.exists()); } - /*** - * 测试按小时清理日志_按小时滚动_三小时 - * @throws IOException - */ @Test public void rolling_by_three_hour() throws IOException { generateLogFilesToBeCleanupHourly(new SimpleDateFormat( @@ -105,12 +97,12 @@ public void rolling_by_three_hour() throws IOException { TimedRollingFileAppender.HOURLY_ROLLING_PATTERN, "0D3H"); appender.cleanup(); - Assert.assertTrue("这个小时前的日志应该还是存在", todayFile.exists()); - Assert.assertTrue("一个小时前的日志应该还是存在", yesterdayFile.exists()); - Assert.assertTrue("两个小时前的日志应该还是存在", twoDayAgoFile.exists()); - Assert.assertTrue("三个小时前的日志应该还是存在", threeDayAgoFile.exists()); - Assert.assertTrue("四个小时前的日志应该不存在", !fourDayAgoFile.exists()); - Assert.assertTrue("五个小时前的日志应该不存在", !fiveDayAgoFile.exists()); + Assert.assertTrue("The log before this hour should still exist", todayFile.exists()); + Assert.assertTrue("The log An hour ago should still exist", yesterdayFile.exists()); + Assert.assertTrue("The log two hours ago should still exist", twoDayAgoFile.exists()); + Assert.assertTrue("The log three hours ago should still exist", threeDayAgoFile.exists()); + Assert.assertTrue("The log four hours ago should not exist", !fourDayAgoFile.exists()); + Assert.assertTrue("The log five hours ago should not exist", !fiveDayAgoFile.exists()); } private void generateLogFilesToBeCleanupHourly(SimpleDateFormat sdf) throws IOException { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/TracerLogRootDaemonTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/TracerLogRootDaemonTest.java index 2e3038da..28c293e9 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/TracerLogRootDaemonTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/TracerLogRootDaemonTest.java @@ -29,7 +29,7 @@ * * @author * @version 1.0 - * @since
七月 24, 2017
+ * @since
July 24, 2017
*/ public class TracerLogRootDaemonTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/builder/JsonStringBuilderTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/builder/JsonStringBuilderTest.java index 0a8e3afa..ef04f3f6 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/builder/JsonStringBuilderTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/builder/JsonStringBuilderTest.java @@ -30,7 +30,7 @@ * * @author * @version 1.0 - * @since
五月 14, 2018
+ * @since
May 14, 2018
*/ public class JsonStringBuilderTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/builder/XStringBuilderTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/builder/XStringBuilderTest.java index baab4062..c3f97113 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/builder/XStringBuilderTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/builder/XStringBuilderTest.java @@ -30,12 +30,12 @@ * * @author * @version 1.0 - * @since
七月 12, 2017
+ * @since
July 12, 2017
*/ public class XStringBuilderTest { - /*** - * 测试_appendEndMap_逗号被转义 + /** + * Test appendEndMap comma is escaped */ @Test public void appendEndMapTransferredMeaning() { @@ -49,8 +49,8 @@ public void appendEndMapTransferredMeaning() { @Test public void testXStringBuilderAppender() { XStringBuilder xStringBuilder = new XStringBuilder(128); - xStringBuilder.append(1l, ","); - xStringBuilder.append(1l, ','); + xStringBuilder.append(1L, ","); + xStringBuilder.append(1L, ','); xStringBuilder.append("test1", ","); Map map = new HashMap(); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/file/TimedRollingFileAppenderTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/file/TimedRollingFileAppenderTest.java index f2d3ae01..ef3c9705 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/file/TimedRollingFileAppenderTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/file/TimedRollingFileAppenderTest.java @@ -58,12 +58,13 @@ public void test() throws IOException, InterruptedException { Resource[] resources = resolver.getResources("file:" + TracerLogRootDaemon.LOG_FILE_DIR + File.separator + ROLLING_TEST_FILE_NAME + "*"); - Assert.assertTrue("文件的数量不正确,以 " + ROLLING_TEST_FILE_NAME + " 为开头的文件数量应该是 2 个", - resources.length == 2); + Assert.assertTrue("The number of files is incorrect. The number of files starting with " + + ROLLING_TEST_FILE_NAME + " should be 2", resources.length == 2); for (Resource resource : resources) { String c = FileUtils.readFileToString(resource.getFile()); - Assert.assertEquals("文件 " + resource.getFilename() + " 中的内容不正确", content, c); + Assert.assertEquals("File content in " + resource.getFilename() + " is incorrect", + content, c); } } } diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/info/StaticInfoLogTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/info/StaticInfoLogTest.java index cf9d2d3d..404d3624 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/info/StaticInfoLogTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/info/StaticInfoLogTest.java @@ -37,7 +37,7 @@ * * @author * @version 1.0 - * @since
七月 2, 2017
+ * @since
July 2, 2017
*/ public class StaticInfoLogTest extends AbstractTestBase { @@ -45,7 +45,7 @@ public class StaticInfoLogTest extends AbstractTestBase { public void testLogStaticInfo() throws IOException, InterruptedException, NoSuchFieldException, IllegalAccessException { - //记录 + //record reflect(); StaticInfoLog.logStaticInfo(); @@ -57,7 +57,7 @@ public void testLogStaticInfo() throws IOException, InterruptedException, NoSuch params.add(TracerUtils.getCurrentZone()); params.add(TracerUtils.getDefaultTimeZone()); List contents = FileUtils.readLines(customFileLog("static-info.log")); - Assert.assertFalse("静态信息日志没有内容", contents.isEmpty()); + Assert.assertFalse("Static information log has no content", contents.isEmpty()); assertTrue(checkResult(params, contents.get(0))); } diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ConcurrentConsumerCorrectTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ConcurrentConsumerCorrectTest.java index 6aada06a..b76519c5 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ConcurrentConsumerCorrectTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ConcurrentConsumerCorrectTest.java @@ -37,7 +37,7 @@ /** * * @author liangen - * @version $Id: ConcurrentConsumerCorrectTest.java, v 0.1 2017年10月23日 下午3:01 liangen Exp $ + * @version $Id: ConcurrentConsumerCorrectTest.java, v 0.1 October 23, 2017 3:01 PM liangen Exp $ */ public class ConcurrentConsumerCorrectTest { @@ -61,7 +61,7 @@ public void clean() throws Exception { @Test public void testConcurrentConsumerCorrect() throws InterruptedException, IOException { - /**不允许丢失日志,避免日志丢失影响结果校验的正确性*/ + /** Logs are not allowed to be lost, and log loss is avoided to affect the correctness of the result check. */ SofaTracerConfiguration.setProperty( SofaTracerConfiguration.TRACER_ASYNC_APPENDER_ALLOW_DISCARD, "false"); @@ -90,65 +90,55 @@ public void testConcurrentConsumerCorrect() throws InterruptedException, IOExcep final CountDownLatch countDownLatch = new CountDownLatch(30); for (int i = 0; i < 20; i++) { - new Thread(new Runnable() { - @Override - public void run() { - - SofaTracerSpan span1 = ManagerTestUtil.createSofaTracerSpan(1); - for (int j = 0; j < 30; j++) { - asyncCommonDigestAppenderManager.append(span1); - } - - SofaTracerSpan span2 = ManagerTestUtil.createSofaTracerSpan(2); - for (int j = 0; j < 40; j++) { - asyncCommonDigestAppenderManager.append(span2); - } - - SofaTracerSpan span3 = ManagerTestUtil.createSofaTracerSpan(3); - for (int j = 0; j < 50; j++) { - asyncCommonDigestAppenderManager.append(span3); - } - - SofaTracerSpan span4 = ManagerTestUtil.createSofaTracerSpan(4); - for (int j = 0; j < 60; j++) { - asyncCommonDigestAppenderManager.append(span4); - } - - SofaTracerSpan span5 = ManagerTestUtil.createSofaTracerSpan(5); - for (int j = 0; j < 70; j++) { - asyncCommonDigestAppenderManager.append(span5); - } - - countDownLatch.countDown(); + new Thread(()->{ + SofaTracerSpan span1 = ManagerTestUtil.createSofaTracerSpan(1); + for (int j = 0; j < 30; j++) { + asyncCommonDigestAppenderManager.append(span1); } + + SofaTracerSpan span2 = ManagerTestUtil.createSofaTracerSpan(2); + for (int j = 0; j < 40; j++) { + asyncCommonDigestAppenderManager.append(span2); + } + + SofaTracerSpan span3 = ManagerTestUtil.createSofaTracerSpan(3); + for (int j = 0; j < 50; j++) { + asyncCommonDigestAppenderManager.append(span3); + } + + SofaTracerSpan span4 = ManagerTestUtil.createSofaTracerSpan(4); + for (int j = 0; j < 60; j++) { + asyncCommonDigestAppenderManager.append(span4); + } + + SofaTracerSpan span5 = ManagerTestUtil.createSofaTracerSpan(5); + for (int j = 0; j < 70; j++) { + asyncCommonDigestAppenderManager.append(span5); + } + + countDownLatch.countDown(); }).start(); } for (int i = 0; i < 10; i++) { - new Thread(new Runnable() { - @Override - public void run() { - - SofaTracerSpan span1 = ManagerTestUtil.createSofaTracerSpan(1); - SofaTracerSpan span2 = ManagerTestUtil.createSofaTracerSpan(2); - SofaTracerSpan span3 = ManagerTestUtil.createSofaTracerSpan(3); - SofaTracerSpan span4 = ManagerTestUtil.createSofaTracerSpan(4); - SofaTracerSpan span5 = ManagerTestUtil.createSofaTracerSpan(5); - - for (int j = 0; j < 40; j++) { - asyncCommonDigestAppenderManager.append(span1); - asyncCommonDigestAppenderManager.append(span2); - asyncCommonDigestAppenderManager.append(span3); - asyncCommonDigestAppenderManager.append(span4); - asyncCommonDigestAppenderManager.append(span5); - } - - countDownLatch.countDown(); + new Thread(()->{ + SofaTracerSpan span1 = ManagerTestUtil.createSofaTracerSpan(1); + SofaTracerSpan span2 = ManagerTestUtil.createSofaTracerSpan(2); + SofaTracerSpan span3 = ManagerTestUtil.createSofaTracerSpan(3); + SofaTracerSpan span4 = ManagerTestUtil.createSofaTracerSpan(4); + SofaTracerSpan span5 = ManagerTestUtil.createSofaTracerSpan(5); + for (int j = 0; j < 40; j++) { + asyncCommonDigestAppenderManager.append(span1); + asyncCommonDigestAppenderManager.append(span2); + asyncCommonDigestAppenderManager.append(span3); + asyncCommonDigestAppenderManager.append(span4); + asyncCommonDigestAppenderManager.append(span5); } + countDownLatch.countDown(); }).start(); } - /**校验*/ + /** check */ countDownLatch.await(); Thread.sleep(3000); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ConcurrentDiscardTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ConcurrentDiscardTest.java index 09d39136..9395d0c7 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ConcurrentDiscardTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ConcurrentDiscardTest.java @@ -40,7 +40,7 @@ /** * * @author liangen - * @version $Id: ConcurrentDiscardTest.java, v 0.1 2017年10月23日 下午8:22 liangen Exp $ + * @version $Id: ConcurrentDiscardTest.java, v 0.1 October 23, 2017 8:22 PM liangen Exp $ */ public class ConcurrentDiscardTest { static final String fileNameRoot = TracerLogRootDaemon.LOG_FILE_DIR + File.separator; @@ -120,40 +120,35 @@ public void testConcurrentDiscard() throws InterruptedException, IOException { final CountDownLatch countDownLatch = new CountDownLatch(50); for (int i = 0; i < 50; i++) { - new Thread(new Runnable() { - @Override - public void run() { - SofaTracerSpan span1 = ManagerTestUtil.createSofaTracerSpan(1); - SofaTracerSpan span2 = ManagerTestUtil.createSofaTracerSpan(2); - SofaTracerSpan span3 = ManagerTestUtil.createSofaTracerSpan(3); - SofaTracerSpan span4 = ManagerTestUtil.createSofaTracerSpan(4); - SofaTracerSpan span5 = ManagerTestUtil.createSofaTracerSpan(5); - - for (int j = 0; j < 100; j++) { - if (!asyncCommonDigestAppenderManager.append(span1)) { - discardNum.incrementAndGet(); - } - if (!asyncCommonDigestAppenderManager.append(span2)) { - discardNum.incrementAndGet(); - } - if (!asyncCommonDigestAppenderManager.append(span3)) { - discardNum.incrementAndGet(); - } - if (!asyncCommonDigestAppenderManager.append(span4)) { - discardNum.incrementAndGet(); - } - if (!asyncCommonDigestAppenderManager.append(span5)) { - discardNum.incrementAndGet(); - } - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } + new Thread(()-> { + SofaTracerSpan span1 = ManagerTestUtil.createSofaTracerSpan(1); + SofaTracerSpan span2 = ManagerTestUtil.createSofaTracerSpan(2); + SofaTracerSpan span3 = ManagerTestUtil.createSofaTracerSpan(3); + SofaTracerSpan span4 = ManagerTestUtil.createSofaTracerSpan(4); + SofaTracerSpan span5 = ManagerTestUtil.createSofaTracerSpan(5); + for (int j = 0; j < 100; j++) { + if (!asyncCommonDigestAppenderManager.append(span1)) { + discardNum.incrementAndGet(); + } + if (!asyncCommonDigestAppenderManager.append(span2)) { + discardNum.incrementAndGet(); + } + if (!asyncCommonDigestAppenderManager.append(span3)) { + discardNum.incrementAndGet(); + } + if (!asyncCommonDigestAppenderManager.append(span4)) { + discardNum.incrementAndGet(); + } + if (!asyncCommonDigestAppenderManager.append(span5)) { + discardNum.incrementAndGet(); + } + try { + Thread.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); } - - countDownLatch.countDown(); } + countDownLatch.countDown(); }).start(); } @@ -161,7 +156,7 @@ public void run() { Thread.sleep(3000); SynchronizingSelfLog.flush(); - /**校验*/ + /**check*/ int log1Num = getLineNum(fileName1); int log2Num = getLineNum(fileName2); int log3Num = getLineNum(fileName3); @@ -169,19 +164,18 @@ public void run() { int log5Num = getLineNum(fileName5); int allNum = log1Num + log2Num + log3Num + log4Num + log5Num; - /**落地日志 + 丢失日志 = 打印日志*/ - SelfLog.info("落地日志:" + allNum); - SelfLog.info("丢失日志:" + discardNum.get()); + /**Landing log + Lost log = Print log*/ + SelfLog.info("Landing log:" + allNum); + SelfLog.info("Lost log:" + discardNum.get()); Assert.assertEquals(25000, allNum + discardNum.get()); - /**sync.log丢失日志数据小于实际丢失数*/ + /** Sync.log lost log data is less than the actual number of lost */ int logDiscard = getDiscardNumFromTracerSelfLog(); - SelfLog.info("sync.log记录丢失日志数:" + logDiscard); + SelfLog.info("Sync.log records the number of lost logs:" + logDiscard); Assert.assertTrue(logDiscard <= discardNum.get()); - /**sync.log记录的具体丢失日志数据的准确性:与真实丢失数的差应该小于500*/ - + /** Accuracy of the specific lost log data recorded by sync.log: the difference from the true lost number should be less than 500 */ int allTraceIdDiscard = traceId1Discard + traceId2Discard + traceId3Discard + traceId4Discard + traceId5Discard; - SelfLog.info("sync.log记录的具有traceId的具体丢失日志数据的数:" + allTraceIdDiscard); + SelfLog.info("The number of specific lost log data with traceId recorded by sync.log:" + allTraceIdDiscard); Assert.assertTrue((discardNum.get() == allTraceIdDiscard) || (discardNum.get() - allTraceIdDiscard) < 500); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ManagerTestUtil.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ManagerTestUtil.java index d197a5b5..f0066f55 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ManagerTestUtil.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/manager/ManagerTestUtil.java @@ -19,30 +19,14 @@ import com.alipay.common.tracer.core.SofaTracer; import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; import com.alipay.common.tracer.core.span.SofaTracerSpan; - import java.io.File; /** * * @author liangen - * @version $Id: ManagerTestUtil.java, v 0.1 2017年10月23日 下午8:34 liangen Exp $ + * @version $Id: ManagerTestUtil.java, v 0.1 October 23, 2017 8:34 PM liangen Exp $ */ public class ManagerTestUtil { - public static void deleteFile(String filePath) { - - File fileRoot = new File(filePath); - - if (fileRoot.isDirectory()) { - String[] childrens = fileRoot.list(); - for (String children : childrens) { - File file = new File(fileRoot, children); - deleteFile(file.getPath()); - } - - } - - fileRoot.delete(); - } public static SofaTracerSpan createSofaTracerSpan(int sequence) { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/self/SelfLogTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/self/SelfLogTest.java index f2a242b5..f2afc729 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/self/SelfLogTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/appender/self/SelfLogTest.java @@ -35,7 +35,7 @@ * * @author * @version 1.0 - * @since
七月 26, 2017
+ * @since
July 26, 2017
*/ public class SelfLogTest extends AbstractTestBase { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/async/SofaTracerCallableTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/async/SofaTracerCallableTest.java index 80baa58e..9f21a69e 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/async/SofaTracerCallableTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/async/SofaTracerCallableTest.java @@ -26,7 +26,7 @@ /** * * @author luoguimu123 - * @version $Id: SofaTracerCallableTest.java, v 0.1 2017年06月22日 下午3:38 luoguimu123 Exp $ + * @version $Id: SofaTracerCallableTest.java, v 0.1 June 22, 2017 3:38 PM luoguimu123 Exp $ */ public class SofaTracerCallableTest { SofaTraceContext traceContext; @@ -69,5 +69,4 @@ public void testInstrumentedCallableNoCurrentSpan() throws Exception { Mockito.verify(wrappedCallable, Mockito.times(1)).call(); Mockito.verifyNoMoreInteractions(traceContext, wrappedCallable); } - } \ No newline at end of file diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/async/SofaTracerRunnableTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/async/SofaTracerRunnableTest.java index 16d6a4a8..2d7f86a2 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/async/SofaTracerRunnableTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/async/SofaTracerRunnableTest.java @@ -30,7 +30,7 @@ /** * @author luoguimu123 - * @version $Id: SofaTracerRunnableTest.java, v 0.1 2017年06月22日 下午3:53 luoguimu123 Exp $ + * @version $Id: SofaTracerRunnableTest.java, v 0.1 June 22, 2017 3:53 PM luoguimu123 Exp $ */ public class SofaTracerRunnableTest { SofaTraceContext traceContext; diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/async/TracedExecutorServiceTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/async/TracedExecutorServiceTest.java index ea2a9530..b1ce6333 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/async/TracedExecutorServiceTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/async/TracedExecutorServiceTest.java @@ -34,7 +34,7 @@ /** * * @author luoguimu123 - * @version $Id: TracedExecutorServiceTest.java, v 0.1 2017年06月22日 下午3:59 luoguimu123 Exp $ + * @version $Id: TracedExecutorServiceTest.java, v 0.1 June 22, 2017 3:59 PM luoguimu123 Exp $ */ public class TracedExecutorServiceTest { private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS; diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/async/TracerScheduleExecutorServiceTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/async/TracerScheduleExecutorServiceTest.java index 3381c690..9283fcf3 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/async/TracerScheduleExecutorServiceTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/async/TracerScheduleExecutorServiceTest.java @@ -105,17 +105,10 @@ public void run() { @Test public void scheduleCallable() throws Exception { final Object testObj = new Object(); - Callable callable = new Callable() { - @Override - public Object call() throws Exception { - return testObj; - } - }; ScheduledFuture schedule = tracerScheduleExecutorService - .schedule(callable, 1000, TIME_UNIT); + .schedule(()-> testObj, 1000, TIME_UNIT); Thread.sleep(1100); Object o = schedule.get(); Assert.assertTrue(testObj == o); } - } \ No newline at end of file diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java index d871e120..2127acbc 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java @@ -105,13 +105,8 @@ protected static File tracerSelfLog() { return new File(logDirectoryPath + File.separator + "tracer-self.log"); } - protected static File middlewareErrorLog() { - return new File(logDirectoryPath + File.separator - + TracerSystemLogEnum.MIDDLEWARE_ERROR.getDefaultLogName()); - } - /** - * 检查传入的参数和日志中的内容是否匹配 + * Whether the parameters and the contents of the log match * * @param params String Array which is compared with logContent. * @param logContent String Content which is split up with comma @@ -124,8 +119,9 @@ public static boolean checkResult(List params, String logContent) { List slots = Arrays.asList(logContent.split(String .valueOf(XStringBuilder.DEFAULT_SEPARATOR))); - assertEquals("日志内容中的栏位数量为 " + slots.size() + ";参数的栏位数量为" + params.size() + ";两者不一致", - params.size(), slots.size()); + assertEquals("The number of fields in the log content is " + slots.size() + + "; the number of fields in the parameter is " + params.size() + + "; the two are inconsistent", params.size(), slots.size()); for (int i = 0; i < params.size(); i++) { String param = params.get(i); @@ -136,11 +132,16 @@ public static boolean checkResult(List params, String logContent) { } } if (param.length() > 2 && param.startsWith("M|")) { - Assert.assertTrue("日志和参数中的第 " + i + " 栏内容不一致,日志中为 " + slot + ";参数中为 " + param, + Assert.assertTrue( + "The contents of the " + i + + " column in the log and parameters are inconsistent. The log is " + + slot + ";The parameter is " + param, TestUtil.compareSlotMap(param.substring(2), slot)); } else { - Assert.assertTrue("日志和参数中的第 " + i + " 栏内容不一致,日志中为 " + slot + ";参数中为 " + param, - param.equals(slot)); + Assert.assertTrue( + "The contents of the " + i + + " column in the log and parameters are inconsistent. The log is " + + slot + ";The parameter is " + param, param.equals(slot)); } } return true; diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/benchmark/CountBenchmark.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/benchmark/CountBenchmark.java index b63cff72..cc88b3ad 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/benchmark/CountBenchmark.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/benchmark/CountBenchmark.java @@ -32,9 +32,9 @@ import java.util.concurrent.TimeUnit; /** - * 对比 JDK6 下 {@link StringTokenizer#countTokens()} 和 {@link String#split(String)} 的性能. + * Compare the performance of {@link StringTokenizer#countTokens()} and {@link String#split(String)} under JDK6. * - * JDK 6, Mac OS 10.11.1, 性能数据如下: + * JDK 6, Mac OS 10.11.1, The performance data is as follows: * *
  * Benchmark                                Mode    Cnt     Score       Error   Units
diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/configuration/SofaTracerConfigurationTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/configuration/SofaTracerConfigurationTest.java
index 1d5beefd..4c987b7a 100644
--- a/tracer-core/src/test/java/com/alipay/common/tracer/core/configuration/SofaTracerConfigurationTest.java
+++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/configuration/SofaTracerConfigurationTest.java
@@ -29,7 +29,7 @@
 /**
  *
  * @author luoguimu123
- * @version $Id: SofaTracerConfigurationTest.java, v 0.1 2017年06月29日 上午10:06 luoguimu123 Exp $
+ * @version $Id: SofaTracerConfigurationTest.java, v 0.1 June 29, 2017 10:06 AM luoguimu123 Exp $
  */
 public class SofaTracerConfigurationTest {
 
diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/context/span/SofaTracerSpanContextTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/context/span/SofaTracerSpanContextTest.java
index 2a29889d..3e89db38 100644
--- a/tracer-core/src/test/java/com/alipay/common/tracer/core/context/span/SofaTracerSpanContextTest.java
+++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/context/span/SofaTracerSpanContextTest.java
@@ -32,7 +32,7 @@
  *
  * @author 
  * @version 1.0
- * @since 
七月 8, 2017
+ * @since
July 8, 2017
*/ public class SofaTracerSpanContextTest { 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 7450e6a5..7dc95f82 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 @@ -29,7 +29,7 @@ * * @author * @version 1.0 - * @since
七月 6, 2017
+ * @since
July 6, 2017
*/ public class SofaTracerThreadLocalTraceContextTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/holder/SofaTraceContextHolderTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/holder/SofaTraceContextHolderTest.java index 5b69d614..be90d983 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/holder/SofaTraceContextHolderTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/holder/SofaTraceContextHolderTest.java @@ -34,7 +34,7 @@ * * @author * @version 1.0 - * @since
七月 6, 2017
+ * @since
July 6, 2017
*/ public class SofaTraceContextHolderTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolderTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolderTest.java index 00df0768..193b814e 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolderTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/listener/SpanReportListenerHolderTest.java @@ -29,7 +29,7 @@ * * @author * @version 1.0 - * @since
五月 7, 2018
+ * @since
May 7, 2018
*/ public class SpanReportListenerHolderTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/mock/MockSofaTracerTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/mock/MockSofaTracerTest.java index b0298d77..e5dd4543 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/mock/MockSofaTracerTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/mock/MockSofaTracerTest.java @@ -30,7 +30,7 @@ * * @author * @version 1.0 - * @since
八月 10, 2017
+ * @since
August 10, 2017
*/ public class MockSofaTracerTest extends AbstractTestBase { 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 f32b977c..0e7bf342 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 @@ -37,7 +37,7 @@ * * @author * @version 1.0 - * @since
六月 24, 2017
+ * @since
June 24, 2017
*/ public class BinaryFormaterTest { @@ -70,7 +70,7 @@ public void testGetFormatType() throws Exception { } /** - * 将我们的 spanContext 放在数据头部 + * Put our spanContext in the data header * Method: inject(SofaTracerSpanContext spanContext, ByteBuffer carrier) *

* Method: extract(ByteBuffer carrier) @@ -89,7 +89,7 @@ public void testExtractCarrier() throws Exception { } /** - * 将我们的 spanContext 放在数据头部 + * Put our spanContext in the data header * Method: inject(SofaTracerSpanContext spanContext, ByteBuffer carrier) *

* Method: extract(ByteBuffer carrier) @@ -97,7 +97,7 @@ public void testExtractCarrier() throws Exception { @Test public void testExtract() throws Exception { SofaTracerSpanContext spanContext = SofaTracerSpanContext.rootStart(); - Map baggage = new HashMap(); + Map baggage = new HashMap<>(); baggage.put("key", "value"); baggage.put("key1", "value1"); baggage.put("key2", "value2"); @@ -115,7 +115,7 @@ public void testExtract() throws Exception { } /** - * 将我们的 spanContext 字节码放在数据中间位置 + * Put our spanContext bytecode in the middle of the data * Method: inject(SofaTracerSpanContext spanContext, ByteBuffer carrier) *

* Method: extract(ByteBuffer carrier) @@ -123,12 +123,12 @@ public void testExtract() throws Exception { @Test public void testExtractInject() throws Exception { SofaTracerSpanContext spanContext = SofaTracerSpanContext.rootStart(); - Map baggage = new HashMap(); + Map baggage = new HashMap<>(); baggage.put("key", "value"); baggage.put("key1", "value1"); baggage.put("key2", "value2"); spanContext.addBizBaggage(baggage); - Map sysBaggage = new HashMap(); + Map sysBaggage = new HashMap<>(); sysBaggage.put("sys1", "value1"); sysBaggage.put("sys2", "value2"); sysBaggage.put("sys3", "value3"); @@ -137,8 +137,8 @@ public void testExtractInject() throws Exception { //inject //200 bytes ByteBuffer carrier = ByteBuffer.allocate(400); - //提前放一些数据进行测试 - String header = "index_=test雪连哈哈"; + //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); @@ -153,7 +153,7 @@ public void testExtractInject() throws Exception { } /** - * 注意:此测试用例不通过,只支持堆内存不支持堆外内存 + * Note: This test case does not pass, only supports heap memory does not support off-heap memory * Method: inject(SofaTracerSpanContext spanContext, ByteBuffer carrier) *

* @@ -171,11 +171,10 @@ public void testDirectByteBufferExtractInjectException() throws Exception { //200 bytes ByteBuffer carrier = ByteBuffer.allocateDirect(200); this.registryExtractorInjector.inject(spanContext, carrier); - SofaTracerSpanContext extractContext = null; //extract boolean isException = false; try { - extractContext = this.registryExtractorInjector.extract(carrier); + this.registryExtractorInjector.extract(carrier); } catch (UnsupportedOperationException exception) { isException = true; } diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/HttpHeadersB3FormatterTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/HttpHeadersB3FormatterTest.java index 68647f28..28a8ef4f 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/HttpHeadersB3FormatterTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/HttpHeadersB3FormatterTest.java @@ -32,7 +32,7 @@ * * @author * @version 1.0 - * @since

七月 8, 2017
+ * @since
July 8, 2017
*/ public class HttpHeadersB3FormatterTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/HttpHeadersFormatterTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/HttpHeadersFormatterTest.java index f1180821..a6505dc8 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/HttpHeadersFormatterTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/HttpHeadersFormatterTest.java @@ -34,7 +34,7 @@ * * @author * @version 1.0 - * @since
七月 8, 2017
+ * @since
July 8, 2017
*/ public class HttpHeadersFormatterTest { @@ -62,15 +62,14 @@ public void testGetFormatType() throws Exception { @Test public void testEncodedValue() throws Exception { SofaTracerSpanContext spanContext = SofaTracerSpanContext.rootStart(); - Map baggage = new HashMap(); + Map baggage = new HashMap<>(); baggage.put("key", "value"); baggage.put("key1", "value1"); baggage.put("key2", "value2"); spanContext.addBizBaggage(baggage); // final TextMap carrier = new TextMap() { - - Map carr = new HashMap(); + Map carr = new HashMap<>(); @Override public Iterator> iterator() { @@ -89,7 +88,7 @@ public String toString() { }; this.registryExtractorInjector.inject(spanContext, carrier); SofaTracerSpanContext extractContext = this.registryExtractorInjector.extract(carrier); - //traceid spanId sampled + // traceId spanId sampled extractContext.equals(spanContext); assertTrue("Extract baggage : " + extractContext.getBizBaggage(), baggage.equals(extractContext.getBizBaggage())); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TextMapB3FormatterTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TextMapB3FormatterTest.java index f7ce246d..c1919a82 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TextMapB3FormatterTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TextMapB3FormatterTest.java @@ -34,7 +34,7 @@ * * @author * @version 1.0 - * @since
七月 8, 2017
+ * @since
July 8, 2017
*/ public class TextMapB3FormatterTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TextMapFormatterTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TextMapFormatterTest.java index 07ad2b88..8970224b 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TextMapFormatterTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TextMapFormatterTest.java @@ -35,7 +35,7 @@ * * @author * @version 1.0 - * @since
七月 8, 2017
+ * @since
July 8, 2017
*/ public class TextMapFormatterTest { @@ -94,7 +94,7 @@ public String toString() { this.registryExtractorInjector.inject(spanContext, carrier); //carrier SofaTracerSpanContext extractContext = this.registryExtractorInjector.extract(carrier); - //traceid spanId sampled + //traceId spanId sampled extractContext.equals(spanContext); assertTrue("Extract : " + extractContext, baggage.equals(extractContext.getBizBaggage())); } diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TracerFormatRegistryTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TracerFormatRegistryTest.java index 492bcb31..90665687 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TracerFormatRegistryTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/registry/TracerFormatRegistryTest.java @@ -26,7 +26,7 @@ * * @author * @version 1.0 - * @since
七月 8, 2017
+ * @since
July 8, 2017
*/ public class TracerFormatRegistryTest { @@ -41,7 +41,7 @@ public void testRegister() throws Exception { .getRegistry(io.opentracing.propagation.Format.Builtin.BINARY); assertTrue(registry == registry1); - //恢复测试影响的registry + //Restore the registry affected by the test BinaryFormater binaryFormater = new BinaryFormater(); TracerFormatRegistry.register(io.opentracing.propagation.Format.Builtin.BINARY, binaryFormater); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/SofaTracerStatisticReporterCycleTimesManagerTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/SofaTracerStatisticReporterCycleTimesManagerTest.java index 0832dba2..eb5a4cb3 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/SofaTracerStatisticReporterCycleTimesManagerTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/SofaTracerStatisticReporterCycleTimesManagerTest.java @@ -25,7 +25,7 @@ * SofaTracerStatisticReporterCycleTimesManager Tester. * * @author -* @since
六月 22, 2017
+* @since
June 22, 2017
* @version 1.0 */ public class SofaTracerStatisticReporterCycleTimesManagerTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java index 39377a0f..cd693a31 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonSpanEncoderTest.java @@ -46,7 +46,7 @@ * * @author * @version 1.0 - * @since
七月 15, 2017
+ * @since
July 15, 2017
*/ public class CommonSpanEncoderTest extends AbstractTestBase { @@ -86,15 +86,14 @@ public void testEncode() throws Exception { sofaTracerSpan.setBaggageItem("baggage1", "value1"); sofaTracerSpan.setBaggageItem("baggage2", "value2"); - //记录一条错误日志 + //Record an error log sofaTracerSpan.reportError(errorType, context, exception, appName, errorSources); - //记录一条client 日志 + //Record a client log sofaTracerSpan.finish(); TestUtil.waitForAsyncLog(); - //检查客户端日志 - //client digest + //Check client logs List clientDigestContents = FileUtils.readLines(new File(logDirectoryPath + File.separator + clientLogType)); @@ -104,15 +103,15 @@ public void testEncode() throws Exception { //error log List errorContents = FileUtils .readLines(customFileLog(TracerSystemLogEnum.MIDDLEWARE_ERROR.getDefaultLogName())); - //错误堆栈 + //Error stack assertTrue(errorContents.size() > 1); assertTrue(errorContents.get(0).contains(sofaTracerSpanContext.getTraceId())); - //去掉头 + //remove head String fileContent = errorContents.get(0).substring(errorContents.get(0).indexOf(",") + 1); - //去掉尾巴 + //remove end fileContent = fileContent.substring(0, fileContent.lastIndexOf(",")); - //构造结果 - List params = new ArrayList(); + //construct result + List params = new ArrayList<>(); params.add(sofaTracerSpan.getTagsWithStr().get(SpanTags.CURR_APP_TAG.getKey())); params.add(sofaTracerSpanContext.getTraceId()); params.add(sofaTracerSpanContext.getSpanId()); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonTracerManagerTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonTracerManagerTest.java index a1b0b139..3edb4575 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonTracerManagerTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/common/CommonTracerManagerTest.java @@ -27,7 +27,6 @@ import org.junit.Test; import java.io.File; -import java.io.IOException; import java.util.List; import static org.junit.Assert.assertTrue; @@ -37,7 +36,7 @@ * * @author * @version 1.0 - * @since
七月 25, 2017
+ * @since
July 25, 2017
*/ public class CommonTracerManagerTest extends AbstractTestBase { @@ -61,7 +60,7 @@ public void testRegisterAndReportCommonSpan() throws Exception { System.currentTimeMillis(), "testReportProfile", SofaTracerSpanContext.rootStart(), null); assertTrue(CommonTracerManager.isAppenderExist(logType)); - //注意:对于 commonSpan 一定要设置日志类型 + //Note: Be sure to set the log type for commonSpan commonLogSpan.setLogType(logType); CommonTracerManager.reportCommonSpan(commonLogSpan); @@ -88,7 +87,7 @@ public void testRegisterAndReportCommonSpanChar() throws Exception { System.currentTimeMillis(), "testReportProfile", SofaTracerSpanContext.rootStart(), null); assertTrue(CommonTracerManager.isAppenderExist(logTypeStr)); - //注意:对于 commonSpan 一定要设置日志类型 + //Note: Be sure to set the log type for commonSpan commonLogSpan.setLogType(logTypeStr); commonLogSpan.addSlot("hello"); commonLogSpan.addSlot("word"); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/composite/SofaTracerCompositeDigestReporterImplTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/composite/SofaTracerCompositeDigestReporterImplTest.java index 8da07dbd..0e3c30d8 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/composite/SofaTracerCompositeDigestReporterImplTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/composite/SofaTracerCompositeDigestReporterImplTest.java @@ -28,7 +28,7 @@ * * @author * @version 1.0 - * @since
五月 8, 2018
+ * @since
May 8, 2018
*/ public class SofaTracerCompositeDigestReporterImplTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/digest/DiskReporterImplTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/digest/DiskReporterImplTest.java index 753cecd7..aa6b52a7 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/digest/DiskReporterImplTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/digest/DiskReporterImplTest.java @@ -47,7 +47,7 @@ * * @author * @version 1.0 - * @since
五月 25, 2018
+ * @since
May 25, 2018
*/ public class DiskReporterImplTest extends AbstractTestBase { @@ -162,7 +162,8 @@ public void testFixInitDigestFile() throws Exception { executor.execute(worker); } Thread.sleep(3 * 1000); - //未控制并发初始化时,report span 会报错;修复方法即初始化未完成时,其他线程需要等待初始化完成 + // When there is no control for concurrent initialization, report span will get an error; + // when the repair method is initialized,other threads need to wait for initialization to complete. List contents = FileUtils.readLines(tracerSelfLog()); assertTrue("Actual concurrent init file size = " + contents.size(), contents.size() == 1); } diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/digest/SofaTracerDigestReporterAsyncManagerTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/digest/SofaTracerDigestReporterAsyncManagerTest.java index 2080b9cd..ec99b662 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/digest/SofaTracerDigestReporterAsyncManagerTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/digest/SofaTracerDigestReporterAsyncManagerTest.java @@ -22,7 +22,6 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; - import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; @@ -32,8 +31,7 @@ /** * * @author abby.zh - * @version $Id: SofaTracerDigestReporterAsyncManagerTest.java, v 0.1 2018/11/12 4:55 PM abby.zh Exp $ - * @since 3.0.1 + * @since 2.5.1 */ public class SofaTracerDigestReporterAsyncManagerTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/stat/SofaTracerStatisticReporterImplTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/stat/SofaTracerStatisticReporterImplTest.java index 77276892..3b4259b2 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/stat/SofaTracerStatisticReporterImplTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/stat/SofaTracerStatisticReporterImplTest.java @@ -30,17 +30,14 @@ * * @author * @version 1.0 - * @since
七月 2, 2017
+ * @since
July 2, 2017
*/ public class SofaTracerStatisticReporterImplTest { - /*** - * 1s 钟统计一次 - */ private final long CYCLE_IN_SECONDS = 1; static { - //调整阈值可测性 + //Adjust threshold measurability SofaTracerStatisticReporterManager.CLEAR_STAT_KEY_THRESHOLD = 5; System.setProperty("com.alipay.ldc.zone", "GZ00A"); @@ -57,7 +54,8 @@ public static void afterCl() { } /** - * 测试keys太多,定时清空的场景 如单独测试,可以把TracerConfiguration.CLEAR_STAT_KEY_THRESHOLD调小以方便测试 + * Test too many keys, timed empty scenes. If you test separately, + * you can reduce TracerConfiguration.CLEAR_STAT_KEY_THRESHOLD to facilitate testing. */ @Test public void testClearKeys() throws InterruptedException { @@ -74,7 +72,7 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { }; - // case 1: 切换时没有达到阈值 + // case 1: Threshold not reached when switching for (int i = 0; i < SofaTracerStatisticReporterManager.CLEAR_STAT_KEY_THRESHOLD; i++) { StatKey statKey = new StatKey(); statKey.setKey(String.valueOf(i)); @@ -89,19 +87,19 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { Thread.sleep(100); } - // 此时发生过下标切换 + // Subscript switching occurred at this time Assert.assertEquals(0, statReporter.getStatData().size()); Assert.assertEquals(SofaTracerStatisticReporterManager.CLEAR_STAT_KEY_THRESHOLD, statReporter.getOtherStatData().size()); - // case 2: 切换时达到阈值 + // case 2: Threshold reached when switching for (int i = 0; i <= SofaTracerStatisticReporterManager.CLEAR_STAT_KEY_THRESHOLD; i++) { StatKey statKey = new StatKey(); statKey.setKey(String.valueOf(i)); statReporter.addStat(statKey, i); } - // 此时应该发生过下标切换 + // At this point, there should be a subscript switch currentSize = statReporter.getStatData().size(); while (true) { if (statReporter.getStatData().size() != currentSize) { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/stat/model/StatMapKeyTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/stat/model/StatMapKeyTest.java index 0e6ba398..4a3c56be 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/stat/model/StatMapKeyTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/reporter/stat/model/StatMapKeyTest.java @@ -27,7 +27,7 @@ * * @author * @version 1.0 - * @since
五月 15, 2018
+ * @since
May 15, 2018
*/ public class StatMapKeyTest { @@ -42,7 +42,7 @@ public void testAddKey() throws Exception { statMapKey.addKey("key3", "value3"); statMapKey.addKey("key4", "value4"); statMapKey.addKey("key5", "value5"); - // + StatMapKey statMapKey1 = new StatMapKey(); statMapKey1.addKey("key3", "value3"); statMapKey1.addKey("key4", "value4"); @@ -52,24 +52,24 @@ public void testAddKey() throws Exception { assertEquals(statMapKey.hashCode(), statMapKey1.hashCode()); assertEquals(statMapKey, statMapKey1); assertEquals(statMapKey.getKeyMap(), statMapKey1.getKeyMap()); - // + StatMapKey statMapKey2 = new StatMapKey(); statMapKey2.addKey("key3", "value3"); statMapKey2.addKey("key4", "value4"); statMapKey2.addKey("key5", "value5"); statMapKey2.addKey("key1", "value1"); assertFalse(statMapKey2.equals(statMapKey1)); - // + statMapKey.setEnd("f"); statMapKey.setResult("Y"); statMapKey.setLoadTest(false); assertFalse(statMapKey.equals(statMapKey1)); - // + statMapKey1.setEnd("t"); statMapKey1.setResult("Y"); statMapKey1.setLoadTest(false); assertFalse(statMapKey.equals(statMapKey1)); - // + statMapKey1.setEnd("f"); statMapKey1.setResult("Y"); statMapKey1.setLoadTest(false); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/span/SofaTracerSpanTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/span/SofaTracerSpanTest.java index 48fb61fc..f9e8b0ae 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/span/SofaTracerSpanTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/span/SofaTracerSpanTest.java @@ -42,7 +42,7 @@ * * @author * @version 1.0 - * @since
七月 6, 2017
+ * @since
July 6, 2017
*/ public class SofaTracerSpanTest extends AbstractTestBase { 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 1d4dd2a7..6375ffa9 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 @@ -38,12 +38,8 @@ import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; - -import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; - import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -53,7 +49,7 @@ * * @author * @version 1.0 - * @since
七月 1, 2017
+ * @since
July 1, 2017
*/ public class SofaTracerTest extends AbstractTestBase { @@ -135,7 +131,7 @@ public void put(String key, String value) { public void testReportSpan() throws Exception { SofaTracerSpan span = (SofaTracerSpan) this.sofaTracer.buildSpan("testInjectSpan") .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).start(); - //report 不要禁写 + //Report Do not prohibit writing span.finish(); TestUtil.waitForAsyncLog(); @@ -144,7 +140,7 @@ public void testReportSpan() throws Exception { .getDefaultLogName())); assertTrue(contents.get(0), contents.size() == 1); String contextStr = contents.get(0); - //测试打印一条只放了一个 tags + //Test print one only put one tag assertTrue(contextStr.contains(Tags.SPAN_KIND.getKey()) && contextStr.contains(Tags.SPAN_KIND_CLIENT)); } @@ -154,7 +150,7 @@ public void testReportSpan() throws Exception { */ @Test public void testIsDisableAllDigestLog() { - //全局关闭摘要日志 + //Close the digest log globally SofaTracerConfiguration.setProperty( SofaTracerConfiguration.DISABLE_MIDDLEWARE_DIGEST_LOG_KEY, "true"); SofaTracerSpan span = (SofaTracerSpan) this.sofaTracer.buildSpan("testInjectSpan") @@ -169,7 +165,7 @@ public void testIsDisableAllDigestLog() { @Test public void testIsDisableClientDigestLog() { - //关闭client摘要日志 + //Close the client digest log String clientLogTypeName = TracerTestLogEnum.RPC_CLIENT.getDefaultLogName(); Map prop = new HashMap(); @@ -182,7 +178,7 @@ public void testIsDisableClientDigestLog() { span.finish(); assertTrue(!customFileLog(clientLogTypeName).exists()); SofaTracerConfiguration.setProperty(SofaTracerConfiguration.DISABLE_DIGEST_LOG_KEY, - new HashMap()); + new HashMap<>()); } /** @@ -207,7 +203,6 @@ public void testTracerClose() { SofaTracer sofaTracer = new SofaTracer.Builder(tracerType).withClientReporter(reporter) .withSampler(sampler).build(); sofaTracer.close(); - //确认被调用 verify(reporter).close(); sampler.close(); verify(sampler).close(); @@ -323,7 +318,7 @@ public void testAsChildOfParentTestBizBaggageAndSysBaggage() { /** * Method: asChildOf(Span parentSpan) - * 多个的时候,baggage 复用 只选择第一个父亲 + * Multiple times, baggage reuse only select the first father */ @Test public void testAsChildOfMultiParentSpan() { @@ -406,9 +401,6 @@ public void testAddReferenceForReferenceTypeReferencedContextAndBaggageMultipleR String fol1BagKey = "fol1BagKey"; String fol1BagValue = "fol1BagValue"; spanFollow1.setBaggageItem(fol1BagKey, fol1BagValue); - - String followTraceId1 = spanFollow1.getSofaTracerSpanContext().getTraceId(); - String followSpanId1 = spanFollow1.getSofaTracerSpanContext().getSpanId(); //follow1 SofaTracerSpan spanFollow2 = (SofaTracerSpan) this.sofaTracer.buildSpan("spanFollow2") .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).start(); diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/type/TracerTestLogEnum.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/type/TracerTestLogEnum.java index faa3802e..7a9838d1 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/type/TracerTestLogEnum.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/tracertest/type/TracerTestLogEnum.java @@ -24,23 +24,15 @@ */ public enum TracerTestLogEnum { - // 其他日志 - RPC_CLIENT("rpc_client_log_name", "rpc_client.log", "rpc_client_rolling"), // 业务成功日志 - RPC_SERVER("rpc_server_log_name", "rpc_server.log", "rpc_server_rolling");// 业务异常日志 + RPC_CLIENT("rpc_client_log_name", "rpc_client.log", "rpc_client_rolling"), RPC_SERVER( + "rpc_server_log_name", + "rpc_server.log", + "rpc_server_rolling"); - /*** - * 获取保留天数 getLogReverseDay 关键字 - */ private String logReverseKey; - /*** - * 默认生成的日志名字 .log 结尾同时作为一个类型 - */ private String defaultLogName; - /*** - * 日志的滚动策略 - */ private String rollingKey; TracerTestLogEnum(String logReverseKey, String defaultLogName, String rollingKey) { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/utils/StringUtilsTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/utils/StringUtilsTest.java index 881bb497..86bdc0b0 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/utils/StringUtilsTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/utils/StringUtilsTest.java @@ -25,7 +25,7 @@ * * @author * @version 1.0 - * @since
五月 15, 2018
+ * @since
May 15, 2018
*/ public class StringUtilsTest { diff --git a/tracer-core/src/test/java/com/alipay/common/tracer/core/utils/TracerUtilsTest.java b/tracer-core/src/test/java/com/alipay/common/tracer/core/utils/TracerUtilsTest.java index 3d03235b..99f4273c 100644 --- a/tracer-core/src/test/java/com/alipay/common/tracer/core/utils/TracerUtilsTest.java +++ b/tracer-core/src/test/java/com/alipay/common/tracer/core/utils/TracerUtilsTest.java @@ -37,20 +37,20 @@ * * @author * @version 1.0 - * @since
七月 2, 2017
+ * @since
July 2, 2017
*/ public class TracerUtilsTest { - /*** - *测试去除URL中的JSessionId_URL为null + /** + * Test removes the JSessionId_URL in the URL to null */ @Test public void JSessionId_URL_is_null() { Assert.assertNull(TracerUtils.removeJSessionIdFromUrl(null)); } - /*** - * 测试去除URL中的JSessionId_URL为空字符串 + /** + * Test removes the JSessionId_URL in the URL to "" */ @Test public void JSessionId_URL_EMPTY() { @@ -58,8 +58,8 @@ public void JSessionId_URL_EMPTY() { TracerUtils.removeJSessionIdFromUrl(StringUtils.EMPTY_STRING)); } - /*** - * 测试去除URL中的JSessionId_URL不包含JSessionId + /** + * The JSessionId_URL in the test removal URL does not contain the JSessionId */ @Test public void JSessionId_URL_NO_JSessionId() { @@ -67,8 +67,8 @@ public void JSessionId_URL_NO_JSessionId() { Assert.assertEquals(url, TracerUtils.removeJSessionIdFromUrl(url)); } - /*** - * 测试去除URL中的JSessionId_URL包含JSessionId + /** + * The JSessionId_URL in the test removal URL contain the JSessionId */ @Test public void JSessionId_URL包含JSessionId() { @@ -87,7 +87,7 @@ public void testGetPID() throws Exception { } @Test - public void 测试_mapToString() { + public void test_mapToString() { Map strMap = new TreeMap(); strMap.put("test1", "test="); strMap.put("test2", "test&"); @@ -97,7 +97,7 @@ public void testGetPID() throws Exception { } @Test - public void 测试_stringToMap() { + public void test_stringToMap() { Map strMap = new HashMap(); StringUtils .stringToMap("test1=test" + XStringBuilder.EQUAL_SEPARATOR_ESCAPE + "&test2=test" @@ -106,30 +106,33 @@ public void testGetPID() throws Exception { Assert.assertEquals("test&", strMap.get("test2")); } - /*** - * 测试_mapToString_stringToMap_包含百分号 + /** + * test_mapToString_stringToMap_contains_percent_sign */ @Test - public void mapToString_stringToMap_() { - Map strMap = new HashMap(); + public void mapToString_stringToMap_contains_percent_sign() { + Map strMap = new HashMap<>(); String key = "test1"; String value = "test" + XStringBuilder.AND_SEPARATOR_ESCAPE; strMap.put(key, value); String result = StringUtils.mapToString(strMap); - Map decodeMap = new HashMap(); + Map decodeMap = new HashMap<>(); StringUtils.stringToMap(result, decodeMap); Assert.assertEquals(value, decodeMap.get(key)); } + /** + * Test parsing log retention time configuration + */ @Test - public void 测试解析日志保留时间配置() { + public void testParseLogRetentionTimeConfig() { LogReserveConfig logReserveConfig = TracerUtils.parseLogReserveConfig("0D1H"); Assert.assertEquals(0, logReserveConfig.getDay()); Assert.assertEquals(1, logReserveConfig.getHour()); } - /*** - * 测试纯数字的日志保留时间配置 + /** + * Test purely digital log retention time configuration */ @Test public void testParseLogReserveConfigByNumber() { @@ -143,7 +146,7 @@ public void testCheckBaggageLength() { SofaTracer sofaTracer = mock(SofaTracer.class); SofaTracerSpanContext sofaTracerSpanContext = new SofaTracerSpanContext(); SofaTracerSpan sofaTracerSpan = new SofaTracerSpan(sofaTracer, System.currentTimeMillis(), - "mock", sofaTracerSpanContext, new HashMap()); + "mock", sofaTracerSpanContext, new HashMap<>()); assertTrue(TracerUtils.checkBaggageLength(sofaTracerSpan, "key", "value")); } From 441bf57c9508fdafd2ebd531fd80d704b7a85ffd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Thu, 1 Aug 2019 16:21:08 +0800 Subject: [PATCH 21/24] cheery pick constants --- .../plugins/datasource/SmartDataSource.java | 2 +- .../DataSourceClientDigestJsonEncoder.java | 14 +++--- .../DataSourceClientStatJsonReporter.java | 20 ++++---- .../tracer/DataSourceClientTracer.java | 8 +-- .../tracer/StatementTracerInterceptor.java | 5 +- .../datasource/utils/DataSourceUtils.java | 2 +- .../tracer/plugins/datasource/DruidTest.java | 2 +- .../plugins/dubbo/DubboSofaTracerFilter.java | 18 +++---- .../encoder/DubboServerDigestJsonEncoder.java | 11 ++-- .../stat/DubboClientStatJsonReporter.java | 20 ++++---- .../stat/DubboServerStatJsonReporter.java | 19 ++++--- .../dubbo/tracer/DubboConsumerSofaTracer.java | 4 +- .../dubbo/tracer/DubboProviderSofaTracer.java | 4 +- .../constants/ComponentNameConstants.java | 39 +++++++++++++++ .../core/constants/SofaTracerConstant.java | 37 ++++++++++++++ .../tracer/core/span/CommonSpanTags.java | 50 +++++++++++++++---- 16 files changed, 185 insertions(+), 70 deletions(-) create mode 100644 tracer-core/src/main/java/com/alipay/common/tracer/core/constants/ComponentNameConstants.java diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/SmartDataSource.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/SmartDataSource.java index 7e520e40..9d8f3bc3 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/SmartDataSource.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/SmartDataSource.java @@ -19,7 +19,6 @@ import com.alipay.common.tracer.core.utils.StringUtils; import com.alipay.sofa.tracer.plugins.datasource.tracer.*; import com.alipay.sofa.tracer.plugins.datasource.utils.DataSourceUtils; -import com.alipay.sofa.tracer.plugins.datasource.tracer.Endpoint; import javax.sql.DataSource; import java.util.ArrayList; @@ -93,6 +92,7 @@ public List getTraceAnnotations() { /** * init method must be invoked first after construction */ + @Override public void init() { if (initialized.compareAndSet(false, true)) { if (StringUtils.isBlank(dbType)) { diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientDigestJsonEncoder.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientDigestJsonEncoder.java index 53cbb53d..cc73ad76 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientDigestJsonEncoder.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientDigestJsonEncoder.java @@ -23,7 +23,7 @@ import com.alipay.common.tracer.core.middleware.parent.AbstractDigestSpanEncoder; import com.alipay.common.tracer.core.span.CommonSpanTags; import com.alipay.common.tracer.core.span.SofaTracerSpan; -import java.io.IOException; + import java.util.Map; /** @@ -32,10 +32,11 @@ * @since 2.2.0 */ public class DataSourceClientDigestJsonEncoder extends AbstractDigestSpanEncoder { + @Override - public String encode(SofaTracerSpan span) throws IOException { + public String encode(SofaTracerSpan span) { JsonStringBuilder jsonStringBuilder = new JsonStringBuilder(); - jsonStringBuilder.appendBegin("time", Timestamp.format(span.getEndTime())); + jsonStringBuilder.appendBegin(CommonSpanTags.TIME, Timestamp.format(span.getEndTime())); appendSlot(jsonStringBuilder, span); return jsonStringBuilder.toString(); } @@ -48,9 +49,9 @@ private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofa jsonStringBuilder .append(CommonSpanTags.LOCAL_APP, tagWithStr.get(CommonSpanTags.LOCAL_APP)); //TraceId - jsonStringBuilder.append("traceId", context.getTraceId()); + jsonStringBuilder.append(CommonSpanTags.TRACE_ID, context.getTraceId()); //SpanId - jsonStringBuilder.append("spanId", context.getSpanId()); + jsonStringBuilder.append(CommonSpanTags.SPAN_ID, context.getSpanId()); //schema jsonStringBuilder.append(DataSourceTracerKeys.DATABASE_NAME, tagWithStr.get(DataSourceTracerKeys.DATABASE_NAME)); @@ -86,6 +87,7 @@ private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofa private void appendBaggage(JsonStringBuilder jsonStringBuilder, SofaTracerSpanContext sofaTracerSpanContext) { //baggage - jsonStringBuilder.appendEnd("baggage", baggageSerialized(sofaTracerSpanContext)); + jsonStringBuilder.appendEnd(CommonSpanTags.BAGGAGE, + baggageSerialized(sofaTracerSpanContext)); } } \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientStatJsonReporter.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientStatJsonReporter.java index 2b534969..fc644ce6 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientStatJsonReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientStatJsonReporter.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.appender.file.LoadTestAwareAppender; import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.appender.self.Timestamp; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.reporter.stat.model.StatKey; import com.alipay.common.tracer.core.reporter.stat.model.StatMapKey; @@ -50,8 +51,9 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { tagsWithStr.get(DataSourceTracerKeys.DATABASE_NAME)); statKey.addKey(DataSourceTracerKeys.SQL, tagsWithStr.get(DataSourceTracerKeys.SQL)); //result - String result = DataSourceClientTracer.RESULT_CODE_SUCCESS.equals(tagsWithStr - .get(DataSourceTracerKeys.RESULT_CODE)) ? "true" : "false"; + String result = SofaTracerConstant.RESULT_CODE_SUCCESS.equals(tagsWithStr + .get(DataSourceTracerKeys.RESULT_CODE)) ? SofaTracerConstant.STAT_FLAG_SUCCESS + : SofaTracerConstant.STAT_FLAG_FAILS; statKey.setResult(result); //pressure mark statKey.setLoadTest(TracerUtils.isLoadTest(sofaTracerSpan)); @@ -59,7 +61,7 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { statKey.setEnd(TracerUtils.getLoadTestMark(sofaTracerSpan)); //value the count and duration long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); - long values[] = new long[] { 1, duration }; + long[] values = new long[] { 1, duration }; //reserve this.addStat(statKey, values); } @@ -77,13 +79,13 @@ public void print(StatKey statKey, long[] values) { try { jsonBuffer.reset(); jsonBuffer.appendBegin(); - jsonBuffer.append("time", Timestamp.currentTime()); - jsonBuffer.append("stat.key", this.statKeySplit(statMapKey)); - jsonBuffer.append("count", values[0]); - jsonBuffer.append("total.cost.milliseconds", values[1]); - jsonBuffer.append("success", statMapKey.getResult()); + jsonBuffer.append(CommonSpanTags.TIME, Timestamp.currentTime()); + jsonBuffer.append(CommonSpanTags.STAT_KEY, this.statKeySplit(statMapKey)); + jsonBuffer.append(CommonSpanTags.COUNT, values[0]); + jsonBuffer.append(CommonSpanTags.TOTAL_COST_MILLISECONDS, values[1]); + jsonBuffer.append(CommonSpanTags.SUCCESS, statMapKey.getResult()); //pressure - jsonBuffer.appendEnd("load.test", statMapKey.getEnd()); + jsonBuffer.appendEnd(CommonSpanTags.LOAD_TEST, statMapKey.getEnd()); if (appender instanceof LoadTestAwareAppender) { ((LoadTestAwareAppender) appender).append(jsonBuffer.toString(), diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientTracer.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientTracer.java index d0f98f73..c182ed65 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientTracer.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/DataSourceClientTracer.java @@ -19,6 +19,7 @@ import com.alipay.common.tracer.core.appender.encoder.SpanEncoder; import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.constants.ComponentNameConstants; import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; import com.alipay.common.tracer.core.context.trace.SofaTraceContext; import com.alipay.common.tracer.core.holder.SofaTraceContextHolder; @@ -41,13 +42,8 @@ protected DataSourceTracerState initialValue() { return null; } }; - private volatile static DataSourceClientTracer dataSourceClientTracer = null; - public static final String RESULT_CODE_SUCCESS = "success"; - - public static final String RESULT_CODE_FAILED = "failed"; - /*** * DataSource Client Tracer Singleton * @return singleton @@ -64,7 +60,7 @@ public static DataSourceClientTracer getDataSourceClientTracer() { } private DataSourceClientTracer() { - super("dataSource"); + super(ComponentNameConstants.DATA_SOURCE); } @Override diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/StatementTracerInterceptor.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/StatementTracerInterceptor.java index ad736833..25489356 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/StatementTracerInterceptor.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/tracer/StatementTracerInterceptor.java @@ -16,6 +16,7 @@ */ package com.alipay.sofa.tracer.plugins.datasource.tracer; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.sofa.tracer.plugins.datasource.Interceptor; /** @@ -34,12 +35,12 @@ public void setClientTracer(DataSourceClientTracer clientTracer) { @Override public Object intercept(Chain chain) throws Exception { long start = System.currentTimeMillis(); - String resultCode = DataSourceClientTracer.RESULT_CODE_SUCCESS; + String resultCode = SofaTracerConstant.RESULT_SUCCESS; try { clientTracer.startTrace(chain.getOriginalSql()); return chain.proceed(); } catch (Exception e) { - resultCode = DataSourceClientTracer.RESULT_CODE_FAILED; + resultCode = SofaTracerConstant.RESULT_FAILED; throw e; } finally { clientTracer.endTrace(System.currentTimeMillis() - start, resultCode); diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java index 8c7cbf5e..c0518bfe 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java @@ -259,7 +259,7 @@ public static String resolveDatabaseFromUrl(String url) { int start = url.lastIndexOf("/"); if (start < 0) { /** - * oracle sid 格式,{@see jdbc:oracle:thin:@host:port:SID} + * oracle sid format,{@see jdbc:oracle:thin:@host:port:SID} */ if ("oracle".equals(resolveDbTypeFromUrl(url))) { start = url.lastIndexOf(":"); diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DruidTest.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DruidTest.java index 2ab79972..5f824a1a 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DruidTest.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DruidTest.java @@ -34,7 +34,7 @@ import static org.mockito.Mockito.when; /** - * @author qilong.zql 18/8/27-上午9:23 + * @author qilong.zql 18/8/27-AM 9:23 */ public class DruidTest extends BaseTest { diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java index a71f64a7..10dec2fc 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java @@ -18,6 +18,7 @@ import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext; import com.alipay.common.tracer.core.context.trace.SofaTraceContext; import com.alipay.common.tracer.core.holder.SofaTraceContextHolder; @@ -50,10 +51,6 @@ public class DubboSofaTracerFilter implements Filter { private static final String BLANK = StringUtils.EMPTY_STRING; - private static final String SUCCESS_CODE = "00"; - - private static final String FAILED_CODE = "99"; - private static final String SPAN_INVOKE_KEY = "sofa.current.span.key"; private DubboConsumerSofaTracer dubboConsumerSofaTracer; @@ -102,14 +99,14 @@ public Result onResponse(Result result, Invoker invoker, Invocation invocatio this.dubboConsumerSofaTracer = DubboConsumerSofaTracer .getDubboConsumerSofaTracerSingleton(); } - String resultCode = SUCCESS_CODE; + String resultCode = SofaTracerConstant.RESULT_CODE_SUCCESS; if (result.hasException()) { if (result.getException() instanceof RpcException) { resultCode = Integer.toString(((RpcException) result.getException()) .getCode()); sofaTracerSpan.setTag(CommonSpanTags.RESULT_CODE, resultCode); } else { - resultCode = FAILED_CODE; + resultCode = SofaTracerConstant.RESULT_CODE_ERROR; } } // add elapsed time @@ -166,7 +163,7 @@ private Result doClientFilter(RpcContext rpcContext, Invoker invoker, Invocat } Result result; Throwable exception = null; - String resultCode = SUCCESS_CODE; + String resultCode = SofaTracerConstant.RESULT_CODE_SUCCESS; try { // do invoke result = invoker.invoke(invocation); @@ -193,7 +190,7 @@ private Result doClientFilter(RpcContext rpcContext, Invoker invoker, Invocat RpcException rpcException = (RpcException) exception; resultCode = String.valueOf(rpcException.getCode()); } else { - resultCode = FAILED_CODE; + resultCode = SofaTracerConstant.RESULT_CODE_ERROR; } } @@ -242,7 +239,6 @@ private Result doServerFilter(RpcContext rpcContext, Invoker invoker, Invocat Throwable exception = null; try { result = invoker.invoke(invocation); - // 处理返回结果 if (result == null) { return null; } else { @@ -259,7 +255,7 @@ private Result doServerFilter(RpcContext rpcContext, Invoker invoker, Invocat exception = t; throw new RpcException(t); } finally { - String resultCode = SUCCESS_CODE; + String resultCode = SofaTracerConstant.RESULT_CODE_SUCCESS; if (exception != null) { if (exception instanceof RpcException) { sofaTracerSpan.setTag(Tags.ERROR.getKey(), exception.getMessage()); @@ -268,7 +264,7 @@ private Result doServerFilter(RpcContext rpcContext, Invoker invoker, Invocat resultCode = String.valueOf(rpcException.getCode()); } } else { - resultCode = FAILED_CODE; + resultCode = SofaTracerConstant.RESULT_CODE_ERROR; } } dubboProviderSofaTracer.serverSend(resultCode); diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/encoder/DubboServerDigestJsonEncoder.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/encoder/DubboServerDigestJsonEncoder.java index 67138081..edf0a3fc 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/encoder/DubboServerDigestJsonEncoder.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/encoder/DubboServerDigestJsonEncoder.java @@ -38,14 +38,14 @@ public class DubboServerDigestJsonEncoder extends AbstractDigestSpanEncoder { public String encode(SofaTracerSpan sofaTracerSpan) throws IOException { JsonStringBuilder data = new JsonStringBuilder(); //span end time - data.appendBegin("time", Timestamp.format(sofaTracerSpan.getEndTime())); + data.appendBegin(CommonSpanTags.TIME, Timestamp.format(sofaTracerSpan.getEndTime())); Map tagStr = sofaTracerSpan.getTagsWithStr(); Map tagNum = sofaTracerSpan.getTagsWithNumber(); SofaTracerSpanContext context = sofaTracerSpan.getSofaTracerSpanContext(); //TraceId - data.append("traceId", context.getTraceId()); + data.append(CommonSpanTags.TRACE_ID, context.getTraceId()); //SpanId - data.append("spanId", context.getSpanId()); + data.append(CommonSpanTags.SPAN_ID, context.getSpanId()); //Span Type data.append(Tags.SPAN_KIND.getKey(), tagStr.get(Tags.SPAN_KIND.getKey())); //local appName @@ -74,7 +74,7 @@ public String encode(SofaTracerSpan sofaTracerSpan) throws IOException { data.append(CommonSpanTags.CURRENT_THREAD_NAME, tagStr.get(CommonSpanTags.CURRENT_THREAD_NAME)); //time-consuming ms - data.append("time.cost.milliseconds", + data.append(CommonSpanTags.TIME_COST_MILLISECONDS, (sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime())); this.appendBaggage(data, context); return data.toString(); @@ -90,6 +90,7 @@ private long getTime(Number number) { private void appendBaggage(JsonStringBuilder jsonStringBuilder, SofaTracerSpanContext sofaTracerSpanContext) { //baggage - jsonStringBuilder.appendEnd("baggage", baggageSerialized(sofaTracerSpanContext)); + jsonStringBuilder.appendEnd(CommonSpanTags.BAGGAGE, + baggageSerialized(sofaTracerSpanContext)); } } diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboClientStatJsonReporter.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboClientStatJsonReporter.java index bbd439f0..ef2d6354 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboClientStatJsonReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboClientStatJsonReporter.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.appender.file.LoadTestAwareAppender; import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.appender.self.Timestamp; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.reporter.stat.model.StatKey; import com.alipay.common.tracer.core.reporter.stat.model.StatMapKey; @@ -58,14 +59,15 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { String methodName = tagsWithStr.get(CommonSpanTags.METHOD); statKey.setKey(buildString(new String[] { fromApp, toApp, serviceName, methodName })); String resultCode = tagsWithStr.get(CommonSpanTags.RESULT_CODE); - statKey.setResult(resultCode.equals("00") ? "Y" : "N"); + statKey + .setResult(SofaTracerConstant.RESULT_CODE_SUCCESS.equals(resultCode) ? SofaTracerConstant.STAT_FLAG_SUCCESS + : SofaTracerConstant.STAT_FLAG_FAILS); statKey.setEnd(buildString(new String[] { getLoadTestMark(sofaTracerSpan) })); statKey.setLoadTest(TracerUtils.isLoadTest(sofaTracerSpan)); statKey.addKey(CommonSpanTags.LOCAL_APP, fromApp); statKey.addKey(CommonSpanTags.REMOTE_APP, toApp); statKey.addKey(CommonSpanTags.SERVICE, serviceName); statKey.addKey(CommonSpanTags.METHOD, methodName); - //次数和耗时,最后一个耗时是单独打印的字段 long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); long[] values = new long[] { 1, duration }; this.addStat(statKey, values); @@ -82,18 +84,18 @@ protected String getLoadTestMark(SofaTracerSpan span) { @Override public void print(StatKey statKey, long[] values) { if (this.isClosePrint.get()) { - //关闭统计日志输出 + //Close the statistics log output return; } StatMapKey statMapKey = (StatMapKey) statKey; jsonBuffer.reset(); - jsonBuffer.appendBegin("time", Timestamp.currentTime()); - jsonBuffer.append("stat.key", this.statKeySplit(statMapKey)); - jsonBuffer.append("count", values[0]); - jsonBuffer.append("total.cost.milliseconds", values[1]); - jsonBuffer.append("success", statMapKey.getResult()); + jsonBuffer.appendBegin(CommonSpanTags.TIME, Timestamp.currentTime()); + jsonBuffer.append(CommonSpanTags.STAT_KEY, this.statKeySplit(statMapKey)); + jsonBuffer.append(CommonSpanTags.COUNT, values[0]); + jsonBuffer.append(CommonSpanTags.TIME_COST_MILLISECONDS, values[1]); + jsonBuffer.append(CommonSpanTags.SUCCESS, statMapKey.getResult()); jsonBuffer.appendEnd(); try { if (appender instanceof LoadTestAwareAppender) { @@ -102,7 +104,7 @@ public void print(StatKey statKey, long[] values) { } else { appender.append(jsonBuffer.toString()); } - // 这里强制刷一次 + // Forced to flush appender.flush(); } catch (Throwable t) { SelfLog.error("stat log<" + statTracerName + "> error!", t); diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboServerStatJsonReporter.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboServerStatJsonReporter.java index 12acdfba..a3305394 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboServerStatJsonReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboServerStatJsonReporter.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.appender.file.LoadTestAwareAppender; import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.appender.self.Timestamp; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.reporter.stat.model.StatKey; import com.alipay.common.tracer.core.reporter.stat.model.StatMapKey; @@ -58,7 +59,9 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { String methodName = tagsWithStr.get(CommonSpanTags.METHOD); statKey.setKey(buildString(new String[] { fromApp, toApp, serviceName, methodName })); String resultCode = tagsWithStr.get(CommonSpanTags.RESULT_CODE); - statKey.setResult(resultCode.equals("00") ? "Y" : "N"); + statKey + .setResult(SofaTracerConstant.RESULT_CODE_SUCCESS.equals(resultCode) ? SofaTracerConstant.STAT_FLAG_SUCCESS + : SofaTracerConstant.STAT_FLAG_FAILS); statKey.setEnd(buildString(new String[] { getLoadTestMark(sofaTracerSpan) })); statKey.setLoadTest(TracerUtils.isLoadTest(sofaTracerSpan)); statKey.addKey(CommonSpanTags.LOCAL_APP, fromApp); @@ -82,18 +85,18 @@ protected String getLoadTestMark(SofaTracerSpan span) { @Override public void print(StatKey statKey, long[] values) { if (this.isClosePrint.get()) { - //关闭统计日志输出 + //Close the statistics log output return; } StatMapKey statMapKey = (StatMapKey) statKey; jsonBuffer.reset(); - jsonBuffer.appendBegin("time", Timestamp.currentTime()); - jsonBuffer.append("stat.key", this.statKeySplit(statMapKey)); - jsonBuffer.append("count", values[0]); - jsonBuffer.append("total.cost.milliseconds", values[1]); - jsonBuffer.append("success", statMapKey.getResult()); + jsonBuffer.appendBegin(CommonSpanTags.TIME, Timestamp.currentTime()); + jsonBuffer.append(CommonSpanTags.STAT_KEY, this.statKeySplit(statMapKey)); + jsonBuffer.append(CommonSpanTags.COUNT, values[0]); + jsonBuffer.append(CommonSpanTags.TIME_COST_MILLISECONDS, values[1]); + jsonBuffer.append(CommonSpanTags.SUCCESS, statMapKey.getResult()); jsonBuffer.appendEnd(); try { if (appender instanceof LoadTestAwareAppender) { @@ -102,7 +105,7 @@ public void print(StatKey statKey, long[] values) { } else { appender.append(jsonBuffer.toString()); } - // 这里强制刷一次 + // Forced to flush appender.flush(); } catch (Throwable t) { SelfLog.error("stat log <" + statTracerName + "> error!", t); diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/tracer/DubboConsumerSofaTracer.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/tracer/DubboConsumerSofaTracer.java index f4d5798f..13bea5fd 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/tracer/DubboConsumerSofaTracer.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/tracer/DubboConsumerSofaTracer.java @@ -18,6 +18,7 @@ import com.alipay.common.tracer.core.appender.encoder.SpanEncoder; import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.constants.ComponentNameConstants; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tracer.AbstractClientTracer; @@ -37,7 +38,8 @@ public static DubboConsumerSofaTracer getDubboConsumerSofaTracerSingleton() { if (dubboConsumerSofaTracer == null) { synchronized (DubboConsumerSofaTracer.class) { if (dubboConsumerSofaTracer == null) { - dubboConsumerSofaTracer = new DubboConsumerSofaTracer("dubbo-client"); + dubboConsumerSofaTracer = new DubboConsumerSofaTracer( + ComponentNameConstants.DUBBO_CLIENT); } } } diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/tracer/DubboProviderSofaTracer.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/tracer/DubboProviderSofaTracer.java index b02dd871..fcd1cb19 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/tracer/DubboProviderSofaTracer.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/tracer/DubboProviderSofaTracer.java @@ -18,6 +18,7 @@ import com.alipay.common.tracer.core.appender.encoder.SpanEncoder; import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.constants.ComponentNameConstants; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tracer.AbstractServerTracer; @@ -37,7 +38,8 @@ public static DubboProviderSofaTracer getDubboProviderSofaTracerSingleton() { if (dubboProviderSofaTracer == null) { synchronized (DubboProviderSofaTracer.class) { if (dubboProviderSofaTracer == null) { - dubboProviderSofaTracer = new DubboProviderSofaTracer("dubbo-server"); + dubboProviderSofaTracer = new DubboProviderSofaTracer( + ComponentNameConstants.DUBBO_SERVER); } } } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/ComponentNameConstants.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/ComponentNameConstants.java new file mode 100644 index 00000000..e77f8047 --- /dev/null +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/ComponentNameConstants.java @@ -0,0 +1,39 @@ +/* + * 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. + */ +package com.alipay.common.tracer.core.constants; + +/** + * Component Name Constants + * @author: guolei.sgl (guolei.sgl@antfin.com) 2019/4/8 9:16 PM + * @since: + **/ +public class ComponentNameConstants { + + public static final String DATA_SOURCE = "dataSource"; + + public static final String DUBBO_CLIENT = "dubbo-client"; + + public static final String DUBBO_SERVER = "dubbo-server"; + + public static final String HTTP_CLIENT = "httpclient"; + + public static final String OK_HTTP = "okhttp"; + + public static final String REST_TEMPLATE = "resttemplate"; + + public static final String SPRING_MVC = "springmvc"; +} diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/SofaTracerConstant.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/SofaTracerConstant.java index 518c42df..819b733c 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/SofaTracerConstant.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/constants/SofaTracerConstant.java @@ -83,4 +83,41 @@ public class SofaTracerConstant { * Return value in case of non-pressure measurement {@link AbstractSofaTracerStatisticReporter} */ public static final String NON_LOAD_TEST_VALUE = "F"; + + /** + * Result code for time out + */ + public static final String RESULT_CODE_TIME_OUT = "03"; + /** + * Result code for success + */ + public static final String RESULT_CODE_SUCCESS = "00"; + /** + * Result code for failure + */ + public static final String RESULT_CODE_ERROR = "99"; + /** + * Result state for success + */ + public static final String RESULT_SUCCESS = "success"; + /** + * Result state for failed + */ + public static final String RESULT_FAILED = "failed"; + /** + * digest result state for success + */ + public static final String DIGEST_FLAG_SUCCESS = "Y"; + /** + * digest result state for failure + */ + public static final String DIGEST_FLAG_FAILS = "N"; + /** + * stat result state for success + */ + public static final String STAT_FLAG_SUCCESS = "true"; + /** + * stat result state for failure + */ + public static final String STAT_FLAG_FAILS = "false"; } diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java index fa4c3c9c..fb77bc0c 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java @@ -123,21 +123,53 @@ public class CommonSpanTags { */ public static final String SERVER_DESERIALIZE_TIME = "server.deserialize.time"; - public static final String COMPONENT_CLIENT = "component.client.impl"; /** - * HYSTRIX_COMMAND_KEY records the hystrix commandKey. + * SPAN_ID records the current span's id */ - public static final String HYSTRIX_COMMAND_KEY = "hystrix.command.key"; + public static final String SPAN_ID = "spanId"; + + /** + * TRACE_ID records the current span's traceId + */ + public static final String TRACE_ID = "traceId"; + /** - * HYSTRIX_COMMAND_GROUP_KEY records the hystrix commandGroup. + * BAGGAGE records the span's baggage */ - public static final String HYSTRIX_COMMAND_GROUP_KEY = "hystrix.command.group"; + public static final String BAGGAGE = "baggage"; + + /** + * TIME records the current span's begin time + */ + public static final String TIME = "time"; + + /** + * TIME_COST_MILLISECONDS records the current span's cost time + */ + public static final String TIME_COST_MILLISECONDS = "time.cost.milliseconds"; + /** - * HYSTRIX_THREAD_POOL_KEY records the hystrix threadPoolKey. + * TOTAL_COST_MILLISECONDS records the span's cost time period */ - public static final String HYSTRIX_THREAD_POOL_KEY = "hystrix.threadpool.key"; + public static final String TOTAL_COST_MILLISECONDS = "total.cost.milliseconds"; + + /** + * STAT_KEY is the span's stat log key for stat.key + */ + public static final String STAT_KEY = "stat.key"; + + /** + * COUNT is the span's stat log key for count + */ + public static final String COUNT = "count"; + + /** + * SUCCESS is the span's stat log key for success + */ + public static final String SUCCESS = "success"; + /** - * HYSTRIX_FALLBACK_METHOD_NAME_KEY records the hystrix fallbackMethodName. + * LOAD_TEST is the span's stat log key for load.test */ - public static final String HYSTRIX_FALLBACK_METHOD_NAME_KEY = "hystrix.fallback.methodname"; + public static final String LOAD_TEST = "load.test"; } \ No newline at end of file From ad27bb6ca68c3450919ab4d59d5f61ec65efb917 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Thu, 1 Aug 2019 16:29:52 +0800 Subject: [PATCH 22/24] cheery pick clean code and use en comment --- .../plugins/datasource/SmartDataSource.java | 2 +- .../datasource/utils/DataSourceUtils.java | 2 +- .../tracer/plugins/datasource/DruidTest.java | 2 +- .../plugins/dubbo/DubboSofaTracerFilter.java | 5 +--- .../stat/DubboClientStatJsonReporter.java | 5 ++-- .../stat/DubboServerStatJsonReporter.java | 4 +-- .../dubbo/wrapper/DataSizeCodecWrapper.java | 29 +++++++++---------- .../AbstractHttpRequestInterceptor.java | 5 ++-- .../SofaTracerOkHttpInterceptor.java | 4 +-- .../springmvc/SpringMvcJsonStatReporter.java | 8 ++--- .../plugins/springmvc/SpringMvcLogEnum.java | 6 ++-- .../springmvc/SpringMvcSofaTracerFilter.java | 5 ---- .../springmvc/SpringMvcStatReporter.java | 3 +- .../ZipkinSofaTracerSpanRemoteReporter.java | 8 ++--- .../zipkin/adapter/ZipkinV2SpanAdapter.java | 4 +-- .../zipkin/ZipkinRestTemplateSenderTest.java | 4 +-- .../SofaTracerStatisticsDemoTest.java | 12 ++++---- 17 files changed, 46 insertions(+), 62 deletions(-) diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/SmartDataSource.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/SmartDataSource.java index 7e520e40..9d8f3bc3 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/SmartDataSource.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/SmartDataSource.java @@ -19,7 +19,6 @@ import com.alipay.common.tracer.core.utils.StringUtils; import com.alipay.sofa.tracer.plugins.datasource.tracer.*; import com.alipay.sofa.tracer.plugins.datasource.utils.DataSourceUtils; -import com.alipay.sofa.tracer.plugins.datasource.tracer.Endpoint; import javax.sql.DataSource; import java.util.ArrayList; @@ -93,6 +92,7 @@ public List getTraceAnnotations() { /** * init method must be invoked first after construction */ + @Override public void init() { if (initialized.compareAndSet(false, true)) { if (StringUtils.isBlank(dbType)) { diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java index 8c7cbf5e..c0518bfe 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/main/java/com/alipay/sofa/tracer/plugins/datasource/utils/DataSourceUtils.java @@ -259,7 +259,7 @@ public static String resolveDatabaseFromUrl(String url) { int start = url.lastIndexOf("/"); if (start < 0) { /** - * oracle sid 格式,{@see jdbc:oracle:thin:@host:port:SID} + * oracle sid format,{@see jdbc:oracle:thin:@host:port:SID} */ if ("oracle".equals(resolveDbTypeFromUrl(url))) { start = url.lastIndexOf(":"); diff --git a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DruidTest.java b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DruidTest.java index 2ab79972..5f824a1a 100644 --- a/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DruidTest.java +++ b/sofa-tracer-plugins/sofa-tracer-datasource-plugin/src/test/java/com/sofa/tracer/plugins/datasource/DruidTest.java @@ -34,7 +34,7 @@ import static org.mockito.Mockito.when; /** - * @author qilong.zql 18/8/27-上午9:23 + * @author qilong.zql 18/8/27-AM 9:23 */ public class DruidTest extends BaseTest { diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java index a71f64a7..c54bdda1 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java @@ -242,7 +242,6 @@ private Result doServerFilter(RpcContext rpcContext, Invoker invoker, Invocat Throwable exception = null; try { result = invoker.invoke(invocation); - // 处理返回结果 if (result == null) { return null; } else { @@ -276,8 +275,7 @@ private Result doServerFilter(RpcContext rpcContext, Invoker invoker, Invocat } private SofaTracerSpan serverReceived(Invocation invocation) { - Map tags = new HashMap(); - //server tags 必须设置 + Map tags = new HashMap<>(); tags.put(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER); String serializeSpanContext = invocation.getAttachments() .get(CommonSpanTags.RPC_TRACE_NAME); @@ -305,7 +303,6 @@ private SofaTracerSpan serverReceived(Invocation invocation) { SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); // Record server receive event serverSpan.log(LogData.SERVER_RECV_EVENT_VALUE); - // 放到线程上下文 sofaTraceContext.push(serverSpan); return serverSpan; } diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboClientStatJsonReporter.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboClientStatJsonReporter.java index bbd439f0..fdc16a14 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboClientStatJsonReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboClientStatJsonReporter.java @@ -65,7 +65,6 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { statKey.addKey(CommonSpanTags.REMOTE_APP, toApp); statKey.addKey(CommonSpanTags.SERVICE, serviceName); statKey.addKey(CommonSpanTags.METHOD, methodName); - //次数和耗时,最后一个耗时是单独打印的字段 long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); long[] values = new long[] { 1, duration }; this.addStat(statKey, values); @@ -82,7 +81,7 @@ protected String getLoadTestMark(SofaTracerSpan span) { @Override public void print(StatKey statKey, long[] values) { if (this.isClosePrint.get()) { - //关闭统计日志输出 + //Close the statistics log output return; } @@ -102,7 +101,7 @@ public void print(StatKey statKey, long[] values) { } else { appender.append(jsonBuffer.toString()); } - // 这里强制刷一次 + // Forced to flush appender.flush(); } catch (Throwable t) { SelfLog.error("stat log<" + statTracerName + "> error!", t); diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboServerStatJsonReporter.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboServerStatJsonReporter.java index 12acdfba..7f679eeb 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboServerStatJsonReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/stat/DubboServerStatJsonReporter.java @@ -82,7 +82,7 @@ protected String getLoadTestMark(SofaTracerSpan span) { @Override public void print(StatKey statKey, long[] values) { if (this.isClosePrint.get()) { - //关闭统计日志输出 + //Close the statistics log output return; } @@ -102,7 +102,7 @@ public void print(StatKey statKey, long[] values) { } else { appender.append(jsonBuffer.toString()); } - // 这里强制刷一次 + // Forced to flush appender.flush(); } catch (Throwable t) { SelfLog.error("stat log <" + statTracerName + "> error!", t); diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/wrapper/DataSizeCodecWrapper.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/wrapper/DataSizeCodecWrapper.java index de1c88d8..e75ce4da 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/wrapper/DataSizeCodecWrapper.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/wrapper/DataSizeCodecWrapper.java @@ -58,22 +58,21 @@ public void encode(Channel channel, ChannelBuffer buffer, Object message) throws return; } } - // 其它走原来 codec.encode(channel, buffer, message); } /** - * @param channel 长连接 - * @param buffer UnsafeByteArrayOutputStream - * @param message 原生Request对象 - * @param invocation Request里的Invocation - * @throws IOException 序列化出现异常 + * @param channel a long connection + * @param buffer buffer + * @param message the original Request object + * @param invocation Invocation in Request + * @throws IOException serialization exception */ protected void encodeRequestWithTracer(Channel channel, ChannelBuffer buffer, Object message, RpcInvocation invocation) throws IOException { long startTime = System.currentTimeMillis(); int index = buffer.writerIndex(); - // 序列化 + // serialization codec.encode(channel, buffer, message); int reqSize = buffer.writerIndex() - index; long elapsed = System.currentTimeMillis() - startTime; @@ -82,11 +81,10 @@ protected void encodeRequestWithTracer(Channel channel, ChannelBuffer buffer, Ob } /** - * @param channel 长连接 - * @param buffer UnsafeByteArrayOutputStream - * @param result 原生Resopnse对象 - * @param rpcResult Resopnse对象的结果 - * @throws IOException 序列化出现异常 + * @param channel a long connection + * @param buffer buffer + * @param message the original Request object + * @throws IOException serialization exception */ protected void encodeResultWithTracer(Channel channel, ChannelBuffer buffer, Object result, RpcResult rpcResult) throws IOException { @@ -101,7 +99,7 @@ protected void encodeResultWithTracer(Channel channel, ChannelBuffer buffer, Obj } /** - * 反序列化操作 + * deserialization operation * @param channel * @param input * @return @@ -115,7 +113,7 @@ public Object decode(Channel channel, ChannelBuffer input) throws IOException { int size = input.readerIndex() - index; long elapsed = System.currentTimeMillis() - startTime; if (ret instanceof Request) { - // 服务端反序列化Request + // server-side deserialize the Request Object data = ((Request) ret).getData(); if (data instanceof RpcInvocation) { RpcInvocation invocation = (RpcInvocation) data; @@ -123,9 +121,8 @@ public Object decode(Channel channel, ChannelBuffer input) throws IOException { invocation.setAttachment(CommonSpanTags.SERVER_DESERIALIZE_TIME, String.valueOf(elapsed)); } - } else if (ret instanceof Response) { - // 客户端反序列化Response + // client-side deserialize the Response Object result = ((Response) ret).getResult(); if (result instanceof RpcResult) { RpcResult rpcResult = (RpcResult) result; diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/AbstractHttpRequestInterceptor.java b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/AbstractHttpRequestInterceptor.java index 3078807f..15294d3c 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/AbstractHttpRequestInterceptor.java +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/interceptor/AbstractHttpRequestInterceptor.java @@ -39,9 +39,9 @@ public abstract class AbstractHttpRequestInterceptor { protected AbstractTracer httpClientTracer; - protected String appName = null; + protected String appName; - protected String targetAppName = null; + protected String targetAppName; public AbstractHttpRequestInterceptor(AbstractTracer httpClientTracer, String appName, String targetAppName) { @@ -68,7 +68,6 @@ public void appendHttpClientRequestSpanTags(HttpRequest httpRequest, //targetAppName httpClientSpan.setTag(CommonSpanTags.REMOTE_APP, this.targetAppName == null ? StringUtils.EMPTY_STRING : this.targetAppName); - //url ((HttpRequestWrapper) request).getOriginal().getRequestLine().getUri() if (httpRequest instanceof HttpRequestWrapper) { HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) httpRequest; httpClientSpan.setTag(CommonSpanTags.REQUEST_URL, httpRequestWrapper.getOriginal() 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 37bca4c7..bef973d9 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 @@ -37,9 +37,9 @@ */ public class SofaTracerOkHttpInterceptor implements okhttp3.Interceptor { - protected String appName = null; + protected String appName; - protected String targetAppName = null; + protected String targetAppName; protected AbstractTracer okHttpTracer; diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcJsonStatReporter.java b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcJsonStatReporter.java index 0a9c7112..2066b81e 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcJsonStatReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcJsonStatReporter.java @@ -36,9 +36,6 @@ */ public class SpringMvcJsonStatReporter extends SpringMvcStatReporter { - /*** - * 输出拼接器 - */ private static JsonStringBuilder jsonBuffer = new JsonStringBuilder(); public SpringMvcJsonStatReporter(String statTracerName, String rollingPolicy, @@ -62,8 +59,7 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { statKey.setResult(success ? "true" : "false"); //end statKey.setEnd(TracerUtils.getLoadTestMark(sofaTracerSpan)); - //value - //次数和耗时,最后一个耗时是单独打印的字段 + //duration long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); long values[] = new long[] { 1, duration }; //reserve @@ -97,7 +93,7 @@ public void print(StatKey statKey, long[] values) { } else { appender.append(jsonBuffer.toString()); } - // 这里强制刷一次 + // Forced to flush appender.flush(); } catch (Throwable t) { SelfLog.error("统计日志<" + statTracerName + ">输出异常", t); diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcLogEnum.java b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcLogEnum.java index ad9b0706..2e4e0c3d 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcLogEnum.java +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcLogEnum.java @@ -24,10 +24,10 @@ */ public enum SpringMvcLogEnum { - // SOFA MVC 日志 SPRING_MVC_DIGEST("spring_mvc_digest_log_name", "spring-mvc-digest.log", - "spring_mvc_digest_rolling"), // - SPRING_MVC_STAT("spring_mvc_stat_log_name", "spring-mvc-stat.log", "spring_mvc_stat_rolling"); + "spring_mvc_digest_rolling"), SPRING_MVC_STAT("spring_mvc_stat_log_name", + "spring-mvc-stat.log", + "spring_mvc_stat_rolling"); private String logNameKey; private String defaultLogName; 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 8dd14014..96409c23 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,8 +24,6 @@ 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.tag.Tags; - import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -81,7 +79,6 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo springMvcSpan.setTag(CommonSpanTags.REQ_SIZE, request.getContentLength()); //wrapper ResponseWrapper responseWrapper = new ResponseWrapper(response); - //filter begin filterChain.doFilter(servletRequest, responseWrapper); //filter end @@ -89,8 +86,6 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo responseSize = responseWrapper.getContentLength(); } catch (Throwable t) { httpStatus = 500; - springMvcSpan.setTag(Tags.ERROR.getKey(), t.getMessage()); - // 异常抛出 throw new RuntimeException(t); } finally { if (springMvcSpan != null) { diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcStatReporter.java b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcStatReporter.java index 2ed649d7..a887f88d 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcStatReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcStatReporter.java @@ -52,8 +52,7 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { statKey.setEnd(buildString(new String[] { TracerUtils.getLoadTestMark(sofaTracerSpan) })); //pressure mark statKey.setLoadTest(TracerUtils.isLoadTest(sofaTracerSpan)); - - //次数和耗时,最后一个耗时是单独打印的字段 + //duration long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); long values[] = new long[] { 1, duration }; this.addStat(statKey, values); diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporter.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporter.java index 1ec46e84..c0a98a47 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinSofaTracerSpanRemoteReporter.java @@ -70,10 +70,10 @@ public void close() { this.delegate.close(); } - /*** - * 功能:将 16 进制字符串转换为:十进制整数 - * @param hexString 16 进制字符串 - * @return 十进制整数 + /** + * To convert hexadecimal string to decimal integer + * @param hexString hexadecimal + * @return decimal */ public static long traceIdToId(String hexString) { Assert.hasText(hexString, "Can't convert empty hex string to long"); diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/adapter/ZipkinV2SpanAdapter.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/adapter/ZipkinV2SpanAdapter.java index 182ed6c0..53f61c5d 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/adapter/ZipkinV2SpanAdapter.java +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/main/java/com/alipay/sofa/tracer/plugins/zipkin/adapter/ZipkinV2SpanAdapter.java @@ -122,7 +122,7 @@ private Endpoint getZipkinEndpoint(SofaTracerSpan span) { ipAddress = InetAddress.getLocalHost(); this.ipAddressInt = ByteBuffer.wrap(ipAddress.getAddress()).getInt(); } catch (UnknownHostException e) { - //127.0.0.1 256 进制 + //127.0.0.1 256 this.ipAddressInt = 256 * 256 * 256 * 127 + 1; } } @@ -131,7 +131,7 @@ private Endpoint getZipkinEndpoint(SofaTracerSpan span) { } /** - * 将Baggage中的数据也放在tags中 + * Put the baggage data into the tags * @param zipkinSpan * @param span */ diff --git a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinRestTemplateSenderTest.java b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinRestTemplateSenderTest.java index 83cda74c..af41810a 100644 --- a/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinRestTemplateSenderTest.java +++ b/sofa-tracer-plugins/sofa-tracer-zipkin-plugin/src/test/java/com/alipay/sofa/tracer/plugins/zipkin/ZipkinRestTemplateSenderTest.java @@ -62,7 +62,7 @@ public void messageMaxBytes() { public void messageSizeInBytes() { byte[] tests = new byte[1]; tests[0] = 0; - List spans = new ArrayList(); + List spans = new ArrayList<>(); spans.add(tests); int i = zipkinRestTemplateSender.messageSizeInBytes(spans); Assert.assertTrue(i == 3); @@ -72,7 +72,7 @@ public void messageSizeInBytes() { public void sendSpans() throws InterruptedException { byte[] tests = new byte[1]; tests[0] = 0; - List encodedSpans = new ArrayList(); + List encodedSpans = new ArrayList<>(); encodedSpans.add(tests); Call voidCall = zipkinRestTemplateSender.sendSpans(encodedSpans); Thread.sleep(500); diff --git a/tracer-test/core-test/src/test/java/com/alipay/common/tracer/test/core/sofatracer/SofaTracerStatisticsDemoTest.java b/tracer-test/core-test/src/test/java/com/alipay/common/tracer/test/core/sofatracer/SofaTracerStatisticsDemoTest.java index 4a2d9ee5..14a572d2 100644 --- a/tracer-test/core-test/src/test/java/com/alipay/common/tracer/test/core/sofatracer/SofaTracerStatisticsDemoTest.java +++ b/tracer-test/core-test/src/test/java/com/alipay/common/tracer/test/core/sofatracer/SofaTracerStatisticsDemoTest.java @@ -28,7 +28,6 @@ import java.io.File; import java.util.List; - import static org.junit.Assert.*; /** @@ -41,6 +40,8 @@ public class SofaTracerStatisticsDemoTest extends AbstractTestBase { @Before public void beforeTest() throws Exception { + // wait stat cycle clean > 1000s(default) + Thread.sleep(1100); File f = customFileLog(TracerTestLogEnum.RPC_SERVER_DIGEST.getDefaultLogName()); if (f.exists()) { FileUtils.writeStringToFile(f, ""); @@ -64,15 +65,15 @@ public void beforeTest() throws Exception { @Test public void testBuildTracerStatisticsTest() throws Exception { - //清除上下文避免影响 + //Clear context to avoid impact SofaTraceContextHolder.getSofaTraceContext().clear(); String serverSpanId = "0.2.3"; SofaTracerSpan serverSpan = recoverServerSpan(serverSpanId); SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); - //放到线程上下文 + //Put into the thread context sofaTraceContext.push(serverSpan); - //在调用5次 + //Call 5 times int times = 5; callClientTimes(times); @@ -112,7 +113,8 @@ public void testBuildTracerStatisticsTest() throws Exception { //统计 String[] clientArray = clientStatContents.get(clientStatContents.size() - 1).split(","); - assertEquals(clientArray[6], String.valueOf(times * duration)); + // 统计调用次数即可 + assertEquals(clientArray[5], String.valueOf(times)); //server stat List serverStatContents = FileUtils .readLines(customFileLog(TracerTestLogEnum.RPC_SERVER_STAT.getDefaultLogName())); From 352c1d535b36161b1121378b74898df53973a641 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Thu, 1 Aug 2019 16:55:58 +0800 Subject: [PATCH 23/24] cheery pick constants --- .../plugins/dubbo/DubboSofaTracerFilter.java | 2 +- .../encoder/DubboClientDigestJsonEncoder.java | 11 ++--- .../HttpClientDigestJsonEncoder.java | 11 ++--- .../HttpClientStatJsonReporter.java | 18 ++++---- .../plugins/httpclient/HttpClientTracer.java | 3 +- .../okhttp/OkHttpDigestJsonEncoder.java | 11 ++--- .../okhttp/OkHttpStatJsonReporter.java | 18 ++++---- .../tracer/plugins/okhttp/OkHttpTracer.java | 3 +- .../encodes/OpenFeignDigestJsonEncoder.java | 13 +++--- .../feign/SofaTracerFeignClient.java | 2 - .../repoters/OpenFeignStatJsonReporter.java | 18 ++++---- .../springmvc/SpringMvcDigestJsonEncoder.java | 38 +++++------------ .../springmvc/SpringMvcHeadersCarrier.java | 3 ++ .../springmvc/SpringMvcJsonStatReporter.java | 24 ++++++----- .../springmvc/SpringMvcStatReporter.java | 6 ++- .../plugins/springmvc/SpringMvcTracer.java | 3 +- .../tracer/core/span/CommonSpanTags.java | 41 ++++++++++--------- 17 files changed, 112 insertions(+), 113 deletions(-) diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java index c5483673..23b0d615 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/DubboSofaTracerFilter.java @@ -203,7 +203,7 @@ private Result doClientFilter(RpcContext rpcContext, Invoker invoker, Invocat // Record client send event sofaTracerSpan.log(LogData.CLIENT_SEND_EVENT_VALUE); } - // 将当前 span 缓存 + // cache the current span TracerSpanMap.put(getTracerSpanMapKey(invoker), sofaTracerSpan); if (clientSpan != null && clientSpan.getParentSofaTracerSpan() != null) { //restore parent diff --git a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/encoder/DubboClientDigestJsonEncoder.java b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/encoder/DubboClientDigestJsonEncoder.java index 73d8c9e5..63db1eb6 100644 --- a/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/encoder/DubboClientDigestJsonEncoder.java +++ b/sofa-tracer-plugins/sofa-tracer-dubbo-plugin/src/main/java/com/alipay/sofa/tracer/plugins/dubbo/encoder/DubboClientDigestJsonEncoder.java @@ -39,16 +39,16 @@ public String encode(SofaTracerSpan sofaTracerSpan) throws IOException { JsonStringBuilder data = new JsonStringBuilder(); //span end time - data.appendBegin("time", Timestamp.format(sofaTracerSpan.getEndTime())); + data.appendBegin(CommonSpanTags.TIME, Timestamp.format(sofaTracerSpan.getEndTime())); Map tagStr = sofaTracerSpan.getTagsWithStr(); Map tagNum = sofaTracerSpan.getTagsWithNumber(); SofaTracerSpanContext context = sofaTracerSpan.getSofaTracerSpanContext(); // TraceId - data.append("traceId", context.getTraceId()); + data.append(CommonSpanTags.TRACE_ID, context.getTraceId()); // SpanId - data.append("spanId", context.getSpanId()); + data.append(CommonSpanTags.SPAN_ID, context.getSpanId()); // Span Type data.append(Tags.SPAN_KIND.getKey(), tagStr.get(Tags.SPAN_KIND.getKey())); // app name @@ -89,7 +89,7 @@ public String encode(SofaTracerSpan sofaTracerSpan) throws IOException { data.append(CommonSpanTags.CURRENT_THREAD_NAME, tagStr.get(CommonSpanTags.CURRENT_THREAD_NAME)); //time-consuming ms - data.append("time.cost.milliseconds", + data.append(CommonSpanTags.TIME_COST_MILLISECONDS, (sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime())); this.appendBaggage(data, context); return data.toString(); @@ -98,7 +98,8 @@ public String encode(SofaTracerSpan sofaTracerSpan) throws IOException { private void appendBaggage(JsonStringBuilder jsonStringBuilder, SofaTracerSpanContext sofaTracerSpanContext) { //baggage - jsonStringBuilder.appendEnd("baggage", baggageSerialized(sofaTracerSpanContext)); + jsonStringBuilder.appendEnd(CommonSpanTags.BAGGAGE, + baggageSerialized(sofaTracerSpanContext)); } } diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientDigestJsonEncoder.java b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientDigestJsonEncoder.java index 1203131d..8fa696c0 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientDigestJsonEncoder.java +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientDigestJsonEncoder.java @@ -38,7 +38,7 @@ public class HttpClientDigestJsonEncoder extends AbstractDigestSpanEncoder { public String encode(SofaTracerSpan span) throws IOException { JsonStringBuilder jsonStringBuilder = new JsonStringBuilder(); //span end time - jsonStringBuilder.appendBegin("time", Timestamp.format(span.getEndTime())); + jsonStringBuilder.appendBegin(CommonSpanTags.TIME, Timestamp.format(span.getEndTime())); appendSlot(jsonStringBuilder, span); return jsonStringBuilder.toString(); } @@ -51,9 +51,9 @@ private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofa jsonStringBuilder .append(CommonSpanTags.LOCAL_APP, tagWithStr.get(CommonSpanTags.LOCAL_APP)); //TraceId - jsonStringBuilder.append("traceId", context.getTraceId()); + jsonStringBuilder.append(CommonSpanTags.TRACE_ID, context.getTraceId()); //SpanId - jsonStringBuilder.append("spanId", context.getSpanId()); + jsonStringBuilder.append(CommonSpanTags.SPAN_ID, context.getSpanId()); //URL jsonStringBuilder.append(CommonSpanTags.REQUEST_URL, tagWithStr.get(CommonSpanTags.REQUEST_URL)); @@ -71,7 +71,7 @@ private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofa jsonStringBuilder.append(CommonSpanTags.RESP_SIZE, (responseSize == null ? 0L : responseSize.longValue())); //time-consuming ms - jsonStringBuilder.append("time.cost.milliseconds", + jsonStringBuilder.append(CommonSpanTags.TIME_COST_MILLISECONDS, (sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime())); jsonStringBuilder.append(CommonSpanTags.CURRENT_THREAD_NAME, tagWithStr.get(CommonSpanTags.CURRENT_THREAD_NAME)); @@ -84,6 +84,7 @@ private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofa private void appendBaggage(JsonStringBuilder jsonStringBuilder, SofaTracerSpanContext sofaTracerSpanContext) { //baggage - jsonStringBuilder.appendEnd("baggage", baggageSerialized(sofaTracerSpanContext)); + jsonStringBuilder.appendEnd(CommonSpanTags.BAGGAGE, + baggageSerialized(sofaTracerSpanContext)); } } \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientStatJsonReporter.java b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientStatJsonReporter.java index 7e1afa9f..46d8343a 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientStatJsonReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientStatJsonReporter.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.appender.file.LoadTestAwareAppender; import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.appender.self.Timestamp; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.reporter.stat.model.StatKey; import com.alipay.common.tracer.core.reporter.stat.model.StatMapKey; @@ -60,12 +61,13 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { String resultCode = tagsWithStr.get(CommonSpanTags.RESULT_CODE); boolean success = (resultCode != null && resultCode.length() > 0 && this .isHttpOrMvcSuccess(resultCode)); - statKey.setResult(success ? "true" : "false"); + statKey.setResult(success ? SofaTracerConstant.STAT_FLAG_SUCCESS + : SofaTracerConstant.STAT_FLAG_FAILS); //end statKey.setEnd(TracerUtils.getLoadTestMark(sofaTracerSpan)); //value the count and duration long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); - long values[] = new long[] { 1, duration }; + long[] values = new long[] { 1, duration }; //reserve this.addStat(statKey, values); } @@ -83,13 +85,13 @@ public void print(StatKey statKey, long[] values) { try { jsonBuffer.reset(); jsonBuffer.appendBegin(); - jsonBuffer.append("time", Timestamp.currentTime()); - jsonBuffer.append("stat.key", this.statKeySplit(statMapKey)); - jsonBuffer.append("count", values[0]); - jsonBuffer.append("total.cost.milliseconds", values[1]); - jsonBuffer.append("success", statMapKey.getResult()); + jsonBuffer.append(CommonSpanTags.TIME, Timestamp.currentTime()); + jsonBuffer.append(CommonSpanTags.STAT_KEY, this.statKeySplit(statMapKey)); + jsonBuffer.append(CommonSpanTags.COUNT, values[0]); + jsonBuffer.append(CommonSpanTags.TOTAL_COST_MILLISECONDS, values[1]); + jsonBuffer.append(CommonSpanTags.SUCCESS, statMapKey.getResult()); //pressure - jsonBuffer.appendEnd("load.test", statMapKey.getEnd()); + jsonBuffer.appendEnd(CommonSpanTags.LOAD_TEST, statMapKey.getEnd()); if (appender instanceof LoadTestAwareAppender) { ((LoadTestAwareAppender) appender).append(jsonBuffer.toString(), diff --git a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientTracer.java b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientTracer.java index 5a20b328..c76ff189 100644 --- a/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientTracer.java +++ b/sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/main/java/com/alipay/sofa/tracer/plugins/httpclient/HttpClientTracer.java @@ -18,6 +18,7 @@ import com.alipay.common.tracer.core.appender.encoder.SpanEncoder; import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.constants.ComponentNameConstants; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tracer.AbstractClientTracer; @@ -48,7 +49,7 @@ public static HttpClientTracer getHttpClientTracerSingleton() { } protected HttpClientTracer() { - super("httpclient"); + super(ComponentNameConstants.HTTP_CLIENT); } @Override diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpDigestJsonEncoder.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpDigestJsonEncoder.java index 9755218f..58b06642 100644 --- a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpDigestJsonEncoder.java +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpDigestJsonEncoder.java @@ -37,7 +37,7 @@ public class OkHttpDigestJsonEncoder extends AbstractDigestSpanEncoder { public String encode(SofaTracerSpan span) throws IOException { JsonStringBuilder jsonStringBuilder = new JsonStringBuilder(); //span end time - jsonStringBuilder.appendBegin("time", Timestamp.format(span.getEndTime())); + jsonStringBuilder.appendBegin(CommonSpanTags.TIME, Timestamp.format(span.getEndTime())); appendSlot(jsonStringBuilder, span); return jsonStringBuilder.toString(); } @@ -50,9 +50,9 @@ private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofa jsonStringBuilder .append(CommonSpanTags.LOCAL_APP, tagWithStr.get(CommonSpanTags.LOCAL_APP)); //TraceId - jsonStringBuilder.append("traceId", context.getTraceId()); + jsonStringBuilder.append(CommonSpanTags.TRACE_ID, context.getTraceId()); //SpanId - jsonStringBuilder.append("spanId", context.getSpanId()); + jsonStringBuilder.append(CommonSpanTags.SPAN_ID, context.getSpanId()); //URL jsonStringBuilder.append(CommonSpanTags.REQUEST_URL, tagWithStr.get(CommonSpanTags.REQUEST_URL)); @@ -70,7 +70,7 @@ private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofa jsonStringBuilder.append(CommonSpanTags.RESP_SIZE, (responseSize == null ? 0L : responseSize.longValue())); //time-consuming ms - jsonStringBuilder.append("time.cost.milliseconds", + jsonStringBuilder.append(CommonSpanTags.TIME_COST_MILLISECONDS, (sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime())); jsonStringBuilder.append(CommonSpanTags.CURRENT_THREAD_NAME, tagWithStr.get(CommonSpanTags.CURRENT_THREAD_NAME)); @@ -83,6 +83,7 @@ private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofa private void appendBaggage(JsonStringBuilder jsonStringBuilder, SofaTracerSpanContext sofaTracerSpanContext) { //baggage - jsonStringBuilder.appendEnd("baggage", baggageSerialized(sofaTracerSpanContext)); + jsonStringBuilder.appendEnd(CommonSpanTags.BAGGAGE, + baggageSerialized(sofaTracerSpanContext)); } } \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpStatJsonReporter.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpStatJsonReporter.java index b0d06837..f341a359 100644 --- a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpStatJsonReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpStatJsonReporter.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.appender.file.LoadTestAwareAppender; import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.appender.self.Timestamp; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.reporter.stat.model.StatKey; import com.alipay.common.tracer.core.reporter.stat.model.StatMapKey; @@ -58,12 +59,13 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { String resultCode = tagsWithStr.get(CommonSpanTags.RESULT_CODE); boolean success = (resultCode != null && resultCode.length() > 0 && this .isHttpOrMvcSuccess(resultCode)); - statKey.setResult(success ? "true" : "false"); + statKey.setResult(success ? SofaTracerConstant.STAT_FLAG_SUCCESS + : SofaTracerConstant.STAT_FLAG_FAILS); //end statKey.setEnd(TracerUtils.getLoadTestMark(sofaTracerSpan)); //value the count and duration long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); - long values[] = new long[] { 1, duration }; + long[] values = new long[] { 1, duration }; //reserve this.addStat(statKey, values); } @@ -81,13 +83,13 @@ public void print(StatKey statKey, long[] values) { try { jsonBuffer.reset(); jsonBuffer.appendBegin(); - jsonBuffer.append("time", Timestamp.currentTime()); - jsonBuffer.append("stat.key", this.statKeySplit(statMapKey)); - jsonBuffer.append("count", values[0]); - jsonBuffer.append("total.cost.milliseconds", values[1]); - jsonBuffer.append("success", statMapKey.getResult()); + jsonBuffer.append(CommonSpanTags.TIME, Timestamp.currentTime()); + jsonBuffer.append(CommonSpanTags.STAT_KEY, this.statKeySplit(statMapKey)); + jsonBuffer.append(CommonSpanTags.COUNT, values[0]); + jsonBuffer.append(CommonSpanTags.TOTAL_COST_MILLISECONDS, values[1]); + jsonBuffer.append(CommonSpanTags.SUCCESS, statMapKey.getResult()); //pressure - jsonBuffer.appendEnd("load.test", statMapKey.getEnd()); + jsonBuffer.appendEnd(CommonSpanTags.LOAD_TEST, statMapKey.getEnd()); if (appender instanceof LoadTestAwareAppender) { ((LoadTestAwareAppender) appender).append(jsonBuffer.toString(), diff --git a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpTracer.java b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpTracer.java index 874378a6..5793002e 100644 --- a/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpTracer.java +++ b/sofa-tracer-plugins/sofa-tracer-okhttp-plugin/src/main/java/com/alipay/sofa/tracer/plugins/okhttp/OkHttpTracer.java @@ -18,6 +18,7 @@ import com.alipay.common.tracer.core.appender.encoder.SpanEncoder; import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.constants.ComponentNameConstants; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tracer.AbstractClientTracer; @@ -31,7 +32,7 @@ public class OkHttpTracer extends AbstractClientTracer { private volatile static OkHttpTracer okHttpTracer = null; protected OkHttpTracer() { - super("okhttp"); + super(ComponentNameConstants.OK_HTTP); } public static OkHttpTracer getOkHttpTracerSingleton() { diff --git a/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/encodes/OpenFeignDigestJsonEncoder.java b/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/encodes/OpenFeignDigestJsonEncoder.java index d90a7dd8..4ea35e00 100644 --- a/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/encodes/OpenFeignDigestJsonEncoder.java +++ b/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/encodes/OpenFeignDigestJsonEncoder.java @@ -38,7 +38,7 @@ public class OpenFeignDigestJsonEncoder extends AbstractDigestSpanEncoder { public String encode(SofaTracerSpan span) throws IOException { JsonStringBuilder result = new JsonStringBuilder(); //span end time - result.appendBegin("time", Timestamp.format(span.getEndTime())); + result.appendBegin(CommonSpanTags.TIME, Timestamp.format(span.getEndTime())); appendSlot(result, span); return result.toString(); } @@ -48,8 +48,8 @@ private void appendSlot(JsonStringBuilder buffer, SofaTracerSpan sofaTracerSpan) Map tagStrMap = sofaTracerSpan.getTagsWithStr(); Map tagNumMap = sofaTracerSpan.getTagsWithNumber(); buffer.append(CommonSpanTags.LOCAL_APP, tagStrMap.get(CommonSpanTags.LOCAL_APP)); - buffer.append("traceId", context.getTraceId()); - buffer.append("spanId", context.getSpanId()); + buffer.append(CommonSpanTags.TRACE_ID, context.getTraceId()); + buffer.append(CommonSpanTags.SPAN_ID, context.getSpanId()); buffer.append(CommonSpanTags.REQUEST_URL, tagStrMap.get(CommonSpanTags.REQUEST_URL)); buffer.append(CommonSpanTags.METHOD, tagStrMap.get(CommonSpanTags.METHOD)); buffer.append(CommonSpanTags.RESULT_CODE, tagStrMap.get(CommonSpanTags.RESULT_CODE)); @@ -64,20 +64,19 @@ private void appendSlot(JsonStringBuilder buffer, SofaTracerSpan sofaTracerSpan) (responseSize == null ? 0L : responseSize.longValue())); long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); //time-consuming ms - buffer.append("time.cost.milliseconds", duration); + buffer.append(CommonSpanTags.TIME_COST_MILLISECONDS, duration); buffer.append(CommonSpanTags.CURRENT_THREAD_NAME, tagStrMap.get(CommonSpanTags.CURRENT_THREAD_NAME)); //target appName buffer.append(CommonSpanTags.REMOTE_HOST, tagStrMap.get(CommonSpanTags.REMOTE_HOST)); buffer.append(CommonSpanTags.REMOTE_PORT, tagStrMap.get(CommonSpanTags.REMOTE_PORT)); - buffer.append(CommonSpanTags.COMPONENT_CLIENT, - tagStrMap.get(CommonSpanTags.COMPONENT_CLIENT)); this.appendBaggage(buffer, context); } private void appendBaggage(JsonStringBuilder jsonStringBuilder, SofaTracerSpanContext sofaTracerSpanContext) { //baggage - jsonStringBuilder.appendEnd("baggage", baggageSerialized(sofaTracerSpanContext)); + jsonStringBuilder.appendEnd(CommonSpanTags.BAGGAGE, + baggageSerialized(sofaTracerSpanContext)); } } diff --git a/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/instruments/feign/SofaTracerFeignClient.java b/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/instruments/feign/SofaTracerFeignClient.java index e9b62259..145d34d2 100644 --- a/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/instruments/feign/SofaTracerFeignClient.java +++ b/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/instruments/feign/SofaTracerFeignClient.java @@ -143,8 +143,6 @@ private void appendRequestSpanTags(Request request, SofaTracerSpan sofaTracerSpa String[] hostWithPort = parseRemoteHostAndPort(request); sofaTracerSpan.setTag(CommonSpanTags.REMOTE_HOST, hostWithPort[0]); sofaTracerSpan.setTag(CommonSpanTags.REMOTE_PORT, hostWithPort[1]); - sofaTracerSpan.setTag(CommonSpanTags.COMPONENT_CLIENT, feignClientTracer.getSofaTracer() - .getTracerType()); if (request.body() != null) { sofaTracerSpan.setTag(CommonSpanTags.REQ_SIZE, request.body().length); diff --git a/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/repoters/OpenFeignStatJsonReporter.java b/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/repoters/OpenFeignStatJsonReporter.java index 86630870..774bcb3d 100644 --- a/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/repoters/OpenFeignStatJsonReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-spring-cloud-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springcloud/repoters/OpenFeignStatJsonReporter.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.appender.file.LoadTestAwareAppender; import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.appender.self.Timestamp; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.reporter.stat.model.StatKey; import com.alipay.common.tracer.core.reporter.stat.model.StatMapKey; @@ -52,14 +53,15 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { String resultCode = tagsWithStr.get(CommonSpanTags.RESULT_CODE); boolean success = (resultCode != null && resultCode.length() > 0 && this .isHttpOrMvcSuccess(resultCode)); - statKey.setResult(success ? "true" : "false"); + statKey.setResult(success ? SofaTracerConstant.STAT_FLAG_SUCCESS + : SofaTracerConstant.STAT_FLAG_FAILS); //pressure mark statKey.setLoadTest(TracerUtils.isLoadTest(sofaTracerSpan)); //end statKey.setEnd(TracerUtils.getLoadTestMark(sofaTracerSpan)); //value the count and duration long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); - long values[] = new long[] { 1, duration }; + long[] values = new long[] { 1, duration }; //reserve this.addStat(statKey, values); } @@ -76,13 +78,13 @@ public void print(StatKey statKey, long[] values) { try { buffer.reset(); buffer.appendBegin(); - buffer.append("time", Timestamp.currentTime()); - buffer.append("stat.key", this.statKeySplit(statMapKey)); - buffer.append("count", values[0]); - buffer.append("total.cost.milliseconds", values[1]); - buffer.append("success", statMapKey.getResult()); + buffer.append(CommonSpanTags.TIME, Timestamp.currentTime()); + buffer.append(CommonSpanTags.STAT_KEY, this.statKeySplit(statMapKey)); + buffer.append(CommonSpanTags.COUNT, values[0]); + buffer.append(CommonSpanTags.TOTAL_COST_MILLISECONDS, values[1]); + buffer.append(CommonSpanTags.SUCCESS, statMapKey.getResult()); //pressure - buffer.appendEnd("load.test", statMapKey.getEnd()); + buffer.appendEnd(CommonSpanTags.LOAD_TEST, statMapKey.getEnd()); if (appender instanceof LoadTestAwareAppender) { ((LoadTestAwareAppender) appender).append(buffer.toString(), statMapKey.isLoadTest()); diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcDigestJsonEncoder.java b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcDigestJsonEncoder.java index 232aba6a..1cfeecb8 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcDigestJsonEncoder.java +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcDigestJsonEncoder.java @@ -22,8 +22,6 @@ import com.alipay.common.tracer.core.middleware.parent.AbstractDigestSpanEncoder; 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.tag.Tags; import java.io.IOException; import java.util.Map; @@ -39,8 +37,7 @@ public class SpringMvcDigestJsonEncoder extends AbstractDigestSpanEncoder { @Override public String encode(SofaTracerSpan span) throws IOException { JsonStringBuilder jsonStringBuilder = new JsonStringBuilder(); - //日志打印时间 - jsonStringBuilder.appendBegin("time", Timestamp.format(span.getEndTime())); + jsonStringBuilder.appendBegin(CommonSpanTags.TIME, Timestamp.format(span.getEndTime())); appendSlot(jsonStringBuilder, span); return jsonStringBuilder.toString(); } @@ -50,48 +47,33 @@ private void appendSlot(JsonStringBuilder jsonStringBuilder, SofaTracerSpan sofa SofaTracerSpanContext context = sofaTracerSpan.getSofaTracerSpanContext(); Map tagWithStr = sofaTracerSpan.getTagsWithStr(); Map tagWithNumber = sofaTracerSpan.getTagsWithNumber(); - //当前应用名 jsonStringBuilder .append(CommonSpanTags.LOCAL_APP, tagWithStr.get(CommonSpanTags.LOCAL_APP)); - //remote address, webflux - if (tagWithStr.get(CommonSpanTags.REMOTE_APP) != null) { - jsonStringBuilder.append(CommonSpanTags.REMOTE_APP, - tagWithStr.get(CommonSpanTags.REMOTE_APP)); - } //TraceId - jsonStringBuilder.append("traceId", context.getTraceId()); + jsonStringBuilder.append(CommonSpanTags.TRACE_ID, context.getTraceId()); //RpcId - jsonStringBuilder.append("spanId", context.getSpanId()); + jsonStringBuilder.append(CommonSpanTags.SPAN_ID, context.getSpanId()); //请求 URL jsonStringBuilder.append(CommonSpanTags.REQUEST_URL, tagWithStr.get(CommonSpanTags.REQUEST_URL)); - //请求方法 + //Request method jsonStringBuilder.append(CommonSpanTags.METHOD, tagWithStr.get(CommonSpanTags.METHOD)); - - //Http 状态码 - jsonStringBuilder.append(CommonSpanTags.RESULT_CODE, - tagWithStr.get(CommonSpanTags.RESULT_CODE)); - //异常信息 - if (StringUtils.isNotBlank(tagWithStr.get(Tags.ERROR.getKey()))) { - jsonStringBuilder.append(Tags.ERROR.getKey(), tagWithStr.get(Tags.ERROR.getKey())); - } - //Http 状态码 + //Http code jsonStringBuilder.append(CommonSpanTags.RESULT_CODE, tagWithStr.get(CommonSpanTags.RESULT_CODE)); Number requestSize = tagWithNumber.get(CommonSpanTags.REQ_SIZE); - //Request Body 大小 单位为byte + //Request Body Size (byte) jsonStringBuilder.append(CommonSpanTags.REQ_SIZE, (requestSize == null ? 0L : requestSize.longValue())); Number responseSize = tagWithNumber.get(CommonSpanTags.RESP_SIZE); - //Response Body 大小,单位为byte + //Response Body Size,(byte) jsonStringBuilder.append(CommonSpanTags.RESP_SIZE, (responseSize == null ? 0L : responseSize.longValue())); - //请求耗时(MS) - jsonStringBuilder.append("time.cost.milliseconds", + //Request time (MS) + jsonStringBuilder.append(CommonSpanTags.TIME_COST_MILLISECONDS, (sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime())); jsonStringBuilder.append(CommonSpanTags.CURRENT_THREAD_NAME, tagWithStr.get(CommonSpanTags.CURRENT_THREAD_NAME)); - //穿透数据放在最后 - jsonStringBuilder.appendEnd("baggage", baggageSerialized(context)); + jsonStringBuilder.appendEnd(CommonSpanTags.BAGGAGE, baggageSerialized(context)); } } \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcHeadersCarrier.java b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcHeadersCarrier.java index 63f8b053..997830cb 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcHeadersCarrier.java +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcHeadersCarrier.java @@ -22,6 +22,9 @@ import java.util.Iterator; import java.util.Map; +/** + * @author yangguanchao + */ public class SpringMvcHeadersCarrier implements TextMap { private HashMap headers; diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcJsonStatReporter.java b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcJsonStatReporter.java index 2066b81e..f89c7887 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcJsonStatReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcJsonStatReporter.java @@ -20,6 +20,7 @@ import com.alipay.common.tracer.core.appender.file.LoadTestAwareAppender; import com.alipay.common.tracer.core.appender.self.SelfLog; import com.alipay.common.tracer.core.appender.self.Timestamp; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.reporter.stat.model.StatMapKey; import com.alipay.common.tracer.core.reporter.stat.model.StatKey; import com.alipay.common.tracer.core.span.CommonSpanTags; @@ -56,12 +57,13 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { String resultCode = tagsWithStr.get(CommonSpanTags.RESULT_CODE); boolean success = (resultCode != null && resultCode.length() > 0 && this .isHttpOrMvcSuccess(resultCode)); - statKey.setResult(success ? "true" : "false"); + statKey.setResult(success ? SofaTracerConstant.STAT_FLAG_SUCCESS + : SofaTracerConstant.STAT_FLAG_FAILS); //end statKey.setEnd(TracerUtils.getLoadTestMark(sofaTracerSpan)); //duration long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); - long values[] = new long[] { 1, duration }; + long[] values = new long[] { 1, duration }; //reserve this.addStat(statKey, values); } @@ -69,7 +71,7 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { @Override public void print(StatKey statKey, long[] values) { if (this.isClosePrint.get()) { - //关闭统计日志输出 + //Close the statistics log output return; } if (!(statKey instanceof StatMapKey)) { @@ -79,13 +81,13 @@ public void print(StatKey statKey, long[] values) { try { jsonBuffer.reset(); jsonBuffer.appendBegin(); - jsonBuffer.append("time", Timestamp.currentTime()); - jsonBuffer.append("stat.key", this.statKeySplit(statMapKey)); - jsonBuffer.append("count", values[0]); - jsonBuffer.append("total.cost.milliseconds", values[1]); - jsonBuffer.append("success", statMapKey.getResult()); - //压测 - jsonBuffer.appendEnd("load.test", statMapKey.getEnd()); + jsonBuffer.append(CommonSpanTags.TIME, Timestamp.currentTime()); + jsonBuffer.append(CommonSpanTags.STAT_KEY, this.statKeySplit(statMapKey)); + jsonBuffer.append(CommonSpanTags.COUNT, values[0]); + jsonBuffer.append(CommonSpanTags.TOTAL_COST_MILLISECONDS, values[1]); + jsonBuffer.append(CommonSpanTags.SUCCESS, statMapKey.getResult()); + //pressure test mark + jsonBuffer.appendEnd(CommonSpanTags.LOAD_TEST, statMapKey.getEnd()); if (appender instanceof LoadTestAwareAppender) { ((LoadTestAwareAppender) appender).append(jsonBuffer.toString(), @@ -96,7 +98,7 @@ public void print(StatKey statKey, long[] values) { // Forced to flush appender.flush(); } catch (Throwable t) { - SelfLog.error("统计日志<" + statTracerName + ">输出异常", t); + SelfLog.error("Stat log<" + statTracerName + "> error!", t); } } diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcStatReporter.java b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcStatReporter.java index a887f88d..7a5122d3 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcStatReporter.java +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcStatReporter.java @@ -16,6 +16,7 @@ */ package com.alipay.sofa.tracer.plugins.springmvc; +import com.alipay.common.tracer.core.constants.SofaTracerConstant; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.reporter.stat.model.StatKey; import com.alipay.common.tracer.core.span.CommonSpanTags; @@ -48,13 +49,14 @@ public void doReportStat(SofaTracerSpan sofaTracerSpan) { String resultCode = tagsWithStr.get(CommonSpanTags.RESULT_CODE); boolean success = (resultCode != null && resultCode.length() > 0 && this .isHttpOrMvcSuccess(resultCode)); - statKey.setResult(success ? "Y" : "N"); + statKey.setResult(success ? SofaTracerConstant.DIGEST_FLAG_SUCCESS + : SofaTracerConstant.DIGEST_FLAG_FAILS); statKey.setEnd(buildString(new String[] { TracerUtils.getLoadTestMark(sofaTracerSpan) })); //pressure mark statKey.setLoadTest(TracerUtils.isLoadTest(sofaTracerSpan)); //duration long duration = sofaTracerSpan.getEndTime() - sofaTracerSpan.getStartTime(); - long values[] = new long[] { 1, duration }; + long[] values = new long[] { 1, duration }; this.addStat(statKey, values); } } \ No newline at end of file diff --git a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcTracer.java b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcTracer.java index 7d6dc6f6..ca3344f6 100644 --- a/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcTracer.java +++ b/sofa-tracer-plugins/sofa-tracer-springmvc-plugin/src/main/java/com/alipay/sofa/tracer/plugins/springmvc/SpringMvcTracer.java @@ -18,6 +18,7 @@ import com.alipay.common.tracer.core.appender.encoder.SpanEncoder; import com.alipay.common.tracer.core.configuration.SofaTracerConfiguration; +import com.alipay.common.tracer.core.constants.ComponentNameConstants; import com.alipay.common.tracer.core.reporter.stat.AbstractSofaTracerStatisticReporter; import com.alipay.common.tracer.core.span.SofaTracerSpan; import com.alipay.common.tracer.core.tracer.AbstractServerTracer; @@ -50,7 +51,7 @@ public static SpringMvcTracer getSpringMvcTracerSingleton() { } private SpringMvcTracer() { - super("springmvc"); + super(ComponentNameConstants.SPRING_MVC); } @Override diff --git a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java index fb77bc0c..31ce77af 100644 --- a/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java +++ b/tracer-core/src/main/java/com/alipay/common/tracer/core/span/CommonSpanTags.java @@ -27,101 +27,101 @@ public class CommonSpanTags { /** * LOCAL_APP records the currnt app name */ - public static final String LOCAL_APP = "local.app"; + public static final String LOCAL_APP = "local.app"; /** * REMOTE_APP records the target app name */ - public static final String REMOTE_APP = "remote.app"; + public static final String REMOTE_APP = "remote.app"; /** * CURRENT_THREAD_NAME records handler result */ - public static final String RESULT_CODE = "result.code"; + public static final String RESULT_CODE = "result.code"; /** * CURRENT_THREAD_NAME records current thread name */ - public static final String CURRENT_THREAD_NAME = "current.thread.name"; + public static final String CURRENT_THREAD_NAME = "current.thread.name"; /** * REQUEST_URL records the url of the incoming request. */ - public static final String REQUEST_URL = "request.url"; + public static final String REQUEST_URL = "request.url"; /** * METHOD records the request method name,(rpc method or http method). */ - public static final String METHOD = "method"; + public static final String METHOD = "method"; /** * REQ_SIZE records the request body size. */ - public static final String REQ_SIZE = "req.size.bytes"; + public static final String REQ_SIZE = "req.size.bytes"; /** * RESP_SIZE records the response body size. */ - public static final String RESP_SIZE = "resp.size.bytes"; + public static final String RESP_SIZE = "resp.size.bytes"; /** * PROTOCOL records the request protocol type. */ - public static final String PROTOCOL = "protocol"; + public static final String PROTOCOL = "protocol"; /** * SERVICE records the rpc service interface. */ - public static final String SERVICE = "service"; + public static final String SERVICE = "service"; /** * REMOTE_HOST records the rpc target host. */ - public static final String REMOTE_HOST = "remote.host"; + public static final String REMOTE_HOST = "remote.host"; /** * REMOTE_PORT records the rpc target port. */ - public static final String REMOTE_PORT = "remote.port"; + public static final String REMOTE_PORT = "remote.port"; /** * LOCAL_HOST records the local host. */ - public static final String LOCAL_HOST = "local.host"; + public static final String LOCAL_HOST = "local.host"; /** * LOCAL_PORT records the local port. */ - public static final String LOCAL_PORT = "local.port"; + public static final String LOCAL_PORT = "local.port"; /** * INVOKE_TYPE records the invoke type(oneway/sync/async). */ - public static final String INVOKE_TYPE = "invoke.type"; + public static final String INVOKE_TYPE = "invoke.type"; /** * RPC_TRACE_NAME constants key for dubbo rpc transfer. */ - public static final String RPC_TRACE_NAME = "dubbo.rpc.sofa.tracer"; + public static final String RPC_TRACE_NAME = "dubbo.rpc.sofa.tracer"; /** * CLIENT_SERIALIZE_TIME records the rpc client serializes the request body time */ - public static final String CLIENT_SERIALIZE_TIME = "client.serialize.time"; + public static final String CLIENT_SERIALIZE_TIME = "client.serialize.time"; /** * SERVER_SERIALIZE_TIME records the rpc server serializes the response body time */ - public static final String SERVER_SERIALIZE_TIME = "server.serialize.time"; + public static final String SERVER_SERIALIZE_TIME = "server.serialize.time"; /** * CLIENT_DESERIALIZE_TIME records the rpc client deserialize the response body time */ - public static final String CLIENT_DESERIALIZE_TIME = "client.deserialize.time"; + public static final String CLIENT_DESERIALIZE_TIME = "client.deserialize.time"; /** * SERVER_DESERIALIZE_TIME records the rpc server deserialize the request body time */ - public static final String SERVER_DESERIALIZE_TIME = "server.deserialize.time"; + public static final String SERVER_DESERIALIZE_TIME = "server.deserialize.time"; /** * SPAN_ID records the current span's id @@ -172,4 +172,5 @@ public class CommonSpanTags { * LOAD_TEST is the span's stat log key for load.test */ public static final String LOAD_TEST = "load.test"; + } \ No newline at end of file From 7157fa92f13e2d2ebb2da8cb5bf0cd8e8465d70a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=AB=E6=81=92?= Date: Thu, 1 Aug 2019 17:11:19 +0800 Subject: [PATCH 24/24] optimized test case --- .../boot/springmvc/SpringMvcFilterJsonOutputTest.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/springmvc/SpringMvcFilterJsonOutputTest.java b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/springmvc/SpringMvcFilterJsonOutputTest.java index 2ebac8dc..f95be0d3 100644 --- a/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/springmvc/SpringMvcFilterJsonOutputTest.java +++ b/tracer-sofa-boot-starter/src/test/java/com/alipay/sofa/tracer/boot/springmvc/SpringMvcFilterJsonOutputTest.java @@ -25,6 +25,7 @@ import com.alipay.sofa.tracer.boot.base.controller.SampleRestController; import com.alipay.sofa.tracer.plugins.springmvc.SpringMvcLogEnum; import org.apache.commons.io.FileUtils; +import org.junit.Before; import org.junit.Test; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; @@ -44,6 +45,12 @@ @ActiveProfiles("json") public class SpringMvcFilterJsonOutputTest extends AbstractTestBase { + @Before + public void before() throws InterruptedException { + // wait other stat log print over + Thread.sleep(1100); + } + @Test public void testSofaRestGet() throws Exception { String restUrl = urlHttpPrefix + "/greeting"; @@ -84,8 +91,7 @@ public void testSofaRestGet() throws Exception { SpringMvcLogEnum.SPRING_MVC_STAT.getDefaultLogName())); //stat log : 设置了周期 1s 输出一次 - Thread.sleep(2000); - + Thread.sleep(1000); //wait for async output List statContents = FileUtils .readLines(customFileLog(SpringMvcLogEnum.SPRING_MVC_STAT.getDefaultLogName()));