목차
MHA故障切换和在线切换的代码解析
前段时间我的同事沈龙星整理了一下MHA故障切换和在线切换的代码流程,在征得其同意后,在此转发。以下是正文
failover的处理流程
php教程 php手册 MHA故障切换和在线切换的代码解析

MHA故障切换和在线切换的代码解析

Jun 13, 2016 am 08:42 AM
android

MHA故障切换和在线切换的代码解析


前段时间我的同事沈龙星整理了一下MHA故障切换和在线切换的代码流程,在征得其同意后,在此转发。以下是正文

本文是以MySQL5.5为基础的,因此没有涉及到gtid相关内容。MHA的主从切换过程分为failover和rotate两种,前者适用于原Master down的情况,后者是在在线切换的情况下使用。下面分别讲解



failover的处理流程


  1. MHA::MasterFailover::main()
  2. ->do_master_failover
  3. Phase 1: Configuration Check Phase
  4. -> check_settings:
  5. check_node_version:查看MHA的版本信息
  6. connect_all_and_read_server_status:确认各个node的MySQL实例是否可以连接
  7. get_dead_servers/get_alive_servers/get_alive_slaves:double check各个node的死活状态
  8. start_sql_threads_if:查看Slave_SQL_Running是否为Yes,若不是则启动SQL thread

  9. Phase 2: Dead Master Shutdown Phase:对于我们来说,唯一的作用就是stop IO thread
  10. -> force_shutdown($dead_master):
  11. stop_io_thread:所有slave的IO thread stop掉(将stop掉master)
  12. force_shutdown_internal(实际上就是执行配置文件中的master_ip_failover_script/shutdown_script,若无则不执行):
  13. master_ip_failover_script:如果设置了VIP,则首先切换VIP
  14. shutdown_script:如果设置了shutdown脚本,则执行

  15. Phase 3: Master Recovery Phase
  16. -> Phase 3.1: Getting Latest Slaves Phase(取得latest slave)
  17. read_slave_status:取得各个slave的binlog file/position
  18. check_slave_status:调用"SHOW SLAVE STATUS"来取得slave的如下信息:
  19. Slave_IO_State, Master_Host,
  20. Master_Port, Master_User,
  21. Slave_IO_Running, Slave_SQL_Running,
  22. Master_Log_File, Read_Master_Log_Pos,
  23. Relay_Master_Log_File, Last_Errno,
  24. Last_Error, Exec_Master_Log_Pos,
  25. Relay_Log_File, Relay_Log_Pos,
  26. Seconds_Behind_Master, Retrieved_Gtid_Set,
  27. Executed_Gtid_Set, Auto_Position
  28. Replicate_Do_DB, Replicate_Ignore_DB, Replicate_Do_Table,
  29. Replicate_Ignore_Table, Replicate_Wild_Do_Table,
  30. Replicate_Wild_Ignore_Table
  31. identify_latest_slaves:
  32. 通过比较各个slave中的Master_Log_File/Read_Master_Log_Pos,来找到latest的slave
  33. identify_oldest_slaves:
  34. 通过比较各个slave中的Master_Log_File/Read_Master_Log_Pos,来找到oldest的slave

  35. -> Phase 3.2: Saving Dead Master's Binlog Phase:
  36. save_master_binlog:
  37. 如果dead master可以ssh连接,则走如下分支:
  38. save_master_binlog_internal:(使用node节点的save_binary_logs脚本在dead master上做拷贝)
  39. save_binary_logs --command=save --start_file=mysql-bin.000281 --start_pos=107 --binlog_dir=/opt/mysql/data/binlog --output_file=/opt/mha/log/saved_master_binlog_from_10.27.177.245_3306_20160108211857.binlog --handle_raw_binlog=1 --disable_log_bin=0 --manager_version=0.55
  40. generate_diff_binary_log:
  41. concat_all_binlogs_from:
  42. dump_binlog:就是将binlog文件dump到target文件中,用的就是binmode read
  43. dump_binlog_header_fde:从0读到position-1
  44. dump_binlog_from_pos:从position开始,dump binlog file到target file
  45. file_copy:
  46. 文件拷贝,是将上述生成的binlog文件拷贝到manage节点的manager_workdir目录下
  47. 如果dead master无法ssh登录,则master上未同步到slave的txn丢失

  48. -> Phase 3.3: Determining New Master Phase
  49. find_latest_base_slave:
  50. find_latest_base_slave_internal:
  51. pos_cmp( $oldest_mlf, $oldest_mlp, $latest_mlf, $latest_mlp )
  52. 判断latest/oldest slave的binlog位置是不是相同,若相同则不需要同步relay log
  53. apply_diff_relay_logs --command=find --latest
  54. 查看latest slave中是否有oldest缺少的relay log,若无则继续,否则failover失败
  55. 查找的方法很简单,就是逆序的读latest slave的relay log文件,一直找到file/position为止

  56. select_new_master:选出新的master节点
  57. If preferred node is specified, one of active preferred nodes will be new master.
  58. If the latest server behinds too much (i.e. stopping sql thread for online backups),
  59. we should not use it as a new master, we should fetch relay log there. Even though preferred
  60. master is configured, it does not become a master if it's far behind.
  61. get_candidate_masters:
  62. 就是配置文件中配置了candidate_master>0的节点
  63. get_bad_candidate_masters:
  64. # The following servers can not be master:
  65. # - dead servers
  66. # - Set no_master in conf files (i.e. DR servers)
  67. # - log_bin is disabled
  68. # - Major version is not the oldest
  69. # - too much replication delay(slave与master的binlog position差距大于100000000)
  70. Searching from candidate_master slaves which have received the latest relay log events
  71. if NOT FOUND:
  72. Searching from all candidate_master slaves
  73. if NOT FOUND:
  74. Searching from all slaves which have received the latest relay log events
  75. if NOT FOUND:
  76. Searching from all slaves

  77. -> Phase 3.4: New Master Diff Log Generation Phase
  78. recover_relay_logs:
  79. 判断new master是不是latest slave,若不是则使用apply_diff_relay_logs --命令生成差分log,
  80. 并发送到新new master
  81. recover_master_internal:
  82. 将3.2中生成的daed master上的binlog发送到new master

  83. -> Phase 3.5: Master Log Apply Phase
  84. recover_slave:
  85. apply_diff:
  86. 0. wait_until_relay_log_applied,等待new master将relaylog执行完
  87. 1. 判断Exec_Master_Log_Pos == Read_Master_Log_Pos,
  88. 如果不相等则使用save_binary_logs --command=save生成差分log
  89. 2. 调用apply_diff_relay_logs命令,让new master进行recover.其中:
  90. 2.1 recover的log分为三部分:
  91. exec_diff:Exec_Master_Log_Pos和Read_Master_Log_Pos的差分
  92. read_diff:new master与lastest slave的relay log的差分
  93. binlog_diff:lastest slave与daed master之间的binlog差分
  94. 实际上apply_diff_relay_logs就是调用mysqlbinlog command进行recover
  95. //如果设置了vip,则需要调用master_ip_failover_script进行vip的failover

  96. Phase 4: Slaves Recovery Phase
  97. -> Phase 4.1: Starting Parallel Slave Diff Log Generation Phase
  98. 生成Slave与New Slave之间的差异日志,并将该日志拷贝到各Slave的工作目录下。

  99. -> Phase 4.2: Starting Parallel Slave Log Apply Phase
  100. recover_slave:
  101. 对各个slave进行恢复,同Phase3.5
  102. change_master_and_start_slave:
  103. 通过CHANGE MASTER TO命令将这些Slave指向新的New Master,最后开始复制(start slave)

  104. Phase 5: New master cleanup phase
  105. reset_slave_on_new_master
  106. 清理New Master其实就是重置slave info,即取消原来的Slave信息。至此整个Master故障切换过程完成


