postgres

package
v0.15.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 7, 2026 License: Apache-2.0, MIT Imports: 67 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	PgControlPath = "/global/pg_control"

	FilesMetadataName = "files_metadata.json"
)
View Source
const (
	PgControl = "pg_control"

	BackupLabelFilename = "backup_label"

	TablespaceMapFilename = "tablespace_map"

	TablespaceFolder = "pg_tblspc"
)
View Source
const (
	DeleteGarbageArchivesModifier = "ARCHIVES"

	DeleteGarbageBackupsModifier = "BACKUPS"
)
View Source
const (
	DoctorCheckConfig       = "config"
	DoctorCheckStorage      = "storage"
	DoctorCheckEncryption   = "encryption"
	DoctorCheckPostgres     = "postgres"
	DoctorCheckArchiving    = "archiving"
	DoctorCheckBackups      = "backups"
	DoctorCheckRestoreSpace = "restore-space"
)

Check names, stable enough to be matched on by scripts.

View Source
const (
	RelFileSizeBound = 1 << 30

	DefaultSpcNode walparser.Oid = 1663
)
View Source
const (
	// number of checksums to calculate in parallel
	NSums int = 32
	// prime multiplier of FNV-1a hash
	FnvPrime uint32 = 16777619
	// page header checksum offset
	PdChecksumOffset = 8
	// page header checksum length (in bytes)
	PdChecksumLen       = 2
	MaxDatabasePageSize = 32768
)
View Source
const (
	SignatureMagicNumber byte = 0x55

	DefaultTablespace = "base"

	GlobalTablespace = "global"

	NonDefaultTablespace = "pg_tblspc"

	XactDir = "pg_xact" // Transaction status

	ClogDir = "pg_clog" // Legacy name for transaction status

	MultiXactDir = "pg_multixact" // Multi-transaction status

)
View Source
const (
	DrillCheckTarget = "target-dir"
	DrillCheckSpace  = "space"
	DrillCheckFetch  = "fetch"
	DrillCheckReplay = "replay"
	DrillCheckRTO    = "rto"
	DrillCheckRPO    = "rpo"
)

Drill phase names, stable enough to be matched on by scripts.

View Source
const (
	RetentionCheckRPO     = "rpo"
	RetentionCheckWindow  = "retention-window"
	RetentionCheckPolicy  = "policy-outcome"
	RetentionCheckCadence = "backup-cadence"
)

Retention check names, stable enough to be matched on by scripts.

View Source
const (
	BasePrefix = "base_prefix"

	Tablespaces = "tablespaces"
)
View Source
const (
	WalFileInDelta      uint64 = 16
	DeltaFilenameSuffix string = "_delta"
	PartFilenameSuffix  string = "_part"
)
View Source
const (
	WalBulkMetadataLevel = "BULK"

	WalIndividualMetadataLevel = "INDIVIDUAL"

	WalNoMetadataLevel = "NOMETADATA"
)
View Source
const (
	TimelineOkStatus = "OK"

	TimelineLostSegmentStatus = "LOST_SEGMENTS"
)
View Source
const (
	WalVerifyIntegrityCheck = iota + 1

	WalVerifyTimelineCheck
)
View Source
const DefaultDrillPort = 5433

DefaultDrillPort is off the usual 5432 so a drill cannot collide with a running cluster on the same host.

View Source
const DefaultDrillStartTimeout = 10 * time.Minute

DefaultDrillStartTimeout bounds waiting for the restored cluster to come up.

View Source
const DefaultRestoreSpaceMargin = 1.2

DefaultRestoreSpaceMargin is the multiple of a backup's uncompressed size that should be free before a restore is considered safe. The headroom covers WAL replayed during recovery and the cluster accepting writes once it is up.

View Source
const DefaultStaleAfter = 26 * time.Hour

DefaultStaleAfter is just over a day, so a daily backup schedule that slips by an hour or two does not read as a failure.

View Source
const MetadataDatetimeFormat = "%Y-%m-%dT%H:%M:%S.%fZ"
View Source
const PatternLSN = "[0-9A-F]{8}"
View Source
const PatternTimelineAndLogSegNo = "[0-9A-F]{24}"
View Source
const (
	RecordPartFilename = "currentRecord.part"
)
View Source
const SIGUSR1 = syscall.SIGUSR1
View Source
const (
	SdNotifyWatchdog = "WATCHDOG=1"
)
View Source
const (
	StandbyMessageTimeout = time.Second * 10
)

Variables

View Source
var DatabasePageSize int64 = int64(walparser.BlockSize)
View Source
var ErrorBasePrefixMissing = fmt.Errorf("base prefix not set while working with tablespaces")
View Source
var ExcludedFilenames = make(map[string]utility.Empty)
View Source
var IncrementFileHeader = []byte{'w', 'i', '1', SignatureMagicNumber}
View Source
var UnwrapAll map[string]bool
View Source
var UtilityFilePaths = map[string]bool{
	PgControlPath: true,

	BackupLabelFilename: true,

	TablespaceMapFilename: true,
}
View Source
var (
	WalSegmentSize = uint64(16 * 1024 * 1024)
)

Functions

func ApplyFileIncrement

func ApplyFileIncrement(fileName string, increment io.Reader, createNewIncrementalFiles bool, fsync bool) error

func BackupCopyingInfo

func BackupCopyingInfo(backup Backup, from storage.Folder, to storage.Folder) ([]copy.InfoProvider, error)

func ClassifyStorageNames added in v0.15.2

func ClassifyStorageNames(names []string) (map[string]bool, map[WalSegmentDescription]bool)

ClassifyStorageNames sorts root-relative object names into the backups and the WAL segments they belong to. Objects that are neither - .history files, the leftovers "delete garbage" targets - belong to no backup and no segment, and are simply not returned.

func CleanupPrefetchDirectories

func CleanupPrefetchDirectories(walFileName string, location string, cleaner Cleaner)

func Connect

func Connect(ctx context.Context, configOptions ...func(config *pgx.ConnConfig) error) (*pgx.Conn, error)

Connect establishes a connection to postgres using a UNIX socket. Must export PGHOST and run with `sudo -E -u postgres`. If PGHOST is not set or if the connection fails, an error is returned and the connection is `<nil>`.

Example: PGHOST=/var/run/postgresql or PGHOST=10.0.0.1

func CreateFileFromIncrement

func CreateFileFromIncrement(increment io.Reader, target ReadWriterAt) (int64, error)

func DeduceBackupName

func DeduceBackupName(object storage.Object) string

func ExtractDeleteGarbagePredicate

func ExtractDeleteGarbagePredicate(args []string) func(storage.Object) bool

func GetBaseFilesToUnwrap

func GetBaseFilesToUnwrap(backupFileStates internal.BackupFileList, currentFilesToUnwrap map[string]bool) (map[string]bool, error)

func GetDeltaFilenameFor

func GetDeltaFilenameFor(walFilename string) (string, error)

func GetFetcherNew

func GetFetcherNew(dbDataDirectory, fileMask, restoreSpecPath string, skipRedundantTars bool,

	extractProv ExtractProvider,

	spaceGuard SpaceGuardOptions,
) internal.Fetcher

func GetFetcherOld

func GetFetcherOld(dbDataDirectory, fileMask, restoreSpecPath string, extractProv ExtractProvider,
	spaceGuard SpaceGuardOptions) internal.Fetcher

func GetFirstWalFilename

func GetFirstWalFilename(backup Backup) (string, error)

func GetIncrementHeaderFields

func GetIncrementHeaderFields(increment io.Reader) (uint64, uint32, []byte, error)

func GetLastWalFilename

func GetLastWalFilename(backup Backup) (string, error)

func GetMissingWals

func GetMissingWals(lastSeg uint64, lastTl, currentTl uint32,

	tlToSeg map[uint32]*TimelineWithSegmentNo,

	walsByTimelines map[uint32]*WalSegmentsSequence,

) ([]string, error)

func GetNextWalFilename

func GetNextWalFilename(name string) (string, error)

func GetPermanentBackupsAndWals

func GetPermanentBackupsAndWals(folder storage.Folder) (map[PermanentObject]bool, map[PermanentObject]bool)

func GetPgServerInfo

func GetPgServerInfo(keepRunner bool) (pgInfo BackupPgInfo, runner *PgQueryRunner, err error)

func GetPositionInDelta

func GetPositionInDelta(walFilename string) int

func GetRelFileIDFrom

func GetRelFileIDFrom(filePath string) (int, error)

func GetRelFileNodeFrom

func GetRelFileNodeFrom(filePath string) (*walparser.RelFileNode, error)

func GetSegmentNoFromLsn

func GetSegmentNoFromLsn(lsn LSN) uint64

func GetWalFileName

func GetWalFileName(filename string) string

func GuardRestoreSpace added in v0.15.2

func GuardRestoreSpace(backup Backup, dataDir string, opts SpaceGuardOptions)

GuardRestoreSpace sizes a restore before it begins and stops it when it demonstrably will not fit. Aborting here costs a storage round-trip; finding out during extraction costs however many hours the restore had already run, and leaves a half-written data directory behind.

It aborts the process rather than returning an error because the fetch path it guards reports all its failures that way.

func HandleBackupVerify added in v0.15.1

func HandleBackupVerify(
	rootFolder storage.Folder,
	opts BackupVerifyOptions,
	output io.Writer,
) int

func HandleCatchupFetch

func HandleCatchupFetch(folder storage.Folder, dbDirectory, backupName string, useNewUnwrap bool)

func HandleCatchupPush

func HandleCatchupPush(ctx context.Context, pgDataDirectory string, fromLSN LSN)

func HandleCatchupReceive

func HandleCatchupReceive(pgDataDirectory string, port int)

func HandleCatchupSend

func HandleCatchupSend(pgDataDirectory string, destination string)

func HandleCopy

func HandleCopy(fromConfigFile string, toConfigFile string, backupName string, withAllHistory bool)

func HandleDaemon

func HandleDaemon(options DaemonOptions)

func HandleDetailedBackupList

func HandleDetailedBackupList(folder storage.Folder, pretty bool, json bool)

func HandleDoctor added in v0.15.2

func HandleDoctor(rootFolder storage.Folder, opts DoctorOptions, output io.Writer) int

HandleDoctor runs every preflight check and reports the results. It returns the process exit code: 0 when nothing failed, 1 otherwise.

func HandlePITRWindow added in v0.15.2

func HandlePITRWindow(rootFolder storage.Folder, opts PITRWindowOptions, output io.Writer) int

HandlePITRWindow reports what the storage can currently be recovered to. It returns the process exit code: 0 when something is restorable and any requested minimum is met, 1 otherwise.

func HandleRestoreDrill added in v0.15.2

func HandleRestoreDrill(rootFolder storage.Folder, opts RestoreDrillOptions, output io.Writer) int

HandleRestoreDrill restores a backup into a scratch directory, measures how long recovery takes, and judges it against the declared objectives. It returns the process exit code: 0 when nothing failed, 1 otherwise.

The restore runs as a subprocess rather than in this process. A fetch that fails hard calls os.Exit, and a drill that dies without a verdict - and without removing the cluster it half-wrote - is a poor test harness. Running the documented command also means the drill exercises the path an operator would actually use, config resolution included.

func HandleWALFetch

func HandleWALFetch(baseReader internal.StorageFolderReader, walFileName string, location string, prefetcher WalPrefetcher) error

func HandleWALPrefetch

func HandleWALPrefetch(folderReader internal.StorageFolderReader, walFileName string, location string) error

func HandleWALPush

func HandleWALPush(ctx context.Context, uploader *WalUploader, walFilePath string) error

func HandleWALReceive

func HandleWALReceive(ctx context.Context, uploader *WalUploader)

func HandleWALRestore

func HandleWALRestore(targetPath, sourcePath string, cloudFolder storage.Folder)

func HandleWalShow

func HandleWalShow(rootFolder storage.Folder, showBackups bool, outputWriter WalShowOutputWriter)

func HandleWalVerify

func HandleWalVerify(

	checkTypes []WalVerifyCheckType,

	rootFolder storage.Folder,

	currentWalSegment WalSegmentDescription,

	backupSearchParams BackupSearchParams,

	outputWriter WalVerifyOutputWriter,

)

func HistoryCopyingInfo

func HistoryCopyingInfo(backup Backup, from storage.Folder, to storage.Folder, withAllHistory bool) ([]copy.InfoProvider, error)

func IsPermanent

func IsPermanent(objectName, storageName string, permanentBackups, permanentWals map[PermanentObject]bool) bool

func IsPgControlRequired

func IsPgControlRequired(backup Backup) bool

func MergeDeployMetadataIntoUserData added in v0.15.1

func MergeDeployMetadataIntoUserData(meta DeployMetadata, userData interface{}) interface{}

func ParseObjectiveDuration added in v0.15.2

func ParseObjectiveDuration(value string) (time.Duration, error)

ParseObjectiveDuration parses a duration, additionally accepting a d suffix for days.

Retention windows are stated in days far more often than in hours, and time.ParseDuration stops at h - so a policy of 30 days has to be written 720h, which is both easy to get wrong and hard to read back. A day here is 24 hours flat: no calendar, no daylight saving, which is the right unit for "how much history must I be able to reach".

func ParseTimelineFromBackupName

func ParseTimelineFromBackupName(backupName string) (uint32, error)

func ParseTimelineFromString

func ParseTimelineFromString(timelineString string) (uint32, error)

func ParseWALFilename

func ParseWALFilename(name string) (timelineID uint32, logSegNo uint64, err error)

func PrepareDirs

func PrepareDirs(fileName string, targetPath string) error

func ProcessConnection

func ProcessConnection(ctx context.Context, c net.Conn, multiSt *multistorage.Storage)

func ReadIncrementFileHeader

func ReadIncrementFileHeader(reader io.Reader) error

func ReadIncrementLocations

func ReadIncrementLocations(filePath string, fileSize int64, lsn LSN) ([]walparser.BlockLocation, error)

func ReadIncrementalFile

func ReadIncrementalFile(filePath string,

	fileSize int64,

	lsn LSN,

	deltaBitmap *roaring.Bitmap) (fileReader io.ReadCloser, size int64, err error)

func RestoreMissingPages

func RestoreMissingPages(base io.Reader, target ReadWriterAt) error

func SdNotify

func SdNotify(state string) error

func SelectRelFileBlocks

func SelectRelFileBlocks(bitmap *roaring.Bitmap, relFileID int) *roaring.Bitmap

func SendSdNotify

func SendSdNotify(c <-chan time.Time)

func SetDatabasePageSize

func SetDatabasePageSize(pageSize uint64)

func SetWalSize

func SetWalSize(sizeMb uint64)

func SetupSignalListener

func SetupSignalListener()

func SortBackupDetails

func SortBackupDetails(backupDetails []BackupDetail)

func ToPartFilename

func ToPartFilename(deltaFilename string) string

func TryFetchTimelineAndLogSegNo

func TryFetchTimelineAndLogSegNo(objectName string) (uint32, uint64, bool)

func TryGetOidPair

func TryGetOidPair(file string) (bool, uint32, uint32)

func ValidateDrillTarget added in v0.15.2

func ValidateDrillTarget(targetDir, pgDataDir string) (created bool, err error)

ValidateDrillTarget checks that a directory is safe to restore into.

The drill writes a whole cluster and then deletes it. Pointing that at a live data directory would destroy the thing being protected, so the two rules are absolute: never the live data directory, and never a directory that already has anything in it.

