MySQL在線DDL"gh-ost"

大表的DDL的變更大部分都是使用Percona的pt-online-schema-change,本文說明下另一種工具gh-ost的使用:不依賴于觸發(fā)器,是因為他是通過模擬從庫,在row binlog中獲取增量變更,再異步應(yīng)用到ghost表的。

成都創(chuàng)新互聯(lián)成立于2013年,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項目做網(wǎng)站、成都網(wǎng)站制作網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元四子王做網(wǎng)站,已為上家服務(wù),為四子王各地企業(yè)和個人服務(wù),聯(lián)系電話:18980820575

1、下載安裝地址:

https://github.com/github/gh-ost/tags

2、參數(shù)說明:gh-ost --help

Usage of gh-ost:

  --aliyun-rds:是否在阿里云數(shù)據(jù)庫上執(zhí)行。true

  --allow-master-master:是否允許gh-ost運行在雙主復(fù)制架構(gòu)中,一般與-assume-master-host參數(shù)一起使用

  --allow-nullable-unique-key:允許gh-ost在數(shù)據(jù)遷移依賴的唯一鍵可以為NULL,默認(rèn)為不允許為NULL的唯一鍵。如果數(shù)據(jù)遷移(migrate)依賴的唯一鍵允許NULL值,則可能造成數(shù)據(jù)不正確,請謹(jǐn)慎使用。

  --allow-on-master:允許gh-ost直接運行在主庫上。默認(rèn)gh-ost連接的從庫。

  --alter string:DDL語句

  --approve-renamed-columns ALTER:如果你修改一個列的名字,gh-ost將會識別到并且需要提供重命名列名的原因,默認(rèn)情況下gh-ost是不繼續(xù)執(zhí)行的,除非提供-approve-renamed-columns ALTER。

  --ask-pass:MySQL密碼

  --assume-master-host string:為gh-ost指定一個主庫,格式為”ip:port”或者”hostname:port”。在這主主架構(gòu)里比較有用,或則在gh-ost發(fā)現(xiàn)不到主的時候有用。

  --assume-rbr:確認(rèn)gh-ost連接的數(shù)據(jù)庫實例的binlog_format=ROW的情況下,可以指定-assume-rbr,這樣可以禁止從庫上運行stop slave,start slave,執(zhí)行g(shù)h-ost用戶也不需要SUPER權(quán)限。

  --check-flag

  --chunk-size int:在每次迭代中處理的行數(shù)量(允許范圍:100-100000),默認(rèn)值為1000。

  --concurrent-rowcount:該參數(shù)如果為True(默認(rèn)值),則進(jìn)行row-copy之后,估算統(tǒng)計行數(shù)(使用explain select count(*)方式),并調(diào)整ETA時間,否則,gh-ost首先預(yù)估統(tǒng)計行數(shù),然后開始row-copy。

  --conf string:gh-ost的配置文件路徑。

  --critical-load string:一系列逗號分隔的status-name=values組成,當(dāng)MySQL中status超過對應(yīng)的values,gh-ost將會退出。-critical-load Threads_connected=20,Connections=1500,指的是當(dāng)MySQL中的狀態(tài)值Threads_connected>20,Connections>1500的時候,gh-ost將會由于該數(shù)據(jù)庫嚴(yán)重負(fù)載而停止并退出。

        Comma delimited status-name=threshold, same format as --max-load. When status exceeds threshold, app panics and quits

  --critical-load-hibernate-seconds int :負(fù)載達(dá)到critical-load時,gh-ost在指定的時間內(nèi)進(jìn)入休眠狀態(tài)。 它不會讀/寫任何來自任何服務(wù)器的任何內(nèi)容。

  --critical-load-interval-millis int:當(dāng)值為0時,當(dāng)達(dá)到-critical-load,gh-ost立即退出。當(dāng)值不為0時,當(dāng)達(dá)到-critical-load,gh-ost會在-critical-load-interval-millis秒數(shù)后,再次進(jìn)行檢查,再次檢查依舊達(dá)到-critical-load,gh-ost將會退出。

  --cut-over string:選擇cut-over類型:atomic/two-step,atomic(默認(rèn))類型的cut-over是github的算法,two-step采用的是facebook-OSC的算法。

  --cut-over-exponential-backoff

  --cut-over-lock-timeout-seconds int:gh-ost在cut-over階段最大的鎖等待時間,當(dāng)鎖超時時,gh-ost的cut-over將重試。(默認(rèn)值:3)

  --database string:數(shù)據(jù)庫名稱。

  --debug:debug模式。

  --default-retries int:各種操作在panick前重試次數(shù)。(默認(rèn)為60)

  --discard-foreign-keys:該參數(shù)針對一個有外鍵的表,在gh-ost創(chuàng)建ghost表時,并不會為ghost表創(chuàng)建外鍵。該參數(shù)很適合用于刪除外鍵,除此之外,請謹(jǐn)慎使用。

  --dml-batch-size int:在單個事務(wù)中應(yīng)用DML事件的批量大小(范圍1-100)(默認(rèn)值為10)

  --exact-rowcount:準(zhǔn)確統(tǒng)計表行數(shù)(使用select count(*)的方式),得到更準(zhǔn)確的預(yù)估時間。

  --execute:實際執(zhí)行alter&migrate表,默認(rèn)為noop,不執(zhí)行,僅僅做測試并退出,如果想要ALTER TABLE語句真正落實到數(shù)據(jù)庫中去,需要明確指定-execute

  --exponential-backoff-max-interval int

  --force-named-cut-over:如果為true,則'unpostpone | cut-over'交互式命令必須命名遷移的表

  --force-table-names string:在臨時表上使用的表名前綴

  --heartbeat-interval-millis int:gh-ost心跳頻率值,默認(rèn)為500

  --help

  --hooks-hint string:任意消息通過GH_OST_HOOKS_HINT注入到鉤子

  --hooks-path string:hook文件存放目錄(默認(rèn)為empty,即禁用hook)。hook會在這個目錄下尋找符合約定命名的hook文件來執(zhí)行。

  --host string :MySQL IP/hostname

  --initially-drop-ghost-table:gh-ost操作之前,檢查并刪除已經(jīng)存在的ghost表。該參數(shù)不建議使用,請手動處理原來存在的ghost表。默認(rèn)不啟用該參數(shù),gh-ost直接退出操作。

  --initially-drop-old-table:gh-ost操作之前,檢查并刪除已經(jīng)存在的舊表。該參數(shù)不建議使用,請手動處理原來存在的ghost表。默認(rèn)不啟用該參數(shù),gh-ost直接退出操作。

  --initially-drop-socket-file:gh-ost強(qiáng)制刪除已經(jīng)存在的socket文件。該參數(shù)不建議使用,可能會刪除一個正在運行的gh-ost程序,導(dǎo)致DDL失敗。

  --master-password string :MySQL 主密碼

  --master-user string:MysQL主賬號

  --max-lag-millis int:主從復(fù)制最大延遲時間,當(dāng)主從復(fù)制延遲時間超過該值后,gh-ost將采取節(jié)流(throttle)措施,默認(rèn)值:1500s。

  --max-load string:逗號分隔狀態(tài)名稱=閾值,如:'Threads_running=100,Threads_connected=500'. When status exceeds threshold, app throttles writes

  --migrate-on-replica:gh-ost的數(shù)據(jù)遷移(migrate)運行在從庫上,而不是主庫上。 

  --nice-ratio float:每次chunk時間段的休眠時間,范圍[0.0…100.0]。0:每個chunk時間段不休眠,即一個chunk接著一個chunk執(zhí)行;1:每row-copy 1毫秒,則另外休眠1毫秒;0.7:每row-copy 10毫秒,則另外休眠7毫秒。

  --ok-to-drop-table:gh-ost操作結(jié)束后,刪除舊表,默認(rèn)狀態(tài)是不刪除舊表,會存在_tablename_del表。

  --panic-flag-file string:當(dāng)這個文件被創(chuàng)建,gh-ost將會立即退出。

  --password string :MySQL密碼

 --port int :MySQL端口,最好用從庫

  --postpone-cut-over-flag-file string:當(dāng)這個文件存在的時候,gh-ost的cut-over階段將會被推遲,數(shù)據(jù)仍然在復(fù)制,直到該文件被刪除。

  --quiet:靜默模式。

  --replica-server-id uint : gh-ost的server_id

  --replication-lag-query string:棄用

  --serve-socket-file string:gh-ost的socket文件絕對路徑。

  --serve-tcp-port int:gh-ost使用端口,默認(rèn)為關(guān)閉端口。

  --skip-foreign-key-checks:確定你的表上沒有外鍵時,設(shè)置為'true',并且希望跳過gh-ost驗證的時間-skip-renamed-columns ALTER

  --skip-renamed-columns ALTER:如果你修改一個列的名字(如change column),gh-ost將會識別到并且需要提供重命名列名的原因,默認(rèn)情況下gh-ost是不繼續(xù)執(zhí)行的。該參數(shù)告訴gh-ost跳該列的數(shù)據(jù)遷移,讓gh-ost把重命名列作為無關(guān)緊要的列。該操作很危險,你會損失該列的所有值。

  --stack:添加錯誤堆棧追蹤。

  --switch-to-rbr:讓gh-ost自動將從庫的binlog_format轉(zhuǎn)換為ROW格式。

  --table string:表名

  --test-on-replica:在從庫上測試gh-ost,包括在從庫上數(shù)據(jù)遷移(migration),數(shù)據(jù)遷移完成后stop slave,原表和ghost表立刻交換而后立刻交換回來。繼續(xù)保持stop slave,使你可以對比兩張表。

  --test-on-replica-skip-replica-stop:當(dāng)-test-on-replica執(zhí)行時,該參數(shù)表示該過程中不用stop slave。

  --throttle-additional-flag-file string:當(dāng)該文件被創(chuàng)建后,gh-ost操作立即停止。該參數(shù)可以用在多個gh-ost同時操作的時候,創(chuàng)建一個文件,讓所有的gh-ost操作停止,或者刪除這個文件,讓所有的gh-ost操作恢復(fù)。

  --throttle-control-replicas string:列出所有需要被檢查主從復(fù)制延遲的從庫。

  --throttle-flag-file string:當(dāng)該文件被創(chuàng)建后,gh-ost操作立即停止。該參數(shù)適合控制單個gh-ost操作。-throttle-additional-flag-file string適合控制多個gh-ost操作。

  --throttle-http string

  --throttle-query string:節(jié)流查詢。每秒鐘執(zhí)行一次。當(dāng)返回值=0時不需要節(jié)流,當(dāng)返回值>0時,需要執(zhí)行節(jié)流操作。該查詢會在數(shù)據(jù)遷移(migrated)服務(wù)器上操作,所以請確保該查詢是輕量級的。

  --timestamp-old-table:在舊表名中使用時間戳。 這會使舊表名稱具有唯一且無沖突的交叉遷移

  --tungsten:告訴gh-ost你正在運行的是一個tungsten-replication拓?fù)浣Y(jié)構(gòu)。

  --user string :MYSQL用戶

  --verbose

  --version

