27.4. Отслеживание выполнения
В PostgreSQL имеется возможность отслеживать выполнение определённых команд. В настоящее время такое отслеживание поддерживается только для команд CREATE INDEX, VACUUM и CLUSTER. В будущем эта поддержка может быть расширена.
27.4.1. Отслеживание выполнения CREATE INDEX
Во время выполнения CREATE INDEX или REINDEX представление pg_stat_progress_create_index будет содержать по одной строке для каждого обслуживающего процесса, создающего индексы в этот момент. Таблицы ниже показывают, какая информация будет отслеживаться, и поясняют, как её интерпретировать.
Таблица 27.22. Представление pg_stat_progress_create_index
| Столбец | Тип | Описание |
|---|---|---|
pid | integer | Идентификатор (PID) обслуживающего процесса |
datid | oid | OID базы данных, к которой подключён этот обслуживающий процесс. |
datname | name | Имя базы данных, к которой подключён этот обслуживающий процесс. |
relid | oid | OID таблицы, в которой создаётся индекс. |
index_relid | oid | OID создаваемого или перестраиваемого индекса. При выполнении CREATE INDEX в неблокирующем режиме содержит 0. |
command | text | Выполняемая команда: CREATE INDEX, CREATE INDEX CONCURRENTLY, REINDEX или REINDEX CONCURRENTLY. |
phase | text | Текущая фаза создания индекса. См. Таблицу 27.23. |
lockers_total | bigint | Общее число процессов, потребовавших ожидания, если таковые имеются. |
lockers_done | bigint | Число процессов, ожидание которых уже завершено. |
current_locker_pid | bigint | Идентификатор процесса, удерживающего конфликтующую блокировку в данный момент. |
blocks_total | bigint | Общее число блоков, которые должны быть обработаны в текущей фазе. |
blocks_done | bigint | Число блоков, уже обработанных в текущей фазе. |
tuples_total | bigint | Общее число кортежей, которые должны быть обработаны в текущей фазе. |
tuples_done | bigint | Число кортежей, уже обработанных в текущей фазе. |
partitions_total | bigint | При создании индекса в секционированной таблице этот столбец содержит общее число секций, в которых создаётся индекс. |
partitions_done | bigint | При создании индекса в секционированной таблице этот столбец содержит число секций, в которых индекс уже построен. |
Таблица 27.23. Фазы CREATE INDEX
| Фаза | Описание |
|---|---|
initializing | Инициализация — процедура CREATE INDEX или REINDEX подготавливается к созданию индекса. Эта фаза должна быть очень быстрой. |
waiting for writers before build | Ожидание окончания записи перед построением — процедура CREATE INDEX CONCURRENTLY или REINDEX CONCURRENTLY ожидает завершения транзакций, которые удерживают блокировки записи и могут читать таблицу. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid. |
building index | Построение индекса — код, реализующий метод доступа, строит индекс. В этой фазе методы доступа, поддерживающие отслеживание процесса, передают свои данные о текущем состоянии, и в этом столбце видна внутренняя фаза. Обычно ход построения индекса отражается в столбцах blocks_total и blocks_done, но также могут меняться и столбцы tuples_total и tuples_done. |
waiting for writers before validation | Ожидание окончания записи перед проверкой — процедура CREATE INDEX CONCURRENTLY или REINDEX CONCURRENTLY ожидает завершения транзакций, которые удерживают блокировки записи и могут записывать в таблицу. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid. |
index validation: scanning index | Проверка индекса: сканирование — процедура CREATE INDEX CONCURRENTLY сканирует индекс, находя кортежи, требующие проверки. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах blocks_total (показывающем общий размер индекса) и blocks_done. |
index validation: sorting tuples | Проверка индекса: сортировка кортежей — процедура CREATE INDEX CONCURRENTLY сортирует результат фазы сканирования индекса. |
index validation: scanning table | Проверка индекса: сканирование таблицы — процедура CREATE INDEX CONCURRENTLY сканирует таблицу, чтобы проверить кортежи индекса, собранные в предыдущих двух фазах. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах blocks_total (показывающем общий размер таблицы) и blocks_done. |
waiting for old snapshots | Ожидание старых снимков — процедура CREATE INDEX CONCURRENTLY или REINDEX CONCURRENTLY ожидает освобождения снимков теми транзакциями, которые могут видеть содержимое таблицы. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid. |
waiting for readers before marking dead | Ожидание завершения чтения перед отключением старого индекса — процедура REINDEX CONCURRENTLY ожидает завершения транзакций, которые удерживают блокировки чтения, прежде чем пометить старый индекс как нерабочий. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid. |
waiting for readers before dropping | Ожидание завершения чтения перед удалением старого индекса — процедура REINDEX CONCURRENTLY ожидает завершения транзакций, которые удерживают блокировки чтения, прежде чем удалить старый индекс. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid. |
27.4.2. Отслеживание выполнения VACUUM
В процессе выполнения VACUUM представление pg_stat_progress_vacuum будет содержать по одной строке для каждого обслуживающего процесса (включая рабочие процессы автоочистки), производящего очистку в данный момент. Таблицы ниже показывают, какая информация будет отслеживаться, и поясняют, как её интерпретировать. Выполнение команд VACUUM FULL отслеживается через pg_stat_progress_cluster, так как и VACUUM FULL, и CLUSTER перезаписывают таблицу, тогда как обычная команда VACUUM модифицирует её саму. См. Подраздел 27.4.3.
Таблица 27.24. Представление pg_stat_progress_vacuum
| Столбец | Тип | Описание |
|---|---|---|
pid | integer | Идентификатор (PID) обслуживающего процесса |
datid | oid | OID базы данных, к которой подключён этот обслуживающий процесс. |
datname | name | Имя базы данных, к которой подключён этот обслуживающий процесс. |
relid | oid | OID очищаемой таблицы. |
phase | text | Текущая фаза очистки. См. Таблицу 27.25. |
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 | Число «мёртвых» кортежей, собранных со времени последнего цикла очистки индекса. |
Таблица 27.25. Фазы 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 завершит свою работу. |
27.4.3. Отслеживание выполнения CLUSTER
Во время выполнения CLUSTER или VACUUM FULL представление pg_stat_progress_cluster будет содержать по одной строке для каждого обслуживающего процесса, выполняющего любую из этих команд. Таблицы ниже показывают, какая информация будет отслеживаться, и поясняют, как её интерпретировать.
Таблица 27.26. Представление pg_stat_progress_cluster
| Столбец | Тип | Описание |
|---|---|---|
pid | integer | Идентификатор (PID) обслуживающего процесса |
datid | oid | OID базы данных, к которой подключён этот обслуживающий процесс. |
datname | name | Имя базы данных, к которой подключён этот обслуживающий процесс. |
relid | oid | OID обрабатываемой таблицы. |
command | text | Выполняемая команда: CLUSTER или VACUUM FULL. |
phase | text | Текущая фаза обработки. См. Таблицу 27.27. |
cluster_index_relid | oid | Если таблица сканируется по индексу, это поле содержит OID данного индекса, а иначе — 0. |
heap_tuples_scanned | bigint | Число просканированных кортежей кучи. Этот счётчик увеличивается только в фазе seq scanning heap, index scanning heap или writing new heap. |
heap_tuples_written | bigint | Число записанных кортежей кучи. Этот счётчик увеличивается только в фазе seq scanning heap, index scanning heap или writing new heap. |
heap_blks_total | bigint | Общее число блоков кучи в таблице. Это число отражает состояние в начале фазы seq scanning heap. |
heap_blks_scanned | bigint | Число просканированных блоков кучи. Этот счётчик увеличивается только в фазе seq scanning heap. |
index_rebuild_count | bigint | Число перестроенных индексов. Это счётчик увеличивается только в фазе rebuilding index. |
Таблица 27.27. Фазы CLUSTER и VACUUM FULL
| Фаза | Описание |
|---|---|
initializing | Команда готовится начать сканирование кучи. Эта фаза должна быть очень быстрой. |
seq scanning heap | Команда в данный момент сканирует таблицу последовательным образом. |
index scanning heap | CLUSTER в данный момент сканирует таблицу по индексу. |
sorting tuples | CLUSTER в данный момент сортирует кортежи. |
writing new heap | CLUSTER в данный момент записывает новую кучу. |
swapping relation files | Команда в данный момент переставляет только что построенные файлы на место. |
rebuilding index | Команда в данный момент перестраивает индекс. |
performing final cleanup | Команда выполняет окончательную очистку. После этой фазы CLUSTER или VACUUM FULL завершит работу. |
27.4. Progress Reporting
PostgreSQL has the ability to report the progress of certain commands during command execution. Currently, the only commands which support progress reporting are CREATE INDEX, VACUUM and CLUSTER. This may be expanded in the future.
27.4.1. CREATE INDEX Progress Reporting
Whenever CREATE INDEX or REINDEX is running, the pg_stat_progress_create_index view will contain one row for each backend that is currently creating indexes. The tables below describe the information that will be reported and provide information about how to interpret it.
Table 27.22. pg_stat_progress_create_index 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 on which the index is being created. |
index_relid | oid | OID of the index being created or reindexed. During a non-concurrent CREATE INDEX, this is 0. |
command | text | The command that is running: CREATE INDEX, CREATE INDEX CONCURRENTLY, REINDEX, or REINDEX CONCURRENTLY. |
phase | text | Current processing phase of index creation. See Table 27.23. |
lockers_total | bigint | Total number of lockers to wait for, when applicable. |
lockers_done | bigint | Number of lockers already waited for. |
current_locker_pid | bigint | Process ID of the locker currently being waited for. |
blocks_total | bigint | Total number of blocks to be processed in the current phase. |
blocks_done | bigint | Number of blocks already processed in the current phase. |
tuples_total | bigint | Total number of tuples to be processed in the current phase. |
tuples_done | bigint | Number of tuples already processed in the current phase. |
partitions_total | bigint | When creating an index on a partitioned table, this column is set to the total number of partitions on which the index is to be created. |
partitions_done | bigint | When creating an index on a partitioned table, this column is set to the number of partitions on which the index has been completed. |
Table 27.23. CREATE INDEX Phases
| Phase | Description |
|---|---|
initializing | CREATE INDEX or REINDEX is preparing to create the index. This phase is expected to be very brief. |
waiting for writers before build | CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY is waiting for transactions with write locks that can potentially see the table to finish. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase. |
building index | The index is being built by the access method-specific code. In this phase, access methods that support progress reporting fill in their own progress data, and the subphase is indicated in this column. Typically, blocks_total and blocks_done will contain progress data, as well as potentially tuples_total and tuples_done. |
waiting for writers before validation | CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY is waiting for transactions with write locks that can potentially write into the table to finish. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase. |
index validation: scanning index | CREATE INDEX CONCURRENTLY is scanning the index searching for tuples that need to be validated. This phase is skipped when not in concurrent mode. Columns blocks_total (set to the total size of the index) and blocks_done contain the progress information for this phase. |
index validation: sorting tuples | CREATE INDEX CONCURRENTLY is sorting the output of the index scanning phase. |
index validation: scanning table | CREATE INDEX CONCURRENTLY is scanning the table to validate the index tuples collected in the previous two phases. This phase is skipped when not in concurrent mode. Columns blocks_total (set to the total size of the table) and blocks_done contain the progress information for this phase. |
waiting for old snapshots | CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY is waiting for transactions that can potentially see the table to release their snapshots. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase. |
waiting for readers before marking dead | REINDEX CONCURRENTLY is waiting for transactions with read locks on the table to finish, before marking the old index dead. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase. |
waiting for readers before dropping | REINDEX CONCURRENTLY is waiting for transactions with read locks on the table to finish, before dropping the old index. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase. |
27.4.2. 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 for VACUUM FULL commands is reported via pg_stat_progress_cluster because both VACUUM FULL and CLUSTER rewrite the table, while regular VACUUM only modifies it in place. See Section 27.4.3.
Table 27.24. 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 27.25. |
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 27.25. 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. |
27.4.3. CLUSTER Progress Reporting
Whenever CLUSTER or VACUUM FULL is running, the pg_stat_progress_cluster view will contain a row for each backend that is currently running either command. The tables below describe the information that will be reported and provide information about how to interpret it.
Table 27.26. pg_stat_progress_cluster 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 clustered. |
command | text | The command that is running. Either CLUSTER or VACUUM FULL. |
phase | text | Current processing phase. See Table 27.27. |
cluster_index_relid | oid | If the table is being scanned using an index, this is the OID of the index being used; otherwise, it is zero. |
heap_tuples_scanned | bigint | Number of heap tuples scanned. This counter only advances when the phase is seq scanning heap, index scanning heap or writing new heap. |
heap_tuples_written | bigint | Number of heap tuples written. This counter only advances when the phase is seq scanning heap, index scanning heap or writing new heap. |
heap_blks_total | bigint | Total number of heap blocks in the table. This number is reported as of the beginning of seq scanning heap. |
heap_blks_scanned | bigint | Number of heap blocks scanned. This counter only advances when the phase is seq scanning heap. |
index_rebuild_count | bigint | Number of indexes rebuilt. This counter only advances when the phase is rebuilding index. |
Table 27.27. CLUSTER and VACUUM FULL Phases
| Phase | Description |
|---|---|
initializing | The command is preparing to begin scanning the heap. This phase is expected to be very brief. |
seq scanning heap | The command is currently scanning the table using a sequential scan. |
index scanning heap | CLUSTER is currently scanning the table using an index scan. |
sorting tuples | CLUSTER is currently sorting tuples. |
writing new heap | CLUSTER is currently writing the new heap. |
swapping relation files | The command is currently swapping newly-built files into place. |
rebuilding index | The command is currently rebuilding an index. |
performing final cleanup | The command is performing final cleanup. When this phase is completed, CLUSTER or VACUUM FULL will end. |