正常退出时识别并关闭没有启动记录的本机 djev
This commit is contained in:
parent
f0f0effb3f
commit
29292a7f19
@ -42,6 +42,8 @@ public sealed record D3StartupResult(bool Ready, bool Started, string Message, b
|
||||
|
||||
public interface ID3ServiceProcess
|
||||
{
|
||||
/// <summary>按本地启动命令和端口识别没有桌面启动记录的 djev。</summary>
|
||||
Task<D3ProcessMarker[]> FindServicesAsync(D3StartupOptions options, CancellationToken token);
|
||||
bool IsAlive(D3ProcessMarker marker);
|
||||
D3ProcessMarker Start(D3StartupOptions options);
|
||||
/// <summary>核对进程身份后停止服务及其子进程,等待退出以释放模型资源。</summary>
|
||||
@ -53,7 +55,7 @@ public sealed class D3ServiceStartup(HttpClient http, ID3ServiceProcess process)
|
||||
{
|
||||
private enum Health { Missing, Ready, Starting, OtherService }
|
||||
|
||||
/// <summary>退出时停止本机记录的服务(包括启动时复用的服务);远程地址和无有效记录的进程不作处理。</summary>
|
||||
/// <summary>正常退出时停止本机服务;记录缺失或失效时按启动参数查找复用的服务。</summary>
|
||||
public async Task StopAsync(D3StartupOptions options, CancellationToken token)
|
||||
{
|
||||
if (!IsLocal(options.Endpoint) || !Directory.Exists(options.Root)) return;
|
||||
@ -67,14 +69,20 @@ public sealed class D3ServiceStartup(HttpClient http, ID3ServiceProcess process)
|
||||
try { shutdownLock = new FileStream(options.LockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }
|
||||
catch (IOException) { await Task.Delay(options.PollInterval, token).ConfigureAwait(false); }
|
||||
}
|
||||
if (!File.Exists(options.MarkerPath)) return;
|
||||
D3ProcessMarker? marker;
|
||||
try { marker = JsonSerializer.Deserialize<D3ProcessMarker>(await File.ReadAllTextAsync(options.MarkerPath, token).ConfigureAwait(false)); }
|
||||
catch (JsonException) { return; }
|
||||
if (marker is null) return;
|
||||
await process.StopAsync(marker, token).ConfigureAwait(false);
|
||||
// 只有确认进程已退出(或记录过期)才移除记录,停止失败时保留以供排查和重试。
|
||||
if (!process.IsAlive(marker)) File.Delete(options.MarkerPath);
|
||||
D3ProcessMarker? marker = null;
|
||||
if (File.Exists(options.MarkerPath))
|
||||
{
|
||||
try { marker = JsonSerializer.Deserialize<D3ProcessMarker>(await File.ReadAllTextAsync(options.MarkerPath, token).ConfigureAwait(false)); }
|
||||
catch (JsonException) { } // 记录损坏时继续核对实际的服务启动参数。
|
||||
}
|
||||
if (marker is not null && process.IsAlive(marker))
|
||||
await process.StopAsync(marker, token).ConfigureAwait(false);
|
||||
else
|
||||
{
|
||||
foreach (var service in await process.FindServicesAsync(options, token).ConfigureAwait(false))
|
||||
await process.StopAsync(service, token).ConfigureAwait(false);
|
||||
}
|
||||
File.Delete(options.MarkerPath);
|
||||
}
|
||||
finally { shutdownLock?.Dispose(); }
|
||||
}
|
||||
@ -174,6 +182,33 @@ public sealed class D3ServiceStartup(HttpClient http, ID3ServiceProcess process)
|
||||
|
||||
public sealed class D3LocalProcess : ID3ServiceProcess
|
||||
{
|
||||
/// <summary>用模型环境读取 Python 服务的启动参数与创建时间;识别脚本只返回候选进程。</summary>
|
||||
public async Task<D3ProcessMarker[]> FindServicesAsync(D3StartupOptions options, CancellationToken token)
|
||||
{
|
||||
if (!File.Exists(options.Python)) return [];
|
||||
var start = new ProcessStartInfo(options.Python)
|
||||
{
|
||||
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true
|
||||
};
|
||||
start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "services", "find_djev_processes.py"));
|
||||
start.ArgumentList.Add(options.Root);
|
||||
start.ArgumentList.Add(options.Endpoint.Port.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
using var probe = Process.Start(start) ?? throw new InvalidOperationException("无法检查本机 djev 进程");
|
||||
try
|
||||
{
|
||||
var output = probe.StandardOutput.ReadToEndAsync(token);
|
||||
var errors = probe.StandardError.ReadToEndAsync(token);
|
||||
await probe.WaitForExitAsync(token).ConfigureAwait(false);
|
||||
if (probe.ExitCode != 0) throw new InvalidOperationException(await errors.ConfigureAwait(false));
|
||||
return JsonSerializer.Deserialize<D3ProcessMarker[]>(await output.ConfigureAwait(false)) ?? [];
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 超时退出时同时回收识别脚本和虚拟环境启动器。
|
||||
if (!probe.HasExited) probe.Kill(entireProcessTree: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>使用同一进程句柄核对 PID 和启动时间后结束进程树,不触碰已复用该 PID 的其他进程。</summary>
|
||||
public async Task StopAsync(D3ProcessMarker marker, CancellationToken token)
|
||||
{
|
||||
|
||||
@ -10,6 +10,8 @@
|
||||
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- 随桌面程序分发旧服务识别脚本,复用模型环境中的 psutil。 -->
|
||||
<None Include="../../tools/find_djev_processes.py" Link="services/find_djev_processes.py" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
<!-- 客户端仅打包验签公钥,发码私钥始终保留在发行方电脑。 -->
|
||||
<EmbeddedResource Include="Licensing/issuer-public.pem" />
|
||||
<PackageReference Include="OpenCvSharp5" Version="5.0.0.20261107" />
|
||||
|
||||
@ -174,7 +174,7 @@ try
|
||||
{
|
||||
using var socket=new System.Net.Sockets.TcpListener(IPAddress.Loopback,0);socket.Start();
|
||||
var port=((IPEndPoint)socket.LocalEndpoint).Port;socket.Stop();
|
||||
var stub=Path.Combine(root,"stub service.py");
|
||||
var stub=Path.Combine(root,"start_d3_lite_local.py");
|
||||
File.WriteAllText(stub,"""
|
||||
import argparse,json,sys
|
||||
from pathlib import Path
|
||||
@ -207,6 +207,16 @@ try
|
||||
Check(launcher.IsAlive(marker),"PID相同但启动时间不符时不误杀真实进程");
|
||||
await new D3ServiceStartup(http,launcher).StopAsync(actual,default);
|
||||
Check(!launcher.IsAlive(marker)&&!File.Exists(actual.MarkerPath),"真实Python服务退出并清除启动记录,不加载模型");
|
||||
// 删除启动记录后按真实进程参数回收,模拟旧部署入口。
|
||||
result=await new D3ServiceStartup(http,launcher).EnsureReadyAsync(actual,null,default);
|
||||
var untracked=JsonSerializer.Deserialize<D3ProcessMarker>(File.ReadAllText(actual.MarkerPath))!;
|
||||
try
|
||||
{
|
||||
File.Delete(actual.MarkerPath);
|
||||
await new D3ServiceStartup(http,launcher).StopAsync(actual,default);
|
||||
Check(result.Ready&&!launcher.IsAlive(untracked),"没有启动记录时识别并关闭本机 djev");
|
||||
}
|
||||
finally { await launcher.StopAsync(untracked,default); }
|
||||
}
|
||||
finally
|
||||
{
|
||||
@ -245,6 +255,9 @@ sealed class FakeHealth:HttpMessageHandler
|
||||
}
|
||||
sealed class FakeProcess(FakeHealth health):ID3ServiceProcess
|
||||
{
|
||||
// 用存活状态模拟按启动参数发现服务。
|
||||
public Task<D3ProcessMarker[]> FindServicesAsync(D3StartupOptions options,CancellationToken token) =>
|
||||
Task.FromResult<D3ProcessMarker[]>(Alive ? [Marker] : []);
|
||||
public int Starts;
|
||||
public int Stops;
|
||||
public bool BecomeReady=true,ExitImmediately;
|
||||
|
||||
46
tools/find_djev_processes.py
Normal file
46
tools/find_djev_processes.py
Normal file
@ -0,0 +1,46 @@
|
||||
"""查找旧版部署或外部启动的本机 djev,供桌面端正常退出时核对并回收进程。"""
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import psutil
|
||||
|
||||
|
||||
def service_arguments(argv):
|
||||
"""仅识别两个已发布的 Python 启动入口,排除 probe、status 和其他 Python 程序。"""
|
||||
args = argv[1:]
|
||||
if args[:1] == ["-u"]:
|
||||
args = args[1:]
|
||||
if not args:
|
||||
return []
|
||||
script = Path(args[0]).name
|
||||
if script == "start_d3_lite_local.py":
|
||||
return args[1:]
|
||||
if script == "d3nano-service.py" and args[1:2] == ["serve"]:
|
||||
return args[2:]
|
||||
return []
|
||||
|
||||
|
||||
def find_services(root, port):
|
||||
"""匹配启动目录与端口,包括尚未监听的模型。切换过目录时只接管实际监听该端口的服务。"""
|
||||
matches = []
|
||||
for proc in psutil.process_iter(["name"]):
|
||||
if not (proc.info["name"] or "").lower().startswith("python"):
|
||||
continue
|
||||
try:
|
||||
args = service_arguments(proc.cmdline())
|
||||
if "--port" not in args or args[args.index("--port") + 1] != str(port):
|
||||
continue
|
||||
same_root = "--root" in args and Path(args[args.index("--root") + 1]).resolve() == root
|
||||
if not same_root and not any(c.status == psutil.CONN_LISTEN and c.laddr.port == port
|
||||
and c.laddr.ip in ("127.0.0.1", "::1") for c in proc.net_connections("tcp")):
|
||||
continue
|
||||
matches.append(dict(Pid=proc.pid, StartedUtc=datetime.fromtimestamp(proc.create_time(), timezone.utc).isoformat().replace("+00:00", "Z")))
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, IndexError):
|
||||
continue
|
||||
return matches
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(find_services(Path(sys.argv[1]).resolve(), int(sys.argv[2]))))
|
||||
Loading…
Reference in New Issue
Block a user