3、使用說明:條件是操作的MySQL上需要的binlog模式是ROW。如果在一個從上測試也必須是ROW模式,還要開啟log_slave_updates。根據(jù)上面的參數(shù)說明按照需求進(jìn)行調(diào)整。

4、環(huán)境: 主庫:192.168.1.7   從庫:192.168.1.8

DDL過程:

① 檢查有沒有外鍵和觸發(fā)器。

② 檢查表的主鍵信息。

③ 檢查是否主庫或從庫,是否開啟log_slave_updates,以及binlog信息  

④ 檢查gho和del結(jié)尾的臨時表是否存在

⑤ 創(chuàng)建ghc結(jié)尾的表,存數(shù)據(jù)遷移的信息,以及binlog信息等    

---以上校驗階段

⑥ 初始化stream的連接,添加binlog的監(jiān)聽

---以下遷移階段

⑥ 創(chuàng)建gho結(jié)尾的臨時表,執(zhí)行DDL在gho結(jié)尾的臨時表上

⑦ 開啟事務(wù),按照主鍵id把源表數(shù)據(jù)寫入到gho結(jié)尾的表上,再提交,以及binlog apply。

---以下cut-over階段

⑧ lock源表,rename 表:rename 源表 to 源_del表,gho表 to 源表。

⑨ 清理ghc表。

