pg_archivecleanup
pg_archivecleanup — вычистить файлы архивов WAL Postgres Pro
Синтаксис
pg_archivecleanup [параметр...] расположение_архива старейший_сохраняемый_файл
Описание
Утилита pg_archivecleanup предназначена для использования в качестве archive_cleanup_command для удаления старых файлов WAL на резервном сервере (см. Раздел 25.2). pg_archivecleanup можно использовать и как отдельную программу для выполнения тех же действий.
Чтобы использовать pg_archivecleanup на резервном сервере, добавьте эту строку в файл конфигурации recovery.conf:
archive_cleanup_command = 'pg_archivecleanup расположение_архива %r' Здесь расположение_архива определяет каталог, из которого должны удаляться файлы сегментов WAL.
Вызываемая в качестве archive_cleanup_command, эта программа просматривает расположение_архива и удаляет все файлы WAL, логически предшествующие значению аргумента %r. Целью этой операции является сокращение числа сохраняемых файлов без потери возможности восстановления при перезапуске. Такой вариант использования уместен, когда расположение_архива указывает на область рабочих файлов конкретного резервного сервера, но не когда расположение_архива — каталог с архивом WAL для долговременного хранения, или когда несколько резервных серверов восстанавливают записи WAL из одного расположения.
При отдельном использовании этой программы из каталога расположение_архива будут удалены все файлы WAL, логически предшествующие файлу старейший_сохраняемый_файл. В этом режиме, если вы укажете имя файла с расширением .partial или .backup, старейший_сохраняемый_файл будет определяться по имени без расширения. Благодаря такой интерпретации расширения .backup будут корректно удалены все файлы WAL, заархивированные до определённой базовой копии. Например, следующая команда удалит все файлы старее файла WAL с именем 000000010000003700000010:
pg_archivecleanup -d archive 000000010000003700000010.00000020.backup pg_archivecleanup: keep WAL file "archive/000000010000003700000010" and later pg_archivecleanup: removing file "archive/00000001000000370000000F" pg_archivecleanup: removing file "archive/00000001000000370000000E"
pg_archivecleanup рассчитывает на то, что расположение_архива доступно для чтения и записи пользователю, владеющему серверным процессом.
Параметры
pg_archivecleanup принимает следующие аргументы командной строки:
-dВыводить подробные отладочные сообщения в
stderr.-nВывести имена файлов, которые должны быть удалены, в
stdout(не выполняя удаление).-V--versionВывести версию pg_archivecleanup и завершиться.
-xрасширениеУстановить расширение, которое будет убрано из имён файлов до принятия решения об удалении определённых файлов. Это обычно полезно для очистки файлов архивов, которые сжимаются для хранения и получают расширение, задаваемое программой сжатия. Например:
-x .gz.-?--helpВывести справку об аргументах командной строки pg_archivecleanup и завершиться.
Замечания
Программа pg_archivecleanup рассчитана на работу с PostgreSQL 8.0 и новее как отдельная утилита, а также с PostgreSQL 9.0 и новее как команда очистки архива.
Программа pg_archivecleanup написана на C; её исходный код легко поддаётся модификации (он содержит секции, предназначенные для изменения при надобности)
Примеры
В системах Linux или Unix можно использовать команду:
archive_cleanup_command = 'pg_archivecleanup -d /mnt/standby/archive %r 2>>cleanup.log'
Предполагается, что каталог архива физически располагается на резервном сервере, так что команда archive_command обращается к нему по NFS, но для резервного сервера эти файлы локальные. Эта команда будет:
выводить отладочную информацию в
cleanup.logудалять ставшие ненужными файлы из каталога архива
См. также
pg_standbypg_archivecleanup
pg_archivecleanup — clean up Postgres Pro WAL archive files
Synopsis
pg_archivecleanup [option...] archivelocation oldestkeptwalfile
Description
pg_archivecleanup is designed to be used as an archive_cleanup_command to clean up WAL file archives when running as a standby server (see Section 25.2). pg_archivecleanup can also be used as a standalone program to clean WAL file archives.
To configure a standby server to use pg_archivecleanup, put this into its recovery.conf configuration file:
archive_cleanup_command = 'pg_archivecleanup archivelocation %r'
where archivelocation is the directory from which WAL segment files should be removed.
When used within archive_cleanup_command, all WAL files logically preceding the value of the %r argument will be removed from archivelocation. This minimizes the number of files that need to be retained, while preserving crash-restart capability. Use of this parameter is appropriate if the archivelocation is a transient staging area for this particular standby server, but not when the archivelocation is intended as a long-term WAL archive area, or when multiple standby servers are recovering from the same archive location.
When used as a standalone program all WAL files logically preceding the oldestkeptwalfile will be removed from archivelocation. In this mode, if you specify a .partial or .backup file name, then only the file prefix will be used as the oldestkeptwalfile. This treatment of .backup file name allows you to remove all WAL files archived prior to a specific base backup without error. For example, the following example will remove all files older than WAL file name 000000010000003700000010:
pg_archivecleanup -d archive 000000010000003700000010.00000020.backup pg_archivecleanup: keep WAL file "archive/000000010000003700000010" and later pg_archivecleanup: removing file "archive/00000001000000370000000F" pg_archivecleanup: removing file "archive/00000001000000370000000E"
pg_archivecleanup assumes that archivelocation is a directory readable and writable by the server-owning user.
Options
pg_archivecleanup accepts the following command-line arguments:
-dPrint lots of debug logging output on
stderr.-nPrint the names of the files that would have been removed on
stdout(performs a dry run).-V--versionPrint the pg_archivecleanup version and exit.
-xextensionProvide an extension that will be stripped from all file names before deciding if they should be deleted. This is typically useful for cleaning up archives that have been compressed during storage, and therefore have had an extension added by the compression program. For example:
-x .gz.-?--helpShow help about pg_archivecleanup command line arguments, and exit.
Notes
pg_archivecleanup is designed to work with PostgreSQL 8.0 and later when used as a standalone utility, or with PostgreSQL 9.0 and later when used as an archive cleanup command.
pg_archivecleanup is written in C and has an easy-to-modify source code, with specifically designated sections to modify for your own needs
Examples
On Linux or Unix systems, you might use:
archive_cleanup_command = 'pg_archivecleanup -d /mnt/standby/archive %r 2>>cleanup.log'
where the archive directory is physically located on the standby server, so that the archive_command is accessing it across NFS, but the files are local to the standby. This will:
produce debugging output in
cleanup.logremove no-longer-needed files from the archive directory