postgres

package
v1.23.4 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2024 License: Apache-2.0 Imports: 14 Imported by: 1

Documentation

Overview

Package postgres contains the function covering the PostgreSQL integrations and the relative data types

Package postgres contains the function covering the PostgreSQL integrations and the relative data types

Index

Constants

View Source
const (

	// ScratchDataDirectory is the directory to be used for scratch data
	ScratchDataDirectory = "/controller"

	// CertificatesDir location to store the certificates
	CertificatesDir = ScratchDataDirectory + "/certificates/"

	// ProjectedVolumeDirectory is the base directory to store ProjectedVolumeSource
	ProjectedVolumeDirectory = "/projected"

	// ServerCertificateLocation is the location where the server certificate
	// is stored
	ServerCertificateLocation = CertificatesDir + "server.crt"

	// ServerKeyLocation is the location where the private key is stored
	ServerKeyLocation = CertificatesDir + "server.key"

	// StreamingReplicaCertificateLocation is the location where the certificate
	// of the "postgres" user is stored
	StreamingReplicaCertificateLocation = CertificatesDir + "streaming_replica.crt"

	// StreamingReplicaKeyLocation is the location where the private key of
	// the "postgres" user is stored
	StreamingReplicaKeyLocation = CertificatesDir + "streaming_replica.key"

	// ClientCACertificateLocation is the location where the CA certificate
	// is stored, and this certificate will be use to authenticate
	// client certificates
	ClientCACertificateLocation = CertificatesDir + "client-ca.crt"

	// ServerCACertificateLocation is the location where the CA certificate
	// is stored, and this certificate will be use to authenticate
	// server certificates
	ServerCACertificateLocation = CertificatesDir + "server-ca.crt"

	// BarmanBackupEndpointCACertificateLocation is the location where the barman endpoint
	// CA certificate is stored
	BarmanBackupEndpointCACertificateLocation = CertificatesDir + BarmanBackupEndpointCACertificateFileName

	// BarmanBackupEndpointCACertificateFileName is the name of the file in which the barman endpoint
	// CA certificate for backups is stored
	BarmanBackupEndpointCACertificateFileName = "backup-" + BarmanEndpointCACertificateFileName

	// BarmanRestoreEndpointCACertificateLocation is the location where the barman endpoint
	// CA certificate is stored
	BarmanRestoreEndpointCACertificateLocation = CertificatesDir + BarmanRestoreEndpointCACertificateFileName

	// BarmanRestoreEndpointCACertificateFileName is the name of the file in which the barman endpoint
	// CA certificate for restores is stored
	BarmanRestoreEndpointCACertificateFileName = "restore-" + BarmanEndpointCACertificateFileName

	// BarmanEndpointCACertificateFileName is the name of the file in which the barman endpoint
	// CA certificate is stored
	BarmanEndpointCACertificateFileName = "barman-ca.crt"

	// BackupTemporaryDirectory provides a path to backup temporary files
	// needed in the recovery process
	BackupTemporaryDirectory = ScratchDataDirectory + "/backup"

	// RecoveryTemporaryDirectory provides a path to store temporary files
	// needed in the recovery process
	RecoveryTemporaryDirectory = ScratchDataDirectory + "/recovery"

	// SocketDirectory provides a path to store the Unix socket to be
	// used by the PostgreSQL server
	SocketDirectory = ScratchDataDirectory + "/run"

	// ServerPort is the port where the postmaster process will be listening.
	// It's also used in the naming of the Unix socket
	ServerPort = 5432

	// LogPath is the path of the folder used by the logging_collector
	LogPath = ScratchDataDirectory + "/log"

	// LogFileName is the name of the file produced by the logging_collector,
	// excluding the extension. The logging collector process will append
	// `.csv` and `.log` as needed.
	LogFileName = "postgres"

	// CNPGConfigSha256 is the parameter to be used to inject the sha256 of the
	// config in the custom.conf file
	CNPGConfigSha256 = "cnpg.config_sha256"

	// SharedPreloadLibraries shared preload libraries key in the config
	SharedPreloadLibraries = "shared_preload_libraries"

	// SynchronousStandbyNames is the postgresql parameter key for synchronous standbys
	SynchronousStandbyNames = "synchronous_standby_names"
)
View Source
const (
	// DefaultWALSegmentSize is the default size of a single WAL file
	// This must be a power of 2
	DefaultWALSegmentSize = int64(1 << 24)

	// WALHexOctetRe is a regex to match 8 Hex characters
	WALHexOctetRe = `([\dA-Fa-f]{8})`

	// WALTimeLineRe is a regex to match the timeline in a WAL filename
	WALTimeLineRe = WALHexOctetRe

	// WALSegmentNameRe is a regex to match the segment parent log file and segment id
	WALSegmentNameRe = WALHexOctetRe + WALHexOctetRe
)
View Source
const MajorVersionRangeUnlimited = 0

