PG锁和阻塞发现与处理

20 篇文章 0 订阅

一、 阻塞查询

PostgreSQL提供了两个视图

  • pg_locks展示锁信息,每一个被锁或者等待锁的对象一条记录。
  • pg_stat_activity,每个会话一条记录,显示会话状态信息。

查看被阻塞进程

-- granted=t是阻塞别人的,f是被阻塞的
SELECT database, locktype, relation, relation::regclass, mode, pid FROM pg_locks where granted='f';

根据pid和relation找到阻塞源(granted=t)

-- granted=t是阻塞别人的,f是被阻塞的
SELECT database, locktype,relation::regclass, mode, pid FROM pg_locks where granted='t';

根据被阻塞/阻塞源的pid查正在执行的语句

select pid,usename,substring(query from 0 for 50),now()-query_start as time,wait_event,state from pg_stat_activity where pid=xxx;

state为idle in transaction,说明该会话执行完了但没有提交

二、 解决方法

1. 找到所在会话执行提交或回滚

2. kill阻塞源会话

SELECT pg_cancel_backend(前步pid); -- Cancel a backend's current query.
-- 或者
SELECT pg_terminate_backend(前步pid); -- Terminate a backend.

区别参考:PostgreSQL: Documentation: 11: 9.26. System Administration Functions

查看当前事务锁等待、持锁信息的SQL

如果觉得前面分步操作太麻烦,可以用下面的sql一次查出(比较长,可以建成视图)

with    
t_wait as    
(    
  select a.mode,a.locktype,a.database,a.relation,a.page,a.tuple,a.classid,a.granted,   
  a.objid,a.objsubid,a.pid,a.virtualtransaction,a.virtualxid,a.transactionid,a.fastpath,    
  b.state,b.query,b.xact_start,b.query_start,b.usename,b.datname,b.client_addr,b.client_port,b.application_name   
    from pg_locks a,pg_stat_activity b where a.pid=b.pid and not a.granted   
),   
t_run as   
(   
  select a.mode,a.locktype,a.database,a.relation,a.page,a.tuple,a.classid,a.granted,   
  a.objid,a.objsubid,a.pid,a.virtualtransaction,a.virtualxid,a.transactionid,a.fastpath,   
  b.state,b.query,b.xact_start,b.query_start,b.usename,b.datname,b.client_addr,b.client_port,b.application_name   
    from pg_locks a,pg_stat_activity b where a.pid=b.pid and a.granted   
),   
t_overlap as   
(   
  select r.* from t_wait w join t_run r on   
  (   
    r.locktype is not distinct from w.locktype and   
    r.database is not distinct from w.database and   
    r.relation is not distinct from w.relation and   
    r.page is not distinct from w.page and   
    r.tuple is not distinct from w.tuple and   
    r.virtualxid is not distinct from w.virtualxid and   
    r.transactionid is not distinct from w.transactionid and   
    r.classid is not distinct from w.classid and   
    r.objid is not distinct from w.objid and   
    r.objsubid is not distinct from w.objsubid and   
    r.pid <> w.pid   
  )    
),    
t_unionall as    
(    
  select r.* from t_overlap r    
  union all    
  select w.* from t_wait w    
)    
select locktype,datname,relation::regclass,page,tuple,virtualxid,transactionid::text,classid::regclass,objid,objsubid,   
string_agg(   
'Pid: '||case when pid is null then 'NULL' else pid::text end||chr(10)||   
'Lock_Granted: '||case when granted is null then 'NULL' else granted::text end||' , Mode: '||case when mode is null then 'NULL' else mode::text end||' , FastPath: '||case when fastpath is null then 'NULL' else fastpath::text end||' , VirtualTransaction: '||case when virtualtransaction is null then 'NULL' else virtualtransaction::text end||' , Session_State: '||case when state is null then 'NULL' else state::text end||chr(10)||   
'Username: '||case when usename is null then 'NULL' else usename::text end||' , Database: '||case when datname is null then 'NULL' else datname::text end||' , Client_Addr: '||case when client_addr is null then 'NULL' else client_addr::text end||' , Client_Port: '||case when client_port is null then 'NULL' else client_port::text end||' , Application_Name: '||case when application_name is null then 'NULL' else application_name::text end||chr(10)||    
'Xact_Start: '||case when xact_start is null then 'NULL' else xact_start::text end||' , Query_Start: '||case when query_start is null then 'NULL' else query_start::text end||' , Xact_Elapse: '||case when (now()-xact_start) is null then 'NULL' else (now()-xact_start)::text end||' , Query_Elapse: '||case when (now()-query_start) is null then 'NULL' else (now()-query_start)::text end||chr(10)||    
'SQL (Current SQL in Transaction): '||chr(10)||  
case when query is null then 'NULL' else query::text end,    
chr(10)||'--------'||chr(10)    
order by    
  (  case mode    
    when 'INVALID' then 0   
    when 'AccessShareLock' then 1   
    when 'RowShareLock' then 2   
    when 'RowExclusiveLock' then 3   
    when 'ShareUpdateExclusiveLock' then 4   
    when 'ShareLock' then 5   
    when 'ShareRowExclusiveLock' then 6   
    when 'ExclusiveLock' then 7   
    when 'AccessExclusiveLock' then 8   
    else 0   
  end  ) desc,   
  (case when granted then 0 else 1 end)  
) as lock_conflict  
from t_unionall   
group by   
locktype,datname,relation,page,tuple,virtualxid,transactionid::text,classid,objid,objsubid ;  

