Documentation
¶
Overview ¶
Package pgbackup backs up Postgres databases to S3.
It runs pg_dump (or pg_dumpall for a whole cluster), compresses the stream, and uploads it to S3 as a multipart upload using a bounded in-memory buffer. There is no scheduler: call Backup or BackupAll from whatever drives your schedule (cron, a systemd timer, a k8s CronJob, a ticker).
Index ¶
- Variables
- func ValidateTarget(t Target) error
- type Backupper
- func (b *Backupper) Backup(ctx context.Context, name string) (*Result, error)
- func (b *Backupper) BackupAll(ctx context.Context) []*Result
- func (b *Backupper) Restore(ctx context.Context, name string, opts RestoreOptions) (*RestoreResult, error)
- func (b *Backupper) RestoreLatest(ctx context.Context, name string, opts RestoreOptions) (*RestoreResult, error)
- type Compression
- type Logger
- type Options
- type RestoreOptions
- type RestoreResult
- type Result
- type Retention
- type Runner
- type S3Config
- type Source
- type Target
Constants ¶
This section is empty.
Variables ¶
var (
ErrObjectNotFound = errors.New("pgbackup: object not found")
)
ErrObjectNotFound is returned when an object key does not exist.
Functions ¶
func ValidateTarget ¶
ValidateTarget applies the same per-target checks New performs: name present and key-safe, DSN and discrete connection fields not mixed, AllDatabases not combined with Tables, ExcludeTables, or a non-plain Format, and Format being plain or custom. It does not check uniqueness across a set. Use it to filter a dynamic target set before constructing a Backupper, or let Runner apply it.
Types ¶
type Backupper ¶
type Backupper struct {
// contains filtered or unexported fields
}
Backupper runs backups and restores against a fixed set of targets.
func New ¶
New validates the configuration and returns a Backupper. It starts no goroutines.
It checks that Names are unique and key-safe, that DSN and the discrete connection fields are not mixed, that AllDatabases is not combined with Tables, ExcludeTables or a non-plain Format, that Format is plain or custom, and that Retention.KeepLast is at least 1 when OlderThan is set.
func (*Backupper) Backup ¶
Backup runs one target and returns its result.
The stream is piped from pg_dump through a compressor into the S3 uploader via an io.Pipe. If pg_dump fails, the error is pushed into the pipe before EOF, so the upload aborts and leaves no partial object.
func (*Backupper) BackupAll ¶
BackupAll runs every target concurrently, bounded by MaxParallel, and returns one Result per target when all finish. A failure in one target does not cancel the others: errgroup is used only for its semaphore, and the per-target function never returns an error.
func (*Backupper) Restore ¶
func (b *Backupper) Restore(ctx context.Context, name string, opts RestoreOptions) (*RestoreResult, error)
Restore downloads the backup named by opts.Key (or the newest backup of name when opts.Latest is set) and loads it into the destination.
func (*Backupper) RestoreLatest ¶
func (b *Backupper) RestoreLatest(ctx context.Context, name string, opts RestoreOptions) (*RestoreResult, error)
RestoreLatest is shorthand for Restore with Latest=true.
type Compression ¶
type Compression string
Compression selects the codec applied to a dump stream.
const ( // None disables compression. None Compression = "none" // Gzip uses the standard library's compress/gzip. Gzip Compression = "gzip" // Zstd is the default codec for plain dumps. Zstd Compression = "zstd" )
type Logger ¶
Logger is the logging interface the library uses. Provide your own, or leave Options.Logger nil for the default slog.Logger.
type Options ¶
type Options struct {
Compression Compression
CompressionLevel int
ObjectKeyFunc func(t Target, ts time.Time, ext string) string
TempDir string
Logger Logger
MaxParallel int
Retention *Retention
}
Options are Backupper-wide defaults.
type RestoreOptions ¶
type RestoreOptions struct {
// Source. Exactly one should be set. If both are zero, Latest is implied.
// Key is a specific object key.
Key string
// Latest picks the newest object under the target's prefix.
Latest bool
// Into is the destination. nil restores into the target's own DSN.
Into *Target
// SingleTransaction wraps the restore in a single transaction. Nil picks
// by format: true for a single plain restore, false for an all-databases
// restore. Setting it true on an all-databases restore is an error.
SingleTransaction *bool
// StopOnError maps to psql's ON_ERROR_STOP=1 or pg_restore's
// --exit-on-error. Nil means true.
StopOnError *bool
// PreDropDatabase drops and recreates the destination database before
// restoring. It is destructive and requires Confirm.
PreDropDatabase bool
// Confirm must be "drop " plus the destination database name, and gates
// PreDropDatabase.
Confirm string
// Force uses DROP DATABASE WITH (FORCE), available on Postgres 13 and
// later.
Force bool
// Echo echoes every statement the client runs.
Echo bool
// DryRun downloads and decompresses the object but discards the output
// instead of restoring. It works even when built with -tags nopgtools.
DryRun bool
// ExtraArgs are passed verbatim to psql or pg_restore.
ExtraArgs []string
}
RestoreOptions controls a single restore run. Restore is destructive, so every field defaults to the safe choice and must be explicitly enabled.
type RestoreResult ¶
type RestoreResult struct {
Target string
// Into is the DSN that received the restore, with the password redacted.
Into string
Bucket string
Key string
Bytes int64
Duration time.Duration
StartedAt time.Time
// Tool is "psql" or "pg_restore".
Tool string
Err error
}
RestoreResult describes one restore outcome.
type Result ¶
type Result struct {
Target string
Bucket, Key string
Bytes int64
Duration time.Duration
StartedAt time.Time
Err error
}
Result describes one target's backup outcome.
type Retention ¶
type Retention struct {
// KeepLast is the number of newest objects always kept, regardless of
// OlderThan.
KeepLast int
// OlderThan deletes objects older than this duration, after KeepLast is
// honored. Zero disables age-based deletion.
OlderThan time.Duration
}
Retention governs cleanup after each backup. Sweeps are scoped to one target's prefix, so they never touch another target's objects.
type Runner ¶
type Runner struct {
Source Source
S3 S3Config
Opts Options
// OnInvalid, when non-nil, is called for each target that fails
// ValidateTarget. Such targets are skipped and Run continues with the
// rest. When nil, the first invalid target makes Run return an error.
OnInvalid func(Target, error)
}
Runner fetches targets from a Source on each run and backs them up. It is a convenience over New + BackupAll: every Run rebuilds a Backupper from the freshly fetched targets, so dynamic inventories need no changes to the core API. Like Backupper, it starts no goroutines and has no scheduler.
func (*Runner) Run ¶
Run fetches the current targets from Source, filters invalid ones (if OnInvalid is set), builds a Backupper, and backs up every target. Returns one Result per target, identical in shape to Backupper.BackupAll.
Uniqueness of target names is enforced by New; duplicates from the Source cause Run to return an error. Deduplicate in Fetch if your inventory may contain them.
type S3Config ¶
type S3Config struct {
Bucket string
// Region is the AWS region. Use "auto" for Cloudflare R2.
Region string
// Endpoint is an alternate S3-compatible endpoint, such as R2 or MinIO.
Endpoint string
// PathStyle enables path-style addressing. nil leaves the SDK default.
PathStyle *bool
// AccessKey is optional. Empty uses the default credential chain.
AccessKey string
SecretKey string
// SessionToken is optional for temporary credentials.
SessionToken string
// Prefix is the object key prefix. Empty uses "pgbackup/".
Prefix string
// StorageClass is an S3 storage class such as "STANDARD_IA". Empty leaves
// the bucket default.
StorageClass string
// PartSize is the multipart part size. Empty uses 16 MiB.
PartSize int64
// ServerSideEncryption is "AES256" for SSE-S3 or "aws:kms" for SSE-KMS.
ServerSideEncryption string
// SSEKMSKeyID is the KMS key ARN/id when ServerSideEncryption is "aws:kms".
SSEKMSKeyID string
// UploadTimeout bounds a single upload. Zero means no timeout.
UploadTimeout time.Duration
}
S3Config is the upload destination. It works with AWS S3, R2, MinIO, B2 and Spaces.
type Source ¶
Source produces the current set of backup targets. Implement it against whatever holds your inventory: a SQL database, Redis, an HTTP API, a file, anything. Fetch is called once per backup run, so targets added or removed between runs are reflected automatically. Fetch must return the complete current set; sources that need pagination handle it internally.
type Target ¶
type Target struct {
// Name identifies the target and becomes part of the S3 object key.
// It must be unique across all targets and contain only [A-Za-z0-9._-]
// (no slash, no "..").
Name string
// DSN is a libpq conninfo or a postgresql:// URI. Leave it empty to
// build one from the discrete fields below.
DSN string
// Host, Port, User, Password, Database and SSLMode build a conninfo
// when DSN is empty. They cannot be combined with DSN.
Host, Port, User, Password, Database, SSLMode string
// AllDatabases uses pg_dumpall to dump every database plus globals and
// roles. The output is always plain SQL.
AllDatabases bool
// Tables and ExcludeTables add --table and --exclude-table flags. They
// cannot be used with AllDatabases.
Tables []string
// ExcludeTables adds --exclude-table flags. See Tables.
ExcludeTables []string
// Format is "plain" (the default, restored with psql) or "custom" (the
// -Fc format, restored with pg_restore).
Format string
// ExtraArgs are passed verbatim to pg_dump, e.g. "--no-owner".
ExtraArgs []string
// Compression overrides Options.Compression for this target. Zero
// falls back to the default: zstd for plain, none for custom.
Compression Compression
}
Target describes one Postgres database to back up.
Either set DSN (a libpq conninfo or a postgresql:// URI) or fill in the discrete fields below and let New assemble them into a conninfo. Mixing the two is an error. The password is moved into a child-scoped PGPASSWORD environment variable and stripped from argv, so it does not appear in ps.