MajorVersionRangeUnlimited is used to represent an unbound limit in a MajorVersionRange

View Source
const ParameterArchiveMode = "archive_mode"

ParameterArchiveMode the configuration key containing the archive_mode value

View Source
const ParameterMaxWalSenders = "max_wal_senders"

ParameterMaxWalSenders the configuration key containing the max_wal_senders value

View Source
const ParameterWalLevel = "wal_level"

ParameterWalLevel the configuration key containing the wal_level value

View Source
const ParameterWalLogHints = "wal_log_hints"

ParameterWalLogHints the configuration key containing the wal_log_hints value

View Source
const (

	// SystemTablespacesPrefix is the prefix denoting tablespaces managed by the Postgres system
	// see https://www.postgresql.org/docs/current/sql-createtablespace.html
	SystemTablespacesPrefix = "pg_"
)

Variables

View Source
var (
	// ManagedExtensions contains the list of extensions the operator supports to manage
	ManagedExtensions = []ManagedExtension{
		{
			Name:                   "pgaudit",
			Namespaces:             []string{"pgaudit"},
			SharedPreloadLibraries: []string{"pgaudit"},
		},
		{
			Name:                   "pg_stat_statements",
			Namespaces:             []string{"pg_stat_statements"},
			SharedPreloadLibraries: []string{"pg_stat_statements"},
		},
		{
			Name:                   "auto_explain",
			SkipCreateExtension:    true,
			Namespaces:             []string{"auto_explain"},
			SharedPreloadLibraries: []string{"auto_explain"},
		},
		{
			Name:                   "pg_failover_slots",
			SkipCreateExtension:    true,
			Namespaces:             []string{"pg_failover_slots"},
			SharedPreloadLibraries: []string{"pg_failover_slots"},
		},
	}

	// FixedConfigurationParameters contains the parameters that can't be
	// changed by the user
	FixedConfigurationParameters = map[string]string{

		"allow_system_table_mods":   blockedConfigurationParameter,
		"archive_mode":              fixedConfigurationParameter,
		"bonjour":                   blockedConfigurationParameter,
		"bonjour_name":              blockedConfigurationParameter,
		"cluster_name":              fixedConfigurationParameter,
		"config_file":               blockedConfigurationParameter,
		"data_directory":            blockedConfigurationParameter,
		"data_sync_retry":           blockedConfigurationParameter,
		"event_source":              blockedConfigurationParameter,
		"external_pid_file":         blockedConfigurationParameter,
		"hba_file":                  blockedConfigurationParameter,
		"hot_standby":               blockedConfigurationParameter,
		"ident_file":                blockedConfigurationParameter,
		"jit_provider":              blockedConfigurationParameter,
		"listen_addresses":          blockedConfigurationParameter,
		"logging_collector":         blockedConfigurationParameter,
		"port":                      fixedConfigurationParameter,
		"primary_conninfo":          fixedConfigurationParameter,
		"primary_slot_name":         fixedConfigurationParameter,
		"recovery_target":           fixedConfigurationParameter,
		"recovery_target_action":    fixedConfigurationParameter,
		"recovery_target_inclusive": fixedConfigurationParameter,
		"recovery_target_lsn":       fixedConfigurationParameter,
		"recovery_target_name":      fixedConfigurationParameter,
		"recovery_target_time":      fixedConfigurationParameter,
		"recovery_target_timeline":  fixedConfigurationParameter,
		"recovery_target_xid":       fixedConfigurationParameter,
		"restore_command":           fixedConfigurationParameter,
		"shared_preload_libraries":  fixedConfigurationParameter,
		"temp_tablespaces":          fixedConfigurationParameter,
		"unix_socket_directories":   blockedConfigurationParameter,
		"unix_socket_group":         blockedConfigurationParameter,
		"unix_socket_permissions":   blockedConfigurationParameter,

		"archive_cleanup_command":                blockedConfigurationParameter,
		"archive_command":                        fixedConfigurationParameter,
		"full_page_writes":                       fixedConfigurationParameter,
		"log_destination":                        blockedConfigurationParameter,
		"log_directory":                          blockedConfigurationParameter,
		"log_file_mode":                          blockedConfigurationParameter,
		"log_filename":                           blockedConfigurationParameter,
		"log_rotation_age":                       blockedConfigurationParameter,
		"log_rotation_size":                      blockedConfigurationParameter,
		"log_truncate_on_rotation":               blockedConfigurationParameter,
		"pg_failover_slots.primary_dsn":          fixedConfigurationParameter,
		"promote_trigger_file":                   blockedConfigurationParameter,
		"recovery_end_command":                   blockedConfigurationParameter,
		"recovery_min_apply_delay":               blockedConfigurationParameter,
		"restart_after_crash":                    blockedConfigurationParameter,
		"ssl":                                    fixedConfigurationParameter,
		"ssl_ca_file":                            fixedConfigurationParameter,
		"ssl_cert_file":                          fixedConfigurationParameter,
		"ssl_crl_file":                           fixedConfigurationParameter,
		"ssl_dh_params_file":                     fixedConfigurationParameter,
		"ssl_ecdh_curve":                         fixedConfigurationParameter,
		"ssl_key_file":                           fixedConfigurationParameter,
		"ssl_passphrase_command":                 fixedConfigurationParameter,
		"ssl_passphrase_command_supports_reload": fixedConfigurationParameter,
		"ssl_prefer_server_ciphers":              fixedConfigurationParameter,
		"stats_temp_directory":                   blockedConfigurationParameter,
		"synchronous_standby_names":              fixedConfigurationParameter,
		"syslog_facility":                        blockedConfigurationParameter,
		"syslog_ident":                           blockedConfigurationParameter,
		"syslog_sequence_numbers":                blockedConfigurationParameter,
		"syslog_split_messages":                  blockedConfigurationParameter,
	}

	// CnpgConfigurationSettings contains the settings that represent the
	// default and the mandatory behavior of CNP
	CnpgConfigurationSettings = ConfigurationSettings{
		GlobalDefaultSettings: SettingsCollection{
			"archive_timeout":            "5min",
			"max_parallel_workers":       "32",
			"max_worker_processes":       "32",
			"max_replication_slots":      "32",
			"logging_collector":          "on",
			"log_destination":            "csvlog",
			"log_rotation_age":           "0",
			"log_rotation_size":          "0",
			"log_truncate_on_rotation":   "false",
			"log_directory":              LogPath,
			"log_filename":               LogFileName,
			"dynamic_shared_memory_type": "posix",
			"wal_sender_timeout":         "5s",
			"wal_receiver_timeout":       "5s",
			"wal_level":                  "logical",
			ParameterWalLogHints:         "on",

			SharedPreloadLibraries: "",
		},
		DefaultSettings: map[MajorVersionRange]SettingsCollection{
			{MajorVersionRangeUnlimited, 120000}: {
				"wal_keep_segments": "32",
			},
			{120000, 130000}: {
				"wal_keep_segments":  "32",
				"shared_memory_type": "mmap",
			},
			{130000, MajorVersionRangeUnlimited}: {
				"wal_keep_size":      "512MB",
				"shared_memory_type": "mmap",
			},
			{120000, MajorVersionRangeUnlimited}: {
				"ssl_max_protocol_version": "TLSv1.3",
				"ssl_min_protocol_version": "TLSv1.3",
			},
		},
		MandatorySettings: SettingsCollection{
			"listen_addresses":        "*",
			"unix_socket_directories": SocketDirectory,
			"hot_standby":             "true",
			"archive_command": fmt.Sprintf(
				"/controller/manager wal-archive --log-destination %s/%s.json %%p",
				LogPath, LogFileName),
			"port":                fmt.Sprint(ServerPort),
			"full_page_writes":    "on",
			"ssl":                 "on",
			"ssl_cert_file":       ServerCertificateLocation,
			"ssl_key_file":        ServerKeyLocation,
			"ssl_ca_file":         ClientCACertificateLocation,
			"restart_after_crash": "false",
		},
	}
)
View Source
var (
	// WALRe is the file segment name parser
	WALRe = regexp.MustCompile(`^` +

		WALTimeLineRe +

		`(?:` +

		WALSegmentNameRe +

		`(?:` +

		`\.[\dA-Fa-f]{8}\.backup` +

		`|` +

		`\.partial` +

		`)?` +

		`|` +

		`\.history` +

		`)$`)

	// WALSegmentRe is the file segment name parser
	WALSegmentRe = regexp.MustCompile(`^` +

		WALTimeLineRe +

		WALSegmentNameRe +
		`$`)

	// ErrorBadWALSegmentName is raised when parsing an invalid segment name
	ErrorBadWALSegmentName = errors.New("invalid WAL segment name")
)

Functions

func CreateHBARules

func CreateHBARules(hba []string,
	defaultAuthenticationMethod, ldapConfigString string,
) (string, error)

CreateHBARules will create the content of pg_hba.conf file given the rules set by the cluster spec

func CreateIdentRules added in v1.20.6

func CreateIdentRules(ident []string, username string) (string, error)

CreateIdentRules will create the content of pg_ident.conf file given the rules set by the cluster spec

func CreatePostgresqlConfFile

func CreatePostgresqlConfFile(configuration *PgConfiguration) (string, string)

CreatePostgresqlConfFile creates the contents of the postgresql.conf file

func GetPostgresMajorVersion

func GetPostgresMajorVersion(parsedVersion int) int

GetPostgresMajorVersion gets only the Major version from a PostgreSQL version string. Example:

GetPostgresMajorVersion("90503") == 90500
GetPostgresMajorVersion("100002") == 100000

func GetPostgresVersionFromTag

func GetPostgresVersionFromTag(version string) (int, error)

GetPostgresVersionFromTag parse a PostgreSQL version string returning a major version ID. Example:

GetPostgresVersionFromTag("9.5.3") == 90503
GetPostgresVersionFromTag("10.2") == 100002
GetPostgresVersionFromTag("15beta1") == 150000

func IsRoleReserved added in v1.20.0

