262 lines
17 KiB
C#
262 lines
17 KiB
C#
using System.Net;
|
||
using System.Text.Json;
|
||
using SopHelper.Engine.Sop;
|
||
|
||
if(args.Length==3&&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()!=args[2])throw new Exception("Configured djev tier was not loaded");
|
||
Console.WriteLine($"PASS: djev自动拉起配置档位,started={result.Started}");
|
||
return;
|
||
}
|
||
|
||
static void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS: "+message);}
|
||
// 模拟安装后未注销的桌面:进程环境缺少变量,但机器配置已经写入 D 盘安装目录。
|
||
if (OperatingSystem.IsWindows())
|
||
{
|
||
var machineRoot = Path.GetFullPath(@"D:\D3Nano");
|
||
var userRoot = Path.GetFullPath(@"D:\UserDjev");
|
||
var processRoot = Path.GetFullPath(@"D:\ProcessDjev");
|
||
var resolved = D3StartupOptions.FromEnvironment("app", "workspace",
|
||
(_, target) => target == EnvironmentVariableTarget.Machine ? machineRoot : null);
|
||
Check(resolved.Root == machineRoot && resolved.Python == Path.Combine(machineRoot, @".venv\Scripts\python.exe"),
|
||
"旧桌面会话未继承变量时读取机器安装目录及其Python,不回退E盘");
|
||
resolved = D3StartupOptions.FromEnvironment("app", "workspace",
|
||
(_, target) => target == EnvironmentVariableTarget.User ? userRoot : target == EnvironmentVariableTarget.Machine ? machineRoot : " ");
|
||
Check(resolved.Root == userRoot, "空进程变量按缺省处理,用户安装目录优先于机器配置");
|
||
resolved = D3StartupOptions.FromEnvironment("app", "workspace",
|
||
(_, target) => target == EnvironmentVariableTarget.Process ? processRoot : machineRoot);
|
||
Check(resolved.Root == processRoot, "显式进程安装目录仍优先于持久配置");
|
||
resolved = D3StartupOptions.FromEnvironment("app", "workspace", (_, _) => null);
|
||
Check(resolved.Root == Path.GetFullPath(@"E:\D3Lite"), "未配置安装目录时保留默认Lite目录");
|
||
}
|
||
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
|
||
{
|
||
// 使用隔离的假安装验证配置,不接触本机模型和当前服务。
|
||
var liteRoot = Path.Combine(root, "D3Lite");
|
||
var nanoRoot = Path.Combine(root, "D3Nano");
|
||
foreach (var (directory, model) in new[] { (liteRoot, "d3-lite"), (nanoRoot, "d3-nano") })
|
||
{
|
||
Directory.CreateDirectory(Path.Combine(directory, "model"));
|
||
File.WriteAllText(Path.Combine(directory, "model", "MODEL_MANIFEST.json"), JsonSerializer.Serialize(new { model_name = model }));
|
||
File.WriteAllText(Path.Combine(directory, "model", "decision_config.json"), "{}");
|
||
}
|
||
var selectionStore = new DjevSelectionStore(liteRoot);
|
||
Check(selectionStore.Read() == new DjevSelection("lite", liteRoot, nanoRoot), "没有配置时兼容默认Lite及同级Nano目录");
|
||
File.WriteAllText(selectionStore.FilePath, "{\"tier\":\"nano\",\"nano_root\":\"../D3Nano\",\"extension\":42}");
|
||
Check(selectionStore.Read().NanoRoot == nanoRoot, "兼容旧配置及相对模型路径");
|
||
selectionStore.Save(new("nano", liteRoot, nanoRoot));
|
||
Check(new DjevSelectionStore(liteRoot).Read().Tier == "nano" && File.ReadAllText(selectionStore.FilePath).Contains("extension"),
|
||
"档位保存后重新读取且保留扩展字段");
|
||
var originalSelection = File.ReadAllText(selectionStore.FilePath);
|
||
var rejectedSelection = false;
|
||
try { selectionStore.Save(new("lite", nanoRoot, nanoRoot)); } catch (InvalidOperationException) { rejectedSelection = true; }
|
||
Check(rejectedSelection && File.ReadAllText(selectionStore.FilePath) == originalSelection, "拒绝错误档位模型且不覆盖旧配置");
|
||
using (var held = new FileStream(Path.Combine(liteRoot, "sophelper-d3-8766.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
|
||
{
|
||
rejectedSelection = false;
|
||
try { selectionStore.Save(new("lite", liteRoot, nanoRoot)); } catch (IOException) { rejectedSelection = true; }
|
||
Check(rejectedSelection && File.ReadAllText(selectionStore.FilePath) == originalSelection, "启动期间拒绝改写选择且保留配置");
|
||
}
|
||
selectionStore.Save(new("lite", liteRoot, nanoRoot));
|
||
Check(selectionStore.Read().Tier == "lite", "可从Nano保存切回Lite");
|
||
var nanoStore = new DjevSelectionStore(nanoRoot);
|
||
Check(nanoStore.Read().Tier == "nano" && nanoStore.Read().LiteRoot == liteRoot && nanoStore.Read().NanoRoot == nanoRoot,
|
||
"Nano独立安装正确显示默认档位并定位两个模型目录");
|
||
|
||
using(var handler=new FakeHealth{Ready=true,Model="d3-nano"})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,"快捷切换后的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,"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"),
|
||
"真实进程复用和服务自行持有日志文件正常");
|
||
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服务退出并清除启动记录,不加载模型");
|
||
}
|
||
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-lite";
|
||
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 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;
|
||
}
|
||
}
|