pg_rewind

pg_rewind — синхронизировать каталог данных Postgres Pro с другим каталогом, ответвлённым от первого

Синтаксис

pg_rewind [параметр...] { -D | --target-pgdata }каталог { --source-pgdata=каталог | --source-server=строка_подключения }

Описание

Утилита pg_rewind представляет собой средство синхронизации кластера Postgres Pro с другой копией того же кластера после расхождения линий времени этих кластеров. Обычный сценарий её использования — вернуть в работу старый главный сервер после переключения на резервный, в качестве резервного для сервера, ставшего главным.

Её результат равнозначен замене целевого каталога данных исходным. Она копирует все файлы, включая файлы конфигурации. Преимущество pg_rewind по сравнению с созданием новой базовой копии или такими средствами, как rsync, состоит в том, что pg_rewind не требует читать все неизменённые файлы в кластере. Благодаря этому она действует гораздо быстрее, когда база данных большая, а объём различий между кластерами невелик.

Утилита pg_rewind изучает историю линий времени исходного и целевого кластеров с целью найти точку, в которой они разошлись, и ожидает найти журналы WAL в каталоге pg_xlog целевого кластера вплоть до точки расхождения. В типичном сценарии отработки отказа, когда целевой кластер отключается вскоре после расхождения, это не проблема, но если целевой кластер проработал долгое время после расхождения, старые файлы WAL могут быть уже удалены. В этом случае их можно вручную скопировать из архива WAL в каталог pg_xlog. Автоматическая загрузка недостающих файлов из архива WAL в настоящее время не поддерживается.

Когда целевой сервер запускается в первый раз после выполнения pg_rewind, он переходит в режим восстановления и воспроизводит все изменения из WAL с исходного сервера после точки расхождения. Если какие-то сегменты WAL оказались недоступны на исходном сервере, когда выполнялась pg_rewind, и поэтому не могли быть скопированы в ходе работы pg_rewind, их необходимо предоставить, когда сервер будет запускаться. Это можно сделать, создав в целевом каталоге данных файл recovery.conf с подходящей командой restore_command.

Утилита pg_rewind требует, чтобы на целевом сервере был либо включён режим wal_log_hints в postgresql.conf, либо включены контрольные суммы, когда кластер был инициализирован командой initdb. Оба эти режима по умолчанию отключены. Также должен быть включён режим full_page_writes. По умолчанию он включён.

Предупреждение

Если во время работы pg_rewind происходит ошибка, вероятнее всего, целевой каталог данных будет в состоянии, не подходящем для восстановления. В этом случае рекомендуется сделать новую резервную копию.

Программа pg_rewind немедленно прекращает работу, если обнаруживает файлы, непосредственная запись в которые невозможна. Это может иметь место, например, когда на исходном и целевом серверах совпадают пути файлов сертификатов и ключей SSL, доступных только для чтения. Если такие файлы существуют на целевом сервере, их рекомендуется удалить до запуска pg_rewind. После выполнения синхронизации некоторые из таких файлов могут быть скопированы из источника и тогда может потребоваться удалить скопированные данные и восстановить ссылки/файлы, существовавшие до синхронизации.

Параметры

pg_rewind принимает следующие аргументы командной строки:

-D каталог
--target-pgdata=каталог

Этот параметр задаёт целевой каталог данных, который будет синхронизирован с источником. Целевой сервер должен быть отключён штатным образом до запуска pg_rewind

--source-pgdata=каталог

Задаёт путь к каталогу данных исходного сервера, с которым будет синхронизироваться целевой. Когда используется ключ --source-pgdata, исходный сервер должен быть остановлен штатным образом.

--source-server=строка_подключения

Задаёт строку подключения libpq для подключения к исходному серверу Postgres Pro, с которым будет синхронизирован целевой. Подключение должно устанавливаться как обычное (не реплицирующее) с правами суперпользователя. Сервер должен быть запущен и работать в обычном режиме, не в режиме восстановления.

-n
--dry-run

Делать всё, кроме внесения изменений в целевой каталог.

-P
--progress

Включает вывод сообщений о прогрессе. При этом в процессе копирования данных из исходного кластера будет выдаваться приблизительный процент выполнения.

--debug

Выводить подробные отладочные сообщения, полезные в основном для разработчиков, отлаживающих pg_rewind.

-V
--version

Показать версию, а затем завершиться.

-?
--help

Показать справку, а затем завершиться.

Переменные окружения

Когда используется --source-server, pg_rewind также использует переменные среды, поддерживаемые libpq (см. Раздел 31.14).

Замечания

Когда исходным кластером для pg_rewind является работающий сервер сразу после повышения, в нём необходимо выполнить команду CHECKPOINT, чтобы его управляющий файл содержал актуальную информацию о линии времени. Эта информацию нужна pg_rewind для проверки, можно ли синхронизировать целевой кластер с выбранным исходным.

Как это работает

