PGHoard Documentation

repository·main·Indexed 23 days ago

https://github.com/aiven-open/pghoard

A PostgreSQL automatic backup and restore service daemon that automates basebackups and WAL (Write-Ahead Log) archiving to cloud object storage including AWS S3, Azure, GCP, OpenStack Swift, and Ceph. PGHoard supports Point-in-Time Recovery (PITR), standby initialization, and provides tools for archive integrity verification, cleanup, and encryption.

Tokens
25.4K
Snippets
40
Records
157
Agent score
80%

What's inside pghoard

  1. Overview of PGHoard features

    main

    PGHoard is a tool designed for PostgreSQL backup and recovery. Its core capabilities include:

    Backup Capabilities

    • Automatic periodic basebackups: Scheduled full backups of the database.
    • Automatic transaction log (WAL/xlog) backups: Supports multiple methods including pg_receivewal (formerly pg_receivexlog), archive_command, or experimental PG native replication protocol support via walreceiver.
    • Standalone Hot Backup support: Optional support for performing backups without a running standby.
    • Cloud object storage support: Compatible with AWS S3, Google Cloud, OpenStack Swift, Azure, and Ceph.

    Recovery and Restoration

    • Point-in-time-recovery (PITR): Restore the database to a specific moment in time.
    • Direct restoration: Restore directly from object storage with built-in compression and encryption.
    • Standby initialization: Automatically configure and initialize a new standby from object storage backups as a replicating hot-standby.

    Reliability and Monitoring

    • Fault-resilience: Retries transfers during temporary object storage connectivity issues and verifies WAL file headers to prevent issues with recycled files.
    • Maintenance tools: Includes an "Archive sync" tool to detect and fix holes in WAL backup streams, and an "Archive cleanup" tool to delete obsolete WAL files.
    • Monitoring: Automatically manages history cleanup (deleting backups/WAL older than N days), updates statistics in a local file, and creates alert files on disk when problems occur.

    Performance

    • Parallelism: Uses parallel compression and encryption.
    • Optimized Restore: Implements WAL pre-fetching during the restoration process.
  2. How PGHoard works: Architecture and PITR

    main

    PGHoard implements PostgreSQL Point In Time Replication (PITR) by managing both basebackups and Write-Ahead Log (WAL) files. It runs as a daemon that automates three core tasks:

    1. Taking periodical basebackups: Captures the state of the database at specific intervals.
    2. Archiving the WAL: Collects the stream of changes occurring after a basebackup.
    3. Managing retention: Automatically expires old backups and associated WAL files based on a configured policy.

    By combining a basebackup with the replayed WAL logs, you can restore a database to any desired point in time.

  3. Use pghoard_postgres_command for PostgreSQL archiving

    main
    The pghoard_postgres_command is a CLI tool designed to be used as PostgreSQL's archive_command or recovery_command. It communicates with a locally running pghoard webserver to handle the compression, encryption, and storage (in archive mode) or retrieval (in restore mode) of WAL files.
  4. Configure WAL Archiving models

    main

    PGHoard provides three different operating models for fetching WAL files, allowing you to choose based on how much access you have to the source PostgreSQL server:

    1. pg_receivewal mode: PGHoard fetches WAL files using the standard pg_receivewal utility (or pg_receivexlog for PostgreSQL versions < 10). This is ideal if you do not want to modify the source server's configuration.
    2. walreceiver mode: PGHoard uses its own internal replication client to fetch WALs. Note that this mode is currently experimental.
    3. pghoard_postgres_command mode: Uses the traditional PostgreSQL archive_command approach by providing a utility that the database calls directly to archive logs.
  5. Configure Compression and Encryption

    main

    PGHoard supports various methods for securing and shrinking backup data:

    Compression

    By default, WAL files and basebackups are compressed using Snappy to balance compression speed and size. You can also configure Zstandard or LZMA compression.

    Encryption

    Encryption is not enabled by default. When enabled, PGHoard encrypts and authenticates each individual file using file-specific keys. These file-specific keys are themselves encrypted using a master RSA private/public key pair and stored within the backup. For setup instructions, refer to the encryption section in the quickstart guide.

  6. Choose a basebackup mode

    main

    The basebackup_mode setting determines how PostgreSQL data is extracted. Note that neither basic nor pipe modes support multiple tablespaces.

    • basic (default): Runs pg_basebackup and waits for it to write an uncompressed tar file to disk before compressing and optionally encrypting it.
    • pipe: Pipes data directly from pg_basebackup to PGHoard's compression/encryption pipeline, reducing temporary disk space requirements.
    • local-tar: Bypasses pg_basebackup by reading files directly from $PGDATA. This mode supports user tablespaces. Requires pg_data_directory to be set. Use basebackup_threads (values 1 or 2) to optimize this mode.
    • delta: Only uploads changed files by using file hashes and manifests. This is efficient for storage but requires a manifest for restoration.
    • local-tar-delta-stats: Behaves like local-tar but collects metrics to help evaluate the efficiency of switching to delta mode.
  7. Configure Backup Retention

    main
    PGHoard manages storage by expiring backups according to a configured retention policy. When the number of backups exceeds the specified limit, PGHoard automatically removes the oldest backups along with their associated WAL files to free up space.
  8. Configure Basebackup modes

    main

    PGHoard handles basebackups internally without requiring an external scheduler like cron. Upon the first launch, it performs an initial basebackup, and subsequent frequencies are managed via configuration.

    There are two primary methods for taking basebackups:

    • Direct File Copying: Copies files directly from PGDATA. This is used with the local-tar or delta modes.
    • Using pg_basebackup: Invokes the standard PostgreSQL utility. This is used with the basic or pipe modes.
  9. Configure PGHoard using a JSON configuration file

    main

    PGHoard uses a JSON-formatted configuration file consisting of nested key-value pairs. The configuration defines global settings and specific backup_sites.

    Key top-level sections include:

    • backup_sites: Defines the database clusters to back up.
    • transfer: Configures WAL and basebackup transfer parameters.
    • compression: Configures compression algorithms and levels.
    • stats / push_gateway: Configures monitoring and metrics.
    • http_address / http_port: Configures the HTTP server for the daemon.
    {
        "json_state_file_path": "/var/lib/pghoard/pghoard_state.json"
        "backup_sites": {
            "mycluster": {
                "nodes": [
                    {
                        "host": "127.0.0.1",
                        "password": "secret",
                        "port": 5432,
                        "user": "backup",
                        "slot": "pghoard"
                    }
                ],
                "basebackup_count": 5,
                "basebackup_mode": "delta",
                "object_storage": {
                    "storage_type": "local",
                    "directory": "/tmp/pghoard/backups"
                }
            }
        }
    }
  10. Restore a database to the latest point in time

    main

    To restore a PostgreSQL database to its latest possible state using PGHoard, follow these steps:

    1. List available basebackups to identify your targets:

      pghoard_restore list-basebackups --config /var/lib/pghoard/pghoard.json
    2. Fetch the required basebackup: Run get-basebackup with the --target-dir flag. The target-dir must be an empty or non-existent directory; PGHoard will create it automatically.

      pghoard_restore get-basebackup --config /var/lib/pghoard/pghoard.json --target-dir /var/lib/pgsql/9.5/data --restore-to-primary
    3. Start the services: PGHoard must be running before you start the PostgreSQL server. On systemd-based systems:

      systemctl start pghoard
      systemctl start postgresql-9.5

      PostgreSQL will then automatically enter the recovery process to the latest point in time.

  11. Enable WAL archiving with `archive_command` mode

    main

    The default way to enable backups is to use PostgreSQL's native archive_command. This instructs PostgreSQL to call the pghoard_postgres_command whenever a new WAL segment is ready.

    In postgresql.conf, set:

    archive_mode = on
    archive_command = pghoard_postgres_command --mode archive --site default --xlog %f

    This mode requires the pghoard daemon to be running locally.

    archive_mode = on
    archive_command = pghoard_postgres_command --mode archive --site default --xlog %f