diff --git a/cluster/events.go b/cluster/events.go index 27b0981..1d20546 100644 --- a/cluster/events.go +++ b/cluster/events.go @@ -29,6 +29,7 @@ type ActivateConfig struct { type UpsertConfig struct { Config entity.Config Create bool + Unsafe bool } type DeleteConfigs struct { diff --git a/controller/common_config.go b/controller/common_config.go index 9c28b95..b531f97 100644 --- a/controller/common_config.go +++ b/controller/common_config.go @@ -87,8 +87,6 @@ func (c *commonConfig) DeleteConfigs(req domain.ConfigIdRequest) (*domain.Delete return &response, nil } -type CompiledConfig map[string]interface{} - // CompileConfigs godoc // @Summary Метод компиляции итоговой конфигурации для модулей // @Description Возвращает скомпилированный объект конфигурации @@ -96,9 +94,9 @@ type CompiledConfig map[string]interface{} // @Accept json // @Produce json // @Param body body domain.CompileConfigsRequest true "перечисление идентификаторов общей конфигурации и исхдных конфиг" -// @Success 200 {object} CompiledConfig +// @Success 200 {object} domain.CompiledConfigResponse // @Router /common_config/compile [POST] -func (c *commonConfig) CompileConfigs(req domain.CompileConfigsRequest) CompiledConfig { +func (c *commonConfig) CompileConfigs(req domain.CompileConfigsRequest) domain.CompiledConfigResponse { var result map[string]interface{} c.rstore.VisitReadonlyState(func(state state.ReadonlyState) { result = service.ConfigService.CompileConfig(req.Data, state, req.CommonConfigsIdList...) diff --git a/controller/config.go b/controller/config.go index cd4b5fd..2e52638 100644 --- a/controller/config.go +++ b/controller/config.go @@ -49,18 +49,19 @@ func (c *config) GetActiveConfigByModuleName(request domain.GetByModuleNameReque // @Tags Конфигурация // @Accept json // @Produce json -// @Param body body entity.Config true "объект для сохранения" -// @Success 200 {object} entity.Config +// @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения" +// @Success 200 {object} domain.ConfigModuleInfo // @Failure 404 {object} structure.GrpcError "если конфигурация не найдена" // @Failure 500 {object} structure.GrpcError // @Router /config/create_update_config [POST] -func (c *config) CreateUpdateConfig(config entity.Config) (*entity.Config, error) { - var response entity.Config +func (c *config) CreateUpdateConfig(config domain.CreateUpdateConfigRequest) (*domain.ConfigModuleInfo, error) { + var response domain.CreateUpdateConfigResponse now := state.GenerateDate() config.CreatedAt = now config.UpdatedAt = now upsertConfig := cluster.UpsertConfig{ - Config: config, + Config: config.Config, + Unsafe: config.Unsafe, } if config.Id == "" { upsertConfig.Config.Id = state.GenerateId() @@ -70,8 +71,11 @@ func (c *config) CreateUpdateConfig(config entity.Config) (*entity.Config, error err := PerformSyncApplyWithError(command, "UpsertConfigCommand", &response) if err != nil { return nil, err + } else if response.Config != nil { + return response.Config, nil + } else { + return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, response.ErrorDetails) } - return &response, nil } // MarkConfigAsActive godoc diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 94eacff..37ca88d 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -13,8 +13,10 @@ definitions: type: array data: type: object - required: - - commonConfigsIdList + type: object + domain.CompiledConfigResponse: + additionalProperties: + type: object type: object domain.ConfigIdRequest: properties: @@ -23,6 +25,37 @@ definitions: required: - id type: object + domain.ConfigModuleInfo: + properties: + active: + type: boolean + commonConfigs: + items: + type: string + type: array + createdAt: + type: string + data: + $ref: '#/definitions/entity.ConfigData' + type: object + description: + type: string + id: + type: string + moduleId: + type: string + name: + type: string + updatedAt: + type: string + valid: + type: boolean + version: + type: integer + required: + - moduleId + - name + type: object domain.Connection: properties: address: @@ -39,6 +72,37 @@ definitions: version: type: string type: object + domain.CreateUpdateConfigRequest: + properties: + active: + type: boolean + commonConfigs: + items: + type: string + type: array + createdAt: + type: string + data: + $ref: '#/definitions/entity.ConfigData' + type: object + description: + type: string + id: + type: string + moduleId: + type: string + name: + type: string + unsafe: + type: boolean + updatedAt: + type: string + version: + type: integer + required: + - moduleId + - name + type: object domain.DeleteCommonConfigResponse: properties: deleted: @@ -75,7 +139,7 @@ definitions: type: object configs: items: - $ref: '#/definitions/entity.Config' + $ref: '#/definitions/domain.ConfigModuleInfo' type: array createdAt: type: string @@ -590,7 +654,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/CompiledConfig' + $ref: '#/definitions/domain.CompiledConfigResponse' summary: Метод компиляции итоговой конфигурации для модулей tags: - Общие конфигурации @@ -623,7 +687,7 @@ paths: description: Internal Server Error schema: $ref: '#/definitions/structure.GrpcError' - summary: Метод обновления оьщей конфигурации + summary: Метод обновления общей конфигурации tags: - Общие конфигурации /common_config/delete_config: @@ -708,7 +772,7 @@ paths: name: body required: true schema: - $ref: '#/definitions/entity.Config' + $ref: '#/definitions/domain.CreateUpdateConfigRequest' type: object produces: - application/json @@ -716,7 +780,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/entity.Config' + $ref: '#/definitions/domain.ConfigModuleInfo' "404": description: если конфигурация не найдена schema: diff --git a/domain/request.go b/domain/request.go index 0c79a9e..e997be9 100644 --- a/domain/request.go +++ b/domain/request.go @@ -1,5 +1,7 @@ package domain +import "isp-config-service/entity" + type ConfigIdRequest struct { Id string `json:"id" valid:"required~Required"` } @@ -16,3 +18,8 @@ type GetByModuleIdRequest struct { type GetByModuleNameRequest struct { ModuleName string `valid:"required~Required"` } + +type CreateUpdateConfigRequest struct { + entity.Config + Unsafe bool +} diff --git a/domain/response.go b/domain/response.go index 35c477f..8ce7a38 100644 --- a/domain/response.go +++ b/domain/response.go @@ -18,9 +18,9 @@ type ModuleInfo struct { CreatedAt time.Time LastConnectedAt time.Time LastDisconnectedAt time.Time - Configs []entity.Config `json:",omitempty"` - ConfigSchema *schema.Schema `json:",omitempty"` - Status []Connection `json:",omitempty"` + Configs []ConfigModuleInfo `json:",omitempty"` + ConfigSchema *schema.Schema `json:",omitempty"` + Status []Connection `json:",omitempty"` } type Connection struct { @@ -33,7 +33,19 @@ type Connection struct { type CommonConfigLinks map[string][]string +type CompiledConfigResponse map[string]interface{} + type DeleteCommonConfigResponse struct { Deleted bool Links CommonConfigLinks } + +type CreateUpdateConfigResponse struct { + ErrorDetails map[string]string + Config *ConfigModuleInfo +} + +type ConfigModuleInfo struct { + entity.Config + Valid bool +} diff --git a/helper/handler.go b/helper/handler.go index e2eab7d..9744e05 100644 --- a/helper/handler.go +++ b/helper/handler.go @@ -13,16 +13,16 @@ type Handlers struct { GetModulesInfo func() ([]domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"` // ===== CONFIG ===== - GetActiveConfigByModuleName func(request domain.GetByModuleNameRequest) (*entity.Config, error) `method:"get_active_config_by_module_name" group:"config" inner:"true"` - CreateUpdateConfig func(config entity.Config) (*entity.Config, error) `method:"create_update_config" group:"config" inner:"true"` - MarkConfigAsActive func(identity domain.ConfigIdRequest) (*entity.Config, error) `method:"mark_config_as_active" group:"config" inner:"true"` - DeleteConfig func(identities []string) (*domain.DeleteResponse, error) `method:"delete_config" group:"config" inner:"true"` + GetActiveConfigByModuleName func(request domain.GetByModuleNameRequest) (*entity.Config, error) `method:"get_active_config_by_module_name" group:"config" inner:"true"` + CreateUpdateConfig func(config domain.CreateUpdateConfigRequest) (*domain.ConfigModuleInfo, error) `method:"create_update_config" group:"config" inner:"true"` + MarkConfigAsActive func(identity domain.ConfigIdRequest) (*entity.Config, error) `method:"mark_config_as_active" group:"config" inner:"true"` + DeleteConfig func(identities []string) (*domain.DeleteResponse, error) `method:"delete_config" group:"config" inner:"true"` // ===== COMMON CONFIG ===== GetCommonConfigs func(identities []string) []entity.CommonConfig `method:"get_configs" group:"common_config" inner:"true"` CreateUpdateCommonConfig func(config entity.CommonConfig) (*entity.CommonConfig, error) `method:"create_update_config" group:"common_config" inner:"true"` DeleteCommonConfig func(req domain.ConfigIdRequest) (*domain.DeleteCommonConfigResponse, error) `method:"delete_config" group:"common_config" inner:"true"` - CompileConfigs func(req domain.CompileConfigsRequest) controller.CompiledConfig `method:"compile" group:"common_config" inner:"true"` + CompileConfigs func(req domain.CompileConfigsRequest) domain.CompiledConfigResponse `method:"compile" group:"common_config" inner:"true"` GetLinks func(req domain.ConfigIdRequest) domain.CommonConfigLinks `method:"get_links" group:"common_config" inner:"true"` // ===== ROUTING ===== diff --git a/service/config.go b/service/config.go index b2625f9..3daab1a 100644 --- a/service/config.go +++ b/service/config.go @@ -2,13 +2,16 @@ package service import ( "encoding/json" + "fmt" "github.com/integration-system/bellows" "github.com/integration-system/isp-lib/utils" log "github.com/integration-system/isp-log" "github.com/pkg/errors" + "github.com/xeipuuv/gojsonschema" codes2 "google.golang.org/grpc/codes" "isp-config-service/cluster" "isp-config-service/codes" + "isp-config-service/domain" "isp-config-service/entity" "isp-config-service/holder" "isp-config-service/model" @@ -23,6 +26,18 @@ const ConfigWatchersRoomSuffix = "_config" type configService struct{} +type validationSchemaError struct { + Description map[string]string +} + +func (e validationSchemaError) Error() string { + resp := "" + for field, desc := range e.Description { + resp = fmt.Sprintf("%s- %s%s\n", resp, field, desc) + } + return resp +} + func (s configService) GetCompiledConfig(moduleName string, state state.ReadonlyState) (map[string]interface{}, error) { module := state.Modules().GetByName(moduleName) if module == nil { @@ -87,8 +102,29 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon config := upsertConfig.Config module := state.Modules().GetById(config.ModuleId) if module == nil { - return cluster.NewResponseErrorf(codes2.InvalidArgument, "invalid moduleId %s", config.ModuleId) + return cluster.NewResponseErrorf(codes2.NotFound, "moduleId %s not found", config.ModuleId) } + + schemaStorage := state.Schemas().GetByModuleIds([]string{config.ModuleId}) + if len(schemaStorage) == 0 { + return cluster.NewResponseErrorf(codes2.NotFound, "schema for moduleId %s not found", config.ModuleId) + } + dataForValidate := cs.CompileConfig(config.Data, state, config.CommonConfigs...) + validSchema, err := cs.validateSchema(schemaStorage[0], dataForValidate) + + if !upsertConfig.Unsafe && err != nil { + switch err := err.(type) { + case validationSchemaError: + return cluster.NewResponse( + domain.CreateUpdateConfigResponse{ + Config: nil, + ErrorDetails: err.Description, + }) + default: + return cluster.NewResponseErrorf(codes2.Internal, "%v", err) + } + } + if upsertConfig.Create { config = state.WritableConfigs().Create(config) } else { @@ -111,7 +147,13 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon } } cs.BroadcastNewConfig(state, config) - return cluster.NewResponse(config) + return cluster.NewResponse(domain.CreateUpdateConfigResponse{ + Config: &domain.ConfigModuleInfo{ + Config: config, + Valid: validSchema, + }, + ErrorDetails: nil, + }) } func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ...entity.Config) { @@ -142,6 +184,22 @@ func (cs configService) broadcast(room, event string, data []byte) { } } +func (configService) validateSchema(schema entity.ConfigSchema, data map[string]interface{}) (bool, error) { + schemaLoader := gojsonschema.NewGoLoader(schema.Schema) + documentLoader := gojsonschema.NewGoLoader(data) + if result, err := gojsonschema.Validate(schemaLoader, documentLoader); err != nil { + return false, err + } else if result.Valid() { + return true, nil + } else { + desc := make(map[string]string) + for _, value := range result.Errors() { + desc[value.Field()] = value.Description() + } + return false, validationSchemaError{Description: desc} + } +} + func mergeNestedMaps(maps ...map[string]interface{}) map[string]interface{} { if len(maps) == 1 { return maps[0] diff --git a/service/config_test.go b/service/config_test.go new file mode 100644 index 0000000..4e1e9ba --- /dev/null +++ b/service/config_test.go @@ -0,0 +1,37 @@ +package service + +import ( + "encoding/json" + "github.com/stretchr/testify/assert" + "isp-config-service/entity" + "testing" +) + +func TestConfigService_validateSchema(t *testing.T) { + var ( + a = assert.New(t) + + schemaDesc = []byte(`{"schema":{"properties":{"configuration":{"required":["address","token"],"properties":{"address":{"type":"string","title":"Адрес"},"token":{"type":"string","title":"Токен"}},"additionalProperties":false,"type":"object"}},"additionalProperties":false,"type":"object","title":"Remote config"},"title":"module_name"}`) + validData = map[string]interface{}{"configuration": map[string]interface{}{"address": "127.0.0.1", "token": "token"}} + invalidValue = map[string]interface{}{"configuration": map[string]interface{}{"address": 127001, "token": "token"}} + invalidName = map[string]interface{}{"config": map[string]interface{}{"test": "127.0.0.1", "token": "token"}} + + schema entity.ConfigSchema + valid bool + err error + ) + + a.NoError(json.Unmarshal(schemaDesc, &schema)) + + valid, err = ConfigService.validateSchema(schema, validData) + a.NoError(err) + a.True(valid) + + valid, err = ConfigService.validateSchema(schema, invalidValue) + a.Error(err) + a.False(valid) + + valid, err = ConfigService.validateSchema(schema, invalidName) + a.Error(err) + a.False(valid) +} diff --git a/service/module_registry.go b/service/module_registry.go index 004c121..b12f2ff 100644 --- a/service/module_registry.go +++ b/service/module_registry.go @@ -126,7 +126,11 @@ func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState) configs := state.Configs().GetByModuleIds(idList) for _, cfg := range configs { info := resMap[cfg.ModuleId] - info.Configs = append(info.Configs, cfg) + info.Configs = append(info.Configs, domain.ConfigModuleInfo{ + Config: cfg, + Valid: false, + }) + resMap[cfg.ModuleId] = info } schemas := state.Schemas().GetByModuleIds(idList) @@ -134,6 +138,12 @@ func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState) info := resMap[s.ModuleId] schema := s.Schema info.ConfigSchema = &schema + + for i, config := range info.Configs { + dataForValidate := ConfigService.CompileConfig(config.Data, state, config.CommonConfigs...) + info.Configs[i].Valid, _ = ConfigService.validateSchema(s, dataForValidate) + } + resMap[s.ModuleId] = info } diff --git a/subs/client.go b/subs/client.go index d1b9229..4824bb2 100644 --- a/subs/client.go +++ b/subs/client.go @@ -107,6 +107,7 @@ func (h *socketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []by upsertConfig := cluster.UpsertConfig{ Config: config, Create: true, + Unsafe: true, } command := cluster.PrepareUpsertConfigCommand(upsertConfig)