Основная идея заключается в том, чтобы скопировать из нового кластера в старый всё, за исключением блоков, которые, насколько нам известно, одинаковые.

  1. Просканировать журнал WAL в старом кластере, начиная с последней контрольной точки, и до точки, в которой история линии времени нового кластера разошлась со старым кластером. Для каждой записи WAL отметить, какие блоки данных были затронуты. В результате будет получен список всех блоков данных, которые были изменены в старом кластере после отделения нового кластера.

  2. Скопировать все эти изменённые блоки из нового кластера в старый.

  3. Скопировать все остальные файлы, в частности clog и файлы конфигурации из нового кластера в старый, пропуская файлы отношений.

  4. Применить WAL из нового кластера, начиная с контрольной точки, созданной при отработке отказа. (Строго говоря, утилита pg_rewind не применяет WAL, она просто создаёт файл метки резервной копии, найдя который при следующем запуске, Postgres Pro начнёт воспроизведение с этой контрольной точки и применит все требуемые записи WAL.)

pg_rewind

pg_rewind — synchronize a Postgres Pro data directory with another data directory that was forked from the first one

Synopsis

pg_rewind [option...] { -D | --target-pgdata } directory { --source-pgdata=directory | --source-server=connstr }

Description

pg_rewind is a tool for synchronizing a Postgres Pro cluster with another copy of the same cluster, after the clusters' timelines have diverged. A typical scenario is to bring an old master server back online after failover, as a standby that follows the new master.

The result is equivalent to replacing the target data directory with the source one. All files are copied, including configuration files. The advantage of pg_rewind over taking a new base backup, or tools like rsync, is that pg_rewind does not require reading through all unchanged files in the cluster. That makes it a lot faster when the database is large and only a small portion of it differs between the clusters.

pg_rewind examines the timeline histories of the source and target clusters to determine the point where they diverged, and expects to find WAL in the target cluster's pg_xlog directory reaching all the way back to the point of divergence. In the typical failover scenario where the target cluster was shut down soon after the divergence, that is not a problem, but if the target cluster had run for a long time after the divergence, the old WAL files might not be present anymore. In that case, they can be manually copied from the WAL archive to the pg_xlog directory. Fetching missing files from a WAL archive automatically is currently not supported.

When the target server is started up for the first time after running pg_rewind, it will go into recovery mode and replay all WAL generated in the source server after the point of divergence. If some of the WAL was no longer available in the source server when pg_rewind was run, and therefore could not be copied by pg_rewind session, it needs to be made available when the target server is started up. That can be done by creating a recovery.conf file in the target data directory with a suitable restore_command.

pg_rewind requires that the target server either has the wal_log_hints option is enabled in postgresql.conf or that data checksums were enabled when the cluster was initialized with initdb. Neither of these are currently on by default. full_page_writes must also be enabled. That is the default.

Warning

If pg_rewind fails while processing, then the data folder of the target is likely not in a state that can be recovered. In such a case, taking a new fresh backup is recommended.

pg_rewind will fail immediately if it finds files it cannot write directly to. This can happen for example when the source and the target server use the same file mapping for read-only SSL keys and certificates. If such files are present on the target server it is recommended to remove them before running pg_rewind. After doing the rewind, some of those files may have been copied from the source, in which case it may be necessary to remove the data copied and restore back the set of links used before the rewind.

Options

pg_rewind accepts the following command-line arguments:

-D directory
--target-pgdata=directory

This option specifies the target data directory that is synchronized with the source. The target server must shut down cleanly before running pg_rewind

--source-pgdata=directory

Specifies path to the data directory of the source server, to synchronize the target with. When --source-pgdata is used, the source server must be cleanly shut down.

--source-server=connstr

Specifies a libpq connection string to connect to the source Postgres Pro server to synchronize the target with. The connection must be a normal (non-replication) connection with superuser access. The server must be up and running, and must not be in recovery mode.

-n
--dry-run

Do everything except actually modifying the target directory.

-P
--progress

Enables progress reporting. Turning this on will deliver an approximate progress report while copying data over from the source cluster.

--debug

Print verbose debugging output that is mostly useful for developers debugging pg_rewind.

-V
--version

Display version information, then exit.

-?
--help

Show help, then exit.

Environment

When --source-server option is used, pg_rewind also uses the environment variables supported by libpq (see Section 31.14).

Notes

When executing pg_rewind using an online cluster as source which has been recently promoted, it is necessary to execute a CHECKPOINT after promotion so as its control file reflects up-to-date timeline information, which is used by pg_rewind to check if the target cluster can be rewound using the designated source cluster.

How it works

The basic idea is to copy everything from the new cluster to the old cluster, except for the blocks that we know to be the same.

  1. Scan the WAL log of the old cluster, starting from the last checkpoint before the point where the new cluster's timeline history forked off from the old cluster. For each WAL record, make a note of the data blocks that were touched. This yields a list of all the data blocks that were changed in the old cluster, after the new cluster forked off.

  2. Copy all those changed blocks from the new cluster to the old cluster.

  3. Copy all other files such as clog and configuration files from the new cluster to the old cluster, everything except the relation files.

  4. Apply the WAL from the new cluster, starting from the checkpoint created at failover. (Strictly speaking, pg_rewind doesn't apply the WAL, it just creates a backup label file indicating that when Postgres Pro is started, it will start replay from that checkpoint and apply all the required WAL.)

FAQ