Opentracing + Uber Jaeger 全链路灰度调用链,Nepxion Discovery

当网关和服务在实施全链路分布式灰度发布和路由时候,我们需要一款追踪系统来监控网关和服务走的是哪个灰度组,哪个灰度版本,哪个灰度区域,甚至监控从Http Header头部全程传递的灰度规则和路由策略。这个功能意义在于:

  • 不仅可以监控全链路中基本的调用信息,也可以监控额外的灰度信息,有助于我们判断灰度发布和路由是否执行准确,一旦有问题,也可以快速定位
  • 可以监控流量何时切换到新版本,或者新的区域,或者新的机器上
  • 可以监控灰度规则和路由策略是否配置准确
  • 可以监控网关和服务灰度上下级树状关系
  • 可以监控全链路流量拓扑图

笔者尝试调研了一系列分布式追踪系统和中间件,包括Opentracing、Uber Jaeger、Twitter Zipkin、Apache Skywalking、Pinpoint、CAT等,最后决定采用Opentracing + Uber Jaeger方式来实现,重要原因除了易用性和可扩展性外,Opentracing支持WebMvc和WebFlux两种方式,业界的追踪系统能支持WebFlux相对较少

[OpenTracing] OpenTracing已进入CNCF,正在为全球的分布式追踪系统提供统一的概念、规范、架构和数据标准。它通过提供平台无关、厂商无关的API,使得开发人员能够方便的添加(或更换)追踪系统的实现。对于存在多样化的技术栈共存的调用链中,Opentracing适配Java、C、Go和.Net等技术栈,实现全链路分布式追踪功能。迄今为止,Uber Jaeger、Twitter Zipkin和Apache Skywalking已经适配了Opentracing规范

笔者以Nepxion社区的Discovery开源框架(对该开源框架感兴趣的同学,请访问如下链接)为例子展开整合

源码主页,请访问 https://github.com/Nepxion/Discovery

指南主页,请访问 https://github.com/Nepxion/DiscoveryGuide

文档主页,请访问 https://pan.baidu.com/s/1i57rXaNKPuhGRqZ2MONZOA#list/path=%2FNepxion

整合的效果图

Alt text Alt text Alt text Alt text Alt text

基本概念

灰度调用链主要包括如下11个参数。使用者可以自行定义要传递的调用链参数,例如:traceId, spanId等;也可以自行定义要传递的业务调用链参数,例如:mobile, user等

11. n-d-service-group - 服务所属组或者应用 22. n-d-service-type - 服务类型,分为“网关”和“服务” 33. n-d-service-id - 服务ID 44. n-d-service-address - 服务地址,包括Host和Port 55. n-d-service-version - 服务版本 66. n-d-service-region - 服务所属区域 77. n-d-version - 版本路由值 88. n-d-region - 区域路由值 99. n-d-address - 地址路由值 1010. n-d-version-weight - 版本权重路由值 1111. n-d-region-weight - 区域权重路由值

核心实现

Opentracing通用模块

源码参考 https://github.com/Nepxion/Discovery/tree/master/discovery-plugin-strategy-opentracing

由于OpenTracing扩展需要兼顾到Spring Cloud Gateway、Zuul和服务,它的核心逻辑存在着一定的可封装性,所以笔者抽取出一个公共模块discovery-plugin-strategy-opentracing,包含configuration、operation、context等模块,着重阐述operation模块,其它比较简单,不一一赘述了

在阐述前,笔者需要解释一个配置,该配置将决定核心实现以及终端界面的显示

  1. 如果开启,灰度信息输出到独立的Span节点中,意味着在界面显示中,灰度信息通过独立的GRAY Span节点来显示。优点是信息简洁明了,缺点是Span节点会增长一倍。我们可以称呼它为【模式A】

  2. 如果关闭,灰度信息输出到原生的Span节点中,意味着在界面显示中,灰度信息会和原生Span节点的调用信息、协议信息等混在一起,缺点是信息庞杂混合,优点是Span节点数不会增长。我们可以称呼它为【模式B】

    启动和关闭调用链的灰度信息在Opentracing中以独立的Span节点输出,如果关闭,则灰度信息输出到原生的Span节点中。缺失则默认为true

    spring.application.strategy.trace.opentracing.separate.span.enabled=true

