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: implement CRUD for instance OpenAPI (#3428)
ecmadao80e41e683870
diff --git a/api/v1/instance.go b/api/v1/instance.goindex b857738737..99357bfeb7 100644--- a/api/v1/instance.go+++ b/api/v1/instance.go@@ -6,7 +6,7 @@ import (// Instance is the API message for an instance.type Instance struct {- ID int `jsonapi:"primary,instance" json:"id"`+ ID int `json:"id"`// Related fieldsEnvironment string `json:"environment"`@@ -20,3 +20,30 @@ type Instance struct {Port string `json:"port"`Username string `json:"username"`}++// InstanceCreate is the API message for creating an instance.+type InstanceCreate struct {+ // Related fields+ Environment string `json:"environment"`++ // Domain specific fields+ Name string `json:"name"`+ Engine db.Type `json:"engine"`+ ExternalLink string `json:"externalLink"`+ Host string `json:"host"`+ Port string `json:"port"`+ Username string `json:"username"`+ Password string `json:"password"`+ SslCa string `json:"sslCa"`+ SslCert string `json:"sslCert"`+ SslKey string `json:"sslKey"`+}++// InstancePatch is the API message for patching an instance.+type InstancePatch struct {+ // Domain specific fields+ Name *string `json:"name"`+ ExternalLink *string `json:"externalLink"`+ Host *string `json:"host"`+ Port *string `json:"port"`+}diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csvindex b4127818b0..efe3afd812 100644--- a/server/acl_casbin_policy_dba.csv+++ b/server/acl_casbin_policy_dba.csv@@ -36,6 +36,7 @@ p, DBA, /instance, POSTp, DBA, /instance, GETp, DBA, /instance/{instanceID}, GETp, DBA, /instance/{instanceID}, PATCH+p, DBA, /instance/{instanceID}, DELETEp, DBA, /instance/{instanceID}/user, GETp, DBA, /instance/{instanceID}/user/{userID}, GETp, DBA, /instance/{instanceID}/migration, POSTdiff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex db714ea7a3..b5ea2ccaa7 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -39,6 +39,7 @@ p, OWNER, /instance, POSTp, OWNER, /instance, GETp, OWNER, /instance/{instanceID}, GETp, OWNER, /instance/{instanceID}, PATCH+p, OWNER, /instance/{instanceID}, DELETEp, OWNER, /instance/{instanceID}/user, GETp, OWNER, /instance/{instanceID}/user/{userID}, GETp, OWNER, /instance/{instanceID}/migration, POSTdiff --git a/server/instance.go b/server/instance.goindex d0ba945863..f519fe9a4a 100644--- a/server/instance.go+++ b/server/instance.go@@ -31,46 +31,17 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {// Besides adding the instance to Bytebase, it will also try to create a "bytebase" db in the newly added instance.g.POST("/instance", func(c echo.Context) error {ctx := c.Request().Context()- if err := s.instanceCountGuard(ctx); err != nil {- return err- }- instanceCreate := &api.InstanceCreate{}+ instanceCreate := &api.InstanceCreate{+ CreatorID: c.Get(getPrincipalIDContextKey()).(int),+ }if err := jsonapi.UnmarshalPayload(c.Request().Body, instanceCreate); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed create instance request").SetInternal(err)}- instanceCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)- if err := s.disallowBytebaseStore(instanceCreate.Engine, instanceCreate.Host, instanceCreate.Port); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)- }- instance, err := s.store.CreateInstance(ctx, instanceCreate)+ instance, err := s.createInstance(ctx, instanceCreate)if err != nil {- if common.ErrorCode(err) == common.Conflict {- return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Instance name already exists: %s", instanceCreate.Name))- }- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create instance").SetInternal(err)- }-- // Try creating the "bytebase" db in the added instance if needed.- // Since we allow user to add new instance upfront even providing the incorrect username/password,- // thus it's OK if it fails. Frontend will surface relevant info suggesting the "bytebase" db hasn't created yet.- db, err := getAdminDatabaseDriver(ctx, instance, "" /* databaseName */, s.pgInstance.BaseDir, s.profile.DataDir)- if err == nil {- defer db.Close(ctx)- if err := db.SetupMigrationIfNeeded(ctx); err != nil {- log.Warn("Failed to setup migration schema on instance creation",- zap.String("instance_name", instance.Name),- zap.String("engine", string(instance.Engine)),- 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.- instanceDatabaseSyncChan <- instance+ return err}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)@@ -136,80 +107,9 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch instance request").SetInternal(err)}- instance, err := s.store.GetInstanceByID(ctx, id)+ instancePatched, err := s.updateInstance(ctx, instancePatch)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get instance ID: %v", id)).SetInternal(err)- }- if instance == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))- }-- host, port := instance.Host, instance.Port- if instancePatch.Host != nil {- host = *instancePatch.Host- }- if instancePatch.Port != nil {- port = *instancePatch.Port- }- if err := s.disallowBytebaseStore(instance.Engine, host, port); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)- }-- var instancePatched *api.Instance- if instancePatch.RowStatus != nil || instancePatch.Name != nil || instancePatch.ExternalLink != nil || instancePatch.Host != nil || instancePatch.Port != nil {- // Users can switch instance status from ARCHIVED to NORMAL.- // So we need to check the current instance count with NORMAL status for quota limitation.- if instancePatch.RowStatus != nil && *instancePatch.RowStatus == string(api.Normal) {- if err := s.instanceCountGuard(ctx); err != nil {- return err- }- }- // Ensure all databases belong to this instance are under the default project before instance is archived.- if v := instancePatch.RowStatus; v != nil && *v == string(api.Archived) {- databases, err := s.store.FindDatabase(ctx, &api.DatabaseFind{InstanceID: &id})- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError,- errors.Errorf("failed to find databases in the instance %d", id)).SetInternal(err)- }- var databaseNameList []string- for _, database := range databases {- if database.ProjectID != api.DefaultProjectID {- databaseNameList = append(databaseNameList, database.Name)- }- }- if len(databaseNameList) > 0 {- return echo.NewHTTPError(http.StatusBadRequest,- fmt.Sprintf("You should transfer these databases to the default project before archiving the instance: %s.", strings.Join(databaseNameList, ", ")))- }- }- instancePatched, err = s.store.PatchInstance(ctx, instancePatch)- if err != nil {- if common.ErrorCode(err) == common.NotFound {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))- }- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch instance ID: %v", id)).SetInternal(err)- }- }-- // Try immediately setup the migration schema, sync the engine version and schema after updating any connection related info.- if instancePatch.Host != nil || instancePatch.Port != nil {- db, err := getAdminDatabaseDriver(ctx, instancePatched, "" /* databaseName */, s.pgInstance.BaseDir, s.profile.DataDir)- if err == nil {- defer db.Close(ctx)- if err := db.SetupMigrationIfNeeded(ctx); err != nil {- log.Warn("Failed to setup migration schema on instance update",- zap.String("instance_name", instancePatched.Name),- zap.String("engine", string(instancePatched.Engine)),- 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.- instanceDatabaseSyncChan <- instancePatched- }+ return err}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)@@ -533,3 +433,124 @@ func (s *Server) disallowBytebaseStore(engine db.Type, host, port string) error}return nil}++func (s *Server) createInstance(ctx context.Context, create *api.InstanceCreate) (*api.Instance, error) {+ if err := s.instanceCountGuard(ctx); err != nil {+ return nil, err+ }++ if err := s.disallowBytebaseStore(create.Engine, create.Host, create.Port); err != nil {+ return nil, echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)+ }++ instance, err := s.store.CreateInstance(ctx, create)+ if err != nil {+ if common.ErrorCode(err) == common.Conflict {+ return nil, echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Instance name already exists: %s", create.Name))+ }+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to create instance").SetInternal(err)+ }++ // Try creating the "bytebase" db in the added instance if needed.+ // Since we allow user to add new instance upfront even providing the incorrect username/password,+ // thus it's OK if it fails. Frontend will surface relevant info suggesting the "bytebase" db hasn't created yet.+ db, err := getAdminDatabaseDriver(ctx, instance, "" /* databaseName */, s.pgInstance.BaseDir, s.profile.DataDir)+ if err == nil {+ defer db.Close(ctx)+ if err := db.SetupMigrationIfNeeded(ctx); err != nil {+ log.Warn("Failed to setup migration schema on instance creation",+ zap.String("instance_name", instance.Name),+ zap.String("engine", string(instance.Engine)),+ 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.+ instanceDatabaseSyncChan <- instance+ }++ return instance, nil+}++func (s *Server) updateInstance(ctx context.Context, patch *api.InstancePatch) (*api.Instance, error) {+ instance, err := s.store.GetInstanceByID(ctx, patch.ID)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get instance ID: %v", patch.ID)).SetInternal(err)+ }+ if instance == nil {+ return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", patch.ID))+ }++ host, port := instance.Host, instance.Port+ if patch.Host != nil {+ host = *patch.Host+ }+ if patch.Port != nil {+ port = *patch.Port+ }+ if err := s.disallowBytebaseStore(instance.Engine, host, port); err != nil {+ return nil, echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)+ }++ var instancePatched *api.Instance+ if patch.RowStatus != nil || patch.Name != nil || patch.ExternalLink != nil || patch.Host != nil || patch.Port != nil {+ // Users can switch instance status from ARCHIVED to NORMAL.+ // So we need to check the current instance count with NORMAL status for quota limitation.+ if patch.RowStatus != nil && *patch.RowStatus == string(api.Normal) {+ if err := s.instanceCountGuard(ctx); err != nil {+ return nil, err+ }+ }+ // Ensure all databases belong to this instance are under the default project before instance is archived.+ if v := patch.RowStatus; v != nil && *v == string(api.Archived) {+ databases, err := s.store.FindDatabase(ctx, &api.DatabaseFind{InstanceID: &patch.ID})+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError,+ errors.Errorf("failed to find databases in the instance %d", patch.ID)).SetInternal(err)+ }+ var databaseNameList []string+ for _, database := range databases {+ if database.ProjectID != api.DefaultProjectID {+ databaseNameList = append(databaseNameList, database.Name)+ }+ }+ if len(databaseNameList) > 0 {+ return nil, echo.NewHTTPError(http.StatusBadRequest,+ fmt.Sprintf("You should transfer these databases to the default project before archiving the instance: %s.", strings.Join(databaseNameList, ", ")))+ }+ }+ instancePatched, err = s.store.PatchInstance(ctx, patch)+ if err != nil {+ if common.ErrorCode(err) == common.NotFound {+ return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", patch.ID))+ }+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch instance ID: %v", patch.ID)).SetInternal(err)+ }+ }++ // Try immediately setup the migration schema, sync the engine version and schema after updating any connection related info.+ if patch.Host != nil || patch.Port != nil {+ db, err := getAdminDatabaseDriver(ctx, instancePatched, "" /* databaseName */, s.pgInstance.BaseDir, s.profile.DataDir)+ if err == nil {+ defer db.Close(ctx)+ if err := db.SetupMigrationIfNeeded(ctx); err != nil {+ log.Warn("Failed to setup migration schema on instance update",+ zap.String("instance_name", instancePatched.Name),+ zap.String("engine", string(instancePatched.Engine)),+ 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.+ instanceDatabaseSyncChan <- instancePatched+ }+ }++ return instancePatched, nil+}diff --git a/server/openapi_instance.go b/server/openapi_instance.goindex 219163b3e4..2b5ed32dea 100644--- a/server/openapi_instance.go+++ b/server/openapi_instance.go@@ -1,7 +1,11 @@package serverimport (+ "encoding/json"+ "fmt"+ "io""net/http"+ "strconv""github.com/labstack/echo/v4"@@ -10,7 +14,11 @@ import ()func (s *Server) registerOpenAPIRoutesForInstance(g *echo.Group) {+ g.POST("/instance", s.createInstanceByOpenAPI)g.GET("/instance", s.listInstance)+ g.GET("/instance/:instanceID", s.getInstanceByID)+ g.PATCH("/instance/:instanceID", s.updateInstanceByOpenAPI)+ g.DELETE("/instance/:instanceID", s.archiveInstanceByOpenAPI)}func (s *Server) listInstance(c echo.Context) error {@@ -33,6 +41,120 @@ func (s *Server) listInstance(c echo.Context) error {return c.JSON(http.StatusOK, response)}+func (s *Server) createInstanceByOpenAPI(c echo.Context) error {+ ctx := c.Request().Context()++ body, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to read request body").SetInternal(err)+ }++ instanceCreate := &openAPIV1.InstanceCreate{}+ if err := json.Unmarshal(body, instanceCreate); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed create instance request").SetInternal(err)+ }++ environmentName := instanceCreate.Environment+ envList, err := s.store.FindEnvironment(ctx, &api.EnvironmentFind{+ Name: &environmentName,+ })+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find environment by name: %s", instanceCreate.Environment)).SetInternal(err)+ }+ if len(envList) != 1 {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Should only find one environment with name: %s", instanceCreate.Environment))+ }++ instance, err := s.createInstance(ctx, &api.InstanceCreate{+ CreatorID: c.Get(getPrincipalIDContextKey()).(int),+ EnvironmentID: envList[0].ID,+ Name: instanceCreate.Name,+ Engine: instanceCreate.Engine,+ ExternalLink: instanceCreate.ExternalLink,+ Host: instanceCreate.Host,+ Port: instanceCreate.Port,+ Username: instanceCreate.Username,+ Password: instanceCreate.Password,+ SslCa: instanceCreate.SslCa,+ SslCert: instanceCreate.SslCert,+ SslKey: instanceCreate.SslKey,+ })+ if err != nil {+ return err+ }++ return c.JSON(http.StatusOK, convertToOpenAPIInstance(instance))+}++func (s *Server) updateInstanceByOpenAPI(c echo.Context) error {+ ctx := c.Request().Context()+ id, err := strconv.Atoi(c.Param("instanceID"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)+ }++ body, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to read request body").SetInternal(err)+ }++ instancePatch := &openAPIV1.InstancePatch{}+ if err := json.Unmarshal(body, instancePatch); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch instance request").SetInternal(err)+ }++ instance, err := s.updateInstance(ctx, &api.InstancePatch{+ ID: id,+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ Name: instancePatch.Name,+ ExternalLink: instancePatch.ExternalLink,+ Host: instancePatch.Host,+ Port: instancePatch.Port,+ })+ if err != nil {+ return err+ }++ return c.JSON(http.StatusOK, convertToOpenAPIInstance(instance))+}++func (s *Server) archiveInstanceByOpenAPI(c echo.Context) error {+ ctx := c.Request().Context()+ id, err := strconv.Atoi(c.Param("instanceID"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)+ }++ rowStatus := string(api.Archived)+ if _, err := s.updateInstance(ctx, &api.InstancePatch{+ ID: id,+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ RowStatus: &rowStatus,+ }); err != nil {+ return err+ }++ return c.String(http.StatusOK, "ok")+}++func (s *Server) getInstanceByID(c echo.Context) error {+ ctx := c.Request().Context()+ id, err := strconv.Atoi(c.Param("instanceID"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)+ }++ instance, err := s.store.GetInstanceByID(ctx, id)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", id)).SetInternal(err)+ }+ if instance == nil {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))+ }++ return c.JSON(http.StatusOK, convertToOpenAPIInstance(instance))+}+func convertToOpenAPIInstance(instance *api.Instance) *openAPIV1.Instance {return &openAPIV1.Instance{ID: instance.ID,