Add a replica to a running server
Turns a single server that already holds data into a replicated pair: a new node is built from the existing server's latest S3 backup, both nodes start their replication history from that same point, and from then on every commit on either node reaches the other. Use it when the database already exists; for two empty nodes, the replication-two-nodes recipe is simpler.
Replication ships what happens from now on, not what happened before, so the new node needs a copy of the data first. A copy restored from the backup is used rather than a copied directory: a copied directory still names the original's paths, and would read and write the original's files.
Before you start
- The existing server backs up to S3 (the s3-backup-pitr recipe), and you have credentials that may read the bucket.
- A new machine with the server binary, reachable from the existing one on the replication port (61171 by default).
- A short maintenance window: no application may write to the existing server from step 2 until step 6. Writes made in between would be on the existing server only.
- Both scripts in this folder:
setup.sh/setup.ps1runs on the new node,prepare-existing-node.sh/.ps1on the existing server.
Settings
New node (setup.sh, setup.ps1):
| bash variable | PowerShell parameter | Default | What it does |
|---|---|---|---|
RDB_BIN | -RdbBin | rasterizeddb / rasterizeddb.exe | The server binary. |
RDB_DATA | -Data | ./data | The new node's database directory. Must be empty or absent on the first run. A file <dir>.seeded beside it records that the copy was made. |
RDB_IDENTITY_DIR | -IdentityDir | ./replication-identity | The new node's replication certificate and key. |
RDB_NODE_ID | -NodeId | 2 | The new node's id; different from the existing server's and not 0. |
RDB_NODE_ADDR | -NodeAddr | required | The new node's address. |
RDB_PEER_ADDR | -PeerAddr | required | The existing server's address. |
RDB_PEER_NAME | -PeerName | one | The existing server's name in SHOW REPLICATION. |
RDB_PEER_FINGERPRINT | -PeerFingerprint | none | The existing server's fingerprint. Without it, the script seeds and prints the new node's fingerprint but does not start. |
RDB_REPL_PORT, RDB_PEER_PORT | -ReplPort, -PeerPort | 61171 | Replication ports. |
RDB_REPL_MODE | -Mode | async | async, sync, quorum:N or all. |
RDB_CLUSTER | -Cluster | rasterizeddb | The cluster name; the same on both. |
RDB_PG_LISTEN | -PgListen | 0.0.0.0 | Where applications reach PostgreSQL on the new node. |
RDB_S3_BUCKET, RDB_S3_PREFIX | -Bucket, -Prefix | required on the first run | The existing server's backups. |
RDB_S3_REGION, RDB_S3_ENDPOINT, RDB_S3_PATH_STYLE=1 | -Region, -Endpoint, -PathStyle | as for backups | The store's region, URL and addressing. |
Existing server (prepare-existing-node.sh, .ps1):
| bash variable | PowerShell parameter | Default | What it does |
|---|---|---|---|
RDB_DATA | -Data | /var/lib/rasterizeddb; C:\ProgramData\RasterizedDB\data | The existing server's --location. |
RDB_IDENTITY_DIR | -IdentityDir | /etc/rasterizeddb/replication; C:\ProgramData\RasterizedDB\replication | Its replication certificate and key. |
RDB_NODE_ID | -NodeId | 1 | Its node id. |
RDB_NODE_ADDR | -NodeAddr | required | Its address. |
RDB_PEER_ADDR | -PeerAddr | required | The new node's address. |
RDB_PEER_NAME | -PeerName | two | The new node's name in SHOW REPLICATION. |
RDB_PEER_FINGERPRINT | -PeerFingerprint | placeholder | The new node's fingerprint, put into the printed flags. |
RDB_SERVICE_USER | none | Linux: the user the server runs as (for example rasterizeddb), to own the identity files. |
Run it
-
Stop writes and archive the log. Stop the applications that write to the existing server, then make everything committed so far restorable:
shPGPASSWORD='…' psql "postgresql://rasterized@10.0.0.1:5432/postgres?sslmode=require" -c "BACKUP WAL" -
Stop the existing server, for example
sudo systemctl stop rasterizeddb. -
Seed the new node from the backup. This restores the copy, removes the existing server's replication files and key/value store definitions from it, and prints the new node's fingerprint:
shexport AWS_ACCESS_KEY_ID='…' AWS_SECRET_ACCESS_KEY='…' RDB_NODE_ADDR=10.0.0.2 RDB_PEER_ADDR=10.0.0.1 RDB_S3_BUCKET=my-backups RDB_S3_PREFIX=prod/main ./setup.sh -
Prepare the existing server. This moves its replication files aside to
<data>.replication-aside-<time>, makes its identity, and prints its fingerprint and the flags to add:shsudo RDB_NODE_ADDR=10.0.0.1 RDB_PEER_ADDR=10.0.0.2 RDB_SERVICE_USER=rasterizeddb \ RDB_PEER_FINGERPRINT=<new node's fingerprint> RDB_BIN=/usr/local/bin/rasterizeddb ./prepare-existing-node.sh -
Start the existing server with the printed flags added to its usual ones (under the systemd-service recipe, append them to
RASTERIZEDDB_ARGSin/etc/rasterizeddb/rasterizeddb.envandsudo systemctl start rasterizeddb). -
Start the new node with the existing server's fingerprint, then start the applications again:
shRDB_NODE_ADDR=10.0.0.2 RDB_PEER_ADDR=10.0.0.1 RDB_PEER_FINGERPRINT=<existing server's fingerprint> ./setup.sh
The PowerShell scripts take the same steps with -NodeAddr, -PeerAddr, -Bucket, -Prefix and -PeerFingerprint.
Check that it works
On the existing server, the new node's line in SHOW REPLICATION reads up, and its acked reaches the existing server's local sequence after a write:
export PGPASSWORD='…'
psql "postgresql://rasterized@10.0.0.1:5432/postgres?sslmode=require" \
-c "CREATE TABLE replica_check (id INT PRIMARY KEY)" -c "INSERT INTO replica_check VALUES (1)" -c "SHOW REPLICATION"
psql "postgresql://rasterized@10.0.0.2:5432/postgres?sslmode=require" -c "SELECT * FROM replica_check" -c "REPLICATION CHECK"If the new node shows acked greater than the existing server's local sequence, a stale replication file survived on one side: stop both and repeat steps 3 and 4.
Stop or undo
To go back to a single server: stop both, remove the replication flags from the existing server's command line, and start it. Its old replication files are in <data>.replication-aside-<time>; it does not need them to run. Delete the new node's directory and its .seeded file.
Limits
- This adds a second node to a server that does not replicate yet. Adding a third node to a running pair would mean resetting the replication files on every node it pairs with, which this recipe does not do.
- The new node does not back up to the existing server's S3 prefix. A restored copy is a new database to the backups, and that prefix refuses it. Give it a prefix of its own if it should be backed up too.
- The copy is as of the last log upload. Anything written after
BACKUP WALin step 1 and before the existing server stopped would be on the existing server only, which is why writes stop first. - Key/value store definitions are removed from the copy so that the two nodes never write to the same store; tables restored from a store come back as ordinary tables on the new node.
The files
#!/usr/bin/env bash
# RasterizedDB: turn a running single server into a replicated pair by adding
# a new node, seeded from the existing server's S3 backups.
#
# Run this on the NEW node; run prepare-existing-node.sh on the existing one.
# The order is in the README. The first run restores the copy, removes what
# belongs to the existing node (its replication files, its key/value store
# definitions), makes this node's replication identity and prints its
# fingerprint. Run it again with RDB_PEER_FINGERPRINT to start (foreground).
set -euo pipefail
RDB_BIN="${RDB_BIN:-rasterizeddb}"
RDB_DATA="${RDB_DATA:-./data}" # the new node's database directory
RDB_IDENTITY_DIR="${RDB_IDENTITY_DIR:-./replication-identity}"
RDB_NODE_ID="${RDB_NODE_ID:-2}" # must differ from the existing node's (1 by default)
RDB_NODE_ADDR="${RDB_NODE_ADDR:-}" # required: this node's address
RDB_PEER_ADDR="${RDB_PEER_ADDR:-}" # required: the existing node's address
RDB_PEER_NAME="${RDB_PEER_NAME:-one}"
RDB_PEER_FINGERPRINT="${RDB_PEER_FINGERPRINT:-}" # the existing node's fingerprint, to start
RDB_REPL_PORT="${RDB_REPL_PORT:-61171}"
RDB_PEER_PORT="${RDB_PEER_PORT:-61171}"
RDB_REPL_MODE="${RDB_REPL_MODE:-async}"
RDB_CLUSTER="${RDB_CLUSTER:-rasterizeddb}"
RDB_PG_LISTEN="${RDB_PG_LISTEN:-0.0.0.0}"
# Where the existing node's backups are (the s3-backup-pitr recipe):
RDB_S3_BUCKET="${RDB_S3_BUCKET:-}"
RDB_S3_PREFIX="${RDB_S3_PREFIX:-rasterizeddb/main}"
RDB_S3_REGION="${RDB_S3_REGION:-${AWS_REGION:-us-east-1}}"
RDB_S3_ENDPOINT="${RDB_S3_ENDPOINT:-}"
RDB_S3_PATH_STYLE="${RDB_S3_PATH_STYLE:-0}"
die() { echo "error: $*" >&2; exit 1; }
command -v "$RDB_BIN" >/dev/null 2>&1 || die "'$RDB_BIN' not found; set RDB_BIN to the server binary"
[ -n "$RDB_NODE_ADDR" ] || die "set RDB_NODE_ADDR to this node's address"
[ -n "$RDB_PEER_ADDR" ] || die "set RDB_PEER_ADDR to the existing node's address"
[ -n "$RDB_NODE_ID" ] && [ "$RDB_NODE_ID" != 0 ] || die "RDB_NODE_ID must be set, differ from the existing node's, and not be 0"
parent="$(dirname "$RDB_DATA")"
mkdir -p "$parent"
RDB_DATA="$(cd "$parent" && pwd)/$(basename "$RDB_DATA")"
seeded="$RDB_DATA.seeded"
# 1. The copy: the existing node's latest backup, restored here once.
if [ ! -f "$seeded" ]; then
if [ -d "$RDB_DATA" ] && [ -n "$(ls -A "$RDB_DATA")" ]; then
die "$RDB_DATA already holds files but was not seeded by this script; give an empty RDB_DATA"
fi
[ -n "$RDB_S3_BUCKET" ] || die "set RDB_S3_BUCKET and RDB_S3_PREFIX to the existing node's backups"
: "${AWS_ACCESS_KEY_ID:?set AWS_ACCESS_KEY_ID for the bucket}"
: "${AWS_SECRET_ACCESS_KEY:?set AWS_SECRET_ACCESS_KEY for the bucket}"
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY
restore=(--restore-to "$RDB_DATA" --s3-bucket "$RDB_S3_BUCKET" --s3-prefix "$RDB_S3_PREFIX" --s3-region "$RDB_S3_REGION")
[ -z "$RDB_S3_ENDPOINT" ] || restore+=(--s3-endpoint "$RDB_S3_ENDPOINT")
[ "$RDB_S3_PATH_STYLE" != 1 ] || restore+=(--s3-path-style)
"$RDB_BIN" "${restore[@]}"
# What describes the existing node rather than this one: its position in its
# own replication stream (left behind, this node would silently skip its
# first writes), and its key/value store definitions and their credentials.
find "$RDB_DATA" -type f \( -name 'db_replication.*' -o -name 'db_kv.cfg' -o -name 'db_kv_secrets.cfg' \
-o -name 'backup_instance.id' \) -print -delete | sed 's/^/removed from the copy: /'
date -u +%Y-%m-%dT%H:%M:%SZ > "$seeded"
echo "Seeded $RDB_DATA"
fi
# 2. This node's identity.
mkdir -p "$RDB_IDENTITY_DIR"
RDB_IDENTITY_DIR="$(cd "$RDB_IDENTITY_DIR" && pwd)"
cert="$RDB_IDENTITY_DIR/replication-cert.pem"
key="$RDB_IDENTITY_DIR/replication-key.pem"
if [ ! -f "$cert" ] || [ ! -f "$key" ]; then
out="$("$RDB_BIN" --replication-generate-identity "$RDB_IDENTITY_DIR" --replication-addr "$RDB_NODE_ADDR")"
echo "$out"
echo "$out" | sed -n 's/^fingerprint: *//p' > "$RDB_IDENTITY_DIR/fingerprint"
fi
mine="$(cat "$RDB_IDENTITY_DIR/fingerprint" 2>/dev/null || true)"
[ -n "$mine" ] || die "no fingerprint saved in $RDB_IDENTITY_DIR/fingerprint; delete the identity files there to make a new one"
if [ -z "$RDB_PEER_FINGERPRINT" ]; then
echo
echo "This node's fingerprint: $mine"
echo "Give it to the existing node (prepare-existing-node.sh prints the flags), then run this"
echo "again with RDB_PEER_FINGERPRINT=<the existing node's fingerprint> to start."
exit 0
fi
# 3. Start, replicating with the existing node. The roles came with the copy.
args=(--location "$RDB_DATA" --protocol both --pg-addr "$RDB_PG_LISTEN"
--replication --node-id "$RDB_NODE_ID" --replication-cluster "$RDB_CLUSTER"
--replication-addr "$RDB_NODE_ADDR" --replication-port "$RDB_REPL_PORT"
--replication-auth pinned --replication-cert "$cert" --replication-key "$key"
--replication-peer-fingerprint "$RDB_PEER_FINGERPRINT"
--peer "$RDB_PEER_NAME@$RDB_PEER_ADDR:$RDB_PEER_PORT"
--replication-mode "$RDB_REPL_MODE")
echo "Node $RDB_NODE_ID: replication on $RDB_NODE_ADDR:$RDB_REPL_PORT, peer $RDB_PEER_NAME at $RDB_PEER_ADDR:$RDB_PEER_PORT."
echo "PostgreSQL: postgresql://rasterized@$RDB_NODE_ADDR:5432/postgres?sslmode=require (the existing node's roles)"
echo
exec "$RDB_BIN" "${args[@]}"#Requires -Version 5.1
<#
.SYNOPSIS
RasterizedDB: turn a running single server into a replicated pair by adding
a new node, seeded from the existing server's S3 backups.
.DESCRIPTION
Run this on the NEW node; run prepare-existing-node.ps1 on the existing one.
The order is in the README. The first run restores the copy, removes what
belongs to the existing node (its replication files, its key/value store
definitions), makes this node's replication identity and prints its
fingerprint. Run it again with -PeerFingerprint to start (foreground).
.EXAMPLE
$env:AWS_ACCESS_KEY_ID = '…'; $env:AWS_SECRET_ACCESS_KEY = '…'
.\setup.ps1 -NodeAddr 10.0.0.2 -PeerAddr 10.0.0.1 -Bucket my-backups -Prefix prod/main
.EXAMPLE
.\setup.ps1 -NodeAddr 10.0.0.2 -PeerAddr 10.0.0.1 -PeerFingerprint 9f86d081…
#>
[CmdletBinding()]
param(
[string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }),
# The new node's database directory.
[string]$Data = $(if ($env:RDB_DATA) { $env:RDB_DATA } else { '.\data' }),
[string]$IdentityDir = $(if ($env:RDB_IDENTITY_DIR) { $env:RDB_IDENTITY_DIR } else { '.\replication-identity' }),
# Must differ from the existing node's (1 by default).
[int]$NodeId = $(if ($env:RDB_NODE_ID) { [int]$env:RDB_NODE_ID } else { 2 }),
[string]$NodeAddr = $env:RDB_NODE_ADDR,
# The existing node's address.
[string]$PeerAddr = $env:RDB_PEER_ADDR,
[string]$PeerName = $(if ($env:RDB_PEER_NAME) { $env:RDB_PEER_NAME } else { 'one' }),
[string]$PeerFingerprint = $env:RDB_PEER_FINGERPRINT,
[int]$ReplPort = $(if ($env:RDB_REPL_PORT) { [int]$env:RDB_REPL_PORT } else { 61171 }),
[int]$PeerPort = $(if ($env:RDB_PEER_PORT) { [int]$env:RDB_PEER_PORT } else { 61171 }),
[string]$Mode = $(if ($env:RDB_REPL_MODE) { $env:RDB_REPL_MODE } else { 'async' }),
[string]$Cluster = $(if ($env:RDB_CLUSTER) { $env:RDB_CLUSTER } else { 'rasterizeddb' }),
[string]$PgListen = $(if ($env:RDB_PG_LISTEN) { $env:RDB_PG_LISTEN } else { '0.0.0.0' }),
# Where the existing node's backups are (the s3-backup-pitr recipe).
[string]$Bucket = $env:RDB_S3_BUCKET,
[string]$Prefix = $(if ($env:RDB_S3_PREFIX) { $env:RDB_S3_PREFIX } else { 'rasterizeddb/main' }),
[string]$Region = $(if ($env:RDB_S3_REGION) { $env:RDB_S3_REGION } elseif ($env:AWS_REGION) { $env:AWS_REGION } else { 'us-east-1' }),
[string]$Endpoint = $env:RDB_S3_ENDPOINT,
[switch]$PathStyle = ($env:RDB_S3_PATH_STYLE -eq '1')
)
$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 $NodeAddr) { throw "Pass -NodeAddr with this node's address." }
if (-not $PeerAddr) { throw "Pass -PeerAddr with the existing node's address." }
if ($NodeId -le 0) { throw "-NodeId must differ from the existing node's and not be 0." }
$parent = Split-Path -Parent $Data
if (-not $parent) { $parent = '.' }
New-Item -ItemType Directory -Force -Path $parent | Out-Null
$Data = Join-Path (Resolve-Path -LiteralPath $parent).Path (Split-Path -Leaf $Data)
$seeded = "$Data.seeded"
# 1. The copy: the existing node's latest backup, restored here once.
if (-not (Test-Path -LiteralPath $seeded)) {
if ((Test-Path -LiteralPath $Data) -and (Get-ChildItem -LiteralPath $Data -Force | Select-Object -First 1)) {
throw "$Data already holds files but was not seeded by this script; give an empty -Data."
}
if (-not $Bucket) { throw "Pass -Bucket and -Prefix for the existing node's backups." }
if (-not $env:AWS_ACCESS_KEY_ID -or -not $env:AWS_SECRET_ACCESS_KEY) { throw 'Set $env:AWS_ACCESS_KEY_ID and $env:AWS_SECRET_ACCESS_KEY for the bucket.' }
$restore = @('--restore-to', $Data, '--s3-bucket', $Bucket, '--s3-prefix', $Prefix, '--s3-region', $Region)
if ($Endpoint) { $restore += @('--s3-endpoint', $Endpoint) }
if ($PathStyle) { $restore += '--s3-path-style' }
& $cmd.Source @restore
if ($LASTEXITCODE -ne 0) { throw "The restore failed (exit $LASTEXITCODE); the message is above." }
# What describes the existing node rather than this one: its position in
# its own replication stream (left behind, this node would silently skip
# its first writes), and its key/value store definitions and credentials.
@(Get-ChildItem -LiteralPath $Data -Recurse -File -Force) |
Where-Object { $_.Name -like 'db_replication.*' -or $_.Name -in @('db_kv.cfg', 'db_kv_secrets.cfg', 'backup_instance.id') } |
ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force; Write-Host "removed from the copy: $($_.FullName)" }
Set-Content -LiteralPath $seeded -Value ((Get-Date).ToUniversalTime().ToString('o')) -Encoding ascii
Write-Host "Seeded $Data"
}
# 2. This node's identity.
New-Item -ItemType Directory -Force -Path $IdentityDir | Out-Null
$IdentityDir = (Resolve-Path -LiteralPath $IdentityDir).Path
$cert = Join-Path $IdentityDir 'replication-cert.pem'
$key = Join-Path $IdentityDir 'replication-key.pem'
$fpFile = Join-Path $IdentityDir 'fingerprint'
if (-not (Test-Path -LiteralPath $cert) -or -not (Test-Path -LiteralPath $key)) {
$out = & $cmd.Source --replication-generate-identity $IdentityDir --replication-addr $NodeAddr
if ($LASTEXITCODE -ne 0) { throw 'Could not generate the replication identity; the message is above.' }
$out | ForEach-Object { Write-Host $_ }
$fp = $out | ForEach-Object { if ($_ -match '^fingerprint:\s*(\S+)') { $Matches[1] } } | Select-Object -First 1
Set-Content -LiteralPath $fpFile -Value $fp -Encoding ascii
& icacls.exe $key /inheritance:r /grant:r "$($env:USERNAME):F" '*S-1-5-18:F' '*S-1-5-32-544:F' | Out-Null
}
$mine = if (Test-Path -LiteralPath $fpFile) { (Get-Content -LiteralPath $fpFile -Raw).Trim() } else { '' }
if (-not $mine) { throw "No fingerprint saved in $fpFile; delete the identity files there to make a new one." }
if (-not $PeerFingerprint) {
Write-Host ''
Write-Host "This node's fingerprint: $mine"
Write-Host 'Give it to the existing node (prepare-existing-node.ps1 prints the flags), then run this'
Write-Host "again with -PeerFingerprint <the existing node's fingerprint> to start."
exit 0
}
# 3. Start, replicating with the existing node. The roles came with the copy.
$serverArgs = @('--location', $Data, '--protocol', 'both', '--pg-addr', $PgListen,
'--replication', '--node-id', "$NodeId", '--replication-cluster', $Cluster,
'--replication-addr', $NodeAddr, '--replication-port', "$ReplPort",
'--replication-auth', 'pinned', '--replication-cert', $cert, '--replication-key', $key,
'--replication-peer-fingerprint', $PeerFingerprint,
'--peer', "$PeerName@${PeerAddr}:$PeerPort",
'--replication-mode', $Mode)
Write-Host "Node ${NodeId}: replication on ${NodeAddr}:$ReplPort, peer $PeerName at ${PeerAddr}:$PeerPort."
Write-Host "PostgreSQL: postgresql://rasterized@${NodeAddr}:5432/postgres?sslmode=require (the existing node's roles)"
Write-Host ''
& $cmd.Source @serverArgs
exit $LASTEXITCODE#!/usr/bin/env bash
# RasterizedDB: prepare the EXISTING server to pair with a new node seeded
# from its backup. Run it while that server is stopped.
#
# It moves the server's replication files aside (never deletes them): they
# describe the stream it had before the copy was made, and a pair that starts
# from one copy must both start from nothing. Then it makes the server's
# replication identity and prints the flags to start it with.
set -euo pipefail
RDB_BIN="${RDB_BIN:-rasterizeddb}"
RDB_DATA="${RDB_DATA:-/var/lib/rasterizeddb}" # the existing server's --location
RDB_IDENTITY_DIR="${RDB_IDENTITY_DIR:-/etc/rasterizeddb/replication}"
RDB_NODE_ID="${RDB_NODE_ID:-1}"
RDB_NODE_ADDR="${RDB_NODE_ADDR:-}" # required: this server's address
RDB_PEER_ADDR="${RDB_PEER_ADDR:-}" # required: the new node's address
RDB_PEER_NAME="${RDB_PEER_NAME:-two}"
RDB_PEER_FINGERPRINT="${RDB_PEER_FINGERPRINT:-<fingerprint of the new node>}"
RDB_REPL_PORT="${RDB_REPL_PORT:-61171}"
RDB_PEER_PORT="${RDB_PEER_PORT:-61171}"
RDB_CLUSTER="${RDB_CLUSTER:-rasterizeddb}"
RDB_SERVICE_USER="${RDB_SERVICE_USER:-}" # e.g. rasterizeddb: owner of the identity files
die() { echo "error: $*" >&2; exit 1; }
command -v "$RDB_BIN" >/dev/null 2>&1 || die "'$RDB_BIN' not found; set RDB_BIN to the server binary"
[ -d "$RDB_DATA" ] || die "$RDB_DATA is not a directory; set RDB_DATA to the existing server's --location"
[ -n "$RDB_NODE_ADDR" ] || die "set RDB_NODE_ADDR to this server's address"
[ -n "$RDB_PEER_ADDR" ] || die "set RDB_PEER_ADDR to the new node's address"
RDB_DATA="$(cd "$RDB_DATA" && pwd)"
# A running server holds an exclusive lock on rasterizeddb.lock.
if [ -f "$RDB_DATA/rasterizeddb.lock" ] && command -v flock >/dev/null 2>&1 \
&& ! flock -n "$RDB_DATA/rasterizeddb.lock" true; then
die "the server on $RDB_DATA is running; stop it first (after BACKUP WAL, see the README)"
fi
# 1. The replication files, every database's, moved aside with their paths.
aside="$RDB_DATA.replication-aside-$(date -u +%Y%m%dT%H%M%SZ)"
moved=0
while IFS= read -r -d '' f; do
rel="${f#"$RDB_DATA"/}"
mkdir -p "$aside/$(dirname "$rel")"
mv "$f" "$aside/$rel"
echo "moved aside: $rel"
moved=$((moved + 1))
done < <(find "$RDB_DATA" -type f -name 'db_replication.*' -print0)
if [ "$moved" -gt 0 ]; then
echo "Kept in $aside"
else
echo "No replication files in $RDB_DATA"
fi
# 2. This server's identity.
mkdir -p "$RDB_IDENTITY_DIR"
RDB_IDENTITY_DIR="$(cd "$RDB_IDENTITY_DIR" && pwd)"
cert="$RDB_IDENTITY_DIR/replication-cert.pem"
key="$RDB_IDENTITY_DIR/replication-key.pem"
if [ ! -f "$cert" ] || [ ! -f "$key" ]; then
out="$("$RDB_BIN" --replication-generate-identity "$RDB_IDENTITY_DIR" --replication-addr "$RDB_NODE_ADDR")"
echo "$out" | sed -n 's/^fingerprint: *//p' > "$RDB_IDENTITY_DIR/fingerprint"
fi
if [ -n "$RDB_SERVICE_USER" ]; then
chown -R "$RDB_SERVICE_USER:" "$RDB_IDENTITY_DIR"
fi
echo
echo "This server's fingerprint: $(cat "$RDB_IDENTITY_DIR/fingerprint")"
echo
echo "Start it with its usual flags plus:"
echo " --replication --node-id $RDB_NODE_ID --replication-cluster $RDB_CLUSTER \\"
echo " --replication-addr $RDB_NODE_ADDR --replication-port $RDB_REPL_PORT \\"
echo " --replication-auth pinned --replication-cert $cert --replication-key $key \\"
echo " --replication-peer-fingerprint $RDB_PEER_FINGERPRINT \\"
echo " --peer $RDB_PEER_NAME@$RDB_PEER_ADDR:$RDB_PEER_PORT"
echo "Under the systemd-service recipe, add them to RASTERIZEDDB_ARGS in /etc/rasterizeddb/rasterizeddb.env"
echo "(on one line, without the backslashes)."#Requires -Version 5.1
<#
.SYNOPSIS
RasterizedDB: prepare the EXISTING server to pair with a new node seeded
from its backup. Run it while that server is stopped.
.DESCRIPTION
Moves the server's replication files aside (never deletes them): they
describe the stream it had before the copy was made, and a pair that starts
from one copy must both start from nothing. Then makes the server's
replication identity and prints the flags to start it with.
.EXAMPLE
.\prepare-existing-node.ps1 -NodeAddr 10.0.0.1 -PeerAddr 10.0.0.2 -PeerFingerprint 3b1c…
#>
[CmdletBinding()]
param(
[string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }),
# The existing server's --location.
[string]$Data = $(if ($env:RDB_DATA) { $env:RDB_DATA } else { 'C:\ProgramData\RasterizedDB\data' }),
[string]$IdentityDir = $(if ($env:RDB_IDENTITY_DIR) { $env:RDB_IDENTITY_DIR } else { 'C:\ProgramData\RasterizedDB\replication' }),
[int]$NodeId = $(if ($env:RDB_NODE_ID) { [int]$env:RDB_NODE_ID } else { 1 }),
[string]$NodeAddr = $env:RDB_NODE_ADDR,
# The new node's address.
[string]$PeerAddr = $env:RDB_PEER_ADDR,
[string]$PeerName = $(if ($env:RDB_PEER_NAME) { $env:RDB_PEER_NAME } else { 'two' }),
[string]$PeerFingerprint = $(if ($env:RDB_PEER_FINGERPRINT) { $env:RDB_PEER_FINGERPRINT } else { '<fingerprint of the new node>' }),
[int]$ReplPort = $(if ($env:RDB_REPL_PORT) { [int]$env:RDB_REPL_PORT } else { 61171 }),
[int]$PeerPort = $(if ($env:RDB_PEER_PORT) { [int]$env:RDB_PEER_PORT } else { 61171 }),
[string]$Cluster = $(if ($env:RDB_CLUSTER) { $env:RDB_CLUSTER } else { '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 (Test-Path -LiteralPath $Data -PathType Container)) { throw "$Data is not a directory; pass -Data with the existing server's --location." }
if (-not $NodeAddr) { throw "Pass -NodeAddr with this server's address." }
if (-not $PeerAddr) { throw "Pass -PeerAddr with the new node's address." }
$Data = (Resolve-Path -LiteralPath $Data).Path.TrimEnd('\')
# A running server holds a lock on rasterizeddb.lock.
$lock = Join-Path $Data 'rasterizeddb.lock'
if (Test-Path -LiteralPath $lock) {
try {
$fs = [System.IO.File]::Open($lock, 'Open', 'ReadWrite', 'ReadWrite')
try { $fs.Lock(0, 1); $fs.Unlock(0, 1) } finally { $fs.Dispose() }
}
catch { throw "The server on $Data is running; stop it first (after BACKUP WAL, see the README)." }
}
# 1. The replication files, every database's, moved aside with their paths.
$aside = "$Data.replication-aside-$((Get-Date).ToUniversalTime().ToString('yyyyMMddTHHmmssZ'))"
$files = @(Get-ChildItem -LiteralPath $Data -Recurse -File -Force -Filter 'db_replication.*')
foreach ($f in $files) {
$rel = $f.FullName.Substring($Data.Length).TrimStart('\')
$dest = Join-Path $aside $rel
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $dest) | Out-Null
Move-Item -LiteralPath $f.FullName -Destination $dest
Write-Host "moved aside: $rel"
}
if ($files.Count -gt 0) { Write-Host "Kept in $aside" } else { Write-Host "No replication files in $Data" }
# 2. This server's identity.
New-Item -ItemType Directory -Force -Path $IdentityDir | Out-Null
$IdentityDir = (Resolve-Path -LiteralPath $IdentityDir).Path
$cert = Join-Path $IdentityDir 'replication-cert.pem'
$key = Join-Path $IdentityDir 'replication-key.pem'
$fpFile = Join-Path $IdentityDir 'fingerprint'
if (-not (Test-Path -LiteralPath $cert) -or -not (Test-Path -LiteralPath $key)) {
$out = & $cmd.Source --replication-generate-identity $IdentityDir --replication-addr $NodeAddr
if ($LASTEXITCODE -ne 0) { throw 'Could not generate the replication identity; the message is above.' }
$fp = $out | ForEach-Object { if ($_ -match '^fingerprint:\s*(\S+)') { $Matches[1] } } | Select-Object -First 1
Set-Content -LiteralPath $fpFile -Value $fp -Encoding ascii
& icacls.exe $key /inheritance:r /grant:r "$($env:USERNAME):F" '*S-1-5-18:F' '*S-1-5-32-544:F' | Out-Null
}
Write-Host ''
Write-Host "This server's fingerprint: $((Get-Content -LiteralPath $fpFile -Raw).Trim())"
Write-Host ''
Write-Host 'Start it with its usual flags plus (one array element per argument for -ExtraArgs):'
Write-Host " --replication --node-id $NodeId --replication-cluster $Cluster"
Write-Host " --replication-addr $NodeAddr --replication-port $ReplPort"
Write-Host " --replication-auth pinned --replication-cert $cert --replication-key $key"
Write-Host " --replication-peer-fingerprint $PeerFingerprint"
Write-Host " --peer $PeerName@${PeerAddr}:$PeerPort"