pg_waldump
pg_waldump — вывести журнал предзаписи кластера БД PostgreSQL в понятном человеку виде
Синтаксис
pg_waldump [параметр...] [начальный_сегмент [конечный_сегмент]]
Описание
Программа pg_waldump показывает содержимое журнала предзаписи (WAL) и прежде всего полезна для целей отладки и обучения.
Эту утилиту может запускать только пользователь, установивший сервер, так как ей требуется доступ на чтение к каталогу данных.
Параметры
Следующие аргументы командной строки задают расположение данных и формат вывода:
начальный_сегментНачать чтение с указанного файла сегмента WAL. Это неявно определяет каталог, в котором будут находиться файлы, и целевую линию времени.
конечный_сегментОстановиться после чтения указанного файла сегмента WAL.
-b--bkp-detailsВыводить подробные сведения о блоках-копиях страниц.
-Bблок--block=блокВыводить только записи, изменяющие указанный блок. При этом также необходимо указать отношение в аргументе
--relationили-R.-eконец--end=конецПрекратить чтение в заданной позиции в WAL, а не читать поток до конца.
-f--followДостигнув конца корректного WAL, проверять раз в секунду поступление новых записей WAL.
-Fслой--fork=слойВыводить только записи, изменяющие блоки в указанном слое. Допустимые значения:
main(основной слой),fsm(карта свободного пространства),vm(карта видимости) иinit(слой инициализации).-nпредел--limit=пределВывести заданное число записей и остановиться.
-pпуть--path=путьЗадаёт каталог, содержащий файлы сегментов WAL, либо каталог с подкаталогом
pg_wal, содержащим такие файлы. По умолчанию в поисках этих файлов просматривается текущий каталог, подкаталогpg_walтекущего каталога и подкаталогpg_walкаталогаPGDATA.-q--quietНе выводить ничего кроме ошибок. Этот ключ может быть полезен, когда вы хотите узнать, можно ли полностью разобрать диапазон записей WAL, но собственно содержимое записей вас не интересует.
-rменеджер_ресурсов--rmgr=менеджер_ресурсовВыводить только записи, созданные указанным менеджером ресурсов. Вы можете указать параметр несколько раз, чтобы выбрать несколько менеджеров ресурсов. Когда в качестве имени менеджера передаётся
list, программа выводит только список возможных имён менеджеров ресурсов и завершается.Расширения могут определять пользовательские менеджеры ресурсов, но pg_waldump не загружает модули расширений и поэтому не может распознать пользовательские менеджеры ресурсов по имени. Вместо этого можно обозначить пользовательского менеджера ресурсов в форме
custom###, где###— трёхзначный идентификатор менеджера ресурсов. Обозначения в этой форме всегда будут считаться действительными.-Rтабл_пространство/бд/отношение--relation=табл_пространство/бд/отношениеВыводить только записи, изменяющие блоки в указанном отношении. Отношение указывается с OID табличного пространства, OID базы данных и номером файла, разделёнными косой чертой, например
1234/12345/12345. В этом же формате отношения обозначаются в выводе программы.-sначало--start=началоПозиция в WAL, с которой нужно начать чтение. По умолчанию чтение начинается с первой корректной записи WAL в самом первом из найденных файлов.
-tлиния_времени--timeline=линия_времениЛиния времени, из которой будут читаться записи WAL. По умолчанию используется значение, заданное параметром
начальный_сегмент, если он присутствует, а иначе — 1. Значение можно задавать в десятичном или шестнадцатеричном представлении, например17или0x11.-V--versionВывести версию pg_waldump и завершиться.
-w--fullpageВыводить только записи, содержащие образы полных страниц.
-xxid--xid=xidВывести только записи, относящиеся к указанной транзакции.
-z--stats[=record]Вывести общую статистику (число и размер записей и образов полных страниц) вместо отдельных записей. Возможен вариант получения статистики по записям, а не по менеджерам ресурсов.
Если программа pg_waldump прерывается сигналом SIGINT (Control+C), она выдаёт сводку по данным, которые были обработаны к моменту прерывания. Эта операция не поддерживается в Windows.
--save-fullpage=путь_храненияСохранять образы полных страниц, записываемые в WAL, в каталог, указанный в
пути_хранения. Фильтровать сохраняемые образы и ограничивать их вывод можно так же, как и для записей.Образы полных страниц сохраняются с именами в таком формате:
. Имена файлов состоят из следующих компонентов:TIMELINE-LSN.RELTABLESPACE.DATOID.RELNODE.BLKNO_FORKКомпонент Описание TIMELINE линия времени файла-сегмента WAL, в котором хранится запись, состоит из одного шестнадцатеричного числа шириной 8 символов %08XLSN LSN записи с этим образом, состоит из двух шестнадцатеричных чисел шириной 8 символов %08X-%08XRELTABLESPACE OID табличного пространства, содержащего блок DATOID OID базы данных, содержащей блок RELNODE номер файлового узла для блока BLKNO номер блока FORK имя слоя, в котором был создан образ полной страницы: main,fsm,vmилиinit-?--helpВывести справку об аргументах командной строки pg_waldump и завершиться.
Переменные окружения
PGDATAКаталог данных; также см. параметр
-p.PG_COLORВыбирает вариант использования цвета в диагностических сообщениях. Возможные значения:
always(всегда),auto(автоматически) иnever(никогда).
Примечания
Когда сервер работает, результаты могут быть некорректными.
Выводятся записи только указанной линии времени (или линии времени по умолчанию, если она не задана явно). Записи в других линиях времени игнорируются.
pg_waldump не будет читать файлы WAL с расширением .partial. Если требуется прочитать такие файлы, расширение .partial нужно убрать из их имён.
См. также
Раздел 28.6pg_waldump
pg_waldump — display a human-readable rendering of the write-ahead log of a PostgreSQL database cluster
Synopsis
pg_waldump [option...] [startseg [endseg]]
Description
pg_waldump displays the write-ahead log (WAL) and is mainly useful for debugging or educational purposes.
This utility can only be run by the user who installed the server, because it requires read-only access to the data directory.
Options
The following command-line options control the location and format of the output:
startsegStart reading at the specified WAL segment file. This implicitly determines the path in which files will be searched for, and the timeline to use.
endsegStop after reading the specified WAL segment file.
-b--bkp-detailsOutput detailed information about backup blocks.
-Bblock--block=blockOnly display records that modify the given block. The relation must also be provided with
--relationor-R.-eend--end=endStop reading at the specified WAL location, instead of reading to the end of the log stream.
-f--followAfter reaching the end of valid WAL, keep polling once per second for new WAL to appear.
-Ffork--fork=forkOnly display records that modify blocks in the given fork. The valid values are
mainfor the main fork,fsmfor the free space map,vmfor the visibility map, andinitfor the init fork.-nlimit--limit=limitDisplay the specified number of records, then stop.
-ppath--path=pathSpecifies a directory to search for WAL segment files or a directory with a
pg_walsubdirectory that contains such files. The default is to search in the current directory, thepg_walsubdirectory of the current directory, and thepg_walsubdirectory ofPGDATA.-q--quietDo not print any output, except for errors. This option can be useful when you want to know whether a range of WAL records can be successfully parsed but don't care about the record contents.
-rrmgr--rmgr=rmgrOnly display records generated by the specified resource manager. You can specify the option multiple times to select multiple resource managers. If
listis passed as name, print a list of valid resource manager names, and exit.Extensions may define custom resource managers, but pg_waldump does not load the extension module and therefore does not recognize custom resource managers by name. Instead, you can specify the custom resource managers as
custom###where###is the three-digit resource manager ID. Names of this form will always be considered valid.-Rtblspc/db/rel--relation=tblspc/db/relOnly display records that modify blocks in the given relation. The relation is specified with tablespace OID, database OID, and relfilenode separated by slashes, for example
1234/12345/12345. This is the same format used for relations in the program's output.-sstart--start=startWAL location at which to start reading. The default is to start reading the first valid WAL record found in the earliest file found.
-ttimeline--timeline=timelineTimeline from which to read WAL records. The default is to use the value in
startseg, if that is specified; otherwise, the default is 1. The value can be specified in decimal or hexadecimal, for example17or0x11.-V--versionPrint the pg_waldump version and exit.
-w--fullpageOnly display records that include full page images.
-xxid--xid=xidOnly display records marked with the given transaction ID.
-z--stats[=record]Display summary statistics (number and size of records and full-page images) instead of individual records. Optionally generate statistics per-record instead of per-rmgr.
If pg_waldump is terminated by signal SIGINT (Control+C), the summary of the statistics computed is displayed up to the termination point. This operation is not supported on Windows.
--save-fullpage=save_pathSave full page images found in the WAL records to the
save_pathdirectory. The images saved are subject to the same filtering and limiting criteria as the records displayed.The full page images are saved with the following file name format:
The file names are composed of the following parts:TIMELINE-LSN.RELTABLESPACE.DATOID.RELNODE.BLKNO_FORKComponent Description TIMELINE The timeline of the WAL segment file where the record is located formatted as one 8-character hexadecimal number %08XLSN The LSN of the record with this image, formatted as two 8-character hexadecimal numbers %08X-%08XRELTABLESPACE tablespace OID of the block DATOID database OID of the block RELNODE filenode of the block BLKNO block number of the block FORK The name of the fork the full page image came from, such as main,fsm,vm, orinit.-?--helpShow help about pg_waldump command line arguments, and exit.
Environment
PGDATAData directory; see also the
-poption.PG_COLORSpecifies whether to use color in diagnostic messages. Possible values are
always,autoandnever.
Notes
Can give wrong results when the server is running.
Only the specified timeline is displayed (or the default, if none is specified). Records in other timelines are ignored.
pg_waldump cannot read WAL files with suffix .partial. If those files need to be read, .partial suffix needs to be removed from the file name.