Opentracing公共操作类 - StrategyOpentracingOperation.java

  • 装配注入Opentracing的Tracer对象

  • opentracingInitialize方法,提供给网关和服务的Span节点初始化

    • 【模式A】下,tracer.buildSpan(...).start()实现新建一个Span,并把它放置到存储上下文的StrategyOpentracingContext的ThreadLocal里
    • 【模式B】下,不需要做任何工作
  • opentracingHeader方法,提供给网关的灰度调用链输出

    • 【模式A】下,首先从StrategyOpentracingContext的ThreadLocal里获取Span对象,其次把customizationMap(自定义的调用链参数)的元素都放入到Tag中,最后把灰度调用链主11个参数(通过strategyContextHolder.getHeader(...)获取)和更多上下文信息放入到Tag中
    • 【模式B】下,跟【模式A】类似,唯一区别的是Tags.COMPONENT的处理,由于原生的Span节点已经带有该信息,所以不需要放入到Tag中
  • opentracingLocal方法,提供给服务的灰度调用链输出

    • 【模式A】下,首先从StrategyOpentracingContext的ThreadLocal里获取Span对象,其次把customizationMap(自定义的调用链参数)的元素都放入到Tag中,最后把灰度调用链主11个参数(通过pluginAdapter.getXXX()获取)和更多上下文信息放入到Tag中
    • 【模式B】下,跟【模式A】类似,唯一区别的是Tags.COMPONENT的处理,由于原生的Span节点已经带有该信息,所以不需要放入到Tag中
  • opentracingError方法,提供给服务的灰度调用链异常输出

    • 【模式A】下,首先从StrategyOpentracingContext的ThreadLocal里获取Span对象,其次span.log(...)方法实现异常输出
    • 【模式B】下,不需要做任何工作
  • opentracingClear方法,灰度调用链的Span上报和清除

    • 【模式A】下,首先从StrategyOpentracingContext的ThreadLocal里获取Span对象,其次span.finish()方法实现Span上报,最后StrategyOpentracingContext.clearCurrentContext()方法实现Span清除
    • 【模式B】下,不需要做任何工作
  • getCurrentSpan方法

    • 【模式A】下,返回StrategyOpentracingContext.getCurrentContext().getSpan(),即opentracingInitialize新建的Span对象
    • 【模式B】下,返回tracer.activeSpan(),即原生的Span对象

    public class StrategyOpentracingOperation { private static final Logger LOG = LoggerFactory.getLogger(StrategyOpentracingOperation.class);

    1@Autowired 2protected PluginAdapter pluginAdapter; 3 4@Autowired 5protected StrategyContextHolder strategyContextHolder; 6 7@Autowired 8private Tracer tracer; 9 10@Value("${" + StrategyOpentracingConstant.SPRING_APPLICATION_STRATEGY_TRACE_OPENTRACING_ENABLED + ":false}") 11protected Boolean traceOpentracingEnabled; 12 13@Value("${" + StrategyOpentracingConstant.SPRING_APPLICATION_STRATEGY_TRACE_OPENTRACING_SEPARATE_SPAN_ENABLED + ":true}") 14protected Boolean traceOpentracingSeparateSpanEnabled; 15 16public void opentracingInitialize() { 17 if (!traceOpentracingEnabled) { 18 return; 19 } 20 21 if (!traceOpentracingSeparateSpanEnabled) { 22 return; 23 } 24 25 Span span = tracer.buildSpan(DiscoveryConstant.SPAN_VALUE).start(); 26 StrategyOpentracingContext.getCurrentContext().setSpan(span); 27 28 LOG.debug("Trace chain for Opentracing initialized..."); 29} 30 31public void opentracingHeader(Map<String, String> customizationMap) { 32 if (!traceOpentracingEnabled) { 33 return; 34 } 35 36 Span span = getCurrentSpan(); 37 if (span == null) { 38 LOG.error("Span not found in context to opentracing header"); 39 40 return; 41 } 42 43 if (MapUtils.isNotEmpty(customizationMap)) { 44 for (Map.Entry<String, String> entry : customizationMap.entrySet()) { 45 span.setTag(entry.getKey(), entry.getValue()); 46 } 47 } 48 49 if (traceOpentracingSeparateSpanEnabled) { 50 span.setTag(Tags.COMPONENT.getKey(), DiscoveryConstant.TAG_COMPONENT_VALUE); 51 } 52 span.setTag(DiscoveryConstant.PLUGIN, DiscoveryConstant.PLUGIN_VALUE); 53 span.setTag(DiscoveryConstant.TRACE_ID, span.context().toTraceId()); 54 span.setTag(DiscoveryConstant.SPAN_ID, span.context().toSpanId()); 55 span.setTag(DiscoveryConstant.N_D_SERVICE_GROUP, strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP)); 56 ... 57 58 String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); 59 if (StringUtils.isNotEmpty(routeVersion)) { 60 span.setTag(DiscoveryConstant.N_D_VERSION, routeVersion); 61 } 62 ... 63 64 LOG.debug("Trace chain information outputs to Opentracing..."); 65} 66 67public void opentracingLocal(String className, String methodName, Map<String, String> customizationMap) { 68 if (!traceOpentracingEnabled) { 69 return; 70 } 71 72 Span span = getCurrentSpan(); 73 if (span == null) { 74 LOG.error("Span not found in context to opentracing local"); 75 76 return; 77 } 78 79 if (MapUtils.isNotEmpty(customizationMap)) { 80 for (Map.Entry<String, String> entry : customizationMap.entrySet()) { 81 span.setTag(entry.getKey(), entry.getValue()); 82 } 83 } 84 85 if (traceOpentracingSeparateSpanEnabled) { 86 span.setTag(Tags.COMPONENT.getKey(), DiscoveryConstant.TAG_COMPONENT_VALUE); 87 } 88 span.setTag(DiscoveryConstant.PLUGIN, DiscoveryConstant.PLUGIN_VALUE); 89 span.setTag(DiscoveryConstant.CLASS, className); 90 span.setTag(DiscoveryConstant.METHOD, methodName); 91 span.setTag(DiscoveryConstant.TRACE_ID, span.context().toTraceId()); 92 span.setTag(DiscoveryConstant.SPAN_ID, span.context().toSpanId()); 93 span.setTag(DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); 94 ... 95 96 String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); 97 if (StringUtils.isNotEmpty(routeVersion)) { 98 span.setTag(DiscoveryConstant.N_D_VERSION, routeVersion); 99 } 100 ... 101 102 LOG.debug("Trace chain information outputs to Opentracing..."); 103} 104 105public void opentracingError(String className, String methodName, Throwable e) { 106 if (!traceOpentracingEnabled) { 107 return; 108 } 109 110 if (!traceOpentracingSeparateSpanEnabled) { 111 return; 112 } 113 114 Span span = getCurrentSpan(); 115 if (span == null) { 116 LOG.error("Span not found in context to opentracing error"); 117 118 return; 119 } 120 121 span.log(new ImmutableMap.Builder<String, Object>() 122 .put(DiscoveryConstant.CLASS, className) 123 .put(DiscoveryConstant.METHOD, methodName) 124 .put(DiscoveryConstant.EVENT, Tags.ERROR.getKey()) 125 .put(DiscoveryConstant.ERROR_OBJECT, e) 126 .build()); 127 128 LOG.debug("Trace chain error outputs to Opentracing..."); 129} 130 131public void opentracingClear() { 132 if (!traceOpentracingEnabled) { 133 return; 134 } 135 136 if (!traceOpentracingSeparateSpanEnabled) { 137 return; 138 } 139 140 Span span = getCurrentSpan(); 141 if (span != null) { 142 span.finish(); 143 } else { 144 LOG.error("Span not found in context to opentracing clear"); 145 } 146 StrategyOpentracingContext.clearCurrentContext(); 147 148 LOG.debug("Trace chain context of Opentracing cleared..."); 149} 150 151public Span getCurrentSpan() { 152 return traceOpentracingSeparateSpanEnabled ? StrategyOpentracingContext.getCurrentContext().getSpan() : tracer.activeSpan(); 153} 154 155public String getTraceId() { 156 if (!traceOpentracingEnabled) { 157 return null; 158 } 159 160 Span span = getCurrentSpan(); 161 if (span != null) { 162 return span.context().toTraceId(); 163 } 164 165 return null; 166} 167 168public String getSpanId() { 169 if (!traceOpentracingEnabled) { 170 return null; 171 } 172 173 Span span = getCurrentSpan(); 174 if (span != null) { 175 return span.context().toSpanId(); 176 } 177 178 return null; 179}

    }

