gh-ost 原理剖析


gh-ost 原理

一 簡介

上一篇文章介紹 gh-ost 參數和具體的使用方法,以及核心特性-可動態調整 暫停,動態修改參數等等。本文分幾部分從源碼方面解釋gh-ost的執行過程,數據遷移,切換細節設計。

二 原理

2.1 執行過程

本例基於在主庫上執行ddl 記錄的核心過程。核心代碼在

github.com/github/gh-ost/go/logic/migrator.go 的Migrate()

func (this *Migrator) Migrate() //Migrate executes the complete migration logic. This is the major gh-ost function.

1 檢查數據庫實例的基礎信息

a 測試db是否可連通,
b 權限驗證 
  show grants for current_user()
c 獲取binlog相關信息,包括row格式和修改binlog格式后的重啟replicate
  select @@global.log_bin, @@global.binlog_format
  select @@global.binlog_row_image
d 原表存儲引擎是否是innodb,檢查表相關的外鍵,是否有觸發器,行數預估等操作,需要注意的是行數預估有兩種方式  一個是通過explain 讀執行計划 另外一個是select count(*) from table ,遇到幾百G的大表,后者一定非常慢。

  explain select /* gh-ost */ * from `test`.`b` where 1=1

2 模擬slave,獲取當前的位點信息,創建binlog streamer監聽binlog

2019-09-08T22:01:20.944172+08:00	17760 Query	show /* gh-ost readCurrentBinlogCoordinates */ master status
2019-09-08T22:01:20.947238+08:00	17762 Connect	root@127.0.0.1 on  using TCP/IP
2019-09-08T22:01:20.947349+08:00	17762 Query	SHOW GLOBAL VARIABLES LIKE 'BINLOG_CHECKSUM'
2019-09-08T22:01:20.947909+08:00	17762 Query	SET @master_binlog_checksum='NONE'
2019-09-08T22:01:20.948065+08:00	17762 Binlog Dump	Log: 'mysql-bin.000005'  Pos: 795282

3 創建 日志記錄表 xx_ghc 和影子表 xx_gho 並且執行alter語句將影子表 變更為目標表結構。如下日志記錄了該過程,gh-ost會將核心步驟記錄到 _b_ghc 中。

2019-09-08T22:01:20.954866+08:00	17760 Query	create /* gh-ost */ table `test`.`_b_ghc` (
			id bigint auto_increment,
			last_update timestamp not null DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			hint varchar(64) charset ascii not null,
			value varchar(4096) charset ascii not null,
			primary key(id),
			unique key hint_uidx(hint)
		) auto_increment=256
2019-09-08T22:01:20.957550+08:00	17760 Query	create /* gh-ost */ table `test`.`_b_gho` like `test`.`b`
2019-09-08T22:01:20.960110+08:00	17760 Query	alter /* gh-ost */ table `test`.`_b_gho` engine=innodb
2019-09-08T22:01:20.966740+08:00	17760 Query 
   insert /* gh-ost */ into `test`.`_b_ghc`(id, hint, value)values (NULLIF(2, 0), 'state', 'GhostTableMigrated') on duplicate key update last_update=NOW(),value=VALUES(value)

4 insert into xx_gho select * from xx 拷貝數據

獲取當前的最大主鍵和最小主鍵 然后根據命令行傳參 chunk 獲取數據 insert到影子表里面

獲取最小主鍵 select `id` from `test`.`b` order by `id` asc limit 1;
獲取最大主鍵 soelect `id` from `test`.`b` order by `id` desc limit 1;
獲取第一個 chunk:
select  /* gh-ost `test`.`b` iteration:0 */ `id` from `test`.`b` where ((`id` > _binary'1') or ((`id` = _binary'1'))) and ((`id` < _binary'21') or ((`id` = _binary'21'))) order by `id` asc limit 1 offset 999;