输出格式如下

postgres=#   \x  
Expanded display is on.  
postgres=# select * from v_locks_monitor ;  
-[ RECORD 1 ]-+------------------------------------------------------------------------------------------------------------------------------------------------------  
locktype      | relation  
datname       | postgres  
relation      | locktest  
page          |   
tuple         |   
virtualxid    |   
transactionid |   
classid       |   
objid         |   
objsubid      |   
string_agg    | Pid: 23043                                                                                                                                           +  
              | Granted: false , Mode: AccessExclusiveLock , FastPath: false , VirtualTransaction: 4/1450064 , Session_State: active                                 +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:43:43.735829+08 , Query_Start: 2017-05-21 21:43:50.965797+08 , Xact_Elapse: 00:01:11.919991 , Query_Elapse: 00:01:04.690023+  
              | Query: truncate locktest ;                                                                                                                           +  
              | --------                                                                                                                                             +  
              | Pid: 40698                                                                                                                                           +  
              | Granted: true , Mode: RowExclusiveLock , FastPath: false , VirtualTransaction: 6/1031925 , Session_State: idle in transaction                        +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:43:15.173798+08 , Query_Start: 2017-05-21 21:43:24.338804+08 , Xact_Elapse: 00:01:40.482022 , Query_Elapse: 00:01:31.317016+  
              | Query: insert into locktest values (2,'test');                                                                                                       +  
              | --------                                                                                                                                             +  
              | Pid: 17515                                                                                                                                           +  
              | Granted: true , Mode: RowExclusiveLock , FastPath: false , VirtualTransaction: 3/5671759 , Session_State: idle in transaction                        +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:42:19.199124+08 , Query_Start: 2017-05-21 21:42:47.820125+08 , Xact_Elapse: 00:02:36.456696 , Query_Elapse: 00:02:07.835695+  
              | Query: select * from locktest ;                                                                                                                      +  
              | --------                                                                                                                                             +  
              | Pid: 17515                                                                                                                                           +  
              | Granted: true , Mode: RowExclusiveLock , FastPath: false , VirtualTransaction: 3/5671759 , Session_State: idle in transaction                        +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:42:19.199124+08 , Query_Start: 2017-05-21 21:42:47.820125+08 , Xact_Elapse: 00:02:36.456696 , Query_Elapse: 00:02:07.835695+  
              | Query: select * from locktest ;                                                                                                                      +  
              | --------                                                                                                                                             +  
              | Pid: 40698                                                                                                                                           +  
              | Granted: true , Mode: RowExclusiveLock , FastPath: false , VirtualTransaction: 6/1031925 , Session_State: idle in transaction                        +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:43:15.173798+08 , Query_Start: 2017-05-21 21:43:24.338804+08 , Xact_Elapse: 00:01:40.482022 , Query_Elapse: 00:01:31.317016+  
              | Query: insert into locktest values (2,'test');                                                                                                       +  
              | --------                                                                                                                                             +  
              | Pid: 40199                                                                                                                                           +  
              | Granted: true , Mode: AccessShareLock , FastPath: false , VirtualTransaction: 5/1029276 , Session_State: idle in transaction                         +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:43:01.745129+08 , Query_Start: 2017-05-21 21:43:05.928125+08 , Xact_Elapse: 00:01:53.910691 , Query_Elapse: 00:01:49.727695+  
              | Query: select * from locktest ;                                                                                                                      +  
              | --------                                                                                                                                             +  
              | Pid: 17515                                                                                                                                           +  
              | Granted: true , Mode: AccessShareLock , FastPath: false , VirtualTransaction: 3/5671759 , Session_State: idle in transaction                         +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:42:19.199124+08 , Query_Start: 2017-05-21 21:42:47.820125+08 , Xact_Elapse: 00:02:36.456696 , Query_Elapse: 00:02:07.835695+  
              | Query: select * from locktest ;                                                                                                                      +  
              | --------                                                                                                                                             +  
              | Pid: 40199                                                                                                                                           +  
              | Granted: true , Mode: AccessShareLock , FastPath: false , VirtualTransaction: 5/1029276 , Session_State: idle in transaction                         +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:43:01.745129+08 , Query_Start: 2017-05-21 21:43:05.928125+08 , Xact_Elapse: 00:01:53.910691 , Query_Elapse: 00:01:49.727695+  
              | Query: select * from locktest ;                                                                                                                      +  
              | --------                                                                                                                                             +  
              | Pid: 17515                                                                                                                                           +  
              | Granted: true , Mode: AccessShareLock , FastPath: false , VirtualTransaction: 3/5671759 , Session_State: idle in transaction                         +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:42:19.199124+08 , Query_Start: 2017-05-21 21:42:47.820125+08 , Xact_Elapse: 00:02:36.456696 , Query_Elapse: 00:02:07.835695+  
              | Query: select * from locktest ;                                                                                                                      +  
              | --------                                                                                                                                             +  
              | Pid: 24781                                                                                                                                           +  
              | Granted: false , Mode: AccessShareLock , FastPath: false , VirtualTransaction: 7/1025270 , Session_State: active                                     +  
              | Username: postgres , Database: postgres , Client_Addr: NULL , Client_Port: -1 , Application_Name: psql                                               +  
              | Xact_Start: 2017-05-21 21:44:20.725834+08 , Query_Start: 2017-05-21 21:44:20.725834+08 , Xact_Elapse: 00:00:34.929986 , Query_Elapse: 00:00:34.929986+  
              | Query: select * from locktest ;  

