NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / SETUP SCRIPTS / RUN AT WINDOWS STARTUP

Run at Windows startup

Starts the server every time Windows boots, as the SYSTEM account, with its data in C:\ProgramData\RasterizedDB\data. PostgreSQL (5432) and the native protocol (61170) listen on localhost until you add flags that open them up.

The server is a console program. It does not implement the Windows service control protocol, so registering it with sc.exe create or New-Service gives a service that Windows reports as failing to start. This recipe uses a scheduled task that runs at startup instead. There is no bash version: it is Windows only. On Linux, see the systemd-service recipe.

Before you start

  • Windows 10, Windows Server 2016 or newer, and an elevated PowerShell (Run as Administrator).
  • rasterizeddb.exe (see the install recipe). The script copies it to C:\Program Files\RasterizedDB.

Settings

ParameterDefaultWhat it does
-RdbBin (or $env:RDB_BIN)rasterizeddb.exeThe binary to install.
-InstallDirC:\Program Files\RasterizedDBWhere the binary is copied.
-RootC:\ProgramData\RasterizedDBHolds data, logs, secrets and the runner script. Only SYSTEM and Administrators can read it.
-ExtraArgsnoneFurther server flags, one array element per argument, for example -ExtraArgs '--pg-addr', '0.0.0.0'.
-TaskNameRasterizedDBThe scheduled task's name.
-NoStartoffRegister the task without starting it now.
$env:RASTERIZEDDB_PG_PASSWORDrequired on the first runPassword of the role rasterized. Saved to secrets\pg_password and read from there at every start.

What the script writes:

FileWhat it is
C:\Program Files\RasterizedDB\rasterizeddb.exeThe server.
C:\ProgramData\RasterizedDB\run-rasterizeddb.ps1What the task runs. It puts the password in its own environment, starts the server with --location …\data --protocol both and your flags, and starts it again 10 seconds after it exits with an error.
C:\ProgramData\RasterizedDB\secrets\pg_passwordThe password. Written once and kept on later runs.
C:\ProgramData\RasterizedDB\logs\server.out.log, server.err.log (the server's log lines) and restarts.log.

Run it

In an elevated PowerShell:

powershell
$env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
.\setup.ps1 -RdbBin .\rasterizeddb.exe

To accept connections from other machines, add the flags and open the firewall:

powershell
.\setup.ps1 -RdbBin .\rasterizeddb.exe -ExtraArgs '--pg-addr', '0.0.0.0', '--rdb-addr', '0.0.0.0'
New-NetFirewallRule -DisplayName 'RasterizedDB PostgreSQL' -Direction Inbound -Protocol TCP -LocalPort 5432 -Action Allow

The production-single-node recipe does this with your own TLS certificate. If PowerShell refuses to run a downloaded script, run Unblock-File .\setup.ps1 first.

Check that it works

powershell
Get-ScheduledTask -TaskName RasterizedDB | Select-Object TaskName, State
Get-Content C:\ProgramData\RasterizedDB\logs\server.err.log -Tail 20
psql "postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require" -c "SELECT 1"

The PostgreSQL listener requires TLS by default. Without a certificate of your own the server makes a self-signed one at each start, which sslmode=require accepts.

Change settings

Run the script again with the new -ExtraArgs. It stops the server, rewrites the runner and the task, and starts it again. The saved password is kept; it creates the role only when the database is first made. After that, change the password with SQL: ALTER USER rasterized PASSWORD '…'.

Stop or undo

powershell
Stop-ScheduledTask -TaskName RasterizedDB
Get-Process rasterizeddb -ErrorAction SilentlyContinue | Stop-Process -Force

Stopping this way ends the process without a clean shutdown. Nothing committed is lost: the next start replays the log. To have it stay stopped across reboots as well, Disable-ScheduledTask -TaskName RasterizedDB.

To remove it completely, which deletes the data too:

powershell
Unregister-ScheduledTask -TaskName RasterizedDB -Confirm:$false
Get-Process rasterizeddb -ErrorAction SilentlyContinue | Stop-Process -Force
Remove-Item 'C:\ProgramData\RasterizedDB', 'C:\Program Files\RasterizedDB' -Recurse -Force

Limits

  • There is no clean stop from outside: Stop-Process ends the server at once, and the next start replays the log. Run it in a console and press Ctrl+C when you need a clean shutdown with a checkpoint.
  • The task runs as SYSTEM. Give a data directory elsewhere (--storage-location, or another -Root) the same permissions.

The files

setup.ps1 · Windows (PowerShell)DOWNLOAD ↓
#Requires -Version 5.1
#Requires -RunAsAdministrator
<#
.SYNOPSIS
  RasterizedDB: run the server at every Windows start, as SYSTEM, from a
  scheduled task. The server is a console program, not a Windows service, so
  a task starts it instead of the service manager.
.DESCRIPTION
  Writes C:\ProgramData\RasterizedDB\run-rasterizeddb.ps1 (what the task runs)
  and C:\ProgramData\RasterizedDB\secrets\pg_password (readable by SYSTEM and
  Administrators only), registers the task "RasterizedDB" and starts it.
  Running it again replaces the task and the runner with the new settings.
.EXAMPLE
  $env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
  .\setup.ps1 -RdbBin .\rasterizeddb.exe
.EXAMPLE
  .\setup.ps1 -ExtraArgs '--pg-addr', '0.0.0.0', '--rdb-addr', '0.0.0.0'
#>
[CmdletBinding()]
param(
    [string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }),
    [string]$InstallDir = $(if ($env:RDB_INSTALL_DIR) { $env:RDB_INSTALL_DIR } else { 'C:\Program Files\RasterizedDB' }),
    [string]$Root = $(if ($env:RDB_ROOT) { $env:RDB_ROOT } else { 'C:\ProgramData\RasterizedDB' }),
    # Further server flags, one array element per argument.
    [string[]]$ExtraArgs = @(),
    [string]$TaskName = 'RasterizedDB',
    [switch]$NoStart
)
$ErrorActionPreference = 'Stop'

