Skip to content

Instantly share code, notes, and snippets.

@pstef
Last active January 4, 2024 11:53
Show Gist options
  • Save pstef/04beb2587503d22646b3fa93be0a74a3 to your computer and use it in GitHub Desktop.
Save pstef/04beb2587503d22646b3fa93be0a74a3 to your computer and use it in GitHub Desktop.
pg_stat_statements plugin for munin
# pwd
/usr/local/etc/munin/plugins
# tail -n4 ../plugin-conf.d/plugins.conf
[pg_stat_statements]
env.STSTSCH statstatements
env.PGUSER munin
env.PGDATABASE postgres
# cat pg_stat_statements
#!/bin/sh
LIM=${STSTLIM:-10}
SCH=${STSTSCH:-public}
[ "$1" = 'config' ] && {
printf 'graph_title pg_stat_statements\ngraph_category postgresql\n'
printf 'graph_scale no\n'
printf 'xrest.label rest\nxrest.draw AREA\nxrest.type DERIVE\nxrest.min 0\n'
psql -qAXt -c \
"SELECT CONCAT('x', queryid, field.attribute)
FROM (
SELECT dbid, to_hex(queryid) AS queryid, regexp_replace(query, '\s+', ' ', 'g') AS query
FROM ${SCH}.pg_stat_statements ORDER BY total_time DESC LIMIT ${LIM}
) statements
JOIN pg_database pgdb ON pgdb.oid = statements.dbid
CROSS JOIN LATERAL (VALUES
('.label ' || queryid),
('.type DERIVE'),
('.draw STACK'),
('.min 0'),
('.info ' || pgdb.datname),
('.extinfo ' || query)
) field (attribute)
ORDER BY 1"
exit 0;
}
psql -qAXt -c \
"SELECT format('x%s.value %s', COALESCE(queryid, 'rest'), sum(total_time)::bigint)
FROM (
SELECT to_hex(queryid) AS queryid, total_time, row_number() OVER (ORDER BY total_time DESC) <= ${LIM} AS top
FROM ${SCH}.pg_stat_statements
) statements
GROUP BY GROUPING SETS (queryid, top)
HAVING (queryid IS NULL AND NOT top) OR queryid IS NOT NULL
ORDER BY queryid IS NULL AND NOT top DESC, sum(total_time) DESC LIMIT ${LIM} + 1"
# su -m munin -c 'munin-run -d pg_stat_statements'
# Processing plugin configuration from /usr/local/etc/munin/plugin-conf.d/plugins.conf
# Processing plugin configuration from /usr/local/etc/munin/plugin-conf.d/plugins.conf.sample
# Setting up environment
# Environment STSTSCH = statstatements
# Environment PGUSER = munin
# Environment PGDATABASE = postgres
# Environment PATH = /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# About to run '/usr/local/etc/munin/plugins/pg_stat_statements'
xrest.value 114566
x7cbe7843cce091aa.value 2124426
x6619b41b5c232882.value 217714
xb7ea8f619d8d22ae.value 106989
x3cedb8245db045f3.value 41997
x4a9ab1ed79654ab6.value 27229
xf5912ee3fcfd3ad3.value 26869
xa42bc634b7889aef.value 20687
x509b0f2cb42a8685.value 16824
xde2ec61e6da45020.value 16666
xf3855adb7283d6ea.value 14622
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment