移除 djev 计划任务自启并在部署验收后释放模型

This commit is contained in:
wanglei 2026-11-27 11:21:10 +08:00
parent 29292a7f19
commit a952b8fa7d
5 changed files with 41 additions and 70 deletions

View File

@ -24,7 +24,7 @@ Windows 工位机用 SSH/SFTP 部署,目录约定与 `tools/Deploy-Linux.ps1`
### d3-nano 判定服务
```powershell
# 打包模型与离线 wheel、传输、远端建 .venv、注册计划任务并用真实图片验收
# 打包模型与离线 wheel、传输、远端建 .venv、用真实图片验收后释放临时模型
.\tools\Deploy-D3Nano.ps1 -Target Administrator@192.168.0.184 -InstallRoot D:\D3Nano
# 常用参数:-ModelSource 本机模型目录、-WheelsSource 本机 wheel 目录、-WheelsRemote 远端 wheel 目录、-SkipWheels 复用已传 wheel、-SkipStart 不启动服务
```
@ -33,8 +33,8 @@ Windows 工位机用 SSH/SFTP 部署,目录约定与 `tools/Deploy-Linux.ps1`
从 pytorch cu128 源与 PyPI 取全依赖,打包传入,远端用 `pip install --no-index --find-links` 离线安装。
工位机直连 pytorch 官方源只有 0.22MB/s,本机同一源 12MB/s,联网自装会拖到数小时。
- `tools/windows/install-d3nano.ps1` 解包模型、装 Python(缺则 winget)、建 `.venv`、离线装依赖、写 `djev.json` 与机器级 `SOPHELPER_D3_ROOT`,
最后校验 torch 能看到显卡与算力。`tools/windows/d3nano-service.py` 提供 `serve`(前台承载)、`status`、`probe` 三个入口,
`tools/windows/register-d3nano-task.ps1` 负责计划任务,`tools/windows/probe-d3nano.py` 用真实相机 JPEG 核对 noul 结果与耗时。
最后校验显卡与算力,禁用旧安装的 djev 自启任务。桌面软件启动时直接拉起本机 djev,正常退出时关闭。
- 部署验收使用 `d3nano-service.py verify`,用真实相机 JPEG 核对 noul 结果与耗时,只回收本次验收启动的服务。
## W-184 首次部署(2026-11-20)

View File