查看final block session

with recursive tmp_lock as (
    select distinct
           --w.mode w_mode,w.page w_page,
           --w.tuple w_tuple,w.xact_start w_xact_start,w.query_start w_query_start,
           --now()-w.query_start w_locktime,w.query w_query 
           w.pid as id,--w_pid,
           r.pid as parentid--r_pid,
           --r.locktype,r.mode r_mode,r.usename r_user,r.datname r_db,
           --r.relation::regclass,
           --r.page r_page,r.tuple r_tuple,r.xact_start r_xact_start,
           --r.query_start r_query_start,
           --now()-r.query_start r_locktime,r.query r_query,   
    from (
          select a.mode,a.locktype,a.database,
                 a.relation,a.page,a.tuple,a.classid,
                 a.objid,a.objsubid,a.pid,a.virtualtransaction,a.virtualxid,
                 a.transactionid,
                 b.query as query,
                 b.xact_start,b.query_start,b.usename,b.datname 
           from pg_locks a,
                pg_stat_activity b 
          where a.pid=b.pid 
            and not a.granted 
          ) w,
         (
          select a.mode,a.locktype,a.database,
                 a.relation,a.page,a.tuple,a.classid,
                 a.objid,a.objsubid,a.pid,a.virtualtransaction,a.virtualxid,
                 a.transactionid,
                 b.query as query,
                 b.xact_start,b.query_start,b.usename,b.datname 
            from pg_locks a,
                 pg_stat_activity b -- select pg_typeof(pid) from pg_stat_activity
           where a.pid=b.pid 
             and a.granted 
          ) r 
    where 1=1
      and r.locktype is not distinct from w.locktype 
      and r.database is not distinct from w.database 
      and r.relation is not distinct from w.relation 
      and r.page is not distinct from w.page 
      and r.tuple is not distinct from w.tuple 
      and r.classid is not distinct from w.classid 
      and r.objid is not distinct from w.objid 
      and r.objsubid is not distinct from w.objsubid 
      and r.transactionid is not distinct from w.transactionid 
      and r.pid <> w.pid
        
),tmp0 as (
  select *
    from tmp_lock tl
   union all
  --查找root,同一时刻可能有多个root
  select t1.parentid,0::int4
    from tmp_lock t1
   where 1=1
     and t1.parentid not in (select id from tmp_lock)
),tmp3 (pathid,depth,id,parentid) as (
  --对过滤出的机构向下递归,构成tree
  SELECT array[id]::text[] as pathid,1 as depth,id,parentid
    FROM tmp0
   where 1=1
     and parentid=0
   union
  SELECT t0.pathid||array[t1.id]::text[] as pathid,t0.depth+1 as depth,t1.id,t1.parentid
    FROM tmp0 t1,  
         tmp3 t0
   where 1=1
     and t1.parentid=t0.id
)
select distinct 
       '/'||array_to_string(a0.pathid,'/') as pathid,
       a0.depth,
       a0.id,a0.parentid,lpad(a0.id::text, 2*a0.depth-1+length(a0.id::text),' ') as tree_id,
       --'select pg_cancel_backend('||a0.id|| ');' as cancel_pid,
       --'select pg_terminate_backend('||a0.id|| ');' as term_pid,
       case when a0.depth =1 then 'select pg_terminate_backend('|| a0.id || ');' else null end  as term_pid,
       case when a0.depth =1 then 'select cancel_backend('|| a0.id || ');' else null end  as cancel_pid
       ,a2.datname,a2.usename,a2.application_name,a2.client_addr,a2.wait_event_type,a2.wait_event,a2.state
       --,a2.backend_start,a2.xact_start,a2.query_start
  from tmp3 a0
       left outer join (select distinct '/'||id||'/' as prefix_id,id
                        from tmp0
             where 1=1 ) a1
                  on position( a1.prefix_id in '/'||array_to_string(a0.pathid,'/')||'/' ) >0
     left outer join pg_stat_activity a2 -- select * from pg_stat_activity
                  on a0.id = a2.pid