It returns whether the directory had to be created, which is what cleanup uses to decide between removing the directory and only emptying it.

func ValidateSlotName

func ValidateSlotName(pgSlotName string) (err error)

ValidateSlotName validates pgSlotName to be a valid slot name

func VerifyPagedFileBase

func VerifyPagedFileBase(path string, fileInfo os.FileInfo, pagedFile io.Reader) ([]uint32, error)

VerifyPagedFileBase verifies pages of a standard paged file

func VerifyPagedFileIncrement

func VerifyPagedFileIncrement(path string, fileInfo os.FileInfo, increment io.Reader) ([]uint32, error)

VerifyPagedFileIncrement verifies pages of an increment

func WildcardInfo

func WildcardInfo(from storage.Folder, to storage.Folder) ([]copy.InfoProvider, error)

func WriteExplanation added in v0.15.2

func WriteExplanation(explanation *DeleteExplanation, format string, output io.Writer) error

WriteExplanation renders the report. Text is for a person deciding whether to add --confirm; JSON is for a pipeline deciding the same thing.

func WritePITRWindowReport added in v0.15.2

func WritePITRWindowReport(report *PITRWindowReport, format string, output io.Writer) error

WritePITRWindowReport renders a window report.

func WritePagesFromIncrement

func WritePagesFromIncrement(increment io.Reader, target ReadWriterAt, overwriteExisting bool) (int64, error)

func WriteRestoreDrillReport added in v0.15.2

func WriteRestoreDrillReport(report *RestoreDrillReport, format string, output io.Writer) error

WriteRestoreDrillReport renders a drill report.

func WriteRetentionReport added in v0.15.2

func WriteRetentionReport(report *RetentionReport, format string, output io.Writer) error

WriteRetentionReport renders a validation report.

Types

type ArchiveMessageHandler

type ArchiveMessageHandler struct {
	// contains filtered or unexported fields
}

func (*ArchiveMessageHandler) Handle

func (h *ArchiveMessageHandler) Handle(ctx context.Context, messageBody []byte) error

type Backup

type Backup struct {
	internal.Backup

	SentinelDto *BackupSentinelDto // used for storage query caching

	FilesMetadataDto *FilesMetadataDto
}

func NewBackup

func NewBackup(baseBackupFolder storage.Folder, name string) (Backup, error)

func NewBackupInStorage

func NewBackupInStorage(baseBackupFolder storage.Folder, name, storage string) (Backup, error)

func ToPgBackup

func ToPgBackup(source internal.Backup) (output Backup)

func (*Backup) FetchMeta

func (backup *Backup) FetchMeta() (ExtendedMetadataDto, error)

func (*Backup) GetFilesToUnwrap

func (backup *Backup) GetFilesToUnwrap(fileMask string) (map[string]bool, error)

func (*Backup) GetSentinel

func (backup *Backup) GetSentinel() (BackupSentinelDto, error)

func (*Backup) GetSentinelAndFilesMetadata

func (backup *Backup) GetSentinelAndFilesMetadata() (BackupSentinelDto, FilesMetadataDto, error)

func (*Backup) GetTarNames

func (backup *Backup) GetTarNames() ([]string, error)

type BackupArguments

type BackupArguments struct {
	Uploader internal.Uploader
	// contains filtered or unexported fields
}

func NewBackupArguments

func NewBackupArguments(uploader internal.Uploader, pgDataDirectory string, backupsFolder string, isPermanent bool,

	verifyPageChecksums bool, isFullBackup bool, storeAllCorruptBlocks bool, tarBallComposerType TarBallComposerType,

	deltaConfigurator DeltaBackupConfigurator, userData interface{}, withoutFilesMetadata bool) BackupArguments

func (*BackupArguments) EnablePreventConcurrentBackups

func (ba *BackupArguments) EnablePreventConcurrentBackups()

type BackupDetail

type BackupDetail struct {
	internal.BackupTime
	ExtendedMetadataDto
}

BackupDetail is used to append ExtendedMetadataDto details to BackupTime struct

func GetBackupDetails

func GetBackupDetails(folder storage.Folder, backupTime internal.BackupTime) (BackupDetail, error)

func GetBackupsDetails

func GetBackupsDetails(folder storage.Folder, backups []internal.BackupTime) ([]BackupDetail, error)

func (*BackupDetail) PrintableFields

func (bd *BackupDetail) PrintableFields() []printlist.TableField

type BackupFileOptions

type BackupFileOptions struct {
	// contains filtered or unexported fields
}

type BackupFileUnwrapper

type BackupFileUnwrapper struct {
	// contains filtered or unexported fields
}

type BackupHandler

type BackupHandler struct {
	CurBackupInfo CurBackupInfo

	Arguments BackupArguments

	Workers BackupWorkers

	PgInfo BackupPgInfo
	// contains filtered or unexported fields
}

func NewBackupHandler

func NewBackupHandler(arguments BackupArguments) (bh *BackupHandler, err error)

func (*BackupHandler) CheckArchiveCommand

func (bh *BackupHandler) CheckArchiveCommand(ctx context.Context) error

func (*BackupHandler) HandleBackupPush

func (bh *BackupHandler) HandleBackupPush(ctx context.Context)

func (*BackupHandler) SetComposerInitFunc

func (bh *BackupHandler) SetComposerInitFunc(initFunc func(handler *BackupHandler) error)

type BackupObject

type BackupObject struct {
	storage.Object

	BackupName string
	// contains filtered or unexported fields
}

func (BackupObject) GetBackupName

func (o BackupObject) GetBackupName() string

func (BackupObject) GetBackupTime

func (o BackupObject) GetBackupTime() time.Time

func (BackupObject) GetBaseBackupName

func (o BackupObject) GetBaseBackupName() string

func (BackupObject) GetIncrementFromName

func (o BackupObject) GetIncrementFromName() string

func (BackupObject) GetStorage

func (o BackupObject) GetStorage() string

func (BackupObject) IsFullBackup

func (o BackupObject) IsFullBackup() bool

type BackupPgInfo

type BackupPgInfo struct {
	PgVersion int

	PgDataDirectory string

	Timeline uint32
	// contains filtered or unexported fields
}

type BackupSearchParams

type BackupSearchParams struct {
	FindEarliestBackup bool

	SpecifiedBackupName *string
}

type BackupSentinelDto

type BackupSentinelDto struct {
	BackupStartLSN *LSN `json:"LSN"`

	IncrementFromLSN *LSN `json:"DeltaLSN,omitempty"`

	IncrementFrom *string `json:"DeltaFrom,omitempty"`

	IncrementFullName *string `json:"DeltaFullName,omitempty"`

	IncrementCount *int `json:"DeltaCount,omitempty"`

	PgVersion int `json:"PgVersion"`

	BackupFinishLSN *LSN `json:"FinishLSN"`

	SystemIdentifier *uint64 `json:"SystemIdentifier,omitempty"`

	UncompressedSize int64 `json:"UncompressedSize"`

	CompressedSize int64 `json:"CompressedSize"`

	DataCatalogSize int64 `json:"DataCatalogSize,omitempty"`

	TablespaceSpec *TablespaceSpec `json:"Spec,omitempty"`

	UserData interface{} `json:"UserData,omitempty"`

	FilesMetadataDisabled bool `json:"FilesMetadataDisabled,omitempty"`

	BackupStartChkpNum *uint32 `json:"ChkpNum"`

	IncrementFromChkpNum *uint32 `json:"DeltaChkpNum,omitempty"`

	DeltaPromotionReason *string `json:"DeltaPromotionReason,omitempty"`
}

func NewBackupSentinelDto

func NewBackupSentinelDto(bh *BackupHandler, tbsSpec *TablespaceSpec) BackupSentinelDto

func (*BackupSentinelDto) IsIncremental

func (dto *BackupSentinelDto) IsIncremental() (isIncremental bool)

func (*BackupSentinelDto) UnmarshalJSON

func (dto *BackupSentinelDto) UnmarshalJSON(data []byte) error

type BackupSentinelDtoV2

type BackupSentinelDtoV2 struct {
	BackupSentinelDto

	Version int `json:"Version"`

	StartTime time.Time `json:"StartTime"`

	FinishTime time.Time `json:"FinishTime"`

	DatetimeFormat string `json:"DateFmt"`

	Hostname string `json:"Hostname"`

	DataDir string `json:"DataDir"`

	IsPermanent bool `json:"IsPermanent"`
}

func NewBackupSentinelDtoV2

func NewBackupSentinelDtoV2(sentinel BackupSentinelDto, meta ExtendedMetadataDto) BackupSentinelDtoV2

type BackupTerminator

type BackupTerminator struct {
	// contains filtered or unexported fields
}

func NewBackupTerminator

func NewBackupTerminator(queryRunner *PgQueryRunner, pgVersion int, pgDataDir string) *BackupTerminator

func (*BackupTerminator) TerminateBackup

func (t *BackupTerminator) TerminateBackup()

type BackupTimeSlicesOrder

type BackupTimeSlicesOrder int
const (
	ByCreationTime BackupTimeSlicesOrder = iota
	ByModificationTime
)

type BackupVerifyOptions added in v0.15.2

type BackupVerifyOptions struct {
	// BackupName is the backup to verify; empty means LATEST.
	BackupName string
	// SamplePct > 0 promotes the run to Tier 2 and sets the partition sample size.
	SamplePct int
	// Seed makes Tier 2 sampling reproducible; 0 means time-based.
	Seed int64
	// TargetLSN and TargetTime bound the WAL chain verification scope.
	TargetLSN  string
	TargetTime string
	// Format is "text" or "json".
	Format string
	// SkipCanary disables the Tier 1 decrypt canary, making the run purely
	// metadata-based (no object data is fetched at all).
	SkipCanary bool
}

BackupVerifyOptions carries the tunables for a single backup-verify run.

type BackupVerifyResult added in v0.15.1

type BackupVerifyResult struct {
	BackupName string           `json:"backup_name"`
	Tier       BackupVerifyTier `json:"tier"`
	Pass       bool             `json:"pass"`

	SentinelExists bool   `json:"sentinel_exists"`
	SentinelError  string `json:"sentinel_error,omitempty"`

	FilesMetadataExists bool `json:"files_metadata_exists"`

	MissingParts []string `json:"missing_parts,omitempty"`

	DeployMetadata interface{} `json:"deploy_metadata"`

	ChecksumCoverage ChecksumCoverage `json:"checksum_coverage"`

	DecryptCanary DecryptCanaryResult `json:"decrypt_canary"`

	WALCheckAvailable bool     `json:"wal_check_available"`
	WALCheckDetails   string   `json:"wal_check_details,omitempty"`
	WALGaps           []string `json:"wal_gaps,omitempty"`

	SamplePercent   int                `json:"sample_percent,omitempty"`
	ActualSamplePct float64            `json:"actual_sample_pct,omitempty"`
	SampledParts    int                `json:"sampled_parts,omitempty"`
	TotalParts      int                `json:"total_parts,omitempty"`
	FileResults     []VerifyFileResult `json:"file_results,omitempty"`
	Tier2Pass       *bool              `json:"tier2_pass,omitempty"`

	Elapsed string `json:"elapsed"`
	Error   string `json:"error,omitempty"`
}

type BackupVerifyTier added in v0.15.1

type BackupVerifyTier int
const (
	Tier1 BackupVerifyTier = 1
	Tier2 BackupVerifyTier = 2
)

func (BackupVerifyTier) MarshalText added in v0.15.1

func (t BackupVerifyTier) MarshalText() ([]byte, error)

func (*BackupVerifyTier) UnmarshalText added in v0.15.2

func (t *BackupVerifyTier) UnmarshalText(data []byte) error

type BackupWorkers

type BackupWorkers struct {
	Bundle *Bundle

	QueryRunner *PgQueryRunner
}

type BgUploader

type BgUploader struct {
	// contains filtered or unexported fields
}

BgUploader represents the state of concurrent WAL upload

func NewBgUploader

func NewBgUploader(ctx context.Context, walFilePath string,
	maxParallelWorkers int32,
	maxNumUploaded int32,
	uploader *WalUploader,
	preventWalOverwrite bool,
	readyRename bool) *BgUploader

NewBgUploader creates a new BgUploader which looks for WAL files adjacent to walFilePath. maxParallelWorkers and maxNumUploaded limits maximum concurrency and total work done by this BgUploader respectively.

func (*BgUploader) Start

func (b *BgUploader) Start()

Start up checking what's inside archive_status

func (*BgUploader) Stop

func (b *BgUploader) Stop() error

Stop pipeline. Stop can be safely called concurrently and repeatedly.

type Bundle

type Bundle struct {
	internal.Bundle

	Timeline uint32

	Replica bool

	IncrementFromLsn *LSN

	IncrementFromFiles internal.BackupFileList

	IncrementFromName string

	DeltaMap PagedFileDeltaMap

	TablespaceSpec TablespaceSpec

	DataCatalogSize atomic.Int64

	IncrementFromChkpNum *uint32
	// contains filtered or unexported fields
}

func NewBundle

func NewBundle(

	directory string, crypter crypto.Crypter,

	incrementFromName string, incrementFromLsn *LSN, incrementFromFiles internal.BackupFileList,

	forceIncremental bool, tarSizeThreshold int64,

) *Bundle

func (*Bundle) DownloadDeltaMap

func (bundle *Bundle) DownloadDeltaMap(reader internal.StorageFolderReader, backupStartLSN LSN) error

func (*Bundle) FinishTarComposer

func (bundle *Bundle) FinishTarComposer() (internal.TarFileSets, error)

func (*Bundle) GetFiles

func (bundle *Bundle) GetFiles() *sync.Map

func (*Bundle) HandleWalkedFSObject

func (bundle *Bundle) HandleWalkedFSObject(path string, info os.FileInfo, err error) error

func (*Bundle) NewTarBall

func (bundle *Bundle) NewTarBall(dedicatedUploader bool) internal.TarBall

func (*Bundle) SetupComposer

func (bundle *Bundle) SetupComposer(composerMaker TarBallComposerMaker) (err error)

func (*Bundle) StartBackup

func (bundle *Bundle) StartBackup(ctx context.Context, queryRunner *PgQueryRunner,

	backup string) (backupName string, lsn LSN, err error)

func (*Bundle) UploadPgControl

func (bundle *Bundle) UploadPgControl(compressorFileExtension string) error

type BytesPerWalSegmentError

type BytesPerWalSegmentError struct {
	// contains filtered or unexported fields
}

func (BytesPerWalSegmentError) Error

func (err BytesPerWalSegmentError) Error() string

type CantDiscardWalDataError

type CantDiscardWalDataError struct {
	// contains filtered or unexported fields
}

func (CantDiscardWalDataError) Error

func (err CantDiscardWalDataError) Error() string

type CantOverwriteWalFileError

type CantOverwriteWalFileError struct {
	// contains filtered or unexported fields
}

func (CantOverwriteWalFileError) Error

func (err CantOverwriteWalFileError) Error() string

type CatchupCommandDto

type CatchupCommandDto struct {
	IsDone bool

	IsIncremental bool

	IsFull bool

	IsDelete bool

	IsBinContents bool

	FileSize uint64

	FileName string

	BinaryContents []byte

	FilesToDelete []string
}

type CatchupDeltaBackupConfigurator

