1. 背景
MySQL 1主2从,半同步复制,主库有较高的写入量,此时在主库重复安装半同步插件,可能导致主库hang住,无响应,只能通过重启数据库来恢复。
MySQL版本:Percona Server 5.7.19
操作系统:Red Hat Enterprise Linux Server release 6.3
2. 复现步骤
- 准备环境MySQL 5.7.19 1主2从,半同步复制
- 使用sysbench往主库写数据
- 在主库循环执行安装半同步插件命令:
a) INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so';
b) INSTALL PLUGIN rpl_semi_sync_slave SONAME 'semisync_slave.so'; - 在应用机器上连接到主库,多线程循环执行:
a) select @@session.tx_read_only - 运行一段时间,复现故障。
a) 主库无法连接,无响应
b) 从库Slave_IO_Running: Connecting
3. 原因分析
通过分析MySQL源码,安装半同步插件过程中,加锁顺序为:
//sql/sql_plugin.cc
mysql_mutex_lock(&LOCK_plugin);
mysql_rwlock_wrlock(&LOCK_system_variables_hash);
…
if (plugin_find_internal(name_cstr, MYSQL_ANY_PLUGIN))
{
mysql_mutex_unlock(&LOCK_plugin);
report_error(report, ER_UDF_EXISTS, name->str);
mysql_mutex_lock(&LOCK_plugin);
DBUG_RETURN(TRUE);
}
…
mysql_rwlock_unlock(&LOCK_system_variables_hash);
mysql_mutex_unlock(&LOCK_plugin);
在发现半同步插件已经安装的情况下,会先释放锁 mysql_mutex_unlock(&LOCK_plugin); 然后报告错误(report_error) ,也就是常见到的 Function 'rpl_semi_sync_master' already exists, 之后再加锁mysql_mutex_lock(&LOCK_plugin);
这个释放锁,报告错误信息,再加锁的间隙,LOCK_plugin 可能会被其他线程拿到。
其他线程加锁顺序为:
mysql_mutex_lock(&LOCK_plugin);
mysql_rwlock_rdlock(&LOCK_system_variables_hash);
拿到第一个锁,等LOCK_system_variables_hash, 而LOCK_system_variables_hash这个锁被安装半同步插件线程持有,导致死锁。
扩展一下,安装插件,除了插件已经存在之外,无法打开动态库(Can't open shared library)和 动态库无法找到符号入口(Can't find symbol in library),都有可能与业务SQL产生死锁。
mysql_mutex_unlock(&LOCK_plugin);
report_error(report, ER_CANT_OPEN_LIBRARY, dl->str, 0, buf);
mysql_mutex_lock(&LOCK_plugin);
mysql_mutex_unlock(&LOCK_plugin);
report_error(report, ER_CANT_FIND_DL_ENTRY, name->str);
mysql_mutex_lock(&LOCK_plugin);
另外,除了半同步插件外,其他的插件,如审计插件(Audit)等,都有可能会触发死锁。
Percona Server 5.7.25 已修复该Bug。
网友评论