28.4. Отслеживание выполнения
Postgres Pro имеет возможность отслеживать выполнение определённых команд. В настоящее время такое отслеживание поддерживает только команда VACUUM
, но в будущем сфера его применения может быть расширена.
28.4.1. Отслеживание выполнения VACUUM
Во время выполнения VACUUM
представление pg_stat_progress_vacuum
будет содержать по одной строке для каждого обслуживающего процесса (включая рабочие процессы автоочистки), производящего очистку. Таблицы ниже показывают, какая информация будет отслеживаться, и рассказывают, как её интерпретировать. В настоящее время отслеживание выполнения не поддерживается для команды VACUUM FULL
, так что процессы, выполняющие VACUUM FULL
, не будут видны в этом представлении.
Таблица 28.20. Представление pg_stat_progress_vacuum
Столбец | Тип | Описание |
---|---|---|
pid | integer | Идентификатор (PID) обслуживающего процесса |
datid | oid | OID базы данных, к которой подключён этот обслуживающий процесс. |
datname | name | Имя базы данных, к которой подключён этот обслуживающий процесс. |
relid | oid | OID очищаемой таблицы. |
phase | text | Текущая фаза очистки. См. Таблицу 28.21. |
heap_blks_total | bigint | Общее число блоков кучи в таблице. Это число отражает состояние в начале сканирования; блоки, добавленные позже, не будут (и не должны) обрабатываться текущей командой VACUUM . |
heap_blks_scanned | bigint | Число просканированных блоков кучи. Так как для оптимизации сканирования применяется карта видимости, некоторые блоки могут пропускаться без осмотра; пропущенные блоки входят в это общее число, так что по завершении очистки это число станет равно heap_blks_total . Этот счётчик увеличивается только в фазе scanning heap . |
heap_blks_vacuumed | bigint | Число очищенных блоков кучи. Если в таблице нет индексов, этот счётчик увеличивается только в фазе vacuuming heap (очистка кучи). Блоки, не содержащие «мёртвых» кортежей, при этом пропускаются, так что этот счётчик иногда может увеличиваться резкими рывками. |
index_vacuum_count | bigint | Количество завершённых циклов очистки индекса. |
max_dead_tuples | bigint | Число «мёртвых» кортежей, которое мы можем сохранить, прежде чем потребуется выполнить цикл очистки индекса, в зависимости от maintenance_work_mem. |
num_dead_tuples | bigint | Число «мёртвых» кортежей, собранных со времени последнего цикла очистки индекса. |
Таблица 28.21. Фазы VACUUM
Фаза | Описание |
---|---|
initializing | Инициализация — VACUUM готовится начать сканирование кучи. Эта фаза должна быть очень быстрой. |
scanning heap | Сканирование кучи — VACUUM в настоящее время сканирует кучу. При этом будет очищена и, если требуется, дефрагментирована каждая страница, а возможно, также будет произведена заморозка. Отслеживать процесс сканирования можно, следя за содержимым столбца heap_blks_scanned . |
vacuuming indexes | Очистка индексов — VACUUM в настоящее время очищает индексы. Если у таблицы есть какие-либо индексы, эта фаза будет наблюдаться минимум единожды в процессе очистки, после того, как куча будет просканирована полностью. Она может повторяться несколько раз в процессе очистки, если объёма maintenance_work_mem (или, в случае автоочистки, autovacuum_work_mem, если он задан) оказывается недостаточно для сохранения всех найденных «мёртвых» кортежей. |
vacuuming heap | Очистка кучи — VACUUM в настоящее время очищает кучу. Очистка кучи отличается от сканирования, так как она происходит после каждой операции очистки индексов. Если heap_blks_scanned меньше чем heap_blks_total , система вернётся к сканированию кучи после завершения этой фазы; в противном случае она начнёт уборку индексов. |
cleaning up indexes | Уборка индексов — VACUUM в настоящее время производит уборку в индексах. Это происходит после завершения полного сканирования кучи и очистки индексов и кучи. |
truncating heap | Усечение кучи — VACUUM в настоящее время усекает кучу, чтобы возвратить операционной системе объём пустых страниц в конце отношения. Это происходит после уборки индексов. |
performing final cleanup | Выполнение окончательной очистки — VACUUM выполняет окончательную очистку. На этой стадии VACUUM очищает карту свободного пространства, обновляет статистику в pg_class и передаёт статистику сборщику статистики, После этой фазы VACUUM завершит свою работу. |
28.4. Progress Reporting
Postgres Pro has the ability to report the progress of certain commands during command execution. Currently, the only command which supports progress reporting is VACUUM
. This may be expanded in the future.
28.4.1. VACUUM Progress Reporting
Whenever VACUUM
is running, the pg_stat_progress_vacuum
view will contain one row for each backend (including autovacuum worker processes) that is currently vacuuming. The tables below describe the information that will be reported and provide information about how to interpret it. Progress reporting is not currently supported for VACUUM FULL
and backends running VACUUM FULL
will not be listed in this view.
Table 28.20. pg_stat_progress_vacuum
View
Column | Type | Description |
---|---|---|
pid | integer | Process ID of backend. |
datid | oid | OID of the database to which this backend is connected. |
datname | name | Name of the database to which this backend is connected. |
relid | oid | OID of the table being vacuumed. |
phase | text | Current processing phase of vacuum. See Table 28.21. |
heap_blks_total | bigint | Total number of heap blocks in the table. This number is reported as of the beginning of the scan; blocks added later will not be (and need not be) visited by this VACUUM . |
heap_blks_scanned | bigint | Number of heap blocks scanned. Because the visibility map is used to optimize scans, some blocks will be skipped without inspection; skipped blocks are included in this total, so that this number will eventually become equal to heap_blks_total when the vacuum is complete. This counter only advances when the phase is scanning heap . |
heap_blks_vacuumed | bigint | Number of heap blocks vacuumed. Unless the table has no indexes, this counter only advances when the phase is vacuuming heap . Blocks that contain no dead tuples are skipped, so the counter may sometimes skip forward in large increments. |
index_vacuum_count | bigint | Number of completed index vacuum cycles. |
max_dead_tuples | bigint | Number of dead tuples that we can store before needing to perform an index vacuum cycle, based on maintenance_work_mem. |
num_dead_tuples | bigint | Number of dead tuples collected since the last index vacuum cycle. |
Table 28.21. VACUUM phases
Phase | Description |
---|---|
initializing | VACUUM is preparing to begin scanning the heap. This phase is expected to be very brief. |
scanning heap | VACUUM is currently scanning the heap. It will prune and defragment each page if required, and possibly perform freezing activity. The heap_blks_scanned column can be used to monitor the progress of the scan. |
vacuuming indexes | VACUUM is currently vacuuming the indexes. If a table has any indexes, this will happen at least once per vacuum, after the heap has been completely scanned. It may happen multiple times per vacuum if maintenance_work_mem (or, in the case of autovacuum, autovacuum_work_mem if set) is insufficient to store the number of dead tuples found. |
vacuuming heap | VACUUM is currently vacuuming the heap. Vacuuming the heap is distinct from scanning the heap, and occurs after each instance of vacuuming indexes. If heap_blks_scanned is less than heap_blks_total , the system will return to scanning the heap after this phase is completed; otherwise, it will begin cleaning up indexes after this phase is completed. |
cleaning up indexes | VACUUM is currently cleaning up indexes. This occurs after the heap has been completely scanned and all vacuuming of the indexes and the heap has been completed. |
truncating heap | VACUUM is currently truncating the heap so as to return empty pages at the end of the relation to the operating system. This occurs after cleaning up indexes. |
performing final cleanup | VACUUM is performing final cleanup. During this phase, VACUUM will vacuum the free space map, update statistics in pg_class , and report statistics to the statistics collector. When this phase is completed, VACUUM will end. |