MySQL MGR集群單主模式的自動搭建和自動化故障修複

来源:https://www.cnblogs.com/wy123/archive/2019/08/24/11391292.html
-Advertisement-
Play Games

/*the waiting game:儘管人生如此艱難,不要放棄;不要妥協;不要失去希望*/ 隨著MySQL MGR的版本的升級以及技術成熟,在把MHA拉下神壇之後, MGR越來越成為MySQL高可用的首選方案。MGR的搭建並不算很複雜,但是有一系列手工操作步驟,為了簡便MGR的搭建和故障診斷,這裡 ...


/*
the waiting game:儘管人生如此艱難,不要放棄;不要妥協;不要失去希望
*/

 

隨著MySQL MGR的版本的升級以及技術成熟,在把MHA拉下神壇之後, MGR越來越成為MySQL高可用的首選方案。
MGR的搭建並不算很複雜,但是有一系列手工操作步驟,為了簡便MGR的搭建和故障診斷,這裡完成了一個自動化的腳本,來實現MGR的自動化搭建,自動化故障診斷以及修複。

 

MGR自動化搭建
為了簡便起見,這裡以單機多實例的模式進行測試,
先裝好三個MySQL實例,埠號分別是7001,7002,7003,其中7001作為寫節點,其餘兩個節點作為讀節,8000節點是筆者的另外一個測試節點,請忽略。
在指明主從節點的情況下,如下為mgr_tool.py一鍵搭建MGR集群的測試demo

 

MGR故障模擬1

MGR節點故障自動監測和自愈實現,如下是搭建完成後的MGR集群,目前集群處於完全正常的狀態中。

主觀造成主從節點間binlog的丟失

在主節點上對於對於從節點丟失的數據操作,GTID無法找到對應的數據,組複製立馬熄火

非寫入節點出現錯誤

看下errorlog

如果是手動解決的話,還是GTID跳過錯誤事物的套路,master上的GTID信息

嘗試跳過最新的一個事物ID,然後重新連接到組,可以正常連接到組,另外一個節點仍舊處於error狀態

stop group_replication; SET GTID_NEXT='6c81c118-e67c-4416-9cb0-2d573d178c1d:13'; BEGIN; COMMIT; set gtid_next='automatic'; 

另外一個節點類似,依次解決。

MGR故障模擬2

從節點脫離Group

這種情況倒是比較簡單,重新開始組複製即可,start group_replication

 

MGR故障自動檢測和修複

對於如上的兩種情況,
1,如果是從節點丟失主節點的事物,嘗試在從節點上跳過GTID,重新開始複製即可
2,如果是從節點非丟失主節點事物,嘗試在從節點重新開始組複製即可

實現代碼如下

def auto_fix_mgr_error(conn_master_dict,conn_slave_dict):
    group_replication_status = get_group_replication_status(conn_slave_dict)
    if(group_replication_status[0]["MEMBER_STATE"]=="ERROR" or group_replication_status[0]["MEMBER_STATE"] == "OFFLINE"):
        print(conn_slave_dict["host"]+str(conn_slave_dict["port"])+'------>'+group_replication_status[0]["MEMBER_STATE"])
        print("auto fixing......")
        while 1 > 0:
            master_gtid_list = get_gtid(conn_master_dict)
            slave_gtid_list = get_gtid(conn_slave_dict)
            master_executed_gtid_value = int((master_gtid_list[-1]["Executed_Gtid_Set"]).split("-")[-1])
            slave_executed_gtid_value = int(slave_gtid_list[-1]["Executed_Gtid_Set"].split("-")[-1])
            slave_executed_gtid_prefix = slave_gtid_list[-1]["Executed_Gtid_Set"].split(":")[0]
            slave_executed_skiped_gtid = slave_executed_gtid_value + 1
            if (master_executed_gtid_value > slave_executed_gtid_value):
                print("skip gtid and restart group replication,skiped gtid is "
                      + slave_gtid_list[-1]["Executed_Gtid_Set"].split(":")[-1].split("-")[0]
                      + ":"+str(slave_executed_skiped_gtid))
                slave_executed_skiped_gtid = slave_executed_gtid_prefix+":"+str(slave_executed_skiped_gtid)
                skip_gtid_on_slave(conn_slave_dict,slave_executed_skiped_gtid)
                time.sleep(10)
                start_group_replication(conn_slave_dict)
                if(get_group_replication_status(conn_slave_dict)[0]["MEMBER_STATE"]=="ONLINE"):
                    print("mgr cluster fixed,back to normal")
                    break
            else:
                start_group_replication(conn_slave_dict)
                if(get_group_replication_status(conn_slave_dict)[0]["MEMBER_STATE"]=="ONLINE"):
                    print("mgr cluster fixed,back to normal")
                break
    elif (group_replication_status[0]['MEMBER_STATE'] == 'ONLINE'):
        print("mgr cluster is normal,nothing to do")
        check_replication_group_members(conn_slave_dict)

 

