Skip to content

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

feat(api): implement the backup part of the database service (#4730)

h3n4l765ceba4a303
diff --git a/backend/api/v1/common.go b/backend/api/v1/common.go
index a0393692d0..bc9278025e 100644
--- a/backend/api/v1/common.go
+++ b/backend/api/v1/common.go
@@ -23,6 +23,7 @@ const (
userNamePrefix = "users/"
identityProviderNamePrefix = "idps/"
settingNamePrefix = "settings/"
+ backupPrefix = "backups/"
deploymentConfigSuffix = "/deploymentConfig"
backupSettingSuffix = "/backupSetting"
@@ -95,6 +96,14 @@ func getEnvironmentInstanceDatabaseID(name string) (string, string, string, erro
return tokens[0], tokens[1], tokens[2], nil
}
+func getEnvironmentIDInstanceDatabaseIDBackupName(name string) (string, string, string, string, error) {
+ tokens, err := getNameParentTokens(name, environmentNamePrefix, instanceNamePrefix, databaseIDPrefix, backupPrefix)
+ if err != nil {
+ return "", "", "", "", err
+ }
+ return tokens[0], tokens[1], tokens[2], tokens[3], nil
+}
+
func getUserID(name string) (int, error) {
tokens, err := getNameParentTokens(name, userNamePrefix)
if err != nil {
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index 3234b7d670..b1561a9637 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -19,6 +19,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
api "github.com/bytebase/bytebase/backend/legacyapi"
+ "github.com/bytebase/bytebase/backend/runner/backuprun"
"github.com/bytebase/bytebase/backend/store"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
@@ -27,13 +28,15 @@ import (
// DatabaseService implements the database service.
type DatabaseService struct {
v1pb.UnimplementedDatabaseServiceServer
- store *store.Store
+ store *store.Store
+ BackupRunner *backuprun.Runner
}
// NewDatabaseService creates a new DatabaseService.
-func NewDatabaseService(store *store.Store) *DatabaseService {
+func NewDatabaseService(store *store.Store, br *backuprun.Runner) *DatabaseService {
return &DatabaseService{
- store: store,
+ store: store,
+ BackupRunner: br,
}
}
@@ -372,6 +375,146 @@ func (s *DatabaseService) UpdateBackupSetting(ctx context.Context, request *v1pb
return convertToBackupSetting(backupSetting, environment.ResourceID, instance.ResourceID, database.DatabaseName)
}
+// ListBackup lists the backups of a database.
+func (s *DatabaseService) ListBackup(ctx context.Context, request *v1pb.ListBackupRequest) (*v1pb.ListBackupResponse, error) {
+ environmentID, instanceID, databaseName, err := getEnvironmentInstanceDatabaseID(request.Parent)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{
+ ResourceID: &environmentID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if environment == nil {
+ return nil, status.Errorf(codes.NotFound, "environment %q not found", environmentID)
+ }
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
+ EnvironmentID: &environmentID,
+ ResourceID: &instanceID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if instance == nil {
+ return nil, status.Errorf(codes.NotFound, "instance %q not found", instanceID)
+ }
+ database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
+ EnvironmentID: &environmentID,
+ InstanceID: &instanceID,
+ DatabaseName: &databaseName,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if database == nil {
+ return nil, status.Errorf(codes.NotFound, "database %q not found", databaseName)
+ }
+
+ existedBackupList, err := s.store.ListBackupV2(ctx, &store.FindBackupMessage{
+ DatabaseUID: database.UID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ var backupList []*v1pb.Backup
+ for _, existedBackup := range existedBackupList {
+ backupList = append(backupList, convertToBackup(existedBackup, environment.ResourceID, instance.ResourceID, database.DatabaseName))
+ }
+ return &v1pb.ListBackupResponse{
+ Backups: backupList,
+ }, nil
+}
+
+// CreateBackup creates a backup of a database.
+func (s *DatabaseService) CreateBackup(ctx context.Context, request *v1pb.CreateBackupRequest) (*v1pb.Backup, error) {
+ environmentID, instanceID, databaseName, backupName, err := getEnvironmentIDInstanceDatabaseIDBackupName(request.Backup.Name)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{
+ ResourceID: &environmentID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if environment == nil {
+ return nil, status.Errorf(codes.NotFound, "environment %q not found", environmentID)
+ }
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
+ EnvironmentID: &environmentID,
+ ResourceID: &instanceID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if instance == nil {
+ return nil, status.Errorf(codes.NotFound, "instance %q not found", instanceID)
+ }
+ database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
+ EnvironmentID: &environmentID,
+ InstanceID: &instanceID,
+ DatabaseName: &databaseName,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if database == nil {
+ return nil, status.Errorf(codes.NotFound, "database %q not found", databaseName)
+ }
+
+ existedBackupList, err := s.store.ListBackupV2(ctx, &store.FindBackupMessage{
+ DatabaseUID: database.UID,
+ Name: &backupName,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if len(existedBackupList) > 0 {
+ return nil, status.Errorf(codes.AlreadyExists, "backup %q in database %q already exists", backupName, databaseName)
+ }
+
+ creatorID := ctx.Value(common.PrincipalIDContextKey).(int)
+ backup, err := s.BackupRunner.ScheduleBackupTask(ctx, database, backupName, api.BackupTypeManual, creatorID)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ return convertToBackup(backup, environmentID, instanceID, databaseName), nil
+}
+
+func convertToBackup(backup *store.BackupMessage, enviromentID string, instanceID string, databaseName string) *v1pb.Backup {
+ createTime := timestamppb.New(time.Unix(backup.CreatedTs, 0))
+ updateTime := timestamppb.New(time.Unix(backup.UpdatedTs, 0))
+ backupState := v1pb.Backup_BACKUP_STATE_UNSPECIFIED
+ switch backup.Status {
+ case api.BackupStatusPendingCreate:
+ backupState = v1pb.Backup_PENDING_CREATE
+ case api.BackupStatusDone:
+ backupState = v1pb.Backup_DONE
+ case api.BackupStatusFailed:
+ backupState = v1pb.Backup_FAILED
+ }
+ backupType := v1pb.Backup_BACKUP_TYPE_UNSPECIFIED
+ switch backup.BackupType {
+ case api.BackupTypeManual:
+ backupType = v1pb.Backup_MANUAL
+ case api.BackupTypeAutomatic:
+ backupType = v1pb.Backup_AUTOMATIC
+ case api.BackupTypePITR:
+ backupType = v1pb.Backup_PITR
+ }
+ return &v1pb.Backup{
+ Name: fmt.Sprintf("%s%s/%s%s/%s%s/%s", environmentNamePrefix, enviromentID, instanceNamePrefix, instanceID, databaseIDPrefix, databaseName, backup.Name),
+ CreateTime: createTime,
+ UpdateTime: updateTime,
+ State: backupState,
+ BackupType: backupType,
+ Comment: backup.Comment,
+ }
+}
+
func convertToDatabase(database *store.DatabaseMessage) *v1pb.Database {
syncState := v1pb.State_STATE_UNSPECIFIED
switch database.SyncState {
@@ -515,7 +658,7 @@ func getDefaultBackupSetting(environmentID, instanceID, databaseName string) *v1
log.Warn("failed to convert period ts to duration", zap.Error(err))
}
return &v1pb.BackupSetting{
- Name: fmt.Sprintf("%s%s%s%s%s%s%s", environmentNamePrefix, environmentID, instanceNamePrefix, instanceID, databaseIDPrefix, databaseName, backupSettingSuffix),
+ Name: fmt.Sprintf("%s%s/%s%s/%s%s/%s", environmentNamePrefix, environmentID, instanceNamePrefix, instanceID, databaseIDPrefix, databaseName, backupSettingSuffix),
BackupRetainDuration: sevenDays,
CronSchedule: "", /* Disable automatic backup */
HookUrl: "",
diff --git a/backend/runner/backuprun/runner.go b/backend/runner/backuprun/runner.go
index a2ba28d0a4..4a4484a96c 100644
--- a/backend/runner/backuprun/runner.go
+++ b/backend/runner/backuprun/runner.go
@@ -398,7 +398,7 @@ func (r *Runner) startAutoBackups(ctx context.Context) {
}
// ScheduleBackupTask schedules a backup task.
-func (r *Runner) ScheduleBackupTask(ctx context.Context, database *store.DatabaseMessage, backupName string, backupType api.BackupType, creatorID int) (*api.Backup, error) {
+func (r *Runner) ScheduleBackupTask(ctx context.Context, database *store.DatabaseMessage, backupName string, backupType api.BackupType, creatorID int) (*store.BackupMessage, error) {
instance, err := r.store.GetInstanceV2(ctx, &store.FindInstanceMessage{EnvironmentID: &database.EnvironmentID, ResourceID: &database.InstanceID})
if err != nil {
return nil, err
@@ -431,17 +431,16 @@ func (r *Runner) ScheduleBackupTask(ctx context.Context, database *store.Databas
if err := createBackupDirectory(r.profile.DataDir, database.UID); err != nil {
return nil, errors.Wrap(err, "failed to create backup directory")
}
- backupCreate := &api.BackupCreate{
- CreatorID: creatorID,
- DatabaseID: database.UID,
+
+ backupNew, err := r.store.CreateBackupV2(ctx, &store.BackupMessage{
Name: backupName,
+ Status: api.BackupStatusPendingCreate,
+ BackupType: backupType,
+ Comment: "",
StorageBackend: r.profile.BackupStorageBackend,
- Type: backupType,
- Path: path,
MigrationHistoryVersion: migrationHistoryVersion,
- }
-
- backupNew, err := r.store.CreateBackup(ctx, backupCreate)
+ Path: path,
+ }, database.UID, creatorID)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
log.Error("Backup already exists for the database", zap.String("backup", backupName), zap.String("database", database.DatabaseName))
@@ -451,7 +450,7 @@ func (r *Runner) ScheduleBackupTask(ctx context.Context, database *store.Databas
}
payload := api.TaskDatabaseBackupPayload{
- BackupID: backupNew.ID,
+ BackupID: backupNew.UID,
}
bytes, err := json.Marshal(payload)
if err != nil {
diff --git a/backend/server/database.go b/backend/server/database.go
index e07b192cc0..698f56909b 100644
--- a/backend/server/database.go
+++ b/backend/server/database.go
@@ -312,7 +312,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, backup); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, backup.ToAPIBackup()); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal create backup response").SetInternal(err)
}
return nil
diff --git a/backend/server/server.go b/backend/server/server.go
index 2b96715bd8..fb2944bba7 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -474,7 +474,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {
v1pb.RegisterEnvironmentServiceServer(s.grpcServer, v1.NewEnvironmentService(s.store, s.licenseService))
v1pb.RegisterInstanceServiceServer(s.grpcServer, v1.NewInstanceService(s.store, s.licenseService, s.secret))
v1pb.RegisterProjectServiceServer(s.grpcServer, v1.NewProjectService(s.store))
- v1pb.RegisterDatabaseServiceServer(s.grpcServer, v1.NewDatabaseService(s.store))
+ v1pb.RegisterDatabaseServiceServer(s.grpcServer, v1.NewDatabaseService(s.store, s.BackupRunner))
v1pb.RegisterInstanceRoleServiceServer(s.grpcServer, v1.NewInstanceRoleService(s.store, s.dbFactory))
v1pb.RegisterOrgPolicyServiceServer(s.grpcServer, v1.NewOrgPolicyService(s.store, s.licenseService))
v1pb.RegisterIdentityProviderServiceServer(s.grpcServer, v1.NewIdentityProviderService(s.store, s.licenseService, &profile))
diff --git a/backend/store/backup.go b/backend/store/backup.go
index ccf6aeccd5..e7592aa708 100644
--- a/backend/store/backup.go
+++ b/backend/store/backup.go
@@ -690,6 +690,63 @@ type FindBackupSettingMessage struct {
InstanceUID *int
}
+// BackupMessage is the message for backup.
+type BackupMessage struct {
+ // Name is the name of the backup.
+ Name string
+ // Status is the status of the backup.
+ Status api.BackupStatus
+ // BackupType is the type of the backup.
+ BackupType api.BackupType
+ // Comment is the comment of the backup.
+ Comment string
+ // Storage Backend is the storage backend of the backup.
+ StorageBackend api.BackupStorageBackend
+ // MigrationHistoryVersion is the migration history version of the database.
+ MigrationHistoryVersion string
+ // Path is the path of the backup file.
+ Path string
+
+ // Output only fields.
+ //
+ // ID is the UID of the backup.
+ UID int
+ // CreatedTs is the timestamp when the backup is created.
+ CreatedTs int64
+ // UpdatedTs is the timestamp when the backup is updated.
+ UpdatedTs int64
+ // RowStatus is the status of the row. ARCHIVED means the backup is deleted.
+ RowStatus api.RowStatus
+ // DatabaseUID is the UID of the database.
+ DatabaseUID int
+}
+
+// ToAPIBackup converts BackupMessage to legacy api Backup.
+func (b *BackupMessage) ToAPIBackup() *api.Backup {
+ return &api.Backup{
+ ID: b.UID,
+ RowStatus: b.RowStatus,
+ CreatedTs: b.CreatedTs,
+ UpdatedTs: b.UpdatedTs,
+ Name: b.Name,
+ Status: b.Status,
+ Type: b.BackupType,
+ StorageBackend: b.StorageBackend,
+ MigrationHistoryVersion: b.MigrationHistoryVersion,
+ Path: b.Path,
+ Comment: b.Comment,
+ DatabaseID: b.DatabaseUID,
+ }
+}
+
+// FindBackupMessage is the message for finding backup.
+type FindBackupMessage struct {
+ // DatabaseUID is the UID of the database.
+ DatabaseUID int
+ // Name is the name of the backup.
+ Name *string
+}
+
// GetBackupSettingV2 retrieves the backup setting for the given database.
func (s *Store) GetBackupSettingV2(ctx context.Context, databaseUID int) (*BackupSettingMessage, error) {
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
@@ -798,6 +855,132 @@ func (s *Store) ListBackupSettingV2(ctx context.Context, find *FindBackupSetting
return backupSettings, nil
}
+// CreateBackupV2 creates a backup for the given database.
+func (s *Store) CreateBackupV2(ctx context.Context, create *BackupMessage, databaseUID int, principalUID int) (*BackupMessage, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to begin transaction")
+ }
+ defer tx.Rollback()
+ query := `
+ INSERT INTO backup (
+ creator_id,
+ updater_id,
+ database_id,
+ name,
+ status,
+ type,
+ storage_backend,
+ migration_history_version,
+ path,
+ comment
+ )
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+ RETURNING id, row_status, name, storage_backend, migration_history_version, path, created_ts, updated_ts, status, type, comment, database_id
+ `
+ var backup BackupMessage
+ if err := tx.QueryRowContext(ctx, query,
+ principalUID,
+ principalUID,
+ databaseUID,
+ create.Name,
+ create.Status,
+ create.BackupType,
+ create.StorageBackend,
+ create.MigrationHistoryVersion,
+ create.Path,
+ create.Comment,
+ ).Scan(
+ &backup.UID,
+ &backup.RowStatus,
+ &backup.Name,
+ &backup.StorageBackend,
+ &backup.MigrationHistoryVersion,
+ &backup.Path,
+ &backup.CreatedTs,
+ &backup.UpdatedTs,
+ &backup.Status,
+ &backup.BackupType,
+ &backup.Comment,
+ &backup.DatabaseUID,
+ ); err != nil {
+ if err == sql.ErrNoRows {
+ return nil, common.FormatDBErrorEmptyRowWithQuery(query)
+ }
+ return nil, FormatError(err)
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, errors.Wrapf(err, "failed to commit transaction")
+ }
+ return &backup, nil
+}
+
+// ListBackupV2 lists the backups for the given database.
+func (s *Store) ListBackupV2(ctx context.Context, find *FindBackupMessage) ([]*BackupMessage, error) {
+ // Build where clause.
+ where, args := []string{"TRUE"}, []interface{}{}
+ where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, find.DatabaseUID)
+ if v := find.Name; v != nil {
+ where, args = append(where, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
+ }
+
+ tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to begin transaction")
+ }
+ defer tx.Rollback()
+
+ rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
+ SELECT
+ id,
+ row_status,
+ name,
+ storage_backend,
+ migration_history_version,
+ path,
+ created_ts,
+ updated_ts,
+ status,
+ type,
+ comment,
+ database_id
+ FROM backup WHERE %s;`, strings.Join(where, " AND ")), args...)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+
+ var backupList []*BackupMessage
+ for rows.Next() {
+ var backup BackupMessage
+ if err := rows.Scan(
+ &backup.UID,
+ &backup.RowStatus,
+ &backup.Name,
+ &backup.StorageBackend,
+ &backup.MigrationHistoryVersion,
+ &backup.Path,
+ &backup.CreatedTs,
+ &backup.UpdatedTs,
+ &backup.Status,
+ &backup.BackupType,
+ &backup.Comment,
+ &backup.DatabaseUID,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+ backupList = append(backupList, &backup)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, errors.Wrapf(err, "failed to commit transaction")
+ }
+ return backupList, nil
+}
+
func (*Store) listBackupSettingImplV2(ctx context.Context, tx *Tx, find *FindBackupSettingMessage) ([]*BackupSettingMessage, error) {
// Build WHERE clause.
where, args := []string{"TRUE"}, []interface{}{}