基於 MySQL 5.5(非 GTID)環境,深度剖析 MHA Manager 兩大核心流程:masterha_master_failover(故障切換)與 masterha_master_switch(在線切換)的完整階段劃分與關鍵調用鏈路。
check_settings:版本檢查、全節點連通性、死活雙重確認start_sql_threads_if:確保所有 Slave SQL 線程運行stop_io_thread:所有 Slave 停止 IO 線程(含已掛掉的 Master)master_ip_failover_script:VIP 漂移shutdown_script:自定義關機腳本read_slave_status 獲取 Master_Log_File/Read_Master_Log_Pos,identify_latest_slaves 比較 Binlog 位置找最新/最舊 Slavesave_binary_logs --command=save 拷貝未同步 Binlog 到 Managergenerate_diff_binary_log / concat_all_binlogs_from / dump_binlog 生成差分candidate_master=1 且位置最新的節點no_master、log_bin=OFF、版本不最舊、延遲 > 1億位置apply_diff_relay_logs --command=find 生成 Relay 差分wait_until_relay_log_applied 等待 Relay 執行完exec_diff (Exec/Read 差異) + read_diff (Relay 差異) + binlog_diff (Master 差異)mysqlbinlog 重放change_master_and_start_slave:CHANGE MASTER TO 指向新 Master + START SLAVEreset_slave_on_new_master:RESET SLAVE 清理舊 Slave 信息,完成角色轉換identify_orig_master:SHOW SLAVE STATUS 為空者為 Masterconnect_check、validate_current_master、check_repl_privMHA_Master_High_Availability_Monitor 防衝突 MonitorMHA_Master_High_Availability_Failover 防衝突 Failovercheck_replication_health:IO/SQL 線程、Seconds_Behind_Master < 1sget_running_update_threads:SHOW PROCESSLIST 檢查寫入線程,有則中止identify_new_master:選主邏輯同 Failovermaster_ip_online_change_script --command=stop:禁寫(VIP 切換前)FLUSH TABLES WITH READ LOCK:全局讀鎖,停止 Binlog 寫入check_binlog_stop:連續兩次 SHOW MASTER STATUS 位置不變確認停寫master_pos_wait:等待所有 Slave 同步到 Master 當前位置get_new_master_binlog_position:SHOW MASTER STATUS 獲取新坐標master_ip_online_change_script --command=start:VIP 指向新 MasterSET GLOBAL read_only=0:新 Master 開啟寫入switch_slaves:CHANGE MASTER TO + START SLAVEUNLOCK TABLES:原 Master 釋放鎖reset_slave_on_new_master、釋放 Advisory Lock| 維度 | 故障切換 | 在線切換 |
|---|---|---|
| 前提 | Master 掛掉 | Master 正常運行 |
| 數據一致性 | 盡力挽救未同步 Binlog | 全局鎖保證零丟失 |
| 業務影響 | 寫入中斷直到切換完成 | 短暫只讀窗口(秒級) |
| 核心難點 | Binlog 拼湊與重放 | 鎖等待與協調 |