A production server on one machine
Sets up one server that other machines can reach: PostgreSQL on port 5432 and the native protocol on 61170, both listening on the network with your TLS certificate, password logins only, started at boot. On Linux it runs under systemd as the user rasterizeddb. On Windows it runs as SYSTEM from a scheduled task, with firewall rules for both ports.
Before you start
- The server binary (see the install recipe).
- A certificate and key in PEM format whose names match the host name or address clients use. The tls-certificates recipe makes a private authority and a certificate. A certificate from your own or a public authority works the same way.
- A password of at least 12 characters for the role
rasterized, inRASTERIZEDDB_PG_PASSWORD. - Linux: systemd and root. Keep
setup.shandrasterizeddb.servicein one directory. - Windows: an elevated PowerShell.
Settings
| bash variable | PowerShell parameter | Default | What it does |
|---|---|---|---|
RDB_BIN | -RdbBin | rasterizeddb / rasterizeddb.exe | The binary to install. |
RDB_TLS_CERT | -CertPath | required | The certificate chain (PEM). Copied to /etc/rasterizeddb/tls/server.pem or C:\ProgramData\RasterizedDB\tls\server.pem. |
RDB_TLS_KEY | -KeyPath | required | Its private key (PEM). |
RDB_LISTEN | -Listen | 0.0.0.0 | The address both protocols bind. Use one interface's address to listen on that interface only. |
RDB_PG_PORT | -PgPort | 5432 | PostgreSQL port. |
RDB_PORT | -Port | 61170 | Native protocol port. |
RDB_MAX_CONNECTIONS | -MaxConnections | 500 | Most PostgreSQL sessions at once. Past it a connection is refused with SQLSTATE 53300. |
RDB_LOG_LEVEL | -LogLevel | warn | off, error, warn, info, debug or trace. |
RDB_EXTRA_ARGS | -ExtraArgs | none | Any other server flags, for example the S3 backup flags from the s3-backup-pitr recipe. |
-AllowFrom | LocalSubnet | Who the Windows firewall rules let in: LocalSubnet, Any, or addresses such as 10.0.0.0/8. | |
RASTERIZEDDB_PG_PASSWORD | $env:RASTERIZEDDB_PG_PASSWORD | required on the first run | The role's password. Saved where only root (Linux) or SYSTEM and Administrators (Windows) can read it. |
The server is started with these flags:
--location <data> --protocol both
--pg-addr <listen> --pg-port 5432 --pg-tls require --pg-cert <cert> --pg-key <key>
--rdb-addr <listen> --rdb-port 61170 --rdb-cert <cert> --rdb-key <key>
--max-connections 500 --log-level warn--pg-tls require refuses any PostgreSQL client that does not use TLS. The native protocol always uses TLS over TCP.
Run it
export RASTERIZEDDB_PG_PASSWORD='use-a-long-secret'
sudo --preserve-env=RASTERIZEDDB_PG_PASSWORD \
RDB_BIN="$HOME/.local/bin/rasterizeddb" \
RDB_TLS_CERT=./tls/server.pem RDB_TLS_KEY=./tls/server.key ./setup.sh$env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
.\setup.ps1 -RdbBin .\rasterizeddb.exe -CertPath .\tls\server.pem -KeyPath .\tls\server.key -AllowFrom 10.0.0.0/8On Linux the script prints example ufw and firewalld commands but changes no firewall. Open 5432, and 61170 if you use the native protocol, to your application hosts only.
Running the script again replaces the flags (and on Windows the firewall rules) and restarts the server. The saved password is kept.
Check that it works
From another machine, with the authority's ca.pem:
PGPASSWORD='use-a-long-secret' psql \
"host=db.example.com port=5432 dbname=postgres user=rasterized sslmode=verify-full sslrootcert=ca.pem" \
-c "SELECT 1"A client without TLS is refused:
psql "host=db.example.com dbname=postgres user=rasterized sslmode=disable" -c "SELECT 1"On the server: systemctl status rasterizeddb and journalctl -u rasterizeddb on Linux; Get-ScheduledTask RasterizedDB and C:\ProgramData\RasterizedDB\logs\server.err.log on Windows.
After the first start
- Make a role for each application rather than sharing
rasterized:CREATE USER app PASSWORD '…', thenGRANTwhat it needs. - Add backups: the s3-backup-pitr recipe's flags go in
RDB_EXTRA_ARGS/-ExtraArgs.
Stop or undo
Linux: sudo systemctl stop rasterizeddb stops it cleanly; sudo systemctl disable rasterizeddb keeps it from starting at boot. The systemd-service recipe lists how to remove everything.
Windows: Stop-ScheduledTask RasterizedDB, then Get-Process rasterizeddb | Stop-Process -Force. Remove the firewall rules with Remove-NetFirewallRule -DisplayName 'RasterizedDB PostgreSQL', 'RasterizedDB native'. The windows-service recipe lists how to remove the rest.
Limits
- The certificate is read at start. After renewing it, run the script again (or copy the new files over the old ones) and restart the server.
- This is one machine. For a second copy that takes writes too, see replication-two-nodes; for recovery after losing the machine, see s3-backup-pitr.
The files
#!/usr/bin/env bash
# RasterizedDB: one production server on Linux. PostgreSQL and the native
# protocol on the network, both with your TLS certificate, run by systemd as
# the user rasterizeddb, data in /var/lib/rasterizeddb.
# Run as root, from the directory that holds rasterizeddb.service.
#
# Every setting can be overridden from the environment, for example:
# sudo --preserve-env=RASTERIZEDDB_PG_PASSWORD RDB_BIN=./rasterizeddb \
# RDB_TLS_CERT=./tls/server.pem RDB_TLS_KEY=./tls/server.key ./setup.sh
set -euo pipefail
RDB_BIN="${RDB_BIN:-rasterizeddb}"
RDB_TLS_CERT="${RDB_TLS_CERT:-}" # PEM certificate chain (required)
RDB_TLS_KEY="${RDB_TLS_KEY:-}" # its PEM private key (required)
RDB_LISTEN="${RDB_LISTEN:-0.0.0.0}" # the address both protocols bind
RDB_PG_PORT="${RDB_PG_PORT:-5432}"
RDB_PORT="${RDB_PORT:-61170}"
RDB_MAX_CONNECTIONS="${RDB_MAX_CONNECTIONS:-500}"
RDB_LOG_LEVEL="${RDB_LOG_LEVEL:-warn}"
RDB_EXTRA_ARGS="${RDB_EXTRA_ARGS:-}" # anything else, for example the S3 backup flags
RDB_SERVICE_USER="${RDB_SERVICE_USER:-rasterizeddb}"
die() { echo "error: $*" >&2; exit 1; }
[ "$(id -u)" -eq 0 ] || die "run this as root (sudo)"
command -v systemctl >/dev/null 2>&1 || die "systemd is needed"
here="$(cd "$(dirname "$0")" && pwd)"
[ -f "$here/rasterizeddb.service" ] || die "rasterizeddb.service must be next to this script"
src="$(command -v "$RDB_BIN" 2>/dev/null)" || die "'$RDB_BIN' not found; set RDB_BIN to the server binary"
[ -n "$RDB_TLS_CERT" ] && [ -f "$RDB_TLS_CERT" ] || die "set RDB_TLS_CERT to the certificate (the tls-certificates recipe makes one)"
[ -n "$RDB_TLS_KEY" ] && [ -f "$RDB_TLS_KEY" ] || die "set RDB_TLS_KEY to the certificate's private key"
env_file=/etc/rasterizeddb/rasterizeddb.env
if [ ! -f "$env_file" ]; then
: "${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD to the password for the role rasterized}"
case "$RASTERIZEDDB_PG_PASSWORD" in
*"'"* | *$'\n'*) die "the password may not contain a single quote or a newline" ;;
esac
[ "${#RASTERIZEDDB_PG_PASSWORD}" -ge 12 ] || die "use a password of at least 12 characters on a networked server"
fi
# The binary and the service user.
if [ "$(readlink -f "$src")" != "/usr/local/bin/rasterizeddb" ]; then
install -m 0755 "$src" /usr/local/bin/rasterizeddb
fi
if ! id "$RDB_SERVICE_USER" >/dev/null 2>&1; then
useradd --system --user-group --home-dir /var/lib/rasterizeddb --no-create-home \
--shell "$(command -v nologin || echo /usr/sbin/nologin)" --comment "RasterizedDB server" "$RDB_SERVICE_USER"
fi
# The certificate: readable by the service, the key by nobody else.
install -d -m 0755 /etc/rasterizeddb
install -d -m 0750 -g "$RDB_SERVICE_USER" /etc/rasterizeddb/tls
install -m 0644 "$RDB_TLS_CERT" /etc/rasterizeddb/tls/server.pem
install -m 0640 -g "$RDB_SERVICE_USER" "$RDB_TLS_KEY" /etc/rasterizeddb/tls/server.key
cert=/etc/rasterizeddb/tls/server.pem
key=/etc/rasterizeddb/tls/server.key
args="--pg-addr $RDB_LISTEN --pg-port $RDB_PG_PORT --pg-tls require --pg-cert $cert --pg-key $key"
args="$args --rdb-addr $RDB_LISTEN --rdb-port $RDB_PORT --rdb-cert $cert --rdb-key $key"
args="$args --max-connections $RDB_MAX_CONNECTIONS --log-level $RDB_LOG_LEVEL"
[ -z "$RDB_EXTRA_ARGS" ] || args="$args $RDB_EXTRA_ARGS"
umask 077
if [ ! -f "$env_file" ]; then
cat > "$env_file" <<EOF
# RasterizedDB service settings, read by rasterizeddb.service.
# Password of the role rasterized, used when the database is first created.
RASTERIZEDDB_PG_PASSWORD='$RASTERIZEDDB_PG_PASSWORD'
# Server flags. Rewritten by the production-single-node setup script.
RASTERIZEDDB_ARGS=$args
EOF
else
# Keep the password; replace the flags.
tmp="$(mktemp /etc/rasterizeddb/.env.XXXXXX)"
grep -v '^RASTERIZEDDB_ARGS=' "$env_file" > "$tmp" || true
printf 'RASTERIZEDDB_ARGS=%s\n' "$args" >> "$tmp"
mv "$tmp" "$env_file"
fi
chmod 0600 "$env_file"
chown root:root "$env_file"
sed -e "s/^User=.*/User=$RDB_SERVICE_USER/" -e "s/^Group=.*/Group=$RDB_SERVICE_USER/" \
"$here/rasterizeddb.service" > /etc/systemd/system/rasterizeddb.service
chmod 0644 /etc/systemd/system/rasterizeddb.service
systemctl daemon-reload
if systemctl is-active --quiet rasterizeddb; then
systemctl restart rasterizeddb
fi
systemctl enable --now rasterizeddb
sleep 3
systemctl is-active --quiet rasterizeddb || {
journalctl -u rasterizeddb -n 30 --no-pager
die "the service did not start; the log is above"
}
host="$(hostname -f 2>/dev/null || hostname)"
echo
echo "Running. Open the ports to your clients only, for example:"
echo " ufw allow from 10.0.0.0/8 to any port $RDB_PG_PORT proto tcp"
echo " firewall-cmd --permanent --add-port=$RDB_PG_PORT/tcp && firewall-cmd --reload"
echo
echo "PostgreSQL: postgresql://rasterized@$host:$RDB_PG_PORT/postgres?sslmode=verify-full&sslrootcert=ca.pem"
echo "Native: $host:$RDB_PORT (user rasterized, TLS)"
echo "The password is the one in $env_file."#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"[Unit]
Description=RasterizedDB server
Documentation=https://github.com/milen-denev/rasterizeddb
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=rasterizeddb
Group=rasterizeddb
EnvironmentFile=/etc/rasterizeddb/rasterizeddb.env
ExecStartPre=/bin/sh -c 'test -n "$$RASTERIZEDDB_PG_PASSWORD" || { echo "set RASTERIZEDDB_PG_PASSWORD in /etc/rasterizeddb/rasterizeddb.env" >&2; exit 1; }'
ExecStart=/usr/local/bin/rasterizeddb --location /var/lib/rasterizeddb --protocol both $RASTERIZEDDB_ARGS
StateDirectory=rasterizeddb
StateDirectoryMode=0700
# A clean stop (SIGTERM) ends with a checkpoint: give it time.
KillSignal=SIGTERM
TimeoutStopSec=120
Restart=on-failure
RestartSec=5
LimitNOFILE=1048576
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
LockPersonality=yes
# Directories outside /var/lib/rasterizeddb that the server writes to
# (--storage-location, unix sockets) need a drop-in with ReadWritePaths=<dir>.
[Install]
WantedBy=multi-user.target