order by '/'||array_to_string(a0.pathid,'/'),a0.depth; 

三、 pg锁机制

锁的等级和对应操作在源码中有定义

/*
 * These are the valid values of type LOCKMODE for all the standard lock
 * methods (both DEFAULT and USER).
 */

/* NoLock is not a lock mode, but a flag value meaning "don't get a lock" */
#define NoLock					0

#define AccessShareLock			1		/* SELECT */
#define RowShareLock			2		/* SELECT FOR UPDATE/FOR SHARE */
#define RowExclusiveLock		3		/* INSERT, UPDATE, DELETE */
#define ShareUpdateExclusiveLock 4		/* VACUUM (non-FULL),ANALYZE, CREATE INDEX CONCURRENTLY */
#define ShareLock				5		/* CREATE INDEX (WITHOUT CONCURRENTLY) */
#define ShareRowExclusiveLock	6		/* like EXCLUSIVE MODE, but allows ROW SHARE */
#define ExclusiveLock			7		/* blocks ROW SHARE/SELECT...FOR UPDATE */
#define AccessExclusiveLock		8		/* ALTER TABLE, DROP TABLE, VACUUM FULL, and unqualified LOCK TABLE */

pg锁兼容性模式

锁兼容性矩阵已有锁模式       
请求的锁模式access sharerow sharerow exclusiveshare update exclusiveshareshare row exclusiveexclusiveaccess exclusive
access share
(select)
X
row share
(select for update
/select for share)
XX
row exclusive
(DML)
XXXX
share update exclusive
(非full模式vacuum/online建索引/analyze)
XXXXX
share
(非online建索引)
XXXXX
share row exclusive
(任何pg命令都不会自动请求该锁等级)
XXXXXX
exclusive
(任何pg命令都不会自动请求该锁等级)
XXXXXXX
access exclusive
(DDL,LOCK TABLE)
XXXXXXXX

