# SPEC — behavior contract for all language implementations This document defines the behavior every implementation (`php/`, `bash/`, `powershell/`) must match. When fixing a bug or adding a feature, update this file first, then bring every implementation in line with it, then update CHANGELOG.md. ## Purpose Backs up all databases of every **running** PostgreSQL cluster/instance on the host into per-day, per-cluster directories, keeps a rolling number of daily generations, and mails a run summary. How clusters are found is distro-dependent — see "Cluster / instance discovery" below. ## Versioning The whole project (all language implementations together) shares one version number, not one per language — e.g. "1.3.0" describes the state of `php/`, `bash/`, etc. combined at that point, even if a given release only actually touched one of them. Record what changed per area in CHANGELOG.md. ## Cluster / instance discovery Per-platform discovery strategies. An implementation must support the primary strategy for its platform where the tooling exists, and fall back to the platform's secondary strategy otherwise. ### 1. `pg_lsclusters` (Debian/Ubuntu, via `postgresql-common`) If the `pg_lsclusters` binary exists, use `pg_lsclusters -h -j` and trust its `version`, `cluster`, `running`, `port`, `socketdir` fields directly. This is the only tool that reports multiple *clusters of the same major version* (e.g. `main` + a second cluster on another port), so prefer it whenever available. ### 2. `postmaster.pid` scan (RHEL/CentOS/Rocky/Alma and any other Linux) RHEL-family PostgreSQL (distro package or PGDG `postgresqlNN-server` packages) has no multi-cluster concept and no equivalent listing tool — each major version is normally exactly one instance, one data directory. Detect it generically, using only facts PostgreSQL itself guarantees, not distro conventions: 1. Look for data directories under a configurable list of glob patterns (default: `/var/lib/pgsql/data`, `/var/lib/pgsql/*/data` — covers both the single-instance distro package and versioned PGDG packages; additional globs can be added in the ini file for non-standard installs). 2. A directory is a valid PG data directory if it contains `PG_VERSION` — its content is the major version string (`version`). 3. It's running if `postmaster.pid` exists in that directory. If not present, skip it (log at terse level) exactly like a `pg_lsclusters` cluster with `running != 1`. 4. If running, **parse `postmaster.pid` directly** instead of asking the distro anything: line 4 is the port, line 5 is the socket directory (first entry if it lists more than one, comma-separated). This format is a PostgreSQL server guarantee, identical across distros — it's the same mechanism `pg_ctl`/`pg_isready` rely on, not something specific to RHEL. 5. `cluster` name: RHEL has no user-facing cluster name, so use `main` — there is normally only one instance per version, so this does not collide. (A future multi-instance-per-version setup on RHEL would need a real name source; out of scope for 1.3.0.) ### 3. Windows service enumeration (PowerShell) Windows has no `pg_lsclusters` equivalent either, but this is closer to Debian's model than to RHEL's: every PostgreSQL install (EDB installer, Chocolatey, etc.) registers itself as its own named Windows service running `pg_ctl.exe`, one per version/instance — and Windows genuinely supports several instances side by side under different service names/ports, unlike RHEL. **Deliberately not a port scanner and not a blind directory scan.** A listening port doesn't tell you it's PostgreSQL, which version, or where its data directory is; you'd have to guess a port range and probe every hit. Windows already tracks this authoritatively — use it: 1. `Get-CimInstance Win32_Service | Where-Object { $_.PathName -match 'pg_ctl\.exe' }` — finds every PostgreSQL service regardless of install location or naming, no guessing needed. 2. Extract the data directory from the service's own command line — the `-D ""` argument inside `PathName` (e.g. `"...\pg_ctl.exe" runservice -N "postgresql-x64-15" -D "C:\Program Files\PostgreSQL\15\data" -w`). This is the service definition's authoritative source, not a guess from a naming convention. 3. `running`: the service's `State -eq 'Running'` — more reliable than a pidfile existence check. 4. `version`: read `PG_VERSION` from the data directory, same as strategy 2 — not parsed from the install path, which is user-configurable. 5. `port`: read `postmaster.pid` line 4 — the same pidfile format PostgreSQL uses on every platform. Windows PostgreSQL has no Unix socket, so `socketdir` is not applicable there. 6. `cluster` name: the Windows service name itself (e.g. `postgresql-x64-15`) — unlike RHEL's hardcoded `main`, this correctly distinguishes genuine multiple instances of the same version. Fallback (portable/non-service installs that never register a service): scan a configurable list of glob patterns, the same `pgdata_globs`-style mechanism as strategy 2, for parity with the Linux fallback. All three strategies must produce the same shape: `{version, cluster, running, port, socketdir}`, so the rest of the pipeline (database enumeration, `pg_dump`, directory layout) is identical regardless of which one found the instance. On Windows, `socketdir` is empty/null and implementations must connect via `-h localhost -p ` instead. ## CLI options | Short | Long | Value | Default | Meaning | |-------|---------------|-------|---------------------------------|--------------------------------------------| | `-i` | | path | `/pg_clusterbackup.ini` | ini file to read/write | | `-h` | | str | `gethostname()` | hostname used in mail subject/paths | | `-D` | | path | `/data/backup/postgresql` | backup root directory | | `-T` | | path | `/tmp` | temp directory for in-progress dumps | | `-L` | | path | value of `-D` | log directory | | `-F` | | c/t/p | `c` | `pg_dump` format | | `-d` | | 0-3 | `1` | debug/log level (0=off,1=log,2=terse,3=verbose) | | `-n` | | int | `7` | number of daily generations to keep | | `-j` | | int | `1` | max concurrent `pg_dump` processes per cluster | | `-C` | | int | `1` | max concurrent cluster backups | | `-Z` | `--compress` | str | `""` (pg_dump default) | compression level / spec for `pg_dump` | | `-N` | `--dry-run` | flag | | simulate run without dumping or deleting files | | | `--exclude` | str | `""` | comma-separated globs of database names to skip| | | `--include` | str | `""` | comma-separated globs of database names to keep| | | `--ping-url` | str | `""` | healthcheck URL (start/fail/ok pings) | | | `--email` | str | `monitor@ibou.net` | mail recipient for the run log | | | `--help` | flag | | print usage and exit | | | `--ini-write` | flag | | persist current settings to the ini file | | | `--ini-show` | flag | | print current settings in ini format | All non-flag options are also persisted to / read from the ini file; CLI values always win over ini values. Additional INI settings without dedicated short flags: - `exclude_databases`: comma-separated glob list (e.g. `"test_*,*_tmp"`) - `include_databases`: comma-separated glob list (e.g. `"prod_*,analytics"`) - `min_free_space_gb`: integer (default `0` = off). If set, checks available disk space on `backupdir` and `tempdir`. - `compression`: string forwarded to `pg_dump` (e.g. `"6"` or `"zstd:3"`) - `ping_url`: URL for healthchecks/monitoring pings **PowerShell deviation:** PowerShell parameter names/aliases are case-insensitive, so `-D` (backup dir) and `-d` (debug level) can't coexist as distinct flags there. The PowerShell port keeps `-D`/`-BackupDir`, but debug level is `-DebugLevel` (alias `-dl`) instead of `-d`. `-C` is aliased to `-ParallelClusters` (alias `-cj`), `-Z` is `-Compression`, `-n` is `-MaxKeep` (so `-DryRun` / alias `-WhatIf` replaces `-N`), `--exclude` is `-ExcludeDatabases`, `--include` is `-IncludeDatabases`, and `--ping-url` is `-PingUrl`. It also uses full names for the long options (`-Help`, `-IniWrite`, `-IniShow`, `-Email`) rather than `--double-dash` syntax, since that isn't idiomatic PowerShell. Behavior is otherwise identical. ## Parallel database dumps and parallel cluster backups - `-j`/`parallel_jobs` (default `1`, i.e. sequential database behavior) bounds how many `pg_dump` processes run concurrently **within one cluster's database list**. - `-C`/`parallel_clusters` (default `1`, i.e. sequential cluster behavior) bounds how many clusters are backed up concurrently. **Deliberately not `pg_dump -j`/`--jobs`.** That flag only works with the directory format (`-Fd`), which would turn each database's backup into a directory of files instead of the single `.cus` file this project promises in "Directory layout produced" and in the documented `pg_restore` command — a breaking change to the restore story, not a tuning knob. Parallelism here instead means: launch up to `-j` separate `pg_dump` processes for different databases at the same time, each still producing its own single `-F` file exactly as today. Requirements common to all implementations: - **Per-cluster temp isolation**: In-progress files (`.cus`, `globals.sql`) are isolated in a dedicated cluster subfolder inside the configured `tempdir` (e.g. `/_/`) or with a distinct prefix, so concurrent clusters never overwrite each other's files. The cluster temp directory is cleaned up upon cluster completion. On Linux the dumps run as `postgres` (`sudo -u postgres`), so the cluster temp directory must belong to `postgres` (mode `0700`): when running as root, create it and `chown` it to `postgres`; otherwise create it as `postgres`. The configured `tempdir` itself only has to be traversable for `postgres` (the default `/tmp` is). - **Cluster log prefix**: When logging events belonging to a specific cluster (listing databases, dumping databases, dumping globals, error messages, rotation), the log line includes the cluster prefix: `[] ` (e.g. `2026-09-14 20:15:00 [main] Starting backup Database: app_db`). This ensures that interleaved logs from concurrent clusters can be clearly distinguished and followed. - **Worker-pool patterns**: - Up to `-C` clusters run in parallel. - Up to `-j` `pg_dump` processes run in parallel per cluster. - On the **first** failure among concurrent jobs: stop launching new ones, let already-running jobs finish (don't leave orphaned child processes), then fail with a fatal error. - A database's temp-to-backup move (and its log line) happens right after *that* job finishes, not batched at the end. - Globals (`pg_dumpall -g`) are never parallelized — always one call per cluster, after all database dumps for that cluster have finished. - **Per-cluster rotation**: Rotation is performed per cluster immediately after that cluster's backup succeeds. It prunes `/*//` older than the newest `-n` generations for that cluster. Any parent date directories that become completely empty as a result are deleted. - **Database filtering (`exclude_databases` / `include_databases`)**: - `postgres` and template databases (`datistemplate = true`) are always excluded. - If `include_databases` is set, only database names matching at least one glob pattern in the comma-separated list are kept. - If `exclude_databases` is set, any database name matching any glob pattern in the comma-separated list is skipped (logged at debug level 1). - Glob matching supports standard wildcards `*` and `?`. - **Database size & disk space checks**: - Query database sizes via `SELECT datname, pg_database_size(datname)`. - Log database raw size at start of dump: `[] Starting backup Database: (raw size: )`. - If `min_free_space_gb` > 0, verify that both `backupdir` and `tempdir` have at least that many gigabytes free before proceeding with dumps. If insufficient, abort with a fatal error. - **Dry-run mode (`-N` / `--dry-run`)**: - Simulates the entire process without writing dumps or deleting old backups. - Logs cluster discovery, database listings with sizes, filter decisions, target paths, and rotation targets. - Prepends `[DRY-RUN]` to log/subject lines. - **Backup manifest (`manifest.json`)**: - Written into `////manifest.json` after successful backup of each cluster. - Contains JSON metadata: version, date, cluster, pg_version, hostname, start/end timestamps, duration, per-database files and raw/dump sizes, and globals status. - **Healthcheck / monitoring webhook (`ping_url`)**: - If configured, sends an HTTP GET/POST to `/start` when the backup run begins. - On overall success, sends an HTTP GET/POST to ``. - On fatal error, sends an HTTP GET/POST to `/fail`. Network errors when calling ping URLs are logged but do not crash the run. ## Ini file format Standard INI, one `key = "value"` per line, no sections unless a setting is itself an array. Written with `ini-write`, read on every run if present. ## Directory layout produced ``` ////.cus ////globals.sql ////manifest.json ``` ## Run behavior (must match across implementations) 1. Acquire an exclusive lock (e.g. `/pg_clusterbackup.lock`) — abort with a clear error if another run holds it. Never let two runs write to the same temp files concurrently. 2. If `ping_url` is configured, send start ping (`/start`). 3. If `min_free_space_gb` is set, verify free disk space on `backupdir` and `tempdir`. 4. Enumerate clusters; skip (and log) any cluster where `running != 1`. 5. For each running cluster (up to `-C` concurrently): a. Create an isolated temp directory for the cluster (`/_/`). b. List non-template databases (excluding `postgres`) with `pg_database_size`. c. Apply `include_databases` / `exclude_databases` filters. d. In dry-run mode, log actions and skip actual dump/delete operations. e. Dump each database with `pg_dump -c -F` (and compression option if set) to a temp file, then move it into the final dated path. Up to `-j` databases may be dumped concurrently. f. Dump globals with `pg_dumpall -g` to `/_/globals.sql` and move to final path. g. Write `manifest.json` with cluster backup metrics. h. Immediately rotate and prune old backup generations for that cluster beyond the newest `-n` generations. i. Clean up the cluster's temp directory. 6. If all running clusters finished without fatal errors, clean up any now-empty date directories. 7. Send success ping to `ping_url` if configured. 8. Mail the collected log (🟢 OK on success, 🟥 failed on any fatal error, 🟡 DRY-RUN for simulation) if an email recipient is configured and there is anything to report. 9. All values interpolated into shell commands must be shell-escaped. 10. A move from temp dir to backup dir must work even when both are on different filesystems (fall back to copy+remove if a direct rename/move fails). ## Exit / error behavior - Any fatal error during backup must still result in a failure mail being sent (and `/fail` pinged), with the error message included in the log — even if the error happened during initial setup. - `--help`, `--ini-write`, `--ini-show` never trigger a backup run.