DefaultDispatcher.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. using AutoMapper;
  2. using Edge.Core.Configuration;
  3. using Edge.Core.Database.Configuration.Models;
  4. using Edge.Core.Processor.Communicator;
  5. using Edge.Core.Processor.Dispatcher.Attributes;
  6. using Edge.Core.UniversalApi;
  7. using Edge.Core.UniversalApi.CommunicationProvider;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.Logging;
  10. using Microsoft.Extensions.Logging.Abstractions;
  11. using Newtonsoft.Json.Schema;
  12. using Newtonsoft.Json.Schema.Generation;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Reflection;
  18. using System.Runtime.Loader;
  19. using System.Text;
  20. using System.Text.Json;
  21. using System.Text.Json.Serialization;
  22. using System.Text.RegularExpressions;
  23. using System.Threading.Tasks;
  24. namespace Edge.Core.Processor.Dispatcher
  25. {
  26. [UniversalApi(Name = DefaultDispatcher.OnProcessorsLifeCycleChangedEventApiName,
  27. EventDataType = typeof(OnProcessorsLifeCycleChangedEventArg),
  28. Description = "When life cycle of processors are changed, an event will fired with details for each processor.")]
  29. [UniversalApi(Name = GenericAlarm.UniversalApiEventName, EventDataType = typeof(object), Description = "Fire GenericAlarm which mostly used in Alarm UI Bar for attracting users.")]
  30. [MetaPartsDescriptor("DefaultDispatcher", "Processors' life cycle manager.",
  31. new[] { "Managment" },
  32. IsSystemInternalComponent = true)]
  33. public partial class DefaultDispatcher : IAppProcessor
  34. {
  35. public const string OnProcessorsLifeCycleChangedEventApiName = "OnProcessorsLifeCycleChanged";
  36. private List<OnProcessorsLifeCycleChangedEventArg> historyProcessorsLifeCycleChangedEvents
  37. = new List<OnProcessorsLifeCycleChangedEventArg>();
  38. public event EventHandler<OnProcessorsInstantiatedEventArg> OnProcessorInstantiated;
  39. /// <summary>
  40. /// latest instantiated processor result.
  41. /// </summary>
  42. private IEnumerable<ProcessorInstanceOperatingResult> currentProcessorInstantiatedOperatingResults;
  43. //public static EventHandler OnRequestDispatch;
  44. protected IServiceProvider services;
  45. protected static ILogger mainLogger = NullLogger.Instance;
  46. public string MetaConfigName { get; set; } = "ProcessorsDispatcher";
  47. public static string DefaultClientAcceptLanguage = "zh-cn";
  48. static DefaultDispatcher()
  49. {
  50. // replace with your license key, https://www.newtonsoft.com/jsonschema
  51. string licenseKey = "4278-fsXeHk11Z1h23Ki2z21y8tDMv43+eMW7Gcnv6caaGWz6w8Q4xrsg/Ow/moZc6GrkgjCaiq33yzr/meweRwNrPHsfqTc1rgpJu385YKKqMbJ5UKUDV1csm5ZwpMBIc1JJDbQwVZuDqUyOFqLZ31uk+10j9i8uMTPGEzLI729edmx7IklkIjo0Mjc4LCJFeHBpcnlEYXRlIjoiMjAyMS0wNy0wNFQwNjoxMjozMC43Mzc1NTE1WiIsIlR5cGUiOiJKc29uU2NoZW1hQnVzaW5lc3MifQ==";
  52. License.RegisterLicense(licenseKey);
  53. //AppDomain.CurrentDomain.TypeResolve += (s, args) =>
  54. //{
  55. // var type = ObjectInstanceCreator.DefaultSearchLocalAssemblyFileTypeResolver(args.Name);
  56. // return type?.Assembly;
  57. //};
  58. //AppDomain.CurrentDomain.AssemblyResolve += (s, args) =>
  59. //{
  60. // return ObjectInstanceCreator.DefaultSearchLocalAssemblyFileAssemblyResolver(args.Name);
  61. //};
  62. }
  63. public DefaultDispatcher(IServiceProvider services)
  64. {
  65. this.services = services;
  66. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  67. mainLogger = loggerFactory.CreateLogger("Main");
  68. ObjectInstanceCreator.mainLogger = mainLogger;
  69. mainLogger.LogInformation("AppDomain.CurrentDomain.CurrentDomainAssemblies: " +
  70. ObjectInstanceCreator.CurrentDomainAssemblies?.Select(ass => ass.FullName + " " + (!ass.IsDynamic ? ass.Location ?? "" : "")).OrderBy(o => o)
  71. .Aggregate(Environment.NewLine, (acc, n) => acc + n + Environment.NewLine) ?? "");
  72. //route this special event into this processor rather than from different processors to form an unified api entrance.
  73. //this.services.GetRequiredService<UniversalApiHub>().OnUniversalGenericAlarmEventFired += async (s, a) =>
  74. //{
  75. // await this.services.GetRequiredService<UniversalApiHub>().FireEvent(this,
  76. // GenericAlarm.UniversalApiEventName, new
  77. // {
  78. // Title = a.GenericAlarm.Title.LocalizedContent(DefaultClientAcceptLanguage),
  79. // Category = a.GenericAlarm.Category?.LocalizedContent(DefaultClientAcceptLanguage),
  80. // SubCategory = a.GenericAlarm.SubCategory?.LocalizedContent(DefaultClientAcceptLanguage),
  81. // Detail = a.GenericAlarm.Detail?.LocalizedContent(DefaultClientAcceptLanguage),
  82. // a.GenericAlarm.Severity,
  83. // a.PersistId
  84. // });
  85. //};
  86. }
  87. /// <summary>
  88. ///
  89. /// </summary>
  90. /// <param name="reason"></param>
  91. /// <returns></returns>
  92. public virtual async Task<IEnumerable<ProcessorInstanceOperatingResult>> CreateProcessorsAsync(string reason, bool enableSafeBoot = false)
  93. {
  94. var processorLoader = this.services.GetRequiredService<IProcessorLoader>();
  95. var defaultDispatcherProcessorInstanceOperatingResult = new ProcessorInstanceOperatingResult()
  96. {
  97. Succeed = true,
  98. ProcessorInstance = this,
  99. //for this special AppProcessor as it's included in Edge.Core, so both version are the same
  100. HostVersion = Assembly.GetAssembly(this.GetType()).GetName().Version.ToString(),
  101. CoreVersion = Assembly.GetAssembly(this.GetType()).GetName().Version.ToString(),
  102. };
  103. if (enableSafeBoot)
  104. this.currentProcessorInstantiatedOperatingResults = new[] { defaultDispatcherProcessorInstanceOperatingResult };
  105. else
  106. this.currentProcessorInstantiatedOperatingResults =
  107. new[] { defaultDispatcherProcessorInstanceOperatingResult }.Concat(processorLoader.CreateAll()).ToList();
  108. this.OnProcessorInstantiated?.Invoke(this, new OnProcessorsInstantiatedEventArg(this.currentProcessorInstantiatedOperatingResults));
  109. var createEvtArg = new OnProcessorsLifeCycleChangedEventArg(
  110. this.currentProcessorInstantiatedOperatingResults.Select(i => ProcessorLifeCycleOperationResult.From(i)).ToList(),
  111. "ProcessorsInstantiate",
  112. reason);
  113. this.historyProcessorsLifeCycleChangedEvents.Add(createEvtArg);
  114. return this.currentProcessorInstantiatedOperatingResults;
  115. }
  116. public virtual async Task<IEnumerable<ProcessorInstanceOperatingResult>> StartProcessorsAsync(
  117. IEnumerable<IProcessor> processorInstances, string reason)
  118. {
  119. //App will call Init(...) before Start()
  120. var initOrStartResults = new List<ProcessorInstanceOperatingResult>();
  121. mainLogger.LogInformation("==============Start Processors (total: " + processorInstances.Count() + ")==============");
  122. Console.WriteLine();
  123. Console.WriteLine("==============Start Processors (total: " + processorInstances.Count() + ")==============");
  124. var pendingForStartInstances = processorInstances.ToList();
  125. // call App.Init(...), and only succeed ones will call its Start() later.
  126. processorInstances.OfType<IAppProcessor>().ToList().ForEach(app =>
  127. {
  128. try
  129. {
  130. app.Init(processorInstances);
  131. }
  132. catch (Exception eee)
  133. {
  134. //remove it for avoid call Start()
  135. pendingForStartInstances.Remove(app);
  136. initOrStartResults.Add(new ProcessorInstanceOperatingResult()
  137. {
  138. //WhatThisProcessorUsedFor = p.ProcessorDescriptor().DeviceHandlerOrApp.GetType().GetCustomAttributes<MetaPartsDescriptor>()?.FirstOrDefault()?.Description,
  139. ProcessorInstance = app,
  140. Succeed = false,
  141. FailedReason = "Call App.Init(...) exceptioned: " + eee.ToString(),
  142. //Description = $"Ordinary start a processor but failed with an unexpected fatal error",
  143. });
  144. mainLogger.LogError("Initing [" + (app.MetaConfigName ?? "") + "] failed and will skip its Start: " + eee.ToString());
  145. Console.BackgroundColor = ConsoleColor.Red;
  146. Console.ForegroundColor = ConsoleColor.Black;
  147. Console.WriteLine("Initing [" + (app.MetaConfigName ?? "") + "] failed: " + Environment.NewLine + " " + eee.ToString().Substring(0, 70) + "...");
  148. Console.ResetColor();
  149. }
  150. });
  151. for (int i = 0; i < pendingForStartInstances.Count(); i++)
  152. {
  153. var p = pendingForStartInstances.ElementAt(i);
  154. try
  155. {
  156. mainLogger.LogInformation("Starting [" + (p.MetaConfigName ?? "") + "]: ");
  157. Console.WriteLine("Starting [" + (p.MetaConfigName ?? "") + "]: ");
  158. bool r = await p.Start();
  159. if (r)
  160. {
  161. initOrStartResults.Add(new ProcessorInstanceOperatingResult()
  162. {
  163. //WhatThisProcessorUsedFor = p.ProcessorDescriptor().DeviceHandlerOrApp.GetType().GetCustomAttributes<MetaPartsDescriptor>()?.FirstOrDefault()?.Description,
  164. ProcessorInstance = p,
  165. Succeed = true,
  166. //Description = $"Ordinary start a processor and succeed.",
  167. });
  168. mainLogger.LogInformation(" Started");
  169. Console.WriteLine(" Started");
  170. }
  171. else
  172. {
  173. initOrStartResults.Add(new ProcessorInstanceOperatingResult()
  174. {
  175. //WhatThisProcessorUsedFor = p.ProcessorDescriptor().DeviceHandlerOrApp.GetType().GetCustomAttributes<MetaPartsDescriptor>()?.FirstOrDefault()?.Description,
  176. ProcessorInstance = p,
  177. Succeed = false,
  178. //Description = $"Ordinary start a processor but failed with a graceful reason",
  179. });
  180. mainLogger.LogInformation(" Failed for starting");
  181. Console.BackgroundColor = ConsoleColor.Red;
  182. Console.ForegroundColor = ConsoleColor.Black;
  183. Console.WriteLine(" !!!Failed for starting!!!");
  184. Console.ResetColor();
  185. }
  186. }
  187. catch (Exception eee)
  188. {
  189. initOrStartResults.Add(new ProcessorInstanceOperatingResult()
  190. {
  191. //WhatThisProcessorUsedFor = p.ProcessorDescriptor().DeviceHandlerOrApp.GetType().GetCustomAttributes<MetaPartsDescriptor>()?.FirstOrDefault()?.Description,
  192. ProcessorInstance = p,
  193. Succeed = false,
  194. FailedReason = eee.ToString(),
  195. //Description = $"Ordinary start a processor but failed with an unexpected fatal error",
  196. });
  197. mainLogger.LogError(" - Failed for start: [" + p.MetaConfigName + "]" + Environment.NewLine + " " + eee.ToString());
  198. Console.BackgroundColor = ConsoleColor.Red;
  199. Console.ForegroundColor = ConsoleColor.Black;
  200. Console.WriteLine(" - Failed for start: [" + p.MetaConfigName + "]" + Environment.NewLine + " " + eee.ToString().Substring(0, 70) + "...");
  201. Console.ResetColor();
  202. }
  203. }
  204. mainLogger.LogInformation("==============Start Processors End==============\r\n");
  205. Console.WriteLine("==============Start Processors End==============\r\n");
  206. var startEvtArg = new OnProcessorsLifeCycleChangedEventArg(
  207. initOrStartResults.Select(i => ProcessorLifeCycleOperationResult.From(i)).ToList(),
  208. "ProcessorsStart",
  209. reason);
  210. //var universalApiHub = this.services.GetRequiredService<UniversalApiHub>();
  211. //await universalApiHub.FireEvent(this, DefaultDispatcher.OnProcessorsLifeCycleChangedEventApiName, startEvtArg);
  212. this.historyProcessorsLifeCycleChangedEvents.Add(startEvtArg);
  213. return initOrStartResults;
  214. }
  215. /// <summary>
  216. /// Call Stop() on target processors, and correlated life cycle operation results will be recorded.
  217. /// </summary>
  218. /// <param name="processors"></param>
  219. /// <param name="reason"></param>
  220. /// <returns></returns>
  221. public virtual async Task<IEnumerable<ProcessorInstanceOperatingResult>> StopProcessorsAsync(
  222. IEnumerable<IProcessor> processors, string reason)
  223. {
  224. if (processors == null || !processors.Any()) return Enumerable.Empty<ProcessorInstanceOperatingResult>();
  225. var stopResults = new List<ProcessorInstanceOperatingResult>();
  226. foreach (var p in processors)
  227. {
  228. try
  229. {
  230. Console.WriteLine(" stopping " + p.MetaConfigName + "..." + " by reason: " + (reason ?? ""));
  231. mainLogger.LogInformation(" stopping " + p.MetaConfigName + " by reason: " + (reason ?? ""));
  232. bool r = await p.Stop();
  233. if (r)
  234. {
  235. stopResults.Add(new ProcessorInstanceOperatingResult()
  236. {
  237. //WhatThisProcessorUsedFor = p.ProcessorDescriptor().DeviceHandlerOrApp.GetType().GetCustomAttributes<MetaPartsDescriptor>()?.FirstOrDefault()?.Description,
  238. //ProcessorMetaConfigName = p.MetaConfigName,
  239. ProcessorInstance = p,
  240. Succeed = true,
  241. //Description = $"Ordinary stop a processor and succeed.",
  242. });
  243. Console.WriteLine(" Stopped");
  244. mainLogger.LogInformation(" Stopped");
  245. }
  246. else
  247. {
  248. stopResults.Add(new ProcessorInstanceOperatingResult()
  249. {
  250. //WhatThisProcessorUsedFor = p.ProcessorDescriptor().DeviceHandlerOrApp.GetType().GetCustomAttributes<MetaPartsDescriptor>()?.FirstOrDefault()?.Description,
  251. //ProcessorMetaConfigName = p.MetaConfigName,
  252. ProcessorInstance = p,
  253. Succeed = false,
  254. //Description = $"Ordinary stop a processor but failed with a graceful reason",
  255. });
  256. }
  257. }
  258. catch (Exception xxxx)
  259. {
  260. stopResults.Add(new ProcessorInstanceOperatingResult()
  261. {
  262. //WhatThisProcessorUsedFor = p.ProcessorDescriptor().DeviceHandlerOrApp.GetType().GetCustomAttributes<MetaPartsDescriptor>()?.FirstOrDefault()?.Description,
  263. //ProcessorMetaConfigName = p.MetaConfigName,
  264. Succeed = false,
  265. FailedReason = xxxx.ToString(),
  266. //Description = $"Ordinary stop a processor but failed with an unexpected fatal error",
  267. });
  268. Console.BackgroundColor = ConsoleColor.Red;
  269. Console.ForegroundColor = ConsoleColor.Black;
  270. Console.WriteLine(" stopping " + p.MetaConfigName + " failed.");
  271. Console.ResetColor();
  272. mainLogger.LogInformation(" stopping " + p.MetaConfigName + " failed: "
  273. + Environment.NewLine
  274. + xxxx);
  275. }
  276. }
  277. var stopEvtArg = new OnProcessorsLifeCycleChangedEventArg(
  278. stopResults.Select(i => ProcessorLifeCycleOperationResult.From(i)).ToList(),
  279. "ProcessorsStop",
  280. reason);
  281. this.historyProcessorsLifeCycleChangedEvents.Add(stopEvtArg);
  282. var universalApiHub = this.services.GetRequiredService<UniversalApiHub>();
  283. await universalApiHub.FireEvent(this, DefaultDispatcher.OnProcessorsLifeCycleChangedEventApiName,
  284. stopEvtArg);
  285. return stopResults;
  286. }
  287. [UniversalApi(Description = "Get history datas for Processors' LifeCycle Changed Event")]
  288. public Task<List<OnProcessorsLifeCycleChangedEventArg>> GetHistoryProcessorsLifeCycleChangedEvents()
  289. {
  290. return Task.FromResult(this.historyProcessorsLifeCycleChangedEvents);
  291. }
  292. [UniversalApi]
  293. public async Task<ProcessorMetaConfig> UpsertProcessorMetaConfigAsync(ProcessorMetaConfig input)
  294. {
  295. var accessor = this.services.GetService<IProcessorMetaConfigAccessor>();
  296. if (accessor == null) throw new NotSupportedException("Could not find ProcessorMetaConfigAccessor, may current ProcessorLoader does not support the MetaConfig Upsert???");
  297. return await accessor.UpsertMetaConfigAsync(input);
  298. }
  299. [UniversalApi(Description = "Get all ProcessorMetaConfigs with endPointFullTypeStr qualified with input parameter, or leave null or empty to get all")]
  300. public async Task<IEnumerable<ProcessorMetaConfig>> GetProcessorMetaConfigAsync(string sourceEndpointFullTypeStr)
  301. {
  302. var accessor = this.services.GetService<IProcessorMetaConfigAccessor>();
  303. if (accessor == null) throw new NotSupportedException("Could not find ProcessorMetaConfigAccessor, may current ProcessorLoader does not support the MetaConfig Get???");
  304. return await accessor.GetMetaConfigAsync(sourceEndpointFullTypeStr);
  305. }
  306. [UniversalApi(InputParametersExampleJson = "[121]", Description = "Remove a ProcessorMetaConfig and all its MetaPartsConfigs")]
  307. public async Task<bool> RemoveProcessorMetaConfigAsync(int metaConfigId)
  308. {
  309. var accessor = this.services.GetService<IProcessorMetaConfigAccessor>();
  310. if (accessor == null) throw new NotSupportedException("Could not find ProcessorMetaConfigAccessor, may current ProcessorLoader does not support the MetaConfig Remove???");
  311. return await accessor.RemoveMetaConfigAsync(metaConfigId);
  312. }
  313. [UniversalApi(InputParametersExampleJson = "[\"wayne dart pump configuration 1\"]",
  314. Description = "Test by constructing a Processor instance on the air from specified metaConfig, start, test and then stop it, any error will treat as test failed.")]
  315. public async Task<bool> TestProcessorMetaConfigAsync(string configName, string[] parameters)
  316. {
  317. var processorLoader = this.services.GetRequiredService<IProcessorLoader>();
  318. IProcessor p = null;
  319. try
  320. {
  321. p = processorLoader.Create(configName);
  322. if (p == null) throw new InvalidOperationException($"Test failed on constructing processor.");//: {p.MetaConfigName}");
  323. var startResult = false;
  324. try
  325. {
  326. startResult = await p.Start();
  327. if (!startResult)
  328. throw new InvalidOperationException($"Test failed on starting processor.");
  329. await p.Test(parameters);
  330. }
  331. catch (Exception eee)
  332. {
  333. throw;// new InvalidOperationException($"Test failed on pre-starting processor with error: {eee}");
  334. }
  335. }
  336. finally
  337. {
  338. if (p != null)
  339. {
  340. var stopResult = false;
  341. try
  342. {
  343. stopResult = await p.Stop();
  344. }
  345. catch (Exception eee)
  346. {
  347. throw;// new InvalidOperationException($"Test failed on pre-stop processor with error: {eee}");
  348. }
  349. if (!stopResult)
  350. throw new InvalidOperationException($"Test failed on stopping processor.");
  351. }
  352. }
  353. return true;
  354. }
  355. /// <summary>
  356. ///
  357. /// </summary>
  358. /// <param name="processorMetaPartsConfigId"></param>
  359. /// <returns>the original ParametersJsonArrayStr if no resolve method defined in target meta part type, or updated value by call the resolve method</returns>
  360. [UniversalApi]
  361. public async Task<string> ResolveProcessorMetaPartsConfigCompatibilityAsync(int processorMetaPartsConfigId)
  362. {
  363. var accessor = this.services.GetService<IProcessorMetaConfigAccessor>();
  364. if (accessor == null) throw new NotSupportedException("Could not find ProcessorMetaConfigAccessor, may current ProcessorLoader does not support the MetaConfig Get???");
  365. var allMetaConfigs = await accessor.GetMetaConfigAsync();
  366. var targetMetaPartsInfo = allMetaConfigs.SelectMany(mc => mc.Parts,
  367. (metaConfig, metaPartsConfig) => new { metaConfig, metaPartsConfig })
  368. .FirstOrDefault(p => p.metaPartsConfig.Id == processorMetaPartsConfigId);
  369. if (targetMetaPartsInfo == null) throw new ArgumentException("Could not find processorMetaPartsConfig with id: " + processorMetaPartsConfigId);
  370. if (targetMetaPartsInfo.metaPartsConfig.TryCallMetaPartsConfigCompatibilityMethodAndUpdate())
  371. {
  372. //targetMetaPartsInfo.metaConfig.Parts.First(p => p.Id == targetMetaPartsInfo.metaPartsConfig.Id)
  373. // .ParametersJsonArrayStr = reformatParamsStr;
  374. //await accessor.UpsertMetaConfigAsync(targetMetaPartsInfo.metaConfig);
  375. }
  376. return targetMetaPartsInfo.metaPartsConfig.ParametersJsonArrayStr;
  377. }
  378. [UniversalApi(Description = "Stop all exist non-system processors, and re-instantiate, re-start them again")]
  379. public async Task<IEnumerable<ProcessorLifeCycleOperationResult>> ReloadProcessorsAsync(string reason = "")
  380. {
  381. try
  382. {
  383. mainLogger.LogInformation($"Stop Non-System Processors is on requesting by reason: {reason}");
  384. Console.BackgroundColor = ConsoleColor.Yellow;
  385. Console.ForegroundColor = ConsoleColor.Black;
  386. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + $"=====>Stop All Processors is on requesting by reason: {reason}");
  387. Console.ResetColor();
  388. var stopResults = await this.StopProcessorsAsync(
  389. this.currentProcessorInstantiatedOperatingResults.Where(r => r.ProcessorInstance != null)
  390. .Select(r => r.ProcessorInstance).Except(new[] { this }),
  391. reason);
  392. mainLogger.LogInformation(" Stop Non-System Processors done successfully");
  393. Console.BackgroundColor = ConsoleColor.Green;
  394. Console.ForegroundColor = ConsoleColor.Black;
  395. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "<=====Stop All Processors done successfully");
  396. Console.ResetColor();
  397. //return stopResults;
  398. }
  399. catch (Exception exx)
  400. {
  401. mainLogger.LogError("******Stop Non-System Processors got internal error!\r\n" + exx.ToString());
  402. Console.BackgroundColor = ConsoleColor.Red;
  403. Console.ForegroundColor = ConsoleColor.Black;
  404. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "******Stop All Processors got internal error: " + exx.ToString().Substring(0, 70) + "...");
  405. Console.ResetColor();
  406. throw;
  407. }
  408. try
  409. {
  410. mainLogger.LogInformation($"Create All Processors is on requesting by reason: {reason}");
  411. Console.BackgroundColor = ConsoleColor.Yellow;
  412. Console.ForegroundColor = ConsoleColor.Black;
  413. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + $"=====>Create All Processors is on requesting by reason: {reason}");
  414. Console.ResetColor();
  415. var createResults = await this.CreateProcessorsAsync(reason);
  416. mainLogger.LogInformation(" Create All Processors done successfully");
  417. Console.BackgroundColor = ConsoleColor.Green;
  418. Console.ForegroundColor = ConsoleColor.Black;
  419. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "<=====Create All Processors done successfully");
  420. Console.ResetColor();
  421. //return createResults;
  422. }
  423. catch (Exception exx)
  424. {
  425. mainLogger.LogError("******Create All Processors got internal error!\r\n" + exx.ToString());
  426. Console.BackgroundColor = ConsoleColor.Red;
  427. Console.ForegroundColor = ConsoleColor.Black;
  428. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "******Create All Processors got internal error: " + exx.ToString().Substring(0, 70) + "...");
  429. Console.ResetColor();
  430. throw;
  431. }
  432. try
  433. {
  434. mainLogger.LogInformation($"Start All Processors is on requesting by reason: {reason}");
  435. Console.BackgroundColor = ConsoleColor.Yellow;
  436. Console.ForegroundColor = ConsoleColor.Black;
  437. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + $"=====>Start All Processors is on requesting by reason: {reason}");
  438. Console.ResetColor();
  439. var startResults = await this.StartProcessorsAsync(
  440. this.currentProcessorInstantiatedOperatingResults.Where(r => r.Succeed).Select(r => r.ProcessorInstance),
  441. reason);
  442. mainLogger.LogInformation(" Start All Processors done successfully");
  443. Console.BackgroundColor = ConsoleColor.Green;
  444. Console.ForegroundColor = ConsoleColor.Black;
  445. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "<=====Start All Processors done successfully");
  446. Console.ResetColor();
  447. return startResults.Select(r => ProcessorLifeCycleOperationResult.From(r));
  448. }
  449. catch (Exception exx)
  450. {
  451. mainLogger.LogError("******Start All Processors got internal error!\r\n" + exx.ToString());
  452. Console.BackgroundColor = ConsoleColor.Red;
  453. Console.ForegroundColor = ConsoleColor.Black;
  454. Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "******Start All Processors got internal error: " + exx.ToString().Substring(0, 70) + "...");
  455. Console.ResetColor();
  456. throw;
  457. }
  458. }
  459. /// <summary>
  460. ///
  461. /// </summary>
  462. /// <param name="apiType">localmqtt, remotemqtt, webapi</param>
  463. /// <param name="tags"></param>
  464. /// <returns></returns>
  465. [UniversalApi(InputParametersExampleJson = "[\"localMqtt\",[\"Pump\",\"ATG\"]]")]
  466. public async Task<IEnumerable<UniversalApiInfoDoc>> ShowMeApi(string apiType, string[] tags)
  467. {
  468. var communicationProvider =
  469. this.services.GetService<UniversalApiHub>()?.CommunicationProviders?.Where(p => p.GetType().Name.Contains(apiType, StringComparison.OrdinalIgnoreCase))?.FirstOrDefault();
  470. if (communicationProvider == null)
  471. return Enumerable.Empty<UniversalApiInfoDoc>();
  472. return communicationProvider.GetApiDocuments().FilterByTags(tags);
  473. }
  474. public void Init(IEnumerable<IProcessor> processors)
  475. {
  476. }
  477. public async Task<bool> Start()
  478. {
  479. try
  480. {
  481. Console.WriteLine(" Setup Universal Api communicators...");
  482. await services.GetRequiredService<UniversalApiHub>()
  483. .InitAsync(this.currentProcessorInstantiatedOperatingResults.Where(r => r.Succeed).Select(r => r.ProcessorInstance));
  484. Console.WriteLine(" Setup finished.");
  485. }
  486. catch (Exception exxx)
  487. {
  488. mainLogger.LogInformation(" Setup UniversalApiHub Failed: " + exxx);
  489. Console.BackgroundColor = ConsoleColor.Red;
  490. Console.ForegroundColor = ConsoleColor.Black;
  491. Console.WriteLine(" Setup UniversalApiHub Failed: " + exxx);
  492. Console.ResetColor();
  493. throw;
  494. }
  495. return true;
  496. }
  497. public Task<bool> Stop()
  498. {
  499. mainLogger.LogError("Stopping DefaultDispatcher processor...");
  500. Console.BackgroundColor = ConsoleColor.Red;
  501. Console.ForegroundColor = ConsoleColor.Black;
  502. Console.WriteLine(" FATAL, Stopping DefaultDispatcher will lose major functions...");
  503. Console.ResetColor();
  504. this.services.GetRequiredService<UniversalApiHub>().CommunicationProviders.ToList().ForEach(c => c.Dispose());
  505. return Task.FromResult(true);
  506. }
  507. }
  508. }