SkyWalking链路追踪上下文TraceContext的追踪身份traceId生成的实现原理剖析

结论先行

SkyWalking 通过字节码增强技术实现,结合依赖注入和控制反转思想,以SkyWalking方式将追踪身份traceId编织到链路追踪上下文TraceContext中。
是不是很有趣,很有意思!!!

实现原理剖析

TraceContext.traceId()

org.apache.skywalking.apm.toolkit.trace.TraceContext#traceId

请求链路追踪上下文TraceContext,调用TraceContext.traceId()获取追踪身份traceId

package org.apache.skywalking.apm.toolkit.trace;import java.util.Optional;/*** Try to access the sky-walking tracer context. The context is not existed, always. only the middleware, component, or* rpc-framework are supported in the current invoke stack, in the same thread, the context will be available.* <p>*/
public class TraceContext {/*** Try to get the traceId of current trace context.** @return traceId, if it exists, or empty {@link String}.*/public static String traceId() {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. The spanId is a negative number when the trace context is* missing.** @return spanId, if it exists, or empty {@link String}.*/public static int spanId() {return -1;}/*** Try to get the custom value from trace context.** @return custom data value.*/public static Optional<String> getCorrelation(String key) {return Optional.empty();}/*** Put the custom key/value into trace context.** @return previous value if it exists.*/public static Optional<String> putCorrelation(String key, String value) {return Optional.empty();}}

1.链路追踪上下文的traceId是如何设置进去的?

skywalking:java-agent项目仓库里搜索org.apache.skywalking.apm.toolkit.trace.TraceContext
repo:apache/skywalking-java org.apache.skywalking.apm.toolkit.trace.TraceContext language:Java
在这里插入图片描述
在IDEA skywalking:java-agent项目源代码里搜索org.apache.skywalking.apm.toolkit.trace.TraceContext
在这里插入图片描述

【结论】通过字节码增强技术实现,结合依赖注入和控制反转思想,以SkyWalking方式将追踪身份traceId编织到链路追踪上下文TraceContext中。
在这里插入图片描述

TraceContextActivation

org.apache.skywalking.apm.toolkit.activation.trace.TraceContextActivation

链路追踪上下文激活TraceContextActivation,通过TraceIDInterceptor拦截TraceContext.traceId(),将追踪身份traceId设置到链路追踪上下文TraceContext

package org.apache.skywalking.apm.toolkit.activation.trace;import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.ClassStaticMethodsEnhancePluginDefine;
import org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;
import org.apache.skywalking.apm.agent.core.plugin.match.NameMatch;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.StaticMethodsInterceptPoint;import static net.bytebuddy.matcher.ElementMatchers.named;/*** Active the toolkit class "TraceContext". Should not dependency or import any class in* "skywalking-toolkit-trace-context" module. Activation's classloader is diff from "TraceContext", using direct will* trigger classloader issue.* <p>*/
public class TraceContextActivation extends ClassStaticMethodsEnhancePluginDefine {// 追踪身份traceId拦截类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_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 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 INTERCEPT_PUT_CORRELATION_CLASS = "org.apache.skywalking.apm.toolkit.activation.trace.CorrelationContextPutInterceptor";/*** @return the target class, which needs active.*/@Overrideprotected ClassMatch enhanceClass() {return NameMatch.byName(ENHANCE_CLASS);}/*** @return the collection of {@link StaticMethodsInterceptPoint}, represent the intercepted methods and their* interceptors.*/@Overridepublic StaticMethodsInterceptPoint[] getStaticMethodsInterceptPoints() {// 方法拦截点return new StaticMethodsInterceptPoint[] {new StaticMethodsInterceptPoint() {@Overridepublic ElementMatcher<MethodDescription> getMethodsMatcher() {return named(ENHANCE_TRACE_ID_METHOD);}@Overridepublic String getMethodsInterceptor() {return TRACE_ID_INTERCEPT_CLASS;}@Overridepublic boolean isOverrideArgs() {return false;}},// ...};}
}

TraceIDInterceptor

org.apache.skywalking.apm.toolkit.activation.trace.TraceIDInterceptor

追踪身份拦截器TraceIDInterceptor,调用ContextManager.getGlobalTraceId()获取追踪身份traceId,将其返回给TraceContext.traceId()
在这里插入图片描述

package org.apache.skywalking.apm.toolkit.activation.trace;import java.lang.reflect.Method;
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.StaticMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;public class TraceIDInterceptor implements StaticMethodsAroundInterceptor {private static final ILog LOGGER = LogManager.getLogger(TraceIDInterceptor.class);@Overridepublic void beforeMethod(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,MethodInterceptResult result) {// 获取第一个全局追踪身份traceId,将其定义为方法返回值result.defineReturnValue(ContextManager.getGlobalTraceId());}@Overridepublic Object afterMethod(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,Object ret) {// 返回追踪身份traceIdreturn ret;}@Overridepublic void handleMethodException(Class clazz, Method method, Object[] allArguments, Class<?>[] parameterTypes,Throwable t) {LOGGER.error("Failed to getDefault trace Id.", t);}
}

ContextManager.getGlobalTraceId()

org.apache.skywalking.apm.agent.core.context.ContextManager#getGlobalTraceId

链路追踪上下文管理器ContextManager
ContextManager.getGlobalTraceId()是获取第一个全局追踪身份traceId,其调用AbstractTracerContext.getReadablePrimaryTraceId()获取全局追踪身份traceId
在这里插入图片描述

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.ServiceManager;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
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.sampling.SamplingService;
import org.apache.skywalking.apm.util.StringUtil;import static org.apache.skywalking.apm.agent.core.conf.Config.Agent.OPERATION_NAME_THRESHOLD;/*** {@link ContextManager} controls the whole context of {@link TraceSegment}. Any {@link TraceSegment} relates to* single-thread, so this context use {@link ThreadLocal} to maintain the context, and make sure, since a {@link* TraceSegment} starts, all ChildOf spans are in the same context. <p> What is 'ChildOf'?* https://github.com/opentracing/specification/blob/master/specification.md#references-between-spans** <p> Also, {@link ContextManager} delegates to all {@link AbstractTracerContext}'s major methods.*/
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 ThreadLocal<AbstractTracerContext> CONTEXT = new ThreadLocal<AbstractTracerContext>();private static ThreadLocal<RuntimeContext> RUNTIME_CONTEXT = new ThreadLocal<RuntimeContext>();private static ContextManagerExtendService EXTEND_SERVICE;private static AbstractTracerContext getOrCreate(String operationName, boolean forceSampling) {AbstractTracerContext context = CONTEXT.get();if (context == null) {if (StringUtil.isEmpty(operationName)) {if (LOGGER.isDebugEnable()) {LOGGER.debug("No operation name, ignore this trace.");}context = new IgnoredTracerContext();} else {if (EXTEND_SERVICE == null) {EXTEND_SERVICE = ServiceManager.INSTANCE.findService(ContextManagerExtendService.class);}context = EXTEND_SERVICE.createTraceContext(operationName, forceSampling);}CONTEXT.set(context);}return context;}private static AbstractTracerContext get() {return CONTEXT.get();}/*** 获取第一个全局追踪身份traceId* @return the first global trace id when tracing. Otherwise, "N/A".*/public static String getGlobalTraceId() {// 追踪上下文AbstractTracerContext context = CONTEXT.get();// 获取全局追踪身份traceIdreturn Objects.nonNull(context) ? context.getReadablePrimaryTraceId() : EMPTY_TRACE_CONTEXT_ID;}/*** @return the current segment id when tracing. 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 when tracing. Otherwise, the value is -1.*/public static int getSpanId() {AbstractTracerContext context = CONTEXT.get();return Objects.nonNull(context) ? context.getSpanId() : -1;}/*** @return the current primary endpoint name. Otherwise, the value is null.*/public static String getPrimaryEndpointName() {AbstractTracerContext context = CONTEXT.get();return Objects.nonNull(context) ? context.getPrimaryEndpointName() : null;}public static AbstractSpan createEntrySpan(String operationName, ContextCarrier carrier) {AbstractSpan span;AbstractTracerContext context;operationName = StringUtil.cut(operationName, OPERATION_NAME_THRESHOLD);if (carrier != null && carrier.isValid()) {SamplingService samplingService = ServiceManager.INSTANCE.findService(SamplingService.class);samplingService.forceSampled();context = getOrCreate(operationName, true);span = context.createEntrySpan(operationName);context.extract(carrier);} else {context = getOrCreate(operationName, false);span = context.createEntrySpan(operationName);}return span;}public static AbstractSpan createLocalSpan(String operationName) {operationName = StringUtil.cut(operationName, OPERATION_NAME_THRESHOLD);AbstractTracerContext context = getOrCreate(operationName, false);return context.createLocalSpan(operationName);}public static AbstractSpan createExitSpan(String operationName, ContextCarrier carrier, String remotePeer) {if (carrier == null) {throw new IllegalArgumentException("ContextCarrier can't be null.");}operationName = StringUtil.cut(operationName, OPERATION_NAME_THRESHOLD);AbstractTracerContext context = getOrCreate(operationName, false);AbstractSpan span = context.createExitSpan(operationName, remotePeer);context.inject(carrier);return span;}public static AbstractSpan createExitSpan(String operationName, String remotePeer) {operationName = StringUtil.cut(operationName, OPERATION_NAME_THRESHOLD);AbstractTracerContext context = getOrCreate(operationName, false);return context.createExitSpan(operationName, remotePeer);}public static void inject(ContextCarrier carrier) {get().inject(carrier);}public static void extract(ContextCarrier carrier) {if (carrier == null) {throw new IllegalArgumentException("ContextCarrier can't be null.");}if (carrier.isValid()) {get().extract(carrier);}}public static ContextSnapshot capture() {return get().capture();}// ...}

AbstractTracerContext.getReadablePrimaryTraceId()

org.apache.skywalking.apm.agent.core.context.AbstractTracerContext#getReadablePrimaryTraceId

追踪上下文定义接口AbstractTracerContext
本方法获取全局追踪身份traceId

package org.apache.skywalking.apm.agent.core.context;import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;/*** The <code>AbstractTracerContext</code> represents the tracer context manager.*/
public interface AbstractTracerContext {/*** Get the global trace id, if needEnhance. How to build, depends on the implementation.* 获取全局追踪身份traceId** @return the string represents the id.*/String getReadablePrimaryTraceId();/*** Prepare for the cross-process propagation. How to initialize the carrier, depends on the implementation.** @param carrier to carry the context for crossing process.*/void inject(ContextCarrier carrier);/*** Build the reference between this segment and a cross-process segment. How to build, depends on the* implementation.** @param carrier carried the context from a cross-process segment.*/void extract(ContextCarrier carrier);/*** Capture a snapshot for cross-thread propagation. It's a similar concept with ActiveSpan.Continuation in* OpenTracing-java How to build, depends on the implementation.** @return the {@link ContextSnapshot} , which includes the reference context.*/ContextSnapshot capture();/*** Build the reference between this segment and a cross-thread segment. How to build, depends on the* implementation.** @param snapshot from {@link #capture()} in the parent thread.*/void continued(ContextSnapshot snapshot);/*** 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.*/int getSpanId();/*** Create an entry span** @param operationName most likely a service name* @return the span represents an entry point of this segment.*/AbstractSpan createEntrySpan(String operationName);/*** Create a local span** @param operationName most likely a local method signature, or business name.* @return the span represents a local logic block.*/AbstractSpan createLocalSpan(String operationName);/*** Create an exit span** @param operationName most likely a service name of remote* @param remotePeer    the network id(ip:port, hostname:port or ip1:port1,ip2,port, etc.). Remote peer could be set*                      later, but must be before injecting.* @return the span represent an exit point of this segment.*/AbstractSpan createExitSpan(String operationName, String remotePeer);/*** @return the active span of current tracing context(stack)*/AbstractSpan activeSpan();/*** Finish the given span, and the given span should be the active span of current tracing context(stack)** @param span to finish* @return true when context should be clear.*/boolean stopSpan(AbstractSpan span);/*** Notify this context, current span is going to be finished async in another thread.** @return The current context*/AbstractTracerContext awaitFinishAsync();/*** The given span could be stopped officially.** @param span to be stopped.*/void asyncStop(AsyncSpan span);/*** Get current correlation context*/CorrelationContext getCorrelationContext();/*** Get current primary endpoint name*/String getPrimaryEndpointName();
}

AbstractTracerContext有两个子类IgnoredTracerContextTracingContext

IgnoredTracerContext.getReadablePrimaryTraceId()

org.apache.skywalking.apm.agent.core.context.IgnoredTracerContext#getReadablePrimaryTraceId

可忽略的追踪上下文IgnoredTracerContext
本方法返回"Ignored_Trace"

package org.apache.skywalking.apm.agent.core.context;import java.util.LinkedList;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.NoopSpan;/*** The <code>IgnoredTracerContext</code> represent a context should be ignored. So it just maintains the stack with an* integer depth field.* <p>* All operations through this will be ignored, and keep the memory and gc cost as low as possible.*/
public class IgnoredTracerContext implements AbstractTracerContext {private static final NoopSpan NOOP_SPAN = new NoopSpan();private static final String IGNORE_TRACE = "Ignored_Trace";private final CorrelationContext correlationContext;private final ExtensionContext extensionContext;private int stackDepth;public IgnoredTracerContext() {this.stackDepth = 0;this.correlationContext = new CorrelationContext();this.extensionContext = new ExtensionContext();}@Overridepublic String getReadablePrimaryTraceId() {// 获取全局追踪身份traceIdreturn IGNORE_TRACE;}@Overridepublic String getSegmentId() {return IGNORE_TRACE;}@Overridepublic int getSpanId() {return -1;}// ...}

TracingContext.getReadablePrimaryTraceId()

org.apache.skywalking.apm.agent.core.context.TracingContext#getReadablePrimaryTraceId

链路追踪上下文TracingContext
本方法返回DistributedTraceIdid字段属性
在这里插入图片描述

package org.apache.skywalking.apm.agent.core.context;import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.dynamic.watcher.SpanLimitWatcher;
import org.apache.skywalking.apm.agent.core.context.ids.DistributedTraceId;
import org.apache.skywalking.apm.agent.core.context.ids.PropagatedTraceId;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.EntrySpan;
import org.apache.skywalking.apm.agent.core.context.trace.ExitSpan;
import org.apache.skywalking.apm.agent.core.context.trace.ExitTypeSpan;
import org.apache.skywalking.apm.agent.core.context.trace.LocalSpan;
import org.apache.skywalking.apm.agent.core.context.trace.NoopExitSpan;
import org.apache.skywalking.apm.agent.core.context.trace.NoopSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegmentRef;
import org.apache.skywalking.apm.agent.core.profile.ProfileStatusReference;
import org.apache.skywalking.apm.agent.core.profile.ProfileTaskExecutionService;/*** The <code>TracingContext</code> represents a core tracing logic controller. It build the final {@link* TracingContext}, by the stack mechanism, which is similar with the codes work.* <p>* In opentracing concept, it means, all spans in a segment tracing context(thread) are CHILD_OF relationship, but no* FOLLOW_OF.* <p>* In skywalking core concept, FOLLOW_OF is an abstract concept when cross-process MQ or cross-thread async/batch tasks* happen, we used {@link TraceSegmentRef} for these scenarios. Check {@link TraceSegmentRef} which is from {@link* ContextCarrier} or {@link ContextSnapshot}.*/
public class TracingContext implements AbstractTracerContext {private static final ILog LOGGER = LogManager.getLogger(TracingContext.class);private long lastWarningTimestamp = 0;/*** @see ProfileTaskExecutionService*/private static ProfileTaskExecutionService PROFILE_TASK_EXECUTION_SERVICE;/*** The final {@link TraceSegment}, which includes all finished spans.* 追踪段,同一线程内的所有调用*/private TraceSegment segment;/*** Active spans stored in a Stack, usually called 'ActiveSpanStack'. This {@link LinkedList} is the in-memory* storage-structure. <p> I use {@link LinkedList#removeLast()}, {@link LinkedList#addLast(Object)} and {@link* LinkedList#getLast()} instead of {@link #pop()}, {@link #push(AbstractSpan)}, {@link #peek()}*/private LinkedList<AbstractSpan> activeSpanStack = new LinkedList<>();/*** @since 8.10.0 replace the removed "firstSpan"(before 8.10.0) reference. see {@link PrimaryEndpoint} for more details.*/private PrimaryEndpoint primaryEndpoint = null;/*** A counter for the next span.*/private int spanIdGenerator;/*** The counter indicates*/@SuppressWarnings("unused") // updated by ASYNC_SPAN_COUNTER_UPDATERprivate volatile int asyncSpanCounter;private static final AtomicIntegerFieldUpdater<TracingContext> ASYNC_SPAN_COUNTER_UPDATER =AtomicIntegerFieldUpdater.newUpdater(TracingContext.class, "asyncSpanCounter");private volatile boolean isRunningInAsyncMode;private volatile ReentrantLock asyncFinishLock;private volatile boolean running;private final long createTime;/*** profile status*/private final ProfileStatusReference profileStatus;@Getter(AccessLevel.PACKAGE)private final CorrelationContext correlationContext;@Getter(AccessLevel.PACKAGE)private final ExtensionContext extensionContext;//CDS watcherprivate final SpanLimitWatcher spanLimitWatcher;/*** Initialize all fields with default value.*/TracingContext(String firstOPName, SpanLimitWatcher spanLimitWatcher) {this.segment = new TraceSegment();this.spanIdGenerator = 0;isRunningInAsyncMode = false;createTime = System.currentTimeMillis();running = true;// profiling statusif (PROFILE_TASK_EXECUTION_SERVICE == null) {PROFILE_TASK_EXECUTION_SERVICE = ServiceManager.INSTANCE.findService(ProfileTaskExecutionService.class);}this.profileStatus = PROFILE_TASK_EXECUTION_SERVICE.addProfiling(this, segment.getTraceSegmentId(), firstOPName);this.correlationContext = new CorrelationContext();this.extensionContext = new ExtensionContext();this.spanLimitWatcher = spanLimitWatcher;}/*** 获取全局追踪身份traceId* @return the first global trace id.*/@Overridepublic String getReadablePrimaryTraceId() {// 获取分布式的追踪身份的id字段属性return getPrimaryTraceId().getId();}private DistributedTraceId getPrimaryTraceId() {// 获取追踪段相关的分布式的追踪身份return segment.getRelatedGlobalTrace();}// ...}

DistributedTraceId

org.apache.skywalking.apm.agent.core.context.ids.DistributedTraceId#id

分布式的追踪身份DistributedTraceId,表示一个分布式调用链路。

package org.apache.skywalking.apm.agent.core.context.ids;import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;/*** The <code>DistributedTraceId</code> presents a distributed call chain.* 表示一个分布式调用链路。* <p>* This call chain has a unique (service) entrance,* <p>* such as: Service : http://www.skywalking.com/cust/query, all the remote, called behind this service, rest remote, db* executions, are using the same <code>DistributedTraceId</code> even in different JVM.* <p>* The <code>DistributedTraceId</code> contains only one string, and can NOT be reset, creating a new instance is the* only option.*/
@RequiredArgsConstructor
@ToString
@EqualsAndHashCode
public abstract class DistributedTraceId {@Getterprivate final String id;
}

DistributedTraceId有两个子类PropagatedTraceIdNewDistributedTraceId

PropagatedTraceId

org.apache.skywalking.apm.agent.core.context.ids.PropagatedTraceId

传播的追踪身份PropagatedTraceId,表示从对等端传播的DistributedTraceId
在这里插入图片描述

package org.apache.skywalking.apm.agent.core.context.ids;/*** The <code>PropagatedTraceId</code> represents a {@link DistributedTraceId}, which is propagated from the peer.*/
public class PropagatedTraceId extends DistributedTraceId {public PropagatedTraceId(String id) {super(id);}
}

NewDistributedTraceId

org.apache.skywalking.apm.agent.core.context.ids.NewDistributedTraceId

新的分布式的追踪身份NewDistributedTraceId,是具有新生成的idDistributedTraceId
默认构造函数调用GlobalIdGenerator.generate()生成新的全局id
在这里插入图片描述

package org.apache.skywalking.apm.agent.core.context.ids;/*** The <code>NewDistributedTraceId</code> is a {@link DistributedTraceId} with a new generated id.*/
public class NewDistributedTraceId extends DistributedTraceId {public NewDistributedTraceId() {// 生成新的全局idsuper(GlobalIdGenerator.generate());}
}

GlobalIdGenerator.generate()

org.apache.skywalking.apm.agent.core.context.ids.GlobalIdGenerator#generate

全局id生成器GlobalIdGenerator
本方法用于生成一个新的全局id,是真正生成traceId的地方。
在这里插入图片描述

package org.apache.skywalking.apm.agent.core.context.ids;import java.util.UUID;import org.apache.skywalking.apm.util.StringUtil;public final class GlobalIdGenerator {// 应用实例进程身份idprivate static final String PROCESS_ID = UUID.randomUUID().toString().replaceAll("-", "");// 线程的id序列号的上下文private static final ThreadLocal<IDContext> THREAD_ID_SEQUENCE = ThreadLocal.withInitial(() -> new IDContext(System.currentTimeMillis(), (short) 0));private GlobalIdGenerator() {}/*** 生成一个新的id。* Generate a new id, combined by three parts.* <p>* The first one represents application instance id.* 第一部分,表示应用实例进程身份id* <p>* The second one represents thread id.* 第二部分,表示线程身份id* <p>* The third one also has two parts, 1) a timestamp, measured in milliseconds 2) a seq, in current thread, between* 0(included) and 9999(included)* 第三部分,也有两个部分, 1) 一个时间戳,单位是毫秒ms 2) 在当前线程中的一个序列号,位于[0,9999]之间** @return unique id to represent a trace or segment* 表示追踪或追踪段的唯一id*/public static String generate() {return StringUtil.join('.',PROCESS_ID,String.valueOf(Thread.currentThread().getId()),String.valueOf(THREAD_ID_SEQUENCE.get().nextSeq()));}private static class IDContext {private long lastTimestamp;private short threadSeq;// Just for considering time-shift-back only.private long lastShiftTimestamp;private int lastShiftValue;private IDContext(long lastTimestamp, short threadSeq) {this.lastTimestamp = lastTimestamp;this.threadSeq = threadSeq;}private long nextSeq() {return timestamp() * 10000 + nextThreadSeq();}private long timestamp() {long currentTimeMillis = System.currentTimeMillis();if (currentTimeMillis < lastTimestamp) {// Just for considering time-shift-back by Ops or OS. @hanahmily 's suggestion.if (lastShiftTimestamp != currentTimeMillis) {lastShiftValue++;lastShiftTimestamp = currentTimeMillis;}return lastShiftValue;} else {lastTimestamp = currentTimeMillis;return lastTimestamp;}}private short nextThreadSeq() {if (threadSeq == 10000) {threadSeq = 0;}return threadSeq++;}}
}

示例验证

Arthas monitor/watch/trace 相关
若不了解其实现原理,是很难想到这个切面点。
实践出真知识!!!

stack org.apache.skywalking.apm.agent.core.context.ids.NewDistributedTraceId <init> '@java.lang.Thread@currentThread().getName().startsWith("wanda_event")'watch org.apache.skywalking.apm.agent.core.context.ids.NewDistributedTraceId <init> '{target, returnObj}' '@java.lang.Thread@currentThread().getName().startsWith("wanda_event")' -x 6
[arthas@7]$ stack org.apache.skywalking.apm.agent.core.context.AbstractTracerContext getReadablePrimaryTraceId '@java.lang.Thread@currentThread().getName().startsWith("wanda_event")'
Press Q or Ctrl+C to abort.
Affect(class count: 2 , method count: 1) cost in 423 ms, listenerId: 3
ts=2024-03-04 21:03:59;thread_name=wanda_event-thread-1;id=140;is_daemon=false;priority=5;TCCL=org.springframework.boot.loader.LaunchedURLClassLoader@67fe380b@org.apache.skywalking.apm.agent.core.context.TracingContext.getReadablePrimaryTraceId()at org.apache.skywalking.apm.agent.core.context.ContextManager.getGlobalTraceId(ContextManager.java:77)at org.apache.skywalking.apm.toolkit.activation.trace.TraceIDInterceptor.beforeMethod(TraceIDInterceptor.java:35)at org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.StaticMethodsInter.intercept(StaticMethodsInter.java:73)at org.apache.skywalking.apm.toolkit.trace.TraceContext.traceId(TraceContext.java:-1)// SkyWalking核心链路是上面👆🏻// 调用TraceContext.traceId()at com.leoao.lpaas.logback.LeoaoJsonLayout.addCustomDataToJsonMap(LeoaoJsonLayout.java:29)at ch.qos.logback.contrib.json.classic.JsonLayout.toJsonMap(null:-1)at ch.qos.logback.contrib.json.classic.JsonLayout.toJsonMap(null:-1)at ch.qos.logback.contrib.json.JsonLayoutBase.doLayout(null:-1)at ch.qos.logback.core.encoder.LayoutWrappingEncoder.encode(LayoutWrappingEncoder.java:115)at ch.qos.logback.core.OutputStreamAppender.subAppend(OutputStreamAppender.java:230)at ch.qos.logback.core.rolling.RollingFileAppender.subAppend(RollingFileAppender.java:235)at ch.qos.logback.core.OutputStreamAppender.append(OutputStreamAppender.java:102)at ch.qos.logback.core.UnsynchronizedAppenderBase.doAppend(UnsynchronizedAppenderBase.java:84)at ch.qos.logback.core.spi.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:51)at ch.qos.logback.classic.Logger.appendLoopOnAppenders(Logger.java:270)at ch.qos.logback.classic.Logger.callAppenders(Logger.java:257)at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:421)at ch.qos.logback.classic.Logger.filterAndLog_1(Logger.java:398)at ch.qos.logback.classic.Logger.info(Logger.java:583)// 输出打印日志// log.info("receive event persistUserPositionEvent=[{}]", event);at com.lefit.wanda.domain.event.listener.PersistUserPositionEventListener.change(PersistUserPositionEventListener.java:23)at sun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethodAccessorImpl.java:-2)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at com.google.common.eventbus.Subscriber.invokeSubscriberMethod$original$ToNcZpNk(Subscriber.java:88)at com.google.common.eventbus.Subscriber.invokeSubscriberMethod$original$ToNcZpNk$accessor$utMvob4N(Subscriber.java:-1)at com.google.common.eventbus.Subscriber$auxiliary$8fYqzzq0.call(null:-1)at org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstMethodsInterWithOverrideArgs.intercept(InstMethodsInterWithOverrideArgs.java:85)at com.google.common.eventbus.Subscriber.invokeSubscriberMethod(Subscriber.java:-1)at com.google.common.eventbus.Subscriber$SynchronizedSubscriber.invokeSubscriberMethod(Subscriber.java:145)at com.google.common.eventbus.Subscriber$1.run(Subscriber.java:73)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)at java.lang.Thread.run(Thread.java:750)

参考引用


祝大家玩得开心!ˇˍˇ

简放,杭州

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/720498.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

1.1_2 性能指标——速率、带宽、吞吐量

文章目录 1.1_2 性能指标——速率、带宽、吞吐量&#xff08;一&#xff09;速率&#xff08;二&#xff09;带宽&#xff08;三&#xff09;吞吐量 1.1_2 性能指标——速率、带宽、吞吐量 &#xff08;一&#xff09;速率 速率即数据率或称数据传输率或比特率。 速率就是“快…

Redis的设计与实现

Redis的设计与实现 数据结构和内部编码 type命令实际返回的就是当前键的数据结构类型&#xff0c;它们分别是&#xff1a;string(字符串)hash(哈希)、list(列表)、set(集合)、zset (有序集合)&#xff0c;但这些只是Redis对外的数据结构。 实际上每种数据结构都有自己底层的…

Docker Protainer可视化平台,忘记登录密码,重置密码。

由于好久没有登录portainer系统&#xff0c;导致忘记了登录密码&#xff0c;试了好多常用的密码都不对&#xff0c;无奈只能重置密码。 一、停止protainer 容器 查看容器ID和COMMAND 用于停止容器 docker ps -a停止容器 docker stop portainer二、查找volume data 宿主机所在…

JavaEE之多线程

一.认识线程 1.多进程实现并发编程的不足之处&#xff1a; 引入多个进程的核心&#xff1a;实现并发编程&#xff08;c的CGI技术就是通过多进程的方式实现的网站后端开发&#xff09;。因为现在是一个多核cpu的时代&#xff0c;并发编程就是刚需。多进程实现并发编程&#xf…

达梦、金仓、南大、瀚高、优炫:从社区建设看企业技术自信心

正文约950字&#xff0c;预计阅读时间2分钟 国产技术厂商在面对自身产品问题时&#xff0c;往往保持回避态度&#xff0c;不愿公之于众&#xff0c;主要原因有2方面&#xff1a; 1&#xff0c;产品技术层面问题较多&#xff0c;如某些根本性缺陷难以攻克&#xff0c;或问题发…

java找工作之Mybatis(入门及xml配置相关)

Mybatis 学习Mybatis就要学会查看官网&#xff0c;官网地址如下&#xff1a;<MyBatis中文网 > 1、简介 1.1什么是Mybatis MyBatis 是一款优秀的持久层框架&#xff0c;它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取…

【Vue3】3-6 : 仿ElementPlus框架的el-button按钮组件实

文章目录 前言 本节内容实现需求完整代码如下&#xff1a; 前言 上节,我们学习了 slot插槽&#xff0c;组件内容的分发处理 本节内容 本小节利用前面学习的组件通信知识&#xff0c;来完成一个仿Element Plus框架的el-button按钮组件实现。 仿造的地址&#xff1a;uhttps://…

预充电阻器选型报告

1. 客户基础条件 预充时间 t≤200ms &#xff0c;电容 C1280uf &#xff0c;电池包最高电压 U410V&#xff0c;预充深度 98% &#xff0c;30 秒内连续预充 15 次。 1.1 现选型号 现选EAK预充电阻额定功率 60W&#xff0c;标称阻值为 35Ω&#xff0c;在 此条件下单次预充…

Unity 协程(Coroutine)到底是什么?

参考链接&#xff1a;Unity 协程(Coroutine)原理与用法详解_unity coroutine-CSDN博客 为啥在Unity中一般不考虑多线程 因为在Unity中&#xff0c;只能在主线程中获取物体的组件、方法、对象&#xff0c;如果脱离这些&#xff0c;Unity的很多功能无法实现&#xff0c;那么多线程…

红黑树的简单介绍

红黑树 红黑树的概念 红黑树&#xff0c;是一种二叉搜索树&#xff0c;但在每个结点上增加一个存储位表示结点的颜色&#xff0c;可以是Red或Black。 通过对任何一条从根到叶子的路径上各个结点着色方式的限制&#xff0c;红黑树确保没有一条路径会比其他路径长出俩倍&#x…

Python类 __init__() 是一个特殊的方法

设计者&#xff1a;ISDF工软未来 版本&#xff1a;v1.0 日期&#xff1a;2024/3/5__init__() 是一个特殊的方法 类似c# C的构造函数 两头都包含两个下划线&#xff0c;这是约定&#xff0c;用于与普通的函数保持区分class User:用户类def __init__(self,first_name,last_name):…

Linux 运维:CentOS/RHEL防火墙和selinux设置

Linux 运维&#xff1a;CentOS/RHEL防火墙和selinux设置 一、防火墙常用管理命令1.1 CentOS/RHEL 7系统1.2 CentOS/RHEL 6系统 二、临时/永久关闭SELinux2.1 临时更改SELinux的执行模式2.2 永久更改SELinux的执行模式 &#x1f496;The Begin&#x1f496;点点关注&#xff0c;…

Finetuning Large Language Models: Sharon Zhou

Finetuning Large Language Models 课程地址&#xff1a;https://www.deeplearning.ai/short-courses/finetuning-large-language-models/ 本文是学习笔记。 Goal&#xff1a; Learn the fundamentals of finetuning a large language model (LLM). Understand how finetu…

STM32(16)使用串口向电脑发送数据

发送字节 发送数组 发送字符和字符串 字符&#xff1a; 字符串&#xff1a; 字符串在电脑中以字符数组的形式存储

ElasticSearch之分布式模型介绍,选主,脑裂

写在前面 本文看下es分布式模型相关内容。 1&#xff1a;分布式模型 1.1&#xff1a;分布式特征 支持水平扩展&#xff0c;可以存储PB级别数据&#xff0c;每个就能都有自己唯一的名称,默认名称时elasticsearch&#xff0c;可以通过配置文件&#xff0c;如cluster.name: my…

PowerBI怎么修改数据库密码

第一步&#xff1a;点击转换数据 第二步&#xff1a;点击数据源设置 第三步&#xff1a;点击编辑权限 第四步&#xff1a;点击编辑 第五步&#xff1a;输入正要修改的密码就可以了

STM32启动过程及反汇编

STM32从Flash启动的过程&#xff0c;主要是从上电复位到main函数的过程&#xff0c;主要有以下步骤&#xff1a; 1.初始化堆栈指针 SP_initial_sp&#xff0c;初始化 PC 指针Reset_Handler 2.初始化中断向量表 3.配置系统时钟 4.调用 C 库函数_main 初始化用户堆栈&#xf…

SAP HANA中PAL算法使用入门

1 应用场合 SAP HANA作为一款内存数据库产品, 使得数据常驻内存, 物理磁盘的存储作为数据备份与日志记录, 以防断电内存中数据丢失. 这种构架大大的缩短了数据存取的时间, 使得SAP HANA很”高速”. 在传统数据模型中,数据库只是作为存取数据一个工具,对于类似下图所示的应用, 客…

星瑞格数据库管理系统

一. 产品介绍 随着信息化的到来&#xff0c;数据安全成为保障信息化建设的一个关键问题&#xff1b;数据库作为信息化系统的基础软件其自身安全以及对数据的保障是至关重要。现阶段国内重要部门的信息系统存放着大量敏感数据&#xff0c;为了保障其数据的安全性&#xff0c;使用…

11、电源管理入门之Regulator驱动

目录 1. Regulator驱动是什么? 2. Regulator框架介绍 2.1 regulator consumer 2.2 regulator core 2.3 regulator driver 3. DTS配置文件及初始化 4. 运行时调用 5. Consumer API 5.1 Consumer Regulator Access (static & dynamic drivers) 5.2 Regulator Outp…