using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading;
namespace ivf_tl_Operate.Helpers
{
///
/// operate 侧:确保 control 独立进程在运行。
/// 探 /ping → 不在则 Process.Start 拉起 control.exe(命令行传账号)→ 轮询就绪。
/// operate 是管理员、control 也是 requireAdministrator,拉起不再弹 UAC。
///
public static class ControlProcessLauncher
{
private static readonly HttpClient _http = new HttpClient { Timeout = TimeSpan.FromSeconds(2) };
public static int Port =>
int.TryParse(ConfigurationManager.AppSettings["controlPort"], out var p) ? p : 38080;
/// 探活:control 的 /ping 是否可达。
public static bool IsControlAlive()
{
try
{
var resp = _http.GetAsync($"http://127.0.0.1:{Port}/ping").GetAwaiter().GetResult();
return resp.IsSuccessStatusCode;
}
catch { return false; }
}
///
/// 确保 control 在跑:已在→直接返回 true;不在→拉起并轮询就绪(最多 waitSeconds)。
///
public static bool EnsureRunning(string account, string password, string cacheDisk,
Action log, int waitSeconds = 60)
{
log = log ?? (_ => { });
if (IsControlAlive()) { log("control 已在运行,直接连接"); return true; }
string exe = ResolveExePath();
if (!File.Exists(exe)) { log("找不到 control.exe:" + exe); return false; }
var psi = new ProcessStartInfo
{
FileName = exe,
Arguments = $"--account={account} --password={password} --cacheDisk={cacheDisk} --port={Port}",
UseShellExecute = true, // requireAdministrator 进程需 ShellExecute 提权启动
WindowStyle = ProcessWindowStyle.Hidden
};
try { Process.Start(psi); }
catch (Exception ex) { log("拉起 control 失败:" + ex.Message); return false; }
log("已拉起 control.exe,等待就绪…");
for (int i = 0; i < waitSeconds; i++)
{
Thread.Sleep(1000);
if (IsControlAlive()) { log("control 就绪"); return true; }
}
log("control 拉起后等待就绪超时");
return false;
}
private static string ResolveExePath()
{
string rel = ConfigurationManager.AppSettings["controlExePath"]
?? @"control\ivf_tl_ControlHost.exe";
return Path.IsPathRooted(rel)
? rel
: Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rel);
}
}
}