循環插入到目標表:
insert /* gh-ost `test`.`b` */ ignore into `test`.`_b_gho` (`id`, `sid`, `name`, `score`, `x`) (select `id`, `sid`, `name`, `score`, `x` from `test`.`b` force index (`PRIMARY`)  where (((`id` > _binary'1') or ((`id` = _binary'1'))) and ((`id` < _binary'21') or ((`id` = _binary'21')))) lock in share mode;

循環到最大的id,之后依賴binlog 增量同步     

需要注意的是

rowcopy過程中是對原表加上 lock in share mode,防止數據在copy的過程中被修改。這點對后續理解整體的數據遷移非常重要。因為gh-ost在copy的過程中不會修改這部分數據記錄。對於解析binlog獲得的 INSERT ,UPDATE,DELETE事件我們只需要分析copy數據之前log before copy 和copy數據之后 log after copy。整體的數據遷移會在后面做詳細分析。

5 增量應用binlog遷移數據

核心代碼在 gh-ost/go/sql/builder.go 中,這里主要做DML轉換的解釋,當然還有其他函數做輔助工作,比如數據庫 ,表名校驗 以及語法完整性校驗。

解析到delete語句 對應轉換為delete語句

func BuildDMLDeleteQuery(databaseName, tableName string, tableColumns, uniqueKeyColumns *ColumnList, args []interface{}) (result string, uniqueKeyArgs []interface{}, err error) {
   ....省略代碼...
	result = fmt.Sprintf(`
			delete /* gh-ost %s.%s */
				from
					%s.%s
				where
					%s
		`, databaseName, tableName,
		databaseName, tableName,
		equalsComparison,
	)
	return result, uniqueKeyArgs, nil
}

解析到insert語句 對應轉換為replace into語句

func BuildDMLInsertQuery(databaseName, tableName string, tableColumns, sharedColumns, mappedSharedColumns *ColumnList, args []interface{}) (result string, sharedArgs []interface{}, err error) {
   ....省略代碼...
	result = fmt.Sprintf(`
			replace /* gh-ost %s.%s */ into
				%s.%s
					(%s)
				values
					(%s)
		`, databaseName, tableName,
		databaseName, tableName,
		strings.Join(mappedSharedColumnNames, ", "),
		strings.Join(preparedValues, ", "),
	)
	return result, sharedArgs, nil
}

解析到update語句 對應轉換為語句

func BuildDMLUpdateQuery(databaseName, tableName string, tableColumns, sharedColumns, mappedSharedColumns, uniqueKeyColumns *ColumnList, valueArgs, whereArgs []interface{}) (result string, sharedArgs, uniqueKeyArgs []interface{}, err error) {
   ....省略代碼...
	result = fmt.Sprintf(`
 			update /* gh-ost %s.%s */
 					%s.%s
				set
					%s
				where
 					%s
 		`, databaseName, tableName,
		databaseName, tableName,
		setClause,
		equalsComparison,
	)
	return result, sharedArgs, uniqueKeyArgs, nil
}

數據遷移的數據一致性分析

gh-ost 做ddl變更期間對原表和影子表的操作有三種:對原表的row copy (我們用A操作代替),業務對原表的DML操作(B),對影子表的apply binlog(C)。而且binlog是基於dml 操作產生的,因此對影子表的apply binlog 一定在 對原表的dml之后,共有如下幾種順序:

通過上面的幾種組合操作的分析,我們可以看到 數據最終是一致的。尤其是當copy 結束之后,只剩下apply binlog,情況更簡單。

6 copy完數據之后進行原始表和影子表cut-over 切換

gh-ost的切換是原子性切換,基本是通過兩個會話的操作來完成 。作者寫了三篇文章解釋cut-over操作的思路和切換算法。詳細的思路請移步到下面的鏈接。

http://code.openark.org/blog/mysql/solving-the-non-atomic-table-swap-take-iii-making-it-atomic

http://code.openark.org/blog/mysql/solving-the-non-atomic-table-swap-take-ii

http://code.openark.org/blog/mysql/solving-the-facebook-osc-non-atomic-table-swap-problem

這里將第三篇文章描述核心切換邏輯摘錄出來。其原理是基於MySQL 內部機制:被lock table 阻塞之后,執行rename的優先級高於dml,也即先執行rename table ,然后執行dml 。假設gh-ost操作的會話是c10 和c20 ,其他業務的dml請求的會話是c1-c9,c11-c19,c21-c29。

1 會話 c1..c9: 對b表正常執行DML操作。
2 會話 c10 : 創建_b_del 防止提前rename 表,導致數據丟失。
      create /* gh-ost */ table `test`.`_b_del` (
			id int auto_increment primary key
		) engine=InnoDB comment='ghost-cut-over-sentry'
		
3 會話 c10 執行LOCK TABLES b WRITE, `_b_del` WRITE。
4 會話c11-c19 新進來的dml或者select請求,但是會因為表b上有鎖而等待。
5 會話c20:設置鎖等待時間並執行rename
	set session lock_wait_timeout:=1
	rename /* gh-ost */ table `test`.`b` to `test`.`_b_20190908220120_del`, `test`.`_b_gho` to `test`.`b`
  c20 的操作因為c10鎖表而等待。
  
6 c21-c29 對於表 b 新進來的請求因為lock table和rename table 而等待。
7 會話c10 通過sql 檢查會話c20 在執行rename操作並且在等待mdl鎖。
select id
			from information_schema.processlist
			where
				id != connection_id()
				and 17765 in (0, id)
				and state like concat('%', 'metadata lock', '%')
				and info  like concat('%', 'rename', '%')

8 c10 基於步驟7 執行drop table `_b_del` ,刪除命令執行完,b表依然不能寫。所有的dml請求都被阻塞。

9 c10 執行UNLOCK TABLES; 此時c20的rename命令第一個被執行。而其他會話c1-c9,c11-c19,c21-c29的請求可以操作新的表b。

划重點點(敲黑板)

1 創建_b_del表是為了防止cut-over提前執行,導致數據丟失。

2 同一個會話先執行write lock之后還是可以drop表的。

3 無論rename table和dml操作誰先執行,被阻塞后rename table總是優先於dml被執行。

大家可以一邊自己執行gh-ost ,一邊開啟general log 查看具體的操作過程。

2019-09-08T22:01:24.086734	17765	create /* gh-ost */ table `test`.`_b_20190908220120_del` (
			id int auto_increment primary key
		) engine=InnoDB comment='ghost-cut-over-sentry'
2019-09-08T22:01:24.091869	17760 Query	lock /* gh-ost */ tables `test`.`b` write, `test`.`_b_20190908220120_del` write
2019-09-08T22:01:24.188687	17765	START TRANSACTION
2019-09-08T22:01:24.188817	17765  	select connection_id()
2019-09-08T22:01:24.188931	17765  	set session lock_wait_timeout:=1
2019-09-08T22:01:24.189046	17765  	rename /* gh-ost */ table `test`.`b` to `test`.`_b_20190908220120_del`, `test`.`_b_gho` to `test`.`b`
2019-09-08T22:01:24.192293+08:00	17766 Connect	root@127.0.0.1 on test using TCP/IP
2019-09-08T22:01:24.192409	17766  	SELECT @@max_allowed_packet
2019-09-08T22:01:24.192487	17766  	SET autocommit=true
2019-09-08T22:01:24.192578	17766  	SET NAMES utf8mb4
2019-09-08T22:01:24.192693	17766  	select id
			from information_schema.processlist
			where
				id != connection_id()
				and 17765 in (0, id)
				and state like concat('%', 'metadata lock', '%')
				and info  like concat('%', 'rename', '%')
2019-09-08T22:01:24.193050	17766 Query	select is_used_lock('gh-ost.17760.lock')
2019-09-08T22:01:24.193194	17760 Query	drop /* gh-ost */ table if exists `test`.`_b_20190908220120_del`
2019-09-08T22:01:24.194858	17760 Query	unlock tables
2019-09-08T22:01:24.194965	17760 Query	ROLLBACK
2019-09-08T22:01:24.197563	17765 Query	ROLLBACK
2019-09-08T22:01:24.197594	17766 Query	show /* gh-ost */ table status from `test` like '_b_20190908220120_del'
2019-09-08T22:01:24.198082	17766 Quit
2019-09-08T22:01:24.298382	17760 Query	drop /* gh-ost */ table if exists `test`.`_b_ghc`

如果cut-over過程的各個環節執行失敗會發生什么? 其實除了安全,什么都不會發生。

如果c10的create `_b_del` 失敗,gh-ost 程序退出。

如果c10的加鎖語句失敗,gh-ost 程序退出,因為表還未被鎖定,dml請求可以正常進行。

如果c10在c20執行rename之前出現異常
 
 A. c10持有的鎖被釋放,查詢c1-c9,c11-c19的請求可以立即在b執行。
 B. 因為`_b_del`表存在,c20的rename table b to  `_b_del`會失敗。
 C. 整個操作都失敗了,但沒有什么可怕的事情發生,有些查詢被阻止了一段時間,我們需要重試。

如果c10在c20執行rename被阻塞時失敗退出,與上述類似,鎖釋放,則c20執行rename操作因為——b_old表存在而失敗,所有請求恢復正常。

如果c20異常失敗,gh-ost會捕獲不到rename,會話c10繼續運行,釋放lock,所有請求恢復正常。

如果c10和c20都失敗了,沒問題:lock被清除,rename鎖被清除。 c1-c9,c11-c19,c21-c29可以在b上正常執行。

整個過程對應用程序的影響

應用程序對表的寫操作被阻止,直到交換影子表成功或直到操作失敗。如果成功,則應用程序繼續在新表上進行操作。如果切換失敗,應用程序繼續繼續在原表上進行操作。

對復制的影響

slave因為binlog文件中不會復制lock語句,只能應用rename 語句進行原子操作,對復制無損。

7 處理收尾工作

最后一部分操作其實和具體參數有一定關系。最重要必不可少的是

關閉binlogsyncer連接

至於刪除中間表 ,其實和參數有關 --initially-drop-ghost-table --initially-drop-old-table

三 小結

縱觀gh-ost的執行過程,查看源碼算法設計, 尤其是cut-over設計思路之精妙,原子操作,任何異常都不會對業務有嚴重影響。歡迎已經使用過的朋友分享各自遇到的問題,也歡迎還未使用過該工具的朋友大膽嘗試。

參考文章

https://www.cnblogs.com/mysql-dba/p/9901589.html


本公眾號長期關注於數據庫技術以及性能優化,故障案例分析,數據庫運維技術知識分享,個人成長和自我管理等主題,歡迎掃碼關注。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM