MySQL 1主2从,半同步复制,主库有较高的写入量,此时在主库重复安装半同步插件,可能导致主库hang住,无响应,只能通过重启数据库来恢复。
二、故障复现
环境:
MySQL版本:Percona Server for MySQL 5.7.19
操作系统:Red Hat Enterprise Linux Server release 6.3
复制步骤:
准备环境MySQL 5.7.19 1主2从,半同步复制使用
sysbench往主库写数据
在主库循环执行安装半同步插件命令:
INSTALL PLUGIN rpl_semi_sync_master SONAME ‘semisync_master.so’;
INSTALL PLUGIN rpl_semi_sync_slave SONAME ‘semisync_slave.so’;
在应用机器上连接到主库,多线程循环执行:
select @@session.tx_read_only
运行一段时间,复现故障。
主库无法连接,无响应
从库Slave_IO_Running: Connecting
三、原因分析
通过分析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);
加锁顺序为:
LOCK_plugin
LOCK_system_variables_hash
释放锁的顺序为:
LOCK_system_variables_hash
LOCK_plugin
看一下其他线程执行select @@session.tx_read_only 时的加锁顺序:
mysql_mutex_lock(&LOCK_plugin);
mysql_rwlock_rdlock(&LOCK_system_variables_hash);
LOCK_plugin
LOCK_system_variables_hash
正常情况下,加锁释放锁的顺序一致,应该不会发生死锁。但是在半同步插件已经安装的情况下,代码逻辑会先释放锁 mysql_mutex_unlock(&LOCK_plugin); 然后报告错误(report_error) ,也就是常见到的 Function ‘rpl_semi_sync_master’ already exists, 之后再加锁mysql_mutex_lock(&LOCK_plugin);
这个释放锁,报告错误信息,再加锁的间隙,LOCK_plugin 可能会被其他线程拿到。
session1
session2
备注
获取锁 LOCK_plugin
获取锁 LOCK_system_variables_hash
发现插件已安装,释放锁LOCK_plugin
获取锁 LOCK_plugin
请求LOCK_system_variables_hash
等待
请求LOCK_plugin
等待
死锁发生
扩展一下,安装插件,除了插件已经存在之外,无法打开动态库(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。