一. 單實例上DDL: 單個實例相當(dāng)于主庫,需要開啟--allow-on-master參數(shù)和ROW模式。

gh-ost --user="root" --password="root" --host=192.168.1.7  --database="test" --table="t1"  --alter="ADD COLUMN cc2 varchar(10),add column cc3 int not null default 0 comment 'test' " --allow-on-master  --execute

二. 主從上DDL:有2個選擇,一是按照1直接在主上執(zhí)行同步到從上,另一個連接到從庫,在主庫做遷移(只要保證從庫的binlog為ROW即可,主庫不需要保證)

gh-ost --user="root" --password="root" --host=192.168.1.8  --database="test" --table="t" --initially-drop-old-table --alter="ADD COLUMN y1 varchar(10),add column y2 int not null default 0 comment 'test' "  --execute

此時的操作大致是:

1、行數(shù)據(jù)在主庫上讀寫

2、讀取從庫的二進(jìn)制日志,將變更應(yīng)用到主庫

3、在從庫收集表格式,字段&索引,行數(shù)等信息

4、在從庫上讀取內(nèi)部的變更事件(如心跳事件)

5、在主庫切換表

在執(zhí)行DDL中,從庫會執(zhí)行一次stop/start slave,要是確定從的binlog是ROW的話可以添加參數(shù):--assume-rbr。如果從庫的binlog不是ROW,可以用參數(shù)--switch-to-rbr來轉(zhuǎn)換成ROW,此時需要注意的是執(zhí)行完畢之后,binlog模式不會被轉(zhuǎn)換成原來的值。--assume-rbr和--switch-to-rbr參數(shù)不能一起使用。

