Documentation ¶
Overview ¶
Package postgres contains the function about starting up, shutting down and managing a PostgreSQL instance. These functions are primarily used by the instance manager
Index ¶
- Constants
- Variables
- func ClonePgData(connectionString, targetPgData, walDir string) error
- func GetEnforcedParametersThroughPgControldata(pgData string) (map[string]string, error)
- func GetReadyWALFiles() (fileNames []string, err error)
- func GetServerPort() int
- func GetSocketDir() string
- func GetWALArchiveCounters() (ready, done int, err error)
- func InstallPgDataFileContent(pgdata, contents, destinationFile string) (bool, error)
- func PatchBackupStatusAndRetry(ctx context.Context, cli client.Client, backup *apiv1.Backup) error
- func PgIsReady() error
- func UpdateReplicaConfiguration(pgData, primaryConnInfo, slotName string) (changed bool, err error)
- func WritePostgresUserMaps(pgData string) error
- type BackupCommand
- type InitInfo
- func (info InitInfo) Bootstrap(ctx context.Context) error
- func (info InitInfo) ConfigureInstanceAfterRestore(cluster *apiv1.Cluster, env []string) error
- func (info InitInfo) ConfigureNewInstance(instance *Instance) error
- func (info InitInfo) CreateDataDirectory() error
- func (info InitInfo) GetInstance() *Instance
- func (info InitInfo) GetPrimaryConnInfo() string
- func (info InitInfo) Join(cluster *apiv1.Cluster) error
- func (info InitInfo) Restore(ctx context.Context) error
- func (info InitInfo) VerifyPGData() error
- func (info InitInfo) WriteInitialPostgresqlConf(cluster *apiv1.Cluster) error
- func (info InitInfo) WriteRestoreHbaConf() error
- type Instance
- func (instance *Instance) CanCheckReadiness() bool
- func (instance *Instance) CheckForExistingPostmaster(postgresExecutables ...string) (*os.Process, error)
- func (instance *Instance) CleanUpStalePid() error
- func (instance *Instance) CompleteCrashRecovery() error
- func (instance *Instance) ConfigureSlotReplicator(config *apiv1.ReplicationSlotsConfiguration)
- func (instance *Instance) ConnectionPool() *pool.ConnectionPool
- func (instance *Instance) Demote(ctx context.Context, cluster *apiv1.Cluster) error
- func (instance *Instance) DropConnections() error
- func (instance *Instance) GeneratePostgresqlHBA(cluster *apiv1.Cluster, ldapBindPassword string) (string, error)
- func (instance *Instance) GetDecreasedSensibleSettings(superUserDB *sql.DB) (map[string]string, error)
- func (instance *Instance) GetInstanceCommandChan() <-chan InstanceCommand
- func (instance *Instance) GetPgVersion() (semver.Version, error)
- func (instance *Instance) GetPostmasterPidFromFile(pidFile string) ([]byte, int, error)
- func (instance *Instance) GetPrimaryConnInfo() string
- func (instance *Instance) GetSmartShutdownTimeout() int32
- func (instance *Instance) GetStatus() (result *postgres.PostgresqlStatus, err error)
- func (instance *Instance) GetSuperUserDB() (*sql.DB, error)
- func (instance *Instance) GetTemplateDB() (*sql.DB, error)
- func (instance *Instance) HandleInstanceCommandRequests(ctx context.Context, req InstanceCommand) (restartNeeded bool, err error)
- func (instance *Instance) IsFenced() bool
- func (instance *Instance) IsPrimary() (bool, error)
- func (instance *Instance) IsServerHealthy() error
- func (instance *Instance) IsServerReady() error
- func (instance *Instance) IsWALReceiverActive() (bool, error)
- func (instance *Instance) LogPgControldata(ctx context.Context, reason string)
- func (instance *Instance) MightBeUnavailable() bool
- func (instance *Instance) PrimaryConnectionPool() *pool.ConnectionPool
- func (instance *Instance) PromoteAndWait(ctx context.Context) error
- func (instance *Instance) RefreshConfigurationFilesFromCluster(cluster *apiv1.Cluster, preserveUserSettings bool) (bool, error)
- func (instance *Instance) RefreshPGHBA(cluster *apiv1.Cluster, ldapBindPassword string) (postgresHBAChanged bool, err error)
- func (instance *Instance) RefreshReplicaConfiguration(ctx context.Context, cluster *apiv1.Cluster, cli client.Client) (changed bool, err error)
- func (instance *Instance) Reload(ctx context.Context) error
- func (instance *Instance) RequestAndWaitFencingOff() error
- func (instance *Instance) RequestAndWaitRestartSmartFast() error
- func (instance *Instance) RequestFastImmediateShutdown()
- func (instance *Instance) RequestFencingOn()
- func (instance *Instance) Rewind(ctx context.Context, postgresMajorVersion int) error
- func (instance *Instance) Run() (*execlog.StreamingCmd, error)
- func (instance *Instance) SetCanCheckReadiness(enabled bool)
- func (instance *Instance) SetFencing(enabled bool)
- func (instance *Instance) SetMightBeUnavailable(enabled bool)
- func (instance *Instance) Shutdown(options shutdownOptions) error
- func (instance *Instance) ShutdownConnections()
- func (instance *Instance) SlotReplicatorChan() <-chan *apiv1.ReplicationSlotsConfiguration
- func (instance *Instance) Startup() error
- func (instance *Instance) TryGetPgStatWAL() (*PgStatWal, error)
- func (instance *Instance) TryShuttingDownFastImmediate(ctx context.Context) error
- func (instance *Instance) TryShuttingDownSmartFast(ctx context.Context) error
- func (instance *Instance) WaitForConfigReload() (*postgres.PostgresqlStatus, error)
- func (instance *Instance) WaitForPrimaryAvailable() error
- func (instance *Instance) WaitForSuperuserConnectionAvailable() error
- func (instance *Instance) WithActiveInstance(inner func() error) error
- type InstanceCommand
- type PgStatWal
Constants ¶
const PostgresqlPidFile = "postmaster.pid" //wokeignore:rule=master
PostgresqlPidFile is the name of the file which contains the PostgreSQL PID file
Variables ¶
var ( // ErrPgRejectingConnection postgres is alive, but rejecting connections ErrPgRejectingConnection = fmt.Errorf("server is alive but rejecting connections") // ErrNoConnectionEstablished postgres is alive, but rejecting connections ErrNoConnectionEstablished = fmt.Errorf("could not establish connection") )
var ( // ErrInstanceInRecovery is raised while PostgreSQL is still in recovery mode ErrInstanceInRecovery = fmt.Errorf("instance in recovery") // RetryUntilRecoveryDone is the default retry configuration that is used // to wait for a restored cluster to promote itself RetryUntilRecoveryDone = wait.Backoff{ Duration: 5 * time.Second, Steps: math.MaxInt32, } )
var RetryUntilServerAvailable = wait.Backoff{ Duration: 5 * time.Second, Steps: math.MaxInt32, }
RetryUntilServerAvailable is the default retry configuration that is used to wait for a successful connection to a certain server
Functions ¶
func ClonePgData ¶
ClonePgData clones an existing server, given its connection string, to a certain data directory
func GetEnforcedParametersThroughPgControldata ¶
GetEnforcedParametersThroughPgControldata will parse the output of pg_controldata in order to get the values of all the hot standby sensible parameters
func GetReadyWALFiles ¶
GetReadyWALFiles returns an array containing the list of all the WAL files that are marked as ready to be archived.
func GetServerPort ¶
func GetServerPort() int
GetServerPort gets the port where the postmaster will be listening using the environment variable or, when empty, the default one
func GetSocketDir ¶
func GetSocketDir() string
GetSocketDir gets the name of the directory that will contain the Unix socket for the PostgreSQL server. This is detected using the PGHOST environment variable or using a default
func GetWALArchiveCounters ¶
GetWALArchiveCounters returns the number of WAL files with status ready, and the number of those in status done.
func InstallPgDataFileContent ¶
InstallPgDataFileContent installs a file in PgData, returning true/false if the file has been changed and an error state
func PatchBackupStatusAndRetry ¶ added in v1.18.3
func PatchBackupStatusAndRetry( ctx context.Context, cli client.Client, backup *apiv1.Backup, ) error
PatchBackupStatusAndRetry updates a certain backup's status in the k8s database, retries when error occurs
func PgIsReady ¶ added in v1.16.4
func PgIsReady() error
PgIsReady gets the status from the pg_isready command
func UpdateReplicaConfiguration ¶
UpdateReplicaConfiguration updates the override.conf or recovery.conf file for the proper version of PostgreSQL, using the specified connection string to connect to the primary server
func WritePostgresUserMaps ¶
WritePostgresUserMaps creates a pg_ident.conf file containing only one map called "local" that maps the current user to "postgres" user.
Types ¶
type BackupCommand ¶
type BackupCommand struct { Cluster *apiv1.Cluster Backup *apiv1.Backup Client client.Client Recorder record.EventRecorder Env []string Log log.Logger Instance *Instance Capabilities *barmanCapabilities.Capabilities }
BackupCommand represent a backup command that is being executed
func NewBackupCommand ¶
func NewBackupCommand( cluster *apiv1.Cluster, backup *apiv1.Backup, client client.Client, recorder record.EventRecorder, instance *Instance, log log.Logger, ) (*BackupCommand, error)
NewBackupCommand initializes a BackupCommand object
type InitInfo ¶
type InitInfo struct { // The data directory where to generate the new cluster PgData string // the data directory where to store the WAL PgWal string // The name of the database to be generated for the applications ApplicationDatabase string // The name of the role to be generated for the applications ApplicationUser string // The parent node, used to fill primary_conninfo ParentNode string // The current node, used to fill application_name PodName string // The cluster name to assign to ClusterName string // The namespace where the cluster will be installed Namespace string // The list options that should be passed to initdb to // create the cluster InitDBOptions []string // The list of queries to be executed just after having // configured a new instance PostInitSQL []string // The list of queries to be executed just after having // the application database created PostInitApplicationSQL []string // The list of queries to be executed inside the template1 // database just after having configured a new instance PostInitTemplateSQL []string // Whether it is a temporary instance that will never contain real data. Temporary bool // PostInitApplicationSQLRefsFolder is the folder which contains a bunch // of SQL files to be executed just after having configured a new instance PostInitApplicationSQLRefsFolder string }
InitInfo contains all the info needed to bootstrap a new PostgreSQL instance
func (InitInfo) ConfigureInstanceAfterRestore ¶
ConfigureInstanceAfterRestore changes the superuser password of the instance to be coherent with the one specified in the cluster. This function also ensures that we can really connect to this cluster using the password in the secrets
func (InitInfo) ConfigureNewInstance ¶
ConfigureNewInstance creates the expected users and databases in a new PostgreSQL instance. If any error occurs, we return it
func (InitInfo) CreateDataDirectory ¶
CreateDataDirectory creates a new data directory given the configuration
func (InitInfo) GetInstance ¶
GetInstance gets the PostgreSQL instance which correspond to these init information
func (InitInfo) GetPrimaryConnInfo ¶ added in v1.18.0
GetPrimaryConnInfo returns the DSN to reach the primary
func (InitInfo) Restore ¶
Restore restores a PostgreSQL cluster from a backup into the object storage
func (InitInfo) VerifyPGData ¶
VerifyPGData verifies if the passed configuration is OK, otherwise it returns an error
func (InitInfo) WriteInitialPostgresqlConf ¶
WriteInitialPostgresqlConf resets the postgresql.conf that there is in the instance using a new bootstrapped instance as reference
func (InitInfo) WriteRestoreHbaConf ¶
WriteRestoreHbaConf writes a pg_hba.conf allowing access without password from localhost. this is needed to set the PostgreSQL password after the postgres server is started and active
type Instance ¶
type Instance struct { // The data directory PgData string // The socket directory SocketDirectory string // The environment variables that will be used to start the instance Env []string // Command line options to pass to the postgres process, see the // '-c' option of pg_ctl for an useful example StartupOptions []string // The namespace of the k8s object representing this cluster Namespace string // The name of the Pod where the controller is executing PodName string // The name of the cluster of which this Pod is belonging ClusterName string // The sha256 of the config. It is computed on the config string, before // adding the PostgreSQL CNPGConfigSha256 parameter ConfigSha256 string // PgCtlTimeoutForPromotion specifies the maximum number of seconds to wait when waiting for promotion to complete PgCtlTimeoutForPromotion int32 // specifies the maximum number of seconds to wait when shutting down for a switchover MaxSwitchoverDelay int32 // InstanceManagerIsUpgrading tells if there is an instance manager upgrade in process InstanceManagerIsUpgrading atomic.Bool // PgRewindIsRunning tells if there is a `pg_rewind` process running PgRewindIsRunning bool // MaxStopDelay is the current MaxStopDelay of the cluster MaxStopDelay int32 // SmartStopDelay is used to control PostgreSQL smart shutdown timeout SmartStopDelay int32 // contains filtered or unexported fields }
Instance represent a PostgreSQL instance to be executed in the current environment
func NewInstance ¶
func NewInstance() *Instance
NewInstance creates a new Instance object setting the defaults
func (*Instance) CanCheckReadiness ¶
CanCheckReadiness checks whether the instance should be checked for readiness
func (*Instance) CheckForExistingPostmaster ¶
func (instance *Instance) CheckForExistingPostmaster(postgresExecutables ...string) (*os.Process, error)
CheckForExistingPostmaster checks if a postmaster process is running on the PGDATA volume. If it is, it returns its process entry.
To do that, this function will read the PID file from the data directory and check the existence of the relative process. If the process exists, then that process entry is returned. If it doesn't exist then the PID file is stale and is removed.
We are requiring a list of PostgreSQL executables that is used to check if the process with the ID read from the PID file is really a postmaster. This isn't really needed per se, but allows this function to be easier to test.
func (*Instance) CleanUpStalePid ¶
CleanUpStalePid cleans up the files left around by a crashed PostgreSQL instance. It removes the default PostgreSQL pid file and the content of the socket directory.
func (*Instance) CompleteCrashRecovery ¶
CompleteCrashRecovery temporary starts up the server and wait for it to be fully available for queries. This will ensure that the crash recovery is fully done. Important: this function must be called only when the instance isn't started
func (*Instance) ConfigureSlotReplicator ¶ added in v1.18.0
func (instance *Instance) ConfigureSlotReplicator(config *apiv1.ReplicationSlotsConfiguration)
ConfigureSlotReplicator sends the configuration to the slot replicator
func (*Instance) ConnectionPool ¶
func (instance *Instance) ConnectionPool() *pool.ConnectionPool
ConnectionPool gets or initializes the connection pool for this instance
func (*Instance) DropConnections ¶ added in v1.15.5
DropConnections drops all the connections of backend_type 'client backend'
func (*Instance) GeneratePostgresqlHBA ¶
func (instance *Instance) GeneratePostgresqlHBA(cluster *apiv1.Cluster, ldapBindPassword string) (string, error)
GeneratePostgresqlHBA generates the pg_hba.conf content with the LDAP configuration if configured.
func (*Instance) GetDecreasedSensibleSettings ¶
func (instance *Instance) GetDecreasedSensibleSettings(superUserDB *sql.DB) (map[string]string, error)
GetDecreasedSensibleSettings tries to get all decreased hot standby sensible parameters from the instance. Returns a map containing all the decreased hot standby sensible parameters with their new value. See https://www.postgresql.org/docs/current/hot-standby.html#HOT-STANDBY-ADMIN for more details.
func (*Instance) GetInstanceCommandChan ¶
func (instance *Instance) GetInstanceCommandChan() <-chan InstanceCommand
GetInstanceCommandChan is the channel where the lifecycle manager will wait for the operations requested on the instance
func (*Instance) GetPgVersion ¶
GetPgVersion queries the postgres instance to know the current version, parses it and memoize it for future uses
func (*Instance) GetPostmasterPidFromFile ¶ added in v1.15.1
GetPostmasterPidFromFile reads the given postmaster pid file, parse it and return its content and the actual pid
func (*Instance) GetPrimaryConnInfo ¶ added in v1.18.0
GetPrimaryConnInfo returns the DSN to reach the primary
func (*Instance) GetSmartShutdownTimeout ¶ added in v1.19.5
GetSmartShutdownTimeout gets the duration in seconds as the timeout of smart shutdown we calculate smart shutdown with following formula max(stopDelay - smartStopDelay, 30)
func (*Instance) GetStatus ¶
func (instance *Instance) GetStatus() (result *postgres.PostgresqlStatus, err error)
GetStatus Extract the status of this PostgreSQL database
func (*Instance) GetSuperUserDB ¶
GetSuperUserDB gets a connection to the "postgres" database on this instance
func (*Instance) GetTemplateDB ¶
GetTemplateDB gets a connection to the "template1" database on this instance
func (*Instance) HandleInstanceCommandRequests ¶ added in v1.19.5
func (instance *Instance) HandleInstanceCommandRequests( ctx context.Context, req InstanceCommand, ) (restartNeeded bool, err error)
HandleInstanceCommandRequests execute a command requested by the reconciliation loop.
func (*Instance) IsPrimary ¶
IsPrimary check if the data directory belongs to a primary server or to a secondary one by looking for a "standby.signal" file inside the data directory. IMPORTANT: this method also works when the instance is not started up
func (*Instance) IsServerHealthy ¶
IsServerHealthy check if the instance is healthy
func (*Instance) IsServerReady ¶
IsServerReady check if the instance is healthy and can really accept connections
func (*Instance) IsWALReceiverActive ¶
IsWALReceiverActive check if the WAL receiver process is active by looking at the number of records in the `pg_stat_wal_receiver` table
func (*Instance) LogPgControldata ¶
LogPgControldata logs the content of PostgreSQL control data, for debugging and tracing
func (*Instance) MightBeUnavailable ¶
MightBeUnavailable checks whether we expect the instance to be down
func (*Instance) PrimaryConnectionPool ¶ added in v1.18.0
func (instance *Instance) PrimaryConnectionPool() *pool.ConnectionPool
PrimaryConnectionPool gets or initializes the primary connection pool for this instance
func (*Instance) PromoteAndWait ¶
PromoteAndWait promotes this instance, and wait DefaultPgCtlTimeoutForPromotion seconds for it to happen
func (*Instance) RefreshConfigurationFilesFromCluster ¶
func (instance *Instance) RefreshConfigurationFilesFromCluster( cluster *apiv1.Cluster, preserveUserSettings bool, ) (bool, error)
RefreshConfigurationFilesFromCluster receives a cluster object, then generates the PostgreSQL configuration and rewrites the file in the PGDATA if needed. This function will return "true" if the configuration has been really changed.
func (*Instance) RefreshPGHBA ¶
func (instance *Instance) RefreshPGHBA(cluster *apiv1.Cluster, ldapBindPassword string) ( postgresHBAChanged bool, err error, )
RefreshPGHBA generates and writes down the pg_hba.conf file
func (*Instance) RefreshReplicaConfiguration ¶ added in v1.19.4
func (instance *Instance) RefreshReplicaConfiguration( ctx context.Context, cluster *apiv1.Cluster, cli client.Client, ) (changed bool, err error)
RefreshReplicaConfiguration writes the PostgreSQL correct replication configuration for connecting to the right primary server, depending on the cluster replica mode
func (*Instance) RequestAndWaitFencingOff ¶
RequestAndWaitFencingOff will request to remove the fencing and wait for the instance to be restarted
func (*Instance) RequestAndWaitRestartSmartFast ¶
RequestAndWaitRestartSmartFast requests the lifecycle manager to restart the postmaster, and wait for the postmaster to be restarted
func (*Instance) RequestFastImmediateShutdown ¶
func (instance *Instance) RequestFastImmediateShutdown()
RequestFastImmediateShutdown request the lifecycle manager to shut down PostgreSQL using the fast strategy and then the immediate strategy.
func (*Instance) RequestFencingOn ¶
func (instance *Instance) RequestFencingOn()
RequestFencingOn request the lifecycle manager to shut down postgres and enable fencing
func (*Instance) Rewind ¶
Rewind uses pg_rewind to align this data directory with the contents of the primary node. If postgres major version is >= 13, add "--restore-target-wal" option
func (*Instance) Run ¶
func (instance *Instance) Run() (*execlog.StreamingCmd, error)
Run this instance returning an OS process needed to control the instance execution
func (*Instance) SetCanCheckReadiness ¶
SetCanCheckReadiness marks whether the instance should be checked for readiness
func (*Instance) SetFencing ¶
SetFencing marks whether the instance is fenced, if enabling, marks also any down to be tolerated
func (*Instance) SetMightBeUnavailable ¶
SetMightBeUnavailable marks whether the instance being down should be tolerated
func (*Instance) Shutdown ¶
Shutdown shuts down a PostgreSQL instance which was previously started with Startup. This function will return an error whether PostgreSQL is still up after the shutdown request.
func (*Instance) ShutdownConnections ¶
func (instance *Instance) ShutdownConnections()
ShutdownConnections tears down database connections
func (*Instance) SlotReplicatorChan ¶ added in v1.18.0
func (instance *Instance) SlotReplicatorChan() <-chan *apiv1.ReplicationSlotsConfiguration
SlotReplicatorChan returns the communication channel to the slot replicator
func (*Instance) Startup ¶
Startup starts up a PostgreSQL instance and wait for the instance to be started
func (*Instance) TryGetPgStatWAL ¶ added in v1.15.1
TryGetPgStatWAL retrieves pg_wal_stat on pg version 14 and further
func (*Instance) TryShuttingDownFastImmediate ¶ added in v1.19.5
TryShuttingDownFastImmediate first tries to shut down the instance with mode fast, then in case of failure or the given timeout expiration, it will issue an immediate shutdown request and wait for it to complete. N.B. immediate shutdown can cause data loss.
func (*Instance) TryShuttingDownSmartFast ¶ added in v1.19.5
TryShuttingDownSmartFast first tries to shut down the instance with mode smart, then in case of failure or the given timeout expiration, it will issue a fast shutdown request and wait for it to complete.
func (*Instance) WaitForConfigReload ¶ added in v1.19.4
func (instance *Instance) WaitForConfigReload() (*postgres.PostgresqlStatus, error)
WaitForConfigReload returns the postgresqlStatus and any error encountered
func (*Instance) WaitForPrimaryAvailable ¶
WaitForPrimaryAvailable waits until we can connect to the primary
func (*Instance) WaitForSuperuserConnectionAvailable ¶
WaitForSuperuserConnectionAvailable waits until we can connect to this instance using the superuser account
func (*Instance) WithActiveInstance ¶
WithActiveInstance execute the internal function while this PostgreSQL instance is running
type InstanceCommand ¶
type InstanceCommand string
InstanceCommand are commands for the goroutine managing postgres
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package constants provides the needed constants in the postgres package
|
Package constants provides the needed constants in the postgres package |
Package logicalimport contains the logic needed to import a logical snapshot
|
Package logicalimport contains the logic needed to import a logical snapshot |
Package logpipe implements reading csv logs from PostgreSQL logging_collector (https://www.postgresql.org/docs/current/runtime-config-logging.html) and convert them to JSON.
|
Package logpipe implements reading csv logs from PostgreSQL logging_collector (https://www.postgresql.org/docs/current/runtime-config-logging.html) and convert them to JSON. |
Package metrics enables to expose a set of metrics and collectors on a given postgres instance
|
Package metrics enables to expose a set of metrics and collectors on a given postgres instance |
histogram
Package histogram contain histogram-metrics related functions
|
Package histogram contain histogram-metrics related functions |
Package pool contain an implementation of a connection pool to multiple database pointing to the same instance
|
Package pool contain an implementation of a connection pool to multiple database pointing to the same instance |
Package utils holds generic utils about postgres instances
|
Package utils holds generic utils about postgres instances |
Package webserver contains the web server powering probes, backups and metrics
|
Package webserver contains the web server powering probes, backups and metrics |
metricserver
Package metricserver contains the web server powering metrics
|
Package metricserver contains the web server powering metrics |