func IsRoleReserved(name string) bool

IsRoleReserved checks if a role is reserved for PostgreSQL or the operator

func IsTablespaceNameValid added in v1.22.0

func IsTablespaceNameValid(name string) (bool, error)

IsTablespaceNameValid check if tablespace name is valid or not

func IsUpgradePossible

func IsUpgradePossible(fromVersion, toVersion int) bool

IsUpgradePossible detect if it's possible to upgrade from fromVersion to toVersion

func IsWALFile

func IsWALFile(name string) bool

IsWALFile check if the passed file name is a regular WAL file. It supports either a full file path or a simple file name

func ParsePostgresConfigBoolean added in v1.21.6

func ParsePostgresConfigBoolean(in string) (bool, error)

ParsePostgresConfigBoolean returns the boolean value parsed from a string as a postgres boolean. It returns an error if the input string is not a valid postgres boolean See: https://www.postgresql.org/docs/current/config-setting.html Boolean: Values can be written as on, off, true, false, yes, no, 1, 0 (all case-insensitive) or any unambiguous prefix of one of these.

func WalSegmentsPerFile

func WalSegmentsPerFile(walSegmentSize int64) int32

WalSegmentsPerFile is the number of WAL Segments in a WAL File

Types

type ConfigurationInfo

type ConfigurationInfo struct {
	// The name of this cluster
	ClusterName string

	// The database settings to be used
	Settings ConfigurationSettings

	// The major version
	MajorVersion int

	// The list of user-level settings
	UserSettings map[string]string

	// The list of replicas
	SyncReplicasElectable []string

	// The number of desired number of synchronous replicas
	SyncReplicas int
	// List of additional sharedPreloadLibraries to be loaded
	AdditionalSharedPreloadLibraries []string

	// Whether we need to include mandatory settings that are
	// not meant to be seen by users. Should be set to
	// true only when writing the configuration to disk
	IncludingMandatory bool

	// Whether we preserve user settings even when they are fixed parameters.
	// This setting is ignored if IncludingMandatory is true.
	// This should be set to true only in the defaulting webhook,
	// to allow the validating webhook to return an error
	PreserveFixedSettingsFromUser bool

	// If the generated configuration should contain shared_preload_libraries too or no
	IncludingSharedPreloadLibraries bool

	// Is this a replica cluster?
	IsReplicaCluster bool

	// TemporaryTablespaces is the list of temporary tablespaces
	TemporaryTablespaces []string

	// IsWalArchivingDisabled is true when user requested to disable WAL archiving
	IsWalArchivingDisabled bool

	// IsAlterSystemEnabled is true when 'allow_alter_system' should be set to on
	IsAlterSystemEnabled bool
}

