天天看點

MySQL線上DDL gh-ost 使用說明

背景:

      作為一個DBA,大表的DDL的變更大部分都是使用Percona的pt-online-schema-change,本文說明下另一種工具gh-ost的使用:不依賴于觸發器,是因為他是通過模拟從庫,在row binlog中擷取增量變更,再異步應用到ghost表的。在使用gh-ost之前,可以先看GitHub 開源的 MySQL 線上更改 Schema 工具【轉】文章或則官網了解其特性和原理。本文隻對使用進行說明。

說明:

1)下載下傳安裝:https://github.com/github/gh-ost/tags

2)參數說明:gh-ost --help

MySQL線上DDL gh-ost 使用說明
MySQL線上DDL gh-ost 使用說明
Usage of gh-ost:
  --aliyun-rds:是否在阿裡雲資料庫上執行。true
  --allow-master-master:是否允許gh-ost運作在雙主複制架構中,一般與-assume-master-host參數一起使用
  --allow-nullable-unique-key:允許gh-ost在資料遷移依賴的唯一鍵可以為NULL,預設為不允許為NULL的唯一鍵。如果資料遷移(migrate)依賴的唯一鍵允許NULL值,則可能造成資料不正确,請謹慎使用。
  --allow-on-master:允許gh-ost直接運作在主庫上。預設gh-ost連接配接的從庫。
  --alter string:DDL語句
  --approve-renamed-columns ALTER:如果你修改一個列的名字,gh-ost将會識别到并且需要提供重命名列名的原因,預設情況下gh-ost是不繼續執行的,除非提供-approve-renamed-columns ALTER。
  --ask-pass:MySQL密碼
  --assume-master-host string:為gh-ost指定一個主庫,格式為”ip:port”或者”hostname:port”。在這主主架構裡比較有用,或則在gh-ost發現不到主的時候有用。
  --assume-rbr:确認gh-ost連接配接的資料庫執行個體的binlog_format=ROW的情況下,可以指定-assume-rbr,這樣可以禁止從庫上運作stop slave,start slave,執行gh-ost使用者也不需要SUPER權限。
  --check-flag
  --chunk-size int:在每次疊代中處理的行數量(允許範圍:100-100000),預設值為1000。
  --concurrent-rowcount:該參數如果為True(預設值),則進行row-copy之後,估算統計行數(使用explain select count(*)方式),并調整ETA時間,否則,gh-ost首先預估統計行數,然後開始row-copy。
  --conf string:gh-ost的配置檔案路徑。
  --critical-load string:一系列逗号分隔的status-name=values組成,當MySQL中status超過對應的values,gh-ost将會退出。-critical-load Threads_connected=20,Connections=1500,指的是當MySQL中的狀态值Threads_connected>20,Connections>1500的時候,gh-ost将會由于該資料庫嚴重負載而停止并退出。
        Comma delimited status-name=threshold, same format as --max-load. When status exceeds threshold, app panics and quits
  --critical-load-hibernate-seconds int :負載達到critical-load時,gh-ost在指定的時間内進入休眠狀态。 它不會讀/寫任何來自任何伺服器的任何内容。
  --critical-load-interval-millis int:當值為0時,當達到-critical-load,gh-ost立即退出。當值不為0時,當達到-critical-load,gh-ost會在-critical-load-interval-millis秒數後,再次進行檢查,再次檢查依舊達到-critical-load,gh-ost将會退出。
  --cut-over string:選擇cut-over類型:atomic/two-step,atomic(預設)類型的cut-over是github的算法,two-step采用的是facebook-OSC的算法。
  --cut-over-exponential-backoff
  --cut-over-lock-timeout-seconds int:gh-ost在cut-over階段最大的鎖等待時間,當鎖逾時時,gh-ost的cut-over将重試。(預設值:3)
  --database string:資料庫名稱。
  --debug:debug模式。
  --default-retries int:各種操作在panick前重試次數。(預設為60)
  --discard-foreign-keys:該參數針對一個有外鍵的表,在gh-ost建立ghost表時,并不會為ghost表建立外鍵。該參數很适合用于删除外鍵,除此之外,請謹慎使用。
  --dml-batch-size int:在單個事務中應用DML事件的批量大小(範圍1-100)(預設值為10)
  --exact-rowcount:準确統計表行數(使用select count(*)的方式),得到更準确的預估時間。
  --execute:實際執行alter&migrate表,預設為noop,不執行,僅僅做測試并退出,如果想要ALTER TABLE語句真正落實到資料庫中去,需要明确指定-execute
  --exponential-backoff-max-interval int
  --force-named-cut-over:如果為true,則'unpostpone | cut-over'互動式指令必須命名遷移的表
  --force-table-names string:在臨時表上使用的表名字首
  --heartbeat-interval-millis int:gh-ost心跳頻率值,預設為500
  --help
  --hooks-hint string:任意消息通過GH_OST_HOOKS_HINT注入到鈎子
  --hooks-path string:hook檔案存放目錄(預設為empty,即禁用hook)。hook會在這個目錄下尋找符合約定命名的hook檔案來執行。
  --host string :MySQL IP/hostname
  --initially-drop-ghost-table:gh-ost操作之前,檢查并删除已經存在的ghost表。該參數不建議使用,請手動處理原來存在的ghost表。預設不啟用該參數,gh-ost直接退出操作。
  --initially-drop-old-table:gh-ost操作之前,檢查并删除已經存在的舊表。該參數不建議使用,請手動處理原來存在的ghost表。預設不啟用該參數,gh-ost直接退出操作。
  --initially-drop-socket-file:gh-ost強制删除已經存在的socket檔案。該參數不建議使用,可能會删除一個正在運作的gh-ost程式,導緻DDL失敗。
  --master-password string :MySQL 主密碼
  --master-user string:MysQL主賬号
  --max-lag-millis int:主從複制最大延遲時間,當主從複制延遲時間超過該值後,gh-ost将采取節流(throttle)措施,預設值:1500s。
  --max-load string:逗号分隔狀态名稱=門檻值,如:'Threads_running=100,Threads_connected=500'. When status exceeds threshold, app throttles writes
  --migrate-on-replica:gh-ost的資料遷移(migrate)運作在從庫上,而不是主庫上。 
  --nice-ratio float:每次chunk時間段的休眠時間,範圍[0.0…100.0]。0:每個chunk時間段不休眠,即一個chunk接着一個chunk執行;1:每row-copy 1毫秒,則另外休眠1毫秒;0.7:每row-copy 10毫秒,則另外休眠7毫秒。
  --ok-to-drop-table:gh-ost操作結束後,删除舊表,預設狀态是不删除舊表,會存在_tablename_del表。
  --panic-flag-file string:當這個檔案被建立,gh-ost将會立即退出。
  --password string :MySQL密碼
 --port int :MySQL端口,最好用從庫
  --postpone-cut-over-flag-file string:當這個檔案存在的時候,gh-ost的cut-over階段将會被推遲,資料仍然在複制,直到該檔案被删除。
  --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使用端口,預設為關閉端口。
  --skip-foreign-key-checks:确定你的表上沒有外鍵時,設定為'true',并且希望跳過gh-ost驗證的時間-skip-renamed-columns ALTER
  --skip-renamed-columns ALTER:如果你修改一個列的名字(如change column),gh-ost将會識别到并且需要提供重命名列名的原因,預設情況下gh-ost是不繼續執行的。該參數告訴gh-ost跳該列的資料遷移,讓gh-ost把重命名列作為無關緊要的列。該操作很危險,你會損失該列的所有值。
  --stack:添加錯誤堆棧追蹤。
  --switch-to-rbr:讓gh-ost自動将從庫的binlog_format轉換為ROW格式。
  --table string:表名
  --test-on-replica:在從庫上測試gh-ost,包括在從庫上資料遷移(migration),資料遷移完成後stop slave,原表和ghost表立刻交換而後立刻交換回來。繼續保持stop slave,使你可以對比兩張表。
  --test-on-replica-skip-replica-stop:當-test-on-replica執行時,該參數表示該過程中不用stop slave。
  --throttle-additional-flag-file string:當該檔案被建立後,gh-ost操作立即停止。該參數可以用在多個gh-ost同時操作的時候,建立一個檔案,讓所有的gh-ost操作停止,或者删除這個檔案,讓所有的gh-ost操作恢複。
  --throttle-control-replicas string:列出所有需要被檢查主從複制延遲的從庫。
  --throttle-flag-file string:當該檔案被建立後,gh-ost操作立即停止。該參數适合控制單個gh-ost操作。-throttle-additional-flag-file string适合控制多個gh-ost操作。
  --throttle-http string
  --throttle-query string:節流查詢。每秒鐘執行一次。當傳回值=0時不需要節流,當傳回值>0時,需要執行節流操作。該查詢會在資料遷移(migrated)伺服器上操作,是以請確定該查詢是輕量級的。
  --timestamp-old-table:在舊表名中使用時間戳。 這會使舊表名稱具有唯一且無沖突的交叉遷移
  --tungsten:告訴gh-ost你正在運作的是一個tungsten-replication拓撲結構。
  --user string :MYSQL使用者
  --verbose
  --version      