type CatchupDeltaBackupConfigurator struct {
	// contains filtered or unexported fields
}

func NewCatchupDeltaBackupConfigurator

func NewCatchupDeltaBackupConfigurator(fakePreviousBackupSentinelDto BackupSentinelDto) CatchupDeltaBackupConfigurator

func (CatchupDeltaBackupConfigurator) Configure

func (c CatchupDeltaBackupConfigurator) Configure(storage.Folder, bool) (prevBackupInfo PrevBackupInfo, decision DeltaDecision, err error)

type CatchupFileUnwrapper

type CatchupFileUnwrapper struct {
	BackupFileUnwrapper
}

func (*CatchupFileUnwrapper) UnwrapExistingFile

func (u *CatchupFileUnwrapper) UnwrapExistingFile(reader io.Reader, header *tar.Header,

	file *os.File, fsync bool) (*FileUnwrapResult, error)

func (*CatchupFileUnwrapper) UnwrapNewFile

func (u *CatchupFileUnwrapper) UnwrapNewFile(reader io.Reader, header *tar.Header,

	file *os.File, fsync bool) (*FileUnwrapResult, error)

type CheckMessageHandler

type CheckMessageHandler struct {
	// contains filtered or unexported fields
}

func (*CheckMessageHandler) Handle

func (h *CheckMessageHandler) Handle(_ context.Context, _ []byte) error

type ChecksumCoverage added in v0.15.1

type ChecksumCoverage struct {
	HasChecksum int `json:"has_checksum"`
	NoChecksum  int `json:"no_checksum"`
	Total       int `json:"total"`
}

type Cleaner

type Cleaner interface {
	GetFiles(directory string) ([]string, error)
	Remove(file string)
}

Cleaner interface serves to separate file system logic from prefetch clean logic to make it testable

type CopyTarBallComposer

type CopyTarBallComposer struct {
	// contains filtered or unexported fields
}

func NewCopyTarBallComposer

func NewCopyTarBallComposer(

	tarBallQueue *internal.TarBallQueue,

	tarBallFilePacker *TarBallFilePackerImpl,

	files *internal.RegularBundleFiles,

	crypter crypto.Crypter,

	prevBackup Backup,

	newBackupName string,

	tarUnchangedFilesCount map[string]int,

	prevFileTar map[string]string,

	prevTarFileSets internal.TarFileSets,

) (*CopyTarBallComposer, error)

func (*CopyTarBallComposer) AddFile

func (c *CopyTarBallComposer) AddFile(info *internal.ComposeFileInfo)

func (*CopyTarBallComposer) AddHeader

func (c *CopyTarBallComposer) AddHeader(fileInfoHeader *tar.Header, info os.FileInfo) error

func (*CopyTarBallComposer) FinishComposing

func (c *CopyTarBallComposer) FinishComposing() (internal.TarFileSets, error)

func (*CopyTarBallComposer) GetFiles

func (*CopyTarBallComposer) SkipFile

func (c *CopyTarBallComposer) SkipFile(tarHeader *tar.Header, fileInfo os.FileInfo)

type CopyTarBallComposerMaker

type CopyTarBallComposerMaker struct {
	// contains filtered or unexported fields
}

func NewCopyTarBallComposerMaker

func NewCopyTarBallComposerMaker(previousBackup Backup, newBackupName string,

	filePackerOptions TarBallFilePackerOptions) *CopyTarBallComposerMaker

func (*CopyTarBallComposerMaker) Make

type CurBackupInfo

type CurBackupInfo struct {
	Name string

	StartTime time.Time

	StartChkpNum *uint32
	// contains filtered or unexported fields
}

type DaemonOptions

type DaemonOptions struct {
	SocketPath string
}

type DaemonPrefetcher

type DaemonPrefetcher struct {
}

func (DaemonPrefetcher) Prefetch

func (p DaemonPrefetcher) Prefetch(reader internal.StorageFolderReader, walFileName string, location string)

type DatabaseObjectsInfo

type DatabaseObjectsInfo struct {
	Oid    uint32               `json:"oid"`
	Tables map[string]TableInfo `json:"tables_new,omitempty"`
}

func NewDatabaseObjectsInfo

func NewDatabaseObjectsInfo(oid uint32) *DatabaseObjectsInfo

type DatabasesByNames

type DatabasesByNames map[string]DatabaseObjectsInfo

func (DatabasesByNames) GetSystemTables

func (meta DatabasesByNames) GetSystemTables() RestoreDesc

func (DatabasesByNames) Resolve

func (meta DatabasesByNames) Resolve(key string) (uint32, uint32, error)

func (DatabasesByNames) ResolveRegexp

func (meta DatabasesByNames) ResolveRegexp(key string) (map[uint32][]uint32, error)

type DecoderReader

type DecoderReader struct {
	*gob.Decoder
	// contains filtered or unexported fields
}

func (*DecoderReader) Read

func (d *DecoderReader) Read(bytes []byte) (n int, err error)

type DecryptCanaryResult added in v0.15.2

type DecryptCanaryResult struct {
	Attempted  bool   `json:"attempted"`
	Pass       bool   `json:"pass"`
	SkipReason string `json:"skip_reason,omitempty"`
	Part       string `json:"part,omitempty"`
	PartSize   int64  `json:"part_size,omitempty"`
	Crypter    string `json:"crypter,omitempty"`
	TarEntries int    `json:"tar_entries"`
	Error      string `json:"error,omitempty"`
}

DecryptCanaryResult reports whether the crypter and compression codec configured on *this* host can actually open the backup's data. The rest of Tier 1 is metadata-only, so without this check a green Tier 1 says nothing about whether the key available here can decrypt the bytes - the exact failure that only surfaces during a restore, when it is too late to do anything about it.

One partition (the smallest) is fetched and the first tar header is read. Nothing else is downloaded, so the cost stays in the "near-zero egress" budget Tier 1 promises.

type DefaultFileUnwrapper

type DefaultFileUnwrapper struct {
	BackupFileUnwrapper
}

func (*DefaultFileUnwrapper) UnwrapExistingFile

func (u *DefaultFileUnwrapper) UnwrapExistingFile(reader io.Reader, header *tar.Header,

	file *os.File, fsync bool) (*FileUnwrapResult, error)

func (*DefaultFileUnwrapper) UnwrapNewFile

func (u *DefaultFileUnwrapper) UnwrapNewFile(reader io.Reader, header *tar.Header,

	file *os.File, fsync bool) (*FileUnwrapResult, error)

type DefaultRestoreDescMaker

type DefaultRestoreDescMaker struct{}

func (DefaultRestoreDescMaker) Make

func (m DefaultRestoreDescMaker) Make(restoreParameters []string, names DatabasesByNames) (RestoreDesc, error)

type DeleteExplainer added in v0.15.2

type DeleteExplainer struct {
	// contains filtered or unexported fields
}

DeleteExplainer collects what a delete would remove and reports the recovery window on either side of it.

The window before the delete is read when the explainer is built, so it reflects storage as it stands. The window after is computed by removing the planned objects from that same snapshot - not by re-listing storage, which would be describing a delete that has not happened.

func NewDeleteExplainer added in v0.15.2

func NewDeleteExplainer(rootFolder storage.Folder, command string) *DeleteExplainer

NewDeleteExplainer snapshots the current recovery window ahead of a delete.

func (*DeleteExplainer) Collect added in v0.15.2

func (e *DeleteExplainer) Collect(plan internal.DeletePlan) error

Collect receives a delete plan. It satisfies internal.CollectPlanFunc.

func (*DeleteExplainer) Explain added in v0.15.2

func (e *DeleteExplainer) Explain() (DeleteExplanation, error)

Explain builds the report from everything collected so far.

func (*DeleteExplainer) ExplainOrLog added in v0.15.2

func (e *DeleteExplainer) ExplainOrLog(format string, output io.Writer) error

ExplainOrLog writes the explanation, reporting a storage read failure without discarding the plan that was collected regardless.

type DeleteExplanation added in v0.15.2

type DeleteExplanation struct {
	Command string `json:"command"`

	Objects     int    `json:"objects"`
	Bytes       int64  `json:"bytes"`
	BytesPretty string `json:"bytes_pretty"`

	BackupsDeleted  []ExplainedBackup `json:"backups_deleted"`
	BackupsRetained []ExplainedBackup `json:"backups_retained"`
	WalSegments     int               `json:"wal_segments_deleted"`

	RecoveryWindowBefore PITRWindowReport `json:"recovery_window_before"`
	RecoveryWindowAfter  PITRWindowReport `json:"recovery_window_after"`

	// Effects are the intended consequences: history given up, space reclaimed.
	Effects []string `json:"effects,omitempty"`
	// Warnings are consequences that are usually not intended. They do not stop
	// anything - --explain never deletes - but they are the reason to read the
	// report before adding --confirm.
	Warnings []string `json:"warnings,omitempty"`
}

DeleteExplanation is what a delete would do, in terms of what could still be recovered afterwards rather than in terms of object counts.

type DeleteHandler

type DeleteHandler struct {
	internal.DeleteHandler
}

func NewDeleteHandler

func NewDeleteHandler(folder storage.Folder, permanentBackups, permanentWals map[PermanentObject]bool,

	useSentinelTime bool,

	options ...internal.DeleteHandlerOption,

) (*DeleteHandler, error)

func (*DeleteHandler) HandleDeleteGarbage

func (dh *DeleteHandler) HandleDeleteGarbage(args []string, confirm bool, deleteWithoutBackups bool) error

type DeltaBackupConfigurator

type DeltaBackupConfigurator interface {
	Configure(folder storage.Folder, isPermanent bool) (PrevBackupInfo, DeltaDecision, error)
}

type DeltaChain added in v0.15.2

type DeltaChain struct {
	// Links are the backups from the base through to the backup the chain was
	// resolved from, oldest first.
	Links []string
	// Depth is how many delta backups stand between the full backup and the end
	// of the chain. A full backup on its own has depth 0.
	Depth int
	// FullBackupName is the full backup at the base. Empty when the chain is broken.
	FullBackupName string
	// Broken is set when the chain does not terminate at a full backup that is
	// present and readable in storage.
	Broken bool
	// BreakReason and BreakDetail describe what went wrong when Broken is set.
	BreakReason DeltaPromotionReason
	BreakDetail string
}

DeltaChain is the increment chain a backup sits at the end of, resolved by walking storage rather than by trusting any single backup's own count.

The count in a sentinel is written once and never revisited. If it is missing - an older backup, a partial write, a backup copied in from elsewhere - the configurator that trusts it restarts counting from one, and the chain grows past its limit without anything saying so. Walking the links costs one sentinel read per link, once per backup-push, and cannot drift.

func ResolveDeltaChain added in v0.15.2

func ResolveDeltaChain(baseBackupFolder storage.Folder, backupName string) (DeltaChain, error)

ResolveDeltaChain walks the increment chain ending at backupName back to the full backup it is built on.

type DeltaDecision added in v0.15.2

type DeltaDecision struct {
	// UseDelta is whether the next backup may be a delta.
	UseDelta bool
	// Reason is set when a delta was possible but is not being taken.
	Reason DeltaPromotionReason
	Detail string
	// Depth is the depth the next backup would have: 0 for a full backup, and
	// the base chain's depth plus one for a delta.
	Depth int
	// MaxDepth is the configured limit, from WALG_DELTA_MAX_STEPS.
	MaxDepth int
	// Chain is the resolved base chain, oldest first.
	Chain []string
}

DeltaDecision is the outcome of deciding whether the next backup may be a delta on top of a candidate base.

func DecideDelta added in v0.15.2

func DecideDelta(input DeltaDecisionInput) DeltaDecision

DecideDelta decides whether the next backup may be a delta on top of a candidate base, and promotes it to a full backup when it may not.

What the limit counts depends on WALG_DELTA_ORIGIN, because the two modes build different shapes:

  • LATEST (default) chains each delta onto the previous one, so the chain deepens and a restore must apply every link. The depth walked from storage is what the limit bounds.
  • LATEST_FULL rebases every delta onto the full backup, so the chain is never deeper than one link and a walked depth could never reach the limit. There the limit bounds how many deltas accumulate on one full backup - which is what keeps the full backup from getting arbitrarily stale - and that is the base's own recorded count.

Under LATEST_FULL the recorded count is therefore still trusted, but the walk is not wasted: a chain that is broken or unreadable promotes in either mode.

func (DeltaDecision) LogDecision added in v0.15.2

func (d DeltaDecision) LogDecision(baseName string)

LogDecision states the outcome once, in the terms an operator would ask about.

func (DeltaDecision) Promoted added in v0.15.2

func (d DeltaDecision) Promoted() bool

Promoted reports whether a delta was possible and was declined.

type DeltaDecisionInput added in v0.15.2

type DeltaDecisionInput struct {
	// Chain is the base backup's increment chain, walked from storage.
	Chain DeltaChain
	// RecordedCount is the base backup's own delta count, which is only used
	// under LATEST_FULL. See DecideDelta.
	RecordedCount *int
	// MaxDeltas is WALG_DELTA_MAX_STEPS.
	MaxDeltas int
	// FromFull is WALG_DELTA_ORIGIN=LATEST_FULL.
	FromFull bool
	// BaseIsPermanent and BaseHasStartLSN describe the candidate base backup.
	BaseIsPermanent bool
	BaseHasStartLSN bool
	// NextIsPermanent is whether the backup about to be taken is permanent.
	NextIsPermanent bool
}

DeltaDecisionInput is what deciding delta-or-full depends on.

type DeltaFile

type DeltaFile struct {
	Locations []walparser.BlockLocation

	WalParser *walparser.WalParser
}

func LoadDeltaFile

func LoadDeltaFile(reader io.Reader) (*DeltaFile, error)

func NewDeltaFile

func NewDeltaFile(walParser *walparser.WalParser) (*DeltaFile, error)

func (*DeltaFile) Save

func (deltaFile *DeltaFile) Save(writer io.Writer) error

type DeltaFileChanWriter

type DeltaFileChanWriter struct {
	DeltaFile             *DeltaFile
	BlockLocationConsumer chan walparser.BlockLocation
}

func NewDeltaFileChanWriter

func NewDeltaFileChanWriter(deltaFile *DeltaFile) *DeltaFileChanWriter

func (*DeltaFileChanWriter) Consume

func (writer *DeltaFileChanWriter) Consume(waitGroup *sync.WaitGroup)

type DeltaFileManager

type DeltaFileManager struct {
	PartFiles *internal.LazyCache[string, *WalPartFile]

	DeltaFileWriters *internal.LazyCache[string, *DeltaFileChanWriter]

	CanceledDeltaFiles map[string]bool
	// contains filtered or unexported fields
}

func NewDeltaFileManager

func NewDeltaFileManager(dataFolder fsutil.DataFolder) *DeltaFileManager

func (*DeltaFileManager) CancelRecording

func (manager *DeltaFileManager) CancelRecording(walFilename string)

func (*DeltaFileManager) CombinePartFile

func (manager *DeltaFileManager) CombinePartFile(deltaFilename string, partFile *WalPartFile) error

func (*DeltaFileManager) FlushDeltaFiles

func (manager *DeltaFileManager) FlushDeltaFiles(ctx context.Context, uploader internal.Uploader, completedPartFiles map[string]bool)

func (*DeltaFileManager) FlushFiles

func (manager *DeltaFileManager) FlushFiles(ctx context.Context, uploader internal.Uploader)