三. 在從上進(jìn)行DDL測試:

gh-ost --user="root" --password="root" --host=192.168.1.8  --database="test" --table="t"  --alter="ADD COLUMN abc1 varchar(10),add column abc2 int not null default 0 comment 'test' " --test-on-replica  --switch-to-rbr --execute

參數(shù)--test-on-replica:在從庫上測試gh-ost,包括在從庫上數(shù)據(jù)遷移(migration),數(shù)據(jù)遷移完成后stop slave,原表和ghost表立刻交換而后立刻交換回來。繼續(xù)保持stop slave,使你可以對比兩張表。如果不想stop slave,則可以再添加參數(shù):--test-on-replica-skip-replica-stop

上面三種是gh-ost操作模式,上面的操作中,到最后不會清理臨時表,需要手動清理,再下次執(zhí)行之前果然臨時表還存在,則會執(zhí)行失敗,可以通過參數(shù)進(jìn)行刪除:

1、--initially-drop-ghost-table:gh-ost操作之前,檢查并刪除已經(jīng)存在的ghost表。該參數(shù)不建議使用,請手動處理原來存在的ghost表。默認(rèn)不啟用該參數(shù),gh-ost直接退出操作

2、--initially-drop-old-table:gh-ost操作之前,檢查并刪除已經(jīng)存在的舊表。該參數(shù)不建議使用,請手動處理原來存在的ghost表。默認(rèn)不啟用該參數(shù),gh-ost直接退出操作

3、--initially-drop-socket-file:gh-ost強(qiáng)制刪除已經(jīng)存在的socket文件。該參數(shù)不建議使用,可能會刪除一個正在運行的gh-ost程序,導(dǎo)致DDL失敗

4、--ok-to-drop-table:gh-ost操作結(jié)束后,刪除舊表,默認(rèn)狀態(tài)是不刪除舊表,會存在_tablename_del表

還有其他的一些參數(shù),比如:--exact-rowcount、--max-lag-millis、--max-load等等,可以看上面的說明,具體大部分常用的參數(shù)命令如下:

gh-osc --user= --password= --host= --database= --table= --max-load=Threads_running=30, --chunk-size=1000 --serve-socket-file=/tmp/gh-ost.test.sock --exact-rowcount --allow-on-master/--test-on-replica --initially-drop-ghost-table/--initially-drop-old-table/--initially-drop-socket-file --max-lag-millis= --max-load='Threads_running=100,Threads_connected=500' --ok-to-drop-table

四.額外說明:終止、暫停、限速

gh-ost --user="root" --password="root" --host=192.168.1.7  --database="test" --table="t1"  --alter="ADD COLUMN o2 varchar(10),add column o1 int not null default 0 comment 'test' " --exact-rowcount --serve-socket-file=/tmp/gh-ost.t1.sock --panic-flag-file=/tmp/gh-ost.panic.t1.flag  --postpone-cut-over-flag-file=/tmp/ghost.postpone.t1.flag --allow-on-master  --execute