View Code

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

     環境:主庫:192.168.163.131;從庫:192.168.163.130

DDL過程:

① 檢查有沒有外鍵和觸發器。
② 檢查表的主鍵資訊。
③ 檢查是否主庫或從庫,是否開啟log_slave_updates,以及binlog資訊  
④ 檢查gho和del結尾的臨時表是否存在
⑤ 建立ghc結尾的表,存資料遷移的資訊,以及binlog資訊等    
---以上校驗階段
⑥ 初始化stream的連接配接,添加binlog的監聽
---以下遷移階段
⑥ 建立gho結尾的臨時表,執行DDL在gho結尾的臨時表上
⑦ 開啟事務,按照主鍵id把源表資料寫入到gho結尾的表上,再送出,以及binlog apply。
---以下cut-over階段
⑧ lock源表,rename 表:rename 源表 to 源_del表,gho表 to 源表。
⑨ 清理ghc表。      

1. 單執行個體上DDL: 單個執行個體相當于主庫,需要開啟--allow-on-master參數和ROW模式。

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

2. 主從上DDL:

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

gh-ost --user="root" --password="root" --host=192.168.163.130  --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      

此時的操作大緻是:

  • 行資料在主庫上讀寫
  • 讀取從庫的二進制日志,将變更應用到主庫
  • 在從庫收集表格式,字段&索引,行數等資訊
  • 在從庫上讀取内部的變更事件(如心跳事件)
  • 在主庫切換表

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

3. 在從上進行DDL測試:

gh-ost --user="root" --password="root" --host=192.168.163.130  --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      

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

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

--initially-drop-ghost-table:gh-ost操作之前,檢查并删除已經存在的ghost表。該參數不建議使用,請手動處理原來存在的ghost表。預設不啟用該參數,gh-ost直接退出操作。

--initially-drop-old-table:gh-ost操作之前,檢查并删除已經存在的舊表。該參數不建議使用,請手動處理原來存在的ghost表。預設不啟用該參數,gh-ost直接退出操作。

--initially-drop-socket-file:gh-ost強制删除已經存在的socket檔案。該參數不建議使用,可能會删除一個正在運作的gh-ost程式,導緻DDL失敗。

--ok-to-drop-table:gh-ost操作結束後,删除舊表,預設狀态是不删除舊表,會存在_tablename_del表。      

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

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      

4)額外說明:終止、暫停、限速

gh-ost --user="root" --password="root" --host=192.168.163.131  --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      

① 标示檔案終止運作:--panic-flag-file