對於故障類型1,GTID事物不一致的自動化修複

 

 對於故障類型2從節點offline的自動化修複

 

完整的實現代碼

該過程要求MySQL實例必須滿足MGR的基本條件,如果環境本身無法滿足MGR,一切都無從談起,因此要非常清楚MGR環境的最基本要求

完成的實現代碼如下,花了一個下午寫的,目前來說存在以下不足
1,創建複製用戶的時候,沒有指定具體的slave機器,目前直接指定的%:create user repl@'%' identified by repl
2,對於slave的修複,目前無法整體修複,只能一臺一臺修複,其實就是少了一個迴圈slave機器判斷的過程
3,目前搭建之前都會reset master(不管主從,主要是清理可能的殘留GTID),因此只適合新環境的搭建
4,目前只支持offline和gtid事物衝突的錯誤類型修複,無法支持其他MGR錯誤類型的修複
5,開發環境是單機多實例模式測試,沒有在多機單實例模式下充分測試
以上都會逐步改善&加強。

# -*- coding: utf-8 -*-

import pymysql
import logging
import time
import decimal


def execute_query(conn_dict,sql):
    conn = pymysql.connect(host=conn_dict['host'],
                           port=conn_dict['port'],
                           user=conn_dict['user'],
                           passwd=conn_dict['password'],
                           db=conn_dict['db'])
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute(sql)
    list = cursor.fetchall()
    cursor.close()
    conn.close()
    return list


def execute_noquery(conn_dict,sql):
    conn = pymysql.connect(host=conn_dict['host'],
                           port=conn_dict['port'],
                           user=conn_dict['user'],
                           passwd=conn_dict['password'],
                           db=conn_dict['db'])
    cursor = conn.cursor()
    cursor.execute(sql)
    conn.commit()
    cursor.close()
    conn.close()
    return list


def get_gtid(conn_dict):
    sql = "show master status;"
    list = execute_query(conn_dict,sql)
    return list


def skip_gtid_on_slave(conn_dict,gtid):
    sql_1 = 'stop group_replication;'
    sql_2 = '''set gtid_next='{0}';'''.format(gtid)
    sql_3 = 'begin;'
    sql_4 = 'commit;'
    sql_5 = '''set gtid_next='automatic';'''

    try:
        execute_noquery(conn_dict, sql_1)
        execute_noquery(conn_dict, sql_2)
        execute_noquery(conn_dict, sql_3)
        execute_noquery(conn_dict, sql_4)
        execute_noquery(conn_dict, sql_5)
    except:
        raise


def get_group_replication_status(conn_dict):
    sql = '''select MEMBER_STATE from performance_schema.replication_group_members 
            where (MEMBER_HOST = '{0}' or ifnull(MEMBER_HOST,'') = '')   
            AND (MEMBER_PORT={1} or ifnull(MEMBER_PORT,'') ='') ; '''.format(conn_dict["host"], conn_dict["port"])
    result = execute_query(conn_dict,sql)
    if result:
        return result
    else:
        return None


