无法访问 PostgreSQL 中的流复制统计信息

Can't get access to streaming replication stats in PostgreSQL

我有需要监控的流复制。所以 Zabbix 有一个特殊的用户。我不想使用 pg_mongz 并决定将我自己的查询设置为 pg_catalog 模式的视图 pg_stat_replication 以获取复制状态。

当我使用查询时:

select * 
from pg_stat_replication;

它 returns 管理员的复制状态记录。但是当我以监控用户身份登录时,它 returns 只是:

pid, usesysid, usename, application_name

所以client_addr、client_hostname、client_port、backend_start、state、sent_location、write_location等参数都是空。

首先,我向我的用户授予了架构和表的权限:

grant usage on schema pg_catalog to usrmonitor;
grant select on all tables in schema pg_catalog to usrmonitor;

但这并没有帮助。当我查看视图时,我发现查询使用函数并授予执行:

grant execute on function pg_stat_get_wal_senders() to usrmonitor;
grant execute on function pg_stat_get_activity(integer) to usrmonitor;

但是 select 查询仍然 returns 空列。可能是什么问题?

是的,有意将这些字段的访问权限限制为超级用户。

作为解决方法,您可以使用具有 SECURITY DEFINER 属性的函数作为代理:

SECURITY DEFINER specifies that the function is to be executed with the privileges of the user that created it.

因此,作为超级用户(通常是 postgres 用户),执行:

CREATE FUNCTION func_stat_replication() RETURNS SETOF pg_stat_replication as
$$ select * from pg_stat_replication; $$
LANGUAGE sql SECURITY DEFINER;

然后revoke/grant允许使用那个功能,这样就只有监听了 允许用户执行它:

REVOKE EXECUTE ON FUNCTION func_stat_replication() FROM public;
GRANT EXECUTE ON FUNCTION func_stat_replication() to usrmonitor;

那么usrmonitor应该执行:

 SELECT * FROM func_stat_replication();

它会得到与超级用户相同的结果。

从 PostgreSQL 10 开始,就这么简单:

GRANT pg_monitor TO monitoring_user;

(来源:https://pganalyze.com/blog/whats-new-in-postgres-10-monitoring-improvements