aisop/tests/D3Startup.Smoke/Program.cs

243 lines
15 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Net;
using System.Text.Json;
using SopHelper.Engine.Sop;
// 复用已有测试工程验证授权状态机,避免创建额外构建目录或重复测试宿主。
if (args.Contains("--license-only")) { LicenseTests.Run(); return; }
// 现场排障:读取本机正式授权记录并打印状态,触发历史主板绑定记录的迁移;不签发、不兑换授权码。
if (args.Contains("--license-check-real")) { Console.WriteLine(LicenseTests.RealStoreCheck()); return; }
if(args.Length==2&&args[0]=="--djev-live")
{
var installed=Path.GetFullPath(args[1]);
var liveOptions=new D3StartupOptions(new("http://127.0.0.1:8766/v1/systemone"),installed,
Path.Combine(installed,".venv","Scripts","python.exe"),Path.GetFullPath("tools/start_d3_lite_local.py"),
Path.GetFullPath("../scratch/logs"),TimeSpan.FromSeconds(180),TimeSpan.FromMilliseconds(500));
using var liveHttp=new HttpClient();
var result=await new D3ServiceStartup(liveHttp,new D3LocalProcess()).EnsureReadyAsync(liveOptions,null,default);
if(!result.Ready)throw new Exception(result.Message);
using var health=JsonDocument.Parse(await liveHttp.GetStringAsync("http://127.0.0.1:8766/health"));
if(health.RootElement.GetProperty("model").GetString()!="d3-nano")throw new Exception("Nano was not loaded");
Console.WriteLine($"PASS: djev自动拉起 Nano,started={result.Started}");
return;
}
static void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS: "+message);}
// 固定路径以传入的程序目录为准,历史环境变量不得改写安装位置。
var previousRoot = Environment.GetEnvironmentVariable("SOPHELPER_D3_ROOT");
try
{
Environment.SetEnvironmentVariable("SOPHELPER_D3_ROOT", "legacy-install");
var resolved = D3StartupOptions.FromEnvironment("app", "workspace");
var expected = Path.GetFullPath(Path.Combine("app", "D3Nano"));
Check(resolved.Root == expected && resolved.Python == Path.Combine(expected, ".venv",
OperatingSystem.IsWindows() ? Path.Combine("Scripts", "python.exe") : Path.Combine("bin", "python")),
"模型和 Python 固定使用程序目录下的 D3Nano");
}
finally { Environment.SetEnvironmentVariable("SOPHELPER_D3_ROOT", previousRoot); }
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
{
// 旧 Lite 仍可能占用端口,启动器应报告冲突并避免拉起第二个服务。
using(var handler=new FakeHealth{Ready=true,Model="d3-lite"})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&&!result.Started&&process.Starts==0&&result.Message.Contains("Nano"),"已就绪的 Lite 不会被复用");
}
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,"取消等待不杀服务、不重复拉起正在载入的进程");
// 应用退出应在取消等待完成后单独停止,不能把已取消的令牌用于清理。
await new D3ServiceStartup(http,process).StopAsync(options,default);
Check(!process.Alive&&process.Stops==1&&!File.Exists(options.MarkerPath),"载入中退出也停止模型并清理记录");
await new D3ServiceStartup(http,process).StopAsync(options,default);
Check(process.Stops==1,"重复停止不重复操作已退出进程");
}
File.Delete(options.MarkerPath);
using(var handler=new FakeHealth{Ready=true})using(var http=new HttpClient(handler))
{
var process=new FakeProcess(handler){Alive=true};
File.WriteAllText(options.MarkerPath,JsonSerializer.Serialize(process.Marker));
var service=new D3ServiceStartup(http,process);
await service.EnsureReadyAsync(options,null,default);
await service.StopAsync(options with {Endpoint=new("http://192.168.0.167:8766/v1/systemone")},default);
Check(process.Alive&&process.Stops==0,"远程配置退出不停止本机进程");
using(var held=new FileStream(options.LockPath,FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None))
using(var cancel=new CancellationTokenSource(TimeSpan.FromMilliseconds(80)))
{
var cancelled=false;
try { await service.StopAsync(options,cancel.Token); } catch(OperationCanceledException) { cancelled=true; }
Check(cancelled&&process.Stops==0,"退出等待启动锁受取消期限约束");
}
await service.StopAsync(options,default);
Check(!process.Alive&&process.Starts==0&&process.Stops==1,"退出停止启动时复用的本机模型");
File.WriteAllText(options.MarkerPath,"invalid json");
await service.StopAsync(options,default);
Check(process.Stops==1,"损坏的进程记录不触发停止");
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,"start_d3_lite_local.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-nano',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"),
"真实进程复用和服务自行持有日志文件正常");
var marker=JsonSerializer.Deserialize<D3ProcessMarker>(File.ReadAllText(actual.MarkerPath))!;
await launcher.StopAsync(marker with {StartedUtc=marker.StartedUtc.AddMinutes(-1)},default);
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
{
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 string Model="d3-nano";
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=Model,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 Task<D3ProcessMarker[]> FindServicesAsync(D3StartupOptions options,CancellationToken token) =>
Task.FromResult<D3ProcessMarker[]>(Alive ? [Marker] : []);
public int Starts;
public int Stops;
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 Task StopAsync(D3ProcessMarker marker,CancellationToken token)
{
token.ThrowIfCancellationRequested();
if(IsAlive(marker)){Stops++;Alive=false;health.Ready=false;}
return Task.CompletedTask;
}
public D3ProcessMarker Start(D3StartupOptions options)
{
Interlocked.Increment(ref Starts);Alive=!ExitImmediately;
if(BecomeReady)health.Ready=true;
return Marker;
}
}