① 標(biāo)示文件終止運行:--panic-flag-file

  創(chuàng)建文件終止運行,例子中創(chuàng)建/tmp/gh-ost.panic.t1.flag文件,終止正在運行的gh-ost,臨時文件清理需要手動進(jìn)行。

② 表示文件禁止cut-over進(jìn)行,即禁止表名切換,數(shù)據(jù)復(fù)制正常進(jìn)行。--postpone-cut-over-flag-file

  創(chuàng)建文件延遲cut-over進(jìn)行,即推遲切換操作。例子中創(chuàng)建/tmp/ghost.postpone.t1.flag文件,gh-ost 會完成行復(fù)制,但并不會切換表,它會持續(xù)的將原表的數(shù)據(jù)更新操作同步到臨時表中。

③ 使用socket監(jiān)聽請求,操作者可以在命令運行后更改相應(yīng)的參數(shù)。--serve-socket-file,--serve-tcp-port(默認(rèn)關(guān)閉)

  創(chuàng)建socket文件進(jìn)行監(jiān)聽,通過接口進(jìn)行參數(shù)調(diào)整,當(dāng)執(zhí)行操作的過程中發(fā)現(xiàn)負(fù)載、延遲上升了,不得不終止操作,重新配置參數(shù),如 chunk-size,然后重新執(zhí)行操作命令,可以通過scoket接口進(jìn)行動態(tài)調(diào)整。如:

暫停操作:

#暫停

echo throttle | socat - /tmp/gh-ost.test.t1.sock

#恢復(fù)

echo no-throttle | socat - /tmp/gh-ost.test.t1.sock

修改限速參數(shù):

echo chunk-size=100 | socat - /tmp/gh-ost.t1.sock

echo max-lag-millis=200 | socat - /tmp/gh-ost.t1.sock

echo max-load=Thread_running=3 | socat - /tmp/gh-ost.t1.sock

結(jié)論:雖然gh-ost不需要觸發(fā)器,對于主庫的壓力和性能影響也小很多,但是針對高并發(fā)的場景進(jìn)行DDL效率還是比pt-osc低,所以還是需要在業(yè)務(wù)低峰的時候處理。

封裝腳本:gh-ost.py

#!/bin/env python

# -*- encoding: utf-8 -*-

#----------------------------------------------

# Purpose:     gh-ost

# Created:     2018-06-16

#----------------------------------------------

import MySQLdb

import re

import sys

import time

import subprocess

import os

from optparse import OptionParser

def calc_time(func):

    def _deco(*args, **kwargs):

        begin_time = time.time()

        func(*args, **kwargs)

        cost_time = time.time() - begin_time

        print 'cost time: %ss' % round(cost_time,2)

    return _deco

def get_table_count(conn,dbname,tbname):

    query  = ''' SELECT count(*) FROM %s.%s ''' %(dbname,tbname)

    cursor = conn.cursor()

    cursor.execute(query)

    row_nums = cursor.fetchone()

    cursor.close()

    conn.close() 

    return row_nums

def online_ddl(conn,ddl_cmd):

    cursor = conn.cursor()

    cursor.execute(ddl_cmd)

    conn.commit()

    cursor.close()

    conn.close()  

#@calc_time

def run_cmd(cmd):

    p = subprocess.Popen(cmd, shell=True)

    return p,p.pid

def drop_ghost_table(conn,ghost_name_list):

    try:

        cursor = conn.cursor()

        query  = ''' DROP TABLE IF EXISTS %s; ''' %(ghost_name_list)

        cursor.execute(query)

        conn.commit()

        cursor.close()

        conn.close()

    except Exception,e:

        print e

if __name__ == "__main__":

    parser = OptionParser()

    parser.add_option("-P", "--Port", help="Port for search", dest="port")

    parser.add_option("-D", "--Dbname", help="the Dbname to use", dest="dbname")

    parser.add_option("-T", "--Table", help="the Table to use", dest="tablename")

    (options, args) = parser.parse_args()

    if not options.port:

        print 'params port need to apply'

        exit()

    if not options.dbname:

        print 'params dbname need to apply'

        exit()

    if not options.tablename:

        print 'params tablename need to apply'

        exit()

    gh_ost_socket   = '/tmp/gh-ost.%s.%s.sock' %(options.dbname,options.tablename)

    #終止標(biāo)志

    panic_flag      = '/tmp/gh-ost.panic.%s.%s.flag' %(options.dbname,options.tablename)

    # postpone_flag   =  '/tmp/gh-ost.postpone.%s.%s.flag' %(options.dbname,options.tablename)

    #暫停標(biāo)志

    throttle_flag   = '/tmp/gh-ost.throttle.%s.%s' %(options.dbname,options.tablename)

