#Requires -Version 5.1 #Requires -RunAsAdministrator <# .SYNOPSIS RasterizedDB: one production server on Windows. PostgreSQL and the native protocol on the network, both with your TLS certificate, started at every boot as SYSTEM by a scheduled task, with firewall rules for both ports. .DESCRIPTION The server is a console program, not a Windows service, so a scheduled task starts it (see the windows-service recipe). Running this again replaces the task, the runner and the firewall rules with the new settings; the saved password is kept. .EXAMPLE $env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret' .\setup.ps1 -RdbBin .\rasterizeddb.exe -CertPath .\tls\server.pem -KeyPath .\tls\server.key #> [CmdletBinding()] param( [string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }), # PEM certificate chain and its private key (the tls-certificates recipe makes them). [string]$CertPath = $env:RDB_TLS_CERT, [string]$KeyPath = $env:RDB_TLS_KEY, [string]$Listen = $(if ($env:RDB_LISTEN) { $env:RDB_LISTEN } else { '0.0.0.0' }), [int]$PgPort = $(if ($env:RDB_PG_PORT) { [int]$env:RDB_PG_PORT } else { 5432 }), [int]$Port = $(if ($env:RDB_PORT) { [int]$env:RDB_PORT } else { 61170 }), [int]$MaxConnections = $(if ($env:RDB_MAX_CONNECTIONS) { [int]$env:RDB_MAX_CONNECTIONS } else { 500 }), [string]$LogLevel = $(if ($env:RDB_LOG_LEVEL) { $env:RDB_LOG_LEVEL } else { 'warn' }), # Who the firewall lets in: LocalSubnet, Any, or addresses such as 10.0.0.0/8. [string[]]$AllowFrom = @('LocalSubnet'), # Anything else, one array element per argument (for example the S3 backup flags). [string[]]$ExtraArgs = @(), [string]$InstallDir = 'C:\Program Files\RasterizedDB', [string]$Root = 'C:\ProgramData\RasterizedDB', [string]$TaskName = 'RasterizedDB' ) $ErrorActionPreference = 'Stop' $cmd = Get-Command $RdbBin -ErrorAction SilentlyContinue if (-not $cmd) { throw "'$RdbBin' not found; pass -RdbBin with the path of rasterizeddb.exe." } if (-not $CertPath -or -not (Test-Path -LiteralPath $CertPath)) { throw 'Pass -CertPath with the certificate (the tls-certificates recipe makes one).' } if (-not $KeyPath -or -not (Test-Path -LiteralPath $KeyPath)) { throw 'Pass -KeyPath with the certificate''s private key.' } $exe = Join-Path $InstallDir 'rasterizeddb.exe' $data = Join-Path $Root 'data' $logs = Join-Path $Root 'logs' $secrets = Join-Path $Root 'secrets' $tls = Join-Path $Root 'tls' $secretFile = Join-Path $secrets 'pg_password' $runner = Join-Path $Root 'run-rasterizeddb.ps1' if (-not (Test-Path -LiteralPath $secretFile)) { if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD to the password for the role rasterized.' } if ($env:RASTERIZEDDB_PG_PASSWORD.Length -lt 12) { throw 'Use a password of at least 12 characters on a networked server.' } } # Stop a running copy first, so the binary can be replaced. if (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue) { Stop-ScheduledTask -TaskName $TaskName Get-Process -Name rasterizeddb -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $exe } | Stop-Process -Force Start-Sleep -Seconds 2 } New-Item -ItemType Directory -Force -Path $InstallDir, $Root, $data, $logs, $secrets, $tls | Out-Null if ($cmd.Source -ne $exe) { Copy-Item -LiteralPath $cmd.Source -Destination $exe -Force } $cert = Join-Path $tls 'server.pem' $key = Join-Path $tls 'server.key' if ((Resolve-Path -LiteralPath $CertPath).Path -ne $cert) { Copy-Item -LiteralPath $CertPath -Destination $cert -Force } if ((Resolve-Path -LiteralPath $KeyPath).Path -ne $key) { Copy-Item -LiteralPath $KeyPath -Destination $key -Force } # Data, logs, password and key: SYSTEM and Administrators only. & icacls.exe $Root /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' /T /Q | Out-Null if ($LASTEXITCODE -ne 0) { throw "icacls could not restrict $Root." } if (-not (Test-Path -LiteralPath $secretFile)) { Set-Content -LiteralPath $secretFile -Value $env:RASTERIZEDDB_PG_PASSWORD -NoNewline -Encoding ascii } $serverArgs = @( '--location', $data, '--protocol', 'both', '--pg-addr', $Listen, '--pg-port', "$PgPort", '--pg-tls', 'require', '--pg-cert', $cert, '--pg-key', $key, '--rdb-addr', $Listen, '--rdb-port', "$Port", '--rdb-cert', $cert, '--rdb-key', $key, '--max-connections', "$MaxConnections", '--log-level', $LogLevel ) + $ExtraArgs function Format-PsString([string]$s) { "'" + ($s -replace "'", "''") + "'" } $runnerText = @' # Written by the RasterizedDB production-single-node setup script; run it again to change this. $ErrorActionPreference = 'Stop' $exe = __EXE__ $serverArgs = @(__ARGS__) $env:RASTERIZEDDB_PG_PASSWORD = (Get-Content -LiteralPath __SECRET__ -Raw).TrimEnd([char]13, [char]10) function Quote([string]$a) { if ($a -notmatch '[\s"]') { return $a } '"' + ($a -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"' } $line = ($serverArgs | ForEach-Object { Quote $_ }) -join ' ' while ($true) { $p = Start-Process -FilePath $exe -ArgumentList $line -NoNewWindow -Wait -PassThru ` -RedirectStandardOutput (Join-Path __LOGS__ 'server.out.log') ` -RedirectStandardError (Join-Path __LOGS__ 'server.err.log') if ($p.ExitCode -eq 0) { break } Add-Content -LiteralPath (Join-Path __LOGS__ 'restarts.log') -Value "$(Get-Date -Format o) exited with $($p.ExitCode); restarting in 10 s" Start-Sleep -Seconds 10 } '@ $runnerText = $runnerText.Replace('__EXE__', (Format-PsString $exe)) $runnerText = $runnerText.Replace('__ARGS__', (($serverArgs | ForEach-Object { Format-PsString $_ }) -join ', ')) $runnerText = $runnerText.Replace('__SECRET__', (Format-PsString $secretFile)) $runnerText = $runnerText.Replace('__LOGS__', (Format-PsString $logs)) Set-Content -LiteralPath $runner -Value $runnerText -Encoding utf8 $action = New-ScheduledTaskAction -Execute 'powershell.exe' ` -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$runner`"" $trigger = New-ScheduledTaskTrigger -AtStartup $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -StartWhenAvailable ` -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Principal $principal ` -Settings $settings -Description 'RasterizedDB server' -Force | Out-Null # Firewall: the two ports, from AllowFrom only. Replaced on every run. foreach ($rule in @(@{ Name = 'RasterizedDB PostgreSQL'; Port = $PgPort }, @{ Name = 'RasterizedDB native'; Port = $Port })) { Get-NetFirewallRule -DisplayName $rule.Name -ErrorAction SilentlyContinue | Remove-NetFirewallRule New-NetFirewallRule -DisplayName $rule.Name -Direction Inbound -Protocol TCP -LocalPort $rule.Port ` -RemoteAddress $AllowFrom -Program $exe -Action Allow | Out-Null } Start-ScheduledTask -TaskName $TaskName Start-Sleep -Seconds 5 if (-not (Get-Process -Name rasterizeddb -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $exe })) { Get-Content -LiteralPath (Join-Path $logs 'server.err.log') -Tail 30 -ErrorAction SilentlyContinue throw "The server did not start; see $logs\server.err.log." } $hostName = [System.Net.Dns]::GetHostEntry('').HostName Write-Host '' Write-Host "Running. Firewall rules let in: $($AllowFrom -join ', ')" Write-Host "PostgreSQL: postgresql://rasterized@${hostName}:$PgPort/postgres?sslmode=verify-full&sslrootcert=ca.pem" Write-Host "Native: ${hostName}:$Port (user rasterized, TLS)" Write-Host "Logs: $logs"