fix: harden Windows service installation CI
This commit is contained in:
1 parent
ac85ac8a0a
commit
1c8e2ab163
4 files changed
+404
-41
No files matched your search
@@ -4,6 +4,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
- codex/desktop-packaging
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
@@ -255,6 +256,81 @@ jobs:
|
||||
Select-Object -First 1
|
||||
if ($null -eq $chromium) { throw 'Windows Chromium runtime 缺少 Chromium 可执行文件' }
|
||||
|
||||
- name: 实际验证 Windows 服务注册
|
||||
shell: pwsh
|
||||
run: |
|
||||
$serviceName = 'YdisksXianyuHelper'
|
||||
$workDir = Join-Path $env:RUNNER_TEMP $serviceName
|
||||
$runtimeRoot = (Resolve-Path 'dist/windows/playwright-runtime/amd64').Path
|
||||
$serviceScript = (Resolve-Path 'packaging/windows/service-control.ps1').Path
|
||||
$serverPath = (Resolve-Path 'dist/windows/xianyu-server.exe').Path
|
||||
try {
|
||||
foreach ($registerAttempt in 1..2) {
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||
-File $serviceScript -Mode register -ServiceName $serviceName `
|
||||
-ExePath $serverPath -WorkDir $workDir -RuntimeRoot $runtimeRoot
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Windows 服务第 $registerAttempt 次注册失败,错误码: $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||
-File $serviceScript -Mode start -ServiceName $serviceName
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows 服务启动失败,错误码: $LASTEXITCODE" }
|
||||
|
||||
$service = Get-Service -Name $serviceName -ErrorAction Stop
|
||||
$serviceStatus = $service.Status
|
||||
$service.Dispose()
|
||||
if ($serviceStatus -ne [System.ServiceProcess.ServiceControllerStatus]::Running) {
|
||||
throw "Windows 服务未进入运行状态: $serviceStatus"
|
||||
}
|
||||
|
||||
$serviceConfig = Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction Stop
|
||||
if ($null -eq $serviceConfig) { throw 'Windows 服务注册后无法读取配置' }
|
||||
if (-not $serviceConfig.PathName.Contains(('"{0}"' -f $serverPath)) -or
|
||||
-not $serviceConfig.PathName.Contains('-service') -or
|
||||
-not $serviceConfig.PathName.Contains(('-workdir "{0}"' -f $workDir)) -or
|
||||
-not $serviceConfig.PathName.Contains(('-playwright-runtime-root "{0}"' -f $runtimeRoot))) {
|
||||
throw "Windows 服务命令行不正确: $($serviceConfig.PathName)"
|
||||
}
|
||||
$delayedStart = Get-ItemPropertyValue `
|
||||
-LiteralPath "Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\$serviceName" `
|
||||
-Name DelayedAutostart -ErrorAction Stop
|
||||
if ($delayedStart -ne 1) { throw "Windows 服务未配置延迟自动启动: $delayedStart" }
|
||||
$sddl = (& "$env:SystemRoot\System32\sc.exe" sdshow $serviceName 2>&1) -join ''
|
||||
if ($LASTEXITCODE -ne 0 -or -not $sddl.Contains('(A;;LCRPWP;;;IU)')) {
|
||||
throw "Windows 服务未授予交互用户启停权限: $sddl"
|
||||
}
|
||||
|
||||
$health = $null
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(60)
|
||||
while ([DateTime]::UtcNow -lt $deadline -and $null -eq $health) {
|
||||
try {
|
||||
$health = Invoke-RestMethod -Uri 'http://127.0.0.1:59188/health' -TimeoutSec 2
|
||||
} catch {
|
||||
Start-Sleep -Seconds 1
|
||||
}
|
||||
}
|
||||
if ($null -eq $health -or $health.status -ne 'ok' -or $health.database -ne 'ok') {
|
||||
throw "Windows 服务健康检查失败: $($health | ConvertTo-Json -Compress)"
|
||||
}
|
||||
} catch {
|
||||
$serverLog = Join-Path $workDir 'logs\server.log'
|
||||
if (Test-Path -LiteralPath $serverLog) {
|
||||
Get-Content -LiteralPath $serverLog -Tail 200
|
||||
}
|
||||
throw
|
||||
} finally {
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||
-File $serviceScript -Mode uninstall -ServiceName $serviceName
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows 服务清理失败,错误码: $LASTEXITCODE" }
|
||||
if ($null -ne (Get-Service -Name $serviceName -ErrorAction SilentlyContinue)) {
|
||||
throw 'Windows 服务卸载后仍然存在'
|
||||
}
|
||||
}
|
||||
|
||||
- name: 保存 Windows Chromium runtime 缓存
|
||||
if: steps.cache-windows-playwright.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v5
|
||||
@@ -309,20 +385,96 @@ jobs:
|
||||
-PfxPath $env:WINDOWS_SIGNING_PFX_PATH `
|
||||
-Files 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe'
|
||||
|
||||
- name: 打包 Windows 二进制归档
|
||||
- name: 使用安装器验证服务安装与卸载
|
||||
shell: pwsh
|
||||
env:
|
||||
APP_VERSION: ${{ env.APP_VERSION }}
|
||||
run: |
|
||||
Compress-Archive -Path dist/windows/xianyu-server.exe,dist/windows/xianyu-tray.exe,dist/windows/playwright-runtime -DestinationPath "dist/windows/Ydisks-Xianyu-Helper-${env:APP_VERSION}-binaries.zip"
|
||||
$serviceName = 'YdisksXianyuHelper'
|
||||
$installer = (Resolve-Path 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe').Path
|
||||
$installLog = Join-Path $env:RUNNER_TEMP 'ydisks-windows-installer.log'
|
||||
$installDir = Join-Path $env:ProgramFiles 'Ydisks Xianyu Helper'
|
||||
$uninstaller = Join-Path $installDir 'unins000.exe'
|
||||
try {
|
||||
& $installer /VERYSILENT /SUPPRESSMSGBOXES /NORESTART "/LOG=$installLog"
|
||||
$installerExitCode = $LASTEXITCODE
|
||||
if ($installerExitCode -ne 0) {
|
||||
if (Test-Path -LiteralPath $installLog) {
|
||||
Get-Content -LiteralPath $installLog -Tail 200
|
||||
}
|
||||
throw "Windows 安装器执行失败,错误码: $installerExitCode"
|
||||
}
|
||||
|
||||
$service = Get-Service -Name $serviceName -ErrorAction Stop
|
||||
$serviceStatus = $service.Status
|
||||
$service.Dispose()
|
||||
if ($serviceStatus -ne [System.ServiceProcess.ServiceControllerStatus]::Running) {
|
||||
throw "安装器未启动 Windows 服务: $serviceStatus"
|
||||
}
|
||||
|
||||
$expectedServer = Join-Path $installDir 'xianyu-server.exe'
|
||||
$expectedRuntime = Join-Path $installDir 'playwright-runtime'
|
||||
$serviceConfig = Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction Stop
|
||||
if ($null -eq $serviceConfig -or
|
||||
-not $serviceConfig.PathName.Contains(('"{0}"' -f $expectedServer)) -or
|
||||
-not $serviceConfig.PathName.Contains(('-playwright-runtime-root "{0}"' -f $expectedRuntime))) {
|
||||
throw "安装器注册的服务命令行不正确: $($serviceConfig.PathName)"
|
||||
}
|
||||
|
||||
$health = $null
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(60)
|
||||
while ([DateTime]::UtcNow -lt $deadline -and $null -eq $health) {
|
||||
try {
|
||||
$health = Invoke-RestMethod -Uri 'http://127.0.0.1:59188/health' -TimeoutSec 2
|
||||
} catch {
|
||||
Start-Sleep -Seconds 1
|
||||
}
|
||||
}
|
||||
if ($null -eq $health -or $health.status -ne 'ok' -or $health.database -ne 'ok') {
|
||||
throw "安装器服务健康检查失败: $($health | ConvertTo-Json -Compress)"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $uninstaller -PathType Leaf)) {
|
||||
throw "Windows 卸载器不存在: $uninstaller"
|
||||
}
|
||||
} catch {
|
||||
if (Test-Path -LiteralPath $installLog) {
|
||||
Get-Content -LiteralPath $installLog -Tail 200
|
||||
}
|
||||
$serverLog = Join-Path $env:ProgramData 'YdisksXianyuHelper\logs\server.log'
|
||||
if (Test-Path -LiteralPath $serverLog) {
|
||||
Get-Content -LiteralPath $serverLog -Tail 200
|
||||
}
|
||||
throw
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $uninstaller -PathType Leaf) {
|
||||
& $uninstaller /VERYSILENT /SUPPRESSMSGBOXES /NORESTART
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows 卸载器执行失败,错误码: $LASTEXITCODE" }
|
||||
} elseif ($null -ne (Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction SilentlyContinue)) {
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||
-File (Resolve-Path 'packaging/windows/service-control.ps1') `
|
||||
-Mode uninstall -ServiceName $serviceName
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows 服务兜底清理失败,错误码: $LASTEXITCODE" }
|
||||
}
|
||||
if ($null -ne (Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction SilentlyContinue)) {
|
||||
throw 'Windows 安装器卸载后服务仍然存在'
|
||||
}
|
||||
}
|
||||
|
||||
- name: 准备唯一 Windows 构建产物
|
||||
shell: pwsh
|
||||
run: |
|
||||
$artifactDir = 'dist/windows-artifact'
|
||||
New-Item -ItemType Directory -Force -Path $artifactDir | Out-Null
|
||||
Copy-Item -LiteralPath 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe' -Destination $artifactDir
|
||||
$artifactFiles = @(Get-ChildItem -LiteralPath $artifactDir -Recurse -File)
|
||||
if ($artifactFiles.Count -ne 1 -or $artifactFiles[0].Name -ne 'Ydisks-Xianyu-Helper-Setup.exe') {
|
||||
throw "Windows 构建产物必须且只能包含安装器: $($artifactFiles.FullName -join ', ')"
|
||||
}
|
||||
|
||||
- name: 上传 Windows 安装包
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ydisks-xianyu-helper-windows-${{ env.APP_VERSION }}
|
||||
path: |
|
||||
dist/windows/Ydisks-Xianyu-Helper-Setup.exe
|
||||
dist/windows/Ydisks-Xianyu-Helper-${{ env.APP_VERSION }}-binaries.zip
|
||||
path: dist/windows-artifact/Ydisks-Xianyu-Helper-Setup.exe
|
||||
if-no-files-found: error
|
||||
|
||||
macos:
|
||||
@@ -510,9 +662,10 @@ jobs:
|
||||
test -f "dist/release/ydisks-xianyu-helper-linux-amd64-${{ needs.prepare.outputs.app_version }}.tar.gz"
|
||||
test -f "dist/release/ydisks-xianyu-helper-linux-arm64-${{ needs.prepare.outputs.app_version }}.tar.gz"
|
||||
test -f "dist/release/Ydisks-Xianyu-Helper-Setup.exe"
|
||||
test -f "dist/release/Ydisks-Xianyu-Helper-${{ needs.prepare.outputs.app_version }}-binaries.zip"
|
||||
test -f "dist/release/Ydisks-Xianyu-Helper-${{ needs.prepare.outputs.app_version }}-arm64.pkg"
|
||||
test -f "dist/release/Ydisks-Xianyu-Helper-${{ needs.prepare.outputs.app_version }}-amd64.pkg"
|
||||
test "$(find dist/release -maxdepth 1 -type f | wc -l)" -eq 5
|
||||
test -z "$(find dist/release -maxdepth 1 -type f -name '*.zip' -print -quit)"
|
||||
(
|
||||
cd dist/release
|
||||
sha256sum * > SHA256SUMS
|
||||
@@ -527,6 +680,13 @@ jobs:
|
||||
set -Eeuo pipefail
|
||||
mapfile -t release_files < <(find dist/release -maxdepth 1 -type f -print | sort)
|
||||
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
|
||||
while IFS= read -r asset_name; do
|
||||
case "$asset_name" in
|
||||
Ydisks-Xianyu-Helper-*-binaries.zip)
|
||||
gh release delete-asset "$GITHUB_REF_NAME" "$asset_name" --yes
|
||||
;;
|
||||
esac
|
||||
done < <(gh release view "$GITHUB_REF_NAME" --json assets --jq '.assets[].name')
|
||||
gh release upload "$GITHUB_REF_NAME" "${release_files[@]}" --clobber
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" "${release_files[@]}" \
|
||||
|
||||
@@ -37,6 +37,9 @@ func serviceAction(action string) error {
|
||||
if action == "stop" && errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
|
||||
return fmt.Errorf("Windows 服务 %s 尚未安装,请重新运行安装器", name)
|
||||
}
|
||||
if errors.Is(err, windows.ERROR_ACCESS_DENIED) {
|
||||
return fmt.Errorf("没有控制 Windows 服务的权限,请重新安装当前版本以更新服务权限")
|
||||
}
|
||||
|
||||
@@ -37,13 +37,27 @@ Name: "{#AppDataDir}\logs"; Permissions: users-modify
|
||||
Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; ValueName: "YdisksXianyuHelperTray"; ValueData: """{app}\xianyu-tray.exe"""; Flags: uninsdeletevalue
|
||||
|
||||
[Run]
|
||||
Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ""{app}\service-control.ps1"" -Mode install -ExePath ""{app}\xianyu-server.exe"" -TrayPath ""{app}\xianyu-tray.exe"" -WorkDir ""{#AppDataDir}"" -RuntimeRoot ""{app}\playwright-runtime"""; Flags: runhidden waituntilterminated
|
||||
Filename: "{app}\xianyu-tray.exe"; Description: "启动菜单栏控制器"; Flags: nowait postinstall skipifsilent runasoriginaluser
|
||||
Filename: "{app}\xianyu-tray.exe"; Description: "启动菜单栏控制器"; Flags: nowait postinstall skipifsilent runasoriginaluser; Check: ServiceStartedSuccessfully
|
||||
|
||||
[UninstallRun]
|
||||
Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ""{app}\service-control.ps1"" -Mode uninstall -TrayPath ""{app}\xianyu-tray.exe"""; Flags: runhidden waituntilterminated
|
||||
|
||||
[Code]
|
||||
var
|
||||
ServiceRegistered: Boolean;
|
||||
ServiceStartFailed: Boolean;
|
||||
InstallationCompleted: Boolean;
|
||||
|
||||
function ServiceScriptParameters(const ScriptPath, Mode: String): String;
|
||||
begin
|
||||
Result := '-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "' +
|
||||
ScriptPath + '" -Mode ' + Mode +
|
||||
' -ExePath "' + ExpandConstant('{app}\xianyu-server.exe') +
|
||||
'" -TrayPath "' + ExpandConstant('{app}\xianyu-tray.exe') +
|
||||
'" -WorkDir "' + ExpandConstant('{commonappdata}\YdisksXianyuHelper') +
|
||||
'" -RuntimeRoot "' + ExpandConstant('{app}\playwright-runtime') + '"';
|
||||
end;
|
||||
|
||||
function PrepareToInstall(var NeedsRestart: Boolean): String;
|
||||
var
|
||||
ResultCode: Integer;
|
||||
@@ -61,3 +75,100 @@ begin
|
||||
else if ResultCode <> 0 then
|
||||
Result := '旧版后台服务停止失败,错误码:' + IntToStr(ResultCode) + '。';
|
||||
end;
|
||||
|
||||
procedure RegisterWindowsService;
|
||||
var
|
||||
ResultCode: Integer;
|
||||
PowerShellPath: String;
|
||||
Parameters: String;
|
||||
begin
|
||||
PowerShellPath := ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe');
|
||||
Parameters := ServiceScriptParameters(
|
||||
ExpandConstant('{tmp}\service-control.ps1'), 'register') +
|
||||
' -CreatedMarkerPath "' + ExpandConstant('{tmp}\service-created.marker') + '"';
|
||||
|
||||
if not Exec(PowerShellPath, Parameters, '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then
|
||||
begin
|
||||
Log('Unable to execute Windows service registration script.');
|
||||
SuppressibleMsgBox(
|
||||
'无法执行 Windows 服务注册脚本。请以管理员身份重新运行安装器。',
|
||||
mbError, MB_OK, IDOK);
|
||||
Abort;
|
||||
end;
|
||||
if ResultCode <> 0 then
|
||||
begin
|
||||
Log('Windows service registration failed, result code: ' + IntToStr(ResultCode));
|
||||
SuppressibleMsgBox(
|
||||
'Windows 服务注册失败(错误码:' + IntToStr(ResultCode) + ')。',
|
||||
mbError, MB_OK, IDOK);
|
||||
Abort;
|
||||
end;
|
||||
ServiceRegistered := True;
|
||||
end;
|
||||
|
||||
procedure StartWindowsService;
|
||||
var
|
||||
ResultCode: Integer;
|
||||
PowerShellPath: String;
|
||||
Parameters: String;
|
||||
begin
|
||||
PowerShellPath := ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe');
|
||||
Parameters := ServiceScriptParameters(
|
||||
ExpandConstant('{app}\service-control.ps1'), 'start');
|
||||
|
||||
ServiceStartFailed :=
|
||||
(not Exec(PowerShellPath, Parameters, '', SW_HIDE,
|
||||
ewWaitUntilTerminated, ResultCode)) or (ResultCode <> 0);
|
||||
if ServiceStartFailed then
|
||||
begin
|
||||
Log('Windows service failed to start, result code: ' + IntToStr(ResultCode));
|
||||
SuppressibleMsgBox(
|
||||
'Windows 后台服务未能启动(错误码:' + IntToStr(ResultCode) +
|
||||
')。安装器将返回失败,请查看安装日志。',
|
||||
mbError, MB_OK, IDOK);
|
||||
end;
|
||||
end;
|
||||
|
||||
procedure CleanupCreatedWindowsService;
|
||||
var
|
||||
ResultCode: Integer;
|
||||
ScriptPath: String;
|
||||
begin
|
||||
if not FileExists(ExpandConstant('{tmp}\service-created.marker')) then
|
||||
exit;
|
||||
ScriptPath := ExpandConstant('{tmp}\service-control.ps1');
|
||||
if FileExists(ScriptPath) then
|
||||
Exec(
|
||||
ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
|
||||
ServiceScriptParameters(ScriptPath, 'uninstall'),
|
||||
'', SW_HIDE, ewWaitUntilTerminated, ResultCode);
|
||||
end;
|
||||
|
||||
function ServiceStartedSuccessfully: Boolean;
|
||||
begin
|
||||
Result := ServiceRegistered and (not ServiceStartFailed);
|
||||
end;
|
||||
|
||||
function GetCustomSetupExitCode: Integer;
|
||||
begin
|
||||
if ServiceStartFailed then
|
||||
Result := 1001
|
||||
else
|
||||
Result := 0;
|
||||
end;
|
||||
|
||||
procedure CurStepChanged(CurStep: TSetupStep);
|
||||
begin
|
||||
if CurStep = ssInstall then
|
||||
RegisterWindowsService
|
||||
else if CurStep = ssPostInstall then
|
||||
StartWindowsService
|
||||
else if CurStep = ssDone then
|
||||
InstallationCompleted := True;
|
||||
end;
|
||||
|
||||
procedure DeinitializeSetup;
|
||||
begin
|
||||
if not InstallationCompleted then
|
||||
CleanupCreatedWindowsService;
|
||||
end;
|
||||
@@ -1,13 +1,14 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateSet('stop', 'install', 'uninstall')]
|
||||
[ValidateSet('stop', 'register', 'start', 'install', 'uninstall')]
|
||||
[string]$Mode,
|
||||
|
||||
[string]$ServiceName = 'YdisksXianyuHelper',
|
||||
[string]$ExePath = '',
|
||||
[string]$TrayPath = '',
|
||||
[string]$WorkDir = '',
|
||||
[string]$RuntimeRoot = ''
|
||||
[string]$RuntimeRoot = '',
|
||||
[string]$CreatedMarkerPath = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -16,17 +17,30 @@ function Get-InstalledService {
|
||||
Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
function Test-ServiceInstalled {
|
||||
$service = Get-InstalledService
|
||||
if ($null -eq $service) {
|
||||
return $false
|
||||
}
|
||||
$service.Dispose()
|
||||
return $true
|
||||
}
|
||||
|
||||
function Stop-InstalledService {
|
||||
$service = Get-InstalledService
|
||||
if ($null -eq $service) {
|
||||
return
|
||||
}
|
||||
if ($service.Status -ne [System.ServiceProcess.ServiceControllerStatus]::Stopped) {
|
||||
Stop-Service -Name $ServiceName -ErrorAction Stop
|
||||
$service.WaitForStatus(
|
||||
[System.ServiceProcess.ServiceControllerStatus]::Stopped,
|
||||
[TimeSpan]::FromSeconds(30)
|
||||
)
|
||||
try {
|
||||
if ($service.Status -ne [System.ServiceProcess.ServiceControllerStatus]::Stopped) {
|
||||
Stop-Service -Name $ServiceName -ErrorAction Stop
|
||||
$service.WaitForStatus(
|
||||
[System.ServiceProcess.ServiceControllerStatus]::Stopped,
|
||||
[TimeSpan]::FromSeconds(30)
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
$service.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +74,16 @@ function Stop-InstalledComponents {
|
||||
Stop-InstalledService
|
||||
}
|
||||
|
||||
function Wait-ServiceDeleted {
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(30)
|
||||
while (Test-ServiceInstalled) {
|
||||
if ([DateTime]::UtcNow -ge $deadline) {
|
||||
throw "等待 Windows 服务 $ServiceName 删除超时"
|
||||
}
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-ScChecked {
|
||||
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Arguments)
|
||||
|
||||
@@ -97,38 +121,103 @@ function Grant-InteractiveUserServiceControl {
|
||||
Invoke-ScChecked sdset $ServiceName $updatedSddl
|
||||
}
|
||||
|
||||
function Assert-ServiceInstallParameters {
|
||||
if ([string]::IsNullOrWhiteSpace($ExePath) -or
|
||||
[string]::IsNullOrWhiteSpace($WorkDir) -or
|
||||
[string]::IsNullOrWhiteSpace($RuntimeRoot)) {
|
||||
throw '安装服务缺少 ExePath、WorkDir 或 RuntimeRoot'
|
||||
}
|
||||
}
|
||||
|
||||
function Register-InstalledService {
|
||||
Assert-ServiceInstallParameters
|
||||
Stop-InstalledComponents
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $WorkDir | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $WorkDir 'data') | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $WorkDir 'logs') | Out-Null
|
||||
|
||||
$binaryPath = '"{0}" -service -workdir "{1}" -data-key-file "{1}\data-key" -addr 127.0.0.1:59188 -playwright-runtime-root "{2}"' -f `
|
||||
$ExePath, $WorkDir, $RuntimeRoot
|
||||
if (-not (Test-ServiceInstalled)) {
|
||||
if (-not [string]::IsNullOrWhiteSpace($CreatedMarkerPath)) {
|
||||
Set-Content -LiteralPath $CreatedMarkerPath -Value $ServiceName -Encoding ASCII
|
||||
}
|
||||
New-Service -Name $ServiceName `
|
||||
-BinaryPathName $binaryPath `
|
||||
-DisplayName 'Ydisks Xianyu Helper' `
|
||||
-StartupType Automatic `
|
||||
-ErrorAction Stop | Out-Null
|
||||
} else {
|
||||
Invoke-ScChecked config $ServiceName 'binPath=' $binaryPath
|
||||
}
|
||||
|
||||
Invoke-ScChecked config $ServiceName 'start=' 'delayed-auto'
|
||||
Invoke-ScChecked description $ServiceName 'Ydisks Xianyu Helper background service'
|
||||
Grant-InteractiveUserServiceControl
|
||||
|
||||
if (-not (Test-ServiceInstalled)) {
|
||||
throw "Windows 服务 $ServiceName 注册后无法查询"
|
||||
}
|
||||
}
|
||||
|
||||
function Start-InstalledService {
|
||||
$service = Get-InstalledService
|
||||
if ($null -eq $service) {
|
||||
throw "Windows 服务 $ServiceName 尚未注册"
|
||||
}
|
||||
|
||||
try {
|
||||
if ($service.Status -eq [System.ServiceProcess.ServiceControllerStatus]::StopPending) {
|
||||
$service.WaitForStatus(
|
||||
[System.ServiceProcess.ServiceControllerStatus]::Stopped,
|
||||
[TimeSpan]::FromSeconds(30)
|
||||
)
|
||||
$service.Refresh()
|
||||
}
|
||||
if ($service.Status -eq [System.ServiceProcess.ServiceControllerStatus]::StartPending) {
|
||||
$service.WaitForStatus(
|
||||
[System.ServiceProcess.ServiceControllerStatus]::Running,
|
||||
[TimeSpan]::FromSeconds(30)
|
||||
)
|
||||
$service.Refresh()
|
||||
}
|
||||
if ($service.Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running) {
|
||||
Start-Service -Name $ServiceName -ErrorAction Stop
|
||||
$service.Refresh()
|
||||
$service.WaitForStatus(
|
||||
[System.ServiceProcess.ServiceControllerStatus]::Running,
|
||||
[TimeSpan]::FromSeconds(30)
|
||||
)
|
||||
$service.Refresh()
|
||||
}
|
||||
if ($service.Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running) {
|
||||
throw "Windows 服务 $ServiceName 未进入运行状态: $($service.Status)"
|
||||
}
|
||||
} finally {
|
||||
$service.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
switch ($Mode) {
|
||||
'stop' {
|
||||
Stop-InstalledComponents
|
||||
}
|
||||
'register' {
|
||||
Register-InstalledService
|
||||
}
|
||||
'start' {
|
||||
Start-InstalledService
|
||||
}
|
||||
'install' {
|
||||
if ([string]::IsNullOrWhiteSpace($ExePath) -or
|
||||
[string]::IsNullOrWhiteSpace($WorkDir) -or
|
||||
[string]::IsNullOrWhiteSpace($RuntimeRoot)) {
|
||||
throw '安装服务缺少 ExePath、WorkDir 或 RuntimeRoot'
|
||||
}
|
||||
|
||||
Stop-InstalledComponents
|
||||
$binaryPath = '"{0}" -service -workdir "{1}" -data-key-file "{1}\data-key" -addr 127.0.0.1:59188 -playwright-runtime-root "{2}"' -f `
|
||||
$ExePath, $WorkDir, $RuntimeRoot
|
||||
if ($null -eq (Get-InstalledService)) {
|
||||
Invoke-ScChecked create $ServiceName 'binPath=' $binaryPath 'start=' 'delayed-auto'
|
||||
} else {
|
||||
Invoke-ScChecked config $ServiceName 'binPath=' $binaryPath 'start=' 'delayed-auto'
|
||||
}
|
||||
Invoke-ScChecked description $ServiceName 'Ydisks闲鱼助手后台服务'
|
||||
Grant-InteractiveUserServiceControl
|
||||
|
||||
Start-Service -Name $ServiceName -ErrorAction Stop
|
||||
(Get-Service -Name $ServiceName).WaitForStatus(
|
||||
[System.ServiceProcess.ServiceControllerStatus]::Running,
|
||||
[TimeSpan]::FromSeconds(30)
|
||||
)
|
||||
Register-InstalledService
|
||||
Start-InstalledService
|
||||
}
|
||||
'uninstall' {
|
||||
Stop-InstalledComponents
|
||||
if ($null -ne (Get-InstalledService)) {
|
||||
if (Test-ServiceInstalled) {
|
||||
Invoke-ScChecked delete $ServiceName
|
||||
Wait-ServiceDeleted
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user