Files
mxaccessgw/scripts/deploy/Install-MxGatewayService.ps1
T
Joseph Doherty 477fa55998
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m26s
ci / java (push) Successful in 2m12s
ci / portable (push) Failing after 4m11s
feat(deploy): on-box NSSM upgrade/rollback and new-box install scripts, runbook updated (mxaccessgw#220)
Add scripts/deploy/Upgrade-MxGatewayService.ps1 (preflight, stop with STOP_PENDING handling,
backup, Server+Worker swap, start, /health/ready + SHA verify, auto/manual rollback,
one-gateway guard, never touches the NSSM env block) and Install-MxGatewayService.ps1
(service install, restart/recovery settings, env block). Both support -DryRun/-WhatIf.
Dry-run validated on macOS pwsh against a fake layout; untested on a real box.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 15:10:26 -05:00

203 lines
12 KiB
PowerShell

#requires -Version 5.1
<#
.SYNOPSIS
On-box NEW-BOX install of the MxAccess Gateway as an NSSM service (mxaccessgw#220).
Companion of Upgrade-MxGatewayService.ps1; see docs/runbooks/DeployUpgradeNssmService.md.
.DESCRIPTION
RUN ON THE WINDOWS BOX (Windows PowerShell 5.1). Creates the service ONCE, with:
* Application / AppDirectory / DisplayName / Description, auto start, account (default LocalSystem);
* NSSM exit handling: restart on any exit with a throttle, graceful-stop timeouts that cover the
Worker shutdown grace (MxGateway:Worker:ShutdownTimeoutSeconds, default 10 s);
* stdout/stderr redirection with rotation;
* Windows SCM recovery (sc failure: restart, restart, restart + reset period);
* the environment block, set in ONE `nssm set AppEnvironmentExtra` call on a service that has none
(so there is nothing to wipe). The env comes from -EnvFile (KEY=VALUE lines, # comments) and/or
-Env (hashtable); -Env wins. Secret VALUES are never printed (dry-run shows names and masks values).
It does NOT start the service unless -Start is given (review the env first), and it refuses to run if
the service already exists (use Upgrade-MxGatewayService.ps1) or if any gateway process is running
(OrphanWorkerTerminator trap: a second gateway kills live Workers).
Required env (checked by name): ZB_SECRETS_MASTER_KEY, a *Pepper* entry (MxGateway__ApiKeyPepper),
MxGateway__Worker__ExecutablePath (defaults to <WorkerDir>\ZB.MOM.WW.MxGateway.Worker.exe),
MxGateway__Authentication__SqlitePath and Secrets__SqlitePath (default under -DataDir; must be absolute and
OUTSIDE the content root, the validator is fail-closed), ASPNETCORE_ENVIRONMENT/DOTNET_ENVIRONMENT.
Kestrel endpoints default to docs/GatewayConfiguration.md's cleartext h2c :5120 + dashboard :5130 unless
the env supplies Kestrel__Endpoints__*.
-DryRun (or -WhatIf) prints every mutating action and performs none.
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)][string]$ServerDir,
[Parameter(Mandatory = $true)][string]$WorkerDir,
[string]$ServiceName = 'MxAccessGw',
[string]$NssmPath = 'nssm',
[string]$DataDir = 'C:\ProgramData\MxGateway',
[string]$LogDir,
[string]$EnvFile,
[hashtable]$Env = @{},
[string]$ServerExeName = 'ZB.MOM.WW.MxGateway.Server.exe',
[string]$ObjectName = 'LocalSystem',
[string]$ServiceAccountPassword,
[string]$EnvironmentName = 'Production',
[int]$RestartDelayMs = 5000,
[int]$ThrottleMs = 10000,
[int]$StopGraceMs = 20000,
[int]$RotateBytes = 10485760,
[switch]$Start,
[switch]$DryRun
)
$ErrorActionPreference = 'Stop'
$script:Dry = $DryRun.IsPresent -or $WhatIfPreference
$ServerProc = 'ZB.MOM.WW.MxGateway.Server'
$WorkerProc = 'ZB.MOM.WW.MxGateway.Worker'
function Say([string]$m) { Write-Host $m }
function Fail([string]$m) { throw "ABORT: $m" }
function Step([string]$Description, [scriptblock]$Action) {
if ($script:Dry) { Say "[DRYRUN] $Description"; return }
Say "[ACTION] $Description"; & $Action
}
function Invoke-Nssm {
param([string[]]$NssmArgs, [switch]$AllowFail)
$raw = & $NssmPath @NssmArgs 2>&1; $code = $LASTEXITCODE
$text = (($raw | ForEach-Object { "$_" }) -join "`n") -replace "`0", ''
if ($code -ne 0 -and -not $AllowFail) { Fail "nssm $($NssmArgs[0..1] -join ' ') failed (exit $code): $text" }
[pscustomobject]@{ Code = $code; Text = $text.Trim() }
}
function Norm([string]$p) { ($p -replace '\\', '/').TrimEnd('/') }
function Test-Rooted([string]$p) { $p -match '^[A-Za-z]:[\\/]' -or $p.StartsWith('/') -or $p.StartsWith('\\') }
function Test-Inside([string]$Path, [string]$Root) {
$a = (Norm $Path).ToLowerInvariant(); $b = (Norm $Root).ToLowerInvariant()
$a -eq $b -or $a.StartsWith("$b/")
}
function Mask([string]$k, [string]$v) {
if ($k -match 'KEY|PASSWORD|SECRET|PEPPER|TOKEN' -and $k -notmatch 'Path$|Url$') { '****' } else { $v }
}
try {
Say "Install-MxGatewayService service=$ServiceName dry=$($script:Dry)"
# --- environment assembly -------------------------------------------------------------------------
$envMap = [ordered]@{}
if ($EnvFile) {
if (-not (Test-Path -LiteralPath $EnvFile)) { Fail "-EnvFile '$EnvFile' not found" }
foreach ($line in (Get-Content -LiteralPath $EnvFile)) {
$t = $line.Trim()
if (-not $t -or $t.StartsWith('#')) { continue }
if ($t -match '^([^=\s]+)=(.*)$') { $envMap[$Matches[1]] = $Matches[2] } else { Fail "-EnvFile line is not KEY=VALUE: '$t'" }
}
}
foreach ($k in $Env.Keys) { $envMap[[string]$k] = [string]$Env[$k] }
$workerExe = Join-Path $WorkerDir "$WorkerProc.exe"
if (-not $envMap.Contains('MxGateway__Worker__ExecutablePath')) { $envMap['MxGateway__Worker__ExecutablePath'] = $workerExe }
if (-not $envMap.Contains('MxGateway__Authentication__SqlitePath')) { $envMap['MxGateway__Authentication__SqlitePath'] = Join-Path $DataDir 'gateway-auth.db' }
if (-not $envMap.Contains('Secrets__SqlitePath')) { $envMap['Secrets__SqlitePath'] = Join-Path $DataDir 'mxgateway-secrets.db' }
if (-not $envMap.Contains('ASPNETCORE_ENVIRONMENT')) { $envMap['ASPNETCORE_ENVIRONMENT'] = $EnvironmentName }
if (-not $envMap.Contains('DOTNET_ENVIRONMENT')) { $envMap['DOTNET_ENVIRONMENT'] = $EnvironmentName }
if (-not ($envMap.Keys | Where-Object { $_ -like 'Kestrel__Endpoints__*' })) {
$envMap['Kestrel__Endpoints__Http__Url'] = 'http://0.0.0.0:5120'
$envMap['Kestrel__Endpoints__Http__Protocols'] = 'Http2'
$envMap['Kestrel__Endpoints__Dashboard__Url'] = 'http://0.0.0.0:5130'
Say '[info] no Kestrel__Endpoints__* supplied: using the documented cleartext defaults (5120 h2c, 5130 dashboard)'
}
# --- validation -------------------------------------------------------------------------------------
if (-not $envMap.Contains('ZB_SECRETS_MASTER_KEY') -or -not $envMap['ZB_SECRETS_MASTER_KEY']) { Fail 'env must supply ZB_SECRETS_MASTER_KEY (the Secrets KEK)' }
if (-not ($envMap.Keys | Where-Object { $_ -match 'Pepper' })) { Fail 'env must supply the API-key pepper (MxGateway__ApiKeyPepper); without it no issued token verifies' }
foreach ($k in 'MxGateway__Authentication__SqlitePath', 'Secrets__SqlitePath') {
$v = $envMap[$k]
if (-not (Test-Rooted $v)) { Fail "$k '$v' must be absolute" }
if ((Test-Inside $v $ServerDir) -or (Test-Inside $v $WorkerDir)) { Fail "$k '$v' is inside the content root; the validator is fail-closed and an upgrade swap would lose it" }
}
foreach ($d in @($ServerDir, $WorkerDir)) { if (-not (Test-Rooted $d)) { Fail "'$d' must be an absolute path" } }
if ((Test-Inside $WorkerDir $ServerDir) -or (Test-Inside $ServerDir $WorkerDir)) { Fail 'Server and Worker directories must be siblings, not nested (the upgrade swap renames them independently)' }
if (-not (Test-Path -LiteralPath (Join-Path $ServerDir $ServerExeName))) { Fail "$ServerExeName not found in $ServerDir" }
if (-not (Test-Path -LiteralPath $workerExe)) { Fail "$WorkerProc.exe not found in $WorkerDir" }
if ($envMap['MxGateway__Worker__ExecutablePath'] -ne $workerExe) { Say '[WARN] MxGateway__Worker__ExecutablePath differs from <WorkerDir>\Worker.exe; keep ONE canonical spelling' }
if ($envMap['ASPNETCORE_ENVIRONMENT'] -ne 'Production') { Say '[WARN] ASPNETCORE_ENVIRONMENT is not exactly Production: DisableLogin / plaintext-LDAP hard-stops are only enforced for Production' }
# --- one-gateway guard + existence -------------------------------------------------------------------
$st = Invoke-Nssm -NssmArgs @('status', $ServiceName) -AllowFail
if ($st.Code -eq 0) { Fail "service '$ServiceName' already exists (state $($st.Text)); use Upgrade-MxGatewayService.ps1" }
$procs = @(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -in @($ServerProc, $WorkerProc) })
if ($procs.Count -gt 0) { Fail "gateway process(es) already running (PIDs $(($procs.Id) -join ',')); installing/starting a second gateway kills their Workers" }
if (-not $LogDir) { $LogDir = Join-Path $DataDir 'logs' }
$exe = Join-Path $ServerDir $ServerExeName
Say "[info] env entries ($($envMap.Count)):"
foreach ($k in $envMap.Keys) { Say " $k=$(Mask $k $envMap[$k])" }
# --- install ------------------------------------------------------------------------------------------------
Step "create $DataDir and $LogDir (stores/certs/logs live OUTSIDE the content root)" {
New-Item -ItemType Directory -Force -Path $DataDir, $LogDir | Out-Null
}
Step "nssm install $ServiceName `"$exe`"" { [void](Invoke-Nssm -NssmArgs @('install', $ServiceName, $exe)); $script:Installed = $true }
$settings = @(
@('AppDirectory', $ServerDir),
@('DisplayName', 'MxAccess Gateway'),
@('Description', 'MxAccess Gateway (gRPC) - Server; launches the x86 Worker per session'),
@('Start', 'SERVICE_AUTO_START'),
@('Type', 'SERVICE_WIN32_OWN_PROCESS'),
@('AppExit', 'Default', 'Restart'),
@('AppRestartDelay', "$RestartDelayMs"),
@('AppThrottle', "$ThrottleMs"),
@('AppStopMethodConsole', "$StopGraceMs"),
@('AppStopMethodWindow', '0'),
@('AppStopMethodThreads', '0'),
@('AppStdout', (Join-Path $LogDir 'service-stdout.log')),
@('AppStderr', (Join-Path $LogDir 'service-stderr.log')),
@('AppRotateFiles', '1'),
@('AppRotateOnline', '1'),
@('AppRotateBytes', "$RotateBytes")
)
foreach ($s in $settings) {
Step "nssm set $ServiceName $($s -join ' ')" { [void](Invoke-Nssm -NssmArgs (@('set', $ServiceName) + $s)) }
}
if ($ObjectName -and $ObjectName -ne 'LocalSystem') {
Step "nssm set $ServiceName ObjectName $ObjectName <password>" { [void](Invoke-Nssm -NssmArgs @('set', $ServiceName, 'ObjectName', $ObjectName, $ServiceAccountPassword)) }
} else {
Step "nssm set $ServiceName ObjectName LocalSystem" { [void](Invoke-Nssm -NssmArgs @('set', $ServiceName, 'ObjectName', 'LocalSystem')) }
}
# Env block: first and only AppEnvironmentExtra write; the service has none, so nothing is wiped.
$pairs = @($envMap.Keys | ForEach-Object { "$_=$($envMap[$_])" })
Step "nssm set $ServiceName AppEnvironmentExtra <$($envMap.Count) entries, values hidden>" {
[void](Invoke-Nssm -NssmArgs (@('set', $ServiceName, 'AppEnvironmentExtra') + $pairs))
}
# SCM recovery: restart x3 (5 s, 5 s, 30 s), reset the counter after 1 day; also on non-crash exits.
Step "sc.exe failure $ServiceName reset= 86400 actions= restart/5000/restart/5000/restart/30000" {
& sc.exe failure $ServiceName reset= 86400 actions= 'restart/5000/restart/5000/restart/30000' | Out-Null
if ($LASTEXITCODE -ne 0) { Fail "sc.exe failure exited $LASTEXITCODE" }
}
Step "sc.exe failureflag $ServiceName 1" {
& sc.exe failureflag $ServiceName 1 | Out-Null
if ($LASTEXITCODE -ne 0) { Fail "sc.exe failureflag exited $LASTEXITCODE" }
}
# Verify read-back (names only) so a silent miss is caught before the first start.
Step "verify: nssm get AppEnvironmentExtra has $($envMap.Count) entries" {
$txt = (Invoke-Nssm -NssmArgs @('get', $ServiceName, 'AppEnvironmentExtra')).Text
$n = @($txt -split "[`r`n]+" | Where-Object { $_.Trim() -match '^[^=\s]+=' }).Count
if ($n -ne $envMap.Count) { Fail "env read-back has $n entries, expected $($envMap.Count)" }
}
if ($Start) {
Step "nssm start $ServiceName (exactly once)" { [void](Invoke-Nssm -NssmArgs @('start', $ServiceName)) }
Say 'Next: GET /health/ready on the dashboard port, then prove a Worker session with an API key (runbook section 7).'
} else {
Say '[info] service installed STOPPED. Review the env, then `nssm start` (or re-run with -Start). Seed secrets with the `secret` CLI using the SAME Secrets__SqlitePath + ZB_SECRETS_MASTER_KEY.'
}
Say '== DONE =='
exit 0
} catch {
Write-Host "ERROR: $($_.Exception.Message)" -ForegroundColor Red
if ($script:Installed) { Write-Host "PARTIAL INSTALL: inspect, then `nssm remove $ServiceName confirm` and re-run." -ForegroundColor Yellow }
exit 1
}