1. 背景
MySQL 1主2從,半同步復(fù)制,主庫有較高的寫入量,此時在主庫重復(fù)安裝半同步插件,可能導(dǎo)致主庫hang住,無響應(yīng),只能通過重啟數(shù)據(jù)庫來恢復(fù)。
MySQL版本:Percona Server 5.7.19
操作系統(tǒng):Red Hat Enterprise Linux Server release 6.3
2. 復(fù)現(xiàn)步驟
- 準(zhǔn)備環(huán)境MySQL 5.7.19 1主2從,半同步復(fù)制
- 使用sysbench往主庫寫數(shù)據(jù)
- 在主庫循環(huán)執(zhí)行安裝半同步插件命令:
a) INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so';
b) INSTALL PLUGIN rpl_semi_sync_slave SONAME 'semisync_slave.so'; - 在應(yīng)用機(jī)器上連接到主庫,多線程循環(huán)執(zhí)行:
a) select @@session.tx_read_only - 運(yùn)行一段時間,復(fù)現(xiàn)故障。
a) 主庫無法連接,無響應(yīng)
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);
在發(fā)現(xiàn)半同步插件已經(jīng)安裝的情況下,會先釋放鎖 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這個鎖被安裝半同步插件線程持有,導(dǎo)致死鎖。
擴(kuò)展一下,安裝插件,除了插件已經(jīng)存在之外,無法打開動態(tài)庫(Can't open shared library)和 動態(tài)庫無法找到符號入口(Can't find symbol in library),都有可能與業(yè)務(wù)SQL產(chǎn)生死鎖。
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)等,都有可能會觸發(fā)死鎖。
Percona Server 5.7.25 已修復(fù)該Bug。