@ -44,7 +44,7 @@ if (!$SkipWheels) {
}
# 3. 传入远端并安装。
$payload = @($modelTar, (Join-Path $PSScriptRoot 'windows\install-d3nano.ps1'), (Join-Path $PSScriptRoot 'windows\register-d3nano-task.ps1'), (Join-Path $PSScriptRoot 'windows\d3nano-service.py'), (Join-Path $PSScriptRoot 'windows\probe-d3nano.py'))
$payload = @($modelTar, (Join-Path $PSScriptRoot 'windows\install-d3nano.ps1'), (Join-Path $PSScriptRoot 'windows\d3nano-service.py'), (Join-Path $PSScriptRoot 'windows\probe-d3nano.py'))
if ($wheelsTar) { $payload += $wheelsTar }
& ssh -o BatchMode=yes $Target "New-Item -ItemType Directory -Force -Path $InstallRoot, $WheelsRemote, $InstallRoot\benchmark | Out-Null"
if ($LASTEXITCODE) { throw 'SSH failed' }
@ -60,12 +60,10 @@ if ($wheelsTar) {
& ssh -o BatchMode=yes $Target "powershell -NoProfile -ExecutionPolicy Bypass -File $InstallRoot\install-d3nano.ps1 -InstallRoot $InstallRoot -WheelsDir $WheelsRemote"
if ($LASTEXITCODE) { throw '安装 d3-nano 失败' }
# 4. 注册开机自启的计划任务承载服务,并实机验证(真实相机 JPEG + noul 请求)。
# 4. 在同一 SSH 会话中临时启动并验收,完成后释放模型。日常服务由桌面程序直接拉起。
$venvPython = Join-Path $InstallRoot '.venv\Scripts\python.exe'
if (!$SkipStart) {
& ssh -o BatchMode=yes $Target "powershell -NoProfile -ExecutionPolicy Bypass -File $InstallRoot\register-d3nano-task.ps1 -InstallRoot $InstallRoot -Port $Port -Script $ServiceScript"
if ($LASTEXITCODE) { throw 'd3-nano 计划任务注册或启动失败' }
& ssh -o BatchMode=yes $Target "$venvPython $InstallRoot\d3nano-service.py probe --root $InstallRoot --port $Port --image-root $InstallRoot\benchmark"
& ssh -o BatchMode=yes $Target "$venvPython $InstallRoot\d3nano-service.py verify --root $InstallRoot --port $Port --script $ServiceScript --image-root $InstallRoot\benchmark"
if ($LASTEXITCODE) { throw 'd3-nano 真实图片请求验证失败' }
}
Write-Host "已部署 d3-nano 到 $Target:$InstallRoot;SOPHELPER_D3_ROOT 已写入系统环境变量。"

View File

@ -42,9 +42,12 @@ def nvidia_memory():
return {"nvidia_smi": out}
def start(root, port, script, log_dir):
def start(root, port, script, log_dir, verify=None):
"""验收模式在同一会话持有测试进程;复用已有服务时只做验证。"""
state = health(port)
if state.get("ready"):
if verify:
verify()
return {"action": "reuse", "health": state}
python = Path(root) / ".venv" / "Scripts" / "python.exe"
if not python.exists():
@ -60,17 +63,26 @@ def start(root, port, script, log_dir):
process = subprocess.Popen([str(python), "-u", str(script), "--root", str(root), "--port", str(port),
"--log-dir", str(log_dir)], cwd=str(root), stdout=stdout, stderr=stderr,
stdin=subprocess.DEVNULL, creationflags=creationflags, close_fds=True)
(Path(root) / "server.pid").write_text(str(process.pid), encoding="ascii")
deadline = time.monotonic() + HEALTH_TIMEOUT_SECONDS
last = {"status": "starting"}
while time.monotonic() < deadline:
last = health(port)
if last.get("ready"):
return {"action": "started", "pid": process.pid, "health": last, "logs": str(log_dir)}
if process.poll() is not None:
raise SystemExit(f"d3-nano 启动失败,退出码 {process.returncode},日志:{log_dir}")
time.sleep(2)
raise SystemExit(f"等待 d3-nano 就绪超时({HEALTH_TIMEOUT_SECONDS}s),日志:{log_dir},最后状态:{last}")
try:
if verify is None:
(Path(root) / "server.pid").write_text(str(process.pid), encoding="ascii")
deadline = time.monotonic() + HEALTH_TIMEOUT_SECONDS
last = {"status": "starting"}
while time.monotonic() < deadline:
last = health(port)
if last.get("ready"):
if verify:
verify()
return {"action": "started", "pid": process.pid, "health": last, "logs": str(log_dir)}
if process.poll() is not None:
raise SystemExit(f"d3-nano 启动失败,退出码 {process.returncode},日志:{log_dir}")
time.sleep(2)
raise SystemExit(f"等待 d3-nano 就绪超时({HEALTH_TIMEOUT_SECONDS}s),日志:{log_dir},最后状态:{last}")
finally:
# 仅回收本次验收创建的进程树,包含 Windows 虚拟环境派生的 Python 子进程。
if verify and process.poll() is None:
subprocess.run(["taskkill", "/pid", str(process.pid), "/t", "/f"], check=True)
process.wait(timeout=10)
def probe(port, image_root, repeat):
@ -102,7 +114,7 @@ def serve(root, port, script, log_dir):
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["serve", "start", "status", "probe"])
parser.add_argument("command", choices=["serve", "start", "status", "probe", "verify"])
parser.add_argument("--root", default=r"D:\D3Nano")
parser.add_argument("--port", type=int, default=8766)
parser.add_argument("--script", default=r"C:\sophelper\current\services\start_d3_lite_local.py")
@ -116,6 +128,9 @@ def main():
return
if args.command == "start":
report = start(args.root, args.port, args.script, log_dir)
elif args.command == "verify":
report = start(args.root, args.port, args.script, log_dir,
lambda: probe(args.port, args.image_root, args.repeat))
elif args.command == "status":
report = {"health": health(args.port), "pid_file": (Path(args.root) / "server.pid").read_text(encoding="ascii")
if (Path(args.root) / "server.pid").exists() else None}

View File

