AppManagerComponent.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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().Coroutine();
  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. Process process = ProcessHelper.Run(exe, arguments);
  50. this.processes.Add(startConfig.AppId, process);
  51. }
  52. catch (Exception e)
  53. {
  54. Log.Error(e);
  55. }
  56. }
  57. /// <summary>
  58. /// 监控启动的进程,如果进程挂掉了,重新拉起
  59. /// </summary>
  60. private async ETVoid WatchProcessAsync()
  61. {
  62. long instanceId = this.InstanceId;
  63. while (true)
  64. {
  65. await Game.Scene.GetComponent<TimerComponent>().WaitAsync(5000);
  66. if (this.InstanceId != instanceId)
  67. {
  68. return;
  69. }
  70. foreach (int appId in this.processes.Keys.ToArray())
  71. {
  72. Process process = this.processes[appId];
  73. if (!process.HasExited)
  74. {
  75. continue;
  76. }
  77. this.processes.Remove(appId);
  78. process.Dispose();
  79. this.StartProcess(appId);
  80. }
  81. }
  82. }
  83. }
  84. }