func (*DeltaFileManager) FlushPartFiles

func (manager *DeltaFileManager) FlushPartFiles() (completedPartFiles map[string]bool)

func (*DeltaFileManager) GetBlockLocationConsumer

func (manager *DeltaFileManager) GetBlockLocationConsumer(deltaFilename string) (chan walparser.BlockLocation, error)

func (*DeltaFileManager) GetPartFile

func (manager *DeltaFileManager) GetPartFile(deltaFilename string) (*WalPartFile, error)

type DeltaFileWriterNotFoundError

type DeltaFileWriterNotFoundError struct {
	// contains filtered or unexported fields
}

func (DeltaFileWriterNotFoundError) Error

type DeltaNo

type DeltaNo uint64

type DeltaPromotionReason added in v0.15.2

type DeltaPromotionReason string

DeltaPromotionReason says why a backup that could have been a delta is being taken as a full backup instead.

Only cases where a delta was actually possible get a reason. "Deltas are switched off" and "there is no previous backup" produce full backups too, but recording those would put a reason on almost every full backup and drown the cases worth auditing.

const (
	// DeltaPromotionMaxDepth means the chain has reached WALG_DELTA_MAX_STEPS.
	DeltaPromotionMaxDepth DeltaPromotionReason = "chain_at_max_depth"
	// DeltaPromotionChainBroken means a backup the chain depends on is not in
	// storage, so extending the chain would build on something unrestorable.
	DeltaPromotionChainBroken DeltaPromotionReason = "chain_broken"
	// DeltaPromotionChainCycle means the chain's links refer back to each other.
	DeltaPromotionChainCycle DeltaPromotionReason = "chain_cycle"
	// DeltaPromotionChainUnreadable means a link's sentinel could not be read, so
	// the true depth is unknown.
	DeltaPromotionChainUnreadable DeltaPromotionReason = "chain_unreadable"
	// DeltaPromotionBasePermanent means the candidate base is a permanent backup.
	DeltaPromotionBasePermanent DeltaPromotionReason = "base_is_permanent"
	// DeltaPromotionBaseWithoutLSN means the candidate base predates the delta
	// feature and records no start LSN to increment from.
	DeltaPromotionBaseWithoutLSN DeltaPromotionReason = "base_without_lsn"
)

type DeployMetadata added in v0.15.1

type DeployMetadata struct {
	GitCommit string `json:"git_commit,omitempty"`
	GitBranch string `json:"git_branch,omitempty"`
	DeployID  string `json:"deploy_id,omitempty"`
}

func CollectDeployMetadata added in v0.15.1

func CollectDeployMetadata(gitCommit, gitBranch, deployID string) DeployMetadata

func ExtractDeployMetadata added in v0.15.1

func ExtractDeployMetadata(userData interface{}) (DeployMetadata, bool)

type DeprecatedSentinelFields

type DeprecatedSentinelFields struct {
	FilesMetadataDto

	DeltaFromLSN *LSN `json:"DeltaFromLSN,omitempty"`
}

type DirDatabaseTarBallComposerMaker

type DirDatabaseTarBallComposerMaker struct {
	// contains filtered or unexported fields
}

func NewDirDatabaseTarBallComposerMaker

func NewDirDatabaseTarBallComposerMaker(files internal.BundleFiles, filePackerOptions TarBallFilePackerOptions,
	tarFileSets internal.TarFileSets) *DirDatabaseTarBallComposerMaker

func (DirDatabaseTarBallComposerMaker) Make

type DoctorCheck added in v0.15.2

type DoctorCheck struct {
	Name    string       `json:"name"`
	Status  DoctorStatus `json:"status"`
	Summary string       `json:"summary"`
	Detail  string       `json:"detail,omitempty"`
	// Remedy states what to do about a warn or fail. A check that can fail
	// should always be able to say how to fix it.
	Remedy  string `json:"remedy,omitempty"`
	Elapsed string `json:"elapsed"`
}

DoctorCheck is the result of one preflight check.

type DoctorOptions added in v0.15.2

type DoctorOptions struct {
	// Format is "text" or "json".
	Format string
	// SkipPG omits the checks that need a live PostgreSQL connection, for hosts
	// that only restore or only hold credentials.
	SkipPG bool
	// DataDir overrides PGDATA when sizing the restore-space check.
	DataDir string
	// SpaceMargin is the multiple of the latest backup's uncompressed size that
	// must be free for a restore to be considered safe.
	SpaceMargin float64
	// StaleAfter is the age past which the latest backup is reported as stale.
	StaleAfter time.Duration
}

DoctorOptions carries the tunables for a doctor run.

type DoctorResult added in v0.15.2

type DoctorResult struct {
	Pass    bool          `json:"pass"`
	Checks  []DoctorCheck `json:"checks"`
	Passed  int           `json:"passed"`
	Warned  int           `json:"warned"`
	Failed  int           `json:"failed"`
	Skipped int           `json:"skipped"`
	Elapsed string        `json:"elapsed"`
}

DoctorResult is the full preflight report.

type DoctorStatus added in v0.15.2

type DoctorStatus string

DoctorStatus is the outcome of a single preflight check.

const (
	// DoctorPass means the check succeeded.
	DoctorPass DoctorStatus = "pass"
	// DoctorWarn means the check succeeded but found something worth attention.
	// Warnings do not affect the exit code.
	DoctorWarn DoctorStatus = "warn"
	// DoctorFail means backup or restore would not work as configured.
	DoctorFail DoctorStatus = "fail"
	// DoctorSkip means the check did not run.
	DoctorSkip DoctorStatus = "skip"
)

type DrillPhase added in v0.15.2

type DrillPhase struct {
	Name    string       `json:"name"`
	Status  DoctorStatus `json:"status"`
	Summary string       `json:"summary"`
	Detail  string       `json:"detail,omitempty"`
	Remedy  string       `json:"remedy,omitempty"`
	Elapsed string       `json:"elapsed,omitempty"`
}

DrillPhase is one step of the drill.

type ExplainedBackup added in v0.15.2

type ExplainedBackup struct {
	Name       string    `json:"name"`
	FinishTime time.Time `json:"finish_time,omitempty"`
	Permanent  bool      `json:"permanent,omitempty"`
	// Restorable is whether the backup could serve a restore before the delete.
	// A backup that was already dead weight is worth distinguishing from one this
	// delete is about to kill.
	Restorable bool `json:"restorable"`
}

ExplainedBackup is one backup as it appears in a delete plan.

type ExtendedMetadataDto

type ExtendedMetadataDto struct {
	StartTime time.Time `json:"start_time"`

	FinishTime time.Time `json:"finish_time"`

	DatetimeFormat string `json:"date_fmt"`

	Hostname string `json:"hostname"`

	DataDir string `json:"data_dir"`

	PgVersion int `json:"pg_version"`

	StartLsn LSN `json:"start_lsn"`

	FinishLsn LSN `json:"finish_lsn"`

	IsPermanent bool `json:"is_permanent"`

	SystemIdentifier *uint64 `json:"system_identifier"`

	UncompressedSize int64 `json:"uncompressed_size"`

	CompressedSize int64 `json:"compressed_size"`

	UserData interface{} `json:"user_data,omitempty"`
}

func NewExtendedMetadataDto

func NewExtendedMetadataDto(isPermanent bool, dataDir string, startTime time.Time,

	sentinelDto BackupSentinelDto) (meta ExtendedMetadataDto)

type ExtractProvider

type ExtractProvider interface {
	Get(backup Backup, filesToUnwrap map[string]bool, skipRedundantTars bool, dbDataDir string, createNewIncrementalFiles bool) (
		interpreter IncrementalTarInterpreter,
		concurrentTarsToExtract []internal.ReaderMaker,
		sequentialTarsToExtract []internal.ReaderMaker,
		err error)
}

type ExtractProviderDBSpec

type ExtractProviderDBSpec struct {
	RestoreParameters []string
	// contains filtered or unexported fields
}

func NewExtractProviderDBSpec

func NewExtractProviderDBSpec(restoreParameters []string) *ExtractProviderDBSpec

func (ExtractProviderDBSpec) Get

func (p ExtractProviderDBSpec) Get(

	backup Backup,

	filesToUnwrap map[string]bool,

	skipRedundantTars bool,

	dbDataDir string,

	createNewIncrementalFiles bool,

) (IncrementalTarInterpreter, []internal.ReaderMaker, []internal.ReaderMaker, error)

type ExtractProviderImpl

type ExtractProviderImpl struct {
	FilesToExtractProviderImpl
}

func (ExtractProviderImpl) Get

func (t ExtractProviderImpl) Get(
	backup Backup,
	filesToUnwrap map[string]bool,
	skipRedundantTars bool,
	dbDataDir string,
	createNewIncrementalFiles bool,
) (IncrementalTarInterpreter, []internal.ReaderMaker, []internal.ReaderMaker, error)

type FetchConfig

type FetchConfig struct {
	// contains filtered or unexported fields
}

func NewFetchConfig

func NewFetchConfig(dbDataDirectory string, backup Backup, rootFolder storage.Folder, spec *TablespaceSpec,

	filesToUnwrap map[string]bool, skipRedundantTars bool, manager ExtractProvider) *FetchConfig

func (*FetchConfig) SkipRedundantFiles

func (fc *FetchConfig) SkipRedundantFiles(unwrapResult *UnwrapResult)

type FileTarInterpreter

type FileTarInterpreter struct {
	DBDataDirectory string

	Sentinel BackupSentinelDto

	FilesMetadata FilesMetadataDto

	FilesToUnwrap map[string]bool

	UnwrapResult *UnwrapResult
	// contains filtered or unexported fields
}

func NewFileTarInterpreter

func NewFileTarInterpreter(

	dbDataDirectory string, sentinel BackupSentinelDto, filesMetadata FilesMetadataDto,

	filesToUnwrap map[string]bool, createNewIncrementalFiles bool,

) *FileTarInterpreter

func (*FileTarInterpreter) AddFileUnwrapResult

func (tarInterpreter *FileTarInterpreter) AddFileUnwrapResult(result *FileUnwrapResult, fileName string)

func (*FileTarInterpreter) GetUnwrapResult

func (tarInterpreter *FileTarInterpreter) GetUnwrapResult() *UnwrapResult

func (*FileTarInterpreter) Interpret

func (tarInterpreter *FileTarInterpreter) Interpret(fileReader io.Reader, fileInfo *tar.Header) error

type FileUnwrapResult

type FileUnwrapResult struct {
	FileUnwrapResultType
	// contains filtered or unexported fields
}

func NewCompletedResult

func NewCompletedResult() *FileUnwrapResult

func NewCreatedFromIncrementResult

func NewCreatedFromIncrementResult(missingBlockCount int64) *FileUnwrapResult

func NewSkippedResult

func NewSkippedResult() *FileUnwrapResult

func NewWroteIncrementBlocksResult

func NewWroteIncrementBlocksResult(restoredBlockCount int64) *FileUnwrapResult

type FileUnwrapResultType

type FileUnwrapResultType int
const (
	Completed FileUnwrapResultType = iota + 1
	CreatedFromIncrement
	WroteIncrementBlocks
	Skipped
)

type FileUnwrapperType

type FileUnwrapperType int
const (
	DefaultBackupFileUnwrapper FileUnwrapperType = iota + 1
	CatchupBackupFileUnwrapper
)

type FilesMetadataDto

type FilesMetadataDto struct {
	Files internal.BackupFileList `json:"Files,omitempty"`

	TarFileSets map[string][]string `json:"TarFileSets,omitempty"`

	DatabasesByNames DatabasesByNames `json:"DatabasesByNames,omitempty"`
}

func NewFilesMetadataDto

func NewFilesMetadataDto(files internal.BackupFileList, tarFileSets internal.TarFileSets) FilesMetadataDto

type FilesToExtractProvider

type FilesToExtractProvider interface {
	Get(backup Backup, filesToUnwrap map[string]bool, skipRedundantTars bool) (

		tarsToExtract []internal.ReaderMaker, pgControlKey string, err error)
}

type FilesToExtractProviderImpl

type FilesToExtractProviderImpl struct {
}

func (FilesToExtractProviderImpl) Get

func (t FilesToExtractProviderImpl) Get(backup Backup, filesToUnwrap map[string]bool, skipRedundantTars bool) (

	concurrentTarsToExtract []internal.ReaderMaker, sequentialTarsToExtract []internal.ReaderMaker, err error)

type FilesystemSpace added in v0.15.2

type FilesystemSpace struct {
	ID         string   `json:"id"`
	Paths      []string `json:"paths"`
	FreeBytes  int64    `json:"free_bytes"`
	TotalBytes int64    `json:"total_bytes"`
}

FilesystemSpace is the capacity of one filesystem a restore would write to, together with the restore paths that land on it.

type GenericMetaFetcher

type GenericMetaFetcher struct{}

func NewGenericMetaFetcher

func NewGenericMetaFetcher() GenericMetaFetcher

func (GenericMetaFetcher) Fetch

func (mf GenericMetaFetcher) Fetch(backupName string, backupFolder storage.Folder) (internal.GenericMetadata, error)

func (GenericMetaFetcher) FetchFromStorage

func (mf GenericMetaFetcher) FetchFromStorage(

	backupName string, backupFolder storage.Folder, storage string,

) (internal.GenericMetadata, error)

type GenericMetaInteractor

type GenericMetaInteractor struct {
	GenericMetaFetcher

	GenericMetaSetter
}

func NewGenericMetaInteractor

func NewGenericMetaInteractor() GenericMetaInteractor

type GenericMetaSetter

type GenericMetaSetter struct{}

func NewGenericMetaSetter

func NewGenericMetaSetter() GenericMetaSetter

func (GenericMetaSetter) SetIsPermanent

func (ms GenericMetaSetter) SetIsPermanent(backupName string, backupFolder storage.Folder, isPermanent bool) error

func (GenericMetaSetter) SetUserData

func (ms GenericMetaSetter) SetUserData(backupName string, backupFolder storage.Folder, userData interface{}) error

type HistoryFileNotFoundError

type HistoryFileNotFoundError struct {
	// contains filtered or unexported fields
}

func (HistoryFileNotFoundError) Error

func (err HistoryFileNotFoundError) Error() string

type IBackupFileUnwrapper

type IBackupFileUnwrapper interface {
	UnwrapNewFile(reader io.Reader, header *tar.Header, file *os.File, fsync bool) (*FileUnwrapResult, error)
	UnwrapExistingFile(reader io.Reader, header *tar.Header, file *os.File, fsync bool) (*FileUnwrapResult, error)
}

func NewFileUnwrapper

func NewFileUnwrapper(unwrapperType FileUnwrapperType, options *BackupFileOptions) IBackupFileUnwrapper

type IncorrectBackupNameError

type IncorrectBackupNameError struct {
	// contains filtered or unexported fields
}

func (IncorrectBackupNameError) Error

func (err IncorrectBackupNameError) Error() string

type IncorrectLogSegNoError

type IncorrectLogSegNoError struct {
	// contains filtered or unexported fields
}

func (IncorrectLogSegNoError) Error

func (err IncorrectLogSegNoError) Error() string

type IncrementDetailsFetcher

type IncrementDetailsFetcher struct {
	// contains filtered or unexported fields
}

func NewIncrementDetailsFetcher

func NewIncrementDetailsFetcher(backup Backup) *IncrementDetailsFetcher

