fix: harden Windows service installation CI

This commit is contained in:
Christ committed 2026-08-13 13:40:44 +08:00
1 parent ac85ac8a0a
commit 1c8e2ab163
4 files changed
+404 -41

No files matched your search

+113 -2
View File
@@ -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;
+120 -31
View File
@@ -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
}
}
}