MySQL 在线DDL “gh-ost”


大表的DDL的变更大部分都是使用Percona的pt-online-schema-change,本文说明下另一种工具gh-ost的使用:不依赖于触发器,是因为他是通过模拟从库,在row binlog中获取增量变更,再异步应用到ghost表的。
1、下载安装地址:
https://github.com/github/gh-ost/tags
2、参数说明:gh-ost –help
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
3、使用说明:条件是操作的MySQL上需要的binlog模式是ROW。如果在一个从上测试也必须是ROW模式,还要开启log_slave_updates。根据上面的参数说明按照需求进行调整。
4、环境: 主库:192.168.1.7 从库:192.168.1.8
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表。
一. 单实例上DDL: 单个实例相当于主库,需要开启–allow-on-master参数和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直接在主上执行同步到从上,另一个连接到从库,在主库做迁移(只要保证从库的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、行数据在主库上读写
2、读取从库的二进制日志,将变更应用到主库
3、在从库收集表格式,字段&索引,行数等信息
4、在从库上读取内部的变更事件(如心跳事件)
5、在主库切换表
在执行DDL中,从库会执行一次stop/start slave,要是确定从的binlog是ROW的话可以添加参数:–assume-rbr。如果从库的binlog不是ROW,可以用参数–switch-to-rbr来转换成ROW,此时需要注意的是执行完毕之后,binlog模式不会被转换成原来的值。–assume-rbr和–switch-to-rbr参数不能一起使用。
三. 在从上进行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
参数–test-on-replica:在从库上测试gh-ost,包括在从库上数据迁移(migration),数据迁移完成后stop slave,原表和ghost表立刻交换而后立刻交换回来。继续保持stop slave,使你可以对比两张表。如果不想stop slave,则可以再添加参数:–test-on-replica-skip-replica-stop
上面三种是gh-ost操作模式,上面的操作中,到最后不会清理临时表,需要手动清理,再下次执行之前果然临时表还存在,则会执行失败,可以通过参数进行删除:
1、–initially-drop-ghost-table:gh-ost操作之前,检查并删除已经存在的ghost表。该参数不建议使用,请手动处理原来存在的ghost表。默认不启用该参数,gh-ost直接退出操作
2、–initially-drop-old-table:gh-ost操作之前,检查并删除已经存在的旧表。该参数不建议使用,请手动处理原来存在的ghost表。默认不启用该参数,gh-ost直接退出操作
3、–initially-drop-socket-file:gh-ost强制删除已经存在的socket文件。该参数不建议使用,可能会删除一个正在运行的gh-ost程序,导致DDL失败
4、–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
四.额外说明:终止、暂停、限速
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
① 标示文件终止运行:–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
结论:虽然gh-ost不需要触发器,对于主库的压力和性能影响也小很多,但是针对高并发的场景进行DDL效率还是比pt-osc低,所以还是需要在业务低峰的时候处理。
封装脚本: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)
#终止标志
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 (“33[0;32m%s33[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 (“33[0;31m%s33[0m” % “renamed columns’ data will be lost,pt-osc exit…”)
exit()
if table_count
ddl = ”’ ALTER TABLE %s %s ”’ %(options.tablename,DDL_CMD)
print (“33[0;36m%s33[0m” %ddl)
print (“33[0;32m%s33[0m” % “online ddl …”)
online_ddl(conn,ddl)
开发云主机域名 print (“33[0;32m%s33[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 (“33[0;31m%s33[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 (“33[0;31m%s33[0m” % “输入类型错误,退出…”)
exit()
print (“33[0;32m%s33[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 (“33[0;36m%s33[0m” %gh_command)

child,pid = run_cmd(gh_command)
print (“33[0;31mgh-ost’s PID:%s33[0m” %pid)
print (“33[0;33m创建:【touch %s】文件,暂停DDL …33[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 (“33[0;32m%s33[0m” % “清理完成 …”)
exit()
print (“33[0;32m%s33[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)
#终止标志
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=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 (“33[0;32m%s33[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 (“33[0;31m%s33[0m” % “renamed columns’ data will be lost,pt-osc exit…”)
exit()
if table_count
ddl = ”’ ALTER TABLE %s %s ”’ %(options.tablename,DDL_CMD)
print (“33[0;36m%s33[0m” %ddl)
print (“33[0;32m%s33[0m” % “online ddl …”)
online_ddl(conn,ddl)
print (“33[0;32m%s33[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 (“33[0;31m%s33[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 (“33[0;31m%s33[0m” % “输入类型错误,退出…”)
exit()
print (“33[0;32m%s33[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 (“33[0;36m%s33[0m” %gh_command)
child,pid = run_cmd(gh_command)
print (“33[0;31mgh-ost’s PID:%s33[0m” %pid)
print (“33[0;33m创建:【touch %s】文件,暂停DDL …33[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 (“33[0;32m%s33[0m” % “清理完成 …”)
exit()
print (“33[0;32m%s33[0m” % “清理完成 …”)
exit()
finally :
pass
运行:
python gh-ost.py -H192.168.1.7 -P3306 -Dyoon -Thank
总结:
gh-ost 放弃了触发器,使用 binlog 来同步。gh-ost 作为一个伪装的备库,可以从主库/备库上拉取 binlog,过滤之后重新应用到主库上去,相当于主库上的增量操作通过 binlog 又应用回主库本身,不过是应用在幽灵表上。
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,在备库上观察变更结果是否正确,再对主库操作,心里更有底。
参考文档:
https://github.com/wing324/helloworld_zh/blob/master/MySQL/gh-ost/GitHub在线DDL工具gh-ost安装文档.md
https://www.cnblogs.com/zhoujinyi/p/9187421.html

相关推荐: Mycat中间件实现Mysql主从读写分离

环境规划: Mycat下载地址:http://dl.mycat.io/1.6.7.3/20190828135747/Mycat-server-1.6.7.3-release-20190828135747-linux.tar.gz Mysql下载地址: http…

免责声明:本站发布的图片视频文字,以转载和分享为主,文章观点不代表本站立场,本站不承担相关法律责任;如果涉及侵权请联系邮箱:360163164@qq.com举报,并提供相关证据,经查实将立刻删除涉嫌侵权内容。

(0)
打赏 微信扫一扫 微信扫一扫
上一篇 06/05 22:00
下一篇 06/05 22:00

相关推荐