#    socket = '/data/%s/tmp/mysql.sock' %(options.port)

    socket = '/var/run/mysqld/mysqld.sock'

    

    get_conn = MySQLdb.connect(host='192.168.163.131', port=int(options.port), user='root', passwd='root', db=options.dbname, unix_socket=socket,charset='utf8')

    conn     = MySQLdb.connect(host='192.168.163.131', port=int(options.port), user='root', passwd='root', db=options.dbname, unix_socket=socket,charset='utf8')

    

    (table_count,) = get_table_count(get_conn,options.dbname,options.tablename)

    print ("\033[0;32m%s\033[0m" % "表的數(shù)量:%s" %table_count)

    DDL_CMD    = raw_input('Enter DDL CMD   : ').replace('`','')

    gh_command_list = re.split('[ ]+',DDL_CMD)

    if gh_command_list[0].upper() == 'CHANGE' and gh_command_list[1] != gh_command_list[2]:

        print ("\033[0;31m%s\033[0m" % "renamed columns' data will be lost,pt-osc exit...")

        exit()

    if table_count <= 10000:

        ddl = ''' ALTER TABLE %s %s ''' %(options.tablename,DDL_CMD)

        print ("\033[0;36m%s\033[0m" %ddl)

        print ("\033[0;32m%s\033[0m" % "online ddl ...")

        online_ddl(conn,ddl)

        print ("\033[0;32m%s\033[0m" % "執(zhí)行完成 ...")

        exit()

    else:

        MAX_LOAD   = raw_input('Enter Max Threads_running【25】 : ')

        if not MAX_LOAD:

            Threads_running = 25 

        else:

            try:

                Threads_running = int(MAX_LOAD)

            except ValueError:

                print ("\033[0;31m%s\033[0m" % "輸入類型錯誤,退出...")

                exit()

        CHUNK_SIZE = raw_input('Enter Max chunk-size【1000】    : ')

        if not CHUNK_SIZE:

            chunk_size = 1000

        else:

            try:

                chunk_size = int(CHUNK_SIZE)

            except ValueError:

                print ("\033[0;31m%s\033[0m" % "輸入類型錯誤,退出...")

                exit()

        print ("\033[0;32m%s\033[0m" % "gh-ost ddl ...")

        #--postpone-cut-over-flag-file=%s 

        gh_command = '''/usr/bin/gh-ost --user="root" --password="root" --host=192.168.163.131 --port=%s --database="%s" --table="%s" --allow-on-master  --max-load='Threads_running=%d' --chunk-size=%d --serve-socket-file=%s --panic-flag-file=%s --throttle-additional-flag-file=%s --alter="%s"  --execute ''' %(options.port,options.dbname,options.tablename,Threads_running,chunk_size,gh_ost_socket,panic_flag,throttle_flag,DDL_CMD)

        print ("\033[0;36m%s\033[0m" %gh_command)

    

        child,pid = run_cmd(gh_command)

        print ("\033[0;31mgh-ost's PID:%s\033[0m" %pid)

        print ("\033[0;33m創(chuàng)建:【touch %s】文件,暫停DDL ...\033[0m" %throttle_flag)

        try:

            child.wait()

        except:

            child.terminate()

            #clean

            ghost_name_list = '_%s_ghc,_%s_gho'  %(options.tablename,options.tablename)

            drop_ghost_table(conn,ghost_name_list)

            if os.path.exists(gh_ost_socket):

                os.system('rm -r %s' %gh_ost_socket)

                print ("\033[0;32m%s\033[0m" % "清理完成 ...")

                exit()

            print ("\033[0;32m%s\033[0m" % "清理完成 ...")

            exit()

        finally :

            pass

運行腳本:

python gh-ost.py -P3306 -Dyoon -Thank

#!/bin/env python

# -*- encoding: utf-8 -*-

#----------------------------------------------

# Purpose:     gh-ost

# Created:     2018-06-16

#----------------------------------------------

import MySQLdb

import re

import sys

import time

import subprocess

import os