func (*IncrementDetailsFetcher) Fetch

type IncrementalPageReader

type IncrementalPageReader struct {
	PagedFile ioextensions.ReadSeekCloser

	FileSize int64

	Lsn LSN

	Next []byte

	Blocks []uint32
}

func (*IncrementalPageReader) AdvanceFileReader

func (pageReader *IncrementalPageReader) AdvanceFileReader() error

func (*IncrementalPageReader) Close

func (pageReader *IncrementalPageReader) Close() error

func (*IncrementalPageReader) DeltaBitmapInitialize

func (pageReader *IncrementalPageReader) DeltaBitmapInitialize(deltaBitmap *roaring.Bitmap)

func (*IncrementalPageReader) DrainMoreData

func (pageReader *IncrementalPageReader) DrainMoreData() (succeed bool, err error)

func (*IncrementalPageReader) FullScanInitialize

func (pageReader *IncrementalPageReader) FullScanInitialize() error

func (*IncrementalPageReader) Read

func (pageReader *IncrementalPageReader) Read(p []byte) (n int, err error)

func (*IncrementalPageReader) SelectNewValidPage

func (pageReader *IncrementalPageReader) SelectNewValidPage(pageBytes []byte, blockNo uint32) (valid bool)

func (*IncrementalPageReader) WriteDiffMapToHeader

func (pageReader *IncrementalPageReader) WriteDiffMapToHeader(headerWriter io.Writer)

type IncrementalTarInterpreter

type IncrementalTarInterpreter interface {
	internal.TarInterpreter

	GetUnwrapResult() *UnwrapResult
}

type IntegrityCheckDetails

type IntegrityCheckDetails []*IntegrityScanSegmentSequence

func (IntegrityCheckDetails) NewPlainTextReader

func (sequences IntegrityCheckDetails) NewPlainTextReader() (io.Reader, error)

type IntegrityCheckRunner

type IntegrityCheckRunner struct {
	// contains filtered or unexported fields
}

func NewIntegrityCheckRunner

func NewIntegrityCheckRunner(

	rootFolder storage.Folder,

	walFolderFilenames []string,

	currentWalSegment WalSegmentDescription,

	backupSearchParams BackupSearchParams,

) (IntegrityCheckRunner, error)

func (IntegrityCheckRunner) Run

func (IntegrityCheckRunner) Type

type IntegrityScanSegmentSequence

type IntegrityScanSegmentSequence struct {
	TimelineID uint32 `json:"timeline_id"`

	StartSegment string `json:"start_segment"`

	EndSegment string `json:"end_segment"`

	SegmentsCount int `json:"segments_count"`

	Status ScannedSegmentStatus `json:"status"`
}

type InvalidIncrementFileHeaderError

type InvalidIncrementFileHeaderError struct {
	// contains filtered or unexported fields
}

func (InvalidIncrementFileHeaderError) Error

type InvalidWalFileMagicError

type InvalidWalFileMagicError struct {
	// contains filtered or unexported fields
}

func (InvalidWalFileMagicError) Error

func (err InvalidWalFileMagicError) Error() string

type LSN

type LSN uint64

func FindLastCommonPoint

func FindLastCommonPoint(target, source []*TimelineHistoryRecord) (LSN, uint32, error)

func ParseLSN

func ParseLSN(s string) (LSN, error)

func (LSN) String

func (lsn LSN) String() string

type NilWalParserError

type NilWalParserError struct {
	// contains filtered or unexported fields
}

func (NilWalParserError) Error

func (err NilWalParserError) Error() string

type NoBitmapFoundError

type NoBitmapFoundError struct {
	// contains filtered or unexported fields
}

func (NoBitmapFoundError) Error

func (err NoBitmapFoundError) Error() string

type NoCorrectBackupFoundError

type NoCorrectBackupFoundError struct {
	// contains filtered or unexported fields
}

func (NoCorrectBackupFoundError) Error

func (err NoCorrectBackupFoundError) Error() string

type NoPostgresVersionError

type NoPostgresVersionError struct {
	// contains filtered or unexported fields
}

func NewNoPostgresVersionError

func NewNoPostgresVersionError() NoPostgresVersionError

func (NoPostgresVersionError) Error

func (err NoPostgresVersionError) Error() string

type NonEmptyDBDataDirectoryError

type NonEmptyDBDataDirectoryError struct {
	// contains filtered or unexported fields
}

func NewNonEmptyDBDataDirectoryError

func NewNonEmptyDBDataDirectoryError(dbDataDirectory string) NonEmptyDBDataDirectoryError

func (NonEmptyDBDataDirectoryError) Error

type NopPrefetcher

type NopPrefetcher struct {
}

func (NopPrefetcher) Prefetch

func (p NopPrefetcher) Prefetch(reader internal.StorageFolderReader, walFileName string, location string)

type NotWalFilenameError

type NotWalFilenameError struct {
	// contains filtered or unexported fields
}

func (NotWalFilenameError) Error

func (err NotWalFilenameError) Error() string

type PITRBackup added in v0.15.2

type PITRBackup struct {
	Name        string
	Timeline    uint32
	StartTime   time.Time
	FinishTime  time.Time
	IsPermanent bool

	// StartSegment and FinishSegment bound the WAL a restore must replay to
	// bring this backup to a consistent state.
	StartSegment  WalSegmentNo
	FinishSegment WalSegmentNo

	// IncrementFrom is the backup this one is a delta of, empty for a full
	// backup. IncrementFull is the full backup at the base of the chain.
	IncrementFrom string
	IncrementFull string
}

PITRBackup is what the window computation needs to know about one backup. It is deliberately a plain value: the computation is a pure function of the backups and WAL present, which is what lets delete --explain run it twice, once against storage as it is and once against storage as it would be.

type PITRBlockReason added in v0.15.2

type PITRBlockReason string

PITRBlockReason says why a backup cannot serve a point-in-time restore.

const (
	// PITRMissingOwnWAL means WAL written between the backup's start and finish
	// LSN is absent, so the backup cannot be replayed to a consistent state. Such
	// a backup restores to nothing at all, not merely to a shorter window.
	PITRMissingOwnWAL PITRBlockReason = "missing_own_wal"
	// PITRBrokenChain means the backup is a delta whose base, or some link on the
	// way to it, is not in storage.
	PITRBrokenChain PITRBlockReason = "broken_increment_chain"
)

type PITRGap added in v0.15.2

type PITRGap struct {
	Timeline uint32    `json:"timeline"`
	Start    time.Time `json:"start"`
	End      time.Time `json:"end"`
}

PITRGap is a stretch between two windows on one timeline that no backup and WAL combination can recover to.

func (PITRGap) Duration added in v0.15.2

func (g PITRGap) Duration() time.Duration

Duration is how much unrecoverable time the gap covers.

type PITRInputs added in v0.15.2

type PITRInputs struct {
	Backups      []PITRBackup
	Segments     map[WalSegmentDescription]bool
	SegmentTimes map[WalSegmentDescription]time.Time
}

PITRInputs is the storage state a window computation runs on.

func LoadPITRInputs added in v0.15.2

func LoadPITRInputs(rootFolder storage.Folder) (PITRInputs, error)

LoadPITRInputs reads the backups and WAL segments in storage into the form the window computation runs on.

func (PITRInputs) Compute added in v0.15.2

func (in PITRInputs) Compute() PITRWindowReport

Compute derives the recovery window from these inputs.

func (PITRInputs) Without added in v0.15.2

func (in PITRInputs) Without(deletedNames []string) PITRInputs

Without returns the inputs as they would be if the named storage objects were deleted, so the same computation can describe a storage that does not exist yet. Names are relative to the storage root.

A backup is dropped when any of its objects is deleted: a backup missing one file is not a smaller backup, it is an unusable one.

type PITRUnrestorableBackup added in v0.15.2

type PITRUnrestorableBackup struct {
	Name   string          `json:"name"`
	Reason PITRBlockReason `json:"reason"`
	Detail string          `json:"detail"`
}

PITRUnrestorableBackup is a backup that is present but cannot be restored.

type PITRWindow added in v0.15.2

type PITRWindow struct {
	Timeline uint32 `json:"timeline"`
	// Start is the earliest recoverable point in this window: the finish time of
	// the oldest backup that reaches consistency within it. Recovery cannot
	// target a moment part-way through a backup, so the window opens when the
	// backup closes, not when it started.
	Start time.Time `json:"start"`
	// End is the last recoverable point, taken from the upload time of the last
	// unbroken WAL segment after the backup.
	End          time.Time `json:"end"`
	StartSegment string    `json:"start_segment"`
	EndSegment   string    `json:"end_segment"`
	// Backups are the backups that can serve as a base for a restore into this
	// window, oldest first.
	Backups []string `json:"backups"`
}

PITRWindow is one continuous range of time a cluster can be recovered to.

func (PITRWindow) Duration added in v0.15.2

func (w PITRWindow) Duration() time.Duration

Duration is how much recoverable time the window covers.

type PITRWindowOptions added in v0.15.2

type PITRWindowOptions struct {
	// Format is "text" or "json".
	Format string
	// MinWindow, when set, is the recoverable span the storage is expected to
	// hold. Falling short of it exits non-zero so a retention policy that has
	// quietly stopped covering its stated RPO can be caught by a CI gate.
	MinWindow time.Duration
}

PITRWindowOptions carries the tunables for a pitr-window run.

type PITRWindowReport added in v0.15.2

type PITRWindowReport struct {
	Windows      []PITRWindow             `json:"windows"`
	Gaps         []PITRGap                `json:"gaps,omitempty"`
	Unrestorable []PITRUnrestorableBackup `json:"unrestorable_backups,omitempty"`

	// EarliestRestorableTime and LatestRestorableTime bound every window. The
	// span between them is not necessarily recoverable in full - see Gaps.
	EarliestRestorableTime time.Time `json:"earliest_restorable_time,omitempty"`
	LatestRestorableTime   time.Time `json:"latest_restorable_time,omitempty"`

	// Coverage is the recoverable time summed across windows, which is less than
	// the span between earliest and latest when there are gaps.
	Coverage string `json:"coverage,omitempty"`

	TotalBackups      int `json:"total_backups"`
	RestorableBackups int `json:"restorable_backups"`
}

PITRWindowReport is the recoverable state of a storage: which moments can be restored to, which cannot, and which backups are dead weight.

func ComputePITRWindow added in v0.15.2

func ComputePITRWindow(
	backups []PITRBackup,
	segments map[WalSegmentDescription]bool,
	segmentTimes map[WalSegmentDescription]time.Time,
) PITRWindowReport

ComputePITRWindow derives the ranges of time a cluster can be recovered to from the backups and WAL segments present.

A restore needs two things: a backup that can reach consistency, and an unbroken run of WAL from that backup forward to the target moment. So each backup opens a window at its finish time that runs until the first missing WAL segment after it. Overlapping windows are merged, and what is left between them is a gap - a stretch of history that is simply not recoverable, however many backups sit on either side of it.

Window ends come from the upload time of the last WAL segment in the run, which approximates the wall-clock time of the transactions inside it. WAL records carry commit timestamps, but reading them would mean fetching and decrypting every segment; the upload time is close enough to size a recovery window and costs one listing.

Windows are computed per timeline. A restore that follows a timeline switch is possible, but which fork a given moment belongs to depends on the recovery target, so folding timelines together would report windows that no single restore could actually deliver.

func (PITRWindowReport) CoverageDuration added in v0.15.2

func (r PITRWindowReport) CoverageDuration() time.Duration

CoverageDuration is Coverage as a duration rather than as text.

func (PITRWindowReport) Empty added in v0.15.2

func (r PITRWindowReport) Empty() bool

Empty reports whether nothing at all can be restored.

type PageHeader struct {
	// contains filtered or unexported fields
}

type PagedFileDeltaMap

type PagedFileDeltaMap map[walparser.RelFileNode]*roaring.Bitmap

func NewPagedFileDeltaMap

func NewPagedFileDeltaMap() PagedFileDeltaMap

func (*PagedFileDeltaMap) AddLocationToDelta

func (deltaMap *PagedFileDeltaMap) AddLocationToDelta(location walparser.BlockLocation)

func (*PagedFileDeltaMap) AddLocationsToDelta

func (deltaMap *PagedFileDeltaMap) AddLocationsToDelta(locations []walparser.BlockLocation)

func (*PagedFileDeltaMap) GetDeltaBitmapFor

func (deltaMap *PagedFileDeltaMap) GetDeltaBitmapFor(filePath string) (*roaring.Bitmap, error)

type PermanentObject

type PermanentObject struct {
	Name string

	StorageName string
}

type PgAliveWatcher

type PgAliveWatcher struct {
	Err <-chan error
}

func NewPgWatcher

func NewPgWatcher(queryRunner *PgQueryRunner, aliveCheckInterval time.Duration) *PgAliveWatcher

type PgChecksummablePage

type PgChecksummablePage [MaxDatabasePageSize / int64(NSums*sizeofInt32)][NSums]uint32

PgChecksummablePage represents single database page divided by NSums blocks for checksum calculation

type PgControlData

type PgControlData struct {
	SystemIdentifier uint64 // SystemIdentifier represents system ID of PG cluster (f.e. [0-8] bytes in pg_control)
	CurrentTimeline  uint32 // CurrentTimeline represents current timeline of PG cluster (f.e. [48-52] bytes in pg_control v. 1100+)
	Checkpoint       LSN    //

}

PgControlData represents data contained in pg_control file

func ExtractPgControl

func ExtractPgControl(folder string) (*PgControlData, error)

ExtractPgControl extract pg_control data of cluster by storage

func (*PgControlData) GetCurrentTimeline

func (data *PgControlData) GetCurrentTimeline() uint32

func (*PgControlData) GetSystemIdentifier

func (data *PgControlData) GetSystemIdentifier() uint64

type PgControlNotFoundError

type PgControlNotFoundError struct {
	// contains filtered or unexported fields
}

func (PgControlNotFoundError) Error

func (err PgControlNotFoundError) Error() string

type PgDatabaseInfo

type PgDatabaseInfo struct {
	Name string

	Oid walparser.Oid

	TblSpcOid walparser.Oid
}

type PgDatabasePage

type PgDatabasePage [MaxDatabasePageSize]byte

PgDatabasePage represents single database page

type PgQueryRunner

type PgQueryRunner struct {
	Connection *pgx.Conn

	Version int

	SystemIdentifier *uint64

	Mu sync.Mutex
	// contains filtered or unexported fields
}

func NewPgQueryRunner

func NewPgQueryRunner(ctx context.Context, conn *pgx.Conn) (*PgQueryRunner, error)

func (*PgQueryRunner) BuildGetDatabasesQuery

func (queryRunner *PgQueryRunner) BuildGetDatabasesQuery() (string, error)

func (*PgQueryRunner) BuildStartBackup

func (queryRunner *PgQueryRunner) BuildStartBackup() (string, error)

func (*PgQueryRunner) BuildStatisticsQuery

func (queryRunner *PgQueryRunner) BuildStatisticsQuery() (string, error)

func (*PgQueryRunner) BuildStopBackup

func (queryRunner *PgQueryRunner) BuildStopBackup() (string, error)

func (*PgQueryRunner) ForEachDatabase

func (queryRunner *PgQueryRunner) ForEachDatabase(ctx context.Context,

	function func(runner *PgQueryRunner, db PgDatabaseInfo) error) error