def check_replication_group_members(conn_dict):
    print('-------------------------------------------------------')
    result = execute_query(conn_dict, " select * from performance_schema.replication_group_members; ")
    if result:
        column = result[0].keys()
        current_row = ''
        for key in column:
            current_row += str(key) + "    "
        print(current_row)

        for row in result:
            current_row = ''
            for key in row.values():
                current_row += str(key) + "    "
            print(current_row)
    print('-------------------------------------------------------')


def auto_fix_mgr_error(conn_master_dict,conn_slave_dict):
    group_replication_status = get_group_replication_status(conn_slave_dict)
    if(group_replication_status[0]["MEMBER_STATE"]=="ERROR" or group_replication_status[0]["MEMBER_STATE"] == "OFFLINE"):
        print(conn_slave_dict["host"]+str(conn_slave_dict["port"])+'------>'+group_replication_status[0]["MEMBER_STATE"])
        print("auto fixing......")
        while 1 > 0:
            master_gtid_list = get_gtid(conn_master_dict)
            slave_gtid_list = get_gtid(conn_slave_dict)
            master_executed_gtid_value = int((master_gtid_list[-1]["Executed_Gtid_Set"]).split("-")[-1])
            slave_executed_gtid_value = int(slave_gtid_list[-1]["Executed_Gtid_Set"].split("-")[-1])
            slave_executed_gtid_prefix = slave_gtid_list[-1]["Executed_Gtid_Set"].split(":")[0]
            slave_executed_skiped_gtid = slave_executed_gtid_value + 1
            if (master_executed_gtid_value > slave_executed_gtid_value):
                print("skip gtid and restart group replication,skiped gtid is "
                      + slave_gtid_list[-1]["Executed_Gtid_Set"].split(":")[-1].split("-")[0]
                      + ":"+str(slave_executed_skiped_gtid))
                slave_executed_skiped_gtid = slave_executed_gtid_prefix+":"+str(slave_executed_skiped_gtid)
                skip_gtid_on_slave(conn_slave_dict,slave_executed_skiped_gtid)
                time.sleep(10)
                start_group_replication(conn_slave_dict)
                if(get_group_replication_status(conn_slave_dict)[0]["MEMBER_STATE"]=="ONLINE"):
                    print("mgr cluster fixed,back to normal")
                    break
            else:
                start_group_replication(conn_slave_dict)
                if(get_group_replication_status(conn_slave_dict)[0]["MEMBER_STATE"]=="ONLINE"):
                    print("mgr cluster fixed,back to normal")
                break
    elif (group_replication_status[0]['MEMBER_STATE'] == 'ONLINE'):
        print("mgr cluster is normal,nothing to do")
        check_replication_group_members(conn_slave_dict)

'''
reset master
'''
def reset_master(conn_dict):
    try:
        execute_noquery(conn_dict, "reset master;")
    except:
        raise


def install_group_replication_plugin(conn_dict):
    get_plugin_sql = "SELECT name,dl FROM mysql.plugin WHERE name = 'group_replication';"
    install_plugin_sql = '''install plugin group_replication soname 'group_replication.so'; '''
    try:
        result = execute_query(conn_dict, get_plugin_sql)
        if not result:
            execute_noquery(conn_dict, install_plugin_sql)
    except:
        raise


def create_mgr_repl_user(conn_master_dict,user,password):
    try:
        reset_master(conn_master_dict)
        sql_exists_user = '''select user from mysql.user where user = '{0}'; '''.format(user)
        user_list = execute_query(conn_master_dict,sql_exists_user)
        if not user_list:
            create_user_sql = '''create user {0}@'%' identified by '{1}'; '''.format(user,password)
            grant_privilege_sql = '''grant replication slave on *.* to {0}@'%';'''.format(user)
            execute_noquery(conn_master_dict,create_user_sql)
            execute_noquery(conn_master_dict, grant_privilege_sql)
            execute_noquery(conn_master_dict, "flush privileges;")
    except:
        raise


