vCloudServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. using System;
  2. using System.Collections.Generic;
  3. using Vinno.IUS.Common.Log;
  4. using Vinno.vCloud.Protocol.Initializers;
  5. using vCloud.Server.Configuration;
  6. using vCloud.Server.Logs;
  7. using vCloud.Server.ServerProtocol;
  8. using vCloud.Server.Services;
  9. using Vinno.IUS.Common.Network.Transfer;
  10. using Vinno.IUS.Common.Network;
  11. using vCloud.Server.Bus;
  12. using System.Threading.Tasks;
  13. using vCloud.Server.Services.ServerRegistry;
  14. using vCloud.Server.Services.Management;
  15. using System.Diagnostics;
  16. using System.IO;
  17. using Vinno.IUS.Common.Utilities;
  18. using vCloud.Server.Services.Database;
  19. using vCloud.Server.Utilities;
  20. using System.Configuration;
  21. namespace vCloud.Server
  22. {
  23. public class vCloudServer
  24. {
  25. private List<string> _dependencieNames = new List<string>();
  26. private readonly List<Service> _localServices = new List<Service>();
  27. private vCloudServiceBus _serviceBus;
  28. /// <summary>
  29. /// Gets all local service which be contained by this server.
  30. /// </summary>
  31. public IReadOnlyList<Service> LocalServices => _localServices;
  32. public vCloudServer(out bool isStartSuccess)
  33. {
  34. isStartSuccess = false;
  35. #if DEBUG
  36. #else
  37. if (!vCloudLicense.Instance.VerifyLicnese())
  38. {
  39. return;
  40. }
  41. vCloudLicense.Instance.NotifyLicenseExpirationClosedEvent += OnNotifyLicenseExpirationClosedEvent;
  42. #endif
  43. try
  44. {
  45. CommonInitializer.Initialize(AppContext.BaseDirectory); //TODO
  46. ServerTagsInitializer.Initialize();
  47. vCloudServerInitializer.Initialize();
  48. InitializeMessagePoolConfig();
  49. InitializeServiceBus();
  50. InitializeServices();
  51. DbMaintenance.SetDbVersion(_serviceBus.LocalHostMode, _serviceBus.IsMaster);
  52. Logger.WriteLineInfo("vCloud Server started!");
  53. InitializeAutoClearCache();
  54. isStartSuccess = true;
  55. StartDBAutoBackup();
  56. SetStarted();
  57. NationalPlatformHelper.Init();
  58. if (NationalPlatformHelper.IsFisrtSync)
  59. {
  60. DataSyncHelper.OrgDatasSync();
  61. DataSyncHelper.UserDatasSync();
  62. }
  63. #if DEBUG
  64. //NationalPlatformHelper.UploadUserInfo("Loki", "23192", "超声医学科", "NX6401052020000007",new DateTime(2022,04,02)).GetAwaiter().GetResult();
  65. //NationalPlatformHelper.UploadOrgInfo("YC2024030610005","测试医院-Loki",DateTime.Now).GetAwaiter().GetResult();UploadOrgInfos
  66. //NationalPlatformHelper.UploadOrgInfos().GetAwaiter().GetResult();
  67. //NationalPlatformHelper.GetOrgInfo("640000").GetAwaiter().GetResult();
  68. //NationalPlatformHelper.GetUserInfo("640000", "NX6401052020000007").GetAwaiter().GetResult();
  69. //NationalPlatformHelper.UploadConsultation(new List<Participateinfo> {new Participateinfo("NX6401052020000007","23192"),new Participateinfo("NX6401052020000009","22896")},
  70. // "NX6401052020000009", "23192", "2024030601","阵痛", DateTime.Now.Millisecond.ToString(),DateTime.Now.AddHours(1), DateTime.Now.AddHours(3)).GetAwaiter().GetResult();
  71. //NationalPlatformHelper.GetConsultation("NX6401052020000007", "22192").GetAwaiter().GetResult();
  72. //NationalPlatformHelper.UploadConsultationSchedule("NX6401052020000007", "22192", Guid.NewGuid().ToString(), DateTime.Now.AddDays(1).AddHours(8), DateTime.Now.AddDays(1).AddHours(10)).GetAwaiter().GetResult();
  73. #endif
  74. }
  75. catch (Exception ex)
  76. {
  77. Close();
  78. throw ex;
  79. }
  80. }
  81. private void SetStarted()
  82. {
  83. _serviceBus.SetStartedServer();
  84. System.Threading.ThreadPool.GetMinThreads(out var minworkThreads, out var minIOThreads);
  85. Logger.WriteLineInfo($"ThreadPool: minworkThreads:{minworkThreads} minIOThreads:{minIOThreads}");
  86. }
  87. private void OnNotifyLicenseExpirationClosedEvent(object sender,bool e)
  88. {
  89. Logger.WriteLineInfo("vCloud Server Closing!");
  90. Close();
  91. }
  92. /// <summary>
  93. /// Close the server.
  94. /// </summary>
  95. public void Close()
  96. {
  97. if (!_serviceBus.LocalHostMode && _serviceBus.Master != null)
  98. {
  99. _serviceBus.Master.UnattachSlave(_serviceBus);
  100. }
  101. foreach (var localService in _localServices)
  102. {
  103. localService?.Dispose();
  104. }
  105. _serviceBus?.Close();
  106. }
  107. private void InitializeAutoClearCache()
  108. {
  109. Task.Run(async () =>
  110. {
  111. await Task.Delay(TimeSpan.FromMinutes(3));
  112. AutoClearCacheManager.Instance.Enable = true;
  113. });
  114. }
  115. /// <summary>
  116. /// Initialize the LogEngine,according to the config, it could be a Trace LogEnhine or MSMQ LogEngine.
  117. /// </summary>
  118. private void InitializeLoggerEngine()
  119. {
  120. UnifyLogEngine engine = new UnifyLogEngine();
  121. engine.EngineSendMessageDelegate = _serviceBus.SendMessage;
  122. Logger.RegisterEngine(engine);
  123. Logger.WriteLineInfo($"{nameof(UnifyLogEngine)} was registered.");
  124. }
  125. /// <summary>
  126. /// Initialize the LogEngine,according to the config. The server may create the ServiceBus or just create the
  127. /// ClientLeafCreator for creating the NetworkServiceBusAdapter.
  128. /// </summary>
  129. private void InitializeServiceBus()
  130. {
  131. var url = Config.GetValue("ServiceBus", "Url", "localhost");
  132. _serviceBus = new vCloudServiceBus(url);
  133. Logger.WriteLineInfo($"Create ServiceBus at {url}.");
  134. var masterUrl = Config.GetValue("ServiceBus", "MasterUrl", string.Empty);
  135. if (!_serviceBus.LocalHostMode)
  136. {
  137. var task = Task.Run(() => {
  138. try
  139. {
  140. if (!string.IsNullOrEmpty(masterUrl))
  141. {
  142. _serviceBus.Master = new MasterServiceBusAdapter(masterUrl);
  143. }
  144. _serviceBus.Start();
  145. }
  146. catch (Exception ex)
  147. {
  148. Logger.WriteLineError($"Attach to master server error {ex}");
  149. Console.WriteLine($"Attach to master server error {ex}");
  150. }
  151. });
  152. task.Wait();
  153. }
  154. }
  155. /// <summary>
  156. /// Initialize the services.
  157. /// </summary>
  158. private void InitializeServices()
  159. {
  160. InitializeLoggerEngine();
  161. foreach (var serviceName in ServiceCreator.ServiceContexts.Keys)
  162. {
  163. var serviceEnabled = Config.GetValue("Service", serviceName, false);
  164. if (serviceEnabled)
  165. {
  166. if (_serviceBus != null)
  167. {
  168. try
  169. {
  170. if (_serviceBus.LocalHostMode && serviceName == ServerRegistryService.ServiceId.Name)
  171. {
  172. continue;
  173. }
  174. //not starat managerment service for slaver
  175. if (!_serviceBus.LocalHostMode && !_serviceBus.IsMaster &&
  176. serviceName == ManagementService.ServiceId.Name)
  177. {
  178. continue;
  179. }
  180. var service = ServiceCreator.CreateService(serviceName, _serviceBus);
  181. _localServices.Add(service);
  182. Logger.WriteLineInfo($"Service:{service.Id} was registered.");
  183. }
  184. catch (Exception ex)
  185. {
  186. Logger.WriteLineError($"Service:{serviceName} error {ex}");
  187. Console.WriteLine($"Service:{serviceName} error {ex}");
  188. }
  189. }
  190. }
  191. }
  192. }
  193. private void InitializeMessagePoolConfig()
  194. {
  195. try
  196. {
  197. var serverMessagePoolConfig = new ServerMessagePoolConfig();
  198. var isCachedvalue = Config.GetValue("MessagePool", "IsCached", false);
  199. serverMessagePoolConfig.SetEnabled(isCachedvalue);
  200. var maximumMessageOfEachTypeValue = Config.GetValue("MessagePool", "MaximumMessageOfEachType", 10);
  201. serverMessagePoolConfig.SetMaximumMessageOfEachType(maximumMessageOfEachTypeValue);
  202. var maximumMessagesOfSpecialTypeList = Config.GetValue("MessagePool", "MaximumMessagesOfSpecialType", new List<string>());
  203. if (maximumMessagesOfSpecialTypeList != null)
  204. {
  205. foreach (var value in maximumMessagesOfSpecialTypeList)
  206. {
  207. var array = value.Split(':');
  208. if (array.Length == 2)
  209. {
  210. var messageName = array[0];
  211. var maximum = Convert.ToInt32(array[1]);
  212. serverMessagePoolConfig.AddCustomMessageCount(messageName, maximum);
  213. }
  214. }
  215. }
  216. MessagePool.Initialize(serverMessagePoolConfig);
  217. }
  218. catch (Exception e)
  219. {
  220. Logger.WriteLineError($"Initialize message pool failed :{e}");
  221. }
  222. }
  223. /// <summary>
  224. /// 启动 工具
  225. /// </summary>
  226. private void StartDBAutoBackup()
  227. {
  228. var _dependencies = Config.GetValue("DependenciesTools", "ToolNames", string.Empty);
  229. if (!string.IsNullOrEmpty(_dependencies))
  230. {
  231. var dependenciesApps = _dependencies.Split(',');
  232. foreach (var item in dependenciesApps)
  233. {
  234. if (!string.IsNullOrEmpty(item))
  235. {
  236. var appPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, item);
  237. if (File.Exists(appPath))
  238. {
  239. StartProcess(appPath);
  240. var arry = item.Split('.');
  241. if (arry.Length > 0)
  242. {
  243. _dependencieNames.Add(arry[0]);
  244. }
  245. else
  246. {
  247. _dependencieNames.Add(item);
  248. }
  249. }
  250. }
  251. }
  252. }
  253. }
  254. /// <summary>
  255. /// 开始执行工具程序
  256. /// </summary>
  257. /// <param name="processName">工具程序名称</param>
  258. private void StartProcess(string namePath)
  259. {
  260. Process process = new Process();
  261. process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
  262. process.StartInfo.FileName = namePath;
  263. process.Start();
  264. }
  265. }
  266. }