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: mysqlbinlog field in server (#1350)
h3n4l61a306f41f9b
diff --git a/common/util.go b/common/util.goindex c09db3f379..d69138b8f0 100644--- a/common/util.go+++ b/common/util.go@@ -59,6 +59,11 @@ func GetPostgresSocketDir() string {return "/tmp"}+// GetResourceDir returns the resource directory of Bytebase.+func GetResourceDir(dataDir string) string {+ return path.Join(dataDir, "resources")+}+// DefaultMigrationVersion returns the default migration version string.// Use the current time in second to guarantee uniqueness in a monotonic increasing way.// We cannot add task ID because tenant mode databases should use the same migration version string when applying a schema update.diff --git a/plugin/restore/mysql/mysql.go b/plugin/restore/mysql/mysql.goindex d45ebccf03..3abcf86c10 100644--- a/plugin/restore/mysql/mysql.go+++ b/plugin/restore/mysql/mysql.go@@ -12,11 +12,9 @@ import ("github.com/bytebase/bytebase/api"mysql "github.com/bytebase/bytebase/plugin/db/mysql"+ "github.com/bytebase/bytebase/resources/mysqlbinlog")-// TODO(zp): refactor this when sure the mysqlbinlog path-var mysqlbinlogBinPath = "UNKNOWN"-const (// MaxDatabaseNameLength is the allowed max database name length in MySQLMaxDatabaseNameLength = 64@@ -24,13 +22,15 @@ const (// Restore implements recovery functions for MySQLtype Restore struct {- driver *mysql.Driver+ driver *mysql.Driver+ mysqlbinlog *mysqlbinlog.Instance}// New creates a new instance of Restore-func New(driver *mysql.Driver) *Restore {+func New(driver *mysql.Driver, instance *mysqlbinlog.Instance) *Restore {return &Restore{- driver: driver,+ driver: driver,+ mysqlbinlog: instance,}}@@ -256,7 +256,7 @@ func (r *Restore) downloadBinlogFile(ctx context.Context, instance *api.Instance// for mysqlbinlog binary, --result-file must end with '/'resultFileDir := strings.TrimRight(saveDir, "/") + "/"// TODO(zp): support ssl?- cmd := exec.CommandContext(ctx, filepath.Join(mysqlbinlogBinPath, "bin", "mysqlbinlog"),+ cmd := exec.CommandContext(ctx, r.mysqlbinlog.GetPath(),binlog.Name,fmt.Sprintf("--read-from-remote-server --host=%s --port=%s --user=%s --password=%s", instance.Host, instance.Port, instance.Username, instance.Password),"--raw",diff --git a/resources/mysqlbinlog/mysqlbinlog.go b/resources/mysqlbinlog/mysqlbinlog.goindex 8822191085..2869c14f2c 100644--- a/resources/mysqlbinlog/mysqlbinlog.go+++ b/resources/mysqlbinlog/mysqlbinlog.go@@ -1,8 +1,10 @@package mysqlbinlogimport (+ "bytes""fmt""os"+ "os/exec""path""path/filepath""runtime"@@ -11,8 +13,33 @@ import ("github.com/bytebase/bytebase/resources/utils")-// Install will extract the mysqlbinlog tar in resourceDir, returns the mysqlbinlog binary directory if no error occur.-func Install(resourceDir string) (string, error) {+// Instance involve the path of mysqlbinlog binary.+type Instance struct {+ binPath string+}++// GetPath returns the mysqlbinlog binary path.+func (ins *Instance) GetPath() string {+ return ins.binPath+}++// Version returns the raw output of `mysqlbinlog -V`+func (ins *Instance) Version() (string, error) {+ var version bytes.Buffer++ cmd := exec.Command(ins.GetPath(), "-V")+ cmd.Stdout = &version+ cmd.Stderr = os.Stderr++ if err := cmd.Run(); err != nil {+ return "", err+ }++ return version.String(), nil+}++// Install will extract the mysqlbinlog tar in resourceDir.+func Install(resourceDir string) (*Instance, error) {var tarName stringswitch {case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":@@ -20,35 +47,36 @@ func Install(resourceDir string) (string, error) {case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":tarName = "mysqlbinlog-8.0.28-linux-glibc-2.17-x86_64.tar.gz"default:- return "", fmt.Errorf("Unsupported combination of OS[%s] and ARCH[%s]", runtime.GOOS, runtime.GOARCH)+ return nil, fmt.Errorf("Unsupported combination of OS[%s] and ARCH[%s]", runtime.GOOS, runtime.GOARCH)}version := strings.TrimRight(tarName, "tar.gz")mysqlbinlogDir := path.Join(resourceDir, version)if _, err := os.Stat(mysqlbinlogDir); err != nil {if !os.IsNotExist(err) {- return "", fmt.Errorf("failed to check binary directory path %q, error: %w", mysqlbinlogDir, err)+ return nil, fmt.Errorf("failed to check binary directory path %q, error: %w", mysqlbinlogDir, err)}// Install if not exist yettmpDir := path.Join(resourceDir, fmt.Sprintf("tmp-%s", version))if err := os.RemoveAll(tmpDir); err != nil {- return "", fmt.Errorf("failed to remove mysqlbinlog binary temp directory %q, error: %w", tmpDir, err)+ return nil, fmt.Errorf("failed to remove mysqlbinlog binary temp directory %q, error: %w", tmpDir, err)}f, err := resources.Open(tarName)if err != nil {- return "", fmt.Errorf("failed to find %q in embedded resources, error: %v", tarName, err)+ return nil, fmt.Errorf("failed to find %q in embedded resources, error: %v", tarName, err)}defer f.Close()if err := utils.ExtractTarGz(f, tmpDir); err != nil {- return "", fmt.Errorf("failed to extract tar.gz file, error: %w", err)+ return nil, fmt.Errorf("failed to extract tar.gz file, error: %w", err)}if err := os.Rename(tmpDir, mysqlbinlogDir); err != nil {- return "", fmt.Errorf("failed to rename mysqlbinlog binary directory from %q to %q, error: %w", tmpDir, mysqlbinlogDir, err)+ return nil, fmt.Errorf("failed to rename mysqlbinlog binary directory from %q to %q, error: %w", tmpDir, mysqlbinlogDir, err)}}-- return filepath.Join(mysqlbinlogDir, version, "bin"), nil+ return &Instance{+ binPath: filepath.Join(mysqlbinlogDir, version, "bin", "mysqlbinlog"),+ }, nil}diff --git a/resources/mysqlbinlog/mysqlbinlog_test.go b/resources/mysqlbinlog/mysqlbinlog_test.goindex 9ab29b010a..be3c87be8f 100644--- a/resources/mysqlbinlog/mysqlbinlog_test.go+++ b/resources/mysqlbinlog/mysqlbinlog_test.go@@ -1,9 +1,6 @@package mysqlbinlogimport (- "os"- "os/exec"- "path/filepath""testing""github.com/stretchr/testify/require"@@ -14,14 +11,9 @@ import (func TestRunBinary(t *testing.T) {a := require.New(t)tmpDir := t.TempDir()- mysqlbinlogDir, err := Install(tmpDir)+ ins, err := Install(tmpDir)a.NoError(err)- mysqlbinlogPath := filepath.Join(mysqlbinlogDir, "mysqlbinlog")- cmd := exec.Command(mysqlbinlogPath, "-V")- cmd.Stdout = os.Stderr- cmd.Stderr = os.Stderr-- err = cmd.Run()+ _, err = ins.Version()a.NoError(err)}diff --git a/server/server.go b/server/server.goindex e57aa5dacf..00a166bbc2 100644--- a/server/server.go+++ b/server/server.go@@ -5,7 +5,6 @@ import ("encoding/json""fmt""net/http"- "path""strings""sync""time"@@ -47,21 +46,19 @@ type Server struct {LicenseService enterpriseAPI.LicenseServicesubscription enterpriseAPI.Subscription- profile Profile- e *echo.Echo- metaDB *store.MetadataDB- db *store.DB- store *store.Store- l *zap.Logger- lvl *zap.AtomicLevel- startedTs int64- secret string-- mysqlbinlogDir string+ profile Profile+ e *echo.Echo+ mysqlbinlog *mysqlbinlog.Instance+ metaDB *store.MetadataDB+ db *store.DB+ store *store.Store+ l *zap.Logger+ lvl *zap.AtomicLevel+ startedTs int64+ secret string// boot specifies that whether the server boot correctlycancel context.CancelFunc- boot bool}//go:embed acl_casbin_model.conf@@ -95,16 +92,25 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLevefmt.Printf("readonly=%t\n", prof.Readonly)fmt.Printf("demo=%t\n", prof.Demo)fmt.Printf("debug=%t\n", prof.Debug)+ fmt.Printf("dataDir=%s\n", prof.DataDir)fmt.Println("-----Config END-------")+ serverStarted := false+ defer func() {+ if !serverStarted {+ _ = s.Shutdown(ctx)+ }+ }()+var err error- // TODO(zp): refactor to keep consistency with embedded Postgres.++ resourceDir := common.GetResourceDir(prof.DataDir)// Install mysqlbinlog.- mysqlbinlogDir, err := mysqlbinlog.Install(path.Join(prof.DataDir, "resources"))+ mysqlbinlogIns, err := mysqlbinlog.Install(resourceDir)if err != nil {return nil, fmt.Errorf("cannot install mysqlbinlog binary, error: %w", err)}- s.mysqlbinlogDir = mysqlbinlogDir+ s.mysqlbinlog = mysqlbinlogIns// New MetadataDB instance.if prof.useEmbedDB() {@@ -122,22 +128,12 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLevereturn nil, fmt.Errorf("cannot new db: %w", err)}s.db = storeDB- defer func() {- if !s.boot {- _ = s.metaDB.Close()- }- }()// Open the database that stores bytebase's own metadata connection.if err = storeDB.Open(ctx); err != nil {// return s so that caller can call s.Close() to shut down the postgres server if embedded.return nil, fmt.Errorf("cannot open db: %w", err)}- defer func() {- if !s.boot {- _ = storeDB.Close()- }- }()cacheService := NewCacheService(logger)storeInstance := store.New(logger, storeDB, cacheService)@@ -193,7 +189,7 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLeveschemaUpdateGhostDropOriginalTableExecutor := NewSchemaUpdateGhostDropOriginalTableTaskExecutor(logger)taskScheduler.Register(string(api.TaskDatabaseSchemaUpdateGhostDropOriginalTable), schemaUpdateGhostDropOriginalTableExecutor)- pitrRestoreExecutor := NewPITRRestoreTaskExecutor(logger)+ pitrRestoreExecutor := NewPITRRestoreTaskExecutor(logger, s.mysqlbinlog)taskScheduler.Register(string(api.TaskDatabasePITRRestore), pitrRestoreExecutor)s.TaskScheduler = taskScheduler@@ -315,7 +311,7 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLeves.initSubscription()logger.Debug(fmt.Sprintf("All registered routes: %v", string(allRoutes)))- s.boot = true+ serverStarted = truereturn s, nil}@@ -444,8 +440,9 @@ func (server *Server) Shutdown(ctx context.Context) error {}// Shutdown postgres server if embed.- server.metaDB.Close()-+ if server.metaDB != nil {+ server.metaDB.Close()+ }server.l.Info("Bytebase stopped properly")return nildiff --git a/server/task_executor_pitr_delete.go b/server/task_executor_pitr_delete.goindex d7d7ca0c0f..213c1c2aff 100644--- a/server/task_executor_pitr_delete.go+++ b/server/task_executor_pitr_delete.go@@ -7,19 +7,22 @@ import ("github.com/bytebase/bytebase/api"pluginmysql "github.com/bytebase/bytebase/plugin/db/mysql"restoremysql "github.com/bytebase/bytebase/plugin/restore/mysql"+ "github.com/bytebase/bytebase/resources/mysqlbinlog""go.uber.org/zap")// NewPITRDeleteTaskExecutor creates a PITR delete task executor.-func NewPITRDeleteTaskExecutor(logger *zap.Logger) TaskExecutor {+func NewPITRDeleteTaskExecutor(logger *zap.Logger, instance *mysqlbinlog.Instance) TaskExecutor {return &PITRDeleteTaskExecutor{- l: logger,+ l: logger,+ mysqlbinlogIns: instance,}}// PITRDeleteTaskExecutor is the PITR delete task executor.type PITRDeleteTaskExecutor struct {- l *zap.Logger+ l *zap.Logger+ mysqlbinlogIns *mysqlbinlog.Instance}// RunOnce will run the PITR delete task executor once.@@ -47,7 +50,7 @@ func (exec *PITRDeleteTaskExecutor) RunOnce(ctx context.Context, server *Server,return true, nil, fmt.Errorf("failed to get issue by PipelineID[%d], error[%w]", task.PipelineID, err)}- mysqlRestore := restoremysql.New(mysqlDriver)+ mysqlRestore := restoremysql.New(mysqlDriver, exec.mysqlbinlogIns)if err := mysqlRestore.DeleteOldDatabase(ctx, task.Database.Name, issue.CreatedTs); err != nil {exec.l.Error("failed to delete the original database after PITR swap",zap.String("instance", task.Instance.Name),diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex 3365d752c4..37e8be6812 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -11,20 +11,23 @@ import ("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/mysqlbinlog""github.com/bytebase/bytebase/store""go.uber.org/zap")// NewPITRRestoreTaskExecutor creates a PITR restore task executor.-func NewPITRRestoreTaskExecutor(logger *zap.Logger) TaskExecutor {+func NewPITRRestoreTaskExecutor(logger *zap.Logger, instance *mysqlbinlog.Instance) TaskExecutor {return &PITRRestoreTaskExecutor{- l: logger,+ l: logger,+ mysqlbinlogIns: instance,}}// PITRRestoreTaskExecutor is the PITR restore task executor.type PITRRestoreTaskExecutor struct {- l *zap.Logger+ l *zap.Logger+ mysqlbinlogIns *mysqlbinlog.Instance}// RunOnce will run the PITR restore task executor once.@@ -77,7 +80,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apreturn fmt.Errorf("[internal] cast driver to mysql.Driver failed")}- mysqlRestore := restoremysql.New(mysqlDriver)+ mysqlRestore := restoremysql.New(mysqlDriver, exec.mysqlbinlogIns)config := pluginmysql.BinlogInfo{}// TODO(dragonly): Search and put the file io of the logical backup file here.// Currently, let's just use the empty backup dump as a placeholder.diff --git a/store/metadb.go b/store/metadb.goindex 5890b0c483..8c5b4d5a6b 100644--- a/store/metadb.go+++ b/store/metadb.go@@ -5,7 +5,6 @@ import ("net""net/url""os"- "path""github.com/bytebase/bytebase/common"dbdriver "github.com/bytebase/bytebase/plugin/db"@@ -38,7 +37,7 @@ func NewMetadataDBWithEmbedPg(logger *zap.Logger, pgUser, dataDir, demoDataDir sembed: true,pgUser: pgUser,}- resourceDir := path.Join(dataDir, "resources")+ resourceDir := common.GetResourceDir(dataDir)pgDataDir := common.GetPostgresDataDir(dataDir)logger.Info("-----Embedded Postgres Config BEGIN-----")logger.Info(fmt.Sprintf("resourceDir=%s\n", resourceDir))diff --git a/tests/backup_restore_test.go b/tests/backup_restore_test.goindex 66f4e1a53e..9fdf12975b 100644--- a/tests/backup_restore_test.go+++ b/tests/backup_restore_test.go@@ -16,6 +16,7 @@ import (pluginmysql "github.com/bytebase/bytebase/plugin/db/mysql"restoremysql "github.com/bytebase/bytebase/plugin/restore/mysql"resourcemysql "github.com/bytebase/bytebase/resources/mysql"+ "github.com/bytebase/bytebase/resources/mysqlbinlog""github.com/stretchr/testify/require""go.uber.org/zap"@@ -126,6 +127,11 @@ func TestPITR(t *testing.T) {)port := getTestPort(t.Name())+ t.Log("install mysqlbinlog binary")+ tmpDir := t.TempDir()+ mysqlbinlogIns, err := mysqlbinlog.Install(tmpDir)+ a.NoError(err)+// test casest.Run("Buggy Application", func(t *testing.T) {t.Parallel()@@ -162,7 +168,7 @@ func TestPITR(t *testing.T) {createPITRIssueTimestamp := time.Now().Unix()mysqlDriver, ok := driver.(*pluginmysql.Driver)a.Equal(true, ok)- mysqlRestore := restoremysql.New(mysqlDriver)+ mysqlRestore := restoremysql.New(mysqlDriver, mysqlbinlogIns)config := pluginmysql.BinlogInfo{}err := mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), config, database, createPITRIssueTimestamp)a.NoError(err)@@ -235,7 +241,7 @@ func TestPITR(t *testing.T) {createPITRIssueTimestamp := time.Now().Unix()mysqlDriver, ok := driver.(*pluginmysql.Driver)a.Equal(true, ok)- mysqlRestore := restoremysql.New(mysqlDriver)+ mysqlRestore := restoremysql.New(mysqlDriver, mysqlbinlogIns)config := pluginmysql.BinlogInfo{}err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), config, database, createPITRIssueTimestamp)a.NoError(err)@@ -287,7 +293,7 @@ func TestPITR(t *testing.T) {t.Log("restore to pitr database")mysqlDriver, ok := driver.(*pluginmysql.Driver)a.Equal(true, ok)- mysqlRestore := restoremysql.New(mysqlDriver)+ mysqlRestore := restoremysql.New(mysqlDriver, mysqlbinlogIns)config := pluginmysql.BinlogInfo{}err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), config, database, createPITRIssueTimestamp)a.NoError(err)