软件启动时自动检查并拉起本机D3-lite服务
This commit is contained in:
parent
d26eddb5f9
commit
4ef5706a27
@ -26,7 +26,7 @@
|
||||
|
||||
地址、模型名和密钥修改时自动保存到工作区的 `workspace/sop-agent.json`,无须先成功分析或保存配方,下次启动自动恢复;清空密钥也会保存。该文件包含本地明文密钥,不应分享或提交,Linux 下文件权限限制为当前用户读写。也可通过环境变量 `SOPHELPER_AGENT_ENDPOINT`、`SOPHELPER_AGENT_MODEL`、`SOPHELPER_AGENT_API_KEY` 覆盖设置。图片会发送到填写的接口。
|
||||
|
||||
验证使用合成视频与模拟工具调用服务,覆盖路径输入、多轮指定不同时刻、真实视频解码、工具结果回传、未读与越界拒绝、时间/区域/证据校验、聊天上下文和手动编辑传入、聊天继续读取视频、只讨论、无效更新回退、合并后更新配方和设置恢复;尚未连接用户实际模型,不代表真实 SOP 拆解准确率已验证。
|
||||
回归验证覆盖路径输入、多轮工具读取、规则必填区域、同区移动拒绝、无效坐标、时段外证据、限次反馈复查、阻塞原因、应用前拦截、聊天和草稿更新。2026-11-13 另使用配置的 `qwen3.8-flash-next-iq3_s` 对现有 12.1 秒标准录像只读试跑:6 轮请求、查看 12 帧、生成 5 步,区域规则与证据校验通过,原配方文件哈希不变。该试跑不代表现场工艺准确率已全面验证。
|
||||
|
||||
## 配置接口
|
||||
|
||||
@ -36,6 +36,10 @@
|
||||
|
||||
本分支默认 `d3-lite` 后端、`http://127.0.0.1:8766/v1/systemone`。不设置模型名或密钥也可连接本机服务;显式的 Laya / Chat Completions provider 仍受支持。
|
||||
|
||||
桌面软件启动时会在后台检查 D3-lite 的 `/health`,已就绪则复用;本机未运行时从已安装环境自动启动,等待就绪最长 180 秒,不阻塞界面。Windows 默认环境为 `E:\D3Lite`,Linux 默认 `~/D3Lite`,可用 `SOPHELPER_D3_ROOT` 指定。启动脚本随构建/发布复制到 `services/start_d3_lite_local.py`,服务输出写入工作区 `logs/d3-service/`。环境缺失、端口被其他服务占用、子进程退出或载入超时均记录明确原因,不自动安装模型。远程 D3 地址和其他视觉 provider 不会拉起本机 D3。
|
||||
|
||||
跨进程启动锁及 PID/启动时间记录防止载入期间重复占用 GPU;等待取消或软件退出不会终止已启动的独立服务。启动探测只读取健康状态,不送判定图。`tests/D3Startup.Smoke` 覆盖上述状态,附加 `--python Python路径` 可用真实 Python 启动轻量测试服务验证进程和日志,不加载模型。
|
||||
|
||||
```powershell
|
||||
# 在仓库根目录运行;复用现有服务,或隐藏启动 E:\D3Lite 的服务,再打开 SOP。
|
||||
pwsh -File tools/Start-HandAiD3.ps1
|
||||
|
||||
@ -15,6 +15,8 @@ pwsh -File tools/Start-HandAiD3.ps1
|
||||
|
||||
桌面程序使用 .NET 8、Avalonia 和 OpenCvSharp;手部检测需要 `models/` 中的 palm / landmark ONNX。D3-lite 是独立服务,默认地址 `http://127.0.0.1:8766/v1/systemone`,不随桌面程序一起打包。具体部署、协议和性能记录见 [HAND_AI.md](HAND_AI.md)。
|
||||
|
||||
启动软件时会自动检查并启动本机已安装的 D3-lite(Windows 默认 `E:\D3Lite`,可设 `SOPHELPER_D3_ROOT`)。已运行则复用,载入和失败信息写入运行日志;不会重复启动,也不会自动开始相机采集。
|
||||
|
||||
## 操作流程
|
||||
|
||||
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
|
||||
@ -56,6 +58,7 @@ dotnet run --project tests/VisionDecision.Smoke
|
||||
dotnet run --project tests/Pipeline.Smoke
|
||||
dotnet run --project tests/Avalonia.Smoke -- --vision-only
|
||||
dotnet run --project tests/SopVideoAgent.Smoke
|
||||
dotnet run --project tests/D3Startup.Smoke
|
||||
dotnet run --project tests/TensorPreprocessing.Smoke
|
||||
```
|
||||
|
||||
|
||||
@ -20,8 +20,11 @@ public partial class App : PrismApplication
|
||||
{
|
||||
private ICameraService? _camera;
|
||||
private DetectionPipeline? _pipeline;
|
||||
private readonly bool _autoStartD3 = true;
|
||||
private readonly CancellationTokenSource _d3StartupCancellation = new();
|
||||
private Task? _d3Startup;
|
||||
public App() { }
|
||||
public App(ICameraService camera) { _camera=camera; }
|
||||
public App(ICameraService camera) { _camera=camera; _autoStartD3=false; }
|
||||
public override void Initialize() { AvaloniaXamlLoader.Load(this); base.Initialize(); }
|
||||
protected override void RegisterTypes(IContainerRegistry containerRegistry)
|
||||
{
|
||||
@ -50,14 +53,37 @@ public partial class App : PrismApplication
|
||||
var item=Container.Resolve<NavigateItem>();item.ViewName=page.ViewName;item.DisplayName=page.DisplayName;navigation.Pages.Add(item);
|
||||
}
|
||||
var window=Container.Resolve<MainWindow>();
|
||||
window.Opened+=(_,_)=> { if(navigation.Pages.Count>0) navigation.SelectedIndex=0; };
|
||||
window.Opened+=(_,_)=>
|
||||
{
|
||||
if(navigation.Pages.Count>0) navigation.SelectedIndex=0;
|
||||
if(_autoStartD3) _d3Startup ??= StartD3Async();
|
||||
};
|
||||
window.Closed+=(_,_)=>
|
||||
{
|
||||
_d3StartupCancellation.Cancel();
|
||||
if(_d3Startup is null || _d3Startup.IsCompleted) _d3StartupCancellation.Dispose();
|
||||
else _ = _d3Startup.ContinueWith(_ => _d3StartupCancellation.Dispose(), TaskScheduler.Default);
|
||||
try{_camera?.Dispose();}catch(Exception ex){Log(ex,"Exit.Camera");}
|
||||
try{_pipeline?.Dispose();}catch(Exception ex){Log(ex,"Exit.Pipeline");}
|
||||
};
|
||||
return window;
|
||||
}
|
||||
private async Task StartD3Async()
|
||||
{
|
||||
var provider=Environment.GetEnvironmentVariable("SOPHELPER_VISION_PROVIDER")?.Trim().ToLowerInvariant();
|
||||
if(provider is not (null or "" or "d3" or "d3-lite")) return;
|
||||
var sop=Container.Resolve<SopPageViewModel>();
|
||||
try
|
||||
{
|
||||
using var http=new System.Net.Http.HttpClient { Timeout=Timeout.InfiniteTimeSpan, MaxResponseContentBufferSize=65536 };
|
||||
var options=D3StartupOptions.FromEnvironment(AppContext.BaseDirectory,Presentation.DesktopPlatform.WorkspaceRoot);
|
||||
var progress=new Progress<string>(message=>sop.ReportD3Service(message));
|
||||
var result=await new D3ServiceStartup(http,new D3LocalProcess()).EnsureReadyAsync(options,progress,_d3StartupCancellation.Token);
|
||||
sop.ReportD3Service(result.Message,!result.Ready&&!result.Skipped);
|
||||
}
|
||||
catch(OperationCanceledException) { }
|
||||
catch(Exception error) { sop.ReportD3Service("D3-lite 自动启动失败:"+error.Message,true);Log(error,"D3.Startup"); }
|
||||
}
|
||||
protected override void ConfigureViewModelLocator()
|
||||
{
|
||||
base.ConfigureViewModelLocator();
|
||||
|
||||
@ -25,6 +25,7 @@
|
||||
<AvaloniaResource Include="Assets/**" />
|
||||
<Content Include="Assets/bws.svg" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="../../configs/**/*" Link="configs/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="../../tools/start_d3_lite_local.py" Link="services/start_d3_lite_local.py" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
<Content Include="../../models/palm*.onnx;../../models/hand_landmark*.onnx" Link="models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="BWS.ico" />
|
||||
<Content Include="../../python/**/*" Exclude="../../python/**/__pycache__/**;../../python/**/*.pyc;../../python/**/*.lnk" Link="python/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="Never" Condition="'$(NativePlatform)' == 'Windows' and '$(BundlePythonRuntime)' == 'true'" />
|
||||
|
||||
@ -171,6 +171,8 @@ public class SopPageViewModel : ViewModelBase
|
||||
|
||||
/// <summary>日志</summary>
|
||||
public ObservableCollection<LogItem> Logs { get; } = [];
|
||||
public void ReportD3Service(string message, bool error = false)
|
||||
=> _dispatcher.BeginInvoke(() => Log(error ? "warn" : "info", message));
|
||||
|
||||
/// <summary>画面 ROI</summary>
|
||||
public ObservableCollection<RoiItem> Rois { get; } = [];
|
||||
|
||||
156
src/SopHelper.CrossPlatform.Engine/Sop/D3ServiceStartup.cs
Normal file
156
src/SopHelper.CrossPlatform.Engine/Sop/D3ServiceStartup.cs
Normal file
@ -0,0 +1,156 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
public sealed record D3StartupOptions(Uri Endpoint, string Root, string Python, string Script, string LogDirectory,
|
||||
TimeSpan Timeout, TimeSpan PollInterval)
|
||||
{
|
||||
public string MarkerPath => Path.Combine(Root, $"sophelper-d3-{Endpoint.Port}.json");
|
||||
public string LockPath => Path.Combine(Root, $"sophelper-d3-{Endpoint.Port}.lock");
|
||||
|
||||
public static D3StartupOptions FromEnvironment(string applicationDirectory, string workspace)
|
||||
{
|
||||
var root = Path.GetFullPath(Environment.GetEnvironmentVariable("SOPHELPER_D3_ROOT")
|
||||
?? (OperatingSystem.IsWindows() ? @"E:\D3Lite" : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "D3Lite")));
|
||||
return new(new Uri(Environment.GetEnvironmentVariable("SOPHELPER_VISION_ENDPOINT") ?? "http://127.0.0.1:8766/v1/systemone"),
|
||||
root, Path.Combine(root, ".venv", OperatingSystem.IsWindows() ? @"Scripts\python.exe" : "bin/python"),
|
||||
Path.Combine(applicationDirectory, "services", "start_d3_lite_local.py"), Path.Combine(workspace, "logs", "d3-service"),
|
||||
TimeSpan.FromSeconds(180), TimeSpan.FromMilliseconds(500));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record D3ProcessMarker(int Pid, DateTime StartedUtc);
|
||||
public sealed record D3StartupResult(bool Ready, bool Started, string Message, bool Skipped = false);
|
||||
|
||||
public interface ID3ServiceProcess
|
||||
{
|
||||
bool IsAlive(D3ProcessMarker marker);
|
||||
D3ProcessMarker Start(D3StartupOptions options);
|
||||
}
|
||||
|
||||
/// <summary>只检查健康状态和启动本机进程,不向模型发送判定图片。</summary>
|
||||
public sealed class D3ServiceStartup(HttpClient http, ID3ServiceProcess process)
|
||||
{
|
||||
private enum Health { Missing, Ready, Starting, OtherService }
|
||||
|
||||
public async Task<D3StartupResult> EnsureReadyAsync(D3StartupOptions options, IProgress<string>? progress, CancellationToken token)
|
||||
{
|
||||
if (options.Endpoint.Scheme is not ("http" or "https")) return new(false, false, "D3-lite 接口地址无效");
|
||||
if (!IsLocal(options.Endpoint)) return new(false, false, "D3-lite 使用远程服务,不启动本机进程", true);
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(options.Timeout);
|
||||
var ct = timeout.Token;
|
||||
FileStream? startupLock = null;
|
||||
var started = false;
|
||||
try
|
||||
{
|
||||
progress?.Report("检查 D3-lite 服务");
|
||||
var health = await ProbeAsync(options, ct).ConfigureAwait(false);
|
||||
if (health == Health.Ready) return new(true, false, "D3-lite 服务已就绪,复用现有服务");
|
||||
if (health == Health.OtherService) return new(false, false, "D3-lite 端口被其他服务占用");
|
||||
if (health == Health.Starting) return await WaitReadyAsync(null).ConfigureAwait(false);
|
||||
if (options.Endpoint.Scheme != "http") return new(false, false, "本机 D3-lite 自动启动仅支持 HTTP 接口");
|
||||
if (!File.Exists(options.Python) || !File.Exists(Path.Combine(options.Root, "model", "decision_config.json")) || !File.Exists(options.Script))
|
||||
return new(false, false, "D3-lite 本地环境缺失,请检查 SOPHELPER_D3_ROOT 和服务脚本");
|
||||
// 跨进程串行启动;模型载入期间端口可能尚未监听,不能仅凭连接失败重复拉起。
|
||||
while (startupLock is null)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try { startupLock = new FileStream(options.LockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }
|
||||
catch (IOException) { await Task.Delay(options.PollInterval, ct).ConfigureAwait(false); }
|
||||
}
|
||||
health = await ProbeAsync(options, ct).ConfigureAwait(false);
|
||||
if (health == Health.Ready) return new(true, false, "D3-lite 服务已就绪,复用现有服务");
|
||||
if (health == Health.OtherService) return new(false, false, "D3-lite 端口被其他服务占用");
|
||||
if (health == Health.Starting) return await WaitReadyAsync(null).ConfigureAwait(false);
|
||||
D3ProcessMarker? marker = null;
|
||||
try
|
||||
{
|
||||
if (File.Exists(options.MarkerPath)) marker = JsonSerializer.Deserialize<D3ProcessMarker>(await File.ReadAllTextAsync(options.MarkerPath, ct).ConfigureAwait(false));
|
||||
}
|
||||
catch (Exception error) when (error is IOException or JsonException) { }
|
||||
if (marker is null || !process.IsAlive(marker))
|
||||
{
|
||||
progress?.Report("正在启动 D3-lite");
|
||||
marker = process.Start(options);
|
||||
started = true;
|
||||
File.WriteAllText(options.MarkerPath, JsonSerializer.Serialize(marker));
|
||||
}
|
||||
else progress?.Report("D3-lite 正在载入,等待就绪");
|
||||
return await WaitReadyAsync(marker).ConfigureAwait(false);
|
||||
|
||||
async Task<D3StartupResult> WaitReadyAsync(D3ProcessMarker? active)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
health = await ProbeAsync(options, ct).ConfigureAwait(false);
|
||||
if (health == Health.Ready) return new(true, started, started ? "D3-lite 已自动启动并就绪" : "D3-lite 已就绪");
|
||||
if (health == Health.OtherService) return new(false, started, "D3-lite 端口被其他服务占用");
|
||||
if (active is not null && !process.IsAlive(active)) return new(false, started, $"D3-lite 启动失败,日志:{options.LogDirectory}");
|
||||
await Task.Delay(options.PollInterval, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (!token.IsCancellationRequested)
|
||||
{ return new(false, started, $"等待 D3-lite 就绪超时,日志:{options.LogDirectory}"); }
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException or InvalidOperationException or System.ComponentModel.Win32Exception)
|
||||
{ return new(false, started, "D3-lite 自动启动失败:" + error.Message); }
|
||||
finally { startupLock?.Dispose(); }
|
||||
}
|
||||
|
||||
private async Task<Health> ProbeAsync(D3StartupOptions options, CancellationToken token)
|
||||
{
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(2));
|
||||
try
|
||||
{
|
||||
var healthUri = new UriBuilder(options.Endpoint) { Path = "/health", Query = "", Fragment = "" }.Uri;
|
||||
using var response = await http.GetAsync(healthUri, deadline.Token).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode) return Health.OtherService;
|
||||
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(deadline.Token).ConfigureAwait(false));
|
||||
if (!body.RootElement.TryGetProperty("model", out var model) || model.GetString() != "d3-lite") return Health.OtherService;
|
||||
if (body.RootElement.TryGetProperty("status", out var status) && status.GetString() == "ready"
|
||||
&& body.RootElement.TryGetProperty("modalities", out var modes) && modes.EnumerateArray().Any(mode => mode.GetString() == "image"))
|
||||
return Health.Ready;
|
||||
return Health.Starting;
|
||||
}
|
||||
catch (HttpRequestException) { return Health.Missing; }
|
||||
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return Health.Missing; }
|
||||
catch (JsonException) { return Health.OtherService; }
|
||||
}
|
||||
|
||||
private static bool IsLocal(Uri uri) => uri.IsLoopback
|
||||
|| IPAddress.TryParse(uri.Host, out var address) && IPAddress.IsLoopback(address);
|
||||
}
|
||||
|
||||
public sealed class D3LocalProcess : ID3ServiceProcess
|
||||
{
|
||||
public bool IsAlive(D3ProcessMarker marker)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var existing = Process.GetProcessById(marker.Pid);
|
||||
return !existing.HasExited && Math.Abs((existing.StartTime.ToUniversalTime() - marker.StartedUtc).TotalSeconds) < 2;
|
||||
}
|
||||
catch (Exception error) when (error is ArgumentException or InvalidOperationException or System.ComponentModel.Win32Exception) { return false; }
|
||||
}
|
||||
|
||||
public D3ProcessMarker Start(D3StartupOptions options)
|
||||
{
|
||||
Directory.CreateDirectory(options.LogDirectory);
|
||||
var start = new ProcessStartInfo(options.Python)
|
||||
{
|
||||
UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden,
|
||||
WorkingDirectory = options.Root
|
||||
};
|
||||
foreach (var argument in new[] { "-u", options.Script, "--root", options.Root, "--port", options.Endpoint.Port.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
"--log-dir", options.LogDirectory })
|
||||
start.ArgumentList.Add(argument);
|
||||
using var child = Process.Start(start) ?? throw new InvalidOperationException("无法创建 D3-lite 进程");
|
||||
var marker = new D3ProcessMarker(child.Id, child.StartTime.ToUniversalTime());
|
||||
return marker;
|
||||
}
|
||||
}
|
||||
4
tests/D3Startup.Smoke/D3Startup.Smoke.csproj
Normal file
4
tests/D3Startup.Smoke/D3Startup.Smoke.csproj
Normal file
@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
148
tests/D3Startup.Smoke/Program.cs
Normal file
148
tests/D3Startup.Smoke/Program.cs
Normal file
@ -0,0 +1,148 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
static void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS: "+message);}
|
||||
var root=Path.Combine(Path.GetTempPath(),"d3-startup-"+Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(Path.Combine(root,"model"));
|
||||
var python=Path.Combine(root,"python.exe");var script=Path.Combine(root,"service.py");
|
||||
File.WriteAllText(python,"");File.WriteAllText(script,"");File.WriteAllText(Path.Combine(root,"model","decision_config.json"),"{}");
|
||||
var options=new D3StartupOptions(new("http://127.0.0.1:8766/v1/systemone"),root,python,script,Path.Combine(root,"logs"),TimeSpan.FromSeconds(2),TimeSpan.FromMilliseconds(20));
|
||||
try
|
||||
{
|
||||
using(var handler=new FakeHealth{Ready=true})using(var http=new HttpClient(handler))
|
||||
{
|
||||
var process=new FakeProcess(handler);
|
||||
var result=await new D3ServiceStartup(http,process).EnsureReadyAsync(options with {Python="absent"},null,default);
|
||||
Check(result.Ready&&!result.Started&&process.Starts==0,"已运行的服务直接复用,不依赖本机安装路径");
|
||||
}
|
||||
using(var handler=new FakeHealth())using(var http=new HttpClient(handler))
|
||||
{
|
||||
var process=new FakeProcess(handler);
|
||||
var first=new D3ServiceStartup(http,process);var second=new D3ServiceStartup(http,process);
|
||||
var results=await Task.WhenAll(first.EnsureReadyAsync(options,null,default),second.EnsureReadyAsync(options,null,default));
|
||||
Check(results.All(result=>result.Ready)&&process.Starts==1,"未运行时自动启动,并发启动只创建一个模型进程");
|
||||
}
|
||||
File.Delete(options.MarkerPath);
|
||||
using(var handler=new FakeHealth())using(var http=new HttpClient(handler))
|
||||
{
|
||||
var process=new FakeProcess(handler){BecomeReady=false};
|
||||
var result=await new D3ServiceStartup(http,process).EnsureReadyAsync(options with {Timeout=TimeSpan.FromMilliseconds(160)},null,default);
|
||||
Check(!result.Ready&&result.Started&&result.Message.Contains("超时")&&process.Starts==1,"载入超时明确报告,不能循环重启进程");
|
||||
var marker=JsonSerializer.Deserialize<D3ProcessMarker>(File.ReadAllText(options.MarkerPath));
|
||||
Check(marker==process.Marker,"超时后保留启动记录,后续启动继续等待原进程");
|
||||
handler.Ready=false;
|
||||
using var cancel=new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
|
||||
var cancelled=false;
|
||||
try{await new D3ServiceStartup(http,process).EnsureReadyAsync(options,null,cancel.Token);}catch(OperationCanceledException){cancelled=true;}
|
||||
Check(cancelled&&process.Starts==1&&process.Alive,"取消等待不杀服务、不重复拉起正在载入的进程");
|
||||
}
|
||||
File.Delete(options.MarkerPath);
|
||||
using(var handler=new FakeHealth())using(var http=new HttpClient(handler))
|
||||
{
|
||||
var process=new FakeProcess(handler){BecomeReady=false,ExitImmediately=true};
|
||||
var result=await new D3ServiceStartup(http,process).EnsureReadyAsync(options,null,default);
|
||||
Check(!result.Ready&&result.Started&&result.Message.Contains("启动失败"),"子进程退出时报告失败和日志目录");
|
||||
}
|
||||
File.Delete(options.MarkerPath);
|
||||
using(var handler=new FakeHealth{Other=true})using(var http=new HttpClient(handler))
|
||||
{
|
||||
var process=new FakeProcess(handler);
|
||||
var result=await new D3ServiceStartup(http,process).EnsureReadyAsync(options,null,default);
|
||||
Check(!result.Ready&&process.Starts==0,"端口被其他服务占用时不另起进程");
|
||||
}
|
||||
using(var handler=new FakeHealth{Warming=true})using(var http=new HttpClient(handler))
|
||||
{
|
||||
var process=new FakeProcess(handler);
|
||||
var result=await new D3ServiceStartup(http,process).EnsureReadyAsync(options with {Timeout=TimeSpan.FromMilliseconds(100)},null,default);
|
||||
Check(!result.Ready&&process.Starts==0,"已监听但仍在载入的D3不被重复启动");
|
||||
}
|
||||
using(var handler=new FakeHealth())using(var http=new HttpClient(handler))
|
||||
{
|
||||
var process=new FakeProcess(handler);
|
||||
var result=await new D3ServiceStartup(http,process).EnsureReadyAsync(options with {Endpoint=new("http://192.168.0.167:8766/v1/systemone")},null,default);
|
||||
Check(result.Skipped&&handler.Requests==0&&process.Starts==0,"远程D3不触发本机模型启动");
|
||||
result=await new D3ServiceStartup(http,process).EnsureReadyAsync(options with {Python="absent"},null,default);
|
||||
Check(!result.Ready&&process.Starts==0&&result.Message.Contains("环境缺失"),"本机环境缺失时报告原因,不下载或安装模型");
|
||||
}
|
||||
if(args.Length==2&&args[0]=="--python")
|
||||
{
|
||||
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");
|
||||
File.WriteAllText(stub,"""
|
||||
import argparse,json,sys
|
||||
from pathlib import Path
|
||||
from http.server import HTTPServer,BaseHTTPRequestHandler
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--root');parser.add_argument('--port',type=int);parser.add_argument('--log-dir')
|
||||
args=parser.parse_args();Path(args.log_dir).mkdir(parents=True,exist_ok=True)
|
||||
sys.stdout=open(Path(args.log_dir)/'stub.stdout.log','a',buffering=1)
|
||||
print('ready')
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
payload=json.dumps(dict(status='ready',model='d3-lite',modalities=['text','image'])).encode()
|
||||
self.send_response(200);self.send_header('Content-Length',str(len(payload)));self.end_headers();self.wfile.write(payload)
|
||||
def log_message(self,*args):pass
|
||||
HTTPServer(('127.0.0.1',args.port),Handler).serve_forever()
|
||||
""");
|
||||
var actual=options with {Endpoint=new($"http://127.0.0.1:{port}/v1/systemone"),Python=Path.GetFullPath(args[1]),Script=stub,Timeout=TimeSpan.FromSeconds(15)};
|
||||
using var http=new HttpClient();var launcher=new D3LocalProcess();
|
||||
try
|
||||
{
|
||||
var result=await new D3ServiceStartup(http,launcher).EnsureReadyAsync(actual,null,default);
|
||||
Check(result.Ready&&result.Started,"真实Python子进程能按参数启动并通过健康检查(不加载模型)");
|
||||
result=await new D3ServiceStartup(http,launcher).EnsureReadyAsync(actual,null,default);
|
||||
using var logStream=new FileStream(Path.Combine(actual.LogDirectory,"stub.stdout.log"),FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
|
||||
using var logReader=new StreamReader(logStream);
|
||||
Check(result.Ready&&!result.Started&&logReader.ReadToEnd().Contains("ready"),
|
||||
"真实进程复用和服务自行持有日志文件正常");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if(File.Exists(actual.MarkerPath))
|
||||
{
|
||||
var marker=JsonSerializer.Deserialize<D3ProcessMarker>(File.ReadAllText(actual.MarkerPath))!;
|
||||
if(launcher.IsAlive(marker))
|
||||
{
|
||||
using var child=System.Diagnostics.Process.GetProcessById(marker.Pid);
|
||||
child.Kill(entireProcessTree:true);await child.WaitForExitAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if(!Path.GetFullPath(root).StartsWith(Path.GetFullPath(Path.GetTempPath())))throw new Exception("Unexpected temporary root");
|
||||
Directory.Delete(root,true);
|
||||
}
|
||||
|
||||
sealed class FakeHealth:HttpMessageHandler
|
||||
{
|
||||
public volatile bool Ready,Other,Warming;
|
||||
public int Requests;
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage message,CancellationToken token)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();Interlocked.Increment(ref Requests);
|
||||
if(message.Method!=HttpMethod.Get||message.RequestUri!.AbsolutePath!="/health")throw new Exception("启动检查不得发送模型推理请求");
|
||||
if(!Ready&&!Other&&!Warming)throw new HttpRequestException("Connection refused");
|
||||
var json=Other?"{\"model\":\"other\",\"status\":\"ready\"}"
|
||||
:JsonSerializer.Serialize(new{model="d3-lite",status=Ready?"ready":"loading",modalities=new[]{"text","image"}});
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent(json)});
|
||||
}
|
||||
}
|
||||
sealed class FakeProcess(FakeHealth health):ID3ServiceProcess
|
||||
{
|
||||
public int Starts;
|
||||
public bool BecomeReady=true,ExitImmediately;
|
||||
public volatile bool Alive;
|
||||
public D3ProcessMarker Marker {get;}=new(42,DateTime.UtcNow);
|
||||
public bool IsAlive(D3ProcessMarker marker)=>marker==Marker&&Alive;
|
||||
public D3ProcessMarker Start(D3StartupOptions options)
|
||||
{
|
||||
Interlocked.Increment(ref Starts);Alive=!ExitImmediately;
|
||||
if(BecomeReady)health.Ready=true;
|
||||
return Marker;
|
||||
}
|
||||
}
|
||||
@ -13,7 +13,14 @@ def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=Path(r"E:\D3Lite"))
|
||||
parser.add_argument("--port", type=int, default=8766)
|
||||
parser.add_argument("--log-dir", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.log_dir is not None:
|
||||
args.log_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{os.getpid()}"
|
||||
# 文件由服务自身持有,桌面软件退出后不会因管道关闭影响服务。
|
||||
sys.stdout = (args.log_dir / f"{stamp}.stdout.log").open("a", encoding="utf-8", buffering=1)
|
||||
sys.stderr = (args.log_dir / f"{stamp}.stderr.log").open("a", encoding="utf-8", buffering=1)
|
||||
root = args.root.resolve()
|
||||
os.environ["HF_HUB_OFFLINE"] = "1"
|
||||
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user