四、 事后如何追踪详细的锁冲突信息

1. 可以通过lock trace跟踪锁等待的详细信息

《PostgreSQL Developer Options (debug, trace, system table mod and so on...) 详解》

2. 通过数据库日志(开启lock_timeout, log_lockwait参数)跟踪锁等待信息

3. 或者通过数据库日志(开启log_statements='all',SQL审计)追踪事务中所有的SQL,分析事务之间的锁冲突

参考:

blog/20170521_01.md at master · digoal/blog · GitHub

PostgreSQL · 特性分析 · 统计信息计算方法

《postgresql修炼之道》

  • 6
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
PostgreSQL中,当执行一张表的insert语句时出现阻塞情况通常是因为事务未正常提交。为了解决这个问题,可以通过以下步骤来查询是否表和释放定: 1. 查询是否表:使用下面的SQL语句查询是否有其他进程定了该表: ``` select oid from pg_class where relname='table_name'; ``` 其中,将"table_name"替换为可能被定的表的名称。 2. 如果查询结果返回了结果,表示该表被定。接下来,可以使用以下SQL语句来释放定: ``` select pg_cancel_backend(pid); ``` 将"pid"替换为上一步查询到的pid。 3. 如果无法取消定,则可以使用以下SQL语句强制终止阻塞的进程: ``` select pg_terminate_backend(pid); ``` 同样,将"pid"替换为上一步查询到的pid。 另外,还可以使用以下SQL语句来查看当前数据库中的定情况: ``` select relation::regclass, s.pid, granted, client_hostname, application_name, usename, query from pg_locks l, pg_stat_activity s where s.pid = l.pid; ``` 这条SQL语句可以显示定表的相关信息,包括定的进程ID(pid)、客户端主机名、应用程序名称、用户名和查询语句等信息。 总结:要解决PostgreSQL阻塞查询的问题,我们可以通过查询是否表,释放定或强制终止阻塞的进程来解决。同时,可以使用特定的SQL语句来查看当前数据库中的定情况。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [postgresql表问题](https://blog.csdn.net/S0001100/article/details/126370990)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [PostgreSQL 查询被阻塞的连接](https://blog.csdn.net/howard_shooter/article/details/122063644)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [que:一个使用PostgreSQL咨询来提高速度和可靠性的Ruby作业队列](https://download.csdn.net/download/weixin_42133918/16279031)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hehuyi_In

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值