ConfigurationInfo contains the required information to create a PostgreSQL configuration

type ConfigurationSettings

type ConfigurationSettings struct {
	// These settings are applied to the PostgreSQL default configuration when
	// the user don't specify something different
	GlobalDefaultSettings SettingsCollection

	// The following settings are like GlobalPostgresSettings
	// but are relative only to certain PostgreSQL versions
	DefaultSettings map[MajorVersionRange]SettingsCollection

	// The following settings are applied to the final PostgreSQL configuration,
	// even if the user specified something different
	MandatorySettings SettingsCollection

	// The following settings are applied if pgaudit is enabled
	PgAuditSettings SettingsCollection
}

ConfigurationSettings is the set of settings that are applied, together with the parameters supplied by the users, to generate a custom PostgreSQL configuration

type LSN

type LSN string

LSN is a string composed by two hexadecimal numbers, separated by "/"

func (LSN) Less

func (lsn LSN) Less(other LSN) bool

Less compares two LSNs

func (LSN) Parse

func (lsn LSN) Parse() (int64, error)

Parse an LSN in its components

type MajorVersionRange

type MajorVersionRange = struct {
	// The minimum limit of PostgreSQL major version, extreme included
	Min int

	// The maximum limit of PostgreSQL version, extreme excluded, or MajorVersionRangeUnlimited
	Max int
}

MajorVersionRange is used to represent a range of PostgreSQL versions

type ManagedExtension

type ManagedExtension struct {
	// Name of the extension
	Name string

	// Namespaces contains the configuration namespaces handled by the extension
	Namespaces []string

	// SharedPreloadLibraries is the list of needed shared preload libraries
	SharedPreloadLibraries []string

	// SkipCreateExtension is true when the extension is made only from a shared preload library
	SkipCreateExtension bool
}

ManagedExtension defines all the information about a managed extension

func (ManagedExtension) IsUsed

func (e ManagedExtension) IsUsed(userConfigs map[string]string) bool

IsUsed checks whether a configuration namespace in the namespaces list is used in the user provided configuration

type PgConfiguration

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

PgConfiguration wraps configuration parameters with some checks

func CreatePostgresqlConfiguration

func CreatePostgresqlConfiguration(info ConfigurationInfo) *PgConfiguration

CreatePostgresqlConfiguration creates the configuration from the settings and the default values

func (*PgConfiguration) AddSharedPreloadLibrary

func (p *PgConfiguration) AddSharedPreloadLibrary(newLibrary string)

AddSharedPreloadLibrary add anew shared preloaded library to PostgreSQL configuration

func (*PgConfiguration) GetConfig

func (p *PgConfiguration) GetConfig(key string) string

GetConfig retrieves a configuration from the map of configurations, given the key

func (*PgConfiguration) GetConfigurationParameters

func (p *PgConfiguration) GetConfigurationParameters() map[string]string

GetConfigurationParameters returns the generated configuration parameters

func (*PgConfiguration) GetSortedList

func (p *PgConfiguration) GetSortedList() []string

