AppEvent.cs 12 KB

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