Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: ghost (#9012)
p0ny598ea0b0744d
diff --git a/backend/component/ghost/config.go b/backend/component/ghost/config.gonew file mode 100644index 0000000000..a111931fa3--- /dev/null+++ b/backend/component/ghost/config.go@@ -0,0 +1,180 @@+package ghost++import (+ "fmt"+ "strconv"+ "strings"++ "github.com/github/gh-ost/go/base"+ ghostsql "github.com/github/gh-ost/go/sql"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/store"+)++// Config is the configuration for gh-ost migration.+type Config struct {+ // serverID should be unique+ ServerID uint+ Host string+ Port string+ User string+ Password string+ Database string+ Table string+ AlterStatement string+ SocketFilename string+ PostponeFlagFilename string+ Noop bool++ // vendor related+ IsAWS bool+}++// getGhostConfig returns a gh-ost configuration for migration.+func getGhostConfig(taskID int, database *store.DatabaseMessage, dataSource *store.DataSourceMessage, secret string, instanceUsers []*store.InstanceUserMessage, tableName string, statement string, noop bool, serverIDOffset uint) (Config, error) {+ var isAWS bool+ for _, user := range instanceUsers {+ if user.Name == "'rdsadmin'@'localhost'" && strings.Contains(user.Grant, "SUPER") {+ isAWS = true+ break+ }+ }+ password, err := common.Unobfuscate(dataSource.ObfuscatedPassword, secret)+ if err != nil {+ return Config{}, err+ }+ return Config{+ Host: dataSource.Host,+ Port: dataSource.Port,+ User: dataSource.Username,+ Password: password,+ Database: database.DatabaseName,+ Table: tableName,+ AlterStatement: statement,+ SocketFilename: getSocketFilename(taskID, database.UID, database.DatabaseName, tableName),+ PostponeFlagFilename: GetPostponeFlagFilename(taskID, database.UID, database.DatabaseName, tableName),+ Noop: noop,+ // On the source and each replica, you must set the server_id system variable to establish a unique replication ID. For each server, you should pick a unique positive integer in the range from 1 to 2^32 − 1, and each ID must be different from every other ID in use by any other source or replica in the replication topology. Example: server-id=3.+ // https://dev.mysql.com/doc/refman/5.7/en/replication-options-source.html+ // Here we use serverID = offset + task.ID to avoid potential conflicts.+ ServerID: serverIDOffset + uint(taskID),+ // https://github.com/github/gh-ost/blob/master/doc/rds.md+ IsAWS: isAWS,+ }, nil+}++func getSocketFilename(taskID int, databaseID int, databaseName string, tableName string) string {+ return fmt.Sprintf("/tmp/gh-ost.%v.%v.%v.%v.sock", taskID, databaseID, databaseName, tableName)+}++// GetPostponeFlagFilename gets the postpone flag filename for gh-ost.+func GetPostponeFlagFilename(taskID int, databaseID int, databaseName string, tableName string) string {+ return fmt.Sprintf("/tmp/gh-ost.%v.%v.%v.%v.postponeFlag", taskID, databaseID, databaseName, tableName)+}++// NewMigrationContext is the context for gh-ost migration.+func NewMigrationContext(taskID int, database *store.DatabaseMessage, dataSource *store.DataSourceMessage, secret string, instanceUsers []*store.InstanceUserMessage, tableName string, statement string, noop bool, serverIDOffset uint) (*base.MigrationContext, error) {+ config, err := getGhostConfig(taskID, database, dataSource, secret, instanceUsers, tableName, statement, noop, serverIDOffset)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get ghost config")+ }++ const (+ allowedRunningOnMaster = true+ concurrentCountTableRows = true+ timestampAllTable = true+ hooksStatusIntervalSec = 60+ heartbeatIntervalMilliseconds = 100+ niceRatio = 0+ chunkSize = 1000+ dmlBatchSize = 10+ maxLagMillisecondsThrottleThreshold = 1500+ defaultNumRetries = 60+ cutoverLockTimeoutSeconds = 60+ exponentialBackoffMaxInterval = 64+ throttleHTTPIntervalMillis = 100+ throttleHTTPTimeoutMillis = 1000+ )+ statement = strings.Join(strings.Fields(config.AlterStatement), " ")+ migrationContext := base.NewMigrationContext()+ migrationContext.InspectorConnectionConfig.Key.Hostname = config.Host+ port := 3306+ if config.Port != "" {+ configPort, err := strconv.Atoi(config.Port)+ if err != nil {+ return nil, errors.Wrap(err, "failed to convert port from string to int")+ }+ port = configPort+ }+ migrationContext.InspectorConnectionConfig.Key.Port = port+ migrationContext.CliUser = config.User+ migrationContext.CliPassword = config.Password+ migrationContext.DatabaseName = config.Database+ migrationContext.OriginalTableName = config.Table+ migrationContext.AlterStatement = statement+ migrationContext.Noop = config.Noop+ migrationContext.ReplicaServerId = config.ServerID+ if config.IsAWS {+ migrationContext.AssumeRBR = true+ }+ // set defaults+ if err := migrationContext.SetConnectionConfig(""); err != nil {+ return nil, err+ }+ migrationContext.AllowedRunningOnMaster = allowedRunningOnMaster+ migrationContext.ConcurrentCountTableRows = concurrentCountTableRows+ migrationContext.HooksStatusIntervalSec = hooksStatusIntervalSec+ migrationContext.CutOverType = base.CutOverAtomic+ migrationContext.ThrottleHTTPIntervalMillis = throttleHTTPIntervalMillis+ migrationContext.ThrottleHTTPTimeoutMillis = throttleHTTPTimeoutMillis++ if migrationContext.AlterStatement == "" {+ return nil, errors.Errorf("alterStatement must be provided and must not be empty")+ }+ parser := ghostsql.NewParserFromAlterStatement(migrationContext.AlterStatement)+ migrationContext.AlterStatementOptions = parser.GetAlterStatementOptions()++ if migrationContext.DatabaseName == "" {+ if !parser.HasExplicitSchema() {+ return nil, errors.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")+ }+ migrationContext.DatabaseName = parser.GetExplicitSchema()+ }+ if migrationContext.OriginalTableName == "" {+ if !parser.HasExplicitTable() {+ return nil, errors.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")+ }+ migrationContext.OriginalTableName = parser.GetExplicitTable()+ }+ migrationContext.ServeSocketFile = config.SocketFilename+ migrationContext.PostponeCutOverFlagFile = config.PostponeFlagFilename+ migrationContext.TimestampAllTable = timestampAllTable+ migrationContext.SetHeartbeatIntervalMilliseconds(heartbeatIntervalMilliseconds)+ migrationContext.SetNiceRatio(niceRatio)+ migrationContext.SetChunkSize(chunkSize)+ migrationContext.SetDMLBatchSize(dmlBatchSize)+ migrationContext.SetMaxLagMillisecondsThrottleThreshold(maxLagMillisecondsThrottleThreshold)+ migrationContext.SetDefaultNumRetries(defaultNumRetries)+ migrationContext.ApplyCredentials()+ if err := migrationContext.SetCutOverLockTimeoutSeconds(cutoverLockTimeoutSeconds); err != nil {+ return nil, err+ }+ if err := migrationContext.SetExponentialBackoffMaxInterval(exponentialBackoffMaxInterval); err != nil {+ return nil, err+ }+ return migrationContext, nil+}++// GetTableNameFromStatement gets the table name from statement for gh-ost.+func GetTableNameFromStatement(statement string) (string, error) {+ // Trim the statement for the parser.+ // This in effect removes all leading and trailing spaces, substitute multiple spaces with one.+ statement = strings.Join(strings.Fields(statement), " ")+ parser := ghostsql.NewParserFromAlterStatement(statement)+ if !parser.HasExplicitTable() {+ return "", errors.Errorf("failed to parse table name from statement, statement: %v", statement)+ }+ return parser.GetExplicitTable(), nil+}diff --git a/backend/runner/plancheck/ghost_sync_executor.go b/backend/runner/plancheck/ghost_sync_executor.goindex 5b4c56732e..aac3da790a 100644--- a/backend/runner/plancheck/ghost_sync_executor.go+++ b/backend/runner/plancheck/ghost_sync_executor.go@@ -8,6 +8,7 @@ import ("github.com/pkg/errors""github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/component/ghost"api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/utils"@@ -101,17 +102,12 @@ func (e *GhostSyncExecutor) Run(ctx context.Context, config *storepb.PlanCheckRu// To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.renderedStatement := utils.RenderStatement(statement, materials)- tableName, err := utils.GetTableNameFromStatement(renderedStatement)+ tableName, err := ghost.GetTableNameFromStatement(renderedStatement)if err != nil {return nil, common.Wrapf(err, common.Internal, "failed to parse table name from statement, statement: %v", statement)}- ghostConfig, err := utils.GetGhostConfig(rand.Intn(10000000), database, adminDataSource, e.secret, instanceUsers, tableName, renderedStatement, true, 20000000)- if err != nil {- return nil, err- }-- migrationContext, err := utils.NewMigrationContext(ghostConfig)+ migrationContext, err := ghost.NewMigrationContext(rand.Intn(10000000), database, adminDataSource, e.secret, instanceUsers, tableName, renderedStatement, true, 20000000)if err != nil {return nil, common.Wrapf(err, common.Internal, "failed to create migration context")}diff --git a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go b/backend/runner/taskrun/schema_update_ghost_cutover_executor.goindex 69024a5e40..266c4e6a35 100644--- a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go+++ b/backend/runner/taskrun/schema_update_ghost_cutover_executor.go@@ -17,6 +17,7 @@ import ("github.com/bytebase/bytebase/backend/component/activity""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/component/dbfactory"+ "github.com/bytebase/bytebase/backend/component/ghost""github.com/bytebase/bytebase/backend/component/state"enterprise "github.com/bytebase/bytebase/backend/enterprise/api"api "github.com/bytebase/bytebase/backend/legacyapi"@@ -92,12 +93,12 @@ func (e *SchemaUpdateGhostCutoverExecutor) RunOnce(ctx context.Context, _ contex// To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.renderedStatement := utils.RenderStatement(statement, materials)- tableName, err := utils.GetTableNameFromStatement(renderedStatement)+ tableName, err := ghost.GetTableNameFromStatement(renderedStatement)if err != nil {return true, nil, common.Wrapf(err, common.Internal, "failed to parse table name from statement, statement: %v", statement)}- postponeFilename := utils.GetPostponeFlagFilename(syncTaskID, database.UID, database.DatabaseName, tableName)+ postponeFilename := ghost.GetPostponeFlagFilename(syncTaskID, database.UID, database.DatabaseName, tableName)value, ok := e.stateCfg.GhostTaskState.Load(syncTaskID)if !ok {diff --git a/backend/runner/taskrun/schema_update_ghost_sync_executor.go b/backend/runner/taskrun/schema_update_ghost_sync_executor.goindex 386409ed6e..a67df3313e 100644--- a/backend/runner/taskrun/schema_update_ghost_sync_executor.go+++ b/backend/runner/taskrun/schema_update_ghost_sync_executor.go@@ -14,6 +14,7 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"+ "github.com/bytebase/bytebase/backend/component/ghost""github.com/bytebase/bytebase/backend/component/state"api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/store"@@ -71,7 +72,7 @@ func (exec *SchemaUpdateGhostSyncExecutor) runGhostMigration(ctx context.Contextstatement = strings.TrimSpace(statement)- tableName, err := utils.GetTableNameFromStatement(statement)+ tableName, err := ghost.GetTableNameFromStatement(statement)if err != nil {return true, nil, err}@@ -105,12 +106,7 @@ func (exec *SchemaUpdateGhostSyncExecutor) runGhostMigration(ctx context.Context// To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.renderedStatement := utils.RenderStatement(statement, materials)- config, err := utils.GetGhostConfig(task.ID, database, adminDataSource, exec.secret, instanceUsers, tableName, renderedStatement, false, 10000000)- if err != nil {- return true, nil, err- }-- migrationContext, err := utils.NewMigrationContext(config)+ migrationContext, err := ghost.NewMigrationContext(task.ID, database, adminDataSource, exec.secret, instanceUsers, tableName, renderedStatement, false, 10000000)if err != nil {return true, nil, errors.Wrap(err, "failed to init migrationContext for gh-ost")}diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex d32ba21612..cf9f92e18f 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -14,8 +14,6 @@ import ("strings""time"- "github.com/github/gh-ost/go/base"- ghostsql "github.com/github/gh-ost/go/sql""github.com/pkg/errors""google.golang.org/grpc/codes""google.golang.org/grpc/status"@@ -63,167 +61,6 @@ func DataSourceFromInstanceWithType(instance *store.InstanceMessage, dataSourceTreturn nil}-// GetTableNameFromStatement gets the table name from statement for gh-ost.-func GetTableNameFromStatement(statement string) (string, error) {- // Trim the statement for the parser.- // This in effect removes all leading and trailing spaces, substitute multiple spaces with one.- statement = strings.Join(strings.Fields(statement), " ")- parser := ghostsql.NewParserFromAlterStatement(statement)- if !parser.HasExplicitTable() {- return "", errors.Errorf("failed to parse table name from statement, statement: %v", statement)- }- return parser.GetExplicitTable(), nil-}--// GhostConfig is the configuration for gh-ost migration.-type GhostConfig struct {- // serverID should be unique- serverID uint- host string- port string- user string- password string- database string- table string- alterStatement string- socketFilename string- postponeFlagFilename string- noop bool-- // vendor related- isAWS bool-}--// GetGhostConfig returns a gh-ost configuration for migration.-func GetGhostConfig(taskID int, database *store.DatabaseMessage, dataSource *store.DataSourceMessage, secret string, instanceUsers []*store.InstanceUserMessage, tableName string, statement string, noop bool, serverIDOffset uint) (GhostConfig, error) {- var isAWS bool- for _, user := range instanceUsers {- if user.Name == "'rdsadmin'@'localhost'" && strings.Contains(user.Grant, "SUPER") {- isAWS = true- break- }- }- password, err := common.Unobfuscate(dataSource.ObfuscatedPassword, secret)- if err != nil {- return GhostConfig{}, err- }- return GhostConfig{- host: dataSource.Host,- port: dataSource.Port,- user: dataSource.Username,- password: password,- database: database.DatabaseName,- table: tableName,- alterStatement: statement,- socketFilename: getSocketFilename(taskID, database.UID, database.DatabaseName, tableName),- postponeFlagFilename: GetPostponeFlagFilename(taskID, database.UID, database.DatabaseName, tableName),- noop: noop,- // On the source and each replica, you must set the server_id system variable to establish a unique replication ID. For each server, you should pick a unique positive integer in the range from 1 to 2^32 − 1, and each ID must be different from every other ID in use by any other source or replica in the replication topology. Example: server-id=3.- // https://dev.mysql.com/doc/refman/5.7/en/replication-options-source.html- // Here we use serverID = offset + task.ID to avoid potential conflicts.- serverID: serverIDOffset + uint(taskID),- // https://github.com/github/gh-ost/blob/master/doc/rds.md- isAWS: isAWS,- }, nil-}--func getSocketFilename(taskID int, databaseID int, databaseName string, tableName string) string {- return fmt.Sprintf("/tmp/gh-ost.%v.%v.%v.%v.sock", taskID, databaseID, databaseName, tableName)-}--// GetPostponeFlagFilename gets the postpone flag filename for gh-ost.-func GetPostponeFlagFilename(taskID int, databaseID int, databaseName string, tableName string) string {- return fmt.Sprintf("/tmp/gh-ost.%v.%v.%v.%v.postponeFlag", taskID, databaseID, databaseName, tableName)-}--// NewMigrationContext is the context for gh-ost migration.-func NewMigrationContext(config GhostConfig) (*base.MigrationContext, error) {- const (- allowedRunningOnMaster = true- concurrentCountTableRows = true- timestampAllTable = true- hooksStatusIntervalSec = 60- heartbeatIntervalMilliseconds = 100- niceRatio = 0- chunkSize = 1000- dmlBatchSize = 10- maxLagMillisecondsThrottleThreshold = 1500- defaultNumRetries = 60- cutoverLockTimeoutSeconds = 60- exponentialBackoffMaxInterval = 64- throttleHTTPIntervalMillis = 100- throttleHTTPTimeoutMillis = 1000- )- statement := strings.Join(strings.Fields(config.alterStatement), " ")- migrationContext := base.NewMigrationContext()- migrationContext.InspectorConnectionConfig.Key.Hostname = config.host- port := 3306- if config.port != "" {- configPort, err := strconv.Atoi(config.port)- if err != nil {- return nil, errors.Wrap(err, "failed to convert port from string to int")- }- port = configPort- }- migrationContext.InspectorConnectionConfig.Key.Port = port- migrationContext.CliUser = config.user- migrationContext.CliPassword = config.password- migrationContext.DatabaseName = config.database- migrationContext.OriginalTableName = config.table- migrationContext.AlterStatement = statement- migrationContext.Noop = config.noop- migrationContext.ReplicaServerId = config.serverID- if config.isAWS {- migrationContext.AssumeRBR = true- }- // set defaults- if err := migrationContext.SetConnectionConfig(""); err != nil {- return nil, err- }- migrationContext.AllowedRunningOnMaster = allowedRunningOnMaster- migrationContext.ConcurrentCountTableRows = concurrentCountTableRows- migrationContext.HooksStatusIntervalSec = hooksStatusIntervalSec- migrationContext.CutOverType = base.CutOverAtomic- migrationContext.ThrottleHTTPIntervalMillis = throttleHTTPIntervalMillis- migrationContext.ThrottleHTTPTimeoutMillis = throttleHTTPTimeoutMillis-- if migrationContext.AlterStatement == "" {- return nil, errors.Errorf("alterStatement must be provided and must not be empty")- }- parser := ghostsql.NewParserFromAlterStatement(migrationContext.AlterStatement)- migrationContext.AlterStatementOptions = parser.GetAlterStatementOptions()-- if migrationContext.DatabaseName == "" {- if !parser.HasExplicitSchema() {- return nil, errors.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")- }- migrationContext.DatabaseName = parser.GetExplicitSchema()- }- if migrationContext.OriginalTableName == "" {- if !parser.HasExplicitTable() {- return nil, errors.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")- }- migrationContext.OriginalTableName = parser.GetExplicitTable()- }- migrationContext.ServeSocketFile = config.socketFilename- migrationContext.PostponeCutOverFlagFile = config.postponeFlagFilename- migrationContext.TimestampAllTable = timestampAllTable- migrationContext.SetHeartbeatIntervalMilliseconds(heartbeatIntervalMilliseconds)- migrationContext.SetNiceRatio(niceRatio)- migrationContext.SetChunkSize(chunkSize)- migrationContext.SetDMLBatchSize(dmlBatchSize)- migrationContext.SetMaxLagMillisecondsThrottleThreshold(maxLagMillisecondsThrottleThreshold)- migrationContext.SetDefaultNumRetries(defaultNumRetries)- migrationContext.ApplyCredentials()- if err := migrationContext.SetCutOverLockTimeoutSeconds(cutoverLockTimeoutSeconds); err != nil {- return nil, err- }- if err := migrationContext.SetExponentialBackoffMaxInterval(exponentialBackoffMaxInterval); err != nil {- return nil, err- }- return migrationContext, nil-}-// isMatchExpression checks whether a databases matches the query.// labels is a mapping from database label key to value.func isMatchExpression(labels map[string]string, expression *api.LabelSelectorRequirement) bool {