Files
HealthAppRepositoryB/Reference/ArchitectureA/deploy/installer/install.ps1
T

160 lines
11 KiB
PowerShell

[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][string]$Services,
[string]$HostName = 'localhost',
[string]$Topology,
[string]$Deployment,
[string]$Certificates,
[string]$PostgresAdminFile,
[string]$Root = "$env:ProgramData\HealthApp",
[switch]$PrepareOnly,
[switch]$DeferTopologyCheck
)
$ErrorActionPreference = 'Stop'
$step = 'arguments'
function Check-Exit([string]$Operation) { if ($LASTEXITCODE -ne 0) { throw "$Operation failed (exit $LASTEXITCODE)." } }
function Protect-Private([string]$Path) {
& icacls.exe $Path /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null
Check-Exit 'Protect private deployment files'
}
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run from an elevated PowerShell session.' }
$assemblies = @{ 'api-gateway'='ApiGateway'; 'patient-profile'='PatientProfileService'; 'observation'='ObservationService'; 'insights'='InsightsService'; 'health-overview'='HealthOverviewService' }
$selected = if ($Services -eq 'all') { @('api-gateway','patient-profile','observation','insights','health-overview') } else { @($Services.Split(',')) }
if (@($selected | Select-Object -Unique).Count -ne $selected.Count) { throw 'Repeated service selection.' }
foreach ($name in $selected) {
if (-not $assemblies.ContainsKey($name)) { throw "Unknown service: $name" }
if (-not (Test-Path "$PSScriptRoot\services\$name\$($assemblies[$name]).dll")) { throw "Missing release: $name" }
if ((Test-Path "$Root\services\$name") -or (Get-Service "healthapp-$name" -ErrorAction SilentlyContinue)) { throw "Already installed: $name. Existing files were not changed." }
}
New-Item -ItemType Directory -Force $Root | Out-Null
Protect-Private $Root
$step = 'install .NET 10 ASP.NET Core runtime'
$dotnet = "$Root\runtime\dotnet.exe"
if (Get-Command dotnet.exe -ErrorAction SilentlyContinue) {
$candidate = (Get-Command dotnet.exe).Source
if ((& $candidate --list-runtimes) -match 'Microsoft.AspNetCore.App 10\.') { $dotnet = $candidate }
}
if (-not (Test-Path $dotnet)) {
$script = "$Root\dotnet-install.ps1"
Invoke-WebRequest 'https://dot.net/v1/dotnet-install.ps1' -OutFile $script -UseBasicParsing
& $script -Channel '10.0' -Runtime 'aspnetcore' -InstallDir "$Root\runtime" -NoPath
if (-not (Test-Path $dotnet)) { throw 'Runtime installation did not produce dotnet.exe.' }
}
$utility = "$PSScriptRoot\provisioner\HealthApp.Provisioning.dll"
$step = 'generate deployment material'
if (-not $Deployment) { $Deployment = "$Root\deployment" }
if (-not (Test-Path "$Deployment\deployment.json")) {
$prepare = @($utility,'prepare','--output',$Deployment,'--host',$HostName)
if ($Topology) { $prepare += @('--topology',$Topology) }
if ($Certificates) { $prepare += @('--certificates',$Certificates) }
& $dotnet @prepare
Check-Exit 'Generate credentials and HTTPS certificates'
}
Protect-Private $Deployment
if ($PrepareOnly) { Write-Host "Generated protected deployment material in $Deployment"; return }
$step = 'install prototype HTTPS trust'
Import-Certificate -FilePath "$Deployment\healthapp-ca.crt" -CertStoreLocation Cert:\LocalMachine\Root | Out-Null
$needsPostgres = ($selected -contains 'patient-profile') -or ($selected -contains 'observation')
if ($needsPostgres -and -not $PostgresAdminFile) {
$PostgresAdminFile = "$Root\postgres-admin.connection"
if (-not (Test-Path $PostgresAdminFile)) {
$step = 'install PostgreSQL'
# Resolve the maintained Microsoft package manifest, verify the vendor binary checksum,
# and pass the generated administrator secret through a protected options file.
$headers = @{ 'User-Agent'='HealthApp-Prototype-Installer' }
$manifestBase = 'https://api.github.com/repos/microsoft/winget-pkgs/contents/manifests/p/PostgreSQL/PostgreSQL/17'
$versions = Invoke-RestMethod $manifestBase -Headers $headers
$latest = $versions | Sort-Object @{Expression={[version]($_.name.Split('-')[0])}}, @{Expression={[int]($_.name.Split('-')[-1])}} -Descending | Select-Object -First 1
$files = Invoke-RestMethod $latest.url -Headers $headers
$manifest = $files | Where-Object { $_.name -like '*.installer.yaml' } | Select-Object -First 1
$yaml = (Invoke-WebRequest $manifest.download_url -UseBasicParsing).Content
$download = [regex]::Match($yaml,'(?m)^\s*InstallerUrl:\s*(\S+)').Groups[1].Value
$checksum = [regex]::Match($yaml,'(?m)^\s*InstallerSha256:\s*([A-Fa-f0-9]{64})').Groups[1].Value
if (-not $download.StartsWith('https://get.enterprisedb.com/') -or -not $checksum) { throw 'PostgreSQL package manifest is invalid.' }
$installer = "$Root\postgresql-installer.exe"
Invoke-WebRequest $download -OutFile $installer -UseBasicParsing
if ((Get-FileHash $installer -Algorithm SHA256).Hash -ne $checksum) { throw 'PostgreSQL installer checksum does not match.' }
$random = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($random); $rng.Dispose()
$adminPassword = [BitConverter]::ToString($random).Replace('-','') + 'a!'
$port = 5432
$listener = New-Object Net.Sockets.TcpListener([Net.IPAddress]::Loopback,$port)
try { $listener.Start() } catch { $listener = New-Object Net.Sockets.TcpListener([Net.IPAddress]::Loopback,0); $listener.Start(); $port = $listener.LocalEndpoint.Port }
finally { $listener.Stop() }
$options = "$Root\postgresql.options"
@('mode=unattended','unattendedmodeui=none','debuglevel=0','enable-components=server,commandlinetools',
"prefix=$Root\postgresql","datadir=$Root\postgresql-data","serverport=$port",'servicename=healthapp-postgresql',
'serviceaccount=NT AUTHORITY\NetworkService',"superpassword=$adminPassword") | Set-Content $options -Encoding UTF8
Protect-Private $options
$installed = Start-Process $installer -ArgumentList @('--optionfile',('"'+$options+'"')) -Wait -PassThru
if ($installed.ExitCode -ne 0) { throw 'PostgreSQL unattended installation failed.' }
"Host=localhost;Port=$port;Database=postgres;Username=postgres;Password=$adminPassword" | Set-Content $PostgresAdminFile -Encoding UTF8
Protect-Private $PostgresAdminFile
Remove-Item $options
}
Start-Service 'healthapp-postgresql'
}
foreach ($name in $selected) {
$step = "configure $name"
if ($name -eq 'patient-profile' -or $name -eq 'observation') {
& $dotnet $utility database --service-dir "$Deployment\$name" --admin-file $PostgresAdminFile
Check-Exit "Create dedicated $name database and credentials"
}
& $dotnet $utility configure --service-dir "$Deployment\$name" --root $Root --platform windows
Check-Exit "Configure $name"
New-Item -ItemType Directory -Force "$Root\services" | Out-Null
$application = "$Root\services\$name"
Copy-Item "$PSScriptRoot\services\$name" $application -Recurse
Copy-Item "$Root\config\$name\appsettings.Production.json" "$application\appsettings.Production.json"
$dll = "$application\$($assemblies[$name]).dll"
if ($name -eq 'patient-profile' -or $name -eq 'observation') {
& $dotnet $dll --migrate --contentRoot $application --environment Production
Check-Exit "Migrate $name database"
}
$serviceName = "healthapp-$name"
$binary = '"'+$dotnet+'" "'+$dll+'" --contentRoot "'+$application+'" --environment Production'
New-Service -Name $serviceName -BinaryPathName $binary -StartupType Automatic -Description "HealthApp $name" | Out-Null
& sc.exe config $serviceName obj= "NT SERVICE\$serviceName" | Out-Null
Check-Exit "Configure independent $name virtual service account"
& icacls.exe $application /grant "NT SERVICE\${serviceName}:(OI)(CI)RX" /T | Out-Null
& icacls.exe "$Root\config\$name" /grant "NT SERVICE\${serviceName}:(OI)(CI)RX" /T | Out-Null
if ($name -eq 'api-gateway') {
New-Item -ItemType Directory -Force "$Root\state\api-gateway\keys" | Out-Null
& icacls.exe "$Root\state\api-gateway" /grant "NT SERVICE\${serviceName}:(OI)(CI)M" /T | Out-Null
}
# Service identities need traversal/runtime access, not other services' private configuration.
foreach ($parent in @("$Root\services","$Root\config","$Root\state")) {
if (Test-Path $parent) { & icacls.exe $parent /grant "NT SERVICE\${serviceName}:RX" | Out-Null }
}
& icacls.exe $Root /grant "NT SERVICE\${serviceName}:RX" | Out-Null
if ($dotnet.StartsWith($Root)) { & icacls.exe "$Root\runtime" /grant "NT SERVICE\${serviceName}:(OI)(CI)RX" /T | Out-Null }
& sc.exe failure $serviceName reset= 86400 actions= restart/5000 | Out-Null
$settings = Get-Content "$Deployment\$name\service.json" -Raw | ConvertFrom-Json
New-NetFirewallRule -DisplayName "HealthApp $name HTTPS" -Direction Inbound -Action Allow -Protocol TCP -LocalPort $settings.Port -Program $dotnet | Out-Null
Start-Service $serviceName
}
$step = 'verify running processes and HTTPS'
$processIds = @()
foreach ($name in $selected) {
$native = Get-CimInstance Win32_Service -Filter "Name='healthapp-$name'"
if ($native.State -ne 'Running' -or $native.ProcessId -eq 0 -or ($processIds -contains $native.ProcessId)) { throw "$name is not an independent running service." }
$processIds += $native.ProcessId
}
& $dotnet $utility verify-startup --deployment $Deployment --services ($selected -join ',')
Check-Exit 'HTTPS startup verification'
if (-not $DeferTopologyCheck) {
$verify = @($utility,'verify','--deployment',$Deployment,'--services',($selected -join ','))
if ($Services -eq 'all') { $verify += @('--complete','true') }
& $dotnet @verify
Check-Exit 'Dependency and representative workflow verification'
}
Write-Host "Installation completed. Generated account credentials are protected in $Deployment\accounts.json"
} catch {
Write-Error "Installation failed at ${step}: $($_.Exception.Message). Existing data and deployment material were retained."
exit 1
}