建立檔案終止運作,例子中建立/tmp/gh-ost.panic.t1.flag檔案,終止正在運作的gh-ost,臨時檔案清理需要手動進行。

② 表示檔案禁止cut-over進行,即禁止表名切換,資料複制正常進行。--postpone-cut-over-flag-file

建立檔案延遲cut-over進行,即推遲切換操作。例子中建立/tmp/ghost.postpone.t1.flag檔案,gh-ost 會完成行複制,但并不會切換表,它會持續的将原表的資料更新操作同步到臨時表中。

③ 使用socket監聽請求,操作者可以在指令運作後更改相應的參數。--serve-socket-file,--serve-tcp-port(預設關閉)

建立socket檔案進行監聽,通過接口進行參數調整,當執行操作的過程中發現負載、延遲上升了,不得不終止操作,重新配置參數,如 chunk-size,然後重新執行操作指令,可以通過scoket接口進行動态調整。如:

暫停操作:

#暫停
echo throttle | socat - /tmp/gh-ost.test.t1.sock
#恢複
echo no-throttle | socat - /tmp/gh-ost.test.t1.sock      

修改限速參數:

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      

 4)和pt-online-schema-change對比測試

 1. 表沒有寫入并且參數為預設的情況下,二者DDL操作時間差不多,畢竟都是copy row操作。

 2. 表有大量寫入(sysbench)的情況下,因為pt-osc是多線程處理的,很快就能執行完成,而gh-ost是模拟“從”單線程應用的,極端的情況下,DDL操作非常困難的執行完畢。

 結論:雖然gh-ost不需要觸發器,對于主庫的壓力和性能影響也小很多,但是針對高并發的場景進行DDL效率還是比pt-osc低,是以還是需要在業務低峰的時候處理。相關的測試可以看gh-ost和pt-osc性能對比。

 5)封裝腳本:

環境:M:192.168.163.131(ROW),S:192.168.163.130/132

封裝腳本:gh-ost.py

MySQL線上DDL gh-ost 使用說明
MySQL線上DDL gh-ost 使用說明
#!/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)
    #終止标志
    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)
    #暫停标志
    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" % "表的數量:%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" % "執行完成 ...")
        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建立:【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      

運作:

MySQL線上DDL gh-ost 使用說明
MySQL線上DDL gh-ost 使用說明
root@test2:~# python gh-ost.py -P3306 -Dtest -Tzjy
表的數量:1310720
Enter DDL CMD   : ADD COLUMN q1 varchar(10),ADD COLUMN q2 varchar(10)
Enter Max Threads_running【25】 : 10
Enter Max chunk-size【1000】    : 200
gh-ost ddl ...
/usr/bin/gh-ost --user="root" --password="root" --host=192.168.163.131 --port=3306 --database="test" --table="zjy" --allow-on-master  --max-load='Threads_running=10' --chunk-size=200 --serve-socket-file=/tmp/gh-ost.test.zjy.sock --panic-flag-file=/tmp/gh-ost.panic.test.zjy.flag --throttle-additional-flag-file=/tmp/gh-ost.throttle.test.zjy --alter="ADD COLUMN q1 varchar(10),ADD COLUMN q2 varchar(10)"  --execute 
gh-ost's PID:2105
建立:【touch /tmp/gh-ost.throttle.test.zjy】檔案,暫停DDL ...
2018/06/17 14:37:37 binlogsyncer.go:79: [info] create BinlogSyncer with config {99999 mysql 192.168.163.131 3306 root   false false <nil>}
2018/06/17 14:37:37 binlogsyncer.go:246: [info] begin to sync binlog from position (mysql-bin.000013, 31197930)
2018/06/17 14:37:37 binlogsyncer.go:139: [info] register slave for master server 192.168.163.131:3306
2018/06/17 14:37:37 binlogsyncer.go:573: [info] rotate to (mysql-bin.000013, 31197930)
# Migrating `test`.`zjy`; Ghost table is `test`.`_zjy_gho`
# Migrating test2:3306; inspecting test2:3306; executing on test2
# Migration started at Sun Jun 17 14:37:37 +0800 2018
# chunk-size: 200; max-lag-millis: 1500ms; dml-batch-size: 10; max-load: Threads_running=10; critical-load: ; nice-ratio: 0.000000
# throttle-additional-flag-file: /tmp/gh-ost.throttle.test.zjy 
# panic-flag-file: /tmp/gh-ost.panic.test.zjy.flag
# Serving on unix socket: /tmp/gh-ost.test.zjy.sock
Copy: 0/1305600 0.0%; Applied: 0; Backlog: 0/1000; Time: 0s(total), 0s(copy); streamer: mysql-bin.000013:31199542; State: migrating; ETA: N/A
Copy: 0/1305600 0.0%; Applied: 0; Backlog: 0/1000; Time: 1s(total), 1s(copy); streamer: mysql-bin.000013:31202866; State: migrating; ETA: N/A
Copy: 44400/1305600 3.4%; Applied: 0; Backlog: 0/1000; Time: 2s(total), 2s(copy); streamer: mysql-bin.000013:33352548; State: migrating; ETA: 56s
Copy: 91200/1305600 7.0%; Applied: 0; Backlog: 0/1000; Time: 3s(total), 3s(copy); streamer: mysql-bin.000013:35598132; State: migrating; ETA: 39s
Copy: 135200/1305600 10.4%; Applied: 0; Backlog: 0/1000; Time: 4s(total), 4s(copy); streamer: mysql-bin.000013:37727925; State: migrating; ETA: 34s
Copy: 174000/1305600 13.3%; Applied: 0; Backlog: 0/1000; Time: 5s(total), 5s(copy); streamer: mysql-bin.000013:39588956; State: migrating; ETA: 32s
Copy: 212200/1305600 16.3%; Applied: 0; Backlog: 0/1000; Time: 6s(total), 6s(copy); streamer: mysql-bin.000013:41430090; State: migrating; ETA: 30s
Copy: 254800/1305600 19.5%; Applied: 0; Backlog: 0/1000; Time: 7s(total), 7s(copy); streamer: mysql-bin.000013:43483555; State: migrating; ETA: 28s
Copy: 303600/1305600 23.3%; Applied: 0; Backlog: 0/1000; Time: 8s(total), 8s(copy); streamer: mysql-bin.000013:45834978; State: migrating; ETA: 26s
Copy: 351200/1305600 26.9%; Applied: 0; Backlog: 0/1000; Time: 9s(total), 9s(copy); streamer: mysql-bin.000013:48128675; State: migrating; ETA: 24s
Copy: 401400/1305600 30.7%; Applied: 0; Backlog: 0/1000; Time: 10s(total), 10s(copy); streamer: mysql-bin.000013:50547454; State: migrating; ETA: 22s
Copy: 451200/1305600 34.6%; Applied: 0; Backlog: 0/1000; Time: 11s(total), 11s(copy); streamer: mysql-bin.000013:52946991; State: migrating; ETA: 20s
Copy: 490000/1305600 37.5%; Applied: 0; Backlog: 0/1000; Time: 12s(total), 12s(copy); streamer: mysql-bin.000013:54817320; State: migrating; ETA: 19s
Copy: 529600/1305600 40.6%; Applied: 0; Backlog: 0/1000; Time: 13s(total), 13s(copy); streamer: mysql-bin.000013:56735431; State: migrating; ETA: 19s
Copy: 589200/1305600 45.1%; Applied: 0; Backlog: 0/1000; Time: 14s(total), 14s(copy); streamer: mysql-bin.000013:59606450; State: migrating; ETA: 17s
Copy: 639400/1305600 49.0%; Applied: 0; Backlog: 0/1000; Time: 15s(total), 15s(copy); streamer: mysql-bin.000013:62025561; State: migrating; ETA: 15s
Copy: 695200/1305600 53.2%; Applied: 0; Backlog: 0/1000; Time: 16s(total), 16s(copy); streamer: mysql-bin.000013:64704138; State: migrating; ETA: 14s
Copy: 751200/1305600 57.5%; Applied: 0; Backlog: 0/1000; Time: 17s(total), 17s(copy); streamer: mysql-bin.000013:67401961; State: migrating; ETA: 12s
Copy: 803800/1305600 61.6%; Applied: 0; Backlog: 0/1000; Time: 18s(total), 18s(copy); streamer: mysql-bin.000013:69935884; State: migrating; ETA: 11s
Copy: 856400/1305600 65.6%; Applied: 0; Backlog: 0/1000; Time: 19s(total), 19s(copy); streamer: mysql-bin.000013:72470455; State: migrating; ETA: 9s
Copy: 907400/1305600 69.5%; Applied: 0; Backlog: 0/1000; Time: 20s(total), 20s(copy); streamer: mysql-bin.000013:74927401; State: migrating; ETA: 8s
Copy: 958800/1305600 73.4%; Applied: 0; Backlog: 0/1000; Time: 21s(total), 21s(copy); streamer: mysql-bin.000013:77404243; State: migrating; ETA: 7s
Copy: 999200/1305600 76.5%; Applied: 0; Backlog: 0/1000; Time: 22s(total), 22s(copy); streamer: mysql-bin.000013:79351223; State: migrating; ETA: 6s
Copy: 1009600/1305600 77.3%; Applied: 0; Backlog: 0/1000; Time: 23s(total), 23s(copy); streamer: mysql-bin.000013:79855229; State: migrating; ETA: 6s
Copy: 1059600/1305600 81.2%; Applied: 0; Backlog: 0/1000; Time: 24s(total), 24s(copy); streamer: mysql-bin.000013:82264712; State: migrating; ETA: 5s
Copy: 1107200/1305600 84.8%; Applied: 0; Backlog: 0/1000; Time: 25s(total), 25s(copy); streamer: mysql-bin.000013:84558411; State: migrating; ETA: 4s
Copy: 1147000/1305600 87.9%; Applied: 0; Backlog: 0/1000; Time: 26s(total), 26s(copy); streamer: mysql-bin.000013:86486148; State: migrating; ETA: 3s
Copy: 1198000/1305600 91.8%; Applied: 0; Backlog: 0/1000; Time: 27s(total), 27s(copy); streamer: mysql-bin.000013:88943747; State: migrating; ETA: 2s
Copy: 1245400/1305600 95.4%; Applied: 0; Backlog: 0/1000; Time: 28s(total), 28s(copy); streamer: mysql-bin.000013:91218202; State: migrating; ETA: 1s
Copy: 1286600/1305600 98.5%; Applied: 0; Backlog: 0/1000; Time: 29s(total), 29s(copy); streamer: mysql-bin.000013:93203991; State: migrating; ETA: 0s
Copy: 1310720/1310720 100.0%; Applied: 0; Backlog: 0/1000; Time: 29s(total), 29s(copy); streamer: mysql-bin.000013:94366846; State: migrating; ETA: due
Copy: 1310720/1310720 100.0%; Applied: 0; Backlog: 1/1000; Time: 30s(total), 29s(copy); streamer: mysql-bin.000013:94369042; State: migrating; ETA: due
# Migrating `test`.`zjy`; Ghost table is `test`.`_zjy_gho`
# Migrating test2:3306; inspecting test2:3306; executing on test2
# Migration started at Sun Jun 17 14:37:37 +0800 2018
# chunk-size: 200; max-lag-millis: 1500ms; dml-batch-size: 10; max-load: Threads_running=10; critical-load: ; nice-ratio: 0.000000
# throttle-additional-flag-file: /tmp/gh-ost.throttle.test.zjy 
# panic-flag-file: /tmp/gh-ost.panic.test.zjy.flag
# Serving on unix socket: /tmp/gh-ost.test.zjy.sock
Copy: 1310720/1310720 100.0%; Applied: 0; Backlog: 0/1000; Time: 30s(total), 29s(copy); streamer: mysql-bin.000013:94371928; State: migrating; ETA: due
2018/06/17 14:38:08 binlogsyncer.go:107: [info] syncer is closing... 
2018/06/17 14:38:08 binlogstreamer.go:47: [error] close sync with err: sync is been closing... (這裡的error不影響使用,重複關閉了sync,等作者修複)
2018/06/17 14:38:08 binlogsyncer.go:122: [info] syncer is closed 
# Done      

