死锁分析是DBA日常工作之一,一般死锁分析的步骤如下
- 阅读死锁日志
- 查看表机构,甚至不需要
- 定位事务场景,进行分析
而正确的理解死锁日志,是进行死锁分析的重点,下面就是对死锁日志的分段解读。
一般的死锁日志如下
------------------------
LATEST DETECTED DEADLOCK
------------------------
2019-01-09 15:11:45 0x70000cc97000 //死锁发生时间
*** (1) TRANSACTION: //事务1
TRANSACTION 1819662/*事务id,trx->id*/, ACTIVE 13 sec starting index read //事务1从开始执行到被死锁检测经历的时间,生产环境一般看到的是0
mysql tables in use 1, locked 1 //事务1当前查询使用到的表,以及已经加锁的表。分别是trx->n_mysql_tables_in_use,trx->mysql_n_tables_locked
LOCK WAIT 2 lock struct(s), heap size 1160, 1 row lock(s)// 这行的LOCK WAIT 2 lock struct(s),应该分成两部分解读,而不是说等待两个锁结构。LOCK WAIT表示事务状态处于锁等待,但是这是个不加锁的脏读输出。有可能不准确,2 lock struct(s)表示此事务中的锁结构数目,UT_LIST_GET_LEN(trx->lock.trx_locks); heap size代表内存堆的byte长度。1 row locks(s) 是锁了一行。
MySQL thread id 5, OS thread handle 123145517932544, query id 39 localhost root statistics
select * from t2 where id = 5 for update
//processlist id , 对应的操作系统的线程结构(pthread_t),查询ID,来源IP,用户名,操作信息(proc_info,不受保护)
*** (1) WAITING FOR THIS LOCK TO BE GRANTED: //此事务要加的锁,但是被阻塞。
RECORD LOCKS/*行锁*/ space id 68/*表空间id*/ page no 3/*page id*/ n bits 72/*bitmap的大小*/ index PRIMARY /*索引*/of table `test_lock`.`t2`/*表名*/ trx id 1819662 /*事务id*/ lock_mode X /*排他锁*/ locks rec but not gap /*只锁行记录,不锁间隙*/ waiting /*加锁等待*/
Record lock, heap no 6/*索引页中所处的逻辑位置*/ PHYSICAL RECORD: n_fields 4; compact format; info bits 0
0: len 4; hex 80000005; asc ;;
1: len 6; hex 0000001b984f; asc O;;
2: len 7; hex 48000001890110; asc H ;;
3: len 8; hex 7570646174655f33; asc update_3;;
*** (2) TRANSACTION:
TRANSACTION 1819663, ACTIVE 24 sec starting index read
mysql tables in use 1, locked 1
4 lock struct(s), heap size 1160, 2 row lock(s)
MySQL thread id 4, OS thread handle 123145516838912, query id 40 localhost root statistics
select * from t2 where id = 5 for update
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 68 page no 3 n bits 72 index PRIMARY of table `test_lock`.`t2` trx id 1819663 lock mode S locks rec but not gap
Record lock, heap no 6 PHYSICAL RECORD: n_fields 4; compact format; info bits 0
0: len 4; hex 80000005; asc ;;
1: len 6; hex 0000001b984f; asc O;;
2: len 7; hex 48000001890110; asc H ;;
3: len 8; hex 7570646174655f33; asc update_3;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 68 page no 3 n bits 72 index PRIMARY of table `test_lock`.`t2` trx id 1819663 lock_mode X locks rec but not gap waiting
Record lock, heap no 6 PHYSICAL RECORD: n_fields 4; compact format; info bits 0
0: len 4; hex 80000005; asc ;;
1: len 6; hex 0000001b984f; asc O;;
2: len 7; hex 48000001890110; asc H ;;
3: len 8; hex 7570646174655f33; asc update_3;;
*** WE ROLL BACK TRANSACTION (1)