$cmd = Get-Command $RdbBin -ErrorAction SilentlyContinue
if (-not $cmd) { throw "'$RdbBin' not found; pass -RdbBin with the path of rasterizeddb.exe." }

$exe = Join-Path $InstallDir 'rasterizeddb.exe'
$data = Join-Path $Root 'data'
$logs = Join-Path $Root 'logs'
$secrets = Join-Path $Root 'secrets'
$secretFile = Join-Path $secrets 'pg_password'
$runner = Join-Path $Root 'run-rasterizeddb.ps1'

# Stop a running copy first, so the binary can be replaced.
$task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
if ($task) {
    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 | Out-Null
if ($cmd.Source -ne $exe) { Copy-Item -LiteralPath $cmd.Source -Destination $exe -Force }

# The data, logs and password: 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)) {
    if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD to the password for the role rasterized.' }
    Set-Content -LiteralPath $secretFile -Value $env:RASTERIZEDDB_PG_PASSWORD -NoNewline -Encoding ascii
    Write-Host "Wrote $secretFile"
}
else {
    Write-Host "Keeping the existing $secretFile"
}

# The runner: sets the password in its own environment, starts the server,
# and starts it again 10 seconds after it exits with an error.
function Format-PsString([string]$s) { "'" + ($s -replace "'", "''") + "'" }
$serverArgs = @('--location', $data, '--protocol', 'both') + $ExtraArgs
$argList = ($serverArgs | ForEach-Object { Format-PsString $_ }) -join ', '
$runnerText = @'
# Written by the RasterizedDB windows-service 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__', $argList)
$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
Write-Host "Registered the scheduled task '$TaskName' (at startup, as SYSTEM)"

if (-not $NoStart) {
    Start-ScheduledTask -TaskName $TaskName
    Start-Sleep -Seconds 5
    $running = Get-Process -Name rasterizeddb -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $exe }
    if ($running) { Write-Host "Running, process id $($running.Id -join ', ')" }
    else { Write-Warning "The server is not running; see $logs\server.err.log" }
}

Write-Host ''
Write-Host 'PostgreSQL: postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require'
Write-Host 'Native:     127.0.0.1:61170 (user rasterized)'
Write-Host "Logs:       $logs"
✓ page rendered in 166 µs axum + tera + htmx · no other javascript