Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(PITR): add a baseline migration history at the end of PITR cutover (#1433)
Yilong Li41805306301b
diff --git a/common/log/logger.go b/common/log/logger.goindex 98d9b90ec6..42a2f6cfd6 100644--- a/common/log/logger.go+++ b/common/log/logger.go@@ -40,6 +40,8 @@ func EnabledLevel(level zapcore.Level) bool {// Debug wraps the zap Logger's Debug method.func Debug(msg string, fields ...zap.Field) {+ // See notes of function Error.+ fields = append(fields, zap.StackSkip("stack", 2))gl.Debug(msg, fields...)}@@ -55,6 +57,9 @@ func Warn(msg string, fields ...zap.Field) {// Error wraps the zap Logger's Error method.func Error(msg string, fields ...zap.Field) {+ // Append the stack info in Error logging for better debugging experience.+ // Note that we should skip 2 stack frames so that the top frame start at the caller of log.Error.+ fields = append(fields, zap.StackSkip("stack", 2))gl.Error(msg, fields...)}diff --git a/plugin/db/driver.go b/plugin/db/driver.goindex 5c619d23f0..c131c7e498 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -242,6 +242,7 @@ type MigrationInfo struct {Description stringCreator stringIssueID string+ // Payload contains JSON-encoded string of VCS push event if the migration is triggered by a VCS push event.Payload stringCreateDatabase bool// UseSemanticVersion is whether version is a semantic version.diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex a05d70aa06..2fb519d506 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -188,7 +188,7 @@ func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migrareturn 0, fmt.Errorf("failed to convert to stored version, error %w", err)}// Phase 1 - Pre-check before executing migration- // Check if the same migration version has already been applied+ // Check if the same migration version has already been applied.if list, err := executor.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{Database: &m.Namespace,Version: &m.Version,diff --git a/server/task_executor.go b/server/task_executor.goindex a5f0cb7094..41f54f231f 100644--- a/server/task_executor.go+++ b/server/task_executor.go@@ -87,7 +87,7 @@ func preMigration(ctx context.Context, server *Server, task *api.Task, migration)// This should not happen normally as we already check this when creating the issue. Just in case.if err != nil {- return nil, fmt.Errorf("failed to start migration, error: %w", err)+ return nil, fmt.Errorf("failed to prepare for database migration, error[%w]", err)}mi.Creator = vcsPushEvent.FileCommit.AuthorName@@ -96,7 +96,7 @@ func preMigration(ctx context.Context, server *Server, task *api.Task, migration}bytes, err := json.Marshal(miPayload)if err != nil {- return nil, fmt.Errorf("failed to start migration, unable to marshal vcs push event payload %w", err)+ return nil, fmt.Errorf("failed to prepare for database migration, unable to marshal vcs push event payload, error[%w]", err)}mi.Payload = string(bytes)}diff --git a/server/task_executor_database_restore.go b/server/task_executor_database_restore.goindex 587bc03587..ed41fa9d9e 100644--- a/server/task_executor_database_restore.go+++ b/server/task_executor_database_restore.go@@ -167,7 +167,6 @@ func createBranchMigrationHistory(ctx context.Context, server *Server, sourceDatDescription: description,Creator: task.Creator.Name,IssueID: issueID,- Payload: "",}migrationID, _, err := targetDriver.ExecuteMigration(ctx, m, "")if err != nil {diff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.goindex 6bc1b31575..496981f2c1 100644--- a/server/task_executor_pitr_cutover.go+++ b/server/task_executor_pitr_cutover.go@@ -3,9 +3,12 @@ package serverimport ("context""fmt"+ "strconv""github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log"+ "github.com/bytebase/bytebase/plugin/db"pluginmysql "github.com/bytebase/bytebase/plugin/db/mysql"restoremysql "github.com/bytebase/bytebase/plugin/restore/mysql""github.com/bytebase/bytebase/resources/mysqlutil"@@ -15,7 +18,6 @@ import (// NewPITRCutoverTaskExecutor creates a PITR cutover task executor.func NewPITRCutoverTaskExecutor(instance *mysqlutil.Instance) TaskExecutor {return &PITRCutoverTaskExecutor{-mysqlutil: instance,}}@@ -70,7 +72,7 @@ func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.)pitrDatabaseName, pitrOldDatabaseName, err := mysqlRestore.SwapPITRDatabase(ctx, task.Database.Name, issue.CreatedTs)if err != nil {- log.Error("failed to swap the original and PITR database",+ log.Error("Failed to swap the original and PITR database",zap.Int("issueID", issue.ID),zap.String("database", task.Database.Name),zap.Stack("stack"),@@ -82,6 +84,26 @@ func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.zap.String("original_database", task.Database.Name),zap.String("pitr_database", pitrDatabaseName),zap.String("old_database", pitrOldDatabaseName))++ log.Info("Appending new migration history record...")+ m := &db.MigrationInfo{+ ReleaseVersion: server.profile.Version,+ Version: common.DefaultMigrationVersion(),+ Namespace: task.Database.Name,+ Database: task.Database.Name,+ Environment: task.Database.Instance.Environment.Name,+ Source: db.MigrationSource(task.Database.Project.WorkflowType),+ Type: db.Baseline,+ Description: fmt.Sprintf("PITR: restoring database %s", task.Database.Name),+ Creator: task.Creator.Name,+ IssueID: strconv.Itoa(issue.ID),+ }++ if _, _, err := driver.ExecuteMigration(ctx, m, "/* pitr cutover */"); err != nil {+ log.Error("Failed to add migration history record", zap.Error(err))+ return true, nil, fmt.Errorf("failed to add migration history record, error[%w]", err)+ }+return true, &api.TaskRunResultPayload{Detail: fmt.Sprintf("Swapped PITR database for target database %q", task.Database.Name),}, nildiff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex 660cd85055..73cce4706e 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -43,8 +43,6 @@ func (exec *PITRRestoreTaskExecutor) RunOnce(ctx context.Context, server *Serverreturn exec.pitrRestore(ctx, task, server)}-// TODO(dragonly): Should establish a BASELINE migration in the swap database task.-// And what's the right schema version in tenant mode?func (exec *PITRRestoreTaskExecutor) pitrRestore(ctx context.Context, task *api.Task, server *Server) (terminated bool, result *api.TaskRunResultPayload, err error) {driver, err := getAdminDatabaseDriver(ctx, task.Instance, "", "" /* pgInstanceDir */)if err != nil {diff --git a/server/task_executor_schema_update_ghost_sync.go b/server/task_executor_schema_update_ghost_sync.goindex 0487499a9b..5c4de54a64 100644--- a/server/task_executor_schema_update_ghost_sync.go+++ b/server/task_executor_schema_update_ghost_sync.go@@ -38,7 +38,7 @@ func (exec *SchemaUpdateGhostSyncTaskExecutor) RunOnce(ctx context.Context, servif err := json.Unmarshal([]byte(task.Payload), payload); err != nil {return true, nil, fmt.Errorf("invalid database schema update gh-ost sync payload: %w", err)}- return runGhostMigration(ctx, server, task, db.Migrate, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)+ return runGhostMigration(ctx, server, task, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)}func getSocketFilename(taskID int, databaseID int, databaseName string, tableName string) string {@@ -87,7 +87,7 @@ func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {dmlBatchSize = 10maxLagMillisecondsThrottleThreshold = 1500defaultNumRetries = 60- cutoverLockTimoutSeconds = 3+ cutoverLockTimeoutSeconds = 3exponentialBackoffMaxInterval = 64)statement := strings.Join(strings.Fields(config.alterStatement), " ")@@ -145,7 +145,7 @@ func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {migrationContext.SetMaxLagMillisecondsThrottleThreshold(maxLagMillisecondsThrottleThreshold)migrationContext.SetDefaultNumRetries(defaultNumRetries)migrationContext.ApplyCredentials()- if err := migrationContext.SetCutOverLockTimeoutSeconds(cutoverLockTimoutSeconds); err != nil {+ if err := migrationContext.SetCutOverLockTimeoutSeconds(cutoverLockTimeoutSeconds); err != nil {return nil, err}if err := migrationContext.SetExponentialBackoffMaxInterval(exponentialBackoffMaxInterval); err != nil {@@ -154,8 +154,8 @@ func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {return migrationContext, nil}-func runGhostMigration(ctx context.Context, server *Server, task *api.Task, migrationType db.MigrationType, statement, schemaVersion string, vcsPushEvent *vcsPlugin.PushEvent) (terminated bool, result *api.TaskRunResultPayload, err error) {- mi, err := preMigration(ctx, server, task, migrationType, statement, schemaVersion, vcsPushEvent)+func runGhostMigration(ctx context.Context, server *Server, task *api.Task, statement, schemaVersion string, vcsPushEvent *vcsPlugin.PushEvent) (terminated bool, result *api.TaskRunResultPayload, err error) {+ mi, err := preMigration(ctx, server, task, db.Migrate, statement, schemaVersion, vcsPushEvent)if err != nil {return true, nil, err}