#Requires -Version 5.1 <# .SYNOPSIS RasterizedDB: a sharded cluster on one machine, to try sharding. Three shard servers that trust one certificate authority, a shard map, a table split across them by its key, and a gateway in front that speaks PostgreSQL and routes each statement by key. 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 .\cluster\*.pid | ForEach-Object { Stop-Process -Id $_ } .EXAMPLE $env:RASTERIZEDDB_PG_PASSWORD = 'change-me' .\setup.ps1 -RdbBin .\rasterizeddb.exe -GatewayBin .\rasterizeddb-gateway.exe #> [CmdletBinding()] param( [string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }), [string]$GatewayBin = $(if ($env:RDB_GATEWAY_BIN) { $env:RDB_GATEWAY_BIN } else { 'rasterizeddb-gateway.exe' }), # Certificates, map, data, logs. [string]$Work = $(if ($env:RDB_WORK) { $env:RDB_WORK } else { '.\cluster' }), [int]$GatewayPort = $(if ($env:RDB_GATEWAY_PORT) { [int]$env:RDB_GATEWAY_PORT } else { 6432 }), # 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 server binary (1.1.0 or later)." } $gateway = Get-Command $GatewayBin -ErrorAction SilentlyContinue if (-not $gateway) { throw "'$GatewayBin' not found; pass -GatewayBin with the gateway binary." } if (-not ((& $server.Source --help) -match '--shard-listen')) { throw "This $RdbBin has no sharding; it needs server 1.1.0 or later, built with the sharding feature." } $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 to create the schema.' } if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD; every shard gets the 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 shards. foreach ($n in $shards) { 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 @( '--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 schema, on every shard. A table's PARTITION BY HASH column is its # route key. The gateway refuses DDL, so schema changes go to every shard. foreach ($n in $shards) { & psql "postgresql://rasterized@127.0.0.1:$($PgBase + $n)/postgres?sslmode=require" -v ON_ERROR_STOP=1 -q ` -c 'CREATE TABLE IF NOT EXISTS orders (id INT PRIMARY KEY, store INT NOT NULL, v INT NOT NULL) PARTITION BY HASH (id)' if ($LASTEXITCODE -ne 0) { throw "Could not create the table on shard $n." } } # 5. The gateway. $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' ) | 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 "Cluster $clusterId is up. Connect through the gateway, as one database:" Write-Host " psql `"postgresql://rasterized@127.0.0.1:$GatewayPort/postgres?sslmode=disable`"" Write-Host "Logs and pids: $Work. Stop with: Get-Content $Work\*.pid | ForEach-Object { Stop-Process -Id `$_ }"