Last modified: Mon Aug 24 18:19:17 JST 2015
pgpool-II is a middle ware that sits between PostgreSQL servers and a PostgreSQL database client. It provides the following features:
pgpool-II maintains established connections to the PostgreSQL servers, and reuses them whenever a new connection with the same properties (i.e. user name, database, protocol version) comes in. It reduces the connection overhead, and improves system's overall throughput.
pgpool-II can manage multiple PostgreSQL servers. Activating the replication feature makes it possible to create a real time backup on 2 or more PostgreSQL clusters, so that the service can continue without interruption if one of those clusters fails.
If a database is replicated(because running in either replication mode or master/slave mode), performing a SELECT query on any server will return the same result. pgpool-II takes advantage of the replication feature in order to reduce the load on each PostgreSQL server. It does that by distributing SELECT queries among available servers, improving the system's overall throughput. In an ideal scenario, read performance could improve proportionally to the number of PostgreSQL servers. Load balancing works best in a scenario where there are a lot of users executing many read-only queries at the same time.
There is a limit on the maximum number of concurrent connections with PostgreSQL, and new connections are rejected when this number is reached. Raising this maximum number of connections, however, increases resource consumption and has a negative impact on overall system performance. pgpool-II also has a limit on the maximum number of connections, but extra connections will be queued instead of returning an error immediately.
pgpool-II speaks PostgreSQL's backend and frontend protocol, and relays messages between a backend and a frontend. Therefore, a database application (frontend) thinks that pgpool-II is the actual PostgreSQL server, and the server (backend) sees pgpool-II as one of its clients. Because pgpool-II is transparent to both the server and the client, an existing database application can be used with pgpool-II almost without a change to its source code.
There are some restrictions to using SQL via pgpool-II. See Restrictions for more details.
Copyright (c) 2003-2015 PgPool Global Development Group
Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.
pgpool-II works on Linux, Solaris, FreeBSD, and most of the UNIX-like architectures. Windows is not supported. Supported PostgreSQL server's versions are 6.4 and higher.
If you are using PostgreSQL 7.3 or older, some features of pgpool-II won't be available. But you shouldn't use such an old release anyway.
You must also make sure that all of your PostgreSQL servers are using the same major PostgreSQL version. In addition to this, we do not recommend mixing different PostgreSQL installation with different build options: including supporting SSL or not, to use --disable-integer-datetimes or not, different block size. These might affect part of functionality of pgpool-II. The difference of PostgreSQL minor versions is not usually a problem. However we do not test every occurrence of minor versions and we recommend to use exact same minor version of PostgreSQL.
pgpool-II can be downloaded from the pgpool Development page. Packages are also provided for various platforms including CentOS, RedHat Enterprise Linux, Fedora and Debian. Check appropriate repository.
pgpool-II's source code can be downloaded from: pgpool development page
Installing pgpool-II from source code requires gcc 2.9 or higher, and GNU make. Also, pgpool-II links with the libpq library, so the libpq library and its development headers must be installed on the machine used to build pgpool-II. Additionally the OpenSSL library and its development headers must be present in order to enable OpenSSL support in pgpool-II.
After extracting the source tarball, execute the configure script.
./configure
If you want non-default values, some options can be set:
--prefix=path |
pgpool-II binaries and docs will be installed in this
directory. Default value is /usr/local |
---|---|
--with-pgsql=path |
The top directory where PostgreSQL's client libraries are
installed. Default value is provided by pg_config |
--with-openssl |
pgpool-II binaries will be built with OpenSSL support. OpenSSL support is disabled by default. V2.3 - |
--enable-sequence-lock |
Use insert_lock compatible with pgpool-II 3.0 series(until 3.0.4). pgpool-II locks against a row in the sequence table. PostgreSQL 8.2 or later which was released after June 2011 cannot use this lock method. V3.1 - |
--enable-table-lock |
Use insert_lock compatible with pgpool-II 2.2 and 2.3 series. pgpool-II locks against the insert target table. This lock method is deprecated because it causes a lock conflict with VACUUM. V3.1 - |
--with-memcached=path |
pgpool-II binaries will use memcached for in memory query cache. You have to install libmemcached. V3.2 - |
make make install
will install pgpool-II. (If you use Solaris or FreeBSD, replace make with gmake)
If you are using PostgreSQL 8.0 or later, installing pgpool_regclass function on all PostgreSQL to be accessed by pgpool-II is strongly recommended, as it is used internally by pgpool-II. Without this, handling of duplicate table names in different schema might cause trouble (temporary tables aren't a problem).
$ cd pgpool-II-x.x.x/sql/pgpool-regclass $ make $ make install
After this:
$ psql -f pgpool-regclass.sql template1
or
$ psql template1 =# CREATE EXTENSION pgpool_regclass;
Executing pgpool-regclass.sql or CREATE EXTENSION
should be performed on every databases accessed
with pgpool-II.
You do not need to do this for a database created after the
execution of "psql -f pgpool-regclass.sql template1
" or CREATE EXTENSION
,
as this template database will be cloned to create new databases.
If you use insert_lock in replication mode, creating pgpool_catalog.insert_lock table for mutual exclusion is strongly recommended. Without this, insert_lock works so far. However in that case pgpool-II locks against the insert target table. This behavior is same as pgpool-II 2.2 and 2.3 series. The table lock conflicts with VACUUM. So INSERT processing may be thereby kept waiting for a long time.
$ cd pgpool-II-x.x.x/sql $ psql -f insert_lock.sql template1
Executing insert_lock.sql should be performed on every databases accessed
with pgpool-II.
You do not need to do this for a database created after the execution of
"psql -f insert_lock.sql template1
", as this template database will be
cloned to create new databases.
If you use online recovery, some functions are needed: pgpool_recovery, pgpool_remote_start, pgpool_switch_xlog.
And, pgpoolAdmin of the tool to control pgpool-II can stop, restart and reload the backend PostgreSQL nodes, and it needs the function named pgpool_pgctl.
Also pgpoolAdmin needs function pgpool_pgctl to stop/restart/reload config PostgreSQL.
You can install those 4 functions in a same manner as pgpool_regclass. However, unlike pgpool_regclass, you only need to install those functions to template1 database.
Here is the way to install those functions.
$ cd pgpool-II-x.x.x/sql/pgpool-recovery $ make $ make install
After this:
$ psql -f pgpool-recovery.sql template1
or
$ psql template1 =# CREATE EXTENSION pgpool_recovery;
The function pgpool_pgctl executes the command whose path is specified by "pgpool.pg_ctl" in postgresql.conf. To use this function, you have to specify this parameter.
ex) $ cat >> /usr/local/pgsql/postgresql.conf pgpool.pg_ctl = '/usr/local/pgsql/bin/pg_ctl' $ pg_ctl reload -D /usr/local/pgsql/data
Default configuration files for pgpool-II are
/usr/local/etc/pgpool.conf
and
/usr/local/etc/pcp.conf
. Several operation modes are available
in pgpool-II. Each mode has associated features which
can be enabled or disabled, and specific configuration parameters to
control their behaviors.
Function/Mode | Raw Mode (*2) | Replication Mode | Master/Slave Mode |
---|---|---|---|
Connection Pool | X | O | O |
Replication | X | O | X |
Load Balance | X | O | O |
Failover | O | O | O |
Online recovery | X | 0 | (*1) |
Required # of Servers | 1 or higher | 2 or higher | 2 or higher |
pcp.conf
pgpool-II provides a control interface where an administrator
can collect pgpool-II status, and terminate pgpool-II processes remotely.
pcp.conf
is the user/password file used for
authentication by this interface. All operation modes require the
pcp.conf
file to be set. A $prefix/etc/pcp.conf.sample
file is created during the installation of pgpool-II. Rename the file to
pcp.conf
and add your user name and password to it.
cp $prefix/etc/pcp.conf.sample $prefix/etc/pcp.conf
An empty line or a line starting with "#
" is treated as a
comment and will be ignored. A user name and its associated password must be
written as one line using the following format:
username:[password encrypted in md5]
[password encrypted in md5]
can be produced with the
$prefix/bin/pg_md5
command.
pg_md5 -p password: <your password>
or
./pg_md5 foo acbd18db4cc2f85cedef654fccc4a4d8
The pcp.conf
file must be readable by the user who
executes pgpool-II.
pgpool.conf
As already explained, each operation mode has its specific
configuration parameters in pgpool.conf
. A
$prefix/etc/pgpool.conf.sample
file is created during the
installation of pgpool-II. Rename the file to
pgpool.conf
and edit its contents.
cp $prefix/etc/pgpool.conf.sample $prefix/etc/pgpool.conf
There are additional sample pgpool.conf for each mode. V2.3 -
Mode | sample file |
---|---|
replication mode | pgpool.conf.sample-replication |
master/slave mode(Slony-I) | pgpool.conf.sample-master-slave |
master/slave mode(Streaming replication) | pgpool.conf.sample-stream |
An empty line or a line starting with "#" is treated as a comment and will be ignored.
Specifies the hostname or IP address, on which pgpool-II will accept
TCP/IP connections. '*'
accepts
all incoming connections. ''
disables TCP/IP
connections. Default is 'localhost'
. Connections via UNIX
domain socket are always accepted.
This parameter can only be set at server start.
The port number used by pgpool-II to listen for connections. Default is 9999.
This parameter can only be set at server start.
The directory where the UNIX domain socket accepting connections for
pgpool-II will be created. Default is '/tmp'
. Be
aware that this socket might be deleted by a cron job. We recommend to
set this value to '/var/run'
or such directory.
This parameter can only be set at server start.
Specifies the hostname or IP address, on which pcp process will accept
TCP/IP connections. '*'
accepts
all incoming connections. ''
disables TCP/IP
connections. Default is '*'
. Connections via UNIX
domain socket are always accepted.
This parameter can only be set at server start.
The port number where PCP process accepts connections. Default is 9898.
This parameter can only be set at server start.
The directory path of the UNIX domain socket accepting
connections for the PCP process. Default is '/tmp'
.
Be aware that the socket might be deleted by cron.
We recommend to set this value to '/var/run'
or such directory.
This parameter can only be set at server start.
The number of preforked pgpool-II server processes. Default is 32. num_init_children is also the concurrent connections limit to pgpool-II from clients. If more than num_init_children clients try to connect to pgpool-II, they are blocked (not rejected) until a connection to any pgpool-II process is closed. Up to listen_backlog_multiplier*num_init_children can be queued.
The queued is inside the kernel called "listen queue". The length of the listen queue is called "backlog". There is an upper limit of the backlog in some systems, and if num_init_children*listen_backlog_multiplier exceeds the number, you need to set the backlong higher. Otherwise, following problems may occur in heavy loaded systems: 1) connecting to pgpool-II fails 2) connecting to pgpool-II is getting slow because of retries in the kernel. You can check if the listen queue is actually overflowed by using "netstat -s" command. If you find something like:
535 times the listen queue of a socket overflowed
then the listen queue is definitely overflowed. You should increase the backlog in this case (you will be required a super user privilege).
# sysctl net.core.somaxconn net.core.somaxconn = 128 # sysctl -w net.core.somaxconn = 256
You could add following to /etc/sysctl.conf instead.
net.core.somaxconn = 256
Number of connections to each PostgreSQL is roughly max_pool*num_init_children
Some hints in addition to above:
In summary, max_pool, num_init_children, max_connections, superuser_reserved_connections must satisfy the following formula:
max_pool*num_init_children <= (max_connections - superuser_reserved_connections) (no query canceling needed) max_pool*num_init_children*2 <= (max_connections - superuser_reserved_connections) (query canceling needed)
This parameter can only be set at server start.
Controls the length of connection queue from frontend to pgpool-II. The default is 2. The queue length (actually "backlog" parameter of listen system call) is defined as listen_backlog_multiplier * num_init_children. If the queue length is not long enough, you should increase the parameter. Some systems have upper limit of the backlog parameter of listen system call. See num_init_children for more details.
This parameter can only be set at server start.
Whether to serialize accept() call for incoming client connections. Default is off, which means no serializing (same behavior as pgpool-II 3.4 or before). If this is off, the kernel wakes up all of pgpool-II child process to execute accept() and one of them actually accepts the incoming connection. Problem here is, because so my child process wake up at a same time, heavy context switching occurred and the performance is affected. This phenomena is a classic problem called "the thundering herd problem". By enabling serialize_accept, only one of pgpool-II child process is woken up and executes accept() and the problem can be avoided. When you should turn on serialize_accept? For large number of num_init_children, it is recommended to turn on serialize_accept. For small number of num_init_children, it may not enhance the performance rather, it may degrade the performance because of serializing overhead. How large is actually large is depending on the environment. It is recommended to do a bench mark test to make the decision. Here is a example pgbench run:
pgbench -n -S -p 9999 -c 32 -C -S -T 300 test
Here, -C tells pgbench to connect to database each time a transaction gets executed. -c 32 specifies the concurrent sessions to pgpool-II. You should change this according to your system's requirement. When pgbench finishes, you want to check the number from "including connections establishing".
Please note that if child_life_time is enabled, serialize_accept has no effect. Make sure that you set child_life_time to 0 if you want to turn on serialize_accept. If you are care about pgpool-II process memory leak or whatever potential issue, you could use child_max_connections instead. This is purely an implementation limitation and maybe removed in the future.
This parameter can only be set at server start.
A pgpool-II child process' life time in seconds. When a child is idle for that many seconds, it is terminated and a new child is created. This parameter is a measure to prevent memory leaks and other unexpected errors. Default value is 300 (5 minutes). 0 disables this feature. Note that this doesn't apply for processes that have not accepted any connection yet.
Note: if this parameter is non 0, serialize_accept has no effect.
You need to reload pgpool.conf if you change this value.
A pgpool-II child process will be terminated after this many connections from clients. This parameter is useful on a server if it is so busy that child_life_time and connection_life_time are never triggered. Thus this is also useful to prevent PostgreSQL servers from getting too big.
You need to reload pgpool.conf if you change this value.
Disconnect a client if it has been idle for client_idle_limit seconds after the last query has completed. This is useful to prevent pgpool childs from being occupied by a lazy client or a broken TCP/IP connection between client and pgpool. The default value for client_idle_limit is 0, which means the feature is turned off. this value. This parameter is ignored in the second stage of online recovery.
You need to reload pgpool.conf if you change client_idle_limit.
If true, use pool_hba.conf for client authentication. See setting up pool_hba.conf for client authentication.
You need to reload pgpool.conf if you change this value.
Specify the file name of pool_passwd for md5 authentication. Default value is "pool_passwd". "" disables to read pool_passwd. See Authentication / Access Controls for more details.
You need to restart pgpool-II if you change this value.
Specify the timeout for pgpool authentication. 0 disables the time out. Default value is 60.
You need to reload pgpool.conf if you change this value.
PgPool II supports several methods for logging server messages, including stderr and syslog. The default is to log to stderr.
Note: you will need to alter the configuration of your system's syslog daemon in order to make use of the syslog option for log_destination. PgPool can log to syslog facilities LOCAL0 through LOCAL7 (see syslog_facility), but the default syslog configuration on most platforms will discard all such messages. You will need to add something like
local0.* /var/log/pgpool.log
to the syslog daemon's configuration file to make it work.
Add timestamps to the logs when set to true. Default is true.
You need to reload pgpool.conf if you change print_timestamp.
Add session user names to the logs when set to true. Default is false.
You need to reload pgpool.conf if you change print_user.
This is a printf-style string that is output at the beginning of each log line. % characters begin "escape sequences" that are replaced with information outlined below. All unrecognized escapes are ignored. Other characters are copied straight to the log line. Default is '%t: pid %p: ', which prints timestamp and process id, which keeps backward compatibily with pre-3.4.
Escape | Effect |
---|---|
%a | Client application name. |
%p | Process ID (PID). |
%P | Process name. |
%t | Time stamp. |
%d | Database name. |
%u | User name. |
%l | Log line number for each process. |
%% | '%' character |
You need to reload pgpool.conf if you change log_line_prefix
Controls the amount of detail emitted for each message that is logged. Valid values are TERSE, DEFAULT, and VERBOSE, each adding more fields to displayed messages. TERSE excludes the logging of DETAIL, HINT, and CONTEXT error information.
You need to reload pgpool.conf if you change this value.
If true, all incoming connections will be printed to the log.
You need to reload pgpool.conf if you change this value.
Controls which minimum message levels are sent to the client. Valid values are DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1, LOG, NOTICE, WARNING and ERROR. Each level includes all the levels that follow it. The default is NOTICE.
You need to reload pgpool.conf if you change this value.
Controls which minimum message levels are emitted to log. Valid values are DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1, INFO, NOTICE, WARNING, ERROR, LOG, FATAL, and PANIC. Each level includes all the levels that follow it. The default is WARNING.
You need to reload pgpool.conf if you change this value.
If true, ps command status will show the client's hostname instead of an IP address. Also, if log_connections is enabled, hostname will be logged.
You need to reload pgpool.conf if you change this value.
Produces SQL log messages when true. This is similar to the log_statement parameter in PostgreSQL. It produces logs even if the debug option was not passed to pgpool-II at start up.
You need to reload pgpool.conf if you change this value.
Similar to log_statement, except that it prints logs for each DB node separately. It can be useful to make sure that replication is working, for example.
You need to reload pgpool.conf if you change this value.
When logging to syslog is enabled, this parameter determines the syslog "facility" to be used. You can choose from LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7; the default is LOCAL0. See also the documentation of your system's syslog daemon.
When logging to syslog is enabled, this parameter determines the program name used to identify PgPool messages in syslog logs. The default is pgpool.
Debug message verbosity level. 0 means no message, greater than 1 means more verbose message. Default value is 0.
Full path to a file which contains pgpool's process id. Default is "/var/run/pgpool/pgpool.pid".
You need to restart pgpool-II if you change this value.
pgpool_status is written into this directory.
Caches connections to backends when set to true. Default is true.
You need to restart pgpool-II if you change this value.
pgpool-II periodically tries to connect to the backends to detect any error on the servers or networks. This error check procedure is called "health check". If an error is detected, pgpool-II tries to perform failover or degeneration.
This parameter serves to prevent the health check from waiting for a long time in a case such as unplugged network cable. The timeout value is in seconds. Default value is 20. 0 disables timeout (waits until TCP/IP timeout).
This health check requires one extra connection to each backend,
so max_connections
in the
postgresql.conf
needs to be incremented as needed.
You need to reload pgpool.conf if you change this value.
This parameter specifies the interval between the health checks in seconds. Default is 0, which means health check is disabled.
You need to reload pgpool.conf if you change health_check_period.
The user name to perform health check. This user must exist in all the PostgreSQL backends. Otherwise, health check causes an error.
You need to reload pgpool.conf if you change health_check_user.
The password of the user to perform health check.
You need to reload pgpool.conf if you change health_check_password.
The database name to perform health check. The default is '', which tries "postgres" database first, then "template1" database until it succeeds. This is the same behavior as 3.4 or before.
You need to reload pgpool.conf if you change health_check_database.
The maximum number of times to retry a failed health check before giving up and initiating failover. This setting can be useful in spotty networks, when it is expected that health checks will fail occasionally even when the master is fine. Default is 0, which means do not retry. It is advised that you disable fail_over_on_backend_error if you want to enable health_check_max_retries.
You need to reload pgpool.conf if you change health_check_max_retries.
The amount of time (in seconds) to sleep between failed health check retries (not used unless health_check_max_retries is > 0). If 0, then retries are immediate (no delay).
You need to reload pgpool.conf if you change health_check_retry_delay.
Timeout value in milliseconds before giving up connecting to backend using connect() system call. Default is 10000 ms (10 second). Flaky network user may want to increase the value. 0 means no timeout. Note that this value is not only used for health check, but also for creating ordinary conection pools.
You need to reload pgpool.conf if you change connect_timeout.
The parameter specifies the maximum amount of time in seconds to search for a primary node when a failover scenario occurs. The default value for the parameter is 10. pgpool-II will search for the primary node for the amount of time given in case of failover before giving up trying to search for a primary node. 0 means keep trying forever. This parameter will be ignored if running in other than streaming replication mode.
You need to reload pgpool.conf if you change search_primary_node_timeout.
This parameter specifies a command to run when a node is detached. pgpool-II replaces the following special characters with backend specific information.
Special character | Description |
---|---|
%d | Backend ID of a detached node. |
%h | Hostname of a detached node. |
%p | Port number of a detached node. |
%D | Database cluster directory of a detached node. |
%M | Old master node ID. |
%m | New master node ID. |
%H | Hostname of the new master node. |
%P | Old primary node ID. |
%r | New master port number. |
%R | New master database cluster directory. |
%% | '%' character |
You need to reload pgpool.conf if you change failover_command.
When a failover is performed, pgpool kills all its child processes, which will in turn terminate all active sessions to pgpool. Then pgpool invokes the failover_command and waits for its completion. After this, pgpool starts new child processes and is ready again to accept connections from clients.
This parameter specifies a command to run when a node is attached. pgpool-II replaces special the following characters with backend specific information.
Special character | Description |
---|---|
%d | Backend ID of an attached node. |
%h | Hostname of an attached node. |
%p | Port number of an attached node. |
%D | Database cluster path of an attached node. |
%M | Old master node |
%m | New master node |
%H | Hostname of the new master node. |
%P | Old primary node ID. |
%r | New master port number. |
%R | New master database cluster directory. |
%% | '%' character |
You need to reload pgpool.conf if you change failback_command.
This parameter specifies a command to run in master/slave streaming replication mode only after a master failover. pgpool-II replaces the following special characters with backend specific information.
Special character | Description |
---|---|
%d | Backend ID of a detached node. |
%h | Hostname of a detached node. |
%p | Port number of a detached node. |
%D | Database cluster directory of a detached node. |
%M | Old master node ID. |
%m | New master node ID. |
%H | Hostname of the new master node. |
%P | Old primary node ID. |
%r | New master port number. |
%R | New master database cluster directory. |
%% | '%' character |
You need to reload pgpool.conf if you change follow_master_command.
If follow_master_command is not empty, when a master failover is completed in master/slave streaming replication, pgpool degenerate all nodes excepted the new master and starts new child processes to be ready again to accept connections from clients. After this, pgpool run the command set into the 'follow_master_command' for each degenerated nodes. Typically the command should be used to recover the slave from the new master by call the pcp_recovery_node command for example.
If true, and an error occurs when reading/writing to the backend communication, pgpool-II will trigger the fail over procedure. If set to false, pgpool will report an error and disconnect the session. If you set this parameter to off, it is recommended that you turn on health checking. Please note that even if this parameter is set to off, however, pgpool will also do the fail over when pgpool detects the administrative shutdown of postmaster.
You need to reload pgpool.conf if you change this value.
pgpool-II ignores white spaces at the beginning of SQL queries while in the load balance mode. It is useful if used with APIs like DBI/DBD:Pg which adds white spaces against the user's will.
You need to reload pgpool.conf if you change this value.
If on, ignore SQL comments when judging if load balance or query cache is possible. If off, SQL comments effectively prevent the judgment (pre 3.4 behavior).
You need to reload pgpool.conf if you change this value.
Specifies where to connect with the PostgreSQL backend. It is used by pgpool-II to communicate with the server.
For TCP/IP communication, this parameter can take a hostname or an IP address.
If this begins with a slash, it specifies Unix-domain communication
rather than TCP/IP; the value is the name of the directory
in which the socket file is stored. The default behavior when backend_hostname
is empty (''
) is to connect to a Unix-domain socket in /tmp
.
Multiple backends can be specified by adding a number at the end
of the parameter name (e.g.backend_hostname0
).
This number is referred to as "DB node ID", and it starts from 0.
The backend which was given the DB node ID of 0 will be called "Master DB".
When multiple backends are defined, the service can be continued
even if the Master DB is down (not true in some modes).
In this case, the youngest DB node ID alive will be the new Master DB.
Please note that the DB node which has id 0 has no special meaning if operated in streaming replication mode. Rather, you should care about if the DB node is the "primary node" or not. See Streaming Replication for more details.
If you plan to use only one PostgreSQL server, specify it by
backend_hostname0
.
New nodes can be added in this parameter by reloading a configuration file. However, values cannot be updated so you must restart pgpool-II in that case.
Specifies the port number of the backends.
Multiple backends can be specified by adding a number at the end of the parameter name
(e.g. backend_port0
).
If you plan to use only one PostgreSQL server, specify it by backend_port0
.
New backend ports can be added in this parameter by reloading a configuration file. However, values cannot be updated so you must restart pgpool-II in that case.
Specifies the load balance ratio for the backends. Multiple
backends can be specified by adding a number at the end of the
parameter name (e.g. backend_weight0
). If you plan
to use only one PostgreSQL server, specify it by
backend_weight0
. In the raw mode, set to 1.
New backend weights can be added in this parameter by reloading a configuration file.
From pgpool-II 2.2.6/2.3 or later, you can change this value by re-loading the configuration file. This will take effect only for new established client sessions. This is useful if you want to prevent any query sent to slaves to perform some administrative work in master/slave mode.
Specifies the database cluster directory of the backends.
Multiple backends can be specified by adding a number
at the end of the parameter name
(e.g. backend_data_directory0
).
If you don't plan to use online recovery, you do not need to specify this parameter.
New backend data directories can be added in this parameter by reloading a configuration file. However, values cannot be updated so you must restart pgpool-II in that case.
Controls various backend behavior.
Multiple backends can be specified by adding a number at the end of the parameter name
(e.g. backend_flag0
).
Currently followings are allowed. Multiple flags can be specified by using "|".
ALLOW_TO_FAILOVER | Allow to failover or detaching backend. This is the default. You cannot specify with DISALLOW_TO_FAILOVER at a same time. |
---|---|
DISALLOW_TO_FAILOVER | Disallow to failover or detaching backend. This is useful when you protect backend by using HA(High Availability) softwares such as Heartbeat or Pacemaker. You cannot specify with ALLOW_TO_FAILOVER at a same time. |
If true, enable SSL support for both the frontend and backend connections.
Note that ssl_key
and ssl_cert
must also be set in order for SSL to work with frontend connections.
SSL is off by default. Note that OpenSSL support must also have been configured at compilation time, as mentioned in the installation section.
The pgpool-II daemon must be restarted when updating SSL related settings.
The path to the private key file to use for incoming frontend connections.
There is no default value for this option, and if left unset SSL will be disabled for incoming frontend connections.
The path to the public x509 certificate file to use for incoming frontend connections.
There is no default value for this option, and if left unset SSL will be disabled for incoming frontend connections.
The path to a PEM format file containing one or more CA root
certificates, which can be used to verify the backend server certificate.
This is analogous to the -CAfile
option
of the OpenSSL verify(1)
command.
The default value for this option is unset, so no verification takes place.
Verification will still occur if this option is not set
but a value has been given for ssl_ca_cert_dir
.
The path to a directory containing PEM format CA certificate
files, which can be used to verify the backend server certificate.
This is analogous to the -CApath
option
of the OpenSSL verify(1)
command.
The default value for this option is unset, so no verification takes place.
Verification will still occur if this option is not set
but a value has been given for ssl_ca_cert
.
Life time of relation cache in seconds. 0 means no cache expiration(the default). The relation cache is used for cache the query result against PostgreSQL system catalog to obtain various information including table structures or if it's a temporary table or not. The cache is maintained in a pgpool child local memory and being kept as long as it survives. If someone modify the table by using ALTER TABLE or some such, the relcache is not consistent anymore. For this purpose, relcache_expiration controls the life time of the cache.
Number of relcache entries. Default is 256. If you see following message frequently, increase the number.
"pool_search_relcache: cache replacement happened"
If on, enable temporary table check in SELECT statements. This initiates queries against system catalog of primary/master thus increases load of primary/master. If you are absolutely sure that your system never uses temporary tables and you want to save access to primary/master, you could turn this off. Default is on.
If on, enable unlogged table check in SELECT statements. This initiates queries against system catalog of primary/master thus increases load of primary/master. If you are absolutely sure that your system never uses unlogged (for example, you are using PostgreSQL 9.0 or before) tables and you want to save access to primary/master, you could turn this off. Default is on.
Certificate handling is outside the scope of this document. The Secure TCP/IP Connections with SSL page at postgresql.org has pointers with sample commands for how to generate self-signed certificates.
Failover can be performed in raw mode if multiple servers are
defined. pgpool-II usually accesses the backend specified by
backend_hostname0
during normal operation.
If the backend_hostname0 fails for some reason, pgpool-II tries to access the
backend specified by backend_hostname1.
If that fails, pgpool-II tries the backend_hostname2, 3 and so on.
In connection pool mode, all functions in raw mode and the connection pool function can be used. To enable this mode, you need to turn on "connection_cache". Following parameters take effect to connection pool.
The maximum number of cached connections in pgpool-II children processes. pgpool-II reuses the cached connection if an incoming connection is connecting to the same database with the same user name. If not, pgpool-II creates a new connection to the backend. If the number of cached connections exceeds max_pool, the oldest connection will be discarded, and uses that slot for the new connection.
Default value is 4. Please be aware that the number of
connections from pgpool-II processes to the backends may reach
num_init_children
*
max_pool
.
This parameter can only be set at server start.
Cached connections expiration time in seconds. An expired cached connection will be disconnected. Default is 0, which means the cached connections will not be disconnected.
Specifies the SQL commands sent to reset the connection to the backend when exiting a session. Multiple commands can be specified by delimiting each by ";". Default is the following, but can be changed to suit your system.
reset_query_list = 'ABORT; DISCARD ALL'
Commands differ in each PostgreSQL versions. Here are the recommended settings.
PostgreSQL version | reset_query_list value |
---|---|
7.1 or before | ABORT |
7.2 to 8.2 | ABORT; RESET ALL; SET SESSION AUTHORIZATION DEFAULT |
8.3 or later | ABORT; DISCARD ALL |
You need to reload pgpool.conf upon modification of this directive.
Failover in the connection pool mode is the same as in the raw mode.
This mode enables data replication between the backends. The configuration parameters below must be set in addition to everything above.
Setting to true enables replication mode. Default is false.
When set to true, SELECT queries will be distributed to each backend for load balancing. Default is false.
This parameter can only be set at server start.
When set to true, if all backends don't return the same packet kind, the backends that differ from most frequent result set are degenerated.
A typical use case is a SELECT statement being part of a transaction, replicate_select set to true, and SELECT returning a different number of rows among backends. Non-SELECT statements might trigger this though. For example, a backend succeeded in an UPDATE, while others failed. Note that pgpool does NOT examine the content of records returned by SELECT.
If set to false, the session is terminated and the backends are not degenerated. Default is false.
When set to true, if backends don't return the same number of affected tuples during an INSERT/UPDATE/DELETE, the backends that differ from most frequent result set are degenerated. If the frequencies are same, the group which includes master DB node (a DB node having the youngest node id) is remained and other groups are degenerated.
If set to false, the session is terminated and the backends are not degenerated. Default is false.
Specify a comma separated list of function names that do not update the database. SELECTs using functions not specified in this list are neither load balanced, nor replicated if in replication mode. In master slave mode, such SELECTs are sent to master (primary) only.
You can use regular expression into the list to match function name (to which added automatically ^ and $), for example if you have prefixed all your read only function with 'get_' or 'select_'
white_function_list = 'get_.*,select_.*'
Specify a comma separated list of function names that do update the database. SELECTs using functions specified in this list are neither load balanced, nor replicated if in replication mode. In master slave mode, such SELECTs are sent to master(primary) only.
You can use regular expression into the list to match function name (to which added automatically ^ and $) for example if you have prefixed all your updating functions with 'set_', 'update_', 'delete_' or 'insert_':
black_function_list = 'nextval,setval,set_.*,update_.*,delete_.*,insert_.*'
Only one of these two lists can be filled in a configuration.
Prior to pgpool-II 3.0, nextval() and setval() were known to do writes to the database. You can emulate this by using white_function_list and black_function_list:
white_function_list = '' black_function_list = 'nextval,setval,lastval,currval'
Please note that we have lastval and currval in addition to nextval and setval. Though lastval() and currval() are not writing functions, it is wise to add lastval() and currval() to avoid errors in the case when these functions are accidentally load balanced to other DB node. Because adding to black_function_list will prevent load balancing.
When set to true, pgpool-II replicates SELECTs replication mode. If false, pgpool-II sends SELECTs without writing function to the Master DB only. Default is false.
If a SELECT query is inside an explicit transaction block, replicate_select and load_balance_mode will have an effect on how replication works. Details are shown below.
replicate_select is true | Y | N | |||
---|---|---|---|---|---|
load_balance_mode is true | any | Y | N | ||
SELECT is inside a transaction block | any | Y | N | any | |
transaction isolation level is SERIALIZABLE and the transaction has issued a write query |
any | Y | N | any | any |
results(R:replication, M: send only to master, L: load balance) | R | M | L | L | M |
If replicating a table with SERIAL data type, the SERIAL column value may differ between the backends. This problem is avoidable by locking the table explicitly (although, transactions' parallelism will be severely degraded). To achieve this, however, the following change must be made:
INSERT INTO ...
to
BEGIN; LOCK TABLE ... INSERT INTO ... COMMIT;
When insert_lock
is true, pgpool-II automatically adds
the above queries each time an INSERT is executed
(if already in transaction, it simply adds LOCK TABLE ....).
pgpool-II 2.2 or later, it automatically detects whether the table has a SERIAL columns or not, so it will never lock the table if it does not use SERIAL columns.
pgpool-II 3.0 series until 3.0.4 uses a row lock against the sequence relation, rather than table lock. This is intended to minimize lock conflict with VACUUM (including autovacuum). However this will lead to another problem. After transaction wraparound happens, row locking against the sequence relation causes PostgreSQL internal error (more precisely, access error on pg_clog, which keeps transaction status). To prevent this, PostgreSQL core developers decided to disallow row locking against sequences and this will break pgpool-II of course (the "fixed" version of PostgreSQL was released as 9.0.5, 8.4.9, 8.3.16 and 8.2.22).
pgpool-II 3.0.5 or later uses a row lock against pgpool_catalog.insert_lock table because new PostgreSQL disallows a row lock against the sequence relation. So creating insert_lock table in all databases which are accessed via pgpool-II beforehand is required. See Creating insert_lock table for more details. If does not exist insert_lock table, pgpool-II locks the insert target table. This behavior is same as pgpool-II 2.2 and 2.3 series. If you want to use insert_lock which is compatible with older releases, you can specify lock method by configure script. See configure for more details.
You might want to have a finer (per statement) control:
insert_lock
to true, and add /*NO INSERT LOCK*/
at the beginning of an INSERT statement for which
you do not want to acquire the table lock.insert_lock
to false, and add /*INSERT LOCK*/
at the beginning of an INSERT statement for which
you want to acquire the table lock.
Default value is false. If insert_lock
is enabled,
the regression tests for PostgreSQL 8.0 will fail in transactions,
privileges, rules, and alter_table. The reason for this is that
pgpool-II tries to LOCK the VIEW for the rule test, and will
produce the following error message:
! ERROR: current transaction is aborted, commands ignored until end of transaction block
For example, the transactions test tries an INSERT into a table which does not exist, and pgpool-II causes PostgreSQL to acquire the lock before that. The transaction will be aborted, and the following INSERT statement produces the above error message.
This parameter specifies a PostgreSQL user name for online recovery. It can be changed without restarting.
This parameter specifies a PostgreSQL password for online recovery. It can be changed without restarting.
This parameter specifies a command to be run by master(primary) PostgreSQL server at the first stage of online recovery. The command file must be put in the database cluster directory for security reasons. For example, if recovery_1st_stage_command = 'sync-command', then pgpool-II executes $PGDATA/sync-command.
recovery_1st_stage_command will receive 4 parameters as follows:
Note that pgpool-II accepts connections and queries while recovery_1st_stage command is executed. You can retrieve and update data during this stage.
CAUTION: recovery_1st_stage_command runs as an SQL command from PostgreSQL's point of view. If you enable PostgreSQL's statement_time_out and it's shorter than the execution time of the recovery_1st_stage_command, PostgreSQL cancels the command. Typical symptoms of this is, rsync used in the command is killed by signal 2 for example.
This parameter can be changed without restarting.
This parameter specifies a command to be run by master(primary) PostgreSQL server at the second stage of online recovery. The command file must be put in the database cluster directory for security reasons. For example, if recovery_2nd_stage_command = 'sync-command', then pgpool-II executes $PGDATA/sync-command.
recovery_2nd_stage_command will receive 4 parameters as follows:
Note that pgpool-II does not accept connections and queries while recovery_2nd_stage_command is running. Thus if a client stays connected for a long time, the recovery command won't be executed. pgpool-II waits until all clients have closed their connections. The command is only executed when no client is connected to pgpool-II anymore.
CAUTION: recovery_2nd_stage_command runs as an SQL command from PostgreSQL's point of view. If you enable PostgreSQL's statement_time_out and it's shorter than the execution time of the recovery_2nd_stage_command, PostgreSQL cancels the command. Typical symptoms of this is, rsync used in the command is killed by signal 2 for example.
This parameter can be changed without restarting.
pgpool does not accept new connections during the second stage. If a client connects to pgpool during recovery processing, it will have to wait for the end of the recovery.
This parameter specifies recovery timeout in sec. If this timeout is reached, pgpool cancels online recovery and accepts connections. 0 means no wait.
This parameter can be changed without restarting.
Similar to client_idle_limit but only takes effect in the second stage of recovery. A client being idle for client_idle_limit_in_recovery seconds since its last query will get disconnected. This is useful for preventing the pgpool recovery from being disturbed by a lazy client or if the TCP/IP connection between the client and pgpool is accidentally down (a cut cable for instance). If set to -1, disconnect the client immediately. The default value for client_idle_limit_in_recovery is 0, which means the feature is turned off.
If your clients are very busy, pgpool-II cannot enter the second stage of recovery whatever value of client_idle_limit_in_recovery you may choose. In this case, you can set client_idle_limit_in_recovery to -1 so that pgpool-II immediately disconnects such busy clients before entering the second stage.
You need to reload pgpool.conf if you change client_idle_limit_in_recovery.
This parameter specifies a table name used for large object replication control. If it is specified, pgpool will lock the table specified by lobj_lock_table and generate a large object id by looking into pg_largeobject system catalog and then call lo_create to create the large object. This procedure guarantees that pgpool will get the same large object id in all DB nodes in replication mode. Please note that PostgreSQL 8.0 or older does not have lo_create, thus this feature will not work.
A call to the libpq function lo_creat() will trigger this feature. Also large object creation through Java API (JDBC driver), PHP API (pg_lo_create, or similar API in PHP library such as PDO), and this same API in various programming languages are known to use a similar protocol, and thus should work.
The following large object create operation will not work:
It does not matter what schema lobj_lock_table is stored in, but this table should be writable by any user. Here is an example showing how to create such a table:
CREATE TABLE public.my_lock_table (); GRANT ALL ON public.my_lock_table TO PUBLIC;
The table specified by lobj_lock_table must be created beforehand. If you create the table in template1, any database created afterward will have it.
If lobj_lock_table has empty string(''), the feature is disabled (thus large object replication will not work). The default value for lobj_lock_table is ''.
For a query to be load balanced, all the following requirements must be met:
Note that you could suppress load balancing by inserting arbitrary comments just in front of the SELECT query:
/*REPLICATION*/ SELECT ...
If you want to use comments without supressing load balancing, you can set allow_sql_comments to on.
Please refer to replicate_select as well. See also a flow chart.
Note: the JDBC driver has an autocommit option. If the autocommit is false, the JDBC driver sends "BEGIN" and "COMMIT" by itself. In this case the same restriction above regarding load balancing will be applied.
pgpool-II detaches a dead backend from the pool, maintaining the database service via the remaining backends provided that there is at least one healthy backend.
In replication mode, if pgpool finds that the number of affected tuples by INSERT, UPDATE, DELETE are not same, it sends erroneous SQL statement to all DB nodes to abort the transaction if failover_if_affected_tuples_mismatch is set to false (fail-over occurs if it is set to true). In this case you will see following error messages on client terminal:
=# UPDATE t SET a = a + 1; ERROR: pgpool detected difference of the number of update tuples Possible last query was: "update t1 set i = 1;" HINT: check data consistency between master and other db node
You will see number of updated rows in PostgreSQL log (in this case DB node 0 has 0 updated row and DB node 1 has 1 updated row)
2010-07-22 13:23:25 LOG: pid 5490: SimpleForwardToFrontend: Number of affected tuples are: 0 1 2010-07-22 13:23:25 LOG: pid 5490: ReadyForQuery: Degenerate backends: 1 2010-07-22 13:23:25 LOG: pid 5490: ReadyForQuery: Number of affected tuples are: 0 1
This mode is used to couple pgpool-II with another master/slave replication software (like Slony-I and Streaming replication), which is responsible for doing the actual data replication.
Please note that the number of slaves is not necessarily limited to just 1. Actually you could have up to 127 slaves (0 slaves is allowed).
DB nodes' information (backend_hostname,
backend_port, backend_weight,
backend_flag and backend_data_directory
if you need the online recovery functionality) must be set, in the same way as in the replication mode.
In addition to that, set master_slave_mode
and
load_balance_mode
to true.
pgpool-II will then send queries that need to be replicated to the Master DB, and other queries will be load balanced if possible. Queries sent to Master DB because they cannot be balanced are of course accounted for in the load balancing algorithm.
In master/slave mode, DDL and DML for temporary table can be executed on the master node only. SELECT can be forced to be executed on the master as well, but for this you need to put a /*NO LOAD BALANCE*/ comment before the SELECT statement.
In the master/slave mode, replication_mode
must be set
to false, and master_slave_mode
to true.
The master/slave mode has a 'master_slave_sub mode'. The default is 'slony' which is suitable for Slony-I. You can also set it to 'stream', which should be set if you want to work with PostgreSQL's built-in replication system (Streaming Replication). The sample configuration file for the Slony-I sub-mode is pgpool.conf.sample-master-slave and the sample for the streaming replication sub-module is pgpool.conf.sample-stream.
Please restart pgpool-II if you change any of the above parameters.
You can set white_function_list and black_function_list to control load balancing in master/slave mode. See white_function_list for more details.
As stated above, pgpool-II can work together with Streaming Replication, which is available since PostgreSQL 9.0. To use it, enable 'master_slave_mode' and set 'master_slave_sub_mode' to 'stream'. pgpool-II assumes that Streaming Replication is used with Hot Standby at present, which means that the standby database is open read-only. The following directives can be used with this mode:
Specifies the maximum tolerated replication delay of the standby against the primary server in WAL bytes. If the delay exceeds delay_threshold, pgpool-II does not send SELECT queries to the standby server anymore. Everything is sent to the primary server even if load balance mode is enabled, until the standby has caught-up. If delay_threshold is 0 or sr checking is disabled, the delay checking is not performed. This check is performed every 'sr_check_period'. The default value for delay_threshold is 0.
You need to reload pgpool.conf if you change this directive.
This parameter specifies the interval between the streaming replication delay checks in seconds. Default is 0, which means the check is disabled.
You need to reload pgpool.conf if you change sr_check_period.
The user name to perform streaming replication check. This user must exist in all the PostgreSQL backends. Otherwise, the check causes an error. Note that sr_check_user and sr_check_password are used even sr_check_period is 0. To identify the primary server, pgpool-II sends function call request to each backend. sr_check_user and sr_check_password are used for this session.
You need to reload pgpool.conf if you change sr_check_user.
The password of the user to perform streaming replication check. If no password is required, specify empty string('').
You need to reload pgpool.conf if you change sr_check_password.
The database to perform streaming replication delay check. The default is "postgres" (which is the built-in database name in 3.4 or before).
You need to reload pgpool.conf if you change sr_check_database.
Specifies how to log the replication delay. If 'none' is specified, no log is written. If 'always', log the delay every time the replication delay is checked. If 'if_over_threshold' is specified, the log is written when the delay exceeds delay_threshold. The default value for log_standby_delay is 'none'. You need to reload pgpool.conf if you change this directive.
You could monitor the replication delay by using the "show pool_status" command as well. The column name is "standby_delay#"(where '#' should be replaced by DB node id).
In master/slave mode with streaming replication, if the primary or standby node goes down, pgpool-II can be set up to trigger a failover. Nodes can be detached automatically without further setup. While doing streaming replication, the standby node checks for the presence of a "trigger file" and on finding it, the standby stops continuous recovery and goes into read-write mode. By using this, you can have the standby database take over when the primary goes down.
Caution: If you plan to use multiple standby nodes, we recommend to set a delay_threshold to prevent any query directed to other standby nodes from retrieving older data.
If a second standby took over primary when the first standby has already taken over too, you would get bogus data from the second standby. We recommend not to plan this kind of configuration.
How to setup a failover configuration is as follows.
$ cd /usr/loca/pgsql/bin $ cat failover_stream.sh #! /bin/sh # Failover command for streaming replication. # This script assumes that DB node 0 is primary, and 1 is standby. # # If standby goes down, do nothing. If primary goes down, create a # trigger file so that standby takes over primary node. # # Arguments: $1: failed node id. $2: new master hostname. $3: path to # trigger file. failed_node=$1 new_master=$2 trigger_file=$3 # Do nothing if standby goes down. if [ $failed_node = 1 ]; then exit 0; fi # Create the trigger file. /usr/bin/ssh -T $new_master /bin/touch $trigger_file exit 0; chmod 755 failover_stream.sh
failover_command = '/usr/local/src/pgsql/9.0-beta/bin/failover_stream.sh %d %H /tmp/trigger_file0'
standby_mode = 'on' primary_conninfo = 'host=name of primary_host user=postgres' trigger_file = '/tmp/trigger_file0'
wal_level = hot_standby max_wal_senders = 1
host replication postgres 192.168.0.10/32 trust
Start primary and secondary PostgreSQL nodes to initiate Streaming replication. If the primary node goes down, the standby node will automatically start as a normal PostgreSQL and will be ready to accept write queries.
While using Streaming replication and Hot Standby, it is important to determine which query can be sent to the primary or the standby, and which one should not be sent to the standby. pgpool-II's Streaming Replication mode carefully takes care of this. In this chapter we'll explain how pgpool-II accomplishes this.
We distinguish which query should be sent to which node by looking at the query itself.
In an explicit transaction:
In the extended protocol, it is possible to determine if the query can be sent to standby or not in load balance mode while parsing the query. The rules are the same as for the non extended protocol. For example, INSERTs are sent to the primary node. Following bind, describe and execute will be sent to the primary node as well.
[Note: If the parse of a SELECT statement is sent to the standby node due to load balancing, and then a DML statement, such as an INSERT, is sent to pgpool-II, then the parsed SELECT will have to be executed on the primary node. Therefore, we re-parse the SELECT on the primary node.]
Lastly, queries that pgpool-II's parser thinks to be an error are sent to the primary node.
You can use database name and application name for smaller granularity in specifying load balance.
you can set "database name:node id" pair to specify the node id when connecting to the database. For example, by specifying "test:1", pgpool-II always redirects SELECT to node 1 in case of connecting to database "test". You can specify multiple "database name:node id" pair by separating them using comma (,). Regular expressions are accepted for database name. Special keyword "primary" indicates the primary node and "standby" indicates one of standby nodes.
Here is an example.
database_redirect_preference_list = 'postgres:primary,mydb[01]:1,mydb2:standby'
SELECTs will be redirected to primary if you connect to postgres database. Connecting to mydb0 or mydb1 will redirect SELECTs to node 1. Connecting to mydb2 will redirect SELECTs to one of standby nodes.
You need to reload pgpool.conf if you change this directive.
you can set "application name:node id" pair to specify the node id when the application is used. "Application name" is a name specified by a client when it connects to database. You can use it in PostgreSQL 9.0 or later.
Caution: JDBC driver postgresql-9.3 or before does not send the application name in the startup packet even if application name is specified for the JDBC driver option "ApplicationName" and "assumeMinServerVersion=9.0" is specified and cannot use this feature. If you want to use the feature through JDBC, please use postgresql-9.4 or later version of driver.
For example, application of psql command is "psql". pgpool-II recognize application names only when clients sends a start up packet. Clients can send application names later on but pgpool-II will not recognize them.
The notion of app_name_redirect_preference_list is same as database_redirect_preference_list. Thus you can use regular expressions for application name.
Here is an example.
app_name_redirect_preference_list = 'psql:primary,myapp1:1,myapp2:standby'
In this example, psql sends SELECTs to primary node, myapp1 sends to node 1, and myapp2 sends to one of standby nodes.
app_name_redirect_preference_list takes precedence over database_redirect_preference_list. See the next example.
database_redirect_preference_list = 'bigdb:primary' app_name_redirect_preference_list = 'myapp:2'
Applications connecting to bigdb database send SELECTs to primary node. However myapp sends SELECTs to node 2 even if it connects to bigdb. This is useful in a scenario: myapp2 sends very heavy SELECTs to execute analysis jobs. You want to use node 2 solely for analysis purpose.
You need to reload pgpool.conf if you change this directive.
In master/slave mode with streaming replication, online recovery can be performed. In the online recovery procedure, primary server acts as a master server and recovers specified standby server. Thus the recovery procedure requires that the primary server is up and running. If the primary server goes down, and no standby server is promoted, you need to stop pgpool-II and all PostgreSQL servers and recover them manually.
recovery_user = 'postgres'
recovery_password = 't-ishii'
recovery_1st_stage_command = 'basebackup.sh'
recovery_2nd_stage_command = ''
# cd pgpool-II-x.x.x/sql/pgpool-recovery # make # make install # psql -f pgpool-recovery.sql template1
That's it. Now you should be able to use pcp_recovery_node (as long as the standby node stops) or push "recovery" button of pgpoolAdmin to perform online recovery. If something goes wrong, please examine pgpool-II log, primary server log and standby server log(s).
For your reference, here are the steps taken in the recovery procedure.
Just like the pg_hba.conf file for PostgreSQL, pgpool supports a similar client authentication function using a configuration file called "pool_hba.conf".
When you install pgpool, pool_hba.conf.sample will be installed in "/usr/local/etc", which is the default directory for configuration files. Copy pool_hba.conf.sample as pool_hba.conf and edit it if necessary. By default, pool_hba authentication is disabled. Change enable_pool_hba to on to enable it.
The format of the pool_hba.conf file follows very closely PostgreSQL's pg_hba.conf format.
local DATABASE USER METHOD [OPTION] host DATABASE USER CIDR-ADDRESS METHOD [OPTION]
See "pool_hba.conf.sample" for a detailed explanation of each field.
Here are the limitations of pool_hba.
Since pgpool does not know anything about users in the backend server, the database name is simply checked against entries in the DATABASE field of pool_hba.conf.
This is for the same reason as for the "samegroup" described above. A user name is simply checked against the entries in the USER field of pool_hba.conf.
pgpool currently does not support IPv6.
Again, this is for the same reason as for the "samegroup" described above. pgpool does not have access to user/password information.
To use md5 authentication, you need to register your name and password in "pool_passwd". See Authentication / Access Controls for more details.
Note that everything described in this section is about the authentication taking place between a client and pgpool; a client still has to go through the PostgreSQL's authentication process. As far as pool_hba is concerned, it does not matter if a user name and/or database name given by a client (i.e. psql -U testuser testdb) really exists in the backend. pool_hba only cares if a match in the pool_hba.conf is found or not.
PAM authentication is supported using user information on the host where pgpool is executed. To enable PAM support in pgpool, specify "--with-pam" option to configure:
configure --with-pam
To enable PAM authentication, you need to create a service-configuration file for pgpool in the system's PAM configuration directory (which is usually at "/etc/pam.d"). A sample service-configuration file is installed as "share/pgpool.pam" under the install directory.
You can use in memory query cache in any mode. It is different from the above query cache on the point that in memory query cache is faster because cache storage is in memory. Moreover you don't need to restart pgpool-II when the cache is outdated because the underlying table gets updated.
In memory cache saves pair of SELECT statements (with its Bind parameters if the SELECT is an extended query). If the same SELECTs comes in, it returns the value from cache. Since no SQL parsing nor access to PostgreSQL are involved, it's extremely fast.
On the other hand, it might be slower than the normal path because it adds some overhead to store cache. Moreover when a table is updated, pgpool automatically deletes all the caches related to the table. So the performance will be degraded by a system with a lot of updates. If the cache_hit_ratio is lower than 70%, you might want to disable in memory cache.
To enable the memory cache functionality, set this to on (default is off).
memory_cache_enabled = on
You can choose a cache storage: shared memory or memcached (you can't use the both). Query cache with shared memory is fast and easy because you don't have to install and configure memcached, but restricted the max size of cache by the one of shared memory. Query cache with memcached needs a overhead to access network, but you can set the size as you like.
Memory cache behavior can be specified by memqcache_method directive. Either "shmem"(shared memory) or "memcached". Default is shmem.
memqcache_method = 'shmem'
Not All of SELECTs and WITH can be cached. In some cases including followings, cache is avoided to keep consistency between caches and databases.
It can happen that even if the matched query cache exists, pgpool doesn't return it.
These are the parameters used with both of shmem and memcached.
Life time of query cache in seconds. Default is 0. 0 means no cache expiration, and cache have been enabled until a table is updated. This parameter and memqcache_auto_cache_invalidation are orthogonal.
If on, automatically deletes cache related to the updated tables. If off, does not delete caches. Default is on. This parameter and memqcache_expire. are orthogonal.
If the size of a SELECT result is larger than memqcache_maxcache bytes, it is not cached and the messages is shown:
2012-05-02 15:08:17 LOG: pid 13756: pool_add_temp_query_cache: data size exceeds memqcache_maxcache. current:4095 requested:111 memq_maxcache:4096
To avoid this problem, you have to set memqcache_maxcache larger. But if you use shared memory as the cache storage, it must be lower than memqcache_cache_block_size. If memqcached, it must be lower than the size of slab (default is 1 MB).
Specify a comma separated list of table names whose SELECT results are to be cached even if they are VIEWs or unlogged tables. You can use regular expression (to which added automatically ^ and $).
TABLEs and VIEWs in both of white_memqcache_table_list and black_memqcache_table_list are cached.
You need to add both non schema qualified name and schema qualified name if you plan to use both of them in your query. For exmaple, if you want to use both "table1" and "public.table1" in your query, you need to add "table1,public.table1", not just "table1".
Specify a comma separated list of table names whose SELECT results are NOT to be cached. You can use regular expression (to which added automatically ^ and $).
You need to add both non schema qualified name and schema qualified name if you plan to use both of them in your query. For exmaple, if you want to use both "table1" and "public.table1" in your query, you need to add "table1,public.table1", not just "table1".
Full path to the directory where oids of tables used by SELECTs are stored. Under memqcache_oiddir there are directories named database oids, and under each of them there are files named table oids used by SELECTs. In the file pointers to query cache are stored. They are used as keys to delete caches.
Directories and files under memqcache_oiddir are not deleted whenever pgpool-II restarts. If you start pgpool by "pgpool -C", pgpool starts without the old oidmap.
This explains how to monitor in memory query cache. To know if a SELECT result is from query cache or not, enable log_per_node_statement.
2012-05-01 15:42:09 LOG: pid 20181: query result fetched from cache. statement: select * from t1;
pool_status command shows the cache hit ratio.
memqcache_stats_start_time | Tue May 1 15:41:59 2012 | Start time of query cache stats memqcache_no_cache_hits | 80471 | Number of SELECTs not hitting query cache memqcache_cache_hits | 36717 | Number of SELECTs hitting query cache
In this example, you can calculate like the below:
(memqcache_cache_hits) / (memqcache_no_cache_hits+memqcache_cache_hits) = 36717 / (36717 + 80471) = 31.3%
show pool_cache commands shows the same one.
These are the parameters used with shared memory as the cache storage.
Specify the size of shared memory as cache storage in bytes.
Specify the number of cache entries. This is used to define the size of cache management space (you need this in addition to memqcache_total_size). The management space size can be calculated by: memqcache_max_num_cache * 48 bytes. Too small number will cause an error while registering cache. On the other hand too large number is just a waste of space.
If cache storage is shared memory, pgpool uses the memory divided by memqcache_cache_block_size. SELECT result is packed into the block. However because the SELECT result cannot be placed in several blocks, it cannot be cached if it is larger than memqcache_cache_block_size. memqcache_cache_block_size must be greater or equal to 512.
These are the parameters used with memcached as the cache storage.
Specify the host name or the IP address in which memcached works. If it is the same one as pgpool-II, set 'localhost'.
Specify the port number of memcached. Default is 11211.
To use memcached as cache storage, pgpool-II needs a working memcached and the client library: libmemcached. It is easy to install them by rpms. This explains how to install from source codes.
memcached's source code can be downloaded from: memcached development page
After extracting the source tarball, execute the configure script.
./configure
make make install
Libmemcached is a client library for memcached. You need to install libmemcached after installing memcached.
libmemcached's source code can be downloaded from: libmemcached development page
After extracting the source tarball, execute the configure script.
./configure
If you want non-default values, some options can be set:
--with-memcached=path
make make install
All the backends must be started before starting pgpool-II.
pgpool [-c][-f config_file][-a hba_file][-F pcp_config_file][-n][-D][-d][x]
-c | --clear-cache | deletes query cache |
-f config_file | --config-file config-file | specifies pgpool.conf |
-a hba_file | --hba-file hba_file | specifies pool_hba.conf |
-F pcp_config_file | --pcp-password-file | specifies pcp.conf |
-n | --no-daemon | no daemon mode (terminal is not detached) |
-D | --discard-status | Discard pgpool_status file and do not restore previous status V3.0 - |
-C | --clear-oidmaps | Discard oid maps in memqcache_oiddir for in memory query cache (only when memqcache_method is 'memcached', if shmem, discard whenever pgpool starts). V3.2 - |
-d | --debug | debug mode |
-x | --debug-assertions | Turns on various assertion checks, This is a debugging aid |
There are two ways to stop pgpool-II. One is using a PCP command (described later), the other using a pgpool-II command. Below is an example of the pgpool-II command.
pgpool [-f config_file][-F pcp_config_file] [-m {s[mart]|f[ast]|i[mmediate]}] stop
-m s[mart] | --mode s[mart] |
waits for clients to disconnect, and shutdown (default) |
-m f[ast] | --mode f[ast] |
does not wait for clients; shutdown immediately |
-m i[mmediate] | --mode i[mmediate] |
the same as '-m f' |
pgpool records backend status into the [logdir]/pgpool_status file. From pgpool-II 3.4.0 the file format of pgpool_status has been changed: it's an ordinary ASCII file and you can read and edit the contents by using your favorite text editor. For example, if you add new backend and restart pgpool-II, you might have wait for long time until pgpool-II detects the new backend and performs failover. By editing pgpool_status to set the backend to be down status, you could avoid the situation because pgpool-II's health check skips down nodes. Each line in the file corresponding to each backend node status. The first backend status is the first line, and and the seconds backend status is the second line and so on. The backend status is represented by any of "up", "down", "unused" (case ignored). Here is an example of pgpool_status:
up down up
Note that pre-3.4.0 pgpool-II uses binary format pgpool_status. Pgpool-II 3.4.0 or later can read the file as well. However pre-3.4.0 pgpool-II cannot read ASCII format pgpool_status file.
When pgpool restarts, it reads this file and restores the backend status. This will prevent a difference in data among DB nodes which might be caused by following scenario:
If for some reason, for example, the stopped DB has been synced with the active DB by another means, pgpool_status can be removed safely before starting pgpool.
pgpool-II can reload configuration files without restarting.
pgpool [-c][-f config_file][-a hba_file][-F pcp_config_file] reload
-f config_file | --config-file config-file | specifies pgpool.conf |
-a hba_file | --hba-file hba_file | specifies pool_hba.conf |
-F pcp_config_file | --pcp-password-file | specifies pcp.conf |
Please note that some configuration items cannot be changed by reloading. New configuration takes effect after a change for new sessions.
pgpool-II provides some information via the SHOW command. SHOW is a real SQL statement, but pgPool-II intercepts this command if it asks for specific pgPool-II information. Available options are:
Other than "pool_status" are added since pgpool-II 3.0.
Note : The term 'pool' refers to the pool of PostgreSQL sessions owned by one pgpool process, not the whole sessions owned by pgpool.
the "pool_status" SQL statement was already available in previous releases, but the other ones have appeared in release 3.0.
"SHOW pool_status" sends back the list of configuration parameters with their name, value, and description. Here is an excerpt of the result:
benchs2=# show pool_status; item | value | description --------------------------------------+--------------------------------+------------------------------------------------------------------ listen_addresses | localhost | host name(s) or IP address(es) to listen to port | 9999 | pgpool accepting port number socket_dir | /tmp | pgpool socket directory pcp_port | 9898 | PCP port # to bind pcp_socket_dir | /tmp | PCP socket directory
"SHOW pool_nodes" sends back a list of all configured nodes. It displays the node id, the hostname, the port, the status, the weight (only meaningful if you use the load balancing mode), the role and the SELECT query counts issued to each backend. The possible values in the status column are explained in the pcp_node_info reference. If the hostname is something like "/tmp", that means pgpool-II is connecting to backend by using UNIX domain sockets. The SELECT count does not include internal queries used by pgoool-II. Also the counters are reset to zero upon starting up of pgpool-II.
benchs2=# show pool_nodes; node_id | hostname | port | status | lb_weight | role | select_cnt ---------+----------+-------+--------+-----------+---------+------------ 0 | /tmp | 11002 | 2 | 0.500000 | primary | 9231 1 | /tmp | 11003 | 2 | 0.500000 | standby | 9469 (2 rows)
"SHOW pool_processes" sends back a list of all pgPool-II processes waiting for connections and dealing with a connection.
It has 6 columns:
This view will always return num_init_children lines.
benchs2=# show pool_processes; pool_pid | start_time | database | username | create_time | pool_counter ----------+---------------------+----------+-----------+---------------------+-------------- 8465 | 2010-08-14 08:35:40 | | | | 8466 | 2010-08-14 08:35:40 | benchs | guillaume | 2010-08-14 08:35:43 | 1 8467 | 2010-08-14 08:35:40 | | | | 8468 | 2010-08-14 08:35:40 | | | | 8469 | 2010-08-14 08:35:40 | | | | (5 lines)
"SHOW pool_pools" sends back a list of pools handled by pgPool-II. their name, value, and description. Here is an excerpt of the result:
It has 11 columns:
It'll always return num_init_children * max_pool * number_of_backends lines.
pool_pid | start_time | pool_id | backend_id | database | username | create_time | majorversion | minorversion | pool_counter | pool_backendpid | pool_connected ----------+---------------------+---------+------------+----------+-----------+---------------------+--------------+--------------+--------------+-----------------+---------------- 8465 | 2010-08-14 08:35:40 | 0 | 0 | | | | | | | | 8465 | 2010-08-14 08:35:40 | 1 | 0 | | | | | | | | 8465 | 2010-08-14 08:35:40 | 2 | 0 | | | | | | | | 8465 | 2010-08-14 08:35:40 | 3 | 0 | | | | | | | | 8466 | 2010-08-14 08:35:40 | 0 | 0 | benchs | guillaume | 2010-08-14 08:35:43 | 3 | 0 | 1 | 8473 | 1 8466 | 2010-08-14 08:35:40 | 1 | 0 | | | | | | | | 8466 | 2010-08-14 08:35:40 | 2 | 0 | | | | | | | | 8466 | 2010-08-14 08:35:40 | 3 | 0 | | | | | | | | 8467 | 2010-08-14 08:35:40 | 0 | 0 | | | | | | | | 8467 | 2010-08-14 08:35:40 | 1 | 0 | | | | | | | | 8467 | 2010-08-14 08:35:40 | 2 | 0 | | | | | | | | 8467 | 2010-08-14 08:35:40 | 3 | 0 | | | | | | | | 8468 | 2010-08-14 08:35:40 | 0 | 0 | | | | | | | | 8468 | 2010-08-14 08:35:40 | 1 | 0 | | | | | | | | 8468 | 2010-08-14 08:35:40 | 2 | 0 | | | | | | | | 8468 | 2010-08-14 08:35:40 | 3 | 0 | | | | | | | | 8469 | 2010-08-14 08:35:40 | 0 | 0 | | | | | | | | 8469 | 2010-08-14 08:35:40 | 1 | 0 | | | | | | | | 8469 | 2010-08-14 08:35:40 | 2 | 0 | | | | | | | | 8469 | 2010-08-14 08:35:40 | 3 | 0 | | | | | | | | (20 lines)
"SHOW pool_version" displays a string containing the pgPool-II release number. Here is an example of it:
benchs2=# show pool_version; pool_version ------------------------ 3.0-dev (umiyameboshi) (1 line)
"SHOW pool_cache" displays cache storage statistics if in memory query cache is enabled. Here is an example of it:
test=# \x \x Expanded display is on. test=# show pool_cache; show pool_cache; -[ RECORD 1 ]---------------+--------- num_cache_hits | 891703 num_selects | 99995 cache_hit_ratio | 0.90 num_hash_entries | 131072 used_hash_entries | 99992 num_cache_entries | 99992 used_cache_enrties_size | 12482600 free_cache_entries_size | 54626264 fragment_cache_entries_size | 0
pgpool-II, while in replication mode, can sync a database and attach a node while still servicing clients. We call this feature "online recovery".
A recovery target node must be in the detached state before doing online recovery. If you wish to add a PostgreSQL server dynamically, add 'backend_hostname' and its associated parameters and reload pgpool.conf. pgpool-II registers this new node as a detached node.
caution: Stop autovacuum on the master node (the first node which is up and running). Autovacuum may change the contents of the database and might cause inconsistency after online recovery if it's running. This applies only if you're recovering with a simple copy mechanism, such as the rsync one explained below. This doesn't apply if you're using PostgreSQL's PITR mechanism.
If the target PostgreSQL server has already started, you need to shut it down.
pgpool-II performs online recovery in two separated phases. There are a few seconds or minutes when client will be waiting to connect to pgpool-II while a recovery node synchronizes database. It follows these steps:
The first step of data synchronization is called "first stage". Data is synchronized during the first stage. In the first stage, data can be updated or retrieved from any table concurrently.
You can specify a script executed during the first stage. pgpool-II passes three arguments to the script.
Data synchronization is finalized during what is called "second stage". Before entering the second stage, pgpool-II waits until all clients have disconnected. It blocks any new incoming connection until the second stage is over.
After all connections have terminated, pgpool-II merges updated data between the first stage and the second stage. This is the final data synchronization step.
Note that there is a restriction about online recovery. If pgpool-II itself is installed on multiple hosts, online recovery does not work correctly, because pgpool-II has to stop all clients during the 2nd stage of online recovery. If there are several pgpool hosts, only one will have received the online recovery command and will block connections.
Set the following parameters for online recovery in pgpool.conf.
You need to install the following C language function for online recovery into the "template1" database of all backend nodes. Its source code is in pgpool-II tarball.
pgpool-II-x.x.x/sql/pgpool-recovery/
Change directory there and do "make install".
% cd pgpool-II-x.x.x/sql/pgpool-recovery/ % make install
Then, install the SQL function.
% cd pgpool-II-x.x.x/sql/pgpool-recovery/ % psql -f pgpool-recovery.sql template1
We must deploy some data sync scripts and a remote start script into the database cluster directory ($PGDATA). Sample script files are available in pgpool-II-x.x.x/sample directory.
Here is how to do online recovery by Point In Time Recovery (PITR), which is available in PostgreSQL 8.2 and later versions. Note that all PostgreSQL servers involved need to have PITR enabled.
A script to get a base backup on a master node and copy it to a recovery target node on the first stage is needed. The script can be named "copy-base-backup" for example. Here is the sample script.
#! /bin/sh DATA=$1 RECOVERY_TARGET=$2 RECOVERY_DATA=$3 psql -c "select pg_start_backup('pgpool-recovery')" postgres echo "restore_command = 'scp $HOSTNAME:/data/archive_log/%f %p'" > /data/recovery.conf tar -C /data -zcf pgsql.tar.gz pgsql psql -c 'select pg_stop_backup()' postgres scp pgsql.tar.gz $RECOVERY_TARGET:$RECOVERY_DATA
This script puts the master database in backup mode, generates the following recovery.conf:
restore_command = 'scp master:/data/archive_log/%f %p'
performs the backup, then puts the master database out of backup mode and copies the backup on the chosen target node.
The second stage of the procedure is a script to force an XLOG file switch. This script is named "pgpool_recovery_pitr" here. It enforces a switch of the transaction log. For this purpose, pg_switch_xlog could be used.
V3.1 - However it may return before the switch is done and this might lead to failure of the online recovery procedure. Pgpool-II provides a safer function called "pgpool_switch_xlog" which will wait until the transaction log switching is actually finished. pgpool_switch_xlog is installed during the procedure performed in the Installing C functions section.
Here is the sample script.
#! /bin/sh # Online recovery 2nd stage script # datadir=$1 # master dabatase cluster DEST=$2 # hostname of the DB node to be recovered DESTDIR=$3 # database cluster of the DB node to be recovered port=5432 # PostgreSQL port number archdir=/data/archive_log # archive log directory # Force to flush current value of sequences to xlog psql -p $port -t -c 'SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn' template1| while read i do if [ "$i" != "" ];then psql -p $port -c "SELECT setval(oid, nextval(oid)) FROM pg_class WHERE relkind = 'S'" $i fi done psql -p $port -c "SELECT pgpool_switch_xlog('$archdir')" template1
This flushing of sequences is only useful in replication mode: in this case, sequences have to have the same starting point on all nodes. It's not useful in master-slave mode.
The loop in the script forces PostgreSQL to emit current value of all sequences in all databases in the master node to the transaction log so that it is propagated to the recovery target node.
We deploy these scripts into the $PGDATA directory.
Finally, we edit pgpool.conf.
recovery_1st_stage_command = 'copy-base-backup' recovery_2nd_stage_command = 'pgpool_recovery_pitr'
We have finished preparing online recovery by PITR.
This script starts up the remote host's postmaster process. pgpool-II executes it the following way.
% pgpool_remote_start remote_host remote_datadir remote_host: Hostname of a recovery target. remote_datadir: Database cluster path of a recovery target.
In this sample script, we start up the postmaster process over ssh. So you need to be able to connect over ssh without a password for it to work.
If you recover with PITR, you need to deploy a base backup. PostgreSQL will automatically start up doing a PITR recovery. Then it will accept connections.
#! /bin/sh DEST=$1 DESTDIR=$2 PGCTL=/usr/local/pgsql/bin/pg_ctl # Deploy a base backup ssh -T $DEST 'cd /data/; tar zxf pgsql.tar.gz' 2>/dev/null 1>/dev/null < /dev/null # Startup PostgreSQL server ssh -T $DEST $PGCTL -w -D $DESTDIR start 2>/dev/null 1>/dev/null < /dev/null &
PostgreSQL 7.4 does not have PITR. PostgreSQL 8.0 and 8.1 cannot force to switch transaction log. So rsync can be used to do online recovery. In the "sample" directory of pgpool-II's tarball, there is a recovery script named "pgpool_recovery". It uses the rsync command. pgpool-II calls the script with three arguments.
% pgpool_recovery datadir remote_host remote_datadir datadir: Database cluster path of a master node. remote_host: Hostname of a recovery target node. remote_datadir: Database cluster path of a recovery target node.
This script copies physical files with rsync over ssh. So you need to be able to connect over ssh without a password.
Note about rsync:
If you use pgpool_recovery, add the following lines into pgpool.conf.
recovery_1st_stage_command = 'pgpool_recovery' recovery_2nd_stage_command = 'pgpool_recovery'
In order to do online recovery, use the pcp_recovery_node command or pgpoolAdmin.
Note that you need to pass a large number to the first argument of pcp_recovery_node. It is the timeout parameter in seconds. If you use pgpoolAdmin, set "_PGPOOL2_PCP_TIMEOUT " parameter to a large number in pgmgt.conf.php.
You can update PostgreSQL on each node without stopping pgpool-II if pgpool-II operated in replication mode. Please note that active sessions from clients to pgpool-II will be disconnected while disconnecting and attaching DB nodes. Also please note that you cannot do major version up in the method described below (i.e. the version up should not require dump/restore).
Prepare online recovery.
Version up should perform nodes which are not master node first. Stop PostgreSQL on a non-master node. Pgpool-II will detect PostgreSQL termination and degenerate emitting logs below. At this point all sessions connected to pgpool-II disconnected.
2010-07-27 16:32:29 LOG: pid 10215: set 1 th backend down status 2010-07-27 16:32:29 LOG: pid 10215: starting degeneration. shutdown host localhost(5433) 2010-07-27 16:32:29 LOG: pid 10215: failover_handler: set new master node: 0 2010-07-27 16:32:29 LOG: pid 10215: failover done. shutdown host localhost(5433)
Version up PostgreSQL on the stopping node. You can overwrite old PostgreSQL, we recommend move old PostgreSQL somewhere so that you could recover it just in case however.
If you install new PostgreSQL in different location from the old one and do not want to update your recovery script, you need to match the path by using tools including symbolic link. If you choose to overwrite, you can skip following steps till installation of C function step. You can execute online recovery immediately.
Change installation directory of old PostgreSQL. Installting directory of PostgreSQL is supposed to be /usr/local/pgsql in following description.
$ mv /usr/local/pgsql /usr/local/pgsql-old
Create a symbolic link to the location where newer version of PostgreSQL installed. This allow you to continue to use command search path you currently use. Installing directory of newer PostgreSQL is supposed to be /usr/local/pgsql-new in following description.
$ ln -s /usr/local/pgsql-new /usr/local/pgsql
If database directory is located under older PostgreSQL installation directory, you should create or copy so that newer PostgreSQL can access it. We use symbolic link in the following example.
$ ln -s /usr/local/pgsql-old/data /usr/local/pgsql/data
Install C functions into PostgreSQL. "Installing C functions" section may help you. Because online recovery copies database cluster, the last step installing functions using psql is not necessary. Do make install.
Do online recovery. You are done with one node version up. To execute online recovery, you can use pcp_recovery_node or pgpoolAdmin.
Repeat steps above on each node. In the very last master node should be updated. You are done.
You can update standby PostgreSQL server without stopping pgpool-II.
The procedure to update standby PostgreSQL servers are same as the one of replication mode. Please refer to "Online recovery with Streaming Replication" to set up recovery_1st_stage_command and recovery_2nd_stage_command.
You cannot version up primary server without stopping pgpool-II. You need to stop pgpool-II while updating primary server. The procedure to update primary PostgreSQL server is same as the one standby server. The procedure to update primary PostgreSQL server is as follows:
To back up backend PostgreSQL servers, you can use physical backup, logical backup (pg_dump, pg_dumpall) and PITR in the same manner as PostgreSQL. Please note that using logical backup and PITR should be performed directory with PostgreSQL, rather than via pgpool-II to avoid errors caused by load_balance_mode and replicate_select.
If pgpool-II is operated in replication mode or master/slave mode, take a backup on one DB nodes in the cluster.
If you are using master/slave mode and asynchronous replication systems(Slony-I and streaming replication) and need the latest backup, you should take a backup on the master node.
pg_dump takes ACCESS SHARE lock on database. Commands taking ACCESS EXECUTE lock, such as ALTER TABLE, DROP TABLE, TRUNCATE, REINDEX, CLUSTER and VACUUM FULL will wait for the completion of pg_dump because of lock conflict. Also this may affect the primary node even if you are doing pg_dump on standby.
pgpool-II can run on a dedicated server, on the server where application server is running on or other servers. In this section we discuss how to make those deployments and pros and cons.
Pgpool-II is running on a dedicated server. It's simple and pgpool-II is not affected by other server softwares. Obvious cons is you need to buy more hardware. Also pgpool-II can be a single point of failure with this configuration (you can avoid this by enabling watchdog or using pgpool-HA described described below).
Deploying pgpool-II on a server where Apache, JBoss, Tomcat or other web server and application servers. Since communication between pgpool-II and web servers and application servers is within a local machine, socket communication can be faster than inter-sever communication. Also if you are using multiple web serves or application servers, you can avoid the single point of failure problem (in this case you must have identical pgpool.conf on each pgpool-II instance except the watchdog section).
We strongly recommend to enable watchdog to avoid following concerns in this configuration.
Running pgpool-II on the server as PostgreSQL is running on. You can avoid the single point of failure problem of pgpool-II with configuration. And obviously you do need to buy additional dedicated server. Problem with this configuration is, application need to aware of which DB server they should connect to. To solve the problem you can use virtual IP with watchdog or pgpool-HA.
Pgpool-HA is a high availability software for pgpool-II using heartbeat. Pgpool-HA is a sub-project of the pgpool project as well as pgpool-II. Pgpool-HA can be available from the pgpool development site as an open source software.
"Watchdog" is a sub process of pgpool-II, which adds high availability. This resolves the single point of failure by coordinating multiple pgpool-IIs. The watchdog system in pgpool-II V3.5 - is significantly enhanced and it now ensures the presence of a quorum at all time. This new addition to watchdog makes it more fault tolerant and robust in handling and guarding against the split-brain syndrome and network partitioning. However to ensure the quorum mechanism properly work, the number of pgpool-II nodes must be greater than or equal to 3 or more and the number must be odd. Watchdog consists of the following features.
Watchdog lifecheck is the sub-component of watchdog to monitor the health of pgpool-II nodes participating in the watchdog cluster to provide the high availability. Traditionally pgpool-II watchdog provides two methods of remote node health checking. "heartbeat" and "query" mode. The watchdog in pgpool-II V3.5 - adds a new "external" health checking method, which enables to hook an external third party health checking system with pgpool-II watchdog. See the section integrating external lifecheck with watchdog for details on how to hook a third party system with watchdog. Apart from remote node health checking watchdog lifecheck can also check the health of node it is installed on by monitoring the connection to upstream servers.
Also watchdog monitors connections to upstream servers (application servers etc.) from the pgpool-II, and checks whether the pgpool-II can serves to the servers. If the monitoring fails, watchdog treats the pgpool-II as down.
Watchdog coordinates multiple pgpool-IIs by exchanging information with each other.
At start up watchdog verifies the pgpool-II configuration of the local node for the consistency with the configurations on the master watchdog node. This eliminates the likelihood of undesired behavior that can happen because of different configuration on different pgpool-II nodes.
When a fault of pgpool-II is detected, watchdog notifies the other watchdogs of it. If this is the active pgpool-II, watchdogs decides the new active pgpool-II by voting and change active/standby state.
When a standby pgpool-II server promotes to active, the new active server brings up virtual IP interface. Meanwhile, the previous active server brings down the virtual IP interface. This enables the active pgpool-II to work using the same IP address even when servers are switched.
When broken server recovers or new server is attached, the watchdog process notifies the other watchdog process along with information of the new server, and the watchdog process receives information on the active server and other servers. Then, the attached server is registered as a standby.
Figure below describes how pgpool-II and watchdog process is configured.
Watchdog process starts/stops automatically as sub-processes of pgpool-II, therefore there is no dedicated command to start/stop it.
Watchdog requires root privilege for controling the virtual IP interface. One method is to start pgpool-II by root privilege. However, for security reason, to set custom commands to if_up_cmd, if_up_cmd, if_up_cmd using sudo or setuid is recommended method.
Watchdog's built-in life-checking starts after all of the pgpool-IIs has started. This doesn't start if not all "other" nodes are alive Until this, failover of the virtual IP never occurs.
Watchdog configuration parameters are described in pgpool.conf. There is sample configuration in WATCHDOG section in pgpool.conf.sample file.
All following options are required to be specified in watchdog process.
If on, activates watchdog. Default is off.
You need to restart pgpool-II if you change this value.
Specifies the hostname or IP address of pgpool-II server. This is used for sending/receiving queries and packets, and also as identifier of watchdog.
You need to restart pgpool-II if you change this value.
Specifies the port number for watchdog communication.
You need to restart pgpool-II if you change this value.
This option specifies the authentication key used in watchdog communication. All the pgpool-II must have the same key. Packets from watchdog of wrong key will be rejects. This authentication is applied also for heatrbeat singals if lifecheck method is heartbeat mode.
Since pgpool-II V3.5 - wd_authkey is also used to authenticate the watchdog IPC clients. All clients communicating with pgpool-II watchdog process needs to provide this wd_authkey value for "IPCAuthKey" key in the JSON data of the command.
If this is empty (default), watchdog IPC and watchdog cluster authentication is disabled.
You need to restart pgpool-II if you change this value.
The list of trusted servers to check the up stream connections. Each server is required to respond to ping. Specify a comma separated list of servers such as "hostA,hostB,hostC". If none of the server are pingable, watchdog regards it as failure of the pgpool-II. Therefore, it is recommended to specify multiple servers.
If this option is empty, watchdog doesn't check up stream connections.
You need to restart pgpool-II if you change this value.
This parameter specifies a path of ping command for monitoring connection to the upper servers. Set the only path such as "/bin".
You need to restart pgpool-II if you change this value.
Configuration about virtual IP interface control
Specifies the virtual IP address (VIP) of pgpool-II that is connected from client servers (application servers etc.). When a pgpool-II is switched from standby to active, the pgpool-II takes over this VIP. If this option is emply, virtual IP is never brought up.
You need to restart pgpool-II if you change this value.
This parameter specifies a path of a command to switch the IP address. Set the only path such as "/sbin".
You need to restart pgpool-II if you change this value.
This parameter specifies a command to bring up the virtual IP. Set the command and parameters such as "ip addr add $_IP_$/24 dev eth0 label eth0:0" $_IP_$ is replaced by the IP address specified in delegate_IP.
You need to restart pgpool-II if you change this value.
This parameter specifies a command to bring down the virtual IP. Set the command and parameters such as "ip addr del $_IP_$/24 dev eth0"
You need to restart pgpool-II if you change this value.
This parameter specifies a path of a command to send an ARP request after the virtual IP is switched. Set the only path such as "/usr/sbin".
You need to restart pgpool-II if you change this value.
This parameter specifies a command to send an ARP request after the virtual IP is switched. Set the command and parameters such as "arping -U $_IP_$ -w 1". $_IP_$ is replaced by the IP address specified in delegate_IP.
You need to restart pgpool-II if you change this value.
Configuration about behavior when pgpool-II escalates to active (virtual IP holder)
If this is on, watchdog clears all the query cache in the shared memory when pgpool-II escaltes to active. This prevents the new active pgpool-II from using old query caches inconsistence to the old active. Default is on.
This works only if memqcache_method is 'shmem'.
Watchdog executes this command on the node that is escalated to the master watchdog.
This command is executed just before bringing up the virtual/floating IP if that is configured on the node.
Watchdog executes this command on the master pgpool-II watchdog node when that node resigns from the master node responsibilities. A master watchdog node can resign from being a master node, when the master node pgpool-II shuts down, detects a network blackout or detects the lost of quorum.
This command is executed before bringing down the virtual/floating IP address if it is configured on the watchdog node
Watchdog checks pgpool-II status periodically. This is called "life check".
This parameter specifies the method of life check. This can be either of 'heartbeat' (default), 'query' or 'external'.
In 'heartbeat' mode, watchdog sends heartbeat singals (UDP packets) periodically to other pgpool-II. Watchdog also receives the signals from other pgpool-II. If there are no signal for a certain period, watchdog regards is as failure of the pgpool-II.
In 'query' mode, watchdog sends monitoring queries to other pgpool-II and checks the response.
CAUTION: In query mode, you need to set num_init_children large enough if you plan to use watchdog. This is because the watchdog process connects to pgpool-II as a client.
The 'external' mode (V3.5 -), disables the built in lifecheck of pgpool-II watchdog and relies on external system to provide node health checking of local and remote watchdog nodes.
You need to restart pgpool-II if you change this value.
Specify a comma separated list of network device names, to be monitored by the watchdog process for the network link state. If all network interfaces in the list become inactive (disabled or cable unplugged), the watchdog will consider it as a complete network failure and the pgpool-II node will commit the suicide. Specifying an empty '' list disables the network interface monitoring. Setting it to 'any' enables the monitoring on all available network interfaces except the loopback. Default is '' empty list (monitoring disabled).
You need to restart pgpool-II if you change this value.
This parameter specifies the interval between life checks of pgpool-II in second. (A number greater than or equal to 1) Default is 10.
You need to restart pgpool-II if you change this value.
This parameter can be used to elevate the local watchdog node priority in the elections to select master watchdog node. The node with the higher wd_priority value will get selected as master watchdog node when cluster will be electing its master node at cluster startup or in the event of old master watchdog node failure
You need to restart pgpool-II if you change this value.
The directory where the UNIX domain socket accepting pgpool-II watchdog IPC
connections will be created. Default is '/tmp'
. Be
aware that this socket might be deleted by a cron job. We recommend to
set this value to '/var/run'
or such directory.
This parameter can only be set at server start.
This option specifies the port number to receive heartbeat signals. Default is 9694. This works only heartbeat mode.
You need to restart pgpool-II if you change this value.
This option specifies the interval time (sec.) of sending heartbeat signals. Default is 2. This works only heartbeat mode.
You need to restart pgpool-II if you change this value.
If there are no heartbeat signal for the period specified by this option, watchdog regards it as failure of the remote pgpool-II. Default is 30. This works only heartbeat mode.
You need to restart pgpool-II if you change this value.
This option specifies the destination of heartbeat signals by IP address or hostname. You can use multiple destination. The number at the end of the parameter name is referred as "destination number", and it starts from 0. This works only heartbeat mode.
You need to restart pgpool-II if you change this value.
This option specifies the port number of destination of heartbeat signals which is specified by heartbeat_destinationX. This is usually the same value as wd_heartbeat_port You must use another value if the port number is unusable on a certain host or there are more than two pgpool-IIs in a host. The number at the end of the parameter name is referred as "destination number", and it starts from 0. This works only heartbeat mode.
You need to restart pgpool-II if you change this value.
This option specifies the network device name for sending heartbeat signals to destination specified by heartbeat_destinationX. You can use the same device for different distinations. The number at the end of the parameter name is referred as "destination number", and it starts from 0. This works only heartbeat mode. This is ignored when the value is empty. In addition, this works only when pgpool-II has root privilege and are running on Linux, because this uses SO_BINDTODEVICE socket option.
You need to restart pgpool-II if you change this value.
The times to retry a failed life check of pgpool-II. (A number greater than or equal to 1) Default is 3. This works only query mode.
You need to restart pgpool-II if you change this value.
Actual query to check pgpool-II. Default is "SELECT 1". This works only query mode.
You need to restart pgpool-II if you change this value.
The database name connected for checking pgpool-II. Default is "template1". This works only query mode.
The user name to check pgpool-II. This user must exist in all the PostgreSQL backends. Default is "nobody". This works only query mode.
The password of the user to check pgpool-II. Default is "". This works only query mode.
Specifies the hostname pgpool-II server to be monitored. This is used for sending/receiving queries and packets, and also as identifier of watchdog. The number at the end of the parameter name is referred as "server id", and it starts from 0.
You need to restart pgpool-II if you change this value.
Specifies the port number for pgpool service of pgpool-II server to be monitored. In query mode, the queries specified in wd_lifecheck_query is sent to this port. The number at the end of the parameter name is referred as "server id", and it starts from 0.
You need to restart pgpool-II if you change this value.
Specifies the port number for watchdog on pgpool-II server to be monitored. The number at the end of the parameter name is referred as "server id", and it starts from 0.
You need to restart pgpool-II if you change this value.
pgpool-II watchdog process uses the BSD sockets for communicating with all pgpool-II processes and the same BSD socket can be used by any third party system to provide the lifecheck function for local and remote pgpool-II watchdog nodes. The BSD socket file name for IPC is constructed by appending pgpool-II wd_port after "s.PGPOOLWD_CMD." string and the socket file is placed in the pgpool-II wd_ipc_socket_dir directory.
The watchdog IPC command packet consists of three fields. Below table details the message fields and description
Field | Type | Description |
---|---|---|
TYPE | BYTE1 | Command Type |
LENGTH | INT32 Network byte order | The length of data to follow |
DATA | DATA in JSON format | Command data in JSON format |
The watchdog IPC command result packet consists of three fields. Below table details the message fields and description
Field | Type | Description |
---|---|---|
TYPE | BYTE1 | Command Type |
LENGTH | INT32 Network byte order | The length of data to follow |
DATA | DATA in JSON format | Command result data in JSON format |
The first byte of the IPC command packet sent to watchdog process and the result returned by watchdog process is identified as the command or command result type. The below table lists all valid types and their meanings
-- The example JSON data contained in "NODES LIST DATA" { "NodeCount":3, "WatchdogNodes": [ { "ID":0, "State":1, "NodeName":"Linux_ubuntu_9999", "HostName":"watchdog-host1", "DelegateIP":"172.16.5.133", "WdPort":9000, "PgpoolPort":9999 }, { "ID":1, "State":1, "NodeName":"Linux_ubuntu_9991", "HostName":"watchdog-host2", "DelegateIP":"172.16.5.133", "WdPort":9000, "PgpoolPort":9991 }, { "ID":2, "State":1, "NodeName":"Linux_ubuntu_9992", "HostName":"watchdog-host3", "DelegateIP":"172.16.5.133", "WdPort":9000, "PgpoolPort":9992 } ] } -- Note that ID 0 is always reserved for local watchdog nodeAfter getting the configured watchdog nodes information from the watchdog the external lifecheck system can proceed with health checking of watchdog nodes, and when it detects some status change of any node it can inform that to watchdog using the "NODE STATUS CHANGE" IPC messages of watchdog. The data in the message should contain the JSON with the node ID of the node whose status is changed (The node ID must be same as returned by watchdog for that node in WatchdogNodes list) and the new status of node.
-- The example JSON to inform pgpool-II watchdog about health check failed on node with ID 1 will look like { "NodeID":1, "NodeStatus":1, "Message":"optional message string to log by watchdog for this event" "IPCAuthKey":"wd_authkey configuration parameter value" } -- NodeStatus values meanings are as follows NODE STATUS DEAD = 1 NODE STATUS ALIVE = 2
PCP commands are UNIX commands which manipulate pgpool-II via the network. Please note that the parameter format for all PCP commands has been changed since pgpool-II 3.5
pcp_node_count | retrieves the number of nodes |
---|---|
pcp_node_info | retrieves the node information |
pcp_watchdog_info V3.3 - | retrieves the watchdog information |
pcp_proc_count | retrieves the process list |
pcp_proc_info | retrieves the process information |
pcp_pool_status V3.1 - | retrieves parameters in pgpool.conf |
pcp_detach_node | detaches a node from pgpool-II |
pcp_attach_node | attaches a node to pgpool-II |
pcp_promote_node V3.1 - | promote a new master node to pgpool-II |
pcp_stop_pgpool | stops pgpool-II |
PCP user names and passwords must be declared in
pcp.conf
in $prefix/etc
directory. -F
option can be used when starting pgpool-II
if pcp.conf
is placed somewhere else.
The file .pcppass in a user's home directory or the file referenced by environment variable PCPPASSFILE can contain passwords to be used if no password has been specified for the pcp connection.
This file should contain lines of the following format:/
hostname:port:username:password
(You can add a reminder comment to the file by copying the line above and preceding it with #.) Each of the first three fields can be a literal value, or *, which matches anything. The password field from the first line that matches the current connection parameters will be used. (Therefore, put more-specific entries first when you are using wildcards.) If an entry needs to contain : or \, escape this character with \. A host name of localhost matches both TCP (host name localhost) and Unix domain socket connections coming from the local machine.
The permissions on .pcppass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pcppass. If the permissions are less strict than this, the file will be ignored.
There are some arguments common to all PCP commands. Most of these are for authentication and the rest are about verbose mode, debug message, and so on.
e.g.) $ pcp_node_count -h localhost -p 9898 -u postgres -w -d -v
All PCP commands display the results to the standard output.
pcp_node_count [options...]
Displays the total number of nodes defined in pgpool.conf
. It does
not distinguish between nodes status, ie attached/detached. ALL nodes are counted.
See common options.
pcp_node_info [options...] [node_id]
Displays the information on the given node ID.
$ pcp_node_info -h localhost -U postgres 0 host1 5432 1 1073741823.500000
The result is in the following order:
Status is represented by a digit from [0 to 3].
The load balance weight is displayed in normalized format.
The --verbose
option can help understand the output. For example:
$ pcp_node_info --verbose -h localhost -U postgres 0 Hostname: host1 Port : 5432 Status : 1 Weight : 0.5
pcp_watchdog_info [options...] [watchdog_id]
Displays the watchdog status of the pgpool-II.
watchdog_id
is the index of watchdog node to get information for.
If this is omitted, display the watchdog status of all watchdog nodes in the cluster.
watchdog_id
= 0 is reserved for local pgpool-II node,
So the index of remote watchdog nodes starts from 1.
Note that since the index numbering in pcp_watchdog_info utility starts from 1 while
the pgpool.conf file uses 0 based indexing to define remote watchdog nodes, so you will require
to add one to the other watchdog index to get its information using pcp_watchdog_info utility.
For example, to get the information of first remote watchdog node configured with prefix 0
defined by other_pgpool_hostname0 parameters you will use watchdog_id
= 1 for pcp_watchdog_info.
$ pcp_watchdog_info -h localhost -u postgres 3 NO Linux_host1.localdomain_9991 host1 Linux_host1.localdomain_9991 host1 9991 9001 7 STANDBY Linux_host2.localdomain_9992 host2 9992 9002 4 MASTER Linux_host3.localdomain_9993 host3 9993 9003 7 STANDBY
The result is in the following order:
The first output line describes the watchdog cluster information:
Next is the list of watchdog nodes:
$ pcp_watchdog_info -h localhost -v -u postgres Watchdog Cluster Information Total Nodes : 3 Remote Nodes : 2 Quorum state : QUORUM EXIST Alive Remote Nodes : 2 VIP up on local node : NO Master Node Name : Linux_host2.localdomain_9992 Master Host Name : localhost Watchdog Node Information Node Name : Linux_host1.localdomain_9991 Host Name : host1 Delegate IP : 192.168.1.10 Pgpool port : 9991 Watchdog port : 9001 Node priority : 1 Status : 7 Status Name : STANDBY Node Name : Linux_host2.localdomain_9992 Host Name : host2 Delegate IP : 192.168.1.10 Pgpool port : 9992 Watchdog port : 9002 Node priority : 1 Status : 4 Status Name : MASTER Node Name : Linux_host3.localdomain_9993 Host Name : host3 Delegate IP : 192.168.1.10 Pgpool port : 9993 Watchdog port : 9003 Node priority : 1 Status : 7 Status Name : STANDBY
pcp_proc_count [options...]
Displays the list of pgpool-II children process IDs. If there is more than one process, IDs will be delimited by a white space.
See common options.
pcp_proc_info [options...] [processid]
Displays the information on the given pgpool-II child process ID.
$ pcp_proc_info -h localhost -p 9898 -U postgres 3815 postgres_db postgres 1150769932 1150767351 3 0 1 1467 1 postgres_db postgres 1150769932 1150767351 3 0 1 1468 1
The result is in the following order:
If there is no connection to the backends, nothing will be displayed. If there are multiple connections, one connection's information will be displayed on each line multiple times. Timestamps are displayed in EPOCH format.
The --verbose option can help understand the output. For example:
$ pcp_proc_info --verbose -U postgres 3815 Database : postgres_db Username : postgres Start time : 1150769932 Creation time: 1150767351 Major : 3 Minor : 0 Counter : 1 PID : 1467 Connected : 1 Database : postgres_db Username : postgres Start time : 1150769932 Creation time: 1150767351 Major : 3 Minor : 0 Counter : 1 PID : 1468 Connected : 1
pcp_pool_status [options...]
Displays the parameter values as defined in pgpool.conf.
See common options.
$ pcp_pool_status -h localhost -U postgres name : listen_addresses value: localhost desc : host name(s) or IP address(es) to listen to name : port value: 9999 desc : pgpool accepting port number name : socket_dir value: /tmp desc : pgpool socket directory name : pcp_port value: 9898 desc : PCP port # to bind
pcp_detach_node [options...] [node_id] [gracefully]
Detaches the given node from pgpool-II. Exisiting connections to pgpool-II are forced to be disconnected.
pcp_attach_node [options...] [node_id]
Attaches the given node to pgpool-II.
pcp_promote_node [options...] [node_id] [gracefully]
Promotes the given node as new master to pgpool-II. In master/slave streaming replication only. Please note that this command does not actually promote standby PostgreSQL backend: it just changes the internal status of pgpool-II and trigger failover and users have to promote standby PostgreSQL outside pgpool-II.
pcp_stop_pgpool [options...] [mode]
Terminate the pgpool-II process.
pcp_recovery_node [options...] [node_id]
Attaches the given backend node with recovery.
pgpoo_adm is a set of extensions to allow SQL access to pcp commands (actually, pcp libraries). It uses foreign data wrapper as shown in the diagram below.
It is possible to call the functions from either via pgpool-II (1) or via PostgreSQL (2). In case (1), pgpool-II accepts query from user (1), then forward to PostgreSQL (3). PostgreSQL connects to pgpool-II (5) and pgpool-II reply back to PostgreSQL with the result (3). PostgreSQL returns the result to pgpool-II (5) and pgpool-II fowards the data to the user (6).
In case (2), PostgreSQL accepts query from user (2). PostgreSQL connects to pgpool-II (5) and pgpool-II reply back to PostgreSQL with the result (3). PostgreSQL replies back the data to the user (6).
There are two forms to call pgpool_adm functions: first form accepts pgpool-II host name (or IP address), pcp port number, pcp user name, its password and another parameters.
In the second form, pgpool-II server name is required. The server name must be already defined using "CREATE FOREIGN SERVER" command of PostgreSQL. The pcp port number is hard coded as 9898, the pcp user name is assumes to be same as caller's PostgreSQL user name. password is extraced from $HOME/.pcppass.
pgpool_adm is an extension and should be installed on all PostgreSQL servers.
$ cd src/sql/pgpool_adm $ make $ make install
Then issue following SQL command for every database you want to access.
$ psql ... $ CREATE EXTENSION pgpool_adm
pcp_node_info | retrieves the node information |
---|---|
pcp_pool_status | retrieves parameters in pgpool.conf |
pcp_node_count | retrieves the number of nodes |
pcp_attach_node | attaches a node to pgpool-II |
pcp_detach_node | detaches a node to pgpool-II |
pcp_node_info(integer node_id, text host, integer port, text username, text password, OUT status text, OUT weight float4) returns record
pcp_node_info(integer node_id, text pcp_server, OUT status text, OUT weight float4) returns record
Retrieves the node information. See pcp_node_info command for more details.
Here is an example output.
test=# SELECT * FROM pcp_node_info(0,'',11001,'t-ishii','t-ishii'); host | port | status | weight ------+-------+-------------------+-------- /tmp | 11002 | Connection in use | 0 (1 row)
pcp_pool_status(text host, integer port, text username, text password) returns record
pcp_pool_status(text pcp_server) returns record
Retrieves parameters in pgpool.conf. See pool_status for more details.
Here is an example output.
test=# SELECT * FROM pcp_pool_status('localhost',11001,'t-ishii','t-ishii') WHERE item ~ 'backend.*0'; item | value | description -------------------------+------------------------------------------------+------------------------------- backend_hostname0 | /tmp | backend #0 hostname backend_port0 | 11002 | backend #0 port number backend_weight0 | 0.500000 | weight of backend #0 backend_data_directory0 | /home/t-ishii/work/pgpool-II/current/aaa/data0 | data directory for backend #0 backend_status0 | 2 | status of backend #0 backend_flag0 | ALLOW_TO_FAILOVER | backend #0 flag (6 rows)
pcp_node_count(integer node_id, text host, integer port, text username, text password, OUT node_count integer) returns integer
pcp_node_count(integer node_id, OUT node_count integer) returns record
Retrieves the number of DB nodes. See pcp_node_count command for more details.
Here is an example output.
test=# SELECT * FROM pcp_node_count('localhost',11001,'t-ishii','t-ishii'); node_count ------------ 2 (1 row)
pcp_attach_node(integer node_id, text host, integer port, text username, text password, OUT node_attached boolean) returns boolean
pcp_attach_node(integer node_id, text pcp_server, OUT node_attached boolean) returns boolean
attaches a node to pgpool-II. See pcp_attach_node command for more details.
Here is an example output.
test=# SELECT * FROM pcp_attach_node(1,'localhost',11001,'t-ishii','t-ishii'); node_attached --------------- t (1 row)
pcp_detach_node(integer node_id, boolean gracefully, text host, integer port, text username, text password, OUT node_detached boolean) returns boolean
pcp_detach_node(integer node_id, boolean gracefully, text pcp_server, OUT node_detached boolean) returns boolean
Detaches a node to pgpool-II and initiate fail over. See pcp_detach_node for more details.
Here is an example output.
test=# SELECT * FROM pcp_detach_node(1, 'false', 'localhost',11001,'t-ishii','t-ishii'); node_detached --------------- t (1 row)
This section describes problems and their workarounds while you are using pgpool-II.
Pgpool-II's health checking feature detects DB nodes failure.
2010-07-23 16:42:57 ERROR: pid 20031: health check failed. 1 th host foo at port 5432 is down 2010-07-23 16:42:57 LOG: pid 20031: set 1 th backend down status 2010-07-23 16:42:57 LOG: pid 20031: starting degeneration. shutdown host foo(5432) 2010-07-23 16:42:58 LOG: pid 20031: failover_handler: set new master node: 0 2010-07-23 16:42:58 LOG: pid 20031: failover done. shutdown host foo(5432)
The log shows that the DB node 1 (host foo) goes down and disconnected (shutdown) from pgpool, and then that DB node 0 becomes new master. Check DB node 1 and remove the cause of failure. After that perform an online recovery against DB node 1 if possible.
2010-07-26 18:43:24 LOG: pid 24161: ProcessFrontendResponse: failed to read kind from frontend. frontend abnormally exited
This log indicates that the frontend program didn't disconnect properly from pgpool-II. The possible causes are: bugs of client applications, forced termination (kill) of a client application, or temporary network failure. This kind of events don't lead to a DB destruction or data consistency problem. It's only a warning about a protocol violation. It is advised that you check the applications and networks if the message keeps on occurring.
It is possible that you get this error when pgpool-II operates in replication mode.
2010-07-22 14:18:32 ERROR: pid 9966: kind mismatch among backends. Possible last query was: "FETCH ALL FROM c;" kind details are: 0[T] 1[E: cursor "c" does not exist]
Pgpool-II waits for responses from the DB nodes after sending an SQL command to them. This message indicates that not all DB nodes returned the same kind of response. You'll get the SQL statement which possibly caused the error after "Possible last query was:". Then the kind of response follows. If the response indicates an error, the error message from PostgreSQL is shown. Here you see "0[T]" displaying the DB node responses: "0[T]" (starting to send row description), and "1[E" indicates that DB node 1 returns an error with message "cursor "c" does not exist", while DB node 0 sends a row description.
Caution: You will see this error when operating in master/slave mode as well. For example, even in the master/slave mode, SET command will be basically sent to all DB nodes to keep all the DB nodes in the same state.
Check the databases and re-sync them using online recovery if you find that they are out of sync.
In replication mode, pgpool-II detects a different number of INSERT/UPDATE/DELETE rows on affected nodes.
2010-07-22 11:49:28 ERROR: pid 30710: pgpool detected difference of the number of inserted, updated or deleted tuples. Possible last query was: "update t1 set i = 1;" 2010-07-22 11:49:28 LOG: pid 30710: ReadyForQuery: Degenerate backends: 1 2010-07-22 11:49:28 LOG: pid 30710: ReadyForQuery: Affected tuples are: 0 1
In the example above, the returned number of updated rows by "update t1 set i = 1" was different among DB nodes. The next line indicates that DB 1 got degenerated (disconnected) as a consequence, and that the number of affected rows for DB node 0 was 0, while for DB node 1 that was 1.
Stop the DB node which is suspected of having wrong data and do an online recovery.
pgpool-II 2.3.2 or later supports large object replication if the backend is PostgreSQL 8.1 or later. For this, you need to enable lobj_lock_table directive in pgpool.conf. Large object replication using backend function lo_import is not supported, however.
Creating/inserting/updating/deleting temporary tables are always executed on the master(primary). With pgpool-II 3.0 or later, SELECT on these tables is executed on master as well. However if the temporary table name is used as a literal in SELECT, there's no way to detect it, and the SELECT will be load balanced. That will trigger a "not found the table" error or will find another table having same name. To avoid the problem, use /*NO LOAD BALANCE*/ SQL comment.
Sample SELECT which causes a problem: SELECT 't1'::regclass::oid;
psql's \d command uses literal table names. pgpool-II 3.0 or later checks if the SELECT includes any access to system catalogs and always send these queries to the master. Thus we avoid the problem.
There is no guarantee that any data provided using a context-dependent mechanism (e.g. random number, transaction ID, OID, SERIAL, sequence), will be replicated correctly on multiple backends.
For SERIAL, enabling insert_lock will help replicating data. insert_lock also helps SELECT setval() and SELECT nextval().
In pgpool-II 2.3 or later, INSERT/UPDATE using CURRENT_TIMESTAMP, CURRENT_DATE, now() will be replicated correctly. INSERT/UPDATE for tables using CURRENT_TIMESTAMP, CURRENT_DATE, now() as their DEFAULT values will also be replicated correctly. This is done by replacing those functions by constants fetched from master at query execution time. There are a few limitations however:
CREATE TABLE rel1( d1 date DEFAULT CURRENT_DATE + 1 )is treated the same as:
CREATE TABLE rel1( d1 date DEFAULT CURRENT_DATE )
pgpool-II 3.1 or later handles these cases correctly. Thus the column "d1" will have tomorrow as the default value. However this enhancement does not apply if extended protocols(used in JDBC, PHP PDO for example) or PREPARE are used.
Please note that if the column type is not a temporal one, rewriting is not performed. Such example:
foo bigint default (date_part('epoch'::text,('now'::text)::timestamp(3) with time zone) * (1000)::double precision)
CREATE TABLE rel1( c1 int, c2 timestamp default now() )We can replicate
INSERT INTO rel1(c1) VALUES(1)since this turn into
INSERT INTO rel1(c1, c2) VALUES(1, '2009-01-01 23:59:59.123456+09')However,
INSERT INTO rel1(c1) SELECT 1cannot to be transformed, thus cannot be properly replicated in the current implementation. Values will still be inserted, with no transformation at all.
Tables created by CREATE TEMP TABLE
will be deleted at the end of
the session by specifying DISCARD ALL in reset_query_list if you are using
PostgreSQL 8.3 or later.
For 8.2.x or earlier, CREATE TEMP TABLE
will not be
deleted after exiting a session. It is because of the connection
pooling which, from PostgreSQL's backend point of view, keeps the
session alive. To avoid this, you must explicitly drop the
temporary tables by issuing DROP TABLE
, or use CREATE TEMP
TABLE ... ON COMMIT DROP
inside the transaction block.
Here are the queries which cannot be processed by pgpool-II
pgpool-II does not translate between different multi-byte characters. The encoding for the client, backends must be the same.
pgpool-II cannot process multi-statement queries.
libpq
is linked while building pgpool-II. libpq
version must be 3.0. Building pgpool-II with libpq version 2.0 will
fail.
A tutorial for pgpool-II is available.