26.2. Параметры управления восстановлением
По умолчанию процесс восстановления производится вплоть до окончания журнала WAL. Нижеуказанные параметры могут использоваться, чтобы остановить процесс восстановления в более ранней точке. Использоваться может только один из параметров recovery_target, recovery_target_lsn, recovery_target_name, recovery_target_time и recovery_target_xid; если в конфигурационном файле задано несколько параметров, будет использоваться последний.
recovery_target= 'immediate'Данный параметр указывает, что процесс восстановления должен завершиться, как только будет достигнуто целостное состояние, т. е. как можно раньше. При восстановлении из оперативной резервной копии, это будет точкой, в которой завершился процесс резервного копирования.
Технически это строковый параметр, но значение
'immediate'— единственно допустимое в данный момент.recovery_target_name(string)Этот параметр указывает именованную точку восстановления (созданную с помощью
pg_create_restore_point()), до которой будет производиться восстановление.recovery_target_time(timestamp)Данный параметр указывает точку времени, вплоть до которой будет производиться восстановление. Точность этой точки останова также зависит от recovery_target_inclusive.
recovery_target_xid(string)Параметр указывает идентификатор транзакции, вплоть до которой необходимо произвести процедуру восстановления. Имейте в виду, что несмотря на то, что при старте идентификаторы транзакций назначаются последовательно, завершаться они могут в ином порядке. Восстанавливаемые транзакции это те, что были зафиксированы до указанной (и, возможно, включая её). Точность точки останова также зависит от recovery_target_inclusive.
recovery_target_lsn(pg_lsn)Данный параметр указывает LSN позиции в журнале предзаписи, до которой должно выполняться восстановление. Точная позиция остановки зависит также от параметра recovery_target_inclusive. Данный параметр принимает значение системного типа данных
pg_lsn.
Следующие параметры уточняют целевую точку восстановления и определяют, что будет происходить при её достижении:
recovery_target_inclusive(boolean)Указывает на необходимость остановки сразу после (
true) либо до (false) достижения целевой точки. Применяется одновременно с recovery_target_lsn, recovery_target_time или recovery_target_xid. Этот параметр определяет, нужно ли восстанавливать транзакции, у которых позиция в WAL (LSN), время фиксации либо идентификатор в точности совпадает с заданным соответствующим значением. По умолчанию выбирается вариантtrue.recovery_target_timeline(string)Указывает линию времени для восстановления. По умолчанию производится восстановление той же линии времени, которая была текущей в момент создания базовой резервной копии. Со значением
latestвосстанавливаться будет последняя линия времени, найденная в архиве, что полезно для резервного сервера. Иное значение параметра может потребоваться в более сложной ситуации повторного восстановления, когда необходимо вернуться к состоянию, которое само было достигнуто после восстановления на момент времени. Это обсуждается в Подразделе 24.3.5.recovery_target_action(enum)Указывает, какое действие должен предпринять сервер после достижения цели восстановления. Вариант по умолчанию —
pause, что означает приостановку восстановления. Второй вариант,promote, означает, что процесс восстановления завершится и сервер начнёт принимать подключения. Наконец, с вариантомshutdownсервер остановится, как только цель восстановления будет достигнута.Вариант
pauseпозволяет выполнить запросы к базе данных и убедиться в том, что достигнутая цель оказалась желаемой точкой восстановления. Для снятия с паузы нужно вызватьpg_wal_replay_resume()(см. Таблицу 9.81), что в итоге приведёт к завершению восстановления. Если же окажется, что мы ещё не достигли желаемой точки восстановления, нужно остановить сервер, установить более позднюю цель и перезапустить сервер для продолжения восстановления.Вариант
shutdownполезен для получения готового экземпляра сервера в желаемой точке. При этом данный экземпляр сможет воспроизводить дополнительные записи WAL (и на самом деле ему придётся воспроизводить записи WAL после последней контрольной точки при следующем перезапуске).Заметьте, что так как
recovery.confне переименовывается, когда вrecovery_target_actionвыбран вариантshutdown, при последующем запуске будет происходить немедленная остановка, пока вы не измените конфигурацию или не удалите файлrecovery.confвручную.Этот параметр не действует, если цель восстановления не установлена. Если не включён режим hot_standby, значение
pauseдействует так же, как иshutdown.
26.2. Recovery Target Settings
By default, recovery will recover to the end of the WAL log. The following parameters can be used to specify an earlier stopping point. At most one of recovery_target, recovery_target_lsn, recovery_target_name, recovery_target_time, or recovery_target_xid can be used; if more than one of these is specified in the configuration file, the last entry will be used.
recovery_target= 'immediate'This parameter specifies that recovery should end as soon as a consistent state is reached, i.e., as early as possible. When restoring from an online backup, this means the point where taking the backup ended.
Technically, this is a string parameter, but
'immediate'is currently the only allowed value.recovery_target_name(string)This parameter specifies the named restore point (created with
pg_create_restore_point()) to which recovery will proceed.recovery_target_time(timestamp)This parameter specifies the time stamp up to which recovery will proceed. The precise stopping point is also influenced by recovery_target_inclusive.
recovery_target_xid(string)This parameter specifies the transaction ID up to which recovery will proceed. Keep in mind that while transaction IDs are assigned sequentially at transaction start, transactions can complete in a different numeric order. The transactions that will be recovered are those that committed before (and optionally including) the specified one. The precise stopping point is also influenced by recovery_target_inclusive.
recovery_target_lsn(pg_lsn)This parameter specifies the LSN of the write-ahead log location up to which recovery will proceed. The precise stopping point is also influenced by recovery_target_inclusive. This parameter is parsed using the system data type
pg_lsn.
The following options further specify the recovery target, and affect what happens when the target is reached:
recovery_target_inclusive(boolean)Specifies whether to stop just after the specified recovery target (
true), or just before the recovery target (false). Applies when recovery_target_lsn, recovery_target_time, or recovery_target_xid is specified. This setting controls whether transactions having exactly the target WAL location (LSN), commit time, or transaction ID, respectively, will be included in the recovery. Default istrue.recovery_target_timeline(string)Specifies recovering into a particular timeline. The default is to recover along the same timeline that was current when the base backup was taken. Setting this to
latestrecovers to the latest timeline found in the archive, which is useful in a standby server. Other than that you only need to set this parameter in complex re-recovery situations, where you need to return to a state that itself was reached after a point-in-time recovery. See Section 24.3.5 for discussion.recovery_target_action(enum)Specifies what action the server should take once the recovery target is reached. The default is
pause, which means recovery will be paused.promotemeans the recovery process will finish and the server will start to accept connections. Finallyshutdownwill stop the server after reaching the recovery target.The intended use of the
pausesetting is to allow queries to be executed against the database to check if this recovery target is the most desirable point for recovery. The paused state can be resumed by usingpg_wal_replay_resume()(see Table 9.81), which then causes recovery to end. If this recovery target is not the desired stopping point, then shut down the server, change the recovery target settings to a later target and restart to continue recovery.The
shutdownsetting is useful to have the instance ready at the exact replay point desired. The instance will still be able to replay more WAL records (and in fact will have to replay WAL records since the last checkpoint next time it is started).Note that because
recovery.confwill not be renamed whenrecovery_target_actionis set toshutdown, any subsequent start will end with immediate shutdown unless the configuration is changed or therecovery.conffile is removed manually.This setting has no effect if no recovery target is set. If hot_standby is not enabled, a setting of
pausewill act the same asshutdown.