F.37. pg_buffercache — информация о состоянии буферного кеша Postgres Pro #
- F.37.1. Представление
pg_buffercache- F.37.2. Представление
pg_buffercache_numa- F.37.3. Функция
pg_buffercache_summary()- F.37.4. Функция
pg_buffercache_usage_counts()- F.37.5. Функция
pg_buffercache_evict()- F.37.6. Функция
pg_buffercache_evict_relation()- F.37.7. Функция
pg_buffercache_evict_all()- F.37.8. Пример вывода
- F.37.9. Авторы
- F.37.2. Представление
Модуль pg_buffercache даёт возможность понять, что происходит в общем кеше буферов в реальном времени, а также позволяет вытеснять данные из него на низком уровне в целях тестирования.
Этот модуль предоставляет функцию pg_buffercache_pages() (обёрнута в представление pg_buffercache), функцию pg_buffercache_numa_pages() (обёрнута в представление pg_buffercache_numa), а также функции pg_buffercache_summary(), pg_buffercache_usage_counts(), pg_buffercache_evict(), pg_buffercache_evict_relation() и pg_buffercache_evict_all().
Функция pg_buffercache_pages() возвращает набор записей, каждая строка которого описывает состояние одного буфера в общем кеше. Для удобства пользования обёрткой функции является представление pg_buffercache.
Функция pg_buffercache_numa_pages() возвращает сопоставления узлов NUMA для буферов в общем кеше. Эта информация не выводится функцией pg_buffercache_pages() без обёртки, поскольку её медленнее извлекать. Для удобства пользования обёрткой функции является представление pg_buffercache_numa.
Функция pg_buffercache_summary() возвращает одну строку со сводной информацией о состоянии общего кеша буферов.
Функция pg_buffercache_usage_counts() возвращает набор записей, в каждой строке которого указано количество буферов в разбивке по счётчику использования.
По умолчанию использование упомянутых выше функций разрешено только суперпользователям и ролям с правами роли pg_monitor. Дать доступ другим ролям можно с помощью GRANT.
Функция pg_buffercache_evict() позволяет вытеснять блоки из пула буферов по идентификатору блока. Вызывать эту функцию разрешено только суперпользователям.
Функция pg_buffercache_evict_relation() позволяет вытеснять из пула буферов все незакреплённые общие буферы в отношении по идентификатору отношения. Вызывать эту функцию разрешено только суперпользователям.
Функция pg_buffercache_evict_all() позволяет вытеснять все незакреплённые общие буферы из пула буферов. Вызывать эту функцию разрешено только суперпользователям.
F.37.1. Представление pg_buffercache #
Определения столбцов, содержащихся в представлении, показаны в Таблице F.19.
Таблица F.19. Столбцы pg_buffercache
Тип столбца Описание |
|---|
ID, в диапазоне 1.. |
Номер файлового узла для отношения |
OID табличного пространства, содержащего отношение |
OID базы данных, содержащей отношение |
Номер слоя в отношении |
Номер страницы в отношении |
Страница загрязнена? |
Счётчик обращений по часовой стрелке |
Число обслуживающих процессов, закрепивших этот буфер |
Для каждого буфера в общем кеше выдаётся одна строка. Для неиспользуемых буферов все поля равны NULL, за исключением bufferid. Общие системные каталоги показываются как относящиеся к базе данных под номером 0.
Так как кеш используется совместно всеми базами данных, обычно в нём находятся и страницы из отношений, не принадлежащих текущей базе данных. Это означает, что для некоторых строк при соединении с pg_class не найдутся соответствующие строки, либо соединение будет некорректным. Если вы хотите выполнить соединение с pg_class, будет правильным ограничить соединение строками, в которых reldatabase содержит OID текущей базы данных или ноль.
Для копирования данных состояния, которые будут отображаться, блокировки в менеджере буферов не устанавливаются. Поэтому обращения к представлению pg_buffercache меньше сказываются на обычной активности буферов, но набор результатов, полученный для всех буферов, в целом может оказаться несогласованным. Однако внутри каждого отдельного буфера согласованность информации гарантируется.
F.37.2. Представление pg_buffercache_numa #
Определения столбцов, содержащихся в представлении, показаны в Таблице F.20.
Таблица F.20. Столбцы pg_buffercache_numa
Тип столбца Описание |
|---|
ID, в диапазоне 1.. |
Номер страницы памяти ОС для этого буфера |
Идентификатор узла NUMA |
Поскольку, чтобы запросить идентификатор узла NUMA для каждой страницы, требуется выгрузить страницы памяти, первое выполнение этой функции может занять много времени. В любом случае (при первом или повторном запуске функции) извлекать информацию таким способом затратно, и часто обращаться к представлению не рекомендуется.
Предупреждение
При определении узла NUMA представление обращается ко всем страницам сегмента разделяемой памяти. Это приводит к принудительному выделению разделяемой памяти, если она не была выделена ранее, при этом память может быть выделена на одном узле NUMA (в зависимости от конфигурации системы).
F.37.3. Функция pg_buffercache_summary() #
Определения столбцов, возвращаемых функцией, показаны в Таблице F.21.
Таблица F.21. Выходные столбцы pg_buffercache_summary()
Тип столбца Описание |
|---|
Число используемых общих буферов |
Число неиспользуемых общих буферов |
Число загрязнённых общих буферов |
Число закреплённых общих буферов |
Среднее значение счётчика использования общих буферов |
Функция pg_buffercache_summary() возвращает одну строку со сводной информацией о состоянии всех общих буферов. Подобную и более подробную информацию можно получить из представления pg_buffercache, но pg_buffercache_summary() обходится существенно дешевле.
Как и представление pg_buffercache, pg_buffercache_summary() не получает блокировки менеджера буферов, поэтому при параллельной работе в базе данных допустима незначительная погрешность результатов функции.
F.37.4. Функция pg_buffercache_usage_counts() #
Определения столбцов, возвращаемых функцией, показаны в Таблице F.22.
Таблица F.22. Выходные столбцы pg_buffercache_usage_counts()
Тип столбца Описание |
|---|
Возможное значение счётчика использования буферов |
Число буферов в разбивке по счётчику использования |
Число загрязнённых буферов в разбивке по счётчику использования |
Число закреплённых буферов в разбивке по счётчику использования |
Функция pg_buffercache_usage_counts() возвращает набор строк со сводной информацией о состоянии всех общих буферов, агрегированных по возможным значениям счётчика использования. Подобную и более подробную информацию можно получить с помощью представления pg_buffercache, но pg_buffercache_usage_counts() обходится существенно дешевле.
Как и представление pg_buffercache, pg_buffercache_usage_counts() не получает блокировки менеджера буферов, поэтому при параллельной работе в базе данных допустима незначительная погрешность результатов функции.
F.37.5. Функция pg_buffercache_evict() #
Функция pg_buffercache_evict() принимает идентификатор буфера, который отображается в столбце bufferid представления pg_buffercache. Возвращает информацию о том, был ли буфер вытеснен и сброшен. В столбце buffer_evicted выводится true, если буфер был вытеснен, и false, если буфер был недействителен, не мог быть вытеснен, так как был закреплён, или снова загрязнился после попытки записи. В столбце buffer_flushed выводится true, если буфер был сброшен. При этом буфер может быть сброшен любым пользователем. После завершения функции результат сразу становится устаревшим, поскольку из-за параллельно выполняемых операций буфер может снова стать действительным в любое время. Эта функция предназначена только для тестирования.
F.37.6. Функция pg_buffercache_evict_relation() #
Функция pg_buffercache_evict_relation() очень похожа на функцию pg_buffercache_evict(). Отличие состоит в том, что вместо идентификатора буфера функция pg_buffercache_evict_relation() принимает идентификатор отношения. Функция пытается вытеснить все буферы для всех слоёв этого отношения. Возвращает количество вытесненных буферов, сброшенных буферов и буферов, которые вытеснить не удалось. Буферы могли быть сброшены любым пользователем. После завершения функции результат сразу становится устаревшим, поскольку из-за параллельно выполняемых операций буфер может быть снова прочитан. Эта функция предназначена только для тестирования.
F.37.7. Функция pg_buffercache_evict_all() #
Функция pg_buffercache_evict_all() очень похожа на функцию pg_buffercache_evict(). Отличие состоит в том, что функция pg_buffercache_evict_all() не принимает аргументов. Вместо этого она пытается вытеснить все буферы из пула буферов. Возвращает количество вытесненных буферов, сброшенных буферов и буферов, которые вытеснить не удалось. Буферы могли быть сброшены любыми пользователями. После завершения функции результат сразу становится устаревшим, поскольку из-за параллельно выполняемых операций буферы могут быть снова прочитаны. Эта функция предназначена только для тестирования.
F.37.8. Пример вывода #
regression=# SELECT n.nspname, c.relname, count(*) AS buffers
FROM pg_buffercache b JOIN pg_class c
ON b.relfilenode = pg_relation_filenode(c.oid) AND
b.reldatabase IN (0, (SELECT oid FROM pg_database
WHERE datname = current_database()))
JOIN pg_namespace n ON n.oid = c.relnamespace
GROUP BY n.nspname, c.relname
ORDER BY 3 DESC
LIMIT 10;
nspname | relname | buffers
------------+------------------------+---------
public | delete_test_table | 593
public | delete_test_table_pkey | 494
pg_catalog | pg_attribute | 472
public | quad_poly_tbl | 353
public | tenk2 | 349
public | tenk1 | 349
public | gin_test_idx | 306
pg_catalog | pg_largeobject | 206
public | gin_test_tbl | 188
public | spgist_text_tbl | 182
(10 rows)
regression=# SELECT * FROM pg_buffercache_summary();
buffers_used | buffers_unused | buffers_dirty | buffers_pinned | usagecount_avg
--------------+----------------+---------------+----------------+----------------
248 | 2096904 | 39 | 0 | 3.141129
(1 row)
regression=# SELECT * FROM pg_buffercache_usage_counts();
usage_count | buffers | dirty | pinned
-------------+---------+-------+--------
0 | 14650 | 0 | 0
1 | 1436 | 671 | 0
2 | 102 | 88 | 0
3 | 23 | 21 | 0
4 | 9 | 7 | 0
5 | 164 | 106 | 0
(6 rows)F.37.9. Авторы #
Марк Кирквуд <markir@paradise.net.nz>
Предложения по конструкции: Нейл Конвей <neilc@samurai.com>
Советы по отладке: Том Лейн <tgl@sss.pgh.pa.us>
F.37. pg_buffercache — inspect Postgres Pro buffer cache state #
- F.37.1. The
pg_buffercacheView- F.37.2. The
pg_buffercache_numaView- F.37.3. The
pg_buffercache_summary()Function- F.37.4. The
pg_buffercache_usage_counts()Function- F.37.5. The
pg_buffercache_evict()Function- F.37.6. The
pg_buffercache_evict_relation()Function- F.37.7. The
pg_buffercache_evict_all()Function- F.37.8. Sample Output
- F.37.9. Authors
- F.37.2. The
The pg_buffercache module provides a means for examining what's happening in the shared buffer cache in real time. It also offers a low-level way to evict data from it, for testing purposes.
This module provides the pg_buffercache_pages() function (wrapped in the pg_buffercache view), the pg_buffercache_numa_pages() function (wrapped in the pg_buffercache_numa view), the pg_buffercache_summary() function, the pg_buffercache_usage_counts() function, the pg_buffercache_evict() function, the pg_buffercache_evict_relation() function and the pg_buffercache_evict_all() function.
The pg_buffercache_pages() function returns a set of records, each row describing the state of one shared buffer entry. The pg_buffercache view wraps the function for convenient use.
The pg_buffercache_numa_pages() function provides NUMA node mappings for shared buffer entries. This information is not part of pg_buffercache_pages() itself, as it is much slower to retrieve. The pg_buffercache_numa view wraps the function for convenient use.
The pg_buffercache_summary() function returns a single row summarizing the state of the shared buffer cache.
The pg_buffercache_usage_counts() function returns a set of records, each row describing the number of buffers with a given usage count.
By default, use of the above functions is restricted to superusers and roles with privileges of the pg_monitor role. Access may be granted to others using GRANT.
The pg_buffercache_evict() function allows a block to be evicted from the buffer pool given a buffer identifier. Use of this function is restricted to superusers only.
The pg_buffercache_evict_relation() function allows all unpinned shared buffers in the relation to be evicted from the buffer pool given a relation identifier. Use of this function is restricted to superusers only.
The pg_buffercache_evict_all() function allows all unpinned shared buffers to be evicted in the buffer pool. Use of this function is restricted to superusers only.
F.37.1. The pg_buffercache View #
The definitions of the columns exposed by the view are shown in Table F.19.
Table F.19. pg_buffercache Columns
Column Type Description |
|---|
ID, in the range 1.. |
Filenode number of the relation |
Tablespace OID of the relation |
Database OID of the relation |
Fork number within the relation |
Page number within the relation |
Is the page dirty? |
Clock-sweep access count |
Number of backends pinning this buffer |
There is one row for each buffer in the shared cache. Unused buffers are shown with all fields null except bufferid. Shared system catalogs are shown as belonging to database zero.
Because the cache is shared by all the databases, there will normally be pages from relations not belonging to the current database. This means that there may not be matching join rows in pg_class for some rows, or that there could even be incorrect joins. If you are trying to join against pg_class, it's a good idea to restrict the join to rows having reldatabase equal to the current database's OID or zero.
Since buffer manager locks are not taken to copy the buffer state data that the view will display, accessing pg_buffercache view has less impact on normal buffer activity but it doesn't provide a consistent set of results across all buffers. However, we ensure that the information of each buffer is self-consistent.
F.37.2. The pg_buffercache_numa View #
The definitions of the columns exposed by the view are shown in Table F.20.
Table F.20. pg_buffercache_numa Columns
Column Type Description |
|---|
ID, in the range 1.. |
number of OS memory page for this buffer |
ID of NUMA node |
As NUMA node ID inquiry for each page requires memory pages to be paged-in, the first execution of this function can take a noticeable amount of time. In all the cases (first execution or not), retrieving this information is costly and querying the view at a high frequency is not recommended.
Warning
When determining the NUMA node, the view touches all memory pages for the shared memory segment. This will force allocation of the shared memory, if it wasn't allocated already, and the memory may get allocated in a single NUMA node (depending on system configuration).
F.37.3. The pg_buffercache_summary() Function #
The definitions of the columns exposed by the function are shown in Table F.21.
Table F.21. pg_buffercache_summary() Output Columns
Column Type Description |
|---|
Number of used shared buffers |
Number of unused shared buffers |
Number of dirty shared buffers |
Number of pinned shared buffers |
Average usage count of used shared buffers |
The pg_buffercache_summary() function returns a single row summarizing the state of all shared buffers. Similar and more detailed information is provided by the pg_buffercache view, but pg_buffercache_summary() is significantly cheaper.
Like the pg_buffercache view, pg_buffercache_summary() does not acquire buffer manager locks. Therefore concurrent activity can lead to minor inaccuracies in the result.
F.37.4. The pg_buffercache_usage_counts() Function #
The definitions of the columns exposed by the function are shown in Table F.22.
Table F.22. pg_buffercache_usage_counts() Output Columns
Column Type Description |
|---|
A possible buffer usage count |
Number of buffers with the usage count |
Number of dirty buffers with the usage count |
Number of pinned buffers with the usage count |
The pg_buffercache_usage_counts() function returns a set of rows summarizing the states of all shared buffers, aggregated over the possible usage count values. Similar and more detailed information is provided by the pg_buffercache view, but pg_buffercache_usage_counts() is significantly cheaper.
Like the pg_buffercache view, pg_buffercache_usage_counts() does not acquire buffer manager locks. Therefore concurrent activity can lead to minor inaccuracies in the result.
F.37.5. The pg_buffercache_evict() Function #
The pg_buffercache_evict() function takes a buffer identifier, as shown in the bufferid column of the pg_buffercache view. It returns information about whether the buffer was evicted and flushed. The buffer_evicted column is true on success, and false if the buffer wasn't valid, if it couldn't be evicted because it was pinned, or if it became dirty again after an attempt to write it out. The buffer_flushed column is true if the buffer was flushed. This does not necessarily mean that buffer was flushed by us, it might be flushed by someone else. The result is immediately out of date upon return, as the buffer might become valid again at any time due to concurrent activity. The function is intended for developer testing only.
F.37.6. The pg_buffercache_evict_relation() Function #
The pg_buffercache_evict_relation() function is very similar to the pg_buffercache_evict() function. The difference is that the pg_buffercache_evict_relation() takes a relation identifier instead of buffer identifier. It tries to evict all buffers for all forks in that relation. It returns the number of evicted buffers, flushed buffers and the number of buffers that could not be evicted. Flushed buffers haven't necessarily been flushed by us, they might have been flushed by someone else. The result is immediately out of date upon return, as buffers might immediately be read back in due to concurrent activity. The function is intended for developer testing only.
F.37.7. The pg_buffercache_evict_all() Function #
The pg_buffercache_evict_all() function is very similar to the pg_buffercache_evict() function. The difference is, the pg_buffercache_evict_all() function does not take an argument; instead it tries to evict all buffers in the buffer pool. It returns the number of evicted buffers, flushed buffers and the number of buffers that could not be evicted. Flushed buffers haven't necessarily been flushed by us, they might have been flushed by someone else. The result is immediately out of date upon return, as buffers might immediately be read back in due to concurrent activity. The function is intended for developer testing only.
F.37.8. Sample Output #
regression=# SELECT n.nspname, c.relname, count(*) AS buffers
FROM pg_buffercache b JOIN pg_class c
ON b.relfilenode = pg_relation_filenode(c.oid) AND
b.reldatabase IN (0, (SELECT oid FROM pg_database
WHERE datname = current_database()))
JOIN pg_namespace n ON n.oid = c.relnamespace
GROUP BY n.nspname, c.relname
ORDER BY 3 DESC
LIMIT 10;
nspname | relname | buffers
------------+------------------------+---------
public | delete_test_table | 593
public | delete_test_table_pkey | 494
pg_catalog | pg_attribute | 472
public | quad_poly_tbl | 353
public | tenk2 | 349
public | tenk1 | 349
public | gin_test_idx | 306
pg_catalog | pg_largeobject | 206
public | gin_test_tbl | 188
public | spgist_text_tbl | 182
(10 rows)
regression=# SELECT * FROM pg_buffercache_summary();
buffers_used | buffers_unused | buffers_dirty | buffers_pinned | usagecount_avg
--------------+----------------+---------------+----------------+----------------
248 | 2096904 | 39 | 0 | 3.141129
(1 row)
regression=# SELECT * FROM pg_buffercache_usage_counts();
usage_count | buffers | dirty | pinned
-------------+---------+-------+--------
0 | 14650 | 0 | 0
1 | 1436 | 671 | 0
2 | 102 | 88 | 0
3 | 23 | 21 | 0
4 | 9 | 7 | 0
5 | 164 | 106 | 0
(6 rows)
F.37.9. Authors #
Mark Kirkwood <markir@paradise.net.nz>
Design suggestions: Neil Conway <neilc@samurai.com>
Debugging advice: Tom Lane <tgl@sss.pgh.pa.us>