#Requires -Version 5.1 <# .SYNOPSIS RasterizedDB Enterprise: per-user shards on one machine. Three enterprise shard servers and the enterprise gateway; each customer's login is pinned to one shard, where its whole database lives, and the gateway sends every one of its statements there. Customers are added through the gateway's configuration API with add-customer.ps1. Needs release 1.1.0 or later. .DESCRIPTION Everything runs in the background, with logs and process ids in -Work. Running it again starts whatever is not running. Stop with: Get-Content .\per-user-cluster\*.pid | ForEach-Object { Stop-Process -Id $_ } .EXAMPLE $env:RASTERIZEDDB_PG_PASSWORD = 'change-me' .\setup.ps1 -RdbBin .\rasterizeddb-enterprise.exe -GatewayBin .\rasterizeddb-gateway-enterprise.exe #> [CmdletBinding()] param( [string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb-enterprise.exe' }), [string]$GatewayBin = $(if ($env:RDB_GATEWAY_BIN) { $env:RDB_GATEWAY_BIN } else { 'rasterizeddb-gateway-enterprise.exe' }), # Certificates, map, data, logs, the API token. [string]$Work = $(if ($env:RDB_WORK) { $env:RDB_WORK } else { '.\per-user-cluster' }), [int]$GatewayPort = $(if ($env:RDB_GATEWAY_PORT) { [int]$env:RDB_GATEWAY_PORT } else { 6432 }), # The gateway's configuration API, on 127.0.0.1. [int]$ApiPort = $(if ($env:RDB_API_PORT) { [int]$env:RDB_API_PORT } else { 6480 }), # prefer: unmapped logins use key routing; require: they are refused. [ValidateSet('prefer', 'require')] [string]$UserRouting = $(if ($env:RDB_USER_ROUTING) { $env:RDB_USER_ROUTING } else { 'prefer' }), # Shard n's ports are base + n. [int]$PgBase = $(if ($env:RDB_PG_BASE) { [int]$env:RDB_PG_BASE } else { 5440 }), [int]$NativeBase = $(if ($env:RDB_NATIVE_BASE) { [int]$env:RDB_NATIVE_BASE } else { 61180 }), [int]$RshardBase = $(if ($env:RDB_RSHARD_BASE) { [int]$env:RDB_RSHARD_BASE } else { 7400 }) ) $ErrorActionPreference = 'Stop' $shards = 0, 1, 2 $server = Get-Command $RdbBin -ErrorAction SilentlyContinue if (-not $server) { throw "'$RdbBin' not found; pass -RdbBin with the enterprise server." } $gateway = Get-Command $GatewayBin -ErrorAction SilentlyContinue if (-not $gateway) { throw "'$GatewayBin' not found; pass -GatewayBin with the enterprise gateway." } if (-not ((& $server.Source --help) -match '--enterprise-config')) { throw "$RdbBin is not the enterprise server." } $openssl = Get-Command openssl -ErrorAction SilentlyContinue if (-not $openssl) { throw 'openssl is needed for the certificates (Git for Windows has one in C:\Program Files\Git\usr\bin).' } if (-not (Get-Command psql -ErrorAction SilentlyContinue)) { throw 'psql is needed.' } if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD; every shard gets the operator role rasterized with it.' } $env:PGPASSWORD = $env:RASTERIZEDDB_PG_PASSWORD New-Item -ItemType Directory -Force -Path (Join-Path $Work 'tls') | Out-Null $Work = (Resolve-Path -LiteralPath $Work).Path $tls = Join-Path $Work 'tls' function Join-Args([string[]]$Items) { ($Items | ForEach-Object { if ($_ -notmatch '[\s"]') { $_ } else { '"' + ($_ -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"' } }) -join ' ' } function Test-Running([string]$Name) { $pidFile = Join-Path $Work "$Name.pid" if (-not (Test-Path -LiteralPath $pidFile)) { return $false } return [bool](Get-Process -Id ([int](Get-Content -LiteralPath $pidFile)) -ErrorAction SilentlyContinue) } function Start-Background([string]$Name, [string]$Exe, [string[]]$Arguments) { $p = Start-Process -FilePath $Exe -ArgumentList (Join-Args $Arguments) -WindowStyle Hidden -PassThru ` -RedirectStandardOutput (Join-Path $Work "$Name.out.log") -RedirectStandardError (Join-Path $Work "$Name.log") Set-Content -LiteralPath (Join-Path $Work "$Name.pid") -Value $p.Id Write-Host "started $Name (pid $($p.Id))" } function Wait-For([int]$Port, [string]$SslMode, [string]$Name) { for ($i = 0; $i -lt 60; $i++) { # Windows PowerShell turns a native program's stderr into errors when # it is redirected, so relax the preference around the probe. $saved = $ErrorActionPreference $ErrorActionPreference = 'Continue' & psql "postgresql://rasterized@127.0.0.1:$Port/postgres?sslmode=$SslMode" -Atqc 'SELECT 1' 2>$null | Out-Null $code = $LASTEXITCODE $ErrorActionPreference = $saved if ($code -eq 0) { return } if (-not (Test-Running $Name)) { throw "$Name exited; see $Work\$Name.log" } Start-Sleep -Seconds 1 } throw "$Name did not answer on port $Port within 60 s; see $Work\$Name.log" } # 1. Certificates: a CA, one for each shard and one for the gateway. if (-not (Test-Path -LiteralPath (Join-Path $tls 'ca.pem'))) { Push-Location $tls try { & $openssl.Source req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=rdb-cluster-ca -keyout ca.key -out ca.pem if ($LASTEXITCODE -ne 0) { throw 'openssl could not make the CA.' } Set-Content -LiteralPath ext.cnf -Value "subjectAltName=DNS:localhost,IP:127.0.0.1`nextendedKeyUsage=serverAuth,clientAuth`n" -Encoding ascii -NoNewline foreach ($name in 'shard0', 'shard1', 'shard2', 'gateway') { & $openssl.Source req -newkey rsa:2048 -nodes -subj "/CN=$name" -keyout "$name.key" -out "$name.csr" if ($LASTEXITCODE -ne 0) { throw "openssl could not make the key for $name." } & $openssl.Source x509 -req -in "$name.csr" -CA ca.pem -CAkey ca.key -CAcreateserial -days 365 -extfile ext.cnf -out "$name.pem" if ($LASTEXITCODE -ne 0) { throw "openssl could not sign the certificate for $name." } Remove-Item -LiteralPath "$name.csr" } } finally { Pop-Location } } # 2. The shard map: which shard owns which slice of the 2^48 key space. $mapFile = Join-Path $Work 'cluster.map' if (-not (Test-Path -LiteralPath $mapFile)) { $clusterId = -join ((1..32) | ForEach-Object { '{0:x}' -f (Get-Random -Maximum 16) }) $lines = @('rasterizeddb shard map', 'format 1', "cluster $clusterId", 'epoch 1', 'route_v 1') $lines += $shards | ForEach-Object { "shard $_ 127.0.0.1:$($RshardBase + $_)" } $lines += @('range 0x0 0', 'range 0x555555555555 1', 'range 0xaaaaaaaaaaaa 2') Set-Content -LiteralPath $mapFile -Value $lines -Encoding ascii } $clusterId = ((Get-Content -LiteralPath $mapFile) | Where-Object { $_ -match '^cluster ' }) -replace '^cluster ', '' # 3. Three enterprise shards. Each keeps the list of customer roles it hosts # in pinned_roles_file, which the gateway's API adds to. foreach ($n in $shards) { $econf = Join-Path $Work "enterprise$n.conf" if (-not (Test-Path -LiteralPath $econf)) { Set-Content -LiteralPath $econf -Value "pinned_roles_file $(Join-Path $Work "shard$n.hosted_roles")" -Encoding ascii } if (Test-Running "shard$n") { Write-Host "shard $n is running"; continue } $dir = Join-Path $Work "shard$n" New-Item -ItemType Directory -Force -Path $dir | Out-Null Start-Background "shard$n" $server.Source @( '--enterprise-config', $econf, '--location', $dir, '--protocol', 'both', '--pg-port', "$($PgBase + $n)", '--rdb-port', "$($NativeBase + $n)", '--role', 'shard', '--cluster-map', $mapFile, '--shard-id', "$n", '--cluster-id', $clusterId, '--shard-listen', "127.0.0.1:$($RshardBase + $n)", '--shard-cert', (Join-Path $tls "shard$n.pem"), '--shard-key', (Join-Path $tls "shard$n.key"), '--gateway-ca', (Join-Path $tls 'ca.pem'), '--peer-ca', (Join-Path $tls 'ca.pem'), '--log-level', 'info') } foreach ($n in $shards) { Wait-For ($PgBase + $n) 'require' "shard$n" } # 4. The enterprise gateway, with per-user routing and its configuration API. $token = Join-Path $Work 'api.token' if (-not (Test-Path -LiteralPath $token)) { $bytes = New-Object byte[] 24 [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes) Set-Content -LiteralPath $token -Value (($bytes | ForEach-Object { $_.ToString('x2') }) -join '') -Encoding ascii -NoNewline & icacls.exe $token /inheritance:r /grant:r "$($env:USERNAME):F" '*S-1-5-18:F' '*S-1-5-32-544:F' | Out-Null } $conf = Join-Path $Work 'gateway.conf' @( "listen = 127.0.0.1:$GatewayPort", "map = $mapFile", 'home_shard = 0', "shard_trust = ca:$(Join-Path $tls 'ca.pem')", "shard_cert = $(Join-Path $tls 'gateway.pem')", "shard_key = $(Join-Path $tls 'gateway.key')", 'auth = scram', 'unrouted = fan_out', 'two_phase = on', "user_routing = $UserRouting", "api_listen = 127.0.0.1:$ApiPort", "api_token_file = $token", "config_dir = $(Join-Path $Work 'gateway_config')" ) | Set-Content -LiteralPath $conf -Encoding ascii if (Test-Running 'gateway') { Write-Host 'the gateway is running' } else { Start-Background 'gateway' $gateway.Source @('--config', $conf) } Wait-For $GatewayPort 'disable' 'gateway' Write-Host '' Write-Host "Up. Operator, through the gateway: psql `"postgresql://rasterized@127.0.0.1:$GatewayPort/postgres?sslmode=disable`"" Write-Host "Configuration API: http://127.0.0.1:$ApiPort (bearer token in $token)" Write-Host 'Add a customer: .\add-customer.ps1 -Customer acme -Shard 1 (password from $env:RDB_CUSTOMER_PASSWORD)' Write-Host "Stop with: Get-Content $Work\*.pid | ForEach-Object { Stop-Process -Id `$_ }"