GetSortedList returns a sorted list of configurations

func (*PgConfiguration) OverwriteConfig

func (p *PgConfiguration) OverwriteConfig(key, value string)

OverwriteConfig overwrites a configuration in the map, given the key/value pair. If the map is nil, it is created and the pair is added

type PgReplicationSlot added in v1.18.0

type PgReplicationSlot struct {
	SlotName    string `json:"slotName,omitempty"`
	Plugin      string `json:"plugin,omitempty"`
	SlotType    string `json:"slotType,omitempty"`
	Datoid      string `json:"datoid,omitempty"`
	Database    string `json:"database,omitempty"`
	Xmin        string `json:"xmin,omitempty"`
	CatalogXmin string `json:"catalogXmin,omitempty"`
	RestartLsn  string `json:"restartLsn,omitempty"`
	WalStatus   string `json:"walStatus,omitempty"`
	SafeWalSize *int   `json:"safeWalSize,omitempty"`
	Active      bool   `json:"active,omitempty"`
}

PgReplicationSlot contains the replication slots status as reported by the primary instance

type PgReplicationSlotList added in v1.18.0

type PgReplicationSlotList []PgReplicationSlot

PgReplicationSlotList is a list of PgReplicationSlot reported by the primary instance

type PgStatBasebackup added in v1.19.6

type PgStatBasebackup struct {
	Usename              string `json:"usename"`
	ApplicationName      string `json:"application_name"`
	BackendStart         string `json:"backend_start"`
	Phase                string `json:"phase"`
	BackupTotal          int64  `json:"backup_total"`
	BackupStreamed       int64  `json:"backup_streamed"`
	BackupTotalPretty    string `json:"backup_total_pretty"`
	BackupStreamedPretty string `json:"backup_streamed_pretty"`
	TablespacesTotal     int64  `json:"tablespaces_total"`
	TablespacesStreamed  int64  `json:"tablespaces_streamed"`
}

PgStatBasebackup contains the information for progress of basebackup as reported by the primary instance

type PgStatReplication

type PgStatReplication struct {
	ApplicationName string `json:"applicationName,omitempty"`
	State           string `json:"state,omitempty"`
	SentLsn         LSN    `json:"receivedLsn,omitempty"`
	WriteLsn        LSN    `json:"writeLsn,omitempty"`
	FlushLsn        LSN    `json:"flushLsn,omitempty"`
	ReplayLsn       LSN    `json:"replayLsn,omitempty"`
	WriteLag        string `json:"writeLag,omitempty"`
	FlushLag        string `json:"flushLag,omitempty"`
	ReplayLag       string `json:"replayLag,omitempty"`
	SyncState       string `json:"syncState,omitempty"`
	SyncPriority    string `json:"syncPriority,omitempty"`
}

PgStatReplication contains the replications of replicas as reported by the primary instance

type PgStatReplicationList added in v1.15.2

type PgStatReplicationList []PgStatReplication

PgStatReplicationList is a list of PgStatReplication reported by the primary instance

func (PgStatReplicationList) Len added in v1.15.2

func (list PgStatReplicationList) Len() int

Len implements sort.Interface extracting the length of the list

func (PgStatReplicationList) Less added in v1.15.2

func (list PgStatReplicationList) Less(i, j int) bool

Less implements sort.Interface to determine the sort order of the replication list Orders by: Sync State, Working State, Sent LSN, Write LSN, ApplicationName

func (PgStatReplicationList) Swap added in v1.15.2

func (list PgStatReplicationList) Swap(i, j int)

Swap implements sort.Interface to swap elements

type PostgresqlStatus

