pg_receivexlog
pg_receivexlog — приём журналов транзакций с сервера Postgres Pro
Синтаксис
pg_receivexlog [параметр...]
Описание
Утилита pg_receivexlog предназначена для приёма журнала транзакций от работающего кластера Postgres Pro. Журнал транзакций передаётся по протоколу потоковой репликации и записывается в локальный каталог. Затем этот каталог можно использовать в качестве архива для восстановления состояния на момент времени (см. Раздел 24.3).
pg_receivexlog принимает журнал транзакций в реальном времени по мере того, как он генерируется на сервере, и не ждёт завершения сегментов, как это делает archive_command. Поэтому pg_receivexlog можно использовать, не устанавливая archive_timeout.
В отличие от приёмника WAL, работающего на ведомом сервере Postgres Pro, pg_receivexlog по умолчанию сохраняет на диск данные WAL, только когда файл WAL закрывается. Для сохранения данных WAL в реальном времени необходимо использовать ключ --synchronous. Так как приёмник pg_receivexlog не применяет WAL, важно не допустить, чтобы он стал синхронным ведомым сервером, когда параметр synchronous_commit равен remote_apply. Если это произойдёт, он будет выглядеть как ведомый, который никогда не может нагнать ведущего, что приведёт к блокированию фиксации транзакций. Чтобы это предотвратить, нужно либо установить подходящее значение параметра synchronous_standby_names, либо задать для pg_receivexlog такое имя приложения (application_name), которое не соответствует установленному имени, либо выбрать для synchronous_commit значение, отличное от remote_apply.
Журнал транзакций передаётся через обычное подключение к Postgres Pro, с использованием протокола репликации. Подключение должен устанавливать суперпользователь или пользователь с правом REPLICATION (см. Раздел 20.2), а на сервере в pg_hba.conf должно разрешаться подключение для репликации. Кроме того, параметр max_wal_senders на сервере должен быть достаточно большим, чтобы можно было создать ещё один сеанс для передачи потока.
Если подключение разорвалось или его c самого начала не удаётся установить с некритической ошибкой, pg_receivexlog будет бесконечно повторять попытки подключения и восстановит передачу, как только сможет. Чтобы отменить это поведение, воспользуйтесь параметром -n.
Параметры
-Dкаталог--directory=каталогКаталог, в который будут записываться данные.
Этот параметр является обязательным.
--if-not-existsНе выдавать ошибку, когда указан параметр
--create-slotи слот с заданным именем уже существует.-n--no-loopНе повторять цикл при ошибках подключения, а сразу завершать работу, возвращая ошибку.
-sinterval--status-interval=intervalУказывает интервал в секундах между отправкой пакетов статуса, отправляемых на сервер. Это позволяет упростить мониторинг прогресса. Чтобы выключить периодическое обновление статуса, необходимо установить значение в ноль. При этом обновление будет отправляться по запросу сервера для избежания отсоединения по истечению времени. Значение по умолчанию составляет 10 секунд.
-Sимя_слота--slot=имя_слотаУказать pg_receivexlog использовать существующий слот репликации (см. Подраздел 25.2.6). Когда задан этот параметр, pg_receivexlog будет сообщать серверу текущую позицию, отмечая, какой сегмент был сохранён на диске, чтобы сервер мог удалить этот сегмент, если он больше не нужен.
Когда клиент репликации pg_receivexlog настроен на сервере как синхронный резервный сервер, для используемого слота репликации серверу будет передаваться позиция сохранённых данных, но только когда файл WAL закрывается. Таким образом, в такой конфигурации транзакции на главном сервере будут ожидать завершения продолжительное время и по сути будут работать неудовлетворительно. Чтобы эта конфигурация работала корректно, нужно дополнительно указать параметр
--synchronous(см. ниже).--synchronousСохранять данные WAL на диск сразу после того, как они были получены. Также передавать пакет состояния сразу после сохранения, вне зависимости от
--status-interval.Этот параметр следует указывать, если клиент репликации pg_receivexlog настроен на сервере как синхронный резервный, чтобы обеспечить своевременную передачу ответа серверу.
-v--verboseВключает режим подробных сообщений.
Далее описаны параметры управления подключением.
-dстрока_подключения--dbname=строка_подключенияУказывает параметры подключения к серверу в формате строки подключения. См. Подраздел 30.1.1 для более подробной информации.
Параметр называется
--dbnameдля согласованности с другими клиентскими приложениями, но так как pg_receivexlog не подключается к какой-либо конкретной базе, это имя в строке подключения игнорируется.-hсервер--host=серверУказывает имя компьютера, на котором работает сервер. Если значение начинается с косой черты, оно определяет каталог Unix-сокета. Значение по умолчанию берётся из переменной окружения
PGHOST, если она установлена. В противном случае выполняется подключение к Unix-сокету.-pпорт--port=портУказывает TCP-порт или расширение файла локального Unix-сокета, через который сервер принимает подключения. Значение по умолчанию определяется переменной окружения
PGPORT, если она установлена, либо числом, заданным при компиляции.-Uимя_пользователя--username=имя_пользователяИмя пользователя, под которым производится подключение.
-w--no-passwordНе выдавать запрос на ввод пароля. Если сервер требует аутентификацию по паролю и пароль не доступен с помощью других средств, таких как файл
.pgpass, попытка соединения не удастся. Этот параметр может быть полезен в пакетных заданиях и скриптах, где нет пользователя, который вводит пароль.-W--passwordПринудительно запрашивать пароль перед подключением к базе данных.
Это несущественный параметр, так как pg_receivexlog запрашивает пароль автоматически, если сервер проверяет подлинность по паролю. Однако чтобы понять это, pg_receivexlog лишний раз подключается к серверу. Поэтому иногда имеет смысл ввести
-W, чтобы исключить эту ненужную попытку подключения.
pg_receivexlog может выполнить одно из двух действий в отношении слотов физической репликации:
--create-slotСоздать слот физической репликации с именем, заданным аргументом
--slot, и завершиться.--drop-slotУдалить слот репликации с именем, заданным аргументом
--slot, и завершиться.
Другие флаги:
-V--versionСообщить версию pg_receivexlog и завершиться.
-?--helpПоказать справку по аргументам командной строки pg_receivexlog и завершиться.
Переменные окружения
Как и большинство других утилит Postgres Pro, приложение также использует переменные окружения, поддерживаемые libpq (см. Раздел 30.14).
Замечания
Применяя pg_receivexlog вместо archive_command в качестве основного способа резервного копирования WAL, настоятельно рекомендуется использовать слоты репликации. В противном случае сервер вполне может переписать или удалить файлы журнала транзакций, прежде чем они будут скопированы, так как он не получает никакой информации, через archive_command или слоты репликации, о том, как проходит архивация потока WAL. Учтите, однако, что при использовании слота репликации может заполниться всё место на диске, если принимающая сторона не будет успевать принимать данные WAL.
Примеры
Следующая команда принимает журнал транзакций с сервера mydbserver и сохраняет его в локальном каталоге /usr/local/pgsql/archive:
$pg_receivexlog -h mydbserver -D /usr/local/pgsql/archive
См. также
pg_basebackuppg_receivexlog
pg_receivexlog — stream transaction logs from a Postgres Pro server
Synopsis
pg_receivexlog [option...]
Description
pg_receivexlog is used to stream the transaction log from a running Postgres Pro cluster. The transaction log is streamed using the streaming replication protocol, and is written to a local directory of files. This directory can be used as the archive location for doing a restore using point-in-time recovery (see Section 24.3).
pg_receivexlog streams the transaction log in real time as it's being generated on the server, and does not wait for segments to complete like archive_command does. For this reason, it is not necessary to set archive_timeout when using pg_receivexlog.
Unlike the WAL receiver of a Postgres Pro standby server, pg_receivexlog by default flushes WAL data only when a WAL file is closed. The option --synchronous must be specified to flush WAL data in real time. Since pg_receivexlog does not apply WAL, you should not allow it to become a synchronous standby when synchronous_commit equals remote_apply. If it does, it will appear to be a standby that never catches up, and will cause transaction commits to block. To avoid this, you should either configure an appropriate value for synchronous_standby_names, or specify application_name for pg_receivexlog that does not match it, or change the value of synchronous_commit to something other than remote_apply.
The transaction log is streamed over a regular Postgres Pro connection and uses the replication protocol. The connection must be made with a superuser or a user having REPLICATION permissions (see Section 20.2), and pg_hba.conf must permit the replication connection. The server must also be configured with max_wal_senders set high enough to leave at least one session available for the stream.
If the connection is lost, or if it cannot be initially established, with a non-fatal error, pg_receivexlog will retry the connection indefinitely, and reestablish streaming as soon as possible. To avoid this behavior, use the -n parameter.
Options
-Ddirectory--directory=directoryDirectory to write the output to.
This parameter is required.
--if-not-existsDo not error out when
--create-slotis specified and a slot with the specified name already exists.-n--no-loopDon't loop on connection errors. Instead, exit right away with an error.
-sinterval--status-interval=intervalSpecifies the number of seconds between status packets sent back to the server. This allows for easier monitoring of the progress from server. A value of zero disables the periodic status updates completely, although an update will still be sent when requested by the server, to avoid timeout disconnect. The default value is 10 seconds.
-Sslotname--slot=slotnameRequire pg_receivexlog to use an existing replication slot (see Section 25.2.6). When this option is used, pg_receivexlog will report a flush position to the server, indicating when each segment has been synchronized to disk so that the server can remove that segment if it is not otherwise needed.
When the replication client of pg_receivexlog is configured on the server as a synchronous standby, then using a replication slot will report the flush position to the server, but only when a WAL file is closed. Therefore, that configuration will cause transactions on the primary to wait for a long time and effectively not work satisfactorily. The option
--synchronous(see below) must be specified in addition to make this work correctly.--synchronousFlush the WAL data to disk immediately after it has been received. Also send a status packet back to the server immediately after flushing, regardless of
--status-interval.This option should be specified if the replication client of pg_receivexlog is configured on the server as a synchronous standby, to ensure that timely feedback is sent to the server.
-v--verboseEnables verbose mode.
The following command-line options control the database connection parameters.
-dconnstr--dbname=connstrSpecifies parameters used to connect to the server, as a connection string. See Section 30.1.1 for more information.
The option is called
--dbnamefor consistency with other client applications, but because pg_receivexlog doesn't connect to any particular database in the cluster, database name in the connection string will be ignored.-hhost--host=hostSpecifies the host name of the machine on which the server is running. If the value begins with a slash, it is used as the directory for the Unix domain socket. The default is taken from the
PGHOSTenvironment variable, if set, else a Unix domain socket connection is attempted.-pport--port=portSpecifies the TCP port or local Unix domain socket file extension on which the server is listening for connections. Defaults to the
PGPORTenvironment variable, if set, or a compiled-in default.-Uusername--username=usernameUser name to connect as.
-w--no-passwordNever issue a password prompt. If the server requires password authentication and a password is not available by other means such as a
.pgpassfile, the connection attempt will fail. This option can be useful in batch jobs and scripts where no user is present to enter a password.-W--passwordForce pg_receivexlog to prompt for a password before connecting to a database.
This option is never essential, since pg_receivexlog will automatically prompt for a password if the server demands password authentication. However, pg_receivexlog will waste a connection attempt finding out that the server wants a password. In some cases it is worth typing
-Wto avoid the extra connection attempt.
pg_receivexlog can perform one of the two following actions in order to control physical replication slots:
--create-slotCreate a new physical replication slot with the name specified in
--slot, then exit.--drop-slotDrop the replication slot with the name specified in
--slot, then exit.
Other options are also available:
-V--versionPrint the pg_receivexlog version and exit.
-?--helpShow help about pg_receivexlog command line arguments, and exit.
Environment
This utility, like most other Postgres Pro utilities, uses the environment variables supported by libpq (see Section 30.14).
Notes
When using pg_receivexlog instead of archive_command as the main WAL backup method, it is strongly recommended to use replication slots. Otherwise, the server is free to recycle or remove transaction log files before they are backed up, because it does not have any information, either from archive_command or the replication slots, about how far the WAL stream has been archived. Note, however, that a replication slot will fill up the server's disk space if the receiver does not keep up with fetching the WAL data.
Examples
To stream the transaction log from the server at mydbserver and store it in the local directory /usr/local/pgsql/archive:
$pg_receivexlog -h mydbserver -D /usr/local/pgsql/archive