From 15ad05277b97ba7be81da854298bbd564db7df96 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Mon, 8 Jun 2020 18:39:25 +0300 Subject: [PATCH] add config version --- .version | 2 +- CHANGELOG.md | 5 + cluster/const.go | 10 ++ cluster/const_string.go | 18 ++-- cluster/events.go | 4 + conf/config.yml | 2 + conf/configuration.go | 13 +-- controller/config.go | 40 ++++++++ docs/swagger.yaml | 97 +++++++++++++++++-- domain/request.go | 1 + entity/config.go | 16 +-- entity/module.go | 2 +- entity/version_config.go | 10 ++ go.mod | 1 + go.sum | 6 ++ helper/handler.go | 4 + ...2020-06-03_create_version_config_table.sql | 13 +++ model/client.go | 9 +- model/version_config.go | 53 ++++++++++ service/config.go | 49 ++++++++-- service/version.go | 42 ++++++++ store/apply.go | 23 ++++- store/restore.go | 7 +- store/state/state.go | 15 ++- store/state/version_config.go | 90 +++++++++++++++++ store/store.go | 2 + 26 files changed, 486 insertions(+), 48 deletions(-) create mode 100644 entity/version_config.go create mode 100644 migrations/00008_2020-06-03_create_version_config_table.sql create mode 100644 model/version_config.go create mode 100644 service/version.go create mode 100644 store/state/version_config.go diff --git a/.version b/.version index 276cbf9..197c4d5 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -2.3.0 +2.4.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index fb5fcdd..b1f2f96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` diff --git a/cluster/const.go b/cluster/const.go index 4729459..72c8c10 100644 --- a/cluster/const.go +++ b/cluster/const.go @@ -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)) diff --git a/cluster/const_string.go b/cluster/const_string.go index 5fdb36c..836a8cc 100644 --- a/cluster/const_string.go +++ b/cluster/const_string.go @@ -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 diff --git a/cluster/events.go b/cluster/events.go index 22b26cb..e42b42d 100644 --- a/cluster/events.go +++ b/cluster/events.go @@ -41,6 +41,10 @@ type DeleteCommonConfig struct { Id string } +type Identity struct { + Id string +} + type UpsertCommonConfig struct { Config entity.CommonConfig Create bool diff --git a/conf/config.yml b/conf/config.yml index 1d387a3..cbc6da0 100644 --- a/conf/config.yml +++ b/conf/config.yml @@ -37,3 +37,5 @@ cluster: bootstrapCluster: true peers: - 127.0.0.1:9001 + +versionConfigCount: 5 diff --git a/conf/configuration.go b/conf/configuration.go index adb75c1..b8aa2f1 100644 --- a/conf/configuration.go +++ b/conf/configuration.go @@ -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 { diff --git a/controller/config.go b/controller/config.go index 770ff0c..2743d4b 100644 --- a/controller/config.go +++ b/controller/config.go @@ -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, diff --git a/docs/swagger.yaml b/docs/swagger.yaml index c5f83a8..40ffbe0 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -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: diff --git a/domain/request.go b/domain/request.go index 645bdca..13345fe 100644 --- a/domain/request.go +++ b/domain/request.go @@ -2,6 +2,7 @@ package domain import ( json2 "encoding/json" + "isp-config-service/entity" ) diff --git a/entity/config.go b/entity/config.go index c2f53c2..6bd5573 100644 --- a/entity/config.go +++ b/entity/config.go @@ -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 { diff --git a/entity/module.go b/entity/module.go index ada68bf..196c470 100644 --- a/entity/module.go +++ b/entity/module.go @@ -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"` } diff --git a/entity/version_config.go b/entity/version_config.go new file mode 100644 index 0000000..bec934e --- /dev/null +++ b/entity/version_config.go @@ -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"` +} diff --git a/go.mod b/go.mod index c3f2d81..4cf350d 100644 --- a/go.mod +++ b/go.mod @@ -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 ) diff --git a/go.sum b/go.sum index 28b59c3..e69761e 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/helper/handler.go b/helper/handler.go index 4943b7b..02b9153 100644 --- a/helper/handler.go +++ b/helper/handler.go @@ -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, diff --git a/migrations/00008_2020-06-03_create_version_config_table.sql b/migrations/00008_2020-06-03_create_version_config_table.sql new file mode 100644 index 0000000..f7d7549 --- /dev/null +++ b/migrations/00008_2020-06-03_create_version_config_table.sql @@ -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; + diff --git a/model/client.go b/model/client.go index 8fda4e5..0812884 100644 --- a/model/client.go +++ b/model/client.go @@ -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} ) diff --git a/model/version_config.go b/model/version_config.go new file mode 100644 index 0000000..3aac07a --- /dev/null +++ b/model/version_config.go @@ -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 +} diff --git a/service/config.go b/service/config.go index 1155b56..04d2210 100644 --- a/service/config.go +++ b/service/config.go @@ -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, diff --git a/service/version.go b/service/version.go new file mode 100644 index 0000000..974bc8a --- /dev/null +++ b/service/version.go @@ -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) +} diff --git a/store/apply.go b/store/apply.go index 34e69a1..ce7c077 100644 --- a/store/apply.go +++ b/store/apply.go @@ -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 +} diff --git a/store/restore.go b/store/restore.go index 1682caa..b628efa 100644 --- a/store/restore.go +++ b/store/restore.go @@ -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 } diff --git a/store/state/state.go b/store/state/state.go index c30cf92..f914942 100644 --- a/store/state/state.go +++ b/store/state/state.go @@ -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), } } diff --git a/store/state/version_config.go b/store/state/version_config.go new file mode 100644 index 0000000..351404a --- /dev/null +++ b/store/state/version_config.go @@ -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 +} diff --git a/store/store.go b/store/store.go index 994b7da..12731f1 100644 --- a/store/store.go +++ b/store/store.go @@ -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 }