from optparse import OptionParser

def calc_time(func):

    def _deco(*args, **kwargs):

        begin_time = time.time()

        func(*args, **kwargs)

        cost_time = time.time() - begin_time

        print 'cost time: %ss' % round(cost_time,2)

    return _deco

def get_table_count(conn,dbname,tbname):

    query  = ''' SELECT count(*) FROM %s.%s ''' %(dbname,tbname)

    cursor = conn.cursor()

    cursor.execute(query)

    row_nums = cursor.fetchone()

    cursor.close()

    conn.close()

    return row_nums

def online_ddl(conn,ddl_cmd):

    cursor = conn.cursor()

    cursor.execute(ddl_cmd)

    conn.commit()

    cursor.close()

    conn.close()

#@calc_time

def run_cmd(cmd):

    p = subprocess.Popen(cmd, shell=True)

    return p,p.pid

def drop_ghost_table(conn,ghost_name_list):

    try:

        cursor = conn.cursor()

        query  = ''' DROP TABLE IF EXISTS %s; ''' %(ghost_name_list)

        cursor.execute(query)

        conn.commit()

        cursor.close()

        conn.close()

    except Exception,e:

        print e

if __name__ == "__main__":

    parser = OptionParser()

    parser.add_option("-P", "--Port", help="Port for search", dest="port")

    parser.add_option("-D", "--Dbname", help="the Dbname to use", dest="dbname")

    parser.add_option("-T", "--Table", help="the Table to use", dest="tablename")

    parser.add_option("-H", "--host", help="the host to use", dest="host")

    (options, args) = parser.parse_args()

    if not options.port:

        print 'params port need to apply'

        exit()

    if not options.dbname:

        print 'params dbname need to apply'

        exit()

    if not options.tablename:

        print 'params tablename need to apply'

        exit()

    if not options.host:

        print 'params host need to apply'

        exit()

    gh_ost_socket   = '/tmp/gh-ost.%s.%s.sock' %(options.dbname,options.tablename)

    #終止標(biāo)志

    panic_flag      = '/tmp/gh-ost.panic.%s.%s.flag' %(options.dbname,options.tablename)

    # postpone_flag   =  '/tmp/gh-ost.postpone.%s.%s.flag' %(options.dbname,options.tablename)

    #暫停標(biāo)志

    throttle_flag   = '/tmp/gh-ost.throttle.%s.%s' %(options.dbname,options.tablename)

#    socket = '/data/%s/tmp/mysql.sock' %(options.port)

    socket = '/var/run/mysqld/mysqld.sock'

    get_conn = MySQLdb.connect(host=options.host, port=int(options.port), user='yoon', passwd='yoon123!@#', db=options.dbname, unix_socket=socket,charset='utf8')

    conn     = MySQLdb.connect(host=options.host, port=int(options.port), user='yoon', passwd='yoon123!@#', db=options.dbname, unix_socket=socket,charset='utf8')

    (table_count,) = get_table_count(get_conn,options.dbname,options.tablename)

    print ("\033[0;32m%s\033[0m" % "表的數(shù)量:%s" %table_count)

    DDL_CMD    = raw_input('Enter DDL CMD   : ').replace('`','')

    gh_command_list = re.split('[ ]+',DDL_CMD)

    if gh_command_list[0].upper() == 'CHANGE' and gh_command_list[1] != gh_command_list[2]:

        print ("\033[0;31m%s\033[0m" % "renamed columns' data will be lost,pt-osc exit...")

        exit()

    if table_count <= 10000:

        ddl = ''' ALTER TABLE %s %s ''' %(options.tablename,DDL_CMD)

        print ("\033[0;36m%s\033[0m" %ddl)

        print ("\033[0;32m%s\033[0m" % "online ddl ...")

        online_ddl(conn,ddl)

        print ("\033[0;32m%s\033[0m" % "執(zhí)行完成 ...")

        exit()

    else:

        MAX_LOAD   = raw_input('Enter Max Threads_running【25】 : ')

        if not MAX_LOAD:

            Threads_running = 25

        else:

            try:

                Threads_running = int(MAX_LOAD)

            except ValueError:

                print ("\033[0;31m%s\033[0m" % "輸入類型錯誤,退出...")

                exit()

        CHUNK_SIZE = raw_input('Enter Max chunk-size【1000】    : ')

        if not CHUNK_SIZE:

            chunk_size = 1000

        else:

            try:

                chunk_size = int(CHUNK_SIZE)

            except ValueError:

                print ("\033[0;31m%s\033[0m" % "輸入類型錯誤,退出...")

                exit()

        print ("\033[0;32m%s\033[0m" % "gh-ost ddl ...")

        #--postpone-cut-over-flag-file=%s

        gh_command = '''/usr/bin/gh-ost --user="yoon" --password="yoon123!@#" --host="%s" --port=%s --database="%s" --table="%s" --allow-on-master  --max-load='Threads_running=%d' --chunk-size=%d --serve-socket-file=%s --panic-flag-file=%s --throttle-additional-flag-file=%s --alter="%s"  --execute ''' %(options.host,options.port,options.dbname,options.tablename,Threads_running,chunk_size,gh_ost_socket,panic_flag,throttle_flag,DDL_CMD)

        print ("\033[0;36m%s\033[0m" %gh_command)

        child,pid = run_cmd(gh_command)

        print ("\033[0;31mgh-ost's PID:%s\033[0m" %pid)

        print ("\033[0;33m創(chuàng)建:【touch %s】文件,暫停DDL ...\033[0m" %throttle_flag)

        try:

            child.wait()

        except:

            child.terminate()

            #clean

            ghost_name_list = '_%s_ghc,_%s_gho'  %(options.tablename,options.tablename)

            drop_ghost_table(conn,ghost_name_list)

            if os.path.exists(gh_ost_socket):

                os.system('rm -r %s' %gh_ost_socket)

                print ("\033[0;32m%s\033[0m" % "清理完成 ...")

                exit()

            print ("\033[0;32m%s\033[0m" % "清理完成 ...")

            exit()

        finally :

            pass

