50.2. Обработчики модулей архивирования #
Обработчики архивирования определяют, как именно модуль будет выполнять архивирование. Сервер будет вызывать их по мере необходимости для обработки каждого отдельного файла WAL.
50.2.1. Обработчик запуска #
Обработчик startup_cb вызывается вскоре после загрузки модуля. Этот обработчик можно использовать для любой необходимой дополнительной инициализации. Если есть данные о состоянии модуля архивирования, обработчик может использовать state->private_data для их хранения.
typedef void (*ArchiveStartupCB) (ArchiveModuleState *state);
50.2.2. Обработчик проверки #
Обработчик check_configured_cb вызывается, чтобы проверить, полностью ли настроен модуль и готов ли он принимать файлы WAL (в частности, что для его параметров конфигурации установлены допустимые значения). Если функция check_configured_cb не определена, сервер всегда предполагает, что модуль готов к работе.
typedef bool (*ArchiveCheckConfiguredCB) (ArchiveModuleState *state);
Если возвращается true, сервер перейдёт к архивированию файла, вызвав обработчик archive_file_cb. Если возвращается false, архивирование не производится и архиватор выдаст в журнал сервера следующее сообщение:
ВНИМАНИЕ: включён режим archive_mode, но архивирование не настроено
В последнем случае сервер будет периодически вызывать эту функцию, и архивирование начнётся только тогда, когда она вернёт true.
Примечание
Может быть полезно добавить дополнительную информацию к общему тексту предупреждения, когда функция возвращает false. Для этого добавьте сообщение в макрос arch_module_check_errdetail перед возвратом false. Как и errdetail(), этот макрос принимает строку формата с необязательным списком аргументов. Строка, переданная в макрос, будет выведена как строка DETAIL в предупреждающем сообщении.
50.2.3. Обработчик архивирования #
Обработчик archive_file_cb вызывается для архивирования одного файла WAL.
typedef bool (*ArchiveFileCB) (ArchiveModuleState *state, const char *file, const char *path);
Если возвращается true, сервер считает, что файл был успешно заархивирован, и может переработать или удалить исходный файл WAL. Если возвращается false или возникает ошибка, сервер сохраняет исходный файл WAL и повторяет попытку архивирования позже. Аргумент файл содержит только имя архивируемого файла WAL, а путь содержит полный путь к файлу WAL (включая имя файла).
Примечание
Обработчик archive_file_cb вызывается в кратковременном контексте памяти, который будет сбрасываться между вызовами. Если нужен долгоживущий контекст, создайте его в обработчике startup_cb.
50.2.4. Обработчик выключения #
Обработчик shutdown_cb вызывается, когда завершается процесс архиватора (например, после ошибки) или изменяется значение archive_library. Если функция shutdown_cb не определена, никакие специальные действия в этих случаях не предпринимаются. Если есть данные о состоянии модуля архивирования, этот обработчик должен удалить их во избежание утечек.
typedef void (*ArchiveShutdownCB) (ArchiveModuleState *state);
50.2. Archive Module Callbacks #
The archive callbacks define the actual archiving behavior of the module. The server will call them as required to process each individual WAL file.
50.2.1. Startup Callback #
The startup_cb callback is called shortly after the module is loaded. This callback can be used to perform any additional initialization required. If the archive module has any state, it can use state->private_data to store it.
typedef void (*ArchiveStartupCB) (ArchiveModuleState *state);
50.2.2. Check Callback #
The check_configured_cb callback is called to determine whether the module is fully configured and ready to accept WAL files (e.g., its configuration parameters are set to valid values). If no check_configured_cb is defined, the server always assumes the module is configured.
typedef bool (*ArchiveCheckConfiguredCB) (ArchiveModuleState *state);
If true is returned, the server will proceed with archiving the file by calling the archive_file_cb callback. If false is returned, archiving will not proceed, and the archiver will emit the following message to the server log:
WARNING: archive_mode enabled, yet archiving is not configured
In the latter case, the server will periodically call this function, and archiving will proceed only when it returns true.
Note
When returning false, it may be useful to append some additional information to the generic warning message. To do that, provide a message to the arch_module_check_errdetail macro before returning false. Like errdetail(), this macro accepts a format string followed by an optional list of arguments. The resulting string will be emitted as the DETAIL line of the warning message.
50.2.3. Archive Callback #
The archive_file_cb callback is called to archive a single WAL file.
typedef bool (*ArchiveFileCB) (ArchiveModuleState *state, const char *file, const char *path);
If true is returned, the server proceeds as if the file was successfully archived, which may include recycling or removing the original WAL file. If false is returned or an error is thrown, the server will keep the original WAL file and retry archiving later. file will contain just the file name of the WAL file to archive, while path contains the full path of the WAL file (including the file name).
Note
The archive_file_cb callback is called in a short-lived memory context that will be reset between invocations. If you need longer-lived storage, create a memory context in the module's startup_cb callback.
50.2.4. Shutdown Callback #
The shutdown_cb callback is called when the archiver process exits (e.g., after an error) or the value of archive_library changes. If no shutdown_cb is defined, no special action is taken in these situations. If the archive module has any state, this callback should free it to avoid leaks.
typedef void (*ArchiveShutdownCB) (ArchiveModuleState *state);