type PostgresqlStatus struct {
	CurrentLsn                LSN         `json:"currentLsn,omitempty"`
	ReceivedLsn               LSN         `json:"receivedLsn,omitempty"`
	ReplayLsn                 LSN         `json:"replayLsn,omitempty"`
	SystemID                  string      `json:"systemID"`
	IsPrimary                 bool        `json:"isPrimary"`
	ReplayPaused              bool        `json:"replayPaused"`
	PendingRestart            bool        `json:"pendingRestart"`
	PendingRestartForDecrease bool        `json:"pendingRestartForDecrease"`
	IsWalReceiverActive       bool        `json:"isWalReceiverActive"`
	IsPgRewindRunning         bool        `json:"isPgRewindRunning"`
	MightBeUnavailable        bool        `json:"mightBeUnavailable"`
	IsArchivingWAL            bool        `json:"isArchivingWAL,omitempty"`
	Node                      string      `json:"node"`
	Pod                       *corev1.Pod `json:"pod"`
	TotalInstanceSize         string      `json:"totalInstanceSize"`
	// populated when MightBeUnavailable reported a healthy status even if it found an error
	MightBeUnavailableMaskedError string `json:"mightBeUnavailableMaskedError,omitempty"`

	LastArchivedWAL     string `json:"lastArchivedWAL,omitempty"`
	LastArchivedWALTime string `json:"lastArchivedWALTime,omitempty"`
	LastFailedWAL       string `json:"lastFailedWAL,omitempty"`
	LastFailedWALTime   string `json:"lastFailedWALTime,omitempty"`

	CurrentWAL string `json:"currentWAL,omitempty"`

	// Is the number of '.ready' wal files contained in the wal archive folder
	ReadyWALFiles int `json:"readyWalFiles,omitempty"`

	// The current timeline ID
	// SELECT timeline_id FROM pg_control_checkpoint()
	TimeLineID int `json:"timeLineID,omitempty"`

	// This field is set when there is an error while extracting the
	// status of a Pod
	Error error `json:"-"`

	// contains the PgStatReplication rows content.
	ReplicationInfo PgStatReplicationList `json:"replicationInfo,omitempty"`
	// contains the PgReplicationSlot rows content.
	ReplicationSlotsInfo PgReplicationSlotList `json:"replicationSlotsInfo,omitempty"`
	// contains the PgStatBasebackup rows content.
	PgStatBasebackupsInfo []PgStatBasebackup `json:"pgStatBasebackupsInfo,omitempty"`

	// Status of the instance manager
	ExecutableHash             string `json:"executableHash"`
	InstanceManagerVersion     string `json:"instanceManagerVersion"`
	InstanceArch               string `json:"instanceArch"`
	IsInstanceManagerUpgrading bool   `json:"isInstanceManagerUpgrading"`

	// This field represents the Kubelet point-of-view of the readiness
	// status of this instance and may be slightly stale when the Kubelet has
	// not still invoked the readiness probe.
	//
	// If you want to check the latest detected status of PostgreSQL, you
	// need to call HasHTTPStatus().
	//
	// This field is never populated in the instance manager.
	IsPodReady bool `json:"isPodReady"`
}

PostgresqlStatus defines a status for every instance in the cluster

func (*PostgresqlStatus) AddPod added in v1.17.2

func (status *PostgresqlStatus) AddPod(pod corev1.Pod)

AddPod store the Pod inside the status

func (PostgresqlStatus) HasHTTPStatus added in v1.18.5

func (status PostgresqlStatus) HasHTTPStatus() bool

HasHTTPStatus checks if the instance manager is reporting this instance as ready.

The result represents the state of PostgreSQL at the moment of the collection of the instance status and is more up-to-date than IsPodReady field, which is updated asynchronously.

type PostgresqlStatusList

type PostgresqlStatusList struct {
	Items []PostgresqlStatus `json:"items"`
}

PostgresqlStatusList is a list of PostgreSQL status received from the Pods that can be sorted considering the replication status

func (PostgresqlStatusList) AllReadyInstancesStatusUnreachable added in v1.18.5

func (list PostgresqlStatusList) AllReadyInstancesStatusUnreachable() bool

AllReadyInstancesStatusUnreachable returns true if all the ready instances are unreachable from the operator via HTTP request.

func (PostgresqlStatusList) ArePodsUpgradingInstanceManager

func (list PostgresqlStatusList) ArePodsUpgradingInstanceManager() bool

ArePodsUpgradingInstanceManager checks if there are pods on which we are upgrading the instance manager

func (PostgresqlStatusList) ArePodsWaitingForDecreasedSettings

func (list PostgresqlStatusList) ArePodsWaitingForDecreasedSettings() bool