rotate的处理过程

  1. MHA::MasterRotate::main()
    -> do_master_online_switch:
    Phase 1: Configuration Check Phase
    -> identify_orig_master
    connect_all_and_read_server_status:
    connect_check:首先进行connect check,确保各个server的MySQL服务都正常
    connect_and_get_status:获取MySQL实例的server_id/mysql_version/log_bin..等信息
    这一步还有一个重要的作用,是获取当前的master节点。通过执行show slave status,
    如果输出为空,说明当前节点是master节点。
    validate_current_master:取得master节点的信息,并判断配置的正确性
    check是否有server down,若有则退出rotate
    check master alive or not,若dead则退出rotate
    check_repl_priv:
    查看用户是否有replication的权限
    获取monitor_advisory_lock,以保证当前没有其他的monitor进程在master上运行
    执行:SELECT GET_LOCK('MHA_Master_High_Availability_Monitor', ?) AS Value
    获取failover_advisory_lock,以保证当前没有其他的failover进程在slave上运行
    执行:SELECT GET_LOCK('MHA_Master_High_Availability_Failover', ?) AS Value
    check_replication_health:
    执行:SHOW SLAVE STATUS来判断如下状态:current_slave_position/has_replication_problem
    其中,has_replication_problem具体check如下内容:IO线程/SQL线程/Seconds_Behind_Master(1s)
    get_running_update_threads:
    使用show processlist来查询当前有没有执行update的线程存在,若有则退出switch
    -> identify_new_master
    set_latest_slaves:当前的slave节点都是latest slave
    select_new_master:选出新的master节点
    If preferred node is specified, one of active preferred nodes will be new master.
    If the latest server behinds too much (i.e. stopping sql thread for online backups),
    we should not use it as a new master, we should fetch relay log there. Even though preferred
    master is configured, it does not become a master if it's far behind.
    get_candidate_masters:
    就是配置文件中配置了candidate_master>0的节点
    get_bad_candidate_masters:
    # The following servers can not be master:
    # - dead servers
    # - Set no_master in conf files (i.e. DR servers)
    # - log_bin is disabled
    # - Major version is not the oldest
    # - too much replication delay(slave与master的binlog position差距大于100000000)
    Searching from candidate_master slaves which have received the latest relay log events
    if NOT FOUND:
    Searching from all candidate_master slaves
    if NOT FOUND:
    Searching from all slaves which have received the latest relay log events
    if NOT FOUND:
    Searching from all slaves

    Phase 2: Rejecting updates Phase
    reject_update:lock table来reject write binlog
    如果MHA的配置文件中设置了"master_ip_online_change_script"参数,则执行该脚本来disable writes on the current master
    该脚本在使用了vip的时候才需要设置
    reconnect:确保当前与master的连接正常
    lock_all_tables:执行FLUSH TABLES WITH READ LOCK,来lock table
    check_binlog_stop:连续两次show master status,来判断写binlog是否已经停止

    read_slave_status:
    get_alive_slaves:
    check_slave_status:调用"SHOW SLAVE STATUS"来取得slave的如下信息:
    Slave_IO_State, Master_Host,
    Master_Port, Master_User,
    Slave_IO_Running, Slave_SQL_Running,
    Master_Log_File, Read_Master_Log_Pos,
    Relay_Master_Log_File, Last_Errno,
    Last_Error, Exec_Master_Log_Pos,
    Relay_Log_File, Relay_Log_Pos,
    Seconds_Behind_Master, Retrieved_Gtid_Set,
    Executed_Gtid_Set, Auto_Position
    Replicate_Do_DB, Replicate_Ignore_DB, Replicate_Do_Table,
    Replicate_Ignore_Table, Replicate_Wild_Do_Table,
    Replicate_Wild_Ignore_Table
    switch_master:
    switch_master_internal:
    master_pos_wait:调用select master_pos_wait函数,等待主从同步完成
    get_new_master_binlog_position:执行'show master status'
    Allow write access on the new master:
    调用master_ip_online_change_script --command=start ...,将vip指向new master
    disable_read_only:
    在新master上执行:SET GLOBAL read_only=0
    switch_slaves:
    switch_slaves_internal:
    change_master_and_start_slave
    change_master:
    start_slave:
    unlock_tables:在orig master上执行unlock table
    Phase 5: New master cleanup phase
    reset_slave_on_new_master
    release_failover_advisory_lock
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

