PostgreSQL锁和阻塞发现与处理

一、 阻塞查询

PostgreSQL提供了两个视图

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

查看被阻塞进程

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

img

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

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

img

根据被阻塞/阻塞源的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;

img

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锁机制

img

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

/*
 * 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…) 详解》

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

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


参考:

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

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

《postgresql修炼之道》


转自:https://blog.csdn.net/Hehuyi_In/article/details/95895473

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PostgreSQL 中,定机制用于控制并发访问数据库中的数据,防止多个事务同时修改同一数据导致的数据不一致。当你在一个事务中持有某个数据表的时,其他事务将无法对该表进行写操作,直到你的事务结束并释放。 要释放 PostgreSQL ,你需要按照以下步骤操作: 1. **确认定状态**:首先,你需要通过 `pg_locks` 系统视图或 `SHOW LOCKS` 命令检查你的事务持有的信息,确定需要释放哪些。 2. **在事务中显式解**:如果你使用的是 `SELECT FOR UPDATE` 或 `FOR SHARE` 语句获取了,那么在事务提交(`COMMIT`)或回滚(`ROLLBACK`)时,这些会自动释放。如果使用的是 `EXCLUSIVE` 或 `ACCESS SHARE` 级别的(如 `LOCK TABLE`),则需要使用 `unlock table` 或 `UNLOCK ALL` 命令来手动解。 ```sql -- 如果是表级 UNLOCK TABLE my_table; -- 或者全局 UNLOCK ALL; ``` 3. **在存储过程或函数中解**:如果你在一个存储过程或函数中获得了,记得在适当的地方调用 `RETURN` 或 `END` 语句时解。 4. **处理**:如果检测到死(当两个或更多事务等待对方释放资源而无法继续时),你可以使用 `ROLLBACK` 语句回滚当前事务,或者使用 `pg_cancel_backend` 来中断阻塞的事务。 5. **检查并修复定循环**:确保没有出现无限循环的定,这可能是因为程序设计错误,需要修复代码逻辑。 请根据你的具体情况进行操作,并确保在执行解操作时,事务已经处理完毕,否则可能会导致数据不一致。如果有疑问,建议查看 PostgreSQL 官方文档或使用 `pg_stat_activity` 查看活跃事务来辅助诊断。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值