AppEvent.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. using Newtonsoft.Json.Linq;
  2. using Sers.Core.Module.App;
  3. using Sers.Core.Module.App.AppEvent;
  4. using Sers.Core.Module.Message;
  5. using Sers.Core.Module.Rpc;
  6. using Sers.Gover.Base;
  7. using System;
  8. using System.Collections.Generic;
  9. using Vit.Core.Module.Log;
  10. using Vit.Extensions;
  11. using Vit.Extensions.IEnumerable;
  12. using zipkin4net;
  13. using zipkin4net.Tracers.Zipkin;
  14. using zipkin4net.Transport.Http;
  15. namespace Sers.Gover.Apm.Zipkin
  16. {
  17. public class AppEvent : IAppEvent
  18. {
  19. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  20. Action<Object, Vit.Core.Util.Pipelines.ByteData> ApiScopeEvent(RpcContextData rpcData, ApiMessage apiRequestMessage)
  21. {
  22. //记录请求数据
  23. #region (x.1)get id(traceId spanId parentSpanId) and create trace
  24. Trace trace = null;
  25. try
  26. {
  27. long spanId = 0;
  28. long traceId = 0;
  29. long? parentSpanId = null;
  30. {
  31. var hexStr = rpcData.caller.rid;
  32. spanId = hexStr.Substring(0, 16).HexStringToInt64();
  33. }
  34. {
  35. var hexStr = rpcData.caller_rootRid_Get();
  36. if (hexStr == null)
  37. {
  38. traceId = spanId;
  39. }
  40. else
  41. {
  42. traceId = hexStr.Substring(0, 16).HexStringToInt64();
  43. }
  44. }
  45. {
  46. var hexStr = rpcData.caller_parentRid_Get();
  47. parentSpanId = hexStr?.Substring(0, 16).HexStringToInt64();
  48. }
  49. var spanState = new zipkin4net.SpanState(traceId, parentSpanId, spanId, true, false);
  50. trace = Trace.CreateFromId(spanState);
  51. }
  52. catch (Exception ex)
  53. {
  54. trace = Trace.Create();
  55. Logger.Error(ex);
  56. }
  57. Trace.Current = trace;
  58. #endregion
  59. trace.Record(Annotations.ClientSend());
  60. trace.Record(Annotations.Rpc(config.rpcName));
  61. trace.Record(Annotations.ServiceName(rpcData.apiStationName_Get()??""));
  62. return (s, apiReplyMessage) => {
  63. //gover会在内部把route处理为真正的route名称
  64. #region rpc data
  65. //trace.Record(Annotations.Tag("http.url", rpcData.http_url_Get()));
  66. //trace.Record(Annotations.Tag("http.method", rpcData.http_method_Get()));
  67. //trace.Record(Annotations.Tag("http.path", rpcData.route));
  68. //try
  69. //{
  70. // trace.Record(Annotations.Tag("ReqRpc", rpcData.oriJson.ToString()));
  71. // string str = apiRequestMessage.value_OriData.ArraySegmentByteToString() ?? "";
  72. // trace.Record(Annotations.Tag("ReqData", str ));
  73. //}
  74. //catch
  75. //{
  76. //}
  77. #endregion
  78. #region method getTagValue
  79. string requestRpc_oriString = null;
  80. JObject requestRpc_json = null;
  81. string requestData_oriString = null;
  82. JObject requestData_json = null;
  83. ApiMessage apiResponseMessage = null;
  84. string responseRpc_oriString = null;
  85. JObject responseRpc_json = null;
  86. string responseData_oriString = null;
  87. JObject responseData_json = null;
  88. string GetTagValue(string valueString)
  89. {
  90. if (string.IsNullOrEmpty(valueString)) return null;
  91. if (!valueString.StartsWith("{{") || !valueString.EndsWith("}}")) return valueString;
  92. try
  93. {
  94. valueString = valueString.Substring(2, valueString.Length - 4);
  95. string dataType;
  96. string path;
  97. var splitIndex = valueString.IndexOf('.');
  98. if (splitIndex < 0)
  99. {
  100. dataType = valueString;
  101. path = "";
  102. }
  103. else
  104. {
  105. dataType = valueString.Substring(0, splitIndex);
  106. path = valueString.Substring(splitIndex + 1);
  107. }
  108. switch (dataType)
  109. {
  110. case "requestRpc":
  111. if (requestRpc_oriString == null)
  112. {
  113. requestRpc_oriString = apiRequestMessage.rpcContextData_OriData.ArraySegmentByteToString();
  114. }
  115. if (string.IsNullOrEmpty(path))
  116. {
  117. return requestRpc_oriString;
  118. }
  119. if (requestRpc_json == null)
  120. {
  121. requestRpc_json = requestRpc_oriString.Deserialize<JObject>();
  122. }
  123. return requestRpc_json?.SelectToken(path).ConvertToString();
  124. case "requestData":
  125. if (requestData_oriString == null)
  126. {
  127. requestData_oriString = apiRequestMessage.value_OriData.ArraySegmentByteToString();
  128. }
  129. if (string.IsNullOrEmpty(path))
  130. {
  131. return requestData_oriString;
  132. }
  133. if (requestData_json == null)
  134. {
  135. requestData_json = requestData_oriString.Deserialize<JObject>();
  136. }
  137. return requestData_json?.SelectToken(path).ConvertToString();
  138. case "responseRpc":
  139. if (apiResponseMessage == null)
  140. {
  141. apiResponseMessage = new ApiMessage();
  142. apiResponseMessage.Unpack(apiReplyMessage.ToArraySegment());
  143. }
  144. if (responseRpc_oriString == null)
  145. {
  146. responseRpc_oriString = apiResponseMessage.rpcContextData_OriData.ArraySegmentByteToString();
  147. }
  148. if (string.IsNullOrEmpty(path))
  149. {
  150. return responseRpc_oriString;
  151. }
  152. if (responseRpc_json == null)
  153. {
  154. responseRpc_json = responseRpc_oriString.Deserialize<JObject>();
  155. }
  156. return responseRpc_json?.SelectToken(path).ConvertToString();
  157. case "responseData":
  158. if (apiResponseMessage == null)
  159. {
  160. apiResponseMessage = new ApiMessage();
  161. apiResponseMessage.Unpack(apiReplyMessage.ToArraySegment());
  162. }
  163. if (responseData_oriString == null)
  164. {
  165. responseData_oriString = apiResponseMessage.value_OriData.ArraySegmentByteToString();
  166. }
  167. if (string.IsNullOrEmpty(path))
  168. {
  169. return responseData_oriString;
  170. }
  171. if (responseData_json == null)
  172. {
  173. responseData_json = responseData_oriString.Deserialize<JObject>();
  174. }
  175. return responseData_json?.SelectToken(path).ConvertToString();
  176. }
  177. }
  178. catch
  179. {
  180. }
  181. return null;
  182. }
  183. #endregion
  184. //tags
  185. config.tags?.ForEach(item =>
  186. {
  187. var key = GetTagValue(item.Key);
  188. var value = GetTagValue(item.Value);
  189. if (key != null && value != null)
  190. {
  191. trace.Record(Annotations.Tag(key, value));
  192. }
  193. });
  194. trace.Record(Annotations.ClientRecv());
  195. };
  196. }
  197. public void InitEvent(JObject arg)
  198. {
  199. config = arg.Deserialize<Config>();
  200. if (string.IsNullOrEmpty(config.rpcName)) config.rpcName = "ServiceCenter";
  201. Logger.Info("[zipkin]初始化中... config: " + config?.Serialize());
  202. }
  203. Config config;
  204. public void BeforeStart()
  205. {
  206. if (config == null) return;
  207. #region (x.1)注册和启动 Zipkin
  208. if (config.SamplingRate <= 0 ) config.SamplingRate = 1;
  209. TraceManager.SamplingRate = config.SamplingRate;
  210. // 在链路追踪控制台获取 Zipkin Endpoint,注意 Endpoint 中不包含“/api/v2/spans”。
  211. HttpZipkinSender httpSender = new HttpZipkinSender(config.zipkinCollectorUrl, "application/json");
  212. var tracer = new ZipkinTracer(httpSender, new JSONSpanSerializer());
  213. TraceManager.RegisterTracer(tracer);
  214. TraceManager.Start(new MyLogger());
  215. #endregion
  216. GoverApiCenterService.Instance.AddApiScopeEvent(ApiScopeEvent);
  217. Logger.Info("[zipkin]启动成功");
  218. }
  219. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  220. public void OnStart()
  221. {
  222. }
  223. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  224. public void AfterStart()
  225. {
  226. }
  227. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  228. public void BeforeStop()
  229. {
  230. TraceManager.Stop();
  231. }
  232. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  233. public void AfterStop()
  234. {
  235. }
  236. }
  237. #region Config Model
  238. class Config
  239. {
  240. public float SamplingRate;
  241. public string zipkinCollectorUrl;
  242. public string rpcName;
  243. public string serviceStationName;
  244. public IDictionary<string, string> tags;
  245. }
  246. #endregion
  247. #region MyLogger
  248. class MyLogger : ILogger
  249. {
  250. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  251. public void LogError(string message)
  252. {
  253. Logger.Error("[zipkin]" + message);
  254. }
  255. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  256. public void LogInformation(string message)
  257. {
  258. Logger.Info("[zipkin]" + message);
  259. }
  260. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  261. public void LogWarning(string message)
  262. {
  263. Logger.log.Log(Level.WARN, "[zipkin]" + message);
  264. }
  265. }
  266. #endregion
  267. }