總結:

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

MySQL線上DDL gh-ost 使用說明

gh-ost 首先連接配接到主庫上,根據 alter 語句建立幽靈表,然後作為一個”備庫“連接配接到其中一個真正的備庫上,一邊在主庫上拷貝已有的資料到幽靈表,一邊從備庫上拉取增量資料的 binlog,然後不斷的把 binlog 應用回主庫。圖中 cut-over 是最後一步,鎖住主庫的源表,等待 binlog 應用完畢,然後替換 gh-ost 表為源表。gh-ost 在執行中,會在原本的 binlog event 裡面增加以下 hint 和心跳包,用來控制整個流程的進度,檢測狀态等。這種架構帶來諸多好處,例如:

  • 整個流程異步執行,對于源表的增量資料操作沒有額外的開銷,高峰期變更業務對性能影響小。
  • 降低寫壓力,觸發器操作都在一個事務内,gh-ost 應用 binlog 是另外一個連接配接在做。
  • 可停止,binlog 有位點記錄,如果變更過程發現主庫性能受影響,可以立刻停止拉binlog,停止應用 binlog,穩定之後繼續應用。
  • 可測試,gh-ost 提供了測試功能,可以連接配接到一個備庫上直接做 Online DDL,在備庫上觀察變更結果是否正确,再對主庫操作,心裡更有底。

注意: sync error的錯誤:https://github.com/github/gh-ost/issues/597

參考文檔:

https://huangzhw.github.io/2018/09/20/mysql-online-ddl/   --推薦

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

GitHub 開源的 MySQL 線上更改 Schema 工具

Online DDL 工具 gh-ost 支援阿裡雲 RDS

gh-ost:不一樣的線上表結構變更

GitHub開源MySQL Online DDL工具gh-ost參數解析 

~~~~~~~~~~~~~~~

萬物之中,希望至美

~~~~~~~~~~~~~~~

2)參數說明:gh-ost --help

