如何在PostgreSQL的Google Cloud SQL中终止会话?

时间:2018-06-11 21:25:32

标签: postgresql google-cloud-sql

由于Google Cloud SQL for PostgreSQL并没有给我们一个超级用户(甚至不是postgres用户),我无法看到其他会话从pg_stat_activity运行的查询,也不能在需要时终止其他会话

例如:

postgres@testdb=> select pg_terminate_backend(1584);
ERROR:  42501: must be a member of the role whose process is being terminated or member of pg_signal_backend
LOCATION:  pg_terminate_backend, misc.c:319
Time: 23.800 ms

如果没有真正的超级用户访问权限,我们如何在Cloud SQL PostgreSQL实例中执行这些操作?只有cloudsqladmin帐户是超级用户而AFAIK我不能成为:

postgres@testdb=> \dg
                                            List of roles
     Role name     |                         Attributes                         |      Member of
-------------------+------------------------------------------------------------+---------------------
 cloudsqladmin     | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 cloudsqlagent     | Create role, Create DB                                     | {cloudsqlsuperuser}
 cloudsqlreplica   | Replication                                                | {}
 cloudsqlsuperuser | Create role, Create DB                                     | {}
 don               | Create role, Create DB                                     | {cloudsqlsuperuser}
 postgres          | Create role, Create DB                                     | {cloudsqlsuperuser}

postgres@testdb=> set role cloudsqladmin;
ERROR:  42501: permission denied to set role "cloudsqladmin"
LOCATION:  call_string_check_hook, guc.c:9803
Time: 25.293 ms

FWIW,如果您以该会话的用户身份登录,可以终止会话。用户可以终止他们的任何会话,标准的PostgreSQL内容。

postgres@postgres=> select pg_terminate_backend(23644);
ERROR:  42501: must be a member of the role whose process is being terminated or member of pg_signal_backend
LOCATION:  pg_terminate_backend, misc.c:319

don@postgres=> select pg_terminate_backend(23644);
 pg_terminate_backend
----------------------
 t
(1 row)

2 个答案:

答案 0 :(得分:1)

pg_terminate_backend说:

  

pg_terminate_backend(pid int)-终止后端。如果调用角色是其后端要终止的角色的成员或已授予调用角色pg_signal_backend,但是只有超级用户可以终止超级用户后端,这也允许。 >

如果您是Google cloudsqlsuperusergcloud sql users create的默认成员)的成员,则可以授予自己权限:

GRANT pg_signal_backend TO myuser;

然后,您可以终止除超级用户之外的任何会话:

SELECT pg_terminate_backend(pid), * FROM pg_stat_activity
WHERE usename = 'rogue_user' AND pid <> pg_backend_pid();

pg_signal_backend是在v9.6中引入的-正是Google Cloud上的版本!

替代方法是担任other角色,以便能够终止me的会话:

GRANT other TO me;

答案 1 :(得分:0)

无法在Cloud SQL中为PostgreSQL用户授予超级用户角色。 {1}

在任何情况下,您都可以在Cloud Console的Cloud SQL部分的图表和日志中查询有关实例的信息。 {2}

{1}:https://cloud.google.com/sql/docs/postgres/users#other_postgresql_users

{2}:https://cloud.google.com/sql/docs/postgres/diagnose-issues