未验证 提交 b0cc9138 编写于 作者: E Evan 提交者: GitHub

export the segmentId and spanId in toolkit (#6213)

上级 98d0430b
...@@ -32,6 +32,7 @@ Release Notes. ...@@ -32,6 +32,7 @@ Release Notes.
* Fix bug that rocketmq-plugin set the wrong tag. * Fix bug that rocketmq-plugin set the wrong tag.
* Fix duplicated `EnhancedInstance` interface added. * Fix duplicated `EnhancedInstance` interface added.
* Fix thread leaks caused by the elasticsearch-6.x-plugin plugin. * Fix thread leaks caused by the elasticsearch-6.x-plugin plugin.
* Support reading segmentId and spanId with toolkit.
#### OAP-Backend #### OAP-Backend
......
...@@ -36,6 +36,24 @@ public class TraceContext { ...@@ -36,6 +36,24 @@ public class TraceContext {
return ""; return "";
} }
/**
* Try to get the segmentId of current trace context.
*
* @return segmentId, if it exists, or empty {@link String}.
*/
public static String segmentId() {
return "";
}
/**
* Try to get the spanId of current trace context.
*
* @return spanId, if it exists, or empty {@link String}.
*/
public static String spanId() {
return "";
}
/** /**
* Try to get the custom value from trace context. * Try to get the custom value from trace context.
* *
......
...@@ -62,6 +62,20 @@ public interface AbstractTracerContext { ...@@ -62,6 +62,20 @@ public interface AbstractTracerContext {
*/ */
String getReadablePrimaryTraceId(); String getReadablePrimaryTraceId();
/**
* Get the current segment id, if needEnhance. How to build, depends on the implementation.
*
* @return the string represents the id.
*/
String getSegmentId();
/**
* Get the active span id, if needEnhance. How to build, depends on the implementation.
*
* @return the string represents the id.
*/
String getSpanId();
/** /**
* Create an entry span * Create an entry span
* *
......
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
package org.apache.skywalking.apm.agent.core.context; package org.apache.skywalking.apm.agent.core.context;
import java.util.Objects;
import org.apache.skywalking.apm.agent.core.boot.BootService; import org.apache.skywalking.apm.agent.core.boot.BootService;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager; import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan; import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
...@@ -38,6 +39,7 @@ import static org.apache.skywalking.apm.agent.core.conf.Config.Agent.OPERATION_N ...@@ -38,6 +39,7 @@ import static org.apache.skywalking.apm.agent.core.conf.Config.Agent.OPERATION_N
* <p> Also, {@link ContextManager} delegates to all {@link AbstractTracerContext}'s major methods. * <p> Also, {@link ContextManager} delegates to all {@link AbstractTracerContext}'s major methods.
*/ */
public class ContextManager implements BootService { public class ContextManager implements BootService {
private static final String EMPTY_TRACE_CONTEXT_ID = "N/A";
private static final ILog LOGGER = LogManager.getLogger(ContextManager.class); private static final ILog LOGGER = LogManager.getLogger(ContextManager.class);
private static ThreadLocal<AbstractTracerContext> CONTEXT = new ThreadLocal<AbstractTracerContext>(); private static ThreadLocal<AbstractTracerContext> CONTEXT = new ThreadLocal<AbstractTracerContext>();
private static ThreadLocal<RuntimeContext> RUNTIME_CONTEXT = new ThreadLocal<RuntimeContext>(); private static ThreadLocal<RuntimeContext> RUNTIME_CONTEXT = new ThreadLocal<RuntimeContext>();
...@@ -71,12 +73,24 @@ public class ContextManager implements BootService { ...@@ -71,12 +73,24 @@ public class ContextManager implements BootService {
* @return the first global trace id if needEnhance. Otherwise, "N/A". * @return the first global trace id if needEnhance. Otherwise, "N/A".
*/ */
public static String getGlobalTraceId() { public static String getGlobalTraceId() {
AbstractTracerContext segment = CONTEXT.get(); AbstractTracerContext context = CONTEXT.get();
if (segment == null) { return Objects.nonNull(context) ? context.getReadablePrimaryTraceId() : EMPTY_TRACE_CONTEXT_ID;
return "N/A";
} else {
return segment.getReadablePrimaryTraceId();
} }
/**
* @return the current segment id if needEnhance. Otherwise, "N/A".
*/
public static String getSegmentId() {
AbstractTracerContext context = CONTEXT.get();
return Objects.nonNull(context) ? context.getSegmentId() : EMPTY_TRACE_CONTEXT_ID;
}
/**
* @return the current span id if needEnhance. Otherwise, "N/A".
*/
public static String getSpanId() {
AbstractTracerContext context = CONTEXT.get();
return Objects.nonNull(context) ? context.getSpanId() : EMPTY_TRACE_CONTEXT_ID;
} }
public static AbstractSpan createEntrySpan(String operationName, ContextCarrier carrier) { public static AbstractSpan createEntrySpan(String operationName, ContextCarrier carrier) {
......
...@@ -31,6 +31,7 @@ import org.apache.skywalking.apm.agent.core.context.trace.NoopSpan; ...@@ -31,6 +31,7 @@ import org.apache.skywalking.apm.agent.core.context.trace.NoopSpan;
*/ */
public class IgnoredTracerContext implements AbstractTracerContext { public class IgnoredTracerContext implements AbstractTracerContext {
private static final NoopSpan NOOP_SPAN = new NoopSpan(); private static final NoopSpan NOOP_SPAN = new NoopSpan();
private static final String IGNORE_TRACE = "Ignored_Trace";
private final CorrelationContext correlationContext; private final CorrelationContext correlationContext;
private final ExtensionContext extensionContext; private final ExtensionContext extensionContext;
...@@ -65,7 +66,17 @@ public class IgnoredTracerContext implements AbstractTracerContext { ...@@ -65,7 +66,17 @@ public class IgnoredTracerContext implements AbstractTracerContext {
@Override @Override
public String getReadablePrimaryTraceId() { public String getReadablePrimaryTraceId() {
return "Ignored_Trace"; return IGNORE_TRACE;
}
@Override
public String getSegmentId() {
return IGNORE_TRACE;
}
@Override
public String getSpanId() {
return IGNORE_TRACE;
} }
@Override @Override
......
...@@ -243,6 +243,16 @@ public class TracingContext implements AbstractTracerContext { ...@@ -243,6 +243,16 @@ public class TracingContext implements AbstractTracerContext {
return segment.getRelatedGlobalTraces().get(0); return segment.getRelatedGlobalTraces().get(0);
} }
@Override
public String getSegmentId() {
return segment.getTraceSegmentId();
}
@Override
public String getSpanId() {
return String.valueOf(activeSpan().getSpanId());
}
/** /**
* Create an entry span * Create an entry span
* *
......
/*
* 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 org.apache.skywalking.apm.toolkit.activation.trace;
import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.StaticMethodsAroundInterceptor;
public class SegmentIDInterceptor implements StaticMethodsAroundInterceptor {
private static final ILog LOGGER = LogManager.getLogger(SegmentIDInterceptor.class);
@Override
public void beforeMethod(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,
MethodInterceptResult result) {
result.defineReturnValue(ContextManager.getSegmentId());
}
@Override
public Object afterMethod(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,
Object ret) {
return ret;
}
@Override
public void handleMethodException(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,
Throwable t) {
LOGGER.error("Failed to getDefault segment Id.", t);
}
}
/*
* 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 org.apache.skywalking.apm.toolkit.activation.trace;
import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.StaticMethodsAroundInterceptor;
public class SpanIDInterceptor implements StaticMethodsAroundInterceptor {
private static final ILog LOGGER = LogManager.getLogger(SpanIDInterceptor.class);
@Override
public void beforeMethod(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,
MethodInterceptResult result) {
result.defineReturnValue(ContextManager.getSpanId());
}
@Override
public Object afterMethod(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,
Object ret) {
return ret;
}
@Override
public void handleMethodException(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,
Throwable t) {
LOGGER.error("Failed to getDefault span Id.", t);
}
}
...@@ -35,9 +35,13 @@ import static net.bytebuddy.matcher.ElementMatchers.named; ...@@ -35,9 +35,13 @@ import static net.bytebuddy.matcher.ElementMatchers.named;
*/ */
public class TraceContextActivation extends ClassStaticMethodsEnhancePluginDefine { public class TraceContextActivation extends ClassStaticMethodsEnhancePluginDefine {
public static final String INTERCEPT_CLASS = "org.apache.skywalking.apm.toolkit.activation.trace.TraceContextInterceptor"; public static final String TRACE_ID_INTERCEPT_CLASS = "org.apache.skywalking.apm.toolkit.activation.trace.TraceIDInterceptor";
public static final String SEGMENT_ID_INTERCEPT_CLASS = "org.apache.skywalking.apm.toolkit.activation.trace.SegmentIDInterceptor";
public static final String SPAN_ID_INTERCEPT_CLASS = "org.apache.skywalking.apm.toolkit.activation.trace.SpanIDInterceptor";
public static final String ENHANCE_CLASS = "org.apache.skywalking.apm.toolkit.trace.TraceContext"; public static final String ENHANCE_CLASS = "org.apache.skywalking.apm.toolkit.trace.TraceContext";
public static final String ENHANCE_METHOD = "traceId"; public static final String ENHANCE_TRACE_ID_METHOD = "traceId";
public static final String ENHANCE_SEGMENT_ID_METHOD = "segmentId";
public static final String ENHANCE_SPAN_ID_METHOD = "spanId";
public static final String ENHANCE_GET_CORRELATION_METHOD = "getCorrelation"; public static final String ENHANCE_GET_CORRELATION_METHOD = "getCorrelation";
public static final String INTERCEPT_GET_CORRELATION_CLASS = "org.apache.skywalking.apm.toolkit.activation.trace.CorrelationContextGetInterceptor"; public static final String INTERCEPT_GET_CORRELATION_CLASS = "org.apache.skywalking.apm.toolkit.activation.trace.CorrelationContextGetInterceptor";
public static final String ENHANCE_PUT_CORRELATION_METHOD = "putCorrelation"; public static final String ENHANCE_PUT_CORRELATION_METHOD = "putCorrelation";
...@@ -61,12 +65,12 @@ public class TraceContextActivation extends ClassStaticMethodsEnhancePluginDefin ...@@ -61,12 +65,12 @@ public class TraceContextActivation extends ClassStaticMethodsEnhancePluginDefin
new StaticMethodsInterceptPoint() { new StaticMethodsInterceptPoint() {
@Override @Override
public ElementMatcher<MethodDescription> getMethodsMatcher() { public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named(ENHANCE_METHOD); return named(ENHANCE_TRACE_ID_METHOD);
} }
@Override @Override
public String getMethodsInterceptor() { public String getMethodsInterceptor() {
return INTERCEPT_CLASS; return TRACE_ID_INTERCEPT_CLASS;
} }
@Override @Override
...@@ -74,6 +78,39 @@ public class TraceContextActivation extends ClassStaticMethodsEnhancePluginDefin ...@@ -74,6 +78,39 @@ public class TraceContextActivation extends ClassStaticMethodsEnhancePluginDefin
return false; return false;
} }
}, },
new StaticMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named(ENHANCE_SEGMENT_ID_METHOD);
}
@Override
public String getMethodsInterceptor() {
return SEGMENT_ID_INTERCEPT_CLASS;
}
@Override
public boolean isOverrideArgs() {
return false;
}
},
new StaticMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
return named(ENHANCE_SPAN_ID_METHOD);
}
@Override
public String getMethodsInterceptor() {
return SPAN_ID_INTERCEPT_CLASS;
}
@Override
public boolean isOverrideArgs() {
return false;
}
},
new StaticMethodsInterceptPoint() { new StaticMethodsInterceptPoint() {
@Override @Override
public ElementMatcher<MethodDescription> getMethodsMatcher() { public ElementMatcher<MethodDescription> getMethodsMatcher() {
......
...@@ -25,9 +25,9 @@ import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.StaticMet ...@@ -25,9 +25,9 @@ import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.StaticMet
import org.apache.skywalking.apm.agent.core.context.ContextManager; import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult; import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
public class TraceContextInterceptor implements StaticMethodsAroundInterceptor { public class TraceIDInterceptor implements StaticMethodsAroundInterceptor {
private static final ILog LOGGER = LogManager.getLogger(TraceContextInterceptor.class); private static final ILog LOGGER = LogManager.getLogger(TraceIDInterceptor.class);
@Override @Override
public void beforeMethod(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes, public void beforeMethod(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,
......
...@@ -14,6 +14,23 @@ import TraceContext; ...@@ -14,6 +14,23 @@ import TraceContext;
modelAndView.addObject("traceId", TraceContext.traceId()); modelAndView.addObject("traceId", TraceContext.traceId());
``` ```
* Use `TraceContext.segmentId()` API to obtain segmentId.
```java
import TraceContext;
...
modelAndView.addObject("segmentId", TraceContext.segmentId());
```
* Use `TraceContext.spanId()` API to obtain spanId.
```java
import TraceContext;
...
modelAndView.addObject("spanId", TraceContext.spanId());
```
_Sample codes only_ _Sample codes only_
* Add `@Trace` to any method you want to trace. After that, you can see the span in the Stack. * Add `@Trace` to any method you want to trace. After that, you can see the span in the Stack.
......
...@@ -143,6 +143,9 @@ segmentItems: ...@@ -143,6 +143,9 @@ segmentItems:
tags: tags:
- {key: url, value: 'http://localhost:8080/apm-toolkit-trace-scenario/case/tool-kit'} - {key: url, value: 'http://localhost:8080/apm-toolkit-trace-scenario/case/tool-kit'}
- {key: http.method, value: GET} - {key: http.method, value: GET}
- {key: traceID, value: not null}
- {key: segmentID, value: not null}
- {key: spanID, value: not null}
skipAnalysis: 'true' skipAnalysis: 'true'
refs: refs:
- {parentEndpoint: /app, networkAddress: '127.0.0.1:8080', refType: CrossProcess, - {parentEndpoint: /app, networkAddress: '127.0.0.1:8080', refType: CrossProcess,
......
...@@ -36,6 +36,24 @@ public class TraceContext { ...@@ -36,6 +36,24 @@ public class TraceContext {
return ""; return "";
} }
/**
* Try to get the segmentId of current trace context.
*
* @return segmentId, if it exists, or empty {@link String}.
*/
public static String segmentId() {
return "";
}
/**
* Try to get the spanId of current trace context.
*
* @return spanId, if it exists, or empty {@link String}.
*/
public static String spanId() {
return "";
}
/** /**
* Try to get the custom value from trace context. * Try to get the custom value from trace context.
* *
......
...@@ -59,6 +59,9 @@ public class TestController { ...@@ -59,6 +59,9 @@ public class TestController {
testService.testTagAnnotation("testTagAnnotationParam1", "testTagAnnotationParam2"); testService.testTagAnnotation("testTagAnnotationParam1", "testTagAnnotationParam2");
testService.testTagAnnotationReturnInfo("zhangsan", 15); testService.testTagAnnotationReturnInfo("zhangsan", 15);
TraceContext.putCorrelation(CORRELATION_CONTEXT_KEY, CORRELATION_CONTEXT_VALUE); TraceContext.putCorrelation(CORRELATION_CONTEXT_KEY, CORRELATION_CONTEXT_VALUE);
ActiveSpan.tag("traceID", TraceContext.traceId());
ActiveSpan.tag("segmentID", TraceContext.segmentId());
ActiveSpan.tag("spanID", TraceContext.spanId());
testService.asyncCallable(() -> { testService.asyncCallable(() -> {
visit("http://localhost:8080/apm-toolkit-trace-scenario/case/asyncVisit/callable"); visit("http://localhost:8080/apm-toolkit-trace-scenario/case/asyncVisit/callable");
return true; return true;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册