def set_super_read_only_off(conn_dict):
    super_read_only_off = '''set global super_read_only = 0;'''
    execute_noquery(conn_dict, super_read_only_off)


def open_group_replication_bootstrap_group(conn_dict):
    sql = '''select variable_name,variable_value from performance_schema.global_variables where variable_name = 'group_replication_bootstrap_group';'''
    result = execute_query(conn_dict, sql)
    open_bootstrap_group_sql = '''set @@global.group_replication_bootstrap_group=on;'''
    if result and result[0]['variable_value']=="OFF":
        execute_noquery(conn_dict, open_bootstrap_group_sql)


def close_group_replication_bootstrap_group(conn_dict):
    sql = '''select variable_name,variable_value from performance_schema.global_variables where variable_name = 'group_replication_bootstrap_group';'''
    result = execute_query(conn_dict, sql)
    close_bootstrap_group_sql = '''set @@global.group_replication_bootstrap_group=off;'''
    if result and result[0]['variable_value'] == "ON":
        execute_noquery(conn_dict, close_bootstrap_group_sql)


def start_group_replication(conn_dict):
    start_group_replication = '''start group_replication;'''
    group_replication_status = get_group_replication_status(conn_dict)
    if not (group_replication_status[0]['MEMBER_STATE'] == 'ONLINE'):
        execute_noquery(conn_dict, start_group_replication)


def connect_to_group(conn_dict,repl_user,repl_password):
    connect_to_group_sql = '''change master to
                                    master_user='{0}',
                                    master_password='{1}'
                                    for channel 'group_replication_recovery'; '''.format(repl_user,repl_password)
    try:
        execute_noquery(conn_dict, connect_to_group_sql)
    except:
        raise


def start_mgr_on_master(conn_master_dict,repl_user,repl_password):
    try:
        set_super_read_only_off(conn_master_dict)
        reset_master(conn_master_dict)
        create_mgr_repl_user(conn_master_dict,repl_user,repl_password)
        connect_to_group(conn_master_dict,repl_user,repl_password)

        open_group_replication_bootstrap_group(conn_master_dict)
        start_group_replication(conn_master_dict)
        close_group_replication_bootstrap_group(conn_master_dict)

        group_replication_status = get_group_replication_status(conn_master_dict)
        if (group_replication_status[0]['MEMBER_STATE'] == 'ONLINE'):
            print("master added in mgr and run successfully")
            return True
    except:
        raise
        print("############start master mgr error################")
        exit(1)


def start_mgr_on_slave(conn_slave_dict,repl_user,repl_password):
    try:
        set_super_read_only_off(conn_slave_dict)
        reset_master(conn_slave_dict)
        connect_to_group(conn_slave_dict,repl_user,repl_password)
        start_group_replication(conn_slave_dict)
        # wait for 10
        time.sleep(10)
        # then check mgr status
        group_replication_status = get_group_replication_status(conn_slave_dict)
        if (group_replication_status[0]['MEMBER_STATE'] == 'ONLINE'):
            print("slave added in mgr and run successfully")
        if (group_replication_status[0]['MEMBER_STATE'] == 'RECOVERING'):
            print("slave is recovering")
    except:
        print("############start slave mgr error################")
        exit(1)


def auto_mgr(conn_master,conn_slave_1,conn_slave_2,repl_user,repl_password):
    install_group_replication_plugin(conn_master)
    master_replication_status = get_group_replication_status(conn_master)

    if not (master_replication_status[0]['MEMBER_STATE'] == 'ONLINE'):
        start_mgr_on_master(conn_master,repl_user,repl_password)

    slave1_replication_status = get_group_replication_status(conn_slave_1)
    if not (slave1_replication_status[0]['MEMBER_STATE'] == 'ONLINE'):
        install_group_replication_plugin(conn_slave_1)
        start_mgr_on_slave(conn_slave_1, repl_user, repl_user)

    slave2_replication_status = get_group_replication_status(conn_slave_2)
    if not (slave2_replication_status[0]['MEMBER_STATE'] == 'ONLINE'):
        install_group_replication_plugin(conn_slave_2)
        start_mgr_on_slave(conn_slave_2, repl_user, repl_user)

    check_replication_group_members(conn_master)

