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: plan check run scheduler step1 (#7211)
p0ny5065de1fe875
diff --git a/backend/common/error.go b/backend/common/error.goindex b41da90bfb..adff2f49a7 100644--- a/backend/common/error.go+++ b/backend/common/error.go@@ -55,6 +55,11 @@ func (c Code) Int() int {return int(c)}+// Int64 returns the int64 type of code.+func (c Code) Int64() int64 {+ return int64(c)+}+// Error represents an application-specific error. Application errors can be// unwrapped by the caller to extract out the code & message.//diff --git a/backend/component/state/state.go b/backend/component/state/state.goindex a57f08ef6d..5d3d1507d2 100644--- a/backend/component/state/state.go+++ b/backend/component/state/state.go@@ -36,6 +36,8 @@ type State struct {RunningTaskChecks sync.Map // map[taskCheckID]bool// RunningTasks is the set of running tasks.RunningTasks sync.Map // map[taskID]bool+ // RunningPlanChecks is the set of running plan checks.+ RunningPlanChecks sync.Map// RunningTasksCancel is the cancel's of running tasks.RunningTasksCancel sync.Map // map[taskID]context.CancelFunc// InstanceOutstandingConnections is the maximum number of connections per instance.diff --git a/backend/runner/plancheck/database_connect_executor.go b/backend/runner/plancheck/database_connect_executor.gonew file mode 100644index 0000000000..0897034c23--- /dev/null+++ b/backend/runner/plancheck/database_connect_executor.go@@ -0,0 +1,70 @@+package plancheck++import (+ "context"+ "fmt"++ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/component/dbfactory"+ "github.com/bytebase/bytebase/backend/store"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var _ Executor = (*DatabaseConnectExecutor)(nil)++// NewDatabaseConnectExecutor creates a task check database connect executor.+func NewDatabaseConnectExecutor(store *store.Store, dbFactory *dbfactory.DBFactory) Executor {+ return &DatabaseConnectExecutor{+ store: store,+ dbFactory: dbFactory,+ }+}++// DatabaseConnectExecutor checks if the database connection is valid.+type DatabaseConnectExecutor struct {+ store *store.Store+ dbFactory *dbfactory.DBFactory+}++// Run runs the executor.+func (e *DatabaseConnectExecutor) Run(ctx context.Context, planCheckRun *store.PlanCheckRunMessage) (results []*storepb.PlanCheckRunResult_Result, err error) {+ databaseID := int(planCheckRun.Config.DatabaseId)+ database, err := e.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: &databaseID})+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get database ID %v", databaseID)+ }+ if database == nil {+ return nil, errors.Wrapf(err, "database ID not found %v", databaseID)+ }+ instance, err := e.store.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &database.InstanceID})+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get instance %v", database.InstanceID)+ }++ driver, err := e.dbFactory.GetAdminDatabaseDriver(ctx, instance, database)+ if err == nil {+ err = driver.Ping(ctx)+ }+ if err != nil {+ return []*storepb.PlanCheckRunResult_Result{+ {+ Status: storepb.PlanCheckRunResult_Result_ERROR,+ Code: common.DbConnectionFailure.Int64(),+ Title: fmt.Sprintf("Failed to connect %q", database.DatabaseName),+ Content: err.Error(),+ },+ }, nil+ }+ defer driver.Close(ctx)++ return []*storepb.PlanCheckRunResult_Result{+ {+ Status: storepb.PlanCheckRunResult_Result_SUCCESS,+ Code: common.Ok.Int64(),+ Title: "OK",+ Content: fmt.Sprintf("Successfully connected %q", database.DatabaseName),+ },+ }, nil+}diff --git a/backend/runner/plancheck/executor.go b/backend/runner/plancheck/executor.gonew file mode 100644index 0000000000..ca21c1841f--- /dev/null+++ b/backend/runner/plancheck/executor.go@@ -0,0 +1,14 @@+package plancheck++import (+ "context"++ "github.com/bytebase/bytebase/backend/store"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++// Executor is the plan check executor.+type Executor interface {+ // Run will be called periodically by the plan check scheduler+ Run(ctx context.Context, planCheckRun *store.PlanCheckRunMessage) (results []*storepb.PlanCheckRunResult_Result, err error)+}diff --git a/backend/runner/plancheck/scheduler.go b/backend/runner/plancheck/scheduler.gonew file mode 100644index 0000000000..31b5e00dd2--- /dev/null+++ b/backend/runner/plancheck/scheduler.go@@ -0,0 +1,174 @@+// Package plancheck is the runner for plan checks.+package plancheck++import (+ "context"+ "fmt"+ "sync"+ "time"++ "github.com/pkg/errors"+ "go.uber.org/zap"++ "github.com/bytebase/bytebase/backend/common/log"+ "github.com/bytebase/bytebase/backend/component/state"+ enterpriseAPI "github.com/bytebase/bytebase/backend/enterprise/api"+ api "github.com/bytebase/bytebase/backend/legacyapi"+ "github.com/bytebase/bytebase/backend/store"++ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++const (+ planCheckSchedulerInterval = time.Duration(1) * time.Second+)++// NewScheduler creates a new plan check scheduler.+func NewScheduler(s *store.Store, licenseService enterpriseAPI.LicenseService, stateCfg *state.State) *Scheduler {+ return &Scheduler{+ store: s,+ licenseService: licenseService,+ stateCfg: stateCfg,+ executors: make(map[store.PlanCheckRunType]Executor),+ }+}++// Scheduler is the plan check run scheduler.+type Scheduler struct {+ store *store.Store+ licenseService enterpriseAPI.LicenseService+ stateCfg *state.State+ executors map[store.PlanCheckRunType]Executor+}++// Run runs the scheduler.+func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {+ ticker := time.NewTicker(planCheckSchedulerInterval)+ defer ticker.Stop()+ defer wg.Done()+ log.Debug(fmt.Sprintf("Plan check scheduler started and will run every %v", planCheckSchedulerInterval))+ for {+ select {+ case <-ticker.C:+ s.runOnce(ctx)+ case <-ctx.Done():+ return+ }+ }+}++// Register registers a plan check executor.+func (s *Scheduler) Register(planCheckRunType store.PlanCheckRunType, executor Executor) {+ if executor == nil {+ panic("plan check scheduler: Register executor is nil for plan check run type: " + planCheckRunType)+ }+ if _, dup := s.executors[planCheckRunType]; dup {+ panic("plan check scheduler: Register called twice for plan check run type: " + planCheckRunType)+ }+ s.executors[planCheckRunType] = executor+}++func (s *Scheduler) runOnce(ctx context.Context) {+ defer func() {+ if r := recover(); r != nil {+ err, ok := r.(error)+ if !ok {+ err = errors.Errorf("%v", r)+ }+ log.Error("Plan check scheduler PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ }+ }()++ planCheckRuns, err := s.store.ListPlanCheckRuns(ctx, &store.FindPlanCheckRunMessage{+ Status: &[]store.PlanCheckRunStatus{+ store.PlanCheckRunStatusRunning,+ },+ })+ if err != nil {+ log.Error("failed to list running plan check runs", zap.Error(err))+ return+ }++ for _, planCheckRun := range planCheckRuns {+ s.runPlanCheckRun(ctx, planCheckRun)+ }+}++func (s *Scheduler) runPlanCheckRun(ctx context.Context, planCheckRun *store.PlanCheckRunMessage) {+ executor, ok := s.executors[planCheckRun.Type]+ if !ok {+ log.Error("Skip running plan check for unknown type", zap.Int("uid", planCheckRun.UID), zap.Int("plan_uid", planCheckRun.PlanUID), zap.String("type", string(planCheckRun.Type)))+ return+ }+ if _, ok := s.stateCfg.RunningPlanChecks.Load(planCheckRun.UID); ok {+ return+ }++ databaseUID := int(planCheckRun.Config.DatabaseId)+ db, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: &databaseUID})+ if err != nil {+ log.Error("failed to get db for plan check run")+ s.markPlanCheckRunFailed(ctx, planCheckRun, errors.Wrapf(err, "failed to get database for plan check run").Error())+ return+ }+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{+ ResourceID: &db.InstanceID,+ })+ if err != nil {+ log.Error("failed to get instance for plan check run")+ s.markPlanCheckRunFailed(ctx, planCheckRun, errors.Wrapf(err, "failed to get instance for plan check run").Error())+ return+ }++ s.stateCfg.Lock()+ if s.stateCfg.InstanceOutstandingConnections[instance.UID] >= state.InstanceMaximumConnectionNumber {+ s.stateCfg.Unlock()+ return+ }+ s.stateCfg.InstanceOutstandingConnections[instance.UID]+++ s.stateCfg.Unlock()++ s.stateCfg.RunningPlanChecks.Store(planCheckRun.UID, true)+ go func() {+ defer func() {+ s.stateCfg.RunningPlanChecks.Delete(planCheckRun.UID)+ s.stateCfg.Lock()+ s.stateCfg.InstanceOutstandingConnections[instance.UID]--+ s.stateCfg.Unlock()+ }()+ results, err := executor.Run(ctx, planCheckRun)+ if err != nil {+ s.markPlanCheckRunFailed(ctx, planCheckRun, err.Error())+ return+ }+ s.markPlanCheckRunDone(ctx, planCheckRun, results)+ }()+}++func (s *Scheduler) markPlanCheckRunDone(ctx context.Context, planCheckRun *store.PlanCheckRunMessage, results []*storepb.PlanCheckRunResult_Result) {+ result := &storepb.PlanCheckRunResult{+ Results: results,+ }+ if err := s.store.UpdatePlanCheckRun(ctx,+ api.SystemBotID,+ store.PlanCheckRunStatusDone,+ result,+ planCheckRun.UID,+ ); err != nil {+ log.Error("failed to mark plan check run failed", zap.Error(err))+ }+}++func (s *Scheduler) markPlanCheckRunFailed(ctx context.Context, planCheckRun *store.PlanCheckRunMessage, reason string) {+ result := &storepb.PlanCheckRunResult{+ Error: reason,+ }+ if err := s.store.UpdatePlanCheckRun(ctx,+ api.SystemBotID,+ store.PlanCheckRunStatusFailed,+ result,+ planCheckRun.UID,+ ); err != nil {+ log.Error("failed to mark plan check run failed", zap.Error(err))+ }+}diff --git a/backend/server/server.go b/backend/server/server.goindex 6b37908458..4904364e6e 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -72,6 +72,7 @@ import ("github.com/bytebase/bytebase/backend/runner/backuprun""github.com/bytebase/bytebase/backend/runner/mail""github.com/bytebase/bytebase/backend/runner/metricreport"+ "github.com/bytebase/bytebase/backend/runner/plancheck""github.com/bytebase/bytebase/backend/runner/relay""github.com/bytebase/bytebase/backend/runner/rollbackrun""github.com/bytebase/bytebase/backend/runner/schemasync"@@ -152,6 +153,7 @@ type Server struct {// Asynchronous runners.TaskScheduler *taskrun.SchedulerTaskCheckScheduler *taskcheck.Scheduler+ PlanCheckScheduler *plancheck.SchedulerMetricReporter *metricreport.ReporterSchemaSyncer *schemasync.SyncerSlowQuerySyncer *slowquerysync.Syncer@@ -465,6 +467,12 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {statementAffectedRowsExecutor := taskcheck.NewStatementAffectedRowsReportExecutor(storeInstance, s.dbFactory)s.TaskCheckScheduler.Register(api.TaskCheckDatabaseStatementAffectedRowsReport, statementAffectedRowsExecutor)+ if s.profile.Mode == common.ReleaseModeDev {+ s.PlanCheckScheduler = plancheck.NewScheduler(storeInstance, s.licenseService, s.stateCfg)+ databaseConnectExecutor := plancheck.NewDatabaseConnectExecutor(storeInstance, s.dbFactory)+ s.PlanCheckScheduler.Register(store.PlanCheckDatabaseConnect, databaseConnectExecutor)+ }+// Anomaly scanners.AnomalyScanner = anomaly.NewScanner(storeInstance, s.dbFactory, s.licenseService)@@ -947,6 +955,11 @@ func (s *Server) Run(ctx context.Context, port int) error {s.runnerWG.Add(1)go s.MetricReporter.Run(ctx, &s.runnerWG)++ if s.profile.Mode == common.ReleaseModeDev {+ s.runnerWG.Add(1)+ go s.PlanCheckScheduler.Run(ctx, &s.runnerWG)+ }}listen, err := net.Listen("tcp", fmt.Sprintf(":%d", port+1))diff --git a/backend/store/plan_check_run.go b/backend/store/plan_check_run.goindex ba74697f18..cbda0d61db 100644--- a/backend/store/plan_check_run.go+++ b/backend/store/plan_check_run.go@@ -1,6 +1,15 @@package store-import storepb "github.com/bytebase/bytebase/proto/generated-go/store"+import (+ "context"+ "fmt"+ "strings"++ "github.com/pkg/errors"+ "google.golang.org/protobuf/encoding/protojson"++ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)// PlanCheckRunType is the type of a plan check run.type PlanCheckRunType string@@ -53,3 +62,143 @@ type PlanCheckRunMessage struct {Config *storepb.PlanCheckRunConfigResult *storepb.PlanCheckRunResult}++// FindPlanCheckRunMessage is the message for finding plan check runs.+type FindPlanCheckRunMessage struct {+ Status *[]PlanCheckRunStatus+}++// CreatePlanCheckRuns creates new plan check runs.+func (s *Store) CreatePlanCheckRuns(ctx context.Context, creates ...*PlanCheckRunMessage) error {+ var query strings.Builder+ var values []any+ if _, err := query.WriteString(`INSERT INTO plan_check_run (+ creator_id,+ updater_id,+ plan_id,+ status,+ type,+ config,+ result+ ) VALUES+ `); err != nil {+ return err+ }+ for i, create := range creates {+ config, err := protojson.Marshal(create.Config)+ if err != nil {+ return errors.Wrapf(err, "faield to marshal create config %v", create.Config)+ }+ result, err := protojson.Marshal(create.Result)+ if err != nil {+ return errors.Wrapf(err, "failed to marshal create result %v", create.Result)+ }+ values = append(values,+ create.CreatorUID,+ create.UpdaterUID,+ create.PlanUID,+ create.Status,+ create.Type,+ config,+ result,+ )+ if i != 0 {+ if _, err := query.WriteString(","); err != nil {+ return err+ }+ }+ count := 7+ if _, err := query.WriteString(getPlaceholders(i*count+1, count)); err != nil {+ return err+ }+ }+ if _, err := s.db.db.ExecContext(ctx, query.String(), values...); err != nil {+ return errors.Wrapf(err, "failed to execute insert")+ }+ return nil+}++// ListPlanCheckRuns returns a list of plan check runs based on find.+func (s *Store) ListPlanCheckRuns(ctx context.Context, find *FindPlanCheckRunMessage) ([]*PlanCheckRunMessage, error) {+ where, args := []string{"TRUE"}, []any{}+ if v := find.Status; v != nil {+ var list []string+ for _, status := range *v {+ list = append(list, fmt.Sprintf("$%d", len(args)+1))+ args = append(args, status)+ }+ where = append(where, fmt.Sprintf("plan_check_run.status in (%s)", strings.Join(list, ",")))+ }+ query := fmt.Sprintf(`+ SELECT+ plan_check_run.id,+ plan_check_run.creator_id,+ plan_check_run.created_ts,+ plan_check_run.updater_id,+ plan_check_run.updated_ts,+ plan_check_run.plan_id,+ plan_check_run.status,+ plan_check_run.type,+ plan_check_run.config,+ plan_check_run.result+ FROM plan_check_run+ WHERE %s+ `, strings.Join(where, " AND "))+ rows, err := s.db.db.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var planCheckRuns []*PlanCheckRunMessage+ for rows.Next() {+ var planCheckRun PlanCheckRunMessage+ var config, result string+ if err := rows.Scan(+ &planCheckRun.UID,+ &planCheckRun.CreatorUID,+ &planCheckRun.CreatedTs,+ &planCheckRun.UpdaterUID,+ &planCheckRun.UpdatedTs,+ &planCheckRun.PlanUID,+ &planCheckRun.Status,+ &planCheckRun.Type,+ &config,+ &result,+ ); err != nil {+ return nil, err+ }+ if err := protojson.Unmarshal([]byte(config), planCheckRun.Config); err != nil {+ return nil, err+ }+ if err := protojson.Unmarshal([]byte(result), planCheckRun.Result); err != nil {+ return nil, err+ }+ planCheckRuns = append(planCheckRuns, &planCheckRun)+ }++ if err := rows.Err(); err != nil {+ return nil, err+ }++ return planCheckRuns, nil+}++// UpdatePlanCheckRun updates a plan check run.+func (s *Store) UpdatePlanCheckRun(ctx context.Context, updaterUID int, status PlanCheckRunStatus, result *storepb.PlanCheckRunResult, uid int) error {+ resultBytes, err := protojson.Marshal(result)+ if err != nil {+ return errors.Wrapf(err, "failed to marshal result %v", result)+ }+ query := `+ UPDATE plan_check_run+ SET+ updater_id = $1,+ status = $2,+ result = $3+ WHERE id = $4`+ if _, err := s.db.db.ExecContext(ctx, query, updaterUID, status, resultBytes, uid); err != nil {+ return errors.Wrapf(err, "failed to update plan check run")+ }+ return nil+}diff --git a/backend/store/store.go b/backend/store/store.goindex e5c58ed2c5..b423d47693 100644--- a/backend/store/store.go+++ b/backend/store/store.go@@ -4,6 +4,7 @@ package storeimport ("context""fmt"+ "strings""sync"cache "github.com/go-pkgz/expirable-cache/v2"@@ -75,3 +76,11 @@ func getDatabaseGroupCacheKey(projectUID int, databaseGroupResourceID string) stfunc getSchemaGroupCacheKey(databaseGroupUID int64, schemaGroupResourceID string) string {return fmt.Sprintf("%d/%s", databaseGroupUID, schemaGroupResourceID)}++func getPlaceholders(start int, count int) string {+ var placeholders []string+ for i := start; i < start+count; i++ {+ placeholders = append(placeholders, fmt.Sprintf("$%d", i))+ }+ return fmt.Sprintf("(%s)", strings.Join(placeholders, ","))+}