Skip to content

Commit 42fa64e

Browse files
author
Shlomi Noach
authored
Merge branch 'master' into test-latin1text
2 parents a954887 + bdd2897 commit 42fa64e

File tree

42 files changed

+369
-121
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+369
-121
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ But then a rare genetic mutation happened, and the `c` transformed into `t`. And
8484

8585
We develop `gh-ost` at GitHub and for the community. We may have different priorities than others. From time to time we may suggest a contribution that is not on our immediate roadmap but which may appeal to others.
8686

87-
Please see [Coding gh-ost](https://github.com/github/gh-ost/blob/develdocs/doc/coding-ghost.md) for a guide to getting started developing with gh-ost.
87+
Please see [Coding gh-ost](doc/coding-ghost.md) for a guide to getting started developing with gh-ost.
8888

8989
## Download/binaries/source
9090

RELEASE_VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1.0.36
1+
1.0.42

doc/cheatsheet.md

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
# Cheatsheet
22

3+
### Operation modes
4+
35
![operation modes](images/gh-ost-operation-modes.png)
46

57

68
`gh-ost` operates by connecting to potentially multiple servers, as well as imposing itself as a replica in order to streamline binary log events directly from one of those servers. There are various operation modes, which depend on your setup, configuration, and where you want to run the migration.
79

8-
### a. Connect to replica, migrate on master
10+
#### a. Connect to replica, migrate on master
911

1012
This is the mode `gh-ost` expects by default. `gh-ost` will investigate the replica, crawl up to find the topology's master, and will hook onto it as well. Migration will:
1113

@@ -47,7 +49,7 @@ gh-ost \
4749
With `--execute`, migration actually copies data and flips tables. Without it this is a `noop` run.
4850

4951

50-
### b. Connect to master
52+
#### b. Connect to master
5153

5254
If you don't have replicas, or do not wish to use them, you are still able to operate directly on the master. `gh-ost` will do all operations directly on the master. You may still ask it to be considerate of replication lag.
5355

@@ -80,7 +82,7 @@ gh-ost \
8082
[--execute]
8183
```
8284

83-
### c. Migrate/test on replica
85+
#### c. Migrate/test on replica
8486

8587
This will perform a migration on the replica. `gh-ost` will briefly connect to the master but will thereafter perform all operations on the replica without modifying anything on the master.
8688
Throughout the operation, `gh-ost` will throttle such that the replica is up to date.
@@ -146,7 +148,7 @@ gh-ost --allow-master-master --assume-master-host=a.specific.master.com
146148

147149
Topologies using _tungsten replicator_ are peculiar in that the participating servers are not actually aware they are replicating. The _tungsten replicator_ looks just like another app issuing queries on those hosts. `gh-ost` is unable to identify that a server participates in a _tungsten_ topology.
148150

149-
If you choose to migrate directly on master (see above), there's nothing special you need to do.
151+
If you choose to migrate directly on master (see above), there's nothing special you need to do.
150152

151153
If you choose to migrate via replica, then you need to make sure Tungsten is configured with log-slave-updates parameter (note this is different from MySQL's own log-slave-updates parameter), otherwise changes will not be in the replica's binlog, causing data to be corrupted after table swap. You must also supply the identity of the master, and indicate this is a tungsten setup, as follows:
152154

@@ -155,3 +157,15 @@ gh-ost --tungsten --assume-master-host=the.topology.master.com
155157
```
156158

157159
Also note that `--switch-to-rbr` does not work for a Tungsten setup as the replication process is external, so you need to make sure `binlog_format` is set to ROW before Tungsten Replicator connects to the server and starts applying events from the master.
160+
161+
### Concurrent migrations
162+
163+
It is possible to run concurrent `gh-ost` migrations.
164+
165+
- Never on the exact same table.
166+
- If running on different replicas, (e.g. `table1` on `replica1` and `table2` on `replica2`) then no further configuration required.
167+
- If running from same server (binaries run on same server, regardless of which replica/replicas are used):
168+
- Make sure not to specify same `-serve-socket-file` (or let `gh-ost` pick one for you).
169+
- You may choose to use same `-throttle-flag-file` (preferably use `-throttle-additional-flag-file`, this is exactly the reason there's two, this latter file is for sharing).
170+
- You may choose to use same `-panic-flag-file`. This all depends on your flow and how you'd like to control your migrations.
171+
- If using same inspected box (either master or replica, `--host=everyone.uses.this.host`) then for each `gh-ost` process you must also provide a different, unique `--replica-server-id`. Optionally use process ID (`$$` in shell) ; but it's on you to choose a number that does not collide with another `gh-ost` or another running replica.

doc/questions.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,8 @@ At this time there is no equivalent to `ALTER IGNORE`, where duplicates are impl
2323
2424
It is therefore unlikely that `gh-ost` will support this behavior.
2525

26+
### Run concurrent migrations?
27+
28+
Yes. TL;DR if running all on same replica/master, make sure to provide `--replica-server-id`. [Read more](cheatsheet.md#concurrent-migrations)
29+
2630
# Why

doc/requirements-and-limitations.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ The `SUPER` privilege is required for `STOP SLAVE`, `START SLAVE` operations. Th
2828

2929
- MySQL 5.7 generated columns are not supported. They may be supported in the future.
3030

31-
- MySQL 5.7 `JSON` columns are not supported. They are likely to be supported shortly.
31+
- MySQL 5.7 `POINT` column type is not supported.
32+
33+
- MySQL 5.7 `JSON` columns are supported but not as part of `PRIMARY KEY`
3234

3335
- The two _before_ & _after_ tables must share a `PRIMARY KEY` or other `UNIQUE KEY`. This key will be used by `gh-ost` to iterate through the table rows when copying. [Read more](shared-key.md)
3436
- The migration key must not include columns with NULL values. This means either:

go/base/context.go

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ type MigrationContext struct {
192192
Iteration int64
193193
MigrationIterationRangeMinValues *sql.ColumnValues
194194
MigrationIterationRangeMaxValues *sql.ColumnValues
195+
ForceTmpTableName string
195196

196197
recentBinlogCoordinates mysql.BinlogCoordinates
197198

@@ -253,25 +254,42 @@ func getSafeTableName(baseName string, suffix string) string {
253254
}
254255

255256
// GetGhostTableName generates the name of ghost table, based on original table name
257+
// or a given table name
256258
func (this *MigrationContext) GetGhostTableName() string {
257-
return getSafeTableName(this.OriginalTableName, "gho")
259+
if this.ForceTmpTableName != "" {
260+
return getSafeTableName(this.ForceTmpTableName, "gho")
261+
} else {
262+
return getSafeTableName(this.OriginalTableName, "gho")
263+
}
258264
}
259265

260266
// GetOldTableName generates the name of the "old" table, into which the original table is renamed.
261267
func (this *MigrationContext) GetOldTableName() string {
268+
var tableName string
269+
if this.ForceTmpTableName != "" {
270+
tableName = this.ForceTmpTableName
271+
} else {
272+
tableName = this.OriginalTableName
273+
}
274+
262275
if this.TimestampOldTable {
263276
t := this.StartTime
264277
timestamp := fmt.Sprintf("%d%02d%02d%02d%02d%02d",
265278
t.Year(), t.Month(), t.Day(),
266279
t.Hour(), t.Minute(), t.Second())
267-
return getSafeTableName(this.OriginalTableName, fmt.Sprintf("%s_del", timestamp))
280+
return getSafeTableName(tableName, fmt.Sprintf("%s_del", timestamp))
268281
}
269-
return getSafeTableName(this.OriginalTableName, "del")
282+
return getSafeTableName(tableName, "del")
270283
}
271284

272285
// GetChangelogTableName generates the name of changelog table, based on original table name
286+
// or a given table name.
273287
func (this *MigrationContext) GetChangelogTableName() string {
274-
return getSafeTableName(this.OriginalTableName, "ghc")
288+
if this.ForceTmpTableName != "" {
289+
return getSafeTableName(this.ForceTmpTableName, "ghc")
290+
} else {
291+
return getSafeTableName(this.OriginalTableName, "ghc")
292+
}
275293
}
276294

277295
// GetVoluntaryLockName returns a name of a voluntary lock to be used throughout
@@ -682,7 +700,7 @@ func (this *MigrationContext) ReadConfigFile() error {
682700
gcfg.RelaxedParserMode = true
683701
gcfgscanner.RelaxedScannerMode = true
684702
if err := gcfg.ReadFileInto(&this.config, this.ConfigFile); err != nil {
685-
return err
703+
return fmt.Errorf("Error reading config file %s. Details: %s", this.ConfigFile, err.Error())
686704
}
687705

688706
// We accept user & password in the form "${SOME_ENV_VARIABLE}" in which case we pull

go/base/context_test.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,30 +18,41 @@ func init() {
1818
}
1919

2020
func TestGetTableNames(t *testing.T) {
21-
context = newMigrationContext()
2221
{
22+
context = newMigrationContext()
2323
context.OriginalTableName = "some_table"
2424
test.S(t).ExpectEquals(context.GetOldTableName(), "_some_table_del")
2525
test.S(t).ExpectEquals(context.GetGhostTableName(), "_some_table_gho")
2626
test.S(t).ExpectEquals(context.GetChangelogTableName(), "_some_table_ghc")
2727
}
2828
{
29+
context = newMigrationContext()
2930
context.OriginalTableName = "a123456789012345678901234567890123456789012345678901234567890"
3031
test.S(t).ExpectEquals(context.GetOldTableName(), "_a1234567890123456789012345678901234567890123456789012345678_del")
3132
test.S(t).ExpectEquals(context.GetGhostTableName(), "_a1234567890123456789012345678901234567890123456789012345678_gho")
3233
test.S(t).ExpectEquals(context.GetChangelogTableName(), "_a1234567890123456789012345678901234567890123456789012345678_ghc")
3334
}
3435
{
36+
context = newMigrationContext()
3537
context.OriginalTableName = "a123456789012345678901234567890123456789012345678901234567890123"
3638
oldTableName := context.GetOldTableName()
3739
test.S(t).ExpectEquals(oldTableName, "_a1234567890123456789012345678901234567890123456789012345678_del")
3840
}
3941
{
42+
context = newMigrationContext()
4043
context.OriginalTableName = "a123456789012345678901234567890123456789012345678901234567890123"
4144
context.TimestampOldTable = true
4245
longForm := "Jan 2, 2006 at 3:04pm (MST)"
4346
context.StartTime, _ = time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
4447
oldTableName := context.GetOldTableName()
4548
test.S(t).ExpectEquals(oldTableName, "_a1234567890123456789012345678901234567890123_20130203195400_del")
4649
}
50+
{
51+
context = newMigrationContext()
52+
context.OriginalTableName = "foo_bar_baz"
53+
context.ForceTmpTableName = "tmp"
54+
test.S(t).ExpectEquals(context.GetOldTableName(), "_tmp_del")
55+
test.S(t).ExpectEquals(context.GetGhostTableName(), "_tmp_gho")
56+
test.S(t).ExpectEquals(context.GetChangelogTableName(), "_tmp_ghc")
57+
}
4758
}

go/base/utils.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ import (
1111
"regexp"
1212
"strings"
1313
"time"
14+
15+
gosql "database/sql"
16+
"github.com/github/gh-ost/go/mysql"
17+
"github.com/outbrain/golib/log"
1418
)
1519

1620
var (
@@ -50,3 +54,25 @@ func StringContainsAll(s string, substrings ...string) bool {
5054
}
5155
return nonEmptyStringsFound
5256
}
57+
58+
func ValidateConnection(db *gosql.DB, connectionConfig *mysql.ConnectionConfig) (string, error) {
59+
query := `select @@global.port, @@global.version`
60+
var port, extraPort int
61+
var version string
62+
if err := db.QueryRow(query).Scan(&port, &version); err != nil {
63+
return "", err
64+
}
65+
extraPortQuery := `select @@global.extra_port`
66+
if err := db.QueryRow(extraPortQuery).Scan(&extraPort); err != nil {
67+
// swallow this error. not all servers support extra_port
68+
}
69+
70+
if connectionConfig.Key.Port == port || (extraPort > 0 && connectionConfig.Key.Port == extraPort) {
71+
log.Infof("connection validated on %+v", connectionConfig.Key)
72+
return version, nil
73+
} else if extraPort == 0 {
74+
return "", fmt.Errorf("Unexpected database port reported: %+v", port)
75+
} else {
76+
return "", fmt.Errorf("Unexpected database port reported: %+v / extra_port: %+v", port, extraPort)
77+
}
78+
}

go/cmd/gh-ost/main.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ func main() {
6363
flag.BoolVar(&migrationContext.AllowedRunningOnMaster, "allow-on-master", false, "allow this migration to run directly on master. Preferably it would run on a replica")
6464
flag.BoolVar(&migrationContext.AllowedMasterMaster, "allow-master-master", false, "explicitly allow running in a master-master setup")
6565
flag.BoolVar(&migrationContext.NullableUniqueKeyAllowed, "allow-nullable-unique-key", false, "allow gh-ost to migrate based on a unique key with nullable columns. As long as no NULL values exist, this should be OK. If NULL values exist in chosen key, data may be corrupted. Use at your own risk!")
66-
flag.BoolVar(&migrationContext.ApproveRenamedColumns, "approve-renamed-columns", false, "in case your `ALTER` statement renames columns, gh-ost will note that and offer its interpretation of the rename. By default gh-ost does not proceed to execute. This flag approves that gh-ost's interpretation si correct")
66+
flag.BoolVar(&migrationContext.ApproveRenamedColumns, "approve-renamed-columns", false, "in case your `ALTER` statement renames columns, gh-ost will note that and offer its interpretation of the rename. By default gh-ost does not proceed to execute. This flag approves that gh-ost's interpretation is correct")
6767
flag.BoolVar(&migrationContext.SkipRenamedColumns, "skip-renamed-columns", false, "in case your `ALTER` statement renames columns, gh-ost will note that and offer its interpretation of the rename. By default gh-ost does not proceed to execute. This flag tells gh-ost to skip the renamed columns, i.e. to treat what gh-ost thinks are renamed columns as unrelated columns. NOTE: you may lose column data")
6868
flag.BoolVar(&migrationContext.IsTungsten, "tungsten", false, "explicitly let gh-ost know that you are running on a tungsten-replication based topology (you are likely to also provide --assume-master-host)")
6969
flag.BoolVar(&migrationContext.DiscardForeignKeys, "discard-foreign-keys", false, "DANGER! This flag will migrate a table that has foreign keys and will NOT create foreign keys on the ghost table, thus your altered table will have NO foreign keys. This is useful for intentional dropping of foreign keys")
@@ -120,6 +120,7 @@ func main() {
120120
help := flag.Bool("help", false, "Display usage")
121121
version := flag.Bool("version", false, "Print version & exit")
122122
checkFlag := flag.Bool("check-flag", false, "Check if another flag exists/supported. This allows for cross-version scripting. Exits with 0 when all additional provided flags exist, nonzero otherwise. You must provide (dummy) values for flags that require a value. Example: gh-ost --check-flag --cut-over-lock-timeout-seconds --nice-ratio 0")
123+
flag.StringVar(&migrationContext.ForceTmpTableName, "force-table-names", "", "table name prefix to be used on the temporary tables")
123124

124125
flag.Parse()
125126

go/logic/applier.go

Lines changed: 37 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,14 @@ func (this *Applier) InitDBConnections() (err error) {
5353
return err
5454
}
5555
this.singletonDB.SetMaxOpenConns(1)
56-
if err := this.validateConnection(this.db); err != nil {
56+
version, err := base.ValidateConnection(this.db, this.connectionConfig)
57+
if err != nil {
5758
return err
5859
}
59-
if err := this.validateConnection(this.singletonDB); err != nil {
60+
if _, err := base.ValidateConnection(this.singletonDB, this.connectionConfig); err != nil {
6061
return err
6162
}
63+
this.migrationContext.ApplierMySQLVersion = version
6264
if err := this.validateAndReadTimeZone(); err != nil {
6365
return err
6466
}
@@ -74,20 +76,6 @@ func (this *Applier) InitDBConnections() (err error) {
7476
return nil
7577
}
7678

77-
// validateConnection issues a simple can-connect to MySQL
78-
func (this *Applier) validateConnection(db *gosql.DB) error {
79-
query := `select @@global.port, @@global.version`
80-
var port int
81-
if err := db.QueryRow(query).Scan(&port, &this.migrationContext.ApplierMySQLVersion); err != nil {
82-
return err
83-
}
84-
if port != this.connectionConfig.Key.Port {
85-
return fmt.Errorf("Unexpected database port reported: %+v", port)
86-
}
87-
log.Infof("connection validated on %+v", this.connectionConfig.Key)
88-
return nil
89-
}
90-
9179
// validateAndReadTimeZone potentially reads server time-zone
9280
func (this *Applier) validateAndReadTimeZone() error {
9381
query := `select @@global.time_zone`
@@ -200,7 +188,7 @@ func (this *Applier) CreateChangelogTable() error {
200188
id bigint auto_increment,
201189
last_update timestamp not null DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
202190
hint varchar(64) charset ascii not null,
203-
value varchar(255) charset ascii not null,
191+
value varchar(4096) charset ascii not null,
204192
primary key(id),
205193
unique key hint_uidx(hint)
206194
) auto_increment=256
@@ -398,35 +386,41 @@ func (this *Applier) CalculateNextIterationRangeEndValues() (hasFurtherRange boo
398386
if this.migrationContext.MigrationIterationRangeMinValues == nil {
399387
this.migrationContext.MigrationIterationRangeMinValues = this.migrationContext.MigrationRangeMinValues
400388
}
401-
query, explodedArgs, err := sql.BuildUniqueKeyRangeEndPreparedQuery(
402-
this.migrationContext.DatabaseName,
403-
this.migrationContext.OriginalTableName,
404-
&this.migrationContext.UniqueKey.Columns,
405-
this.migrationContext.MigrationIterationRangeMinValues.AbstractValues(),
406-
this.migrationContext.MigrationRangeMaxValues.AbstractValues(),
407-
atomic.LoadInt64(&this.migrationContext.ChunkSize),
408-
this.migrationContext.GetIteration() == 0,
409-
fmt.Sprintf("iteration:%d", this.migrationContext.GetIteration()),
410-
)
411-
if err != nil {
412-
return hasFurtherRange, err
413-
}
414-
rows, err := this.db.Query(query, explodedArgs...)
415-
if err != nil {
416-
return hasFurtherRange, err
417-
}
418-
iterationRangeMaxValues := sql.NewColumnValues(this.migrationContext.UniqueKey.Len())
419-
for rows.Next() {
420-
if err = rows.Scan(iterationRangeMaxValues.ValuesPointers...); err != nil {
389+
for i := 0; i < 2; i++ {
390+
buildFunc := sql.BuildUniqueKeyRangeEndPreparedQueryViaOffset
391+
if i == 1 {
392+
buildFunc = sql.BuildUniqueKeyRangeEndPreparedQueryViaTemptable
393+
}
394+
query, explodedArgs, err := buildFunc(
395+
this.migrationContext.DatabaseName,
396+
this.migrationContext.OriginalTableName,
397+
&this.migrationContext.UniqueKey.Columns,
398+
this.migrationContext.MigrationIterationRangeMinValues.AbstractValues(),
399+
this.migrationContext.MigrationRangeMaxValues.AbstractValues(),
400+
atomic.LoadInt64(&this.migrationContext.ChunkSize),
401+
this.migrationContext.GetIteration() == 0,
402+
fmt.Sprintf("iteration:%d", this.migrationContext.GetIteration()),
403+
)
404+
if err != nil {
421405
return hasFurtherRange, err
422406
}
423-
hasFurtherRange = true
424-
}
425-
if !hasFurtherRange {
426-
log.Debugf("Iteration complete: no further range to iterate")
427-
return hasFurtherRange, nil
407+
rows, err := this.db.Query(query, explodedArgs...)
408+
if err != nil {
409+
return hasFurtherRange, err
410+
}
411+
iterationRangeMaxValues := sql.NewColumnValues(this.migrationContext.UniqueKey.Len())
412+
for rows.Next() {
413+
if err = rows.Scan(iterationRangeMaxValues.ValuesPointers...); err != nil {
414+
return hasFurtherRange, err
415+
}
416+
hasFurtherRange = true
417+
}
418+
if hasFurtherRange {
419+
this.migrationContext.MigrationIterationRangeMaxValues = iterationRangeMaxValues
420+
return hasFurtherRange, nil
421+
}
428422
}
429-
this.migrationContext.MigrationIterationRangeMaxValues = iterationRangeMaxValues
423+
log.Debugf("Iteration complete: no further range to iterate")
430424
return hasFurtherRange, nil
431425
}
432426

0 commit comments

Comments
 (0)