func (*PgQueryRunner) GetArchiveCommand

func (queryRunner *PgQueryRunner) GetArchiveCommand(ctx context.Context) (string, error)

func (*PgQueryRunner) GetArchiveMode

func (queryRunner *PgQueryRunner) GetArchiveMode(ctx context.Context) (string, error)

func (*PgQueryRunner) GetDataChecksums

func (queryRunner *PgQueryRunner) GetDataChecksums(ctx context.Context) (string, error)

func (*PgQueryRunner) GetDataDir

func (queryRunner *PgQueryRunner) GetDataDir(ctx context.Context) (dataDir string, err error)

func (*PgQueryRunner) GetDatabaseInfos

func (queryRunner *PgQueryRunner) GetDatabaseInfos(ctx context.Context) ([]PgDatabaseInfo, error)

func (*PgQueryRunner) GetLockingPID

func (queryRunner *PgQueryRunner) GetLockingPID(ctx context.Context) (int, error)

func (*PgQueryRunner) GetParameter

func (queryRunner *PgQueryRunner) GetParameter(ctx context.Context, parameterName string) (string, error)

func (*PgQueryRunner) GetPhysicalSlotInfo

func (queryRunner *PgQueryRunner) GetPhysicalSlotInfo(ctx context.Context, slotName string) (PhysicalSlot, error)

func (*PgQueryRunner) GetWalSegmentBytes

func (queryRunner *PgQueryRunner) GetWalSegmentBytes(ctx context.Context) (segBlocks uint64, err error)

func (*PgQueryRunner) IsStandby

func (queryRunner *PgQueryRunner) IsStandby(ctx context.Context) (bool, error)

func (*PgQueryRunner) IsTablespaceMapExists

func (queryRunner *PgQueryRunner) IsTablespaceMapExists() bool

func (*PgQueryRunner) Ping

func (queryRunner *PgQueryRunner) Ping() error

func (*PgQueryRunner) ReadTimeline

func (queryRunner *PgQueryRunner) ReadTimeline(ctx context.Context) (timeline uint32, err error)

func (*PgQueryRunner) StartBackup

func (queryRunner *PgQueryRunner) StartBackup(ctx context.Context, backup string) (backupName string,

	lsnString string, inRecovery bool, err error)

func (*PgQueryRunner) StopBackup

func (queryRunner *PgQueryRunner) StopBackup(ctx context.Context) (label string, offsetMap string, lsnStr string, err error)

func (*PgQueryRunner) TryGetLock

func (queryRunner *PgQueryRunner) TryGetLock(ctx context.Context) (err error)

type PgRelationStat

type PgRelationStat struct {
	// contains filtered or unexported fields
}

type PhysicalSlot

type PhysicalSlot struct {
	Name       string
	Exists     bool
	Active     bool
	RestartLSN pglogrepl.LSN
}

The PhysicalSlot represents a Physical Replication Slot.

func NewPhysicalSlot

func NewPhysicalSlot(name string, exists bool, active bool, restartLSN string) (slot PhysicalSlot, err error)

NewPhysicalSlot is a helper function to declare a new PhysicalSlot object and set vaues from the parsed arguments

type PrevBackupInfo

type PrevBackupInfo struct {
	// contains filtered or unexported fields
}

func NewPrevBackupInfo

func NewPrevBackupInfo(name string, sentinel BackupSentinelDto, filesMeta FilesMetadataDto) PrevBackupInfo

type ProcessMessageResult

type ProcessMessageResult int

The ProcessMessageResult is an enum representing possible results from the methods processing the messages as received from Postgres into the wal segment.

const (
	ProcessMessageOK ProcessMessageResult = iota
	ProcessMessageUnknown
	ProcessMessageCopyDone
	ProcessMessageReplyRequested
	ProcessMessageSegmentGap
	ProcessMessageMismatch
)

These are the multiple results that the methods can return

type QueryRunner

type QueryRunner interface {
	StartBackup(ctx context.Context, backup string) (string, string, bool, error)

	StopBackup(ctx context.Context) (string, string, string, error)
}

type RatedComposeFileInfo

type RatedComposeFileInfo struct {
	internal.ComposeFileInfo
	// contains filtered or unexported fields
}

type RatingTarBallComposer

type RatingTarBallComposer struct {
	// contains filtered or unexported fields
}

func NewRatingTarBallComposer

func NewRatingTarBallComposer(

	tarSizeThreshold uint64, updateRatingEvaluator internal.ComposeRatingEvaluator,

	incrementBaseLsn *LSN, deltaMap PagedFileDeltaMap, tarBallQueue *internal.TarBallQueue,

	crypter crypto.Crypter, fileStats RelFileStatistics, bundleFiles internal.BundleFiles, packer *TarBallFilePackerImpl,

) (*RatingTarBallComposer, error)

func (*RatingTarBallComposer) AddFile

func (*RatingTarBallComposer) AddHeader

func (c *RatingTarBallComposer) AddHeader(fileInfoHeader *tar.Header, info os.FileInfo) error

func (*RatingTarBallComposer) FinishComposing

func (c *RatingTarBallComposer) FinishComposing() (internal.TarFileSets, error)

func (*RatingTarBallComposer) GetFiles

func (*RatingTarBallComposer) SkipFile

func (c *RatingTarBallComposer) SkipFile(tarHeader *tar.Header, fileInfo os.FileInfo)

type RatingTarBallComposerMaker

type RatingTarBallComposerMaker struct {
	// contains filtered or unexported fields
}

func NewRatingTarBallComposerMaker

func NewRatingTarBallComposerMaker(relFileStats RelFileStatistics,

	filePackerOptions TarBallFilePackerOptions) (*RatingTarBallComposerMaker, error)

func (*RatingTarBallComposerMaker) Make

type ReachedStopSegmentError

type ReachedStopSegmentError struct {
	// contains filtered or unexported fields
}

func (ReachedStopSegmentError) Error

func (err ReachedStopSegmentError) Error() string

type ReadWriterAt

type ReadWriterAt interface {
	io.ReaderAt

	io.WriterAt

	Size() int64

	Name() string
}

func NewReadWriterAtFrom

func NewReadWriterAtFrom(file *os.File) (ReadWriterAt, error)

type ReadWriterAtFileImpl

type ReadWriterAtFileImpl struct {
	*os.File
	// contains filtered or unexported fields
}

func (*ReadWriterAtFileImpl) Size

func (rw *ReadWriterAtFileImpl) Size() int64

type RegexpRestoreDescMaker

type RegexpRestoreDescMaker struct{}

func (RegexpRestoreDescMaker) Make

func (m RegexpRestoreDescMaker) Make(restoreParameters []string, names DatabasesByNames) (RestoreDesc, error)

type RegularDeltaBackupConfigurator

type RegularDeltaBackupConfigurator struct {
	// contains filtered or unexported fields
}

func NewRegularDeltaBackupConfigurator

func NewRegularDeltaBackupConfigurator(deltaBaseSelector internal.BackupSelector) RegularDeltaBackupConfigurator

func (RegularDeltaBackupConfigurator) Configure

func (c RegularDeltaBackupConfigurator) Configure(

	folder storage.Folder, isPermanent bool,

) (prevBackupInfo PrevBackupInfo, decision DeltaDecision, err error)

type RegularPrefetcher

type RegularPrefetcher struct {
}

func (RegularPrefetcher) Prefetch

func (p RegularPrefetcher) Prefetch(_ internal.StorageFolderReader, walFileName string, location string)

type RegularTarBallComposer

type RegularTarBallComposer struct {
	// contains filtered or unexported fields
}

func NewRegularTarBallComposer

func NewRegularTarBallComposer(
	tarBallQueue *internal.TarBallQueue,
	tarBallFilePacker *TarBallFilePackerImpl,
	files internal.BundleFiles,
	tarFileSets internal.TarFileSets,
	crypter crypto.Crypter,
) *RegularTarBallComposer

func (*RegularTarBallComposer) AddFile

func (*RegularTarBallComposer) AddHeader

func (c *RegularTarBallComposer) AddHeader(fileInfoHeader *tar.Header, info os.FileInfo) error

func (*RegularTarBallComposer) FinishComposing

func (c *RegularTarBallComposer) FinishComposing() (internal.TarFileSets, error)

func (*RegularTarBallComposer) GetFiles

func (*RegularTarBallComposer) SkipFile

func (c *RegularTarBallComposer) SkipFile(tarHeader *tar.Header, fileInfo os.FileInfo)

type RegularTarBallComposerMaker

type RegularTarBallComposerMaker struct {
	// contains filtered or unexported fields
}

func NewRegularTarBallComposerMaker

func NewRegularTarBallComposerMaker(
	filePackerOptions TarBallFilePackerOptions, files internal.BundleFiles, tarFileSets internal.TarFileSets,
) *RegularTarBallComposerMaker

func (*RegularTarBallComposerMaker) Make

type RelFileStatistics

type RelFileStatistics map[walparser.RelFileNode]PgRelationStat

type RestoreDesc

type RestoreDesc map[uint32]map[uint32]uint32

func (RestoreDesc) Add

func (desc RestoreDesc) Add(database, filenode, oid uint32)

func (RestoreDesc) FilterFilesToUnwrap

func (desc RestoreDesc) FilterFilesToUnwrap(filesToUnwrap map[string]bool)

func (RestoreDesc) IsFull

func (desc RestoreDesc) IsFull(database uint32) bool

func (RestoreDesc) IsSkipped

func (desc RestoreDesc) IsSkipped(database, tableFile uint32) bool

type RestoreDescMaker

type RestoreDescMaker interface {
	Make(restoreParameters []string, names DatabasesByNames) (RestoreDesc, error)
}

type RestoreDrillOptions added in v0.15.2

type RestoreDrillOptions struct {
	// TargetDir is where the backup is restored. It must be empty or absent,
	// and must not be the live data directory.
	TargetDir string
	// BackupName is the backup to restore; empty means LATEST.
	BackupName string
	// RTO is the recovery time budget the drill is judged against.
	RTO time.Duration
	// RPO is the data loss budget the reachable recovery point is judged against.
	RPO time.Duration
	// StartPostgres runs the restored cluster and measures WAL replay. Without
	// it the drill measures the fetch only, and says so.
	StartPostgres bool
	// PGCtlPath is the pg_ctl to start the restored cluster with.
	PGCtlPath string
	// Port is the port the restored cluster listens on during the drill.
	Port int
	// Keep leaves the restored directory in place for inspection.
	Keep bool
	// WalgBinary is the wal-g used for the restore and for restore_command.
	WalgBinary string
	// ConfigFile is passed through to those invocations, since a subprocess does
	// not inherit a --config flag.
	ConfigFile string
	// SpaceMargin is the free-space multiple required before restoring.
	SpaceMargin float64
	// StartTimeout bounds waiting for the restored cluster to accept connections.
	StartTimeout time.Duration
	// PGDataDir is the live data directory the target must not be, normally PGDATA.
	PGDataDir string
	// Format is "text" or "json".
	Format string
}

RestoreDrillOptions carries the tunables for one restore drill.

type RestoreDrillReport added in v0.15.2

type RestoreDrillReport struct {
	Pass       bool         `json:"pass"`
	BackupName string       `json:"backup_name,omitempty"`
	Phases     []DrillPhase `json:"phases"`

	// RestoredBytes and FetchSeconds describe the restore that was actually
	// performed, so a drill can be compared against the last one.
	RestoredBytes  int64   `json:"restored_bytes,omitempty"`
	FetchSeconds   float64 `json:"fetch_seconds,omitempty"`
	ReplaySeconds  float64 `json:"replay_seconds,omitempty"`
	TotalSeconds   float64 `json:"total_seconds"`
	ThroughputMBps float64 `json:"throughput_mibps,omitempty"`

	// PostgresStarted records whether replay was measured or only the fetch was.
	PostgresStarted bool `json:"postgres_started"`

	// ScratchDirRemoved says whether the drill cleaned up after itself.
	ScratchDirRemoved bool `json:"scratch_dir_removed"`
	// ScratchDirPresent says whether anything is actually on disk at the end. It
	// is not simply the inverse of ScratchDirRemoved: a restore that failed
	// before writing anything leaves nothing behind even with --keep, and
	// claiming otherwise would send someone looking for a cluster that is not
	// there.
	ScratchDirPresent bool   `json:"scratch_dir_present"`
	ScratchDir        string `json:"scratch_dir,omitempty"`

	Passed  int `json:"passed"`
	Warned  int `json:"warned"`
	Failed  int `json:"failed"`
	Skipped int `json:"skipped"`
}

RestoreDrillReport is the result of a restore drill.

type RestorePreflight added in v0.15.2

type RestorePreflight struct {
	BackupName string       `json:"backup_name"`
	Verdict    SpaceVerdict `json:"verdict"`
	// RequiredBytes is the backup's uncompressed size.
	RequiredBytes int64 `json:"required_bytes"`
	// NeededBytes is RequiredBytes with the margin applied.
	NeededBytes int64   `json:"needed_bytes"`
	Margin      float64 `json:"margin"`
	// FreeBytes is the combined free space across every filesystem involved.
	FreeBytes   int64             `json:"free_bytes"`
	Filesystems []FilesystemSpace `json:"filesystems"`
	// Reason explains a verdict that is not simply "sufficient".
	Reason string `json:"reason,omitempty"`
}

RestorePreflight is the result of sizing a restore before starting it.

func CheckRestoreSpace added in v0.15.2

func CheckRestoreSpace(backup Backup, dataDir string, margin float64) (RestorePreflight, error)

CheckRestoreSpace sizes a restore of backup into dataDir against the free space actually available to it.

The backup's sentinel records only a total uncompressed size, with no per-file or per-tablespace breakdown. So when tablespaces put parts of the restore on different filesystems, how the total divides between them is not knowable here. Rather than guess - and either block a restore that would have fit or wave through one that would not - that case is reported as indeterminate, and only a total that cannot fit anywhere is called a failure.

func (RestorePreflight) Describe added in v0.15.2

func (p RestorePreflight) Describe() string

Describe renders the per-filesystem breakdown for a human reading a report.

func (RestorePreflight) Fits added in v0.15.2

func (p RestorePreflight) Fits() bool

Fits reports whether the restore is known not to fit. Indeterminate and unknown verdicts are not failures: refusing on them would block restores this check cannot actually rule on.

func (RestorePreflight) Summary added in v0.15.2

func (p RestorePreflight) Summary() string

Summary renders the verdict as a single line for logs and reports.

type RetentionCheck added in v0.15.2

type RetentionCheck struct {
	Name    string       `json:"name"`
	Status  DoctorStatus `json:"status"`
	Summary string       `json:"summary"`
	Detail  string       `json:"detail,omitempty"`
	Remedy  string       `json:"remedy,omitempty"`
}

RetentionCheck is the result of validating one objective.

type RetentionObjectives added in v0.15.2

type RetentionObjectives struct {
	// RPO is the most recent data loss tolerated: how far behind now the latest
	// restorable point is allowed to be.
	RPO time.Duration
	// RetentionWindow is how far back a restore must remain possible.
	RetentionWindow time.Duration
	// RetainCount is the backup count the policy keeps, as passed to
	// "delete retain". Zero means no policy was declared, and the policy-outcome
	// and cadence checks are skipped.
	RetainCount int
	// Format is "text" or "json".
	Format string
}

RetentionObjectives are the recovery guarantees being claimed, and the policy claimed to deliver them.