if __name__ == '__main__':
    conn_master  = {'host': '127.0.0.1', 'port': 7001, 'user': 'root', 'password': 'root', 'db': 'mysql', 'charset': 'utf8mb4'}
    conn_slave_1 = {'host': '127.0.0.1', 'port': 7002, 'user': 'root', 'password': 'root', 'db': 'mysql', 'charset': 'utf8mb4'}
    conn_slave_2 = {'host': '127.0.0.1', 'port': 7003, 'user': 'root', 'password': 'root', 'db': 'mysql', 'charset': 'utf8mb4'}
    repl_user = "repl"
    repl_password = "repl"
    #auto_mgr(conn_master,conn_slave_1,conn_slave_2,repl_user,repl_password)

    auto_fix_mgr_error(conn_master,conn_slave_1)
    check_replication_group_members(conn_master)

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 目錄 Cacti+nagios監控部署步驟... 2 一、Cacti安裝... 2 1需要安裝的依賴軟體包:... 2 2安裝rrdtool 2 3啟動資料庫和httpd服務... 3 4將servername和ip對應寫入hosts 3 5安裝cacti 3 6創建cacti資料庫並授權:... ...
  • 隊列的分類 隊列一般分為三種:順序隊列、迴圈隊列、鏈式隊列 其中順序隊列和迴圈隊列按照存儲方式又可以分為動態和靜態,鏈式隊列是動態的。 順序隊列 順序隊列存在”假溢出“現象:即隊頭由於出隊操作,還有剩餘空間,但隊尾指針已達到數組的末尾,如果繼續插入元素,隊尾指針就會越出數組的上界,而造成“溢出”,這 ...
  • 一、在struct termios結構體中,對串口進行基本配置(如波特率設置,校驗位和停止位設置 等)。 (一): struct termios //串口的設置主要是設置struct termios結構體的各成員 { tcflag_t c_iflag; //input mode flags 輸入模式 ...
  • 許可權的基本介紹: rwx許可權詳解: rwx作用到文件: [r]:代表可讀,可以讀取、查看 [w]:代表可寫,可以修改,但不代表可以刪除該文件,刪除一個文件的前提條件是對該文件所在的目錄有寫許可權才能刪除該文件 [x]:代表可執行 rwx作用在目錄: [r]:代表可讀,可以讀取、ls查看目錄內容 [w] ...
  • 平常我經常使用 htop 工具來進行對主機進行性能檢測。但是它只能對 進行進行管理。並簡要顯示 進程和cpu和記憶體使用信息; glances 是比較好的性能檢測工具。相比較htop還能顯示 disk io net 等更多信息。並且還有web ui和ipc 模式。當我們有多台機器的時候,使用此工具極為 ...
  • 使用 Linux 好久了,一定會意識到一個問題,某個分區容量不夠用了,想要擴容怎麼辦?這裡就涉及到 LVM 邏輯捲的管理了,可以動態調整 Linux 分區容量。 ...
  • [20190823]關於CPU成本計算2.txt--//前幾天探究CPU cost時遇到的問題,獲取行成本時我的測試查詢結果出現跳躍,不知道為什麼,感覺有點奇怪,分析看看。--//ITPUB原始鏈接已經不存在,我的日記本還有記錄,現在想想當時的記錄思路很亂,不過這些都是猜測的過程,以前思路混亂也是正 ...
  • 前言: 前面幾篇文章為大家介紹了各種SQL語法的使用,本篇文章將主要介紹MySQL用戶及許可權相關知識,如果你不是DBA的話可能平時用的不多,但是瞭解下也是好處多多。 1.創建用戶 官方推薦創建語法為: 通常我們常用的創建語法為: 語法說明如下: 1) 指定創建用戶賬號,格式為 'user_name' ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...