Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: migrate webhook to rollout API (part1) (#7739)
Danny Xu9f7d4eb35aec
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.goindex e661c9a3b4..20e2935d5e 100644--- a/backend/runner/taskrun/scheduler.go+++ b/backend/runner/taskrun/scheduler.go@@ -324,49 +324,6 @@ func (s *Scheduler) PatchTask(ctx context.Context, task *store.TaskMessage, taskif err := canUpdateTaskStatement(task); err != nil {return err}- // If task created in UI mode in VCS Project, we should give it a new migration version.- // https://linear.app/bytebase/issue/BYT-3311/the-executed-sql-is-not-expected- isUICreatedInVCSProject := false- if issue.Project.Workflow == api.VCSWorkflow {- switch task.Type {- case api.TaskDatabaseSchemaUpdate:- var payload api.TaskDatabaseSchemaUpdatePayload- if err := json.Unmarshal([]byte(task.Payload), &payload); err != nil {- return errors.Wrapf(err, "failed to unmarshal task payload")- }- if payload.VCSPushEvent == nil {- isUICreatedInVCSProject = true- }- case api.TaskDatabaseSchemaUpdateSDL:- var payload api.TaskDatabaseSchemaUpdateSDLPayload- if err := json.Unmarshal([]byte(task.Payload), &payload); err != nil {- return errors.Wrapf(err, "failed to unmarshal task payload")- }- if payload.VCSPushEvent == nil {- isUICreatedInVCSProject = true- }- case api.TaskDatabaseSchemaUpdateGhostSync:- var payload api.TaskDatabaseSchemaUpdateGhostSyncPayload- if err := json.Unmarshal([]byte(task.Payload), &payload); err != nil {- return errors.Wrapf(err, "failed to unmarshal task payload")- }- if payload.VCSPushEvent == nil {- isUICreatedInVCSProject = true- }- case api.TaskDatabaseDataUpdate:- var payload api.TaskDatabaseDataUpdatePayload- if err := json.Unmarshal([]byte(task.Payload), &payload); err != nil {- return errors.Wrapf(err, "failed to unmarshal task payload")- }- if payload.VCSPushEvent == nil {- isUICreatedInVCSProject = true- }- }- }- if issue.Project.Workflow == api.UIWorkflow || isUICreatedInVCSProject {- schemaVersion := common.DefaultMigrationVersion()- taskPatch.SchemaVersion = &schemaVersion- }}// Reset because we are trying to builddiff --git a/backend/server/task.go b/backend/server/task.goindex ba7533be12..7603bfb45e 100644--- a/backend/server/task.go+++ b/backend/server/task.go@@ -115,6 +115,10 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {if err := jsonapi.UnmarshalPayload(c.Request().Body, taskPatch); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed update task request").SetInternal(err)}+ if taskPatch.SheetID != nil {+ schemaVersion := common.DefaultMigrationVersion()+ taskPatch.SchemaVersion = &schemaVersion+ }task, err := s.store.GetTaskV2ByID(ctx, taskID)if err != nil {diff --git a/backend/server/webhook.go b/backend/server/webhook.goindex a7e18ed1da..ffd3576216 100644--- a/backend/server/webhook.go+++ b/backend/server/webhook.go@@ -16,6 +16,7 @@ import ("path/filepath""regexp""sort"+ "strconv""strings""sync"@@ -45,6 +46,7 @@ import ("github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/utils"storepb "github.com/bytebase/bytebase/proto/generated-go/store"+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")const (@@ -1456,7 +1458,7 @@ func (s *Server) processFilesInProject(ctx context.Context, pushEvent vcs.PushEvdatabaseName := fileInfo.migrationInfo.DatabaseissueName := fmt.Sprintf(sdlIssueNameTemplate, databaseName, "Alter schema")issueDescription := fmt.Sprintf("Apply schema diff by file %s", strings.TrimPrefix(fileInfo.item.FileName, repoInfo.repository.BaseDirectory+"/"))- if err := s.createIssueFromMigrationDetailList(ctx, issueName, issueDescription, pushEvent, creatorID, repoInfo.project.UID, migrationDetailListForFile); err != nil {+ if err := s.createIssueFromMigrationDetailList(ctx, repoInfo.project, issueName, issueDescription, pushEvent, creatorID, migrationDetailListForFile); err != nil {return "", false, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, "Failed to create issue").SetInternal(err)}createdIssueList = append(createdIssueList, issueName)@@ -1497,7 +1499,7 @@ func (s *Server) processFilesInProject(ctx context.Context, pushEvent vcs.PushEvdescription := strings.ReplaceAll(fileInfoList[0].migrationInfo.Description, "_", " ")issueName := fmt.Sprintf(issueNameTemplate, databaseName, migrateType, description)issueDescription := fmt.Sprintf("By VCS files:\n\n%s\n", strings.Join(fileNameList, "\n"))- if err := s.createIssueFromMigrationDetailList(ctx, issueName, issueDescription, pushEvent, creatorID, repoInfo.project.UID, migrationDetailList); err != nil {+ if err := s.createIssueFromMigrationDetailList(ctx, repoInfo.project, issueName, issueDescription, pushEvent, creatorID, migrationDetailList); err != nil {return "", len(createdIssueList) != 0, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create issue %s", issueName)).SetInternal(err)}createdIssueList = append(createdIssueList, issueName)@@ -1525,8 +1527,164 @@ func sortFilesBySchemaVersion(fileInfoList []fileInfo) []fileInfo {return ret}-func (s *Server) createIssueFromMigrationDetailList(ctx context.Context, issueName, issueDescription string, pushEvent vcs.PushEvent, creatorID, projectID int, migrationDetailList []*api.MigrationDetail) error {- // TODO(d): use new API.+func (s *Server) createIssueFromMigrationDetailsV2(ctx context.Context, project *store.ProjectMessage, issueName, issueDescription string, pushEvent vcs.PushEvent, creatorID int, migrationDetailList []*api.MigrationDetail) error {+ var steps []*v1pb.Plan_Step+ if len(migrationDetailList) == 1 && migrationDetailList[0].DatabaseID == 0 {+ migrationDetail := migrationDetailList[0]+ deploymentConfig, err := s.store.GetDeploymentConfigV2(ctx, project.UID)+ if err != nil {+ return err+ }+ apiDeploymentConfig, err := deploymentConfig.ToAPIDeploymentConfig()+ if err != nil {+ return err+ }+ deploySchedule, err := api.ValidateAndGetDeploymentSchedule(apiDeploymentConfig.Payload)+ if err != nil {+ return err+ }+ allDatabases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{ProjectID: &project.ResourceID})+ if err != nil {+ return err+ }+ matrix, err := utils.GetDatabaseMatrixFromDeploymentSchedule(deploySchedule, allDatabases)+ if err != nil {+ return err+ }+ changeType := getChangeType(migrationDetail.MigrationType)+ for _, stage := range matrix {+ step := &v1pb.Plan_Step{}+ for _, database := range stage {+ step.Specs = append(step.Specs, &v1pb.Plan_Spec{+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{+ Type: changeType,+ Target: fmt.Sprintf("instances/%s/databases/%s", database.InstanceID, database.DatabaseName),+ Sheet: fmt.Sprintf("projects/%s/sheets/%d", project.ResourceID, migrationDetail.SheetID),+ SchemaVersion: migrationDetail.SchemaVersion,+ },+ },+ })+ }+ steps = append(steps, step)+ }+ } else {+ var specs []*v1pb.Plan_Spec+ for _, migrationDetail := range migrationDetailList {+ changeType := getChangeType(migrationDetail.MigrationType)+ var target string+ if migrationDetail.DatabaseID != 0 {+ database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: &migrationDetail.DatabaseID})+ if err != nil {+ return err+ }+ if database == nil {+ return errors.Errorf("database %d not found", migrationDetail.DatabaseID)+ }+ target = fmt.Sprintf("instances/%s/databases/%s", database.InstanceID, database.DatabaseName)+ } else {+ // TODO(d): should never reach this.+ return errors.Errorf("tenant database is not supported yet")+ }+ specs = append(specs, &v1pb.Plan_Spec{+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{+ Type: changeType,+ Target: target,+ Sheet: fmt.Sprintf("projects/%s/sheets/%d", project.ResourceID, migrationDetail.SheetID),+ SchemaVersion: migrationDetail.SchemaVersion,+ },+ },+ })+ }+ steps = []*v1pb.Plan_Step{+ {+ Specs: specs,+ },+ }+ }+ childCtx := context.WithValue(ctx, common.PrincipalIDContextKey, creatorID)+ plan, err := s.rolloutService.CreatePlan(childCtx, &v1pb.CreatePlanRequest{+ Parent: fmt.Sprintf("projects/%s", project.ResourceID),+ Plan: &v1pb.Plan{+ Title: issueName,+ Steps: steps,+ },+ })+ if err != nil {+ return errors.Wrapf(err, "failed to create plan for sample project")+ }+ rollout, err := s.rolloutService.CreateRollout(childCtx, &v1pb.CreateRolloutRequest{+ Parent: fmt.Sprintf("projects/%s", project.ResourceID),+ Plan: plan.Name,+ })+ if err != nil {+ return errors.Wrapf(err, "failed to create rollout for sample project")+ }+ issue, err := s.issueService.CreateIssue(childCtx, &v1pb.CreateIssueRequest{+ Parent: fmt.Sprintf("projects/%s", project.ResourceID),+ Issue: &v1pb.Issue{+ Title: issueName,+ Description: issueDescription,+ Type: v1pb.Issue_DATABASE_CHANGE,+ Assignee: fmt.Sprintf("users/%s", api.SystemBotEmail),+ Plan: plan.Name,+ Rollout: rollout.Name,+ },+ })+ if err != nil {+ return errors.Wrapf(err, "failed to create issue for sample project")+ }+ issueUID, err := strconv.Atoi(issue.Uid)+ if err != nil {+ return err+ }+ // Create a project activity after successfully creating the issue from the push event.+ activityPayload, err := json.Marshal(+ api.ActivityProjectRepositoryPushPayload{+ VCSPushEvent: pushEvent,+ IssueID: issueUID,+ IssueName: issue.Name,+ },+ )+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)+ }++ activityCreate := &store.ActivityMessage{+ CreatorUID: creatorID,+ ContainerUID: project.UID,+ Type: api.ActivityProjectRepositoryPush,+ Level: api.ActivityInfo,+ Comment: fmt.Sprintf("Created issue %q.", issue.Name),+ Payload: string(activityPayload),+ }+ if _, err := s.ActivityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{}); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issueUID)).SetInternal(err)+ }++ return nil+}++func getChangeType(migrationType db.MigrationType) v1pb.Plan_ChangeDatabaseConfig_Type {+ switch migrationType {+ case db.Baseline:+ return v1pb.Plan_ChangeDatabaseConfig_BASELINE+ case db.Migrate:+ return v1pb.Plan_ChangeDatabaseConfig_MIGRATE+ case db.MigrateSDL:+ return v1pb.Plan_ChangeDatabaseConfig_MIGRATE_SDL+ case db.Data:+ return v1pb.Plan_ChangeDatabaseConfig_DATA+ }+ return v1pb.Plan_ChangeDatabaseConfig_TYPE_UNSPECIFIED+}++func (s *Server) createIssueFromMigrationDetailList(ctx context.Context, project *store.ProjectMessage, issueName, issueDescription string, pushEvent vcs.PushEvent, creatorID int, migrationDetailList []*api.MigrationDetail) error {+ if s.profile.DevelopmentUseV2Scheduler {+ return s.createIssueFromMigrationDetailsV2(ctx, project, issueName, issueDescription, pushEvent, creatorID, migrationDetailList)+ }+createContext, err := json.Marshal(&api.MigrationContext{VCSPushEvent: &pushEvent,@@ -1545,7 +1703,7 @@ func (s *Server) createIssueFromMigrationDetailList(ctx context.Context, issueNa}}issueCreate := &api.IssueCreate{- ProjectID: projectID,+ ProjectID: project.UID,Name: issueName,Type: issueType,Description: issueDescription,@@ -1579,7 +1737,7 @@ func (s *Server) createIssueFromMigrationDetailList(ctx context.Context, issueNaactivityCreate := &store.ActivityMessage{CreatorUID: creatorID,- ContainerUID: projectID,+ ContainerUID: project.UID,Type: api.ActivityProjectRepositoryPush,Level: api.ActivityInfo,Comment: fmt.Sprintf("Created issue %q.", issue.Name),@@ -1787,13 +1945,12 @@ func (s *Server) prepareIssueFromSDLFile(ctx context.Context, repoInfo *repoInfovar migrationDetailList []*api.MigrationDetailif repoInfo.project.TenantMode == api.TenantModeTenant {- migrationDetailList = append(migrationDetailList,- &api.MigrationDetail{+ return []*api.MigrationDetail{+ {MigrationType: db.MigrateSDL,SheetID: sheet.UID,},- )- return migrationDetailList, nil+ }, nil}databases, err := s.findProjectDatabases(ctx, repoInfo.project.UID, dbName, schemaInfo.Environment)@@ -2023,6 +2180,31 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [return nil}+ if issue.PlanUID != nil {+ plan, err := s.store.GetPlan(ctx, *issue.PlanUID)+ if err != nil {+ log.Error("failed to get plan", zap.Int64("plan ID", *issue.PlanUID), zap.Error(err))+ }+ for _, step := range plan.Config.Steps {+ for _, spec := range step.Specs {+ v, ok := spec.Config.(*storepb.PlanConfig_Spec_ChangeDatabaseConfig)+ if !ok {+ continue+ }+ if v.ChangeDatabaseConfig.SchemaVersion == schemaVersion {+ v.ChangeDatabaseConfig.Sheet = fmt.Sprintf("projects/%s/sheets/%d", issue.Project.ResourceID, sheet.UID)+ }+ }+ }+ if err := s.store.UpdatePlan(ctx, &store.UpdatePlanMessage{+ UID: *issue.PlanUID,+ Config: plan.Config,+ UpdaterID: api.SystemBotID,+ }); err != nil {+ log.Error("failed to update plan", zap.Int64("plan ID", *issue.PlanUID), zap.Error(err))+ }+ }+// dismiss stale review, re-find the approval template// it's ok if we failedif err := func() error {diff --git a/backend/store/principal.go b/backend/store/principal.goindex c561cdaa01..a2d46d4844 100644--- a/backend/store/principal.go+++ b/backend/store/principal.go@@ -92,6 +92,14 @@ type UserMessage struct {// GetUser gets an user.func (s *Store) GetUser(ctx context.Context, find *FindUserMessage) (*UserMessage, error) {+ if find.Email != nil && *find.Email == api.SystemBotEmail {+ return &UserMessage{+ ID: api.SystemBotID,+ Email: api.SystemBotEmail,+ Type: api.SystemBot,+ Role: api.Owner,+ }, nil+ }tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, errdiff --git a/backend/tests/database.go b/backend/tests/database.goindex 563f754e24..582af925fc 100644--- a/backend/tests/database.go+++ b/backend/tests/database.go@@ -18,6 +18,77 @@ import (v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")+func (ctl *controller) createDatabaseV2(ctx context.Context, instance *v1pb.Instance, projectName, databaseName string, owner string, labels map[string]string) error {+ characterSet, collation := "utf8mb4", "utf8mb4_general_ci"+ if instance.Engine == v1pb.Engine_POSTGRES {+ characterSet = "UTF8"+ collation = "en_US.UTF-8"+ }++ plan, err := ctl.rolloutServiceClient.CreatePlan(ctx, &v1pb.CreatePlanRequest{+ Parent: projectName,+ Plan: &v1pb.Plan{+ Steps: []*v1pb.Plan_Step{+ {+ Specs: []*v1pb.Plan_Spec{+ {+ Config: &v1pb.Plan_Spec_CreateDatabaseConfig{+ CreateDatabaseConfig: &v1pb.Plan_CreateDatabaseConfig{+ Target: instance.Name,+ Database: databaseName,+ CharacterSet: characterSet,+ Collation: collation,+ Owner: owner,+ Labels: labels,+ },+ },+ },+ },+ },+ },+ },+ })+ if err != nil {+ return err+ }++ rollout, err := ctl.rolloutServiceClient.CreateRollout(ctx, &v1pb.CreateRolloutRequest{Parent: projectName, Plan: plan.Name})+ if err != nil {+ return err+ }++ issue, err := ctl.issueServiceClient.CreateIssue(ctx, &v1pb.CreateIssueRequest{+ Parent: projectName,+ Issue: &v1pb.Issue{+ Title: fmt.Sprintf("create database %q", databaseName),+ Description: fmt.Sprintf("This creates a database %q.", databaseName),+ Plan: plan.Name,+ Rollout: rollout.Name,+ Type: v1pb.Issue_DATABASE_CHANGE,+ Assignee: fmt.Sprintf("users/%s", api.SystemBotEmail),+ },+ })+ if err != nil {+ return err+ }++ if err := ctl.waitRollout(ctx, rollout.Name); err != nil {+ return err+ }++ _, err = ctl.issueServiceClient.BatchUpdateIssuesStatus(ctx, &v1pb.BatchUpdateIssuesStatusRequest{+ Parent: projectName,+ Issues: []string{issue.Name},+ Status: v1pb.IssueStatus_DONE,+ })+ if err != nil {+ return err+ }+ // Add a second sleep to avoid schema version conflict.+ time.Sleep(time.Second)+ return nil+}+func (ctl *controller) createDatabase(ctx context.Context, projectUID int, instance *v1pb.Instance, databaseName string, owner string, labelMap map[string]string) error {environmentResourceID := strings.TrimPrefix(instance.Environment, "environments/")instanceUID, err := strconv.Atoi(instance.Uid)diff --git a/backend/tests/issue.go b/backend/tests/issue.goindex 97f7010cfb..5c6e5009bc 100644--- a/backend/tests/issue.go+++ b/backend/tests/issue.go@@ -15,6 +15,17 @@ import (v1 "github.com/bytebase/bytebase/proto/generated-go/v1")+func (ctl *controller) closeIssue(ctx context.Context, projectName, issueName string) error {+ if _, err := ctl.issueServiceClient.BatchUpdateIssuesStatus(ctx, &v1.BatchUpdateIssuesStatusRequest{+ Parent: projectName,+ Issues: []string{issueName},+ Status: v1.IssueStatus_DONE,+ }); err != nil {+ return err+ }+ return nil+}+// createIssue creates an issue.func (ctl *controller) createIssue(issueCreate api.IssueCreate) (*api.Issue, error) {buf := new(bytes.Buffer)diff --git a/backend/tests/rollout.go b/backend/tests/rollout.gonew file mode 100644index 0000000000..95cc5ee1e7--- /dev/null+++ b/backend/tests/rollout.go@@ -0,0 +1,69 @@+package tests++import (+ "context"+ "fmt"+ "time"++ "github.com/pkg/errors"++ v1 "github.com/bytebase/bytebase/proto/generated-go/v1"+)++// waitRollout waits for pipeline to finish and approves tasks when necessary.+func (ctl *controller) waitRollout(ctx context.Context, rolloutName string) error {+ // Sleep for 1 second between issues so that we don't get migration version conflict because we are using second-level timestamp for the version string. We choose sleep because it mimics the user's behavior.+ time.Sleep(1 * time.Second)++ ticker := time.NewTicker(100 * time.Millisecond)+ defer ticker.Stop()++ for range ticker.C {+ rollout, err := ctl.rolloutServiceClient.GetRollout(ctx, &v1.GetRolloutRequest{+ Name: rolloutName,+ })+ if err != nil {+ return err+ }+ var anyError error+ completed := true+ var runTasks []string+ for _, stage := range rollout.Stages {+ for _, task := range stage.Tasks {+ switch task.Status {+ case v1.Task_NOT_STARTED:+ runTasks = append(runTasks, task.Name)+ completed = false+ case v1.Task_DONE:+ continue+ case v1.Task_FAILED:+ resp, err := ctl.rolloutServiceClient.ListTaskRuns(ctx, &v1.ListTaskRunsRequest{Parent: task.Name, PageSize: 1})+ if err != nil {+ return err+ }+ if len(resp.TaskRuns) > 0 {+ anyError = errors.Errorf(resp.TaskRuns[0].Detail)+ }+ default:+ completed = false+ }+ }+ }++ // Rollout tasks.+ if len(runTasks) > 0 {+ _, err := ctl.rolloutServiceClient.BatchRunTasks(ctx, &v1.BatchRunTasksRequest{+ Parent: fmt.Sprintf("%s/stages/-", rolloutName),+ Tasks: runTasks,+ })+ if err != nil {+ return err+ }+ }++ if completed {+ return anyError+ }+ }+ return nil+}diff --git a/backend/tests/schema_update_test.go b/backend/tests/schema_update_test.goindex c144041b30..a789bd6861 100644--- a/backend/tests/schema_update_test.go+++ b/backend/tests/schema_update_test.go@@ -442,8 +442,9 @@ func TestVCS(t *testing.T) {ctx := context.Background()ctl := &controller{}ctx, err := ctl.StartServerWithExternalPg(ctx, &config{- dataDir: t.TempDir(),- vcsProviderCreator: test.vcsProviderCreator,+ dataDir: t.TempDir(),+ vcsProviderCreator: test.vcsProviderCreator,+ developmentUseV2Scheduler: true,})a.NoError(err)defer func() {@@ -519,7 +520,7 @@ func TestVCS(t *testing.T) {// Create an issue that creates a database.databaseName := "testVCSSchemaUpdate"- err = ctl.createDatabase(ctx, projectUID, instance, databaseName, "", nil /* labelMap */)+ err = ctl.createDatabaseV2(ctx, instance, project.Name, databaseName, "", nil /* labelMap */)a.NoError(err)database, err := ctl.databaseServiceClient.GetDatabase(ctx, &v1pb.GetDatabaseRequest{@@ -563,9 +564,8 @@ func TestVCS(t *testing.T) {a.NoError(err)a.Len(issues, 1)issue := issues[0]- status, err := ctl.waitIssuePipeline(ctx, issue.ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)issue, err = ctl.getIssue(issue.ID)a.NoError(err)// TODO(p0ny): expose task DAG list and check the dependency.@@ -573,12 +573,7 @@ func TestVCS(t *testing.T) {a.Equal(api.TaskDatabaseSchemaUpdate, issue.Pipeline.StageList[0].TaskList[0].Type)a.Equal("[testVCSSchemaUpdate] Alter schema: 😊create table book", issue.Name)a.Equal("By VCS files:\n\nprod/testVCSSchemaUpdate##ver1##migrate##😊create_table_book.sql\nprod/testVCSSchemaUpdate##ver2##migrate##新建create_table_book2.sql\nprod/testVCSSchemaUpdate##ver3##migrate##create_table_book3.sql\n", issue.Description)- _, err = ctl.patchIssueStatus(- api.IssueStatusPatch{- ID: issue.ID,- Status: api.IssueDone,- },- )+ err = ctl.closeIssue(ctx, project.Name, fmt.Sprintf("%s/issues/%d", project.Name, issue.Pipeline.ID))a.NoError(err)// Query schema.@@ -604,9 +599,8 @@ func TestVCS(t *testing.T) {a.NoError(err)a.Len(issues, 1)issue = issues[0]- status, err = ctl.waitIssuePipeline(ctx, issue.ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID))a.Error(err)- a.Equal(api.TaskFailed, status)// Simulate Git commits for a correct modified date update.err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile4: dataUpdateStatement})@@ -626,32 +620,29 @@ func TestVCS(t *testing.T) {a.Len(issues, 1)issue = issues[0]- a.Len(issue.Pipeline.StageList, 1)- stage := issue.Pipeline.StageList[0]- a.Len(stage.TaskList, 1)- task := stage.TaskList[0]+ // TODO(d): waiting for approval finding to complete.+ time.Sleep(2 * time.Second)+ rollout, err := ctl.rolloutServiceClient.GetRollout(ctx, &v1pb.GetRolloutRequest{Name: fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID)})+ a.NoError(err)+ a.Len(rollout.Stages, 1)+ stage := rollout.Stages[0]+ a.Len(stage.Tasks, 1)+ task := stage.Tasks[0]// simulate retrying the failed task.- _, err = ctl.patchTaskStatus(api.TaskStatusPatch{- ID: task.ID,- UpdaterID: api.SystemBotID,- Status: api.TaskPendingApproval,- }, issue.Pipeline.ID, task.ID)+ _, err = ctl.rolloutServiceClient.BatchRunTasks(ctx, &v1pb.BatchRunTasksRequest{+ Parent: fmt.Sprintf("%s/stages/-", rollout.Name),+ Tasks: []string{task.Name},+ })a.NoError(err)- status, err = ctl.waitIssuePipeline(ctx, issue.ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)issue, err = ctl.getIssue(issue.ID)a.NoError(err)a.Equal(api.TaskDatabaseDataUpdate, issue.Pipeline.StageList[0].TaskList[0].Type)a.Equal("[testVCSSchemaUpdate] Change data: Insert data", issue.Name)a.Equal("By VCS files:\n\nprod/testVCSSchemaUpdate##ver4##data##insert_data.sql\n", issue.Description)- _, err = ctl.patchIssueStatus(- api.IssueStatusPatch{- ID: issue.ID,- Status: api.IssueDone,- },- )+ err = ctl.closeIssue(ctx, project.Name, fmt.Sprintf("%s/issues/%d", project.Name, issue.Pipeline.ID))a.NoError(err)sheet, err := ctl.sheetServiceClient.CreateSheet(ctx, &v1pb.CreateSheetRequest{@@ -689,9 +680,8 @@ func TestVCS(t *testing.T) {CreateContext: string(createContext),})a.NoError(err)- status, err = ctl.waitIssuePipeline(ctx, issue.ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)environmentResourceID := strings.TrimPrefix(prodEnvironment.Name, "environments/")latestFileName := fmt.Sprintf("%s/%s/.%s##LATEST.sql", baseDirectory, environmentResourceID, databaseName)files, err := ctl.vcsProvider.GetFiles(test.externalID, latestFileName)@@ -707,35 +697,30 @@ func TestVCS(t *testing.T) {histories := resp.ChangeHistorieswantHistories := []*v1pb.ChangeHistory{{- Source: v1pb.ChangeHistory_UI,Type: v1pb.ChangeHistory_MIGRATE,Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema4,PrevSchema: dumpedSchema3,},{- Source: v1pb.ChangeHistory_VCS,Type: v1pb.ChangeHistory_DATA,Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema3,PrevSchema: dumpedSchema3,},{- Source: v1pb.ChangeHistory_VCS,Type: v1pb.ChangeHistory_MIGRATE,Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema3,PrevSchema: dumpedSchema2,},{- Source: v1pb.ChangeHistory_VCS,Type: v1pb.ChangeHistory_MIGRATE,Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema2,PrevSchema: dumpedSchema,},{- Source: v1pb.ChangeHistory_VCS,Type: v1pb.ChangeHistory_MIGRATE,Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema,@@ -745,14 +730,13 @@ func TestVCS(t *testing.T) {a.Equal(len(wantHistories), len(histories))for i, history := range histories {got := &v1pb.ChangeHistory{- Source: history.Source,Type: history.Type,Status: history.Status,Schema: history.Schema,PrevSchema: history.PrevSchema,}want := wantHistories[i]- a.True(proto.Equal(got, want))+ a.Equal(got, want)a.NotEqual(history.Version, "")}@@ -848,8 +832,9 @@ func TestVCS_SDL_POSTGRES(t *testing.T) {ctx := context.Background()ctl := &controller{}ctx, err := ctl.StartServerWithExternalPg(ctx, &config{- dataDir: t.TempDir(),- vcsProviderCreator: test.vcsProviderCreator,+ dataDir: t.TempDir(),+ vcsProviderCreator: test.vcsProviderCreator,+ developmentUseV2Scheduler: true,})a.NoError(err)defer func() {@@ -944,7 +929,7 @@ func TestVCS_SDL_POSTGRES(t *testing.T) {a.NoError(err)// Create an issue that creates a database- err = ctl.createDatabase(ctx, projectUID, instance, databaseName, "bytebase", nil /* labelMap */)+ err = ctl.createDatabaseV2(ctx, instance, project.Name, databaseName, "bytebase", nil /* labelMap */)a.NoError(err)database, err := ctl.databaseServiceClient.GetDatabase(ctx, &v1pb.GetDatabaseRequest{Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName)})@@ -971,19 +956,13 @@ func TestVCS_SDL_POSTGRES(t *testing.T) {a.NoError(err)a.Len(issues, 1)issue := issues[0]- status, err := ctl.waitIssuePipeline(ctx, issue.ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)issue, err = ctl.getIssue(issue.ID)a.NoError(err)a.Equal("[testVCSSchemaUpdate] Alter schema", issue.Name)a.Equal("Apply schema diff by file prod/.testVCSSchemaUpdate##LATEST.sql", issue.Description)- _, err = ctl.patchIssueStatus(- api.IssueStatusPatch{- ID: issue.ID,- Status: api.IssueDone,- },- )+ err = ctl.closeIssue(ctx, project.Name, fmt.Sprintf("%s/issues/%d", project.Name, issue.Pipeline.ID))a.NoError(err)// Simulate Git commits for data update to the table "users".@@ -1006,19 +985,13 @@ func TestVCS_SDL_POSTGRES(t *testing.T) {a.NoError(err)a.Len(issues, 1)issue = issues[0]- status, err = ctl.waitIssuePipeline(ctx, issue.ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)issue, err = ctl.getIssue(issue.ID)a.NoError(err)a.Equal("[testVCSSchemaUpdate] Change data", issue.Name)a.Equal("By VCS files:\n\nprod/testVCSSchemaUpdate##ver2##data##insert_data.sql\n", issue.Description)- _, err = ctl.patchIssueStatus(- api.IssueStatusPatch{- ID: issue.ID,- Status: api.IssueDone,- },- )+ err = ctl.closeIssue(ctx, project.Name, fmt.Sprintf("%s/issues/%d", project.Name, issue.Pipeline.ID))a.NoError(err)// Get migration history@@ -1103,21 +1076,18 @@ ALTER TABLE ONLY public.usershistories := resp.ChangeHistorieswantHistories := []*v1pb.ChangeHistory{{- Source: v1pb.ChangeHistory_VCS,Type: v1pb.ChangeHistory_DATA,Status: v1pb.ChangeHistory_DONE,Schema: updatedSchema,PrevSchema: updatedSchema,},{- Source: v1pb.ChangeHistory_VCS,Type: v1pb.ChangeHistory_MIGRATE_SDL,Status: v1pb.ChangeHistory_DONE,Schema: updatedSchema,PrevSchema: initialSchema,},{- Source: v1pb.ChangeHistory_UI,Type: v1pb.ChangeHistory_MIGRATE,Status: v1pb.ChangeHistory_DONE,Schema: initialSchema,@@ -1127,7 +1097,6 @@ ALTER TABLE ONLY public.usersa.Equal(len(wantHistories), len(histories))for i, history := range histories {got := &v1pb.ChangeHistory{- Source: history.Source,Type: history.Type,Status: history.Status,Schema: history.Schema,@@ -1351,8 +1320,9 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {ctx := context.Background()ctl := &controller{}ctx, err := ctl.StartServerWithExternalPg(ctx, &config{- dataDir: t.TempDir(),- vcsProviderCreator: test.vcsProviderCreator,+ dataDir: t.TempDir(),+ vcsProviderCreator: test.vcsProviderCreator,+ developmentUseV2Scheduler: true,})a.NoError(err)defer func() {@@ -1432,7 +1402,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {a.NoError(err)// Create an issue that creates a database.- err = ctl.createDatabase(ctx, projectUID, instance, dbName, "", nil /* labelMap */)+ err = ctl.createDatabaseV2(ctx, instance, project.Name, dbName, "", nil /* labelMap */)a.NoError(err)a.Equal(len(test.expect), len(test.commitNewFileNames))@@ -1460,15 +1430,9 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {if test.expect[idx] {a.Len(issues, 1)issue := issues[0]- status, err := ctl.waitIssuePipeline(ctx, issue.ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)- _, err = ctl.patchIssueStatus(- api.IssueStatusPatch{- ID: issue.ID,- Status: api.IssueDone,- },- )+ err = ctl.closeIssue(ctx, project.Name, fmt.Sprintf("%s/issues/%d", project.Name, issue.Pipeline.ID))a.NoError(err)} else {a.Len(issues, 0)@@ -2435,8 +2399,9 @@ func TestVCS_SDL_MySQL(t *testing.T) {ctx := context.Background()ctl := &controller{}ctx, err := ctl.StartServerWithExternalPg(ctx, &config{- dataDir: t.TempDir(),- vcsProviderCreator: test.vcsProviderCreator,+ dataDir: t.TempDir(),+ vcsProviderCreator: test.vcsProviderCreator,+ developmentUseV2Scheduler: true,})a.NoError(err)defer func() {@@ -2540,7 +2505,7 @@ func TestVCS_SDL_MySQL(t *testing.T) {a.NoError(err)// Create an issue that creates a database- err = ctl.createDatabase(ctx, projectUID, instance, databaseName, "bytebase", nil /* labelMap */)+ err = ctl.createDatabaseV2(ctx, instance, project.Name, databaseName, "bytebase", nil /* labelMap */)a.NoError(err)database, err := ctl.databaseServiceClient.GetDatabase(ctx, &v1pb.GetDatabaseRequest{Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName)})@@ -2567,19 +2532,13 @@ func TestVCS_SDL_MySQL(t *testing.T) {a.NoError(err)a.Len(issues, 1)issue := issues[0]- status, err := ctl.waitIssuePipeline(ctx, issue.ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)issue, err = ctl.getIssue(issue.ID)a.NoError(err)a.Equal(fmt.Sprintf("[%s] Alter schema", databaseName), issue.Name)a.Equal(fmt.Sprintf("Apply schema diff by file prod/.%s##LATEST.sql", databaseName), issue.Description)- _, err = ctl.patchIssueStatus(- api.IssueStatusPatch{- ID: issue.ID,- Status: api.IssueDone,- },- )+ err = ctl.closeIssue(ctx, project.Name, fmt.Sprintf("%s/issues/%d", project.Name, issue.Pipeline.ID))a.NoError(err)// Simulate Git commits for data update to the table "users".@@ -2602,19 +2561,13 @@ func TestVCS_SDL_MySQL(t *testing.T) {a.NoError(err)a.Len(issues, 1)issue = issues[0]- status, err = ctl.waitIssuePipeline(ctx, issue.ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issue.Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)issue, err = ctl.getIssue(issue.ID)a.NoError(err)a.Equal(fmt.Sprintf("[%s] Change data: Insert data", databaseName), issue.Name)a.Equal(fmt.Sprintf("By VCS files:\n\nprod/%s##ver2##data##insert_data.sql\n", databaseName), issue.Description)- _, err = ctl.patchIssueStatus(- api.IssueStatusPatch{- ID: issue.ID,- Status: api.IssueDone,- },- )+ err = ctl.closeIssue(ctx, project.Name, fmt.Sprintf("%s/issues/%d", project.Name, issue.Pipeline.ID))a.NoError(err)// Get migration history@@ -2664,14 +2617,12 @@ func TestVCS_SDL_MySQL(t *testing.T) {histories := resp.ChangeHistorieswantHistories := []*v1pb.ChangeHistory{{- Source: v1pb.ChangeHistory_VCS,Type: v1pb.ChangeHistory_DATA,Status: v1pb.ChangeHistory_DONE,Schema: updatedSchema,PrevSchema: updatedSchema,},{- Source: v1pb.ChangeHistory_VCS,Type: v1pb.ChangeHistory_MIGRATE_SDL,Status: v1pb.ChangeHistory_DONE,Schema: updatedSchema,@@ -2681,14 +2632,13 @@ func TestVCS_SDL_MySQL(t *testing.T) {a.Equal(len(wantHistories), len(histories))for i, history := range histories {got := &v1pb.ChangeHistory{- Source: history.Source,Type: history.Type,Status: history.Status,Schema: history.Schema,PrevSchema: history.PrevSchema,}want := wantHistories[i]- a.True(proto.Equal(got, want))+ a.Equal(got, want)a.NotEqual(history.Version, "")}diff --git a/backend/tests/tenant_test.go b/backend/tests/tenant_test.goindex 3d49fc8d60..6c5a37bfa4 100644--- a/backend/tests/tenant_test.go+++ b/backend/tests/tenant_test.go@@ -1321,8 +1321,9 @@ func TestTenantVCS_YAML(t *testing.T) {ctx := context.Background()ctl := &controller{}ctx, err := ctl.StartServerWithExternalPg(ctx, &config{- dataDir: t.TempDir(),- vcsProviderCreator: test.vcsProviderCreator,+ dataDir: t.TempDir(),+ vcsProviderCreator: test.vcsProviderCreator,+ developmentUseV2Scheduler: true,})a.NoError(err)defer func() {@@ -1448,7 +1449,7 @@ func TestTenantVCS_YAML(t *testing.T) {for i, testInstance := range testInstances {tenant := fmt.Sprintf("tenant%d", i)databaseName := baseDatabaseName + "_" + tenant- err := ctl.createDatabase(ctx, projectUID, testInstance, databaseName, "", nil /* labelMap */)+ err := ctl.createDatabaseV2(ctx, testInstance, project.Name, databaseName, "", nil /* labelMap */)a.NoError(err)}@@ -1488,9 +1489,8 @@ func TestTenantVCS_YAML(t *testing.T) {issues, err := ctl.getIssues(&projectUID, api.IssueOpen)a.NoError(err)a.Len(issues, 1)- status, err := ctl.waitIssuePipeline(ctx, issues[0].ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issues[0].Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)// Simulate Git commits for data update.database0Name := "TestTenantVCS_YAML_tenant0"@@ -1521,9 +1521,8 @@ statement: |// Get data update issues.issues, err = ctl.getIssues(&projectUID, api.IssueOpen)a.NoError(err)- status, err = ctl.waitIssuePipeline(ctx, issues[0].ID)+ err = ctl.waitRollout(ctx, fmt.Sprintf("%s/rollouts/%d", project.Name, issues[0].Pipeline.ID))a.NoError(err)- a.Equal(api.TaskDone, status)})}}diff --git a/backend/tests/tests.go b/backend/tests/tests.goindex 85aeec3012..38d710d2c0 100644--- a/backend/tests/tests.go+++ b/backend/tests/tests.go@@ -162,6 +162,7 @@ type controller struct {client *http.ClientgrpcConn *grpc.ClientConnissueServiceClient v1pb.IssueServiceClient+ rolloutServiceClient v1pb.RolloutServiceClientorgPolicyServiceClient v1pb.OrgPolicyServiceClientprojectServiceClient v1pb.ProjectServiceClientauthServiceClient v1pb.AuthServiceClient@@ -189,11 +190,12 @@ type controller struct {}type config struct {- dataDir string- vcsProviderCreator fake.VCSProviderCreator- feishuProverdierCreator fake.FeishuProviderCreator- readOnly bool- skipOnboardingData bool+ dataDir string+ vcsProviderCreator fake.VCSProviderCreator+ feishuProverdierCreator fake.FeishuProviderCreator+ readOnly bool+ skipOnboardingData bool+ developmentUseV2Scheduler bool}var (@@ -258,7 +260,7 @@ func (ctl *controller) StartServerWithExternalPg(ctx context.Context, config *copgURL := fmt.Sprintf("postgresql://%s@:%d/%s?host=%s", externalPgUser, externalPgPort, databaseName, common.GetPostgresSocketDir())serverPort := getTestPort()- profile := getTestProfileWithExternalPg(config.dataDir, resourceDir, serverPort, externalPgUser, pgURL, ctl.feishuProvider.APIURL(ctl.feishuURL), config.skipOnboardingData)+ profile := getTestProfileWithExternalPg(config.dataDir, resourceDir, serverPort, externalPgUser, pgURL, ctl.feishuProvider.APIURL(ctl.feishuURL), config.skipOnboardingData, config.developmentUseV2Scheduler)server, err := server.NewServer(ctx, profile)if err != nil {return nil, err@@ -337,7 +339,7 @@ func getTestProfile(dataDir, resourceDir string, port int, readOnly bool, feishu// GetTestProfileWithExternalPg will return a profile for testing with external Postgres.// We require port as an argument of GetTestProfile so that test can run in parallel in different ports,// pgURL for connect to Postgres.-func getTestProfileWithExternalPg(dataDir, resourceDir string, port int, pgUser string, pgURL string, feishuAPIURL string, skipOnboardingData bool) componentConfig.Profile {+func getTestProfileWithExternalPg(dataDir, resourceDir string, port int, pgUser string, pgURL string, feishuAPIURL string, skipOnboardingData, developmentUseV2Scheduler bool) componentConfig.Profile {return componentConfig.Profile{Mode: testReleaseMode,ExternalURL: fmt.Sprintf("http://localhost:%d", port),@@ -352,6 +354,7 @@ func getTestProfileWithExternalPg(dataDir, resourceDir string, port int, pgUserFeishuAPIURL: feishuAPIURL,PgURL: pgURL,TestOnlySkipOnboardingData: skipOnboardingData,+ DevelopmentUseV2Scheduler: developmentUseV2Scheduler,}}@@ -436,6 +439,7 @@ func (ctl *controller) start(ctx context.Context, port int) (context.Context, er}ctl.grpcConn = grpcConnctl.issueServiceClient = v1pb.NewIssueServiceClient(ctl.grpcConn)+ ctl.rolloutServiceClient = v1pb.NewRolloutServiceClient(ctl.grpcConn)ctl.orgPolicyServiceClient = v1pb.NewOrgPolicyServiceClient(ctl.grpcConn)ctl.projectServiceClient = v1pb.NewProjectServiceClient(ctl.grpcConn)ctl.authServiceClient = v1pb.NewAuthServiceClient(ctl.grpcConn)