#!/usr/bin/env bash # RasterizedDB Enterprise: add a customer to a server in strict tenant mode. # Creates the database RDB_TENANT with only its administrator RDB_TENANT_OWNER # in it, and records its limits in the tenant directory. # Needs release 1.1.0 or later. # # PGPASSWORD= RDB_TENANT=acme RDB_TENANT_OWNER=acme_admin \ # RDB_TENANT_PASSWORD='…' RDB_TENANT_CONNECTIONS=50 ./create-tenant.sh set -euo pipefail RDB_PG_URL="${RDB_PG_URL:-postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require}" # the operator database RDB_TENANT="${RDB_TENANT:-}" # required: the customer's database RDB_TENANT_OWNER="${RDB_TENANT_OWNER:-}" # required: its administrator role RDB_TENANT_CONNECTIONS="${RDB_TENANT_CONNECTIONS:-}" # e.g. 50 RDB_TENANT_STORAGE="${RDB_TENANT_STORAGE:-}" # e.g. 20GB RDB_TENANT_STATEMENT_TIMEOUT="${RDB_TENANT_STATEMENT_TIMEOUT:-}" # e.g. 60s die() { echo "error: $*" >&2; exit 1; } command -v psql >/dev/null 2>&1 || die "psql is needed" [ -n "${PGPASSWORD:-}" ] || die "set PGPASSWORD to the operator's password" [ -n "$RDB_TENANT" ] && [ -n "$RDB_TENANT_OWNER" ] || die "set RDB_TENANT and RDB_TENANT_OWNER" : "${RDB_TENANT_PASSWORD:?set RDB_TENANT_PASSWORD to the password of the administrator}" for v in "$RDB_TENANT" "$RDB_TENANT_OWNER"; do [[ "$v" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "$v: use letters, digits and _ only" done case "$RDB_TENANT_PASSWORD$RDB_TENANT_STORAGE$RDB_TENANT_STATEMENT_TIMEOUT" in *"'"*) die "values may not contain a single quote" ;; esac limits="" [ -z "$RDB_TENANT_CONNECTIONS" ] || limits="${limits:+$limits, }connections = $RDB_TENANT_CONNECTIONS" [ -z "$RDB_TENANT_STORAGE" ] || limits="${limits:+$limits, }storage = '$RDB_TENANT_STORAGE'" [ -z "$RDB_TENANT_STATEMENT_TIMEOUT" ] || limits="${limits:+$limits, }statement_timeout = '$RDB_TENANT_STATEMENT_TIMEOUT'" # On standard input, so the password does not appear in the process list. statement="CREATE TENANT $RDB_TENANT OWNER $RDB_TENANT_OWNER PASSWORD '$RDB_TENANT_PASSWORD'${limits:+ LIMITS ($limits)};" printf '%s\n' "$statement" | psql "$RDB_PG_URL" -v ON_ERROR_STOP=1 -X -q psql "$RDB_PG_URL" -X -c "SHOW TENANTS" host="$(printf '%s' "$RDB_PG_URL" | sed -E 's#^[a-z]+://([^@/]*@)?([^/?]*).*#\2#')" echo "The customer connects with: postgresql://$RDB_TENANT_OWNER@$host/$RDB_TENANT?sslmode=require"