ServiceHost.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. using LocalDB.DBModel;
  2. using log4net;
  3. using SCADA.CommonLib;
  4. using SCADA.CommonLib.Data.DIL;
  5. using SCADA.CommonLib.Helper;
  6. using SCADA.CommonLib.Service;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Threading.Tasks;
  14. namespace SCADA_DAQ
  15. {
  16. /// <summary>
  17. ///
  18. /// </summary>
  19. public class ServiceHost : IServiceHost
  20. {
  21. /// <summary>
  22. ///
  23. /// </summary>
  24. public IApp AppRuntime { get; set; }
  25. /// <summary>
  26. ///
  27. /// </summary>
  28. readonly ILog log = SCADA.CommonLib.LoggerHelper.Logger.CreateLogger(typeof(ServiceHost));
  29. /// <summary> 已经加载的服务器集合
  30. /// </summary>
  31. public ConcurrentDictionary<string, IService> ServiceCollection { get; private set; } = new ConcurrentDictionary<string, IService>();
  32. /// <summary> 可选服务类型
  33. /// </summary>
  34. public Dictionary<string, Type> ServiceTypes { get; private set; } = new Dictionary<string, Type>();
  35. /// <summary>
  36. ///
  37. /// </summary>
  38. /// <typeparam name="T"></typeparam>
  39. /// <param name="serviceName"></param>
  40. /// <returns></returns>
  41. public T GetService<T>(string serviceName) where T : IService
  42. {
  43. if (ServiceCollection.ContainsKey(serviceName))
  44. {
  45. return (T)ServiceCollection[serviceName];
  46. }
  47. return default;
  48. }
  49. /// <summary>
  50. ///
  51. /// </summary>
  52. /// <typeparam name="T"></typeparam>
  53. /// <returns></returns>
  54. public T GetService<T>() where T : IService
  55. {
  56. return ServiceCollection.Values.OfType<T>().FirstOrDefault();
  57. }
  58. bool isDisposed = false;
  59. private ServiceHost()
  60. {
  61. }
  62. private static ServiceHost _instance;
  63. /// <summary>
  64. ///
  65. /// </summary>
  66. public static ServiceHost Instance { get => _instance ?? (_instance = new ServiceHost()); private set { _instance = value; } }
  67. private ITable serviceTable { get; set; }
  68. /// <summary>
  69. ///
  70. /// </summary>
  71. /// <param name="app"></param>
  72. /// <returns></returns>
  73. public bool Start(IApp app)
  74. {
  75. AppRuntime = app;
  76. return Start();
  77. }
  78. /// <summary>
  79. ///
  80. /// </summary>
  81. /// <returns></returns>
  82. public bool Start()
  83. {
  84. try
  85. {
  86. RpcService.GetInstance().Regiseter(this);
  87. var serviceTasks = new List<Task>() { };
  88. serviceTable = AppRuntime.RuntimeInfo.LocalAppDB?.GetValueByPath("Sys_Service", true) as ITable;
  89. var services = DataTableHelper.DtToList<Sys_Service>(serviceTable.GetData())?.OrderBy(t => t.StartSquence_Int);
  90. ServiceTypes = GetPluginTypes<IService>().ToDictionary(t => t.FullName, t => t);
  91. if (services == null) return false;
  92. foreach (var item in services)
  93. {
  94. if (item.IsEnable_Bit)
  95. {
  96. var exMsg = "";
  97. var serviceState = "";
  98. var startTime = DateTime.Now;
  99. if (ServiceTypes.ContainsKey(item.ServiceType_Str))
  100. {
  101. var task = Task.Factory.StartNew(() =>
  102. {
  103. System.Diagnostics.Stopwatch st = null;
  104. try
  105. {
  106. System.Threading.Thread.Sleep(item.StartDelay_Int);
  107. log.Debug($"服务ID:{item.ID} ,类型:{item.ServiceType_Str} 开始启动");
  108. st = new System.Diagnostics.Stopwatch();
  109. st.Start();
  110. var type = ServiceTypes[item.ServiceType_Str];
  111. var constructorInfoArray = type.GetConstructors(BindingFlags.Instance
  112. | BindingFlags.NonPublic
  113. | BindingFlags.Public);
  114. ConstructorInfo noParameterConstructorInfo = null;
  115. foreach (ConstructorInfo constructorInfo in constructorInfoArray)
  116. {
  117. ParameterInfo[] parameterInfoArray = constructorInfo.GetParameters();
  118. if (0 == parameterInfoArray.Length)
  119. {
  120. noParameterConstructorInfo = constructorInfo;
  121. break;
  122. }
  123. }
  124. if (null == noParameterConstructorInfo)
  125. {
  126. throw new NotSupportedException($"Service {item.ServiceType_Str} 没有默认构造函数");
  127. }
  128. var service = (IService)noParameterConstructorInfo.Invoke(null);
  129. if (service.ConfigType != null)
  130. {
  131. service.ServiceConfig = (ObservableObject)JsonHelper.JsonDeserialize(item.ServiceConfig_Str, service.ConfigType) ??
  132. (ObservableObject)Activator.CreateInstance(service.ConfigType);
  133. }
  134. service.AppRuntime = AppRuntime;
  135. service.ServiceId = item.ID.ToString();
  136. service.ServiceName = item.ServiceName_Str;
  137. service.Start();
  138. startTime = DateTime.Now;
  139. serviceState = "启动成功";
  140. ServiceCollection.TryAdd(service.ServiceName, service);
  141. st.Stop();
  142. log.Debug($"服务ID:{item.ID},名称:{item.ServiceName_Str},类型:{item.ServiceType_Str} 启动成功,耗时:{st.Elapsed}");
  143. }
  144. catch (Exception ex)
  145. {
  146. log.Warn($"服务ID:{item.ID},名称:{item.ServiceName_Str},类型:{item.ServiceType_Str} 启动失败:{ex.Message}");
  147. startTime = DateTime.Now;
  148. log.Error(ex);
  149. exMsg = ex.ToString();
  150. }
  151. finally
  152. {
  153. st?.Stop();
  154. }
  155. });
  156. serviceTasks.Add(task);
  157. task.Wait();
  158. }
  159. else
  160. {
  161. exMsg = $"没有找到 {item.ServiceName_Str}:{item.ServiceType_Str}";
  162. log.Warn(exMsg);
  163. }
  164. if (!string.IsNullOrEmpty(exMsg))
  165. {
  166. serviceState = "启动失败";
  167. }
  168. item.ServiceState_Str = serviceState;
  169. item.StartTime_Dt = startTime;
  170. item.ServiceMessage_Str = exMsg;
  171. }
  172. }
  173. Task.WaitAll(serviceTasks.ToArray());
  174. (serviceTable as BaseTable).Update(
  175. services, t => new { t.ID },
  176. t => new { t.ServiceState_Str, t.StartTime_Dt, t.ServiceMessage_Str });
  177. return true;
  178. }
  179. catch (Exception ex)
  180. {
  181. log.Error(ex);
  182. }
  183. return false;
  184. }
  185. /// <summary>
  186. /// 获取远程桌面的开启状态
  187. /// </summary>
  188. /// <returns></returns>
  189. private bool? GetTSState()
  190. {
  191. try
  192. {
  193. #if WINDOWS || NETFRAMEWORK
  194. Microsoft.Win32.RegistryKey registryRoot = Microsoft.Win32.Registry.LocalMachine;
  195. string[] path = new string[] { "SYSTEM", "CurrentControlSet", "Control", "Terminal Server", "" };
  196. foreach (string p in path)
  197. {
  198. if (registryRoot != null)
  199. registryRoot = registryRoot.OpenSubKey(p);
  200. }
  201. if (registryRoot != null)
  202. {
  203. return (int)registryRoot.GetValue("fDenyTSConnections") == 0;
  204. }
  205. #endif
  206. }
  207. catch (Exception)
  208. {
  209. }
  210. return null;
  211. }
  212. /// <summary>
  213. ///
  214. /// </summary>
  215. /// <returns></returns>
  216. public bool Stop()
  217. {
  218. if (isDisposed == false)
  219. {
  220. isDisposed = true;
  221. DisposeResource();
  222. }
  223. return true;
  224. }
  225. /// <summary>
  226. ///
  227. /// </summary>
  228. /// <returns></returns>
  229. public bool Paused()
  230. {
  231. //foreach (var item in MachineManage.GetInstance().GetAllMachine())
  232. //{
  233. // item.BaseProtocol?.Pause();
  234. //}
  235. //foreach (var item in Env.Instruments)
  236. //{
  237. // item.Value.Dispose();
  238. //}
  239. return true;
  240. }
  241. /// <summary>
  242. ///
  243. /// </summary>
  244. /// <returns></returns>
  245. public bool Resume()
  246. {
  247. //foreach (var item in MachineManage.GetInstance().GetAllMachine())
  248. //{
  249. // item.BaseProtocol?.Resume();
  250. //}
  251. return true;
  252. }
  253. /// <summary>
  254. ///
  255. /// </summary>
  256. /// <returns></returns>
  257. public bool Restart()
  258. {
  259. DisposeResource();
  260. System.Threading.Thread.Sleep(1 * 1000);
  261. Start();
  262. return true;
  263. }
  264. private bool DisposeResource()
  265. {
  266. isDisposed = true;
  267. var services = ServiceCollection.Values.ToList();
  268. for (int i = services.Count - 1; i >= 0; i--)
  269. {
  270. var item = services[i];
  271. try
  272. {
  273. log.Debug($"服务ID:{item.ServiceId},名称:{item.ServiceName} is Stopping");
  274. item.Stop();
  275. }
  276. catch (Exception ex)
  277. {
  278. log.Error(ex);
  279. }
  280. }
  281. ServiceCollection.Clear();
  282. return true;
  283. }
  284. /// <summary>
  285. ///
  286. /// </summary>
  287. /// <typeparam name="T"></typeparam>
  288. /// <returns></returns>
  289. public List<Type> GetPluginTypes<T>()
  290. {
  291. return GetPluginTypes<T>(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase
  292. .Replace("file:///", "")));
  293. }
  294. /// <summary>
  295. ///
  296. /// </summary>
  297. /// <typeparam name="T"></typeparam>
  298. /// <returns></returns>
  299. public List<Type> GetPluginTypes<T>(string basePath)
  300. {
  301. var typeList = new List<Type>();
  302. var assemblys = new List<Assembly>();
  303. if (Assembly.GetEntryAssembly() != null)
  304. {
  305. assemblys.Add(Assembly.GetEntryAssembly());
  306. }
  307. assemblys.Add(Assembly.GetEntryAssembly());
  308. var currentPath = string.IsNullOrEmpty(basePath) ? AppDomain.CurrentDomain.BaseDirectory : basePath;
  309. var files = new DirectoryInfo(currentPath).GetFiles(@"SCADA_DAQ.Plugin.*.dll");
  310. var pluginFiles = Directory.CreateDirectory($"{currentPath}\\plugin")
  311. .GetFiles(@"SCADA_DAQ.Plugin.*.dll");
  312. return ReflectionHelper.GetTypes<T>(files.Concat(pluginFiles).ToLookup(t => t.Name).Select(t => t.FirstOrDefault().FullName));
  313. }
  314. #region Web接口
  315. private List<Sys_Service> QueryServiceInfo()
  316. {
  317. return serviceTable.GetData().DtToList<Sys_Service>();
  318. }
  319. private bool ServiceIsRuning()
  320. {
  321. return true;
  322. }
  323. #endregion
  324. }
  325. }