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: sync instance offline on instance creation (#2871)
Danny Xu7a5c17eccf61
diff --git a/api/data_source.go b/api/data_source.goindex ecb382fea2..fad596c5c2 100644--- a/api/data_source.go+++ b/api/data_source.go@@ -91,10 +91,6 @@ type DataSourceCreate struct {SslKey string `jsonapi:"attr,sslKey"`HostOverride string `jsonapi:"attr,hostOverride"`PortOverride string `jsonapi:"attr,portOverride"`- // If true, syncs the schema after creating the data source. The client- // may set to false if the target data source's instance contains too many databases- // to avoid the request timeout.- SyncSchema bool `jsonapi:"attr,syncSchema"`}// DataSourceFind is the API message for finding data sources.@@ -134,8 +130,4 @@ type DataSourcePatch struct {SslKey *string `jsonapi:"attr,sslKey"`HostOverride *string `jsonapi:"attr,hostOverride"`PortOverride *string `jsonapi:"attr,portOverride"`- // If true, syncs the schema after patching the data source. The client- // may set to false if the target data source's instance contains too many databases- // to avoid the request timeout.- SyncSchema bool `jsonapi:"attr,syncSchema"`}diff --git a/api/database.go b/api/database.goindex 2f0a6de126..780af802cf 100644--- a/api/database.go+++ b/api/database.go@@ -70,10 +70,11 @@ type DatabaseCreate struct {EnvironmentID int// Domain specific fields- Name string `jsonapi:"attr,name"`- CharacterSet string `jsonapi:"attr,characterSet"`- Collation string `jsonapi:"attr,collation"`- IssueID int `jsonapi:"attr,issueId"`+ Name string `jsonapi:"attr,name"`+ CharacterSet string `jsonapi:"attr,characterSet"`+ Collation string `jsonapi:"attr,collation"`+ IssueID int `jsonapi:"attr,issueId"`+ LastSuccessfulSyncTs int64// Labels is a json-encoded string from a list of DatabaseLabel,// e.g. "[{"key":"bb.location","value":"earth"},{"key":"bb.tenant","value":"bytebase"}]".Labels *string `jsonapi:"attr,labels"`diff --git a/api/instance.go b/api/instance.goindex 625aeed314..f31c94e0cd 100644--- a/api/instance.go+++ b/api/instance.go@@ -56,10 +56,6 @@ type InstanceCreate struct {SslCa string `jsonapi:"attr,sslCa"`SslCert string `jsonapi:"attr,sslCert"`SslKey string `jsonapi:"attr,sslKey"`- // If true, syncs the schema after adding the instance. The client- // may set to false if the target instance contains too many databases- // to avoid the request timeout.- SyncSchema bool `jsonapi:"attr,syncSchema"`}// InstanceFind is the API message for finding instances.@@ -100,10 +96,6 @@ type InstancePatch struct {ExternalLink *string `jsonapi:"attr,externalLink"`Host *string `jsonapi:"attr,host"`Port *string `jsonapi:"attr,port"`- // If true, syncs the schema after patching the instance. The client- // may set to false if the target instance contains too many databases- // to avoid the request timeout.- SyncSchema bool `jsonapi:"attr,syncSchema"`}// DataSourceFromInstanceWithType gets a typed data source from a instance.diff --git a/frontend/src/components/CreateInstanceForm.vue b/frontend/src/components/CreateInstanceForm.vueindex 0d73e8f57c..f577738e9f 100644--- a/frontend/src/components/CreateInstanceForm.vue+++ b/frontend/src/components/CreateInstanceForm.vue@@ -194,14 +194,9 @@</div><!-- Action Button Group -->- <div class="pt-4 px-2">+ <div class="pt-4"><!-- Create button group -->- <div class="flex justify-between items-center">- <BBCheckbox- :title="$t('instance.sync-schema-now')"- :value="state.instance.syncSchema"- @toggle="state.instance.syncSchema = !state.instance.syncSchema"- />+ <div class="flex justify-end items-center"><div class="flex justify-end items-center"><BBSpinv-if="state.isCreatingInstance"@@ -305,7 +300,6 @@ const state = reactive<LocalState>({// In release mode, Bytebase is likely run inside docker and access the local network via host.docker.internal.host: isDev() ? "127.0.0.1" : "host.docker.internal",username: "",- syncSchema: true,},showCreateInstanceWarningModal: false,createInstanceWarning: "",diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vueindex a5aba9d140..89d2b31f71 100644--- a/frontend/src/components/InstanceForm.vue+++ b/frontend/src/components/InstanceForm.vue@@ -328,14 +328,6 @@<!-- Action Button Group --><div class="pt-4 px-2"><div class="flex justify-between items-center">- <div>- <BBCheckbox- v-if="connectionInfoChanged"- :title="$t('instance.sync-schema-now')"- :value="state.syncSchema"- @toggle="state.syncSchema = !state.syncSchema"- />- </div><div class="flex justify-end items-center"><div><BBSpin v-if="state.isUpdating" :title="$t('common.updating')" />@@ -395,7 +387,6 @@ interface State {originalInstance: Instance;instance: Instance;isUpdating: boolean;- syncSchema: boolean;dataSourceList: EditDataSource[];currentDataSourceType: DataSourceType;}@@ -427,7 +418,6 @@ const state = reactive<State>({// Make hard copy since we are going to make equal comparison to determine the update button enable state.instance: cloneDeep(props.instance),isUpdating: false,- syncSchema: true,dataSourceList: dataSourceList,currentDataSourceType: "ADMIN",});@@ -655,7 +645,7 @@ const updateInstance = (field: string, value: string) => {};const doUpdate = () => {- const patchedInstance: InstancePatch = { syncSchema: state.syncSchema };+ const patchedInstance: InstancePatch = {};let instanceInfoChanged = false;let dataSourceListChanged = false;const reloadDatabaseAndUser = connectionInfoChanged.value;@@ -705,7 +695,6 @@ const doUpdate = () => {password: dataSource.password,hostOverride: dataSource.hostOverride,portOverride: dataSource.portOverride,- syncSchema: state.syncSchema,};if (typeof dataSource.sslCa !== "undefined") {dataSourceCreate.sslCa = dataSource.sslCa;@@ -725,7 +714,7 @@ const doUpdate = () => {dataSourceStore.patchDataSource({databaseId: dataSource.databaseId,dataSourceId: dataSource.id,- dataSource: { ...dataSource, syncSchema: state.syncSchema },+ dataSource: { ...dataSource },}));}@@ -770,7 +759,6 @@ const doUpdate = () => {}).finally(() => {state.isUpdating = false;- state.syncSchema = true;});});}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 6bca32cbab..bb210ec02f 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -581,7 +581,6 @@"select-database-user": "Select database user","new-database": "New Database","syncing": "Syncing ...",- "sync-schema-now": "Sync schema now","create-migration-schema": "Create migration schema","missing-migration-schema": "Missing migration schema","unable-to-connect-instance-to-check-migration-schema": "Unable to connect instance to check migration schema",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 1f1da319cd..76f3f23063 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -581,7 +581,6 @@"select-database-user": "选择数据库用户","new-database": "@:common.new@:common.database","syncing": "同步中 ...",- "sync-schema-now": "随即同步 schema","create-migration-schema": "@:common.create@:common.migration @:{'common.schema'}","missing-migration-schema": "缺少@:common.migration @:common.schema","unable-to-connect-instance-to-check-migration-schema": "无法连接到@:{'common.instance'}以检查@:{'common.migration'} @:{'common.schema'}",diff --git a/frontend/src/types/dataSource.ts b/frontend/src/types/dataSource.tsindex bf1e598153..900625c276 100644--- a/frontend/src/types/dataSource.ts+++ b/frontend/src/types/dataSource.ts@@ -59,7 +59,6 @@ export type DataSourceCreate = {sslKey?: string;hostOverride: string;portOverride: string;- syncSchema: boolean;};export type DataSourcePatch = {@@ -73,7 +72,6 @@ export type DataSourcePatch = {sslKey?: string;hostOverride: string;portOverride: string;- syncSchema: boolean;};export type DataSourceMember = {diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.tsindex dfce908939..3781e6d109 100644--- a/frontend/src/types/instance.ts+++ b/frontend/src/types/instance.ts@@ -81,8 +81,6 @@ export type InstanceCreate = {sslCa?: string;sslCert?: string;sslKey?: string;-- syncSchema: boolean;};export type InstancePatch = {@@ -94,7 +92,6 @@ export type InstancePatch = {externalLink?: string;host?: string;port?: string;- syncSchema?: boolean;};export type MigrationSchemaStatus = "UNKNOWN" | "OK" | "NOT_EXIST";diff --git a/server/database.go b/server/database.goindex c3fa6c62a1..64664feafe 100644--- a/server/database.go+++ b/server/database.go@@ -690,18 +690,18 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create data source").SetInternal(err)}- if dataSourceCreate.SyncSchema {- // Refetch the instance to get the updated data source.- updatedInstance, err := s.store.GetInstanceByID(ctx, database.InstanceID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated instance with ID %d", database.InstanceID)).SetInternal(err)- }- if err := s.syncEngineVersionAndSchema(ctx, updatedInstance); err != nil {- log.Warn("Failed to sync instance schema",- zap.Int("instance_id", updatedInstance.ID),- zap.Error(err))- }+ // Refetch the instance to get the updated data source.+ updatedInstance, err := s.store.GetInstanceByID(ctx, database.InstanceID)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated instance with ID %d", database.InstanceID)).SetInternal(err)+ }+ if _, err := s.syncInstance(ctx, updatedInstance); err != nil {+ log.Warn("Failed to sync instance",+ zap.Int("instance_id", updatedInstance.ID),+ zap.Error(err))}+ // Sync all databases in the instance asynchronously.+ instanceSyncChan <- updatedInstancec.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, dataSource); err != nil {@@ -765,18 +765,18 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update data source with ID %d", dataSourceID)).SetInternal(err)}- if dataSourcePatch.SyncSchema {- // Refetch the instance to get the updated data source.- updatedInstance, err := s.store.GetInstanceByID(ctx, database.InstanceID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated instance with ID %d", database.InstanceID)).SetInternal(err)- }- if err := s.syncEngineVersionAndSchema(ctx, updatedInstance); err != nil {- log.Warn("Failed to sync instance schema",- zap.Int("instance_id", updatedInstance.ID),- zap.Error(err))- }+ // Refetch the instance to get the updated data source.+ updatedInstance, err := s.store.GetInstanceByID(ctx, database.InstanceID)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated instance with ID %d", database.InstanceID)).SetInternal(err)+ }+ if _, err := s.syncInstance(ctx, updatedInstance); err != nil {+ log.Warn("Failed to sync instance",+ zap.Int("instance_id", updatedInstance.ID),+ zap.Error(err))}+ // Sync all databases in the instance asynchronously.+ instanceSyncChan <- updatedInstancec.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, dataSourceNew); err != nil {diff --git a/server/instance.go b/server/instance.goindex 0da01d2d4c..20a17b1f38 100644--- a/server/instance.go+++ b/server/instance.go@@ -64,13 +64,13 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {zap.String("engine", string(instance.Engine)),zap.Error(err))}- if instanceCreate.SyncSchema {- if err := s.syncEngineVersionAndSchema(ctx, instance); err != nil {- log.Warn("Failed to sync instance schema",- zap.Int("instance_id", instance.ID),- zap.Error(err))- }+ if _, err := s.syncInstance(ctx, instance); err != nil {+ log.Warn("Failed to sync instance",+ zap.Int("instance_id", instance.ID),+ zap.Error(err))}+ // Sync all databases in the instance asynchronously.+ instanceSyncChan <- instance}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)@@ -202,13 +202,13 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {zap.String("engine", string(instancePatched.Engine)),zap.Error(err))}- if instancePatch.SyncSchema {- if err := s.syncEngineVersionAndSchema(ctx, instancePatched); err != nil {- log.Warn("Failed to sync instance schema",- zap.Int("instance_id", instancePatched.ID),- zap.Error(err))- }+ if _, err := s.syncInstance(ctx, instancePatched); err != nil {+ log.Warn("Failed to sync instance",+ zap.Int("instance_id", instancePatched.ID),+ zap.Error(err))}+ // Sync all databases in the instance asynchronously.+ instanceSyncChan <- instancePatched}}diff --git a/server/schema_syncer.go b/server/schema_syncer.goindex 40daedb49b..bc17f3c244 100644--- a/server/schema_syncer.go+++ b/server/schema_syncer.go@@ -17,6 +17,10 @@ const (schemaSyncInterval = time.Duration(30) * time.Minute)+var (+ instanceSyncChan chan *api.Instance = make(chan *api.Instance)+)+// NewSchemaSyncer creates a schema syncer.func NewSchemaSyncer(server *Server) *SchemaSyncer {return &SchemaSyncer{@@ -52,8 +56,6 @@ func (s *SchemaSyncer) Run(ctx context.Context, wg *sync.WaitGroup) {}}()- ctx := context.Background()-rowStatus := api.NormalinstanceFind := &api.InstanceFind{RowStatus: &rowStatus,@@ -80,15 +82,62 @@ func (s *SchemaSyncer) Run(ctx context.Context, wg *sync.WaitGroup) {delete(runningTasks, instance.ID)mu.Unlock()}()- if err := s.server.syncEngineVersionAndSchema(ctx, instance); err != nil {+ databaseList, err := s.server.syncInstance(ctx, instance)+ if err != nil {log.Debug("Failed to sync instance",zap.Int("id", instance.ID),zap.String("name", instance.Name),zap.String("error", err.Error()))+ return+ }+ for _, databaseName := range databaseList {+ // If we fail to sync a particular database due to permission issue, we will continue to sync the rest of the databases.+ if err := s.server.syncDatabaseSchema(ctx, instance, databaseName); err != nil {+ log.Debug("Failed to sync database schema",+ zap.Int("instanceID", instance.ID),+ zap.String("instanceName", instance.Name),+ zap.String("databaseName", databaseName),+ zap.String("error", err.Error()))+ }}}(instance)}}()+ case instance := <-instanceSyncChan:+ go func(instance *api.Instance) {+ defer func() {+ if r := recover(); r != nil {+ err, ok := r.(error)+ if !ok {+ err = errors.Errorf("%v", r)+ }+ log.Error("Schema syncer PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ }+ }()++ databaseList, err := s.server.store.FindDatabase(ctx, &api.DatabaseFind{InstanceID: &instance.ID})+ if err != nil {+ log.Debug("Failed to find databases for the syncing instance",+ zap.Int("id", instance.ID),+ zap.String("name", instance.Name),+ zap.String("error", err.Error()))+ return+ }+ for _, database := range databaseList {+ if database.SyncStatus != api.OK {+ continue+ }++ // If we fail to sync a particular database due to permission issue, we will continue to sync the rest of the databases.+ if err := s.server.syncDatabaseSchema(ctx, instance, database.Name); err != nil {+ log.Debug("Failed to sync database schema",+ zap.Int("instanceID", instance.ID),+ zap.String("instanceName", instance.Name),+ zap.String("databaseName", database.Name),+ zap.String("error", err.Error()))+ }+ }+ }(instance)case <-ctx.Done(): // if cancel() executereturn}diff --git a/server/sql.go b/server/sql.goindex 6e7326767c..179306b777 100644--- a/server/sql.go+++ b/server/sql.go@@ -126,9 +126,11 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {if instance == nil {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", *sync.InstanceID))}- if err := s.syncEngineVersionAndSchema(ctx, instance); err != nil {+ if _, err := s.syncInstance(ctx, instance); err != nil {resultSet.Error = err.Error()}+ // Sync all databases in the instance asynchronously.+ instanceSyncChan <- instance}if sync.DatabaseID != nil {database, err := s.store.GetDatabase(ctx, &api.DatabaseFind{ID: sync.DatabaseID})@@ -344,30 +346,14 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {})}-func (s *Server) syncEngineVersionAndSchema(ctx context.Context, instance *api.Instance) error {+func (s *Server) syncInstance(ctx context.Context, instance *api.Instance) ([]string, error) {driver, err := tryGetReadOnlyDatabaseDriver(ctx, instance, "")if err != nil {- return err+ return nil, err}defer driver.Close(ctx)- databaseList, err := s.syncInstanceSchema(ctx, instance, driver)- if err != nil {- return err- }-- var errorList []string- for _, databaseName := range databaseList {- // If we fail to sync a particular database due to permission issue, we will continue to sync the rest of the databases.- if err := s.syncDatabaseSchema(ctx, instance, databaseName); err != nil {- errorList = append(errorList, err.Error())- }- }- if len(errorList) > 0 {- return errors.Errorf("sync database schema errors, %s", strings.Join(errorList, ", "))- }-- return nil+ return s.syncInstanceSchema(ctx, instance, driver)}// syncInstanceSchema syncs the instance and all database metadata first without diving into the deep structure of each database.@@ -463,13 +449,14 @@ func (s *Server) syncInstanceSchema(ctx context.Context, instance *api.Instance,}// Case 2, only appear in the synced db schema.databaseCreate := &api.DatabaseCreate{- CreatorID: api.SystemBotID,- ProjectID: api.DefaultProjectID,- InstanceID: instance.ID,- EnvironmentID: instance.EnvironmentID,- Name: databaseName,- CharacterSet: databaseMetadata.CharacterSet,- Collation: databaseMetadata.Collation,+ CreatorID: api.SystemBotID,+ ProjectID: api.DefaultProjectID,+ InstanceID: instance.ID,+ EnvironmentID: instance.EnvironmentID,+ Name: databaseName,+ CharacterSet: databaseMetadata.CharacterSet,+ Collation: databaseMetadata.Collation,+ LastSuccessfulSyncTs: 0,}if _, err := s.store.CreateDatabase(ctx, databaseCreate); err != nil {if common.ErrorCode(err) == common.Conflict {@@ -566,14 +553,15 @@ func (s *Server) syncDatabaseSchema(ctx context.Context, instance *api.Instance,database = dbPatched} else {databaseCreate := &api.DatabaseCreate{- CreatorID: api.SystemBotID,- ProjectID: api.DefaultProjectID,- InstanceID: instance.ID,- EnvironmentID: instance.EnvironmentID,- Name: schema.Name,- CharacterSet: schema.CharacterSet,- Collation: schema.Collation,- SchemaVersion: schemaVersion,+ CreatorID: api.SystemBotID,+ ProjectID: api.DefaultProjectID,+ InstanceID: instance.ID,+ EnvironmentID: instance.EnvironmentID,+ Name: schema.Name,+ CharacterSet: schema.CharacterSet,+ Collation: schema.Collation,+ SchemaVersion: schemaVersion,+ LastSuccessfulSyncTs: time.Now().Unix(),}createdDatabase, err := s.store.CreateDatabase(ctx, databaseCreate)if err != nil {diff --git a/server/task_executor_database_create.go b/server/task_executor_database_create.goindex 02fe8e28e8..f4e929de55 100644--- a/server/task_executor_database_create.go+++ b/server/task_executor_database_create.go@@ -7,6 +7,7 @@ import ("strconv""strings""sync/atomic"+ "time""github.com/pkg/errors""go.uber.org/zap"@@ -125,15 +126,16 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser}if database == nil {databaseCreate := &api.DatabaseCreate{- CreatorID: api.SystemBotID,- ProjectID: payload.ProjectID,- InstanceID: task.InstanceID,- EnvironmentID: instance.EnvironmentID,- Name: payload.DatabaseName,- CharacterSet: payload.CharacterSet,- Collation: payload.Collation,- Labels: &payload.Labels,- SchemaVersion: payload.SchemaVersion,+ CreatorID: api.SystemBotID,+ ProjectID: payload.ProjectID,+ InstanceID: task.InstanceID,+ EnvironmentID: instance.EnvironmentID,+ Name: payload.DatabaseName,+ CharacterSet: payload.CharacterSet,+ Collation: payload.Collation,+ LastSuccessfulSyncTs: time.Now().Unix(),+ Labels: &payload.Labels,+ SchemaVersion: payload.SchemaVersion,}createdDatabase, err := server.store.CreateDatabase(ctx, databaseCreate)if err != nil {diff --git a/store/database.go b/store/database.goindex f5bcb2dd9f..52b2f10273 100644--- a/store/database.go+++ b/store/database.go@@ -439,7 +439,7 @@ func (*Store) createDatabaseImpl(ctx context.Context, tx *Tx, create *api.Databalast_successful_sync_ts,schema_version)- VALUES ($1, $2, $3, $4, $5, $6, $7, 'OK', EXTRACT(epoch from NOW()), $8)+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'OK', $8, $9)RETURNINGid,creator_id,@@ -464,6 +464,7 @@ func (*Store) createDatabaseImpl(ctx context.Context, tx *Tx, create *api.Databacreate.Name,create.CharacterSet,create.Collation,+ create.LastSuccessfulSyncTs,create.SchemaVersion,).Scan(&databaseRaw.ID,diff --git a/tests/sql_review_test.go b/tests/sql_review_test.goindex df02707ae6..c0687a5f3b 100644--- a/tests/sql_review_test.go+++ b/tests/sql_review_test.go@@ -331,11 +331,6 @@ func TestSQLReviewForPostgreSQL(t *testing.T) {})a.NoError(err)a.Nil(databases)- databases, err = ctl.getDatabases(api.DatabaseFind{- InstanceID: &instance.ID,- })- a.NoError(err)- a.Nil(databases)err = ctl.createDatabase(project, instance, databaseName, "bytebase", nil)a.NoError(err)