새로운 보고서는 소문난 삼성 갤럭시 S25, 갤럭시 S25 플러스, 갤럭시 S25 울트라 카메라 업그레이드에 대한 비판적인 평가를 제공합니다. 새로운 보고서는 소문난 삼성 갤럭시 S25, 갤럭시 S25 플러스, 갤럭시 S25 울트라 카메라 업그레이드에 대한 비판적인 평가를 제공합니다. Sep 12, 2024 pm 12:23 PM

최근 아이스 유니버스는 삼성의 차기 플래그십 스마트폰으로 널리 알려진 갤럭시 S25 울트라에 대한 세부 정보를 꾸준히 공개해 왔습니다. 무엇보다도 유출자는 삼성이 카메라 업그레이드를 하나만 가져올 계획이라고 주장했습니다.

삼성 갤럭시 S25 울트라, 디자인 변경 루머가 공개된 첫 번째 렌더링 이미지 유출 삼성 갤럭시 S25 울트라, 디자인 변경 루머가 공개된 첫 번째 렌더링 이미지 유출 Sep 11, 2024 am 06:37 AM

OnLeaks는 이제 Android Headlines와 제휴하여 X(이전 Twitter) 팔로어로부터 4,000달러 이상의 수익을 창출하려는 시도가 실패한 지 며칠 후 Galaxy S25 Ultra에 대한 첫 번째 모습을 제공합니다. 맥락에 따라 h 아래에 포함된 렌더링 이미지

