Merge remote-tracking branch 'origin/v2' into v2_migrate_etp

This commit is contained in:
ykomissarov committed 2019-10-30 15:07:42 +03:00
commit 3ad5dfe030
11 files changed
+204 -58

No files matched your search

+2 -2
View File
@@ -72,8 +72,8 @@ func PrepareUpdateConfigSchemaCommand(schema entity.ConfigSchema) []byte {
return prepareCommand(UpdateConfigSchemaCommand, schema)
}
func PrepareDeleteCommonConfigsCommand(ids []string) []byte {
return prepareCommand(DeleteCommonConfigsCommand, DeleteModules{Ids: ids})
func PrepareDeleteCommonConfigsCommand(id string) []byte {
return prepareCommand(DeleteCommonConfigsCommand, DeleteCommonConfig{Id: id})
}
func PrepareUpsertCommonConfigCommand(config UpsertCommonConfig) []byte {
+4
View File
@@ -35,6 +35,10 @@ type DeleteConfigs struct {
Ids []string
}
type DeleteCommonConfig struct {
Id string
}
type UpsertCommonConfig struct {
Config entity.CommonConfig
Create bool
+45 -18
View File
@@ -1,11 +1,10 @@
package controller
import (
"github.com/integration-system/isp-lib/utils"
"google.golang.org/grpc/codes"
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
)
@@ -37,7 +36,7 @@ func (c *commonConfig) GetConfigs(identities []string) []entity.CommonConfig {
}
// CreateUpdateConfig godoc
// @Summary Метод обновления конфигурации
// @Summary Метод обновления общей конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию
// @Tags Общие конфигурации
@@ -69,26 +68,18 @@ func (c *commonConfig) CreateUpdateConfig(config entity.CommonConfig) (*entity.C
}
// DeleteConfigs godoc
// @Summary Метод удаления объектов конфигурации по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Summary Метод удаления объектов общей конфигурации по идентификаторам
// @Description Возвращает флаг удаления и набор связей с модулями и конфигурациями, в случае наличия связей deleted всегда false
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов конфигураций"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} structure.GrpcError "если конфигурации где-то используются либо не указан объект identities"
// @Param body body domain.ConfigIdRequest true "id общей конфигурации"
// @Success 200 {object} domain.DeleteCommonConfigResponse
// @Failure 500 {object} structure.GrpcError
// @Router /common_config/delete_config [POST]
func (c *commonConfig) DeleteConfigs(identities []string) (*domain.DeleteResponse, error) {
if len(identities) == 0 {
validationErrors := map[string]string{
"ids": "Required",
}
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, validationErrors)
}
var response domain.DeleteResponse
command := cluster.PrepareDeleteCommonConfigsCommand(identities)
func (c *commonConfig) DeleteConfigs(req domain.ConfigIdRequest) (*domain.DeleteCommonConfigResponse, error) {
var response domain.DeleteCommonConfigResponse
command := cluster.PrepareDeleteCommonConfigsCommand(req.Id)
err := PerformSyncApplyWithError(command, "DeleteCommonConfigsCommand", &response)
if err != nil {
return nil, err
@@ -96,6 +87,42 @@ func (c *commonConfig) DeleteConfigs(identities []string) (*domain.DeleteRespons
return &response, nil
}
type CompiledConfig map[string]interface{}
// CompileConfigs godoc
// @Summary Метод компиляции итоговой конфигурации для модулей
// @Description Возвращает скомпилированный объект конфигурации
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body domain.CompileConfigsRequest true "перечисление идентификаторов общей конфигурации и исхдных конфиг"
// @Success 200 {object} CompiledConfig
// @Router /common_config/compile [POST]
func (c *commonConfig) CompileConfigs(req domain.CompileConfigsRequest) CompiledConfig {
var result map[string]interface{}
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = service.ConfigService.CompileConfig(req.Data, state, req.CommonConfigsIdList...)
})
return result
}
// GetLinks godoc
// @Summary Метод получения связей общей конфигурациями с конфигурацией модулей
// @Description Возвращает ассоциативный массив, ключами которого являются название модулей, а значения - название конфигурации модуля
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id общей конфигурации"
// @Success 200 {object} domain.CommonConfigLinks
// @Router /common_config/get_links [POST]
func (c *commonConfig) GetLinks(req domain.ConfigIdRequest) domain.CommonConfigLinks {
var result domain.CommonConfigLinks
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = service.CommonConfigService.GetCommonConfigLinks(req.Id, state)
})
return result
}
func NewCommonConfig(rstore *store.Store) *commonConfig {
return &commonConfig{
rstore: rstore,
+6 -3
View File
@@ -23,15 +23,18 @@ type config struct {
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "название модуля"
// @Param body body domain.GetByModuleNameRequest true "название модуля"
// @Success 200 {object} entity.Config
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_active_config_by_module_name [POST]
func (c *config) GetActiveConfigByModuleName(request domain.GetByModuleIdRequest) (*entity.Config, error) {
func (c *config) GetActiveConfigByModuleName(request domain.GetByModuleNameRequest) (*entity.Config, error) {
var response *entity.Config
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = state.Configs().GetActiveByModuleId(request.ModuleId)
module := state.Modules().GetByName(request.ModuleName)
if module != nil {
response = state.Configs().GetActiveByModuleId(module.Id)
}
})
if response == nil {
return nil, status.Error(codes.NotFound, utils.ValidationError)
+87 -14
View File
@@ -1,5 +1,21 @@
basePath: /api/config
definitions:
domain.CommonConfigLinks:
additionalProperties:
items: {}
type: array
type: object
domain.CompileConfigsRequest:
properties:
commonConfigsIdList:
items:
type: string
type: array
data:
type: object
required:
- commonConfigsIdList
type: object
domain.ConfigIdRequest:
properties:
id:
@@ -23,6 +39,14 @@ definitions:
version:
type: string
type: object
domain.DeleteCommonConfigResponse:
properties:
deleted:
type: boolean
links:
$ref: '#/definitions/domain.CommonConfigLinks'
type: object
type: object
domain.DeleteResponse:
properties:
deleted:
@@ -35,6 +59,13 @@ definitions:
required:
- moduleId
type: object
domain.GetByModuleNameRequest:
properties:
moduleName:
type: string
required:
- moduleName
type: object
domain.ModuleInfo:
properties:
active:
@@ -540,6 +571,29 @@ info:
title: ISP configuration service
version: 2.0.0
paths:
/common_config/compile:
post:
consumes:
- application/json
description: Возвращает скомпилированный объект конфигурации
parameters:
- description: перечисление идентификаторов общей конфигурации и исхдных конфиг
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.CompileConfigsRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/CompiledConfig'
summary: Метод компиляции итоговой конфигурации для модулей
tags:
- Общие конфигурации
/common_config/create_update_config:
post:
consumes:
@@ -569,40 +623,35 @@ paths:
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод обновления конфигурации
summary: Метод обновления оьщей конфигурации
tags:
- Общие конфигурации
/common_config/delete_config:
post:
consumes:
- application/json
description: Возвращает количество удаленных модулей
description: Возвращает флаг удаления и набор связей с модулями и конфигурациями,
в случае наличия связей deleted всегда false
parameters:
- description: массив идентификаторов конфигураций
- description: id общей конфигурации
in: body
name: body
required: true
schema:
items:
type: string
type: array
$ref: '#/definitions/domain.ConfigIdRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"400":
description: если конфигурации где-то используются либо не указан объект
identities
schema:
$ref: '#/definitions/structure.GrpcError'
$ref: '#/definitions/domain.DeleteCommonConfigResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод удаления объектов конфигурации по идентификаторам
summary: Метод удаления объектов общей конфигурации по идентификаторам
tags:
- Общие конфигурации
/common_config/get_configs:
@@ -623,6 +672,30 @@ paths:
summary: Метод получения объектов конфигурации по идентификаторам
tags:
- Общие конфигурации
/common_config/get_links:
post:
consumes:
- application/json
description: Возвращает ассоциативный массив, ключами которого являются название
модулей, а значения - название конфигурации модуля
parameters:
- description: id общей конфигурации
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.CommonConfigLinks'
summary: Метод получения связей общей конфигурациями с конфигурацией модулей
tags:
- Общие конфигурации
/config/create_update_config:
post:
consumes:
@@ -698,7 +771,7 @@ paths:
name: body
required: true
schema:
$ref: '#/definitions/domain.GetByModuleIdRequest'
$ref: '#/definitions/domain.GetByModuleNameRequest'
type: object
produces:
- application/json
+9
View File
@@ -4,6 +4,15 @@ type ConfigIdRequest struct {
Id string `json:"id" valid:"required~Required"`
}
type CompileConfigsRequest struct {
Data map[string]interface{}
CommonConfigsIdList []string `valid:"required~Required"`
}
type GetByModuleIdRequest struct {
ModuleId string `valid:"required~Required"`
}
type GetByModuleNameRequest struct {
ModuleName string `valid:"required~Required"`
}
+7
View File
@@ -30,3 +30,10 @@ type Connection struct {
Endpoints []structure.EndpointConfig `json:",omitempty"`
EstablishedAt time.Time
}
type CommonConfigLinks map[string][]string
type DeleteCommonConfigResponse struct {
Deleted bool
Links CommonConfigLinks
}
+11 -7
View File
@@ -13,15 +13,17 @@ type Handlers struct {
GetModulesInfo func() ([]domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"`
// ===== CONFIG =====
GetActiveConfigByModuleName func(request domain.GetByModuleIdRequest) (*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 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"`
// ===== 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(identities []string) (*domain.DeleteResponse, error) `method:"delete_config" group:"common_config" inner:"true"`
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"`
GetLinks func(req domain.ConfigIdRequest) domain.CommonConfigLinks `method:"get_links" group:"common_config" inner:"true"`
// ===== ROUTING =====
GetRoutes func() ([]structure.BackendDeclaration, error) `method:"get_routes" group:"routing" inner:"true"`
@@ -43,6 +45,8 @@ func GetHandlers() *Handlers {
GetCommonConfigs: controller.CommonConfig.GetConfigs,
CreateUpdateCommonConfig: controller.CommonConfig.CreateUpdateConfig,
DeleteCommonConfig: controller.CommonConfig.DeleteConfigs,
CompileConfigs: controller.CommonConfig.CompileConfigs,
GetLinks: controller.CommonConfig.GetLinks,
GetRoutes: controller.Routes.GetRoutes,
+23 -8
View File
@@ -17,13 +17,12 @@ var (
type commonConfigService struct{}
func (commonConfigService) HandleDeleteConfigsCommand(deleteConfigs cluster.DeleteConfigs, state state.WritableState) cluster.ResponseWithError {
ids := deleteConfigs.Ids
affectedConfigs := state.Configs().FilterByCommonConfigs(ids)
if len(affectedConfigs) > 0 {
// TODO обсудить формат и сделать ошибку содержательнее
return cluster.NewResponseErrorf(codes2.InvalidArgument, "cant delete, common configs are in use")
func (s commonConfigService) HandleDeleteConfigsCommand(deleteCommonConfig cluster.DeleteCommonConfig, state state.WritableState) cluster.ResponseWithError {
links := s.GetCommonConfigLinks(deleteCommonConfig.Id, state)
if len(links) > 0 {
return cluster.NewResponse(domain.DeleteCommonConfigResponse{Deleted: false, Links: links})
}
ids := []string{deleteCommonConfig.Id}
deleted := state.WritableCommonConfigs().DeleteByIds(ids)
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
@@ -34,10 +33,10 @@ func (commonConfigService) HandleDeleteConfigsCommand(deleteConfigs cluster.Dele
}).Errorf(codes.DatabaseOperationError, "delete configs: %v", err)
}
}
return cluster.NewResponse(domain.DeleteResponse{Deleted: deleted})
return cluster.NewResponse(domain.DeleteCommonConfigResponse{Deleted: deleted > 0})
}
func (commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCommonConfig, state state.WritableState) cluster.ResponseWithError {
func (s commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCommonConfig, state state.WritableState) cluster.ResponseWithError {
config := upsertConfig.Config
configsByName := state.CommonConfigs().GetByName(config.Name)
if upsertConfig.Create {
@@ -73,3 +72,19 @@ func (commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.Upsert
}
return cluster.NewResponse(config)
}
func (s commonConfigService) GetCommonConfigLinks(commonConfigId string, state state.ReadonlyState) domain.CommonConfigLinks {
configs := state.Configs().FilterByCommonConfigs([]string{commonConfigId})
result := make(domain.CommonConfigLinks)
for _, c := range configs {
module := state.Modules().GetById(c.ModuleId)
if module != nil {
if configs, ok := result[module.Name]; ok {
result[module.Name] = append(configs, c.Name)
} else {
result[module.Name] = []string{c.Name}
}
}
}
return result
}
+9 -5
View File
@@ -23,7 +23,7 @@ const ConfigWatchersRoomSuffix = "_config"
type configService struct{}
func (configService) GetCompiledConfig(moduleName string, state state.ReadonlyState) (map[string]interface{}, error) {
func (s configService) GetCompiledConfig(moduleName string, state state.ReadonlyState) (map[string]interface{}, error) {
module := state.Modules().GetByName(moduleName)
if module == nil {
return nil, errors.Errorf("module with name %s not found", moduleName)
@@ -32,15 +32,19 @@ func (configService) GetCompiledConfig(moduleName string, state state.ReadonlySt
if config == nil {
return nil, errors.Errorf("no active configs for moduleId %s", module.Id)
}
commonConfigs := state.CommonConfigs().GetByIds(config.CommonConfigs)
return s.CompileConfig(config.Data, state, config.CommonConfigs...), nil
}
func (configService) CompileConfig(data map[string]interface{}, state state.ReadonlyState, commonConfigsIds ...string) map[string]interface{} {
commonConfigs := state.CommonConfigs().GetByIds(commonConfigsIds)
configsToMerge := make([]map[string]interface{}, 0, len(commonConfigs))
for _, common := range commonConfigs {
configsToMerge = append(configsToMerge, common.Data)
}
configsToMerge = append(configsToMerge, config.Data)
configsToMerge = append(configsToMerge, data)
resultData := mergeNestedMaps(configsToMerge...)
return resultData, nil
return mergeNestedMaps(configsToMerge...)
}
func (configService) HandleActivateConfigCommand(activateConfig cluster.ActivateConfig, state state.WritableState) cluster.ResponseWithError {
+1 -1
View File
@@ -103,7 +103,7 @@ func (s *Store) applyUpsertConfigCommand(data []byte) (interface{}, error) {
}
func (s *Store) applyDeleteCommonConfigsCommand(data []byte) (interface{}, error) {
deleteConfigs := cluster.DeleteConfigs{}
deleteConfigs := cluster.DeleteCommonConfig{}
err := json.Unmarshal(data, &deleteConfigs)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.DeleteConfigs")