Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor: remove mysqlutil instance (#2147)

h3n4l132152b5b83a
diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.go
index f55dcffaa6..68f94c40bd 100644
--- a/plugin/db/mysql/mysql.go
+++ b/plugin/db/mysql/mysql.go
@@ -10,7 +10,6 @@ import (
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/util"
- "github.com/bytebase/bytebase/resources/mysqlutil"
"github.com/go-sql-driver/mysql"
"go.uber.org/zap"
)
@@ -32,7 +31,6 @@ type Driver struct {
connectionCtx db.ConnectionContext
connCfg db.ConnectionConfig
dbType db.Type
- mysqlutil mysqlutil.Instance
resourceDir string
binlogDir string
db *sql.DB
diff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.go
index 77cb786821..a23d18a76d 100644
--- a/plugin/db/mysql/restore.go
+++ b/plugin/db/mysql/restore.go
@@ -94,8 +94,7 @@ func newBinlogCoordinate(binlogFileName string, pos int64) (binlogCoordinate, er
}
// SetUpForPITR sets necessary fields for MySQL PITR recovery.
-func (driver *Driver) SetUpForPITR(mysqlutilInstance mysqlutil.Instance, binlogDir string) {
- driver.mysqlutil = mysqlutilInstance
+func (driver *Driver) SetUpForPITR(binlogDir string) {
driver.binlogDir = binlogDir
}
@@ -160,8 +159,8 @@ func (driver *Driver) replayBinlog(ctx context.Context, originalDatabase, pitrDa
mysqlArgs = append(mysqlArgs, fmt.Sprintf("--password=%s", driver.connCfg.Password))
}
- mysqlbinlogCmd := exec.CommandContext(ctx, driver.mysqlutil.GetPath(mysqlutil.MySQLBinlog), mysqlbinlogArgs...)
- mysqlCmd := exec.CommandContext(ctx, driver.mysqlutil.GetPath(mysqlutil.MySQL), mysqlArgs...)
+ mysqlbinlogCmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQLBinlog, driver.resourceDir), mysqlbinlogArgs...)
+ mysqlCmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQL, driver.resourceDir), mysqlArgs...)
log.Debug("Start replay binlog commands.",
zap.String("mysqlbinlog", mysqlbinlogCmd.String()),
zap.String("mysql", mysqlCmd.String()))
@@ -373,7 +372,7 @@ func (driver *Driver) getLatestBackupBeforeOrEqualBinlogCoord(backupList []*api.
"--base64-output=DECODE-ROWS",
filepath.Join(driver.binlogDir, fmt.Sprintf("binlog.%06d", targetBinlogCoordinate.Seq)),
}
- cmd := exec.Command(driver.mysqlutil.GetPath(mysqlutil.MySQLBinlog), args...)
+ cmd := exec.Command(mysqlutil.GetPath(mysqlutil.MySQLBinlog, driver.resourceDir), args...)
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
@@ -597,7 +596,7 @@ func (driver *Driver) downloadBinlogFile(ctx context.Context, binlogFileToDownlo
args = append(args, fmt.Sprintf("--password=%s", driver.connCfg.Password))
}
- cmd := exec.CommandContext(ctx, driver.mysqlutil.GetPath(mysqlutil.MySQLBinlog), args...)
+ cmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQLBinlog, driver.resourceDir), args...)
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
@@ -770,7 +769,7 @@ func (driver *Driver) parseLocalBinlogFirstEventTs(ctx context.Context, fileName
// Tell mysqlbinlog to suppress the BINLOG statements for row events, which reduces the unneeded output.
"--base64-output=DECODE-ROWS",
}
- cmd := exec.CommandContext(ctx, driver.mysqlutil.GetPath(mysqlutil.MySQLBinlog), args...)
+ cmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQLBinlog, driver.resourceDir), args...)
cmd.Stderr = os.Stderr
pr, err := cmd.StdoutPipe()
if err != nil {
@@ -815,7 +814,7 @@ func (driver *Driver) getBinlogEventPositionAtOrAfterTs(ctx context.Context, bin
// Instruct mysqlbinlog to start output only after encountering the first binlog event with timestamp equal or after targetTs.
"--start-datetime", formatDateTime(targetTs),
}
- cmd := exec.CommandContext(ctx, driver.mysqlutil.GetPath(mysqlutil.MySQLBinlog), args...)
+ cmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQLBinlog, driver.resourceDir), args...)
cmd.Stderr = os.Stderr
pr, err := cmd.StdoutPipe()
if err != nil {
diff --git a/resources/mysqlutil/mysqlutil.go b/resources/mysqlutil/mysqlutil.go
index 0a0ff4096c..465a8abfcf 100644
--- a/resources/mysqlutil/mysqlutil.go
+++ b/resources/mysqlutil/mysqlutil.go
@@ -24,37 +24,35 @@ const (
MySQLDump binaryName = "mysqldump"
)
-// Instance involve the path of all binaries binary.
-type Instance struct {
- mysqlBinPath string
- mysqlbinlogBinPath string
- mysqldumpBinPath string
-}
-
-// GetPath returns the binary path specified by `binName`.
-func (ins *Instance) GetPath(binName binaryName) string {
+// GetPath returns the binary path specified by `binName`, `resourceDir` is the path that installed the mysqlutil.
+func GetPath(binName binaryName, resourceDir string) string {
+ _, version, err := getTarNameAndVersion()
+ if err != nil {
+ return "UNEXPECTED_ERROR"
+ }
+ baseDir := filepath.Join(resourceDir, version)
switch binName {
case MySQL:
- return ins.mysqlBinPath
+ return filepath.Join(baseDir, "bin", "mysql")
case MySQLBinlog:
- return ins.mysqlbinlogBinPath
+ return filepath.Join(baseDir, "bin", "mysqlbinlog")
case MySQLDump:
- return ins.mysqldumpBinPath
+ return filepath.Join(baseDir, "bin", "mysqldump")
}
- return "UNKNOWN"
+ return "UNKNOWN_BINARY"
}
-// Version returns the raw output of ``binName` -V`.
-func (ins *Instance) Version(binName binaryName) (string, error) {
+// getExecutableVersion returns the raw output of ``binName` -V`.
+func getExecutableVersion(binName binaryName, resourceDir string) (string, error) {
var cmd *exec.Cmd
var version bytes.Buffer
switch binName {
case MySQL:
- cmd = exec.Command(ins.GetPath(MySQL), "-V")
+ cmd = exec.Command(GetPath(MySQL, resourceDir), "-V")
case MySQLBinlog:
- cmd = exec.Command(ins.GetPath(MySQLBinlog), "-V")
+ cmd = exec.Command(GetPath(MySQLBinlog, resourceDir), "-V")
case MySQLDump:
- cmd = exec.Command(ins.GetPath(MySQLDump), "-V")
+ cmd = exec.Command(GetPath(MySQLDump, resourceDir), "-V")
default:
return "", fmt.Errorf("unknown binary name: %s", binName)
}
@@ -67,8 +65,7 @@ func (ins *Instance) Version(binName binaryName) (string, error) {
return version.String(), nil
}
-// Install will extract the mysqlutil tar in resourceDir.
-func Install(resourceDir string) (*Instance, error) {
+func getTarNameAndVersion() (tarname string, version string, err error) {
var tarName string
switch {
case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":
@@ -78,18 +75,27 @@ func Install(resourceDir string) (*Instance, error) {
case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
tarName = "mysqlutil-8.0.28-linux-glibc2.17-x86_64.tar.gz"
default:
- return nil, fmt.Errorf("unsupported combination of OS %q and ARCH %q", runtime.GOOS, runtime.GOARCH)
+ return "", "", fmt.Errorf("unsupported combination of OS %q and ARCH %q", runtime.GOOS, runtime.GOARCH)
+ }
+ return tarName, strings.TrimRight(tarName, "tar.gz"), nil
+}
+
+// Install will extract the mysqlutil tar in resourceDir.
+func Install(resourceDir string) error {
+ tarName, version, err := getTarNameAndVersion()
+ if err != nil {
+ return fmt.Errorf("failed to get tarball name and version, error: %w", err)
}
- version := strings.TrimRight(tarName, "tar.gz")
mysqlutilDir := path.Join(resourceDir, version)
+
if _, err := os.Stat(mysqlutilDir); err != nil {
if !os.IsNotExist(err) {
- return nil, fmt.Errorf("failed to check binary directory path %q, error: %w", mysqlutilDir, err)
+ return fmt.Errorf("failed to check binary directory path %q, error: %w", mysqlutilDir, err)
}
// Install if not exist yet
if err := install(resourceDir, mysqlutilDir, tarName, version); err != nil {
- return nil, fmt.Errorf("cannot install mysqlutil, error: %w", err)
+ return fmt.Errorf("cannot install mysqlutil, error: %w", err)
}
}
@@ -108,25 +114,21 @@ func Install(resourceDir string) (*Instance, error) {
for _, fp := range checks {
if _, err := os.Stat(fp); err != nil {
if !os.IsNotExist(err) {
- return nil, fmt.Errorf("failed to check libncurses library path %q, error: %w", fp, err)
+ return fmt.Errorf("failed to check libncurses library path %q, error: %w", fp, err)
}
// Remove mysqlutil of old version and reinstall it
if err := os.RemoveAll(mysqlutilDir); err != nil {
- return nil, fmt.Errorf("failed to remove the old version mysqlutil binary directory %q, error: %w", mysqlutilDir, err)
+ return fmt.Errorf("failed to remove the old version mysqlutil binary directory %q, error: %w", mysqlutilDir, err)
}
// Install the current version
if err := install(resourceDir, mysqlutilDir, tarName, version); err != nil {
- return nil, fmt.Errorf("cannot install mysqlutil, error: %w", err)
+ return fmt.Errorf("cannot install mysqlutil, error: %w", err)
}
break
}
}
- return &Instance{
- mysqlBinPath: filepath.Join(mysqlutilDir, "bin", "mysql"),
- mysqlbinlogBinPath: filepath.Join(mysqlutilDir, "bin", "mysqlbinlog"),
- mysqldumpBinPath: filepath.Join(mysqlutilDir, "bin", "mysqldump"),
- }, nil
+ return nil
}
// install installs mysqlutil in resourceDir.
diff --git a/resources/mysqlutil/mysqlutil_test.go b/resources/mysqlutil/mysqlutil_test.go
index 23e301f9eb..a238707fda 100644
--- a/resources/mysqlutil/mysqlutil_test.go
+++ b/resources/mysqlutil/mysqlutil_test.go
@@ -16,21 +16,21 @@ func TestRunBinary(t *testing.T) {
a := require.New(t)
tmpDir := t.TempDir()
- ins, err := Install(tmpDir)
+ err := Install(tmpDir)
a.NoError(err)
t.Run("run mysql client", func(t *testing.T) {
- _, err := ins.Version(MySQL)
+ _, err := getExecutableVersion(MySQL, tmpDir)
a.NoError(err)
})
t.Run("run mysqlbinlog", func(t *testing.T) {
- _, err := ins.Version(MySQLBinlog)
+ _, err := getExecutableVersion(MySQLBinlog, tmpDir)
a.NoError(err)
})
t.Run("run mysqldump", func(t *testing.T) {
- _, err := ins.Version(MySQLDump)
+ _, err := getExecutableVersion(MySQLDump, tmpDir)
a.NoError(err)
})
}
@@ -46,7 +46,7 @@ func TestReinstallOnLinuxAmd64(t *testing.T) {
a := require.New(t)
tmpDir := t.TempDir()
- instance, err := Install(tmpDir)
+ err := Install(tmpDir)
a.NoError(err)
baseDir := filepath.Join(tmpDir, "mysqlutil-8.0.28-linux-glibc2.17-x86_64" /*Hard code, don't care about this*/)
@@ -59,7 +59,7 @@ func TestReinstallOnLinuxAmd64(t *testing.T) {
filepath.Join(binDir, "mysqldump"),
}
- mysqlPath := instance.GetPath(MySQL)
+ mysqlPath := GetPath(MySQL, tmpDir)
for _, fp := range checks {
a.FileExists(fp)
@@ -68,7 +68,7 @@ func TestReinstallOnLinuxAmd64(t *testing.T) {
a.NoError(err)
a.NoFileExists(fp)
- _, err = Install(tmpDir)
+ err = Install(tmpDir)
a.NoError(err)
a.FileExists(fp)
a.FileExists(mysqlPath)
diff --git a/server/backup_runner.go b/server/backup_runner.go
index 90dba0169c..42f7134584 100644
--- a/server/backup_runner.go
+++ b/server/backup_runner.go
@@ -17,7 +17,6 @@ import (
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/mysql"
- "github.com/bytebase/bytebase/resources/mysqlutil"
"go.uber.org/zap"
)
@@ -207,13 +206,13 @@ func (r *BackupRunner) downloadBinlogFiles(ctx context.Context) {
for _, instance := range instanceList {
if _, ok := r.downloadBinlogInstanceIDs[instance.ID]; !ok {
r.downloadBinlogInstanceIDs[instance.ID] = true
- go r.downloadBinlogFilesForInstance(ctx, instance, r.server.profile.DataDir, r.server.mysqlutil)
+ go r.downloadBinlogFilesForInstance(ctx, instance, r.server.profile.DataDir)
r.downloadBinlogWg.Add(1)
}
}
}
-func (r *BackupRunner) downloadBinlogFilesForInstance(ctx context.Context, instance *api.Instance, dataDir string, mysqlutil mysqlutil.Instance) {
+func (r *BackupRunner) downloadBinlogFilesForInstance(ctx context.Context, instance *api.Instance, dataDir string) {
log.Debug("Downloading binlog files for MySQL instance", zap.String("instance", instance.Name))
defer func() {
r.downloadBinlogMu.Lock()
@@ -242,7 +241,7 @@ func (r *BackupRunner) downloadBinlogFilesForInstance(ctx context.Context, insta
log.Error("Failed to cast driver to mysql.Driver", zap.String("instance", instance.Name))
return
}
- mysqlDriver.SetUpForPITR(mysqlutil, binlogDir)
+ mysqlDriver.SetUpForPITR(binlogDir)
if err := mysqlDriver.FetchAllBinlogFiles(ctx, false /* downloadLatestBinlogFile */); err != nil {
log.Error("Failed to download all binlog files for instance", zap.String("instance", instance.Name), zap.Error(err))
return
diff --git a/server/server.go b/server/server.go
index b6985ec0c1..9a25bc4079 100644
--- a/server/server.go
+++ b/server/server.go
@@ -56,7 +56,6 @@ type Server struct {
profile Profile
e *echo.Echo
- mysqlutil mysqlutil.Instance
pgInstanceDir string
metaDB *store.MetadataDB
store *store.Store
@@ -129,11 +128,9 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {
resourceDir := common.GetResourceDir(prof.DataDir)
// Install mysqlutil
- mysqlutilIns, err := mysqlutil.Install(resourceDir)
- if err != nil {
+ if err := mysqlutil.Install(resourceDir); err != nil {
return nil, fmt.Errorf("cannot install mysqlbinlog binary, error: %w", err)
}
- s.mysqlutil = *mysqlutilIns
// Install Postgres.
pgDataDir := common.GetPostgresDataDir(prof.DataDir)
@@ -216,9 +213,9 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {
taskScheduler.Register(api.TaskDatabaseSchemaUpdateGhostCutover, NewSchemaUpdateGhostCutoverTaskExecutor)
- taskScheduler.Register(api.TaskDatabasePITRRestore, func() TaskExecutor { return NewPITRRestoreTaskExecutor(s.mysqlutil) })
+ taskScheduler.Register(api.TaskDatabasePITRRestore, NewPITRRestoreTaskExecutor)
- taskScheduler.Register(api.TaskDatabasePITRCutover, func() TaskExecutor { return NewPITRCutoverTaskExecutor(s.mysqlutil) })
+ taskScheduler.Register(api.TaskDatabasePITRCutover, NewPITRCutoverTaskExecutor)
s.TaskScheduler = taskScheduler
diff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.go
index 1b7a0c7df7..6870d089e5 100644
--- a/server/task_executor_pitr_cutover.go
+++ b/server/task_executor_pitr_cutover.go
@@ -12,21 +12,17 @@ import (
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/mysql"
- "github.com/bytebase/bytebase/resources/mysqlutil"
"go.uber.org/zap"
)
// NewPITRCutoverTaskExecutor creates a PITR cutover task executor.
-func NewPITRCutoverTaskExecutor(instance mysqlutil.Instance) TaskExecutor {
- return &PITRCutoverTaskExecutor{
- mysqlutil: instance,
- }
+func NewPITRCutoverTaskExecutor() TaskExecutor {
+ return &PITRCutoverTaskExecutor{}
}
// PITRCutoverTaskExecutor is the PITR cutover task executor.
type PITRCutoverTaskExecutor struct {
completed int32
- mysqlutil mysqlutil.Instance
}
// RunOnce will run the PITR cutover task executor once.
diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.go
index cd19239533..94f5698ccf 100644
--- a/server/task_executor_pitr_restore.go
+++ b/server/task_executor_pitr_restore.go
@@ -14,22 +14,18 @@ import (
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/mysql"
- "github.com/bytebase/bytebase/resources/mysqlutil"
"github.com/bytebase/bytebase/store"
"go.uber.org/zap"
)
// NewPITRRestoreTaskExecutor creates a PITR restore task executor.
-func NewPITRRestoreTaskExecutor(instance mysqlutil.Instance) TaskExecutor {
- return &PITRRestoreTaskExecutor{
- mysqlutil: instance,
- }
+func NewPITRRestoreTaskExecutor() TaskExecutor {
+ return &PITRRestoreTaskExecutor{}
}
// PITRRestoreTaskExecutor is the PITR restore task executor.
type PITRRestoreTaskExecutor struct {
completed int32
- mysqlutil mysqlutil.Instance
}
// RunOnce will run the PITR restore task executor once.
@@ -70,7 +66,7 @@ func (*PITRRestoreTaskExecutor) GetProgress() api.Progress {
return api.Progress{}
}
-func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Task, store *store.Store, driver db.Driver, dataDir string, targetTs int64, mode common.ReleaseMode) error {
+func (*PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Task, store *store.Store, driver db.Driver, dataDir string, targetTs int64, mode common.ReleaseMode) error {
instance := task.Instance
database := task.Database
@@ -96,7 +92,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *ap
log.Error("Failed to cast driver to mysql.Driver")
return fmt.Errorf("[internal] cast driver to mysql.Driver failed")
}
- mysqlDriver.SetUpForPITR(exec.mysqlutil, binlogDir)
+ mysqlDriver.SetUpForPITR(binlogDir)
log.Debug("Downloading all binlog files")
if err := mysqlDriver.FetchAllBinlogFiles(ctx, true /* downloadLatestBinlogFile */); err != nil {
diff --git a/tests/mysql.go b/tests/mysql.go
index ef7805dfed..853f5282bd 100644
--- a/tests/mysql.go
+++ b/tests/mysql.go
@@ -31,11 +31,17 @@ func connectTestMySQL(port int, database string) (*sql.DB, error) {
}
func getTestMySQLDriver(ctx context.Context, port, database string) (db.Driver, error) {
+ return getTestMySQLDriverWithResourceDir(ctx, port, database, "" /*resourceDir*/)
+}
+
+func getTestMySQLDriverWithResourceDir(ctx context.Context, port, database, resourceDir string) (db.Driver, error) {
connCfg := getMySQLConnectionConfig(port, database)
return db.Open(
ctx,
db.MySQL,
- db.DriverConfig{},
+ db.DriverConfig{
+ ResourceDir: resourceDir,
+ },
connCfg,
db.ConnectionContext{},
)
diff --git a/tests/mysql_test.go b/tests/mysql_test.go
index e3a5c6a1a1..01aad27ee9 100644
--- a/tests/mysql_test.go
+++ b/tests/mysql_test.go
@@ -134,17 +134,18 @@ func TestFetchBinlogFiles(t *testing.T) {
a.NoError(err)
defer db.Close()
- driver, err := getTestMySQLDriver(ctx, strconv.Itoa(port), "")
+ utilDir := t.TempDir()
+ err = mysqlutil.Install(utilDir)
+ a.NoError(err)
+
+ driver, err := getTestMySQLDriverWithResourceDir(ctx, strconv.Itoa(port), "", utilDir)
a.NoError(err)
defer driver.Close(ctx)
mysqlDriver, ok := driver.(*pluginmysql.Driver)
a.Equal(true, ok)
- utilDir := t.TempDir()
- utilInstance, err := mysqlutil.Install(utilDir)
binlogDir := t.TempDir()
- mysqlDriver.SetUpForPITR(*utilInstance, binlogDir)
- a.NoError(err)
+ mysqlDriver.SetUpForPITR(binlogDir)
// init schema
_, err = db.ExecContext(ctx, `