Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement cancel plan check runs (#12803)
boojack1f303eab3cc6
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.goindex 08ab4c9de2..afc6d8fbce 100644--- a/backend/api/v1/plan_service.go+++ b/backend/api/v1/plan_service.go@@ -818,6 +818,76 @@ func (s *PlanService) RunPlanChecks(ctx context.Context, request *v1pb.RunPlanChreturn &v1pb.RunPlanChecksResponse{}, nil}+// BatchCancelPlanCheckRuns cancels a list of plan check runs.+func (s *PlanService) BatchCancelPlanCheckRuns(ctx context.Context, request *v1pb.BatchCancelPlanCheckRunsRequest) (*v1pb.BatchCancelPlanCheckRunsResponse, error) {+ if len(request.PlanCheckRuns) == 0 {+ return nil, status.Errorf(codes.InvalidArgument, "plan check runs cannot be empty")+ }++ projectID, _, err := common.GetProjectIDPlanID(request.Parent)+ if err != nil {+ return nil, status.Errorf(codes.InvalidArgument, err.Error())+ }+ project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{+ ResourceID: &projectID,+ })+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to find project, error: %v", err)+ }+ if project == nil {+ return nil, status.Errorf(codes.NotFound, "project %v not found", projectID)+ }++ principalID, ok := ctx.Value(common.PrincipalIDContextKey).(int)+ if !ok {+ return nil, status.Errorf(codes.Internal, "principal ID not found")+ }+ user, err := s.store.GetUserByID(ctx, principalID)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to find user, error: %v", err)+ }+ if user == nil {+ return nil, status.Errorf(codes.NotFound, "user %v not found", principalID)+ }++ var planCheckRunIDs []int+ for _, planCheckRun := range request.PlanCheckRuns {+ _, _, planCheckRunID, err := common.GetProjectIDPlanIDPlanCheckRunID(planCheckRun)+ if err != nil {+ return nil, status.Errorf(codes.InvalidArgument, err.Error())+ }+ planCheckRunIDs = append(planCheckRunIDs, planCheckRunID)+ }++ planCheckRuns, err := s.store.ListPlanCheckRuns(ctx, &store.FindPlanCheckRunMessage{+ UIDs: &planCheckRunIDs,+ })+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to list plan check runs, error: %v", err)+ }++ // Check if any of the given plan check runs are not running.+ for _, planCheckRun := range planCheckRuns {+ switch planCheckRun.Status {+ case store.PlanCheckRunStatusRunning:+ default:+ return nil, status.Errorf(codes.InvalidArgument, "planCheckRun %v(%v) is not running", planCheckRun.UID, planCheckRun.Type)+ }+ }+ // Cancel the plan check runs.+ for _, planCheckRun := range planCheckRuns {+ if cancelFunc, ok := s.stateCfg.RunningPlanCheckRunsCancelFunc.Load(planCheckRun.UID); ok {+ cancelFunc.(context.CancelFunc)()+ }+ }+ // Update the status of the plan check runs to canceled.+ if err := s.store.BatchCancelPlanCheckRuns(ctx, planCheckRunIDs, principalID); err != nil {+ return nil, status.Errorf(codes.Internal, "failed to batch patch task run status to canceled, error: %v", err)+ }++ return &v1pb.BatchCancelPlanCheckRunsResponse{}, nil+}+func (s *PlanService) buildPlanFindWithFilter(ctx context.Context, planFind *store.FindPlanMessage, filter string) error {filters, err := parseFilter(filter)if err != nil {diff --git a/backend/common/resource_name.go b/backend/common/resource_name.goindex 7ccb434135..efc1025eea 100644--- a/backend/common/resource_name.go+++ b/backend/common/resource_name.go@@ -320,6 +320,23 @@ func GetProjectIDPlanID(name string) (string, int64, error) {return tokens[0], planID, nil}+// GetProjectIDPlanIDPlanCheckRunID returns the project ID, plan ID and plan check run ID from a resource name.+func GetProjectIDPlanIDPlanCheckRunID(name string) (string, int, int, error) {+ tokens, err := GetNameParentTokens(name, ProjectNamePrefix, PlanPrefix, PlanCheckRunPrefix)+ if err != nil {+ return "", 0, 0, err+ }+ planID, err := strconv.Atoi(tokens[1])+ if err != nil {+ return "", 0, 0, errors.Errorf("invalid plan ID %q", tokens[1])+ }+ planCheckRunID, err := strconv.Atoi(tokens[2])+ if err != nil {+ return "", 0, 0, errors.Errorf("invalid plan check run ID %q", tokens[2])+ }+ return tokens[0], planID, planCheckRunID, nil+}+// GetProjectIDRolloutID returns the project ID and rollout ID from a resource name.func GetProjectIDRolloutID(name string) (string, int, error) {tokens, err := GetNameParentTokens(name, ProjectNamePrefix, RolloutPrefix)diff --git a/backend/component/state/state.go b/backend/component/state/state.goindex 6c21fb37d2..f67488c48d 100644--- a/backend/component/state/state.go+++ b/backend/component/state/state.go@@ -40,6 +40,8 @@ type State struct {// RunningPlanChecks is the set of running plan checks.RunningPlanChecks sync.Map+ // RunningPlanCheckRunsCancelFunc is the cancelFunc of running plan checks.+ RunningPlanCheckRunsCancelFunc sync.Map // map[planCheckRunUID]context.CancelFunc// InstanceOutstandingConnections is the maximum number of connections per instance.InstanceOutstandingConnections *connectionLimiterdiff --git a/backend/runner/plancheck/scheduler.go b/backend/runner/plancheck/scheduler.goindex 29de03f664..f08d75e5d2 100644--- a/backend/runner/plancheck/scheduler.go+++ b/backend/runner/plancheck/scheduler.go@@ -101,6 +101,7 @@ func (s *Scheduler) runPlanCheckRun(ctx context.Context, planCheckRun *store.Plaslog.Error("Skip running plan check for unknown type", slog.Int("uid", planCheckRun.UID), slog.Int64("plan_uid", planCheckRun.PlanUID), slog.String("type", string(planCheckRun.Type)))return}+ // Skip the plan check run if it is already running.if _, ok := s.stateCfg.RunningPlanChecks.Load(planCheckRun.UID); ok {return}@@ -121,14 +122,24 @@ func (s *Scheduler) runPlanCheckRun(ctx context.Context, planCheckRun *store.Plago func() {defer func() {s.stateCfg.RunningPlanChecks.Delete(planCheckRun.UID)+ s.stateCfg.RunningPlanCheckRunsCancelFunc.Delete(planCheckRun.UID)s.stateCfg.InstanceOutstandingConnections.Decrement(instanceUID)}()- results, err := runExecutorOnce(ctx, executor, planCheckRun.Config)++ ctxWithCancel, cancel := context.WithCancel(ctx)+ defer cancel()+ s.stateCfg.RunningPlanCheckRunsCancelFunc.Store(planCheckRun.UID, cancel)++ results, err := runExecutorOnce(ctxWithCancel, executor, planCheckRun.Config)if err != nil {- s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())- return+ if errors.Is(err, context.Canceled) {+ s.markPlanCheckRunCanceled(ctx, planCheckRun, err.Error())+ } else {+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())+ }+ } else {+ s.markPlanCheckRunDone(ctx, planCheckRun, results)}- s.markPlanCheckRunDone(ctx, planCheckRun, results)}()}@@ -142,7 +153,7 @@ func (s *Scheduler) markPlanCheckRunDone(ctx context.Context, planCheckRun *storresult,planCheckRun.UID,); err != nil {- slog.Error("failed to mark plan check run failed", log.BBError(err))+ slog.Error("failed to mark plan check run done", log.BBError(err))}}@@ -159,3 +170,17 @@ func (s *Scheduler) markPlanCheckRunFailed(ctx context.Context, planCheckRun *stslog.Error("failed to mark plan check run failed", log.BBError(err))}}++func (s *Scheduler) markPlanCheckRunCanceled(ctx context.Context, planCheckRun *store.PlanCheckRunMessage, reason string) {+ result := &storepb.PlanCheckRunResult{+ Error: reason,+ }+ if err := s.store.UpdatePlanCheckRun(ctx,+ api.SystemBotID,+ store.PlanCheckRunStatusCanceled,+ result,+ planCheckRun.UID,+ ); err != nil {+ slog.Error("failed to mark plan check run canceled", log.BBError(err))+ }+}diff --git a/backend/store/plan_check_run.go b/backend/store/plan_check_run.goindex a9c1a15dae..82d17b5e3f 100644--- a/backend/store/plan_check_run.go+++ b/backend/store/plan_check_run.go@@ -64,9 +64,9 @@ type PlanCheckRunMessage struct {// FindPlanCheckRunMessage is the message for finding plan check runs.type FindPlanCheckRunMessage struct {PlanUID *int64-- Status *[]PlanCheckRunStatus- Type *[]PlanCheckRunType+ UIDs *[]int+ Status *[]PlanCheckRunStatus+ Type *[]PlanCheckRunType}// CreatePlanCheckRuns creates new plan check runs.@@ -130,6 +130,9 @@ func (s *Store) ListPlanCheckRuns(ctx context.Context, find *FindPlanCheckRunMeswhere = append(where, fmt.Sprintf("plan_check_run.plan_id = $%d", len(args)+1))args = append(args, *v)}+ if v := find.UIDs; v != nil {+ where, args = append(where, fmt.Sprintf("plan_check_run.id = ANY($%d)", len(args)+1)), append(args, *v)+ }if v := find.Status; v != nil {where = append(where, fmt.Sprintf("plan_check_run.status = ANY($%d)", len(args)+1))args = append(args, *v)@@ -215,3 +218,18 @@ func (s *Store) UpdatePlanCheckRun(ctx context.Context, updaterUID int, status P}return nil}++// BatchCancelPlanCheckRuns updates the status of planCheckRuns to CANCELED.+func (s *Store) BatchCancelPlanCheckRuns(ctx context.Context, planCheckRunUIDs []int, updaterID int) error {+ query := `+ UPDATE plan_check_run+ SET+ status = $1,+ updater_id = $2,+ updated_ts = $3+ WHERE id = ANY($4)`+ if _, err := s.db.db.ExecContext(ctx, query, PlanCheckRunStatusCanceled, updaterID, time.Now().Unix(), planCheckRunUIDs); err != nil {+ return err+ }+ return nil+}