94 lines
2.6 KiB
C#
Raw Normal View History

using System.Diagnostics;
using CodexClient;
using Logging;
namespace CodexPlugin
{
public class BinaryProcessControl : IProcessControl
{
2025-01-31 14:24:55 +01:00
private readonly LogFile logFile;
private readonly Process process;
private readonly CodexProcessConfig config;
2025-02-03 10:47:37 +01:00
private List<string> logBuffer = new List<string>();
2025-01-31 14:24:55 +01:00
private readonly object bufferLock = new object();
private readonly List<Task> streamTasks = new List<Task>();
private bool running;
2025-01-31 14:24:55 +01:00
public BinaryProcessControl(ILog log, Process process, CodexProcessConfig config)
{
2025-01-31 14:24:55 +01:00
logFile = log.CreateSubfile(config.Name);
running = true;
this.process = process;
this.config = config;
streamTasks.Add(Task.Run(() => ReadProcessStream(process.StandardOutput)));
streamTasks.Add(Task.Run(() => ReadProcessStream(process.StandardError)));
2025-01-31 14:24:55 +01:00
streamTasks.Add(Task.Run(() => WriteLog()));
}
private void ReadProcessStream(StreamReader reader)
{
while (running)
{
var line = reader.ReadLine();
2025-01-31 14:24:55 +01:00
if (!string.IsNullOrEmpty(line))
{
lock (bufferLock)
{
logBuffer.Add(line);
}
}
}
}
private void WriteLog()
{
while (running || logBuffer.Count > 0)
{
if (logBuffer.Count > 0)
{
2025-02-03 10:47:37 +01:00
List<string> lines = null!;
2025-01-31 14:24:55 +01:00
lock (bufferLock)
{
2025-02-03 10:47:37 +01:00
lines = logBuffer;
logBuffer = new List<string>();
2025-01-31 14:24:55 +01:00
}
2025-02-03 10:47:37 +01:00
logFile.WriteRawMany(lines);
2025-01-31 14:24:55 +01:00
}
else Thread.Sleep(100);
}
}
public void DeleteDataDirFolder()
{
if (!Directory.Exists(config.DataDir)) throw new Exception("datadir not found");
Directory.Delete(config.DataDir, true);
}
public IDownloadedLog DownloadLog(LogFile file)
{
2025-01-31 14:24:55 +01:00
return new DownloadedLog(logFile, config.Name);
}
public bool HasCrashed()
{
2025-01-29 14:44:19 +01:00
return process.HasExited;
}
public void Stop(bool waitTillStopped)
{
running = false;
process.Kill();
if (waitTillStopped)
{
2025-01-28 14:58:37 +01:00
process.WaitForExit();
foreach (var t in streamTasks) t.Wait();
}
DeleteDataDirFolder();
}
}
}