Opentracing Service模块

源码参考 https://github.com/Nepxion/Discovery/tree/master/discovery-plugin-strategy-starter-service-opentracing

实现OpenTracing对服务的扩展,包含configuration、tracer等模块,着重阐述tracer模块,其它比较简单,不一一赘述了

Opentracing的服务追踪类 - DefaultServiceStrategyOpentracingTracer.java

  • 继承DefaultServiceStrategyTracer,并注入StrategyOpentracingOperation

  • trace方法里先执行opentracingInitialize初始化Span,这样可以让后面的逻辑都可以从Span中拿到traceId和spanId,执行opentracingLocal实现服务的灰度调用链输出

  • error方法里执行opentracingError实现服务的灰度调用链异常输出

  • release方法里执行opentracingClear实现灰度调用链的Span上报和清除

    public class DefaultServiceStrategyOpentracingTracer extends DefaultServiceStrategyTracer { @Autowired private StrategyOpentracingOperation strategyOpentracingOperation;

    1@Override 2public void trace(ServiceStrategyTracerInterceptor interceptor, MethodInvocation invocation) { 3 strategyOpentracingOperation.opentracingInitialize(); 4 5 super.trace(interceptor, invocation); 6 7 strategyOpentracingOperation.opentracingLocal(interceptor.getMethod(invocation).getDeclaringClass().getName(), interceptor.getMethodName(invocation), getCustomizationMap()); 8} 9 10@Override 11public void error(ServiceStrategyTracerInterceptor interceptor, MethodInvocation invocation, Throwable e) { 12 super.error(interceptor, invocation, e); 13 14 strategyOpentracingOperation.opentracingError(interceptor.getMethod(invocation).getDeclaringClass().getName(), interceptor.getMethodName(invocation), e); 15} 16 17@Override 18public void release(ServiceStrategyTracerInterceptor interceptor, MethodInvocation invocation) { 19 super.release(interceptor, invocation); 20 21 strategyOpentracingOperation.opentracingClear(); 22} 23 24@Override 25public String getTraceId() { 26 return strategyOpentracingOperation.getTraceId(); 27} 28 29@Override 30public String getSpanId() { 31 return strategyOpentracingOperation.getSpanId(); 32}

    }