MySQL線上DDL gh-ost 使用說明
MySQL線上DDL gh-ost 使用說明
Usage of gh-ost:
  --aliyun-rds:是否在阿裡雲資料庫上執行。true
  --allow-master-master:是否允許gh-ost運作在雙主複制架構中,一般與-assume-master-host參數一起使用
  --allow-nullable-unique-key:允許gh-ost在資料遷移依賴的唯一鍵可以為NULL,預設為不允許為NULL的唯一鍵。如果資料遷移(migrate)依賴的唯一鍵允許NULL值,則可能造成資料不正确,請謹慎使用。
  --allow-on-master:允許gh-ost直接運作在主庫上。預設gh-ost連接配接的從庫。
  --alter string:DDL語句
  --approve-renamed-columns ALTER:如果你修改一個列的名字,gh-ost将會識别到并且需要提供重命名列名的原因,預設情況下gh-ost是不繼續執行的,除非提供-approve-renamed-columns ALTER。
  --ask-pass:MySQL密碼
  --assume-master-host string:為gh-ost指定一個主庫,格式為”ip:port”或者”hostname:port”。在這主主架構裡比較有用,或則在gh-ost發現不到主的時候有用。
  --assume-rbr:确認gh-ost連接配接的資料庫執行個體的binlog_format=ROW的情況下,可以指定-assume-rbr,這樣可以禁止從庫上運作stop slave,start slave,執行gh-ost使用者也不需要SUPER權限。
  --check-flag
  --chunk-size int:在每次疊代中處理的行數量(允許範圍:100-100000),預設值為1000。
  --concurrent-rowcount:該參數如果為True(預設值),則進行row-copy之後,估算統計行數(使用explain select count(*)方式),并調整ETA時間,否則,gh-ost首先預估統計行數,然後開始row-copy。
  --conf string:gh-ost的配置檔案路徑。
  --critical-load string:一系列逗号分隔的status-name=values組成,當MySQL中status超過對應的values,gh-ost将會退出。-critical-load Threads_connected=20,Connections=1500,指的是當MySQL中的狀态值Threads_connected>20,Connections>1500的時候,gh-ost将會由于該資料庫嚴重負載而停止并退出。
        Comma delimited status-name=threshold, same format as --max-load. When status exceeds threshold, app panics and quits
  --critical-load-hibernate-seconds int :負載達到critical-load時,gh-ost在指定的時間内進入休眠狀态。 它不會讀/寫任何來自任何伺服器的任何内容。
  --critical-load-interval-millis int:當值為0時,當達到-critical-load,gh-ost立即退出。當值不為0時,當達到-critical-load,gh-ost會在-critical-load-interval-millis秒數後,再次進行檢查,再次檢查依舊達到-critical-load,gh-ost将會退出。
  --cut-over string:選擇cut-over類型:atomic/two-step,atomic(預設)類型的cut-over是github的算法,two-step采用的是facebook-OSC的算法。
  --cut-over-exponential-backoff
  --cut-over-lock-timeout-seconds int:gh-ost在cut-over階段最大的鎖等待時間,當鎖逾時時,gh-ost的cut-over将重試。(預設值:3)
  --database string:資料庫名稱。
  --debug:debug模式。
  --default-retries int:各種操作在panick前重試次數。(預設為60)
  --discard-foreign-keys:該參數針對一個有外鍵的表,在gh-ost建立ghost表時,并不會為ghost表建立外鍵。該參數很适合用于删除外鍵,除此之外,請謹慎使用。
  --dml-batch-size int:在單個事務中應用DML事件的批量大小(範圍1-100)(預設值為10)
  --exact-rowcount:準确統計表行數(使用select count(*)的方式),得到更準确的預估時間。
  --execute:實際執行alter&migrate表,預設為noop,不執行,僅僅做測試并退出,如果想要ALTER TABLE語句真正落實到資料庫中去,需要明确指定-execute
  --exponential-backoff-max-interval int
  --force-named-cut-over:如果為true,則'unpostpone | cut-over'互動式指令必須命名遷移的表
  --force-table-names string:在臨時表上使用的表名字首
  --heartbeat-interval-millis int:gh-ost心跳頻率值,預設為500
  --help
  --hooks-hint string:任意消息通過GH_OST_HOOKS_HINT注入到鈎子
  --hooks-path string:hook檔案存放目錄(預設為empty,即禁用hook)。hook會在這個目錄下尋找符合約定命名的hook檔案來執行。
  --host string :MySQL IP/hostname
  --initially-drop-ghost-table:gh-ost操作之前,檢查并删除已經存在的ghost表。該參數不建議使用,請手動處理原來存在的ghost表。預設不啟用該參數,gh-ost直接退出操作。
  --initially-drop-old-table:gh-ost操作之前,檢查并删除已經存在的舊表。該參數不建議使用,請手動處理原來存在的ghost表。預設不啟用該參數,gh-ost直接退出操作。
  --initially-drop-socket-file:gh-ost強制删除已經存在的socket檔案。該參數不建議使用,可能會删除一個正在運作的gh-ost程式,導緻DDL失敗。
  --master-password string :MySQL 主密碼
  --master-user string:MysQL主賬号
  --max-lag-millis int:主從複制最大延遲時間,當主從複制延遲時間超過該值後,gh-ost将采取節流(throttle)措施,預設值:1500s。
  --max-load string:逗号分隔狀态名稱=門檻值,如:'Threads_running=100,Threads_connected=500'. When status exceeds threshold, app throttles writes
  --migrate-on-replica:gh-ost的資料遷移(migrate)運作在從庫上,而不是主庫上。 
  --nice-ratio float:每次chunk時間段的休眠時間,範圍[0.0…100.0]。0:每個chunk時間段不休眠,即一個chunk接着一個chunk執行;1:每row-copy 1毫秒,則另外休眠1毫秒;0.7:每row-copy 10毫秒,則另外休眠7毫秒。
  --ok-to-drop-table:gh-ost操作結束後,删除舊表,預設狀态是不删除舊表,會存在_tablename_del表。
  --panic-flag-file string:當這個檔案被建立,gh-ost将會立即退出。
  --password string :MySQL密碼
 --port int :MySQL端口,最好用從庫
  --postpone-cut-over-flag-file string:當這個檔案存在的時候,gh-ost的cut-over階段将會被推遲,資料仍然在複制,直到該檔案被删除。
  --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使用端口,預設為關閉端口。
  --skip-foreign-key-checks:确定你的表上沒有外鍵時,設定為'true',并且希望跳過gh-ost驗證的時間-skip-renamed-columns ALTER
  --skip-renamed-columns ALTER:如果你修改一個列的名字(如change column),gh-ost将會識别到并且需要提供重命名列名的原因,預設情況下gh-ost是不繼續執行的。該參數告訴gh-ost跳該列的資料遷移,讓gh-ost把重命名列作為無關緊要的列。該操作很危險,你會損失該列的所有值。
  --stack:添加錯誤堆棧追蹤。
  --switch-to-rbr:讓gh-ost自動将從庫的binlog_format轉換為ROW格式。
  --table string:表名
  --test-on-replica:在從庫上測試gh-ost,包括在從庫上資料遷移(migration),資料遷移完成後stop slave,原表和ghost表立刻交換而後立刻交換回來。繼續保持stop slave,使你可以對比兩張表。
  --test-on-replica-skip-replica-stop:當-test-on-replica執行時,該參數表示該過程中不用stop slave。
  --throttle-additional-flag-file string:當該檔案被建立後,gh-ost操作立即停止。該參數可以用在多個gh-ost同時操作的時候,建立一個檔案,讓所有的gh-ost操作停止,或者删除這個檔案,讓所有的gh-ost操作恢複。
  --throttle-control-replicas string:列出所有需要被檢查主從複制延遲的從庫。
  --throttle-flag-file string:當該檔案被建立後,gh-ost操作立即停止。該參數适合控制單個gh-ost操作。-throttle-additional-flag-file string适合控制多個gh-ost操作。
  --throttle-http string
  --throttle-query string:節流查詢。每秒鐘執行一次。當傳回值=0時不需要節流,當傳回值>0時,需要執行節流操作。該查詢會在資料遷移(migrated)伺服器上操作,是以請確定該查詢是輕量級的。
  --timestamp-old-table:在舊表名中使用時間戳。 這會使舊表名稱具有唯一且無沖突的交叉遷移
  --tungsten:告訴gh-ost你正在運作的是一個tungsten-replication拓撲結構。
  --user string :MYSQL使用者
  --verbose
  --version      
① 檢查有沒有外鍵和觸發器。
② 檢查表的主鍵資訊。
③ 檢查是否主庫或從庫,是否開啟log_slave_updates,以及binlog資訊  
④ 檢查gho和del結尾的臨時表是否存在
⑤ 建立ghc結尾的表,存資料遷移的資訊,以及binlog資訊等    
---以上校驗階段
⑥ 初始化stream的連接配接,添加binlog的監聽
---以下遷移階段
⑥ 建立gho結尾的臨時表,執行DDL在gho結尾的臨時表上
⑦ 開啟事務,按照主鍵id把源表資料寫入到gho結尾的表上,再送出,以及binlog apply。
---以下cut-over階段
⑧ lock源表,rename 表:rename 源表 to 源_del表,gho表 to 源表。
⑨ 清理ghc表。      
gh-ost --user="root" --password="root" --host=192.168.163.131  --database="test" --table="t1"  --alter="ADD COLUMN cc2 varchar(10),add column cc3 int not null default 0 comment 'test' " --allow-on-master  --execute      
gh-ost --user="root" --password="root" --host=192.168.163.130  --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      
gh-ost --user="root" --password="root" --host=192.168.163.130  --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      
--initially-drop-ghost-table:gh-ost操作之前,檢查并删除已經存在的ghost表。該參數不建議使用,請手動處理原來存在的ghost表。預設不啟用該參數,gh-ost直接退出操作。