type RetentionReport added in v0.15.2

type RetentionReport struct {
	Pass   bool             `json:"pass"`
	Checks []RetentionCheck `json:"checks"`

	// Declared restates the objectives, so a stored report says what it was
	// judged against rather than only how it scored.
	Declared struct {
		RPO             string `json:"rpo,omitempty"`
		RetentionWindow string `json:"retention_window,omitempty"`
		RetainCount     int    `json:"retain_count,omitempty"`
	} `json:"declared"`

	Passed  int `json:"passed"`
	Warned  int `json:"warned"`
	Failed  int `json:"failed"`
	Skipped int `json:"skipped"`
}

RetentionReport is the full validation of a retention policy against the objectives it is supposed to meet.

func ValidateRetention added in v0.15.2

func ValidateRetention(
	explanation *DeleteExplanation,
	objectives RetentionObjectives,
	now time.Time,
) RetentionReport

ValidateRetention judges a retention policy against the objectives it is meant to deliver.

The policy is not modeled or approximated here: explanation carries the recovery window computed before and after running the real delete through the real handler, so what is validated is the delete that would actually happen.

Two questions are asked, and they fail independently. Does storage meet the objectives right now? And would it still meet them once the declared policy has been applied? A storage that passes the first and fails the second is the case worth catching: it looks healthy only because the policy has not caught up with it yet.

type ScannedSegmentDescription

type ScannedSegmentDescription struct {
	WalSegmentDescription
	// contains filtered or unexported fields
}

type ScannedSegmentStatus

type ScannedSegmentStatus int
const (
	// Surely lost missing segment
	Lost ScannedSegmentStatus = iota + 1
	// Missing but probably still uploading segment
	ProbablyUploading
	// Missing but probably delayed segment
	ProbablyDelayed
	// Segment exists in storage
	Found
)

func (ScannedSegmentStatus) MarshalText

func (status ScannedSegmentStatus) MarshalText() ([]byte, error)

MarshalText marshals the ScannedSegmentStatus enum as a string

func (ScannedSegmentStatus) String

func (status ScannedSegmentStatus) String() string

type SegmentScanConfig

type SegmentScanConfig struct {
	UnlimitedScan bool
	// ScanSegmentsLimit is used in case of UnlimitedScan is set to false
	ScanSegmentsLimit       int
	StopOnFirstFoundSegment bool
	// MissingSegmentStatus is set to all missing segments encountered during scan
	MissingSegmentStatus ScannedSegmentStatus
}

SegmentScanConfig is used to configure the single Scan() call of the WalSegmentScanner

type SkippedFileError

type SkippedFileError struct {
	// contains filtered or unexported fields
}

func (SkippedFileError) Error

func (err SkippedFileError) Error() string

type SocketMessageHandler

type SocketMessageHandler interface {
	Handle(ctx context.Context, messageBody []byte) error
}

func NewMessageHandler

func NewMessageHandler(

	messageType daemon.SocketMessageType,

	c net.Conn,

	storage storage.Storage,

) (SocketMessageHandler, error)

type SocketMessageReader

type SocketMessageReader struct {
	// contains filtered or unexported fields
}

func NewMessageReader

func NewMessageReader(c net.Conn) *SocketMessageReader

func (SocketMessageReader) Next

func (r SocketMessageReader) Next() (messageType daemon.SocketMessageType, messageBody []byte, err error)

type SocketWriteFailedError

type SocketWriteFailedError struct {
	// contains filtered or unexported fields
}

func (SocketWriteFailedError) Error

func (err SocketWriteFailedError) Error() string

type SpaceGuardOptions added in v0.15.2

type SpaceGuardOptions struct {
	// Margin is the multiple of the backup's uncompressed size that must be free.
	Margin float64
	// Skip disables the preflight entirely.
	Skip bool
	// Force downgrades a refusal to a warning, for operators who know something
	// the check does not - a filesystem about to be grown, say.
	Force bool
}

SpaceGuardOptions controls the space preflight that runs before a restore writes anything.

type SpaceVerdict added in v0.15.2

type SpaceVerdict string

SpaceVerdict is the outcome of sizing a restore against the free space available for it.

const (
	// SpaceSufficient means the restore fits, with the configured margin.
	SpaceSufficient SpaceVerdict = "sufficient"
	// SpaceInsufficient means the restore demonstrably does not fit. This is only
	// ever reported when it can be established without guessing.
	SpaceInsufficient SpaceVerdict = "insufficient"
	// SpaceIndeterminate means the restore spans filesystems whose individual
	// shares of the total are not recorded in the backup, so whether it fits
	// cannot be decided - only that the combined free space is large enough for
	// the total.
	SpaceIndeterminate SpaceVerdict = "indeterminate"
	// SpaceUnknown means the backup records no uncompressed size to size against.
	SpaceUnknown SpaceVerdict = "unknown"
)

type StatBundleFiles

type StatBundleFiles struct {
	sync.Map
	// contains filtered or unexported fields
}

StatBundleFiles contains the bundle files. Additionally, it calculates and stores the updates count for each added file

func (*StatBundleFiles) AddFile

func (files *StatBundleFiles) AddFile(tarHeader *tar.Header, fileInfo os.FileInfo, isIncremented bool)

func (*StatBundleFiles) AddFileDescription

func (files *StatBundleFiles) AddFileDescription(name string, backupFileDescription internal.BackupFileDescription)

func (*StatBundleFiles) AddFileWithCorruptBlocks

func (files *StatBundleFiles) AddFileWithCorruptBlocks(tarHeader *tar.Header,
	fileInfo os.FileInfo,
	isIncremented bool,
	corruptedBlocks []uint32,
	storeAllBlocks bool)

func (*StatBundleFiles) AddSkippedFile

func (files *StatBundleFiles) AddSkippedFile(tarHeader *tar.Header, fileInfo os.FileInfo)

func (*StatBundleFiles) GetUnderlyingMap

func (files *StatBundleFiles) GetUnderlyingMap() *sync.Map

type StreamingBaseBackup

type StreamingBaseBackup struct {
	TimeLine uint32

	StartLSN pglogrepl.LSN

	EndLSN pglogrepl.LSN

	UncompressedSize int64

	Files internal.BackupFileList
	// contains filtered or unexported fields
}

func NewStreamingBaseBackup

func NewStreamingBaseBackup(pgDataDir string, maxTarSize int64, pgVersion int, pgConn *pgconn.PgConn) *StreamingBaseBackup

func (*StreamingBaseBackup) Archives

func (bb *StreamingBaseBackup) Archives(ctx context.Context) iter.Seq2[*archive, error]

func (*StreamingBaseBackup) BackupName

func (bb *StreamingBaseBackup) BackupName() string

func (*StreamingBaseBackup) FileName

func (bb *StreamingBaseBackup) FileName() string

func (*StreamingBaseBackup) Finish

func (bb *StreamingBaseBackup) Finish() (err error)

func (*StreamingBaseBackup) GetTablespaceSpec

func (bb *StreamingBaseBackup) GetTablespaceSpec() *TablespaceSpec

func (*StreamingBaseBackup) Path

func (bb *StreamingBaseBackup) Path() string

func (*StreamingBaseBackup) Start

func (bb *StreamingBaseBackup) Start(verifyChecksum bool, diskLimit int32) (err error)

func (*StreamingBaseBackup) Upload

func (bb *StreamingBaseBackup) Upload(ctx context.Context, uploader internal.Uploader, bundleFiles internal.BundleFiles) error

type TableInfo

type TableInfo struct {
	Oid         uint32               `json:"oid"`
	Relfilenode uint32               `json:"relfilenode"`
	SubTables   map[string]TableInfo `json:"subtables,omitempty"`
}

type TablespaceLocation

type TablespaceLocation struct {
	Location string `json:"loc"`

	Symlink string `json:"link"`
}

type TablespaceSpec

type TablespaceSpec struct {
	// contains filtered or unexported fields
}

func NewTablespaceSpec

func NewTablespaceSpec(basePrefix string) TablespaceSpec

func (*TablespaceSpec) BasePrefix

func (spec *TablespaceSpec) BasePrefix() (string, bool)

func (*TablespaceSpec) EnsureSymlinkExist

func (spec *TablespaceSpec) EnsureSymlinkExist(location TablespaceLocation) error

func (*TablespaceSpec) MarshalJSON

func (spec *TablespaceSpec) MarshalJSON() ([]byte, error)

func (*TablespaceSpec) TablespaceNames

func (spec *TablespaceSpec) TablespaceNames() []string

func (*TablespaceSpec) UnmarshalJSON

func (spec *TablespaceSpec) UnmarshalJSON(b []byte) error

type TarBallComposerMaker

type TarBallComposerMaker interface {
	Make(bundle *Bundle) (internal.TarBallComposer, error)
}

func NewTarBallComposerMaker

func NewTarBallComposerMaker(composerType TarBallComposerType, queryRunner *PgQueryRunner, uploader internal.Uploader,

	newBackupName string, filePackOptions TarBallFilePackerOptions,

	withoutFilesMetadata bool) (TarBallComposerMaker, error)

type TarBallComposerType

type TarBallComposerType int
const (
	RegularComposer TarBallComposerType = iota + 1

	RatingComposer

	CopyComposer

	DatabaseComposer
)

type TarBallFilePackerImpl

type TarBallFilePackerImpl struct {
	IncrementFromChkpNum *uint32
	// contains filtered or unexported fields
}

func NewTarBallFilePacker

func NewTarBallFilePacker(deltaMap PagedFileDeltaMap, incrementFromLsn *LSN, files internal.BundleFiles,

	options TarBallFilePackerOptions) *TarBallFilePackerImpl

func (*TarBallFilePackerImpl) PackFileIntoTar

func (p *TarBallFilePackerImpl) PackFileIntoTar(cfi *internal.ComposeFileInfo, tarBall internal.TarBall) error

func (*TarBallFilePackerImpl) UpdateDeltaMap

func (p *TarBallFilePackerImpl) UpdateDeltaMap(deltaMap PagedFileDeltaMap)

type TarBallFilePackerOptions

type TarBallFilePackerOptions struct {
	// contains filtered or unexported fields
}

func NewTarBallFilePackerOptions

func NewTarBallFilePackerOptions(verifyPageChecksums, storeAllCorruptBlocks bool) TarBallFilePackerOptions

type TarFilesCollection

type TarFilesCollection struct {
	// contains filtered or unexported fields
}

func (*TarFilesCollection) AddFile

func (collection *TarFilesCollection) AddFile(file *RatedComposeFileInfo)

type TarSizeError

type TarSizeError struct {
	// contains filtered or unexported fields
}

func (TarSizeError) Error

func (err TarSizeError) Error() string

type TarballStreamer

type TarballStreamer struct {
	Tee []string

	TeeIo *bytes.Buffer

	Remaps TarballStreamerRemaps

	Files internal.BundleFiles
	// contains filtered or unexported fields
}

func NewTarballStreamer

func NewTarballStreamer(input io.Reader, maxTarSize int64, bundleFiles internal.BundleFiles) (streamer *TarballStreamer)

func (*TarballStreamer) ArchiveDone

func (streamer *TarballStreamer) ArchiveDone() bool

func (*TarballStreamer) NextInputFile

func (streamer *TarballStreamer) NextInputFile() (err error)

func (*TarballStreamer) Read

func (streamer *TarballStreamer) Read(p []byte) (n int, err error)

type TarballStreamerRemap

type TarballStreamerRemap struct {
	// contains filtered or unexported fields
}

func NewTarballStreamerRemap

func NewTarballStreamerRemap(from string, to string) (tsr *TarballStreamerRemap, err error)

type TarballStreamerRemaps

type TarballStreamerRemaps []TarballStreamerRemap

type TimeLineHistFile

type TimeLineHistFile struct {
	TimeLineID uint32
	Filename   string
	// contains filtered or unexported fields
}

The TimeLineHistFile struct represents a TimeLineHistory file containing TimeLineHistFileRows. Since TimeLineHistFileRows are only parsed 0 or 1 rimes, the data is only preserved as []byte and parsed to TimeLineHistFileRows when required.

func NewTimeLineHistFile

func NewTimeLineHistFile(timelineid uint32, filename string, body []byte) (TimeLineHistFile, error)

NewTimeLineHistFile is a helper function to define a new TimeLineHistFile

func (TimeLineHistFile) LSNToTimeLine

func (tlh TimeLineHistFile) LSNToTimeLine(lsn pglogrepl.LSN) (uint32, error)

LSNToTimeLine uses rows() to get all TimeLineHistFileRows and from those rows get the timeline that a LS belongs too.

func (TimeLineHistFile) Name

func (tlh TimeLineHistFile) Name() string

Name returns the filename of this wal segment. This is a convenience function used by the WalUploader.

func (TimeLineHistFile) Read

func (tlh TimeLineHistFile) Read(p []byte) (n int, err error)

Read is what makes the WalSegment an io.Reader, which can be handled by WalUploader.UploadWalFile.

type TimeLineHistFileRow

type TimeLineHistFileRow struct {
	TimeLineID uint32
	StartLSN   pglogrepl.LSN
	Comment    string
}

The TimeLineHistFileRow struct represents one line in the TimeLineHistory file

type TimelineCheckDetails

type TimelineCheckDetails struct {
	CurrentTimelineID uint32 `json:"current_timeline_id"`

	HighestStorageTimelineID uint32 `json:"highest_storage_timeline_id"`
}

func (TimelineCheckDetails) NewPlainTextReader

func (details TimelineCheckDetails) NewPlainTextReader() (io.Reader, error)

type TimelineCheckRunner

type TimelineCheckRunner struct {
	// contains filtered or unexported fields
}

func NewTimelineCheckRunner

func NewTimelineCheckRunner(walFolderFilenames []string,

	currentSegment WalSegmentDescription) (TimelineCheckRunner, error)

func (TimelineCheckRunner) Name

func (check TimelineCheckRunner) Name() string

func (TimelineCheckRunner) Run

func (TimelineCheckRunner) Type

type TimelineHistoryRecord

type TimelineHistoryRecord struct {
	// contains filtered or unexported fields
}

func GetTimeLineHistoryRecords

func GetTimeLineHistoryRecords(startTimeline uint32, walFolder storage.Folder) ([]*TimelineHistoryRecord, error)

func NewTimelineHistoryRecord

func NewTimelineHistoryRecord(timeline uint32, lsn LSN, comment string) *TimelineHistoryRecord

type TimelineInfo

type TimelineInfo struct {
	ID uint32 `json:"id"`

	ParentID uint32 `json:"parent_id"`

	SwitchPointLsn LSN `json:"switch_point_lsn"`

	StartSegment string `json:"start_segment"`

	EndSegment string `json:"end_segment"`

	SegmentsCount int `json:"segments_count"`

	MissingSegments []string `json:"missing_segments"`

	Backups []*BackupDetail `json:"backups,omitempty"`

	SegmentRangeSize uint64 `json:"segment_range_size"`

	Status string `json:"status"`
}

func NewTimelineInfo

func NewTimelineInfo(walSegments *WalSegmentsSequence, historyRecords []*TimelineHistoryRecord) (*TimelineInfo, error)

type TimelineWithSegmentNo

type TimelineWithSegmentNo struct {
	// contains filtered or unexported fields
}

func NewTimelineWithSegmentNo

func NewTimelineWithSegmentNo(tl uint32, seg uint64) *TimelineWithSegmentNo

