skywalking部署--SkyWalking 源码分析 —— Agent 插件(二)之 Dubbo - * 异常处理方法
一、Dubbo 插件概述
1.1 插件作用与定位
SkyWalking 的 Dubbo 插件是分布式链路追踪中对 Dubbo 框架进行埋点支持的核心组件。它在 Dubbo 的服务消费端(Consumer)和服务提供端(Provider)分别进行拦截,实现:
跨进程链路传播:在 Dubbo 调用间传递 TraceContext
性能指标收集:记录 Dubbo 调用的耗时、状态等指标
拓扑关系构建:自动发现 Dubbo 服务间的依赖关系
异常追踪:捕获 Dubbo 调用过程中的异常信息
1.2 支持的 Dubbo 版本
xml
org.apache.dubbo
dubbo
2.7.0+
org.apache.dubbo
dubbo
3.0.0+
二、插件架构设计
2.1 整体架构
text
Dubbo Plugin Architecture:
┌─────────────────────────────────────────────────────────────┐
│ SkyWalking Agent │
├─────────────────────────────────────────────────────────────┤
│ Dubbo Plugin │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Consumer │ │ Provider │ │
│ │ Interceptor │ │ Interceptor │ │
│ └─────────────────┘ └─────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ ByteBuddy Bootstrap Plugin │
│ Instrumentation ClassLoader Definitions │
└─────────────────────────────────────────────────────────────┘
2.2 核心拦截点
java
// Dubbo 插件拦截点定义
public class DubboInstrumentation extends ClassInstanceMethodsEnhancePluginDefine {
// 消费端拦截点
public static class ConsumerInstrumentation extends AbstractClassEnhancePluginDefine {
protected ClassMatch enhanceClass() {
return byName("org.apache.dubbo.monitor.support.MonitorFilter");
}
}
// 提供端拦截点
public static class ProviderInstrumentation extends AbstractClassEnhancePluginDefine {
protected ClassMatch enhanceClass() {
return byName("org.apache.dubbo.monitor.support.MonitorFilter");
}
}
}
三、消费端拦截器深度解析
3.1 DubboConsumerInterceptor 实现
java
public class DubboConsumerInterceptor implements InstanceMethodsAroundInterceptor {
private static final String ARGUMENTS = "arguments";
/**
* 前置拦截方法 - 在 Dubbo 调用前执行
*/
@Override
public void beforeMethod(EnhancedInstance objInst, Method method,
Object[] allArguments, Class[] argumentsTypes,
MethodInterceptResult result) throws Throwable {
// 1. 获取 Dubbo 调用上下文
Invoker invoker = (Invoker) allArguments[0];
Invocation invocation = (Invocation) allArguments[1];
// 2. 创建 ContextCarrier 用于跨进程上下文传播
ContextCarrier contextCarrier = new ContextCarrier();
// 3. 创建出口 Span
String remotePeer = getRemotePeer(invoker);
String operationName = buildOperationName(invoker, invocation);
AbstractSpan span = ContextManager.createExitSpan(operationName, contextCarrier, remotePeer);
// 4. 设置 Span 标签
Tags.URL.set(span, generateRequestURL(invoker, invocation));
Tags.SPAN_KIND.set(span, SpanKind.CLIENT);
setApplicationTag(span, invoker);
// 5. 将上下文注入到 Dubbo Invocation
injectContextCarrier(contextCarrier, invocation);
}
/**
* 获取远程服务地址
*/
private String getRemotePeer(Invoker invoker) {
URL url = invoker.getUrl();
return url.getHost() + ":" + url.getPort();
}
/**
* 构建操作名称
*/
private String buildOperationName(Invoker invoker, Invocation invocation) {
// 格式: ${interface}.${method}
return invoker.getInterface().getSimpleName() + "." + invocation.getMethodName();
}
/**
* 生成请求 URL
*/
private String generateRequestURL(Invoker invoker, Invocation invocation) {
URL url = invoker.getUrl();
StringBuilder requestURL = new StringBuilder();
requestURL.append(url.getProtocol()).append("://")
.append(url.getHost()).append(":").append(url.getPort())
.append("/").append(invoker.getInterface().getName())
.append(".").append(invocation.getMethodName());
return requestURL.toString();
}
/**
* 注入上下文到 Dubbo Invocation
*/
private void injectContextCarrier(ContextCarrier contextCarrier, Invocation invocation) {
CarrierItem next = contextCarrier.items();
while (next.hasNext()) {
next = next.next();
// 通过 Dubbo 的 attachment 机制传播上下文
invocation.getAttachments().put(next.getHeadKey(), next.getHeadValue());
}
}
}
3.2 消费端后置处理
java
public class DubboConsumerInterceptor implements InstanceMethodsAroundInterceptor {
/**
* 后置拦截方法 - 在 Dubbo 调用返回后执行
*/
@Override
public Object afterMethod(EnhancedInstance objInst, Method method,
Object[] allArguments, Class[] argumentsTypes,
Object ret) throws Throwable {
// 1. 获取当前活跃的 Span
AbstractSpan span = ContextManager.activeSpan();
// 2. 处理响应结果
if (ret instanceof Result) {
Result result = (Result) ret;
// 处理异常情况
if (result.hasException()) {
handleException(span, result.getException());
}
// 记录响应标签
Tags.STATUS_CODE.set(span, result.getException() == null ? "200" : "500");
}
// 3. 停止 Span
ContextManager.stopSpan();
return ret;
}
/**
* 异常处理方法
*/
private void handleException(AbstractSpan span, Throwable throwable) {
span.errorOccurred();
span.log(throwable);
// 记录异常类型标签
Tags.ERROR_TYPE.set(span, throwable.getClass().getName());
// 记录异常堆栈(可配置是否开启)
if (Config.Agent.RECORD_EXCEPTION_FULL_STACK) {
span.log(throwable);
}
}
/**
* 异常拦截方法
*/
@Override
public void handleMethodException(EnhancedInstance objInst, Method method,
Object[] allArguments, Class[] argumentsTypes,
Throwable t) {
AbstractSpan span = ContextManager.activeSpan();
handleException(span, t);
}
}
四、提供端拦截器深度解析
4.1 DubboProviderInterceptor 实现
java
public class DubboProviderInterceptor implements InstanceMethodsAroundInterceptor {
/**
* 前置拦截方法 - 在服务提供端接收请求时执行
*/
@Override
public void beforeMethod(EnhancedInstance objInst, Method method,
Object[] allArguments, Class[] argumentsTypes,
MethodInterceptResult result) throws Throwable {
// 1. 获取 Dubbo 调用上下文
Invoker invoker = (Invoker) allArguments[0];
Invocation invocation = (Invocation) allArguments[1];
// 2. 从 Dubbo Invocation 中提取上下文
ContextCarrier contextCarrier = new ContextCarrier();
extractContextCarrier(contextCarrier, invocation);
// 3. 创建入口 Span
String operationName = buildOperationName(invoker, invocation);
AbstractSpan span = ContextManager.createEntrySpan(operationName, contextCarrier);
// 4. 设置 Span 标签
Tags.URL.set(span, generateRequestURL(invoker, invocation));
Tags.SPAN_KIND.set(span, SpanKind.SERVER);
setApplicationTag(span, invoker);
// 5. 记录来源地址
String remotePeer = getRemoteAddress(invocation);
if (StringUtil.isNotEmpty(remotePeer)) {
span.setPeer(remotePeer);
}
}
/**
* 从 Dubbo Invocation 中提取上下文
*/
private void extractContextCarrier(ContextCarrier contextCarrier, Invocation invocation) {
Mapattachments = invocation.getAttachments();
if (attachments != null) {
CarrierItem next = contextCarrier.items();
while (next.hasNext()) {
next = next.next();
String value = attachments.get(next.getHeadKey());
if (StringUtil.isNotEmpty(value)) {
next.setHeadValue(value);
}
}
}
}
/**
* 获取客户端地址
*/
private String getRemoteAddress(Invocation invocation) {
// 从 RpcContext 获取客户端地址
RpcContext rpcContext = RpcContext.getContext();
if (rpcContext != null) {
String remoteHost = rpcContext.getRemoteHost();
int remotePort = rpcContext.getRemotePort();
if (StringUtil.isNotEmpty(remoteHost) && remotePort > 0) {
return remoteHost + ":" + remotePort;
}
}
return "";
}
}
4.2 提供端后置处理
java
public class DubboProviderInterceptor implements InstanceMethodsAroundInterceptor {
/**
* 后置拦截方法 - 在服务处理完成后执行
*/
@Override
public Object afterMethod(EnhancedInstance objInst, Method method,
Object[] allArguments, Class[] argumentsTypes,
Object ret) throws Throwable {
// 1. 获取当前 Span
AbstractSpan span = ContextManager.activeSpan();
// 2. 处理响应结果
if (ret instanceof Result) {
Result result = (Result) ret;
// 处理异常
if (result.hasException()) {
handleException(span, result.getException());
}
// 记录状态码
Tags.STATUS_CODE.set(span, result.getException() == null ? "200" : "500");
}
// 3. 停止 Span
ContextManager.stopSpan();
return ret;
}
/**
* 异常处理方法
*/
private void handleException(AbstractSpan span, Throwable throwable) {
span.errorOccurred();
// 记录异常类型
Tags.ERROR_TYPE.set(span, throwable.getClass().getName());
// 记录业务异常(非系统异常)
if (isBusinessException(throwable)) {
Tags.IS_BUSINESS_ERROR.set(span, true);
}
// 记录完整堆栈(根据配置)
if (Config.Agent.RECORD_EXCEPTION_FULL_STACK) {
span.log(throwable);
}
}
/**
* 判断是否为业务异常
*/
private boolean isBusinessException(Throwable throwable) {
// 根据异常类型判断,通常 RuntimeException 的子类被认为是业务异常
return throwable instanceof RuntimeException &&
!(throwable instanceof NullPointerException) &&
!(throwable instanceof IllegalArgumentException);
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method,
Object[] allArguments, Class[] argumentsTypes,
Throwable t) {
AbstractSpan span = ContextManager.activeSpan();
handleException(span, t);
}
}
五、上下文传播机制
5.1 Dubbo 上下文传播实现
java
public class DubboContextCarrierHelper {
/**
* Dubbo 上下文键值定义
*/
public static class ContextKey {
// SkyWalking 上下文头前缀
public static final String HEADER_NAME = "sw8";
// 跨进程传播的数据
public static final String CARRIER_DATA = "sw8-carrier";
}
/**
* 序列化上下文数据
*/
public static String serialize(ContextCarrier contextCarrier) {
if (contextCarrier == null) {
return null;
}
try {
// 使用 Base64 编码序列化数据
byte[] bytes = ContextCarrierSerializer.serialize(contextCarrier);
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
LOGGER.warn("Serialize context carrier error", e);
return null;
}
}
/**
* 反序列化上下文数据
*/
public static ContextCarrier deserialize(String base64Data) {
if (StringUtil.isEmpty(base64Data)) {
return null;
}
try {
byte[] bytes = Base64.getDecoder().decode(base64Data);
return ContextCarrierSerializer.deserialize(bytes);
} catch (Exception e) {
LOGGER.warn("Deserialize context carrier error", e);
return null;
}
}
}
5.2 自定义 Dubbo Filter 实现
java
/**
* SkyWalking 自定义 Dubbo Filter
* 用于增强上下文传播能力
*/
@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER})
public class SkyWalkingDubboFilter implements Filter {
private static final String SKYWALKING_FILTER_ENABLED = "skywalking.filter.enabled";
@Override
public Result invoke(Invoker invoker, Invocation invocation) throws RpcException {
// 检查是否启用 SkyWalking 过滤
if (!isSkyWalkingEnabled(invoker, invocation)) {
return invoker.invoke(invocation);
}
// 获取当前上下文
ContextManagerRuntimeContext context = getCurrentContext();
try {
if (RpcContext.getContext().isConsumerSide()) {
// 消费端处理
return handleConsumerSide(invoker, invocation, context); 拼多多帮助力入口
} else {
// 提供端处理
return handleProviderSide(invoker, invocation, context);
}
} catch (Throwable t) {
// 异常处理
return new AppResponse(t);
}
}
/**
* 消费端处理逻辑
*/
private Result handleConsumerSide(Invoker invoker, Invocation invocation,
ContextManagerRuntimeContext context) {
// 创建上下文载体
ContextCarrier carrier = new ContextCarrier();
// 构建操作名称
String operationName = buildOperationName(invoker, invocation);
// 创建出口 Span
AbstractSpan span = ContextManager.createExitSpan(operationName, carrier,
getRemoteAddress(invoker));
try {
// 注入上下文到 Dubbo Attachment
injectContextToAttachment(carrier, invocation);
// 执行原始调用
Result result = invoker.invoke(invocation);
// 处理响应
processResponse(span, result);
return result;
} finally {
ContextManager.stopSpan();
}
}
/**
* 提供端处理逻辑
*/
private Result handleProviderSide(Invoker invoker, Invocation invocation,
ContextManagerRuntimeContext context) {
// 从 Attachment 提取上下文
ContextCarrier carrier = extractContextFromAttachment(invocation);
// 构建操作名称
String operationName = buildOperationName(invoker, invocation);
// 创建入口 Span
AbstractSpan span = ContextManager.createEntrySpan(operationName, carrier);
try {
// 执行原始调用
Result result = invoker.invoke(invocation);
// 处理响应
processResponse(span, result);
return result;
} finally {
ContextManager.stopSpan();
}
}
}
六、插件配置与扩展
6.1 插件配置文件
properties
# plugin.config
plugin.dubbo.consumer.enable=true
plugin.dubbo.provider.enable=true
plugin.dubbo.arguments_collect_length=256
plugin.dubbo.operation_name_suffix=.call
# 采样配置
plugin.dubbo.sample_rate=10000
plugin.dubbo.ignore_methods=healthCheck,echo
# 异常配置
plugin.dubbo.record_exception_full_stack=true
plugin.dubbo.ignore_business_exception=false
6.2 自定义增强点
java
/**
* 自定义 Dubbo 增强点配置
*/
public class CustomDubboEnhance extends ClassInstanceMethodsEnhancePluginDefine {
@Override
protected ClassMatch enhanceClass() {
return NameMatch.byName("org.apache.dubbo.rpc.Filter");
}
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
return new ConstructorInterceptPoint[0];
}
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
return new InstanceMethodsInterceptPoint[] {
new InstanceMethodsInterceptPoint() {
@Override
public ElementMatchergetMethodsMatcher() {
return named("invoke");
}
@Override
public String getMethodsInterceptor() {
return "org.apache.skywalking.apm.plugin.dubbo.CustomDubboInterceptor";
}
@Override
public boolean isOverrideArgs() {
return false;
}
}
};
}
}
七、性能优化策略
7.1 异步调用支持
java
/**
* Dubbo 异步调用支持
*/
public class DubboAsyncInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method,
Object[] allArguments, Class[] argumentsTypes,
MethodInterceptResult result) throws Throwable {
// 对于异步调用,需要特殊处理上下文传播
if (isAsyncInvocation(allArguments)) {
handleAsyncInvocation(objInst, allArguments);
} else {
// 同步调用处理
handleSyncInvocation(objInst, allArguments);
}
}
/**
* 处理异步调用
*/
private void handleAsyncInvocation(EnhancedInstance objInst, Object[] allArguments) {
// 捕获当前上下文
ContextSnapshot snapshot = ContextManager.capture();
// 将上下文快照存储到异步上下文中
AsyncContext asyncContext = new AsyncContext(snapshot);
storeAsyncContext(allArguments, asyncContext);
}
/**
* 异步回调拦截
*/
public class DubboAsyncCallbackInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method,
Object[] allArguments, Class[] argumentsTypes,
MethodInterceptResult result) throws Throwable {
// 从异步上下文中恢复上下文
AsyncContext asyncContext = retrieveAsyncContext(allArguments);
if (asyncContext != null) {
ContextManager.continued(asyncContext.getSnapshot());
}
// 创建异步 Span
AbstractSpan span = ContextManager.createLocalSpan("dubbo.async.callback");
Tags.SPAN_LAYER.asHttp(span);
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method,
Object[] allArguments, Class[] argumentsTypes,
Object ret) throws Throwable {
// 停止异步 Span
ContextManager.stopSpan();
// 继续之前的上下文
ContextManager.continueAsyncContext();
return ret;
}
}
}
7.2 采样策略实现
java
/**
* Dubbo 采样策略
*/
public class DubboSamplingService {
private static final AtomicLong COUNTER = new AtomicLong(0);
private static final int SAMPLE_INTERVAL = 10000; // 采样间隔
/**
* 判断是否需要采样
*/
public static boolean needSample() {
// 固定比例采样
long count = COUNTER.incrementAndGet();
return count % SAMPLE_INTERVAL == 0;
}
/**
* 自适应采样
*/
public static boolean adaptiveSample(Invocation invocation) {
// 根据方法重要性进行采样
String methodName = invocation.getMethodName();
// 关键方法全量采样
if (isCriticalMethod(methodName)) {
return true;
}
// 高频方法降级采样
if (isHighFrequencyMethod(methodName)) {
return needSample();
}
// 普通方法默认采样
return true;
}
private static boolean isCriticalMethod(String methodName) {
return methodName.startsWith("create") ||
methodName.startsWith("update") ||
methodName.startsWith("delete");
}
private static boolean isHighFrequencyMethod(String methodName) {
return methodName.startsWith("query") ||
methodName.startsWith("get") ||
methodName.startsWith("list");
}
}
八、异常处理与容错
8.1 异常处理策略
java
/**
* Dubbo 插件异常处理器
*/
public class DubboExceptionHandler {
private static final ILog LOGGER = LogManager.getLogger(DubboExceptionHandler.class);
/**
* 处理 Dubbo 异常
*/
public static void handleException(AbstractSpan span, Throwable throwable,
Invocation invocation) {
if (throwable == null) {
return;
}
// 记录异常基本信息
span.errorOccurred();
span.log(throwable);
// 分类处理异常
ExceptionCategory category = categorizeException(throwable);
switch (category) {
case BUSINESS:
handleBusinessException(span, throwable, invocation);
break;
case NETWORK:
handleNetworkException(span, throwable, invocation);
break;
case TIMEOUT:
handleTimeoutException(span, throwable, invocation);
break;
default:
handleSystemException(span, throwable, invocation);
}
}
/**
* 异常分类
*/
private static ExceptionCategory categorizeException(Throwable throwable) {
if (throwable instanceof RpcException) {
RpcException rpcException = (RpcException) throwable;
if (rpcException.isTimeout()) {
return ExceptionCategory.TIMEOUT;
} else if (rpcException.isNetwork()) {
return ExceptionCategory.NETWORK;
} else if (rpcException.isBiz()) {
return ExceptionCategory.BUSINESS;
}
} else if (throwable instanceof RuntimeException) {
return ExceptionCategory.BUSINESS;
}
return ExceptionCategory.SYSTEM;
}
/**
* 处理业务异常
*/
private static void handleBusinessException(AbstractSpan span, Throwable throwable,
Invocation invocation) {
Tags.ERROR_TYPE.set(span, "BusinessError");
Tags.IS_BUSINESS_ERROR.set(span, true);
// 业务异常不记录完整堆栈(可配置)
if (Config.Plugin.Dubbo.RECORD_BUSINESS_EXCEPTION_STACK) {
span.log(throwable);
}
}
}
九、测试与验证
9.1 单元测试示例
java
/**
* Dubbo 插件单元测试
*/
public class DubboPluginTest {
@Test
public void testConsumerInterceptor() throws Throwable {
// 准备测试数据
EnhancedInstance enhancedInstance = mock(EnhancedInstance.class);
Method method = mock(Method.class);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(Invocation.class);
// 设置 Mock 行为
when(invoker.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:20880/test.Service"));
when(invoker.getInterface()).thenReturn(TestService.class);
when(invocation.getMethodName()).thenReturn("sayHello");
when(invocation.getArguments()).thenReturn(new Object[]{"world"});
Object[] allArguments = new Object[]{invoker, invocation};
// 执行拦截器
DubboConsumerInterceptor interceptor = new DubboConsumerInterceptor();
interceptor.beforeMethod(enhancedInstance, method, allArguments, new Class[0], null);
// 验证结果
AbstractSpan span = ContextManager.activeSpan();
assertNotNull(span);
assertEquals("TestService.sayHello", span.getOperationName());
}
@Test
public void testContextPropagation() {
// 测试上下文传播
ContextCarrier carrier = new ContextCarrier();
carrier.setTraceId("test-trace-id");
carrier.setSpanId(1);
// 序列化上下文
String serialized = DubboContextCarrierHelper.serialize(carrier);
assertNotNull(serialized);
// 反序列化上下文
ContextCarrier deserialized = DubboContextCarrierHelper.deserialize(serialized);
assertEquals("test-trace-id", deserialized.getTraceId());
assertEquals(1, deserialized.getSpanId());
}
}
十、总结
通过以上万字详细分析,我们可以看到 SkyWalking Dubbo 插件的核心实现机制:
双重拦截机制:通过拦截 Dubbo Filter 实现对消费端和提供端的统一处理
上下文传播:利用 Dubbo 的 Attachment 机制实现跨进程链路追踪
异步支持:完善的异步调用上下文传递机制
异常处理:细粒度的异常分类和处理策略
性能优化:采样策略和自适应优化机制