AppManagerComponent.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. namespace ETModel
  7. {
  8. [ObjectSystem]
  9. public class AppManagerComponentAwakeSystem : AwakeSystem<AppManagerComponent>
  10. {
  11. public override void Awake(AppManagerComponent self)
  12. {
  13. self.Awake();
  14. }
  15. }
  16. public class AppManagerComponent: Component
  17. {
  18. private readonly Dictionary<int, Process> processes = new Dictionary<int, Process>();
  19. public void Awake()
  20. {
  21. string[] ips = NetHelper.GetAddressIPs();
  22. StartConfig[] startConfigs = StartConfigComponent.Instance.GetAll();
  23. foreach (StartConfig startConfig in startConfigs)
  24. {
  25. Game.Scene.GetComponent<TimerComponent>().WaitAsync(100);
  26. if (!ips.Contains(startConfig.ServerIP) && startConfig.ServerIP != "*")
  27. {
  28. continue;
  29. }
  30. if (startConfig.AppType.Is(AppType.Manager))
  31. {
  32. continue;
  33. }
  34. StartProcess(startConfig.AppId);
  35. }
  36. this.WatchProcessAsync();
  37. }
  38. private void StartProcess(int appId)
  39. {
  40. OptionComponent optionComponent = Game.Scene.GetComponent<OptionComponent>();
  41. StartConfigComponent startConfigComponent = StartConfigComponent.Instance;
  42. string configFile = optionComponent.Options.Config;
  43. StartConfig startConfig = startConfigComponent.Get(appId);
  44. const string exe = "dotnet";
  45. string arguments = $"App.dll --appId={startConfig.AppId} --appType={startConfig.AppType} --config={configFile}";
  46. Log.Info($"{exe} {arguments}");
  47. try
  48. {
  49. bool useShellExecute = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
  50. ProcessStartInfo info = new ProcessStartInfo { FileName = exe, Arguments = arguments, CreateNoWindow = true, UseShellExecute = useShellExecute };
  51. Process process = Process.Start(info);
  52. this.processes.Add(startConfig.AppId, process);
  53. }
  54. catch (Exception e)
  55. {
  56. Log.Error(e);
  57. }
  58. }
  59. /// <summary>
  60. /// 监控启动的进程,如果进程挂掉了,重新拉起
  61. /// </summary>
  62. private async void WatchProcessAsync()
  63. {
  64. long instanceId = this.InstanceId;
  65. while (true)
  66. {
  67. await Game.Scene.GetComponent<TimerComponent>().WaitAsync(5000);
  68. if (this.InstanceId != instanceId)
  69. {
  70. return;
  71. }
  72. foreach (int appId in this.processes.Keys.ToArray())
  73. {
  74. Process process = this.processes[appId];
  75. if (!process.HasExited)
  76. {
  77. continue;
  78. }
  79. this.processes.Remove(appId);
  80. process.Dispose();
  81. this.StartProcess(appId);
  82. }
  83. }
  84. }
  85. }
  86. }