IFA 2024 | TCL의 NXTPAPER 14는 성능 면에서는 Galaxy Tab S10 Ultra와 일치하지 않지만 크기에서는 거의 일치합니다. IFA 2024 | TCL의 NXTPAPER 14는 성능 면에서는 Galaxy Tab S10 Ultra와 일치하지 않지만 크기에서는 거의 일치합니다. Sep 07, 2024 am 06:35 AM

TCL은 두 가지 새로운 스마트폰을 발표하는 것과 함께 NXTPAPER 14라는 새로운 Android 태블릿도 발표했는데, TCL의 거대한 화면 크기는 판매 포인트 중 하나입니다. NXTPAPER 14는 TCL의 시그니처 브랜드인 무광택 LCD 패널 버전 3.0을 갖추고 있습니다.

새로운 보고서는 소문난 삼성 갤럭시 S25, 갤럭시 S25 플러스, 갤럭시 S25 울트라 카메라 업그레이드에 대한 비판적인 평가를 제공합니다. 새로운 보고서는 소문난 삼성 갤럭시 S25, 갤럭시 S25 플러스, 갤럭시 S25 울트라 카메라 업그레이드에 대한 비판적인 평가를 제공합니다. Sep 12, 2024 pm 12:22 PM

최근 아이스 유니버스는 삼성의 차기 플래그십 스마트폰으로 널리 알려진 갤럭시 S25 울트라에 대한 세부 정보를 꾸준히 공개해 왔습니다. 무엇보다도 유출자는 삼성이 카메라 업그레이드를 하나만 가져올 계획이라고 주장했습니다.

Vivo Y300 Pro는 7.69mm의 슬림한 본체에 6,500mAh 배터리를 탑재했습니다. Vivo Y300 Pro는 7.69mm의 슬림한 본체에 6,500mAh 배터리를 탑재했습니다. Sep 07, 2024 am 06:39 AM

Vivo Y300 Pro는 방금 완전히 공개되었으며 대용량 배터리를 갖춘 가장 얇은 중급 Android 휴대폰 중 하나입니다. 정확히 말하면 스마트폰의 두께는 7.69mm에 불과하지만 배터리 용량은 6,500mAh입니다. 최근 출시된 것과 동일한 용량이다.

Samsung Galaxy S24 FE는 4가지 색상과 2가지 메모리 옵션으로 예상보다 낮은 가격으로 출시될 예정 Samsung Galaxy S24 FE는 4가지 색상과 2가지 메모리 옵션으로 예상보다 낮은 가격으로 출시될 예정 Sep 12, 2024 pm 09:21 PM

삼성전자는 팬에디션(FE) 스마트폰 시리즈를 언제 업데이트할지 아직 힌트를 주지 않았다. 현재 상태로 Galaxy S23 FE는 2023년 10월 초에 출시된 회사의 최신 버전으로 남아 있습니다.

Xiaomi Redmi Note 14 Pro Plus는 Light Hunter 800 카메라를 탑재한 최초의 Qualcomm Snapdragon 7s Gen 3 스마트폰으로 출시됩니다. Xiaomi Redmi Note 14 Pro Plus는 Light Hunter 800 카메라를 탑재한 최초의 Qualcomm Snapdragon 7s Gen 3 스마트폰으로 출시됩니다. Sep 27, 2024 am 06:23 AM

Redmi Note 14 Pro Plus는 이제 작년 Redmi Note 13 Pro Plus(Amazon에서 현재 $375)의 직접적인 후속 제품으로 공식화되었습니다. 예상대로 Redmi Note 14 Pro Plus는 Redmi Note 14 및 Redmi Note 14 Pro와 함께 Redmi Note 14 시리즈를 주도합니다. 리

iQOO Z9 Turbo Plus: 잠재적으로 강화된 시리즈 플래그십에 대한 예약 시작 iQOO Z9 Turbo Plus: 잠재적으로 강화된 시리즈 플래그십에 대한 예약 시작 Sep 10, 2024 am 06:45 AM

OnePlus의 자매 브랜드 iQOO는 2023-4년 제품 주기가 거의 끝날 수 있습니다. 그럼에도 불구하고 브랜드는 Z9 시리즈가 아직 끝나지 않았다고 선언했습니다. 최종이자 아마도 최고급인 Turbo+ 변형이 예상대로 발표되었습니다. 티

See all articles