func NewTimelineWithSegmentNoBy

func NewTimelineWithSegmentNoBy(record *TimelineHistoryRecord) *TimelineWithSegmentNo

type UnexpectedTarDataError

type UnexpectedTarDataError struct {
	// contains filtered or unexported fields
}

func (UnexpectedTarDataError) Error

func (err UnexpectedTarDataError) Error() string

type UnknownIncrementFileHeaderError

type UnknownIncrementFileHeaderError struct {
	// contains filtered or unexported fields
}

func (UnknownIncrementFileHeaderError) Error

type UnknownTableSpaceError

type UnknownTableSpaceError struct {
	// contains filtered or unexported fields
}

func (UnknownTableSpaceError) Error

func (err UnknownTableSpaceError) Error() string

type UnknownWalVerifyCheckError

type UnknownWalVerifyCheckError struct {
	// contains filtered or unexported fields
}

func NewUnknownWalVerifyCheckError

func NewUnknownWalVerifyCheckError(checkType WalVerifyCheckType) UnknownWalVerifyCheckError

func (UnknownWalVerifyCheckError) Error

func (err UnknownWalVerifyCheckError) Error() string

type UnsupportedPostgresVersionError

type UnsupportedPostgresVersionError struct {
	// contains filtered or unexported fields
}

func NewUnsupportedPostgresVersionError

func NewUnsupportedPostgresVersionError(version int) UnsupportedPostgresVersionError

func (UnsupportedPostgresVersionError) Error

type UnwrapResult

type UnwrapResult struct {
	// contains filtered or unexported fields
}

type VerifyFileResult added in v0.15.1

type VerifyFileResult struct {
	Name             string `json:"name"`
	StoredSHA256     string `json:"stored_sha256,omitempty"`
	ComputedSHA256   string `json:"computed_sha256,omitempty"`
	Match            bool   `json:"match"`
	NoStoredChecksum bool   `json:"no_stored_checksum,omitempty"`
	ReadError        string `json:"read_error,omitempty"`
}

type WalDeltaRecorder

type WalDeltaRecorder struct {
	// contains filtered or unexported fields
}

func NewWalDeltaRecorder

func NewWalDeltaRecorder(blockLocationConsumer chan walparser.BlockLocation) *WalDeltaRecorder

type WalDeltaRecordingReader

type WalDeltaRecordingReader struct {
	PageReader walparser.WalPageReader

	WalParser walparser.WalParser

	PageDataLeftover []byte

	Recorder *WalDeltaRecorder
	// contains filtered or unexported fields
}

func NewWalDeltaRecordingReader

func NewWalDeltaRecordingReader(walFileReader io.Reader,

	walFilename string,

	manager *DeltaFileManager) (*WalDeltaRecordingReader, error)

func (*WalDeltaRecordingReader) Close

func (reader *WalDeltaRecordingReader) Close() error

func (*WalDeltaRecordingReader) Read

func (reader *WalDeltaRecordingReader) Read(p []byte) (n int, err error)

func (*WalDeltaRecordingReader) RecordBlockLocationsFromPage

func (reader *WalDeltaRecordingReader) RecordBlockLocationsFromPage() error

type WalFetchMessageHandler

type WalFetchMessageHandler struct {
	// contains filtered or unexported fields
}

func (*WalFetchMessageHandler) Handle

func (h *WalFetchMessageHandler) Handle(_ context.Context, messageBody []byte) error

type WalMetadataDescription

type WalMetadataDescription struct {
	CreatedTime time.Time `json:"created_time"`

	DatetimeFormat string `json:"date_fmt"`
}

type WalMetadataUploader

type WalMetadataUploader struct {
	// contains filtered or unexported fields
}

func NewWalMetadataUploader

func NewWalMetadataUploader(walMetadataSetting string) (*WalMetadataUploader, error)

func (*WalMetadataUploader) UploadWalMetadata

func (u *WalMetadataUploader) UploadWalMetadata(

	ctx context.Context,

	walFileName string,

	createdTime time.Time,

	uploader internal.Uploader,

) error

type WalPart

type WalPart struct {
	// contains filtered or unexported fields
}

func LoadWalPart

func LoadWalPart(reader io.Reader) (*WalPart, error)

func NewWalPart

func NewWalPart(dataType WalPartDataType, id uint8, data []byte) *WalPart

func (*WalPart) Save

func (part *WalPart) Save(writer io.Writer) error

type WalPartDataType

type WalPartDataType uint8
const (
	PreviousWalHeadType WalPartDataType = 0
	WalTailType         WalPartDataType = 1
	WalHeadType         WalPartDataType = 2
)

type WalPartFile

type WalPartFile struct {
	WalTails [][]byte

	PreviousWalHead []byte

	WalHeads [][]byte
}

func LoadPartFile

func LoadPartFile(reader io.Reader) (*WalPartFile, error)

func NewWalPartFile

func NewWalPartFile() *WalPartFile

func (*WalPartFile) CombineRecords

func (partFile *WalPartFile) CombineRecords() ([]walparser.XLogRecord, error)

func (*WalPartFile) IsComplete

func (partFile *WalPartFile) IsComplete() bool

func (*WalPartFile) Save

func (partFile *WalPartFile) Save(writer io.Writer) error

type WalPartRecorder

type WalPartRecorder struct {
	// contains filtered or unexported fields
}

func NewWalPartRecorder

func NewWalPartRecorder(walFilename string, manager *DeltaFileManager) (*WalPartRecorder, error)

func (*WalPartRecorder) SaveNextWalHead

func (recorder *WalPartRecorder) SaveNextWalHead(head []byte) error

func (*WalPartRecorder) SavePreviousWalTail

func (recorder *WalPartRecorder) SavePreviousWalTail(tailData []byte) error

type WalPrefetcher

type WalPrefetcher interface {
	Prefetch(reader internal.StorageFolderReader, walFileName string, location string)
}

type WalSegment

type WalSegment struct {
	TimeLine uint32
	StartLSN pglogrepl.LSN
	// contains filtered or unexported fields
}

The WalSegment object represents a Postgres Wal Segment, holding all wal data for a wal file.

func NewWalSegment

func NewWalSegment(timeline uint32, location pglogrepl.LSN, walSegmentBytes uint64) *WalSegment

NewWalSegment is a helper function to declare a new WalSegment.

func (*WalSegment) Name

func (seg *WalSegment) Name() string

Name returns the filename of this wal segment. This is also used by the WalUploader to set the name of the destination file during upload of the wal segment.

func (*WalSegment) NextWalSegment

func (seg *WalSegment) NextWalSegment() (*WalSegment, error)

NextWalSegment is a helper function to create the next wal segment which comes after this wal segment. Note that this will be on the same timeline. the convenience is that it also automatically processes a message that crosses the boundary between the two segments.

func (*WalSegment) Read

func (seg *WalSegment) Read(p []byte) (n int, err error)

Read is what makes the WalSegment an io.Reader, which can be handled by WalUploader.UploadWalFile to write to a file.

func (*WalSegment) Stream

func (seg *WalSegment) Stream(conn *pgconn.PgConn, standbyMessageTimeout time.Duration) (ProcessMessageResult, error)

Stream is a helper function to retrieve messages from Postgres and have them processed by processMessage().

type WalSegmentDescription

type WalSegmentDescription struct {
	Number WalSegmentNo

	Timeline uint32
}

func NewWalSegmentDescription

func NewWalSegmentDescription(name string) (WalSegmentDescription, error)

func QueryCurrentWalSegment

func QueryCurrentWalSegment() WalSegmentDescription

func (WalSegmentDescription) GetFileName

func (desc WalSegmentDescription) GetFileName() string

type WalSegmentNo

type WalSegmentNo uint64

func NewWalSegmentNo

func NewWalSegmentNo(lsn LSN) WalSegmentNo

func (WalSegmentNo) GetFilename

func (walSegmentNo WalSegmentNo) GetFilename(timeline uint32) string

func (WalSegmentNo) Next

func (walSegmentNo WalSegmentNo) Next() WalSegmentNo

type WalSegmentNotFoundError

type WalSegmentNotFoundError struct {
	// contains filtered or unexported fields
}

func (WalSegmentNotFoundError) Error

func (err WalSegmentNotFoundError) Error() string

type WalSegmentRunner

type WalSegmentRunner struct {
	// contains filtered or unexported fields
}

func NewWalSegmentRunner

func NewWalSegmentRunner(

	startWalSegment WalSegmentDescription,

	segments map[WalSegmentDescription]bool,

	stopSegmentNo WalSegmentNo,

	timelineSwitchMap map[WalSegmentNo]*TimelineHistoryRecord,

) *WalSegmentRunner

func (*WalSegmentRunner) Current

func (*WalSegmentRunner) ForceMoveNext

func (r *WalSegmentRunner) ForceMoveNext()

func (*WalSegmentRunner) Next

type WalSegmentScanner

type WalSegmentScanner struct {
	ScannedSegments []ScannedSegmentDescription
	// contains filtered or unexported fields
}

WalSegmentScanner is used to scan the WAL segments storage

func NewWalSegmentScanner

func NewWalSegmentScanner(walSegmentRunner *WalSegmentRunner) *WalSegmentScanner

func (*WalSegmentScanner) AddScannedSegment

func (sc *WalSegmentScanner) AddScannedSegment(description WalSegmentDescription, status ScannedSegmentStatus)

func (*WalSegmentScanner) GetMissingSegmentsDescriptions

func (sc *WalSegmentScanner) GetMissingSegmentsDescriptions() []WalSegmentDescription

GetMissingSegmentsDescriptions returns a slice containing WalSegmentDescription of each missing segment

func (*WalSegmentScanner) Scan

func (sc *WalSegmentScanner) Scan(config SegmentScanConfig) error

Scan traverse the WAL storage with WalSegmentRunner. Scan starts from the WalSegmentRunner's current position, so in case of subsequent Scan() call it will continue from the position where it stopped previously.

Scan always stops if: - Stop segment is reached OR - Unknown error encountered Also, it may be configured to stop after: - Scanning the ScanSegmentsLimit of segments - Finding the first segment which exists in WAL storage

type WalSegmentsSequence

type WalSegmentsSequence struct {
	TimelineID uint32

	WalSegmentNumbers map[WalSegmentNo]bool

	MinSegmentNo WalSegmentNo

	MaxSegmentNo WalSegmentNo
}

func NewSegmentsSequence

func NewSegmentsSequence(id uint32, segmentNo WalSegmentNo) *WalSegmentsSequence

func (*WalSegmentsSequence) AddWalSegmentNo

func (seq *WalSegmentsSequence) AddWalSegmentNo(number WalSegmentNo)

func (*WalSegmentsSequence) FindMissingSegments

func (seq *WalSegmentsSequence) FindMissingSegments() ([]WalSegmentDescription, error)

type WalShowJSONOutputWriter

type WalShowJSONOutputWriter struct {
	// contains filtered or unexported fields
}

WalShowJsonOutputWriter writes the detailed JSON output

func (*WalShowJSONOutputWriter) Write

func (writer *WalShowJSONOutputWriter) Write(timelineInfos []*TimelineInfo) error

type WalShowOutputType

type WalShowOutputType int
const (
	TableOutput WalShowOutputType = iota + 1
	JSONOutput
)

type WalShowOutputWriter

type WalShowOutputWriter interface {
	Write(timelineInfos []*TimelineInfo) error
}

WalShowOutputWriter writes the output of wal-show command execution result

func NewWalShowOutputWriter

func NewWalShowOutputWriter(outputType WalShowOutputType, output io.Writer, includeBackups bool) WalShowOutputWriter

type WalShowTableOutputWriter

type WalShowTableOutputWriter struct {
	// contains filtered or unexported fields
}

WalShowTableOutputWriter writes the output in compact pretty table

func (*WalShowTableOutputWriter) Write

func (writer *WalShowTableOutputWriter) Write(timelineInfos []*TimelineInfo) error

type WalUploader

type WalUploader struct {
	internal.Uploader

	ArchiveStatusManager asm.ArchiveStatusManager

	PGArchiveStatusManager asm.ArchiveStatusManager

	*DeltaFileManager
}

func ConfigureWalUploader

func ConfigureWalUploader(baseUploader internal.Uploader) (uploader *WalUploader, err error)

func NewWalUploader

func NewWalUploader(

	baseUploader internal.Uploader,

	deltaFileManager *DeltaFileManager,

) *WalUploader

func PrepareMultiStorageWalUploader

func PrepareMultiStorageWalUploader(folder storage.Folder, targetStorage string) (*WalUploader, error)

func (*WalUploader) FlushFiles

func (walUploader *WalUploader) FlushFiles(ctx context.Context)

func (*WalUploader) UploadWalFile

func (walUploader *WalUploader) UploadWalFile(ctx context.Context, file ioextensions.NamedReader) error

type WalVerifyCheckDetails

type WalVerifyCheckDetails interface {
	NewPlainTextReader() (io.Reader, error) // used in plaintext output
}

type WalVerifyCheckResult

type WalVerifyCheckResult struct {
	Status WalVerifyCheckStatus `json:"status"`

	Details WalVerifyCheckDetails `json:"details"`
}

type WalVerifyCheckRunner

type WalVerifyCheckRunner interface {
	Type() WalVerifyCheckType

	Run() (WalVerifyCheckResult, error)
}

func BuildWalVerifyCheckRunner

func BuildWalVerifyCheckRunner(

	checkType WalVerifyCheckType,

	rootFolder storage.Folder,

	walFolderFilenames []string,

	currentWalSegment WalSegmentDescription,

	backupSearchParams BackupSearchParams,

) (WalVerifyCheckRunner, error)

type WalVerifyCheckStatus

type WalVerifyCheckStatus int
const (
	StatusOk WalVerifyCheckStatus = iota + 1

	StatusWarning

	StatusFailure
)

func (WalVerifyCheckStatus) MarshalText

func (status WalVerifyCheckStatus) MarshalText() ([]byte, error)

func (WalVerifyCheckStatus) String

func (status WalVerifyCheckStatus) String() string

type WalVerifyCheckType

type WalVerifyCheckType int

func (WalVerifyCheckType) MarshalText

func (checkType WalVerifyCheckType) MarshalText() (text []byte, err error)

func (WalVerifyCheckType) String

func (checkType WalVerifyCheckType) String() string

type WalVerifyJSONOutputWriter

type WalVerifyJSONOutputWriter struct {
	// contains filtered or unexported fields
}

WalVerifyJsonOutputWriter writes the detailed JSON output

func (*WalVerifyJSONOutputWriter) Write

type WalVerifyOutputType

type WalVerifyOutputType int
const (
	WalVerifyTableOutput WalVerifyOutputType = iota + 1
	WalVerifyJSONOutput
)

type WalVerifyOutputWriter

type WalVerifyOutputWriter interface {
	Write(results map[WalVerifyCheckType]WalVerifyCheckResult) error
}

WalVerifyOutputWriter writes the output of wal-verify command execution result

func NewWalVerifyOutputWriter

func NewWalVerifyOutputWriter(outputType WalVerifyOutputType, output io.Writer) WalVerifyOutputWriter

type WalVerifyTableOutputWriter

type WalVerifyTableOutputWriter struct {
	// contains filtered or unexported fields
}

WalVerifyTableOutputWriter writes the output as pretty table

func (*WalVerifyTableOutputWriter) Write

Source Files

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL