Skip to content

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

Make backup operation to be asynchronous using tasks.

spinningbotddb72be9f89d
diff --git a/api/backup.go b/api/backup.go
index 9f8a1fd7e4..8a6258ed3e 100644
--- a/api/backup.go
+++ b/api/backup.go
@@ -5,6 +5,16 @@ import (
"encoding/json"
)
+// BackupStatus is the status of a backup.
+type BackupStatus string
+
+const (
+ // BackupStatusPendingCreate is the status for PENDING_CREATE.
+ BackupStatusPendingCreate BackupStatus = "PENDING_CREATE"
+ // BackupStatusDone is the status for DONE.
+ BackupStatusDone BackupStatus = "DONE"
+)
+
type Backup struct {
ID int `jsonapi:"primary,table"`
diff --git a/api/task.go b/api/task.go
index ec4301d7e7..0b8a6f88d8 100644
--- a/api/task.go
+++ b/api/task.go
@@ -45,6 +45,7 @@ const (
TaskGeneral TaskType = "bb.task.general"
TaskDatabaseCreate TaskType = "bb.task.database.create"
TaskDatabaseSchemaUpdate TaskType = "bb.task.database.schema.update"
+ TaskDatabaseBackup TaskType = "bb.task.database.backup"
)
// These payload types are only used when marshalling to the json format for saving into the database.
@@ -57,12 +58,18 @@ type TaskDatabaseCreatePayload struct {
Collation string `json:"collation,omitempty"`
}
+// TaskDatabaseSchemaUpdatePayload is the task payload for database schema update.
type TaskDatabaseSchemaUpdatePayload struct {
Statement string `json:"statement,omitempty"`
RollbackStatement string `json:"rollbackStatement,omitempty"`
VCSPushEvent *common.VCSPushEvent `json:"pushEvent,omitempty"`
}
+// TaskDatabaseBackupPayload is the task payload for database backup.
+type TaskDatabaseBackupPayload struct {
+ BackupID int `jsonapi:"primary,table"`
+}
+
type Task struct {
ID int `jsonapi:"primary,task"`
diff --git a/server/database.go b/server/database.go
index 113e8babc3..eb9775ce80 100644
--- a/server/database.go
+++ b/server/database.go
@@ -2,15 +2,13 @@ package server
import (
"context"
+ "encoding/json"
"fmt"
"net/http"
- "os"
"strconv"
"github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/bin/bb/connect"
- "github.com/bytebase/bytebase/bin/bb/dump/mysqldump"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
)
@@ -290,8 +288,45 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
}
backup.Database = database
- if err := s.BackupDatabase(backup); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create backup %q.", backup.Name)).SetInternal(err)
+ payload := api.TaskDatabaseBackupPayload{
+ BackupID: backup.ID,
+ }
+ bytes, err := json.Marshal(payload)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create task payload").SetInternal(err)
+ }
+
+ createdPipeline, err := s.PipelineService.CreatePipeline(context.Background(), &api.PipelineCreate{
+ Name: fmt.Sprintf("backup-pipeline-%s", backup.Name),
+ CreatorId: backupCreate.CreatorId,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create pipeline").SetInternal(err)
+ }
+
+ createdStage, err := s.StageService.CreateStage(context.Background(), &api.StageCreate{
+ Name: fmt.Sprintf("backup-stage-%s", backup.Name),
+ EnvironmentId: database.Instance.EnvironmentId,
+ PipelineId: createdPipeline.ID,
+ CreatorId: backupCreate.CreatorId,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create stage").SetInternal(err)
+ }
+
+ _, err = s.TaskService.CreateTask(context.Background(), &api.TaskCreate{
+ Name: fmt.Sprintf("backup-%s-task", backup.Name),
+ PipelineId: createdPipeline.ID,
+ StageId: createdStage.ID,
+ InstanceId: database.InstanceId,
+ DatabaseId: &database.ID,
+ Status: api.TaskPending,
+ Type: api.TaskDatabaseBackup,
+ Payload: string(bytes),
+ CreatorId: backupCreate.CreatorId,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create task").SetInternal(err)
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
@@ -393,26 +428,3 @@ func (s *Server) ComposeDatabaseRelationship(ctx context.Context, database *api.
return nil
}
-
-// BackupDatabase will take a backup of a database.
-func (s *Server) BackupDatabase(backup *api.Backup) error {
- instance := backup.Database.Instance
- conn, err := connect.NewMysql(instance.Username, instance.Password, instance.Host, instance.Port, backup.Database.Name, nil /* tlsConfig */)
- if err != nil {
- return fmt.Errorf("connect.NewMysql(%q, %q, %q, %q) got error: %v", instance.Username, instance.Password, instance.Host, instance.Port, err)
- }
- defer conn.Close()
- dp := mysqldump.New(conn)
-
- f, err := os.Create(backup.Path)
- if err != nil {
- return fmt.Errorf("failed to open backup path: %s", backup.Path)
- }
- defer f.Close()
-
- if err := dp.Dump(backup.Database.Name, f, false /* schemaOnly */); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/server/server.go b/server/server.go
index 49f73f7312..ed3f195e47 100644
--- a/server/server.go
+++ b/server/server.go
@@ -102,9 +102,11 @@ func NewServer(logger *zap.Logger, version string, host string, port int, mode s
defaultExecutor := NewDefaultTaskExecutor(logger)
createDBExecutor := NewDatabaseCreateTaskExecutor(logger)
sqlExecutor := NewSchemaUpdateTaskExecutor(logger)
+ backupDBExecutor := NewDatabaseBackupTaskExecutor(logger)
scheduler.Register(string(api.TaskGeneral), defaultExecutor)
scheduler.Register(string(api.TaskDatabaseCreate), createDBExecutor)
scheduler.Register(string(api.TaskDatabaseSchemaUpdate), sqlExecutor)
+ scheduler.Register(string(api.TaskDatabaseBackup), backupDBExecutor)
s.TaskScheduler = scheduler
schemaSyncer := NewSchemaSyncer(logger, s)
diff --git a/server/task.go b/server/task.go
index 531df11537..857db52eae 100644
--- a/server/task.go
+++ b/server/task.go
@@ -188,99 +188,102 @@ func (s *Server) ChangeTaskStatusWithPatch(ctx context.Context, task *api.Task,
return nil, fmt.Errorf("failed to change task %v(%v) status: %w", task.ID, task.Name, err)
}
+ // Update the issue and activity for database create and database schema update tasks.
// TODO(tianzhou): This indiciates a coupling that pipeline belongs to an issue.
// A better way is to implement this as an onTaskStatusChange callback
- issueFind := &api.IssueFind{
- PipelineId: &task.PipelineId,
- }
- issue, err := s.IssueService.FindIssue(ctx, issueFind)
- if err != nil {
- return nil, fmt.Errorf("failed to fetch containing issue for creating activity after changing the task status: %v, err: %w", task.Name, err)
- }
-
- // Create an activity
- payload, err := json.Marshal(api.ActivityPipelineTaskStatusUpdatePayload{
- TaskId: task.ID,
- OldStatus: task.Status,
- NewStatus: updatedTask.Status,
- IssueName: issue.Name,
- TaskName: task.Name,
- })
- if err != nil {
- return nil, fmt.Errorf("failed to marshal activity after changing the task status: %v, err: %w", task.Name, err)
- }
-
- level := api.ACTIVITY_INFO
- if updatedTask.Status == api.TaskFailed {
- level = api.ACTIVITY_ERROR
- }
- activityCreate := &api.ActivityCreate{
- CreatorId: taskStatusPatch.UpdaterId,
- ContainerId: issue.ID,
- Type: api.ActivityPipelineTaskStatusUpdate,
- Comment: taskStatusPatch.Comment,
- Level: level,
- Payload: string(payload),
- }
- activity, err := s.ActivityService.CreateActivity(ctx, activityCreate)
- if err != nil {
- return nil, fmt.Errorf("failed to create activity after changing the task status: %v, err: %w", task.Name, err)
- }
-
- // To reduce noise, for now we only post status update to inbox upon task failure.
- if updatedTask.Status == api.TaskFailed {
- if err := s.PostInboxIssueActivity(context.Background(), issue, activity.ID); err != nil {
- return nil, err
+ if updatedTask.Type == api.TaskDatabaseCreate || updatedTask.Type == api.TaskDatabaseSchemaUpdate {
+ issueFind := &api.IssueFind{
+ PipelineId: &task.PipelineId,
+ }
+ issue, err := s.IssueService.FindIssue(ctx, issueFind)
+ if err != nil {
+ return nil, fmt.Errorf("failed to fetch containing issue for creating activity after changing the task status: %v, err: %w", task.Name, err)
}
- }
- // Schedule the task if it's being just approved
- if task.Status == api.TaskPendingApproval && updatedTask.Status == api.TaskPending {
- updatedTask, err = s.TaskScheduler.Schedule(ctx, updatedTask)
+ // Create an activity
+ payload, err := json.Marshal(api.ActivityPipelineTaskStatusUpdatePayload{
+ TaskId: task.ID,
+ OldStatus: task.Status,
+ NewStatus: updatedTask.Status,
+ IssueName: issue.Name,
+ TaskName: task.Name,
+ })
if err != nil {
- return nil, fmt.Errorf("failed to schedule task \"%v\" after approval", updatedTask.Name)
+ return nil, fmt.Errorf("failed to marshal activity after changing the task status: %v, err: %w", task.Name, err)
}
- }
- // If create database task completes, then we will create a database entry
- if updatedTask.Type == api.TaskDatabaseCreate && updatedTask.Status == api.TaskDone {
- payload := &api.TaskDatabaseCreatePayload{}
- if err := json.Unmarshal([]byte(updatedTask.Payload), payload); err != nil {
- return nil, fmt.Errorf("invalid create database task payload: %w", err)
+ level := api.ACTIVITY_INFO
+ if updatedTask.Status == api.TaskFailed {
+ level = api.ACTIVITY_ERROR
}
- databaseCreate := &api.DatabaseCreate{
- CreatorId: taskStatusPatch.UpdaterId,
- ProjectId: issue.ProjectId,
- InstanceId: task.InstanceId,
- Name: payload.DatabaseName,
- CharacterSet: payload.CharacterSet,
- Collation: payload.Collation,
+ activityCreate := &api.ActivityCreate{
+ CreatorId: taskStatusPatch.UpdaterId,
+ ContainerId: issue.ID,
+ Type: api.ActivityPipelineTaskStatusUpdate,
+ Comment: taskStatusPatch.Comment,
+ Level: level,
+ Payload: string(payload),
}
- _, err := s.DatabaseService.CreateDatabase(ctx, databaseCreate)
+ activity, err := s.ActivityService.CreateActivity(ctx, activityCreate)
if err != nil {
- // Just emits an error instead of failing, since we have another periodic job to sync db info.
- // Though the db will be assigned to the default project instead of the desired project in that case.
- s.l.Error("failed to record database after creating database",
- zap.String("database_name", payload.DatabaseName),
- zap.Int("instance_id", task.InstanceId),
- zap.Error(err),
- )
+ return nil, fmt.Errorf("failed to create activity after changing the task status: %v, err: %w", task.Name, err)
}
- }
- // If this is the last task in the pipeline and just completed, and the assignee is system bot,
- // then we mark the issue as DONE.
- if updatedTask.Status == "DONE" && issue.AssigneeId == api.SYSTEM_BOT_ID {
- issue.Pipeline, err = s.ComposePipelineById(ctx, issue.PipelineId)
- if err != nil {
- return nil, fmt.Errorf("failed to fetch pipeline to mark issue %v as DONE after completing task %v", issue.Name, updatedTask.Name)
+ // To reduce noise, for now we only post status update to inbox upon task failure.
+ if updatedTask.Status == api.TaskFailed {
+ if err := s.PostInboxIssueActivity(context.Background(), issue, activity.ID); err != nil {
+ return nil, err
+ }
+ }
+
+ // Schedule the task if it's being just approved
+ if task.Status == api.TaskPendingApproval && updatedTask.Status == api.TaskPending {
+ updatedTask, err = s.TaskScheduler.Schedule(ctx, updatedTask)
+ if err != nil {
+ return nil, fmt.Errorf("failed to schedule task \"%v\" after approval", updatedTask.Name)
+ }
}
- lastStage := issue.Pipeline.StageList[len(issue.Pipeline.StageList)-1]
- if lastStage.TaskList[len(lastStage.TaskList)-1].ID == task.ID {
- _, err := s.ChangeIssueStatus(ctx, issue, api.Issue_Done, taskStatusPatch.UpdaterId, "")
+ // If create database task completes, then we will create a database entry
+ if updatedTask.Type == api.TaskDatabaseCreate && updatedTask.Status == api.TaskDone {
+ payload := &api.TaskDatabaseCreatePayload{}
+ if err := json.Unmarshal([]byte(updatedTask.Payload), payload); err != nil {
+ return nil, fmt.Errorf("invalid create database task payload: %w", err)
+ }
+ databaseCreate := &api.DatabaseCreate{
+ CreatorId: taskStatusPatch.UpdaterId,
+ ProjectId: issue.ProjectId,
+ InstanceId: task.InstanceId,
+ Name: payload.DatabaseName,
+ CharacterSet: payload.CharacterSet,
+ Collation: payload.Collation,
+ }
+ _, err := s.DatabaseService.CreateDatabase(ctx, databaseCreate)
+ if err != nil {
+ // Just emits an error instead of failing, since we have another periodic job to sync db info.
+ // Though the db will be assigned to the default project instead of the desired project in that case.
+ s.l.Error("failed to record database after creating database",
+ zap.String("database_name", payload.DatabaseName),
+ zap.Int("instance_id", task.InstanceId),
+ zap.Error(err),
+ )
+ }
+ }
+
+ // If this is the last task in the pipeline and just completed, and the assignee is system bot,
+ // then we mark the issue as DONE.
+ if updatedTask.Status == "DONE" && issue.AssigneeId == api.SYSTEM_BOT_ID {
+ issue.Pipeline, err = s.ComposePipelineById(ctx, issue.PipelineId)
if err != nil {
- return nil, fmt.Errorf("failed to mark issue %v as DONE after completing task %v", issue.Name, updatedTask.Name)
+ return nil, fmt.Errorf("failed to fetch pipeline to mark issue %v as DONE after completing task %v", issue.Name, updatedTask.Name)
+ }
+
+ lastStage := issue.Pipeline.StageList[len(issue.Pipeline.StageList)-1]
+ if lastStage.TaskList[len(lastStage.TaskList)-1].ID == task.ID {
+ _, err := s.ChangeIssueStatus(ctx, issue, api.Issue_Done, taskStatusPatch.UpdaterId, "")
+ if err != nil {
+ return nil, fmt.Errorf("failed to mark issue %v as DONE after completing task %v", issue.Name, updatedTask.Name)
+ }
}
}
}
diff --git a/server/task_executor_database_backup.go b/server/task_executor_database_backup.go
new file mode 100644
index 0000000000..e14769e48c
--- /dev/null
+++ b/server/task_executor_database_backup.go
@@ -0,0 +1,108 @@
+package server
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/bin/bb/connect"
+ "github.com/bytebase/bytebase/bin/bb/dump/mysqldump"
+ "go.uber.org/zap"
+)
+
+// NewDatabaseBackupTaskExecutor creates a new database backup task executor.
+func NewDatabaseBackupTaskExecutor(logger *zap.Logger) TaskExecutor {
+ return &DatabaseBackupTaskExecutor{
+ l: logger,
+ }
+}
+
+// DatabaseBackupTaskExecutor is the task executor for database backup.
+type DatabaseBackupTaskExecutor struct {
+ l *zap.Logger
+}
+
+// RunOnce will run database backup once.
+func (exec *DatabaseBackupTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, detail string, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ panicErr, ok := r.(error)
+ if !ok {
+ panicErr = fmt.Errorf("%v", r)
+ }
+ exec.l.Error("DatabaseBackupTaskExecutor PANIC RECOVER", zap.Error(panicErr))
+ terminated = true
+ err = fmt.Errorf("encounter internal error when backing database")
+ }
+ }()
+ // Close the pipeline when the backup task is completed regardless its status.
+ defer func() {
+ status := api.Pipeline_Done
+ pipelinePatch := &api.PipelinePatch{
+ ID: task.PipelineId,
+ UpdaterId: api.SYSTEM_BOT_ID,
+ Status: &status,
+ }
+ if _, err := server.PipelineService.PatchPipeline(context.Background(), pipelinePatch); err != nil {
+ err = fmt.Errorf("failed to update pipeline status: %w", err)
+ }
+ }()
+
+ payload := &api.TaskDatabaseBackupPayload{}
+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {
+ return true, "", fmt.Errorf("invalid database backup payload: %w", err)
+ }
+
+ if err := server.ComposeTaskRelationship(ctx, task); err != nil {
+ return true, "", err
+ }
+
+ backup, err := server.BackupService.FindBackup(ctx, &api.BackupFind{ID: &payload.BackupID})
+ if err != nil {
+ return true, "", fmt.Errorf("failed to find backup: %w", err)
+ }
+ exec.l.Debug("Start database backup...",
+ zap.String("instance", task.Instance.Name),
+ zap.String("database", task.Database.Name),
+ zap.String("backup", backup.Name),
+ )
+
+ // TODO(spinningbot): handle backup failure.
+ if err := backupDatabase(task.Instance, task.Database, backup); err != nil {
+ return true, "", err
+ }
+
+ if _, err = server.BackupService.PatchBackup(ctx, &api.BackupPatch{
+ ID: backup.ID,
+ Status: string(api.BackupStatusDone),
+ UpdaterId: api.SYSTEM_BOT_ID,
+ }); err != nil {
+ return true, "", fmt.Errorf("failed to patch backup: %w", err)
+ }
+
+ return true, fmt.Sprintf("Backup database '%s'", task.Database.Name), nil
+}
+
+// backupDatabase will take a backup of a database.
+func backupDatabase(instance *api.Instance, database *api.Database, backup *api.Backup) error {
+ conn, err := connect.NewMysql(instance.Username, instance.Password, instance.Host, instance.Port, database.Name, nil /* tlsConfig */)
+ if err != nil {
+ return fmt.Errorf("connect.NewMysql(%q, %q, %q, %q) got error: %v", instance.Username, instance.Password, instance.Host, instance.Port, err)
+ }
+ defer conn.Close()
+ dp := mysqldump.New(conn)
+
+ f, err := os.Create(backup.Path)
+ if err != nil {
+ return fmt.Errorf("failed to open backup path: %s", backup.Path)
+ }
+ defer f.Close()
+
+ if err := dp.Dump(database.Name, f, false /* schemaOnly */); err != nil {
+ return err
+ }
+
+ return nil
+}