運行:

python gh-ost.py -H192.168.1.7 -P3306 -Dyoon -Thank

總結(jié):

gh-ost 放棄了觸發(fā)器,使用 binlog 來同步。gh-ost 作為一個偽裝的備庫,可以從主庫/備庫上拉取 binlog,過濾之后重新應(yīng)用到主庫上去,相當(dāng)于主庫上的增量操作通過 binlog 又應(yīng)用回主庫本身,不過是應(yīng)用在幽靈表上。

gh-ost 首先連接到主庫上,根據(jù) alter 語句創(chuàng)建幽靈表,然后作為一個”備庫“連接到其中一個真正的備庫上,一邊在主庫上拷貝已有的數(shù)據(jù)到幽靈表,一邊從備庫上拉取增量數(shù)據(jù)的 binlog,然后不斷的把 binlog 應(yīng)用回主庫。圖中 cut-over 是最后一步,鎖住主庫的源表,等待 binlog 應(yīng)用完畢,然后替換 gh-ost 表為源表。gh-ost 在執(zhí)行中,會在原本的 binlog event 里面增加以下 hint 和心跳包,用來控制整個流程的進(jìn)度,檢測狀態(tài)等。這種架構(gòu)帶來諸多好處,例如:

整個流程異步執(zhí)行,對于源表的增量數(shù)據(jù)操作沒有額外的開銷,高峰期變更業(yè)務(wù)對性能影響小。

降低寫壓力,觸發(fā)器操作都在一個事務(wù)內(nèi),gh-ost 應(yīng)用 binlog 是另外一個連接在做。

可停止,binlog 有位點記錄,如果變更過程發(fā)現(xiàn)主庫性能受影響,可以立刻停止拉binlog,停止應(yīng)用 binlog,穩(wěn)定之后繼續(xù)應(yīng)用。

可測試,gh-ost 提供了測試功能,可以連接到一個備庫上直接做 Online DDL,在備庫上觀察變更結(jié)果是否正確,再對主庫操作,心里更有底。

參考文檔:

https://github.com/wing324/helloworld_zh/blob/master/MySQL/gh-ost/GitHub在線DDL工具gh-ost安裝文檔.md

https://www.cnblogs.com/zhoujinyi/p/9187421.html

新聞標(biāo)題:MySQL在線DDL"gh-ost"
分享網(wǎng)址:http://bm7419.com/article44/jcijee.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站、定制開發(fā)網(wǎng)站設(shè)計、微信公眾號、響應(yīng)式網(wǎng)站、網(wǎng)頁設(shè)計公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)