add config version

This commit is contained in:
DeniskaRediska committed 2020-06-08 18:39:25 +03:00
1 parent 14c5b0a678
commit 15ad05277b
26 files changed
+486 -48

No files matched your search

+1 -1
View File
@@ -1 +1 @@
2.3.0
2.4.0
+5
View File
@@ -1,3 +1,8 @@
### v2.4.0
* add saving old configs
* add method `/config/delete_version`
* add method `/config/get_all_version`
### v2.3.0
* add method `/module/broadcast_event` to broadcast arbitrary event to modules
* add module dependencies to response `/module/get_modules_info`
+10
View File
@@ -33,6 +33,8 @@ const (
ModuleConnectedCommand
ModuleDisconnectedCommand
DeleteModulesCommand
DeleteVersionConfigCommand
GetAllVersionConfigCommand
ActivateConfigCommand
DeleteConfigsCommand
@@ -96,6 +98,14 @@ func PrepareBroadcastEventCommand(event BroadcastEvent) []byte {
return prepareCommand(BroadcastEventCommand, event)
}
func PrepareDeleteConfigVersionCommand(id string) []byte {
return prepareCommand(DeleteVersionConfigCommand, Identity{Id: id})
}
func PrepareGetAllConfigVersionCommand(id string) []byte {
return prepareCommand(GetAllVersionConfigCommand, Identity{Id: id})
}
func prepareCommand(command Command, payload interface{}) []byte {
cmd := make([]byte, 8)
binary.BigEndian.PutUint64(cmd, uint64(command))
+10 -8
View File
@@ -14,17 +14,19 @@ func _() {
_ = x[ModuleConnectedCommand-4]
_ = x[ModuleDisconnectedCommand-5]
_ = x[DeleteModulesCommand-6]
_ = x[ActivateConfigCommand-7]
_ = x[DeleteConfigsCommand-8]
_ = x[UpsertConfigCommand-9]
_ = x[DeleteCommonConfigsCommand-10]
_ = x[UpsertCommonConfigCommand-11]
_ = x[BroadcastEventCommand-12]
_ = x[DeleteVersionConfigCommand-7]
_ = x[GetAllVersionConfigCommand-8]
_ = x[ActivateConfigCommand-9]
_ = x[DeleteConfigsCommand-10]
_ = x[UpsertConfigCommand-11]
_ = x[DeleteCommonConfigsCommand-12]
_ = x[UpsertCommonConfigCommand-13]
_ = x[BroadcastEventCommand-14]
}
const _Command_name = "UpdateBackendDeclarationCommandDeleteBackendDeclarationCommandUpdateConfigSchemaCommandModuleConnectedCommandModuleDisconnectedCommandDeleteModulesCommandActivateConfigCommandDeleteConfigsCommandUpsertConfigCommandDeleteCommonConfigsCommandUpsertCommonConfigCommandBroadcastEventCommand"
const _Command_name = "UpdateBackendDeclarationCommandDeleteBackendDeclarationCommandUpdateConfigSchemaCommandModuleConnectedCommandModuleDisconnectedCommandDeleteModulesCommandDeleteVersionConfigCommandGetAllVersionConfigCommandActivateConfigCommandDeleteConfigsCommandUpsertConfigCommandDeleteCommonConfigsCommandUpsertCommonConfigCommandBroadcastEventCommand"
var _Command_index = [...]uint16{0, 31, 62, 87, 109, 134, 154, 175, 195, 214, 240, 265, 286}
var _Command_index = [...]uint16{0, 31, 62, 87, 109, 134, 154, 180, 206, 227, 247, 266, 292, 317, 338}
func (i Command) String() string {
i -= 1
+4
View File
@@ -41,6 +41,10 @@ type DeleteCommonConfig struct {
Id string
}
type Identity struct {
Id string
}
type UpsertCommonConfig struct {
Config entity.CommonConfig
Create bool
+2
View File
@@ -37,3 +37,5 @@ cluster:
bootstrapCluster: true
peers:
- 127.0.0.1:9001
versionConfigCount: 5
+7 -6
View File
@@ -6,12 +6,13 @@ import (
)
type Configuration struct {
Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"`
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
ModuleName string `valid:"required~Required"`
WS WebService `valid:"required~Required" schema:"Конфигурация веб сервиса"`
Metrics structure.MetricConfiguration
Cluster ClusterConfiguration `valid:"required~Required"`
Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"`
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
ModuleName string `valid:"required~Required"`
WS WebService `valid:"required~Required" schema:"Конфигурация веб сервиса"`
Metrics structure.MetricConfiguration
Cluster ClusterConfiguration `valid:"required~Required"`
VersionConfigCount int `schema:"Количество сохраняемых старых версий конфигурации"`
}
type ClusterConfiguration struct {
+40
View File
@@ -128,6 +128,46 @@ func (c *config) DeleteConfigs(identities []string) (*domain.DeleteResponse, err
return &response, nil
}
// @Summary Метод удаления версии конфигурации
// @Description Возвращает количество удаленных версий
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id версии конфигурации"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
// @Failure 500 {object} structure.GrpcError
// @Router /config/delete_version [POST]
func (c *config) DeleteConfigVersion(req domain.ConfigIdRequest) (*domain.DeleteResponse, error) {
var response domain.DeleteResponse
command := cluster.PrepareDeleteConfigVersionCommand(req.Id)
err := PerformSyncApplyWithError(command, &response)
if err != nil {
return nil, err
}
return &response, nil
}
// @Summary Метод получение старых версий конфигурации
// @Description Возвращает предыдущие версии конфигураций
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации"
// @Success 200 {array} entity.VersionConfig
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_all_version [POST]
func (c *config) GetAllVersion(req domain.ConfigIdRequest) ([]entity.VersionConfig, error) {
var response []entity.VersionConfig
command := cluster.PrepareGetAllConfigVersionCommand(req.Id)
err := PerformSyncApplyWithError(command, &response)
if err != nil {
return nil, err
}
return response, nil
}
func NewConfig(rstore *store.Store) *config {
return &config{
rstore: rstore,
+88 -9
View File
@@ -85,10 +85,6 @@ definitions:
type: string
libVersion:
type: string
requiredModules:
items:
$ref: '#/definitions/domain.ModuleDependency'
type: array
version:
type: string
type: object
@@ -180,6 +176,10 @@ definitions:
type: string
name:
type: string
requiredModules:
items:
$ref: '#/definitions/domain.ModuleDependency'
type: array
status:
items:
$ref: '#/definitions/domain.Connection'
@@ -266,6 +266,18 @@ definitions:
required:
- name
type: object
entity.VersionConfig:
properties:
configId:
type: string
configVersion:
type: integer
data:
$ref: '#/definitions/entity.ConfigData'
type: object
id:
type: string
type: object
json.RawMessage:
$ref: '#/definitions/json.RawMessage'
jsonschema.Definitions:
@@ -651,7 +663,8 @@ paths:
post:
consumes:
- application/json
description: Возвращает флаг удаления и набор связей с модулями и конфигурациями, в случае наличия связей deleted всегда false
description: Возвращает флаг удаления и набор связей с модулями и конфигурациями,
в случае наличия связей deleted всегда false
parameters:
- description: id общей конфигурации
in: body
@@ -677,7 +690,8 @@ paths:
post:
consumes:
- application/json
description: Возвращает массив конфигураций по запрошенным идентификаторам (все, если массив пустой)
description: Возвращает массив конфигураций по запрошенным идентификаторам (все,
если массив пустой)
produces:
- application/json
responses:
@@ -694,7 +708,8 @@ paths:
post:
consumes:
- application/json
description: Возвращает ассоциативный массив, ключами которого являются название модулей, а значения - название конфигурации модуля
description: Возвращает ассоциативный массив, ключами которого являются название
модулей, а значения - название конфигурации модуля
parameters:
- description: id общей конфигурации
in: body
@@ -776,6 +791,36 @@ paths:
summary: Метод удаления объектов конфигурации по идентификаторам
tags:
- Конфигурация
/config/delete_version:
post:
consumes:
- application/json
description: Возвращает количество удаленных версий
parameters:
- description: id версии конфигурации
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"400":
description: если не указан массив идентификаторов
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод удаления версии конфигурации
tags:
- Конфигурация
/config/get_active_config_by_module_name:
post:
consumes:
@@ -806,11 +851,44 @@ paths:
summary: Метод получения объекта конфигурации по названию модуля
tags:
- Конфигурация
/config/get_all_version:
post:
consumes:
- application/json
description: Возвращает предыдущие версии конфигураций
parameters:
- description: id конфигурации
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/entity.VersionConfig'
type: array
"400":
description: если не указан массив идентификаторов
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод получение старых версий конфигурации
tags:
- Конфигурация
/config/mark_config_as_active:
post:
consumes:
- application/json
description: Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию
description: Активирует указанную конфигурацию и деактивирует остальные, возвращает
активированную конфигурацию
parameters:
- description: id конфигурации для изменения
in: body
@@ -920,7 +998,8 @@ paths:
post:
consumes:
- application/json
description: Возвращает полное состояние всех модулей в кластере (конфигурация, схема конфигурации, подключенные экземпляры)
description: Возвращает полное состояние всех модулей в кластере (конфигурация,
схема конфигурации, подключенные экземпляры)
produces:
- application/json
responses:
+1
View File
@@ -2,6 +2,7 @@ package domain
import (
json2 "encoding/json"
"isp-config-service/entity"
)
+8 -8
View File
@@ -16,11 +16,11 @@ type Config struct {
CommonConfigs []string `json:"commonConfigs" pg:",array"`
Description string `json:"description"`
ModuleId string `json:"moduleId" valid:"required~Required"`
Version int32 `json:"version" sql:",null"`
Active bool `json:"active" sql:",null"`
CreatedAt time.Time `json:"createdAt" sql:",null"`
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
Data ConfigData `json:"data" sql:",notnull"`
Version int32 `json:"version" pg:",null"`
Active bool `json:"active" pg:",null"`
CreatedAt time.Time `json:"createdAt" pg:",null"`
UpdatedAt time.Time `json:"updatedAt" pg:",null"`
Data ConfigData `json:"data" pg:",notnull"`
}
type CommonConfig struct {
@@ -29,9 +29,9 @@ type CommonConfig struct {
Id string `json:"id"`
Name string `json:"name" valid:"required~Required"`
Description string `json:"description"`
CreatedAt time.Time `json:"createdAt" sql:",null"`
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
Data ConfigData `json:"data" sql:",notnull"`
CreatedAt time.Time `json:"createdAt" pg:",null"`
UpdatedAt time.Time `json:"updatedAt" pg:",null"`
Data ConfigData `json:"data" pg:",notnull"`
}
type ConfigSchema struct {
+1 -1
View File
@@ -7,7 +7,7 @@ type Module struct {
tableName string `pg:"?db_schema.modules" json:"-"`
Id string `json:"id"`
Name string `json:"name" valid:"required~Required"`
CreatedAt time.Time `json:"createdAt" sql:",null"`
CreatedAt time.Time `json:"createdAt" pg:",null"`
LastConnectedAt time.Time `json:"lastConnectedAt"`
LastDisconnectedAt time.Time `json:"lastDisconnectedAt"`
}
+10
View File
@@ -0,0 +1,10 @@
package entity
type VersionConfig struct {
//nolint
tableName string `pg:"?db_schema.version_config" json:"-"`
Id string
ConfigVersion int32
ConfigId string
Data ConfigData `json:"data" pg:",notnull"`
}
+1
View File
@@ -21,5 +21,6 @@ require (
github.com/stretchr/testify v1.5.1
github.com/thecodeteam/goodbye v0.0.0-20170927022442-a83968bda2d3
github.com/xeipuuv/gojsonschema v1.2.0
golang.org/x/tools v0.0.0-20200606014950-c42cb6316fb6 // indirect
google.golang.org/grpc v1.29.1
)
+6
View File
@@ -385,6 +385,7 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.opentelemetry.io/otel v0.5.0/go.mod h1:jzBIgIzK43Iu1BpDAXwqOd6UPsSAk+ewVZ5ofSXw4Ek=
@@ -424,6 +425,7 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee h1:WG0RUwxtNT4qqaXX3DPA8zHFNm/D9xaBpxzHt1WcA/E=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -498,12 +500,16 @@ golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBn
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200220224806-8a925fa4c0df h1:oQFmpjL+rb2xLkgPCpdGSAGDdq1geTZVvIfCMxSB/wQ=
golang.org/x/tools v0.0.0-20200220224806-8a925fa4c0df/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200606014950-c42cb6316fb6 h1:5Y8c5HBW6hBYnGEE3AbJPV0R8RsQmg1/eaJrpvasns0=
golang.org/x/tools v0.0.0-20200606014950-c42cb6316fb6/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
+4
View File
@@ -20,6 +20,8 @@ type Handlers struct {
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"`
DeleteVersion func(identity domain.ConfigIdRequest) (*domain.DeleteResponse, error) `method:"delete_version" group:"config" inner:"true"`
GetAllVersion func(identity domain.ConfigIdRequest) ([]entity.VersionConfig, error) `method:"get_all_version" group:"config" inner:"true"`
// ===== COMMON CONFIG =====
GetCommonConfigs func(identities []string) []entity.CommonConfig `method:"get_configs" group:"common_config" inner:"true"`
@@ -46,6 +48,8 @@ func GetHandlers() *Handlers {
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
MarkConfigAsActive: controller.Config.MarkConfigAsActive,
DeleteConfig: controller.Config.DeleteConfigs,
DeleteVersion: controller.Config.DeleteConfigVersion,
GetAllVersion: controller.Config.GetAllVersion,
GetCommonConfigs: controller.CommonConfig.GetConfigs,
CreateUpdateCommonConfig: controller.CommonConfig.CreateUpdateConfig,
@@ -0,0 +1,13 @@
-- +goose Up
CREATE TABLE version_config
(
id VARCHAR(255) NOT NULL PRIMARY KEY,
config_id VARCHAR(255) NOT NULL,
config_version INT4 NOT NULL,
data JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
-- +goose Down
DROP TABLE version_config;
+5 -4
View File
@@ -15,8 +15,9 @@ var (
log.Fatal(stdcodes.InitializingDbError, err.Error())
}),
)
ConfigRep ConfigRepository = &configRepPg{rxClient: DbClient}
CommonConfigRep CommonConfigRepository = &commonConfigRepPg{rxClient: DbClient}
SchemaRep SchemaRepository = &schemaRepPg{rxClient: DbClient}
ModuleRep ModulesRepository = &modulesRepPg{rxClient: DbClient}
ConfigRep ConfigRepository = &configRepPg{rxClient: DbClient}
CommonConfigRep CommonConfigRepository = &commonConfigRepPg{rxClient: DbClient}
SchemaRep SchemaRepository = &schemaRepPg{rxClient: DbClient}
ModuleRep ModulesRepository = &modulesRepPg{rxClient: DbClient}
VersionStoreRep VersionConfigRepository = &versionConfigRepPg{rxClient: DbClient}
)
+53
View File
@@ -0,0 +1,53 @@
package model
import (
"github.com/go-pg/pg/v9"
"github.com/integration-system/isp-lib/v2/database"
"isp-config-service/entity"
)
type VersionConfigRepository interface {
Snapshot() ([]entity.VersionConfig, error)
Upsert(model entity.VersionConfig) (*entity.VersionConfig, error)
Delete(identities string) (int, error)
}
type versionConfigRepPg struct {
rxClient *database.RxDbClient
}
func (r *versionConfigRepPg) Snapshot() ([]entity.VersionConfig, error) {
modules := make([]entity.VersionConfig, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&modules).Select()
})
return modules, err
}
func (r *versionConfigRepPg) Upsert(module entity.VersionConfig) (*entity.VersionConfig, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&module).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
if err != nil {
return nil, err
}
return &module, err
}
func (r *versionConfigRepPg) Delete(id string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.VersionConfig{}).
Where("id = ?", id).Delete()
return err
})
if err != nil {
return 0, err
}
return res.RowsAffected(), err
}
+41 -8
View File
@@ -3,6 +3,7 @@ package service
import (
"encoding/json"
"fmt"
"github.com/integration-system/bellows"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
@@ -100,18 +101,23 @@ func (configService) HandleDeleteConfigsCommand(deleteConfigs cluster.DeleteConf
return deleted
}
func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertConfig, state state.WritableState) cluster.ResponseWithError {
func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertConfig,
writableState state.WritableState) cluster.ResponseWithError {
config := upsertConfig.Config
module := state.Modules().GetById(config.ModuleId)
module := writableState.Modules().GetById(config.ModuleId)
if module == nil {
return cluster.NewResponseErrorf(codes2.NotFound, "moduleId %s not found", config.ModuleId)
}
schemaStorage := state.Schemas().GetByModuleIds([]string{config.ModuleId})
var (
removedVersionId string
versionConfig entity.VersionConfig
)
schemaStorage := writableState.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...)
dataForValidate := cs.CompileConfig(config.Data, writableState, config.CommonConfigs...)
validSchema, err := cs.validateSchema(schemaStorage[0], dataForValidate)
if !upsertConfig.Unsafe && err != nil {
@@ -128,17 +134,27 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
}
if upsertConfig.Create {
config = state.WritableConfigs().Create(config)
config = writableState.WritableConfigs().Create(config)
} else {
// Update
configs := state.Configs().GetByIds([]string{config.Id})
configs := writableState.Configs().GetByIds([]string{config.Id})
if len(configs) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "config with id %s not found", config.Id)
}
lastConfig := configs[0]
config.CreatedAt = lastConfig.CreatedAt
config.Active = lastConfig.Active
state.WritableConfigs().UpdateById(config)
config.Version = lastConfig.Version + 1
writableState.WritableConfigs().UpdateById(config)
versionConfig = entity.VersionConfig{
Id: state.GenerateId(),
ConfigId: lastConfig.Id,
ConfigVersion: lastConfig.Version,
Data: lastConfig.Data,
}
removedVersionId = writableState.WriteableVersionConfigStore().Update(versionConfig)
}
if holder.ClusterClient.IsLeader() {
@@ -149,8 +165,25 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
"config": config,
}).Errorf(codes.DatabaseOperationError, "upsert config: %v", err)
}
if !upsertConfig.Create && writableState.VersionConfig().CheckCount() {
_, err := model.VersionStoreRep.Upsert(versionConfig)
if err != nil {
log.WithMetadata(map[string]interface{}{
"config": config,
}).Errorf(codes.DatabaseOperationError, "upsert common config: %v", err)
}
if removedVersionId != "" {
_, err := model.VersionStoreRep.Delete(removedVersionId)
if err != nil {
log.WithMetadata(map[string]interface{}{
"config": config,
}).Errorf(codes.DatabaseOperationError, "upsert common config: %v", err)
}
}
}
}
cs.BroadcastActiveConfigs(state, config)
cs.BroadcastActiveConfigs(writableState, config)
return cluster.NewResponse(domain.CreateUpdateConfigResponse{
Config: &domain.ConfigModuleInfo{
Config: config,
+42
View File
@@ -0,0 +1,42 @@
package service
import (
log "github.com/integration-system/isp-log"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/domain"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/store/state"
)
var (
VersionConfig = versionConfigService{}
)
type versionConfigService struct{}
func (versionConfigService) HandleDeleteVersionConfigCommand(cfg cluster.Identity,
state state.WritableState) cluster.ResponseWithError {
state.WriteableVersionConfigStore().Delete(cfg.Id)
var (
deleted int
err error
)
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
deleted, err = model.VersionStoreRep.Delete(cfg.Id)
if err != nil {
log.WithMetadata(map[string]interface{}{
"versionConfigId": cfg.Id,
}).Errorf(codes.DatabaseOperationError, "delete configs: %v", err)
}
}
return cluster.NewResponse(domain.DeleteResponse{Deleted: deleted})
}
func (versionConfigService) HandleGetAllVersionConfigCommand(cfg cluster.Identity,
state state.WritableState) cluster.ResponseWithError {
resp := state.VersionConfig().GetByConfigId(cfg.Id)
return cluster.NewResponse(resp)
}
+22 -1
View File
@@ -1,13 +1,14 @@
package store
import (
"time"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/pkg/errors"
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service"
"time"
)
func (s *Store) applyUpdateBackendDeclarationCommand(data []byte) (interface{}, error) {
@@ -134,3 +135,23 @@ func (s *Store) applyBroadcastEventCommand(data []byte) (interface{}, error) {
}
return nil, nil
}
func (s *Store) applyDeleteVersionConfigCommand(data []byte) (interface{}, error) {
cfg := cluster.Identity{}
err := json.Unmarshal(data, &cfg)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.Identity")
}
response := service.VersionConfig.HandleDeleteVersionConfigCommand(cfg, s.state)
return response, nil
}
func (s *Store) applyAllVersionConfigCommand(data []byte) (interface{}, error) {
cfg := cluster.Identity{}
err := json.Unmarshal(data, &cfg)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.Identity")
}
response := service.VersionConfig.HandleGetAllVersionConfigCommand(cfg, s.state)
return response, nil
}
+6 -1
View File
@@ -24,6 +24,11 @@ func NewStateFromRepository() (*state.State, error) {
return nil, errors.WithMessage(err, "load common configs")
}
st := state.NewStateFromSnapshot(configs, schemas, modules, commonConfigs)
versionStore, err := model.VersionStoreRep.Snapshot()
if err != nil {
return nil, errors.WithMessage(err, "load version store")
}
st := state.NewStateFromSnapshot(configs, schemas, modules, commonConfigs, versionStore)
return st, nil
}
+14 -1
View File
@@ -10,6 +10,7 @@ type State struct {
SchemasStore *SchemaStore
ModulesStore *ModuleStore
CommonConfigsStore *CommonConfigStore
VersionConfigStore *VersionConfigStore
}
func (s State) Mesh() ReadonlyMesh {
@@ -32,6 +33,10 @@ func (s State) CommonConfigs() ReadonlyCommonConfigStore {
return s.CommonConfigsStore
}
func (s State) VersionConfig() ReadonlyVersionConfigStore {
return s.VersionConfigStore
}
func (s *State) WritableMesh() WriteableMesh {
return s.MeshStore
}
@@ -52,6 +57,10 @@ func (s *State) WritableCommonConfigs() WriteableCommonConfigStore {
return s.CommonConfigsStore
}
func (s *State) WriteableVersionConfigStore() WriteableVersionConfigStore {
return s.VersionConfigStore
}
type WritableState interface {
ReadonlyState
WritableMesh() WriteableMesh
@@ -59,6 +68,7 @@ type WritableState interface {
WritableSchemas() WriteableSchemaStore
WritableModules() WriteableModuleStore
WritableCommonConfigs() WriteableCommonConfigStore
WriteableVersionConfigStore() WriteableVersionConfigStore
}
type ReadonlyState interface {
@@ -67,6 +77,7 @@ type ReadonlyState interface {
Schemas() ReadonlySchemaStore
Modules() ReadonlyModuleStore
CommonConfigs() ReadonlyCommonConfigStore
VersionConfig() ReadonlyVersionConfigStore
}
func NewState() *State {
@@ -76,16 +87,18 @@ func NewState() *State {
SchemasStore: NewSchemaStore(),
ModulesStore: NewModuleStore(),
CommonConfigsStore: NewCommonConfigStore(),
VersionConfigStore: NewVersionConfigStore(),
}
}
func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema,
modules []entity.Module, commConfigs []entity.CommonConfig) *State {
modules []entity.Module, commConfigs []entity.CommonConfig, versionStore []entity.VersionConfig) *State {
return &State{
MeshStore: NewMesh(),
ConfigsStore: &ConfigStore{Configs: configs},
SchemasStore: &SchemaStore{Schemas: schemas},
ModulesStore: &ModuleStore{Modules: modules},
CommonConfigsStore: &CommonConfigStore{Configs: commConfigs},
VersionConfigStore: NewVersionConfigStoreFromSnapshot(versionStore),
}
}
+90
View File
@@ -0,0 +1,90 @@
package state
import (
"github.com/integration-system/isp-lib/v2/config"
"isp-config-service/conf"
"isp-config-service/entity"
)
type WriteableVersionConfigStore interface {
ReadonlyVersionConfigStore
Update(config entity.VersionConfig) (removedId string)
Delete(id string)
}
type ReadonlyVersionConfigStore interface {
GetByConfigId(id string) []entity.VersionConfig
CheckCount() bool
}
type VersionConfigStore struct {
VersionByConfigId map[string][]entity.VersionConfig
count int
}
func (s *VersionConfigStore) Update(req entity.VersionConfig) string {
if !(s.count > 0) {
return req.Id
}
var (
newStore []entity.VersionConfig
removedId string
)
store, found := s.VersionByConfigId[req.ConfigId]
if found {
if len(store) >= s.count {
removedId = store[0].Id
newStore = append(store[1:], req)
} else {
newStore = append(store, req)
}
} else {
newStore = []entity.VersionConfig{req}
}
s.VersionByConfigId[req.ConfigId] = newStore
return removedId
}
func (s *VersionConfigStore) Delete(id string) {
for cfgId, versionCfg := range s.VersionByConfigId {
for i, versionConfig := range versionCfg {
if versionConfig.Id == id {
newVersionCfg := versionCfg[:i+copy(versionCfg[i:], versionCfg[i+1:])]
if len(newVersionCfg) == 0 {
delete(s.VersionByConfigId, cfgId)
} else {
s.VersionByConfigId[cfgId] = newVersionCfg
}
return
}
}
}
}
func (s VersionConfigStore) GetByConfigId(id string) []entity.VersionConfig {
response, found := s.VersionByConfigId[id]
if found {
return response
}
return []entity.VersionConfig{}
}
func (s *VersionConfigStore) CheckCount() bool {
return s.count > 0
}
func NewVersionConfigStore() *VersionConfigStore {
count := config.Get().(*conf.Configuration).VersionConfigCount
return &VersionConfigStore{
count: count,
VersionByConfigId: make(map[string][]entity.VersionConfig),
}
}
func NewVersionConfigStoreFromSnapshot(req []entity.VersionConfig) *VersionConfigStore {
store := NewVersionConfigStore()
for i := 0; i < len(req); i++ {
_ = store.Update(req[i])
}
return store
}
+2
View File
@@ -131,6 +131,8 @@ func NewStateStore(st *state.State) *Store {
cluster.DeleteCommonConfigsCommand: store.applyDeleteCommonConfigsCommand,
cluster.UpsertCommonConfigCommand: store.applyUpsertCommonConfigCommand,
cluster.BroadcastEventCommand: store.applyBroadcastEventCommand,
cluster.DeleteVersionConfigCommand: store.applyDeleteVersionConfigCommand,
cluster.GetAllVersionConfigCommand: store.applyAllVersionConfigCommand,
}
return store
}