Opentracing Spring Cloud Gateway模块

源码参考 https://github.com/Nepxion/Discovery/tree/master/discovery-plugin-strategy-starter-gateway-opentracing

实现OpenTracing对Spring Cloud Gateway的扩展,跟discovery-plugin-strategy-starter-service-opentracing模块类似,不一一赘述了

Opentracing Zuul模块

源码参考 https://github.com/Nepxion/Discovery/tree/master/discovery-plugin-strategy-starter-zuul-opentracing

实现OpenTracing对Zuul的扩展,跟discovery-plugin-strategy-starter-service-opentracing模块类似,不一一赘述了

使用说明

示例参考 https://github.com/Nepxion/DiscoveryGuide

使用方式

Opentracing输出方式以Uber Jaeger为例来说明,步骤非常简单

  1. https://pan.baidu.com/s/1i57rXaNKPuhGRqZ2MONZOA#list/path=%2FNepxion获取Jaeger-1.14.0.zip,Windows操作系统下解压后运行jaeger.bat,Mac和Lunix操作系统请自行研究
  2. 执行Postman调用后,访问http://localhost:16686查看灰度调用链
  3. 灰度调用链支持WebMvc和WebFlux两种方式,以GRAY字样的标记来标识

开关控制

对于Opentracing调用链功能的开启和关闭,需要通过如下开关做控制:

1# 启动和关闭调用链。缺失则默认为false 2spring.application.strategy.trace.enabled=true 3# 启动和关闭调用链的Opentracing输出,支持F版或更高版本的配置,其它版本不需要该行配置。缺失则默认为false 4spring.application.strategy.trace.opentracing.enabled=true 5# 启动和关闭调用链的灰度信息在Opentracing中以独立的Span节点输出,如果关闭,则灰度信息输出到原生的Span节点中。缺失则默认为true 6spring.application.strategy.trace.opentracing.separate.span.enabled=true

可选功能

自定义调用链上下文参数的创建(该类不是必须的),继承DefaultStrategyTracerAdapter

1// 自定义调用链上下文参数的创建 2// 对于getTraceId和getSpanId方法,在Opentracing等调用链中间件引入的情况下,由调用链中间件决定,在这里定义不会起作用;在Opentracing等调用链中间件未引入的情况下,在这里定义才有效,下面代码中表示从Http Header中获取,并全链路传递 3// 对于getCustomizationMap方法,表示输出到调用链中的定制化业务参数,可以同时输出到日志和Opentracing等调用链中间件,下面代码中表示从Http Header中获取,并全链路传递 4public class MyStrategyTracerAdapter extends DefaultStrategyTracerAdapter { 5 @Override 6 public String getTraceId() { 7 return StringUtils.isNotEmpty(strategyContextHolder.getHeader(DiscoveryConstant.TRACE_ID)) ? strategyContextHolder.getHeader(DiscoveryConstant.TRACE_ID) : StringUtils.EMPTY; 8 } 9 10 @Override 11 public String getSpanId() { 12 return StringUtils.isNotEmpty(strategyContextHolder.getHeader(DiscoveryConstant.SPAN_ID)) ? strategyContextHolder.getHeader(DiscoveryConstant.SPAN_ID) : StringUtils.EMPTY; 13 } 14 15 @Override 16 public Map<String, String> getCustomizationMap() { 17 return new ImmutableMap.Builder<String, String>() 18 .put("mobile", StringUtils.isNotEmpty(strategyContextHolder.getHeader("mobile")) ? strategyContextHolder.getHeader("mobile") : StringUtils.EMPTY) 19 .put("user", StringUtils.isNotEmpty(strategyContextHolder.getHeader("user")) ? strategyContextHolder.getHeader("user") : StringUtils.EMPTY) 20 .build(); 21 } 22} 23

在配置类里@Bean方式进行调用链类创建,覆盖框架内置的调用链类

1@Bean 2public StrategyTracerAdapter strategyTracerAdapter() { 3 return new MyStrategyTracerAdapter(); 4}

本文作者

任浩军, 10 多年开源经历,Github ID:@HaojunRen,Nepxion 开源社区创始人,Nacos Group Member,Spring Cloud Alibaba & Nacos & Sentinel Committer

请联系我

微信、公众号和文档

Alt textAlt textAlt text

本文由博客一文多发平台 OpenWrite 发布!

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

Nepxion Discovery Agent

前言基于SpringCloud的全链路灰度蓝绿发布功能,其中一个场景是,基于Header传递的全链路灰度路由,采用配置中心配置路由策略映射在网关或者服务上,支持根据用户自定义Header跟路由策略整合,最终转化为路由Header信息而实现,路由策略传递到全链路服务中。这是一个非常普遍的需求,但如果业务方用了服务之间异步调用的方式,会导致存储在Th