ArePodsWaitingForDecreasedSettings checks if a rollout due to hot standby sensible parameters being decreased is ongoing

func (PostgresqlStatusList) AreWalReceiversDown

func (list PostgresqlStatusList) AreWalReceiversDown(primaryName string) bool

AreWalReceiversDown checks if every WAL receiver of the cluster is down ignoring the status of the primary, that does not matter during a switchover or a failover

func (*PostgresqlStatusList) GetNames added in v1.18.4

func (list *PostgresqlStatusList) GetNames() []string

GetNames returns a list of names of Pods

func (PostgresqlStatusList) InstancesReportingStatus added in v1.16.0

func (list PostgresqlStatusList) InstancesReportingStatus() int

InstancesReportingStatus returns the number of instances that are Ready or MightBeUnavailable

func (PostgresqlStatusList) IsComplete

func (list PostgresqlStatusList) IsComplete() bool

IsComplete checks the PostgreSQL status list for Pods which contain errors. Returns true if everything is green and false otherwise

func (PostgresqlStatusList) IsPodReporting

func (list PostgresqlStatusList) IsPodReporting(podname string) bool

IsPodReporting if a pod is ready

func (*PostgresqlStatusList) Len

func (list *PostgresqlStatusList) Len() int

Len implements sort.Interface extracting the length of the list

func (*PostgresqlStatusList) Less

func (list *PostgresqlStatusList) Less(i, j int) bool

Less compares two elements. Primary instances always go first, ordered by their Pod name (split brain?), and secondaries always go by their replication status with the more updated one coming as first

func (*PostgresqlStatusList) LogStatus added in v1.15.2

func (list *PostgresqlStatusList) LogStatus(ctx context.Context)

LogStatus logs the current status of the instances

func (PostgresqlStatusList) ReportingMightBeUnavailable added in v1.16.0

func (list PostgresqlStatusList) ReportingMightBeUnavailable(instance string) bool

ReportingMightBeUnavailable checks whether the given instance might be unavailable

func (*PostgresqlStatusList) Swap

func (list *PostgresqlStatusList) Swap(i, j int)

Swap swaps two elements, implements sort.Interface

type Segment

type Segment struct {
	// Timeline number
	Tli int32

	// Log number
	Log int32

	// Segment number
	Seg int32
}

Segment contains the information inside a WAL segment name

func MustSegmentFromName

func MustSegmentFromName(name string) Segment

MustSegmentFromName is analogous to SegmentFromName but panics if the segment name is invalid

func SegmentFromName

func SegmentFromName(name string) (Segment, error)

SegmentFromName retrieves the timeline, log ID and segment ID from the name of a xlog segment, and can also handle a full path or a simple file name

func (Segment) Name

func (segment Segment) Name() string

Name gets the name of the segment

func (Segment) NextSegments

func (segment Segment) NextSegments(size int, postgresVersion *int, segmentSize *int64) []Segment

NextSegments generate the list of all possible segment names starting from `segment`, until the specified size is reached. This function will not ever generate timeline changes. If postgresVersion == nil, the latest postgres version is assumed. If segmentSize == nil, wal_segment_size=DefaultWALSegmentSize is assumed.

type SettingsCollection

type SettingsCollection = map[string]string

SettingsCollection is a collection of PostgreSQL settings

type WalLevelValue added in v1.21.4

type WalLevelValue string

WalLevelValue a value that is assigned to the 'wal_level' configuration field

const (
	WalLevelValueLogical WalLevelValue = "logical"
	WalLevelValueReplica WalLevelValue = "replica"
	WalLevelValueMinimal WalLevelValue = "minimal"
)

An acceptable wal_level value

func (WalLevelValue) IsKnownValue added in v1.21.4

func (w WalLevelValue) IsKnownValue() bool

IsKnownValue returns a bool indicating if the contained value is a well-know value

func (WalLevelValue) IsStricterThanMinimal added in v1.21.4

func (w WalLevelValue) IsStricterThanMinimal() bool

IsStricterThanMinimal returns a boolean indicating if the contained value is stricter than the minimal wal_level

Jump to

Keyboard shortcuts

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