--initially-drop-old-table:gh-ost操作之前,檢查并删除已經存在的舊表。該參數不建議使用,請手動處理原來存在的ghost表。預設不啟用該參數,gh-ost直接退出操作。

--initially-drop-socket-file:gh-ost強制删除已經存在的socket檔案。該參數不建議使用,可能會删除一個正在運作的gh-ost程式,導緻DDL失敗。

--ok-to-drop-table:gh-ost操作結束後,删除舊表,預設狀态是不删除舊表,會存在_tablename_del表。      
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.163.131  --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      
#暫停
echo throttle | socat - /tmp/gh-ost.test.t1.sock
#恢複
echo no-throttle | socat - /tmp/gh-ost.test.t1.sock      
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      
MySQL線上DDL gh-ost 使用說明
MySQL線上DDL gh-ost 使用說明
#!/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)
    #終止标志
    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)
    #暫停标志
    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" % "表的數量:%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" % "執行完成 ...")
        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建立:【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      
MySQL線上DDL gh-ost 使用說明
MySQL線上DDL gh-ost 使用說明
root@test2:~# python gh-ost.py -P3306 -Dtest -Tzjy
表的數量:1310720
Enter DDL CMD   : ADD COLUMN q1 varchar(10),ADD COLUMN q2 varchar(10)
Enter Max Threads_running【25】 : 10
Enter Max chunk-size【1000】    : 200
gh-ost ddl ...
/usr/bin/gh-ost --user="root" --password="root" --host=192.168.163.131 --port=3306 --database="test" --table="zjy" --allow-on-master  --max-load='Threads_running=10' --chunk-size=200 --serve-socket-file=/tmp/gh-ost.test.zjy.sock --panic-flag-file=/tmp/gh-ost.panic.test.zjy.flag --throttle-additional-flag-file=/tmp/gh-ost.throttle.test.zjy --alter="ADD COLUMN q1 varchar(10),ADD COLUMN q2 varchar(10)"  --execute 
gh-ost's PID:2105
建立:【touch /tmp/gh-ost.throttle.test.zjy】檔案,暫停DDL ...
2018/06/17 14:37:37 binlogsyncer.go:79: [info] create BinlogSyncer with config {99999 mysql 192.168.163.131 3306 root   false false <nil>}
2018/06/17 14:37:37 binlogsyncer.go:246: [info] begin to sync binlog from position (mysql-bin.000013, 31197930)
2018/06/17 14:37:37 binlogsyncer.go:139: [info] register slave for master server 192.168.163.131:3306
2018/06/17 14:37:37 binlogsyncer.go:573: [info] rotate to (mysql-bin.000013, 31197930)
# Migrating `test`.`zjy`; Ghost table is `test`.`_zjy_gho`
# Migrating test2:3306; inspecting test2:3306; executing on test2
# Migration started at Sun Jun 17 14:37:37 +0800 2018
# chunk-size: 200; max-lag-millis: 1500ms; dml-batch-size: 10; max-load: Threads_running=10; critical-load: ; nice-ratio: 0.000000
# throttle-additional-flag-file: /tmp/gh-ost.throttle.test.zjy 
# panic-flag-file: /tmp/gh-ost.panic.test.zjy.flag
# Serving on unix socket: /tmp/gh-ost.test.zjy.sock
Copy: 0/1305600 0.0%; Applied: 0; Backlog: 0/1000; Time: 0s(total), 0s(copy); streamer: mysql-bin.000013:31199542; State: migrating; ETA: N/A
Copy: 0/1305600 0.0%; Applied: 0; Backlog: 0/1000; Time: 1s(total), 1s(copy); streamer: mysql-bin.000013:31202866; State: migrating; ETA: N/A
Copy: 44400/1305600 3.4%; Applied: 0; Backlog: 0/1000; Time: 2s(total), 2s(copy); streamer: mysql-bin.000013:33352548; State: migrating; ETA: 56s
Copy: 91200/1305600 7.0%; Applied: 0; Backlog: 0/1000; Time: 3s(total), 3s(copy); streamer: mysql-bin.000013:35598132; State: migrating; ETA: 39s
Copy: 135200/1305600 10.4%; Applied: 0; Backlog: 0/1000; Time: 4s(total), 4s(copy); streamer: mysql-bin.000013:37727925; State: migrating; ETA: 34s
Copy: 174000/1305600 13.3%; Applied: 0; Backlog: 0/1000; Time: 5s(total), 5s(copy); streamer: mysql-bin.000013:39588956; State: migrating; ETA: 32s
Copy: 212200/1305600 16.3%; Applied: 0; Backlog: 0/1000; Time: 6s(total), 6s(copy); streamer: mysql-bin.000013:41430090; State: migrating; ETA: 30s
Copy: 254800/1305600 19.5%; Applied: 0; Backlog: 0/1000; Time: 7s(total), 7s(copy); streamer: mysql-bin.000013:43483555; State: migrating; ETA: 28s
Copy: 303600/1305600 23.3%; Applied: 0; Backlog: 0/1000; Time: 8s(total), 8s(copy); streamer: mysql-bin.000013:45834978; State: migrating; ETA: 26s
Copy: 351200/1305600 26.9%; Applied: 0; Backlog: 0/1000; Time: 9s(total), 9s(copy); streamer: mysql-bin.000013:48128675; State: migrating; ETA: 24s
Copy: 401400/1305600 30.7%; Applied: 0; Backlog: 0/1000; Time: 10s(total), 10s(copy); streamer: mysql-bin.000013:50547454; State: migrating; ETA: 22s
Copy: 451200/1305600 34.6%; Applied: 0; Backlog: 0/1000; Time: 11s(total), 11s(copy); streamer: mysql-bin.000013:52946991; State: migrating; ETA: 20s
Copy: 490000/1305600 37.5%; Applied: 0; Backlog: 0/1000; Time: 12s(total), 12s(copy); streamer: mysql-bin.000013:54817320; State: migrating; ETA: 19s
Copy: 529600/1305600 40.6%; Applied: 0; Backlog: 0/1000; Time: 13s(total), 13s(copy); streamer: mysql-bin.000013:56735431; State: migrating; ETA: 19s
Copy: 589200/1305600 45.1%; Applied: 0; Backlog: 0/1000; Time: 14s(total), 14s(copy); streamer: mysql-bin.000013:59606450; State: migrating; ETA: 17s
Copy: 639400/1305600 49.0%; Applied: 0; Backlog: 0/1000; Time: 15s(total), 15s(copy); streamer: mysql-bin.000013:62025561; State: migrating; ETA: 15s
Copy: 695200/1305600 53.2%; Applied: 0; Backlog: 0/1000; Time: 16s(total), 16s(copy); streamer: mysql-bin.000013:64704138; State: migrating; ETA: 14s
Copy: 751200/1305600 57.5%; Applied: 0; Backlog: 0/1000; Time: 17s(total), 17s(copy); streamer: mysql-bin.000013:67401961; State: migrating; ETA: 12s
Copy: 803800/1305600 61.6%; Applied: 0; Backlog: 0/1000; Time: 18s(total), 18s(copy); streamer: mysql-bin.000013:69935884; State: migrating; ETA: 11s
Copy: 856400/1305600 65.6%; Applied: 0; Backlog: 0/1000; Time: 19s(total), 19s(copy); streamer: mysql-bin.000013:72470455; State: migrating; ETA: 9s
Copy: 907400/1305600 69.5%; Applied: 0; Backlog: 0/1000; Time: 20s(total), 20s(copy); streamer: mysql-bin.000013:74927401; State: migrating; ETA: 8s
Copy: 958800/1305600 73.4%; Applied: 0; Backlog: 0/1000; Time: 21s(total), 21s(copy); streamer: mysql-bin.000013:77404243; State: migrating; ETA: 7s
Copy: 999200/1305600 76.5%; Applied: 0; Backlog: 0/1000; Time: 22s(total), 22s(copy); streamer: mysql-bin.000013:79351223; State: migrating; ETA: 6s
Copy: 1009600/1305600 77.3%; Applied: 0; Backlog: 0/1000; Time: 23s(total), 23s(copy); streamer: mysql-bin.000013:79855229; State: migrating; ETA: 6s
Copy: 1059600/1305600 81.2%; Applied: 0; Backlog: 0/1000; Time: 24s(total), 24s(copy); streamer: mysql-bin.000013:82264712; State: migrating; ETA: 5s
Copy: 1107200/1305600 84.8%; Applied: 0; Backlog: 0/1000; Time: 25s(total), 25s(copy); streamer: mysql-bin.000013:84558411; State: migrating; ETA: 4s
Copy: 1147000/1305600 87.9%; Applied: 0; Backlog: 0/1000; Time: 26s(total), 26s(copy); streamer: mysql-bin.000013:86486148; State: migrating; ETA: 3s
Copy: 1198000/1305600 91.8%; Applied: 0; Backlog: 0/1000; Time: 27s(total), 27s(copy); streamer: mysql-bin.000013:88943747; State: migrating; ETA: 2s
Copy: 1245400/1305600 95.4%; Applied: 0; Backlog: 0/1000; Time: 28s(total), 28s(copy); streamer: mysql-bin.000013:91218202; State: migrating; ETA: 1s
Copy: 1286600/1305600 98.5%; Applied: 0; Backlog: 0/1000; Time: 29s(total), 29s(copy); streamer: mysql-bin.000013:93203991; State: migrating; ETA: 0s
Copy: 1310720/1310720 100.0%; Applied: 0; Backlog: 0/1000; Time: 29s(total), 29s(copy); streamer: mysql-bin.000013:94366846; State: migrating; ETA: due
Copy: 1310720/1310720 100.0%; Applied: 0; Backlog: 1/1000; Time: 30s(total), 29s(copy); streamer: mysql-bin.000013:94369042; State: migrating; ETA: due
# Migrating `test`.`zjy`; Ghost table is `test`.`_zjy_gho`
# Migrating test2:3306; inspecting test2:3306; executing on test2
# Migration started at Sun Jun 17 14:37:37 +0800 2018
# chunk-size: 200; max-lag-millis: 1500ms; dml-batch-size: 10; max-load: Threads_running=10; critical-load: ; nice-ratio: 0.000000
# throttle-additional-flag-file: /tmp/gh-ost.throttle.test.zjy 
# panic-flag-file: /tmp/gh-ost.panic.test.zjy.flag
# Serving on unix socket: /tmp/gh-ost.test.zjy.sock
Copy: 1310720/1310720 100.0%; Applied: 0; Backlog: 0/1000; Time: 30s(total), 29s(copy); streamer: mysql-bin.000013:94371928; State: migrating; ETA: due
2018/06/17 14:38:08 binlogsyncer.go:107: [info] syncer is closing... 
2018/06/17 14:38:08 binlogstreamer.go:47: [error] close sync with err: sync is been closing... (這裡的error不影響使用,重複關閉了sync,等作者修複)
2018/06/17 14:38:08 binlogsyncer.go:122: [info] syncer is closed 
# Done      

MySQL線上DDL gh-ost 使用說明