Guard.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. using ClashDotNetFramework.Models.Enums;
  2. using ClashDotNetFramework.Utils;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Timers;
  12. namespace ClashDotNetFramework.Controllers
  13. {
  14. public abstract class Guard
  15. {
  16. /// <summary>
  17. /// 保存Buffer计时器
  18. /// </summary>
  19. private static readonly Timer SaveBufferTimer = new Timer(300) { AutoReset = true };
  20. /// <summary>
  21. /// 日志Buffer
  22. /// </summary>
  23. private readonly StringBuilder _logBuffer = new StringBuilder();
  24. /// <summary>
  25. /// 日志文件(重定向输出文件)
  26. /// </summary>
  27. private string _logPath;
  28. /// <summary>
  29. /// 成功启动关键词
  30. /// </summary>
  31. protected virtual IEnumerable<string> StartedKeywords { get; } = null;
  32. /// <summary>
  33. /// 启动失败关键词
  34. /// </summary>
  35. protected virtual IEnumerable<string> StoppedKeywords { get; } = null;
  36. /// <summary>
  37. /// 主程序名称
  38. /// </summary>
  39. public virtual string Name { get; }
  40. /// <summary>
  41. /// 主程序文件名
  42. /// </summary>
  43. public virtual string MainFile { get; protected set; }
  44. /// <summary>
  45. /// 实例状态
  46. /// </summary>
  47. protected State State { get; set; } = State.Waiting;
  48. /// <summary>
  49. /// 重定向输出
  50. /// </summary>
  51. protected bool RedirectStd { get; set; } = false;
  52. /// <summary>
  53. /// 程序输出的编码
  54. /// </summary>
  55. protected Encoding InstanceOutputEncoding { get; set; } = Encoding.GetEncoding("utf-8");
  56. /// <summary>
  57. /// 进程实例
  58. /// </summary>
  59. public Process Instance { get; private set; }
  60. /// <summary>
  61. /// 停止进程
  62. /// </summary>
  63. public abstract void Stop();
  64. /// <summary>
  65. /// 初始化实例
  66. /// </summary>
  67. /// <param name="argument">进程参数</param>
  68. protected virtual void InitInstance(string argument)
  69. {
  70. Instance = new Process
  71. {
  72. StartInfo =
  73. {
  74. FileName = Path.GetFullPath($"bin\\{MainFile}"),
  75. WorkingDirectory = $"{Global.ClashDotNetFrameworkDir}\\bin",
  76. Arguments = argument,
  77. CreateNoWindow = true,
  78. UseShellExecute = !RedirectStd,
  79. RedirectStandardOutput = RedirectStd,
  80. StandardOutputEncoding = RedirectStd ? InstanceOutputEncoding : null,
  81. RedirectStandardError = RedirectStd,
  82. StandardErrorEncoding = RedirectStd ? InstanceOutputEncoding : null,
  83. WindowStyle = ProcessWindowStyle.Hidden
  84. }
  85. };
  86. }
  87. /// <summary>
  88. /// 停止实例
  89. /// </summary>
  90. protected void StopInstance()
  91. {
  92. try
  93. {
  94. if (Instance == null || Instance.HasExited)
  95. return;
  96. Instance.Kill();
  97. Instance.WaitForExit();
  98. }
  99. catch (Win32Exception e)
  100. {
  101. Logging.Error($"停止 {MainFile} 错误:\n" + e);
  102. }
  103. catch
  104. {
  105. }
  106. }
  107. /// <summary>
  108. /// 启动实例
  109. /// </summary>
  110. /// <param name="argument">进程参数</param>
  111. /// <param name="priority">进程优先级</param>
  112. protected void StartInstanceAuto(string argument, ProcessPriorityClass priority = ProcessPriorityClass.Normal)
  113. {
  114. InitInstance(argument);
  115. Instance.EnableRaisingEvents = true;
  116. if (RedirectStd)
  117. {
  118. // 清理日志
  119. _logPath = Path.Combine(Utils.Utils.GetClashLogsDir(), $"{Name}.log");
  120. if (File.Exists(_logPath))
  121. File.Delete(_logPath);
  122. Instance.OutputDataReceived += OnOutputDataReceived;
  123. Instance.ErrorDataReceived += OnOutputDataReceived;
  124. }
  125. Instance.Exited += OnExited;
  126. Instance.Start();
  127. if (priority != ProcessPriorityClass.Normal)
  128. {
  129. Instance.PriorityClass = priority;
  130. }
  131. if (!RedirectStd)
  132. return;
  133. Instance.BeginOutputReadLine();
  134. Instance.BeginErrorReadLine();
  135. SaveBufferTimer.Elapsed += SaveBufferTimerEvent;
  136. SaveBufferTimer.Enabled = true;
  137. if (!(StartedKeywords?.Any() ?? false))
  138. {
  139. State = State.Started;
  140. return;
  141. }
  142. }
  143. /// <summary>
  144. /// 退出时执行的操作
  145. /// </summary>
  146. /// <param name="sender"></param>
  147. /// <param name="e"></param>
  148. private void OnExited(object sender, EventArgs e)
  149. {
  150. if (RedirectStd)
  151. SaveBufferTimer.Enabled = false;
  152. SaveBufferTimerEvent(null, null);
  153. State = State.Stopped;
  154. }
  155. /// <summary>
  156. /// 写入日志文件缓冲
  157. /// </summary>
  158. /// <param name="info"></param>
  159. /// <returns>转码后的字符串</returns>
  160. private void Write(string info)
  161. {
  162. _logBuffer.Append(info + Global.EOF);
  163. }
  164. /// <summary>
  165. /// 接收输出数据
  166. /// </summary>
  167. /// <param name="sender">发送者</param>
  168. /// <param name="e">数据</param>
  169. protected void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
  170. {
  171. // 程序结束, 接收到 null
  172. if (e.Data == null)
  173. return;
  174. Write(e.Data);
  175. // 检查启动
  176. if (State == State.Starting)
  177. {
  178. if (StartedKeywords.Any(s => e.Data.Contains(s)))
  179. State = State.Started;
  180. else if (StoppedKeywords.Any(s => e.Data.Contains(s)))
  181. State = State.Stopped;
  182. }
  183. }
  184. /// <summary>
  185. /// 计时器存储日志
  186. /// </summary>
  187. /// <param name="sender">发送者</param>
  188. /// <param name="e">数据</param>
  189. private void SaveBufferTimerEvent(object sender, EventArgs e)
  190. {
  191. try
  192. {
  193. if (_logPath != null && _logBuffer != null)
  194. {
  195. File.AppendAllText(_logPath, _logBuffer.ToString());
  196. _logBuffer.Clear();
  197. }
  198. }
  199. catch (Exception exception)
  200. {
  201. Logging.Warning($"写入 {Name} 日志错误:\n" + exception.Message);
  202. }
  203. }
  204. }
  205. }