GoverManage.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. using System;
  2. using System.Collections.Generic;
  3. using Newtonsoft.Json;
  4. using Sers.Core.CL.MessageOrganize;
  5. using Sers.Core.Module.Api.ApiDesc;
  6. using Sers.Core.Module.Api.Data;
  7. using Sers.Core.Module.Api.RouteMap;
  8. using Sers.Core.Module.Env;
  9. using Sers.Core.Module.Message;
  10. using Sers.Core.Module.Rpc;
  11. using Sers.Gover.Base.Model;
  12. using Sers.Gover.Persistence;
  13. using Sers.Gover.RateLimit;
  14. using Sers.ServiceCenter.ApiCenter;
  15. using Sers.ServiceCenter.Entity;
  16. using Vit.Core.Module.Log;
  17. using Vit.Core.Util.ComponentModel.SsError;
  18. using Vit.Core.Util.ConfigurationManager;
  19. using Vit.Core.Util.Pipelines;
  20. using Vit.Extensions;
  21. namespace Sers.Gover.Base
  22. {
  23. [JsonObject(MemberSerialization.OptIn)]
  24. public class GoverManage : ApiCenterService
  25. {
  26. #region static
  27. public static readonly GoverManage Instance = LoadFromFile();
  28. static GoverManage LoadFromFile()
  29. {
  30. var mng=new GoverManage();
  31. Persistence_ApiDesc.ApiDesc_LoadAllFromJsonFile(mng.apiStationMng);
  32. Persistence_Counter.LoadCounterFromJsonFile(mng.apiStationMng);
  33. return mng;
  34. }
  35. public static void SaveToFile()
  36. {
  37. Persistence_Counter.SaveCounterToJsonFile(Instance.apiStationMng);
  38. }
  39. #endregion
  40. public GoverManage()
  41. {
  42. //init apiLoadBalancingMng
  43. switch (ConfigurationManager.Instance.GetStringByPath("Sers.ServiceCenter.ApiRouteType"))
  44. {
  45. case "IgnoreHttpMethod": apiLoadBalancingMng = new ApiLoadBalancingMng(); break;
  46. default: apiLoadBalancingMng = new ApiLoadBalancingMng_RESTful(); break;
  47. }
  48. serviceStationMng = new ServiceStationMng();
  49. serviceStationMng.Init(this);
  50. apiStationMng = new ApiStationMng();
  51. apiStationMng.Init(this);
  52. }
  53. internal readonly ApiLoadBalancingMng apiLoadBalancingMng;
  54. [JsonProperty]
  55. internal ApiStationMng apiStationMng { get; private set; }
  56. [JsonIgnore]
  57. internal ServiceStationMng serviceStationMng { get; private set; }
  58. [JsonIgnore]
  59. public RateLimitMng rateLimitMng { get; private set; } = new RateLimitMng();
  60. public void SaveUsageInfo(EnvUsageInfo item)
  61. {
  62. serviceStationMng.SaveUsageInfo(item);
  63. }
  64. #region ServiceStation
  65. public IEnumerable<SsApiDesc> ApiDesc_GetActive()
  66. {
  67. return apiLoadBalancingMng.GetAllApiDesc();
  68. }
  69. public IEnumerable<SsApiDesc> ApiDesc_GetAll()
  70. {
  71. return apiStationMng.ApiDesc_GetAll();
  72. }
  73. #endregion
  74. #region CallApi
  75. public override void CallApiAsync(IRpcContextData rpcData, ApiMessage requestMessage, Object sender, Action<object, Vit.Core.Util.Pipelines.ByteData> callback)
  76. {
  77. try
  78. {
  79. #region (x.0)ApiScopeEvent
  80. apiScopeEventList?.ForEach(onScope =>
  81. {
  82. try
  83. {
  84. var onDispose = onScope(rpcData, requestMessage);
  85. if (onDispose != null)
  86. {
  87. callback += onDispose;
  88. }
  89. }
  90. catch (Exception ex)
  91. {
  92. Logger.Error(ex);
  93. }
  94. });
  95. #endregion
  96. #region (x.1)route 判空
  97. if (string.IsNullOrWhiteSpace(rpcData.route))
  98. {
  99. //返回api 不存在
  100. SendReply(SsError.Err_ApiNotExists);
  101. return;
  102. }
  103. #endregion
  104. #region (x.2) 服务限流 BeforeLoadBalancing
  105. var error = rateLimitMng.BeforeLoadBalancing(rpcData, requestMessage);
  106. if (null != error)
  107. {
  108. SendReply(error);
  109. return;
  110. }
  111. #endregion
  112. #region (x.3) 负载均衡,获取对应服务端
  113. var apiNode = apiLoadBalancingMng.GetCurApiNodeByLoadBalancing(rpcData, out var routeType);
  114. if (null == apiNode)
  115. {
  116. //返回api 不存在
  117. SendReply(SsError.Err_ApiNotExists);
  118. return;
  119. }
  120. #endregion
  121. #region (x.4) 服务限流 BeforeCallRemoteApi
  122. error = rateLimitMng.BeforeCallRemoteApi(rpcData, requestMessage, apiNode);
  123. if (null != error)
  124. {
  125. SendReply(error);
  126. return;
  127. }
  128. #endregion
  129. #region (x.5) BeforeCallApi
  130. try
  131. {
  132. BeforeCallApi?.Invoke(rpcData, requestMessage);
  133. }
  134. catch (Exception ex)
  135. {
  136. Logger.Error(ex);
  137. }
  138. #endregion
  139. #region (x.6) 权限校验 SsValid
  140. // 权限校验不通过,调用次数也计数
  141. // TODO:应当有其他计数
  142. //(x.x.1) rpcValidations Sers1校验
  143. if (!Sers.Core.Module.Valid.Sers1.RpcVerify1.Verify(rpcData.oriJson, apiNode.apiDesc.rpcValidations, out var validError))
  144. {
  145. SendReply(validError);
  146. return;
  147. }
  148. //(x.x.2) rpcVerify2 Sers2校验
  149. if (!Sers.Core.Module.Valid.Sers2.RpcVerify2.Verify(rpcData.oriJson, apiNode.apiDesc.rpcVerify2, out var verifyError))
  150. {
  151. SendReply(verifyError);
  152. return;
  153. }
  154. #endregion
  155. #region (x.7) RpcContextData 修正
  156. //(x.x.1) 修正route
  157. // 调用服务端 泛接口(如: "/station1/fold2/*")时,route应修正为"/station1/fold2/*",而不是原始 地址(如: "/station1/fold2/index.html")
  158. if (routeType == ERouteType.genericRoute)
  159. {
  160. rpcData.route = apiNode.apiDesc.route;
  161. requestMessage.rpcContextData_OriData = ArraySegmentByteExtensions.Null;
  162. }
  163. //(x.x.2) 修正 requestMessage
  164. if (requestMessage.rpcContextData_OriData.Count <= 0) {
  165. requestMessage.RpcContextData_OriData_Set(rpcData);
  166. }
  167. #endregion
  168. #region (x.8)服务调用
  169. apiNode.CallApiAsync(rpcData, requestMessage, sender,callback);
  170. #endregion
  171. }
  172. catch (Exception ex)
  173. {
  174. Logger.Error(ex);
  175. ApiSysError.LogSysError(rpcData, requestMessage, ex.ToSsError());
  176. SendReply(SsError.Err_SysErr);
  177. return;
  178. }
  179. void SendReply(SsError error)
  180. {
  181. //callback(sender, new ApiMessage().InitByError(error).SetSysErrToRpcData(error).Package().ByteDataToBytes().BytesToArraySegmentByte());
  182. callback(sender, new ApiMessage().InitAsApiReplyMessageByError(error).Package());
  183. }
  184. }
  185. #endregion
  186. #region ServiceStation
  187. public List<ServiceStationData> ServiceStation_GetAll()
  188. {
  189. return serviceStationMng.ServiceStation_GetAll();
  190. }
  191. public override void ServiceStation_Regist(ServiceStation serviceStation)
  192. {
  193. Logger.Info("[ApiCenterService]Regist serviceStation,stationName:" + serviceStation?.serviceStationInfo?.serviceStationName);
  194. serviceStationMng.ServiceStation_Add(serviceStation);
  195. }
  196. /// <summary>
  197. /// 更新服务站点设备硬件信息
  198. /// </summary>
  199. /// <param name="serviceStation"></param>
  200. public override bool ServiceStation_UpdateStationInfo(ServiceStation serviceStation)
  201. {
  202. Logger.Info("[ApiCenterService]ServiceStation_UpdateStationInfo,stationName:" + serviceStation?.serviceStationInfo?.serviceStationName);
  203. return serviceStationMng.ServiceStation_UpdateStationInfo(serviceStation);
  204. }
  205. public override void ServiceStation_Remove(IOrganizeConnection conn)
  206. {
  207. string connKey = ""+ conn.GetHashCode();
  208. var serviceStation = serviceStationMng.ServiceStation_Remove(connKey);
  209. if (serviceStation != null)
  210. {
  211. Logger.Info("[ApiCenterService]Remove serviceStation,stationName:" + serviceStation?.serviceStationInfo?.serviceStationName);
  212. }
  213. }
  214. public bool ServiceStation_Pause(string connKey)
  215. {
  216. var serviceStation = serviceStationMng.ServiceStation_Pause(connKey);
  217. if (serviceStation != null)
  218. {
  219. Logger.Info("[ApiCenterService]Pause serviceStation,stationName:" + serviceStation?.serviceStationInfo?.serviceStationName);
  220. }
  221. return serviceStation != null;
  222. }
  223. public bool ServiceStation_Start(string connKey)
  224. {
  225. var serviceStation = serviceStationMng.ServiceStation_Start(connKey);
  226. if (serviceStation != null)
  227. {
  228. Logger.Info("[ApiCenterService]Start serviceStation,stationName:" + serviceStation?.serviceStationInfo?.serviceStationName);
  229. }
  230. return serviceStation != null;
  231. }
  232. public bool ServiceStation_Stop(string connKey)
  233. {
  234. var serviceStation = serviceStationMng.ServiceStation_Remove(connKey);
  235. if (serviceStation != null)
  236. {
  237. Logger.Info("[ApiCenterService]Stop serviceStation,stationName:" + serviceStation?.serviceStationInfo?.serviceStationName);
  238. serviceStation.connection.Close();
  239. }
  240. return serviceStation != null;
  241. }
  242. #endregion
  243. #region ApiStation
  244. public List<ApiStationData> ApiStation_GetAll()
  245. {
  246. return apiStationMng.ApiStation_GetAll();
  247. }
  248. public bool ApiStation_Pause(string stationName)
  249. {
  250. Logger.Info("[ApiCenterService]Pause ApiStation,stationName:" + stationName);
  251. return apiStationMng.ApiStation_Pause(stationName);
  252. }
  253. public bool ApiStation_Start(string stationName)
  254. {
  255. Logger.Info("[ApiCenterService]Start ApiStation,stationName:" + stationName);
  256. return apiStationMng.ApiStation_Start(stationName);
  257. }
  258. #endregion
  259. #region ApiScopeEvent
  260. /// <summary>
  261. ///
  262. /// </summary>
  263. List<Func<IRpcContextData, ApiMessage, Action<Object, Vit.Core.Util.Pipelines.ByteData>>> apiScopeEventList = null;
  264. /// <summary>
  265. /// 在调用api前调用onScope,若onScope返回的结果(onDispose)不为空,则在api调用结束前调用onDispose
  266. /// </summary>
  267. /// <param name="apiScopeEvent"></param>
  268. public void AddApiScopeEvent(Func<IRpcContextData, ApiMessage, Action<Object, Vit.Core.Util.Pipelines.ByteData>> apiScopeEvent)
  269. {
  270. if (apiScopeEventList == null) apiScopeEventList=new List<Func<IRpcContextData, ApiMessage, Action<Object, Vit.Core.Util.Pipelines.ByteData>>>();
  271. apiScopeEventList.Add(apiScopeEvent);
  272. }
  273. #endregion
  274. }
  275. }