@ -62,7 +62,7 @@ if (!$SkipVenv) {
if ($LASTEXITCODE) { throw "解压 wheel 包失败: $WheelsTar" }
}
if (!(Test-Path -LiteralPath $WheelsDir)) { throw "缺少 wheel 目录: $WheelsDir" }
& $python -m pip install --no-index --find-links $WheelsDir --no-warn-script-location torch torchvision transformers accelerate safetensors huggingface_hub pillow
& $python -m pip install --no-index --find-links $WheelsDir --no-warn-script-location torch torchvision transformers accelerate safetensors huggingface_hub pillow "psutil>=6"
if ($LASTEXITCODE) { throw '离线安装 d3-nano 依赖失败' }
}
if (!(Test-Path -LiteralPath $python)) { throw "缺少虚拟环境解释器: $python" }
@ -94,6 +94,12 @@ print(json.dumps({
if ($LASTEXITCODE) { throw 'd3-nano 运行环境校验失败' }
Remove-Item -LiteralPath $verify -Force
# 迁移旧工位的开机/登录自启;仅禁用本安装目录对应的旧任务,下次正常关闭由桌面端回收进程。
$legacy = Get-ScheduledTask -TaskName 'SopHelper d3-nano' -TaskPath '\' -ErrorAction SilentlyContinue
if ($legacy -and $legacy.Actions.Execute -eq $python -and $legacy.Actions.Arguments -like '*d3nano-service.py* serve *') {
$legacy | Disable-ScheduledTask -ErrorAction Stop | Out-Null
}
Write-Output (ConvertTo-Json -InputObject ([ordered]@{
installed = $InstallRoot
python = $python

View File

@ -1,48 +0,0 @@
param(
[string]$InstallRoot = 'D:\D3Nano',
[int]$Port = 8766,
[string]$Script = 'C:\sophelper\current\services\start_d3_lite_local.py',
[string]$TaskName = 'SopHelper d3-nano',
[int]$StartNow = 1
)
# 把 d3-nano 注册为开机自启计划任务:SSH 会话里用分离进程启动的服务会随会话被作业对象回收,
# 计划任务由 Task Scheduler 服务承载,服务才能常驻,桌面程序启动时直接复用。
$ErrorActionPreference = 'Stop'
$python = Join-Path $InstallRoot '.venv\Scripts\python.exe'
$helper = Join-Path $InstallRoot 'd3nano-service.py'
foreach ($required in @($python, $helper)) {
if (!(Test-Path -LiteralPath $required)) { throw "缺少文件: $required" }
}
$argument = '-u "' + $helper + '" serve --root "' + $InstallRoot + '" --port ' + $Port + ' --script "' + $Script + '"'
$action = New-ScheduledTaskAction -Execute $python -Argument $argument -WorkingDirectory $InstallRoot
$trigger = @((New-ScheduledTaskTrigger -AtStartup), (New-ScheduledTaskTrigger -AtLogOn -User 'Administrator'))
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable `
-ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -Priority 7 `
-RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$description = 'SopHelper d3-nano 判定服务(djev),监听 127.0.0.1:' + $Port
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal `
-Description $description -Force | Out-Null
Write-Output ('已注册计划任务: ' + $TaskName)
if ($StartNow) {
Start-ScheduledTask -TaskName $TaskName
$deadline = [DateTime]::UtcNow.AddSeconds(300)
$ready = $false
while ([DateTime]::UtcNow -lt $deadline) {
try {
$health = Invoke-RestMethod -Uri ('http://127.0.0.1:' + $Port + '/health') -TimeoutSec 3
if ($health.status -eq 'ready' -and $health.model -in @('d3-lite', 'd3-nano') -and 'image' -in $health.modalities) { $ready = $true; break }
} catch { }
Start-Sleep -Seconds 3
}
$state = (Get-ScheduledTask -TaskName $TaskName).State
$info = (Get-ScheduledTaskInfo -TaskName $TaskName)
if (!$ready) {
Write-Output ('任务状态=' + $state + ' 上次结果=' + $info.LastTaskResult + ' 日志=' + (Join-Path $InstallRoot 'logs'))
throw '等待 d3-nano 就绪超时'
}
Write-Output ('d3-nano 就绪:' + ($health | ConvertTo-Json -Compress -Depth 6))
}
$task = Get-ScheduledTaskInfo -TaskName $TaskName
Write-Output (ConvertTo-Json -InputObject ([ordered]@{ task = $TaskName; state = (Get-ScheduledTask -TaskName $TaskName).State;
lastTaskResult = $task.LastTaskResult; numberOfRuns = $task.NumberOfRuns }) -Compress)